@cairnvibe/sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";(()=>{var It=Object.defineProperty;var Nt=(n,e)=>{for(var t in e)It(n,t,{get:e[t],enumerable:!0})};function He(){if(typeof document>"u"||typeof window>"u")return[];let n=document.querySelectorAll("[data-ai]"),e=[];return n.forEach(t=>{let r=t.getBoundingClientRect();if(!(r.bottom>0&&r.top<window.innerHeight&&r.right>0&&r.left<window.innerWidth))return;let a=t.getAttribute("data-ai");a&&e.push(a)}),e}function R(n,e){let t=e?.get(n);if(t)return t;if(typeof document>"u")return null;let r=document.querySelector(`[data-ai="${ze(n)}"]`);if(r)return r;let i=document.querySelector(`[aria-label="${ze(n)}"]`);if(i)return i;let a=document.querySelector(`[role="${ze(n)}"]`);if(a)return a;let o=document.querySelectorAll("button, a, [role='button'], input[type='submit'], input[type='button']"),c=$(n);for(let d of Array.from(o))if($(d.textContent??"")===c)return d;for(let d of Array.from(o))if($(d.textContent??"").includes(c))return d;return null}async function V(n,e,t=2,r=300){for(let i=0;i<t;i++){let a=R(n,e);if(a)return a;i<t-1&&await new Promise(o=>setTimeout(o,r))}return null}function O(n=100,e=200,t=1500){return new Promise(r=>{if(typeof document>"u"||typeof MutationObserver>"u"||!document.body){r();return}let i=!1,a=!1,o=null,c=()=>{i||(i=!0,d.disconnect(),o&&clearTimeout(o),clearTimeout(u),r())},d=new MutationObserver(()=>{a=!0,o&&clearTimeout(o),o=setTimeout(c,e)});d.observe(document.body,{childList:!0,subtree:!0,characterData:!0,attributes:!0});let u=setTimeout(c,t);setTimeout(()=>{a||c()},n)})}function M(n,e=4e3){n.scrollIntoView({behavior:"smooth",block:"center"}),n.classList.add("cairn-glow"),window.setTimeout(()=>n.classList.remove("cairn-glow"),e)}function st(n){return n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.tagName==="SELECT"}function Ze(n,e){if(!st(n))return!1;let r=(typeof window<"u"?{INPUT:window.HTMLInputElement,TEXTAREA:window.HTMLTextAreaElement,SELECT:window.HTMLSelectElement}:{})[n.tagName],i=r&&Object.getOwnPropertyDescriptor(r.prototype,"value")?.set;return i?i.call(n,e):n.value=e,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0})),!0}function Fe(n){let t=(st(n)?n.value:n.textContent??"").replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,499)}\u2026`:t||"(empty)"}function Ue(n,e){if(n.tagName==="SELECT"){let i=n,a=Array.from(i.options).find(o=>$(o.textContent??"")===$(e))??Array.from(i.options).find(o=>$(o.textContent??"").includes($(e)));return a?(i.value=a.value,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}let t=n.querySelectorAll('[role="option"], option, li, [role="menuitem"]'),r=Array.from(t).find(i=>$(i.textContent??"")===$(e))??Array.from(t).find(i=>$(i.textContent??"").includes($(e)));return r?(r.click(),!0):!1}function We(n,e,t=5){let r=n.getBoundingClientRect(),i=e.getBoundingClientRect(),a=r.left+r.width/2,o=r.top+r.height/2,c=i.left+i.width/2,d=i.top+i.height/2,u=(m,k,L,ee)=>{let Ce={bubbles:!0,cancelable:!0,clientX:L,clientY:ee,view:typeof window<"u"?window:void 0};typeof PointerEvent<"u"&&m.dispatchEvent(new PointerEvent(k.replace("mouse","pointer"),Ce)),m.dispatchEvent(new MouseEvent(k,Ce))};u(n,"mousedown",a,o);for(let m=1;m<=t;m++){let k=a+(c-a)*m/t,L=o+(d-o)*m/t;u(m===t?e:n,"mousemove",k,L)}u(e,"mouseup",c,d)}var Lt=new Set(["Enter","Tab"]);function qe(n,e){typeof n.focus=="function"&&n.focus();let t={bubbles:!0,cancelable:!0,key:e};n.dispatchEvent(new KeyboardEvent("keydown",t)),Lt.has(e)&&n.dispatchEvent(new KeyboardEvent("keypress",t)),n.dispatchEvent(new KeyboardEvent("keyup",t))}var at="cairn:misses",Bt=200;function w(n){try{let e=window.localStorage.getItem(at),t=e?JSON.parse(e):[];t.push({...n,at:new Date().toISOString()}),window.localStorage.setItem(at,JSON.stringify(t.slice(-Bt)))}catch{}}function $(n){return n.trim().toLowerCase().replace(/\s+/g," ")}function ze(n){return n.replace(/["\\]/g,"\\$&")}var s={};Nt(s,{BRAND:()=>cn,DIRTY:()=>ne,EMPTY_PATH:()=>Vt,INVALID:()=>g,NEVER:()=>Wn,OK:()=>C,ParseStatus:()=>S,Schema:()=>b,ZodAny:()=>X,ZodArray:()=>q,ZodBigInt:()=>ie,ZodBoolean:()=>ae,ZodBranded:()=>Me,ZodCatch:()=>ge,ZodDate:()=>se,ZodDefault:()=>me,ZodDiscriminatedUnion:()=>Le,ZodEffects:()=>P,ZodEnum:()=>pe,ZodError:()=>I,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>je,ZodIntersection:()=>de,ZodIssueCode:()=>l,ZodLazy:()=>ue,ZodLiteral:()=>he,ZodMap:()=>Te,ZodNaN:()=>Se,ZodNativeEnum:()=>fe,ZodNever:()=>D,ZodNull:()=>ce,ZodNullable:()=>Z,ZodNumber:()=>re,ZodObject:()=>N,ZodOptional:()=>B,ZodParsedType:()=>p,ZodPipeline:()=>Re,ZodPromise:()=>Q,ZodReadonly:()=>ye,ZodRecord:()=>Be,ZodSchema:()=>b,ZodSet:()=>Ee,ZodString:()=>K,ZodSymbol:()=>_e,ZodTransformer:()=>P,ZodTuple:()=>z,ZodType:()=>b,ZodUndefined:()=>oe,ZodUnion:()=>le,ZodUnknown:()=>W,ZodVoid:()=>we,addIssueToContext:()=>h,any:()=>yn,array:()=>kn,bigint:()=>hn,boolean:()=>yt,coerce:()=>Un,custom:()=>ft,date:()=>pn,datetimeRegex:()=>ht,defaultErrorMap:()=>F,discriminatedUnion:()=>En,effect:()=>Pn,enum:()=>Ln,function:()=>On,getErrorMap:()=>be,getParsedType:()=>H,instanceof:()=>dn,intersection:()=>Sn,isAborted:()=>Ie,isAsync:()=>xe,isDirty:()=>Ne,isValid:()=>J,late:()=>ln,lazy:()=>In,literal:()=>Nn,makeIssue:()=>Ae,map:()=>Mn,nan:()=>un,nativeEnum:()=>Bn,never:()=>bn,null:()=>gn,nullable:()=>Vn,number:()=>gt,object:()=>_n,objectUtil:()=>Ge,oboolean:()=>Fn,onumber:()=>Zn,optional:()=>$n,ostring:()=>zn,pipeline:()=>Hn,preprocess:()=>Dn,promise:()=>jn,quotelessJson:()=>jt,record:()=>An,set:()=>Rn,setErrorMap:()=>$t,strictObject:()=>wn,string:()=>mt,symbol:()=>fn,transformer:()=>Pn,tuple:()=>Cn,undefined:()=>mn,union:()=>Tn,unknown:()=>vn,util:()=>x,void:()=>xn});var x;(function(n){n.assertEqual=i=>{};function e(i){}n.assertIs=e;function t(i){throw new Error}n.assertNever=t,n.arrayToEnum=i=>{let a={};for(let o of i)a[o]=o;return a},n.getValidEnumValues=i=>{let a=n.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),o={};for(let c of a)o[c]=i[c];return n.objectValues(o)},n.objectValues=i=>n.objectKeys(i).map(function(a){return i[a]}),n.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},n.find=(i,a)=>{for(let o of i)if(a(o))return o},n.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}n.joinValues=r,n.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(x||(x={}));var Ge;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Ge||(Ge={}));var p=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),H=n=>{switch(typeof n){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(n)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(n)?p.array:n===null?p.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?p.promise:typeof Map<"u"&&n instanceof Map?p.map:typeof Set<"u"&&n instanceof Set?p.set:typeof Date<"u"&&n instanceof Date?p.date:p.object;default:return p.unknown}};var l=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),jt=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),I=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},r={_errors:[]},i=a=>{for(let o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let c=r,d=0;for(;d<o.path.length;){let u=o.path[d];d===o.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(o))):c[u]=c[u]||{_errors:[]},c=c[u],d++}}};return i(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];t[a]=t[a]||[],t[a].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};I.create=n=>new I(n);var Pt=(n,e)=>{let t;switch(n.code){case l.invalid_type:n.received===p.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case l.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,x.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(n.keys,", ")}`;break;case l.invalid_union:t="Invalid input";break;case l.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(n.options)}`;break;case l.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(n.options)}, received '${n.received}'`;break;case l.invalid_arguments:t="Invalid function arguments";break;case l.invalid_return_type:t="Invalid function return type";break;case l.invalid_date:t="Invalid date";break;case l.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:x.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case l.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case l.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case l.custom:t="Invalid input";break;case l.invalid_intersection_types:t="Intersection results could not be merged";break;case l.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case l.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(n)}return{message:t}},F=Pt;var ot=F;function $t(n){ot=n}function be(){return ot}var Ae=n=>{let{data:e,path:t,errorMaps:r,issueData:i}=n,a=[...t,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let c="",d=r.filter(u=>!!u).slice().reverse();for(let u of d)c=u(o,{data:e,defaultError:c}).message;return{...i,path:a,message:c}},Vt=[];function h(n,e){let t=be(),r=Ae({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===F?void 0:F].filter(i=>!!i)});n.common.issues.push(r)}var S=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let i of t){if(i.status==="aborted")return g;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let i of t){let a=await i.key,o=await i.value;r.push({key:a,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let i of t){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return g;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[a.value]=o.value)}return{status:e.value,value:r}}},g=Object.freeze({status:"aborted"}),ne=n=>({status:"dirty",value:n}),C=n=>({status:"valid",value:n}),Ie=n=>n.status==="aborted",Ne=n=>n.status==="dirty",J=n=>n.status==="valid",xe=n=>typeof Promise<"u"&&n instanceof Promise;var f;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(f||(f={}));var j=class{constructor(e,t,r,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ct=(n,e)=>{if(J(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new I(n.common.issues);return this._error=t,this._error}}};function v(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:i}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,c)=>{let{message:d}=n;return o.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:d??r??c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:d??t??c.defaultError}},description:i}}var b=class{get description(){return this._def.description}_getType(e){return H(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:H(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new S,ctx:{common:e.parent.common,data:e.data,parsedType:H(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(xe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:H(e)},i=this._parseSync({data:e,path:r.path,parent:r});return ct(r,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:H(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return J(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>J(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:H(e)},i=this._parse({data:e,path:r.path,parent:r}),a=await(xe(i)?i:Promise.resolve(i));return ct(r,a)}refine(e,t){let r=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,a)=>{let o=e(i),c=()=>a.addIssue({code:l.custom,...r(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(d=>d?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(e,t){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof t=="function"?t(r,i):t),!1))}_refinement(e){return new P({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return B.create(this,this._def)}nullable(){return Z.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return q.create(this)}promise(){return Q.create(this,this._def)}or(e){return le.create([this,e],this._def)}and(e){return de.create(this,e,this._def)}transform(e){return new P({...v(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new me({...v(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new Me({typeName:y.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ge({...v(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Re.create(this,e)}readonly(){return ye.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Dt=/^c[^\s-]{8,}$/i,Ht=/^[0-9a-z]+$/,zt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ft=/^[a-z0-9_-]{21}$/i,Ut=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Wt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,qt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Gt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ye,Yt=/^(?:(?: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])$/,Jt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Kt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Xt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Qt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,en=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dt="((\\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])))",tn=new RegExp(`^${dt}$`);function ut(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function nn(n){return new RegExp(`^${ut(n)}$`)}function ht(n){let e=`${dt}T${ut(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function rn(n,e){return!!((e==="v4"||!e)&&Yt.test(n)||(e==="v6"||!e)&&Kt.test(n))}function an(n,e){if(!Ut.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function sn(n,e){return!!((e==="v4"||!e)&&Jt.test(n)||(e==="v6"||!e)&&Xt.test(n))}var K=class n extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let a=this._getOrReturnCtx(e);return h(a,{code:l.invalid_type,expected:p.string,received:a.parsedType}),g}let r=new S,i;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,c=e.data.length<a.value;(o||c)&&(i=this._getOrReturnCtx(e,i),o?h(i,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):c&&h(i,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")qt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"email",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")Ye||(Ye=new RegExp(Gt,"u")),Ye.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"emoji",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")Zt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"uuid",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")Ft.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"nanoid",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")Dt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"cuid",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")Ht.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"cuid2",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")zt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"ulid",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),h(i,{validation:"url",code:l.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"regex",code:l.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?ht(a).test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?tn.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?nn(a).test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?Wt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"duration",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?rn(e.data,a.version)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"ip",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?an(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"jwt",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?sn(e.data,a.version)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"cidr",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?Qt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"base64",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?en.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"base64url",code:l.invalid_string,message:a.message}),r.dirty()):x.assertNever(a);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(i=>e.test(i),{validation:t,code:l.invalid_string,...f.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...f.errToObj(e)})}url(e){return this._addCheck({kind:"url",...f.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...f.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...f.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...f.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...f.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...f.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...f.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...f.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...f.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...f.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...f.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...f.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...f.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...f.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...f.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...f.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...f.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...f.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...f.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...f.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...f.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...f.errToObj(t)})}nonempty(e){return this.min(1,f.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};K.create=n=>new K({checks:[],typeName:y.ZodString,coerce:n?.coerce??!1,...v(n)});function on(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=t>r?t:r,a=Number.parseInt(n.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var re=class n extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==p.number){let a=this._getOrReturnCtx(e);return h(a,{code:l.invalid_type,expected:p.number,received:a.parsedType}),g}let r,i=new S;for(let a of this._def.checks)a.kind==="int"?x.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),h(r,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?on(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),h(r,{code:l.not_finite,message:a.message}),i.dirty()):x.assertNever(a);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,r,i){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:f.toString(i)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:f.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:f.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:f.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:f.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};re.create=n=>new re({checks:[],typeName:y.ZodNumber,coerce:n?.coerce||!1,...v(n)});var ie=class n extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==p.bigint)return this._getInvalidInput(e);let r,i=new S;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):x.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return h(t,{code:l.invalid_type,expected:p.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,r,i){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:f.toString(i)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};ie.create=n=>new ie({checks:[],typeName:y.ZodBigInt,coerce:n?.coerce??!1,...v(n)});var ae=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.boolean,received:r.parsedType}),g}return C(e.data)}};ae.create=n=>new ae({typeName:y.ZodBoolean,coerce:n?.coerce||!1,...v(n)});var se=class n extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let a=this._getOrReturnCtx(e);return h(a,{code:l.invalid_type,expected:p.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return h(a,{code:l.invalid_date}),g}let r=new S,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):x.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:f.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:f.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};se.create=n=>new se({checks:[],coerce:n?.coerce||!1,typeName:y.ZodDate,...v(n)});var _e=class extends b{_parse(e){if(this._getType(e)!==p.symbol){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.symbol,received:r.parsedType}),g}return C(e.data)}};_e.create=n=>new _e({typeName:y.ZodSymbol,...v(n)});var oe=class extends b{_parse(e){if(this._getType(e)!==p.undefined){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.undefined,received:r.parsedType}),g}return C(e.data)}};oe.create=n=>new oe({typeName:y.ZodUndefined,...v(n)});var ce=class extends b{_parse(e){if(this._getType(e)!==p.null){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.null,received:r.parsedType}),g}return C(e.data)}};ce.create=n=>new ce({typeName:y.ZodNull,...v(n)});var X=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return C(e.data)}};X.create=n=>new X({typeName:y.ZodAny,...v(n)});var W=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return C(e.data)}};W.create=n=>new W({typeName:y.ZodUnknown,...v(n)});var D=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return h(t,{code:l.invalid_type,expected:p.never,received:t.parsedType}),g}};D.create=n=>new D({typeName:y.ZodNever,...v(n)});var we=class extends b{_parse(e){if(this._getType(e)!==p.undefined){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.void,received:r.parsedType}),g}return C(e.data)}};we.create=n=>new we({typeName:y.ZodVoid,...v(n)});var q=class n extends b{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),i=this._def;if(t.parsedType!==p.array)return h(t,{code:l.invalid_type,expected:p.array,received:t.parsedType}),g;if(i.exactLength!==null){let o=t.data.length>i.exactLength.value,c=t.data.length<i.exactLength.value;(o||c)&&(h(t,{code:o?l.too_big:l.too_small,minimum:c?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&t.data.length<i.minLength.value&&(h(t,{code:l.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&(h(t,{code:l.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,c)=>i.type._parseAsync(new j(t,o,t.path,c)))).then(o=>S.mergeArray(r,o));let a=[...t.data].map((o,c)=>i.type._parseSync(new j(t,o,t.path,c)));return S.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:f.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:f.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:f.toString(t)}})}nonempty(e){return this.min(1,e)}};q.create=(n,e)=>new q({type:n,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...v(e)});function ke(n){if(n instanceof N){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=B.create(ke(r))}return new N({...n._def,shape:()=>e})}else return n instanceof q?new q({...n._def,type:ke(n.element)}):n instanceof B?B.create(ke(n.unwrap())):n instanceof Z?Z.create(ke(n.unwrap())):n instanceof z?z.create(n.items.map(e=>ke(e))):n}var N=class n extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==p.object){let u=this._getOrReturnCtx(e);return h(u,{code:l.invalid_type,expected:p.object,received:u.parsedType}),g}let{status:r,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof D&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||c.push(u);let d=[];for(let u of o){let m=a[u],k=i.data[u];d.push({key:{status:"valid",value:u},value:m._parse(new j(i,k,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof D){let u=this._def.unknownKeys;if(u==="passthrough")for(let m of c)d.push({key:{status:"valid",value:m},value:{status:"valid",value:i.data[m]}});else if(u==="strict")c.length>0&&(h(i,{code:l.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let m of c){let k=i.data[m];d.push({key:{status:"valid",value:m},value:u._parse(new j(i,k,i.path,m)),alwaysSet:m in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let m of d){let k=await m.key,L=await m.value;u.push({key:k,value:L,alwaysSet:m.alwaysSet})}return u}).then(u=>S.mergeObjectSync(r,u)):S.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return f.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let i=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:f.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of x.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of x.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return ke(this)}partial(e){let t={};for(let r of x.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?t[r]=i:t[r]=i.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of x.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof B;)a=a._def.innerType;t[r]=a}return new n({...this._def,shape:()=>t})}keyof(){return pt(x.objectKeys(this.shape))}};N.create=(n,e)=>new N({shape:()=>n,unknownKeys:"strip",catchall:D.create(),typeName:y.ZodObject,...v(e)});N.strictCreate=(n,e)=>new N({shape:()=>n,unknownKeys:"strict",catchall:D.create(),typeName:y.ZodObject,...v(e)});N.lazycreate=(n,e)=>new N({shape:n,unknownKeys:"strip",catchall:D.create(),typeName:y.ZodObject,...v(e)});var le=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function i(a){for(let c of a)if(c.result.status==="valid")return c.result;for(let c of a)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let o=a.map(c=>new I(c.ctx.common.issues));return h(t,{code:l.invalid_union,unionErrors:o}),g}if(t.common.async)return Promise.all(r.map(async a=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(i);{let a,o=[];for(let d of r){let u={...t,common:{...t.common,issues:[]},parent:null},m=d._parseSync({data:t.data,path:t.path,parent:u});if(m.status==="valid")return m;m.status==="dirty"&&!a&&(a={result:m,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let c=o.map(d=>new I(d));return h(t,{code:l.invalid_union,unionErrors:c}),g}}get options(){return this._def.options}};le.create=(n,e)=>new le({options:n,typeName:y.ZodUnion,...v(e)});var U=n=>n instanceof ue?U(n.schema):n instanceof P?U(n.innerType()):n instanceof he?[n.value]:n instanceof pe?n.options:n instanceof fe?x.objectValues(n.enum):n instanceof me?U(n._def.innerType):n instanceof oe?[void 0]:n instanceof ce?[null]:n instanceof B?[void 0,...U(n.unwrap())]:n instanceof Z?[null,...U(n.unwrap())]:n instanceof Me||n instanceof ye?U(n.unwrap()):n instanceof ge?U(n._def.innerType):[],Le=class n extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.object)return h(t,{code:l.invalid_type,expected:p.object,received:t.parsedType}),g;let r=this.discriminator,i=t.data[r],a=this.optionsMap.get(i);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let i=new Map;for(let a of t){let o=U(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of o){if(i.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);i.set(c,a)}}return new n({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...v(r)})}};function Je(n,e){let t=H(n),r=H(e);if(n===e)return{valid:!0,data:n};if(t===p.object&&r===p.object){let i=x.objectKeys(e),a=x.objectKeys(n).filter(c=>i.indexOf(c)!==-1),o={...n,...e};for(let c of a){let d=Je(n[c],e[c]);if(!d.valid)return{valid:!1};o[c]=d.data}return{valid:!0,data:o}}else if(t===p.array&&r===p.array){if(n.length!==e.length)return{valid:!1};let i=[];for(let a=0;a<n.length;a++){let o=n[a],c=e[a],d=Je(o,c);if(!d.valid)return{valid:!1};i.push(d.data)}return{valid:!0,data:i}}else return t===p.date&&r===p.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var de=class extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=(a,o)=>{if(Ie(a)||Ie(o))return g;let c=Je(a.value,o.value);return c.valid?((Ne(a)||Ne(o))&&t.dirty(),{status:t.value,value:c.data}):(h(r,{code:l.invalid_intersection_types}),g)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,o])=>i(a,o)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};de.create=(n,e,t)=>new de({left:n,right:e,typeName:y.ZodIntersection,...v(t)});var z=class n extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.array)return h(r,{code:l.invalid_type,expected:p.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return h(r,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&r.data.length>this._def.items.length&&(h(r,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((o,c)=>{let d=this._def.items[c]||this._def.rest;return d?d._parse(new j(r,o,r.path,c)):null}).filter(o=>!!o);return r.common.async?Promise.all(a).then(o=>S.mergeArray(t,o)):S.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};z.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new z({items:n,typeName:y.ZodTuple,rest:null,...v(e)})};var Be=class n extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return h(r,{code:l.invalid_type,expected:p.object,received:r.parsedType}),g;let i=[],a=this._def.keyType,o=this._def.valueType;for(let c in r.data)i.push({key:a._parse(new j(r,c,r.path,c)),value:o._parse(new j(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?S.mergeObjectAsync(t,i):S.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof b?new n({keyType:e,valueType:t,typeName:y.ZodRecord,...v(r)}):new n({keyType:K.create(),valueType:e,typeName:y.ZodRecord,...v(t)})}},Te=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.map)return h(r,{code:l.invalid_type,expected:p.map,received:r.parsedType}),g;let i=this._def.keyType,a=this._def.valueType,o=[...r.data.entries()].map(([c,d],u)=>({key:i._parse(new j(r,c,r.path,[u,"key"])),value:a._parse(new j(r,d,r.path,[u,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let d of o){let u=await d.key,m=await d.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&t.dirty(),c.set(u.value,m.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let d of o){let u=d.key,m=d.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&t.dirty(),c.set(u.value,m.value)}return{status:t.value,value:c}}}};Te.create=(n,e,t)=>new Te({valueType:e,keyType:n,typeName:y.ZodMap,...v(t)});var Ee=class n extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.set)return h(r,{code:l.invalid_type,expected:p.set,received:r.parsedType}),g;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(h(r,{code:l.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(h(r,{code:l.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let a=this._def.valueType;function o(d){let u=new Set;for(let m of d){if(m.status==="aborted")return g;m.status==="dirty"&&t.dirty(),u.add(m.value)}return{status:t.value,value:u}}let c=[...r.data.values()].map((d,u)=>a._parse(new j(r,d,r.path,u)));return r.common.async?Promise.all(c).then(d=>o(d)):o(c)}min(e,t){return new n({...this._def,minSize:{value:e,message:f.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:f.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Ee.create=(n,e)=>new Ee({valueType:n,minSize:null,maxSize:null,typeName:y.ZodSet,...v(e)});var je=class n extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.function)return h(t,{code:l.invalid_type,expected:p.function,received:t.parsedType}),g;function r(c,d){return Ae({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,be(),F].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:d}})}function i(c,d){return Ae({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,be(),F].filter(u=>!!u),issueData:{code:l.invalid_return_type,returnTypeError:d}})}let a={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Q){let c=this;return C(async function(...d){let u=new I([]),m=await c._def.args.parseAsync(d,a).catch(ee=>{throw u.addIssue(r(d,ee)),u}),k=await Reflect.apply(o,this,m);return await c._def.returns._def.type.parseAsync(k,a).catch(ee=>{throw u.addIssue(i(k,ee)),u})})}else{let c=this;return C(function(...d){let u=c._def.args.safeParse(d,a);if(!u.success)throw new I([r(d,u.error)]);let m=Reflect.apply(o,this,u.data),k=c._def.returns.safeParse(m,a);if(!k.success)throw new I([i(m,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:z.create(e).rest(W.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||z.create([]).rest(W.create()),returns:t||W.create(),typeName:y.ZodFunction,...v(r)})}},ue=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ue.create=(n,e)=>new ue({getter:n,typeName:y.ZodLazy,...v(e)});var he=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:l.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};he.create=(n,e)=>new he({value:n,typeName:y.ZodLiteral,...v(e)});function pt(n,e){return new pe({values:n,typeName:y.ZodEnum,...v(e)})}var pe=class n extends b{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return h(t,{expected:x.joinValues(r),received:t.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return h(t,{received:t.data,code:l.invalid_enum_value,options:r}),g}return C(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};pe.create=pt;var fe=class extends b{_parse(e){let t=x.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==p.string&&r.parsedType!==p.number){let i=x.objectValues(t);return h(r,{expected:x.joinValues(i),received:r.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=x.objectValues(t);return h(r,{received:r.data,code:l.invalid_enum_value,options:i}),g}return C(e.data)}get enum(){return this._def.values}};fe.create=(n,e)=>new fe({values:n,typeName:y.ZodNativeEnum,...v(e)});var Q=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.promise&&t.common.async===!1)return h(t,{code:l.invalid_type,expected:p.promise,received:t.parsedType}),g;let r=t.parsedType===p.promise?t.data:Promise.resolve(t.data);return C(r.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Q.create=(n,e)=>new Q({type:n,typeName:y.ZodPromise,...v(e)});var P=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{h(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(r.data,a);if(r.common.async)return Promise.resolve(o).then(async c=>{if(t.value==="aborted")return g;let d=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return d.status==="aborted"?g:d.status==="dirty"?ne(d.value):t.value==="dirty"?ne(d.value):d});{if(t.value==="aborted")return g;let c=this._def.schema._parseSync({data:o,path:r.path,parent:r});return c.status==="aborted"?g:c.status==="dirty"?ne(c.value):t.value==="dirty"?ne(c.value):c}}if(i.type==="refinement"){let o=c=>{let d=i.refinement(c,a);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?g:(c.status==="dirty"&&t.dirty(),o(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?g:(c.status==="dirty"&&t.dirty(),o(c.value).then(()=>({status:t.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!J(o))return g;let c=i.transform(o.value,a);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>J(o)?Promise.resolve(i.transform(o.value,a)).then(c=>({status:t.value,value:c})):g);x.assertNever(i)}};P.create=(n,e,t)=>new P({schema:n,typeName:y.ZodEffects,effect:e,...v(t)});P.createWithPreprocess=(n,e,t)=>new P({schema:e,effect:{type:"preprocess",transform:n},typeName:y.ZodEffects,...v(t)});var B=class extends b{_parse(e){return this._getType(e)===p.undefined?C(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};B.create=(n,e)=>new B({innerType:n,typeName:y.ZodOptional,...v(e)});var Z=class extends b{_parse(e){return this._getType(e)===p.null?C(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Z.create=(n,e)=>new Z({innerType:n,typeName:y.ZodNullable,...v(e)});var me=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===p.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};me.create=(n,e)=>new me({innerType:n,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var ge=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return xe(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new I(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new I(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ge.create=(n,e)=>new ge({innerType:n,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var Se=class extends b{_parse(e){if(this._getType(e)!==p.nan){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.nan,received:r.parsedType}),g}return{status:"valid",value:e.data}}};Se.create=n=>new Se({typeName:y.ZodNaN,...v(n)});var cn=Symbol("zod_brand"),Me=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},Re=class n extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?g:a.status==="dirty"?(t.dirty(),ne(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?g:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:y.ZodPipeline})}},ye=class extends b{_parse(e){let t=this._def.innerType._parse(e),r=i=>(J(i)&&(i.value=Object.freeze(i.value)),i);return xe(t)?t.then(i=>r(i)):r(t)}unwrap(){return this._def.innerType}};ye.create=(n,e)=>new ye({innerType:n,typeName:y.ZodReadonly,...v(e)});function lt(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function ft(n,e={},t){return n?X.create().superRefine((r,i)=>{let a=n(r);if(a instanceof Promise)return a.then(o=>{if(!o){let c=lt(e,r),d=c.fatal??t??!0;i.addIssue({code:"custom",...c,fatal:d})}});if(!a){let o=lt(e,r),c=o.fatal??t??!0;i.addIssue({code:"custom",...o,fatal:c})}}):X.create()}var ln={object:N.lazycreate},y;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(y||(y={}));var dn=(n,e={message:`Input not instance of ${n.name}`})=>ft(t=>t instanceof n,e),mt=K.create,gt=re.create,un=Se.create,hn=ie.create,yt=ae.create,pn=se.create,fn=_e.create,mn=oe.create,gn=ce.create,yn=X.create,vn=W.create,bn=D.create,xn=we.create,kn=q.create,_n=N.create,wn=N.strictCreate,Tn=le.create,En=Le.create,Sn=de.create,Cn=z.create,An=Be.create,Mn=Te.create,Rn=Ee.create,On=je.create,In=ue.create,Nn=he.create,Ln=pe.create,Bn=fe.create,jn=Q.create,Pn=P.create,$n=B.create,Vn=Z.create,Dn=P.createWithPreprocess,Hn=Re.create,zn=()=>mt().optional(),Zn=()=>gt().optional(),Fn=()=>yt().optional(),Un={string:n=>K.create({...n,coerce:!0}),number:n=>re.create({...n,coerce:!0}),boolean:n=>ae.create({...n,coerce:!0}),bigint:n=>ie.create({...n,coerce:!0}),date:n=>se.create({...n,coerce:!0})};var Wn=g;var qn=["pending","in_progress","done","failed","skipped"],Gn=s.object({id:s.string(),description:s.string().min(1),doneContract:s.string().min(1),status:s.enum(qn)}).strict(),oi=s.object({version:s.number().int().min(1),goal:s.string().min(1),facts:s.array(s.string()),tasks:s.array(Gn).min(1)}).strict(),ci=s.object({planVersion:s.number().int().min(1),currentTaskIndex:s.number().int().min(0),stallCount:s.number().int().min(0)}).strict(),Yn=s.object({id:s.string(),description:s.string().min(1),doneContract:s.string().min(1)}).strict(),li=s.object({goal:s.string().min(1),facts:s.array(s.string()),tasks:s.array(Yn).min(1)}).strict(),Jn=["continue","task_complete","replan","give_up"],di=s.object({verdict:s.enum(Jn),expected:s.string().optional(),actual:s.string().optional(),learnedFact:s.string().optional(),reasoning:s.string().min(1)}).strict();var mi=s.object({id:s.string().min(1),name:s.string().min(1),description:s.string().min(1),instructions:s.string().min(1),pattern:s.string().optional(),createdAt:s.string()}).strict();var bt=s.object({method:s.enum(["POST","PUT","PATCH","DELETE"]),url:s.string(),handledBy:s.array(s.string()).optional(),constraints:s.array(s.string()).optional()}),Kn=s.object({id:s.string(),label:s.string(),selector:s.string(),fallbacks:s.array(s.string()),does:s.string(),confidence:s.number().min(0).max(1),evidence:s.array(s.string()),apiCall:bt.nullable().optional()}),Xn=s.object({name:s.string(),type:s.string(),optional:s.boolean()}),Qn=s.object({name:s.string(),fields:s.array(Xn),source:s.string()}),er=s.object({tag:s.enum(["h1","h2","h3","h4","h5","h6","p"]),text:s.string(),file:s.string(),line:s.number()}),tr=s.object({id:s.string(),route:s.string(),file:s.string(),title:s.string(),purpose:s.string(),whenToUse:s.string(),confidence:s.number().min(0).max(1),elements:s.array(Kn),dataShapes:s.array(Qn).optional(),inAppCopy:s.array(er).optional()}),nr=s.object({candidates:s.array(s.string()),chose:s.string(),reason:s.string(),confidence:s.number().min(0).max(1)}),vi=s.object({version:s.literal("1"),commit:s.string(),generatedAt:s.string(),pages:s.array(tr),dead:s.array(s.string()),conflicts:s.array(nr)}),E=()=>s.preprocess(n=>n===null?void 0:n,s.string().optional()),rr=()=>s.preprocess(n=>n===null?void 0:n,bt.optional()),xt=()=>s.preprocess(n=>n===null?void 0:n,s.boolean().optional()),Pe=()=>s.preprocess(n=>n===null?void 0:n,s.record(s.string(),s.unknown()).optional()),vt=()=>s.preprocess(n=>n===null?void 0:n,s.array(s.unknown()).optional()),A={text:E(),target:E(),route:E(),action:E(),value:E(),name:E(),args:Pe(),steps:vt(),actions:vt(),continueAfter:xt(),to:E(),key:E()},G={target:E(),value:E(),name:E(),args:Pe(),to:E(),key:E()},ir=s.discriminatedUnion("verb",[s.object({...G,verb:s.literal("click"),target:s.string().min(1)}).strict(),s.object({...G,verb:s.literal("fill"),target:s.string().min(1),value:s.string()}).strict(),s.object({...G,verb:s.literal("read"),target:s.string().min(1)}).strict(),s.object({...G,verb:s.literal("call_tool"),name:s.string().min(1),args:Pe()}).strict(),s.object({...G,verb:s.literal("drag"),target:s.string().min(1),to:s.string().min(1)}).strict(),s.object({...G,verb:s.literal("select"),target:s.string().min(1),value:s.string().min(1)}).strict(),s.object({...G,verb:s.literal("key"),target:E(),key:s.string().min(1)}).strict(),s.object({...G,verb:s.literal("scroll"),target:s.string().min(1)}).strict(),s.object({...G,verb:s.literal("wait_for"),target:s.string().min(1)}).strict()]),Ke=s.discriminatedUnion("verb",[s.object({...A,verb:s.literal("explain"),text:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("highlight"),target:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("open"),target:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("navigate"),route:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("do"),action:s.string().min(1),target:E(),apiCall:rr()}).strict(),s.object({...A,verb:s.literal("tour"),steps:s.array(s.object({text:s.string().min(1),target:E(),route:E(),click:xt()}).strict()).min(2).max(6)}).strict(),s.object({...A,verb:s.literal("click"),target:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("fill"),target:s.string().min(1),value:s.string()}).strict(),s.object({...A,verb:s.literal("read"),target:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("call_tool"),name:s.string().min(1),args:Pe()}).strict(),s.object({...A,verb:s.literal("drag"),target:s.string().min(1),to:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("select"),target:s.string().min(1),value:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("key"),target:E(),key:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("scroll"),target:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("wait_for"),target:s.string().min(1)}).strict(),s.object({...A,verb:s.literal("batch"),actions:s.array(ir).min(2).max(5)}).strict()]);var ar=s.object({role:s.enum(["user","assistant"]),text:s.string()}),sr=s.object({id:s.string().max(200),role:s.string().max(50),label:s.string().max(120)}),or=["safe","confirm"],cr=s.object({name:s.string().max(200),description:s.string().max(500),inputSchema:s.record(s.string(),s.unknown()).optional(),riskTier:s.enum(or).optional()}),bi=s.object({route:s.string(),question:s.string().min(1),visible:s.array(s.string()),history:s.array(ar).optional(),liveElements:s.array(sr).max(60).optional(),webMcpTools:s.array(cr).max(30).optional(),scopeId:s.string().optional()});var xi=s.discriminatedUnion("type",[s.object({type:s.literal("act"),verb:Ke,at:s.number()}),s.object({type:s.literal("obs"),observation:s.string(),ok:s.boolean(),at:s.number()}),s.object({type:s.literal("thk"),text:s.string(),at:s.number()}),s.object({type:s.literal("inj"),text:s.string(),at:s.number()})]);function lr(){return typeof document>"u"?null:document.modelContext??null}async function Xe(n,e,t){let r=lr();if(!r?.getTools||!r.executeTool)return{ok:!1,observation:"This page no longer has that tool available."};try{let i=await r.getTools(),a=Array.isArray(i)?i.find(d=>d.name===n):void 0;if(!a)return{ok:!1,observation:`No tool named "${n}" is available on this page right now.`};if(a.riskTier==="confirm"&&!(t?await t({name:a.name,description:a.description??""}):!1))return{ok:!1,observation:"This action needs the user's real confirmation before it can run, and it wasn't confirmed."};let o=await r.executeTool(a,e??{});return{ok:!0,observation:(typeof o=="string"?o:JSON.stringify(o??null)).slice(0,2e3)}}catch(i){return{ok:!1,observation:`That tool failed: ${i instanceof Error?i.message:"unknown error"}`}}}var kt=6,_t=500;var dr="I'm not sure \u2014 I couldn't understand that response. Try rephrasing your question.";function wt(n,e,t){let r=Ke.safeParse(n);if(!r.success){t.onExplain(dr);return}ur(r.data,e,t)}function ur(n,e,t){switch(n.verb){case"explain":t.onExplain(n.text);return;case"highlight":case"open":{let r=R(n.target,t.liveElements);if(!r){(t.onMiss??w)({attempted:n.target,route:e}),t.onExplain(n.text??"I know what you need, but I can't find it on this page right now.");return}M(r),n.verb==="open"&&r.click(),n.text&&t.onExplain(n.text);return}case"navigate":{if(n.continueAfter&&t.onToolStep){n.text&&t.onExplain(n.text),t.onNavigate?.(n.route),O(300,200,2e3).then(()=>{t.onToolStep?.({verb:"navigate",target:n.route,ok:!0,observation:`Navigated to ${n.route}.`})});return}t.onNavigate?.(n.route),n.text&&t.onExplain(n.text);return}case"do":{if((t.registeredActions??[]).includes(n.action)){t.onDo?.(n.action,n.target),n.text&&t.onExplain(n.text);return}if(n.target||n.apiCall){let i=n.target?R(n.target,t.liveElements):null;if(i){M(i),i.click(),n.text&&t.onExplain(n.text);return}if(n.target&&(t.onMiss??w)({attempted:n.target,route:e}),n.apiCall){n.text&&t.onExplain(n.text),fr(n.apiCall).then(a=>{a.ok||t.onExplain("I tried to do that, but something went wrong \u2014 try again in a moment.")});return}}t.onExplain(n.text??"That action isn't available here.");return}case"tour":t.onTour?t.onTour(n.steps):t.onExplain(n.steps.map(r=>r.text).join(" "));return;case"click":{n.text&&t.onExplain(n.text);let r=R(n.target,t.liveElements);if(!r){(t.onMiss??w)({attempted:n.target,route:e}),t.onToolStep?.({verb:"click",target:n.target,ok:!1,observation:"Could not find that element on the page."});return}M(r),r.click(),O().then(()=>{t.onToolStep?.({verb:"click",target:n.target,ok:!0,observation:"Clicked it."})});return}case"fill":{n.text&&t.onExplain(n.text);let r=R(n.target,t.liveElements);if(!r||!Ze(r,n.value)){(t.onMiss??w)({attempted:n.target,route:e}),t.onToolStep?.({verb:"fill",target:n.target,ok:!1,observation:r?"That element isn't a real form field \u2014 can't type into it.":"Could not find that element on the page."});return}M(r),O().then(()=>{t.onToolStep?.({verb:"fill",target:n.target,ok:!0,observation:`Typed "${n.value}" into it.`})});return}case"read":{n.text&&t.onExplain(n.text);let r=R(n.target,t.liveElements);if(!r){(t.onMiss??w)({attempted:n.target,route:e}),t.onToolStep?.({verb:"read",target:n.target,ok:!1,observation:"Could not find that element on the page."});return}t.onToolStep?.({verb:"read",target:n.target,ok:!0,observation:Fe(r)});return}case"call_tool":{n.text&&t.onExplain(n.text),Xe(n.name,n.args,t.onConfirmTool).then(r=>{t.onToolStep?.({verb:"call_tool",target:n.name,ok:r.ok,observation:r.observation})});return}case"drag":{n.text&&t.onExplain(n.text);let r=R(n.target,t.liveElements),i=r?R(n.to,t.liveElements):null;if(!r||!i){(t.onMiss??w)({attempted:r?n.to:n.target,route:e}),t.onToolStep?.({verb:"drag",target:n.target,ok:!1,observation:r?"Could not find the drop destination on the page.":"Could not find that element on the page."});return}M(r),We(r,i),O().then(()=>{t.onToolStep?.({verb:"drag",target:n.target,ok:!0,observation:`Dragged it to ${n.to}.`})});return}case"select":{n.text&&t.onExplain(n.text);let r=R(n.target,t.liveElements);if(!r||!Ue(r,n.value)){(t.onMiss??w)({attempted:n.target,route:e}),t.onToolStep?.({verb:"select",target:n.target,ok:!1,observation:r?`Could not find an option matching "${n.value}".`:"Could not find that element on the page."});return}M(r),O().then(()=>{t.onToolStep?.({verb:"select",target:n.target,ok:!0,observation:`Selected "${n.value}".`})});return}case"key":{n.text&&t.onExplain(n.text);let r=n.target?R(n.target,t.liveElements):document.activeElement;if(!r){n.target&&(t.onMiss??w)({attempted:n.target,route:e}),t.onToolStep?.({verb:"key",target:n.target,ok:!1,observation:"Could not find that element on the page."});return}qe(r,n.key),O().then(()=>{t.onToolStep?.({verb:"key",target:n.target,ok:!0,observation:`Pressed ${n.key}.`})});return}case"scroll":{n.text&&t.onExplain(n.text);let r=R(n.target,t.liveElements);if(!r){(t.onMiss??w)({attempted:n.target,route:e}),t.onToolStep?.({verb:"scroll",target:n.target,ok:!1,observation:"Could not find that element on the page."});return}M(r),O().then(()=>{t.onToolStep?.({verb:"scroll",target:n.target,ok:!0,observation:"Scrolled it into view."})});return}case"wait_for":{n.text&&t.onExplain(n.text),V(n.target,t.liveElements,kt,_t).then(r=>{if(!r){(t.onMiss??w)({attempted:n.target,route:e}),t.onToolStep?.({verb:"wait_for",target:n.target,ok:!1,observation:"It never appeared."});return}t.onToolStep?.({verb:"wait_for",target:n.target,ok:!0,observation:"It appeared."})});return}case"batch":{n.text&&t.onExplain(n.text),hr(n.actions,e,t).then(r=>{t.onToolStep?.({verb:"batch",ok:r.ok,observation:r.observation})});return}}}async function hr(n,e,t){let r=[];for(let i of n){let a=await pr(i,e,t),o="target"in i&&i.target||"name"in i&&i.name||"(focused element)";if(r.push(`${i.verb} ${o}: ${a.observation}`),!a.ok)return{ok:!1,observation:r.join(" | ")}}return{ok:!0,observation:r.join(" | ")}}async function pr(n,e,t){switch(n.verb){case"click":{let r=await V(n.target,t.liveElements);return r?(M(r),r.click(),await O(),{ok:!0,observation:"Clicked it."}):((t.onMiss??w)({attempted:n.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"fill":{let r=await V(n.target,t.liveElements);return!r||!Ze(r,n.value)?((t.onMiss??w)({attempted:n.target,route:e}),{ok:!1,observation:r?"That element isn't a real form field \u2014 can't type into it.":"Could not find that element on the page."}):(M(r),await O(),{ok:!0,observation:`Typed "${n.value}" into it.`})}case"read":{let r=await V(n.target,t.liveElements);return r?{ok:!0,observation:Fe(r)}:((t.onMiss??w)({attempted:n.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"call_tool":{let r=await Xe(n.name,n.args,t.onConfirmTool);return{ok:r.ok,observation:r.observation}}case"drag":{let r=await V(n.target,t.liveElements),i=r?await V(n.to,t.liveElements):null;return!r||!i?((t.onMiss??w)({attempted:r?n.to:n.target,route:e}),{ok:!1,observation:r?"Could not find the drop destination on the page.":"Could not find that element on the page."}):(M(r),We(r,i),await O(),{ok:!0,observation:`Dragged it to ${n.to}.`})}case"select":{let r=await V(n.target,t.liveElements);return!r||!Ue(r,n.value)?((t.onMiss??w)({attempted:n.target,route:e}),{ok:!1,observation:r?`Could not find an option matching "${n.value}".`:"Could not find that element on the page."}):(M(r),await O(),{ok:!0,observation:`Selected "${n.value}".`})}case"key":{let r=n.target?await V(n.target,t.liveElements):document.activeElement;return r?(qe(r,n.key),await O(),{ok:!0,observation:`Pressed ${n.key}.`}):(n.target&&(t.onMiss??w)({attempted:n.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"scroll":{let r=await V(n.target,t.liveElements);return r?(M(r),await O(),{ok:!0,observation:"Scrolled it into view."}):((t.onMiss??w)({attempted:n.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"wait_for":return await V(n.target,t.liveElements,kt,_t)?{ok:!0,observation:"It appeared."}:((t.onMiss??w)({attempted:n.target,route:e}),{ok:!1,observation:"It never appeared."})}}async function fr(n){try{let e=await fetch(n.url,{method:n.method,credentials:"same-origin"});return{ok:e.ok,status:e.status}}catch{return{ok:!1}}}function mr(n){if(n.length===0)return 0;let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return Math.sqrt(e/n.length)}function gr(n){if(n.length<2)return 0;let e=0;for(let t=1;t<n.length;t++)n[t]>=0!=n[t-1]>=0&&e++;return e/(n.length-1)}function Tt(){let n=0;return{process(e){let t=mr(e),r=gr(e),i=Math.max(.02,n*3),a=t>i&&r>=.003&&r<=.4;return a||(n=n*(1-.05)+t*.05),{isSpeech:a,rms:t,zcr:r,noiseFloor:n}},reset(){n=0}}}var yr=200;function Et(n=yr){let e=0,t=!1;return{update(r,i){return r.isSpeech?(e+=i,t||e<n?!1:(t=!0,!0)):(e=0,t=!1,!1)},reset(){e=0,t=!1}}}var vr={idle:"",asking:"Thinking\u2026",recording:"Listening \u2014 transcribing live\u2026","rt-connecting":"Connecting\u2026","rt-listening":"Listening\u2026","rt-thinking":"Thinking\u2026","rt-speaking":"Speaking\u2026"},br=8,xr=`
1
+ "use strict";(()=>{var Pt=Object.defineProperty;var $t=(t,e)=>{for(var n in e)Pt(t,n,{get:e[n],enumerable:!0})};function Fe(){if(typeof document>"u"||typeof window>"u")return[];let t=document.querySelectorAll("[data-ai]"),e=[];return t.forEach(n=>{let r=n.getBoundingClientRect();if(!(r.bottom>0&&r.top<window.innerHeight&&r.right>0&&r.left<window.innerWidth))return;let a=n.getAttribute("data-ai");a&&e.push(a)}),e}function O(t,e){let n=e?.get(t);if(n)return n;if(typeof document>"u")return null;let r=document.querySelector(`[data-ai="${Ue(t)}"]`);if(r)return r;let i=document.querySelector(`[aria-label="${Ue(t)}"]`);if(i)return i;let a=document.querySelector(`[role="${Ue(t)}"]`);if(a)return a;let o=document.querySelectorAll("button, a, [role='button'], input[type='submit'], input[type='button']"),c=V(t);for(let d of Array.from(o))if(V(d.textContent??"")===c)return d;for(let d of Array.from(o))if(V(d.textContent??"").includes(c))return d;return null}async function D(t,e,n=2,r=300){for(let i=0;i<n;i++){let a=O(t,e);if(a)return a;i<n-1&&await new Promise(o=>setTimeout(o,r))}return null}function I(t=100,e=200,n=1500){return new Promise(r=>{if(typeof document>"u"||typeof MutationObserver>"u"||!document.body){r();return}let i=!1,a=!1,o=null,c=()=>{i||(i=!0,d.disconnect(),o&&clearTimeout(o),clearTimeout(u),r())},d=new MutationObserver(()=>{a=!0,o&&clearTimeout(o),o=setTimeout(c,e)});d.observe(document.body,{childList:!0,subtree:!0,characterData:!0,attributes:!0});let u=setTimeout(c,n);setTimeout(()=>{a||c()},t)})}function R(t,e=4e3){t.scrollIntoView({behavior:"smooth",block:"center"}),t.classList.add("cairn-glow"),window.setTimeout(()=>t.classList.remove("cairn-glow"),e)}function ut(t){return t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"}function We(t,e){if(!ut(t))return!1;let r=(typeof window<"u"?{INPUT:window.HTMLInputElement,TEXTAREA:window.HTMLTextAreaElement,SELECT:window.HTMLSelectElement}:{})[t.tagName],i=r&&Object.getOwnPropertyDescriptor(r.prototype,"value")?.set;return i?i.call(t,e):t.value=e,t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),!0}function qe(t){let n=(ut(t)?t.value:t.textContent??"").replace(/\s+/g," ").trim();return n.length>500?`${n.slice(0,499)}\u2026`:n||"(empty)"}function Ge(t,e){if(t.tagName==="SELECT"){let i=t,a=Array.from(i.options).find(o=>V(o.textContent??"")===V(e))??Array.from(i.options).find(o=>V(o.textContent??"").includes(V(e)));return a?(i.value=a.value,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}let n=t.querySelectorAll('[role="option"], option, li, [role="menuitem"]'),r=Array.from(n).find(i=>V(i.textContent??"")===V(e))??Array.from(n).find(i=>V(i.textContent??"").includes(V(e)));return r?(r.click(),!0):!1}function Ye(t,e,n=5){let r=t.getBoundingClientRect(),i=e.getBoundingClientRect(),a=r.left+r.width/2,o=r.top+r.height/2,c=i.left+i.width/2,d=i.top+i.height/2,u=(m,k,B,te)=>{let Ae={bubbles:!0,cancelable:!0,clientX:B,clientY:te,view:typeof window<"u"?window:void 0};typeof PointerEvent<"u"&&m.dispatchEvent(new PointerEvent(k.replace("mouse","pointer"),Ae)),m.dispatchEvent(new MouseEvent(k,Ae))};u(t,"mousedown",a,o);for(let m=1;m<=n;m++){let k=a+(c-a)*m/n,B=o+(d-o)*m/n;u(m===n?e:t,"mousemove",k,B)}u(e,"mouseup",c,d)}var Vt=new Set(["Enter","Tab"]);function Je(t,e){typeof t.focus=="function"&&t.focus();let n={bubbles:!0,cancelable:!0,key:e};t.dispatchEvent(new KeyboardEvent("keydown",n)),Vt.has(e)&&t.dispatchEvent(new KeyboardEvent("keypress",n)),t.dispatchEvent(new KeyboardEvent("keyup",n))}var dt="cairn:misses",Dt=200;function _(t){try{let e=window.localStorage.getItem(dt),n=e?JSON.parse(e):[];n.push({...t,at:new Date().toISOString()}),window.localStorage.setItem(dt,JSON.stringify(n.slice(-Dt)))}catch{}}function V(t){return t.trim().toLowerCase().replace(/\s+/g," ")}function Ue(t){return t.replace(/["\\]/g,"\\$&")}var Ke="cairn-cursor";function Ht(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}var Ne=null,Le=null;function zt(){if(typeof document>"u"||!document.body)return null;let t=document.getElementById(Ke);return t||(t=document.createElement("div"),t.id=Ke,t.setAttribute("aria-hidden","true"),t.innerHTML='<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M2 1.5 L2 18.2 L6.3 14.4 L9.1 20.6 L11.7 19.4 L8.9 13.3 L14.6 13.1 Z" fill="#E07A3F" stroke="#1B1815" stroke-width="1.1" stroke-linejoin="round"/></svg>',t.style.cssText="position:fixed;left:0;top:0;z-index:2147483001;pointer-events:none;opacity:0;transition:opacity 180ms ease;will-change:transform;filter:drop-shadow(0 3px 6px rgba(0,0,0,0.35));",document.body.appendChild(t),t)}function T(t){if(typeof document>"u"||typeof window>"u"||typeof t.getBoundingClientRect!="function")return Promise.resolve();let e=zt();if(!e)return Promise.resolve();let n=t.getBoundingClientRect(),r=n.left+n.width/2,i=n.top+n.height/2;(Ne===null||Le===null)&&(Ne=window.innerWidth-40,Le=window.innerHeight-40,e.style.transform=`translate(${Ne}px, ${Le}px)`);let a=Ht(),o=a?60:550,c=a?40:160;return e.style.transition=`transform ${o}ms cubic-bezier(.4,0,.2,1), opacity 180ms ease`,e.style.opacity="1",e.offsetHeight,e.style.transform=`translate(${r}px, ${i}px)`,Ne=r,Le=i,new Promise(d=>{window.setTimeout(()=>{e.classList.add("cairn-cursor-hover"),window.setTimeout(()=>{e.classList.remove("cairn-cursor-hover"),d()},c)},o)})}function Xe(){if(typeof document>"u")return;let t=document.getElementById(Ke);t&&(t.style.opacity="0")}var s={};$t(s,{BRAND:()=>mn,DIRTY:()=>re,EMPTY_PATH:()=>Wt,INVALID:()=>g,NEVER:()=>Qn,OK:()=>A,ParseStatus:()=>C,Schema:()=>b,ZodAny:()=>Q,ZodArray:()=>G,ZodBigInt:()=>ae,ZodBoolean:()=>se,ZodBranded:()=>Re,ZodCatch:()=>ye,ZodDate:()=>oe,ZodDefault:()=>ge,ZodDiscriminatedUnion:()=>Pe,ZodEffects:()=>$,ZodEnum:()=>fe,ZodError:()=>N,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>Ve,ZodIntersection:()=>ue,ZodIssueCode:()=>l,ZodLazy:()=>he,ZodLiteral:()=>pe,ZodMap:()=>Ee,ZodNaN:()=>Ce,ZodNativeEnum:()=>me,ZodNever:()=>H,ZodNull:()=>le,ZodNullable:()=>F,ZodNumber:()=>ie,ZodObject:()=>L,ZodOptional:()=>j,ZodParsedType:()=>p,ZodPipeline:()=>Oe,ZodPromise:()=>ee,ZodReadonly:()=>ve,ZodRecord:()=>$e,ZodSchema:()=>b,ZodSet:()=>Se,ZodString:()=>X,ZodSymbol:()=>we,ZodTransformer:()=>$,ZodTuple:()=>Z,ZodType:()=>b,ZodUndefined:()=>ce,ZodUnion:()=>de,ZodUnknown:()=>q,ZodVoid:()=>Te,addIssueToContext:()=>h,any:()=>Tn,array:()=>An,bigint:()=>bn,boolean:()=>_t,coerce:()=>Xn,custom:()=>bt,date:()=>xn,datetimeRegex:()=>yt,defaultErrorMap:()=>U,discriminatedUnion:()=>In,effect:()=>Fn,enum:()=>Hn,function:()=>$n,getErrorMap:()=>xe,getParsedType:()=>z,instanceof:()=>yn,intersection:()=>Nn,isAborted:()=>Be,isAsync:()=>ke,isDirty:()=>je,isValid:()=>K,late:()=>gn,lazy:()=>Vn,literal:()=>Dn,makeIssue:()=>Me,map:()=>jn,nan:()=>vn,nativeEnum:()=>zn,never:()=>Sn,null:()=>wn,nullable:()=>Wn,number:()=>kt,object:()=>Mn,objectUtil:()=>Qe,oboolean:()=>Kn,onumber:()=>Jn,optional:()=>Un,ostring:()=>Yn,pipeline:()=>Gn,preprocess:()=>qn,promise:()=>Zn,quotelessJson:()=>Zt,record:()=>Bn,set:()=>Pn,setErrorMap:()=>Ut,strictObject:()=>Rn,string:()=>xt,symbol:()=>kn,transformer:()=>Fn,tuple:()=>Ln,undefined:()=>_n,union:()=>On,unknown:()=>En,util:()=>x,void:()=>Cn});var x;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function n(i){throw new Error}t.assertNever=n,t.arrayToEnum=i=>{let a={};for(let o of i)a[o]=o;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),o={};for(let c of a)o[c]=i[c];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},t.find=(i,a)=>{for(let o of i)if(a(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=r,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(x||(x={}));var Qe;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Qe||(Qe={}));var p=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),z=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}};var l=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Zt=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),N=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(a){return a.message},r={_errors:[]},i=a=>{for(let o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let c=r,d=0;for(;d<o.path.length;){let u=o.path[d];d===o.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(o))):c[u]=c[u]||{_errors:[]},c=c[u],d++}}};return i(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];n[a]=n[a]||[],n[a].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};N.create=t=>new N(t);var Ft=(t,e)=>{let n;switch(t.code){case l.invalid_type:t.received===p.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case l.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,x.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:n=`Unrecognized key(s) in object: ${x.joinValues(t.keys,", ")}`;break;case l.invalid_union:n="Invalid input";break;case l.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${x.joinValues(t.options)}`;break;case l.invalid_enum_value:n=`Invalid enum value. Expected ${x.joinValues(t.options)}, received '${t.received}'`;break;case l.invalid_arguments:n="Invalid function arguments";break;case l.invalid_return_type:n="Invalid function return type";break;case l.invalid_date:n="Invalid date";break;case l.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:x.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case l.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case l.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case l.custom:n="Invalid input";break;case l.invalid_intersection_types:n="Intersection results could not be merged";break;case l.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case l.not_finite:n="Number must be finite";break;default:n=e.defaultError,x.assertNever(t)}return{message:n}},U=Ft;var ht=U;function Ut(t){ht=t}function xe(){return ht}var Me=t=>{let{data:e,path:n,errorMaps:r,issueData:i}=t,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let c="",d=r.filter(u=>!!u).slice().reverse();for(let u of d)c=u(o,{data:e,defaultError:c}).message;return{...i,path:a,message:c}},Wt=[];function h(t,e){let n=xe(),r=Me({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===U?void 0:U].filter(i=>!!i)});t.common.issues.push(r)}var C=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let i of n){if(i.status==="aborted")return g;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let i of n){let a=await i.key,o=await i.value;r.push({key:a,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let i of n){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return g;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[a.value]=o.value)}return{status:e.value,value:r}}},g=Object.freeze({status:"aborted"}),re=t=>({status:"dirty",value:t}),A=t=>({status:"valid",value:t}),Be=t=>t.status==="aborted",je=t=>t.status==="dirty",K=t=>t.status==="valid",ke=t=>typeof Promise<"u"&&t instanceof Promise;var f;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(f||(f={}));var P=class{constructor(e,n,r,i){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},pt=(t,e)=>{if(K(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new N(t.common.issues);return this._error=n,this._error}}};function v(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:i}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,c)=>{let{message:d}=t;return o.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:d??r??c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:d??n??c.defaultError}},description:i}}var b=class{get description(){return this._def.description}_getType(e){return z(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:z(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:z(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(ke(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:z(e)},i=this._parseSync({data:e,path:r.path,parent:r});return pt(r,i)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:z(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return K(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>K(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:z(e)},i=this._parse({data:e,path:r.path,parent:r}),a=await(ke(i)?i:Promise.resolve(i));return pt(r,a)}refine(e,n){let r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,a)=>{let o=e(i),c=()=>a.addIssue({code:l.custom,...r(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(d=>d?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(e,n){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(e){return new $({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return j.create(this,this._def)}nullable(){return F.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return G.create(this)}promise(){return ee.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return ue.create(this,e,this._def)}transform(e){return new $({...v(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new ge({...v(this._def),innerType:this,defaultValue:n,typeName:y.ZodDefault})}brand(){return new Re({typeName:y.ZodBranded,type:this,...v(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new ye({...v(this._def),innerType:this,catchValue:n,typeName:y.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Oe.create(this,e)}readonly(){return ve.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qt=/^c[^\s-]{8,}$/i,Gt=/^[0-9a-z]+$/,Yt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Jt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Kt=/^[a-z0-9_-]{21}$/i,Xt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,en=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",et,nn=/^(?:(?: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])$/,rn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,an=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,sn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,on=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mt="((\\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])))",ln=new RegExp(`^${mt}$`);function gt(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function dn(t){return new RegExp(`^${gt(t)}$`)}function yt(t){let e=`${mt}T${gt(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function un(t,e){return!!((e==="v4"||!e)&&nn.test(t)||(e==="v6"||!e)&&an.test(t))}function hn(t,e){if(!Xt.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function pn(t,e){return!!((e==="v4"||!e)&&rn.test(t)||(e==="v6"||!e)&&sn.test(t))}var X=class t extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let a=this._getOrReturnCtx(e);return h(a,{code:l.invalid_type,expected:p.string,received:a.parsedType}),g}let r=new C,i;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,c=e.data.length<a.value;(o||c)&&(i=this._getOrReturnCtx(e,i),o?h(i,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):c&&h(i,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")en.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"email",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")et||(et=new RegExp(tn,"u")),et.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"emoji",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")Jt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"uuid",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")Kt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"nanoid",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")qt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"cuid",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")Gt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"cuid2",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")Yt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"ulid",code:l.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),h(i,{validation:"url",code:l.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"regex",code:l.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?yt(a).test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?ln.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?dn(a).test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:l.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?Qt.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"duration",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?un(e.data,a.version)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"ip",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?hn(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"jwt",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?pn(e.data,a.version)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"cidr",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?on.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"base64",code:l.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?cn.test(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{validation:"base64url",code:l.invalid_string,message:a.message}),r.dirty()):x.assertNever(a);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(i=>e.test(i),{validation:n,code:l.invalid_string,...f.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...f.errToObj(e)})}url(e){return this._addCheck({kind:"url",...f.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...f.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...f.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...f.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...f.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...f.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...f.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...f.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...f.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...f.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...f.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...f.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...f.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...f.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...f.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...f.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...f.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...f.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...f.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...f.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...f.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...f.errToObj(n)})}nonempty(e){return this.min(1,f.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};X.create=t=>new X({checks:[],typeName:y.ZodString,coerce:t?.coerce??!1,...v(t)});function fn(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=n>r?n:r,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var ie=class t extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==p.number){let a=this._getOrReturnCtx(e);return h(a,{code:l.invalid_type,expected:p.number,received:a.parsedType}),g}let r,i=new C;for(let a of this._def.checks)a.kind==="int"?x.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),h(r,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?fn(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),h(r,{code:l.not_finite,message:a.message}),i.dirty()):x.assertNever(a);return{status:i.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,f.toString(n))}gt(e,n){return this.setLimit("min",e,!1,f.toString(n))}lte(e,n){return this.setLimit("max",e,!0,f.toString(n))}lt(e,n){return this.setLimit("max",e,!1,f.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:f.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:f.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:f.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:f.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:f.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:f.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};ie.create=t=>new ie({checks:[],typeName:y.ZodNumber,coerce:t?.coerce||!1,...v(t)});var ae=class t extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==p.bigint)return this._getInvalidInput(e);let r,i=new C;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),h(r,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):x.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return h(n,{code:l.invalid_type,expected:p.bigint,received:n.parsedType}),g}gte(e,n){return this.setLimit("min",e,!0,f.toString(n))}gt(e,n){return this.setLimit("min",e,!1,f.toString(n))}lte(e,n){return this.setLimit("max",e,!0,f.toString(n))}lt(e,n){return this.setLimit("max",e,!1,f.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:f.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:f.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};ae.create=t=>new ae({checks:[],typeName:y.ZodBigInt,coerce:t?.coerce??!1,...v(t)});var se=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.boolean,received:r.parsedType}),g}return A(e.data)}};se.create=t=>new se({typeName:y.ZodBoolean,coerce:t?.coerce||!1,...v(t)});var oe=class t extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let a=this._getOrReturnCtx(e);return h(a,{code:l.invalid_type,expected:p.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return h(a,{code:l.invalid_date}),g}let r=new C,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):x.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:f.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:f.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};oe.create=t=>new oe({checks:[],coerce:t?.coerce||!1,typeName:y.ZodDate,...v(t)});var we=class extends b{_parse(e){if(this._getType(e)!==p.symbol){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.symbol,received:r.parsedType}),g}return A(e.data)}};we.create=t=>new we({typeName:y.ZodSymbol,...v(t)});var ce=class extends b{_parse(e){if(this._getType(e)!==p.undefined){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.undefined,received:r.parsedType}),g}return A(e.data)}};ce.create=t=>new ce({typeName:y.ZodUndefined,...v(t)});var le=class extends b{_parse(e){if(this._getType(e)!==p.null){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.null,received:r.parsedType}),g}return A(e.data)}};le.create=t=>new le({typeName:y.ZodNull,...v(t)});var Q=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return A(e.data)}};Q.create=t=>new Q({typeName:y.ZodAny,...v(t)});var q=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return A(e.data)}};q.create=t=>new q({typeName:y.ZodUnknown,...v(t)});var H=class extends b{_parse(e){let n=this._getOrReturnCtx(e);return h(n,{code:l.invalid_type,expected:p.never,received:n.parsedType}),g}};H.create=t=>new H({typeName:y.ZodNever,...v(t)});var Te=class extends b{_parse(e){if(this._getType(e)!==p.undefined){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.void,received:r.parsedType}),g}return A(e.data)}};Te.create=t=>new Te({typeName:y.ZodVoid,...v(t)});var G=class t extends b{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),i=this._def;if(n.parsedType!==p.array)return h(n,{code:l.invalid_type,expected:p.array,received:n.parsedType}),g;if(i.exactLength!==null){let o=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(o||c)&&(h(n,{code:o?l.too_big:l.too_small,minimum:c?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(h(n,{code:l.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(h(n,{code:l.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,c)=>i.type._parseAsync(new P(n,o,n.path,c)))).then(o=>C.mergeArray(r,o));let a=[...n.data].map((o,c)=>i.type._parseSync(new P(n,o,n.path,c)));return C.mergeArray(r,a)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:f.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:f.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:f.toString(n)}})}nonempty(e){return this.min(1,e)}};G.create=(t,e)=>new G({type:t,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...v(e)});function _e(t){if(t instanceof L){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=j.create(_e(r))}return new L({...t._def,shape:()=>e})}else return t instanceof G?new G({...t._def,type:_e(t.element)}):t instanceof j?j.create(_e(t.unwrap())):t instanceof F?F.create(_e(t.unwrap())):t instanceof Z?Z.create(t.items.map(e=>_e(e))):t}var L=class t extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=x.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==p.object){let u=this._getOrReturnCtx(e);return h(u,{code:l.invalid_type,expected:p.object,received:u.parsedType}),g}let{status:r,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof H&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||c.push(u);let d=[];for(let u of o){let m=a[u],k=i.data[u];d.push({key:{status:"valid",value:u},value:m._parse(new P(i,k,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof H){let u=this._def.unknownKeys;if(u==="passthrough")for(let m of c)d.push({key:{status:"valid",value:m},value:{status:"valid",value:i.data[m]}});else if(u==="strict")c.length>0&&(h(i,{code:l.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let m of c){let k=i.data[m];d.push({key:{status:"valid",value:m},value:u._parse(new P(i,k,i.path,m)),alwaysSet:m in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let m of d){let k=await m.key,B=await m.value;u.push({key:k,value:B,alwaysSet:m.alwaysSet})}return u}).then(u=>C.mergeObjectSync(r,u)):C.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return f.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:f.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of x.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of x.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return _e(this)}partial(e){let n={};for(let r of x.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?n[r]=i:n[r]=i.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of x.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof j;)a=a._def.innerType;n[r]=a}return new t({...this._def,shape:()=>n})}keyof(){return vt(x.objectKeys(this.shape))}};L.create=(t,e)=>new L({shape:()=>t,unknownKeys:"strip",catchall:H.create(),typeName:y.ZodObject,...v(e)});L.strictCreate=(t,e)=>new L({shape:()=>t,unknownKeys:"strict",catchall:H.create(),typeName:y.ZodObject,...v(e)});L.lazycreate=(t,e)=>new L({shape:t,unknownKeys:"strip",catchall:H.create(),typeName:y.ZodObject,...v(e)});var de=class extends b{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function i(a){for(let c of a)if(c.result.status==="valid")return c.result;for(let c of a)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let o=a.map(c=>new N(c.ctx.common.issues));return h(n,{code:l.invalid_union,unionErrors:o}),g}if(n.common.async)return Promise.all(r.map(async a=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await a._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let a,o=[];for(let d of r){let u={...n,common:{...n.common,issues:[]},parent:null},m=d._parseSync({data:n.data,path:n.path,parent:u});if(m.status==="valid")return m;m.status==="dirty"&&!a&&(a={result:m,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(a)return n.common.issues.push(...a.ctx.common.issues),a.result;let c=o.map(d=>new N(d));return h(n,{code:l.invalid_union,unionErrors:c}),g}}get options(){return this._def.options}};de.create=(t,e)=>new de({options:t,typeName:y.ZodUnion,...v(e)});var W=t=>t instanceof he?W(t.schema):t instanceof $?W(t.innerType()):t instanceof pe?[t.value]:t instanceof fe?t.options:t instanceof me?x.objectValues(t.enum):t instanceof ge?W(t._def.innerType):t instanceof ce?[void 0]:t instanceof le?[null]:t instanceof j?[void 0,...W(t.unwrap())]:t instanceof F?[null,...W(t.unwrap())]:t instanceof Re||t instanceof ve?W(t.unwrap()):t instanceof ye?W(t._def.innerType):[],Pe=class t extends b{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return h(n,{code:l.invalid_type,expected:p.object,received:n.parsedType}),g;let r=this.discriminator,i=n.data[r],a=this.optionsMap.get(i);return a?n.common.async?a._parseAsync({data:n.data,path:n.path,parent:n}):a._parseSync({data:n.data,path:n.path,parent:n}):(h(n,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let i=new Map;for(let a of n){let o=W(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of o){if(i.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);i.set(c,a)}}return new t({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...v(r)})}};function tt(t,e){let n=z(t),r=z(e);if(t===e)return{valid:!0,data:t};if(n===p.object&&r===p.object){let i=x.objectKeys(e),a=x.objectKeys(t).filter(c=>i.indexOf(c)!==-1),o={...t,...e};for(let c of a){let d=tt(t[c],e[c]);if(!d.valid)return{valid:!1};o[c]=d.data}return{valid:!0,data:o}}else if(n===p.array&&r===p.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let o=t[a],c=e[a],d=tt(o,c);if(!d.valid)return{valid:!1};i.push(d.data)}return{valid:!0,data:i}}else return n===p.date&&r===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ue=class extends b{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=(a,o)=>{if(Be(a)||Be(o))return g;let c=tt(a.value,o.value);return c.valid?((je(a)||je(o))&&n.dirty(),{status:n.value,value:c.data}):(h(r,{code:l.invalid_intersection_types}),g)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,o])=>i(a,o)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};ue.create=(t,e,n)=>new ue({left:t,right:e,typeName:y.ZodIntersection,...v(n)});var Z=class t extends b{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.array)return h(r,{code:l.invalid_type,expected:p.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return h(r,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&r.data.length>this._def.items.length&&(h(r,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let a=[...r.data].map((o,c)=>{let d=this._def.items[c]||this._def.rest;return d?d._parse(new P(r,o,r.path,c)):null}).filter(o=>!!o);return r.common.async?Promise.all(a).then(o=>C.mergeArray(n,o)):C.mergeArray(n,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Z.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Z({items:t,typeName:y.ZodTuple,rest:null,...v(e)})};var $e=class t extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return h(r,{code:l.invalid_type,expected:p.object,received:r.parsedType}),g;let i=[],a=this._def.keyType,o=this._def.valueType;for(let c in r.data)i.push({key:a._parse(new P(r,c,r.path,c)),value:o._parse(new P(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?C.mergeObjectAsync(n,i):C.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof b?new t({keyType:e,valueType:n,typeName:y.ZodRecord,...v(r)}):new t({keyType:X.create(),valueType:e,typeName:y.ZodRecord,...v(n)})}},Ee=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.map)return h(r,{code:l.invalid_type,expected:p.map,received:r.parsedType}),g;let i=this._def.keyType,a=this._def.valueType,o=[...r.data.entries()].map(([c,d],u)=>({key:i._parse(new P(r,c,r.path,[u,"key"])),value:a._parse(new P(r,d,r.path,[u,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let d of o){let u=await d.key,m=await d.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&n.dirty(),c.set(u.value,m.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let d of o){let u=d.key,m=d.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&n.dirty(),c.set(u.value,m.value)}return{status:n.value,value:c}}}};Ee.create=(t,e,n)=>new Ee({valueType:e,keyType:t,typeName:y.ZodMap,...v(n)});var Se=class t extends b{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.set)return h(r,{code:l.invalid_type,expected:p.set,received:r.parsedType}),g;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(h(r,{code:l.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(h(r,{code:l.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let a=this._def.valueType;function o(d){let u=new Set;for(let m of d){if(m.status==="aborted")return g;m.status==="dirty"&&n.dirty(),u.add(m.value)}return{status:n.value,value:u}}let c=[...r.data.values()].map((d,u)=>a._parse(new P(r,d,r.path,u)));return r.common.async?Promise.all(c).then(d=>o(d)):o(c)}min(e,n){return new t({...this._def,minSize:{value:e,message:f.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:f.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Se.create=(t,e)=>new Se({valueType:t,minSize:null,maxSize:null,typeName:y.ZodSet,...v(e)});var Ve=class t extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==p.function)return h(n,{code:l.invalid_type,expected:p.function,received:n.parsedType}),g;function r(c,d){return Me({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,xe(),U].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:d}})}function i(c,d){return Me({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,xe(),U].filter(u=>!!u),issueData:{code:l.invalid_return_type,returnTypeError:d}})}let a={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof ee){let c=this;return A(async function(...d){let u=new N([]),m=await c._def.args.parseAsync(d,a).catch(te=>{throw u.addIssue(r(d,te)),u}),k=await Reflect.apply(o,this,m);return await c._def.returns._def.type.parseAsync(k,a).catch(te=>{throw u.addIssue(i(k,te)),u})})}else{let c=this;return A(function(...d){let u=c._def.args.safeParse(d,a);if(!u.success)throw new N([r(d,u.error)]);let m=Reflect.apply(o,this,u.data),k=c._def.returns.safeParse(m,a);if(!k.success)throw new N([i(m,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Z.create(e).rest(q.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Z.create([]).rest(q.create()),returns:n||q.create(),typeName:y.ZodFunction,...v(r)})}},he=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};he.create=(t,e)=>new he({getter:t,typeName:y.ZodLazy,...v(e)});var pe=class extends b{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return h(n,{received:n.data,code:l.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};pe.create=(t,e)=>new pe({value:t,typeName:y.ZodLiteral,...v(e)});function vt(t,e){return new fe({values:t,typeName:y.ZodEnum,...v(e)})}var fe=class t extends b{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return h(n,{expected:x.joinValues(r),received:n.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return h(n,{received:n.data,code:l.invalid_enum_value,options:r}),g}return A(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};fe.create=vt;var me=class extends b{_parse(e){let n=x.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==p.string&&r.parsedType!==p.number){let i=x.objectValues(n);return h(r,{expected:x.joinValues(i),received:r.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=x.objectValues(n);return h(r,{received:r.data,code:l.invalid_enum_value,options:i}),g}return A(e.data)}get enum(){return this._def.values}};me.create=(t,e)=>new me({values:t,typeName:y.ZodNativeEnum,...v(e)});var ee=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==p.promise&&n.common.async===!1)return h(n,{code:l.invalid_type,expected:p.promise,received:n.parsedType}),g;let r=n.parsedType===p.promise?n.data:Promise.resolve(n.data);return A(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};ee.create=(t,e)=>new ee({type:t,typeName:y.ZodPromise,...v(e)});var $=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{h(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(r.data,a);if(r.common.async)return Promise.resolve(o).then(async c=>{if(n.value==="aborted")return g;let d=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return d.status==="aborted"?g:d.status==="dirty"?re(d.value):n.value==="dirty"?re(d.value):d});{if(n.value==="aborted")return g;let c=this._def.schema._parseSync({data:o,path:r.path,parent:r});return c.status==="aborted"?g:c.status==="dirty"?re(c.value):n.value==="dirty"?re(c.value):c}}if(i.type==="refinement"){let o=c=>{let d=i.refinement(c,a);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?g:(c.status==="dirty"&&n.dirty(),o(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?g:(c.status==="dirty"&&n.dirty(),o(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!K(o))return g;let c=i.transform(o.value,a);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>K(o)?Promise.resolve(i.transform(o.value,a)).then(c=>({status:n.value,value:c})):g);x.assertNever(i)}};$.create=(t,e,n)=>new $({schema:t,typeName:y.ZodEffects,effect:e,...v(n)});$.createWithPreprocess=(t,e,n)=>new $({schema:e,effect:{type:"preprocess",transform:t},typeName:y.ZodEffects,...v(n)});var j=class extends b{_parse(e){return this._getType(e)===p.undefined?A(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j.create=(t,e)=>new j({innerType:t,typeName:y.ZodOptional,...v(e)});var F=class extends b{_parse(e){return this._getType(e)===p.null?A(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};F.create=(t,e)=>new F({innerType:t,typeName:y.ZodNullable,...v(e)});var ge=class extends b{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===p.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};ge.create=(t,e)=>new ge({innerType:t,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var ye=class extends b{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ke(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new N(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new N(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ye.create=(t,e)=>new ye({innerType:t,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var Ce=class extends b{_parse(e){if(this._getType(e)!==p.nan){let r=this._getOrReturnCtx(e);return h(r,{code:l.invalid_type,expected:p.nan,received:r.parsedType}),g}return{status:"valid",value:e.data}}};Ce.create=t=>new Ce({typeName:y.ZodNaN,...v(t)});var mn=Symbol("zod_brand"),Re=class extends b{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Oe=class t extends b{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?g:a.status==="dirty"?(n.dirty(),re(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?g:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:y.ZodPipeline})}},ve=class extends b{_parse(e){let n=this._def.innerType._parse(e),r=i=>(K(i)&&(i.value=Object.freeze(i.value)),i);return ke(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};ve.create=(t,e)=>new ve({innerType:t,typeName:y.ZodReadonly,...v(e)});function ft(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function bt(t,e={},n){return t?Q.create().superRefine((r,i)=>{let a=t(r);if(a instanceof Promise)return a.then(o=>{if(!o){let c=ft(e,r),d=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:d})}});if(!a){let o=ft(e,r),c=o.fatal??n??!0;i.addIssue({code:"custom",...o,fatal:c})}}):Q.create()}var gn={object:L.lazycreate},y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(y||(y={}));var yn=(t,e={message:`Input not instance of ${t.name}`})=>bt(n=>n instanceof t,e),xt=X.create,kt=ie.create,vn=Ce.create,bn=ae.create,_t=se.create,xn=oe.create,kn=we.create,_n=ce.create,wn=le.create,Tn=Q.create,En=q.create,Sn=H.create,Cn=Te.create,An=G.create,Mn=L.create,Rn=L.strictCreate,On=de.create,In=Pe.create,Nn=ue.create,Ln=Z.create,Bn=$e.create,jn=Ee.create,Pn=Se.create,$n=Ve.create,Vn=he.create,Dn=pe.create,Hn=fe.create,zn=me.create,Zn=ee.create,Fn=$.create,Un=j.create,Wn=F.create,qn=$.createWithPreprocess,Gn=Oe.create,Yn=()=>xt().optional(),Jn=()=>kt().optional(),Kn=()=>_t().optional(),Xn={string:t=>X.create({...t,coerce:!0}),number:t=>ie.create({...t,coerce:!0}),boolean:t=>se.create({...t,coerce:!0}),bigint:t=>ae.create({...t,coerce:!0}),date:t=>oe.create({...t,coerce:!0})};var Qn=g;var er=["pending","in_progress","done","failed","skipped"],tr=s.object({id:s.string(),description:s.string().min(1),doneContract:s.string().min(1),status:s.enum(er)}).strict(),mi=s.object({version:s.number().int().min(1),goal:s.string().min(1),facts:s.array(s.string()),tasks:s.array(tr).min(1)}).strict(),gi=s.object({planVersion:s.number().int().min(1),currentTaskIndex:s.number().int().min(0),stallCount:s.number().int().min(0)}).strict(),nr=s.object({id:s.string(),description:s.string().min(1),doneContract:s.string().min(1)}).strict(),yi=s.object({goal:s.string().min(1),facts:s.array(s.string()),tasks:s.array(nr).min(1)}).strict(),rr=["continue","task_complete","replan","give_up"],vi=s.object({verdict:s.enum(rr),expected:s.string().optional(),actual:s.string().optional(),learnedFact:s.string().optional(),reasoning:s.string().min(1)}).strict();var wi=s.object({id:s.string().min(1),name:s.string().min(1),description:s.string().min(1),instructions:s.string().min(1),pattern:s.string().optional(),createdAt:s.string()}).strict();var Tt=s.object({method:s.enum(["POST","PUT","PATCH","DELETE"]),url:s.string(),handledBy:s.array(s.string()).optional(),constraints:s.array(s.string()).optional()}),ir=s.object({id:s.string(),label:s.string(),selector:s.string(),fallbacks:s.array(s.string()),does:s.string(),confidence:s.number().min(0).max(1),evidence:s.array(s.string()),apiCall:Tt.nullable().optional()}),ar=s.object({name:s.string(),type:s.string(),optional:s.boolean()}),sr=s.object({name:s.string(),fields:s.array(ar),source:s.string()}),or=s.object({tag:s.enum(["h1","h2","h3","h4","h5","h6","p"]),text:s.string(),file:s.string(),line:s.number()}),cr=s.object({id:s.string(),route:s.string(),file:s.string(),title:s.string(),purpose:s.string(),whenToUse:s.string(),confidence:s.number().min(0).max(1),elements:s.array(ir),dataShapes:s.array(sr).optional(),inAppCopy:s.array(or).optional()}),lr=s.object({candidates:s.array(s.string()),chose:s.string(),reason:s.string(),confidence:s.number().min(0).max(1)}),Si=s.object({version:s.literal("1"),commit:s.string(),generatedAt:s.string(),pages:s.array(cr),dead:s.array(s.string()),conflicts:s.array(lr)}),S=()=>s.preprocess(t=>t===null?void 0:t,s.string().optional()),dr=()=>s.preprocess(t=>t===null?void 0:t,Tt.optional()),Et=()=>s.preprocess(t=>t===null?void 0:t,s.boolean().optional()),De=()=>s.preprocess(t=>t===null?void 0:t,s.record(s.string(),s.unknown()).optional()),wt=()=>s.preprocess(t=>t===null?void 0:t,s.array(s.unknown()).optional()),M={text:S(),target:S(),route:S(),action:S(),value:S(),name:S(),args:De(),steps:wt(),actions:wt(),continueAfter:Et(),to:S(),key:S()},Y={target:S(),value:S(),name:S(),args:De(),to:S(),key:S()},ur=s.discriminatedUnion("verb",[s.object({...Y,verb:s.literal("click"),target:s.string().min(1)}).strict(),s.object({...Y,verb:s.literal("fill"),target:s.string().min(1),value:s.string()}).strict(),s.object({...Y,verb:s.literal("read"),target:s.string().min(1)}).strict(),s.object({...Y,verb:s.literal("call_tool"),name:s.string().min(1),args:De()}).strict(),s.object({...Y,verb:s.literal("drag"),target:s.string().min(1),to:s.string().min(1)}).strict(),s.object({...Y,verb:s.literal("select"),target:s.string().min(1),value:s.string().min(1)}).strict(),s.object({...Y,verb:s.literal("key"),target:S(),key:s.string().min(1)}).strict(),s.object({...Y,verb:s.literal("scroll"),target:s.string().min(1)}).strict(),s.object({...Y,verb:s.literal("wait_for"),target:s.string().min(1)}).strict()]),nt=s.discriminatedUnion("verb",[s.object({...M,verb:s.literal("explain"),text:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("highlight"),target:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("open"),target:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("navigate"),route:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("do"),action:s.string().min(1),target:S(),apiCall:dr()}).strict(),s.object({...M,verb:s.literal("tour"),steps:s.array(s.object({text:s.string().min(1),target:S(),route:S(),click:Et()}).strict()).min(2).max(6)}).strict(),s.object({...M,verb:s.literal("click"),target:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("fill"),target:s.string().min(1),value:s.string()}).strict(),s.object({...M,verb:s.literal("read"),target:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("call_tool"),name:s.string().min(1),args:De()}).strict(),s.object({...M,verb:s.literal("drag"),target:s.string().min(1),to:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("select"),target:s.string().min(1),value:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("key"),target:S(),key:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("scroll"),target:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("wait_for"),target:s.string().min(1)}).strict(),s.object({...M,verb:s.literal("batch"),actions:s.array(ur).min(2).max(5)}).strict()]);var hr=s.object({role:s.enum(["user","assistant"]),text:s.string()}),pr=s.object({id:s.string().max(200),role:s.string().max(50),label:s.string().max(120)}),fr=["safe","confirm"],mr=s.object({name:s.string().max(200),description:s.string().max(500),inputSchema:s.record(s.string(),s.unknown()).optional(),riskTier:s.enum(fr).optional()}),Ci=s.object({route:s.string(),question:s.string().min(1),visible:s.array(s.string()),history:s.array(hr).optional(),liveElements:s.array(pr).max(60).optional(),webMcpTools:s.array(mr).max(30).optional(),scopeId:s.string().optional()});var Ai=s.discriminatedUnion("type",[s.object({type:s.literal("act"),verb:nt,at:s.number()}),s.object({type:s.literal("obs"),observation:s.string(),ok:s.boolean(),at:s.number()}),s.object({type:s.literal("thk"),text:s.string(),at:s.number()}),s.object({type:s.literal("inj"),text:s.string(),at:s.number()})]);function gr(){return typeof document>"u"?null:document.modelContext??null}async function rt(t,e,n){let r=gr();if(!r?.getTools||!r.executeTool)return{ok:!1,observation:"This page no longer has that tool available."};try{let i=await r.getTools(),a=Array.isArray(i)?i.find(d=>d.name===t):void 0;if(!a)return{ok:!1,observation:`No tool named "${t}" is available on this page right now.`};if(a.riskTier==="confirm"&&!(n?await n({name:a.name,description:a.description??""}):!1))return{ok:!1,observation:"This action needs the user's real confirmation before it can run, and it wasn't confirmed."};let o=await r.executeTool(a,e??{});return{ok:!0,observation:(typeof o=="string"?o:JSON.stringify(o??null)).slice(0,2e3)}}catch(i){return{ok:!1,observation:`That tool failed: ${i instanceof Error?i.message:"unknown error"}`}}}var St=6,Ct=500;var yr="I'm not sure \u2014 I couldn't understand that response. Try rephrasing your question.";function At(t,e,n){let r=nt.safeParse(t);if(!r.success){n.onExplain(yr);return}vr(r.data,e,n)}function vr(t,e,n){switch(t.verb){case"explain":n.onExplain(t.text);return;case"highlight":case"open":{let r=O(t.target,n.liveElements);if(!r){(n.onMiss??_)({attempted:t.target,route:e}),n.onExplain(t.text??"I know what you need, but I can't find it on this page right now.");return}R(r),T(r).then(()=>{t.verb==="open"&&r.click(),t.text&&n.onExplain(t.text)});return}case"navigate":{if(t.continueAfter&&n.onToolStep){t.text&&n.onExplain(t.text),n.onNavigate?.(t.route),I(300,200,2e3).then(()=>{n.onToolStep?.({verb:"navigate",target:t.route,ok:!0,observation:`Navigated to ${t.route}.`})});return}n.onNavigate?.(t.route),t.text&&n.onExplain(t.text);return}case"do":{if((n.registeredActions??[]).includes(t.action)){n.onDo?.(t.action,t.target),t.text&&n.onExplain(t.text);return}if(t.target||t.apiCall){let i=t.target?O(t.target,n.liveElements):null;if(i){R(i),T(i).then(()=>{i.click(),t.text&&n.onExplain(t.text)});return}if(t.target&&(n.onMiss??_)({attempted:t.target,route:e}),t.apiCall){t.text&&n.onExplain(t.text),kr(t.apiCall).then(a=>{a.ok||n.onExplain("I tried to do that, but something went wrong \u2014 try again in a moment.")});return}}n.onExplain(t.text??"That action isn't available here.");return}case"tour":n.onTour?n.onTour(t.steps):n.onExplain(t.steps.map(r=>r.text).join(" "));return;case"click":{t.text&&n.onExplain(t.text);let r=O(t.target,n.liveElements);if(!r){(n.onMiss??_)({attempted:t.target,route:e}),n.onToolStep?.({verb:"click",target:t.target,ok:!1,observation:"Could not find that element on the page."});return}R(r),T(r).then(()=>{r.click(),I().then(()=>{n.onToolStep?.({verb:"click",target:t.target,ok:!0,observation:"Clicked it."})})});return}case"fill":{t.text&&n.onExplain(t.text);let r=O(t.target,n.liveElements);if(!r){(n.onMiss??_)({attempted:t.target,route:e}),n.onToolStep?.({verb:"fill",target:t.target,ok:!1,observation:"Could not find that element on the page."});return}R(r),T(r).then(()=>{if(!We(r,t.value)){(n.onMiss??_)({attempted:t.target,route:e}),n.onToolStep?.({verb:"fill",target:t.target,ok:!1,observation:"That element isn't a real form field \u2014 can't type into it."});return}I().then(()=>{n.onToolStep?.({verb:"fill",target:t.target,ok:!0,observation:`Typed "${t.value}" into it.`})})});return}case"read":{t.text&&n.onExplain(t.text);let r=O(t.target,n.liveElements);if(!r){(n.onMiss??_)({attempted:t.target,route:e}),n.onToolStep?.({verb:"read",target:t.target,ok:!1,observation:"Could not find that element on the page."});return}T(r).then(()=>{n.onToolStep?.({verb:"read",target:t.target,ok:!0,observation:qe(r)})});return}case"call_tool":{t.text&&n.onExplain(t.text),rt(t.name,t.args,n.onConfirmTool).then(r=>{n.onToolStep?.({verb:"call_tool",target:t.name,ok:r.ok,observation:r.observation})});return}case"drag":{t.text&&n.onExplain(t.text);let r=O(t.target,n.liveElements),i=r?O(t.to,n.liveElements):null;if(!r||!i){(n.onMiss??_)({attempted:r?t.to:t.target,route:e}),n.onToolStep?.({verb:"drag",target:t.target,ok:!1,observation:r?"Could not find the drop destination on the page.":"Could not find that element on the page."});return}R(r),T(r).then(()=>{Ye(r,i),T(i),I().then(()=>{n.onToolStep?.({verb:"drag",target:t.target,ok:!0,observation:`Dragged it to ${t.to}.`})})});return}case"select":{t.text&&n.onExplain(t.text);let r=O(t.target,n.liveElements);if(!r){(n.onMiss??_)({attempted:t.target,route:e}),n.onToolStep?.({verb:"select",target:t.target,ok:!1,observation:"Could not find that element on the page."});return}R(r),T(r).then(()=>{if(!Ge(r,t.value)){(n.onMiss??_)({attempted:t.target,route:e}),n.onToolStep?.({verb:"select",target:t.target,ok:!1,observation:`Could not find an option matching "${t.value}".`});return}I().then(()=>{n.onToolStep?.({verb:"select",target:t.target,ok:!0,observation:`Selected "${t.value}".`})})});return}case"key":{t.text&&n.onExplain(t.text);let r=t.target?O(t.target,n.liveElements):document.activeElement;if(!r){t.target&&(n.onMiss??_)({attempted:t.target,route:e}),n.onToolStep?.({verb:"key",target:t.target,ok:!1,observation:"Could not find that element on the page."});return}let i=()=>{Je(r,t.key),I().then(()=>{n.onToolStep?.({verb:"key",target:t.target,ok:!0,observation:`Pressed ${t.key}.`})})};t.target?T(r).then(i):i();return}case"scroll":{t.text&&n.onExplain(t.text);let r=O(t.target,n.liveElements);if(!r){(n.onMiss??_)({attempted:t.target,route:e}),n.onToolStep?.({verb:"scroll",target:t.target,ok:!1,observation:"Could not find that element on the page."});return}R(r),T(r).then(()=>{I().then(()=>{n.onToolStep?.({verb:"scroll",target:t.target,ok:!0,observation:"Scrolled it into view."})})});return}case"wait_for":{t.text&&n.onExplain(t.text),D(t.target,n.liveElements,St,Ct).then(r=>{if(!r){(n.onMiss??_)({attempted:t.target,route:e}),n.onToolStep?.({verb:"wait_for",target:t.target,ok:!1,observation:"It never appeared."});return}T(r).then(()=>{n.onToolStep?.({verb:"wait_for",target:t.target,ok:!0,observation:"It appeared."})})});return}case"batch":{t.text&&n.onExplain(t.text),br(t.actions,e,n).then(r=>{n.onToolStep?.({verb:"batch",ok:r.ok,observation:r.observation})});return}}}async function br(t,e,n){let r=[];for(let i of t){let a=await xr(i,e,n),o="target"in i&&i.target||"name"in i&&i.name||"(focused element)";if(r.push(`${i.verb} ${o}: ${a.observation}`),!a.ok)return{ok:!1,observation:r.join(" | ")}}return{ok:!0,observation:r.join(" | ")}}async function xr(t,e,n){switch(t.verb){case"click":{let r=await D(t.target,n.liveElements);return r?(R(r),await T(r),r.click(),await I(),{ok:!0,observation:"Clicked it."}):((n.onMiss??_)({attempted:t.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"fill":{let r=await D(t.target,n.liveElements);return r?(R(r),await T(r),We(r,t.value)?(await I(),{ok:!0,observation:`Typed "${t.value}" into it.`}):((n.onMiss??_)({attempted:t.target,route:e}),{ok:!1,observation:"That element isn't a real form field \u2014 can't type into it."})):((n.onMiss??_)({attempted:t.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"read":{let r=await D(t.target,n.liveElements);return r?(await T(r),{ok:!0,observation:qe(r)}):((n.onMiss??_)({attempted:t.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"call_tool":{let r=await rt(t.name,t.args,n.onConfirmTool);return{ok:r.ok,observation:r.observation}}case"drag":{let r=await D(t.target,n.liveElements),i=r?await D(t.to,n.liveElements):null;return!r||!i?((n.onMiss??_)({attempted:r?t.to:t.target,route:e}),{ok:!1,observation:r?"Could not find the drop destination on the page.":"Could not find that element on the page."}):(R(r),await T(r),Ye(r,i),T(i),await I(),{ok:!0,observation:`Dragged it to ${t.to}.`})}case"select":{let r=await D(t.target,n.liveElements);return r?(R(r),await T(r),Ge(r,t.value)?(await I(),{ok:!0,observation:`Selected "${t.value}".`}):((n.onMiss??_)({attempted:t.target,route:e}),{ok:!1,observation:`Could not find an option matching "${t.value}".`})):((n.onMiss??_)({attempted:t.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"key":{let r=t.target?await D(t.target,n.liveElements):document.activeElement;return r?(t.target&&await T(r),Je(r,t.key),await I(),{ok:!0,observation:`Pressed ${t.key}.`}):(t.target&&(n.onMiss??_)({attempted:t.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"scroll":{let r=await D(t.target,n.liveElements);return r?(R(r),await T(r),await I(),{ok:!0,observation:"Scrolled it into view."}):((n.onMiss??_)({attempted:t.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"wait_for":{let r=await D(t.target,n.liveElements,St,Ct);return r?(await T(r),{ok:!0,observation:"It appeared."}):((n.onMiss??_)({attempted:t.target,route:e}),{ok:!1,observation:"It never appeared."})}}}async function kr(t){try{let e=await fetch(t.url,{method:t.method,credentials:"same-origin"});return{ok:e.ok,status:e.status}}catch{return{ok:!1}}}function _r(t){if(t.length===0)return 0;let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];return Math.sqrt(e/t.length)}function wr(t){if(t.length<2)return 0;let e=0;for(let n=1;n<t.length;n++)t[n]>=0!=t[n-1]>=0&&e++;return e/(t.length-1)}function Mt(){let t=0;return{process(e){let n=_r(e),r=wr(e),i=Math.max(.02,t*3),a=n>i&&r>=.003&&r<=.4;return a||(t=t*(1-.05)+n*.05),{isSpeech:a,rms:n,zcr:r,noiseFloor:t}},reset(){t=0}}}var Tr=200;function Rt(t=Tr){let e=0,n=!1;return{update(r,i){return r.isSpeech?(e+=i,n||e<t?!1:(n=!0,!0)):(e=0,n=!1,!1)},reset(){e=0,n=!1}}}var Er={idle:"",asking:"Thinking\u2026",recording:"Listening \u2014 transcribing live\u2026","rt-connecting":"Connecting\u2026","rt-listening":"Listening\u2026","rt-thinking":"Thinking\u2026","rt-speaking":"Speaking\u2026"},Sr=8,Cr=`
2
2
  :host {
3
3
  all: initial;
4
4
  font: 13.5px/1.5 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", sans-serif;
@@ -13,9 +13,13 @@
13
13
  0%, 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); }
14
14
  70% { box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }
15
15
  }
16
- @keyframes cairn-pulse-indigo {
17
- 0%, 100% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.4); }
18
- 70% { box-shadow: 0 0 0 10px rgba(99, 102, 241, 0); }
16
+ @keyframes cairn-pulse-ember {
17
+ 0%, 100% { box-shadow: 0 0 0 0 rgba(224, 122, 63, 0.4); }
18
+ 70% { box-shadow: 0 0 0 10px rgba(224, 122, 63, 0); }
19
+ }
20
+ @keyframes cairn-cursor-arrive {
21
+ 0% { box-shadow: 0 0 0 0 rgba(224, 122, 63, 0.55); }
22
+ 100% { box-shadow: 0 0 0 9px rgba(224, 122, 63, 0); }
19
23
  }
20
24
  @keyframes cairn-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
21
25
  @keyframes cairn-rt-dot {
@@ -32,7 +36,7 @@
32
36
  }
33
37
  @keyframes cairn-word-sweep {
34
38
  0% { opacity: 0.35; text-shadow: none; }
35
- 35% { opacity: 1; color: #4f46e5; text-shadow: 0 0 10px rgba(99, 102, 241, 0.45); }
39
+ 35% { opacity: 1; color: #E07A3F; text-shadow: 0 0 10px rgba(224, 122, 63, 0.45); }
36
40
  100% { opacity: 1; color: inherit; text-shadow: none; }
37
41
  }
38
42
  @keyframes cairn-thinking-bounce {
@@ -40,14 +44,15 @@
40
44
  40% { opacity: 0.9; transform: translateY(-3px); }
41
45
  }
42
46
  .cairn-glow {
43
- animation: cairn-pulse-indigo 1.1s ease-out 2;
44
- outline: 2px solid #6366f1;
47
+ animation: cairn-pulse-ember 1.1s ease-out 2;
48
+ outline: 2px solid #E07A3F;
45
49
  outline-offset: 3px;
46
50
  border-radius: 8px;
47
51
  }
48
52
  .cairn-spin { animation: cairn-spin 0.8s linear infinite; }
53
+ .cairn-cursor-hover { animation: cairn-cursor-arrive 0.3s ease-out; }
49
54
  @media (prefers-reduced-motion: reduce) {
50
- .cairn-fab, .cairn-panel, .cairn-bubble, .cairn-word, .cairn-thinking-dot {
55
+ .cairn-fab, .cairn-panel, .cairn-bubble, .cairn-word, .cairn-thinking-dot, #cairn-cursor {
51
56
  animation: none !important;
52
57
  transition: none !important;
53
58
  }
@@ -225,4 +230,4 @@
225
230
  .cairn-rt-dot-rt-thinking { background: #f59e0b; }
226
231
  .cairn-rt-label { flex: 1; font-size: 12.5px; color: #33384a; }
227
232
  .cairn-rt-controls { display: flex; gap: 6px; }
228
- `,St='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>',$e='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v1a7 7 0 0 1-14 0v-1"/><line x1="12" x2="12" y1="18" y2="22"/></svg>',kr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="2" x2="22" y2="22"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"/><path d="M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"/><line x1="12" y1="19" x2="12" y2="22"/></svg>',_r='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>',wr='<svg class="cairn-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',Tr='<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>',Ct='<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><rect x="7" y="12.5" width="6" height="2.6" rx="0.5" fill="currentColor"/><rect x="4.5" y="8.5" width="11" height="2.6" rx="0.5" fill="currentColor" opacity="0.75"/><rect x="8.2" y="4.5" width="3.6" height="2.6" rx="0.5" fill="currentColor" opacity="0.5"/></svg>',Er='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"/></svg>',Sr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.83 16.57a1 1 0 0 0 1.21-.3l.36-.47A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A17.87 17.87 0 0 1 9.3 17.6"/><path d="M4.27 5.34C3.5 6.44 4 8 4 8a17.9 17.9 0 0 0 2.14 6.6"/><path d="M2 2v0"/><line x1="2" y1="2" x2="22" y2="22"/></svg>',At='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>',Cr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="22" y1="9" x2="16" y2="15"/><line x1="16" y1="9" x2="22" y2="15"/></svg>',Qe=class extends HTMLElement{shadow;fab;panel;stackEl;userBubbleEl;agentBubbleEl;chipEl;agentTextEl;thinkingEl;formEl;inputEl;sendBtn;micBtn=null;phoneBtn=null;rtBar;rtDot;rtLabel;rtMicBtn;rtSpeakerBtn;rtEndBtn;isOpen=!1;status="idle";recording=!1;touringActive=!1;caption="";answer=null;lastQuestion=null;tourGeneration=0;mediaRecorder=null;audioChunks=[];transcribeInFlight=!1;activeAudio=null;history=[];rtSocket=null;rtCleanup=null;rtMicMuted=!1;rtSpeakerMuted=!1;rtStarting=!1;rtLastFinalGeneration=0;rtPlaybackCtx=null;rtPlaybackGain=null;rtNextPlayTime=0;rtScheduledSources=[];rtThinkingWatchdog=null;rtAudioDoneArriving=!0;rtTourAudioDoneResolve=null;static get observedAttributes(){return["persona"]}connectedCallback(){this.shadow||(this.shadow=this.attachShadow({mode:"open"}),this.buildDom())}attributeChangedCallback(e){e==="persona"&&this.panel&&this.panel.setAttribute("aria-label",`${this.persona} help panel`)}disconnectedCallback(){(this.rtSocket||this.rtCleanup)&&this.endRealtime()}get endpoint(){return this.getAttribute("endpoint")??"/api/copilot"}get speakEndpoint(){return this.getAttribute("speak-endpoint")}get transcribeEndpoint(){return this.getAttribute("transcribe-endpoint")}get reportMissesEndpoint(){return this.getAttribute("report-misses-endpoint")}get realtimeUrl(){return this.getAttribute("realtime-url")}get persona(){return this.getAttribute("persona")??"Cairn"}get registeredActions(){return(this.getAttribute("registered-actions")??"").split(",").map(e=>e.trim()).filter(Boolean)}get realtimeActive(){return this.status.startsWith("rt-")}get busy(){return this.status==="asking"||this.status==="rt-thinking"||this.touringActive}micSupported(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<"u"}buildDom(){let e=document.createElement("style");e.textContent=xr,this.shadow.appendChild(e),this.fab=document.createElement("button"),this.fab.className="cairn-fab",this.fab.innerHTML=Ct,this.fab.setAttribute("aria-label",`Open ${this.persona} help`),this.fab.addEventListener("click",()=>this.toggleOpen()),this.shadow.appendChild(this.fab),this.panel=document.createElement("div"),this.panel.className="cairn-panel",this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label",`${this.persona} help panel`),this.stackEl=document.createElement("div"),this.stackEl.className="cairn-stack",this.stackEl.style.display="none",this.userBubbleEl=document.createElement("div"),this.userBubbleEl.className="cairn-bubble cairn-bubble-user",this.userBubbleEl.style.display="none",this.stackEl.appendChild(this.userBubbleEl),this.agentBubbleEl=document.createElement("div"),this.agentBubbleEl.className="cairn-bubble cairn-bubble-agent",this.agentBubbleEl.style.display="none",this.chipEl=document.createElement("span"),this.chipEl.className="cairn-chip",this.chipEl.style.display="none",this.agentBubbleEl.appendChild(this.chipEl),this.agentTextEl=document.createElement("span"),this.agentTextEl.className="cairn-bubble-text",this.agentBubbleEl.appendChild(this.agentTextEl),this.thinkingEl=document.createElement("span"),this.thinkingEl.className="cairn-thinking",this.thinkingEl.setAttribute("aria-label","Thinking"),this.thinkingEl.style.display="none",this.thinkingEl.innerHTML='<span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span>',this.agentBubbleEl.appendChild(this.thinkingEl),this.stackEl.appendChild(this.agentBubbleEl),this.panel.appendChild(this.stackEl),this.rtBar=document.createElement("div"),this.rtBar.className="cairn-rt-bar",this.rtBar.style.display="none",this.rtDot=document.createElement("span"),this.rtDot.className="cairn-rt-dot",this.rtBar.appendChild(this.rtDot),this.rtLabel=document.createElement("span"),this.rtLabel.className="cairn-rt-label",this.rtBar.appendChild(this.rtLabel);let t=document.createElement("div");t.className="cairn-rt-controls",this.rtMicBtn=document.createElement("button"),this.rtMicBtn.type="button",this.rtMicBtn.className="cairn-icon-btn",this.rtMicBtn.innerHTML=$e,this.rtMicBtn.setAttribute("aria-label","Mute microphone"),this.rtMicBtn.addEventListener("click",()=>this.toggleRtMic()),t.appendChild(this.rtMicBtn),this.rtSpeakerBtn=document.createElement("button"),this.rtSpeakerBtn.type="button",this.rtSpeakerBtn.className="cairn-icon-btn",this.rtSpeakerBtn.innerHTML=At,this.rtSpeakerBtn.setAttribute("aria-label","Mute speaker"),this.rtSpeakerBtn.addEventListener("click",()=>this.toggleRtSpeaker()),t.appendChild(this.rtSpeakerBtn),this.rtEndBtn=document.createElement("button"),this.rtEndBtn.type="button",this.rtEndBtn.className="cairn-icon-btn cairn-icon-btn-end",this.rtEndBtn.innerHTML=Sr,this.rtEndBtn.setAttribute("aria-label","End conversation"),this.rtEndBtn.addEventListener("click",()=>this.endRealtime()),t.appendChild(this.rtEndBtn),this.rtBar.appendChild(t),this.panel.appendChild(this.rtBar),this.formEl=document.createElement("form");let r=document.createElement("div");r.className="cairn-input-row",this.inputEl=document.createElement("input"),this.inputEl.placeholder="What do you need help with?",this.inputEl.setAttribute("aria-label",`Ask ${this.persona} a question`),this.inputEl.addEventListener("input",()=>this.updateBusyState()),r.appendChild(this.inputEl),this.realtimeUrl&&this.micSupported()&&(this.phoneBtn=document.createElement("button"),this.phoneBtn.type="button",this.phoneBtn.className="cairn-icon-btn",this.phoneBtn.innerHTML=Er,this.phoneBtn.setAttribute("aria-label","Start realtime conversation"),this.phoneBtn.addEventListener("click",()=>void this.startRealtime()),r.appendChild(this.phoneBtn)),this.transcribeEndpoint&&this.micSupported()&&(this.micBtn=document.createElement("button"),this.micBtn.type="button",this.micBtn.className="cairn-icon-btn",this.micBtn.innerHTML=$e,this.micBtn.setAttribute("aria-label","Ask by voice"),this.micBtn.addEventListener("click",()=>this.recording?this.stopRecording():void this.startRecording()),r.appendChild(this.micBtn)),this.sendBtn=document.createElement("button"),this.sendBtn.type="submit",this.sendBtn.className="cairn-send",this.sendBtn.innerHTML=St,this.sendBtn.setAttribute("aria-label","Send"),r.appendChild(this.sendBtn),this.formEl.appendChild(r),this.formEl.addEventListener("submit",i=>{i.preventDefault();let a=this.inputEl.value.trim();a&&this.ask(a)}),this.panel.appendChild(this.formEl),this.shadow.appendChild(this.panel),this.render()}toggleOpen(){this.isOpen=!this.isOpen,this.panel.classList.toggle("cairn-open",this.isOpen),this.fab.innerHTML=this.isOpen?Tr:Ct,this.fab.setAttribute("aria-label",this.isOpen?`Close ${this.persona} help`:`Open ${this.persona} help`),this.isOpen&&!this.realtimeActive&&this.inputEl.focus()}render(){let e=this.realtimeActive;if(this.fab.classList.toggle("cairn-fab-speaking",this.status==="rt-speaking"),this.rtBar.style.display=e?"flex":"none",this.formEl.style.display=e?"none":"block",e){this.rtDot.className=`cairn-rt-dot cairn-rt-dot-${this.status}`,this.rtLabel.textContent=vr[this.status];let a=this.status==="rt-speaking";this.rtMicBtn.className=a?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtSpeakerBtn.className=a?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtMicBtn.innerHTML=this.rtMicMuted?kr:$e,this.rtMicBtn.setAttribute("aria-label",this.rtMicMuted?"Unmute microphone":"Mute microphone"),this.rtSpeakerBtn.innerHTML=this.rtSpeakerMuted?Cr:At,this.rtSpeakerBtn.setAttribute("aria-label",this.rtSpeakerMuted?"Unmute speaker":"Mute speaker")}let t=this.touringActive?this.caption:"",r=!this.touringActive&&(this.recording||e)?this.caption:this.lastQuestion??"",i=!!this.answer||this.busy;this.stackEl.style.display=r||i?"flex":"none",this.userBubbleEl.style.display=r?"block":"none",this.userBubbleEl.textContent=r,this.agentBubbleEl.style.display=i?"flex":"none",this.chipEl.style.display=t?"inline-block":"none",this.chipEl.textContent=t,this.answer?(this.agentTextEl.style.display="inline",this.renderCaptionWords(this.agentTextEl,this.answer),this.thinkingEl.style.display="none"):(this.agentTextEl.style.display="none",this.agentTextEl.textContent="",this.thinkingEl.style.display=this.busy?"inline-flex":"none"),this.phoneBtn&&(this.phoneBtn.disabled=this.busy||this.recording),this.updateBusyState()}setStatus(e){this.status=e,this.render()}setCaption(e){this.caption=e,this.render()}updateBusyState(){this.inputEl.disabled=this.recording||this.touringActive,this.sendBtn.disabled=this.busy||this.recording||!this.inputEl.value.trim(),this.sendBtn.innerHTML=this.busy?wr:St,this.micBtn&&(this.micBtn.disabled=this.touringActive)}setAnswer(e){this.answer=e,this.render()}renderCaptionWords(e,t){e.innerHTML="";let r=t.split(" ");r.forEach((i,a)=>{let o=document.createElement("span");o.className="cairn-word",o.style.animationDelay=`${Math.min(a*55,2800)}ms`,o.textContent=a<r.length-1?i+" ":i,e.appendChild(o)})}reportMiss(e){w(e);let t=this.reportMissesEndpoint;t&&fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}).catch(()=>{})}async ask(e){this.setStatus("asking"),this.setAnswer(null),this.lastQuestion=e,this.inputEl.value="",this.render();try{let r=await(await fetch(this.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:location.pathname,question:e,visible:He(),history:this.history})})).json().catch(()=>null);this.handleVerb(r),this.history=[...this.history,{role:"user",text:e},{role:"assistant",text:Ar(r)}].slice(-br)}catch{this.setAnswer("Something went wrong reaching the help service \u2014 try again in a moment.")}finally{this.setStatus("idle")}}handleVerb(e){wt(e,location.pathname,{onExplain:t=>{this.setAnswer(t),this.realtimeActive||this.speak(t)},onNavigate:t=>{location.assign(t)},onMiss:t=>this.reportMiss(t),onDo:(t,r)=>{this.dispatchEvent(new CustomEvent("cairn-do",{detail:{action:t,target:r},bubbles:!0,composed:!0}))},onTour:t=>void this.runTour(t),registeredActions:this.registeredActions})}async runTour(e){let t=++this.tourGeneration,r=this.realtimeActive;this.touringActive=!0,r&&this.setStatus("rt-speaking"),this.setAnswer(null);let i=location.pathname;try{for(let a=0;a<e.length;a++){if(this.tourGeneration!==t)return;let o=e[a];if(this.setCaption(`Step ${a+1} of ${e.length}`),this.setAnswer(o.text),o.route&&o.route!==i){location.assign(o.route);return}if(o.target){let c=R(o.target);c?M(c):this.reportMiss({attempted:o.target,route:i})}if(r&&this.rtSocket?.readyState===WebSocket.OPEN?await this.speakOverRealtime(o.text):this.speakEndpoint?await this.speakAndWait(o.text):await new Promise(c=>setTimeout(c,Math.max(1200,o.text.length*45))),this.tourGeneration!==t)return}if(this.tourGeneration!==t)return;this.setCaption(""),r&&this.realtimeActive&&this.setStatus("rt-listening")}finally{this.tourGeneration===t&&(this.touringActive=!1,this.render())}}playResponseAudio(e){this.activeAudio&&(this.activeAudio.pause(),this.activeAudio.currentTime=0);let t=URL.createObjectURL(e),r=new Audio(t);return this.activeAudio=r,new Promise(i=>{let a=()=>{URL.revokeObjectURL(t),this.activeAudio===r&&(this.activeAudio=null),i()};r.onended=a,r.play().catch(a)})}async speak(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;this.playResponseAudio(await t.blob())}catch{}}async speakAndWait(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;await this.playResponseAudio(await t.blob())}catch{}}speakOverRealtime(e){return new Promise(t=>{let r=this.rtSocket;if(!r||r.readyState!==WebSocket.OPEN){t();return}this.rtAudioDoneArriving=!1;let i=!1,a=()=>{i||(i=!0,this.rtTourAudioDoneResolve=null,t())};this.rtTourAudioDoneResolve=a,setTimeout(()=>{i||console.warn("[cairn] tour step audio confirmation timed out \u2014 continuing"),a()},15e3),r.send(JSON.stringify({type:"speak",text:e}))})}async startRecording(){if(!(!this.transcribeEndpoint||!this.micSupported()||this.realtimeActive))try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e);this.audioChunks=[],this.setCaption(""),t.ondataavailable=r=>{r.data.size!==0&&(this.audioChunks.push(r.data),this.transcribeSoFar(t.mimeType||"audio/webm",!0))},t.onstop=()=>void this.transcribeSoFar(t.mimeType||"audio/webm",!1),this.mediaRecorder=t,t.start(2e3),this.recording=!0,this.micBtn&&(this.micBtn.innerHTML=_r,this.micBtn.classList.add("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Stop recording")),this.render()}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site.")}}stopRecording(){let e=this.mediaRecorder?.stream;this.mediaRecorder?.stop(),e?.getTracks().forEach(t=>t.stop()),this.recording=!1,this.micBtn&&(this.micBtn.innerHTML=$e,this.micBtn.classList.remove("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Ask by voice")),this.render()}async transcribeSoFar(e,t){if(this.transcribeEndpoint&&!(t&&this.transcribeInFlight)){this.transcribeInFlight=!0;try{let r=new Blob(this.audioChunks,{type:e}),a=await(await fetch(this.transcribeEndpoint,{method:"POST",headers:{"content-type":e},body:r})).json().catch(()=>null);a?.text?(this.inputEl.value=a.text,this.setCaption(a.text),this.updateBusyState()):t||this.setAnswer("Couldn't make that out \u2014 try typing instead.")}catch{t||this.setAnswer("Couldn't reach the transcription service.")}finally{this.transcribeInFlight=!1}}}isStaleRtMessage(e){return typeof e.generation=="number"&&e.generation<this.rtLastFinalGeneration}async startRealtime(){if(!(!this.realtimeUrl||!this.micSupported()||this.realtimeActive||this.rtStarting)){this.rtStarting=!0,this.setAnswer(null),this.setCaption(""),this.setStatus("rt-connecting");try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new WebSocket(this.realtimeUrl);t.binaryType="arraybuffer",this.rtSocket=t;let r=new AudioContext,i=r.createGain();i.gain.value=this.rtSpeakerMuted?0:1,i.connect(r.destination),this.rtPlaybackCtx=r,this.rtPlaybackGain=i,this.rtNextPlayTime=0,this.rtScheduledSources=[],this.rtAudioDoneArriving=!0;let a=new AudioContext,o=a.createMediaStreamSource(e),c=a.createScriptProcessor(4096,1,1),d=a.createGain();d.gain.value=0;let u=Tt(),m=Et(),k=()=>{if(this.rtAudioDoneArriving&&!(this.rtScheduledSources.length>0)){if(this.touringActive){this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null;return}a.resume().catch(()=>{}),this.setStatus("rt-listening"),this.setCaption("")}},L=()=>{this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null)},ee=()=>{L(),this.rtThinkingWatchdog=setTimeout(()=>{this.rtThinkingWatchdog=null,console.warn("[cairn] realtime turn timed out waiting on the server \u2014 resuming listening"),et(),this.setAnswer("That's taking longer than expected \u2014 try asking again.")},2e4)},Ce=()=>{for(let T of this.rtScheduledSources)try{T.stop()}catch{}this.rtScheduledSources=[],this.rtNextPlayTime=this.rtPlaybackCtx?.currentTime??0},et=()=>{L(),Ce(),this.rtAudioDoneArriving=!0,t.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"barge_in"})),this.setStatus("rt-listening"),this.setCaption("")};c.onaudioprocess=T=>{if(t.readyState!==WebSocket.OPEN||this.rtMicMuted)return;if(this.status==="rt-speaking"&&!this.touringActive){let te=u.process(T.inputBuffer.getChannelData(0)),Oe=T.inputBuffer.length/a.sampleRate*1e3;m.update(te,Oe)&&et();return}if(m.reset(),this.status!=="rt-listening")return;let _=Rr(Mr(T.inputBuffer.getChannelData(0),a.sampleRate));t.send(_)},o.connect(c),c.connect(d),d.connect(a.destination);let Mt=setInterval(()=>{a.state!=="running"&&a.resume().catch(()=>{});let T=e.getAudioTracks()[0];T&&(T.readyState==="ended"||T.muted)&&(this.setAnswer("The microphone connection was lost \u2014 try starting the call again."),this.endRealtime())},2e3),tt=()=>{this.setAnswer("The microphone connection was lost \u2014 try starting the call again."),this.endRealtime()};e.getAudioTracks().forEach(T=>T.addEventListener("ended",tt)),this.rtCleanup=()=>{clearInterval(Mt),e.getAudioTracks().forEach(T=>T.removeEventListener("ended",tt)),c.disconnect(),o.disconnect(),e.getTracks().forEach(T=>T.stop()),a.close(),Ce(),r.close(),this.rtPlaybackCtx=null,this.rtPlaybackGain=null},t.onopen=()=>{t.send(JSON.stringify({type:"context",route:location.pathname,visible:He()})),this.setStatus("rt-listening"),this.rtStarting=!1},t.onmessage=T=>{if(typeof T.data!="string")return;let _=JSON.parse(T.data);if(_.type==="interim")this.setCaption(_.text);else if(_.type==="final")this.rtLastFinalGeneration=typeof _.generation=="number"?_.generation:0,this.setCaption(_.text),this.setStatus("rt-thinking"),ee();else if(_.type==="verb"){if(this.isStaleRtMessage(_))return;L(),this.handleVerb(_.verb)}else if(_.type==="speaking_start"){if(this.isStaleRtMessage(_))return;L(),this.rtAudioDoneArriving=!1,this.setStatus("rt-speaking")}else if(_.type==="audio_chunk"){if(this.isStaleRtMessage(_))return;let te=this.rtPlaybackCtx,Oe=this.rtPlaybackGain;if(!te||!Oe)return;te.resume().catch(()=>{});let nt=Uint8Array.from(atob(_.audio),Y=>Y.charCodeAt(0)),Ve=nt.length/2,rt=new Float32Array(Ve),Rt=new DataView(nt.buffer);for(let Y=0;Y<Ve;Y++)rt[Y]=Rt.getInt16(Y*2,!0)/32768;let Ot=typeof _.sampleRate=="number"?_.sampleRate:24e3,De=te.createBuffer(1,Ve,Ot);De.copyToChannel(rt,0);let ve=te.createBufferSource();ve.buffer=De,ve.connect(Oe);let it=Math.max(te.currentTime,this.rtNextPlayTime);ve.start(it),this.rtNextPlayTime=it+De.duration,this.rtScheduledSources.push(ve),ve.onended=()=>{this.rtScheduledSources=this.rtScheduledSources.filter(Y=>Y!==ve),k()}}else if(_.type==="speaking_end"||_.type==="turn_complete"){if(this.isStaleRtMessage(_))return;L(),this.rtAudioDoneArriving=!0,k()}else _.type==="error"&&(L(),this.setAnswer(_.message??"Something went wrong."),this.touringActive||(this.setStatus("rt-listening"),this.setCaption("")))},t.onerror=()=>{this.setAnswer("Couldn't connect to the realtime voice service."),this.endRealtime()},t.onclose=()=>{this.status!=="idle"&&this.endRealtime()}}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site."),this.setStatus("idle"),this.rtStarting=!1}}}endRealtime(){this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null),this.rtStarting=!1,this.activeAudio?.pause(),this.activeAudio=null,this.rtSocket?.close(),this.rtSocket=null,this.rtCleanup?.(),this.rtCleanup=null,this.rtMicMuted=!1,this.rtSpeakerMuted=!1,this.setCaption(""),this.setStatus("idle"),this.tourGeneration++,this.touringActive=!1,this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null,this.render()}toggleRtMic(){this.rtMicMuted=!this.rtMicMuted,this.render()}toggleRtSpeaker(){this.rtSpeakerMuted=!this.rtSpeakerMuted,this.rtPlaybackGain&&(this.rtPlaybackGain.gain.value=this.rtSpeakerMuted?0:1),this.render()}};function Ar(n){if(!n||typeof n!="object")return"(no response)";let e=n;if(typeof e.text=="string"&&e.text)return e.text;switch(e.verb){case"highlight":case"open":return`(highlighted ${String(e.target)})`;case"navigate":return`(navigated to ${String(e.route)})`;case"do":return`(ran ${String(e.action)}${e.target?` on ${String(e.target)}`:""})`;case"tour":return Array.isArray(e.steps)?e.steps.map(t=>t.text??"").join(" "):"(tour)";default:return"(no response)"}}function Mr(n,e){if(e===16e3)return n;let r=e/16e3,i=Math.round(n.length/r),a=new Float32Array(i),o=0,c=0;for(;o<i;){let d=Math.round((o+1)*r),u=0,m=0;for(let k=c;k<d&&k<n.length;k++)u+=n[k],m++;a[o]=m>0?u/m:0,o++,c=d}return a}function Rr(n){let e=new ArrayBuffer(n.length*2),t=new DataView(e);for(let r=0;r<n.length;r++){let i=Math.max(-1,Math.min(1,n[r]));t.setInt16(r*2,i<0?i*32768:i*32767,!0)}return e}typeof customElements<"u"&&!customElements.get("cairn-widget")&&customElements.define("cairn-widget",Qe);})();
233
+ `,Ot='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>',He='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v1a7 7 0 0 1-14 0v-1"/><line x1="12" x2="12" y1="18" y2="22"/></svg>',Ar='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="2" x2="22" y2="22"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"/><path d="M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"/><line x1="12" y1="19" x2="12" y2="22"/></svg>',Mr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>',Rr='<svg class="cairn-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',Or='<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>',It='<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><rect x="7" y="12.5" width="6" height="2.6" rx="0.5" fill="currentColor"/><rect x="4.5" y="8.5" width="11" height="2.6" rx="0.5" fill="currentColor" opacity="0.75"/><rect x="8.2" y="4.5" width="3.6" height="2.6" rx="0.5" fill="currentColor" opacity="0.5"/></svg>',Ir='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"/></svg>',Nr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.83 16.57a1 1 0 0 0 1.21-.3l.36-.47A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A17.87 17.87 0 0 1 9.3 17.6"/><path d="M4.27 5.34C3.5 6.44 4 8 4 8a17.9 17.9 0 0 0 2.14 6.6"/><path d="M2 2v0"/><line x1="2" y1="2" x2="22" y2="22"/></svg>',Nt='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>',Lr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="22" y1="9" x2="16" y2="15"/><line x1="16" y1="9" x2="22" y2="15"/></svg>',it=class extends HTMLElement{shadow;fab;panel;stackEl;userBubbleEl;agentBubbleEl;chipEl;agentTextEl;thinkingEl;formEl;inputEl;sendBtn;micBtn=null;phoneBtn=null;rtBar;rtDot;rtLabel;rtMicBtn;rtSpeakerBtn;rtEndBtn;isOpen=!1;status="idle";recording=!1;touringActive=!1;caption="";answer=null;lastQuestion=null;tourGeneration=0;mediaRecorder=null;audioChunks=[];transcribeInFlight=!1;activeAudio=null;history=[];rtSocket=null;rtCleanup=null;rtMicMuted=!1;rtSpeakerMuted=!1;rtStarting=!1;rtLastFinalGeneration=0;rtPlaybackCtx=null;rtPlaybackGain=null;rtNextPlayTime=0;rtScheduledSources=[];rtThinkingWatchdog=null;rtAudioDoneArriving=!0;rtTourAudioDoneResolve=null;static get observedAttributes(){return["persona"]}connectedCallback(){this.shadow||(this.shadow=this.attachShadow({mode:"open"}),this.buildDom())}attributeChangedCallback(e){e==="persona"&&this.panel&&this.panel.setAttribute("aria-label",`${this.persona} help panel`)}disconnectedCallback(){(this.rtSocket||this.rtCleanup)&&this.endRealtime(),Xe()}get endpoint(){return this.getAttribute("endpoint")??"/api/copilot"}get speakEndpoint(){return this.getAttribute("speak-endpoint")}get transcribeEndpoint(){return this.getAttribute("transcribe-endpoint")}get reportMissesEndpoint(){return this.getAttribute("report-misses-endpoint")}get realtimeUrl(){return this.getAttribute("realtime-url")}get persona(){return this.getAttribute("persona")??"Cairn"}get registeredActions(){return(this.getAttribute("registered-actions")??"").split(",").map(e=>e.trim()).filter(Boolean)}get realtimeActive(){return this.status.startsWith("rt-")}get busy(){return this.status==="asking"||this.status==="rt-thinking"||this.touringActive}micSupported(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<"u"}buildDom(){let e=document.createElement("style");e.textContent=Cr,this.shadow.appendChild(e),this.fab=document.createElement("button"),this.fab.className="cairn-fab",this.fab.innerHTML=It,this.fab.setAttribute("aria-label",`Open ${this.persona} help`),this.fab.addEventListener("click",()=>this.toggleOpen()),this.shadow.appendChild(this.fab),this.panel=document.createElement("div"),this.panel.className="cairn-panel",this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label",`${this.persona} help panel`),this.stackEl=document.createElement("div"),this.stackEl.className="cairn-stack",this.stackEl.style.display="none",this.userBubbleEl=document.createElement("div"),this.userBubbleEl.className="cairn-bubble cairn-bubble-user",this.userBubbleEl.style.display="none",this.stackEl.appendChild(this.userBubbleEl),this.agentBubbleEl=document.createElement("div"),this.agentBubbleEl.className="cairn-bubble cairn-bubble-agent",this.agentBubbleEl.style.display="none",this.chipEl=document.createElement("span"),this.chipEl.className="cairn-chip",this.chipEl.style.display="none",this.agentBubbleEl.appendChild(this.chipEl),this.agentTextEl=document.createElement("span"),this.agentTextEl.className="cairn-bubble-text",this.agentBubbleEl.appendChild(this.agentTextEl),this.thinkingEl=document.createElement("span"),this.thinkingEl.className="cairn-thinking",this.thinkingEl.setAttribute("aria-label","Thinking"),this.thinkingEl.style.display="none",this.thinkingEl.innerHTML='<span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span>',this.agentBubbleEl.appendChild(this.thinkingEl),this.stackEl.appendChild(this.agentBubbleEl),this.panel.appendChild(this.stackEl),this.rtBar=document.createElement("div"),this.rtBar.className="cairn-rt-bar",this.rtBar.style.display="none",this.rtDot=document.createElement("span"),this.rtDot.className="cairn-rt-dot",this.rtBar.appendChild(this.rtDot),this.rtLabel=document.createElement("span"),this.rtLabel.className="cairn-rt-label",this.rtBar.appendChild(this.rtLabel);let n=document.createElement("div");n.className="cairn-rt-controls",this.rtMicBtn=document.createElement("button"),this.rtMicBtn.type="button",this.rtMicBtn.className="cairn-icon-btn",this.rtMicBtn.innerHTML=He,this.rtMicBtn.setAttribute("aria-label","Mute microphone"),this.rtMicBtn.addEventListener("click",()=>this.toggleRtMic()),n.appendChild(this.rtMicBtn),this.rtSpeakerBtn=document.createElement("button"),this.rtSpeakerBtn.type="button",this.rtSpeakerBtn.className="cairn-icon-btn",this.rtSpeakerBtn.innerHTML=Nt,this.rtSpeakerBtn.setAttribute("aria-label","Mute speaker"),this.rtSpeakerBtn.addEventListener("click",()=>this.toggleRtSpeaker()),n.appendChild(this.rtSpeakerBtn),this.rtEndBtn=document.createElement("button"),this.rtEndBtn.type="button",this.rtEndBtn.className="cairn-icon-btn cairn-icon-btn-end",this.rtEndBtn.innerHTML=Nr,this.rtEndBtn.setAttribute("aria-label","End conversation"),this.rtEndBtn.addEventListener("click",()=>this.endRealtime()),n.appendChild(this.rtEndBtn),this.rtBar.appendChild(n),this.panel.appendChild(this.rtBar),this.formEl=document.createElement("form");let r=document.createElement("div");r.className="cairn-input-row",this.inputEl=document.createElement("input"),this.inputEl.placeholder="What do you need help with?",this.inputEl.setAttribute("aria-label",`Ask ${this.persona} a question`),this.inputEl.addEventListener("input",()=>this.updateBusyState()),r.appendChild(this.inputEl),this.realtimeUrl&&this.micSupported()&&(this.phoneBtn=document.createElement("button"),this.phoneBtn.type="button",this.phoneBtn.className="cairn-icon-btn",this.phoneBtn.innerHTML=Ir,this.phoneBtn.setAttribute("aria-label","Start realtime conversation"),this.phoneBtn.addEventListener("click",()=>void this.startRealtime()),r.appendChild(this.phoneBtn)),this.transcribeEndpoint&&this.micSupported()&&(this.micBtn=document.createElement("button"),this.micBtn.type="button",this.micBtn.className="cairn-icon-btn",this.micBtn.innerHTML=He,this.micBtn.setAttribute("aria-label","Ask by voice"),this.micBtn.addEventListener("click",()=>this.recording?this.stopRecording():void this.startRecording()),r.appendChild(this.micBtn)),this.sendBtn=document.createElement("button"),this.sendBtn.type="submit",this.sendBtn.className="cairn-send",this.sendBtn.innerHTML=Ot,this.sendBtn.setAttribute("aria-label","Send"),r.appendChild(this.sendBtn),this.formEl.appendChild(r),this.formEl.addEventListener("submit",i=>{i.preventDefault();let a=this.inputEl.value.trim();a&&this.ask(a)}),this.panel.appendChild(this.formEl),this.shadow.appendChild(this.panel),this.render()}toggleOpen(){this.isOpen=!this.isOpen,this.panel.classList.toggle("cairn-open",this.isOpen),this.fab.innerHTML=this.isOpen?Or:It,this.fab.setAttribute("aria-label",this.isOpen?`Close ${this.persona} help`:`Open ${this.persona} help`),this.isOpen&&!this.realtimeActive&&this.inputEl.focus(),this.isOpen||Xe()}render(){let e=this.realtimeActive;if(this.fab.classList.toggle("cairn-fab-speaking",this.status==="rt-speaking"),this.rtBar.style.display=e?"flex":"none",this.formEl.style.display=e?"none":"block",e){this.rtDot.className=`cairn-rt-dot cairn-rt-dot-${this.status}`,this.rtLabel.textContent=Er[this.status];let a=this.status==="rt-speaking";this.rtMicBtn.className=a?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtSpeakerBtn.className=a?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtMicBtn.innerHTML=this.rtMicMuted?Ar:He,this.rtMicBtn.setAttribute("aria-label",this.rtMicMuted?"Unmute microphone":"Mute microphone"),this.rtSpeakerBtn.innerHTML=this.rtSpeakerMuted?Lr:Nt,this.rtSpeakerBtn.setAttribute("aria-label",this.rtSpeakerMuted?"Unmute speaker":"Mute speaker")}let n=this.touringActive?this.caption:"",r=!this.touringActive&&(this.recording||e)?this.caption:this.lastQuestion??"",i=!!this.answer||this.busy;this.stackEl.style.display=r||i?"flex":"none",this.userBubbleEl.style.display=r?"block":"none",this.userBubbleEl.textContent=r,this.agentBubbleEl.style.display=i?"flex":"none",this.chipEl.style.display=n?"inline-block":"none",this.chipEl.textContent=n,this.answer?(this.agentTextEl.style.display="inline",this.renderCaptionWords(this.agentTextEl,this.answer),this.thinkingEl.style.display="none"):(this.agentTextEl.style.display="none",this.agentTextEl.textContent="",this.thinkingEl.style.display=this.busy?"inline-flex":"none"),this.phoneBtn&&(this.phoneBtn.disabled=this.busy||this.recording),this.updateBusyState()}setStatus(e){this.status=e,this.render()}setCaption(e){this.caption=e,this.render()}updateBusyState(){this.inputEl.disabled=this.recording||this.touringActive,this.sendBtn.disabled=this.busy||this.recording||!this.inputEl.value.trim(),this.sendBtn.innerHTML=this.busy?Rr:Ot,this.micBtn&&(this.micBtn.disabled=this.touringActive)}setAnswer(e){this.answer=e,this.render()}renderCaptionWords(e,n){e.innerHTML="";let r=n.split(" ");r.forEach((i,a)=>{let o=document.createElement("span");o.className="cairn-word",o.style.animationDelay=`${Math.min(a*55,2800)}ms`,o.textContent=a<r.length-1?i+" ":i,e.appendChild(o)})}reportMiss(e){_(e);let n=this.reportMissesEndpoint;n&&fetch(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}).catch(()=>{})}async ask(e){this.setStatus("asking"),this.setAnswer(null),this.lastQuestion=e,this.inputEl.value="",this.render();try{let r=await(await fetch(this.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:location.pathname,question:e,visible:Fe(),history:this.history})})).json().catch(()=>null);this.handleVerb(r),this.history=[...this.history,{role:"user",text:e},{role:"assistant",text:Br(r)}].slice(-Sr)}catch{this.setAnswer("Something went wrong reaching the help service \u2014 try again in a moment.")}finally{this.setStatus("idle")}}handleVerb(e){At(e,location.pathname,{onExplain:n=>{this.setAnswer(n),this.realtimeActive||this.speak(n)},onNavigate:n=>{location.assign(n)},onMiss:n=>this.reportMiss(n),onDo:(n,r)=>{this.dispatchEvent(new CustomEvent("cairn-do",{detail:{action:n,target:r},bubbles:!0,composed:!0}))},onTour:n=>void this.runTour(n),registeredActions:this.registeredActions})}async runTour(e){let n=++this.tourGeneration,r=this.realtimeActive;this.touringActive=!0,r&&this.setStatus("rt-speaking"),this.setAnswer(null);let i=location.pathname;try{for(let a=0;a<e.length;a++){if(this.tourGeneration!==n)return;let o=e[a];if(this.setCaption(`Step ${a+1} of ${e.length}`),this.setAnswer(o.text),o.route&&o.route!==i){location.assign(o.route);return}if(o.target){let c=O(o.target);c?R(c):this.reportMiss({attempted:o.target,route:i})}if(r&&this.rtSocket?.readyState===WebSocket.OPEN?await this.speakOverRealtime(o.text):this.speakEndpoint?await this.speakAndWait(o.text):await new Promise(c=>setTimeout(c,Math.max(1200,o.text.length*45))),this.tourGeneration!==n)return}if(this.tourGeneration!==n)return;this.setCaption(""),r&&this.realtimeActive&&this.setStatus("rt-listening")}finally{this.tourGeneration===n&&(this.touringActive=!1,this.render())}}playResponseAudio(e){this.activeAudio&&(this.activeAudio.pause(),this.activeAudio.currentTime=0);let n=URL.createObjectURL(e),r=new Audio(n);return this.activeAudio=r,new Promise(i=>{let a=()=>{URL.revokeObjectURL(n),this.activeAudio===r&&(this.activeAudio=null),i()};r.onended=a,r.play().catch(a)})}async speak(e){if(!(!this.speakEndpoint||!e.trim()))try{let n=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!n.ok)return;this.playResponseAudio(await n.blob())}catch{}}async speakAndWait(e){if(!(!this.speakEndpoint||!e.trim()))try{let n=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!n.ok)return;await this.playResponseAudio(await n.blob())}catch{}}speakOverRealtime(e){return new Promise(n=>{let r=this.rtSocket;if(!r||r.readyState!==WebSocket.OPEN){n();return}this.rtAudioDoneArriving=!1;let i=!1,a=()=>{i||(i=!0,this.rtTourAudioDoneResolve=null,n())};this.rtTourAudioDoneResolve=a,setTimeout(()=>{i||console.warn("[cairn] tour step audio confirmation timed out \u2014 continuing"),a()},15e3),r.send(JSON.stringify({type:"speak",text:e}))})}async startRecording(){if(!(!this.transcribeEndpoint||!this.micSupported()||this.realtimeActive))try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=new MediaRecorder(e);this.audioChunks=[],this.setCaption(""),n.ondataavailable=r=>{r.data.size!==0&&(this.audioChunks.push(r.data),this.transcribeSoFar(n.mimeType||"audio/webm",!0))},n.onstop=()=>void this.transcribeSoFar(n.mimeType||"audio/webm",!1),this.mediaRecorder=n,n.start(2e3),this.recording=!0,this.micBtn&&(this.micBtn.innerHTML=Mr,this.micBtn.classList.add("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Stop recording")),this.render()}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site.")}}stopRecording(){let e=this.mediaRecorder?.stream;this.mediaRecorder?.stop(),e?.getTracks().forEach(n=>n.stop()),this.recording=!1,this.micBtn&&(this.micBtn.innerHTML=He,this.micBtn.classList.remove("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Ask by voice")),this.render()}async transcribeSoFar(e,n){if(this.transcribeEndpoint&&!(n&&this.transcribeInFlight)){this.transcribeInFlight=!0;try{let r=new Blob(this.audioChunks,{type:e}),a=await(await fetch(this.transcribeEndpoint,{method:"POST",headers:{"content-type":e},body:r})).json().catch(()=>null);a?.text?(this.inputEl.value=a.text,this.setCaption(a.text),this.updateBusyState()):n||this.setAnswer("Couldn't make that out \u2014 try typing instead.")}catch{n||this.setAnswer("Couldn't reach the transcription service.")}finally{this.transcribeInFlight=!1}}}isStaleRtMessage(e){return typeof e.generation=="number"&&e.generation<this.rtLastFinalGeneration}async startRealtime(){if(!(!this.realtimeUrl||!this.micSupported()||this.realtimeActive||this.rtStarting)){this.rtStarting=!0,this.setAnswer(null),this.setCaption(""),this.setStatus("rt-connecting");try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=new WebSocket(this.realtimeUrl);n.binaryType="arraybuffer",this.rtSocket=n;let r=new AudioContext,i=r.createGain();i.gain.value=this.rtSpeakerMuted?0:1,i.connect(r.destination),this.rtPlaybackCtx=r,this.rtPlaybackGain=i,this.rtNextPlayTime=0,this.rtScheduledSources=[],this.rtAudioDoneArriving=!0;let a=new AudioContext,o=a.createMediaStreamSource(e),c=a.createScriptProcessor(4096,1,1),d=a.createGain();d.gain.value=0;let u=Mt(),m=Rt(),k=()=>{if(this.rtAudioDoneArriving&&!(this.rtScheduledSources.length>0)){if(this.touringActive){this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null;return}a.resume().catch(()=>{}),this.setStatus("rt-listening"),this.setCaption("")}},B=()=>{this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null)},te=()=>{B(),this.rtThinkingWatchdog=setTimeout(()=>{this.rtThinkingWatchdog=null,console.warn("[cairn] realtime turn timed out waiting on the server \u2014 resuming listening"),at(),this.setAnswer("That's taking longer than expected \u2014 try asking again.")},2e4)},Ae=()=>{for(let E of this.rtScheduledSources)try{E.stop()}catch{}this.rtScheduledSources=[],this.rtNextPlayTime=this.rtPlaybackCtx?.currentTime??0},at=()=>{B(),Ae(),this.rtAudioDoneArriving=!0,n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({type:"barge_in"})),this.setStatus("rt-listening"),this.setCaption("")};c.onaudioprocess=E=>{if(n.readyState!==WebSocket.OPEN||this.rtMicMuted)return;if(this.status==="rt-speaking"&&!this.touringActive){let ne=u.process(E.inputBuffer.getChannelData(0)),Ie=E.inputBuffer.length/a.sampleRate*1e3;m.update(ne,Ie)&&at();return}if(m.reset(),this.status!=="rt-listening")return;let w=Pr(jr(E.inputBuffer.getChannelData(0),a.sampleRate));n.send(w)},o.connect(c),c.connect(d),d.connect(a.destination);let Lt=setInterval(()=>{a.state!=="running"&&a.resume().catch(()=>{});let E=e.getAudioTracks()[0];E&&(E.readyState==="ended"||E.muted)&&(this.setAnswer("The microphone connection was lost \u2014 try starting the call again."),this.endRealtime())},2e3),st=()=>{this.setAnswer("The microphone connection was lost \u2014 try starting the call again."),this.endRealtime()};e.getAudioTracks().forEach(E=>E.addEventListener("ended",st)),this.rtCleanup=()=>{clearInterval(Lt),e.getAudioTracks().forEach(E=>E.removeEventListener("ended",st)),c.disconnect(),o.disconnect(),e.getTracks().forEach(E=>E.stop()),a.close(),Ae(),r.close(),this.rtPlaybackCtx=null,this.rtPlaybackGain=null},n.onopen=()=>{n.send(JSON.stringify({type:"context",route:location.pathname,visible:Fe()})),this.setStatus("rt-listening"),this.rtStarting=!1},n.onmessage=E=>{if(typeof E.data!="string")return;let w=JSON.parse(E.data);if(w.type==="interim")this.setCaption(w.text);else if(w.type==="final")this.rtLastFinalGeneration=typeof w.generation=="number"?w.generation:0,this.setCaption(w.text),this.setStatus("rt-thinking"),te();else if(w.type==="verb"){if(this.isStaleRtMessage(w))return;B(),this.handleVerb(w.verb)}else if(w.type==="speaking_start"){if(this.isStaleRtMessage(w))return;B(),this.rtAudioDoneArriving=!1,this.setStatus("rt-speaking")}else if(w.type==="audio_chunk"){if(this.isStaleRtMessage(w))return;let ne=this.rtPlaybackCtx,Ie=this.rtPlaybackGain;if(!ne||!Ie)return;ne.resume().catch(()=>{});let ot=Uint8Array.from(atob(w.audio),J=>J.charCodeAt(0)),ze=ot.length/2,ct=new Float32Array(ze),Bt=new DataView(ot.buffer);for(let J=0;J<ze;J++)ct[J]=Bt.getInt16(J*2,!0)/32768;let jt=typeof w.sampleRate=="number"?w.sampleRate:24e3,Ze=ne.createBuffer(1,ze,jt);Ze.copyToChannel(ct,0);let be=ne.createBufferSource();be.buffer=Ze,be.connect(Ie);let lt=Math.max(ne.currentTime,this.rtNextPlayTime);be.start(lt),this.rtNextPlayTime=lt+Ze.duration,this.rtScheduledSources.push(be),be.onended=()=>{this.rtScheduledSources=this.rtScheduledSources.filter(J=>J!==be),k()}}else if(w.type==="speaking_end"||w.type==="turn_complete"){if(this.isStaleRtMessage(w))return;B(),this.rtAudioDoneArriving=!0,k()}else w.type==="error"&&(B(),this.setAnswer(w.message??"Something went wrong."),this.touringActive||(this.setStatus("rt-listening"),this.setCaption("")))},n.onerror=()=>{this.setAnswer("Couldn't connect to the realtime voice service."),this.endRealtime()},n.onclose=()=>{this.status!=="idle"&&this.endRealtime()}}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site."),this.setStatus("idle"),this.rtStarting=!1}}}endRealtime(){this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null),this.rtStarting=!1,this.activeAudio?.pause(),this.activeAudio=null,this.rtSocket?.close(),this.rtSocket=null,this.rtCleanup?.(),this.rtCleanup=null,this.rtMicMuted=!1,this.rtSpeakerMuted=!1,this.setCaption(""),this.setStatus("idle"),this.tourGeneration++,this.touringActive=!1,this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null,this.render()}toggleRtMic(){this.rtMicMuted=!this.rtMicMuted,this.render()}toggleRtSpeaker(){this.rtSpeakerMuted=!this.rtSpeakerMuted,this.rtPlaybackGain&&(this.rtPlaybackGain.gain.value=this.rtSpeakerMuted?0:1),this.render()}};function Br(t){if(!t||typeof t!="object")return"(no response)";let e=t;if(typeof e.text=="string"&&e.text)return e.text;switch(e.verb){case"highlight":case"open":return`(highlighted ${String(e.target)})`;case"navigate":return`(navigated to ${String(e.route)})`;case"do":return`(ran ${String(e.action)}${e.target?` on ${String(e.target)}`:""})`;case"tour":return Array.isArray(e.steps)?e.steps.map(n=>n.text??"").join(" "):"(tour)";default:return"(no response)"}}function jr(t,e){if(e===16e3)return t;let r=e/16e3,i=Math.round(t.length/r),a=new Float32Array(i),o=0,c=0;for(;o<i;){let d=Math.round((o+1)*r),u=0,m=0;for(let k=c;k<d&&k<t.length;k++)u+=t[k],m++;a[o]=m>0?u/m:0,o++,c=d}return a}function Pr(t){let e=new ArrayBuffer(t.length*2),n=new DataView(e);for(let r=0;r<t.length;r++){let i=Math.max(-1,Math.min(1,t[r]));n.setInt16(r*2,i<0?i*32768:i*32767,!0)}return e}typeof customElements<"u"&&!customElements.get("cairn-widget")&&customElements.define("cairn-widget",it);})();