nexsight 0.6.1 → 0.6.3
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/insight4.min.js +1 -1
- package/insight4.nxs +6 -6
- package/package.json +1 -1
package/insight4.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(){function e(){return nexusclient.variables()}var t=["insight4"];function n(e,n){const r=`insight4.${e}`;return eventStream.registerEvent(e,n,{id:r,tags:t}),()=>{eventStream.removeListener(e,r)}}var r=Object.freeze({display:Object.freeze(["addLine"]),storage:Object.freeze(["get","set","clear"]),triggers:Object.freeze(["register","unregister"]),events:Object.freeze(["onSkillMatch","on","raise"]),gmcp:Object.freeze(["read"]),text:Object.freeze(["snapshot"]),clock:Object.freeze(["now","setTimer","clearTimer"])}),i={display:["addStream"]};Object.freeze(["events.onSkillMatch","events.on"]);function s(e){const t=function(e){if(null===e||"object"!=typeof e)return["adapter is not an object"];const t=[];for(const[n,i]of Object.entries(r)){const r=e[n];if(null!==r&&"object"==typeof r)for(const e of i)"function"!=typeof r[e]&&t.push(`${n}.${e} is not a function`);else t.push(`${n} is missing`)}for(const[n,r]of Object.entries(i)){const i=e[n];if(null!==i&&"object"==typeof i)for(const e of r)void 0!==i[e]&&"function"!=typeof i[e]&&t.push(`${n}.${e} is not a function`)}return t}(e);if(t.length>0)throw new Error(`Adapter contract violation: ${t.join("; ")}`);return e}var a,o=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,d="nexsight",l=`https://unpkg.com/${d}@latest/package.json`,c=e=>{const t=o.exec(String(e??"").trim());if(!t)throw new Error(`invalid version '${e??""}'`);return{core:t.slice(1,4).map(Number),prerelease:t[4]?.split(".")??[]}},f=(e,t)=>{const n=/^\d+$/.test(e)?Number(e):null,r=/^\d+$/.test(t)?Number(t):null;return null!==n&&null!==r?Math.sign(n-r):null!==n?-1:null!==r?1:e===t?0:e<t?-1:1},u=(e,t,n)=>{try{e?.({text:t,severity:n})}catch{}},p=async({enabled:e=!1,currentVersion:t,notice:n=null,fetchFn:r=globalThis.fetch,consoleObj:i=console,setTimeoutFn:s=setTimeout,clearTimeoutFn:a=clearTimeout,timeoutMs:o=1e4,url:p=l}={})=>{if(!e)return null;let h=null;try{if("function"!=typeof r)throw new Error("fetch is not available");c(t);const e=globalThis.AbortController;let i;if(e&&o>0){const t=new e;h=s(()=>t.abort(),o),i=t.signal}const a=await r(p,{cache:"no-store",...i?{signal:i}:{}});if(!a?.ok)throw new Error(`${a?.status??"no"} response from ${p}`);const l=(await a.json())?.version;if(c(l),((e,t)=>{const n=c(e),r=c(t);for(let s=0;s<n.core.length;s+=1)if(n.core[s]!==r.core[s])return Math.sign(n.core[s]-r.core[s]);if(0===n.prerelease.length||0===r.prerelease.length)return n.prerelease.length===r.prerelease.length?0:0===n.prerelease.length?1:-1;const i=Math.max(n.prerelease.length,r.prerelease.length);for(let s=0;s<i;s+=1){if(void 0===n.prerelease[s])return-1;if(void 0===r.prerelease[s])return 1;const e=f(n.prerelease[s],r.prerelease[s]);if(0!==e)return e}return 0})(l,t)<=0)return null;const m=(e=>`https://unpkg.com/${d}@${e}/insight4.nxs`)(l);return u(n,`Update available: ${t} → ${l}. Import ${m}`,"warning"),{currentVersion:t,latestVersion:l,url:m}}catch(m){const e="AbortError"===m?.name?"Update check timed out — check your connection.":`Update check failed: ${m?.message??String(m)}`;return i.error(`[insight4] ${e}`),u(n,e,"error"),null}finally{null!==h&&a(h)}};function h(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const i=a.prototype,s=Object.keys(i);for(let e=0;e<s.length;e++){const t=s[e];t in n||(n[t]=i[t].bind(n))}}const i=n?.Parent??Object;class s extends i{}function a(e){var t;const i=n?.Parent?new s:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const n of i._zod.deferred)n();return i}return Object.defineProperty(s,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var m=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},g=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(a=globalThis).__zod_globalConfig??(a.__zod_globalConfig={});var y=globalThis.__zod_globalConfig;function b(e){return e&&Object.assign(y,e),y}function v(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function k(e,t){return"bigint"==typeof t?t.toString():t}function w(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function I(e){return null==e}function z(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var _=Symbol("evaluating");function O(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==_)return void 0===r&&(r=_,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function $(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function S(...e){const t={};for(const n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function N(e){return JSON.stringify(e)}var x="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function j(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var M=w(()=>{if(y.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function T(e){if(!1===j(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==j(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function A(e){return T(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var E=new Set(["string","number","symbol"]);function C(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function P(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function R(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}var Z={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function D(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function F(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function L(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function q(e){return"string"==typeof e?e:e?.message}function B(e,t,n){const r=e.message?e.message:q(e.inst?._zod.def?.error?.(e))??q(t?.error?.(e))??q(n.customError?.(e))??q(n.localeError?.(e))??"Invalid input",{inst:i,continue:s,input:a,...o}=e;return o.path??(o.path=[]),o.message=r,t?.reportInput&&(o.input=a),o}function G(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function J(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}var U=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,k,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},H=h("$ZodError",U),V=h("$ZodError",U,{Parent:Error});var Y=e=>(t,n,r,i)=>{const s=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new m;if(a.issues.length){const t=new(i?.Err??e)(a.issues.map(e=>B(e,s,b())));throw x(t,i?.callee),t}return a.value},W=e=>async(t,n,r,i)=>{const s=r?{...r,async:!0}:{async:!0};let a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(i?.Err??e)(a.issues.map(e=>B(e,s,b())));throw x(t,i?.callee),t}return a.value},K=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new m;return s.issues.length?{success:!1,error:new(e??H)(s.issues.map(e=>B(e,i,b())))}:{success:!0,data:s.value}},Q=K(V),X=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(e=>B(e,i,b())))}:{success:!0,data:s.value}},ee=X(V),te=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Y(e)(t,n,i)},ne=e=>(t,n,r)=>Y(e)(t,n,r),re=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return W(e)(t,n,i)},ie=e=>async(t,n,r)=>W(e)(t,n,r),se=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return K(e)(t,n,i)},ae=e=>(t,n,r)=>K(e)(t,n,r),oe=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return X(e)(t,n,i)},de=e=>async(t,n,r)=>X(e)(t,n,r),le=/^[cC][0-9a-z]{6,}$/,ce=/^[0-9a-z]+$/,fe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ue=/^[0-9a-vA-V]{20}$/,pe=/^[A-Za-z0-9]{27}$/,he=/^[a-zA-Z0-9_-]{21}$/,me=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ge=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ye=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,be=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var ve=/^(?:(?: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])$/,ke=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,we=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ie=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ze=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_e=/^[A-Za-z0-9_-]*$/,Oe=/^https?$/,$e=/^\+[1-9]\d{6,14}$/,Se="(?:(?:\\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])))",Ne=new RegExp(`^${Se}$`);function xe(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}var je=/^-?\d+$/,Me=/^-?\d+(?:\.\d+)?$/,Te=/^(?:true|false)$/i,Ae=/^[^A-Z]*$/,Ee=/^[^a-z]*$/,Ce=h("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Pe={number:"number",bigint:"bigint",object:"date"},Re=h("$ZodCheckLessThan",(e,t)=>{Ce.init(e,t);const n=Pe[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ze=h("$ZodCheckGreaterThan",(e,t)=>{Ce.init(e,t);const n=Pe[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),De=h("$ZodCheckMultipleOf",(e,t)=>{Ce.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value!==BigInt(0):0!==function(e,t){const n=e/t,r=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}(n.value,t.value))&&n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Fe=h("$ZodCheckNumberFormat",(e,t)=>{Ce.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,s]=Z[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=s,n&&(r.pattern=je)}),e._zod.check=a=>{const o=a.value;if(n){if(!Number.isInteger(o))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?a.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}o<i&&a.issues.push({origin:"number",input:o,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),o>s&&a.issues.push({origin:"number",input:o,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Le=h("$ZodCheckMaxLength",(e,t)=>{var n;Ce.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!I(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const i=G(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qe=h("$ZodCheckMinLength",(e,t)=>{var n;Ce.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!I(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const i=G(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Be=h("$ZodCheckLengthEquals",(e,t)=>{var n;Ce.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!I(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,i=r.length;if(i===t.length)return;const s=G(r),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ge=h("$ZodCheckStringFormat",(e,t)=>{var n,r;Ce.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Je=h("$ZodCheckRegex",(e,t)=>{Ge.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ue=h("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ae),Ge.init(e,t)}),He=h("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ee),Ge.init(e,t)}),Ve=h("$ZodCheckIncludes",(e,t)=>{Ce.init(e,t);const n=C(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ye=h("$ZodCheckStartsWith",(e,t)=>{Ce.init(e,t);const n=new RegExp(`^${C(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),We=h("$ZodCheckEndsWith",(e,t)=>{Ce.init(e,t);const n=new RegExp(`.*${C(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ke=h("$ZodCheckOverwrite",(e,t)=>{Ce.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Qe=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const i of r)this.content.push(i)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}},Xe={major:4,minor:4,patch:3},et=h("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Xe;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const t of i._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,i=D(e);for(const s of t){if(s._zod.def.when){if(F(e))continue;if(!s._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,a=s._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new m;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(i||(i=D(e,t)))});else{if(e.issues.length===t)continue;i||(i=D(e,t))}}return r?r.then(()=>e):e},n=(n,i,s)=>{if(D(n))return n.aborted=!0,n;const a=t(i,r,s);if(a instanceof Promise){if(!1===s.async)throw new m;return a.then(t=>e._zod.parse(t,s))}return e._zod.parse(a,s)};e._zod.run=(i,s)=>{if(s.skipChecks)return e._zod.parse(i,s);if("backward"===s.direction){const t=e._zod.parse({value:i.value,issues:[]},{...s,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,s)):n(t,i,s)}const a=e._zod.parse(i,s);if(a instanceof Promise){if(!1===s.async)throw new m;return a.then(e=>t(e,r,s))}return t(a,r,s)}}O(e,"~standard",()=>({validate:t=>{try{const n=Q(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return ee(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),tt=h("$ZodString",(e,t)=>{var n;et.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),nt=h("$ZodStringFormat",(e,t)=>{Ge.init(e,t),tt.init(e,t)}),rt=h("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ge),nt.init(e,t)}),it=h("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ye(e))}else t.pattern??(t.pattern=ye());nt.init(e,t)}),st=h("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=be),nt.init(e,t)}),at=h("$ZodURL",(e,t)=>{nt.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===Oe.source&&!/^https?:\/\//i.test(r))return void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});const i=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=i.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ot=h("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nt.init(e,t)}),dt=h("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=he),nt.init(e,t)}),lt=h("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=le),nt.init(e,t)}),ct=h("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ce),nt.init(e,t)}),ft=h("$ZodULID",(e,t)=>{t.pattern??(t.pattern=fe),nt.init(e,t)}),ut=h("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ue),nt.init(e,t)}),pt=h("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=pe),nt.init(e,t)}),ht=h("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=xe({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Se}T(?:${r})$`)}(t)),nt.init(e,t)}),mt=h("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ne),nt.init(e,t)}),gt=h("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${xe(t)}$`)),nt.init(e,t)}),yt=h("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=me),nt.init(e,t)}),bt=h("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ve),nt.init(e,t),e._zod.bag.format="ipv4"}),vt=h("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ke),nt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),kt=h("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=we),nt.init(e,t)}),wt=h("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Ie),nt.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function It(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var zt=h("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ze),nt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{It(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});var _t=h("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_e),nt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!_e.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return It(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Ot=h("$ZodE164",(e,t)=>{t.pattern??(t.pattern=$e),nt.init(e,t)});var $t=h("$ZodJWT",(e,t)=>{nt.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),St=h("$ZodNumber",(e,t)=>{et.init(e,t),e._zod.pattern=e._zod.bag.pattern??Me,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const s="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),n}}),Nt=h("$ZodNumberFormat",(e,t)=>{Fe.init(e,t),St.init(e,t)}),xt=h("$ZodBoolean",(e,t)=>{et.init(e,t),e._zod.pattern=Te,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),jt=h("$ZodUnknown",(e,t)=>{et.init(e,t),e._zod.parse=e=>e}),Mt=h("$ZodNever",(e,t)=>{et.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Tt(e,t,n){e.issues.length&&t.issues.push(...L(n,e.issues)),t.value[n]=e.value}var At=h("$ZodArray",(e,t)=>{et.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const s=[];for(let e=0;e<i.length;e++){const a=i[e],o=t.element._zod.run({value:a,issues:[]},r);o instanceof Promise?s.push(o.then(t=>Tt(t,n,e))):Tt(o,n,e)}return s.length?Promise.all(s).then(()=>n):n}});function Et(e,t,n,r,i,s){const a=n in r;if(e.issues.length){if(i&&s&&!a)return;t.issues.push(...L(n,e.issues))}a||i?void 0===e.value?a&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}function Ct(e){const t=Object.keys(e.shape);for(const i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Pt(e,t,n,r,i,s){const a=[],o=i.keySet,d=i.catchall._zod,l=d.def.type,c="optional"===d.optin,f="optional"===d.optout;for(const u in t){if("__proto__"===u)continue;if(o.has(u))continue;if("never"===l){a.push(u);continue}const i=d.run({value:t[u],issues:[]},r);i instanceof Promise?e.push(i.then(e=>Et(e,n,u,t,c,f))):Et(i,n,u,t,c,f)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s}),e.length?Promise.all(e).then(()=>n):n}var Rt=h("$ZodObject",(e,t)=>{if(et.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const n=w(()=>Ct(t));O(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const r=j,i=t.catchall;let s;e._zod.parse=(t,a)=>{s??(s=n.value);const o=t.value;if(!r(o))return t.issues.push({expected:"object",code:"invalid_type",input:o,inst:e}),t;t.value={};const d=[],l=s.shape;for(const e of s.keys){const n=l[e],r="optional"===n._zod.optin,i="optional"===n._zod.optout,s=n._zod.run({value:o[e],issues:[]},a);s instanceof Promise?d.push(s.then(n=>Et(n,t,e,o,r,i))):Et(s,t,e,o,r,i)}return i?Pt(d,o,t,a,n.value,e):d.length?Promise.all(d).then(()=>t):t}}),Zt=h("$ZodObjectJIT",(e,t)=>{Rt.init(e,t);const n=e._zod.parse,r=w(()=>Ct(t));let i;const s=j,a=!y.jitless,o=a&&M.value,d=t.catchall;let l;e._zod.parse=(c,f)=>{l??(l=r.value);const u=c.value;return s(u)?a&&o&&!1===f?.async&&!0!==f.jitless?(i||(i=(e=>{const t=new Qe(["shape","payload","ctx"]),n=r.value,i=e=>{const t=N(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const s=Object.create(null);let a=0;for(const r of n.keys)s[r]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=s[r],a=N(r),o=e[r],d="optional"===o?._zod?.optin,l="optional"===o?._zod?.optout;t.write(`const ${n} = ${i(r)};`),d&&l?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):d?t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n const ${n}_present = ${a} in input;\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${a}]\n });\n }\n\n if (${n}_present) {\n if (${n}.value === undefined) {\n newResult[${a}] = undefined;\n } else {\n newResult[${a}] = ${n}.value;\n }\n }\n\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const o=t.compile();return(t,n)=>o(e,t,n)})(t.shape)),c=i(c,f),d?Pt([],u,c,f,l,e):c):n(c,f):(c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c)}});function Dt(e,t,n,r){for(const s of e)if(0===s.issues.length)return t.value=s.value,t;const i=e.filter(e=>!D(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>B(e,r,b())))}),t)}var Ft=h("$ZodUnion",(e,t)=>{et.init(e,t),O(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),O(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),O(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),O(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>z(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>Dt(t,r,e,i)):Dt(a,r,e,i)}}),Lt=h("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ft.init(e,t);const n=e._zod.parse;O(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=w(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,s)=>{const a=i.value;if(!j(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),i;const o=r.value.get(a?.[t.discriminator]);return o?o._zod.run(i,s):t.unionFallback||"backward"===s.direction?n(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:a,path:[t.discriminator],inst:e}),i)}}),qt=h("$ZodIntersection",(e,t)=>{et.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),s=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([t,n])=>Gt(e,t,n)):Gt(e,i,s)}});function Bt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(T(e)&&T(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const s of r){const n=Bt(e[s],t[s]);if(!n.valid)return{valid:!1,mergeErrorPath:[s,...n.mergeErrorPath]};i[s]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=Bt(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Gt(e,t,n){const r=new Map;let i;for(const o of t.issues)if("unrecognized_keys"===o.code){i??(i=o);for(const e of o.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(o);for(const o of n.issues)if("unrecognized_keys"===o.code)for(const e of o.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(o);const s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length&&i&&e.issues.push({...i,keys:s}),D(e))return e;const a=Bt(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Jt=h("$ZodRecord",(e,t)=>{et.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!T(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const s=[],a=t.keyType._zod.values;if(a){n.value={};const o=new Set;for(const l of a)if("string"==typeof l||"number"==typeof l||"symbol"==typeof l){o.add("number"==typeof l?l.toString():l);const a=t.keyType._zod.run({value:l,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>B(e,r,b())),input:l,path:[l],inst:e});continue}const d=a.value,c=t.valueType._zod.run({value:i[l],issues:[]},r);c instanceof Promise?s.push(c.then(e=>{e.issues.length&&n.issues.push(...L(l,e.issues)),n.value[d]=e.value})):(c.issues.length&&n.issues.push(...L(l,c.issues)),n.value[d]=c.value)}let d;for(const e in i)o.has(e)||(d=d??[],d.push(e));d&&d.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:d})}else{n.value={};for(const a of Reflect.ownKeys(i)){if("__proto__"===a)continue;if(!Object.prototype.propertyIsEnumerable.call(i,a))continue;let o=t.keyType._zod.run({value:a,issues:[]},r);if(o instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof a&&Me.test(a)&&o.issues.length){const e=t.keyType._zod.run({value:Number(a),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(o=e)}if(o.issues.length){"loose"===t.mode?n.value[a]=i[a]:n.issues.push({code:"invalid_key",origin:"record",issues:o.issues.map(e=>B(e,r,b())),input:a,path:[a],inst:e});continue}const d=t.valueType._zod.run({value:i[a],issues:[]},r);d instanceof Promise?s.push(d.then(e=>{e.issues.length&&n.issues.push(...L(a,e.issues)),n.value[o.value]=e.value})):(d.issues.length&&n.issues.push(...L(a,d.issues)),n.value[o.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Ut=h("$ZodEnum",(e,t)=>{et.init(e,t);const n=v(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>E.has(typeof e)).map(e=>"string"==typeof e?C(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const s=t.value;return r.has(s)||t.issues.push({code:"invalid_value",values:n,input:s,inst:e}),t}}),Ht=h("$ZodLiteral",(e,t)=>{if(et.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?C(e):e?C(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,i)=>{const s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),Vt=h("$ZodTransform",(e,t)=>{et.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new g(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new m;return n.value=i,n.fallback=!0,n}});function Yt(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Wt=h("$ZodOptional",(e,t)=>{et.init(e,t),e._zod.optin="optional",e._zod.optout="optional",O(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),O(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${z(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Yt(e,r)):Yt(i,r)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Kt=h("$ZodExactOptional",(e,t)=>{Wt.init(e,t),O(e._zod,"values",()=>t.innerType._zod.values),O(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Qt=h("$ZodNullable",(e,t)=>{et.init(e,t),O(e._zod,"optin",()=>t.innerType._zod.optin),O(e._zod,"optout",()=>t.innerType._zod.optout),O(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${z(e.source)}|null)$`):void 0}),O(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Xt=h("$ZodDefault",(e,t)=>{et.init(e,t),e._zod.optin="optional",O(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>en(e,t)):en(r,t)}});function en(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var tn=h("$ZodPrefault",(e,t)=>{et.init(e,t),e._zod.optin="optional",O(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),nn=h("$ZodNonOptional",(e,t)=>{et.init(e,t),O(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>rn(t,e)):rn(i,e)}});function rn(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var sn=h("$ZodCatch",(e,t)=>{et.init(e,t),e._zod.optin="optional",O(e._zod,"optout",()=>t.innerType._zod.optout),O(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>B(e,n,b()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>B(e,n,b()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),an=h("$ZodPipe",(e,t)=>{et.init(e,t),O(e._zod,"values",()=>t.in._zod.values),O(e._zod,"optin",()=>t.in._zod.optin),O(e._zod,"optout",()=>t.out._zod.optout),O(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>on(e,t.in,n)):on(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>on(e,t.out,n)):on(r,t.out,n)}});function on(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var dn=h("$ZodReadonly",(e,t)=>{et.init(e,t),O(e._zod,"propValues",()=>t.innerType._zod.propValues),O(e._zod,"values",()=>t.innerType._zod.values),O(e._zod,"optin",()=>t.innerType?._zod?.optin),O(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(ln):ln(r)}});function ln(e){return e.value=Object.freeze(e.value),e}var cn,fn=h("$ZodCustom",(e,t)=>{Ce.init(e,t),et.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>un(t,n,r,e));un(i,n,r,e)}});function un(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(J(e))}}var pn=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};(cn=globalThis).__zod_globalRegistry??(cn.__zod_globalRegistry=new pn);var hn=globalThis.__zod_globalRegistry;function mn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function gn(e,t){return new Re({check:"less_than",...R(t),value:e,inclusive:!1})}function yn(e,t){return new Re({check:"less_than",...R(t),value:e,inclusive:!0})}function bn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!1})}function vn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!0})}function kn(e,t){return new De({check:"multiple_of",...R(t),value:e})}function wn(e,t){return new Le({check:"max_length",...R(t),maximum:e})}function In(e,t){return new qe({check:"min_length",...R(t),minimum:e})}function zn(e,t){return new Be({check:"length_equals",...R(t),length:e})}function _n(e){return new Ke({check:"overwrite",tx:e})}function On(e,t){const n=new Ce({check:"custom",...R(t)});return n._zod.check=e,n}function $n(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??hn,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Sn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const o=e._zod.toJSONSchema?.();if(o)a.schema=o;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,s=t.processors[i.type];if(!s)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);s(e,t,n,r)}const s=e._zod.parent;s&&(a.ref||(a.ref=s),Sn(s,t,r),t.seen.get(s).isParent=!0)}const d=t.metadataRegistry.get(e);return d&&Object.assign(a.schema,d),"input"===t.io&&jn(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&"_prefault"in a.schema&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Nn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const s of e.seen.entries()){const t=e.metadataRegistry.get(s[0])?.id;if(t){const e=r.get(t);if(e&&e!==s[0])throw new Error(`Duplicate schema id "${t}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(t,s[0])}}const i=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:i,defId:s}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};const s=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=s,{defId:s,ref:`${i("__shared")}#/${r}/${s}`}}if(t[1]===n)return{ref:"#"};const i=`#/${r}/`,s=t[1].schema.id??"__schema"+e.counter++;return{defId:s,ref:i+s}})(t);r.def={...r.schema},s&&(r.defId=s);const a=r.schema;for(const e in a)delete a[e];a.$ref=i};if("throw"===e.cycles)for(const s of e.seen.entries()){const e=s[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const n=s[1];if(t!==s[0]){if(e.external){const n=e.external.registry.get(s[0])?.id;if(t!==s[0]&&n){i(s);continue}}(e.metadataRegistry.get(s[0])?.id||n.cycle||n.count>1&&"ref"===e.reused)&&i(s)}else i(s)}}function xn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const i=n.def??n.schema,s={...i},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),o=n.schema;if(!o.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(i,o):(i.allOf=i.allOf??[],i.allOf.push(o)),Object.assign(i,s),t._zod.parent===a)for(const e in i)"$ref"!==e&&"allOf"!==e&&(e in s||delete i[e]);if(o.$ref&&n.def)for(const e in i)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}const o=t._zod.parent;if(o&&o!==a){r(o);const t=e.seen.get(o);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(const e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(const d of[...e.seen.entries()].reverse())r(d[0]);const i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);const s=e.metadataRegistry.get(t)?.id;void 0!==s&&i.id===s&&delete i.id;const a=e.external?.defs??{};for(const d of e.seen.entries()){const e=d[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&("draft-2020-12"===e.target?i.$defs=a:i.definitions=a);try{const n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:Mn(t,"input",e.processors),output:Mn(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(o){throw new Error("Error converting schema to JSON.")}}function jn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return jn(r.element,n);if("set"===r.type)return jn(r.valueType,n);if("lazy"===r.type)return jn(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return jn(r.innerType,n);if("intersection"===r.type)return jn(r.left,n)||jn(r.right,n);if("record"===r.type||"map"===r.type)return jn(r.keyType,n)||jn(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(jn(r.in,n)||jn(r.out,n));if("object"===r.type){for(const e in r.shape)if(jn(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(jn(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(jn(e,n))return!0;return!(!r.rest||!jn(r.rest,n))}return!1}var Mn=(e,t,n={})=>r=>{const{libraryOptions:i,target:s}=r??{},a=$n({...i??{},target:s,io:t,processors:n});return Sn(e,a),Nn(a,e),xn(a,e)},Tn={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},An=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);t.seen.get(e).ref=i.innerType},En=h("ZodISODateTime",(e,t)=>{ht.init(e,t),dr.init(e,t)});function Cn(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}(En,e)}var Pn=h("ZodISODate",(e,t)=>{mt.init(e,t),dr.init(e,t)});function Rn(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}(Pn,e)}var Zn=h("ZodISOTime",(e,t)=>{gt.init(e,t),dr.init(e,t)});function Dn(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}(Zn,e)}var Fn=h("ZodISODuration",(e,t)=>{yt.init(e,t),dr.init(e,t)});function Ln(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}(Fn,e)}var qn=(e,t)=>{H.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=(e,i=[])=>{for(const s of e.issues)if("invalid_union"===s.code&&s.errors.length)s.errors.map(e=>r({issues:e},[...i,...s.path]));else if("invalid_key"===s.code)r({issues:s.issues},[...i,...s.path]);else if("invalid_element"===s.code)r({issues:s.issues},[...i,...s.path]);else{const e=[...i,...s.path];if(0===e.length)n._errors.push(t(s));else{let r=n,i=0;for(;i<e.length;){const n=e[i];i!==e.length-1?r[n]=r[n]||{_errors:[]}:(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(s))),r=r[n],i++}}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,k,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,k,2)}},isEmpty:{get:()=>0===e.issues.length}})},Bn=h("ZodError",qn,{Parent:Error}),Gn=Y(Bn),Jn=W(Bn),Un=K(Bn),Hn=X(Bn),Vn=te(Bn),Yn=ne(Bn),Wn=re(Bn),Kn=ie(Bn),Qn=se(Bn),Xn=ae(Bn),er=oe(Bn),tr=de(Bn),nr=new WeakMap;function rr(e,t,n){const r=Object.getPrototypeOf(e);let i=nr.get(r);if(i||(i=new Set,nr.set(r,i)),!i.has(t)){i.add(t);for(const e in n){const t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){const n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var ir=h("ZodType",(e,t)=>(et.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Mn(e,"input"),output:Mn(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=$n({...n,processors:t});return Sn(e,r),Nn(r,e),xn(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Gn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Un(e,t,n),e.parseAsync=async(t,n)=>Jn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Hn(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Vn(e,t,n),e.decode=(t,n)=>Yn(e,t,n),e.encodeAsync=async(t,n)=>Wn(e,t,n),e.decodeAsync=async(t,n)=>Kn(e,t,n),e.safeEncode=(t,n)=>Qn(e,t,n),e.safeDecode=(t,n)=>Xn(e,t,n),e.safeEncodeAsync=async(t,n)=>er(e,t,n),e.safeDecodeAsync=async(t,n)=>tr(e,t,n),rr(e,"ZodType",{check(...e){const t=this.def;return this.clone(S(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return P(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...R(n)})}(ui,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return function(e,t){const n=On(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(J(e,t.value,n._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(J(r))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(_n(e))},optional(){return ti(this)},exactOptional(){return new ni({type:"optional",innerType:this})},nullable(){return ii(this)},nullish(){return ti(ii(this))},nonoptional(e){return function(e,t){return new oi({type:"nonoptional",innerType:e,...R(t)})}(this,e)},array(){return Dr(this)},or(e){return Gr([this,e])},and(e){return new Ur({type:"intersection",left:this,right:e})},transform(e){return ci(this,new Xr({type:"transform",transform:e}))},default(e){return t=e,new si({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():A(t)}});var t},prefault(e){return t=e,new ai({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():A(t)}});var t},catch(e){return new di({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return ci(this,e)},readonly(){return new fi({type:"readonly",innerType:this})},describe(e){const t=this.clone();return hn.add(t,{description:e}),t},meta(...e){if(0===e.length)return hn.get(this);const t=this.clone();return hn.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>hn.get(e)?.description,configurable:!0}),e)),sr=h("_ZodString",(e,t)=>{tt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:i,maximum:s,format:a,patterns:o,contentEncoding:d}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof s&&(r.maxLength=s),a&&(r.format=Tn[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),d&&(r.contentEncoding=d),o&&o.size>0){const e=[...o];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,rr(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new Je({check:"string_format",format:"regex",...R(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new Ve({check:"string_format",format:"includes",...R(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Ye({check:"string_format",format:"starts_with",...R(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new We({check:"string_format",format:"ends_with",...R(t),suffix:e})}(...e))},min(...e){return this.check(In(...e))},max(...e){return this.check(wn(...e))},length(...e){return this.check(zn(...e))},nonempty(...e){return this.check(In(1,...e))},lowercase(e){return this.check(function(e){return new Ue({check:"string_format",format:"lowercase",...R(e)})}(e))},uppercase(e){return this.check(function(e){return new He({check:"string_format",format:"uppercase",...R(e)})}(e))},trim(){return this.check(_n(e=>e.trim()))},normalize(...e){return this.check(function(e){return _n(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(_n(e=>e.toLowerCase()))},toUpperCase(){return this.check(_n(e=>e.toUpperCase()))},slugify(){return this.check(_n(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),ar=h("ZodString",(e,t)=>{tt.init(e,t),sr.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}(lr,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}(ur,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}(Sr,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}(pr,t)),e.guid=t=>e.check(mn(cr,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}(fr,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}(fr,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}(fr,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}(fr,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}(hr,t)),e.guid=t=>e.check(mn(cr,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}(mr,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}(gr,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}(yr,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}(_r,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}(Or,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}(br,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}(vr,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}(kr,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}(wr,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}(Ir,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}(zr,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}($r,t)),e.datetime=t=>e.check(Cn(t)),e.date=t=>e.check(Rn(t)),e.time=t=>e.check(Dn(t)),e.duration=t=>e.check(Ln(t))});function or(e){return function(e,t){return new e({type:"string",...R(t)})}(ar,e)}var dr=h("ZodStringFormat",(e,t)=>{nt.init(e,t),sr.init(e,t)}),lr=h("ZodEmail",(e,t)=>{st.init(e,t),dr.init(e,t)}),cr=h("ZodGUID",(e,t)=>{rt.init(e,t),dr.init(e,t)}),fr=h("ZodUUID",(e,t)=>{it.init(e,t),dr.init(e,t)}),ur=h("ZodURL",(e,t)=>{at.init(e,t),dr.init(e,t)}),pr=h("ZodEmoji",(e,t)=>{ot.init(e,t),dr.init(e,t)}),hr=h("ZodNanoID",(e,t)=>{dt.init(e,t),dr.init(e,t)}),mr=h("ZodCUID",(e,t)=>{lt.init(e,t),dr.init(e,t)}),gr=h("ZodCUID2",(e,t)=>{ct.init(e,t),dr.init(e,t)}),yr=h("ZodULID",(e,t)=>{ft.init(e,t),dr.init(e,t)}),br=h("ZodXID",(e,t)=>{ut.init(e,t),dr.init(e,t)}),vr=h("ZodKSUID",(e,t)=>{pt.init(e,t),dr.init(e,t)}),kr=h("ZodIPv4",(e,t)=>{bt.init(e,t),dr.init(e,t)}),wr=h("ZodIPv6",(e,t)=>{vt.init(e,t),dr.init(e,t)}),Ir=h("ZodCIDRv4",(e,t)=>{kt.init(e,t),dr.init(e,t)}),zr=h("ZodCIDRv6",(e,t)=>{wt.init(e,t),dr.init(e,t)}),_r=h("ZodBase64",(e,t)=>{zt.init(e,t),dr.init(e,t)}),Or=h("ZodBase64URL",(e,t)=>{_t.init(e,t),dr.init(e,t)}),$r=h("ZodE164",(e,t)=>{Ot.init(e,t),dr.init(e,t)}),Sr=h("ZodJWT",(e,t)=>{$t.init(e,t),dr.init(e,t)}),Nr=h("ZodNumber",(e,t)=>{St.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:i,maximum:s,format:a,multipleOf:o,exclusiveMaximum:d,exclusiveMinimum:l}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number";const c="number"==typeof l&&l>=(i??Number.NEGATIVE_INFINITY),f="number"==typeof d&&d<=(s??Number.POSITIVE_INFINITY),u="draft-04"===t.target||"openapi-3.0"===t.target;c?u?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l:"number"==typeof i&&(r.minimum=i),f?u?(r.maximum=d,r.exclusiveMaximum=!0):r.exclusiveMaximum=d:"number"==typeof s&&(r.maximum=s),"number"==typeof o&&(r.multipleOf=o)})(e,t,n),rr(e,"ZodNumber",{gt(e,t){return this.check(bn(e,t))},gte(e,t){return this.check(vn(e,t))},min(e,t){return this.check(vn(e,t))},lt(e,t){return this.check(gn(e,t))},lte(e,t){return this.check(yn(e,t))},max(e,t){return this.check(yn(e,t))},int(e){return this.check(Mr(e))},safe(e){return this.check(Mr(e))},positive(e){return this.check(bn(0,e))},nonnegative(e){return this.check(vn(0,e))},negative(e){return this.check(gn(0,e))},nonpositive(e){return this.check(yn(0,e))},multipleOf(e,t){return this.check(kn(e,t))},step(e,t){return this.check(kn(e,t))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function xr(e){return function(e,t){return new e({type:"number",checks:[],...R(t)})}(Nr,e)}var jr=h("ZodNumberFormat",(e,t)=>{Nt.init(e,t),Nr.init(e,t)});function Mr(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}(jr,e)}var Tr=h("ZodBoolean",(e,t)=>{xt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function Ar(e){return function(e,t){return new e({type:"boolean",...R(t)})}(Tr,e)}var Er=h("ZodUnknown",(e,t)=>{jt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Cr(){return new Er({type:"unknown"})}var Pr=h("ZodNever",(e,t)=>{Mt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function Rr(e){return function(e,t){return new e({type:"never",...R(t)})}(Pr,e)}var Zr=h("ZodArray",(e,t)=>{At.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,s=e._zod.def,{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(i.minItems=a),"number"==typeof o&&(i.maxItems=o),i.type="array",i.items=Sn(s.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,rr(e,"ZodArray",{min(e,t){return this.check(In(e,t))},nonempty(e){return this.check(In(1,e))},max(e,t){return this.check(wn(e,t))},length(e,t){return this.check(zn(e,t))},unwrap(){return this.element}})});function Dr(e,t){return function(e,t,n){return new e({type:"array",element:t,...R(n)})}(Zr,e,t)}var Fr=h("ZodObject",(e,t)=>{Zt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,s=e._zod.def;i.type="object",i.properties={};const a=s.shape;for(const l in a)i.properties[l]=Sn(a[l],t,{...r,path:[...r.path,"properties",l]});const o=new Set(Object.keys(a)),d=new Set([...o].filter(e=>{const n=s.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));d.size>0&&(i.required=Array.from(d)),"never"===s.catchall?._zod.def.type?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=Sn(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),O(e,"shape",()=>t.shape),rr(e,"ZodObject",{keyof(){return Wr(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Cr()})},loose(){return this.clone({...this._zod.def,catchall:Cr()})},strict(){return this.clone({...this._zod.def,catchall:Rr()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!T(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return P(e,S(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return $(this,"shape",n),n}}))}(this,e)},safeExtend(e){return function(e,t){if(!T(t))throw new Error("Invalid input to safeExtend: expected a plain object");return P(e,S(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return $(this,"shape",n),n}}))}(this,e)},merge(e){return function(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");return P(e,S(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return $(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}(this,e)},pick(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return P(e,S(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return $(this,"shape",e),e},checks:[]}))}(this,e)},omit(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return P(e,S(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return $(this,"shape",r),r},checks:[]}))}(this,e)},partial(...e){return function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return P(t,S(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return $(this,"shape",i),i},checks:[]}))}(ei,this,e[0])},required(...e){return t=oi,n=this,r=e[0],P(n,S(n._zod.def,{get shape(){const e=n._zod.def.shape,i={...e};if(r)for(const n in r){if(!(n in i))throw new Error(`Unrecognized key: "${n}"`);r[n]&&(i[n]=new t({type:"nonoptional",innerType:e[n]}))}else for(const n in e)i[n]=new t({type:"nonoptional",innerType:e[n]});return $(this,"shape",i),i}}));var t,n,r}})});function Lr(e,t){return new Fr({type:"object",shape:e??{},...R(t)})}function qr(e,t){return new Fr({type:"object",shape:e,catchall:Rr(),...R(t)})}var Br=h("ZodUnion",(e,t)=>{Ft.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,s=!1===i.inclusive,a=i.options.map((e,n)=>Sn(e,t,{...r,path:[...r.path,s?"oneOf":"anyOf",n]}));s?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options});function Gr(e,t){return new Br({type:"union",options:e,...R(t)})}var Jr=h("ZodDiscriminatedUnion",(e,t)=>{Br.init(e,t),Lt.init(e,t)});var Ur=h("ZodIntersection",(e,t)=>{qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,s=Sn(i.left,t,{...r,path:[...r.path,"allOf",0]}),a=Sn(i.right,t,{...r,path:[...r.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length;n.allOf=[...o(s)?s.allOf:[s],...o(a)?a.allOf:[a]]})(e,t,n,r)});var Hr=h("ZodRecord",(e,t)=>{Jt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,s=e._zod.def;i.type="object";const a=s.keyType,o=a._zod.bag?.patterns;if("loose"===s.mode&&o&&o.size>0){const e=Sn(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const t of o)i.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(i.propertyNames=Sn(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Sn(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=a._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Vr(e,t,n){return t&&t._zod?new Hr({type:"record",keyType:e,valueType:t,...R(n)}):new Hr({type:"record",keyType:or(),valueType:e,...R(t)})}var Yr=h("ZodEnum",(e,t)=>{Ut.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=v(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const s of e){if(!n.has(s))throw new Error(`Key ${s} not found in enum`);i[s]=t.entries[s]}return new Yr({...t,checks:[],...R(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new Yr({...t,checks:[],...R(r),entries:i})}});function Wr(e,t){return new Yr({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...R(t)})}var Kr=h("ZodLiteral",(e,t)=>{Ht.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,i=[];for(const s of r.values)if(void 0===s){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof s){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(0===i.length);else if(1===i.length){const e=i[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),i.every(e=>"boolean"==typeof e)&&(n.type="boolean"),i.every(e=>null===e)&&(n.type="null"),n.enum=i})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Qr(e,t){return new Kr({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}var Xr=h("ZodTransform",(e,t)=>{Vt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new g(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(J(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(J(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});var ei=h("ZodOptional",(e,t)=>{Wt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>An(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function ti(e){return new ei({type:"optional",innerType:e})}var ni=h("ZodExactOptional",(e,t)=>{Kt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>An(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ri=h("ZodNullable",(e,t)=>{Qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,s=Sn(i.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=i.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ii(e){return new ri({type:"nullable",innerType:e})}var si=h("ZodDefault",(e,t)=>{Xt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var ai=h("ZodPrefault",(e,t)=>{tn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var oi=h("ZodNonOptional",(e,t)=>{nn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var di=h("ZodCatch",(e,t)=>{sn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;let s;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType;try{s=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var li=h("ZodPipe",(e,t)=>{an.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,s=i.in._zod.traits.has("$ZodTransform"),a="input"===t.io?s?i.out:i.in:i.out;Sn(a,t,r),t.seen.get(e).ref=a})(e,t,0,r),e.in=t.in,e.out=t.out});function ci(e,t){return new li({type:"pipe",in:e,out:t})}var fi=h("ZodReadonly",(e,t)=>{dn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var ui=h("ZodCustom",(e,t)=>{fn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});var pi,hi=or().regex(/^[a-z]+$/,"aff ids are single lowercase words"),mi=or().regex(/^[a-z][a-zA-Z]*$/,"balance ids are lowercase-led words"),gi=or().regex(/^[a-z]+( [a-z]+)*$/,"cure ids are lowercase words separated by single spaces"),yi=or().regex(/^[a-z]+$/,"venom ids are single lowercase words"),bi=or().regex(/^[a-z]+$/,"profession ids are single lowercase words"),vi=qr({shortName:or().min(1),fg:or(),bg:or()}),ki={id:hi,display:vi.optional(),curesTo:hi.optional(),pseudo:Ar().default(!1),curedLast:Ar().default(!1)},wi=qr({...ki,kind:Qr("plain")}),Ii=qr({...ki,kind:Qr("timed"),durationMs:xr().int().positive(),provenance:Wr(["verified","unverified"]).default("verified")}),zi=qr({...ki,kind:Qr("countable"),min:xr().int().min(0),max:xr().int().positive()}).refine(e=>e.max>e.min,{message:"countable affs need max > min"}),_i=Dr(new Jr({type:"union",options:[wi,Ii,zi],discriminator:"kind",...R(pi)})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"aff ids must be unique"}),Oi=qr({fg:or(),bg:or()}),$i=Vr(or().min(1),Oi),Si=Vr(hi,vi),Ni=qr({delimiter:Oi,label:Oi}),xi=qr({info:Oi,warning:Oi,error:Oi}),ji=qr({bracket:Oi,detail:Oi,tag:Ni,severity:xi}),Mi=qr({affs:Si,chrome:ji}),Ti=$i.parse({antimony:{fg:"olive",bg:""},argentum:{fg:"royalblue",bg:""},arsenic:{fg:"",bg:""},aurum:{fg:"ForestGreen",bg:""},azurite:{fg:"",bg:""},calamine:{fg:"",bg:""},calcite:{fg:"slategray",bg:""},cinnabar:{fg:"greenyellow",bg:""},cuprum:{fg:"DeepSkyBlue",bg:""},ferrum:{fg:"DarkOrange",bg:""},gypsum:{fg:"",bg:""},magnesium:{fg:"Red",bg:""},plumbum:{fg:"Gold",bg:""},quartz:{fg:"",bg:""},quicksilver:{fg:"",bg:""},realgar:{fg:"firebrick",bg:""},stannum:{fg:"Tan",bg:""},caloric:{fg:"darkseagreen",bg:""},mending:{fg:"orchid",bg:""},epidermal:{fg:"sienna",bg:""},restoration:{fg:"darkviolet",bg:""},health:{fg:"lightpink",bg:""},writhe:{fg:"paleyellow",bg:"darkslategray"}}),Ai={addiction:{shortName:"add",...Ti.ferrum},aeon:{shortName:"ae",...Ti.cinnabar},agoraphobia:{shortName:"agor",...Ti.argentum},amnesia:{shortName:"amn",fg:"",bg:""},anorexia:{shortName:"ANO",...Ti.epidermal},asthma:{shortName:"AST",...Ti.aurum},blackout:{shortName:"bo",fg:"",bg:""},blindness:{shortName:"unb",...Ti.arsenic},bound:{shortName:"bnd",...Ti.writhe},brokenleftarm:{shortName:"la1",...Ti.mending},brokenleftleg:{shortName:"ll1",...Ti.mending},brokenrightarm:{shortName:"ra1",...Ti.mending},brokenrightleg:{shortName:"rl1",...Ti.mending},bruisedribs:{shortName:"ribs",fg:"",bg:""},burning:{shortName:"burn",...Ti.mending},calcifiedskull:{shortName:"calh",...Ti.restoration},calcifiedtorso:{shortName:"calt",...Ti.restoration},claustrophobia:{shortName:"clau",...Ti.stannum},cleanseaura:{shortName:"cleanse",fg:"",bg:""},clumsiness:{shortName:"clu",...Ti.aurum},concussion:{shortName:"conc",...Ti.restoration},confusion:{shortName:"con",...Ti.stannum},corruption:{shortName:"corr",fg:"",bg:""},crackedribs:{shortName:"cr",...Ti.health},crushedthroat:{shortName:"cru",...Ti.mending},daeggerimpale:{shortName:"daeg",...Ti.writhe},damagedleftarm:{shortName:"la2",...Ti.restoration},damagedleftleg:{shortName:"ll2",...Ti.restoration},damagedrightarm:{shortName:"ra2",...Ti.restoration},damagedrightleg:{shortName:"rl2",...Ti.restoration},damagedhead:{shortName:"hd2",...Ti.restoration},darkshade:{shortName:"dark",...Ti.ferrum},dazed:{shortName:"dzd",...Ti.cinnabar},dazzled:{shortName:"dzl",...Ti.mending},deadening:{shortName:"dea",...Ti.cinnabar},deafness:{shortName:"und",...Ti.calamine},dehydrated:{shortName:"deh",fg:"",bg:""},dementia:{shortName:"dem",...Ti.stannum},depression:{shortName:"dep",...Ti.plumbum},deteriorate:{shortName:"det",fg:"",bg:""},disloyalty:{shortName:"disl",...Ti.realgar},disrupted:{shortName:"disr",fg:"",bg:""},dissonance:{shortName:"disso",...Ti.plumbum},dizziness:{shortName:"diz",...Ti.plumbum},enmesh:{shortName:"enmsh",...Ti.writhe},ensorcelled:{shortName:"ensor",fg:"",bg:""},entangled:{shortName:"entgl",...Ti.writhe},epilepsy:{shortName:"epi",...Ti.plumbum},fear:{shortName:"fear",fg:"",bg:""},flushings:{shortName:"flush",...Ti.ferrum},frostbite:{shortName:"frost",...Ti.caloric},frozen:{shortName:"frz",...Ti.caloric},fulminated:{shortName:"fulm",...Ti.plumbum},generosity:{shortName:"gen",...Ti.cuprum},grievouswounds:{shortName:"grv",...Ti.health},guilt:{shortName:"gui",...Ti.argentum},haemophilia:{shortName:"haem",...Ti.ferrum},hallucinations:{shortName:"hall",...Ti.stannum},hamstrung:{shortName:"hms",fg:"",bg:""},healthleech:{shortName:"hthl",...Ti.aurum},heartseed:{shortName:"heart",...Ti.restoration},hellsight:{shortName:"hell",...Ti.realgar},horror:{shortName:"hor",...Ti.argentum},hypersomnia:{shortName:"hypers",...Ti.stannum},hypochondria:{shortName:"hypoch",...Ti.aurum},hypothermia:{shortName:"hypoth",...Ti.restoration},icefisted:{shortName:"ice",fg:"",bg:""},impaled:{shortName:"impl",...Ti.writhe},impatience:{shortName:"IMPAT",...Ti.plumbum},indifference:{shortName:"ind",...Ti.cuprum},itching:{shortName:"itch",...Ti.epidermal},justice:{shortName:"just",...Ti.cuprum},kkractlebrand:{shortName:"kkr",...Ti.health},laceratedthroat:{shortName:"lac2",...Ti.restoration},latched:{shortName:"latch",...Ti.health},lethargy:{shortName:"let",...Ti.ferrum},lightbind:{shortName:"light",fg:"",bg:""},loneliness:{shortName:"lon",...Ti.argentum},lovers:{shortName:"love",...Ti.cuprum},manaleech:{shortName:"man",...Ti.realgar},mangledleftarm:{shortName:"la3",...Ti.restoration},mangledleftleg:{shortName:"ll3",...Ti.restoration},mangledrightarm:{shortName:"ra3",...Ti.restoration},mangledrightleg:{shortName:"rl3",...Ti.restoration},mangledhead:{shortName:"hd3",...Ti.restoration},masochism:{shortName:"maso",...Ti.argentum},mildtrauma:{shortName:"tor1",...Ti.restoration},mycalium:{shortName:"myc",...Ti.plumbum},nausea:{shortName:"nau",...Ti.ferrum},numbedleftarm:{shortName:"nbla",fg:"",bg:""},numbedrightarm:{shortName:"nbra",fg:"",bg:""},pacified:{shortName:"pac",...Ti.cuprum},palpatarfeed:{shortName:"worm",fg:"",bg:""},paralysis:{shortName:"PAR",...Ti.magnesium},paranoia:{shortName:"prn",...Ti.stannum},parasite:{shortName:"prs",...Ti.aurum},peace:{shortName:"pea",...Ti.cuprum},phlogisticated:{shortName:"phlog",fg:"",bg:""},pinshot:{shortName:"psh",fg:"",bg:""},pressure:{shortName:"pres",...Ti.calcite},prone:{shortName:"pr",fg:"",bg:""},pyramides:{shortName:"pyra",...Ti.magnesium},pyre:{shortName:"pyre",...Ti.cuprum},rebbies:{shortName:"reb",...Ti.aurum},recklessness:{shortName:"reck",...Ti.argentum},retribution:{shortName:"retr",...Ti.cuprum},revealed:{shortName:"rev",fg:"",bg:""},sandfever:{shortName:"sand",...Ti.plumbum},scalded:{shortName:"scald",...Ti.epidermal},scytherus:{shortName:"scy",...Ti.ferrum},selarnia:{shortName:"sel",...Ti.mending},sensitivity:{shortName:"sen",...Ti.aurum},serioustrauma:{shortName:"tor2",...Ti.restoration},shadowmadness:{shortName:"shad",...Ti.plumbum},shivering:{shortName:"shiv",...Ti.caloric},shyness:{shortName:"shy",...Ti.plumbum},skullfractures:{shortName:"sf",...Ti.health},slashedthroat:{shortName:"lac1",...Ti.epidermal},sleeping:{shortName:"slp",fg:"",bg:""},slickness:{shortName:"SLI",...Ti.magnesium},slimeobscure:{shortName:"slime",fg:"",bg:""},spiritburn:{shortName:"spirB",...Ti.argentum},spiritwrack:{shortName:"spirW",fg:"",bg:""},stupidity:{shortName:"st",...Ti.plumbum},stuttering:{shortName:"stut",...Ti.epidermal},homunculusmercury:{shortName:"merc",fg:"",bg:""},temperedcholeric:{shortName:"choH",...Ti.antimony},temperedmelancholic:{shortName:"melaH",...Ti.antimony},temperedphlegmatic:{shortName:"phleH",...Ti.antimony},temperedsanguine:{shortName:"sanH",...Ti.antimony},tenderskin:{shortName:"tend",...Ti.argentum},tension:{shortName:"tens",...Ti.cinnabar},timeflux:{shortName:"tmfx",fg:"",bg:""},timeloop:{shortName:"tmlp",...Ti.cuprum},tonguetied:{shortName:"tngt",...Ti.restoration},torntendons:{shortName:"tt",...Ti.health},transfixation:{shortName:"trfx",...Ti.writhe},unweavingbody:{shortName:"unwB",...Ti.ferrum},unweavingspirit:{shortName:"unwS",...Ti.cinnabar},unweavingmind:{shortName:"unwM",...Ti.plumbum},unblind:{shortName:"unB",fg:"",bg:""},undeaf:{shortName:"unD",fg:"",bg:""},vertigo:{shortName:"vert",...Ti.argentum},vitrified:{shortName:"vitri",fg:"",bg:""},voidfisted:{shortName:"void",fg:"",bg:""},voyria:{shortName:"voy",fg:"",bg:""},weariness:{shortName:"wea",...Ti.aurum},webbed:{shortName:"web",...Ti.writhe},whisperingmadness:{shortName:"wmad",...Ti.argentum},wristfractures:{shortName:"wf",...Ti.health}},Ei=Mi.parse({affs:Ai,chrome:{bracket:{fg:"LightGoldenRodYellow",bg:""},detail:{fg:"darkgray",bg:""},tag:{delimiter:{fg:"#784695",bg:""},label:{fg:"#CBCE91",bg:""}},severity:{info:{fg:"#FFF2D7",bg:""},warning:{fg:"orange",bg:""},error:{fg:"red",bg:""}}}}),Ci=Ei.affs,Pi=(Ei.chrome,new Set(["undeaf","unblind","cleanseaura"])),Ri=new Set(["dissonance"]),Zi=new Map([["mangledleftleg","damagedleftleg"],["mangledleftarm","damagedleftarm"],["mangledrightleg","damagedrightleg"],["mangledrightarm","damagedrightarm"],["mangledhead","damagedhead"],["serioustrauma","mildtrauma"],["damagedleftleg","brokenleftleg"],["damagedleftarm","brokenleftarm"],["damagedrightleg","brokenrightleg"],["damagedrightarm","brokenrightarm"]]),Di=(e,t,n={})=>({id:e,kind:t,...n,...Zi.has(e)?{curesTo:Zi.get(e)}:{},...Pi.has(e)?{pseudo:!0}:{},...Ri.has(e)?{curedLast:!0}:{},...Ci[e]?{display:Ci[e]}:{}}),Fi=_i.parse([...["undeaf","unblind","cleanseaura","addiction","agoraphobia","amnesia","anorexia","asphyxiating","asthma","blindness","bloodfire","bound","brokenleftarm","brokenrightarm","brokenleftleg","brokenrightleg","calcifiedskull","calcifiedtorso","claustrophobia","clumsiness","coldfate","concussion","conflagration","confusion","convergence","cremated","crushedthroat","daeggerimpale","damagedhead","damagedleftarm","damagedleftleg","damagedrightarm","damagedrightleg","darkshade","dazed","deadening","deafness","death","deathsickness","deepsleep","degenerate","dementia","depression","deteriorate","diminished","disloyalty","disrupted","dissonance","dizziness","earworm","enlightenment","entangled","epilepsy","fear","flushings","fratricide","frostbite","frozen","fulminated","generosity","grievouswounds","guilt","haemophilia","hallucinations","hatred","healthleech","hellsight","hindered","homunculusmercury","hypersomnia","hypochondria","hypothermia","icebound","impaled","impatience","indifference","insomnia","isolation","itching","justice","kkractlebrand","laceratedthroat","lapsingconsciousness","latched","lethargy","loneliness","lovers","lullaby","manaleech","masochism","mildtrauma","mangledleftarm","mangledleftleg","mangledrightarm","mangledrightleg","mangledhead","mindclamp","mycalium","nausea","pacified","paralysis","paranoia","parasite","peace","penitence","prone","pyramides","rebbies","recklessness","retribution","sandfever","scytherus","selarnia","sensitivity","serioustrauma","shadowmadness","shivering","shyness","slashedthroat","sleeping","slickness","spiritburn","stupidity","stuttering","tenderskin","tension","timeloop","tonguetied","transfixation","vertigo","vitiated","voyria","weariness","webbed","whisperingmadness","harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"].map(e=>Di(e,"plain")),...Object.entries({accentato:{durationMs:2e4,provenance:"unverified"},aeon:{durationMs:16e3},airfisted:{durationMs:16e3},betrayal:{durationMs:15e3},blackout:{durationMs:4e3,provenance:"unverified"},blistered:{durationMs:15e3,provenance:"unverified"},breathless:{durationMs:3e3},bruisedribs:{durationMs:3e4},cadmuscurse:{durationMs:2e4},condemned:{durationMs:2e4},constricted:{durationMs:3e4},corruption:{durationMs:45e3},dazzled:{durationMs:6e4},dehydrated:{durationMs:6e4},demonstain:{durationMs:12e4},empoweredloshre:{durationMs:12e3},empoweredmannaz:{durationMs:2e4},enmesh:{durationMs:5e3},ensorcelled:{durationMs:2e4},flamefisted:{durationMs:3e4},hamstrung:{durationMs:9e3},heartseed:{durationMs:11e3},hecatecurse:{durationMs:16e3},icefisted:{durationMs:3e4},internalbleeding:{durationMs:3e4},inquisition:{durationMs:3e4},kaisurge:{durationMs:15e3,provenance:"unverified"},lightbind:{durationMs:22e3},lovestruck:{durationMs:5e3},mindravaged:{durationMs:2e4,provenance:"unverified"},muddled:{durationMs:12e3},numbedleftarm:{durationMs:7500},numbedrightarm:{durationMs:7500},petrified:{durationMs:1e4,provenance:"unverified"},palpatarfeed:{durationMs:19e3,provenance:"unverified"},phlogisticated:{durationMs:45e3},pinshot:{durationMs:18e3},reeling:{durationMs:2e4},revealed:{durationMs:6e4},scalded:{durationMs:2e4},scrambledbrains:{durationMs:6e4},silenced:{durationMs:2e4,provenance:"unverified"},silver:{durationMs:18e4},slimeobscure:{durationMs:6e4},solarburn:{durationMs:5e3},snared:{durationMs:2e4},speechless:{durationMs:3e5},stridulating:{durationMs:15e3},stun:{durationMs:3e3,provenance:"unverified"},succumbed:{durationMs:3e4},timeflux:{durationMs:6e4},trueblind:{durationMs:6e3},unconsciousness:{durationMs:1e4},vinewreathed:{durationMs:3e4},vitrified:{durationMs:45e3},voidfisted:{durationMs:5e3},waterbonds:{durationMs:3e4},weakenedmind:{durationMs:6e4},woeconstrained:{durationMs:3e4}}).map(([e,t])=>Di(e,"timed",t)),...Object.entries({pressure:{min:0,max:5},crescendo:{min:0,max:5},unweavingbody:{min:0,max:5},unweavingspirit:{min:0,max:5},unweavingmind:{min:0,max:5},burning:{min:0,max:5},horror:{min:0,max:5},pyre:{min:0,max:3},temperedcholeric:{min:0,max:8},temperedmelancholic:{min:0,max:8},temperedphlegmatic:{min:0,max:8},temperedsanguine:{min:0,max:8},torntendons:{min:0,max:6},crackedribs:{min:0,max:6},skullfractures:{min:0,max:6},wristfractures:{min:0,max:6}}).map(([e,t])=>Di(e,"countable",t))]),Li=qr({id:bi,skills:Dr(or().regex(/^[a-z]+$/,"skill keys are single lowercase words")).default([])}),qi=Dr(Li).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"profession ids must be unique"}),Bi=qi.parse([{id:"alchemist",skills:[]},{id:"apostate",skills:[]},{id:"bard",skills:[]},{id:"blademaster",skills:[]},{id:"depthswalker",skills:["aeonics","shadowmancy"]},{id:"dragon",skills:["dragoncraft"]},{id:"firelord",skills:[]},{id:"jester",skills:["tarot"]},{id:"magi",skills:["elementalism","crystalism","artificing"]},{id:"monk",skills:[]},{id:"occultist",skills:["occultism","domination","tarot"]},{id:"priest",skills:[]},{id:"psion",skills:["weaving"]},{id:"runewarden",skills:[]},{id:"serpent",skills:["venom"]},{id:"shikudo",skills:[]}]),Gi=Gr([hi,Dr(hi).min(2)]),Ji=qr({id:gi,command:or().min(1),class:Wr(["linear","tree","special"]),order:Dr(hi).default([]),ordered:Ar().default(!1),layered:Ar().default(!1),bals_used:Dr(mi).default([]),bals_req:Dr(mi).default([]),blocks:Dr(Gi).default([]),professions:Dr(bi).optional(),bestowable:Ar().default(!1),prio:xr().int().min(0),delayMs:xr().int().positive().optional()}).refine(e=>!e.bestowable||void 0!==e.professions,{message:"bestowable is a class-cure trait — it requires a professions gate"}),Ui=Dr(Ji).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"cure ids must be unique"}),Hi=["itching","paralysis","fear","brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg","lapsingconsciousness","aeon","lovers","confusion","epilepsy","pacified","blackout","dazed","justice","slashedthroat","hellsight","peace","dazzled","shyness","dizziness","slickness","asthma","nausea","selarnia","weariness","scytherus","fratricide","haemophilia","clumsiness","hallucinations","healthleech","dementia","recklessness","anorexia","masochism","impatience","stupidity","generosity","addiction","deadening","manaleech","stuttering","paranoia","agoraphobia","loneliness","claustrophobia","vertigo","hypersomnia","shivering","frozen","burning","sensitivity","hypochondria","lethargy","disloyalty","darkshade","voyria","dissonance","phlogisticated","silver","spiritburn","tenderskin","guilt","skullfractures","wristfractures","crackedribs","torntendons","indifference","retribution","shadowmadness","parasite","depression","timeloop","crushedthroat","tension","unweavingspirit","grievouswounds","pyramides","flushings","rebbies","mycalium","sandfever","crescendo","fulminated","frostbite"],Vi=["death","anorexia","sleeping"],Yi=["death","asthma","sleeping"],Wi=["death","slickness","sleeping"],Ki=["death","sleeping","anorexia"],Qi=[["brokenleftarm","brokenrightarm"],["brokenleftarm","damagedrightarm"],["brokenleftarm","mangledrightarm"],["damagedleftarm","brokenrightarm"],["damagedleftarm","damagedrightarm"],["damagedleftarm","mangledrightarm"],["mangledleftarm","brokenrightarm"],["mangledleftarm","damagedrightarm"],["mangledleftarm","mangledrightarm"]],Xi=["entangled","transfixation","impaled","webbed","bound"],es=["darkshade","haemophilia","lethargy","addiction","scytherus","nausea","flushings","unweavingbody"],ts=["paralysis","slickness","pyramides"],ns=["clumsiness","healthleech","sensitivity","weariness","asthma","hypochondria","rebbies","parasite"],rs=["undeaf","deafness"],is=["horror","fratricide","masochism","loneliness","vertigo","recklessness","agoraphobia","guilt","whisperingmadness","spiritburn","tenderskin"],ss=["pacified","peace","lovers","justice","generosity","indifference","retribution","pyre","timeloop","diminished","stridulating"],as=["temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"],os=["unblind","blindness"],ds=["claustrophobia","paranoia","confusion","hypersomnia","hallucinations","dementia","crescendo"],ls=["stupidity","epilepsy","dizziness","shyness","impatience","dissonance","depression","sandfever","mycalium","shadowmadness","unweavingmind","fulminated"],cs=["pressure"],fs=["disloyalty","hellsight","manaleech","slickness"],us=["aeon","deadening","tension","unweavingspirit","earworm"],ps=(e,t,n={})=>({id:e,command:`eat ${e}`,class:"linear",order:t,bals_used:["herb"],bals_req:["herb"],blocks:Vi,prio:0,...n}),hs=(e,t)=>({id:e,command:`smoke ${e}`,class:"linear",...t?{order:t}:{},bals_used:["smoke"],bals_req:["smoke"],blocks:Yi,prio:0}),ms=(e,t,n={})=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["salve"],bals_req:["salve","restoration"],blocks:Wi,prio:0,...n}),gs=(e,t)=>({...ms(e,t),bals_used:["restoration"],delayMs:4e3}),ys=(e,t)=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["sip"],bals_req:["sip"],prio:0}),bs=(e,t)=>({id:e,class:"tree",order:Hi,prio:0,...t}),vs=Ui.parse([ps("ferrum",es),ps("magnesium",ts),ps("aurum",ns),ps("calamine",rs,{delayMs:2500}),ps("argentum",is),ps("cuprum",ss),ps("antimony",as),ps("arsenic",os),ps("stannum",ds),ps("plumbum",ls,{class:"special"}),ps("calcite",cs),ps("ginseng",es),ps("bloodroot",ts),ps("kelp",ns),ps("hawthorn",rs,{delayMs:2500}),ps("lobelia",is),ps("bellwort",ss),ps("ginger",as),ps("bayberry",os),ps("ash",ds),ps("goldenseal",ls,{class:"special"}),ps("pear",cs),{...hs("smoke",["aeon","disloyalty","hellsight","manaleech","slickness","deadening","tension","unweavingspirit","earworm"]),command:"smoke cinnabar"},hs("cinnabar",us),hs("malachite"),hs("realgar",fs),hs("elm",us),hs("skullcap"),hs("valerian",fs),ms("caloric",["frozen","shivering","frostbite"],{layered:!0}),ms("epidermal to body",["anorexia"]),ms("epidermal to head",["stuttering","blindness","deafness"]),ms("epidermal to ears",["deafness"]),ms("mending to head",["crushedthroat","dazzled"]),ms("mending to arms",["brokenleftarm","brokenrightarm"],{ordered:!0}),ms("mending to legs",["brokenleftleg","brokenrightleg"],{ordered:!0}),ms("mending to body",["burning"]),gs("restoration to head",["mangledhead","damagedhead","calcifiedskull","concussion","tonguetied"]),gs("restoration to torso",["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso","internalbleeding"]),gs("restoration to arms",["mangledleftarm","mangledrightarm","damagedleftarm","damagedrightarm"]),gs("restoration to legs",["mangledleftleg","mangledrightleg","damagedleftleg","damagedrightleg"]),{id:"health",command:"sip health",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:Ki,prio:0},{id:"mana",command:"sip mana",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:Ki,prio:0},ys("health to head",["skullfractures"]),ys("health to torso",["crackedribs","grievouswounds"]),ys("health to arms",["wristfractures"]),ys("health to legs",["torntendons","latched","kkractlebrand"]),{id:"fitness",command:"fitness",class:"linear",order:["asthma"],bals_used:["balance","fitness"],bals_req:["equilibrium","balance","fitness"],blocks:["death","weariness","sleeping"],professions:["monk","shikudo","runewarden"],prio:0},bs("bloodboil",{command:"cast bloodboil",bals_used:["equilibrium","bloodboil"],bals_req:["equilibrium","balance","bloodboil"],blocks:["death","haemophilia","sleeping",...Qi,...Xi],professions:["magi"]}),{id:"dragonflex",command:"dragonflex",class:"linear",order:["webbed","entangled"],bals_used:["balance"],bals_req:["balance"],professions:["dragon"],prio:0},bs("dragonheal",{command:"dragonheal",bals_used:["dragonheal","equilibrium"],bals_req:["balance","equilibrium"],blocks:["death","sleeping",["recklessness","weariness"]],professions:["dragon"]}),{id:"dwinnu",command:"chant dwinnu",class:"linear",order:["webbed","entangled"],bals_used:["voice"],bals_req:["voice"],professions:["bard"],prio:0},{id:"rage",command:"rage",class:"linear",order:["pacified","peace","lovers","generosity","stridulating"],bals_used:["rage"],bals_req:["rage"],professions:["runewarden"],prio:95},bs("salt",{command:"educe salt",bals_used:["salt","equilibrium"],bals_req:["equilibrium","salt"],blocks:["death","stupidity","sleeping"],professions:["alchemist"]}),bs("siphon",{command:"siphon",bals_used:["angel"],bals_req:["angel"],blocks:["death","sleeping"],professions:["apostate","priest"]}),bs("shrugging",{command:"shrugging",bals_used:["shrugging"],bals_req:["equilibrium","balance","shrugging"],blocks:["death","weariness","sleeping"],professions:["serpent"]}),bs("slough",{command:"slough impurities",bals_used:["slough","balance"],bals_req:["equilibrium","balance","slough"],blocks:["death","weariness","sleeping"],professions:["firelord"]}),bs("fool",{command:"fling fool at me",bals_used:["fool","balance"],bals_req:["equilibrium","balance","fool"],blocks:["death","prone","paralysis","sleeping",...Qi,...Xi],professions:["occultist"]}),bs("accelerate",{command:"chrono accelerate",bals_used:["accelerate","balance"],bals_req:["equilibrium","balance","accelerate"],blocks:["death","sleeping","recklessness"],professions:["depthswalker"]}),bs("alleviate",{command:"alleviate",bals_used:["alleviate","balance"],bals_req:["equilibrium","balance","alleviate"],blocks:["death","paralysis","sleeping"],professions:["blademaster"]}),bs("dagaz",{command:"sketch dagaz on ground",bals_used:["dagaz"],blocks:["death"],professions:["runewarden"],bestowable:!0}),bs("generic",{command:"classcure",bals_used:["generic"],bals_req:["equilibrium","balance","generic"],blocks:["death"],professions:[]}),{id:"insomnia",command:"insomnia",class:"linear",order:["insomnia"],blocks:["death","hypersomnia","sleeping"],prio:0},{id:"focus",command:"focus",class:"linear",order:["stupidity","epilepsy","dizziness","shyness","claustrophobia","paranoia","confusion","hallucinations","dementia","pacified","peace","lovers","generosity","masochism","loneliness","vertigo","recklessness","agoraphobia","anorexia","stuttering"],bals_used:["focus"],bals_req:["focus"],blocks:["death","impatience","sleeping"],prio:0},{id:"concentrate",command:"concentrate",class:"linear",order:["disrupted"],blocks:["death","sleeping","confusion"],prio:0},{id:"immunity",command:"sip immunity",class:"linear",order:["voyria"],bals_used:["immunity"],bals_req:["immunity"],blocks:Ki,prio:0},{id:"stand",command:"stand",class:"linear",order:["prone"],bals_req:["balance","equilibrium"],blocks:["death","sleeping","paralysis","brokenrightleg","brokenleftleg","damagedleftleg","damagedrightleg","mangledrightleg","mangledleftleg",...Xi],prio:0},bs("tree",{command:"touch tree",bals_used:["tree"],bals_req:["tree"],blocks:["death","sleeping","paralysis",...Qi,...Xi]}),{id:"potash",command:"eat potash",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:Ki,prio:0},{id:"moss",command:"eat moss",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:Ki,prio:0},{id:"restore",command:"restore",class:"linear",order:["brokenleftarm","brokenrightarm","brokenleftleg","brokenrightleg","skullfractures","torntendons","wristfractures","crackedribs"],bals_used:["equilibrium"],bals_req:["balance","equilibrium"],prio:0},{id:"touch soul",command:"touch soul",class:"linear",order:["amnesia"],blocks:["death"],prio:101}]),ks=Dr(qr({id:mi,observedDurationMs:xr().int().positive(),predictiveDurationMs:xr().int().positive(),bufferPolicy:Wr(["buffered","exact"])}).refine(e=>"buffered"===e.bufferPolicy?e.observedDurationMs===Math.round(.75*e.predictiveDurationMs):e.observedDurationMs===e.predictiveDurationMs,{message:"observedDurationMs must follow the declared bufferPolicy"})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"balance ids must be unique"}),ws=(e,t)=>({id:e,predictiveDurationMs:t,observedDurationMs:Math.round(.75*t),bufferPolicy:"buffered"}),Is=ks.parse([ws("balance",2e3),ws("equilibrium",2e3),ws("sip",4500),ws("herb",1500),ws("smoke",1500),ws("salve",1e3),ws("restoration",4e3),ws("focus",2500),ws("tree",15e3),ws("moss",6e3),ws("immunity",1e4),ws("accelerate",1e4),ws("alleviate",1e4),ws("angel",1e4),ws("bloodboil",1e4),ws("dragonheal",2e4),ws("fitness",1e4),ws("fool",3e4),ws("rage",1e4),ws("salt",1e4),ws("shrugging",12e3),ws("slough",1e4),ws("dagaz",2e4),ws("voice",2500),ws("generic",12e3)]),zs=Dr(qr({id:hi,level:xr().int().min(1),prio:xr().int().min(0)})).min(1).refine(e=>new Set(e.map(e=>`${e.id}:${e.level}`)).size===e.length,{message:"priority (id, level) pairs must be unique"}),_s=(e,t)=>t.map(t=>({id:t,level:1,prio:e})),Os=(e,t,n)=>Array.from({length:t},(t,r)=>({id:e,level:r+1,prio:n})),$s=zs.parse([..._s(0,["accentato","airfisted","asphyxiating","blistered","bloodfire","bruisedribs","cadmuscurse","coldfate","condemned","conflagration","constricted","convergence","corruption","cremated","death","deathsickness","deepsleep","degenerate","dehydrated","demonstain","deteriorate","empoweredloshre","empoweredmannaz","enlightenment","enmesh","ensorcelled","flamefisted","hamstrung","hatred","hecatecurse","hindered","homunculusmercury","icefisted","inquisition","isolation","kaisurge","lightbind","lullaby","mindclamp","mindravaged","muddled","numbedleftarm","numbedrightarm","palpatarfeed","petrified","phlogisticated","pinshot","revealed","scalded","scrambledbrains","silenced","silver","slimeobscure","solarburn","stun","timeflux","trueblind","vinewreathed","vitiated","vitrified","voidfisted","waterbonds","weakenedmind","unconsciousness"]),..._s(2,["aeon","concussion","crushedthroat","paralysis","peace"]),..._s(3,["sleeping","grievouswounds","latched","dazzled","weariness","prone","timeloop","fulminated"]),...Os("unweavingbody",5,3),...Os("unweavingmind",5,3),...Os("unweavingspirit",5,3),..._s(4,["spiritburn","heartseed","guilt","tenderskin","pyramides","parasite","hypochondria","pacified","depression","confusion","retribution","shadowmadness","whisperingmadness","hellsight"]),..._s(5,["anorexia","mycalium","flushings","rebbies","sandfever","asthma","healthleech"]),..._s(6,["impatience","itching","scytherus","clumsiness","kkractlebrand","damagedleftleg","darkshade","slickness","recklessness","dementia","fratricide","icebound"]),..._s(7,["bound","daeggerimpale","entangled","sensitivity","transfixation","webbed","tonguetied","haemophilia","lethargy","manaleech","dissonance"]),{id:"pyre",level:1,prio:7},{id:"pyre",level:2,prio:6},{id:"pyre",level:3,prio:5},..._s(8,["damagedrightleg","hypersomnia","earworm","diminished"]),...Os("skullfractures",6,8),...Os("crescendo",5,8),..._s(9,["brokenleftleg","brokenrightleg","hallucinations"]),...Os("torntendons",6,9),..._s(10,["calcifiedskull","calcifiedtorso","mangledleftleg","mangledrightleg","disrupted","mangledhead","voyria"]),...Os("crackedribs",6,10),..._s(11,["hypothermia","impaled","brokenleftarm","brokenrightarm","indifference","addiction","nausea","deadening","frozen","shivering","mildtrauma","internalbleeding"]),..._s(12,["stupidity","damagedleftarm","disloyalty"]),...Os("wristfractures",6,12),..._s(13,["tension","damagedhead","dazed"]),...Os("burning",5,13),..._s(14,["lovers","damagedrightarm","temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"]),...Os("pressure",5,14),..._s(15,["mangledleftarm","mangledrightarm"]),..._s(16,["agoraphobia","claustrophobia","generosity","justice","loneliness","vertigo"]),..._s(17,["paranoia"]),..._s(18,["serioustrauma","epilepsy"]),..._s(20,["laceratedthroat","slashedthroat","stuttering"]),..._s(21,["selarnia","fear","masochism"]),..._s(23,["dizziness","shyness"]),...Os("horror",5,26),..._s(30,["amnesia","blackout"]),..._s(0,["insomnia","deafness","blindness"]),..._s(100,["harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"])]),Ss=qr({profession:bi,pools:Vr(or().min(1),Dr(hi).min(1))}),Ns=Dr(Ss).min(1).refine(e=>new Set(e.map(e=>e.profession)).size===e.length,{message:"professions must be unique"}),xs=Ns.parse([{profession:"occultist",pools:{mentals:["claustrophobia","agoraphobia","lovers","dementia","epilepsy","hallucinations","confusion","stupidity","paranoia","vertigo","shyness","addiction","recklessness","masochism"],physicals:["asthma","paralysis","slickness","haemophilia","clumsiness","healthleech","sensitivity","darkshade"],bubonis:["vertigo","recklessness","confusion","masochism","paranoia","shyness","claustrophobia"],chimera:["confusion","hallucinations","agoraphobia","claustrophobia","dementia"],moon:["stupidity","masochism","hallucinations","hypersomnia","confusion","epilepsy","claustrophobia","agoraphobia"],whisperingmadness:["dementia","stupidity","confusion","hypersomnia","paranoia","hallucinations","impatience","addiction","agoraphobia","lovers","loneliness","recklessness","masochism"],justice:["paralysis","sensitivity","healthleech","haemophilia","weariness","asthma","clumsiness"]}},{profession:"psion",pools:{blast:["impatience","stupidity","blackout","dizziness","epilepsy","unweavingmind"]}},{profession:"depthswalker",pools:{leach:["parasite","healthleech","manaleech"],madness:["shadowmadness","vertigo","hallucinations"],retribution:["retribution","justice"],degeneration:["clumsiness","weariness","paralysis"],depression:["depression","nausea","hypochondria"]}}]),js=Dr(qr({id:yi,aff:hi.nullable()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"venom ids must be unique"}),Ms=js.parse([{id:"xentio",aff:"clumsiness"},{id:"eurypteria",aff:"recklessness"},{id:"kalmia",aff:"asthma"},{id:"digitalis",aff:"shyness"},{id:"darkshade",aff:"darkshade"},{id:"curare",aff:"paralysis"},{id:"epteth",aff:null},{id:"prefarar",aff:"sensitivity"},{id:"monkshood",aff:"disloyalty"},{id:"euphorbia",aff:"nausea"},{id:"oculus",aff:"unblind"},{id:"vernalius",aff:"weariness"},{id:"epseth",aff:null},{id:"larkspur",aff:"dizziness"},{id:"slike",aff:"anorexia"},{id:"delphinium",aff:"sleeping"},{id:"notechis",aff:"haemophilia"},{id:"vardrax",aff:"addiction"},{id:"loki",aff:"loki"},{id:"aconite",aff:"stupidity"},{id:"selarnia",aff:null},{id:"gecko",aff:"slickness"},{id:"scytherus",aff:"scytherus"},{id:"nechamadra",aff:"shivering"}]),Ts=new Map(Fi.map(e=>[e.id,e])),As=new Map(vs.map(e=>[e.id,e])),Es=new Map(Is.map(e=>[e.id,e])),Cs=(()=>{const e=new Map;for(const t of $s)e.has(t.id)||e.set(t.id,new Map),e.get(t.id).set(t.level,t.prio);return e})(),Ps=(...e)=>new Set(vs.filter(t=>t.bals_used.some(t=>e.includes(t))).map(e=>e.id)),Rs=Object.freeze({layers:Object.freeze(vs.filter(e=>e.layered).map(e=>Object.freeze([...e.order]))),curedLast:Object.freeze(Fi.filter(e=>e.curedLast).map(e=>Object.freeze({affId:e.id,pool:Object.freeze([...new Set(vs.filter(t=>"tree"!==t.class&&t.order.includes(e.id)).flatMap(e=>e.order).filter(t=>t!==e.id))])})))}),Zs=e=>new Set(vs.filter(t=>e.has(t.id)).flatMap(e=>e.order)),Ds=Zs(Ps("herb")),Fs=Zs(Ps("smoke")),Ls=new Map(Ms.map(e=>[e.id,e.aff])),qs=new Map(xs.map(e=>[e.profession,e.pools])),Bs=(()=>{const e=new Map;for(const t of Bi)for(const n of t.skills)e.set(n,e.has(n)?null:t.id);return new Map([...e].filter(([,e])=>null!==e))})(),Gs=Object.freeze({epsilon:1e-4,forkCap:128}),Js=(e,t)=>{if(!e)throw new Error(`insight engine: ${t}`)},Us=e=>Object.keys(e).sort().map(t=>`${t}=${!0===e[t]?"t":e[t]}`).join(","),Hs=(e,t)=>{let n=0;for(const r of Object.keys(e))if(Object.hasOwn(t,r)){if(e[r]!==t[r]){const i=!0===e[r]?1:e[r],s=!0===t[r]?1:t[r];n+=Math.abs(i-s)}}else n+=1;for(const r of Object.keys(t))Object.hasOwn(e,r)||(n+=1);return n},Vs=e=>Object.freeze({p:e.p,affs:Object.freeze({...e.affs})}),Ys=e=>({p:e.p,affs:{...e.affs}}),Ws=e=>{const t=e.reduce((e,t)=>e+t.p,0);if(Js(t>0,"cannot normalize a belief with zero total mass"),Math.abs(t-1)>1e-12)for(const n of e)n.p/=t;return e},Ks=Object.freeze([]),Qs=(e,t,{contradiction:n=!1}={})=>{Js(Array.isArray(e)&&e.length>0,"finalizeForks needs at least one fork");const r=t?.growth??Gs;let i=(e=>{const t=new Map;for(const n of e){const e=Us(n.affs),r=t.get(e);r?r.p+=n.p:t.set(e,{p:n.p,affs:n.affs,encoding:e})}return[...t.values()]})(e);i=Ws(i);const{forks:s,capDiagnostic:a}=((e,t)=>{if(t<=0||e.length<=t)return{forks:e,capDiagnostic:null};const n=[...e].sort((e,t)=>t.p-e.p||(e.encoding<t.encoding?-1:1)).slice(0,t);return{forks:Ws(n),capDiagnostic:{type:"forkCapExceeded",beforeCount:e.length,afterCount:n.length,forkCap:t}}})(i,r.forkCap??Gs.forkCap);return i=((e,t)=>{if(t<=0||e.length<2)return e;const n=e.filter(e=>e.p>=t);if(0===n.length||n.length===e.length)return e;for(const r of e){if(r.p>=t)continue;let e=null,i=1/0;for(const t of n){const n=Hs(r.affs,t.affs);(n<i||n===i&&(t.p>e.p||t.p===e.p&&t.encoding<e.encoding))&&(e=t,i=n)}e.p+=r.p}return n})(s,r.epsilon??Gs.epsilon),i.sort((e,t)=>e.encoding<t.encoding?-1:e.encoding>t.encoding?1:0),!0===t?.guards?Object.freeze({forks:Object.freeze(i.map(Vs)),contradiction:n,diagnostics:a?Object.freeze([Object.freeze(a)]):Ks}):{forks:i.map(Ys),contradiction:n,diagnostics:a?[a]:Ks}},Xs=e=>!1===e.contradiction&&0===e.diagnostics.length,ea=(e,t)=>!0===t?.guards?Object.freeze({forks:Object.freeze(e.forks.map(Vs)),contradiction:!0,diagnostics:e.diagnostics}):{forks:e.forks,contradiction:!0,diagnostics:e.diagnostics},ta=({guards:e=!1}={})=>{const t={forks:[{p:1,affs:{}}],contradiction:!1,diagnostics:Ks};return e?Object.freeze({...t,forks:Object.freeze(t.forks.map(Vs))}):t},na=e=>"countable"!==e.kind||1,ra=(e,t)=>{const n=e.affById.get(t);return Js(n,`unknown affliction '${t}'`),n},ia=Object.freeze(["uniform","firstMissing","ordered"]),sa=new Set,aa=(e,t,n,r=sa)=>{let i=((e,t)=>{let n=e;for(const r of t.layers){const e=r.find(e=>n.includes(e));e&&(n=n.filter(t=>!r.includes(t)||t===e))}for(const r of t.curedLast)n.includes(r.affId)&&r.pool.some(e=>n.includes(e))&&(n=n.filter(e=>e!==r.affId));return n})(Object.keys(e),n.cureMasks);if(t.ordered){const e=t.order.find(e=>i.includes(e));i=i.filter(n=>!t.order.includes(n)||n===e)}return t.order.filter(e=>i.includes(e)&&!r.has(e))},oa=(e,t,n)=>{const r=ra(n,t),i={...e};if("countable"===r.kind){const e=i[t]-1;e<=r.min?delete i[t]:i[t]=e}else delete i[t];if(r.curesTo){const e=ra(n,r.curesTo);i[e.id]=na(e)}return i},da=Object.freeze(["=","!=","<","<=",">",">="]),la=(e,t,n)=>{switch(t){case"=":return e===n;case"!=":return e!==n;case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:return Js(!1,`unknown comparison operator '${t}'`),!1}},ca=Object.freeze({afflicted:(e,t,n)=>{const r=ra(n,t.affId),i="countable"!==r.kind||r.max;return Xs(e)&&e.forks.every(e=>e.affs[r.id]===i)?e:Qs(e.forks.map(e=>{const t={...e.affs};if("countable"===r.kind){const e=t[r.id]??r.min;t[r.id]=Math.min(e+1,r.max)}else t[r.id]=!0;return{p:e.p,affs:t}}),n)},afflictedOneOf:(e,t,n)=>{const{pool:r,mode:i}=t;Js(Array.isArray(r)&&r.length>0,"afflictedOneOf needs a non-empty pool"),Js(ia.includes(i),`unknown afflictedOneOf mode '${i}'`);const s=new Map(r.map(e=>[e,ra(n,e)]));if(Xs(e)&&e.forks.every(e=>r.every(t=>Object.hasOwn(e.affs,t))))return e;const a=[];for(const o of e.forks){if("uniform"===i){const e=o.p/r.length;for(const t of r){const n={...o.affs};Object.hasOwn(n,t)||(n[t]=na(s.get(t))),a.push({p:e,affs:n})}continue}const e=r.filter(e=>!Object.hasOwn(o.affs,e));if(0===e.length){a.push({p:o.p,affs:o.affs});continue}if("ordered"===i){const t=e[0];a.push({p:o.p,affs:{...o.affs,[t]:na(s.get(t))}});continue}const t=o.p/e.length;for(const n of e)a.push({p:t,affs:{...o.affs,[n]:na(s.get(n))}})}return Qs(a,n)},advanced:(e,t,n)=>{Js(Array.isArray(t.rungs)&&t.rungs.length>0,"advanced needs rungs");const r=new Set,i=new Map;for(const o of t.rungs){Js(o&&"string"==typeof o.affId,"advanced rungs need an affId"),Js(!r.has(o.affId),`advanced has duplicate rung '${o.affId}'`),r.add(o.affId),i.set(o.affId,ra(n,o.affId));for(const e of[...o.gains??[],...o.consumes??[]])i.set(e,ra(n,e))}let s=!1;const a=e.forks.map(e=>{let n=-1;for(let i=0;i<t.rungs.length;i+=1)Object.hasOwn(e.affs,t.rungs[i].affId)&&(n=i);const r=t.rungs.slice(0,Math.max(0,n)),a=r.some(({affId:t})=>Object.hasOwn(e.affs,t)),o=n===t.rungs.length-1;if(o&&!a)return{p:e.p,affs:e.affs};const d={...e.affs};for(const{affId:t}of r)delete d[t];if(!o){n>=0&&delete d[t.rungs[n].affId];const e=t.rungs[n+1];d[e.affId]=na(i.get(e.affId));for(const t of e.gains??[])d[t]=na(i.get(t));for(const t of e.consumes??[])delete d[t]}return s=!0,{p:e.p,affs:d}});return!s&&Xs(e)?e:Qs(a,n)},cured:(e,t,n)=>{const r=((e,t)=>{const n=e.cureById.get(t);return Js(n,`unknown cure '${t}'`),n})(n,t.cureId);if(0===r.order.length)return e;const i=new Set(t.excludedAffs??[]),s=[];let a=!1;for(const o of e.forks){const e=aa(o.affs,r,n,i);if(0===e.length)continue;a=!0;const t=o.p/e.length;for(const r of e)s.push({p:t,affs:oa(o.affs,r,n)})}return a?Qs(s,n):e},confirmed:(e,t,n)=>{const r=ra(n,t.affId),{present:i}=t,s=e.forks.filter(e=>Object.hasOwn(e.affs,t.affId)===i);return s.length===e.forks.length&&Xs(e)?e:s.length>0?Qs(s.map(e=>({p:e.p,affs:e.affs})),n):Qs(e.forks.map(e=>{const t={...e.affs};return i?t[r.id]=na(r):delete t[r.id],{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedBlocked:(e,t,n)=>{const r=ra(n,t.blockerId),{pool:i}=t;Js(Array.isArray(i)&&i.length>0,"confirmedBlocked needs a non-empty pool");for(const a of i)ra(n,a);const s=e.forks.filter(e=>Object.hasOwn(e.affs,r.id)||!i.some(t=>Object.hasOwn(e.affs,t)));return s.length===e.forks.length&&Xs(e)?e:s.length>0?Qs(s.map(e=>({p:e.p,affs:e.affs})),n):Qs(e.forks.map(e=>({p:e.p,affs:{...e.affs,[r.id]:e.affs[r.id]??na(r)}})),n,{contradiction:!0})},confirmedCount:(e,t,n)=>{const{pool:r,op:i,n:s}=t;Js(Array.isArray(r)&&r.length>0,"confirmedCount needs a non-empty pool"),Js(Number.isInteger(s)&&s>=0,"confirmedCount needs an integer n >= 0");for(const o of r)ra(n,o);const a=e.forks.filter(e=>la((e=>r.reduce((t,n)=>t+(Object.hasOwn(e.affs,n)?1:0),0))(e),i,s));return a.length===e.forks.length&&Xs(e)?e:a.length>0?Qs(a.map(e=>({p:e.p,affs:e.affs})),n):"="===i&&0===s||"<"===i&&s<=1||"<="===i&&0===s?Qs(e.forks.map(e=>{const t={...e.affs};for(const n of r)delete t[n];return{p:e.p,affs:t}}),n,{contradiction:!0}):ea(e,n)},confirmedLevel:(e,t,n)=>{const{affId:r,op:i,n:s}=t,a=ra(n,r);Js("countable"===a.kind,`confirmedLevel needs a countable aff, got '${r}'`),Js(Number.isInteger(s)&&s>=0,"confirmedLevel needs an integer n >= 0");const o=e.forks.filter(e=>la((e=>Object.hasOwn(e.affs,r)?e.affs[r]:0)(e),i,s));if(o.length===e.forks.length&&Xs(e))return e;if(o.length>0)return Qs(o.map(e=>({p:e.p,affs:e.affs})),n);const d=((e,t)=>{switch(e){case"=":case"<=":case">=":return t;case"<":return t-1;case">":return t+1;default:return null}})(i,s);return null===d||d<0||d>a.max||!la(d,i,s)?ea(e,n):Qs(e.forks.map(e=>{const t={...e.affs};return 0===d?delete t[r]:t[r]=d,{p:e.p,affs:t}}),n,{contradiction:!0})},converted:(e,t,n)=>{const r=ra(n,t.from),i=ra(n,t.to);return e.forks.some(e=>Object.hasOwn(e.affs,r.id))?Qs(e.forks.map(e=>{if(!Object.hasOwn(e.affs,r.id))return{p:e.p,affs:e.affs};const t={...e.affs},n=t[r.id];if(delete t[r.id],"countable"===i.kind){const e=!0===n?1:n;t[i.id]=Math.min(Math.max(e,1),i.max)}else t[i.id]=!0;return{p:e.p,affs:t}}),n):e},removed:(e,t,n)=>{const r=ra(n,t.affId);return Xs(e)&&!e.forks.some(e=>Object.hasOwn(e.affs,r.id))?e:Qs(e.forks.map(e=>{if(!Object.hasOwn(e.affs,r.id))return{p:e.p,affs:e.affs};const t={...e.affs};return delete t[r.id],{p:e.p,affs:t}}),n)},predictedCure:(e,t,n)=>{const{forkBranches:r}=t;if(Js(Array.isArray(r),"predictedCure needs a forkBranches array"),0===r.length)return e;const i=new Map;for(const a of r)Js(Number.isInteger(a?.forkIndex)&&a.forkIndex>=0&&a.forkIndex<e.forks.length,`predictedCure fork index '${a?.forkIndex}' is out of range`),Js(!i.has(a.forkIndex),`predictedCure addresses fork ${a.forkIndex} twice`),Js(Array.isArray(a.options)&&a.options.length>0,`predictedCure fork ${a.forkIndex} needs at least one option`),i.set(a.forkIndex,a.options);const s=[];return e.forks.forEach((e,t)=>{const r=i.get(t);if(!r)return void s.push({p:e.p,affs:e.affs});let a=0;for(const n of r)Js("number"==typeof n.weight&&Number.isFinite(n.weight)&&n.weight>0,`predictedCure option weight for '${n.affId}' must be a positive number`),Js(Object.hasOwn(e.affs,n.affId),`predictedCure option '${n.affId}' is absent from fork ${t}`),a+=n.weight;for(const i of r)s.push({p:e.p*(i.weight/a),affs:oa(e.affs,i.affId,n)})}),Qs(s,n)}}),fa=(Object.freeze(Object.keys(ca)),(e,t)=>Object.hasOwn(e.affs,t)),ua=e=>{Js(Array.isArray(e)&&e.length>0,"affliction projection needs a non-empty pool");const t=new Set;for(const n of e)Js("string"==typeof n&&n.length>0,"affliction pool ids must be non-empty strings"),Js(!t.has(n),`affliction pool contains duplicate '${n}'`),t.add(n)},pa=(e,t)=>t.reduce((t,n)=>t+(fa(e,n)?1:0),0),ha=(e,t)=>{let n=0;for(const r of e.forks)fa(r,t)&&(n+=r.p);return n},ma=(e,t)=>{ua(t);let n=0;for(const r of e.forks)t.some(e=>fa(r,e))&&(n+=r.p);return n},ga=(e,t)=>{ua(t);let n=0;for(const r of e.forks)t.every(e=>fa(r,e))&&(n+=r.p);return n},ya=(e,t)=>{ua(t);let n=0;for(const r of e.forks)n+=r.p*pa(r,t);return n},ba=(e,t)=>{let n=0,r=0;for(const i of e.forks)if(fa(i,t)){const e=!0===i.affs[t]?1:i.affs[t];n+=i.p,r+=e*i.p}return 0===n?0:r/n},va=e=>{let t=0;for(const n of e.forks)n.p>0&&(t-=n.p*Math.log2(n.p));return t},ka=Object.freeze(["healthy","damaged","mangled"]),wa=(e,t)=>{if(!e)throw new Error(`insight domain: ${t}`)},Ia=Object.freeze(["best","worst","distribution"]),za=["focus","herb","smoke","salve","restoration","sip","tree","balance","equilibrium"],_a=new WeakMap,Oa=(e,t,n=1)=>{const r=e.priorityByAff.get(t);if(!r)return null;const i=r.get(n);if(void 0!==i)return i;let s=null,a=null;for(const o of r.keys())o<=n&&(null===s||o>s)&&(s=o),(null===a||o<a)&&(a=o);return r.get(s??a)},$a=(e,t)=>t.some(t=>Array.isArray(t)?t.every(t=>Object.hasOwn(e,t)):Object.hasOwn(e,t)),Sa=(e,t)=>!e.professions||null!==t&&e.professions.includes(t),Na=e=>e.reduce((e,t)=>t.prio<e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),xa=e=>e.reduce((e,t)=>t.prio>e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),ja=(e,t,n,r)=>{wa(Ia.includes(n),`unknown predictive policy '${n}'`);const i=[],s=new Set;return e.forks.forEach((e,a)=>{const o=((e,t,n)=>{const{tables:r,context:i,opponentClass:s,isBalanceReady:a}=n,o=i.curesByChannel.get(t);if(!o)return[];const d=new Map;for(const l of o)if(Sa(l,s)&&l.bals_req.every(a)&&!$a(e,l.blocks))for(const t of aa(e,l,r)){const n=Oa(r,t,!0===e[t]?1:e[t]);if(null===n||n<1||n>25)continue;const i=d.get(t);(!i||l.id<i.cureId)&&d.set(t,{affId:t,prio:n,cureId:l.id,balsUsed:l.bals_used})}return[...d.values()]})(e.affs,t,r);if(0===o.length)return;let d;d="best"===n?[{...Na(o),weight:1}]:"worst"===n?[{...xa(o),weight:1}]:(e=>{const t=[...e].sort((e,t)=>e.prio-t.prio||(e.affId<t.affId?-1:1));let n=0,r=null;return t.map(e=>(e.prio!==r&&(n+=1,r=e.prio),{...e,weight:1/n}))})(o);for(const t of d)for(const e of t.balsUsed)s.add(e);i.push({forkIndex:a,options:d.map(({affId:e,weight:t})=>({affId:e,weight:t}))})}),0===i.length?null:{event:{type:"predictedCure",forkBranches:i},consumed:s}},Ma=Object.freeze({stalenessHalfLifeMs:6e4,entropyScaleBits:Math.log2(Gs.forkCap)}),Ta=(e,t={})=>{const n=t.stalenessHalfLifeMs??Ma.stalenessHalfLifeMs,r=t.entropyScaleBits??(void 0===(i=t.forkCap)?Ma.entropyScaleBits:Math.max(1,Math.log2(i)));var i;const s=Math.min(1,va(e.belief)/r),a=Math.max(0,e.now-e.lastObservedAt);return 1-(1-s)*(1-a/(a+n))},Aa=(e,t={})=>Object.freeze({affId:e,...t.gains?{gains:Object.freeze(t.gains)}:{},...t.consumes?{consumes:Object.freeze(t.consumes)}:{}}),Ea=Object.freeze({head:Object.freeze([Aa("damagedhead",{gains:["stupidity"]}),Aa("mangledhead",{gains:["stuttering","clumsiness"]})]),torso:Object.freeze([Aa("mildtrauma"),Aa("serioustrauma")]),leftarm:Object.freeze([Aa("damagedleftarm",{consumes:["brokenleftarm"]}),Aa("mangledleftarm")]),rightarm:Object.freeze([Aa("damagedrightarm",{consumes:["brokenrightarm"]}),Aa("mangledrightarm")]),leftleg:Object.freeze([Aa("damagedleftleg",{consumes:["brokenleftleg"]}),Aa("mangledleftleg")]),rightleg:Object.freeze([Aa("damagedrightleg",{consumes:["brokenrightleg"]}),Aa("mangledrightleg")])}),Ca=Object.freeze(Object.keys(Ea)),Pa=Object.freeze(new Map(Object.entries(Ea).flatMap(([e,t])=>t.map(t=>[t.affId,e])))),Ra=e=>{const t=Ea[e];return wa(t,`unknown limb '${e}'`),t},Za=(e,t)=>((e,t)=>{Js(Array.isArray(t)&&2===t.length,"ladder projection needs two rungs");const n={healthy:0,damaged:0,mangled:0};for(const i of e.forks){let e=-1;for(let n=0;n<t.length;n+=1)fa(i,t[n].affId)&&(e=n);n[ka[e+1]]+=i.p}const r=n.healthy+n.damaged+n.mangled;return 1!==r&&(n.healthy/=r,n.damaged/=r,n.mangled/=r),n})(e,Ra(t)),Da=Object.freeze(["observed","simulated"]),Fa=Ca,La=Object.freeze(["hp","mana"]),qa=Object.freeze({policy:"distribution",predictionEnabled:!1,limbResetMs:18e4}),Ba=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))Ba(e[t])}return e},Ga=e=>{const t={};for(const[n,r]of[...e].sort(([e],[t])=>e<t?-1:e>t?1:0))t[n]=r;return t},Ja=(e,t,n={})=>{wa("string"==typeof e&&e.length>0,"createOpponentModel needs an id"),wa(t?.affById&&t?.cureById&&t?.cureMasks,"createOpponentModel needs engine tables (affById, cureById, cureMasks)"),wa(t?.balanceById&&t?.priorityByAff,"createOpponentModel needs domain tables (balanceById, priorityByAff)");const r={...qa,...n};wa(Ia.includes(r.policy),`unknown predictive policy '${r.policy}'`);const i=!0===r.guards,s=(e=>{const t=_a.get(e);if(t)return t;const n=new Map;for(const s of e.cureById.values()){if(0===s.bals_used.length||0===s.order.length)continue;const e=s.bals_used[0];n.has(e)||n.set(e,[]),n.get(e).push(s)}const r=Object.freeze([...za.filter(e=>n.has(e)),...[...n.keys()].filter(e=>!za.includes(e)).sort()]),i=Object.freeze({curesByChannel:n,channelOrder:r});return _a.set(e,i),i})(t);let a=ta({guards:i}),o=0,d=0,l="observed",c=r.policy,f=!0===r.predictionEnabled,u=null;const p=new Map([...t.balanceById.keys()].map(e=>[e,0])),h=new Map,m=[];let g=0;const y=new Map(Fa.map(e=>[e,{percent:0,lastHitAt:null}])),b=new Map,v=new Map;let k={shadowInstill:null,timeloop:{count:0,max:3}};const w=new Set;let I=!1,z=null,_=0,O=0;const $=()=>{I||(_+=1),I=!0,z=null},S=()=>{d!==o&&(d=o,O+=1)},N=()=>{if(I&&(I=!1,w.size>0)){const e=U();for(const t of[...w])t(e)}},x=e=>{const n=t.balanceById.get(e);return wa(n,`unknown balance '${e}'`),n},j=(e,t)=>{p.get(e)!==t&&(p.set(e,t),$())},M=(e,t)=>{j(e,o+(t??x(e).observedDurationMs))},T=e=>{j(e,o+x(e).predictiveDurationMs)},A=e=>{const t=H(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,$())},E=new Set(["cured","removed","converted","confirmed"]),C=e=>{const n=a,r=((e,t,n)=>{Js(e&&Array.isArray(e.forks),"apply needs a Belief"),Js(t&&"string"==typeof t.type,"apply needs an event with a type"),Js(n?.affById&&n?.cureById&&n?.cureMasks,"apply needs tables");const r=ca[t.type];Js(r,`unknown event type '${t.type}'`);const i=r(e,t,n);return 0===i.diagnostics.length?i:!0===n.guards?Object.freeze({forks:i.forks,contradiction:i.contradiction,diagnostics:Object.freeze(i.diagnostics.map(e=>e.eventType?e:Object.freeze({...e,eventType:t.type})))}):{forks:i.forks,contradiction:i.contradiction,diagnostics:i.diagnostics.map(e=>e.eventType?e:{...e,eventType:t.type})}})(a,e,t);return r!==a&&(a=r,((e,n,r)=>{if(!E.has(r.type))return;if("confirmed"===r.type&&!1!==r.present)return;let i=!1;for(const t of y.values())if(0!==t.percent||null!==t.lastHitAt){i=!0;break}if(i){if("removed"===r.type||"converted"===r.type||"confirmed"===r.type){const t="converted"===r.type?r.from:r.affId;if(t){const r=Pa.get(t);if(r){const i=ha(e,t);i>0&&ha(n,t)<i&&A(r)}}return}if("cured"===r.type){const i=t.cureById.get(r.cureId);if(!i||!i.order)return;for(const t of i.order){const r=Pa.get(t);if(r){const i=ha(e,t);i>0&&ha(n,t)<i&&A(r)}}}}})(n,r,e),$()),r},P=(e,t)=>{h.get(e)!==t&&(h.set(e,t),$())},R=e=>{h.delete(e)&&$()},Z=(e,n)=>{const r=t.affById.get(e);"timed"===r?.kind&&P(e,o+(n??r.durationMs))},D=(e,n)=>{const r=t.affById.get(e);if("timed"===r?.kind){const t=o+(n??r.durationMs),i=h.get(e);P(e,void 0===i?t:Math.max(i,t))}},F=()=>{for(const e of[...h.keys()])0===ha(a,e)&&R(e)},L=(e,t)=>{const n=[...h.entries()].filter(([,e])=>e<=o).sort((e,t)=>e[1]-t[1]||(e[0]<t[0]?-1:1));for(const[r,i]of n)if(R(r),ha(a,r)>0){const n=C({type:"removed",affId:r});t.push(...n.diagnostics),e.push({affId:r,atMs:i})}},q=(e,t)=>{const n=m.filter(({atMs:e})=>e<=o).sort((e,t)=>e.atMs-t.atMs||e.sequence-t.sequence);for(const r of n){m.splice(m.indexOf(r),1),$();const n=C(r.event);t.push(...n.diagnostics),F(),e.push({atMs:r.atMs,cureId:r.event.cureId})}},B=(e,n)=>{if(!f)return;const r=e=>(p.get(e)??1/0)<=o;let i=!0;for(;i;){i=!1;for(const d of s.channelOrder){const l=p.get(d);if(void 0===l||l>o)continue;const f=ja(a,d,c,{tables:t,context:s,opponentClass:u,isBalanceReady:r});if(!f)continue;const h=C(f.event);n.push(...h.diagnostics);for(const e of f.consumed)T(e);e.push({atMs:o,channelId:d,policy:c,event:f.event,consumed:[...f.consumed].sort()}),i=!0}}F()},G=(e,t)=>{let n=1/0;for(const[,r]of h)r>o&&r<=e&&r<n&&(n=r);for(const{atMs:r}of m)r>o&&r<=e&&r<n&&(n=r);for(const i of y.values()){const t=null===i.lastHitAt?null:i.lastHitAt+r.limbResetMs;null!==t&&t>o&&t<=e&&t<n&&(n=t)}if(t)for(const r of s.channelOrder){const t=p.get(r);void 0!==t&&t>o&&t<=e&&t<n&&(n=t)}return n},J=()=>{const e=(e=>{const t={};for(const n of e.forks)for(const e of Object.keys(n.affs))t[e]=(t[e]??0)+n.p;return t})(a),n={};for(const i of Object.keys(e).sort())n[i]="countable"===t.affById.get(i)?.kind?{probability:e[i],count:ba(a,i)}:{probability:e[i]};const r={};for(const t of Fa)r[t]={percent:y.get(t).percent,stages:Za(a,t)};return{mode:l,policy:c,predictionEnabled:f,class:u,entropy:va(a),forkCount:a.forks.length,affs:n,expiries:Ga(h.entries()),pendingCures:m.slice().sort((e,t)=>e.atMs-t.atMs||e.sequence-t.sequence).map(({atMs:e,event:t})=>({atMs:e,cureId:t.cureId,excludedAffs:[...t.excludedAffs]})),limbs:r,stats:Ga([...b.entries()].map(([e,t])=>[e,{...t}])),defs:Ga([...v.entries()].map(([e,t])=>[e,{...t}])),skillState:i?JSON.parse(JSON.stringify(k)):k}},U=()=>{null===z&&(z=i?Ba(J()):J());const n=z,s={};for(const[e,t]of[...p.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0))s[e]={readyAtMs:t,remainingMs:Math.max(0,t-o)};const a={id:e,mode:n.mode,policy:n.policy,predictionEnabled:n.predictionEnabled,class:n.class,now:o,lastObservedAt:d,staleness:Ta(V,{stalenessHalfLifeMs:r.stalenessHalfLifeMs,forkCap:t.growth?.forkCap}),entropy:n.entropy,forkCount:n.forkCount,affs:n.affs,balances:s,expiries:n.expiries,pendingCures:n.pendingCures,limbs:n.limbs,stats:n.stats,defs:n.defs,skillState:n.skillState};return i?Ba(a):a},H=e=>{const t=y.get(e);return wa(t,`unknown limb '${e}'`),t},V={id:e,get revision(){return _},get timeEpoch(){return O},get now(){return o},get mode(){return l},get policy(){return c},get class(){return u},get lastObservedAt(){return d},get belief(){return a},isPredictionEnabled:()=>f,isBalanceReady:e=>(x(e),(p.get(e)??0)<=o),haveDef:e=>!0===v.get(e)?.have,getStat:e=>{wa(La.includes(e),`unknown stat '${e}'`);const t=b.get(e);return t?{...t}:null},limbPercent:e=>H(e).percent,limbStages:e=>(H(e),Za(a,e)),getSkillState:()=>i?Ba(JSON.parse(JSON.stringify(k))):k,nextInterestingAt({prediction:e=f,includeDue:t=!1}={}){if(t&&e)for(const r of s.channelOrder){const e=p.get(r);if(void 0!==e&&e<=o)return o}const n=G(1/0,e);return Number.isFinite(n)?n:null},apply:e=>{wa(e&&"string"==typeof e.type,"apply needs an event with a type"),wa("elapsed"!==e.type&&"predictedCure"!==e.type,`'${e.type}' is not an observation — it is produced by the simulation itself`);const n="cured"===e.type?t.cureById.get(e.cureId):null,r=void 0!==n?.delayMs,i=r?{contradiction:!1,diagnostics:[]}:C(e);switch(e.type){case"afflicted":Z(e.affId,e.durationMs);break;case"afflictedOneOf":for(const t of e.pool)D(t,e.durationMs);break;case"confirmed":e.present&&(e=>{const n=t.affById.get(e);"timed"!==n?.kind||h.has(e)||P(e,o+n.durationMs)})(e.affId);break;case"converted":R(e.from),Z(e.to);break;case"cured":if(n){for(const e of n.bals_used)M(e);r&&((e,t)=>{m.push({atMs:o+t,sequence:g,event:{type:"cured",cureId:e.cureId,excludedAffs:[...e.excludedAffs??[]]}}),g+=1,$()})(e,n.delayMs)}}return F(),S(),N(),{contradiction:i.contradiction,diagnostics:i.diagnostics}},elapsed:e=>{wa("number"==typeof e&&Number.isFinite(e)&&e>=0,"elapsed needs a non-negative dtMs");const t=o+e;e>0&&(O+=1);const n=[],i=[],s=[],a=[];for(;;){L(n,a),q(i,a),B(s,a);const e=G(t,f);if(!Number.isFinite(e))break;o=e}o=t;for(const d of y.values())null!==d.lastHitAt&&o-d.lastHitAt>=r.limbResetMs&&(d.percent=0,d.lastHitAt=null,$());return N(),{expired:n,resolvedCures:i,predicted:s,diagnostics:a}},snapshot:U,onChange:e=>(wa("function"==typeof e,"onChange needs a function"),w.add(e),()=>w.delete(e)),setMode(e){wa(Da.includes(e),`unknown observation mode '${e}'`),l!==e&&(l=e,$()),"observed"===e&&S(),N()},setPolicy(e){wa(Ia.includes(e),`unknown predictive policy '${e}'`),c!==e&&(c=e,$()),N()},enablePrediction(){f||(f=!0,$()),N()},disablePrediction(){f&&(f=!1,$()),N()},setClass(e){const t="string"==typeof e&&e.trim()?e.trim().toLowerCase():null;u!==t&&(u=t,$()),N()},consumeBalance(e,t){x(e),M(e,t),N()},setStat(e,t){wa(La.includes(e),`unknown stat '${e}'`),wa("number"==typeof t&&Number.isFinite(t),"setStat needs a number");const n=b.get(e);n&&n.value===t&&n.atMs===o||(b.set(e,{value:t,atMs:o}),$()),N()},setDef(e,t){wa("string"==typeof e&&e.length>0,"setDef needs a def id");const n=!0===t,r=v.get(e);r&&r.have===n&&r.atMs===o||(v.set(e,{have:n,atMs:o}),$()),N()},hitLimb(e,t){wa("number"==typeof t&&Number.isFinite(t)&&t>=0,"hitLimb needs a non-negative percent");const n=H(e),r=n.percent+t>=100,i=r?0:n.percent+t,s=r?null:o;return n.percent===i&&n.lastHitAt===s||(n.percent=i,n.lastHitAt=s,$()),N(),{advanced:r,percent:i}},resetLimb(e){const t=H(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,$()),N()},updateSkillState(e){wa(e&&"object"==typeof e,"updateSkillState needs a patch object");for(const[t,n]of Object.entries(e)){const e=k[t];null===n||"object"!=typeof n||Array.isArray(n)||null===e||"object"!=typeof e||Array.isArray(e)?e!==n&&(k[t]=n,$()):Object.entries(n).some(([t,n])=>e[t]!==n)&&(k[t]={...e,...n},$())}N()},reset(){a=ta({guards:i}),h.clear(),m.length=0;for(const e of p.keys())p.set(e,o);for(const e of y.values())e.percent=0,e.lastHitAt=null;b.clear(),v.clear(),k={shadowInstill:null,timeloop:{count:0,max:3}},$(),N()}};return Object.freeze(V)},Ua=/^[A-Za-z]+$/,Ha=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&Ua.test(t)?t.toLowerCase():null},Va=(e={})=>{const{tables:t,...n}=e;wa(t,"createRosterModel needs config.tables");const r=!0===n.guards,i=new Map,s=new Map;let a=null,o=0;const d=new Set,l=new Set,c=()=>{if(o+=1,0===d.size)return;const e={ids:[...i.keys()],targetId:a};r&&(Object.freeze(e.ids),Object.freeze(e));for(const t of[...d])t(e)},f=e=>{let r=i.get(e);return r||(r=Ja(e,t,n),i.set(e,r),s.set(e,r.onChange(t=>{o+=1,((e,t)=>{for(const n of[...l])n(e,t)})(e,t)})),c()),r},u={track(e){const t=Ha(e);if(!t)return null;const n=f(t);return n.setMode("observed"),n},untrack(e){const t=Ha(e),n=t?i.get(t):null;return!!n&&(n.setMode("simulated"),!0)},setTarget(e){if(null===e)return null!==a&&(a=null,c()),null;const t=Ha(e);if(!t)return null;const n=f(t);return a!==t&&(a=t,c()),n},get targetId(){return a},get revision(){return o},getTarget:()=>a?i.get(a)??null:null,get(e){const t=Ha(e);return t?i.get(t)??null:null},list:()=>[...i.keys()],listObserved(){const e=[];for(const[t,n]of i)"observed"===n.mode&&e.push(t);return e},remove(e){const t=Ha(e);return!(!t||!i.has(t))&&(s.get(t)(),s.delete(t),i.delete(t),a===t&&(a=null),c(),!0)},updateDefaults(e={}){const{policy:t,predictionEnabled:r}=e;void 0!==t&&(wa(Ia.includes(t),`unknown predictive policy '${t}'`),n.policy=t),void 0!==r&&(n.predictionEnabled=!0===r);for(const n of i.values())void 0!==t&&n.setPolicy(t),void 0!==r&&(!0===r?n.enablePrediction():n.disablePrediction())},reset(e){const t=u.get(e);return!!t&&(t.reset(),!0)},resetAll(){for(const e of i.values())e.reset()},elapsed(e){const t={};for(const[n,r]of i)t[n]=r.elapsed(e);return t},snapshot(){const e={};for(const t of[...i.keys()].sort())e[t]=i.get(t).snapshot();return r?Object.freeze({targetId:a,opponents:Object.freeze(e)}):{targetId:a,opponents:e}},onChange:e=>(wa("function"==typeof e,"onChange needs a function"),d.add(e),()=>d.delete(e)),onOpponentChange:e=>(wa("function"==typeof e,"onOpponentChange needs a function"),l.add(e),()=>l.delete(e))};return Object.freeze(u)},Ya=Object.freeze({lovers:/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/,shadowmadness:/^Lucidity returns to the eyes of (\w+)\.$/,whisperingmadness:/^(\w+) ceases \w+ violent trembling\.$/}),Wa=Object.freeze([Object.freeze({id:"asthma-blocks-smoke",blockerId:"asthma",balanceId:"smoke",pool:Object.freeze([...Fs].sort()),evidence:/^\w+ takes a long drag off \w+ pipe\.$/}),Object.freeze({id:"anorexia-blocks-herb",blockerId:"anorexia",balanceId:"herb",pool:Object.freeze([...Ds].sort()),evidence:/^\w+ eats a.+\.$/})]),Ka=Object.freeze([Object.freeze({id:"fulminate-paralysis-on-focus",cureId:"focus",affId:"fulminated",absentAffId:"paralysis",evidence:/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/})]),Qa=qs.get("depthswalker"),Xa=[{skill:"aeonics",id:"timeloop",handler:(e,t)=>[{type:"afflicted",affId:"timeloop"},{type:"updateSkillState",patch:{timeloop:{max:t.checkBlock("You have now aged yourself")?4:3,count:0}}}]},{skill:"aeonics",id:"timeloopProc",handler:(e,t,n)=>{const r=[],i=Qa[n.skillState.shadowInstill];i&&r.push({type:"afflictedOneOf",pool:[...i],mode:"ordered"});const{count:s=0,max:a=3}=n.skillState.timeloop??{},o=s+1;return o>=a?r.push({type:"removed",affId:"timeloop"},{type:"updateSkillState",patch:{timeloop:{count:0}}}):r.push({type:"updateSkillState",patch:{timeloop:{count:o}}}),r}},{skill:"aeonics",id:"accelerate",handler:(e,t)=>{const n={type:"cured",cureId:"accelerate"};return t.nextLine("grows older before your eyes.")?[n,{...n}]:[n]}}],eo={dissipate:[{type:"statChanged",statId:"mana",delta:-.15}],palpitation:[{type:"statChanged",statId:"hp",delta:-.15}],heat:[{type:"afflicted",affId:"burning"}],creeps:[{type:"afflicted",affId:"agoraphobia"},{type:"afflicted",affId:"claustrophobia"}],oscillate:[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"epilepsy"}],disorientation:[{type:"afflicted",affId:"prone"},{type:"afflicted",affId:"dizziness"}],dissonance:[{type:"defStripped",defId:"shield"}],plague:[{type:"afflicted",affId:"brokenrightarm"},{type:"afflicted",affId:"brokenrightleg"},{type:"afflicted",affId:"brokenleftleg"}],lullaby:[{type:"defStripped",defId:"insomnia"}],retardation:[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]};eo.plauge=eo.plague;var to={disorientation:[{type:"afflicted",affId:"dizziness"}],creeps:[{type:"afflicted",affId:"shyness"}],dissonance:[{type:"afflicted",affId:"dissonance"}]},no=e=>(e.args.info??"").toLowerCase(),ro=[{skill:"crystalism",id:"destabilise",handler:e=>(eo[no(e)]??[]).map(e=>({...e}))},{skill:"crystalism",id:"vibeTick",handler:e=>(to[no(e)]??[]).map(e=>({...e}))}],io=e=>(t,n,r)=>"thirdPerson"===t.matchType?e(t,n,r):[],so=(e,t)=>t.some(t=>e.have(t)),ao={body:e=>e.have("anorexia")?[{type:"cured",cureId:"epidermal to body"}]:so(e,["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso"])?[{type:"cured",cureId:"restoration to torso"}]:[{type:"cured",cureId:"mending to body"}],head:e=>so(e,["damagedhead","mangledhead","calcifiedskull"])?[{type:"cured",cureId:"restoration to head"}]:e.have("stuttering")?[{type:"cured",cureId:"epidermal to head"}]:e.have("unblind")||e.have("undeaf")?[{type:"afflicted",affId:"undeaf"}]:[],arms:e=>so(e,["damagedleftarm","damagedrightarm","mangledleftarm","mangledrightarm"])?[{type:"cured",cureId:"restoration to arms"}]:[{type:"cured",cureId:"mending to arms"}],legs:e=>so(e,["damagedleftleg","damagedrightleg","mangledleftleg","mangledrightleg"])?[{type:"cured",cureId:"restoration to legs"}]:[{type:"cured",cureId:"mending to legs"}],skin:e=>so(e,["frozen","shivering","frostbite"])?[{type:"cured",cureId:"caloric"}]:[{type:"defRaised",defId:"insulation"}]};ao.torso=ao.body;var oo=[{skill:"curing",id:"apply",handler:io((e,t,n)=>{const r=(e.args.info??"").toLowerCase();return ao[r]?ao[r](n):[]})},{skill:"curing",id:"health",handler:io(e=>{const t=`health to ${(e.args.info??"").toLowerCase()}`;return As.has(t)?[{type:"cured",cureId:t}]:[]})},{skill:"curing",id:"smoke",handler:io((e,t,n)=>so(n,["aeon","deadening","tension","unweavingspirit"])?[{type:"cured",cureId:"cinnabar"}]:so(n,["disloyalty","hellsight","manaleech","slickness"])?[{type:"cured",cureId:"realgar"}]:[])},{skill:"curing",id:"focus",handler:io(()=>[{type:"cured",cureId:"focus"}])},{skill:"tattoos",id:"tree",handler:io(()=>[{type:"cured",cureId:"tree"}])},{skill:"tattoos",id:"shield",handler:io(()=>[{type:"defRaised",defId:"shield"}])},{skill:"defense",id:"prismatic",handler:io(()=>[{type:"defRaised",defId:"prismatic"}])},{skill:"venom",id:"shrugging",handler:io(()=>[{type:"cured",cureId:"shrugging"}])}],lo=qs.get("occultist"),co=/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/,fo=["brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg"],uo=e=>{const t=e.queuedCommand("c!p!w!t"),n=t?t.match(/COMMAND FIRELORD AT \w+ (\w+)/):null;return n?n[1].toLowerCase():null},po=[{skill:"domination",id:"humbugCommand",handler:()=>[{type:"afflicted",affId:"addiction"}]},{skill:"domination",id:"houndCommand",handler:()=>[{type:"afflicted",affId:"weariness"}]},{skill:"domination",id:"stormCommand",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"domination",id:"stormCommand2",handler:()=>[{type:"confirmed",affId:"clumsiness",present:!0}]},{skill:"domination",id:"bloodleechCommand",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"domination",id:"sycophantCommand",handler:()=>[{type:"afflicted",affId:"weakenedmind"}]},{skill:"domination",id:"slimeCommand",handler:(e,t)=>[{type:"afflicted",affId:"slimeobscure"},{type:"confirmed",affId:"asthma",present:t.checkBlock(co)}]},{skill:"domination",id:"chimeraCommandDeaf",handler:()=>[{type:"confirmed",affId:"undeaf",present:!1}]},{skill:"domination",id:"chimeraCommand",handler:(e,t,n)=>{const r=[{type:"confirmed",affId:"undeaf",present:!0}];var i;return t.checkBlock((i=n.id).charAt(0).toUpperCase()+i.slice(1))||r.push({type:"afflicted",affId:"hallucinations"}),r}},{skill:"domination",id:"bubonisCommand",handler:(e,t,n)=>n.haveDef("fangbarrier")?t.nextLine("The protective coating covering the skin of")?[{type:"confirmed",affId:"asthma",present:!0},{type:"afflicted",affId:"slickness"}]:[{type:"afflicted",affId:"asthma"}]:n.probability("asthma")>.49?[{type:"afflicted",affId:"slickness"}]:[{type:"afflicted",affId:"asthma"}]},{skill:"domination",id:"wormCommand",handler:()=>[{type:"afflicted",affId:"palpatarfeed"}]},{skill:"domination",id:"wormTick",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"domination",id:"croneCommand",handler:()=>[{type:"afflictedOneOf",pool:[...fo],mode:"firstMissing"}]},{skill:"domination",id:"cronePrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...fo],mode:"firstMissing"}]},{skill:"domination",id:"abominationCommandFail",handler:()=>[{type:"removed",affId:"cleanseaura"}]},{skill:"domination",id:"gremlinCommand",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"domination",id:"gremlinCommandFail",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"domination",id:"firelordCommand",handler:(e,t)=>{const n=uo(t);return"manaleech"===n?[{type:"confirmed",affId:"manaleech",present:!0},{type:"removed",affId:"manaleech"},{type:"afflicted",affId:"anorexia"}]:"healthleech"===n?[{type:"confirmed",affId:"healthleech",present:!0}]:"whisperingmadness"===n?[{type:"confirmed",affId:"whisperingmadness",present:!0},{type:"removed",affId:"whisperingmadness"},{type:"afflicted",affId:"recklessness"}]:[]}},{skill:"domination",id:"firelordCommandFail",handler:(e,t)=>{const n=uo(t);return n?[{type:"confirmed",affId:n,present:!1}]:[]}},{skill:"domination",id:"wormPrimebond",handler:()=>[{type:"afflicted",affId:"nausea"}]},{skill:"domination",id:"gremlinPrimebond",handler:()=>[{type:"afflicted",affId:"dizziness"}]},{skill:"domination",id:"gremlinPrimebond2",handler:()=>[{type:"confirmed",affId:"dizziness",present:!0}]},{skill:"domination",id:"humbugPrimebond",handler:(e,t,n)=>{const r=n.probability("addiction")>.49?-.1:-.05;return[{type:"statChanged",statId:"hp",delta:r},{type:"statChanged",statId:"mana",delta:r}]}},{skill:"domination",id:"bubonisPrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...lo.bubonis],mode:"firstMissing"}]},{skill:"domination",id:"chimeraPrimebondGas",handler:()=>[{type:"defStripped",defId:"insomnia"}]},{skill:"domination",id:"chimeraPrimebondRam",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"domination",id:"chimeraPrimebondRoar",handler:()=>[{type:"afflicted",affId:"undeaf"},{type:"afflicted",affId:"prone"}]},{skill:"domination",id:"chimeraPrimebondUndeaf",handler:()=>[{type:"afflicted",affId:"undeaf"}]}],ho=[{skill:"dragoncraft",id:"gust",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonroar",handler:(e,t)=>{if("thirdPerson"===e.matchType)return[{type:"afflicted",affId:"undeaf"}];const n=t.queuedCommand();return n&&/DRAGONROAR \w+/.test(n)?[{type:"afflicted",affId:"undeaf"}]:[]}},{skill:"dragoncraft",id:"rendTargeted",handler:(e,t,n)=>mo(n)},{skill:"dragoncraft",id:"rendUntargeted",handler:(e,t,n)=>mo(n)},{skill:"dragoncraft",id:"tailsweepHit",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonheal",handler:e=>"thirdPerson"===e.matchType?[{type:"cured",cureId:"dragonheal"}]:[]}],mo=e=>{const t=e.skillState.envenom;if(!t)return[];const n=Ls.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},go=e=>`broken${(e??"").replace(/\s/g,"").toLowerCase()}`,yo=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],bo=[{skill:"elementalism",id:"shalestormTick",handler:e=>[{type:"afflicted",affId:go(e.args.limb)}]},{skill:"elementalism",id:"shalestormRaze",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"elementalism",id:"firelash",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"firelashLOS",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"freeze",handler:(e,t,n)=>yo(n)},{skill:"elementalism",id:"dehydrate",handler:()=>[{type:"afflicted",affId:"nausea"},{type:"afflicted",affId:"weariness"}]},{skill:"elementalism",id:"fulminate",handler:()=>[{type:"afflictedOneOf",pool:["fulminated","epilepsy","paralysis"],mode:"ordered"}]},{skill:"elementalism",id:"bombard",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"elementalism",id:"mudslide",handler:()=>[{type:"afflicted",affId:"slickness"},{type:"afflicted",affId:"prone"}]},{skill:"elementalism",id:"magma",handler:()=>[{type:"afflicted",affId:"scalded"}]},{skill:"elementalism",id:"emanationFire",handler:()=>[{type:"afflicted",affId:"burning"},{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"emanationAir",handler:()=>[{type:"afflicted",affId:"paralysis"},{type:"afflicted",affId:"dizziness"}]},{skill:"elementalism",id:"emanationEarth",handler:()=>[{type:"afflicted",affId:"calcifiedtorso"}]},{skill:"elementalism",id:"emanationWater",handler:(e,t,n)=>yo(n)},{skill:"elementalism",id:"resonanceAirMinor",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"elementalism",id:"resonanceAirModerate",handler:(e,t,n)=>n.have("undeaf")?[{type:"afflicted",affId:"sensitivity"}]:[{type:"afflicted",affId:"undeaf"}]},{skill:"elementalism",id:"resonanceAirMajor",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"elementalism",id:"resonanceEarthMinor",handler:e=>[{type:"afflicted",affId:go(e.args.limb)}]},{skill:"elementalism",id:"resonanceEarthModerate",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"elementalism",id:"resonanceEarthMajor",handler:()=>[{type:"afflicted",affId:"crackedribs"}]},{skill:"elementalism",id:"resonanceFireMinor",handler:()=>[{type:"defStripped",defId:"temperence"}]},{skill:"elementalism",id:"resonanceFireModerate",handler:(e,t,n)=>n.have("scalded")?[{type:"afflicted",affId:"burning"}]:[{type:"afflicted",affId:"scalded"}]},{skill:"elementalism",id:"resonanceFireMajor",handler:(e,t,n)=>n.have("blistered")?[{type:"afflicted",affId:"burning"}]:[{type:"afflicted",affId:"blistered"}]},{skill:"elementalism",id:"resonanceWaterMinor",handler:()=>[{type:"afflicted",affId:"frostbite"}]},{skill:"elementalism",id:"resonanceWaterModerate",handler:()=>[{type:"afflicted",affId:"stuttering"}]},{skill:"elementalism",id:"resonanceWaterMajor",handler:()=>[{type:"afflicted",affId:"anorexia"}]}],vo=qs.get("occultist"),ko=e=>[{type:"confirmedCount",pool:[...vo.physicals],op:"=",n:e.args.physical},{type:"confirmedCount",pool:[...vo.mentals],op:"=",n:e.args.mental}],wo=e=>{const t=[{type:"confirmedCount",pool:[...vo.physicals,...vo.mentals],op:e.args.met?">=":"<",n:5}];return e.args.met&&t.push({type:"afflicted",affId:"enlightenment"}),t},Io=[{skill:"occultism",id:"ague",handler:(e,t,n)=>n.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}]},{skill:"occultism",id:"instill",handler:(e,t,n)=>{const r=[{type:"statChanged",statId:"hp",delta:-.03},{type:"statChanged",statId:"mana",delta:-.03}],i=e.args.affs?.[0];return"sensitivity"===i?r.push(n.have("undeaf")?{type:"afflicted",affId:"sensitivity"}:{type:"afflicted",affId:"undeaf"}):i&&r.push({type:"afflicted",affId:i}),r}},{skill:"occultism",id:"enervate",handler:()=>[{type:"statChanged",statId:"mana",delta:-.2}]},{skill:"occultism",id:"attend",handler:()=>[{type:"afflicted",affId:"undeaf"},{type:"afflicted",affId:"unblind"}]},{skill:"occultism",id:"shrivelTargeted",handler:e=>e.args.affs?.[0]?[{type:"afflicted",affId:e.args.affs[0]}]:[]},{skill:"occultism",id:"shrivelArms",handler:()=>[{type:"afflictedOneOf",pool:["brokenrightarm","brokenleftarm"],mode:"firstMissing"}]},{skill:"occultism",id:"shrivelLegs",handler:()=>[{type:"afflictedOneOf",pool:["brokenrightleg","brokenleftleg"],mode:"firstMissing"}]},{skill:"occultism",id:"shrivelRehit",handler:e=>{return"arm"===(t=(e.args.groups?.limb??"").replace(/\s/g,"").toLowerCase())?[{type:"confirmed",affId:"brokenleftarm",present:!0},{type:"confirmed",affId:"brokenrightarm",present:!0}]:"leg"===t?[{type:"confirmed",affId:"brokenleftleg",present:!0},{type:"confirmed",affId:"brokenrightleg",present:!0}]:[{type:"confirmed",affId:`broken${t}`,present:!0}];var t}},{skill:"occultism",id:"unnamableSpeak",handler:()=>[]},{skill:"occultism",id:"unnamableVision",handler:()=>[]},{skill:"occultism",id:"regress",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"occultism",id:"devolve",handler:()=>[{type:"afflicted",affId:"shyness"},{type:"afflicted",affId:"disloyalty"}]},{skill:"occultism",id:"whisperingmadness",handler:()=>[{type:"afflicted",affId:"whisperingmadness"}]},{skill:"occultism",id:"whisperingmadnessMiss",handler:()=>vo.whisperingmadness.map(e=>({type:"removed",affId:e}))},{skill:"occultism",id:"cleanseaura",handler:(e,t)=>t.checkBlock("A look of sudden concern")?[{type:"afflicted",affId:"cleanseaura"}]:[{type:"removed",affId:"cleanseaura"}]}],zo=qs.get("psion"),_o=(e,t)=>e.args[t]??e.args.match?.groups?.[t],Oo=[{skill:"psionics",id:"splinterHit",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"psionics",id:"splinterMiss",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"psionics",id:"expand",handler:()=>[{type:"statChanged",statId:"mana",delta:.15}]},{skill:"psionics",id:"combustion",handler:()=>[{type:"afflicted",affId:"bloodfire"}]},{skill:"psionics",id:"blastMiss",handler:()=>[{type:"confirmedCount",pool:[...zo.blast],op:"<",n:3}]},{skill:"weaving",id:"invert",handler:e=>{const t=_o(e,"old"),n=_o(e,"new");return t&&n?[{type:"converted",from:`unweaving${t}`,to:`unweaving${n}`}]:[]}}],$o=qs.get("depthswalker"),So=["depression","retribution","shadowmadness","parasite"],No=e=>()=>[{type:"afflictedOneOf",pool:[...e],mode:"ordered"}],xo=e=>()=>e.map(e=>({type:"confirmed",affId:e,present:!0})),jo=e=>{const t=e.skillState.envenom;if(!t)return[];const n=Ls.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},Mo=[{skill:"shadowmancy",id:"reap",handler:(e,t,n)=>t.checkBlock("you corrupt the weapon's timestream.")?[]:jo(n)},{skill:"shadowmancy",id:"cull",handler:(e,t,n)=>jo(n)},{skill:"shadowmancy",id:"degeneration",handler:No($o.degeneration)},{skill:"shadowmancy",id:"degenerationFull",handler:xo($o.degeneration)},{skill:"shadowmancy",id:"depression",handler:No($o.depression)},{skill:"shadowmancy",id:"depressionFull",handler:()=>[...xo($o.depression)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"}]},{skill:"shadowmancy",id:"retribution",handler:No($o.retribution)},{skill:"shadowmancy",id:"retributionFull",handler:(e,t,n)=>{const r=So.reduce((e,t)=>e+n.probability(t),0);return[...xo($o.retribution)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"},{type:"statChanged",statId:"mana",delta:-.05*r}]}},{skill:"shadowmancy",id:"madness",handler:No($o.madness)},{skill:"shadowmancy",id:"madnessFull",handler:xo($o.madness)},{skill:"shadowmancy",id:"leach",handler:No($o.leach)},{skill:"shadowmancy",id:"leachFull",handler:xo($o.leach)},{skill:"shadowmancy",id:"consume",handler:()=>[{type:"statChanged",statId:"mana",delta:-.1}]},{skill:"shadowmancy",id:"mutilate",handler:()=>[{type:"statChanged",statId:"mana",delta:-.4},{type:"statChanged",statId:"hp",delta:-.4}]}],To=qs.get("occultist"),Ao=To.moon.filter(e=>"claustrophobia"!==e&&"agoraphobia"!==e),Eo=[{skill:"tarot",id:"magician",handler:()=>[{type:"statChanged",statId:"mana",delta:.25}]},{skill:"tarot",id:"priestess",handler:()=>[{type:"statChanged",statId:"hp",delta:.25}]},{skill:"tarot",id:"lovers",handler:()=>[{type:"afflicted",affId:"lovers"}]},{skill:"tarot",id:"aeon",handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{skill:"tarot",id:"aeonStrip",handler:()=>[{type:"defStripped",defId:"speed"}]},{skill:"tarot",id:"justice",handler:()=>[{type:"afflicted",affId:"justice"}]},{skill:"tarot",id:"deathRub",handler:(e,t,n)=>n.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflicted",affId:"shivering"}]},{skill:"tarot",id:"ruinateLovers",handler:()=>[{type:"afflicted",affId:"manaleech"}]},{skill:"tarot",id:"ruinateJustice",handler:(e,t)=>t.nextLine("violently spasms")?[]:To.justice.map(e=>({type:"confirmed",affId:e,present:!1}))},{skill:"tarot",id:"moon",handler:(e,t)=>{const n=t.queuedCommand(),r=n?n.match(/FLING MOON AT \w+ (\w+)/):null;return r?[{type:"afflicted",affId:r[1].toLowerCase()}]:[{type:"afflictedOneOf",pool:[...Ao],mode:"firstMissing"}]}}],Co=/^(\w+) stumbles, falling to the ground\.$/,Po=[{skill:"weaving",id:"cleaveHit",handler:()=>[{type:"afflicted",affId:"prone"},{type:"defStripped",defId:"shield"}]},{skill:"weaving",id:"cleaveMiss",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"weaving",id:"overhand",handler:(e,t,n)=>n.have("prone")||n.limbPercent("head")>=87.6?[{type:"afflicted",affId:"impatience"}]:[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"prone"}]},{skill:"weaving",id:"hamstring",handler:(e,t)=>{const n=(e=>(e??"").replace(/\s/g,"").toLowerCase())(e.args.limb),r=[{type:"afflicted",affId:`broken${n}`}];return"thirdPerson"===e.matchType&&r.push(t.checkBlock(Co)?{type:"limbAdvance",limbId:n}:{type:"limbHit",limbId:n,percent:22.1}),r}},{skill:"weaving",id:"entwineProne",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"weaving",id:"entwineEntangle",handler:()=>[{type:"afflicted",affId:"entangled"}]},{skill:"weaving",id:"puncture",handler:()=>[{type:"afflicted",affId:"weariness"}]},{skill:"weaving",id:"sever",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"weaving",id:"unweave",handler:e=>e.args.info?[{type:"afflicted",affId:`unweaving${e.args.info}`}]:[]},{skill:"weaving",id:"deathblow",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"weaving",id:"backhand",handler:()=>[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"dizziness"}]},{skill:"weaving",id:"exsanguinate",handler:()=>[{type:"afflicted",affId:"nausea"}]},{skill:"weaving",id:"disruption",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"weaving",id:"disruption2",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"weaving",id:"laceration",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"weaving",id:"laceration2",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"weaving",id:"dazzle",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"weaving",id:"rattle",handler:()=>[{type:"afflicted",affId:"epilepsy"}]},{skill:"weaving",id:"vapours",handler:()=>[{type:"afflicted",affId:"asthma"}]}],Ro=e=>String(e).toLowerCase(),Zo=(e,t)=>`${Ro(e)}.${String(t).toLowerCase()}`,Do=Object.freeze([...Xa,{skill:"artificing",id:"efreeti",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"artificing",id:"stoneback",handler:()=>[{type:"defRaised",defId:"shield"}]},...ro,...oo,...po,...ho,...bo,...Io,...Oo,...Mo,...Eo,...Po]),Fo=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!0}]}),Lo=[Fo("agoraphobia","agoraphobia",/^(\w+) is gripped with fear, staring out with terrified eyes\.$/),Fo("claustrophobia","claustrophobia",/^(\w+) begins to pant in terror\.$/),Fo("confusion","confusion",/^(\w+) looks about bemusedly\.$/),Fo("darkshade","darkshade",/^(\w+) lets out a piercing scream, as if wounded by the very sunlight\.$/),Fo("dementia","dementia",/^(\w+) stares about \w+ frenziedly, wild-eyed\.$/),Fo("epilepsy","epilepsy",/^(\w+) begins to jerk and shake violently, foaming at the mouth\.$/),{id:"affConfirms.hallucinations",pattern:/^(\w+) leaps up in what is apparently an attempt at a graceful swan dive\. \w+ smacks headfirst into the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"hallucinations",present:!0},{type:"afflicted",affId:"prone"}]},Fo("hypersomnia","hypersomnia",/^(\w+) suddenly appears tired all of a sudden\.$/),Fo("impatience","impatience",/^(\w+) shuffles \w+ feet in boredom\.$/),Fo("masochism1","masochism",/^(\w+) smiles as \w+ rams \w+ fist into \w+ jaw\.$/),Fo("masochism2","masochism",/^(\w+) uses \w+ right foot to stomp on \w+ left as hard as possible\.$/),Fo("masochism3","masochism",/^With the heel of \w+ palm, (\w+) smacks \w+ upside the head\.$/),Fo("nausea","nausea",/^(\w+) doubles over, vomiting violently\.$/),Fo("paralysis1","paralysis",/^Horror overcomes the face of (\w+?) as \w+ body locks in paralysis\.$/),Fo("paralysis2","paralysis",/^Horror overcomes (\w+)'s face as \w+ body stiffens into paralysis\.$/),Fo("shyness","shyness",/^(\w+) trembles with fear\.$/),{id:"affConfirms.sleep",pattern:/^(\w+)'s eyes close suddenly as \w+ falls asleep\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"}]},Fo("shivering","shivering",/^(\w+) shivers particularly intensely\.$/),Fo("burning","burning",/^The fires consuming (\w+) diminish somewhat\.$/)],qo=(e,t,n)=>({id:`classCures.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:t}]}),Bo=[qo("sunTarot","dagaz",/^The globe of light illuminates (\w+) with its brilliance\.$/),qo("runewardenSun","dagaz",/^A rune like a rising sun upon the ground flares, bathing (\w+) with healing magic\.$/),qo("genericMist","generic",/^(\w+) is surrounded in a cool, refreshing mist\.$/),qo("genericGlow","generic",/^A demonic crimson glow emanates from (\w+)\.$/),qo("genericLeech","generic",/^Something pulses from within the chest of (\w+), and \w+ seems more vital\.$/)],Go=(e,t,n)=>({id:`cureConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!1}]}),Jo=[{id:"cureConfirms.stand",pattern:/^(\w+) stands up\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"stand"}]},Go("lovers","lovers",/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/),Go("whisperingmadness","whisperingmadness",/^(\w+) ceases \w+ violent trembling\.$/),{id:"cureConfirms.slimeLost",pattern:/^(\w+) finally rids \w+ of the slime covering \w+\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"slimeobscure"}]},Go("sileris","slickness",/^(\w+) applies a (?:quicksilver droplet|sileris berry) to \w+\.$/),Go("shadowmadness","shadowmadness",/^Lucidity returns to the eyes of (\w+)\.$/),Go("unweavingspirit","unweavingspirit",/^(\w+) seems suddenly unburdened, clarity reasserting itself upon \w+ features\.$/),Go("unweavingmind","unweavingmind",/^The light behind the eyes of (\w+) reignites\.$/),Go("unweavingbody","unweavingbody",/^(\w+) suddenly seems much more vital\.$/),Go("bloodfire","bloodfire",/^The unnatural flames that burn upon the skin of (\w+) wink out\.$/)],Uo=(e,t)=>({id:`curatives.${e}`,pattern:t,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:e}]}),Ho=[Uo("antimony",/^(\w+) eats (?:a ginger root|an antimony flake)\.$/),Uo("argentum",/^(\w+) eats (?:a lobelia seed|an argentum flake)\.$/),Uo("arsenic",/^(\w+) eats (?:some bayberry bark|an arsenic pellet)\.$/),Uo("aurum",/^(\w+) eats (?:a piece of kelp|an aurum flake)\.$/),Uo("cuprum",/^(\w+) eats a (?:bellwort flower|cuprum flake)\.$/),Uo("ferrum",/^(\w+) eats a (?:ginseng root|ferrum flake)\.$/),Uo("magnesium",/^(\w+) eats a (?:bloodroot leaf|magnesium chip)\.$/),Uo("plumbum",/^(\w+) eats a (?:goldenseal root|plumbum flake)\.$/),Uo("stannum",/^(\w+) eats (?:some prickly ash bark|a stannum flake)\.$/),{id:"curatives.calamine",pattern:/^(\w+) eats a (?:hawthorn berry|calamine crystal)\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"undeaf"}]},{id:"curatives.potash",pattern:/^(\w+) eats (?:some irid moss|a potash crystal)\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"potash"},{type:"statChanged",statId:"hp",delta:.08},{type:"statChanged",statId:"mana",delta:.08}]},{id:"curatives.restore",pattern:/^(\w+) crackles with blue energy that wreathes itself about \w+ limbs\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"brokenrightarm"},{type:"removed",affId:"brokenrightleg"},{type:"removed",affId:"brokenleftarm"},{type:"removed",affId:"brokenleftleg"}]}],Vo=(e,t,n)=>({id:`defences.${e}`,pattern:t,lifetime:"session",actor:1,handler:n}),Yo=[Vo("shieldHit1",/^A dizzying beam of energy strikes you as your attack rebounds off of (\w+)'s shield\.$/,()=>[{type:"defRaised",defId:"shield"}]),Vo("shieldHit2",/^The magical shield surrounding (\w+) makes that impossible\.$/,()=>[{type:"defRaised",defId:"shield"}]),Vo("sileris",/^A supple purple shell of sileris berry juice has formed around (\w+)\.$/,()=>[{type:"defRaised",defId:"fangbarrier"}]),Vo("silerisLost",/^The protective coating covering the skin of (\w+) sloughs off\.$/,()=>[{type:"afflicted",affId:"slickness"},{type:"defStripped",defId:"fangbarrier"}]),Vo("insomnia",/^(\w+) clenches \w+ fists and grits \w+ teeth\.$/,()=>[{type:"defRaised",defId:"insomnia"}]),Vo("prismaticHit",/^Your attack is repelled by the prismatic barrier surrounding (\w+)\.$/,()=>[{type:"defRaised",defId:"prismatic"}]),Vo("prismaticLost",/^(\w+)'s prismatic barrier dissolves into nothing\.$/,()=>[{type:"defStripped",defId:"prismatic"}]),Vo("speedStripped",/^(\w+) suddenly seems less dexterous, \w+ reactions becoming noticeably slower\.$/,()=>[{type:"defStripped",defId:"speed"}])],Wo=e=>(e??"").replace(/\s/g,"").toLowerCase(),Ko=(e,t)=>Number(`${e}.${t}`),Qo=[{id:"prep.limbDamage",pattern:/^As you carve into (\w+), you perceive that you have dealt (\d+)\.(\d+)% damage to \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbHit",limbId:Wo(e[4]),percent:Ko(e[2],e[3])}]},{id:"prep.limbDamage2",pattern:/^As your blow lands with a crunch, you perceive that you have dealt (\d+)\.(\d+)% damage to (\w+)'s (.+)\.$/,lifetime:"session",actor:3,handler:e=>[{type:"limbHit",limbId:Wo(e[4]),percent:Ko(e[1],e[2])}]},{id:"prep.interlinkDamage",pattern:/^As the immaterial cleaves the material, you perceive that you have dealt (\d+)\.(\d+)% damage to (\w+)'s (.+)\.$/,lifetime:"session",actor:3,handler:e=>[{type:"limbHit",limbId:Wo(e[4]),percent:Ko(e[1],e[2])}]},{id:"prep.limbReset",pattern:/^(\w+) ceases to favour \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbReset",limbId:Wo(e[2])}]},{id:"prep.limbMangle",pattern:/^(\w+)'s ((?:left|right) (?:arm|leg)) has been beaten into uselessness\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbAdvance",limbId:Wo(e[2])}]},{id:"prep.calcifiedskullResolve",pattern:/^A look of pain comes over (\w+) and the bones seem to shift beneath the skin stretched across \w+ skull\.$/,lifetime:"session",actor:1,handler:()=>[{type:"converted",from:"calcifiedskull",to:"damagedhead"}]}],Xo=[{defId:"insomnia",pattern:/^\w+ has insomnia, and cannot easily go to sleep\.$/},{defId:"speed",pattern:/^\w+ sense of time is heightened, and \w+ reactions are speeded\.$/},{defId:"kola",pattern:/^\w+ is feeling extremely energetic\.$/},{defId:"cloak",pattern:/^\w+ is surrounded by a cloak of protection\.$/},{defId:"insulation",pattern:/^\w+ is coated in an insulating unguent\.$/},{defId:"fangbarrier",pattern:/^\w+ is protected from the fangs of serpents\.$/},{defId:"rebounding",pattern:/^\w+ is protected from hand-held weapons with an aura of rebounding\.$/},{defId:"curseward",pattern:/^A curseward has been established about \w+ person\.$/},{defId:"selfishness",pattern:/^\w+ is feeling quite selfish\.$/},{defId:"shield",pattern:/^\w+ is surrounded by a nearly invisible magical shield\.$/}],ed={id:"occultism.readaura",lifetime:"prompt",armedBy:{trigger:"skills.readauraStart"},initState:({actorId:e})=>({actorId:e,pendingDefs:Xo.map(({defId:e})=>e)}),captures:[...Xo.map(({defId:e,pattern:t})=>({id:`def.${e}`,pattern:t,actor:"armed",handler:(t,n,r,i)=>(i.pendingDefs=i.pendingDefs.filter(t=>t!==e),[{type:"defRaised",defId:e}])})),{id:"deaf",pattern:/^\w+ is deaf\.$/,actor:"armed",handler:()=>[{type:"removed",affId:"undeaf"}]},{id:"blind",pattern:/^\w+ is blind\.$/,actor:"armed",handler:()=>[{type:"removed",affId:"unblind"}]},{id:"counts",pattern:/^You perceive that (\w+) suffers from (\d+) physical afflictions and (\d+) mental afflictions\.$/,actor:1,handler:(e,t,n)=>ko({args:{physical:Number(e[2]),mental:Number(e[3])}},t,n)},{id:"mana",pattern:/^You sense that the mana of (\w+) stands at (\d+) of a maximum (\d+)\.$/,actor:1,handler:(e,t,n,r)=>{const i=r.pendingDefs.map(e=>({type:"defStripped",defId:e}));return r.pendingDefs=[],i.push({type:"statObserved",statId:"mana",value:Number(e[2])/Number(e[3])}),i}}]},td=["paralysis","asthma","healthleech","haemophilia","sensitivity","clumsiness","weariness"],nd={indigo:()=>[{type:"afflicted",affId:"stupidity"}],orange:()=>[{type:"afflicted",affId:"paralysis"}],violet:e=>e.haveDef("speed")?[{type:"defStripped",defId:"speed"}]:[{type:"afflicted",affId:"aeon"}]},rd=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],id=[{id:"skills.earworm",pattern:/^Your rapier sings out with a high, piercing note\.$/,lifetime:"session",actor:null,handler:()=>[{type:"confirmed",affId:"earworm",present:!0}]},{id:"skills.commandMinionMiss",pattern:/^A minion of chaos thrusts a hand in the direction of (\w+), but nothing seems to happen\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"enlightenment",present:!1}]},{id:"skills.firelordPrimebond",pattern:/^(\w+) cries out in horror as \w+ body erupts into flames!$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"burning"}]},{id:"skills.rendVenom",pattern:/^You rub some (\w+) on your wickedly sharp claws\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{envenom:e[1].toLowerCase()}}]},{id:"skills.dragoncurseAff",pattern:/^You summon your ancient power and direct the curse of (\w+) to strike down (\w+) in (\d+) seconds\.$/,lifetime:"session",actor:2,handler:e=>[{type:"updateSkillState",patch:{dragoncurse:e[1].toLowerCase()}}]},{id:"skills.dragoncurseHit",pattern:/^(\w+) convulses under the influence of some invisible force\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>{const r=n.skillState.dragoncurse;if(!r)return[];const i=[{type:"updateSkillState",patch:{dragoncurse:null}}];return Ts.has(r)&&i.unshift({type:"afflicted",affId:r}),i}},{id:"skills.readauraStart",pattern:/^Studying the aura of (\w+), you look for traces of anything that may be protecting it\.$/,lifetime:"session",actor:1,handler:()=>[]},{id:"skills.whisperingmadnessTick",pattern:/^(\w+) trembles and \w+ eyes widen in terror\. \w+ looks around \w+ as if searching for something that isn't there\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"whisperingmadness",present:!0}]},{id:"skills.chaosrays",pattern:/^(\w+) is hit by a (.+) ray\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>e[2].replace(/ and /g,",").replace(/\s/g,"").replace(/,,/g,",").split(",").filter(Boolean).flatMap(e=>nd[e]?.(n)??[])},{id:"skills.truename",pattern:/^Drawing back with a knowing smirk, you utter the truename of (\w+), who suddenly becomes very still and bleeds from \w+ eyes and ears\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{id:"skills.unnamableHits",pattern:/^(\w+) has been struck down by (\d) curses of the unnamable\.$/,lifetime:"session",actor:1,handler:e=>Array.from({length:Number(e[2])},()=>({type:"afflictedOneOf",pool:["confusion","stupidity","dementia"],mode:"firstMissing"}))},{id:"skills.enlighten",pattern:/^You place both hands on either side of (\w+)'s head and stare straight into \w+ eyes\. Summoning all your knowledge of the occult mysteries, you will your knowledge into \w+'s mind\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>wo({args:{met:t.nextLine("You see")}},t,n)},{id:"skills.enlightenYell",pattern:/^You see (.+) yell, "No, it cannot be true! I cannot accept it! I beg of you to make it stop!"$/,lifetime:"session",actor:1,handler:(e,t,n)=>wo({args:{met:!0}},t,n)},{id:"skills.enlightenShout",pattern:/^You see (.+) shout, "No, it cannot be true! I cannot accept it! I beg of you to make it stop!"$/,lifetime:"session",actor:1,handler:(e,t,n)=>wo({args:{met:!0}},t,n)},{id:"skills.regressAnorexia",pattern:/^The face of (\w+) turns a particularly vibrant shade of green\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"anorexia"},{type:"confirmed",affId:"prone",present:!0}]},{id:"skills.compelDiscord",pattern:/^(\w+) clutches at \w+ head as \w+ begins to mutter gibberish over and over under his breath\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"healthleech",present:!0},{type:"confirmed",affId:"asthma",present:!0},{type:"afflicted",affId:"loneliness"},{type:"afflicted",affId:"dizziness"}]},{id:"skills.compelEntropyAeon",pattern:/^(\w+) twists and writhes in the grip of an unnatural force, parts of \w+ body flickering as if seen through a veil of mist\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{id:"skills.compelPotentialLimbs",pattern:/^The body of (\w+) goes slack, \w+ eyes rolling almost completely back in \w+ head as \w+ face goes a ghostly white\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>["leftarm","leftleg","rightarm","rightleg"].flatMap(e=>{for(const t of["mangled","damaged","broken"])if(n.probability(`${t}${e}`)>.25)return[{type:"confirmed",affId:`${t}${e}`,present:!0}];return[]})},{id:"skills.compelPotentialFrozen",pattern:/^(\w+) twitches in the grip of some terrible power, skin splitting and cracking under its unforgiving grasp\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"shivering",present:!0},{type:"confirmed",affId:"frozen",present:!0},{type:"defStripped",defId:"insulation"}]},{id:"skills.shadowInstill",pattern:/^Focusing upon .+?, you instill it with the directive of (\w+)\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{shadowInstill:e[1].toLowerCase()}}]},{id:"skills.shadowEnvenom",pattern:/^You rub some (\w+) on .+?\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{envenom:e[1].toLowerCase()}}]},{id:"skills.attuneMadness",pattern:/^You sense that (\w+) has been struck down with the (\w+) madness\.$/,lifetime:"session",actor:1,handler:e=>{const t=e[2].toLowerCase(),n=Ts.has(t)?t:`${t}madness`;return Ts.has(n)?[{type:"afflicted",affId:n}]:[]}},{id:"skills.attuneDegeneration",pattern:/^You determine that (\w+) is suffering from (\w+)\.$/,lifetime:"session",actor:1,handler:e=>{const t=e[2].toLowerCase();return Ts.has(t)?[{type:"afflicted",affId:t}]:[]}},{id:"skills.shadowstrikeMiss",pattern:/^(\w+) is not surrounded by a magical shield\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"shield"}]},{id:"skills.ruinateJusticeBreak",pattern:/^An audible crack emanates from the bones in the (.+) of (\w+)\.$/,lifetime:"session",actor:2,handler:(e,t,n)=>{const r=(i=e[1],i.replace(/ and /g,",").replace(/,,/g,",").replace(/\s/g,"").split(",").filter(Boolean)).map(e=>({type:"afflicted",affId:`broken${e}`}));var i;return td.reduce((e,t)=>e+n.probability(t),0)>=4&&(r.push(...rd(n)),r.push({type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"})),r}},{id:"skills.ruinateJusticeProne",pattern:/^The broken legs of (\w+) give way, and \w+ collapses to the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"},{type:"confirmed",affId:"brokenleftleg",present:!0},{type:"confirmed",affId:"brokenrightleg",present:!0}]},{id:"skills.wheelAgue",pattern:/^Rays of cold blue light lash out from the Wheel of Chaos, irradiating the location\.$/,lifetime:"session",actor:"room",handler:(e,t,n)=>rd(n)},{id:"skills.wheelStuttering",pattern:/^Vibrant indigo rays of light lash out from the Wheel of Chaos\.$/,lifetime:"session",actor:"room",handler:()=>[{type:"afflicted",affId:"stuttering"}]},{id:"skills.wheelBlackout",pattern:/^Rays of orange light lash out at the location from the Wheel of Chaos\.$/,lifetime:"session",actor:"room",handler:()=>[{type:"afflicted",affId:"blackout",durationMs:3e3}]},{id:"skills.stumbleProne",pattern:/^(\w+) stumbles, falling to the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"}]},{id:"skills.erodeDefence",pattern:/^(?:His|Her|Faen) (\w+) defence is eroded away\.$/,lifetime:"session",actor:null,handler:e=>[{type:"defStripped",defId:e[1].toLowerCase()}]},{id:"skills.scintillaBurn",pattern:/^Flames ignite all over the body of (\w+), fanned to intensity in an instant\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"burning"}]},{id:"skills.conflagrateFail",pattern:/^You bend your will upon (\w+), attempting to rouse a conflagration to consume \w+, but to no avail\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmedLevel",affId:"burning",op:"<",n:2}]},{id:"skills.assess",pattern:/^You glance over (\w+) and see that \w+ health is at (\d+)\/(\d+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"statObserved",statId:"hp",value:Number(e[2])/Number(e[3])}]},{id:"skills.contemplate",pattern:/^(\w+)'s mana stands at (\d+)\/(\d+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"statObserved",statId:"mana",value:Number(e[2])/Number(e[3])}]}],sd=/^(\w+) pales as the blood drains from \w+ face\.$/,ad=(e,t,n)=>({id:e,lifetime:"prompt",armedBy:{skill:"occultism",id:t},initState:({observedIds:e})=>({exposed:[...e]}),captures:[{id:"pale",pattern:sd,actor:1,handler:(e,t,r,i)=>(i.exposed=i.exposed.filter(e=>e!==r.id),[{type:"afflicted",affId:n}])}],finalize:e=>e.exposed.map(e=>({id:e,type:"removed",affId:n}))}),od=ad("occultism.unnamableSpeak","unnamableSpeak","undeaf"),dd=ad("occultism.unnamableVision","unnamableVision","unblind"),ld=Object.freeze([...Ho,...Bo,...Jo,...Lo,...Yo,...id,...Qo,{id:"queues.queueTracker",pattern:/^\[System\]: Running queued (.+?) command: (.+)/,lifetime:"session",remember:e=>({queue:{name:e[1],text:e[2]}})}]),cd=Object.freeze([od,dd,ed]),fd=(e,t)=>t instanceof RegExp?t.test(e):"string"==typeof t&&e.includes(t),ud=(e,t)=>{const n=[e?.target,e?.target?.id,e?.victim,e?.player,e?.player?.id,e?.user];for(const r of n)if("string"==typeof r&&""!==r&&"self"!==r.toLowerCase()){const e=Ha(r);if(e&&e!==t)return e}return null},pd=e=>"string"==typeof e?e:"string"==typeof e?.name?e.name:null,hd=({adapter:e,publish:t,commandMemory:n=null,skills:r=null})=>{const i=[],s=new Map;let a=!1;const o=()=>Ha(pd(e.gmcp.read("Char.Name"))),d=(t=null)=>(({lines:e=[],currentLineIndex:t=-1,actorId:n=null,timestampMs:r=0,commands:i=null}={})=>{const s=Object.freeze(e.map(e=>Object.freeze({text:"string"==typeof e.text?e.text:null,isPrompt:!0===e.isPrompt,isHtml:!0===e.isHtml}))),a=Object.freeze({queues:Object.freeze({...i?.queues??{}}),lastQueue:i?.lastQueue??null});return Object.freeze({lines:s,currentLineIndex:t,actorId:n,timestampMs:r,commands:a,nextLine:e=>{for(let n=t+1;n<s.length;n+=1){const t=s[n];if(!t.isHtml&&!t.isPrompt&&null!==t.text)return fd(t.text,e)}return!1},checkBlock:e=>s.some(t=>null!==t.text&&fd(t.text,e)),queuedCommand:e=>{const t=e??a.lastQueue;return null===t?null:a.queues[t]??null}})})({...e.text.snapshot(),actorId:Ha(t),timestampMs:e.clock.now(),commands:n?n.snapshot():null}),l=e=>{const n=Ha(pd(e));n&&n!==o()&&t("insight.ingress.room.entered",{id:n})},c=e=>{const n=(e=>{const{skill:t,id:n,matchType:r,match:i,...s}=e??{};return"string"!=typeof t||""===t||"string"!=typeof n||""===n?null:{skill:t,id:n,matchType:r??i,args:s}})(e);n&&"secondPerson"!==n.matchType&&t("insight.ingress.skill",{action:n,context:d(ud(e,o()))})},f=t=>{if(a)for(const n of t){if("string"!=typeof n||""===n)continue;const t=Ro(n);s.has(t)||s.set(t,e.events.onSkillMatch(c,t))}};return Object.freeze({start(){a=!0,r?f(r()):i.push(e.events.onSkillMatch(c)),i.push(e.events.on("nexskill.error.reaction",e=>{const n=e?.action,i="string"==typeof n?.skill&&""!==n.skill?Ro(n.skill):null;r&&!s.has(i)||t("insight.ingress.skillError",{skill:i,id:"string"==typeof n?.id&&""!==n.id?n.id:null,line:"string"==typeof n?.originalLine?n.originalLine:null,message:e?.error?.message??String(e?.error)})})),i.push(e.events.on("IRE.Target.Set",e=>{"number"!=typeof e&&t("insight.ingress.target",{id:"string"==typeof e?e:null})})),i.push(e.events.on("Room.AddPlayer",l)),i.push(e.events.on("Room.RemovePlayer",e=>{const n=Ha(pd(e));n&&n!==o()&&t("insight.ingress.room.left",{id:n})})),i.push(e.events.on("Room.Info",()=>{const n=e.gmcp.read("RoomPlayers"),r=o();t("insight.ingress.room.list",{ids:(Array.isArray(n)?n:[]).map(e=>Ha(pd(e))).filter(e=>null!==e&&e!==r)})})),i.push(e.events.on("PromptEvent",()=>{t("insight.ingress.prompt",{})}))},observeSkills:f,stop(){for(a=!1;i.length>0;)i.pop()();for(const e of s.values())e();s.clear()},capture:d})},md=new Set(["afflicted","afflictedOneOf","cured","confirmed","confirmedBlocked","confirmedCount","confirmedLevel","converted","removed"]),gd=e=>Math.min(1,Math.max(0,e)),yd=({roster:e,tables:t,publish:n,notice:r,advanceToNow:i})=>{const s=new Map,a=new Set,o=(e,t)=>{((e,t,i)=>{i.contradiction&&n("insight.belief.contradiction",{id:e,event:t});for(const s of i.diagnostics)"forkCapExceeded"===s.type&&(n("insight.belief.growthCapped",{id:e,event:s.eventType??t.type,beforeCount:s.beforeCount,afterCount:s.afterCount,forkCap:s.forkCap}),r({text:`fork cap hit for ${e} — ${s.beforeCount} → ${s.afterCount} forks (cap ${s.forkCap}) on '${t.type}'. Belief detail was discarded; this is a red-flag condition.`,severity:"error"}))})(e.id,t,e.apply(t))},d=t=>{const n=Ha(t)??e.targetId;return n?e.track(n):null},l=e=>(i(e.id),c(e)),c=e=>({id:e.id,class:e.class,have:t=>ha(e.belief,t)>0,probability:t=>ha(e.belief,t),isBalanceReady:t=>e.isBalanceReady(t),haveDef:t=>e.haveDef(t),limbPercent:t=>e.limbPercent(t),limbStages:t=>e.limbStages(t),skillState:e.getSkillState()}),f=(e,t)=>{switch(t.type){case"defRaised":return e.setDef(t.defId,!0),!0;case"defStripped":return e.setDef(t.defId,!1),!0;case"statObserved":return e.setStat(t.statId,gd(t.value)),!0;case"statChanged":{const n=e.getStat(t.statId);return n&&e.setStat(t.statId,gd(n.value+t.delta)),!0}case"limbHit":return 1===e.limbStages(t.limbId).mangled||e.hitLimb(t.limbId,t.percent).advanced&&p(e,t),!0;case"limbReset":return e.resetLimb(t.limbId),!0;case"updateSkillState":return e.updateSkillState(t.patch),!0;case"classObserved":return e.setClass(t.class),!0;default:return!1}},u=(e,r,i)=>{const s=t.cureById.get(r.cureId);if(!s)return;if(!s.bals_req.every(t=>e.isBalanceReady(t)))return;(i?Ha(i.actorId)!==e.id:Ha(r.id)!==e.id)||1!==s.professions?.length||s.bestowable||f(e,{type:"classObserved",class:s.professions[0]});const a=c(e);for(const t of s.blocks)Array.isArray(t)?o(e,{type:"confirmedCount",pool:t,op:"<",n:t.length}):a.have(t)&&o(e,{type:"confirmed",affId:t,present:!1});const d=(e=>e?Object.entries(Ya).filter(([,t])=>!e.nextLine(t)).map(([e])=>e):[])(i);o(e,{type:"cured",cureId:s.id,excludedAffs:d}),n("insight.cure.observed",{id:e.id,cureId:s.id});for(const t of(({cure:e,view:t,context:n})=>{if(wa(e&&Array.isArray(e.order),"cureInferenceEvents needs a cure row"),wa(t&&"function"==typeof t.have&&"function"==typeof t.isBalanceReady,"cureInferenceEvents needs an opponent view"),!n)return[];const r=[];for(const i of Wa)e.order.includes(i.blockerId)&&t.have(i.blockerId)&&t.isBalanceReady(i.balanceId)&&i.pool.some(e=>t.have(e))&&(n.checkBlock(i.evidence)||r.push({type:"confirmedBlocked",pool:[...i.pool],blockerId:i.blockerId}));for(const i of Ka)e.id===i.cureId&&t.have(i.affId)&&!t.have(i.absentAffId)&&n.checkBlock(i.evidence)&&r.push({type:"confirmed",affId:i.affId,present:!0});return r})({cure:s,view:c(e),context:i}))o(e,t)},p=(e,t)=>{const r=e.belief;return o(e,(e=>({type:"advanced",rungs:Ra(e)}))(t.limbId)),e.belief!==r&&(e.resetLimb(t.limbId),n("insight.limb.advanced",{id:e.id,limb:t.limbId,stages:e.limbStages(t.limbId)}),!0)},h={observe(e,t=null){if(!e||"string"!=typeof e.type)return!1;const n=d(e.id);if(!n)return!1;if(i(n.id),"limbAdvance"===e.type)return p(n,e),!0;if(f(n,e))return!0;if("cured"===e.type)return u(n,e,t),!0;if(!md.has(e.type))throw new Error(`unknown observation type '${e.type}'`);return o(n,(e=>{switch(e.type){case"afflicted":case"removed":return{type:e.type,affId:e.affId};case"afflictedOneOf":return{type:e.type,pool:e.pool,mode:e.mode};case"confirmed":return{type:e.type,affId:e.affId,present:e.present};case"confirmedBlocked":return{type:e.type,pool:e.pool,blockerId:e.blockerId};case"confirmedCount":return{type:e.type,pool:e.pool,op:e.op,n:e.n};case"confirmedLevel":return{type:e.type,affId:e.affId,op:e.op,n:e.n};case"converted":return{type:e.type,from:e.from,to:e.to};case"cured":return{type:e.type,cureId:e.cureId,excludedAffs:e.excludedAffs};default:throw new Error(`cannot construct engine event '${e.type}'`)}})(e)),!0},resolveView(e){const t=d(e);return t?l(t):null},addDefinitions(e){for(const t of e){if("string"!=typeof t?.skill||"string"!=typeof t?.id||"function"!=typeof t?.handler)throw new Error("skill definitions need { skill, id, handler }");s.set(Zo(t.skill,t.id),t),a.add(Ro(t.skill))}},listDefinitions:()=>[...s.keys()],listSkills:()=>[...a],dispatchAction({action:e,context:t}){const n=s.get(Zo(e.skill,e.id));if(!n)return;const r=d(t?.actorId);if(!r)return;if("thirdPerson"===e.matchType){const t=Bs.get(Ro(e.skill));t&&(i=e.args,a=r.id,[i.player,i.player?.id,i.user].some(e=>"string"==typeof e&&Ha(e)===a))&&f(r,{type:"classObserved",class:t})}var i,a;const o=n.handler(e,t,l(r))??[];for(const s of o)h.observe({...s,id:r.id},t)}};return Object.freeze(h)},bd=({onSubscriberError:e=null}={})=>{const t=new Map,n="function"==typeof e;return Object.freeze({on:(e,n)=>(t.has(e)||t.set(e,new Set),t.get(e).add(n),()=>{t.get(e)?.delete(n)}),off(e,n){t.get(e)?.delete(n)},raise(r,i){const s=t.get(r);if(s)for(const t of[...s])if(n)try{t(i)}catch(a){try{e({topic:r,handler:t,cause:a})}catch{}}else t(i)}})},vd=(Object.freeze(["internal","js","eventstream"]),Object.freeze(["locked","experimental"]),(e,t,n,r)=>Object.freeze({audience:e,stability:t,payload:Object.freeze(n),description:r})),kd=Object.freeze({"insight.ready":vd("eventstream","locked",{},"Bootstrap reached READY."),"insight.target.changed":vd("eventstream","locked",{id:"string | null"},"The tracked target changed (null = target cleared)."),"insight.opponent.tracked":vd("eventstream","locked",{id:"string"},"An opponent entered observed tracking (new, or re-acquired after leaving the room)."),"insight.opponent.unobserved":vd("eventstream","locked",{id:"string"},"A tracked opponent left observation; simulation continues on their belief."),"insight.opponent.removed":vd("eventstream","experimental",{id:"string"},"A tracked opponent was removed from the roster. Roster lifecycle, not belief evolution: removal deliberately emits no per-aff insight.aff.lost sweep. Experimental until Phase 6 locks it."),"insight.aff.got":vd("eventstream","locked",{id:"string",affId:"string",probability:"number"},"An affliction became present (marginal probability rose above zero) for an opponent."),"insight.aff.lost":vd("eventstream","locked",{id:"string",affId:"string"},"An affliction left an opponent's belief (marginal probability returned to zero)."),"insight.def.got":vd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed present on an opponent."),"insight.def.lost":vd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed absent on an opponent."),"insight.affs.updated":vd("eventstream","locked",{id:"string"},"Prompt-batched per-opponent change flush: this opponent's affliction state changed since the last flush."),"insight.opponent.updated":vd("eventstream","locked",{id:"string"},"Prompt-batched signal that an opponent's display-visible state changed; consumers should re-read insight.state.opponents[id]."),"insight.cure.observed":vd("eventstream","locked",{id:"string",cureId:"string"},"An opponent was observed using a cure after balance gating. Emitted at application time; a cure with delayMs changes affliction state only at resolution."),"insight.limb.advanced":vd("eventstream","locked",{id:"string",limb:"string",stages:"{ healthy: number, damaged: number, mangled: number }"},"A limb damage ladder advanced; stages is the normalized post-transition distribution."),"insight.belief.growthCapped":vd("js","locked",{id:"string",event:"string",beforeCount:"number",afterCount:"number",forkCap:"number"},"Red flag: fork-cap enforcement discarded hypotheses (charter §5.4). Accompanied by a high-visibility notice."),"insight.belief.contradiction":vd("js","locked",{id:"string",event:"object"},"Evidence contradicted every hypothesis; the belief was repaired, not reset (charter §5.3)."),"insight.ingress.skill":vd("internal","experimental",{action:"object",context:"ObservationContext"},"Normalized nexSkills match action with its ingress-captured ObservationContext."),"insight.ingress.skillError":vd("internal","experimental",{skill:"string | null",id:"string | null",line:"string | null",message:"string"},"nexSkills reported a definition reaction that threw (nexskill.error.reaction). The match still raises, so the action insight observes may carry a stale id or missing affs; the composition renders a warning notice."),"insight.ingress.trigger":vd("internal","experimental",{id:"string",match:"object",context:"ObservationContext"},"A trigger-pack pattern fired, with its ingress-captured ObservationContext."),"insight.ingress.target":vd("internal","experimental",{id:"string | null"},"Normalized IRE.Target.Set."),"insight.ingress.room.entered":vd("internal","experimental",{id:"string"},"GMCP Room.AddPlayer, self excluded."),"insight.ingress.room.left":vd("internal","experimental",{id:"string"},"GMCP Room.RemovePlayer."),"insight.ingress.room.list":vd("internal","experimental",{ids:"string[]"},"GMCP Room.Info occupancy resync, self excluded."),"insight.ingress.prompt":vd("internal","experimental",{},"Host PromptEvent boundary — drives the prompt-batched flush."),"insight.display.flush":vd("internal","experimental",{ids:"string[]"},"The prompt-batched flush completed for these dirty opponents — the display coordinator renders on this boundary."),"insight.display.changed":vd("internal","experimental",{id:"string"},"An opponent's display-visible state changed or the opponent became the target; drives the prompt-batched display/opponent.updated flush."),"insight.model.changed":vd("internal","experimental",{id:"string"},"An opponent's aff marginals or observation mode changed — deliberately aff/mode-scoped, driving insight.affs.updated only (the scheduler reschedules from the roster's full per-opponent change surface)."),"insight.scheduler.elapsed":vd("internal","experimental",{id:"string",expired:"object[]",resolvedCures:"object[]",predicted:"object[]"},"A scheduler timer delivered an elapsed window to an opponent model."),"insight.settings.changed":vd("internal","experimental",{document:"SettingsDocument"},"The settings document changed through the composition's settings surface (every document-mutating verb) — carries the new frozen document; runtime subscribers apply the change live (SETTINGS_AUTHORITY.md §5).")}),wd=(e,t=new WeakMap)=>{if(!e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);const n=Array.isArray(e)?[]:{};t.set(e,n);for(const[r,i]of Object.entries(e))n[r]=wd(i,t);return Object.freeze(n)},Id=({adapter:e,notice:t=()=>{}})=>{const n=bd(),r=(e,n,r)=>{t({text:`${e} failed — ${n} (${r?.message??String(r)})`,severity:"error"})},i=bd({onSubscriberError:({topic:e,cause:t})=>r("public event subscriber",e,t)}),s=e=>{const t=kd[e];if(!t)throw new Error(`Undeclared topic '${e}' — every emitted topic must be declared in topicRegistry.js (charter §8)`);return t},a=e=>{if("internal"===s(e).audience)throw new Error(`Topic '${e}' is internal — not part of the public contract`)};return Object.freeze({publish(t,a={}){const o=s(t);if("internal"===o.audience)return void n.raise(t,a);const d=wd(a);if(i.raise(t,d),"eventstream"===o.audience)try{e.events.raise(t,d)}catch(l){r("EventStream forward",t,l)}},on:(e,t)=>(e=>"internal"===s(e).audience?n:i)(e).on(e,t),events:Object.freeze({on(e,t){if(a(e),"function"!=typeof t)throw new TypeError("insight.events.on needs a function");return i.on(e,t)},off(e,t){if(a(e),"function"!=typeof t)throw new TypeError("insight.events.off needs a function");i.off(e,t)}})})},zd=Object.freeze({safetyFlushMs:200}),_d=e=>`insight4.elapsed.${e}`,Od="insight4.flush.safety",$d=({adapter:e,roster:t,publisher:n,notice:r,safetyFlushMs:i=zd.safetyFlushMs})=>{const{publish:s}=n,a=new Map,o=new Set,d=new Set;let l=!1,c=0;const f=[],u=(e,t)=>{for(const n of t)"forkCapExceeded"===n.type&&(s("insight.belief.growthCapped",{id:e,event:n.eventType??"elapsed",beforeCount:n.beforeCount,afterCount:n.afterCount,forkCap:n.forkCap}),r({text:`fork cap hit for ${e} — ${n.beforeCount} → ${n.afterCount} forks (cap ${n.forkCap}) during simulation. Belief detail was discarded; this is a red-flag condition.`,severity:"error"}))},p=(n,{includeDue:r=!1}={})=>{const i=t.get(n);if(!i)return a.delete(n),void e.clock.clearTimer(_d(n));a.has(n)||a.set(n,e.clock.now());const o=((t,n)=>{const r=t.nextInterestingAt({includeDue:n});if(null===r)return null;const i=e.clock.now(),s=a.get(t.id)??i;return Math.max(0,r-t.now-(i-s))})(i,r);null!==o?e.clock.setTimer(_d(n),o,()=>{const t=e.clock.now(),r=a.get(n)??t;a.set(n,t);const o=Math.max(0,t-r);o>0&&(c+=1);const d=i.elapsed(o);u(n,d.diagnostics),s("insight.scheduler.elapsed",{id:n,expired:d.expired,resolvedCures:d.resolvedCures,predicted:d.predicted}),p(n)}):e.clock.clearTimer(_d(n))},h=()=>{if(l=!1,e.clock.clearTimer(Od),0===o.size&&0===d.size)return;const t=[...o].sort(),n=[...d].sort();o.clear(),d.clear();for(const e of t)s("insight.affs.updated",{id:e});for(const e of n)s("insight.opponent.updated",{id:e});n.length>0&&s("insight.display.flush",{ids:n})},m=()=>{l||(l=!0,e.clock.setTimer(Od,i,h))},g=e=>{o.add(e),m()},y=e=>{d.add(e),m()};return Object.freeze({start(){f.push(t.onOpponentChange(e=>p(e,{includeDue:!0})),n.on("insight.model.changed",({id:e})=>g(e)),n.on("insight.display.changed",({id:e})=>y(e)),n.on("insight.opponent.removed",({id:e})=>{o.delete(e),d.delete(e),p(e)}),n.on("insight.ingress.prompt",h))},stop(){for(;f.length>0;)f.pop()();e.clock.clearTimer(Od),l=!1;for(const t of a.keys())e.clock.clearTimer(_d(t));a.clear(),o.clear(),d.clear()},advanceToNow:n=>{const r=t.get(n);if(!r)return null;const i=e.clock.now(),s=a.get(n)??i;a.set(n,i);const o=i-s;if(o<=0)return null;c+=1;const d=r.elapsed(o);return u(n,d.diagnostics),d},getTimeEpoch:()=>c,reschedule:p,markDirty:e=>{g(e),y(e)},flush:h})},Sd=({roster:e,publish:t})=>{let n=null;const r=new Map;let i=!1;const s=[],a=[],o=e=>({mode:e.mode,affs:e.affs??{},defs:e.defs??{},stats:e.stats??{},limbs:e.limbs??{}}),d=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),l=(e,t,n)=>{const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!0;for(const s of i)if(!d(e,s)||n(e[s])!==n(t[s]))return!0;return!1},c=(e,n)=>{const i=o(n),s=r.get(e);let a=!1,c=!1;s?s.mode!==i.mode&&(a=!0,c=!0,"observed"===i.mode?t("insight.opponent.tracked",{id:e}):t("insight.opponent.unobserved",{id:e})):(a=!0,c=!0,t("insight.opponent.tracked",{id:e}));for(const[r,o]of Object.entries(i.affs)){const n=o.probability;s&&d(s.affs,r)?s.affs[r].probability!==n&&(a=!0,c=!0):(a=!0,c=!0,t("insight.aff.got",{id:e,affId:r,probability:n}))}for(const r of Object.keys(s?.affs??{}))d(i.affs,r)||(a=!0,c=!0,t("insight.aff.lost",{id:e,affId:r}));for(const[r,o]of Object.entries(i.defs))!0===o.have&&!0!==s?.defs[r]?.have&&(c=!0,t("insight.def.got",{id:e,defId:r}));for(const[r,o]of Object.entries(s?.defs??{}))!0===o.have&&!0!==i.defs[r]?.have&&(c=!0,t("insight.def.lost",{id:e,defId:r}));s&&(l(s.stats,i.stats,e=>e.value)||l(s.limbs,i.limbs,e=>e.percent))&&(c=!0),r.set(e,i),a&&t("insight.model.changed",{id:e}),c&&t("insight.display.changed",{id:e})},f=e=>{if(s.push(e),!i){i=!0;try{for(;s.length>0;)s.shift()()}finally{i=!1}}};return Object.freeze({start(){n=e.targetId;for(const t of e.list()){const n=e.get(t);n&&r.set(t,o(n.snapshot()))}a.push(e.onOpponentChange((e,t)=>f(()=>c(e,t))),e.onChange(i=>f(()=>(({ids:i,targetId:s})=>{const a=new Set(i);for(const t of i)if(!r.has(t)){const n=e.get(t);n&&c(t,n.snapshot())}for(const e of[...r.keys()])a.has(e)||(r.delete(e),t("insight.opponent.removed",{id:e}));s!==n&&(n=s,t("insight.target.changed",{id:n}),n&&t("insight.display.changed",{id:n}))})(i))))},stop(){for(;a.length>0;)a.pop()()}})},Nd=(e,t)=>"number"==typeof e?Ha(t?.[e]):null,xd=({adapter:e,settings:t,safetyFlushMs:n,display:r,displaySink:i,notice:s=()=>{},guards:a})=>{const o=Object.freeze({affById:Ts,cureById:As,cureMasks:Rs,balanceById:Es,priorityByAff:Cs,guards:!0===a,get growth(){return t.get().pruning}}),d=Id({adapter:e,notice:s}),{publish:l}=d;let c=0;const f=e=>(c+=1,l("insight.settings.changed",{document:e}),e),u=(e,t)=>{try{return e()}catch(n){throw s({text:`Settings storage ${t} failed: ${n?.message??String(n)}`,severity:"error"}),n}},p=Object.freeze({get:t.get,save:()=>u(t.save,"write"),load:()=>f(u(t.load,"read")),update:e=>f(u(()=>t.update(e),"write")),updateDisplay:e=>f(u(()=>t.updateDisplay(e),"write")),updatePredictive:e=>f(u(()=>t.updatePredictive(e),"write")),replace:e=>f(u(()=>t.replace(e),"write")),reset:()=>f(t.reset()),clear:()=>f(u(t.clear,"clear"))}),h=Va({tables:o,guards:!0===a,policy:t.get().predictive.defaultPolicy,predictionEnabled:t.get().predictive.enabled}),m=$d({adapter:e,roster:h,publisher:d,notice:s,safetyFlushMs:n??t.get().display.safetyFlushMs}),g=yd({roster:h,tables:o,publish:l,notice:s,advanceToNow:m.advanceToNow}),y=Sd({roster:h,publish:l}),b=r?(({publisher:e,roster:t,settings:n,display:r,sink:i})=>{const{renderTarget:s,renderRoster:a,displayTable:o}=r,d=[],l=(e,t)=>{const n=e.targetId?e.opponents[e.targetId]:null;n&&i(s(n,o,t))},c=(e,t)=>{t.display.showRoster&&Object.keys(e.opponents).length>0&&i(a(e.opponents,o,t))};return Object.freeze({start(){d.push(e.on("insight.display.flush",({ids:e})=>{const r=t.snapshot(),i=n.get();r.targetId&&e.includes(r.targetId)&&l(r,i),c(r,i)}))},stop(){for(;d.length>0;)d.pop()()},refresh(){const e=t.snapshot(),r=n.get();l(e,r),c(e,r)}})})({publisher:d,roster:h,settings:p,display:r,sink:i??(t=>e.display.addLine(t))}):null,v=r?(({publisher:e,roster:t,settings:n,display:r,notice:i})=>{const{displayTable:s,renderAffNotice:a,renderDefNotice:o}=r,d=[],l=e=>!0===n.get().display.notices&&t.targetId===e,c=e=>t=>{l(t.id)&&i({html:a({affId:t.affId,present:e},s,n.get())})},f=e=>t=>{l(t.id)&&i({html:o({defId:t.defId,present:e},s,n.get())})};return Object.freeze({start(){d.push(e.on("insight.aff.got",c(!0)),e.on("insight.aff.lost",c(!1)),e.on("insight.def.got",f(!0)),e.on("insight.def.lost",f(!1)))},stop(){for(;d.length>0;)d.pop()()}})})({publisher:d,roster:h,settings:p,display:r,notice:s}):null,k=(()=>{const e=new Map;let t=null;return Object.freeze({rememberQueue(n,r){"string"==typeof n&&n&&"string"==typeof r&&(e.set(n,r),t=n)},snapshot:()=>({queues:Object.fromEntries(e),lastQueue:t}),clear(){e.clear(),t=null}})})(),w=hd({adapter:e,publish:l,commandMemory:k,skills:()=>[...g.listSkills(),...I.listArmingSkills()]}),I=(({adapter:e,roster:t,router:n,publisher:r,capture:i,commandMemory:s,sessionPacks:a=[],promptPacks:o=[]})=>{const{publish:d}=r,l=new Map(a.map(e=>[e.id,e])),c=new Map(o.map(e=>[e.id,e])),f=new Map,u=new Set;for(const z of c.values()){const{skill:e,id:t}=z.armedBy??{};if("string"!=typeof e||""===e||"string"!=typeof t||""===t)continue;const n=Zo(e,t),r=f.get(n);r?r.push(z):f.set(n,[z]),u.add(Ro(e))}const p=new Map,h=new Map,m=[],g=()=>t.listObserved(),y=(e,t,r)=>{for(const i of e??[])n.observe({...i,id:i.id??t},r)},b=(e,r)=>{if(e.remember){const t=e.remember(r);return void(t?.queue&&s.rememberQueue(t.queue.name,t.queue.text))}const a=e.actor??null,o="number"==typeof a?Nd(a,r):null,l=i(o);d("insight.ingress.trigger",{id:e.id,match:r,context:l});const f="room"===a?g():"tracked"===a?t.list():[o];for(const t of f){const i=n.resolveView(t);i&&y(e.handler(r,l,i),i.id,l)}for(const t of c.values())t.armedBy?.trigger===e.id&&w(t,o)},v=(e,t,r)=>{const s=h.get(e.id);if(!s)return;const a="armed"===t.actor?s.state.actorId:Nd(t.actor,r),o=i(a);d("insight.ingress.trigger",{id:`${e.id}.${t.id}`,match:r,context:o});const l=n.resolveView(a);l&&y(t.handler(r,o,l,s.state),l.id,o)},k=t=>{const n=h.get(t);if(!n)return null;for(const r of n.captureIds.values())e.triggers.unregister(r);return h.delete(t),n},w=(n,r=null)=>{k(n.id);const i=n.initState?n.initState({actorId:r,observedIds:g(),targetId:t.targetId}):{actorId:r},s=new Map;for(const t of n.captures)s.set(t.id,e.triggers.register(t.pattern,"prompt",e=>v(n,t,e)));h.set(n.id,{pack:n,state:i,captureIds:s})},I=()=>{for(const e of[...h.keys()]){const t=k(e);if(t?.pack.finalize){const e=i(t.state.actorId??null);y(t.pack.finalize(t.state),t.state.actorId??null,e)}}};return Object.freeze({start(){for(const t of l.values())p.set(t.id,e.triggers.register(t.pattern,"session",e=>b(t,e)));m.push(r.on("insight.ingress.skill",({action:e})=>{const t=f.get(Zo(e.skill,e.id));for(const n of t??[])w(n,null)}),r.on("insight.ingress.prompt",I))},stop(){for(;m.length>0;)m.pop()();for(const e of[...h.keys()])k(e);for(const t of p.values())e.triggers.unregister(t);p.clear()},listSession:()=>[...l.keys()],listArmed:()=>[...h.keys()],listArmingSkills:()=>[...u]})})({adapter:e,roster:h,router:g,publisher:d,capture:w.capture,commandMemory:k,sessionPacks:ld,promptPacks:cd}),z=e=>{g.addDefinitions(e),w.observeSkills(g.listSkills())};z(Do);const _=[],O=()=>{for(w.stop(),I.stop(),m.stop(),y.stop(),b?.stop(),v?.stop();_.length>0;)_.pop()()};try{y.start(),m.start(),b?.start(),v?.start(),_.push(d.on("insight.ingress.skill",g.dispatchAction),d.on("insight.ingress.skillError",({skill:e,id:t,message:n})=>s({text:`nexSkills reaction failed for ${e??"?"}.${t??"?"} — ${n}. Observations from that line may be incomplete.`,severity:"warning"})),d.on("insight.ingress.target",({id:e})=>h.setTarget(e)),d.on("insight.ingress.room.entered",({id:e})=>h.track(e)),d.on("insight.ingress.room.left",({id:e})=>h.untrack(e)),d.on("insight.ingress.room.list",({ids:e})=>(e=>{const t=new Set(e);for(const n of e)h.track(n);for(const n of h.list())t.has(n)||h.untrack(n)})(e)),d.on("insight.settings.changed",({document:e})=>h.updateDefaults({policy:e.predictive.defaultPolicy,predictionEnabled:e.predictive.enabled}))),I.start(),w.start()}catch($){throw O(),$}return Object.freeze({roster:h,router:g,scheduler:m,registrar:I,publish:l,events:d.events,settings:p,getSettingsRevision:()=>c,display:b,observe:g.observe,addDefinitions:z,capture:w.capture,dispose:O})},jd=Object.freeze({schemaVersion:2,autoUpdate:!1,display:Object.freeze({threshold:0,shortNames:!0,colors:!0,notices:!0,showRoster:!1,safetyFlushMs:200}),predictive:Object.freeze({enabled:!1,defaultPolicy:"distribution"}),queries:Object.freeze({presenceFloor:.01}),pruning:Object.freeze({epsilon:Gs.epsilon,forkCap:Gs.forkCap})}),Md=Lr({threshold:xr().min(0).max(1).catch(jd.display.threshold),shortNames:Ar().catch(jd.display.shortNames),colors:Ar().catch(jd.display.colors),notices:Ar().catch(jd.display.notices),showRoster:Ar().catch(jd.display.showRoster),safetyFlushMs:xr().int().min(0).max(1e4).catch(jd.display.safetyFlushMs)}).catch({...jd.display}),Td=Lr({enabled:Ar().catch(jd.predictive.enabled),defaultPolicy:Wr(Ia).catch(jd.predictive.defaultPolicy)}).catch({...jd.predictive}),Ad=Lr({presenceFloor:xr().min(0).max(1).catch(jd.queries.presenceFloor)}).catch({...jd.queries}),Ed=Lr({epsilon:xr().positive().max(.1).catch(jd.pruning.epsilon),forkCap:xr().int().min(1).catch(jd.pruning.forkCap)}).catch({...jd.pruning}),Cd=Lr({schemaVersion:Qr(2).catch(2),autoUpdate:Ar().catch(jd.autoUpdate),display:Md,predictive:Td,queries:Ad,pruning:Ed}).catch({schemaVersion:2,autoUpdate:jd.autoUpdate,display:{...jd.display},predictive:{...jd.predictive},queries:{...jd.queries},pruning:{...jd.pruning}}),Pd=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))Pd(e[t])}return e},Rd=e=>Pd(Cd.parse(e)),Zd=(e,{key:t="insightSettings"}={})=>{let n=Rd(null);const r=(r=n)=>(e.storage.set(t,JSON.stringify(r)),n=r,r);return Object.freeze({get:()=>n,load:()=>(n=Rd((e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return null}return e??null})(e.storage.get(t))),n),save:()=>r(),update:(e={})=>r(Rd({...n,...e,display:{...n.display,...e.display},predictive:{...n.predictive,...e.predictive},queries:{...n.queries,...e.queries},pruning:{...n.pruning,...e.pruning}})),updateDisplay:(e={})=>r(Rd({...n,display:{...n.display,...e}})),updatePredictive:(e={})=>r(Rd({...n,predictive:{...n.predictive,...e}})),replace:e=>r(Rd(e)),reset:()=>(n=Rd(null),n),clear:()=>(e.storage.clear(t),n=Rd(null),n)})},Dd=Object.freeze({forks:Object.freeze([])}),Fd=({roster:e,events:t,settings:n,observe:r,capture:i,advanceToNow:s,reschedule:a,displayRendering:o,refreshDisplay:d,notice:l,addLine:c,getPhase:f,getPhaseRevision:u,getSettingsRevision:p,getTimeEpoch:h,version:m})=>{const g=t=>{const n=t?.id;return null==n?e.getTarget():e.get(n)},y=(e,t)=>{const n=g(e);return n?ha(n.belief,t):0},b=(e,t,n)=>e(g(t)?.belief??Dd,n),v=(e,t)=>b(ma,e,t),k=(e,t)=>b(ga,e,t),w=(e,t)=>((e,t,n,r)=>{ua(t),Js(da.includes(n),`unknown comparison operator '${n}'`),Js(Number.isInteger(r)&&r>=0,"pool count probability needs an integer n >= 0");let i=0;for(const s of e.forks)la(pa(s,t),n,r)&&(i+=s.p);return i})(g(e)?.belief??Dd,t,e?.op,e?.n),I=(e,t)=>e>n.get().queries.presenceFloor&&e>=(e=>{const t="number"==typeof e?.threshold?e.threshold:0;return t>1?t/100:t})(t),z=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))z(e[t])}return e},_=e=>e&&"object"==typeof e?Array.isArray(e)?e.map(_):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_(t)])):e,O=new Map,$=(e,t)=>{const n=O.get(e.id);if(n?.model===e&&n.revision===e.revision&&n.timeEpoch===e.timeEpoch&&n.settingsRevision===t)return n.branch;const r=e.snapshot(),i=z(_({id:r.id,affs:r.affs,limbs:r.limbs,balances:r.balances,stats:r.stats,defs:r.defs,staleness:r.staleness}));return O.set(e.id,{model:e,revision:e.revision,timeEpoch:e.timeEpoch,settingsRevision:t,branch:i}),i};let S=null,N=null;const x=()=>{const t={rosterRevision:e.revision,settingsRevision:p(),phaseRevision:u(),timeEpoch:h()};if(N?.rosterRevision===t.rosterRevision&&N.settingsRevision===t.settingsRevision&&N.phaseRevision===t.phaseRevision&&N.timeEpoch===t.timeEpoch)return S;const r={},i=[...e.list()].sort(),s=new Set(i);for(const n of i)r[n]=$(e.get(n),t.settingsRevision);for(const e of O.keys())s.has(e)||O.delete(e);return S=Object.freeze({system:Object.freeze({phase:f(),version:m}),target:e.targetId?r[e.targetId]??null:null,opponents:Object.freeze(r),settings:n.get()}),N=t,S},j=Object.freeze({get:()=>e.targetId,set:t=>{const n=e.setTarget(t??null);return n?n.id:null},is:t=>null!==e.targetId&&Ha(t)===e.targetId}),M=Object.freeze({track:t=>{const n=e.track(t);return n?n.id:null},remove:t=>e.remove(t),list:()=>e.list(),reset:t=>e.reset(t),resetAll:()=>{e.resetAll()}}),T=Object.freeze({have:(e,t)=>I(y(t,e),t),haveAll:(e,t)=>I(k(t,e),t),haveAny:(e,t)=>I(v(t,e),t),probability:(e,t)=>y(t,e),probabilityAll:(e,t)=>k(t,e),probabilityAny:(e,t)=>v(t,e),expectedPoolCount:(e,t)=>((e,t)=>b(ya,e,t))(t,e),poolCountProbability:(e,t)=>w(t,e)}),A=Object.freeze({have:(e,t)=>!0===g(t)?.haveDef(e)}),E=Object.freeze({get:(e,t)=>{const n=g(t);return n?Object.freeze({percent:n.limbPercent(e),stages:Object.freeze(n.limbStages(e))}):null},hit:(e,t)=>r({type:"limbHit",limbId:e,percent:t?.percent,id:t?.id}),advance:(e,t)=>r({type:"limbAdvance",limbId:e,id:t?.id}),reset:(e,t)=>r({type:"limbReset",limbId:e,id:t?.id})}),C=Object.freeze({have:(e,t)=>{const n=g(t);return!!n&&n.isBalanceReady(e)},remainingMs:(e,t)=>{const n=g(t);return n?n.snapshot().balances[e]?.remainingMs??null:null}}),P=(e,t={})=>{const{id:n,...s}=t;return r({type:e,...s,id:n},i(n??null))},R=Object.freeze({afflicted:e=>P("afflicted",e),afflictedOneOf:({mode:e="firstMissing",...t}={})=>P("afflictedOneOf",{mode:e,...t}),advanced:e=>P("limbAdvance",e),cured:e=>P("cured",e),confirmed:({present:e=!0,...t}={})=>P("confirmed",{present:e,...t}),confirmedCount:e=>P("confirmedCount",e),confirmedLevel:e=>P("confirmedLevel",e),converted:e=>P("converted",e),removed:e=>P("removed",e)}),Z=Object.freeze({enable:e=>{const t=g({id:e});return!!t&&(t.enablePrediction(),!0)},disable:e=>{const t=g({id:e});return!!t&&(t.disablePrediction(),!0)},setPolicy:(e,t)=>{const n=g({id:t});return!!n&&(n.setPolicy(e),!0)},isEnabled:e=>{const t=g({id:e});return!!t&&t.isPredictionEnabled()},stepNow:e=>{const t=g({id:e});if(!t)return null;const n=s(t.id)??{expired:[],predicted:[],diagnostics:[]};return a(t.id),n}}),D=Object.freeze({get:({view:e="target",id:t,affId:r,defId:i,present:s}={})=>{const a=n.get();if("affNotice"===e){if("string"!=typeof r||0===r.length||"boolean"!=typeof s)throw new TypeError("display.get affNotice needs affId and boolean present");return o.renderAffNotice({affId:r,present:s},o.displayTable,a)}if("defNotice"===e){if("string"!=typeof i||0===i.length||"boolean"!=typeof s)throw new TypeError("display.get defNotice needs defId and boolean present");return o.renderDefNotice({defId:i,present:s},o.displayTable,a)}if(!["target","affState","statState"].includes(e))throw new TypeError(`unknown display view '${e}'`);const d=g({id:t});if(!d)return"";const l=d.snapshot();return"target"===e?o.renderTarget(l,o.displayTable,a):"affState"===e?o.renderAffState(l,o.displayTable,a):o.renderStatState(l,o.displayTable,a)},notice:(e,t)=>{l({html:e,severity:t})},refresh:()=>{d()},openDebug:()=>{c(o.renderDebug(x()))}}),F=Object.freeze({target:j,opponents:M,affs:T,defs:A,limbs:E,balances:C,observe:R,simulate:Z,display:D,settings:n}),L=Object.freeze(Object.fromEntries(Object.entries(kd).filter(([,e])=>"internal"!==e.audience))),q=Object.freeze({on:t.on,off:t.off,topics:L});return Object.freeze({get state(){return x()},api:F,events:q})},Ld=["head","torso","leftarm","rightarm","leftleg","rightleg"],qd=e=>String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),Bd=(e,t="",n="")=>{const r=[t?`color: ${t}`:"",n?`background: ${n}`:""].filter(Boolean).join("; ");return r?`<span style="${r}">${e}</span>`:`<span>${e}</span>`},Gd=(e,t="",n="")=>Bd(qd(e),t,n),Jd=e=>e.charAt(0).toUpperCase()+e.slice(1),Ud=(e,t)=>Object.entries(e).filter(([,e])=>e.probability>0&&e.probability>=t).sort(([e,t],[n,r])=>r.probability-t.probability||(e<n?-1:1)),Hd=(e,t,n,r)=>{const i=n.affs[e],s=r.shortNames&&i?i.shortName:e,a=void 0!==t.count?(e=>String(parseFloat(e.toFixed(1))))(t.count):"",o=r.colors&&i?i.fg:"",d=r.colors&&i?i.bg:"";return Gd(`${s}${a}`,o,d)},Vd=(e,t,n)=>{const r=n.display,{bracket:i}=t.chrome,s=[Gd("[",i.fg,i.bg)],a=Ud(e.affs,r.threshold);return a.forEach(([e,n],i)=>{s.push(Hd(e,n,t,r));const o=i<a.length-1?", ":"";s.push(Gd(`: ${(e=>String(Math.round(100*e)/100))(n.probability)}${o}`))}),s.push(Gd("]",i.fg,i.bg)),s},Yd=[["hp","H"],["mana","M"]],Wd=e=>{const t=Math.round(100*Math.min(1,Math.max(0,e)));return`hsl(${1.2*t}, 100%, ${t<75?50:Math.abs(t-100)/2+25}%)`},Kd=(e,t)=>{const n=[],{detail:r}=t.chrome;for(const[i,s]of Yd){const t=e.stats?.[i];if(!t)continue;n.length>0&&n.push(Gd(" "));const a=Math.round(100*Math.min(1,Math.max(0,t.value)));n.push(Gd(`${s}:`,r.fg,r.bg)),n.push(Gd(`${a}%`,Wd(t.value)))}return n},Qd=(e,t,n,r,i)=>{const s=[Gd(`${n?"+":"-"}${e} `,n?"lime":"red")];if("aff"===e){const e=r.affs[t],n=i.display;s.push(Gd(Jd(t),n.colors&&e?e.fg:"",n.colors&&e?e.bg:""))}else s.push(Gd(Jd(t)));return s},Xd=({text:e="",html:t,severity:n="info"},r)=>{const i=r.chrome.severity,s=i[n]??i.info,a="string"==typeof t?Bd(t,s.fg,s.bg):Gd(e,s.fg,s.bg);return`<span class="mono">${(e=>{const{delimiter:t,label:n}=e.chrome.tag;return[Gd("<<",t.fg,t.bg),Gd("insight",n.fg,n.bg),Gd(">> ",t.fg,t.bg)]})(r).join("")}${a}</span>`},el="0.6.1",tl=Object.freeze({BOOTING:"BOOTING",LOADING_SETTINGS:"LOADING_SETTINGS",REGISTERING_TRIGGERS:"REGISTERING_TRIGGERS",READY:"READY",DEGRADED:"DEGRADED"}),nl=Object.freeze({[tl.BOOTING]:Object.freeze([tl.LOADING_SETTINGS,tl.DEGRADED]),[tl.LOADING_SETTINGS]:Object.freeze([tl.REGISTERING_TRIGGERS,tl.DEGRADED]),[tl.REGISTERING_TRIGGERS]:Object.freeze([tl.READY,tl.DEGRADED]),[tl.READY]:Object.freeze([]),[tl.DEGRADED]:Object.freeze([])});var rl="__insight4StorageProbe",il=Object.freeze({displayTable:Ei,renderAffNotice:({affId:e,present:t},n,r)=>`<span class="mono">${Qd("aff",e,t,n,r).join("")}</span>`,renderAffState:(e,t,n)=>`<span class="mono">${Vd(e,t,n).join("")}</span>`,renderDebug:e=>`<pre class="mono">${qd(JSON.stringify(e,null,2))}</pre>`,renderDefNotice:({defId:e,present:t},n,r)=>`<span class="mono">${Qd("def",e,t,n,r).join("")}</span>`,renderNotice:Xd,renderRoster:(e,t,n)=>{const r=n.display;if(!r.showRoster)return"";const{bracket:i,detail:s}=t.chrome,a=[];return Object.keys(e).sort().forEach((n,o)=>{const d=e[n];o>0&&a.push(Gd(" ")),a.push(Gd(`${Jd(n)} `),Gd("[",i.fg,i.bg));const l=Ud(d.affs,r.threshold);l.forEach(([e,n],i)=>{a.push(Hd(e,n,t,r)),i<l.length-1&&a.push(Gd(" "))}),a.push(Gd("]",i.fg,i.bg));const c=Math.round(100*d.staleness);c>0&&a.push(Gd(` ~${c}%`,s.fg,s.bg))}),`<span class="mono">${a.join("")}</span>`},renderStatState:(e,t)=>{const n=Kd(e,t);return n.length>0?`<span class="mono">${n.join("")}</span>`:""},renderTarget:(e,t,n)=>{const{detail:r}=t.chrome,i=[Gd(`${Jd(e.id)} `),...Vd(e,t,n)],s=Kd(e,t);s.length>0&&i.push(Gd(" "),...s);const a=Ld.filter(t=>e.limbs[t]?.percent>0);if(a.length>0){const t=a.map(t=>{const n=e.limbs[t];return`${t}:${Math.round(n.percent)}%`}).join(" ");i.push(Gd(` ${t}`,r.fg,r.bg))}return`<span class="mono">${i.join("")}</span>`}});function sl(e,{safetyFlushMs:t,updateNxs:n=p,guards:r}={}){const i=function({onTransition:e}={}){let t=tl.BOOTING,n=0;const r=[tl.BOOTING];return{getPhase:()=>t,getRevision:()=>n,getHistory:()=>[...r],transition(i){if(!nl[t].includes(i))throw new Error(`Invalid phase transition: ${t} → ${i}`);return t=i,n+=1,r.push(i),e?.(i),t}}}();let a,o=null,d=null,l=null,c=null,f=!1;const u={getPhase:i.getPhase,getPhaseHistory:i.getHistory,getError:()=>o,isReady:()=>i.getPhase()===tl.READY,dispose(){f||(f=!0,l?.dispose(),c&&globalThis.insight===c&&delete globalThis.insight)},get settings(){return d},get runtime(){return l},get state(){return c?c.state:null},get api(){return c?c.api:null},get events(){return c?c.events:null}},h=t=>{try{e.display.addLine(Xd(t,Ei))}catch{}},m=()=>{!0===d?.get?.().autoUpdate&&n({enabled:!0,currentVersion:el,notice:h})},g=e=>(o=e,i.transition(tl.DEGRADED),h({text:`DEGRADED: ${e?.message??String(e)}`,severity:"error"}),m(),u);try{if(s(e),e.storage.clear(rl),e.storage.set(rl,"probe"),e.storage.clear(rl),"function"==typeof e.display.addStream){const t=e.display.addStream.bind(e.display);a=e=>t(e,"combat")}else{const t=e.display.addLine.bind(e.display);a=e=>t(e)}}catch(b){try{e?.storage?.clear?.(rl)}catch{}return g(b)}i.transition(tl.LOADING_SETTINGS);const y=Zd(e);d=y;try{y.load()}catch(b){y.reset(),h({text:`Settings storage is unavailable — running on default settings. (${b?.message??String(b)})`,severity:"warning"})}i.transition(tl.REGISTERING_TRIGGERS);try{l=xd({adapter:e,settings:y,safetyFlushMs:t,guards:r,displaySink:a,notice:h,display:il}),d=l.settings,c=Fd({roster:l.roster,events:l.events,settings:l.settings,observe:l.observe,capture:l.capture,advanceToNow:l.scheduler.advanceToNow,reschedule:l.scheduler.reschedule,displayRendering:il,refreshDisplay:l.display.refresh,notice:h,addLine:a,getPhase:i.getPhase,getPhaseRevision:i.getRevision,getSettingsRevision:l.getSettingsRevision,getTimeEpoch:l.scheduler.getTimeEpoch,version:el})}catch(b){return l?.dispose(),l=null,d=y,g(b)}return i.transition(tl.READY),globalThis.insight=c,l.publish("insight.ready",{}),m(),u}var al=Symbol.for("insight4.instance");!function(t){globalThis[al]?.dispose();const r=sl(function(){const t=new Map;let r=1;const i="undefined"!=typeof nexGui&&"function"==typeof nexGui?.api?.stream?.add?{receiver:nexGui.api.stream,add:nexGui.api.stream.add}:null,s={addLine(e){nexusclient.add_html_line(e)}};return i&&(s.addStream=(e,t)=>{i.add.call(i.receiver,{html:e,stream:t})}),{display:s,storage:{get(t){const n=e();return"function"==typeof n?.get?n.get(t):n?.vars?.[t]},set(t,n){const r=e();if("function"!=typeof r?.set){if(!r?.vars)throw new Error("insight4 storage.set failed — host variables expose neither set() nor a vars record");r.vars[t]=n}else r.set(t,n)},clear(t){const n=e();if("function"!=typeof n?.delete)if("function"!=typeof n?.set){if(!n?.vars)throw new Error("insight4 storage.clear failed — host variables expose neither delete()/set() nor a vars record");delete n.vars[t]}else n.set(t,void 0);else n.delete(t)}},triggers:{register(e,t,n){const i="insight4.trigger."+r++;return nexAction.triggers.add({id:i,tags:["insight4",`lifetime:${t}`],regex:e,action:n}),i},unregister(e){nexAction.triggers.remove(e)}},events:{onSkillMatch(e,t=null){if("undefined"==typeof nexSkills||!nexSkills)throw new Error("nexSkills is unavailable — insight cannot observe skill events");return n(t?`nexskill.match.skill.${t}`:"nexskill.match.skill",e)},on:n,raise(e,t){eventStream.raiseEvent(e,t)}},gmcp:{read:e=>String(e).split(".").reduce((e,t)=>null==e?e:e[t],GMCP)},text:{snapshot:()=>({lines:(nexusclient.current_block??[]).map(e=>({text:"string"==typeof e.line?"function"==typeof e.parsed_line?.text?e.parsed_line.text():e.line:null,isPrompt:!0===e.is_prompt,isHtml:Boolean(e.html_text)})),currentLineIndex:nexusclient.current_line?.index??-1})},clock:{now:()=>Date.now(),setTimer(e,n,r){const i=t.get(e);void 0!==i&&clearTimeout(i),t.set(e,setTimeout(()=>{t.delete(e),r()},n))},clearTimer(e){const n=t.get(e);void 0!==n&&(clearTimeout(n),t.delete(e))}}}}(),t);globalThis[al]=r}()}();
|
|
1
|
+
!function(){var e=async(e,{fetchFn:t=globalThis.fetch,AbortControllerCtor:n=globalThis.AbortController,setTimeoutFn:r=globalThis.setTimeout,clearTimeoutFn:s=globalThis.clearTimeout,timeoutMs:i=1e4}={})=>{if("function"!=typeof t)throw new Error("fetch is not available");const a=`https://api.achaea.com/characters/${e}.json`;let o=null;try{let e;if("function"==typeof n&&i>0){const t=new n;o=r(()=>t.abort(),i),e=t.signal}const s=await t(a,{cache:"no-store",...e?{signal:e}:{}});if(404===s?.status)return null;if(!s?.ok)throw new Error(`${s?.status??"no"} response from ${a}`);return d=(await s.json())?.class,String(d??"").trim().toLowerCase().replace(/\belemental\b/g,"").replace(/[^a-z]/g,"")||null}finally{null!==o&&s(o)}var d},t=(t={})=>Object.freeze({read:n=>e(n,t)});function n(){return nexusclient.variables()}var r=["insight4"];function s(e,t){const n=`insight4.${e}`;return eventStream.registerEvent(e,t,{id:n,tags:r}),()=>{eventStream.removeListener(e,n)}}var i=Object.freeze({display:Object.freeze(["addLine"]),storage:Object.freeze(["get","set","clear"]),triggers:Object.freeze(["register","unregister"]),events:Object.freeze(["onSkillMatch","on","raise"]),gmcp:Object.freeze(["read"]),directory:Object.freeze(["read"]),text:Object.freeze(["snapshot"]),clock:Object.freeze(["now","setTimer","clearTimer"])});Object.freeze(["events.onSkillMatch","events.on"]);function a(e){const t=function(e){if(null===e||"object"!=typeof e)return["adapter is not an object"];const t=[];for(const[n,r]of Object.entries(i)){const s=e[n];if(null!==s&&"object"==typeof s)for(const e of r)"function"!=typeof s[e]&&t.push(`${n}.${e} is not a function`);else t.push(`${n} is missing`)}return t}(e);if(t.length>0)throw new Error(`Adapter contract violation: ${t.join("; ")}`);return e}var o,d=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,l="nexsight",c=`https://unpkg.com/${l}@latest/package.json`,f=e=>{const t=d.exec(String(e??"").trim());if(!t)throw new Error(`invalid version '${e??""}'`);return{core:t.slice(1,4).map(Number),prerelease:t[4]?.split(".")??[]}},u=(e,t)=>{const n=/^\d+$/.test(e)?Number(e):null,r=/^\d+$/.test(t)?Number(t):null;return null!==n&&null!==r?Math.sign(n-r):null!==n?-1:null!==r?1:e===t?0:e<t?-1:1},p=(e,t,n)=>{try{e?.({text:t,severity:n})}catch{}},h=async({enabled:e=!1,currentVersion:t,notice:n=null,fetchFn:r=globalThis.fetch,consoleObj:s=console,setTimeoutFn:i=setTimeout,clearTimeoutFn:a=clearTimeout,timeoutMs:o=1e4,url:d=c}={})=>{if(!e)return null;let h=null;try{if("function"!=typeof r)throw new Error("fetch is not available");f(t);const e=globalThis.AbortController;let s;if(e&&o>0){const t=new e;h=i(()=>t.abort(),o),s=t.signal}const a=await r(d,{cache:"no-store",...s?{signal:s}:{}});if(!a?.ok)throw new Error(`${a?.status??"no"} response from ${d}`);const c=(await a.json())?.version;if(f(c),((e,t)=>{const n=f(e),r=f(t);for(let i=0;i<n.core.length;i+=1)if(n.core[i]!==r.core[i])return Math.sign(n.core[i]-r.core[i]);if(0===n.prerelease.length||0===r.prerelease.length)return n.prerelease.length===r.prerelease.length?0:0===n.prerelease.length?1:-1;const s=Math.max(n.prerelease.length,r.prerelease.length);for(let i=0;i<s;i+=1){if(void 0===n.prerelease[i])return-1;if(void 0===r.prerelease[i])return 1;const e=u(n.prerelease[i],r.prerelease[i]);if(0!==e)return e}return 0})(c,t)<=0)return null;const m=(e=>`https://unpkg.com/${l}@${e}/insight4.nxs`)(c);return p(n,`Update available: ${t} → ${c}. Import ${m}`,"warning"),{currentVersion:t,latestVersion:c,url:m}}catch(m){const e="AbortError"===m?.name?"Update check timed out — check your connection.":`Update check failed: ${m?.message??String(m)}`;return s.error(`[insight4] ${e}`),p(n,e,"error"),null}finally{null!==h&&a(h)}};function m(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const s=a.prototype,i=Object.keys(s);for(let e=0;e<i.length;e++){const t=i[e];t in n||(n[t]=s[t].bind(n))}}const s=n?.Parent??Object;class i extends s{}function a(e){var t;const s=n?.Parent?new i:this;r(s,e),(t=s._zod).deferred??(t.deferred=[]);for(const n of s._zod.deferred)n();return s}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var g=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},b=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(o=globalThis).__zod_globalConfig??(o.__zod_globalConfig={});var y=globalThis.__zod_globalConfig;function v(e){return e&&Object.assign(y,e),y}function k(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function w(e,t){return"bigint"==typeof t?t.toString():t}function I(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function z(e){return null==e}function _(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var O=Symbol("evaluating");function $(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==O)return void 0===r&&(r=O,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function S(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function M(...e){const t={};for(const n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function x(e){return JSON.stringify(e)}var j="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function N(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var A=I(()=>{if(y.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function T(e){if(!1===N(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==N(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function E(e){return T(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var C=new Set(["string","number","symbol"]);function P(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function D(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function R(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}var Z={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function L(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function B(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function F(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function q(e){return"string"==typeof e?e:e?.message}function G(e,t,n){const r=e.message?e.message:q(e.inst?._zod.def?.error?.(e))??q(t?.error?.(e))??q(n.customError?.(e))??q(n.localeError?.(e))??"Invalid input",{inst:s,continue:i,input:a,...o}=e;return o.path??(o.path=[]),o.message=r,t?.reportInput&&(o.input=a),o}function J(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function U(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}var H=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,w,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},V=m("$ZodError",H),W=m("$ZodError",H,{Parent:Error});var Y=e=>(t,n,r,s)=>{const i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new g;if(a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>G(e,i,v())));throw j(t,s?.callee),t}return a.value},K=e=>async(t,n,r,s)=>{const i=r?{...r,async:!0}:{async:!0};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>G(e,i,v())));throw j(t,s?.callee),t}return a.value},Q=e=>(t,n,r)=>{const s=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new g;return i.issues.length?{success:!1,error:new(e??V)(i.issues.map(e=>G(e,s,v())))}:{success:!0,data:i.value}},X=Q(W),ee=e=>async(t,n,r)=>{const s=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>G(e,s,v())))}:{success:!0,data:i.value}},te=ee(W),ne=e=>(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Y(e)(t,n,s)},re=e=>(t,n,r)=>Y(e)(t,n,r),se=e=>async(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return K(e)(t,n,s)},ie=e=>async(t,n,r)=>K(e)(t,n,r),ae=e=>(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Q(e)(t,n,s)},oe=e=>(t,n,r)=>Q(e)(t,n,r),de=e=>async(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return ee(e)(t,n,s)},le=e=>async(t,n,r)=>ee(e)(t,n,r),ce=/^[cC][0-9a-z]{6,}$/,fe=/^[0-9a-z]+$/,ue=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pe=/^[0-9a-vA-V]{20}$/,he=/^[A-Za-z0-9]{27}$/,me=/^[a-zA-Z0-9_-]{21}$/,ge=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,be=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ye=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ve=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var ke=/^(?:(?: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])$/,we=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,Ie=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,ze=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_e=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Oe=/^[A-Za-z0-9_-]*$/,$e=/^https?$/,Se=/^\+[1-9]\d{6,14}$/,Me="(?:(?:\\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])))",xe=new RegExp(`^${Me}$`);function je(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}var Ne=/^-?\d+$/,Ae=/^-?\d+(?:\.\d+)?$/,Te=/^(?:true|false)$/i,Ee=/^[^A-Z]*$/,Ce=/^[^a-z]*$/,Pe=m("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),De={number:"number",bigint:"bigint",object:"date"},Re=m("$ZodCheckLessThan",(e,t)=>{Pe.init(e,t);const n=De[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ze=m("$ZodCheckGreaterThan",(e,t)=>{Pe.init(e,t);const n=De[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Le=m("$ZodCheckMultipleOf",(e,t)=>{Pe.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value!==BigInt(0):0!==function(e,t){const n=e/t,r=Math.round(n),s=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<s?0:n-r}(n.value,t.value))&&n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Be=m("$ZodCheckNumberFormat",(e,t)=>{Pe.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[s,i]=Z[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=s,r.maximum=i,n&&(r.pattern=Ne)}),e._zod.check=a=>{const o=a.value;if(n){if(!Number.isInteger(o))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?a.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}o<s&&a.issues.push({origin:"number",input:o,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),o>i&&a.issues.push({origin:"number",input:o,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Fe=m("$ZodCheckMaxLength",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!z(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const s=J(r);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qe=m("$ZodCheckMinLength",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!z(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const s=J(r);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ge=m("$ZodCheckLengthEquals",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!z(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,s=r.length;if(s===t.length)return;const i=J(r),a=s>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Je=m("$ZodCheckStringFormat",(e,t)=>{var n,r;Pe.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ue=m("$ZodCheckRegex",(e,t)=>{Je.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),He=m("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ee),Je.init(e,t)}),Ve=m("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ce),Je.init(e,t)}),We=m("$ZodCheckIncludes",(e,t)=>{Pe.init(e,t);const n=P(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ye=m("$ZodCheckStartsWith",(e,t)=>{Pe.init(e,t);const n=new RegExp(`^${P(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ke=m("$ZodCheckEndsWith",(e,t)=>{Pe.init(e,t);const n=new RegExp(`.*${P(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Qe=m("$ZodCheckOverwrite",(e,t)=>{Pe.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Xe=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const s of r)this.content.push(s)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}},et={major:4,minor:4,patch:3},tt=m("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=et;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const s of r)for(const t of s._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,s=L(e);for(const i of t){if(i._zod.def.when){if(B(e))continue;if(!i._zod.def.when(e))continue}else if(s)continue;const t=e.issues.length,a=i._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new g;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(s||(s=L(e,t)))});else{if(e.issues.length===t)continue;s||(s=L(e,t))}}return r?r.then(()=>e):e},n=(n,s,i)=>{if(L(n))return n.aborted=!0,n;const a=t(s,r,i);if(a instanceof Promise){if(!1===i.async)throw new g;return a.then(t=>e._zod.parse(t,i))}return e._zod.parse(a,i)};e._zod.run=(s,i)=>{if(i.skipChecks)return e._zod.parse(s,i);if("backward"===i.direction){const t=e._zod.parse({value:s.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,s,i)):n(t,s,i)}const a=e._zod.parse(s,i);if(a instanceof Promise){if(!1===i.async)throw new g;return a.then(e=>t(e,r,i))}return t(a,r,i)}}$(e,"~standard",()=>({validate:t=>{try{const n=X(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return te(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),nt=m("$ZodString",(e,t)=>{var n;tt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),rt=m("$ZodStringFormat",(e,t)=>{Je.init(e,t),nt.init(e,t)}),st=m("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=be),rt.init(e,t)}),it=m("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ye(e))}else t.pattern??(t.pattern=ye());rt.init(e,t)}),at=m("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ve),rt.init(e,t)}),ot=m("$ZodURL",(e,t)=>{rt.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===$e.source&&!/^https?:\/\//i.test(r))return void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});const s=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=s.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),dt=m("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),rt.init(e,t)}),lt=m("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=me),rt.init(e,t)}),ct=m("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ce),rt.init(e,t)}),ft=m("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=fe),rt.init(e,t)}),ut=m("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ue),rt.init(e,t)}),pt=m("$ZodXID",(e,t)=>{t.pattern??(t.pattern=pe),rt.init(e,t)}),ht=m("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=he),rt.init(e,t)}),mt=m("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=je({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Me}T(?:${r})$`)}(t)),rt.init(e,t)}),gt=m("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=xe),rt.init(e,t)}),bt=m("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${je(t)}$`)),rt.init(e,t)}),yt=m("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ge),rt.init(e,t)}),vt=m("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ke),rt.init(e,t),e._zod.bag.format="ipv4"}),kt=m("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=we),rt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),wt=m("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ie),rt.init(e,t)}),It=m("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ze),rt.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function zt(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var _t=m("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=_e),rt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{zt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});var Ot=m("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Oe),rt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!Oe.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return zt(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),$t=m("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Se),rt.init(e,t)});var St=m("$ZodJWT",(e,t)=>{rt.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&"JWT"!==s?.typ||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Mt=m("$ZodNumber",(e,t)=>{tt.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ae,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}const s=n.value;if("number"==typeof s&&!Number.isNaN(s)&&Number.isFinite(s))return n;const i="number"==typeof s?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...i?{received:i}:{}}),n}}),xt=m("$ZodNumberFormat",(e,t)=>{Be.init(e,t),Mt.init(e,t)}),jt=m("$ZodBoolean",(e,t)=>{tt.init(e,t),e._zod.pattern=Te,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}const s=n.value;return"boolean"==typeof s||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),n}}),Nt=m("$ZodUnknown",(e,t)=>{tt.init(e,t),e._zod.parse=e=>e}),At=m("$ZodNever",(e,t)=>{tt.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Tt(e,t,n){e.issues.length&&t.issues.push(...F(n,e.issues)),t.value[n]=e.value}var Et=m("$ZodArray",(e,t)=>{tt.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=Array(s.length);const i=[];for(let e=0;e<s.length;e++){const a=s[e],o=t.element._zod.run({value:a,issues:[]},r);o instanceof Promise?i.push(o.then(t=>Tt(t,n,e))):Tt(o,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function Ct(e,t,n,r,s,i){const a=n in r;if(e.issues.length){if(s&&i&&!a)return;t.issues.push(...F(n,e.issues))}a||s?void 0===e.value?a&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}function Pt(e){const t=Object.keys(e.shape);for(const s of t)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${s}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Dt(e,t,n,r,s,i){const a=[],o=s.keySet,d=s.catchall._zod,l=d.def.type,c="optional"===d.optin,f="optional"===d.optout;for(const u in t){if("__proto__"===u)continue;if(o.has(u))continue;if("never"===l){a.push(u);continue}const s=d.run({value:t[u],issues:[]},r);s instanceof Promise?e.push(s.then(e=>Ct(e,n,u,t,c,f))):Ct(s,n,u,t,c,f)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}var Rt=m("$ZodObject",(e,t)=>{if(tt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const n=I(()=>Pt(t));$(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const r=N,s=t.catchall;let i;e._zod.parse=(t,a)=>{i??(i=n.value);const o=t.value;if(!r(o))return t.issues.push({expected:"object",code:"invalid_type",input:o,inst:e}),t;t.value={};const d=[],l=i.shape;for(const e of i.keys){const n=l[e],r="optional"===n._zod.optin,s="optional"===n._zod.optout,i=n._zod.run({value:o[e],issues:[]},a);i instanceof Promise?d.push(i.then(n=>Ct(n,t,e,o,r,s))):Ct(i,t,e,o,r,s)}return s?Dt(d,o,t,a,n.value,e):d.length?Promise.all(d).then(()=>t):t}}),Zt=m("$ZodObjectJIT",(e,t)=>{Rt.init(e,t);const n=e._zod.parse,r=I(()=>Pt(t));let s;const i=N,a=!y.jitless,o=a&&A.value,d=t.catchall;let l;e._zod.parse=(c,f)=>{l??(l=r.value);const u=c.value;return i(u)?a&&o&&!1===f?.async&&!0!==f.jitless?(s||(s=(e=>{const t=new Xe(["shape","payload","ctx"]),n=r.value,s=e=>{const t=x(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let a=0;for(const r of n.keys)i[r]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=i[r],a=x(r),o=e[r],d="optional"===o?._zod?.optin,l="optional"===o?._zod?.optout;t.write(`const ${n} = ${s(r)};`),d&&l?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):d?t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n const ${n}_present = ${a} in input;\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${a}]\n });\n }\n\n if (${n}_present) {\n if (${n}.value === undefined) {\n newResult[${a}] = undefined;\n } else {\n newResult[${a}] = ${n}.value;\n }\n }\n\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const o=t.compile();return(t,n)=>o(e,t,n)})(t.shape)),c=s(c,f),d?Dt([],u,c,f,l,e):c):n(c,f):(c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c)}});function Lt(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const s=e.filter(e=>!L(e));return 1===s.length?(t.value=s[0].value,s[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>G(e,r,v())))}),t)}var Bt=m("$ZodUnion",(e,t)=>{tt.init(e,t),$(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),$(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),$(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),$(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>_(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,s)=>{if(n)return n(r,s);let i=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},s);if(t instanceof Promise)a.push(t),i=!0;else{if(0===t.issues.length)return t;a.push(t)}}return i?Promise.all(a).then(t=>Lt(t,r,e,s)):Lt(a,r,e,s)}}),Ft=m("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Bt.init(e,t);const n=e._zod.parse;$(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=I(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(s,i)=>{const a=s.value;if(!N(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),s;const o=r.value.get(a?.[t.discriminator]);return o?o._zod.run(s,i):t.unionFallback||"backward"===i.direction?n(s,i):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:a,path:[t.discriminator],inst:e}),s)}}),qt=m("$ZodIntersection",(e,t)=>{tt.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,s=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([t,n])=>Jt(e,t,n)):Jt(e,s,i)}});function Gt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(T(e)&&T(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const i of r){const n=Gt(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};s[i]=n.data}return{valid:!0,data:s}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const s=Gt(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Jt(e,t,n){const r=new Map;let s;for(const o of t.issues)if("unrecognized_keys"===o.code){s??(s=o);for(const e of o.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(o);for(const o of n.issues)if("unrecognized_keys"===o.code)for(const e of o.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(o);const i=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(i.length&&s&&e.issues.push({...s,keys:i}),L(e))return e;const a=Gt(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Ut=m("$ZodRecord",(e,t)=>{tt.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!T(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;const i=[],a=t.keyType._zod.values;if(a){n.value={};const o=new Set;for(const l of a)if("string"==typeof l||"number"==typeof l||"symbol"==typeof l){o.add("number"==typeof l?l.toString():l);const a=t.keyType._zod.run({value:l,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>G(e,r,v())),input:l,path:[l],inst:e});continue}const d=a.value,c=t.valueType._zod.run({value:s[l],issues:[]},r);c instanceof Promise?i.push(c.then(e=>{e.issues.length&&n.issues.push(...F(l,e.issues)),n.value[d]=e.value})):(c.issues.length&&n.issues.push(...F(l,c.issues)),n.value[d]=c.value)}let d;for(const e in s)o.has(e)||(d=d??[],d.push(e));d&&d.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:d})}else{n.value={};for(const a of Reflect.ownKeys(s)){if("__proto__"===a)continue;if(!Object.prototype.propertyIsEnumerable.call(s,a))continue;let o=t.keyType._zod.run({value:a,issues:[]},r);if(o instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof a&&Ae.test(a)&&o.issues.length){const e=t.keyType._zod.run({value:Number(a),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(o=e)}if(o.issues.length){"loose"===t.mode?n.value[a]=s[a]:n.issues.push({code:"invalid_key",origin:"record",issues:o.issues.map(e=>G(e,r,v())),input:a,path:[a],inst:e});continue}const d=t.valueType._zod.run({value:s[a],issues:[]},r);d instanceof Promise?i.push(d.then(e=>{e.issues.length&&n.issues.push(...F(a,e.issues)),n.value[o.value]=e.value})):(d.issues.length&&n.issues.push(...F(a,d.issues)),n.value[o.value]=d.value)}}return i.length?Promise.all(i).then(()=>n):n}}),Ht=m("$ZodEnum",(e,t)=>{tt.init(e,t);const n=k(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>C.has(typeof e)).map(e=>"string"==typeof e?P(e):e.toString()).join("|")})$`),e._zod.parse=(t,s)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}}),Vt=m("$ZodLiteral",(e,t)=>{if(tt.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?P(e):e?P(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,s)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),Wt=m("$ZodTransform",(e,t)=>{tt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new b(e.constructor.name);const s=t.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(e=>(n.value=e,n.fallback=!0,n));if(s instanceof Promise)throw new g;return n.value=s,n.fallback=!0,n}});function Yt(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Kt=m("$ZodOptional",(e,t)=>{tt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",$(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),$(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${_(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=e.value,s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(e=>Yt(e,r)):Yt(s,r)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Qt=m("$ZodExactOptional",(e,t)=>{Kt.init(e,t),$(e._zod,"values",()=>t.innerType._zod.values),$(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Xt=m("$ZodNullable",(e,t)=>{tt.init(e,t),$(e._zod,"optin",()=>t.innerType._zod.optin),$(e._zod,"optout",()=>t.innerType._zod.optout),$(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${_(e.source)}|null)$`):void 0}),$(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),en=m("$ZodDefault",(e,t)=>{tt.init(e,t),e._zod.optin="optional",$(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>tn(e,t)):tn(r,t)}});function tn(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var nn=m("$ZodPrefault",(e,t)=>{tt.init(e,t),e._zod.optin="optional",$(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),rn=m("$ZodNonOptional",(e,t)=>{tt.init(e,t),$(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(t=>sn(t,e)):sn(s,e)}});function sn(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var an=m("$ZodCatch",(e,t)=>{tt.init(e,t),e._zod.optin="optional",$(e._zod,"optout",()=>t.innerType._zod.optout),$(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>G(e,n,v()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>G(e,n,v()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),on=m("$ZodPipe",(e,t)=>{tt.init(e,t),$(e._zod,"values",()=>t.in._zod.values),$(e._zod,"optin",()=>t.in._zod.optin),$(e._zod,"optout",()=>t.out._zod.optout),$(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>dn(e,t.in,n)):dn(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>dn(e,t.out,n)):dn(r,t.out,n)}});function dn(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var ln=m("$ZodReadonly",(e,t)=>{tt.init(e,t),$(e._zod,"propValues",()=>t.innerType._zod.propValues),$(e._zod,"values",()=>t.innerType._zod.values),$(e._zod,"optin",()=>t.innerType?._zod?.optin),$(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(cn):cn(r)}});function cn(e){return e.value=Object.freeze(e.value),e}var fn,un=m("$ZodCustom",(e,t)=>{Pe.init(e,t),tt.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,s=t.fn(r);if(s instanceof Promise)return s.then(t=>pn(t,n,r,e));pn(s,n,r,e)}});function pn(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(U(e))}}var hn=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};(fn=globalThis).__zod_globalRegistry??(fn.__zod_globalRegistry=new hn);var mn=globalThis.__zod_globalRegistry;function gn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function bn(e,t){return new Re({check:"less_than",...R(t),value:e,inclusive:!1})}function yn(e,t){return new Re({check:"less_than",...R(t),value:e,inclusive:!0})}function vn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!1})}function kn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!0})}function wn(e,t){return new Le({check:"multiple_of",...R(t),value:e})}function In(e,t){return new Fe({check:"max_length",...R(t),maximum:e})}function zn(e,t){return new qe({check:"min_length",...R(t),minimum:e})}function _n(e,t){return new Ge({check:"length_equals",...R(t),length:e})}function On(e){return new Qe({check:"overwrite",tx:e})}function $n(e,t){const n=new Pe({check:"custom",...R(t)});return n._zod.check=e,n}function Sn(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??mn,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Mn(e,t,n={path:[],schemaPath:[]}){var r;const s=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const o=e._zod.toJSONSchema?.();if(o)a.schema=o;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,i=t.processors[s.type];if(!i)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);i(e,t,n,r)}const i=e._zod.parent;i&&(a.ref||(a.ref=i),Mn(i,t,r),t.seen.get(i).isParent=!0)}const d=t.metadataRegistry.get(e);return d&&Object.assign(a.schema,d),"input"===t.io&&Nn(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&"_prefault"in a.schema&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function xn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const i of e.seen.entries()){const t=e.metadataRegistry.get(i[0])?.id;if(t){const e=r.get(t);if(e&&e!==i[0])throw new Error(`Duplicate schema id "${t}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(t,i[0])}}const s=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:s,defId:i}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,s=e.external.uri??(e=>e);if(n)return{ref:s(n)};const i=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=i,{defId:i,ref:`${s("__shared")}#/${r}/${i}`}}if(t[1]===n)return{ref:"#"};const s=`#/${r}/`,i=t[1].schema.id??"__schema"+e.counter++;return{defId:i,ref:s+i}})(t);r.def={...r.schema},i&&(r.defId=i);const a=r.schema;for(const e in a)delete a[e];a.$ref=s};if("throw"===e.cycles)for(const i of e.seen.entries()){const e=i[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const n=i[1];if(t!==i[0]){if(e.external){const n=e.external.registry.get(i[0])?.id;if(t!==i[0]&&n){s(i);continue}}(e.metadataRegistry.get(i[0])?.id||n.cycle||n.count>1&&"ref"===e.reused)&&s(i)}else s(i)}}function jn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const s=n.def??n.schema,i={...s},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),o=n.schema;if(!o.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(s,o):(s.allOf=s.allOf??[],s.allOf.push(o)),Object.assign(s,i),t._zod.parent===a)for(const e in s)"$ref"!==e&&"allOf"!==e&&(e in i||delete s[e]);if(o.$ref&&n.def)for(const e in s)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(s[e])===JSON.stringify(n.def[e])&&delete s[e]}const o=t._zod.parent;if(o&&o!==a){r(o);const t=e.seen.get(o);if(t?.schema.$ref&&(s.$ref=t.schema.$ref,t.def))for(const e in s)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(s[e])===JSON.stringify(t.def[e])&&delete s[e]}e.override({zodSchema:t,jsonSchema:s,path:n.path??[]})};for(const d of[...e.seen.entries()].reverse())r(d[0]);const s={};if("draft-2020-12"===e.target?s.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?s.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(n)}Object.assign(s,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;void 0!==i&&s.id===i&&delete s.id;const a=e.external?.defs??{};for(const d of e.seen.entries()){const e=d[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&("draft-2020-12"===e.target?s.$defs=a:s.definitions=a);try{const n=JSON.parse(JSON.stringify(s));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:An(t,"input",e.processors),output:An(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(o){throw new Error("Error converting schema to JSON.")}}function Nn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return Nn(r.element,n);if("set"===r.type)return Nn(r.valueType,n);if("lazy"===r.type)return Nn(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return Nn(r.innerType,n);if("intersection"===r.type)return Nn(r.left,n)||Nn(r.right,n);if("record"===r.type||"map"===r.type)return Nn(r.keyType,n)||Nn(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(Nn(r.in,n)||Nn(r.out,n));if("object"===r.type){for(const e in r.shape)if(Nn(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(Nn(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(Nn(e,n))return!0;return!(!r.rest||!Nn(r.rest,n))}return!1}var An=(e,t,n={})=>r=>{const{libraryOptions:s,target:i}=r??{},a=Sn({...s??{},target:i,io:t,processors:n});return Mn(e,a),xn(a,e),jn(a,e)},Tn={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},En=(e,t,n,r)=>{const s=e._zod.def;Mn(s.innerType,t,r);t.seen.get(e).ref=s.innerType},Cn=m("ZodISODateTime",(e,t)=>{mt.init(e,t),lr.init(e,t)});function Pn(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}(Cn,e)}var Dn=m("ZodISODate",(e,t)=>{gt.init(e,t),lr.init(e,t)});function Rn(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}(Dn,e)}var Zn=m("ZodISOTime",(e,t)=>{bt.init(e,t),lr.init(e,t)});function Ln(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}(Zn,e)}var Bn=m("ZodISODuration",(e,t)=>{yt.init(e,t),lr.init(e,t)});function Fn(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}(Bn,e)}var qn=(e,t)=>{V.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=(e,s=[])=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>r({issues:e},[...s,...i.path]));else if("invalid_key"===i.code)r({issues:i.issues},[...s,...i.path]);else if("invalid_element"===i.code)r({issues:i.issues},[...s,...i.path]);else{const e=[...s,...i.path];if(0===e.length)n._errors.push(t(i));else{let r=n,s=0;for(;s<e.length;){const n=e[s];s!==e.length-1?r[n]=r[n]||{_errors:[]}:(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(i))),r=r[n],s++}}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const s of e.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,w,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,w,2)}},isEmpty:{get:()=>0===e.issues.length}})},Gn=m("ZodError",qn,{Parent:Error}),Jn=Y(Gn),Un=K(Gn),Hn=Q(Gn),Vn=ee(Gn),Wn=ne(Gn),Yn=re(Gn),Kn=se(Gn),Qn=ie(Gn),Xn=ae(Gn),er=oe(Gn),tr=de(Gn),nr=le(Gn),rr=new WeakMap;function sr(e,t,n){const r=Object.getPrototypeOf(e);let s=rr.get(r);if(s||(s=new Set,rr.set(r,s)),!s.has(t)){s.add(t);for(const e in n){const t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){const n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var ir=m("ZodType",(e,t)=>(tt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:An(e,"input"),output:An(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Sn({...n,processors:t});return Mn(e,r),xn(r,e),jn(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Jn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Hn(e,t,n),e.parseAsync=async(t,n)=>Un(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Vn(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Wn(e,t,n),e.decode=(t,n)=>Yn(e,t,n),e.encodeAsync=async(t,n)=>Kn(e,t,n),e.decodeAsync=async(t,n)=>Qn(e,t,n),e.safeEncode=(t,n)=>Xn(e,t,n),e.safeDecode=(t,n)=>er(e,t,n),e.safeEncodeAsync=async(t,n)=>tr(e,t,n),e.safeDecodeAsync=async(t,n)=>nr(e,t,n),sr(e,"ZodType",{check(...e){const t=this.def;return this.clone(M(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return D(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...R(n)})}(ps,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return function(e,t){const n=$n(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(U(e,t.value,n._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(U(r))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(On(e))},optional(){return ns(this)},exactOptional(){return new rs({type:"optional",innerType:this})},nullable(){return is(this)},nullish(){return ns(is(this))},nonoptional(e){return function(e,t){return new ds({type:"nonoptional",innerType:e,...R(t)})}(this,e)},array(){return Lr(this)},or(e){return Jr([this,e])},and(e){return new Hr({type:"intersection",left:this,right:e})},transform(e){return fs(this,new es({type:"transform",transform:e}))},default(e){return t=e,new as({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():E(t)}});var t},prefault(e){return t=e,new os({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():E(t)}});var t},catch(e){return new ls({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return fs(this,e)},readonly(){return new us({type:"readonly",innerType:this})},describe(e){const t=this.clone();return mn.add(t,{description:e}),t},meta(...e){if(0===e.length)return mn.get(this);const t=this.clone();return mn.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>mn.get(e)?.description,configurable:!0}),e)),ar=m("_ZodString",(e,t)=>{nt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:s,maximum:i,format:a,patterns:o,contentEncoding:d}=e._zod.bag;if("number"==typeof s&&(r.minLength=s),"number"==typeof i&&(r.maxLength=i),a&&(r.format=Tn[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),d&&(r.contentEncoding=d),o&&o.size>0){const e=[...o];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,sr(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new Ue({check:"string_format",format:"regex",...R(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new We({check:"string_format",format:"includes",...R(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Ye({check:"string_format",format:"starts_with",...R(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new Ke({check:"string_format",format:"ends_with",...R(t),suffix:e})}(...e))},min(...e){return this.check(zn(...e))},max(...e){return this.check(In(...e))},length(...e){return this.check(_n(...e))},nonempty(...e){return this.check(zn(1,...e))},lowercase(e){return this.check(function(e){return new He({check:"string_format",format:"lowercase",...R(e)})}(e))},uppercase(e){return this.check(function(e){return new Ve({check:"string_format",format:"uppercase",...R(e)})}(e))},trim(){return this.check(On(e=>e.trim()))},normalize(...e){return this.check(function(e){return On(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(On(e=>e.toLowerCase()))},toUpperCase(){return this.check(On(e=>e.toUpperCase()))},slugify(){return this.check(On(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),or=m("ZodString",(e,t)=>{nt.init(e,t),ar.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}(cr,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}(pr,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}(Mr,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}(hr,t)),e.guid=t=>e.check(gn(fr,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}(ur,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}(ur,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}(ur,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}(ur,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}(mr,t)),e.guid=t=>e.check(gn(fr,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}(gr,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}(br,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}(yr,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}(Or,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}($r,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}(vr,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}(kr,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}(wr,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}(Ir,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}(zr,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}(_r,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}(Sr,t)),e.datetime=t=>e.check(Pn(t)),e.date=t=>e.check(Rn(t)),e.time=t=>e.check(Ln(t)),e.duration=t=>e.check(Fn(t))});function dr(e){return function(e,t){return new e({type:"string",...R(t)})}(or,e)}var lr=m("ZodStringFormat",(e,t)=>{rt.init(e,t),ar.init(e,t)}),cr=m("ZodEmail",(e,t)=>{at.init(e,t),lr.init(e,t)}),fr=m("ZodGUID",(e,t)=>{st.init(e,t),lr.init(e,t)}),ur=m("ZodUUID",(e,t)=>{it.init(e,t),lr.init(e,t)}),pr=m("ZodURL",(e,t)=>{ot.init(e,t),lr.init(e,t)}),hr=m("ZodEmoji",(e,t)=>{dt.init(e,t),lr.init(e,t)}),mr=m("ZodNanoID",(e,t)=>{lt.init(e,t),lr.init(e,t)}),gr=m("ZodCUID",(e,t)=>{ct.init(e,t),lr.init(e,t)}),br=m("ZodCUID2",(e,t)=>{ft.init(e,t),lr.init(e,t)}),yr=m("ZodULID",(e,t)=>{ut.init(e,t),lr.init(e,t)}),vr=m("ZodXID",(e,t)=>{pt.init(e,t),lr.init(e,t)}),kr=m("ZodKSUID",(e,t)=>{ht.init(e,t),lr.init(e,t)}),wr=m("ZodIPv4",(e,t)=>{vt.init(e,t),lr.init(e,t)}),Ir=m("ZodIPv6",(e,t)=>{kt.init(e,t),lr.init(e,t)}),zr=m("ZodCIDRv4",(e,t)=>{wt.init(e,t),lr.init(e,t)}),_r=m("ZodCIDRv6",(e,t)=>{It.init(e,t),lr.init(e,t)}),Or=m("ZodBase64",(e,t)=>{_t.init(e,t),lr.init(e,t)}),$r=m("ZodBase64URL",(e,t)=>{Ot.init(e,t),lr.init(e,t)}),Sr=m("ZodE164",(e,t)=>{$t.init(e,t),lr.init(e,t)}),Mr=m("ZodJWT",(e,t)=>{St.init(e,t),lr.init(e,t)}),xr=m("ZodNumber",(e,t)=>{Mt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:s,maximum:i,format:a,multipleOf:o,exclusiveMaximum:d,exclusiveMinimum:l}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number";const c="number"==typeof l&&l>=(s??Number.NEGATIVE_INFINITY),f="number"==typeof d&&d<=(i??Number.POSITIVE_INFINITY),u="draft-04"===t.target||"openapi-3.0"===t.target;c?u?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l:"number"==typeof s&&(r.minimum=s),f?u?(r.maximum=d,r.exclusiveMaximum=!0):r.exclusiveMaximum=d:"number"==typeof i&&(r.maximum=i),"number"==typeof o&&(r.multipleOf=o)})(e,t,n),sr(e,"ZodNumber",{gt(e,t){return this.check(vn(e,t))},gte(e,t){return this.check(kn(e,t))},min(e,t){return this.check(kn(e,t))},lt(e,t){return this.check(bn(e,t))},lte(e,t){return this.check(yn(e,t))},max(e,t){return this.check(yn(e,t))},int(e){return this.check(Ar(e))},safe(e){return this.check(Ar(e))},positive(e){return this.check(vn(0,e))},nonnegative(e){return this.check(kn(0,e))},negative(e){return this.check(bn(0,e))},nonpositive(e){return this.check(yn(0,e))},multipleOf(e,t){return this.check(wn(e,t))},step(e,t){return this.check(wn(e,t))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function jr(e){return function(e,t){return new e({type:"number",checks:[],...R(t)})}(xr,e)}var Nr=m("ZodNumberFormat",(e,t)=>{xt.init(e,t),xr.init(e,t)});function Ar(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}(Nr,e)}var Tr=m("ZodBoolean",(e,t)=>{jt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function Er(e){return function(e,t){return new e({type:"boolean",...R(t)})}(Tr,e)}var Cr=m("ZodUnknown",(e,t)=>{Nt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Pr(){return new Cr({type:"unknown"})}var Dr=m("ZodNever",(e,t)=>{At.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function Rr(e){return function(e,t){return new e({type:"never",...R(t)})}(Dr,e)}var Zr=m("ZodArray",(e,t)=>{Et.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=n,i=e._zod.def,{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(s.minItems=a),"number"==typeof o&&(s.maxItems=o),s.type="array",s.items=Mn(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,sr(e,"ZodArray",{min(e,t){return this.check(zn(e,t))},nonempty(e){return this.check(zn(1,e))},max(e,t){return this.check(In(e,t))},length(e,t){return this.check(_n(e,t))},unwrap(){return this.element}})});function Lr(e,t){return function(e,t,n){return new e({type:"array",element:t,...R(n)})}(Zr,e,t)}var Br=m("ZodObject",(e,t)=>{Zt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=n,i=e._zod.def;s.type="object",s.properties={};const a=i.shape;for(const l in a)s.properties[l]=Mn(a[l],t,{...r,path:[...r.path,"properties",l]});const o=new Set(Object.keys(a)),d=new Set([...o].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));d.size>0&&(s.required=Array.from(d)),"never"===i.catchall?._zod.def.type?s.additionalProperties=!1:i.catchall?i.catchall&&(s.additionalProperties=Mn(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(s.additionalProperties=!1)})(e,t,n,r),$(e,"shape",()=>t.shape),sr(e,"ZodObject",{keyof(){return Kr(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Pr()})},loose(){return this.clone({...this._zod.def,catchall:Pr()})},strict(){return this.clone({...this._zod.def,catchall:Rr()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!T(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return D(e,M(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return S(this,"shape",n),n}}))}(this,e)},safeExtend(e){return function(e,t){if(!T(t))throw new Error("Invalid input to safeExtend: expected a plain object");return D(e,M(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return S(this,"shape",n),n}}))}(this,e)},merge(e){return function(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");return D(e,M(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return S(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}(this,e)},pick(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return D(e,M(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return S(this,"shape",e),e},checks:[]}))}(this,e)},omit(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return D(e,M(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return S(this,"shape",r),r},checks:[]}))}(this,e)},partial(...e){return function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return D(t,M(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(s[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)s[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return S(this,"shape",s),s},checks:[]}))}(ts,this,e[0])},required(...e){return t=ds,n=this,r=e[0],D(n,M(n._zod.def,{get shape(){const e=n._zod.def.shape,s={...e};if(r)for(const n in r){if(!(n in s))throw new Error(`Unrecognized key: "${n}"`);r[n]&&(s[n]=new t({type:"nonoptional",innerType:e[n]}))}else for(const n in e)s[n]=new t({type:"nonoptional",innerType:e[n]});return S(this,"shape",s),s}}));var t,n,r}})});function Fr(e,t){return new Br({type:"object",shape:e??{},...R(t)})}function qr(e,t){return new Br({type:"object",shape:e,catchall:Rr(),...R(t)})}var Gr=m("ZodUnion",(e,t)=>{Bt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=!1===s.inclusive,a=s.options.map((e,n)=>Mn(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options});function Jr(e,t){return new Gr({type:"union",options:e,...R(t)})}var Ur=m("ZodDiscriminatedUnion",(e,t)=>{Gr.init(e,t),Ft.init(e,t)});var Hr=m("ZodIntersection",(e,t)=>{qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=Mn(s.left,t,{...r,path:[...r.path,"allOf",0]}),a=Mn(s.right,t,{...r,path:[...r.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length;n.allOf=[...o(i)?i.allOf:[i],...o(a)?a.allOf:[a]]})(e,t,n,r)});var Vr=m("ZodRecord",(e,t)=>{Ut.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=n,i=e._zod.def;s.type="object";const a=i.keyType,o=a._zod.bag?.patterns;if("loose"===i.mode&&o&&o.size>0){const e=Mn(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});s.patternProperties={};for(const t of o)s.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(s.propertyNames=Mn(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=Mn(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=a._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(s.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Wr(e,t,n){return t&&t._zod?new Vr({type:"record",keyType:e,valueType:t,...R(n)}):new Vr({type:"record",keyType:dr(),valueType:e,...R(t)})}var Yr=m("ZodEnum",(e,t)=>{Ht.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=k(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const s={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);s[i]=t.entries[i]}return new Yr({...t,checks:[],...R(r),entries:s})},e.exclude=(e,r)=>{const s={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete s[t]}return new Yr({...t,checks:[],...R(r),entries:s})}});function Kr(e,t){return new Yr({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...R(t)})}var Qr=m("ZodLiteral",(e,t)=>{Vt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,s=[];for(const i of r.values)if(void 0===i){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof i){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(0===s.length);else if(1===s.length){const e=s[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else s.every(e=>"number"==typeof e)&&(n.type="number"),s.every(e=>"string"==typeof e)&&(n.type="string"),s.every(e=>"boolean"==typeof e)&&(n.type="boolean"),s.every(e=>null===e)&&(n.type="null"),n.enum=s})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Xr(e,t){return new Qr({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}var es=m("ZodTransform",(e,t)=>{Wt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new b(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(U(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(U(t))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=s,n.fallback=!0,n)}});var ts=m("ZodOptional",(e,t)=>{Kt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>En(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function ns(e){return new ts({type:"optional",innerType:e})}var rs=m("ZodExactOptional",(e,t)=>{Qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>En(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ss=m("ZodNullable",(e,t)=>{Xt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=Mn(s.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=s.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function is(e){return new ss({type:"nullable",innerType:e})}var as=m("ZodDefault",(e,t)=>{en.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.default=JSON.parse(JSON.stringify(s.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var os=m("ZodPrefault",(e,t)=>{nn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(s.innerType,t,r),t.seen.get(e).ref=s.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(s.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var ds=m("ZodNonOptional",(e,t)=>{rn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(s.innerType,t,r),t.seen.get(e).ref=s.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ls=m("ZodCatch",(e,t)=>{an.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;let i;Mn(s.innerType,t,r),t.seen.get(e).ref=s.innerType;try{i=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var cs=m("ZodPipe",(e,t)=>{on.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=s.in._zod.traits.has("$ZodTransform"),a="input"===t.io?i?s.out:s.in:s.out;Mn(a,t,r),t.seen.get(e).ref=a})(e,t,0,r),e.in=t.in,e.out=t.out});function fs(e,t){return new cs({type:"pipe",in:e,out:t})}var us=m("ZodReadonly",(e,t)=>{ln.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var ps=m("ZodCustom",(e,t)=>{un.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});var hs,ms,gs,bs=dr().regex(/^[a-z]+$/,"aff ids are single lowercase words"),ys=dr().regex(/^[a-z][a-zA-Z]*$/,"balance ids are lowercase-led words"),vs=dr().regex(/^[a-z]+( [a-z]+)*$/,"cure ids are lowercase words separated by single spaces"),ks=dr().regex(/^[a-z]+$/,"venom ids are single lowercase words"),ws=dr().regex(/^[a-z]+$/,"profession ids are single lowercase words"),Is=qr({shortName:dr().min(1),fg:dr(),bg:dr()}),zs={id:bs,display:Is.optional(),curesTo:bs.optional(),pseudo:Er().default(!1),curedLast:Er().default(!1)},_s=qr({...zs,kind:Xr("plain")}),Os=qr({...zs,kind:Xr("timed"),durationMs:jr().int().positive(),provenance:Kr(["verified","unverified"]).default("verified")}),$s=qr({...zs,kind:Xr("countable"),min:jr().int().min(0),max:jr().int().positive()}).refine(e=>e.max>e.min,{message:"countable affs need max > min"}),Ss=(hs="kind",ms=[_s,Os,$s],new Ur({type:"union",options:ms,discriminator:hs,...R(gs)})),Ms=Lr(Ss).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"aff ids must be unique"}),xs=qr({fg:dr(),bg:dr()}),js=Wr(dr().min(1),xs),Ns=Wr(bs,Is),As=qr({delimiter:xs,label:xs}),Ts=qr({info:xs,warning:xs,error:xs}),Es=qr({bracket:xs,detail:xs,tag:As,severity:Ts}),Cs=qr({affs:Ns,chrome:Es}),Ps=js.parse({antimony:{fg:"olive",bg:""},argentum:{fg:"royalblue",bg:""},arsenic:{fg:"",bg:""},aurum:{fg:"ForestGreen",bg:""},azurite:{fg:"",bg:""},calamine:{fg:"",bg:""},calcite:{fg:"slategray",bg:""},cinnabar:{fg:"greenyellow",bg:""},cuprum:{fg:"DeepSkyBlue",bg:""},ferrum:{fg:"DarkOrange",bg:""},gypsum:{fg:"",bg:""},magnesium:{fg:"Red",bg:""},plumbum:{fg:"Gold",bg:""},quartz:{fg:"",bg:""},quicksilver:{fg:"",bg:""},realgar:{fg:"firebrick",bg:""},stannum:{fg:"Tan",bg:""},caloric:{fg:"darkseagreen",bg:""},mending:{fg:"orchid",bg:""},epidermal:{fg:"sienna",bg:""},restoration:{fg:"darkviolet",bg:""},health:{fg:"lightpink",bg:""},writhe:{fg:"paleyellow",bg:"darkslategray"}}),Ds=Ps,Rs={addiction:{shortName:"add",...Ds.ferrum},aeon:{shortName:"ae",...Ds.cinnabar},agoraphobia:{shortName:"agor",...Ds.argentum},amnesia:{shortName:"amn",fg:"",bg:""},anorexia:{shortName:"ANO",...Ds.epidermal},asthma:{shortName:"AST",...Ds.aurum},blackout:{shortName:"bo",fg:"",bg:""},blindness:{shortName:"unb",...Ds.arsenic},bound:{shortName:"bnd",...Ds.writhe},brokenleftarm:{shortName:"la1",...Ds.mending},brokenleftleg:{shortName:"ll1",...Ds.mending},brokenrightarm:{shortName:"ra1",...Ds.mending},brokenrightleg:{shortName:"rl1",...Ds.mending},bruisedribs:{shortName:"ribs",fg:"",bg:""},burning:{shortName:"burn",...Ds.mending},calcifiedskull:{shortName:"calh",...Ds.restoration},calcifiedtorso:{shortName:"calt",...Ds.restoration},claustrophobia:{shortName:"clau",...Ds.stannum},cleanseaura:{shortName:"cleanse",fg:"",bg:""},clumsiness:{shortName:"clu",...Ds.aurum},concussion:{shortName:"conc",...Ds.restoration},confusion:{shortName:"con",...Ds.stannum},corruption:{shortName:"corr",fg:"",bg:""},crackedribs:{shortName:"cr",...Ds.health},crushedthroat:{shortName:"cru",...Ds.mending},daeggerimpale:{shortName:"daeg",...Ds.writhe},damagedleftarm:{shortName:"la2",...Ds.restoration},damagedleftleg:{shortName:"ll2",...Ds.restoration},damagedrightarm:{shortName:"ra2",...Ds.restoration},damagedrightleg:{shortName:"rl2",...Ds.restoration},damagedhead:{shortName:"hd2",...Ds.restoration},darkshade:{shortName:"dark",...Ds.ferrum},dazed:{shortName:"dzd",...Ds.cinnabar},dazzled:{shortName:"dzl",...Ds.mending},deadening:{shortName:"dea",...Ds.cinnabar},deafness:{shortName:"und",...Ds.calamine},dehydrated:{shortName:"deh",fg:"",bg:""},dementia:{shortName:"dem",...Ds.stannum},depression:{shortName:"dep",...Ds.plumbum},deteriorate:{shortName:"det",fg:"",bg:""},disloyalty:{shortName:"disl",...Ds.realgar},disrupted:{shortName:"disr",fg:"",bg:""},dissonance:{shortName:"disso",...Ds.plumbum},dizziness:{shortName:"diz",...Ds.plumbum},enmesh:{shortName:"enmsh",...Ds.writhe},ensorcelled:{shortName:"ensor",fg:"",bg:""},entangled:{shortName:"entgl",...Ds.writhe},epilepsy:{shortName:"epi",...Ds.plumbum},fear:{shortName:"fear",fg:"",bg:""},flushings:{shortName:"flush",...Ds.ferrum},frostbite:{shortName:"frost",...Ds.caloric},frozen:{shortName:"frz",...Ds.caloric},fulminated:{shortName:"fulm",...Ds.plumbum},generosity:{shortName:"gen",...Ds.cuprum},grievouswounds:{shortName:"grv",...Ds.health},guilt:{shortName:"gui",...Ds.argentum},haemophilia:{shortName:"haem",...Ds.ferrum},hallucinations:{shortName:"hall",...Ds.stannum},hamstrung:{shortName:"hms",fg:"",bg:""},healthleech:{shortName:"hthl",...Ds.aurum},heartseed:{shortName:"heart",...Ds.restoration},hellsight:{shortName:"hell",...Ds.realgar},horror:{shortName:"hor",...Ds.argentum},hypersomnia:{shortName:"hypers",...Ds.stannum},hypochondria:{shortName:"hypoch",...Ds.argentum},hypothermia:{shortName:"hypoth",...Ds.restoration},icefisted:{shortName:"ice",fg:"",bg:""},impaled:{shortName:"impl",...Ds.writhe},impatience:{shortName:"IMPAT",...Ds.plumbum},indifference:{shortName:"ind",...Ds.cuprum},itching:{shortName:"itch",...Ds.epidermal},justice:{shortName:"just",...Ds.cuprum},kkractlebrand:{shortName:"kkr",...Ds.health},laceratedthroat:{shortName:"lac2",...Ds.restoration},latched:{shortName:"latch",...Ds.health},lethargy:{shortName:"let",...Ds.ferrum},lightbind:{shortName:"light",fg:"",bg:""},loneliness:{shortName:"lon",...Ds.argentum},lovers:{shortName:"love",...Ds.cuprum},manaleech:{shortName:"man",...Ds.realgar},mangledleftarm:{shortName:"la3",...Ds.restoration},mangledleftleg:{shortName:"ll3",...Ds.restoration},mangledrightarm:{shortName:"ra3",...Ds.restoration},mangledrightleg:{shortName:"rl3",...Ds.restoration},mangledhead:{shortName:"hd3",...Ds.restoration},masochism:{shortName:"maso",...Ds.argentum},mildtrauma:{shortName:"tor1",...Ds.restoration},mycalium:{shortName:"myc",...Ds.plumbum},nausea:{shortName:"nau",...Ds.ferrum},numbedleftarm:{shortName:"nbla",fg:"",bg:""},numbedrightarm:{shortName:"nbra",fg:"",bg:""},pacified:{shortName:"pac",...Ds.cuprum},palpatarfeed:{shortName:"worm",fg:"",bg:""},paralysis:{shortName:"PAR",...Ds.magnesium},paranoia:{shortName:"prn",...Ds.stannum},parasite:{shortName:"prs",...Ds.aurum},peace:{shortName:"pea",...Ds.cuprum},phlogisticated:{shortName:"phlog",fg:"",bg:""},pinshot:{shortName:"psh",fg:"",bg:""},pressure:{shortName:"pres",...Ds.calcite},prone:{shortName:"pr",fg:"",bg:""},pyramides:{shortName:"pyra",...Ds.magnesium},pyre:{shortName:"pyre",...Ds.cuprum},rebbies:{shortName:"reb",...Ds.aurum},recklessness:{shortName:"reck",...Ds.argentum},retribution:{shortName:"retr",...Ds.cuprum},revealed:{shortName:"rev",fg:"",bg:""},sandfever:{shortName:"sand",...Ds.plumbum},scalded:{shortName:"scald",...Ds.epidermal},scytherus:{shortName:"scy",...Ds.ferrum},selarnia:{shortName:"sel",...Ds.mending},sensitivity:{shortName:"sen",...Ds.aurum},serioustrauma:{shortName:"tor2",...Ds.restoration},shadowmadness:{shortName:"shad",...Ds.plumbum},shivering:{shortName:"shiv",...Ds.caloric},shyness:{shortName:"shy",...Ds.plumbum},skullfractures:{shortName:"sf",...Ds.health},slashedthroat:{shortName:"lac1",...Ds.epidermal},sleeping:{shortName:"slp",fg:"",bg:""},slickness:{shortName:"SLI",...Ds.magnesium},slimeobscure:{shortName:"slime",fg:"",bg:""},spiritburn:{shortName:"spirB",...Ds.argentum},spiritwrack:{shortName:"spirW",fg:"",bg:""},stupidity:{shortName:"st",...Ds.plumbum},stuttering:{shortName:"stut",...Ds.epidermal},homunculusmercury:{shortName:"merc",fg:"",bg:""},temperedcholeric:{shortName:"choH",...Ds.antimony},temperedmelancholic:{shortName:"melaH",...Ds.antimony},temperedphlegmatic:{shortName:"phleH",...Ds.antimony},temperedsanguine:{shortName:"sanH",...Ds.antimony},tenderskin:{shortName:"tend",...Ds.argentum},tension:{shortName:"tens",...Ds.cinnabar},timeflux:{shortName:"tmfx",fg:"",bg:""},timeloop:{shortName:"tmlp",...Ds.cuprum},tonguetied:{shortName:"tngt",...Ds.restoration},torntendons:{shortName:"tt",...Ds.health},transfixation:{shortName:"trfx",...Ds.writhe},unweavingbody:{shortName:"unwB",...Ds.ferrum},unweavingspirit:{shortName:"unwS",...Ds.cinnabar},unweavingmind:{shortName:"unwM",...Ds.plumbum},unblind:{shortName:"unB",fg:"",bg:""},undeaf:{shortName:"unD",fg:"",bg:""},unnamable:{shortName:"unnam",fg:"",bg:""},vertigo:{shortName:"vert",...Ds.argentum},vitrified:{shortName:"vitri",fg:"",bg:""},voidfisted:{shortName:"void",fg:"",bg:""},voyria:{shortName:"voy",fg:"",bg:""},weariness:{shortName:"wea",...Ds.aurum},webbed:{shortName:"web",...Ds.writhe},whisperingmadness:{shortName:"wmad",...Ds.argentum},wristfractures:{shortName:"wf",...Ds.health}},Zs=Cs.parse({affs:Rs,chrome:{bracket:{fg:"LightGoldenRodYellow",bg:""},detail:{fg:"darkgray",bg:""},tag:{delimiter:{fg:"#784695",bg:""},label:{fg:"#CBCE91",bg:""}},severity:{info:{fg:"#FFF2D7",bg:""},warning:{fg:"orange",bg:""},error:{fg:"red",bg:""}}}}),Ls=Zs.affs,Bs=(Zs.chrome,new Set(["undeaf","unblind","cleanseaura","unnamable"])),Fs=new Set(["dissonance"]),qs=new Map([["mangledleftleg","damagedleftleg"],["mangledleftarm","damagedleftarm"],["mangledrightleg","damagedrightleg"],["mangledrightarm","damagedrightarm"],["mangledhead","damagedhead"],["serioustrauma","mildtrauma"],["damagedleftleg","brokenleftleg"],["damagedleftarm","brokenleftarm"],["damagedrightleg","brokenrightleg"],["damagedrightarm","brokenrightarm"]]),Gs=(e,t,n={})=>({id:e,kind:t,...n,...qs.has(e)?{curesTo:qs.get(e)}:{},...Bs.has(e)?{pseudo:!0}:{},...Fs.has(e)?{curedLast:!0}:{},...Ls[e]?{display:Ls[e]}:{}}),Js=Ms.parse([...["undeaf","unblind","cleanseaura","addiction","agoraphobia","amnesia","anorexia","asphyxiating","asthma","blindness","bloodfire","bound","brokenleftarm","brokenrightarm","brokenleftleg","brokenrightleg","calcifiedskull","calcifiedtorso","claustrophobia","clumsiness","coldfate","concussion","conflagration","confusion","convergence","cremated","crushedthroat","daeggerimpale","damagedhead","damagedleftarm","damagedleftleg","damagedrightarm","damagedrightleg","darkshade","dazed","deadening","deafness","death","deathsickness","deepsleep","degenerate","dementia","depression","deteriorate","diminished","disloyalty","disrupted","dissonance","dizziness","earworm","enlightenment","entangled","epilepsy","fear","flushings","fratricide","frostbite","frozen","fulminated","generosity","grievouswounds","guilt","haemophilia","hallucinations","hatred","healthleech","hellsight","hindered","homunculusmercury","hypersomnia","hypochondria","hypothermia","icebound","impaled","impatience","indifference","insomnia","isolation","itching","justice","kkractlebrand","laceratedthroat","lapsingconsciousness","latched","lethargy","loneliness","lovers","lullaby","manaleech","masochism","mildtrauma","mangledleftarm","mangledleftleg","mangledrightarm","mangledrightleg","mangledhead","mindclamp","mycalium","nausea","pacified","paralysis","paranoia","parasite","peace","penitence","prone","pyramides","rebbies","recklessness","retribution","sandfever","scytherus","selarnia","sensitivity","serioustrauma","shadowmadness","shivering","shyness","slashedthroat","sleeping","slickness","spiritburn","stupidity","stuttering","tenderskin","tension","timeloop","tonguetied","transfixation","vertigo","vitiated","voyria","weariness","webbed","whisperingmadness","harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"].map(e=>Gs(e,"plain")),...Object.entries({accentato:{durationMs:2e4,provenance:"unverified"},aeon:{durationMs:16e3},airfisted:{durationMs:16e3},betrayal:{durationMs:15e3},blackout:{durationMs:4e3,provenance:"unverified"},blistered:{durationMs:15e3,provenance:"unverified"},breathless:{durationMs:3e3},bruisedribs:{durationMs:3e4},cadmuscurse:{durationMs:2e4},condemned:{durationMs:2e4},constricted:{durationMs:3e4},corruption:{durationMs:45e3},dazzled:{durationMs:6e4},dehydrated:{durationMs:6e4},demonstain:{durationMs:12e4},empoweredloshre:{durationMs:12e3},empoweredmannaz:{durationMs:2e4},enmesh:{durationMs:5e3},ensorcelled:{durationMs:2e4},flamefisted:{durationMs:3e4},hamstrung:{durationMs:9e3},heartseed:{durationMs:11e3},hecatecurse:{durationMs:16e3},icefisted:{durationMs:3e4},internalbleeding:{durationMs:3e4},inquisition:{durationMs:3e4},kaisurge:{durationMs:15e3,provenance:"unverified"},lightbind:{durationMs:22e3},lovestruck:{durationMs:5e3},mindravaged:{durationMs:2e4,provenance:"unverified"},muddled:{durationMs:12e3},numbedleftarm:{durationMs:7500},numbedrightarm:{durationMs:7500},petrified:{durationMs:1e4,provenance:"unverified"},palpatarfeed:{durationMs:19e3,provenance:"unverified"},phlogisticated:{durationMs:45e3},pinshot:{durationMs:18e3},reeling:{durationMs:2e4},revealed:{durationMs:6e4},scalded:{durationMs:2e4},scrambledbrains:{durationMs:6e4},silenced:{durationMs:2e4,provenance:"unverified"},silver:{durationMs:18e4},slimeobscure:{durationMs:6e4},solarburn:{durationMs:5e3},snared:{durationMs:2e4},speechless:{durationMs:3e5},stridulating:{durationMs:15e3},stun:{durationMs:3e3,provenance:"unverified"},succumbed:{durationMs:3e4},timeflux:{durationMs:6e4},trueblind:{durationMs:6e3},unconsciousness:{durationMs:1e4},unnamable:{durationMs:4800},vinewreathed:{durationMs:3e4},vitrified:{durationMs:45e3},voidfisted:{durationMs:5e3},waterbonds:{durationMs:3e4},weakenedmind:{durationMs:6e4},woeconstrained:{durationMs:3e4}}).map(([e,t])=>Gs(e,"timed",t)),...Object.entries({pressure:{min:0,max:5},crescendo:{min:0,max:5},unweavingbody:{min:0,max:5},unweavingspirit:{min:0,max:5},unweavingmind:{min:0,max:5},burning:{min:0,max:5},horror:{min:0,max:5},pyre:{min:0,max:3},temperedcholeric:{min:0,max:8},temperedmelancholic:{min:0,max:8},temperedphlegmatic:{min:0,max:8},temperedsanguine:{min:0,max:8},torntendons:{min:0,max:6},crackedribs:{min:0,max:6},skullfractures:{min:0,max:6},wristfractures:{min:0,max:6}}).map(([e,t])=>Gs(e,"countable",t))]),Us=qr({id:ws,skills:Lr(dr().regex(/^[a-z]+$/,"skill keys are single lowercase words")).default([])}),Hs=Lr(Us).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"profession ids must be unique"}),Vs=Hs.parse([{id:"alchemist",skills:[]},{id:"apostate",skills:[]},{id:"bard",skills:[]},{id:"blademaster",skills:[]},{id:"depthswalker",skills:["aeonics","shadowmancy"]},{id:"dragon",skills:["dragoncraft"]},{id:"firelord",skills:[]},{id:"jester",skills:["tarot"]},{id:"magi",skills:["elementalism","crystalism","artificing"]},{id:"monk",skills:[]},{id:"occultist",skills:["occultism","domination","tarot"]},{id:"priest",skills:[]},{id:"psion",skills:["weaving"]},{id:"runewarden",skills:[]},{id:"serpent",skills:["venom"]},{id:"shikudo",skills:[]}]),Ws=Jr([bs,Lr(bs).min(2)]),Ys=qr({id:vs,command:dr().min(1),class:Kr(["linear","tree","special"]),order:Lr(bs).default([]),ordered:Er().default(!1),layered:Er().default(!1),bals_used:Lr(ys).default([]),bals_req:Lr(ys).default([]),blocks:Lr(Ws).default([]),professions:Lr(ws).optional(),bestowable:Er().default(!1),prio:jr().int().min(0),delayMs:jr().int().positive().optional()}).refine(e=>!e.bestowable||void 0!==e.professions,{message:"bestowable is a class-cure trait — it requires a professions gate"}),Ks=Lr(Ys).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"cure ids must be unique"}),Qs=["itching","paralysis","fear","brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg","lapsingconsciousness","aeon","lovers","confusion","epilepsy","pacified","blackout","dazed","justice","slashedthroat","hellsight","peace","dazzled","shyness","dizziness","slickness","asthma","nausea","selarnia","weariness","scytherus","fratricide","haemophilia","clumsiness","hallucinations","healthleech","dementia","recklessness","anorexia","masochism","impatience","stupidity","generosity","addiction","deadening","manaleech","stuttering","paranoia","agoraphobia","loneliness","claustrophobia","vertigo","hypersomnia","shivering","frozen","burning","sensitivity","hypochondria","lethargy","disloyalty","darkshade","voyria","dissonance","phlogisticated","silver","spiritburn","tenderskin","guilt","skullfractures","wristfractures","crackedribs","torntendons","indifference","retribution","shadowmadness","parasite","depression","timeloop","crushedthroat","tension","unweavingspirit","grievouswounds","pyramides","flushings","rebbies","mycalium","sandfever","crescendo","fulminated","frostbite"],Xs=["death","anorexia","sleeping"],ei=["death","asthma","sleeping"],ti=["death","slickness","sleeping"],ni=["death","sleeping","anorexia"],ri=[["brokenleftarm","brokenrightarm"],["brokenleftarm","damagedrightarm"],["brokenleftarm","mangledrightarm"],["damagedleftarm","brokenrightarm"],["damagedleftarm","damagedrightarm"],["damagedleftarm","mangledrightarm"],["mangledleftarm","brokenrightarm"],["mangledleftarm","damagedrightarm"],["mangledleftarm","mangledrightarm"]],si=["entangled","transfixation","impaled","webbed","bound"],ii=["darkshade","haemophilia","lethargy","addiction","scytherus","nausea","flushings","unweavingbody"],ai=["paralysis","slickness","pyramides"],oi=["clumsiness","healthleech","sensitivity","weariness","asthma","rebbies","parasite"],di=["undeaf","deafness"],li=["horror","fratricide","masochism","loneliness","vertigo","recklessness","agoraphobia","guilt","whisperingmadness","spiritburn","tenderskin","hypochondria"],ci=["pacified","peace","lovers","justice","generosity","indifference","retribution","pyre","timeloop","diminished","stridulating"],fi=["temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"],ui=["unblind","blindness"],pi=["claustrophobia","paranoia","confusion","hypersomnia","hallucinations","dementia","crescendo"],hi=["stupidity","epilepsy","dizziness","shyness","impatience","dissonance","depression","sandfever","mycalium","shadowmadness","unweavingmind","fulminated"],mi=["pressure"],gi=["disloyalty","hellsight","manaleech","slickness"],bi=["aeon","dazed","deadening","tension","unweavingspirit","earworm"],yi=(e,t,n={})=>({id:e,command:`eat ${e}`,class:"linear",order:t,bals_used:["herb"],bals_req:["herb"],blocks:Xs,prio:0,...n}),vi=(e,t)=>({id:e,command:`smoke ${e}`,class:"linear",...t?{order:t}:{},bals_used:["smoke"],bals_req:["smoke"],blocks:ei,prio:0}),ki=(e,t,n={})=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["salve"],bals_req:["salve","restoration"],blocks:ti,prio:0,...n}),wi=(e,t)=>({...ki(e,t),bals_used:["restoration"],delayMs:4e3}),Ii=(e,t)=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["sip"],bals_req:["sip"],prio:0}),zi=(e,t)=>({id:e,class:"tree",order:Qs,prio:0,...t}),_i=Ks.parse([yi("ferrum",ii),yi("magnesium",ai),yi("aurum",oi),yi("calamine",di,{delayMs:2500}),yi("argentum",li),yi("cuprum",ci),yi("antimony",fi),yi("arsenic",ui),yi("stannum",pi),yi("plumbum",hi,{class:"special"}),yi("calcite",mi),yi("ginseng",ii),yi("bloodroot",ai),yi("kelp",oi),yi("hawthorn",di,{delayMs:2500}),yi("lobelia",li),yi("bellwort",ci),yi("ginger",fi),yi("bayberry",ui),yi("ash",pi),yi("goldenseal",hi,{class:"special"}),yi("pear",mi),{...vi("smoke",["aeon","disloyalty","hellsight","manaleech","slickness","deadening","tension","unweavingspirit","earworm"]),command:"smoke cinnabar"},vi("cinnabar",bi),vi("malachite"),vi("realgar",gi),vi("elm",bi),vi("skullcap"),vi("valerian",gi),ki("caloric",["frozen","shivering","frostbite"],{layered:!0}),ki("epidermal to body",["anorexia"]),ki("epidermal to head",["stuttering","blindness","deafness"]),ki("epidermal to ears",["deafness"]),ki("mending to head",["crushedthroat","dazzled"]),ki("mending to arms",["brokenleftarm","brokenrightarm"],{ordered:!0}),ki("mending to legs",["brokenleftleg","brokenrightleg"],{ordered:!0}),ki("mending to body",["burning"]),wi("restoration to head",["mangledhead","damagedhead","calcifiedskull","concussion","tonguetied"]),wi("restoration to torso",["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso","internalbleeding"]),wi("restoration to arms",["mangledleftarm","mangledrightarm","damagedleftarm","damagedrightarm"]),wi("restoration to legs",["mangledleftleg","mangledrightleg","damagedleftleg","damagedrightleg"]),{id:"health",command:"sip health",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:ni,prio:0},{id:"mana",command:"sip mana",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:ni,prio:0},Ii("health to head",["skullfractures"]),Ii("health to torso",["crackedribs","grievouswounds"]),Ii("health to arms",["wristfractures"]),Ii("health to legs",["torntendons","latched","kkractlebrand"]),{id:"fitness",command:"fitness",class:"linear",order:["asthma"],bals_used:["balance","fitness"],bals_req:["equilibrium","balance","fitness"],blocks:["death","weariness","sleeping"],professions:["monk","shikudo","runewarden"],prio:0},zi("bloodboil",{command:"cast bloodboil",bals_used:["equilibrium","bloodboil"],bals_req:["equilibrium","balance","bloodboil"],blocks:["death","haemophilia","sleeping",...ri,...si],professions:["magi"]}),{id:"dragonflex",command:"dragonflex",class:"linear",order:["webbed","entangled"],bals_used:["balance"],bals_req:["balance"],professions:["dragon"],prio:0},zi("dragonheal",{command:"dragonheal",bals_used:["dragonheal","equilibrium"],bals_req:["balance","equilibrium"],blocks:["death","sleeping",["recklessness","weariness"]],professions:["dragon"]}),{id:"dwinnu",command:"chant dwinnu",class:"linear",order:["webbed","entangled"],bals_used:["voice"],bals_req:["voice"],professions:["bard"],prio:0},{id:"rage",command:"rage",class:"linear",order:["pacified","peace","lovers","generosity","stridulating"],bals_used:["rage"],bals_req:["rage"],professions:["runewarden"],prio:95},zi("salt",{command:"educe salt",bals_used:["salt","equilibrium"],bals_req:["equilibrium","salt"],blocks:["death","stupidity","sleeping"],professions:["alchemist"]}),zi("siphon",{command:"siphon",bals_used:["angel"],bals_req:["angel"],blocks:["death","sleeping"],professions:["apostate","priest"]}),zi("shrugging",{command:"shrugging",bals_used:["shrugging"],bals_req:["equilibrium","balance","shrugging"],blocks:["death","weariness","sleeping"],professions:["serpent"]}),zi("slough",{command:"slough impurities",bals_used:["slough","balance"],bals_req:["equilibrium","balance","slough"],blocks:["death","weariness","sleeping"],professions:["firelord"]}),zi("fool",{command:"fling fool at me",bals_used:["fool","balance"],bals_req:["equilibrium","balance","fool"],blocks:["death","prone","paralysis","sleeping",...ri,...si],professions:["occultist"]}),zi("accelerate",{command:"chrono accelerate",bals_used:["accelerate","balance"],bals_req:["equilibrium","balance","accelerate"],blocks:["death","sleeping","recklessness"],professions:["depthswalker"]}),zi("alleviate",{command:"alleviate",bals_used:["alleviate","balance"],bals_req:["equilibrium","balance","alleviate"],blocks:["death","paralysis","sleeping"],professions:["blademaster"]}),zi("dagaz",{command:"sketch dagaz on ground",bals_used:["dagaz"],blocks:["death"],professions:["runewarden"],bestowable:!0}),zi("generic",{command:"classcure",bals_used:["generic"],bals_req:["equilibrium","balance","generic"],blocks:["death"],professions:[]}),{id:"insomnia",command:"insomnia",class:"linear",order:["insomnia"],blocks:["death","hypersomnia","sleeping"],prio:0},{id:"focus",command:"focus",class:"linear",order:["stupidity","epilepsy","dizziness","shyness","claustrophobia","paranoia","confusion","hallucinations","dementia","pacified","lovers","generosity","masochism","loneliness","vertigo","recklessness","agoraphobia","anorexia","stuttering"],bals_used:["focus"],bals_req:["focus"],blocks:["death","impatience","sleeping"],prio:0},{id:"concentrate",command:"concentrate",class:"linear",order:["disrupted"],blocks:["death","sleeping","confusion"],prio:0},{id:"immunity",command:"sip immunity",class:"linear",order:["voyria"],bals_used:["immunity"],bals_req:["immunity"],blocks:ni,prio:0},{id:"stand",command:"stand",class:"linear",order:["prone"],bals_req:["balance","equilibrium"],blocks:["death","sleeping","paralysis","brokenrightleg","brokenleftleg","damagedleftleg","damagedrightleg","mangledrightleg","mangledleftleg",...si],prio:0},zi("tree",{command:"touch tree",bals_used:["tree"],bals_req:["tree"],blocks:["death","sleeping","paralysis",...ri,...si]}),{id:"potash",command:"eat potash",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:ni,prio:0},{id:"moss",command:"eat moss",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:ni,prio:0},{id:"restore",command:"restore",class:"linear",order:["brokenleftarm","brokenrightarm","brokenleftleg","brokenrightleg","skullfractures","torntendons","wristfractures","crackedribs"],bals_used:["equilibrium"],bals_req:["balance","equilibrium"],prio:0},{id:"touch soul",command:"touch soul",class:"linear",order:["amnesia"],blocks:["death"],prio:101}]),Oi=dr().regex(/^[a-z]+$/,"defence ids are single lowercase words"),$i=qr({stripDelayMs:jr().int().positive(),applyDelayMs:jr().int().positive(),conservativeLeadMs:jr().int().nonnegative(),blockedBy:Lr(bs).min(1)}).refine(e=>e.conservativeLeadMs<e.applyDelayMs,{message:"conservativeLeadMs must leave a positive effective application delay"}).refine(e=>new Set(e.blockedBy).size===e.blockedBy.length,{message:"blockedBy ids must be unique"}),Si=Lr(qr({id:Oi,default:Er().default(!1),restore:$i.optional()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"defence ids must be unique"}),Mi=Si.parse([{id:"speed",default:!0,restore:{stripDelayMs:2200,applyDelayMs:3e3,conservativeLeadMs:200,blockedBy:ni}},{id:"insulation",default:!0},{id:"temperence",default:!0},{id:"kola",default:!0},{id:"insomnia",default:!0},{id:"cloak",default:!0},{id:"fangbarrier",default:!0},{id:"levitating",default:!0},{id:"selfishness",default:!0},{id:"curseward"},{id:"prismatic"},{id:"rebounding"},{id:"shield"}]),xi=qr({affId:bs,observedDurationMs:jr().int().positive(),predictiveDurationMs:jr().int().positive()}),ji=qr({id:ys,observedDurationMs:jr().int().positive(),predictiveDurationMs:jr().int().positive(),bufferPolicy:Kr(["buffered","exact"]),extendedBy:Lr(xi).default([])}).refine(e=>[e,...e.extendedBy].every(t=>((e,{observedDurationMs:t,predictiveDurationMs:n})=>"buffered"===e?t===Math.round(.75*n):t===n)(e.bufferPolicy,t)),{message:"observedDurationMs must follow the declared bufferPolicy"}).refine(e=>e.extendedBy.every(t=>t.predictiveDurationMs>e.predictiveDurationMs),{message:"an extension must be longer than the base duration"}).refine(e=>new Set(e.extendedBy.map(e=>e.affId)).size===e.extendedBy.length,{message:"extension aff ids must be unique within a balance"}),Ni=Lr(ji).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"balance ids must be unique"}),Ai=e=>({predictiveDurationMs:e,observedDurationMs:Math.round(.75*e)}),Ti=(e,t,n=[])=>({id:e,...Ai(t),bufferPolicy:"buffered",extendedBy:n.map(([e,t])=>({affId:e,...Ai(t)}))}),Ei=Ni.parse([Ti("balance",2e3),Ti("equilibrium",2e3),Ti("sip",4500),Ti("herb",1500),Ti("smoke",1500),Ti("salve",1e3),Ti("restoration",4e3),Ti("focus",2500,[["whisperingmadness",4e3],["weakenedmind",5e3]]),Ti("tree",15e3),Ti("moss",6e3),Ti("immunity",1e4),Ti("accelerate",1e4),Ti("alleviate",1e4),Ti("angel",1e4),Ti("bloodboil",1e4),Ti("dragonheal",2e4),Ti("fitness",1e4),Ti("fool",3e4),Ti("rage",1e4),Ti("salt",1e4),Ti("shrugging",12e3),Ti("slough",1e4),Ti("dagaz",2e4),Ti("voice",2500),Ti("generic",12e3)]),Ci=Lr(qr({id:bs,level:jr().int().min(1),prio:jr().int().min(0)})).min(1).refine(e=>new Set(e.map(e=>`${e.id}:${e.level}`)).size===e.length,{message:"priority (id, level) pairs must be unique"}),Pi=(e,t)=>t.map(t=>({id:t,level:1,prio:e})),Di=(e,t,n)=>Array.from({length:t},(t,r)=>({id:e,level:r+1,prio:n})),Ri=Ci.parse([...Pi(0,["accentato","airfisted","asphyxiating","blistered","bloodfire","bruisedribs","cadmuscurse","coldfate","condemned","conflagration","constricted","convergence","corruption","cremated","death","deathsickness","deepsleep","degenerate","dehydrated","demonstain","deteriorate","empoweredloshre","empoweredmannaz","enlightenment","enmesh","ensorcelled","flamefisted","hamstrung","hatred","hecatecurse","hindered","homunculusmercury","icefisted","inquisition","isolation","kaisurge","lightbind","lullaby","mindclamp","mindravaged","muddled","numbedleftarm","numbedrightarm","palpatarfeed","petrified","phlogisticated","pinshot","revealed","scalded","scrambledbrains","silenced","silver","slimeobscure","solarburn","stun","timeflux","trueblind","vinewreathed","vitiated","vitrified","voidfisted","waterbonds","weakenedmind","unconsciousness"]),...Pi(2,["aeon","concussion","crushedthroat","paralysis","peace"]),...Pi(3,["sleeping","grievouswounds","latched","dazzled","weariness","prone","timeloop","fulminated"]),...Di("unweavingbody",5,3),...Di("unweavingmind",5,3),...Di("unweavingspirit",5,3),...Pi(4,["spiritburn","heartseed","guilt","tenderskin","pyramides","parasite","hypochondria","pacified","depression","confusion","retribution","shadowmadness","whisperingmadness","hellsight"]),...Pi(5,["anorexia","mycalium","flushings","rebbies","sandfever","asthma","healthleech"]),...Pi(6,["impatience","itching","scytherus","clumsiness","kkractlebrand","damagedleftleg","darkshade","slickness","recklessness","dementia","fratricide","icebound"]),...Pi(7,["bound","daeggerimpale","entangled","sensitivity","transfixation","webbed","tonguetied","haemophilia","lethargy","manaleech","dissonance"]),{id:"pyre",level:1,prio:7},{id:"pyre",level:2,prio:6},{id:"pyre",level:3,prio:5},...Pi(8,["damagedrightleg","hypersomnia","earworm","diminished"]),...Di("skullfractures",6,8),...Di("crescendo",5,8),...Pi(9,["brokenleftleg","brokenrightleg","hallucinations"]),...Di("torntendons",6,9),...Pi(10,["calcifiedskull","calcifiedtorso","mangledleftleg","mangledrightleg","disrupted","mangledhead","voyria"]),...Di("crackedribs",6,10),...Pi(11,["hypothermia","impaled","brokenleftarm","brokenrightarm","indifference","addiction","nausea","deadening","frozen","shivering","mildtrauma","internalbleeding"]),...Pi(12,["stupidity","damagedleftarm","disloyalty"]),...Di("wristfractures",6,12),...Pi(13,["tension","damagedhead","dazed"]),...Di("burning",5,13),...Pi(14,["lovers","damagedrightarm","temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"]),...Di("pressure",5,14),...Pi(15,["mangledleftarm","mangledrightarm"]),...Pi(16,["agoraphobia","claustrophobia","generosity","justice","loneliness","vertigo"]),...Pi(17,["paranoia"]),...Pi(18,["serioustrauma","epilepsy"]),...Pi(20,["laceratedthroat","slashedthroat","stuttering"]),...Pi(21,["selarnia","fear","masochism"]),...Pi(23,["dizziness","shyness"]),...Di("horror",5,26),...Pi(30,["amnesia","blackout"]),...Pi(0,["insomnia","deafness","blindness"]),...Pi(100,["harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"])]),Zi=Lr(bs).min(1).refine(e=>new Set(e).size===e.length,{message:"pool affliction ids must be unique"}),Li=Lr(qr({profession:ws,pools:Wr(dr().min(1),Zi)})).min(1).refine(e=>new Set(e.map(e=>e.profession)).size===e.length,{message:"professions must be unique"}),Bi=Li.parse([{profession:"occultist",pools:{mentals:["claustrophobia","agoraphobia","lovers","dementia","epilepsy","hallucinations","confusion","stupidity","paranoia","vertigo","shyness","addiction","recklessness","masochism"],physicals:["asthma","paralysis","slickness","haemophilia","clumsiness","healthleech","sensitivity","darkshade"],bubonis:["vertigo","recklessness","confusion","masochism","paranoia","shyness","claustrophobia"],chimera:["confusion","hallucinations","agoraphobia","claustrophobia","dementia"],moon:["stupidity","masochism","hallucinations","hypersomnia","confusion","epilepsy","claustrophobia","agoraphobia"],whisperingmadness:["dementia","stupidity","confusion","hypersomnia","paranoia","hallucinations","impatience","addiction","agoraphobia","lovers","loneliness","recklessness","masochism"],justice:["paralysis","sensitivity","healthleech","haemophilia","weariness","asthma","clumsiness"],unnamable:["confusion","stupidity","dementia"]}},{profession:"psion",pools:{blast:["impatience","stupidity","blackout","dizziness","epilepsy","unweavingmind"]}},{profession:"depthswalker",pools:{leach:["parasite","healthleech","manaleech"],madness:["shadowmadness","vertigo","hallucinations"],retribution:["retribution","justice"],degeneration:["clumsiness","weariness","paralysis"],depression:["depression","nausea","hypochondria"]}}]),Fi=Lr(qr({id:ks,aff:bs.nullable()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"venom ids must be unique"}),qi=Fi.parse([{id:"xentio",aff:"clumsiness"},{id:"eurypteria",aff:"recklessness"},{id:"kalmia",aff:"asthma"},{id:"digitalis",aff:"shyness"},{id:"darkshade",aff:"darkshade"},{id:"curare",aff:"paralysis"},{id:"epteth",aff:null},{id:"prefarar",aff:"sensitivity"},{id:"monkshood",aff:"disloyalty"},{id:"euphorbia",aff:"nausea"},{id:"oculus",aff:"unblind"},{id:"vernalius",aff:"weariness"},{id:"epseth",aff:null},{id:"larkspur",aff:"dizziness"},{id:"slike",aff:"anorexia"},{id:"delphinium",aff:"sleeping"},{id:"notechis",aff:"haemophilia"},{id:"vardrax",aff:"addiction"},{id:"loki",aff:"loki"},{id:"aconite",aff:"stupidity"},{id:"selarnia",aff:null},{id:"gecko",aff:"slickness"},{id:"scytherus",aff:"scytherus"},{id:"nechamadra",aff:"shivering"}]),Gi=new Map(Js.map(e=>[e.id,e])),Ji=new Map(_i.map(e=>[e.id,e])),Ui=new Map(Ei.map(e=>[e.id,e])),Hi=new Map(Mi.map(e=>[e.id,e])),Vi=Object.freeze(Object.fromEntries(Mi.filter(e=>e.default).map(({id:e})=>[e,!0]))),Wi=(()=>{const e=new Map;for(const t of Ri)e.has(t.id)||e.set(t.id,new Map),e.get(t.id).set(t.level,t.prio);return e})(),Yi=(...e)=>new Set(_i.filter(t=>t.bals_used.some(t=>e.includes(t))).map(e=>e.id)),Ki=Object.freeze({layers:Object.freeze(_i.filter(e=>e.layered).map(e=>Object.freeze([...e.order]))),curedLast:Object.freeze(Js.filter(e=>e.curedLast).map(e=>Object.freeze({affId:e.id,pool:Object.freeze([...new Set(_i.filter(t=>"tree"!==t.class&&t.order.includes(e.id)).flatMap(e=>e.order).filter(t=>t!==e.id))])})))}),Qi=e=>new Set(_i.filter(t=>e.has(t.id)).flatMap(e=>e.order)),Xi=Qi(Yi("herb")),ea=Qi(Yi("smoke")),ta=new Map(qi.map(e=>[e.id,e.aff])),na=new Map(Bi.map(e=>[e.profession,e.pools])),ra=(()=>{const e=new Map;for(const t of Vs)for(const n of t.skills)e.set(n,e.has(n)?null:t.id);return new Map([...e].filter(([,e])=>null!==e))})(),sa=Object.freeze({epsilon:1e-4,forkCap:256}),ia=(e,t)=>{if(!e)throw new Error(`insight engine: ${t}`)},aa=e=>Object.keys(e).sort().map(t=>`${t}=${!0===e[t]?"t":e[t]}`).join(","),oa=(e,t)=>{let n=0;for(const r of Object.keys(e))if(Object.hasOwn(t,r)){if(e[r]!==t[r]){const s=!0===e[r]?1:e[r],i=!0===t[r]?1:t[r];n+=Math.abs(s-i)}}else n+=1;for(const r of Object.keys(t))Object.hasOwn(e,r)||(n+=1);return n},da=e=>Object.freeze({p:e.p,affs:Object.freeze({...e.affs})}),la=e=>({p:e.p,affs:{...e.affs}}),ca=e=>{const t=e.reduce((e,t)=>e+t.p,0);if(ia(t>0,"cannot normalize a belief with zero total mass"),Math.abs(t-1)>1e-12)for(const n of e)n.p/=t;return e},fa=Object.freeze([]),ua=(e,t,{contradiction:n=!1}={})=>{ia(Array.isArray(e)&&e.length>0,"finalizeForks needs at least one fork");const r=t?.growth??sa;let s=(e=>{const t=new Map;for(const n of e){const e=aa(n.affs),r=t.get(e);r?r.p+=n.p:t.set(e,{p:n.p,affs:n.affs,encoding:e})}return[...t.values()]})(e);s=ca(s);const{forks:i,capDiagnostic:a}=((e,t)=>{if(t<=0||e.length<=t)return{forks:e,capDiagnostic:null};const n=[...e].sort((e,t)=>t.p-e.p||(e.encoding<t.encoding?-1:1)).slice(0,t);return{forks:ca(n),capDiagnostic:{type:"forkCapExceeded",beforeCount:e.length,afterCount:n.length,forkCap:t}}})(s,r.forkCap??sa.forkCap);return s=((e,t)=>{if(t<=0||e.length<2)return e;const n=e.filter(e=>e.p>=t);if(0===n.length||n.length===e.length)return e;for(const r of e){if(r.p>=t)continue;let e=null,s=1/0;for(const t of n){const n=oa(r.affs,t.affs);(n<s||n===s&&(t.p>e.p||t.p===e.p&&t.encoding<e.encoding))&&(e=t,s=n)}e.p+=r.p}return n})(i,r.epsilon??sa.epsilon),s.sort((e,t)=>e.encoding<t.encoding?-1:e.encoding>t.encoding?1:0),!0===t?.guards?Object.freeze({forks:Object.freeze(s.map(da)),contradiction:n,diagnostics:a?Object.freeze([Object.freeze(a)]):fa}):{forks:s.map(la),contradiction:n,diagnostics:a?[a]:fa}},pa=e=>!1===e.contradiction&&0===e.diagnostics.length,ha=(e,t)=>!0===t?.guards?Object.freeze({forks:Object.freeze(e.forks.map(da)),contradiction:!0,diagnostics:e.diagnostics}):{forks:e.forks,contradiction:!0,diagnostics:e.diagnostics},ma=({guards:e=!1}={})=>{const t={forks:[{p:1,affs:{}}],contradiction:!1,diagnostics:fa};return e?Object.freeze({...t,forks:Object.freeze(t.forks.map(da))}):t},ga=e=>"countable"!==e.kind||1,ba=(e,t)=>{const n=e.affById.get(t);return ia(n,`unknown affliction '${t}'`),n},ya=Object.freeze(["uniform","firstMissing","ordered"]),va=new Set,ka=(e,t,n,r=va)=>{let s=((e,t)=>{let n=e;for(const r of t.layers){const e=r.find(e=>n.includes(e));e&&(n=n.filter(t=>!r.includes(t)||t===e))}for(const r of t.curedLast)n.includes(r.affId)&&r.pool.some(e=>n.includes(e))&&(n=n.filter(e=>e!==r.affId));return n})(Object.keys(e),n.cureMasks);if(t.ordered){const e=t.order.find(e=>s.includes(e));s=s.filter(n=>!t.order.includes(n)||n===e)}return t.order.filter(e=>s.includes(e)&&!r.has(e))},wa=(e,t,n)=>{const r=ba(n,t),s={...e};if("countable"===r.kind){const e=s[t]-1;e<=r.min?delete s[t]:s[t]=e}else delete s[t];if(r.curesTo){const e=ba(n,r.curesTo);s[e.id]=ga(e)}return s},Ia=Object.freeze(["=","!=","<","<=",">",">="]),za=(e,t,n)=>{switch(t){case"=":return e===n;case"!=":return e!==n;case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:return ia(!1,`unknown comparison operator '${t}'`),!1}},_a=Object.freeze({afflicted:(e,t,n)=>{const r=ba(n,t.affId),s="countable"!==r.kind||r.max;return pa(e)&&e.forks.every(e=>e.affs[r.id]===s)?e:ua(e.forks.map(e=>{const t={...e.affs};if("countable"===r.kind){const e=t[r.id]??r.min;t[r.id]=Math.min(e+1,r.max)}else t[r.id]=!0;return{p:e.p,affs:t}}),n)},afflictedOneOf:(e,t,n)=>{const{pool:r,mode:s}=t;ia(Array.isArray(r)&&r.length>0,"afflictedOneOf needs a non-empty pool"),ia(ya.includes(s),`unknown afflictedOneOf mode '${s}'`);const i=new Map(r.map(e=>[e,ba(n,e)]));if(pa(e)&&e.forks.every(e=>r.every(t=>Object.hasOwn(e.affs,t))))return e;const a=[];for(const o of e.forks){if("uniform"===s){const e=o.p/r.length;for(const t of r){const n={...o.affs};Object.hasOwn(n,t)||(n[t]=ga(i.get(t))),a.push({p:e,affs:n})}continue}const e=r.filter(e=>!Object.hasOwn(o.affs,e));if(0===e.length){a.push({p:o.p,affs:o.affs});continue}if("ordered"===s){const t=e[0];a.push({p:o.p,affs:{...o.affs,[t]:ga(i.get(t))}});continue}const t=o.p/e.length;for(const n of e)a.push({p:t,affs:{...o.affs,[n]:ga(i.get(n))}})}return ua(a,n)},advanced:(e,t,n)=>{ia(Array.isArray(t.rungs)&&t.rungs.length>0,"advanced needs rungs");const r=new Set,s=new Map;for(const o of t.rungs){ia(o&&"string"==typeof o.affId,"advanced rungs need an affId"),ia(!r.has(o.affId),`advanced has duplicate rung '${o.affId}'`),r.add(o.affId),s.set(o.affId,ba(n,o.affId));for(const e of[...o.gains??[],...o.consumes??[]])s.set(e,ba(n,e))}let i=!1;const a=e.forks.map(e=>{let n=-1;for(let s=0;s<t.rungs.length;s+=1)Object.hasOwn(e.affs,t.rungs[s].affId)&&(n=s);const r=t.rungs.slice(0,Math.max(0,n)),a=r.some(({affId:t})=>Object.hasOwn(e.affs,t)),o=n===t.rungs.length-1;if(o&&!a)return{p:e.p,affs:e.affs};const d={...e.affs};for(const{affId:t}of r)delete d[t];if(!o){n>=0&&delete d[t.rungs[n].affId];const e=t.rungs[n+1];d[e.affId]=ga(s.get(e.affId));for(const t of e.gains??[])d[t]=ga(s.get(t));for(const t of e.consumes??[])delete d[t]}return i=!0,{p:e.p,affs:d}});return!i&&pa(e)?e:ua(a,n)},cured:(e,t,n)=>{const r=((e,t)=>{const n=e.cureById.get(t);return ia(n,`unknown cure '${t}'`),n})(n,t.cureId);if(0===r.order.length)return e;const s=new Set(t.excludedAffs??[]),i=[];let a=!1;for(const o of e.forks){const e=ka(o.affs,r,n,s);if(0===e.length)continue;a=!0;const t=o.p/e.length;for(const r of e)i.push({p:t,affs:wa(o.affs,r,n)})}return a?ua(i,n):e},confirmed:(e,t,n)=>{const r=ba(n,t.affId),{present:s}=t,i=e.forks.filter(e=>Object.hasOwn(e.affs,t.affId)===s);return i.length===e.forks.length&&pa(e)?e:i.length>0?ua(i.map(e=>({p:e.p,affs:e.affs})),n):ua(e.forks.map(e=>{const t={...e.affs};return s?t[r.id]=ga(r):delete t[r.id],{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedBlocked:(e,t,n)=>{const r=ba(n,t.blockerId),{pool:s}=t;ia(Array.isArray(s)&&s.length>0,"confirmedBlocked needs a non-empty pool");for(const a of s)ba(n,a);const i=e.forks.filter(e=>Object.hasOwn(e.affs,r.id)||!s.some(t=>Object.hasOwn(e.affs,t)));return i.length===e.forks.length&&pa(e)?e:i.length>0?ua(i.map(e=>({p:e.p,affs:e.affs})),n):ua(e.forks.map(e=>({p:e.p,affs:{...e.affs,[r.id]:e.affs[r.id]??ga(r)}})),n,{contradiction:!0})},confirmedCount:(e,t,n)=>{const{pool:r,op:s,n:i}=t;ia(Array.isArray(r)&&r.length>0,"confirmedCount needs a non-empty pool"),ia(Number.isInteger(i)&&i>=0,"confirmedCount needs an integer n >= 0");for(const l of r)ba(n,l);const a=e.forks.filter(e=>za((e=>r.reduce((t,n)=>t+(Object.hasOwn(e.affs,n)?1:0),0))(e),s,i));if(a.length===e.forks.length&&pa(e))return e;if(a.length>0)return ua(a.map(e=>({p:e.p,affs:e.affs})),n);let o=-1;for(let l=0;l<=r.length;l+=1)if(za(l,s,i)){if(-1!==o)return ha(e,n);o=l}if(0!==o&&o!==r.length)return ha(e,n);const d=0===o;return ua(e.forks.map(e=>{const t={...e.affs};for(const s of r)d?delete t[s]:Object.hasOwn(t,s)||(t[s]=ga(ba(n,s)));return{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedCounts:(e,t,n)=>{const{counts:r}=t;ia(Array.isArray(r)&&r.length>0,"confirmedCounts needs count entries");for(const i of r){ia(i&&"object"==typeof i,"confirmedCounts needs count objects"),ia(Array.isArray(i.pool)&&i.pool.length>0,"confirmedCounts needs non-empty pools"),ia(Number.isInteger(i.n)&&i.n>=0,"confirmedCounts needs integer counts >= 0");for(const e of i.pool)ba(n,e)}const s=e.forks.filter(e=>r.every(t=>((e,t)=>t.pool.reduce((t,n)=>t+(Object.hasOwn(e.affs,n)?1:0),0)===t.n)(e,t)));return s.length===e.forks.length&&pa(e)?e:s.length>0?ua(s.map(e=>({p:e.p,affs:e.affs})),n):ua([{p:1,affs:{}}],n,{contradiction:!0})},confirmedLevel:(e,t,n)=>{const{affId:r,op:s,n:i}=t,a=ba(n,r);ia("countable"===a.kind,`confirmedLevel needs a countable aff, got '${r}'`),ia(Number.isInteger(i)&&i>=0,"confirmedLevel needs an integer n >= 0");const o=e.forks.filter(e=>za((e=>Object.hasOwn(e.affs,r)?e.affs[r]:0)(e),s,i));if(o.length===e.forks.length&&pa(e))return e;if(o.length>0)return ua(o.map(e=>({p:e.p,affs:e.affs})),n);const d=((e,t)=>{switch(e){case"=":case"<=":case">=":return t;case"<":return t-1;case">":return t+1;default:return null}})(s,i);return null===d||d<0||d>a.max||!za(d,s,i)?ha(e,n):ua(e.forks.map(e=>{const t={...e.affs};return 0===d?delete t[r]:t[r]=d,{p:e.p,affs:t}}),n,{contradiction:!0})},converted:(e,t,n)=>{const r=ba(n,t.from),s=ba(n,t.to);return e.forks.some(e=>Object.hasOwn(e.affs,r.id))?ua(e.forks.map(e=>{if(!Object.hasOwn(e.affs,r.id))return{p:e.p,affs:e.affs};const t={...e.affs},n=t[r.id];if(delete t[r.id],"countable"===s.kind){const e=!0===n?1:n;t[s.id]=Math.min(Math.max(e,1),s.max)}else t[s.id]=!0;return{p:e.p,affs:t}}),n):e},removed:(e,t,n)=>{const r=ba(n,t.affId);return pa(e)&&!e.forks.some(e=>Object.hasOwn(e.affs,r.id))?e:ua(e.forks.map(e=>{if(!Object.hasOwn(e.affs,r.id))return{p:e.p,affs:e.affs};const t={...e.affs};return delete t[r.id],{p:e.p,affs:t}}),n)},predictedCure:(e,t,n)=>{const{forkBranches:r}=t;if(ia(Array.isArray(r),"predictedCure needs a forkBranches array"),0===r.length)return e;const s=new Map;for(const a of r)ia(Number.isInteger(a?.forkIndex)&&a.forkIndex>=0&&a.forkIndex<e.forks.length,`predictedCure fork index '${a?.forkIndex}' is out of range`),ia(!s.has(a.forkIndex),`predictedCure addresses fork ${a.forkIndex} twice`),ia(Array.isArray(a.options)&&a.options.length>0,`predictedCure fork ${a.forkIndex} needs at least one option`),s.set(a.forkIndex,a.options);const i=[];return e.forks.forEach((e,t)=>{const r=s.get(t);if(!r)return void i.push({p:e.p,affs:e.affs});let a=0;for(const n of r)ia("number"==typeof n.weight&&Number.isFinite(n.weight)&&n.weight>0,`predictedCure option weight for '${n.affId}' must be a positive number`),ia(Object.hasOwn(e.affs,n.affId),`predictedCure option '${n.affId}' is absent from fork ${t}`),a+=n.weight;for(const s of r)i.push({p:e.p*(s.weight/a),affs:wa(e.affs,s.affId,n)})}),ua(i,n)}}),Oa=(Object.freeze(Object.keys(_a)),(e,t)=>Object.hasOwn(e.affs,t)),$a=e=>{ia(Array.isArray(e)&&e.length>0,"affliction projection needs a non-empty pool");const t=new Set;for(const n of e)ia("string"==typeof n&&n.length>0,"affliction pool ids must be non-empty strings"),ia(!t.has(n),`affliction pool contains duplicate '${n}'`),t.add(n)},Sa=(e,t)=>t.reduce((t,n)=>t+(Oa(e,n)?1:0),0),Ma=(e,t)=>{let n=0;for(const r of e.forks)Oa(r,t)&&(n+=r.p);return n},xa=(e,t)=>{let n=!1,r=!1;for(const s of e.forks)if(Oa(s,t)?n=!0:r=!0,n&&r)return null;return n},ja=(e,t)=>{$a(t);let n=0;for(const r of e.forks)t.some(e=>Oa(r,e))&&(n+=r.p);return n},Na=(e,t)=>{$a(t);let n=0;for(const r of e.forks)t.every(e=>Oa(r,e))&&(n+=r.p);return n},Aa=(e,t)=>{$a(t);let n=0;for(const r of e.forks)n+=r.p*Sa(r,t);return n},Ta=(e,t)=>{let n=0,r=0;for(const s of e.forks)if(Oa(s,t)){const e=!0===s.affs[t]?1:s.affs[t];n+=s.p,r+=e*s.p}return 0===n?0:r/n},Ea=e=>{let t=0;for(const n of e.forks)n.p>0&&(t-=n.p*Math.log2(n.p));return t},Ca=Object.freeze(["healthy","damaged","mangled"]),Pa=(e,t)=>{if(!e)throw new Error(`insight domain: ${t}`)},Da=Object.freeze(["best","worst","distribution"]),Ra=["focus","herb","smoke","salve","restoration","sip","tree","balance","equilibrium"],Za=new WeakMap,La=(e,t,n=1)=>{const r=e.priorityByAff.get(t);if(!r)return null;const s=r.get(n);if(void 0!==s)return s;let i=null,a=null;for(const o of r.keys())o<=n&&(null===i||o>i)&&(i=o),(null===a||o<a)&&(a=o);return r.get(i??a)},Ba=(e,t)=>t.some(t=>Array.isArray(t)?t.every(t=>Object.hasOwn(e,t)):Object.hasOwn(e,t)),Fa=(e,t,n)=>{const{tables:r,opponentClass:s,isBalanceReady:i}=n,a=new Map;if(!((e,t)=>!e.professions||null!==t&&e.professions.includes(t))(t,s)||!t.bals_req.every(i)||Ba(e,t.blocks))return[];for(const o of ka(e,t,r)){const n=La(r,o,!0===e[o]?1:e[o]);null===n||n<1||n>25||a.set(o,{affId:o,prio:n,cureId:t.id,balsUsed:t.bals_used})}return[...a.values()]},qa=e=>e.reduce((e,t)=>t.prio<e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),Ga=e=>e.reduce((e,t)=>t.prio>e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),Ja=(e,t,n,r)=>{Pa(Da.includes(n),`unknown predictive policy '${n}'`);const s=[],i=new Set;return e.forks.forEach((e,a)=>{const o=((e,t,n)=>{const r=n.context.curesByChannel.get(t);if(!r)return[];const s=new Map;for(const i of r)for(const t of Fa(e,i,n)){const e=s.get(t.affId);(!e||t.cureId<e.cureId)&&s.set(t.affId,t)}return[...s.values()]})(e.affs,t,r);if(0===o.length)return;let d;d="best"===n?[{...qa(o),weight:1}]:"worst"===n?[{...Ga(o),weight:1}]:(e=>{const t=[...e].sort((e,t)=>e.prio-t.prio||(e.affId<t.affId?-1:1));let n=0,r=null;return t.map(e=>(e.prio!==r&&(n+=1,r=e.prio),{...e,weight:1/n}))})(o);for(const t of d)for(const e of t.balsUsed)i.add(e);s.push({forkIndex:a,options:d.map(({affId:e,weight:t})=>({affId:e,weight:t}))})}),0===s.length?null:{event:{type:"predictedCure",forkBranches:s},consumed:i}},Ua=(Object.freeze(["pendingStrip","blocked","applying"]),na.get("occultist").unnamable),Ha=Object.freeze([...Ua]),Va=Ha.length,Wa=e=>(Pa(Number.isInteger(e)&&e>=0&&e<=Va,`unnamable curse count must be an integer in [0, ${Va}] (got ${e})`),[{type:"confirmedCount",pool:[...Ha],op:0===e?"=":"<=",n:Va-e},...Array.from({length:e},()=>({type:"afflictedOneOf",pool:[...Ha],mode:"firstMissing"}))]),Ya=new Map([["unnamable",()=>Wa(0)]]),Ka="whisperingmadness",Qa="focus",Xa=({belief:e,balance:t,usedAtMs:n})=>{const r=(({belief:e,balance:t,affId:n})=>{if(null!==xa(e,n))return null;const r=Ma(e,n);Pa(r>0&&r<1,"structurally uncertain affliction needs interior probability");const s=new Map;for(const d of t.extendedBy){if(d.affId===n)continue;const t=xa(e,d.affId);if(null===t)return null;s.set(d.affId,t)}const i=e=>((e,t)=>e.extendedBy.find(e=>t(e.affId))??e)(t,t=>t===n?e:!0===s.get(t)).predictiveDurationMs,a=i(!0),o=i(!1);return a===o?null:{probabilityAtUse:r,durationIfPresentMs:a,durationIfAbsentMs:o}})({belief:e,balance:t,affId:Ka});if(!r)return null;const s=Math.min(r.durationIfPresentMs,r.durationIfAbsentMs),i=Math.max(r.durationIfPresentMs,r.durationIfAbsentMs),a=s-500,o=s+500,d=i-500,l=i+500;if(o>d)return null;const c=n+d;return{affId:Ka,...r,usedAtMs:n,probeAtMs:n+s,resolveAbsenceAtMs:c,settleSilenceAtMs:c+1,presentIfFocusObserved:r.durationIfPresentMs<r.durationIfAbsentMs,earlyMs:s,lateMs:i,earlyWindowStartMs:a,earlyWindowEndMs:o,lateWindowStartMs:d,lateWindowEndMs:l}},eo=Object.freeze({stalenessHalfLifeMs:6e4,entropyScaleBits:Math.log2(sa.forkCap)}),to=(e,t={})=>{const n=t.stalenessHalfLifeMs??eo.stalenessHalfLifeMs,r=t.entropyScaleBits??(void 0===(s=t.forkCap)?eo.entropyScaleBits:Math.max(1,Math.log2(s)));var s;const i=Math.min(1,Ea(e.belief)/r),a=Math.max(0,e.now-e.lastObservedAt);return 1-(1-i)*(1-a/(a+n))},no=(e,t={})=>Object.freeze({affId:e,...t.gains?{gains:Object.freeze(t.gains)}:{},...t.consumes?{consumes:Object.freeze(t.consumes)}:{}}),ro=Object.freeze({head:Object.freeze([no("damagedhead",{gains:["stupidity"]}),no("mangledhead",{gains:["stuttering","clumsiness"]})]),torso:Object.freeze([no("mildtrauma"),no("serioustrauma")]),leftarm:Object.freeze([no("damagedleftarm",{consumes:["brokenleftarm"]}),no("mangledleftarm")]),rightarm:Object.freeze([no("damagedrightarm",{consumes:["brokenrightarm"]}),no("mangledrightarm")]),leftleg:Object.freeze([no("damagedleftleg",{consumes:["brokenleftleg"]}),no("mangledleftleg")]),rightleg:Object.freeze([no("damagedrightleg",{consumes:["brokenrightleg"]}),no("mangledrightleg")])}),so=Object.freeze(Object.keys(ro)),io=Object.freeze(new Map(Object.entries(ro).flatMap(([e,t])=>t.map(t=>[t.affId,e])))),ao=e=>{const t=ro[e];return Pa(t,`unknown limb '${e}'`),t},oo=(e,t)=>((e,t)=>{ia(Array.isArray(t)&&2===t.length,"ladder projection needs two rungs");const n={healthy:0,damaged:0,mangled:0};for(const s of e.forks){let e=-1;for(let n=0;n<t.length;n+=1)Oa(s,t[n].affId)&&(e=n);n[Ca[e+1]]+=s.p}const r=n.healthy+n.damaged+n.mangled;return 1!==r&&(n.healthy/=r,n.damaged/=r,n.mangled/=r),n})(e,ao(t)),lo=Object.freeze(["observed","simulated"]),co=so,fo=Object.freeze(["hp","mana"]),uo=Object.freeze({policy:"distribution",predictionEnabled:!1,focusEnabled:!0,limbResetMs:18e4}),po=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))po(e[t])}return e},ho=e=>{const t={};for(const[n,r]of[...e].sort(([e],[t])=>e<t?-1:e>t?1:0))t[n]=r;return t},mo=(e,t,n={})=>{Pa("string"==typeof e&&e.length>0,"createOpponentModel needs an id"),Pa(t?.affById&&t?.cureById&&t?.cureMasks,"createOpponentModel needs engine tables (affById, cureById, cureMasks)"),Pa(t?.balanceById&&t?.priorityByAff,"createOpponentModel needs domain tables (balanceById, priorityByAff)"),Pa(t?.defenceById&&t?.defenceDefaults,"createOpponentModel needs defence tables (defenceById, defenceDefaults)");const r={...uo,...n};Pa(Da.includes(r.policy),`unknown predictive policy '${r.policy}'`);const s=!0===r.guards,i=(e=>{const t=Za.get(e);if(t)return t;const n=new Map;for(const i of e.cureById.values()){if(0===i.bals_used.length||0===i.order.length)continue;const e=i.bals_used[0];n.has(e)||n.set(e,[]),n.get(e).push(i)}const r=Object.freeze([...Ra.filter(e=>n.has(e)),...[...n.keys()].filter(e=>!Ra.includes(e)).sort()]),s=Object.freeze({curesByChannel:n,channelOrder:r});return Za.set(e,s),s})(t);let a=ma({guards:s}),o=0,d=0,l="observed",c=r.policy,f=!0===r.predictionEnabled,u=null;const p=new Map([...t.balanceById.keys()].map(e=>[e,0])),h=new Map([...t.balanceById.keys()].map(e=>[e,0]));let m=null;const g=new Map,b=new Set,y=[];let v=0;const k=new Map(co.map(e=>[e,{percent:0,lastHitAt:null}])),w=new Map;let I={shadowInstill:null,timeloop:{count:0,max:3}};const z=new Set;let _=!1,O=null,$=0,S=0;const M=()=>{_||($+=1),_=!0,O=null},x=()=>{d!==o&&(d=o,S+=1)},j=()=>{if(_&&(_=!1,z.size>0)){const e=ie();for(const t of[...z])t(e)}},N=(({tables:e,getNow:t,isBlocked:n,onChange:r})=>{Pa(e?.defenceById&&e?.defenceDefaults,"defence state needs defence tables"),Pa("function"==typeof t,"defence state needs a clock read"),Pa("function"==typeof n,"defence state needs a blocker predicate"),Pa("function"==typeof r,"defence state needs a change callback");const s=new Map,i=new Map,a=t=>{Pa("string"==typeof t&&t.length>0,"defence operation needs a def id");const n=e.defenceById.get(t);return Pa(n,`unknown defence '${t}'`),n},o=(e,n,i=t())=>{const a={have:!0===n,atMs:i};var o,d;o=s.get(e),d=a,(o?.have!==d.have||o?.atMs!==d.atMs)&&(s.set(e,a),r())},d=(e,t)=>{var n,s;n=i.get(e),s=t,(n?.phase!==s.phase||n?.stripAt!==s.stripAt||n?.restoreAt!==s.restoreAt||n?.stripConfirmed!==s.stripConfirmed)&&(i.set(e,t),r())},l=e=>{i.delete(e)&&r()},c=e=>e.applyDelayMs-e.conservativeLeadMs,f=(e,r,s,i)=>{n(r.blockedBy)?d(e,{phase:"blocked",stripAt:s,restoreAt:null,stripConfirmed:i}):d(e,{phase:"applying",stripAt:s,restoreAt:t()+c(r),stripConfirmed:i})},u=()=>{s.clear(),i.clear();for(const n of Object.keys(e.defenceDefaults))s.set(n,{have:!0,atMs:t()})};return u(),Object.freeze({have:e=>(a(e),!0===s.get(e)?.have),confirm(e,t){a(e),Pa("boolean"==typeof t,"defence confirmation needs a boolean"),o(e,t),l(e)},raise(e){a(e),o(e,!0),l(e)},strip(e){const n=a(e),r=s.get(e),d=i.get(e);!1===r?.have&&!0===d?.stripConfirmed||(o(e,!1),n.restore?f(e,n.restore,t(),!0):l(e))},startStrip(e){const n=a(e);Pa(n.restore?.stripDelayMs,`defence '${e}' has no delayed-strip policy`);const r=t()+n.restore.stripDelayMs;o(e,!1),d(e,{phase:"pendingStrip",stripAt:r,restoreAt:r+c(n.restore),stripConfirmed:!1})},maintain(){for(const[r,s]of i){if("blocked"!==s.phase)continue;const i=e.defenceById.get(r).restore;n(i.blockedBy)||d(r,{...s,phase:"applying",restoreAt:t()+c(i)})}},fireDue(n,r){const s=[...i.entries()].filter(([,e])=>"pendingStrip"===e.phase&&e.stripAt<=t()).sort((e,t)=>e[1].stripAt-t[1].stripAt||(e[0]<t[0]?-1:1));for(const[t,i]of s){const r=e.defenceById.get(t).restore;f(t,r,i.stripAt,!1),n.push({atMs:i.stripAt,defId:t})}const a=[...i.entries()].filter(([,e])=>"applying"===e.phase&&e.restoreAt<=t()).sort((e,t)=>e[1].restoreAt-t[1].restoreAt||(e[0]<t[0]?-1:1));for(const[e,t]of a)o(e,!0,t.restoreAt),l(e),r.push({atMs:t.restoreAt,defId:e})},nextInstantWithin(e){let n=1/0;for(const r of i.values()){const s="pendingStrip"===r.phase?r.stripAt:"applying"===r.phase?r.restoreAt:null;"number"==typeof s&&s>t()&&s<=e&&s<n&&(n=s)}return n},snapshotEntries:()=>[...s.entries()].map(([e,t])=>{const n=i.get(e);return[e,{...t,phase:n?.phase??null,stripAt:n?.stripAt??null,restoreAt:n?.restoreAt??null}]}),reset:u})})({tables:t,getNow:()=>o,isBlocked:e=>((e,t)=>e.forks.every(e=>Ba(e.affs,t)))(a,e),onChange:M}),A=e=>{const n=t.balanceById.get(e);return Pa(n,`unknown balance '${e}'`),n},T=(e,t)=>{p.get(e)!==t&&(p.set(e,t),M())},E=(e,t)=>{h.get(e)!==t&&(h.set(e,t),M())},C=(e,t)=>{const n=A(e);if(0===n.extendedBy.length)return n;const[r,...s]=((e,t)=>{$a(t);const n=new Array(t.length+1).fill(0);for(const r of e.forks){let e=-1;for(let n=0;n<t.length;n+=1)if(Oa(r,t[n])){e=n;break}n[e+1]+=r.p}return n})(t,n.extendedBy.map(e=>e.affId));return r>0?n:n.extendedBy.filter((e,t)=>s[t]>0).reduce((e,t)=>t.predictiveDurationMs<e.predictiveDurationMs?t:e)},P=(e,t,n)=>{const r=C(e,t);T(e,o+(n??r.predictiveDurationMs)),E(e,o+(n??r.observedDurationMs))},D=(e,t)=>{T(e,o+C(e,t).predictiveDurationMs)},R=t.cureById.get("focus"),Z=t.balanceById.get(Qa);Pa(R&&Z,"focus timing needs canonical focus cure and balance rows");const L=()=>{null!==m&&(m=null,M())},B=()=>{if("observed"!==l||!0!==r.focusEnabled||!1!==xa(a,"aeon")||!((e,t)=>e.forks.every(e=>!Ba(e.affs,t.blocks)))(a,R))return!1;const e=e=>"focus"===e||(p.get(e)??1/0)<=o;return a.forks.every(n=>Fa(n.affs,R,{tables:t,opponentClass:u,isBalanceReady:e}).length>0)},F=()=>{!m||null===xa(a,"whisperingmadness")&&B()||L()},q=(e,t)=>{L();const n={type:"confirmed",affId:e.affId,present:t.present},r=H(n);return((e,t)=>{T(Qa,e.usedAtMs+t);const n=[Z,...Z.extendedBy].find(e=>e.predictiveDurationMs===t);n&&E(Qa,e.usedAtMs+n.observedDurationMs)})(e,t.resolvedDurationMs),{event:n,result:r}},G=e=>{if(!m)return;if(F(),!m)return;const t=m,n=((e,t)=>{Pa(e?.affId===Ka,"focus timing classification needs an episode");const n=t-e.usedAtMs,r=n>=e.earlyWindowStartMs&&n<=e.earlyWindowEndMs;if(r===(n>=e.lateWindowStartMs&&n<=e.lateWindowEndMs))return{type:"cancelled"};const s=r?e.earlyMs:e.lateMs;return{type:"confirmed",present:s===e.durationIfPresentMs,resolvedDurationMs:s}})(t,o);if("confirmed"!==n.type)return void L();const{result:r}=q(t,n);e.push(...r.diagnostics)},J=e=>{const t=oe(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,M())},U=new Set(["cured","removed","converted","confirmed"]),H=e=>{const n=a,r=((e,t,n)=>{ia(e&&Array.isArray(e.forks),"apply needs a Belief"),ia(t&&"string"==typeof t.type,"apply needs an event with a type"),ia(n?.affById&&n?.cureById&&n?.cureMasks,"apply needs tables");const r=_a[t.type];ia(r,`unknown event type '${t.type}'`);const s=r(e,t,n);return 0===s.diagnostics.length?s:!0===n.guards?Object.freeze({forks:s.forks,contradiction:s.contradiction,diagnostics:Object.freeze(s.diagnostics.map(e=>e.eventType?e:Object.freeze({...e,eventType:t.type})))}):{forks:s.forks,contradiction:s.contradiction,diagnostics:s.diagnostics.map(e=>e.eventType?e:{...e,eventType:t.type})}})(a,e,t);return r!==a&&(a=r,((e,n,r)=>{if(!U.has(r.type))return;if("confirmed"===r.type&&!1!==r.present)return;let s=!1;for(const t of k.values())if(0!==t.percent||null!==t.lastHitAt){s=!0;break}if(s){if("removed"===r.type||"converted"===r.type||"confirmed"===r.type){const t="converted"===r.type?r.from:r.affId;if(t){const r=io.get(t);if(r){const s=Ma(e,t);s>0&&Ma(n,t)<s&&J(r)}}return}if("cured"===r.type){const s=t.cureById.get(r.cureId);if(!s||!s.order)return;for(const t of s.order){const r=io.get(t);if(r){const s=Ma(e,t);s>0&&Ma(n,t)<s&&J(r)}}}}})(n,r,e),N.maintain(),M()),r},V=(e,t)=>{g.get(e)!==t&&(g.set(e,t),M())},W=e=>{b.delete(e),g.delete(e)&&M()},Y=(e,n)=>{const r=t.affById.get(e);"timed"===r?.kind&&V(e,o+(n??r.durationMs))},K=(e,n)=>{const r=t.affById.get(e);if("timed"===r?.kind){const t=o+(n??r.durationMs),s=g.get(e);V(e,void 0===s?t:Math.max(s,t))}},Q=()=>{for(const e of[...g.keys()])0===Ma(a,e)&&W(e)},X=(e,t)=>{const n=[...g.entries()].filter(([,e])=>e<=o).sort((e,t)=>e[1]-t[1]||(e[0]<t[0]?-1:1));for(const[r,s]of n){const n=Ya.get(r),i=void 0!==n&&"observed"===l&&b.has(r)&&1===Ma(a,r);if(W(r),Ma(a,r)>0){const n=H({type:"removed",affId:r});t.push(...n.diagnostics),e.push({affId:r,atMs:s}),F()}if(i)for(const e of n()){const n=H(e);t.push(...n.diagnostics),n.contradiction&&t.push({type:"contradiction",event:e})}}},ee=(e,t)=>{const n=y.filter(({atMs:e})=>e<=o).sort((e,t)=>e.atMs-t.atMs||e.sequence-t.sequence);for(const r of n){y.splice(y.indexOf(r),1),M();const n=H(r.event);t.push(...n.diagnostics),Q(),F(),e.push({atMs:r.atMs,cureId:r.event.cureId})}},te=(e,n)=>{if(!f)return;const r=e=>(p.get(e)??1/0)<=o;let s=!0;for(;s;){s=!1;for(const d of i.channelOrder){const l=p.get(d);if(void 0===l||l>o)continue;const f=Ja(a,d,c,{tables:t,context:i,opponentClass:u,isBalanceReady:r});if(!f)continue;const h=a,m=H(f.event);n.push(...m.diagnostics),"focus"===d&&L();for(const e of f.consumed)D(e,h);e.push({atMs:o,channelId:d,policy:c,event:f.event,consumed:[...f.consumed].sort()}),F(),s=!0}}Q()},ne=(e,t)=>{if(!m)return;if(F(),!m)return;const n=m,r=((e,t)=>t<e.settleSilenceAtMs?null:{type:"confirmed",present:e.durationIfPresentMs===e.lateMs,resolvedDurationMs:e.lateMs})(n,o);if(!r)return;const{event:s,result:i}=q(n,r);t.push(...i.diagnostics),i.contradiction&&t.push({type:"contradiction",event:s}),e.push({atMs:o,event:s})},re=(e,t)=>{let n=1/0;for(const[,r]of g)r>o&&r<=e&&r<n&&(n=r);for(const{atMs:r}of y)r>o&&r<=e&&r<n&&(n=r);const s=N.nextInstantWithin(e);s<n&&(n=s);for(const i of k.values()){const t=null===i.lastHitAt?null:i.lastHitAt+r.limbResetMs;null!==t&&t>o&&t<=e&&t<n&&(n=t)}if(t)for(const r of i.channelOrder){const t=p.get(r);void 0!==t&&t>o&&t<=e&&t<n&&(n=t)}return m&&m.settleSilenceAtMs>o&&m.settleSilenceAtMs<=e&&m.settleSilenceAtMs<n&&(n=m.settleSilenceAtMs),n},se=()=>{const e=(e=>{const t={};for(const n of e.forks)for(const e of Object.keys(n.affs))t[e]=(t[e]??0)+n.p;return t})(a),n={};for(const s of Object.keys(e).sort())n[s]="countable"===t.affById.get(s)?.kind?{probability:e[s],count:Ta(a,s)}:{probability:e[s]};const r={};for(const t of co)r[t]={percent:k.get(t).percent,stages:oo(a,t)};return{mode:l,policy:c,predictionEnabled:f,class:u,entropy:Ea(a),forkCount:a.forks.length,affs:n,expiries:ho(g.entries()),pendingCures:y.slice().sort((e,t)=>e.atMs-t.atMs||e.sequence-t.sequence).map(({atMs:e,event:t})=>({atMs:e,cureId:t.cureId,excludedAffs:[...t.excludedAffs]})),limbs:r,stats:ho([...w.entries()].map(([e,t])=>[e,{...t}])),defs:ho(N.snapshotEntries()),skillState:s?JSON.parse(JSON.stringify(I)):I}},ie=()=>{null===O&&(O=s?po(se()):se());const n=O,i={};for(const[e,t]of[...p.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0))i[e]={readyAtMs:t,remainingMs:Math.max(0,t-o)};const a={id:e,mode:n.mode,policy:n.policy,predictionEnabled:n.predictionEnabled,class:n.class,now:o,lastObservedAt:d,staleness:to(de,{stalenessHalfLifeMs:r.stalenessHalfLifeMs,forkCap:t.growth?.forkCap}),entropy:n.entropy,forkCount:n.forkCount,affs:n.affs,balances:i,expiries:n.expiries,pendingCures:n.pendingCures,limbs:n.limbs,stats:n.stats,defs:n.defs,skillState:n.skillState};return s?po(a):a},ae=(e,t,n)=>{switch(t){case"=":return e===n;case"!=":return e!==n;case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:Pa(!1,`unknown balance remaining comparison '${t}'`)}},oe=e=>{const t=k.get(e);return Pa(t,`unknown limb '${e}'`),t},de={id:e,get revision(){return $},get timeEpoch(){return S},get now(){return o},get mode(){return l},get policy(){return c},get class(){return u},get lastObservedAt(){return d},get belief(){return a},isPredictionEnabled:()=>f,isBalanceReady:e=>(A(e),(p.get(e)??0)<=o),isObservationBalanceReady:e=>(A(e),(h.get(e)??0)<=o),balanceRemainingProbability:(e,{op:n,ms:r,affIds:s=[]})=>{A(e),Pa("number"==typeof r&&Number.isFinite(r)&&r>=0,"balance remaining probability needs a non-negative finite ms"),Pa(Array.isArray(s),"balance remaining probability affIds must be an array");const i=new Set;for(const a of s)Pa(t.affById.has(a),`unknown affliction '${a}'`),Pa(!i.has(a),`balance remaining probability repeats '${a}'`),i.add(a);let d=0;for(const t of a.forks){if(!s.every(e=>Object.hasOwn(t.affs,e)))continue;let i=p.get(e)??0;if("focus"===e&&m){const e=Object.hasOwn(t.affs,m.affId)?m.durationIfPresentMs:m.durationIfAbsentMs;i=m.usedAtMs+e}ae(Math.max(0,i-o),n,r)&&(d+=t.p)}return d},getBalanceTimingInference:e=>(A(e),"focus"===e&&m?m:null),haveDef:N.have,getStat:e=>{Pa(fo.includes(e),`unknown stat '${e}'`);const t=w.get(e);return t?{...t}:null},limbPercent:e=>oe(e).percent,limbStages:e=>(oe(e),oo(a,e)),getSkillState:()=>s?po(JSON.parse(JSON.stringify(I))):I,nextInterestingAt({prediction:e=f,includeDue:t=!1}={}){if(t&&e)for(const r of i.channelOrder){const e=p.get(r);if(void 0!==e&&e<=o)return o}const n=re(1/0,e);return Number.isFinite(n)?n:null},apply:e=>{Pa(e&&"string"==typeof e.type,"apply needs an event with a type"),Pa("elapsed"!==e.type&&"predictedCure"!==e.type,`'${e.type}' is not an observation — it is produced by the simulation itself`);const n="cured"===e.type?t.cureById.get(e.cureId):null,r=void 0!==n?.delayMs,i=[];let d=!1;"cured"===e.type&&"focus"===e.cureId?G(i):m&&((e,t)=>"cured"===e.type?!0===t?.order.includes(Ka):"afflictedOneOf"===e.type?e.pool.includes(Ka):"converted"===e.type?"whisperingmadness"===e.from||"whisperingmadness"===e.to:["afflicted","removed","confirmed"].includes(e.type)&&"whisperingmadness"===e.affId)(e,n)&&L();const l=a,c=r?{contradiction:!1,diagnostics:[]}:H(e);switch(d||=c.contradiction,i.push(...c.diagnostics),e.type){case"afflicted":Y(e.affId,e.durationMs),f=e.affId,Ya.has(f)&&g.has(f)&&1===Ma(a,f)&&b.add(f);break;case"afflictedOneOf":for(const t of e.pool)K(t,e.durationMs);break;case"confirmed":e.present&&(e=>{const n=t.affById.get(e);"timed"!==n?.kind||g.has(e)||V(e,o+n.durationMs)})(e.affId);break;case"converted":W(e.from),Y(e.to);break;case"cured":if(n){for(const e of n.bals_used)P(e,l);r&&((e,t)=>{y.push({atMs:o+t,sequence:v,event:{type:"cured",cureId:e.cureId,excludedAffs:[...e.excludedAffs??[]]}}),v+=1,M()})(e,n.delayMs),"focus"===n.id&&(e=>{if(!B())return;const t=Xa({belief:e,balance:Z,usedAtMs:o});t&&(m=s?po(t):t,M())})(l)}}var f;return Q(),F(),x(),j(),{contradiction:d,diagnostics:i}},elapsed:e=>{Pa("number"==typeof e&&Number.isFinite(e)&&e>=0,"elapsed needs a non-negative dtMs");const t=o+e;e>0&&(S+=1);const n=[],s=[],i=[],a=[],d=[],l=[],c=[];for(;;){X(n,c),ee(s,c),N.fireDue(i,a),te(d,c),ne(l,c);const e=re(t,f);if(!Number.isFinite(e))break;o=e}o=t;for(const f of k.values())null!==f.lastHitAt&&o-f.lastHitAt>=r.limbResetMs&&(f.percent=0,f.lastHitAt=null,M());return j(),{expired:n,resolvedCures:s,resolvedDefenceStrips:i,restoredDefs:a,predicted:d,timingConfirmations:l,diagnostics:c}},snapshot:ie,onChange:e=>(Pa("function"==typeof e,"onChange needs a function"),z.add(e),()=>z.delete(e)),setMode(e){Pa(lo.includes(e),`unknown observation mode '${e}'`),l!==e&&(l=e,M()),"simulated"===e&&(b.clear(),L()),"observed"===e&&x(),j()},setPolicy(e){Pa(Da.includes(e),`unknown predictive policy '${e}'`),c!==e&&(c=e,M()),j()},enablePrediction(){f||(f=!0,M()),j()},disablePrediction(){f&&(f=!1,M()),j()},setClass(e,{source:t="observed"}={}){if("directory"===t&&null!==u)return;const n="string"==typeof e&&e.trim()?e.trim().toLowerCase():null;u!==n&&(u=n,M()),j()},consumeBalance(e,t){A(e),P(e,a,t),j()},setStat(e,t){Pa(fo.includes(e),`unknown stat '${e}'`),Pa("number"==typeof t&&Number.isFinite(t),"setStat needs a number");const n=w.get(e);n&&n.value===t&&n.atMs===o||(w.set(e,{value:t,atMs:o}),M()),j()},confirmDef(e,t){N.confirm(e,t),j()},raiseDef(e){N.raise(e),j()},stripDef(e){N.strip(e),j()},startDefStrip(e){N.startStrip(e),j()},hitLimb(e,t){Pa("number"==typeof t&&Number.isFinite(t)&&t>=0,"hitLimb needs a non-negative percent");const n=oe(e),r=n.percent+t>=100,s=r?0:n.percent+t,i=r?null:o;return n.percent===s&&n.lastHitAt===i||(n.percent=s,n.lastHitAt=i,M()),j(),{advanced:r,percent:s}},resetLimb(e){const t=oe(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,M()),j()},updateSkillState(e){Pa(e&&"object"==typeof e,"updateSkillState needs a patch object");for(const[t,n]of Object.entries(e)){const e=I[t];null===n||"object"!=typeof n||Array.isArray(n)||null===e||"object"!=typeof e||Array.isArray(e)?e!==n&&(I[t]=n,M()):Object.entries(n).some(([t,n])=>e[t]!==n)&&(I[t]={...e,...n},M())}j()},reset(){a=ma({guards:s}),g.clear(),b.clear(),y.length=0,L();for(const e of p.keys())p.set(e,o),h.set(e,o);for(const e of k.values())e.percent=0,e.lastHitAt=null;w.clear(),N.reset(),I={shadowInstill:null,timeloop:{count:0,max:3}},M(),j()}};return Object.freeze(de)},go=/^[A-Za-z]+$/,bo=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&go.test(t)?t.toLowerCase():null},yo=(e={})=>{const{tables:t,...n}=e;Pa(t,"createRosterModel needs config.tables");const r=!0===n.guards,s=new Map,i=new Map;let a=null,o=0;const d=new Set,l=new Set,c=()=>{if(o+=1,0===d.size)return;const e={ids:[...s.keys()],targetId:a};r&&(Object.freeze(e.ids),Object.freeze(e));for(const t of[...d])t(e)},f=e=>{let r=s.get(e);return r||(r=mo(e,t,n),s.set(e,r),i.set(e,r.onChange(t=>{o+=1,((e,t)=>{for(const n of[...l])n(e,t)})(e,t)})),c()),r},u={track(e){const t=bo(e);if(!t)return null;const n=f(t);return n.setMode("observed"),n},untrack(e){const t=bo(e),n=t?s.get(t):null;return!!n&&(n.setMode("simulated"),!0)},setTarget(e){if(null===e)return null!==a&&(a=null,c()),null;const t=bo(e);if(!t)return null;const n=f(t);return a!==t&&(a=t,c()),n},get targetId(){return a},get revision(){return o},getTarget:()=>a?s.get(a)??null:null,get(e){const t=bo(e);return t?s.get(t)??null:null},list:()=>[...s.keys()],listObserved(){const e=[];for(const[t,n]of s)"observed"===n.mode&&e.push(t);return e},remove(e){const t=bo(e);return!(!t||!s.has(t))&&(i.get(t)(),i.delete(t),s.delete(t),a===t&&(a=null),c(),!0)},updateDefaults(e={}){const{policy:t,predictionEnabled:r}=e;void 0!==t&&(Pa(Da.includes(t),`unknown predictive policy '${t}'`),n.policy=t),void 0!==r&&(n.predictionEnabled=!0===r);for(const n of s.values())void 0!==t&&n.setPolicy(t),void 0!==r&&(!0===r?n.enablePrediction():n.disablePrediction())},reset(e){const t=u.get(e);return!!t&&(t.reset(),!0)},resetAll(){for(const e of s.values())e.reset()},elapsed(e){const t={};for(const[n,r]of s)t[n]=r.elapsed(e);return t},snapshot(){const e={};for(const t of[...s.keys()].sort())e[t]=s.get(t).snapshot();return r?Object.freeze({targetId:a,opponents:Object.freeze(e)}):{targetId:a,opponents:e}},onChange:e=>(Pa("function"==typeof e,"onChange needs a function"),d.add(e),()=>d.delete(e)),onOpponentChange:e=>(Pa("function"==typeof e,"onOpponentChange needs a function"),l.add(e),()=>l.delete(e))};return Object.freeze(u)},vo=Object.freeze({lovers:/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/,shadowmadness:/^Lucidity returns to the eyes of (\w+)\.$/,whisperingmadness:/^(\w+) ceases \w+ violent trembling\.$/}),ko=Object.freeze([Object.freeze({id:"asthma-blocks-smoke",blockerId:"asthma",balanceId:"smoke",pool:Object.freeze([...ea].sort()),evidence:/^\w+ takes a long drag off \w+ pipe\.$/}),Object.freeze({id:"anorexia-blocks-herb",blockerId:"anorexia",balanceId:"herb",pool:Object.freeze([...Xi].sort()),evidence:/^\w+ eats a.+\.$/})]),wo=Object.freeze([Object.freeze({id:"fulminate-paralysis-on-focus",cureId:"focus",affId:"fulminated",absentAffId:"paralysis",evidence:/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/})]),Io=na.get("depthswalker"),zo=[{skill:"aeonics",id:"timeloop",handler:(e,t)=>[{type:"afflicted",affId:"timeloop"},{type:"updateSkillState",patch:{timeloop:{max:t.checkBlock("You have now aged yourself")?4:3,count:0}}}]},{skill:"aeonics",id:"timeloopProc",handler:(e,t,n)=>{const r=[],s=Io[n.skillState.shadowInstill];s&&r.push({type:"afflictedOneOf",pool:[...s],mode:"ordered"});const{count:i=0,max:a=3}=n.skillState.timeloop??{},o=i+1;return o>=a?r.push({type:"removed",affId:"timeloop"},{type:"updateSkillState",patch:{timeloop:{count:0}}}):r.push({type:"updateSkillState",patch:{timeloop:{count:o}}}),r}},{skill:"aeonics",id:"accelerate",handler:(e,t)=>{const n={type:"cured",cureId:"accelerate"};return t.nextLine("grows older before your eyes.")?[n,{...n}]:[n]}}],_o={dissipate:[{type:"statChanged",statId:"mana",delta:-.15}],palpitation:[{type:"statChanged",statId:"hp",delta:-.15}],heat:[{type:"afflicted",affId:"burning"}],creeps:[{type:"afflicted",affId:"agoraphobia"},{type:"afflicted",affId:"claustrophobia"}],oscillate:[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"epilepsy"}],disorientation:[{type:"afflicted",affId:"prone"},{type:"afflicted",affId:"dizziness"}],dissonance:[{type:"defStripped",defId:"shield"}],plague:[{type:"afflicted",affId:"brokenrightarm"},{type:"afflicted",affId:"brokenrightleg"},{type:"afflicted",affId:"brokenleftleg"}],lullaby:[{type:"defStripped",defId:"insomnia"}],retardation:[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]};_o.plauge=_o.plague;var Oo={disorientation:[{type:"afflicted",affId:"dizziness"}],creeps:[{type:"afflicted",affId:"shyness"}],dissonance:[{type:"afflicted",affId:"dissonance"}]},$o=e=>(e.args.info??"").toLowerCase(),So=[{skill:"crystalism",id:"destabilise",handler:e=>(_o[$o(e)]??[]).map(e=>({...e}))},{skill:"crystalism",id:"vibeTick",handler:e=>(Oo[$o(e)]??[]).map(e=>({...e}))}],Mo=e=>(t,n,r)=>"thirdPerson"===t.matchType?e(t,n,r):[],xo=(e,t)=>t.some(t=>e.have(t)),jo={body:e=>e.have("anorexia")?[{type:"cured",cureId:"epidermal to body"}]:xo(e,["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso"])?[{type:"cured",cureId:"restoration to torso"}]:[{type:"cured",cureId:"mending to body"}],head:e=>xo(e,["damagedhead","mangledhead","calcifiedskull"])?[{type:"cured",cureId:"restoration to head"}]:e.have("stuttering")?[{type:"cured",cureId:"epidermal to head"}]:e.have("unblind")||e.have("undeaf")?[{type:"afflicted",affId:"undeaf"}]:[],arms:e=>xo(e,["damagedleftarm","damagedrightarm","mangledleftarm","mangledrightarm"])?[{type:"cured",cureId:"restoration to arms"}]:[{type:"cured",cureId:"mending to arms"}],legs:e=>xo(e,["damagedleftleg","damagedrightleg","mangledleftleg","mangledrightleg"])?[{type:"cured",cureId:"restoration to legs"}]:[{type:"cured",cureId:"mending to legs"}],skin:e=>xo(e,["frozen","shivering","frostbite"])?[{type:"cured",cureId:"caloric"}]:[{type:"defRaised",defId:"insulation"}]};jo.torso=jo.body;var No=[{skill:"curing",id:"apply",handler:Mo((e,t,n)=>{const r=(e.args.info??"").toLowerCase();return jo[r]?jo[r](n):[]})},{skill:"curing",id:"health",handler:Mo(e=>{const t=`health to ${(e.args.info??"").toLowerCase()}`;return Ji.has(t)?[{type:"cured",cureId:t}]:[]})},{skill:"curing",id:"smoke",handler:Mo((e,t,n)=>xo(n,["aeon","deadening","tension","unweavingspirit"])?[{type:"cured",cureId:"cinnabar"}]:xo(n,["disloyalty","hellsight","manaleech","slickness"])?[{type:"cured",cureId:"realgar"}]:[])},{skill:"curing",id:"focus",handler:Mo(()=>[{type:"cured",cureId:"focus"}])},{skill:"tattoos",id:"tree",handler:Mo(()=>[{type:"cured",cureId:"tree"}])},{skill:"tattoos",id:"shield",handler:Mo(()=>[{type:"defRaised",defId:"shield"}])},{skill:"defense",id:"prismatic",handler:Mo(()=>[{type:"defRaised",defId:"prismatic"}])},{skill:"venom",id:"shrugging",handler:Mo(()=>[{type:"cured",cureId:"shrugging"}])}],Ao=Object.freeze({agoraphobia:/^(\w+) is gripped with fear, staring out with terrified eyes\.$/,claustrophobia:/^(\w+) begins to pant in terror\.$/,confusion:/^(\w+) looks about bemusedly\.$/,dementia:/^(\w+) stares about \w+ frenziedly, wild-eyed\.$/}),To=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!0}]}),Eo=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:t}]}),Co=[Eo("confusion","confusion",Ao.confusion),Eo("dementia","dementia",Ao.dementia),Eo("paralysis1","paralysis",/^Horror overcomes the face of (\w+?) as \w+ body locks in paralysis\.$/),Eo("paralysis2","paralysis",/^Horror overcomes (\w+)'s face as \w+ body stiffens into paralysis\.$/),Eo("hypersomnia","hypersomnia",/^(\w+) suddenly appears tired all of a sudden\.$/),Eo("impatience","impatience",/^(\w+) shuffles \w+ feet in boredom\.$/),To("agoraphobia","agoraphobia",Ao.agoraphobia),To("claustrophobia","claustrophobia",Ao.claustrophobia),To("darkshade","darkshade",/^(\w+) lets out a piercing scream, as if wounded by the very sunlight\.$/),To("epilepsy","epilepsy",/^(\w+) begins to jerk and shake violently, foaming at the mouth\.$/),{id:"affConfirms.hallucinations",pattern:/^(\w+) leaps up in what is apparently an attempt at a graceful swan dive\. \w+ smacks headfirst into the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"hallucinations",present:!0},{type:"afflicted",affId:"prone"}]},To("masochism1","masochism",/^(\w+) smiles as \w+ rams \w+ fist into \w+ jaw\.$/),To("masochism2","masochism",/^(\w+) uses \w+ right foot to stomp on \w+ left as hard as possible\.$/),To("masochism3","masochism",/^With the heel of \w+ palm, (\w+) smacks \w+ upside the head\.$/),To("nausea","nausea",/^(\w+) doubles over, vomiting violently\.$/),To("shyness","shyness",/^(\w+) trembles with fear\.$/),{id:"affConfirms.sleep",pattern:/^(\w+)'s eyes close suddenly as \w+ falls asleep\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"}]},To("shivering","shivering",/^(\w+) shivers particularly intensely\.$/),To("burning","burning",/^The fires consuming (\w+) diminish somewhat\.$/)],Po=na.get("occultist"),Do=/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/,Ro=["brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg"],Zo=["asthma","slickness"],Lo=Po.chimera.filter(e=>"hallucinations"!==e),Bo=(e,t)=>{for(let n=Math.max(0,e.currentLineIndex+1);n<e.lines.length;n+=1){const r=e.lines[n];if(r.isPrompt)break;if(!r.isHtml&&null!==r.text)for(const e of Lo)if(bo(Ao[e].exec(r.text)?.[1])===t)return e}return"hallucinations"},Fo=e=>{const t=e.queuedCommand("c!p!w!t"),n=t?t.match(/COMMAND FIRELORD AT \w+ (\w+)/):null;return n?n[1].toLowerCase():null},qo=[{skill:"domination",id:"humbugCommand",handler:()=>[{type:"afflicted",affId:"addiction"}]},{skill:"domination",id:"houndCommand",handler:()=>[{type:"afflicted",affId:"weariness"}]},{skill:"domination",id:"stormCommand",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"domination",id:"stormCommand2",handler:()=>[{type:"confirmed",affId:"clumsiness",present:!0}]},{skill:"domination",id:"bloodleechCommand",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"domination",id:"sycophantCommand",handler:()=>[{type:"afflicted",affId:"weakenedmind"}]},{skill:"domination",id:"slimeCommand",handler:(e,t)=>[{type:"afflicted",affId:"slimeobscure"},{type:"confirmed",affId:"asthma",present:t.checkBlock(Do)}]},{skill:"domination",id:"chimeraCommandDeaf",handler:()=>[{type:"confirmed",affId:"undeaf",present:!1}]},{skill:"domination",id:"chimeraCommand",handler:(e,t,n)=>[{type:"confirmed",affId:"undeaf",present:!0},{type:"afflicted",affId:Bo(t,n.id)}]},{skill:"domination",id:"bubonisCommand",handler:(e,t,n)=>n.haveDef("fangbarrier")?t.nextLine("The protective coating covering the skin of")?[{type:"confirmed",affId:"asthma",present:!0},{type:"afflicted",affId:"slickness"}]:[{type:"afflicted",affId:"asthma"}]:[{type:"afflictedOneOf",pool:[...Zo],mode:"ordered"}]},{skill:"domination",id:"wormCommand",handler:()=>[{type:"afflicted",affId:"palpatarfeed"}]},{skill:"domination",id:"wormTick",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"domination",id:"croneCommand",handler:()=>[{type:"afflictedOneOf",pool:[...Ro],mode:"firstMissing"}]},{skill:"domination",id:"cronePrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...Ro],mode:"firstMissing"}]},{skill:"domination",id:"abominationCommandFail",handler:()=>[{type:"removed",affId:"cleanseaura"}]},{skill:"domination",id:"gremlinCommand",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"domination",id:"gremlinCommandFail",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"domination",id:"firelordCommand",handler:(e,t)=>{const n=Fo(t);return"manaleech"===n?[{type:"confirmed",affId:"manaleech",present:!0},{type:"removed",affId:"manaleech"},{type:"afflicted",affId:"anorexia"}]:"healthleech"===n?[{type:"confirmed",affId:"healthleech",present:!0}]:"whisperingmadness"===n?[{type:"confirmed",affId:"whisperingmadness",present:!0},{type:"removed",affId:"whisperingmadness"},{type:"afflicted",affId:"recklessness"}]:[]}},{skill:"domination",id:"firelordCommandFail",handler:(e,t)=>{const n=Fo(t);return n?[{type:"confirmed",affId:n,present:!1}]:[]}},{skill:"domination",id:"wormPrimebond",handler:()=>[{type:"afflicted",affId:"nausea"}]},{skill:"domination",id:"gremlinPrimebond",handler:()=>[{type:"afflicted",affId:"dizziness"}]},{skill:"domination",id:"gremlinPrimebond2",handler:()=>[{type:"confirmed",affId:"dizziness",present:!0}]},{skill:"domination",id:"humbugPrimebond",handler:(e,t,n)=>{const r=n.probability("addiction")>.49?-.1:-.05;return[{type:"statChanged",statId:"hp",delta:r},{type:"statChanged",statId:"mana",delta:r}]}},{skill:"domination",id:"bubonisPrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...Po.bubonis],mode:"firstMissing"}]},{skill:"domination",id:"chimeraPrimebondGas",handler:()=>[{type:"defStripped",defId:"insomnia"}]},{skill:"domination",id:"chimeraPrimebondRam",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"domination",id:"chimeraPrimebondRoar",handler:()=>[{type:"afflicted",affId:"undeaf"},{type:"afflicted",affId:"prone"}]},{skill:"domination",id:"chimeraPrimebondUndeaf",handler:()=>[{type:"afflicted",affId:"undeaf"}]}],Go=[{skill:"dragoncraft",id:"gust",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonroar",handler:(e,t)=>{if("thirdPerson"===e.matchType)return[{type:"afflicted",affId:"undeaf"}];const n=t.queuedCommand();return n&&/DRAGONROAR \w+/.test(n)?[{type:"afflicted",affId:"undeaf"}]:[]}},{skill:"dragoncraft",id:"rendTargeted",handler:(e,t,n)=>Jo(n)},{skill:"dragoncraft",id:"rendUntargeted",handler:(e,t,n)=>Jo(n)},{skill:"dragoncraft",id:"tailsweepHit",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonheal",handler:e=>"thirdPerson"===e.matchType?[{type:"cured",cureId:"dragonheal"}]:[]}],Jo=e=>{const t=e.skillState.envenom;if(!t)return[];const n=ta.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},Uo=e=>`broken${(e??"").replace(/\s/g,"").toLowerCase()}`,Ho=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],Vo=[{skill:"elementalism",id:"shalestormTick",handler:e=>[{type:"afflicted",affId:Uo(e.args.limb)}]},{skill:"elementalism",id:"shalestormRaze",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"elementalism",id:"firelash",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"firelashLOS",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"freeze",handler:(e,t,n)=>Ho(n)},{skill:"elementalism",id:"dehydrate",handler:()=>[{type:"afflicted",affId:"nausea"},{type:"afflicted",affId:"weariness"}]},{skill:"elementalism",id:"fulminate",handler:()=>[{type:"afflictedOneOf",pool:["fulminated","epilepsy","paralysis"],mode:"ordered"}]},{skill:"elementalism",id:"bombard",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"elementalism",id:"mudslide",handler:()=>[{type:"afflicted",affId:"slickness"},{type:"afflicted",affId:"prone"}]},{skill:"elementalism",id:"magma",handler:()=>[{type:"afflicted",affId:"scalded"}]},{skill:"elementalism",id:"emanationFire",handler:()=>[{type:"afflicted",affId:"burning"},{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"emanationAir",handler:()=>[{type:"afflicted",affId:"paralysis"},{type:"afflicted",affId:"dizziness"}]},{skill:"elementalism",id:"emanationEarth",handler:()=>[{type:"afflicted",affId:"calcifiedtorso"}]},{skill:"elementalism",id:"emanationWater",handler:(e,t,n)=>Ho(n)},{skill:"elementalism",id:"resonanceAirMinor",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"elementalism",id:"resonanceAirModerate",handler:(e,t,n)=>n.have("undeaf")?[{type:"afflicted",affId:"sensitivity"}]:[{type:"afflicted",affId:"undeaf"}]},{skill:"elementalism",id:"resonanceAirMajor",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"elementalism",id:"resonanceEarthMinor",handler:e=>[{type:"afflicted",affId:Uo(e.args.limb)}]},{skill:"elementalism",id:"resonanceEarthModerate",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"elementalism",id:"resonanceEarthMajor",handler:()=>[{type:"afflicted",affId:"crackedribs"}]},{skill:"elementalism",id:"resonanceFireMinor",handler:()=>[{type:"defStripped",defId:"temperence"}]},{skill:"elementalism",id:"resonanceFireModerate",handler:(e,t,n)=>n.have("scalded")?[{type:"afflicted",affId:"burning"}]:[{type:"afflicted",affId:"scalded"}]},{skill:"elementalism",id:"resonanceFireMajor",handler:(e,t,n)=>n.have("blistered")?[{type:"afflicted",affId:"burning"}]:[{type:"afflicted",affId:"blistered"}]},{skill:"elementalism",id:"resonanceWaterMinor",handler:()=>[{type:"afflicted",affId:"frostbite"}]},{skill:"elementalism",id:"resonanceWaterModerate",handler:()=>[{type:"afflicted",affId:"stuttering"}]},{skill:"elementalism",id:"resonanceWaterMajor",handler:()=>[{type:"afflicted",affId:"anorexia"}]}],Wo=na.get("occultist"),Yo=Object.freeze({cloak:"cloak",speed:"speed",caloric:"insulation",frost:"temperence",levitation:"levitating",insomnia:"insomnia",kola:"kola"}),Ko=/^pinchaura(?:\s|$)/i,Qo=/^pinchaura\s+([A-Za-z]+)\s+([A-Za-z]+)$/i,Xo=/^\[System\]: Running queued (.+?) command: (.+)/,ed=e=>[{type:"confirmedCounts",source:"readaura",counts:[{label:"physical",pool:[...Wo.physicals],n:e.args.physical},{label:"mental",pool:[...Wo.mentals],n:e.args.mental}]}],td=e=>{const t=[{type:"confirmedCount",pool:[...Wo.physicals,...Wo.mentals],op:e.args.met?">=":"<",n:5}];return e.args.met&&t.push({type:"afflicted",affId:"enlightenment"}),t},nd=[{skill:"occultism",id:"pinchaura",handler:(e,t,n)=>{if("firstPerson"!==e.matchType)return[];const r=bo(e.args.target);if(!r||r!==n.id)return[];const s=t.queuedCommand();if(!s||!((e,t)=>{const n=e.commands?.lastQueue;if("string"!=typeof n||!Number.isInteger(e.currentLineIndex)||e.currentLineIndex<=0)return!1;for(let r=0;r<e.currentLineIndex;r+=1){const s=e.lines[r];if(s?.isHtml||"string"!=typeof s?.text)continue;const i=Xo.exec(s.text);if(i?.[1]===n&&i[2]===t)return!0}return!1})(t,s))return[];const i=(e=>{if("string"!=typeof e)return null;const t=e.split("|").map(e=>e.trim()).filter(e=>Ko.test(e));if(1!==t.length)return null;const n=Qo.exec(t[0]);if(!n)return null;const r=Yo[n[2].toLowerCase()];return r?{targetId:bo(n[1]),defId:r}:null})(s);return i?.targetId&&i.targetId===r?[{type:"speed"===i.defId?"defStripStarted":"defStripped",defId:i.defId}]:[]}},{skill:"occultism",id:"ague",handler:(e,t,n)=>n.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}]},{skill:"occultism",id:"instill",handler:(e,t,n)=>{const r=[{type:"statChanged",statId:"hp",delta:-.03},{type:"statChanged",statId:"mana",delta:-.03}],s=e.args.affs?.[0];return"sensitivity"===s?r.push(n.have("undeaf")?{type:"afflicted",affId:"sensitivity"}:{type:"afflicted",affId:"undeaf"}):s&&r.push({type:"afflicted",affId:s}),r}},{skill:"occultism",id:"enervate",handler:()=>[{type:"statChanged",statId:"mana",delta:-.2}]},{skill:"occultism",id:"attend",handler:()=>[{type:"afflicted",affId:"undeaf"},{type:"afflicted",affId:"unblind"}]},{skill:"occultism",id:"shrivelTargeted",handler:e=>e.args.affs?.[0]?[{type:"afflicted",affId:e.args.affs[0]}]:[]},{skill:"occultism",id:"shrivelArms",handler:()=>[{type:"afflictedOneOf",pool:["brokenrightarm","brokenleftarm"],mode:"firstMissing"}]},{skill:"occultism",id:"shrivelLegs",handler:()=>[{type:"afflictedOneOf",pool:["brokenrightleg","brokenleftleg"],mode:"firstMissing"}]},{skill:"occultism",id:"shrivelRehit",handler:e=>{return"arm"===(t=(e.args.groups?.limb??"").replace(/\s/g,"").toLowerCase())?[{type:"confirmed",affId:"brokenleftarm",present:!0},{type:"confirmed",affId:"brokenrightarm",present:!0}]:"leg"===t?[{type:"confirmed",affId:"brokenleftleg",present:!0},{type:"confirmed",affId:"brokenrightleg",present:!0}]:[{type:"confirmed",affId:`broken${t}`,present:!0}];var t}},{skill:"occultism",id:"unnamableSpeak",handler:()=>[]},{skill:"occultism",id:"unnamableVision",handler:()=>[]},{skill:"occultism",id:"regress",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"occultism",id:"devolve",handler:()=>[{type:"afflicted",affId:"shyness"},{type:"afflicted",affId:"disloyalty"}]},{skill:"occultism",id:"whisperingmadness",handler:()=>[{type:"afflicted",affId:"whisperingmadness"}]},{skill:"occultism",id:"whisperingmadnessMiss",handler:()=>Wo.whisperingmadness.map(e=>({type:"removed",affId:e}))},{skill:"occultism",id:"cleanseaura",handler:(e,t)=>t.checkBlock("A look of sudden concern")?[{type:"afflicted",affId:"cleanseaura"}]:[{type:"removed",affId:"cleanseaura"}]}],rd=na.get("psion"),sd=(e,t)=>e.args[t]??e.args.match?.groups?.[t],id=[{skill:"psionics",id:"splinterHit",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"psionics",id:"splinterMiss",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"psionics",id:"expand",handler:()=>[{type:"statChanged",statId:"mana",delta:.15}]},{skill:"psionics",id:"combustion",handler:()=>[{type:"afflicted",affId:"bloodfire"}]},{skill:"psionics",id:"blastMiss",handler:()=>[{type:"confirmedCount",pool:[...rd.blast],op:"<",n:3}]},{skill:"weaving",id:"invert",handler:e=>{const t=sd(e,"old"),n=sd(e,"new");return t&&n?[{type:"converted",from:`unweaving${t}`,to:`unweaving${n}`}]:[]}}],ad=na.get("depthswalker"),od=["depression","retribution","shadowmadness","parasite"],dd=e=>()=>[{type:"afflictedOneOf",pool:[...e],mode:"ordered"}],ld=e=>()=>e.map(e=>({type:"confirmed",affId:e,present:!0})),cd=e=>{const t=e.skillState.envenom;if(!t)return[];const n=ta.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},fd=[{skill:"shadowmancy",id:"reap",handler:(e,t,n)=>t.checkBlock("you corrupt the weapon's timestream.")?[]:cd(n)},{skill:"shadowmancy",id:"cull",handler:(e,t,n)=>cd(n)},{skill:"shadowmancy",id:"degeneration",handler:dd(ad.degeneration)},{skill:"shadowmancy",id:"degenerationFull",handler:ld(ad.degeneration)},{skill:"shadowmancy",id:"depression",handler:dd(ad.depression)},{skill:"shadowmancy",id:"depressionFull",handler:()=>[...ld(ad.depression)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"}]},{skill:"shadowmancy",id:"retribution",handler:dd(ad.retribution)},{skill:"shadowmancy",id:"retributionFull",handler:(e,t,n)=>{const r=od.reduce((e,t)=>e+n.probability(t),0);return[...ld(ad.retribution)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"},{type:"statChanged",statId:"mana",delta:-.05*r}]}},{skill:"shadowmancy",id:"madness",handler:dd(ad.madness)},{skill:"shadowmancy",id:"madnessFull",handler:ld(ad.madness)},{skill:"shadowmancy",id:"leach",handler:dd(ad.leach)},{skill:"shadowmancy",id:"leachFull",handler:ld(ad.leach)},{skill:"shadowmancy",id:"consume",handler:()=>[{type:"statChanged",statId:"mana",delta:-.1}]},{skill:"shadowmancy",id:"mutilate",handler:()=>[{type:"statChanged",statId:"mana",delta:-.4},{type:"statChanged",statId:"hp",delta:-.4}]}],ud=na.get("occultist"),pd=ud.moon.filter(e=>"claustrophobia"!==e&&"agoraphobia"!==e),hd=[{skill:"tarot",id:"magician",handler:()=>[{type:"statChanged",statId:"mana",delta:.25}]},{skill:"tarot",id:"priestess",handler:()=>[{type:"statChanged",statId:"hp",delta:.25}]},{skill:"tarot",id:"lovers",handler:()=>[{type:"afflicted",affId:"lovers"}]},{skill:"tarot",id:"aeon",handler:()=>[{type:"defStripStarted",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{skill:"tarot",id:"aeonStrip",handler:()=>[{type:"defStripStarted",defId:"speed"}]},{skill:"tarot",id:"justice",handler:()=>[{type:"afflicted",affId:"justice"}]},{skill:"tarot",id:"deathRub",handler:(e,t,n)=>n.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflicted",affId:"shivering"}]},{skill:"tarot",id:"ruinateLovers",handler:()=>[{type:"afflicted",affId:"manaleech"}]},{skill:"tarot",id:"ruinateJustice",handler:(e,t)=>t.nextLine("violently spasms")?[]:ud.justice.map(e=>({type:"confirmed",affId:e,present:!1}))},{skill:"tarot",id:"moon",handler:(e,t)=>{const n=t.queuedCommand(),r=n?n.match(/FLING MOON AT \w+ (\w+)/):null;return r?[{type:"afflicted",affId:r[1].toLowerCase()}]:[{type:"afflictedOneOf",pool:[...pd],mode:"firstMissing"}]}}],md=/^(\w+) stumbles, falling to the ground\.$/,gd=[{skill:"weaving",id:"cleaveHit",handler:()=>[{type:"afflicted",affId:"prone"},{type:"defStripped",defId:"shield"}]},{skill:"weaving",id:"cleaveMiss",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"weaving",id:"overhand",handler:(e,t,n)=>n.have("prone")||n.limbPercent("head")>=87.6?[{type:"afflicted",affId:"impatience"}]:[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"prone"}]},{skill:"weaving",id:"hamstring",handler:(e,t)=>{const n=(e=>(e??"").replace(/\s/g,"").toLowerCase())(e.args.limb),r=[{type:"afflicted",affId:`broken${n}`}];return"thirdPerson"===e.matchType&&r.push(t.checkBlock(md)?{type:"limbAdvance",limbId:n}:{type:"limbHit",limbId:n,percent:22.1}),r}},{skill:"weaving",id:"entwineProne",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"weaving",id:"entwineEntangle",handler:()=>[{type:"afflicted",affId:"entangled"}]},{skill:"weaving",id:"puncture",handler:()=>[{type:"afflicted",affId:"weariness"}]},{skill:"weaving",id:"sever",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"weaving",id:"unweave",handler:e=>e.args.info?[{type:"afflicted",affId:`unweaving${e.args.info}`}]:[]},{skill:"weaving",id:"deathblow",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"weaving",id:"backhand",handler:()=>[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"dizziness"}]},{skill:"weaving",id:"exsanguinate",handler:()=>[{type:"afflicted",affId:"nausea"}]},{skill:"weaving",id:"disruption",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"weaving",id:"disruption2",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"weaving",id:"laceration",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"weaving",id:"laceration2",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"weaving",id:"dazzle",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"weaving",id:"rattle",handler:()=>[{type:"afflicted",affId:"epilepsy"}]},{skill:"weaving",id:"vapours",handler:()=>[{type:"afflicted",affId:"asthma"}]}],bd=e=>String(e).toLowerCase(),yd=(e,t)=>`${bd(e)}.${String(t).toLowerCase()}`,vd=Object.freeze([...zo,{skill:"artificing",id:"efreeti",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"artificing",id:"stoneback",handler:()=>[{type:"defRaised",defId:"shield"}]},...So,...No,...qo,...Go,...Vo,...nd,...id,...fd,...hd,...gd]),kd=(e,t,n)=>({id:`classCures.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:t}]}),wd=[kd("sunTarot","dagaz",/^The globe of light illuminates (\w+) with its brilliance\.$/),kd("runewardenSun","dagaz",/^A rune like a rising sun upon the ground flares, bathing (\w+) with healing magic\.$/),kd("genericMist","generic",/^(\w+) is surrounded in a cool, refreshing mist\.$/),kd("genericGlow","generic",/^A demonic crimson glow emanates from (\w+)\.$/),kd("genericLeech","generic",/^Something pulses from within the chest of (\w+), and \w+ seems more vital\.$/)],Id=(e,t,n)=>({id:`cureConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!1}]}),zd=[{id:"cureConfirms.stand",pattern:/^(\w+) stands up\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"stand"}]},Id("lovers","lovers",/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/),Id("whisperingmadness","whisperingmadness",/^(\w+) ceases \w+ violent trembling\.$/),{id:"cureConfirms.slimeLost",pattern:/^(\w+) finally rids \w+ of the slime covering \w+\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"slimeobscure"}]},Id("sileris","slickness",/^(\w+) applies a (?:quicksilver droplet|sileris berry) to \w+\.$/),Id("shadowmadness","shadowmadness",/^Lucidity returns to the eyes of (\w+)\.$/),Id("unweavingspirit","unweavingspirit",/^(\w+) seems suddenly unburdened, clarity reasserting itself upon \w+ features\.$/),Id("unweavingmind","unweavingmind",/^The light behind the eyes of (\w+) reignites\.$/),Id("unweavingbody","unweavingbody",/^(\w+) suddenly seems much more vital\.$/),Id("bloodfire","bloodfire",/^The unnatural flames that burn upon the skin of (\w+) wink out\.$/)],_d=(e,t)=>({id:`curatives.${e}`,pattern:t,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:e}]}),Od=[_d("antimony",/^(\w+) eats (?:a ginger root|an antimony flake)\.$/),_d("argentum",/^(\w+) eats (?:a lobelia seed|an argentum flake)\.$/),_d("arsenic",/^(\w+) eats (?:some bayberry bark|an arsenic pellet)\.$/),_d("aurum",/^(\w+) eats (?:a piece of kelp|an aurum flake)\.$/),_d("cuprum",/^(\w+) eats a (?:bellwort flower|cuprum flake)\.$/),_d("ferrum",/^(\w+) eats a (?:ginseng root|ferrum flake)\.$/),_d("magnesium",/^(\w+) eats a (?:bloodroot leaf|magnesium chip)\.$/),_d("plumbum",/^(\w+) eats a (?:goldenseal root|plumbum flake)\.$/),_d("stannum",/^(\w+) eats (?:some prickly ash bark|a stannum flake)\.$/),{id:"curatives.calamine",pattern:/^(\w+) eats a (?:hawthorn berry|calamine crystal)\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"undeaf"}]},{id:"curatives.potash",pattern:/^(\w+) eats (?:some irid moss|a potash crystal)\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"potash"},{type:"statChanged",statId:"hp",delta:.08},{type:"statChanged",statId:"mana",delta:.08}]},{id:"curatives.restore",pattern:/^(\w+) crackles with blue energy that wreathes itself about \w+ limbs\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"brokenrightarm"},{type:"removed",affId:"brokenrightleg"},{type:"removed",affId:"brokenleftarm"},{type:"removed",affId:"brokenleftleg"}]}],$d=(e,t,n)=>({id:`defences.${e}`,pattern:t,lifetime:"session",actor:1,handler:n}),Sd=[$d("shieldHit1",/^A dizzying beam of energy strikes you as your attack rebounds off of (\w+)'s shield\.$/,()=>[{type:"defRaised",defId:"shield"}]),$d("shieldHit2",/^The magical shield surrounding (\w+) makes that impossible\.$/,()=>[{type:"defRaised",defId:"shield"}]),$d("sileris",/^A supple purple shell of sileris berry juice has formed around (\w+)\.$/,()=>[{type:"defRaised",defId:"fangbarrier"}]),$d("silerisLost",/^The protective coating covering the skin of (\w+) sloughs off\.$/,()=>[{type:"afflicted",affId:"slickness"},{type:"defStripped",defId:"fangbarrier"}]),$d("insomnia",/^(\w+) clenches \w+ fists and grits \w+ teeth\.$/,()=>[{type:"defRaised",defId:"insomnia"},{type:"confirmed",affId:"hypersomnia",present:!1}]),$d("prismaticHit",/^Your attack is repelled by the prismatic barrier surrounding (\w+)\.$/,()=>[{type:"defRaised",defId:"prismatic"}]),$d("prismaticLost",/^(\w+)'s prismatic barrier dissolves into nothing\.$/,()=>[{type:"defStripped",defId:"prismatic"}]),$d("speedStripped",/^(\w+) suddenly seems less dexterous, \w+ reactions becoming noticeably slower\.$/,()=>[{type:"defStripped",defId:"speed"}])],Md=e=>(e??"").replace(/\s/g,"").toLowerCase(),xd=(e,t)=>Number(`${e}.${t}`),jd=[{id:"prep.limbDamage",pattern:/^As you carve into (\w+), you perceive that you have dealt (\d+)\.(\d+)% damage to \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbHit",limbId:Md(e[4]),percent:xd(e[2],e[3])}]},{id:"prep.limbDamage2",pattern:/^As your blow lands with a crunch, you perceive that you have dealt (\d+)\.(\d+)% damage to (\w+)'s (.+)\.$/,lifetime:"session",actor:3,handler:e=>[{type:"limbHit",limbId:Md(e[4]),percent:xd(e[1],e[2])}]},{id:"prep.interlinkDamage",pattern:/^As the immaterial cleaves the material, you perceive that you have dealt (\d+)\.(\d+)% damage to (\w+)'s (.+)\.$/,lifetime:"session",actor:3,handler:e=>[{type:"limbHit",limbId:Md(e[4]),percent:xd(e[1],e[2])}]},{id:"prep.limbReset",pattern:/^(\w+) ceases to favour \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbReset",limbId:Md(e[2])}]},{id:"prep.limbMangle",pattern:/^(\w+)'s ((?:left|right) (?:arm|leg)) has been beaten into uselessness\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbAdvance",limbId:Md(e[2])}]},{id:"prep.calcifiedskullResolve",pattern:/^A look of pain comes over (\w+) and the bones seem to shift beneath the skin stretched across \w+ skull\.$/,lifetime:"session",actor:1,handler:()=>[{type:"converted",from:"calcifiedskull",to:"damagedhead"}]}],Nd=[{defId:"insomnia",pattern:/^\w+ has insomnia, and cannot easily go to sleep\.$/},{defId:"speed",pattern:/^\w+ sense of time is heightened, and \w+ reactions are speeded\.$/},{defId:"kola",pattern:/^\w+ is feeling extremely energetic\.$/},{defId:"cloak",pattern:/^\w+ is surrounded by a cloak of protection\.$/},{defId:"insulation",pattern:/^\w+ is coated in an insulating unguent\.$/},{defId:"fangbarrier",pattern:/^\w+ is protected from the fangs of serpents\.$/},{defId:"rebounding",pattern:/^\w+ is protected from hand-held weapons with an aura of rebounding\.$/},{defId:"curseward",pattern:/^A curseward has been established about \w+ person\.$/},{defId:"selfishness",pattern:/^\w+ is feeling quite selfish\.$/},{defId:"shield",pattern:/^\w+ is surrounded by a nearly invisible magical shield\.$/}],Ad={id:"occultism.readaura",lifetime:"prompt",armedBy:{trigger:"skills.readauraStart"},initState:({actorId:e})=>({actorId:e,pendingDefs:Nd.map(({defId:e})=>e)}),captures:[...Nd.map(({defId:e,pattern:t})=>({id:`def.${e}`,pattern:t,actor:"armed",handler:(t,n,r,s)=>(s.pendingDefs=s.pendingDefs.filter(t=>t!==e),[{type:"defConfirmed",defId:e,have:!0}])})),{id:"deaf",pattern:/^\w+ is deaf\.$/,actor:"armed",handler:()=>[{type:"removed",affId:"undeaf"}]},{id:"blind",pattern:/^\w+ is blind\.$/,actor:"armed",handler:()=>[{type:"removed",affId:"unblind"}]},{id:"counts",pattern:/^You perceive that (\w+) suffers from (\d+) physical afflictions and (\d+) mental afflictions\.$/,actor:1,handler:(e,t,n)=>ed({args:{physical:Number(e[2]),mental:Number(e[3])}},t,n)},{id:"mana",pattern:/^You sense that the mana of (\w+) stands at (\d+) of a maximum (\d+)\.$/,actor:1,handler:(e,t,n,r)=>{const s=r.pendingDefs.map(e=>({type:"defConfirmed",defId:e,have:!1}));return r.pendingDefs=[],s.push({type:"statObserved",statId:"mana",value:Number(e[2])/Number(e[3])}),s}}]},Td=["paralysis","asthma","healthleech","haemophilia","sensitivity","clumsiness","weariness"],Ed={indigo:()=>[{type:"afflicted",affId:"stupidity"}],orange:()=>[{type:"afflicted",affId:"paralysis"}],violet:e=>e.haveDef("speed")?[{type:"defStripped",defId:"speed"}]:[{type:"afflicted",affId:"aeon"}]},Cd=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],Pd=[{id:"skills.earworm",pattern:/^Your rapier sings out with a high, piercing note\.$/,lifetime:"session",actor:null,handler:()=>[{type:"confirmed",affId:"earworm",present:!0}]},{id:"skills.commandMinionMiss",pattern:/^A minion of chaos thrusts a hand in the direction of (\w+), but nothing seems to happen\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"enlightenment",present:!1}]},{id:"skills.firelordPrimebond",pattern:/^(\w+) cries out in horror as \w+ body erupts into flames!$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"burning"}]},{id:"skills.rendVenom",pattern:/^You rub some (\w+) on your wickedly sharp claws\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{envenom:e[1].toLowerCase()}}]},{id:"skills.dragoncurseAff",pattern:/^You summon your ancient power and direct the curse of (\w+) to strike down (\w+) in (\d+) seconds\.$/,lifetime:"session",actor:2,handler:e=>[{type:"updateSkillState",patch:{dragoncurse:e[1].toLowerCase()}}]},{id:"skills.dragoncurseHit",pattern:/^(\w+) convulses under the influence of some invisible force\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>{const r=n.skillState.dragoncurse;if(!r)return[];const s=[{type:"updateSkillState",patch:{dragoncurse:null}}];return Gi.has(r)&&s.unshift({type:"afflicted",affId:r}),s}},{id:"skills.readauraStart",pattern:/^Studying the aura of (\w+), you look for traces of anything that may be protecting it\.$/,lifetime:"session",actor:1,handler:()=>[]},{id:"skills.whisperingmadnessTick",pattern:/^(\w+) trembles and \w+ eyes widen in terror\. \w+ looks around \w+ as if searching for something that isn't there\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"whisperingmadness",present:!0}]},{id:"skills.chaosrays",pattern:/^(\w+) is hit by a (.+) ray\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>e[2].replace(/ and /g,",").replace(/\s/g,"").replace(/,,/g,",").split(",").filter(Boolean).flatMap(e=>Ed[e]?.(n)??[])},{id:"skills.truename",pattern:/^Drawing back with a knowing smirk, you utter the truename of (\w+), who suddenly becomes very still and bleeds from \w+ eyes and ears\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{id:"skills.unnamableHits",pattern:/^(\w+) has been struck down by (\d) curses of the unnamable\.$/,lifetime:"session",actor:1,handler:e=>[{type:"removed",affId:"unnamable"},...Wa(Number(e[2]))]},{id:"skills.enlighten",pattern:/^You place both hands on either side of (\w+)'s head and stare straight into \w+ eyes\. Summoning all your knowledge of the occult mysteries, you will your knowledge into \w+'s mind\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>td({args:{met:t.nextLine("You see")}},t,n)},{id:"skills.enlightenYell",pattern:/^You see (.+) yell, "No, it cannot be true! I cannot accept it! I beg of you to make it stop!"$/,lifetime:"session",actor:1,handler:(e,t,n)=>td({args:{met:!0}},t,n)},{id:"skills.enlightenShout",pattern:/^You see (.+) shout, "No, it cannot be true! I cannot accept it! I beg of you to make it stop!"$/,lifetime:"session",actor:1,handler:(e,t,n)=>td({args:{met:!0}},t,n)},{id:"skills.regressAnorexia",pattern:/^The face of (\w+) turns a particularly vibrant shade of green\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"anorexia"},{type:"confirmed",affId:"prone",present:!0}]},{id:"skills.compelDiscord",pattern:/^(\w+) clutches at \w+ head as \w+ begins to mutter gibberish over and over under his breath\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"healthleech",present:!0},{type:"confirmed",affId:"asthma",present:!0},{type:"afflicted",affId:"loneliness"},{type:"afflicted",affId:"dizziness"}]},{id:"skills.compelEntropyAeon",pattern:/^(\w+) twists and writhes in the grip of an unnatural force, parts of \w+ body flickering as if seen through a veil of mist\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{id:"skills.compelPotentialLimbs",pattern:/^The body of (\w+) goes slack, \w+ eyes rolling almost completely back in \w+ head as \w+ face goes a ghostly white\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>["leftarm","leftleg","rightarm","rightleg"].flatMap(e=>{for(const t of["mangled","damaged","broken"])if(n.probability(`${t}${e}`)>.25)return[{type:"confirmed",affId:`${t}${e}`,present:!0}];return[]})},{id:"skills.compelPotentialFrozen",pattern:/^(\w+) twitches in the grip of some terrible power, skin splitting and cracking under its unforgiving grasp\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"shivering",present:!0},{type:"confirmed",affId:"frozen",present:!0},{type:"defStripped",defId:"insulation"}]},{id:"skills.shadowInstill",pattern:/^Focusing upon .+?, you instill it with the directive of (\w+)\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{shadowInstill:e[1].toLowerCase()}}]},{id:"skills.shadowEnvenom",pattern:/^You rub some (\w+) on .+?\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{envenom:e[1].toLowerCase()}}]},{id:"skills.attuneMadness",pattern:/^You sense that (\w+) has been struck down with the (\w+) madness\.$/,lifetime:"session",actor:1,handler:e=>{const t=e[2].toLowerCase(),n=Gi.has(t)?t:`${t}madness`;return Gi.has(n)?[{type:"afflicted",affId:n}]:[]}},{id:"skills.attuneDegeneration",pattern:/^You determine that (\w+) is suffering from (\w+)\.$/,lifetime:"session",actor:1,handler:e=>{const t=e[2].toLowerCase();return Gi.has(t)?[{type:"afflicted",affId:t}]:[]}},{id:"skills.shadowstrikeMiss",pattern:/^(\w+) is not surrounded by a magical shield\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"shield"}]},{id:"skills.ruinateJusticeBreak",pattern:/^An audible crack emanates from the bones in the (.+) of (\w+)\.$/,lifetime:"session",actor:2,handler:(e,t,n)=>{const r=(s=e[1],s.replace(/ and /g,",").replace(/,,/g,",").replace(/\s/g,"").split(",").filter(Boolean)).map(e=>({type:"afflicted",affId:`broken${e}`}));var s;return Td.reduce((e,t)=>e+n.probability(t),0)>=4&&(r.push(...Cd(n)),r.push({type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"})),r}},{id:"skills.ruinateJusticeProne",pattern:/^The broken legs of (\w+) give way, and \w+ collapses to the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"},{type:"confirmed",affId:"brokenleftleg",present:!0},{type:"confirmed",affId:"brokenrightleg",present:!0}]},{id:"skills.wheelAgue",pattern:/^Rays of cold blue light lash out from the Wheel of Chaos, irradiating the location\.$/,lifetime:"session",actor:"room",handler:(e,t,n)=>Cd(n)},{id:"skills.wheelStuttering",pattern:/^Vibrant indigo rays of light lash out from the Wheel of Chaos\.$/,lifetime:"session",actor:"room",handler:()=>[{type:"afflicted",affId:"stuttering"}]},{id:"skills.wheelBlackout",pattern:/^Rays of orange light lash out at the location from the Wheel of Chaos\.$/,lifetime:"session",actor:"room",handler:()=>[{type:"afflicted",affId:"blackout",durationMs:3e3}]},{id:"skills.stumbleProne",pattern:/^(\w+) stumbles, falling to the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"}]},{id:"skills.namedDefenceRemoved",pattern:/^(?:His|Her|Faen) (\w+) defence is eroded away\.$/,lifetime:"session",actor:null,handler:e=>{const t=e[1].toLowerCase();return Hi.has(t)?[{type:"defStripped",defId:t}]:[]}},{id:"skills.scintillaBurn",pattern:/^Flames ignite all over the body of (\w+), fanned to intensity in an instant\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"burning"}]},{id:"skills.conflagrateFail",pattern:/^You bend your will upon (\w+), attempting to rouse a conflagration to consume \w+, but to no avail\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmedLevel",affId:"burning",op:"<",n:2}]},{id:"skills.assess",pattern:/^You glance over (\w+) and see that \w+ health is at (\d+)\/(\d+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"statObserved",statId:"hp",value:Number(e[2])/Number(e[3])}]},{id:"skills.contemplate",pattern:/^(\w+)'s mana stands at (\d+)\/(\d+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"statObserved",statId:"mana",value:Number(e[2])/Number(e[3])}]}],Dd=/^(\w+) pales as the blood drains from \w+ face\.$/,Rd=(e,t,n)=>({id:e,lifetime:"prompt",armedBy:{skill:"occultism",id:t},initState:({observedIds:e})=>({exposed:[...e]}),captures:[{id:"pale",pattern:Dd,actor:1,handler:(e,t,r,s)=>(s.exposed=s.exposed.filter(e=>e!==r.id),[{type:"afflicted",affId:n},{type:"afflicted",affId:"unnamable"}])}],finalize:e=>e.exposed.map(e=>({id:e,type:"removed",affId:n}))}),Zd=Rd("occultism.unnamableSpeak","unnamableSpeak","undeaf"),Ld=Rd("occultism.unnamableVision","unnamableVision","unblind"),Bd=Object.freeze([...Od,...wd,...zd,...Co,...Sd,...Pd,...jd,{id:"queues.queueTracker",pattern:/^\[System\]: Running queued (.+?) command: (.+)/,lifetime:"session",remember:e=>({queue:{name:e[1],text:e[2]}})}]),Fd=Object.freeze([Zd,Ld,Ad]),qd=(e,t)=>t instanceof RegExp?t.test(e):"string"==typeof t&&e.includes(t),Gd=(e,t)=>{const n=[e?.target,e?.target?.id,e?.victim,e?.player,e?.player?.id,e?.user];for(const r of n)if("string"==typeof r&&""!==r&&"self"!==r.toLowerCase()){const e=bo(r);if(e&&e!==t)return e}return null},Jd=e=>"string"==typeof e?e:"string"==typeof e?.name?e.name:null,Ud=({adapter:e,publish:t,commandMemory:n=null,skills:r=null})=>{const s=[],i=new Map;let a=!1;const o=()=>bo(Jd(e.gmcp.read("Char.Name"))),d=(t=null)=>(({lines:e=[],currentLineIndex:t=-1,actorId:n=null,timestampMs:r=0,commands:s=null}={})=>{const i=Object.freeze(e.map(e=>Object.freeze({text:"string"==typeof e.text?e.text:null,isPrompt:!0===e.isPrompt,isHtml:!0===e.isHtml}))),a=Object.freeze({queues:Object.freeze({...s?.queues??{}}),lastQueue:s?.lastQueue??null});return Object.freeze({lines:i,currentLineIndex:t,actorId:n,timestampMs:r,commands:a,nextLine:e=>{for(let n=t+1;n<i.length;n+=1){const t=i[n];if(!t.isHtml&&!t.isPrompt&&null!==t.text)return qd(t.text,e)}return!1},checkBlock:e=>i.some(t=>null!==t.text&&qd(t.text,e)),queuedCommand:e=>{const t=e??a.lastQueue;return null===t?null:a.queues[t]??null}})})({...e.text.snapshot(),actorId:bo(t),timestampMs:e.clock.now(),commands:n?n.snapshot():null}),l=e=>{const n=bo(Jd(e));n&&n!==o()&&t("insight.ingress.room.entered",{id:n})},c=e=>{const n=(e=>{const{skill:t,id:n,matchType:r,match:s,...i}=e??{};return"string"!=typeof t||""===t||"string"!=typeof n||""===n?null:{skill:t,id:n,matchType:r??s,args:i}})(e);n&&"secondPerson"!==n.matchType&&t("insight.ingress.skill",{action:n,context:d(Gd(e,o()))})},f=t=>{if(a)for(const n of t){if("string"!=typeof n||""===n)continue;const t=bd(n);i.has(t)||i.set(t,e.events.onSkillMatch(c,t))}};return Object.freeze({start(){a=!0,r?f(r()):s.push(e.events.onSkillMatch(c)),s.push(e.events.on("nexskill.error.reaction",e=>{const n=e?.action,s="string"==typeof n?.skill&&""!==n.skill?bd(n.skill):null;r&&!i.has(s)||t("insight.ingress.skillError",{skill:s,id:"string"==typeof n?.id&&""!==n.id?n.id:null,line:"string"==typeof n?.originalLine?n.originalLine:null,message:e?.error?.message??String(e?.error)})})),s.push(e.events.on("IRE.Target.Set",e=>{"number"!=typeof e&&t("insight.ingress.target",{id:"string"==typeof e?e:null})})),s.push(e.events.on("Room.AddPlayer",l)),s.push(e.events.on("Room.RemovePlayer",e=>{const n=bo(Jd(e));n&&n!==o()&&t("insight.ingress.room.left",{id:n})})),s.push(e.events.on("Room.Info",()=>{const n=e.gmcp.read("RoomPlayers"),r=o();t("insight.ingress.room.list",{ids:(Array.isArray(n)?n:[]).map(e=>bo(Jd(e))).filter(e=>null!==e&&e!==r)})})),s.push(e.events.on("PromptEvent",()=>{t("insight.ingress.prompt",{})}))},observeSkills:f,stop(){for(a=!1;s.length>0;)s.pop()();for(const e of i.values())e();i.clear()},capture:d})},Hd=new Set(["afflicted","afflictedOneOf","cured","confirmed","confirmedBlocked","confirmedCount","confirmedCounts","confirmedLevel","converted","removed"]),Vd=e=>Math.min(1,Math.max(0,e)),Wd=({roster:e,tables:t,publish:n,notice:r,advanceToNow:s})=>{const i=new Map,a=new Set,o=(e,t)=>{((e,t,s)=>{if(s.contradiction&&(n("insight.belief.contradiction",{id:e,event:t}),"confirmedCounts"===t.type)){const n=t.counts.map((e,t)=>`${e.n} ${e.label??`pool ${t+1}`}`).join(" and ");r({text:`${"readaura"===t.source?"Readaura":"Hard count"} validation failed for ${e} — no tracked fork matched ${n}. The belief was reset. This indicates tracking drift; inspect the preceding inference.`,severity:"error"})}for(const i of s.diagnostics)"forkCapExceeded"===i.type&&(n("insight.belief.growthCapped",{id:e,event:i.eventType??t.type,beforeCount:i.beforeCount,afterCount:i.afterCount,forkCap:i.forkCap}),r({text:`fork cap hit for ${e} — ${i.beforeCount} → ${i.afterCount} forks (cap ${i.forkCap}) on '${t.type}'. Belief detail was discarded; this is a red-flag condition.`,severity:"error"}))})(e.id,t,e.apply(t))},d=t=>{const n=bo(t)??e.targetId;return n?e.track(n):null},l=e=>(s(e.id),c(e)),c=e=>({id:e.id,class:e.class,have:t=>Ma(e.belief,t)>0,probability:t=>Ma(e.belief,t),isBalanceReady:t=>e.isBalanceReady(t),haveDef:t=>e.haveDef(t),limbPercent:t=>e.limbPercent(t),limbStages:t=>e.limbStages(t),skillState:e.getSkillState()}),f=(e,t)=>{switch(t.type){case"defRaised":return e.raiseDef(t.defId),!0;case"defStripped":return e.stripDef(t.defId),!0;case"defStripStarted":return e.startDefStrip(t.defId),!0;case"defConfirmed":return e.confirmDef(t.defId,t.have),!0;case"statObserved":return e.setStat(t.statId,Vd(t.value)),!0;case"statChanged":{const n=e.getStat(t.statId);return n&&e.setStat(t.statId,Vd(n.value+t.delta)),!0}case"limbHit":return 1===e.limbStages(t.limbId).mangled||e.hitLimb(t.limbId,t.percent).advanced&&p(e,t),!0;case"limbReset":return e.resetLimb(t.limbId),!0;case"updateSkillState":return e.updateSkillState(t.patch),!0;case"classObserved":return e.setClass(t.class,{source:t.source}),!0;default:return!1}},u=(e,r,s)=>{const i=t.cureById.get(r.cureId);if(!i)return;if(!i.bals_req.every(t=>e.isObservationBalanceReady(t)))return;(s?bo(s.actorId)!==e.id:bo(r.id)!==e.id)||1!==i.professions?.length||i.bestowable||f(e,{type:"classObserved",class:i.professions[0]});const a=c(e);for(const t of i.blocks)Array.isArray(t)?o(e,{type:"confirmedCount",pool:t,op:"<",n:t.length}):a.have(t)&&o(e,{type:"confirmed",affId:t,present:!1});const d=(e=>e?Object.entries(vo).filter(([,t])=>!e.nextLine(t)).map(([e])=>e):[])(s);o(e,{type:"cured",cureId:i.id,excludedAffs:d}),n("insight.cure.observed",{id:e.id,cureId:i.id});for(const t of(({cure:e,view:t,context:n})=>{if(Pa(e&&Array.isArray(e.order),"cureInferenceEvents needs a cure row"),Pa(t&&"function"==typeof t.have&&"function"==typeof t.isBalanceReady,"cureInferenceEvents needs an opponent view"),!n)return[];const r=[];for(const s of ko)e.order.includes(s.blockerId)&&t.have(s.blockerId)&&t.isBalanceReady(s.balanceId)&&s.pool.some(e=>t.have(e))&&(n.checkBlock(s.evidence)||r.push({type:"confirmedBlocked",pool:[...s.pool],blockerId:s.blockerId}));for(const s of wo)e.id===s.cureId&&t.have(s.affId)&&!t.have(s.absentAffId)&&n.checkBlock(s.evidence)&&r.push({type:"confirmed",affId:s.affId,present:!0});return r})({cure:i,view:c(e),context:s}))o(e,t)},p=(e,t)=>{const r=e.belief;return o(e,(e=>({type:"advanced",rungs:ao(e)}))(t.limbId)),e.belief!==r&&(e.resetLimb(t.limbId),n("insight.limb.advanced",{id:e.id,limb:t.limbId,stages:e.limbStages(t.limbId)}),!0)},h={observe(e,t=null){if(!e||"string"!=typeof e.type)return!1;const n=d(e.id);if(!n)return!1;if(s(n.id),"limbAdvance"===e.type)return p(n,e),!0;if(f(n,e))return!0;if("cured"===e.type)return u(n,e,t),!0;if(!Hd.has(e.type))throw new Error(`unknown observation type '${e.type}'`);return o(n,(e=>{switch(e.type){case"afflicted":case"removed":return{type:e.type,affId:e.affId};case"afflictedOneOf":return{type:e.type,pool:e.pool,mode:e.mode};case"confirmed":return{type:e.type,affId:e.affId,present:e.present};case"confirmedBlocked":return{type:e.type,pool:e.pool,blockerId:e.blockerId};case"confirmedCount":return{type:e.type,pool:e.pool,op:e.op,n:e.n};case"confirmedCounts":return{type:e.type,counts:e.counts,...e.source?{source:e.source}:{}};case"confirmedLevel":return{type:e.type,affId:e.affId,op:e.op,n:e.n};case"converted":return{type:e.type,from:e.from,to:e.to};case"cured":return{type:e.type,cureId:e.cureId,excludedAffs:e.excludedAffs};default:throw new Error(`cannot construct engine event '${e.type}'`)}})(e)),!0},resolveView(e){const t=d(e);return t?l(t):null},addDefinitions(e){for(const t of e){if("string"!=typeof t?.skill||"string"!=typeof t?.id||"function"!=typeof t?.handler)throw new Error("skill definitions need { skill, id, handler }");i.set(yd(t.skill,t.id),t),a.add(bd(t.skill))}},listDefinitions:()=>[...i.keys()],listSkills:()=>[...a],dispatchAction({action:e,context:t}){const n=i.get(yd(e.skill,e.id));if(!n)return;const r=d(t?.actorId);if(!r)return;if("thirdPerson"===e.matchType){const t=ra.get(bd(e.skill));t&&(s=e.args,a=r.id,[s.player,s.player?.id,s.user].some(e=>"string"==typeof e&&bo(e)===a))&&f(r,{type:"classObserved",class:t})}var s,a;const o=n.handler(e,t,l(r))??[];for(const i of o)h.observe({...i,id:r.id},t)}};return Object.freeze(h)},Yd=({onSubscriberError:e=null}={})=>{const t=new Map,n="function"==typeof e;return Object.freeze({on:(e,n)=>(t.has(e)||t.set(e,new Set),t.get(e).add(n),()=>{t.get(e)?.delete(n)}),off(e,n){t.get(e)?.delete(n)},raise(r,s){const i=t.get(r);if(i)for(const t of[...i])if(n)try{t(s)}catch(a){try{e({topic:r,handler:t,cause:a})}catch{}}else t(s)}})},Kd=(Object.freeze(["internal","js","eventstream"]),Object.freeze(["locked","experimental"]),(e,t,n,r)=>Object.freeze({audience:e,stability:t,payload:Object.freeze(n),description:r})),Qd=Object.freeze({"insight.ready":Kd("eventstream","locked",{},"Bootstrap reached READY."),"insight.target.changed":Kd("eventstream","locked",{id:"string | null"},"The tracked target changed (null = target cleared)."),"insight.opponent.tracked":Kd("eventstream","locked",{id:"string"},"An opponent entered observed tracking (new, or re-acquired after leaving the room)."),"insight.opponent.unobserved":Kd("eventstream","locked",{id:"string"},"A tracked opponent left observation; simulation continues on their belief."),"insight.opponent.removed":Kd("eventstream","experimental",{id:"string"},"A tracked opponent was removed from the roster. Roster lifecycle, not belief evolution: removal deliberately emits no per-aff insight.aff.lost sweep. Experimental until Phase 6 locks it."),"insight.aff.got":Kd("eventstream","locked",{id:"string",affId:"string",probability:"number"},"An affliction became present (marginal probability rose above zero) for an opponent."),"insight.aff.lost":Kd("eventstream","locked",{id:"string",affId:"string"},"An affliction left an opponent's belief (marginal probability returned to zero)."),"insight.def.got":Kd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed present on an opponent."),"insight.def.lost":Kd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed absent on an opponent."),"insight.affs.updated":Kd("eventstream","locked",{id:"string"},"Prompt-batched per-opponent change flush: this opponent's affliction state changed since the last flush."),"insight.opponent.updated":Kd("eventstream","locked",{id:"string"},"Prompt-batched signal that an opponent's display-visible state changed; consumers should re-read insight.state.opponents[id]."),"insight.cure.observed":Kd("eventstream","locked",{id:"string",cureId:"string"},"An opponent was observed using a cure after balance gating. Emitted at application time; a cure with delayMs changes affliction state only at resolution."),"insight.limb.advanced":Kd("eventstream","locked",{id:"string",limb:"string",stages:"{ healthy: number, damaged: number, mangled: number }"},"A limb damage ladder advanced; stages is the normalized post-transition distribution."),"insight.belief.growthCapped":Kd("js","locked",{id:"string",event:"string",beforeCount:"number",afterCount:"number",forkCap:"number"},"Red flag: fork-cap enforcement discarded hypotheses (charter §5.4). Accompanied by a high-visibility notice."),"insight.belief.contradiction":Kd("js","locked",{id:"string",event:"object"},"Evidence contradicted every hypothesis; the belief was repaired or hard-validation reset under its declared policy (charter §5.3, ADR-0035)."),"insight.ingress.skill":Kd("internal","experimental",{action:"object",context:"ObservationContext"},"Normalized nexSkills match action with its ingress-captured ObservationContext."),"insight.ingress.skillError":Kd("internal","experimental",{skill:"string | null",id:"string | null",line:"string | null",message:"string"},"nexSkills reported a definition reaction that threw (nexskill.error.reaction). The match still raises, so the action insight observes may carry a stale id or missing affs; the composition renders a warning notice."),"insight.ingress.trigger":Kd("internal","experimental",{id:"string",match:"object",context:"ObservationContext"},"A trigger-pack pattern fired, with its ingress-captured ObservationContext."),"insight.ingress.target":Kd("internal","experimental",{id:"string | null"},"Normalized IRE.Target.Set."),"insight.ingress.room.entered":Kd("internal","experimental",{id:"string"},"GMCP Room.AddPlayer, self excluded."),"insight.ingress.room.left":Kd("internal","experimental",{id:"string"},"GMCP Room.RemovePlayer."),"insight.ingress.room.list":Kd("internal","experimental",{ids:"string[]"},"GMCP Room.Info occupancy resync, self excluded."),"insight.ingress.prompt":Kd("internal","experimental",{},"Host PromptEvent boundary — drives the prompt-batched flush."),"insight.display.flush":Kd("internal","experimental",{ids:"string[]"},"The prompt-batched flush completed for these dirty opponents — the display coordinator renders on this boundary."),"insight.display.changed":Kd("internal","experimental",{id:"string"},"An opponent's display-visible state changed or the opponent became the target; drives the prompt-batched display/opponent.updated flush."),"insight.model.changed":Kd("internal","experimental",{id:"string"},"An opponent's aff marginals or observation mode changed — deliberately aff/mode-scoped, driving insight.affs.updated only (the scheduler reschedules from the roster's full per-opponent change surface)."),"insight.scheduler.elapsed":Kd("internal","experimental",{id:"string",expired:"object[]",resolvedCures:"object[]",resolvedDefenceStrips:"object[]",restoredDefs:"object[]",predicted:"object[]"},"A scheduler timer delivered an elapsed window to an opponent model."),"insight.settings.changed":Kd("internal","experimental",{document:"SettingsDocument"},"The settings document changed through the composition's settings surface (every document-mutating verb) — carries the new frozen document; runtime subscribers apply the change live (SETTINGS_AUTHORITY.md §5).")}),Xd=(e,t=new WeakMap)=>{if(!e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);const n=Array.isArray(e)?[]:{};t.set(e,n);for(const[r,s]of Object.entries(e))n[r]=Xd(s,t);return Object.freeze(n)},el=({adapter:e,notice:t=()=>{}})=>{const n=Yd(),r=(e,n,r)=>{t({text:`${e} failed — ${n} (${r?.message??String(r)})`,severity:"error"})},s=Yd({onSubscriberError:({topic:e,cause:t})=>r("public event subscriber",e,t)}),i=e=>{const t=Qd[e];if(!t)throw new Error(`Undeclared topic '${e}' — every emitted topic must be declared in topicRegistry.js (charter §8)`);return t},a=e=>{if("internal"===i(e).audience)throw new Error(`Topic '${e}' is internal — not part of the public contract`)};return Object.freeze({publish(t,a={}){const o=i(t);if("internal"===o.audience)return void n.raise(t,a);const d=Xd(a);if(s.raise(t,d),"eventstream"===o.audience)try{e.events.raise(t,d)}catch(l){r("EventStream forward",t,l)}},on:(e,t)=>(e=>"internal"===i(e).audience?n:s)(e).on(e,t),events:Object.freeze({on(e,t){if(a(e),"function"!=typeof t)throw new TypeError("insight.events.on needs a function");return s.on(e,t)},off(e,t){if(a(e),"function"!=typeof t)throw new TypeError("insight.events.off needs a function");s.off(e,t)}})})},tl=Object.freeze({safetyFlushMs:200}),nl=e=>`insight4.elapsed.${e}`,rl="insight4.flush.safety",sl=({adapter:e,roster:t,publisher:n,notice:r,safetyFlushMs:s=tl.safetyFlushMs})=>{const{publish:i}=n,a=new Map,o=new Set,d=new Set;let l=!1,c=0;const f=[],u=(e,t)=>{for(const n of t)"contradiction"===n.type&&i("insight.belief.contradiction",{id:e,event:n.event}),"forkCapExceeded"===n.type&&(i("insight.belief.growthCapped",{id:e,event:n.eventType??"elapsed",beforeCount:n.beforeCount,afterCount:n.afterCount,forkCap:n.forkCap}),r({text:`fork cap hit for ${e} — ${n.beforeCount} → ${n.afterCount} forks (cap ${n.forkCap}) during simulation. Belief detail was discarded; this is a red-flag condition.`,severity:"error"}))},p=(n,{includeDue:r=!1}={})=>{const s=t.get(n);if(!s)return a.delete(n),void e.clock.clearTimer(nl(n));a.has(n)||a.set(n,e.clock.now());const o=((t,n)=>{const r=t.nextInterestingAt({includeDue:n});if(null===r)return null;const s=e.clock.now(),i=a.get(t.id)??s;return Math.max(0,r-t.now-(s-i))})(s,r);null!==o?e.clock.setTimer(nl(n),o,()=>{const t=e.clock.now(),r=a.get(n)??t;a.set(n,t);const o=Math.max(0,t-r);o>0&&(c+=1);const d=s.elapsed(o);u(n,d.diagnostics),i("insight.scheduler.elapsed",{id:n,expired:d.expired,resolvedCures:d.resolvedCures,resolvedDefenceStrips:d.resolvedDefenceStrips,restoredDefs:d.restoredDefs,predicted:d.predicted}),p(n)}):e.clock.clearTimer(nl(n))},h=()=>{if(l=!1,e.clock.clearTimer(rl),0===o.size&&0===d.size)return;const t=[...o].sort(),n=[...d].sort();o.clear(),d.clear();for(const e of t)i("insight.affs.updated",{id:e});for(const e of n)i("insight.opponent.updated",{id:e});n.length>0&&i("insight.display.flush",{ids:n})},m=()=>{l||(l=!0,e.clock.setTimer(rl,s,h))},g=e=>{o.add(e),m()},b=e=>{d.add(e),m()};return Object.freeze({start(){f.push(t.onOpponentChange(e=>p(e,{includeDue:!0})),n.on("insight.model.changed",({id:e})=>g(e)),n.on("insight.display.changed",({id:e})=>b(e)),n.on("insight.opponent.removed",({id:e})=>{o.delete(e),d.delete(e),p(e)}),n.on("insight.ingress.prompt",h))},stop(){for(;f.length>0;)f.pop()();e.clock.clearTimer(rl),l=!1;for(const t of a.keys())e.clock.clearTimer(nl(t));a.clear(),o.clear(),d.clear()},advanceToNow:n=>{const r=t.get(n);if(!r)return null;const s=e.clock.now(),i=a.get(n)??s;a.set(n,s);const o=s-i;if(o<=0)return null;c+=1;const d=r.elapsed(o);return u(n,d.diagnostics),d},getTimeEpoch:()=>c,reschedule:p,markDirty:e=>{g(e),b(e)},flush:h})},il=({roster:e,publish:t,defenceDefaults:n={}})=>{const r=Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Object.freeze({have:t,atMs:0,phase:null,stripAt:null,restoreAt:null})])));let s=null;const i=new Map;let a=!1;const o=[],d=[],l=e=>({mode:e.mode,affs:e.affs??{},defs:e.defs??{},stats:e.stats??{},limbs:e.limbs??{}}),c=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),f=(e,t,n)=>{const r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!0;for(const i of s)if(!c(e,i)||n(e[i])!==n(t[i]))return!0;return!1},u=(e,n)=>{const s=l(n),a=i.get(e);let o=!1,d=!1;a?a.mode!==s.mode&&(o=!0,d=!0,"observed"===s.mode?t("insight.opponent.tracked",{id:e}):t("insight.opponent.unobserved",{id:e})):(o=!0,d=!0,t("insight.opponent.tracked",{id:e}));for(const[r,i]of Object.entries(s.affs)){const n=i.probability;a&&c(a.affs,r)?a.affs[r].probability!==n&&(o=!0,d=!0):(o=!0,d=!0,t("insight.aff.got",{id:e,affId:r,probability:n}))}for(const r of Object.keys(a?.affs??{}))c(s.affs,r)||(o=!0,d=!0,t("insight.aff.lost",{id:e,affId:r}));const u=a?.defs??r;for(const[r,i]of Object.entries(s.defs))!0===i.have&&!0!==u[r]?.have&&(d=!0,t("insight.def.got",{id:e,defId:r}));for(const[r,i]of Object.entries(u))!0===i.have&&!0!==s.defs[r]?.have&&(d=!0,t("insight.def.lost",{id:e,defId:r}));a&&((e,t)=>{const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!0;for(const s of r){const n=e[s],r=t[s];if(!n||n.have!==r.have||n.atMs!==r.atMs||n.phase!==r.phase||n.stripAt!==r.stripAt||n.restoreAt!==r.restoreAt)return!0}return!1})(a.defs,s.defs)&&(d=!0),a&&(f(a.stats,s.stats,e=>e.value)||f(a.limbs,s.limbs,e=>e.percent))&&(d=!0),i.set(e,s),o&&t("insight.model.changed",{id:e}),d&&t("insight.display.changed",{id:e})},p=e=>{if(o.push(e),!a){a=!0;try{for(;o.length>0;)o.shift()()}finally{a=!1}}};return Object.freeze({start(){s=e.targetId;for(const t of e.list()){const n=e.get(t);n&&i.set(t,l(n.snapshot()))}d.push(e.onOpponentChange((e,t)=>p(()=>u(e,t))),e.onChange(n=>p(()=>(({ids:n,targetId:r})=>{const a=new Set(n);for(const t of n)if(!i.has(t)){const n=e.get(t);n&&u(t,n.snapshot())}for(const e of[...i.keys()])a.has(e)||(i.delete(e),t("insight.opponent.removed",{id:e}));r!==s&&(s=r,t("insight.target.changed",{id:s}),s&&t("insight.display.changed",{id:s}))})(n))))},stop(){for(;d.length>0;)d.pop()()}})},al=(e,t)=>"number"==typeof e?bo(t?.[e]):null,ol=({adapter:e,settings:t,safetyFlushMs:n,display:r,displaySink:s,notice:i=()=>{},guards:a})=>{const o=Object.freeze({affById:Gi,cureById:Ji,cureMasks:Ki,balanceById:Ui,priorityByAff:Wi,defenceById:Hi,defenceDefaults:Vi,guards:!0===a,get growth(){return t.get().pruning}}),d=el({adapter:e,notice:i}),{publish:l}=d;let c=0;const f=e=>(c+=1,l("insight.settings.changed",{document:e}),e),u=(e,t)=>{try{return e()}catch(n){throw i({text:`Settings storage ${t} failed: ${n?.message??String(n)}`,severity:"error"}),n}},p=Object.freeze({get:t.get,save:()=>u(t.save,"write"),load:()=>f(u(t.load,"read")),update:e=>f(u(()=>t.update(e),"write")),updateDisplay:e=>f(u(()=>t.updateDisplay(e),"write")),updatePredictive:e=>f(u(()=>t.updatePredictive(e),"write")),replace:e=>f(u(()=>t.replace(e),"write")),reset:()=>f(t.reset()),clear:()=>f(u(t.clear,"clear"))}),h=yo({tables:o,guards:!0===a,policy:t.get().predictive.defaultPolicy,predictionEnabled:t.get().predictive.enabled}),m=sl({adapter:e,roster:h,publisher:d,notice:i,safetyFlushMs:n??t.get().display.safetyFlushMs}),g=Wd({roster:h,tables:o,publish:l,notice:i,advanceToNow:m.advanceToNow}),b=il({roster:h,publish:l,defenceDefaults:Vi}),y=r?(({publisher:e,roster:t,settings:n,display:r,sink:s})=>{const{renderTarget:i,renderRoster:a,displayTable:o}=r,d=[],l=(e,t)=>{const n=e.targetId?e.opponents[e.targetId]:null;n&&s(i(n,o,t))},c=(e,t)=>{t.display.showRoster&&Object.keys(e.opponents).length>0&&s(a(e.opponents,o,t))};return Object.freeze({start(){d.push(e.on("insight.display.flush",({ids:e})=>{const r=t.snapshot(),s=n.get();r.targetId&&e.includes(r.targetId)&&l(r,s),c(r,s)}))},stop(){for(;d.length>0;)d.pop()()},refresh(){const e=t.snapshot(),r=n.get();l(e,r),c(e,r)}})})({publisher:d,roster:h,settings:p,display:r,sink:s??(t=>e.display.addLine(t))}):null,v=r?(({publisher:e,roster:t,settings:n,display:r,notice:s})=>{const{displayTable:i,renderAffNotice:a,renderDefNotice:o}=r,d=[],l=e=>!0===n.get().display.notices&&t.targetId===e,c=e=>t=>{l(t.id)&&s({html:a({affId:t.affId,present:e},i,n.get())})},f=e=>t=>{l(t.id)&&s({html:o({defId:t.defId,present:e},i,n.get())})};return Object.freeze({start(){d.push(e.on("insight.aff.got",c(!0)),e.on("insight.aff.lost",c(!1)),e.on("insight.def.got",f(!0)),e.on("insight.def.lost",f(!1)))},stop(){for(;d.length>0;)d.pop()()}})})({publisher:d,roster:h,settings:p,display:r,notice:i}):null,k=(()=>{const e=new Map;let t=null;return Object.freeze({rememberQueue(n,r){"string"==typeof n&&n&&"string"==typeof r&&(e.set(n,r),t=n)},snapshot:()=>({queues:Object.fromEntries(e),lastQueue:t}),clear(){e.clear(),t=null}})})(),w=Ud({adapter:e,publish:l,commandMemory:k,skills:()=>[...g.listSkills(),...I.listArmingSkills()]}),I=(({adapter:e,roster:t,router:n,publisher:r,capture:s,commandMemory:i,sessionPacks:a=[],promptPacks:o=[]})=>{const{publish:d}=r,l=new Map(a.map(e=>[e.id,e])),c=new Map(o.map(e=>[e.id,e])),f=new Map,u=new Set;for(const z of c.values()){const{skill:e,id:t}=z.armedBy??{};if("string"!=typeof e||""===e||"string"!=typeof t||""===t)continue;const n=yd(e,t),r=f.get(n);r?r.push(z):f.set(n,[z]),u.add(bd(e))}const p=new Map,h=new Map,m=[],g=()=>t.listObserved(),b=(e,t,r)=>{for(const s of e??[])n.observe({...s,id:s.id??t},r)},y=(e,r)=>{if(e.remember){const t=e.remember(r);return void(t?.queue&&i.rememberQueue(t.queue.name,t.queue.text))}const a=e.actor??null,o="number"==typeof a?al(a,r):null,l=s(o);d("insight.ingress.trigger",{id:e.id,match:r,context:l});const f="room"===a?g():"tracked"===a?t.list():[o];for(const t of f){const s=n.resolveView(t);s&&b(e.handler(r,l,s),s.id,l)}for(const t of c.values())t.armedBy?.trigger===e.id&&w(t,o)},v=(e,t,r)=>{const i=h.get(e.id);if(!i)return;const a="armed"===t.actor?i.state.actorId:al(t.actor,r),o=s(a);d("insight.ingress.trigger",{id:`${e.id}.${t.id}`,match:r,context:o});const l=n.resolveView(a);l&&b(t.handler(r,o,l,i.state),l.id,o)},k=t=>{const n=h.get(t);if(!n)return null;for(const r of n.captureIds.values())e.triggers.unregister(r);return h.delete(t),n},w=(n,r=null)=>{k(n.id);const s=n.initState?n.initState({actorId:r,observedIds:g(),targetId:t.targetId}):{actorId:r},i=new Map;for(const t of n.captures)i.set(t.id,e.triggers.register(t.pattern,"prompt",e=>v(n,t,e)));h.set(n.id,{pack:n,state:s,captureIds:i})},I=()=>{for(const e of[...h.keys()]){const t=k(e);if(t?.pack.finalize){const e=s(t.state.actorId??null);b(t.pack.finalize(t.state),t.state.actorId??null,e)}}};return Object.freeze({start(){for(const t of l.values())p.set(t.id,e.triggers.register(t.pattern,"session",e=>y(t,e)));m.push(r.on("insight.ingress.skill",({action:e})=>{const t=f.get(yd(e.skill,e.id));for(const n of t??[])w(n,null)}),r.on("insight.ingress.prompt",I))},stop(){for(;m.length>0;)m.pop()();for(const e of[...h.keys()])k(e);for(const t of p.values())e.triggers.unregister(t);p.clear()},listSession:()=>[...l.keys()],listArmed:()=>[...h.keys()],listArmingSkills:()=>[...u]})})({adapter:e,roster:h,router:g,publisher:d,capture:w.capture,commandMemory:k,sessionPacks:Bd,promptPacks:Fd}),z=e=>{g.addDefinitions(e),w.observeSkills(g.listSkills())};z(vd);const _=new Set,O=new Map;let $=!1;const S=({id:n})=>{const r=h.setTarget(n);if(!r||!t.get().classLookup||null!==r.class||_.has(r.id)||O.has(r.id))return;const s=Promise.resolve().then(()=>e.directory.read(r.id));O.set(r.id,s),s.then(e=>{if(_.add(r.id),$||null===e)return;const t=h.get(r.id);t&&null===t.class&&g.observe({type:"classObserved",class:e,source:"directory",id:r.id})}).catch(()=>{}).finally(()=>{O.get(r.id)===s&&O.delete(r.id)})},M=[],x=()=>{for($=!0,O.clear(),w.stop(),I.stop(),m.stop(),b.stop(),y?.stop(),v?.stop();M.length>0;)M.pop()()};try{b.start(),m.start(),y?.start(),v?.start(),M.push(d.on("insight.ingress.skill",g.dispatchAction),d.on("insight.ingress.skillError",({skill:e,id:t,message:n})=>i({text:`nexSkills reaction failed for ${e??"?"}.${t??"?"} — ${n}. Observations from that line may be incomplete.`,severity:"warning"})),d.on("insight.ingress.target",S),d.on("insight.ingress.room.entered",({id:e})=>h.track(e)),d.on("insight.ingress.room.left",({id:e})=>h.untrack(e)),d.on("insight.ingress.room.list",({ids:e})=>(e=>{const t=new Set(e);for(const n of e)h.track(n);for(const n of h.list())t.has(n)||h.untrack(n)})(e)),d.on("insight.settings.changed",({document:e})=>h.updateDefaults({policy:e.predictive.defaultPolicy,predictionEnabled:e.predictive.enabled}))),I.start(),w.start()}catch(j){throw x(),j}return Object.freeze({roster:h,router:g,scheduler:m,registrar:I,publish:l,events:d.events,settings:p,getSettingsRevision:()=>c,display:y,observe:g.observe,addDefinitions:z,capture:w.capture,dispose:x})},dl=Object.freeze({schemaVersion:3,autoUpdate:!1,classLookup:!0,display:Object.freeze({threshold:0,shortNames:!0,colors:!0,notices:!0,showRoster:!1,safetyFlushMs:200}),predictive:Object.freeze({enabled:!1,defaultPolicy:"distribution"}),queries:Object.freeze({presenceFloor:.01}),pruning:Object.freeze({epsilon:sa.epsilon,forkCap:sa.forkCap})}),ll=Fr({threshold:jr().min(0).max(1).catch(dl.display.threshold),shortNames:Er().catch(dl.display.shortNames),colors:Er().catch(dl.display.colors),notices:Er().catch(dl.display.notices),showRoster:Er().catch(dl.display.showRoster),safetyFlushMs:jr().int().min(0).max(1e4).catch(dl.display.safetyFlushMs)}).catch({...dl.display}),cl=Fr({enabled:Er().catch(dl.predictive.enabled),defaultPolicy:Kr(Da).catch(dl.predictive.defaultPolicy)}).catch({...dl.predictive}),fl=Fr({presenceFloor:jr().min(0).max(1).catch(dl.queries.presenceFloor)}).catch({...dl.queries}),ul=Fr({epsilon:jr().positive().max(.1).catch(dl.pruning.epsilon),forkCap:jr().int().min(1).catch(dl.pruning.forkCap)}).catch({...dl.pruning}),pl=Fr({schemaVersion:Xr(3).catch(3),autoUpdate:Er().catch(dl.autoUpdate),classLookup:Er().catch(dl.classLookup),display:ll,predictive:cl,queries:fl,pruning:ul}).catch({schemaVersion:3,autoUpdate:dl.autoUpdate,classLookup:dl.classLookup,display:{...dl.display},predictive:{...dl.predictive},queries:{...dl.queries},pruning:{...dl.pruning}}),hl=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))hl(e[t])}return e},ml=e=>hl(pl.parse((e=>{if(!e||"object"!=typeof e||Array.isArray(e)||!Number.isInteger(e.schemaVersion)||e.schemaVersion>=3)return e;const t=e.pruning&&"object"==typeof e.pruning&&!Array.isArray(e.pruning)?{...e.pruning,...128===e.pruning.forkCap?{forkCap:dl.pruning.forkCap}:{}}:e.pruning;return{...e,schemaVersion:3,pruning:t}})(e))),gl=(e,{key:t="insightSettings"}={})=>{let n=ml(null);const r=(r=n)=>(e.storage.set(t,JSON.stringify(r)),n=r,r);return Object.freeze({get:()=>n,load:()=>(n=ml((e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return null}return e??null})(e.storage.get(t))),n),save:()=>r(),update:(e={})=>r(ml({...n,...e,display:{...n.display,...e.display},predictive:{...n.predictive,...e.predictive},queries:{...n.queries,...e.queries},pruning:{...n.pruning,...e.pruning}})),updateDisplay:(e={})=>r(ml({...n,display:{...n.display,...e}})),updatePredictive:(e={})=>r(ml({...n,predictive:{...n.predictive,...e}})),replace:e=>r(ml(e)),reset:()=>(n=ml(null),n),clear:()=>(e.storage.clear(t),n=ml(null),n)})},bl=Object.freeze({forks:Object.freeze([])}),yl=({roster:e,resolveCure:t,events:n,settings:r,observe:s,capture:i,advanceToNow:a,reschedule:o,displayRendering:d,refreshDisplay:l,notice:c,addLine:f,getPhase:u,getPhaseRevision:p,getSettingsRevision:h,getTimeEpoch:m,version:g})=>{const b=t=>{const n=t?.id;return null==n?e.getTarget():e.get(n)},y=(e,t)=>{const n=b(e);return n?Ma(n.belief,t):0},v=(e,t,n)=>e(b(t)?.belief??bl,n),k=(e,t)=>v(ja,e,t),w=(e,t)=>v(Na,e,t),I=(e,t)=>((e,t,n,r)=>{$a(t),ia(Ia.includes(n),`unknown comparison operator '${n}'`),ia(Number.isInteger(r)&&r>=0,"pool count probability needs an integer n >= 0");let s=0;for(const i of e.forks)za(Sa(i,t),n,r)&&(s+=i.p);return s})(b(e)?.belief??bl,t,e?.op,e?.n),z=(e,t)=>e>r.get().queries.presenceFloor&&e>=(e=>{const t="number"==typeof e?.threshold?e.threshold:0;return t>1?t/100:t})(t),_=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))_(e[t])}return e},O=e=>e&&"object"==typeof e?Array.isArray(e)?e.map(O):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,O(t)])):e,$=new Map,S=(e,t)=>{const n=$.get(e.id);if(n?.model===e&&n.revision===e.revision&&n.timeEpoch===e.timeEpoch&&n.settingsRevision===t)return n.branch;const r=e.snapshot(),s=_(O({id:r.id,class:r.class,affs:r.affs,limbs:r.limbs,balances:r.balances,stats:r.stats,defs:r.defs,staleness:r.staleness}));return $.set(e.id,{model:e,revision:e.revision,timeEpoch:e.timeEpoch,settingsRevision:t,branch:s}),s};let M=null,x=null;const j=()=>{const t={rosterRevision:e.revision,settingsRevision:h(),phaseRevision:p(),timeEpoch:m()};if(x?.rosterRevision===t.rosterRevision&&x.settingsRevision===t.settingsRevision&&x.phaseRevision===t.phaseRevision&&x.timeEpoch===t.timeEpoch)return M;const n={},s=[...e.list()].sort(),i=new Set(s);for(const r of s)n[r]=S(e.get(r),t.settingsRevision);for(const e of $.keys())i.has(e)||$.delete(e);return M=Object.freeze({system:Object.freeze({phase:u(),version:g}),target:e.targetId?n[e.targetId]??null:null,opponents:Object.freeze(n),settings:r.get()}),x=t,M},N=Object.freeze({get:()=>e.targetId,set:t=>{const n=e.setTarget(t??null);return n?n.id:null},is:t=>null!==e.targetId&&bo(t)===e.targetId}),A=Object.freeze({track:t=>{const n=e.track(t);return n?n.id:null},remove:t=>e.remove(t),list:()=>e.list(),reset:t=>e.reset(t),resetAll:()=>{e.resetAll()}}),T=(e,t)=>String(e??"").trim().toLowerCase()===String(t??"").trim().toLowerCase(),E=Object.freeze({get:e=>b(e)?.class??null,is:(e,t)=>{if(void 0===e)return!0;if(!e)return!1;const n=b(t)?.class??"";return Array.isArray(e)?e.some(e=>T(n,e)):T(n,e)}}),C=Object.freeze({have:(e,t)=>z(y(t,e),t),haveAll:(e,t)=>z(w(t,e),t),haveAny:(e,t)=>z(k(t,e),t),probability:(e,t)=>y(t,e),probabilityAll:(e,t)=>w(t,e),probabilityAny:(e,t)=>k(t,e),expectedPoolCount:(e,t)=>((e,t)=>v(Aa,e,t))(t,e),poolCountProbability:(e,t)=>I(t,e)}),P=Object.freeze({poolCountProbability:(e,n)=>I(n,(e=>{const n=t(e);if(!n)throw new Error(`insight api: unknown cure '${String(e)}'`);return n.order})(e))}),D=Object.freeze({have:(e,t)=>!0===b(t)?.haveDef(e),get:(e,t)=>{const n=b(t)?.snapshot().defs[e];return n?Object.freeze({...n}):null}}),R=Object.freeze({get:(e,t)=>{const n=b(t);return n?Object.freeze({percent:n.limbPercent(e),stages:Object.freeze(n.limbStages(e))}):null},hit:(e,t)=>s({type:"limbHit",limbId:e,percent:t?.percent,id:t?.id}),advance:(e,t)=>s({type:"limbAdvance",limbId:e,id:t?.id}),reset:(e,t)=>s({type:"limbReset",limbId:e,id:t?.id})}),Z=Object.freeze({have:(e,t)=>{const n=b(t);return!!n&&n.isBalanceReady(e)},remainingMs:(e,t)=>{const n=b(t);return n?n.snapshot().balances[e]?.remainingMs??null:null},remainingProbability:(e,t={})=>{const n=b(t);return n?n.balanceRemainingProbability(e,{op:t?.op,ms:t?.ms,affIds:t?.affs??[]}):0}}),L=(e,t={})=>{const{id:n,...r}=t;return s({type:e,...r,id:n},i(n??null))},B=Object.freeze({afflicted:e=>L("afflicted",e),afflictedOneOf:({mode:e="firstMissing",...t}={})=>L("afflictedOneOf",{mode:e,...t}),advanced:e=>L("limbAdvance",e),cured:e=>L("cured",e),confirmed:({present:e=!0,...t}={})=>L("confirmed",{present:e,...t}),confirmedCount:e=>L("confirmedCount",e),confirmedCounts:e=>L("confirmedCounts",e),confirmedLevel:e=>L("confirmedLevel",e),converted:e=>L("converted",e),removed:e=>L("removed",e)}),F=Object.freeze({enable:e=>{const t=b({id:e});return!!t&&(t.enablePrediction(),!0)},disable:e=>{const t=b({id:e});return!!t&&(t.disablePrediction(),!0)},setPolicy:(e,t)=>{const n=b({id:t});return!!n&&(n.setPolicy(e),!0)},isEnabled:e=>{const t=b({id:e});return!!t&&t.isPredictionEnabled()},stepNow:e=>{const t=b({id:e});if(!t)return null;const n=a(t.id)??{expired:[],resolvedCures:[],predicted:[],timingConfirmations:[],diagnostics:[]};return o(t.id),n}}),q=Object.freeze({get:({view:e="target",id:t,affId:n,defId:s,present:i}={})=>{const a=r.get();if("affNotice"===e){if("string"!=typeof n||0===n.length||"boolean"!=typeof i)throw new TypeError("display.get affNotice needs affId and boolean present");return d.renderAffNotice({affId:n,present:i},d.displayTable,a)}if("defNotice"===e){if("string"!=typeof s||0===s.length||"boolean"!=typeof i)throw new TypeError("display.get defNotice needs defId and boolean present");return d.renderDefNotice({defId:s,present:i},d.displayTable,a)}if(!["target","affState","statState"].includes(e))throw new TypeError(`unknown display view '${e}'`);const o=b({id:t});if(!o)return"";const l=o.snapshot();return"target"===e?d.renderTarget(l,d.displayTable,a):"affState"===e?d.renderAffState(l,d.displayTable,a):d.renderStatState(l,d.displayTable,a)},notice:(e,t)=>{c({html:e,severity:t})},refresh:()=>{l()},openDebug:()=>{f(d.renderDebug(j()))}}),G=Object.freeze({target:N,opponents:A,class:E,affs:C,cures:P,defs:D,limbs:R,balances:Z,observe:B,simulate:F,display:q,settings:r}),J=Object.freeze(Object.fromEntries(Object.entries(Qd).filter(([,e])=>"internal"!==e.audience))),U=Object.freeze({on:n.on,off:n.off,topics:J});return Object.freeze({get state(){return j()},api:G,events:U})},vl=["head","torso","leftarm","rightarm","leftleg","rightleg"],kl=e=>String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),wl=(e,t="",n="")=>{const r=[t?`color: ${t}`:"",n?`background: ${n}`:""].filter(Boolean).join("; ");return r?`<span style="${r}">${e}</span>`:`<span>${e}</span>`},Il=(e,t="",n="")=>wl(kl(e),t,n),zl=e=>e.charAt(0).toUpperCase()+e.slice(1),_l=(e,t)=>Object.entries(e).filter(([,e])=>e.probability>0&&e.probability>=t).sort(([e,t],[n,r])=>r.probability-t.probability||(e<n?-1:1)),Ol=(e,t,n,r)=>{const s=n.affs[e],i=r.shortNames&&s?s.shortName:e,a=void 0!==t.count?(e=>String(parseFloat(e.toFixed(1))))(t.count):"",o=r.colors&&s?s.fg:"",d=r.colors&&s?s.bg:"";return Il(`${i}${a}`,o,d)},$l=(e,t,n)=>{const r=n.display,{bracket:s}=t.chrome,i=[Il("[",s.fg,s.bg)],a=_l(e.affs,r.threshold);return a.forEach(([e,n],s)=>{i.push(Ol(e,n,t,r));const o=s<a.length-1?", ":"";i.push(Il(`: ${(e=>String(Math.round(100*e)/100))(n.probability)}${o}`))}),i.push(Il("]",s.fg,s.bg)),i},Sl=[["hp","H"],["mana","M"]],Ml=e=>{const t=Math.round(100*Math.min(1,Math.max(0,e)));return`hsl(${1.2*t}, 100%, ${t<75?50:Math.abs(t-100)/2+25}%)`},xl=(e,t)=>{const n=[],{detail:r}=t.chrome;for(const[s,i]of Sl){const t=e.stats?.[s];if(!t)continue;n.length>0&&n.push(Il(" "));const a=Math.round(100*Math.min(1,Math.max(0,t.value)));n.push(Il(`${i}:`,r.fg,r.bg)),n.push(Il(`${a}%`,Ml(t.value)))}return n},jl=(e,t,n,r,s)=>{const i=[Il(`${n?"+":"-"}${e} `,n?"lime":"red")];if("aff"===e){const e=r.affs[t],n=s.display;i.push(Il(zl(t),n.colors&&e?e.fg:"",n.colors&&e?e.bg:""))}else i.push(Il(zl(t)));return i},Nl=({text:e="",html:t,severity:n="info"},r)=>{const s=r.chrome.severity,i=s[n]??s.info,a="string"==typeof t?wl(t,i.fg,i.bg):Il(e,i.fg,i.bg);return`<span class="mono">${(e=>{const{delimiter:t,label:n}=e.chrome.tag;return[Il("<<",t.fg,t.bg),Il("insight",n.fg,n.bg),Il(">> ",t.fg,t.bg)]})(r).join("")}${a}</span>`},Al="0.6.3",Tl=Object.freeze({BOOTING:"BOOTING",LOADING_SETTINGS:"LOADING_SETTINGS",REGISTERING_TRIGGERS:"REGISTERING_TRIGGERS",READY:"READY",DEGRADED:"DEGRADED"}),El=Object.freeze({[Tl.BOOTING]:Object.freeze([Tl.LOADING_SETTINGS,Tl.DEGRADED]),[Tl.LOADING_SETTINGS]:Object.freeze([Tl.REGISTERING_TRIGGERS,Tl.DEGRADED]),[Tl.REGISTERING_TRIGGERS]:Object.freeze([Tl.READY,Tl.DEGRADED]),[Tl.READY]:Object.freeze([]),[Tl.DEGRADED]:Object.freeze([])});var Cl="__insight4StorageProbe",Pl=Object.freeze({displayTable:Zs,renderAffNotice:({affId:e,present:t},n,r)=>`<span class="mono">${jl("aff",e,t,n,r).join("")}</span>`,renderAffState:(e,t,n)=>`<span class="mono">${$l(e,t,n).join("")}</span>`,renderDebug:e=>`<pre class="mono">${kl(JSON.stringify(e,null,2))}</pre>`,renderDefNotice:({defId:e,present:t},n,r)=>`<span class="mono">${jl("def",e,t,n,r).join("")}</span>`,renderNotice:Nl,renderRoster:(e,t,n)=>{const r=n.display;if(!r.showRoster)return"";const{bracket:s,detail:i}=t.chrome,a=[];return Object.keys(e).sort().forEach((n,o)=>{const d=e[n];o>0&&a.push(Il(" ")),a.push(Il(`${zl(n)} `),Il("[",s.fg,s.bg));const l=_l(d.affs,r.threshold);l.forEach(([e,n],s)=>{a.push(Ol(e,n,t,r)),s<l.length-1&&a.push(Il(" "))}),a.push(Il("]",s.fg,s.bg));const c=Math.round(100*d.staleness);c>0&&a.push(Il(` ~${c}%`,i.fg,i.bg))}),`<span class="mono">${a.join("")}</span>`},renderStatState:(e,t)=>{const n=xl(e,t);return n.length>0?`<span class="mono">${n.join("")}</span>`:""},renderTarget:(e,t,n)=>{const{detail:r}=t.chrome,s=[Il(`${zl(e.id)} `),...$l(e,t,n)],i=xl(e,t);i.length>0&&s.push(Il(" "),...i);const a=vl.filter(t=>e.limbs[t]?.percent>0);if(a.length>0){const t=a.map(t=>{const n=e.limbs[t];return`${t}:${Math.round(n.percent)}%`}).join(" ");s.push(Il(` ${t}`,r.fg,r.bg))}return`<span class="mono">${s.join("")}</span>`}}),Dl=e=>Ji.get(e);function Rl(e,{safetyFlushMs:t,updateNxs:n=h,guards:r}={}){const s=function({onTransition:e}={}){let t=Tl.BOOTING,n=0;const r=[Tl.BOOTING];return{getPhase:()=>t,getRevision:()=>n,getHistory:()=>[...r],transition(s){if(!El[t].includes(s))throw new Error(`Invalid phase transition: ${t} → ${s}`);return t=s,n+=1,r.push(s),e?.(s),t}}}();let i,o=null,d=null,l=null,c=null,f=!1;const u={getPhase:s.getPhase,getPhaseHistory:s.getHistory,getError:()=>o,isReady:()=>s.getPhase()===Tl.READY,dispose(){f||(f=!0,l?.dispose(),c&&globalThis.insight===c&&delete globalThis.insight)},get settings(){return d},get runtime(){return l},get state(){return c?c.state:null},get api(){return c?c.api:null},get events(){return c?c.events:null}},p=t=>{try{e.display.addLine(Nl(t,Zs))}catch{}},m=()=>{!0===d?.get?.().autoUpdate&&n({enabled:!0,currentVersion:Al,notice:p})},g=e=>(o=e,s.transition(Tl.DEGRADED),p({text:`DEGRADED: ${e?.message??String(e)}`,severity:"error"}),m(),u);try{a(e),e.storage.clear(Cl),e.storage.set(Cl,"probe"),e.storage.clear(Cl),i=e.display.addLine.bind(e.display)}catch(y){try{e?.storage?.clear?.(Cl)}catch{}return g(y)}s.transition(Tl.LOADING_SETTINGS);const b=gl(e);d=b;try{b.load()}catch(y){b.reset(),p({text:`Settings storage is unavailable — running on default settings. (${y?.message??String(y)})`,severity:"warning"})}s.transition(Tl.REGISTERING_TRIGGERS);try{l=ol({adapter:e,settings:b,safetyFlushMs:t,guards:r,displaySink:i,notice:p,display:Pl}),d=l.settings,c=yl({roster:l.roster,resolveCure:Dl,events:l.events,settings:l.settings,observe:l.observe,capture:l.capture,advanceToNow:l.scheduler.advanceToNow,reschedule:l.scheduler.reschedule,displayRendering:Pl,refreshDisplay:l.display.refresh,notice:p,addLine:i,getPhase:s.getPhase,getPhaseRevision:s.getRevision,getSettingsRevision:l.getSettingsRevision,getTimeEpoch:l.scheduler.getTimeEpoch,version:Al})}catch(y){return l?.dispose(),l=null,d=b,g(y)}return s.transition(Tl.READY),globalThis.insight=c,l.publish("insight.ready",{}),m(),u}var Zl=Symbol.for("insight4.instance");!function(e){globalThis[Zl]?.dispose();const r=Rl(function({fetchFn:e=globalThis.fetch,AbortControllerCtor:r=globalThis.AbortController,setTimeoutFn:i=globalThis.setTimeout,clearTimeoutFn:a=globalThis.clearTimeout,directoryTimeoutMs:o}={}){const d=new Map;let l=1;return{display:{addLine(e){nexusclient.add_html_line(e)}},directory:t({fetchFn:e,AbortControllerCtor:r,setTimeoutFn:i,clearTimeoutFn:a,...void 0===o?{}:{timeoutMs:o}}),storage:{get(e){const t=n();return"function"==typeof t?.get?t.get(e):t?.vars?.[e]},set(e,t){const r=n();if("function"!=typeof r?.set){if(!r?.vars)throw new Error("insight4 storage.set failed — host variables expose neither set() nor a vars record");r.vars[e]=t}else r.set(e,t)},clear(e){const t=n();if("function"!=typeof t?.delete)if("function"!=typeof t?.set){if(!t?.vars)throw new Error("insight4 storage.clear failed — host variables expose neither delete()/set() nor a vars record");delete t.vars[e]}else t.set(e,void 0);else t.delete(e)}},triggers:{register(e,t,n){const r="insight4.trigger."+l++;return nexAction.triggers.add({id:r,tags:["insight4",`lifetime:${t}`],regex:e,action:n}),r},unregister(e){nexAction.triggers.remove(e)}},events:{onSkillMatch(e,t=null){if("undefined"==typeof nexSkills||!nexSkills)throw new Error("nexSkills is unavailable — insight cannot observe skill events");return s(t?`nexskill.match.skill.${t}`:"nexskill.match.skill",e)},on:s,raise(e,t){eventStream.raiseEvent(e,t)}},gmcp:{read:e=>String(e).split(".").reduce((e,t)=>null==e?e:e[t],GMCP)},text:{snapshot:()=>({lines:(nexusclient.current_block??[]).map(e=>({text:"string"==typeof e.line?"function"==typeof e.parsed_line?.text?e.parsed_line.text():e.line:null,isPrompt:!0===e.is_prompt,isHtml:Boolean(e.html_text)})),currentLineIndex:nexusclient.current_line?.index??-1})},clock:{now:()=>Date.now(),setTimer(e,t,n){const r=d.get(e);void 0!==r&&clearTimeout(r),d.set(e,setTimeout(()=>{d.delete(e),n()},t))},clearTimer(e){const t=d.get(e);void 0!==t&&(clearTimeout(t),d.delete(e))}}}}(),e);globalThis[Zl]=r}()}();
|