@kya-os/mcp-i 1.11.0 → 1.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ "use strict";exports.id=337,exports.ids=[337],exports.modules={31337:(e,t,n)=>{n.r(t),n.d(t,{ANON_NONCE_TTL_MS:()=>D,AUTH_NONCE_TTL_MS:()=>I,AuditLogProvider:()=>nr,BitstringManager:()=>We,CascadingRevocationManager:()=>Ge,ClockProvider:()=>Cn,CryptoProvider:()=>Nn,DEFAULT_CLOCK_SKEW_SECONDS:()=>In,DEFAULT_SESSION_TTL_MINUTES:()=>S,DEFAULT_TIMESTAMP_SKEW_SECONDS:()=>k,DELEGATION_CREDENTIAL_CONTEXT:()=>y,DefaultPolicyEngine:()=>yr,DelegationCredentialIssuer:()=>Z,DelegationCredentialVerifier:()=>Ze,DelegationGraphManager:()=>Le,DidWebResolver:()=>an,ED25519_KEY_SIZE:()=>Kt,ED25519_PKCS8_DER_HEADER:()=>Mt,ED25519_SPKI_DER_HEADER_LENGTH:()=>Zt,FetchProvider:()=>Rn,GrantStore:()=>or,HOLDER_BINDING_ERROR:()=>Yt,IdentityProvider:()=>Zn,KYA_OS_ERROR_CODES:()=>a,KYA_OS_PROOF_META_KEY:()=>Lt,LEGACY_PROOF_META_KEY:()=>Ut,MAX_CLOCK_SKEW_SECONDS:()=>zn,MIN_CLOCK_SKEW_SECONDS:()=>Dn,MemoryAuditLogProvider:()=>rr,MemoryDelegationGraphStorage:()=>tn,MemoryGrantStore:()=>sr,MemoryIdentityProvider:()=>Un,MemoryNonceCacheProvider:()=>Ln,MemoryPendingFlowStore:()=>cr,MemoryResumeTokenStore:()=>vn,MemorySessionStore:()=>Hn,MemoryStatusListStorage:()=>en,MemoryStorageProvider:()=>Kn,NONCE_LENGTH_BYTES:()=>E,NodeCryptoProvider:()=>Yn,NonceCacheProvider:()=>Mn,NoopAuditLogProvider:()=>ir,NoopFetchProvider:()=>er,OUTBOUND_HEADER_NAMES:()=>Ct,PROOF_VERIFICATION_ERROR_CODES:()=>Sn,PendingFlowStore:()=>ar,ProofGenerator:()=>Ht,ProofVerificationError:()=>kn,ProofVerifier:()=>An,RiskClassifier:()=>fr,RuntimeFetchProvider:()=>Qn,SENSITIVE_VERBS:()=>lr,SessionManager:()=>Wn,SessionStore:()=>Jn,StatusList2021Manager:()=>Be,StorageProvider:()=>jn,SystemClockProvider:()=>Xn,assertHolderBinding:()=>Qt,base58Decode:()=>pt,base58Encode:()=>lt,base64ToBytes:()=>h,base64urlDecodeToBytes:()=>u,base64urlEncodeFromBytes:()=>p,buildAuditRecord:()=>tr,buildChainString:()=>ct,buildDelegationProofJWT:()=>at,buildDidResolverRegistry:()=>gn,buildDidWebDocument:()=>ln,buildOutboundDelegationHeaders:()=>Rt,buildPolicyRequest:()=>vr,bytesToBase64:()=>f,canonicalizeJSON:()=>N,compareDids:()=>gt,completeVCJWT:()=>j,createCascadingRevocationManager:()=>Ye,createDefaultConsoleLogger:()=>Dt,createDelegationGraph:()=>Ue,createDelegationIssuer:()=>K,createDelegationVerifier:()=>Ke,createDidKeyResolver:()=>Pt,createDidWebResolver:()=>cn,createHandshakeRequest:()=>Fn,createKyaOsError:()=>c,createKyaOsMiddleware:()=>Dr,createNeedsApprovalError:()=>$,createNeedsAuthorizationError:()=>z,createProofResponse:()=>Wt,createProofVerificationError:()=>En,createStatusListManager:()=>qe,createUnsignedVCJWT:()=>R,didKeyFragment:()=>Et,didWebToUrl:()=>sn,extractAgentId:()=>wt,extractAgentSlug:()=>bt,extractCanonicalData:()=>Ft,extractDelegationFromVC:()=>v,extractProofFromMeta:()=>Pn,extractPublicKeyFromDidKey:()=>Ot,generateDidKeyFromBase64:()=>kt,generateDidKeyFromBytes:()=>St,generateIdentity:()=>Ap,generateRequestProof:()=>Gt,getDidMethod:()=>mt,getServerDid:()=>vt,hasSensitiveScopes:()=>_n,isDelegationCredentialExpired:()=>w,isDelegationCredentialNotYetValid:()=>b,isDidWeb:()=>rn,isEd25519DidKey:()=>Tt,isHolderBindingApplicable:()=>Xt,isIndexSet:()=>Ve,isKyaOsControlArg:()=>Bt,isNeedsApprovalError:()=>T,isNeedsAuthorizationError:()=>A,isReservedMcpMetaKey:()=>On,isValidBase58:()=>ft,isValidDid:()=>ht,logger:()=>zt,matchScope:()=>kr,normalizeDid:()=>yt,parseDidWeb:()=>on,parseVCJWT:()=>M,publicKeyToJwk:()=>xt,resolveDidKeySync:()=>Nt,scopeSatisfies:()=>Er,toHolderBindingRequest:()=>qt,validateDelegationCredential:()=>_,validateDetachedProof:()=>x,validateHandshakeFormat:()=>Vn,validateMetaStructure:()=>xn,verifyApprovalQuorum:()=>gr,verifyDelegationAudience:()=>Xe,verifyDidLinkage:()=>fn,verifyOrHints:()=>wn,withKyaOs:()=>$p,wrapDelegationAsVC:()=>g});var r={};n.r(r),n.d(r,{base64:()=>eo,base64url:()=>to,bigint:()=>po,boolean:()=>mo,browserEmail:()=>Fi,cidrv4:()=>Xi,cidrv6:()=>Qi,cuid:()=>Ai,cuid2:()=>$i,date:()=>so,datetime:()=>uo,domain:()=>ro,duration:()=>Ni,e164:()=>io,email:()=>Li,emoji:()=>Bi,extendedDuration:()=>Ci,guid:()=>Ri,hex:()=>bo,hostname:()=>no,html5Email:()=>Ui,idnEmail:()=>Wi,integer:()=>fo,ipv4:()=>qi,ipv6:()=>Gi,ksuid:()=>xi,lowercase:()=>vo,mac:()=>Yi,md5_base64:()=>Eo,md5_base64url:()=>Io,md5_hex:()=>ko,nanoid:()=>Pi,null:()=>yo,number:()=>ho,rfc5322Email:()=>Ji,sha1_base64:()=>zo,sha1_base64url:()=>Ao,sha1_hex:()=>Do,sha256_base64:()=>To,sha256_base64url:()=>Oo,sha256_hex:()=>$o,sha384_base64:()=>Po,sha384_base64url:()=>No,sha384_hex:()=>xo,sha512_base64:()=>Ro,sha512_base64url:()=>jo,sha512_hex:()=>Co,string:()=>lo,time:()=>co,ulid:()=>Ti,undefined:()=>go,unicodeEmail:()=>Hi,uppercase:()=>wo,uuid:()=>ji,uuid4:()=>Mi,uuid6:()=>Zi,uuid7:()=>Ki,xid:()=>Oi});var i={};n.r(i),n.d(i,{endsWith:()=>Zc,gt:()=>_c,gte:()=>Sc,includes:()=>jc,length:()=>Pc,lowercase:()=>Cc,lt:()=>wc,lte:()=>bc,maxLength:()=>Oc,maxSize:()=>Ac,mime:()=>Lc,minLength:()=>xc,minSize:()=>$c,multipleOf:()=>zc,negative:()=>Ec,nonnegative:()=>Dc,nonpositive:()=>Ic,normalize:()=>Jc,overwrite:()=>Uc,positive:()=>kc,property:()=>Kc,regex:()=>Nc,size:()=>Tc,slugify:()=>Vc,startsWith:()=>Mc,toLowerCase:()=>Wc,toUpperCase:()=>Fc,trim:()=>Hc,uppercase:()=>Rc});var o={};n.r(o),n.d(o,{ZodISODate:()=>sd,ZodISODateTime:()=>id,ZodISODuration:()=>ud,ZodISOTime:()=>cd,date:()=>ad,datetime:()=>od,duration:()=>ld,time:()=>dd});var s={};n.r(s),n.d(s,{ZodAny:()=>Vu,ZodArray:()=>rl,ZodBase64:()=>fu,ZodBase64URL:()=>mu,ZodBigInt:()=>Ru,ZodBigIntFormat:()=>Mu,ZodBoolean:()=>Nu,ZodCIDRv4:()=>du,ZodCIDRv6:()=>lu,ZodCUID:()=>Vd,ZodCUID2:()=>qd,ZodCatch:()=>Xl,ZodCodec:()=>ip,ZodCustom:()=>yp,ZodCustomStringFormat:()=>_u,ZodDate:()=>tl,ZodDefault:()=>Hl,ZodDiscriminatedUnion:()=>hl,ZodE164:()=>gu,ZodEmail:()=>Od,ZodEmoji:()=>Jd,ZodEnum:()=>Al,ZodExactOptional:()=>Zl,ZodFile:()=>Pl,ZodFunction:()=>hp,ZodGUID:()=>Pd,ZodIPv4:()=>ru,ZodIPv6:()=>au,ZodIntersection:()=>yl,ZodJWT:()=>wu,ZodKSUID:()=>tu,ZodLazy:()=>up,ZodLiteral:()=>Ol,ZodMAC:()=>ou,ZodMap:()=>El,ZodNaN:()=>ep,ZodNanoID:()=>Wd,ZodNever:()=>Yu,ZodNonOptional:()=>Bl,ZodNull:()=>Wu,ZodNullable:()=>Ll,ZodNumber:()=>Du,ZodNumberFormat:()=>Au,ZodObject:()=>sl,ZodOptional:()=>jl,ZodPipe:()=>np,ZodPrefault:()=>Fl,ZodPromise:()=>pp,ZodReadonly:()=>sp,ZodRecord:()=>bl,ZodSet:()=>Dl,ZodString:()=>Ad,ZodStringFormat:()=>Td,ZodSuccess:()=>Gl,ZodSymbol:()=>Lu,ZodTemplateLiteral:()=>cp,ZodTransform:()=>Cl,ZodTuple:()=>vl,ZodType:()=>Dd,ZodULID:()=>Yd,ZodURL:()=>Kd,ZodUUID:()=>Cd,ZodUndefined:()=>Ju,ZodUnion:()=>ul,ZodUnknown:()=>qu,ZodVoid:()=>Qu,ZodXID:()=>Qd,ZodXor:()=>pl,_ZodString:()=>zd,_default:()=>Wl,_function:()=>mp,any:()=>Bu,array:()=>il,base64:()=>hu,base64url:()=>yu,bigint:()=>ju,boolean:()=>Cu,catch:()=>Ql,check:()=>gp,cidrv4:()=>uu,cidrv6:()=>pu,codec:()=>op,cuid:()=>Bd,cuid2:()=>Gd,custom:()=>vp,date:()=>nl,describe:()=>_p,discriminatedUnion:()=>ml,e164:()=>vu,email:()=>xd,emoji:()=>Hd,enum:()=>$l,exactOptional:()=>Kl,file:()=>Nl,float32:()=>Tu,float64:()=>Ou,function:()=>mp,guid:()=>Nd,hash:()=>Iu,hex:()=>Eu,hostname:()=>ku,httpUrl:()=>Ud,instanceof:()=>kp,int:()=>$u,int32:()=>xu,int64:()=>Zu,intersection:()=>gl,ipv4:()=>iu,ipv6:()=>cu,json:()=>Ip,jwt:()=>bu,keyof:()=>ol,ksuid:()=>nu,lazy:()=>lp,literal:()=>xl,looseObject:()=>dl,looseRecord:()=>kl,mac:()=>su,map:()=>Il,meta:()=>Sp,nan:()=>tp,nanoid:()=>Fd,nativeEnum:()=>Tl,never:()=>Xu,nonoptional:()=>ql,null:()=>Fu,nullable:()=>Ul,nullish:()=>Jl,number:()=>zu,object:()=>al,optional:()=>Ml,partialRecord:()=>Sl,pipe:()=>rp,prefault:()=>Vl,preprocess:()=>Dp,promise:()=>fp,readonly:()=>ap,record:()=>_l,refine:()=>wp,set:()=>zl,strictObject:()=>cl,string:()=>$d,stringFormat:()=>Su,stringbool:()=>Ep,success:()=>Yl,superRefine:()=>bp,symbol:()=>Uu,templateLiteral:()=>dp,transform:()=>Rl,tuple:()=>wl,uint32:()=>Pu,uint64:()=>Ku,ulid:()=>Xd,undefined:()=>Hu,union:()=>ll,unknown:()=>Gu,url:()=>Ld,uuid:()=>Rd,uuidv4:()=>jd,uuidv6:()=>Md,uuidv7:()=>Zd,void:()=>el,xid:()=>eu,xor:()=>fl});const a={invalid_proof:"invalid_proof",invalid_jws:"invalid_jws",nonce_replay:"nonce_replay",timestamp_skew:"timestamp_skew",did_not_found:"did_not_found",invalid_public_key:"invalid_public_key",handshake_failed:"handshake_failed",session_expired:"session_expired",invalid_request:"invalid_request",needs_authorization:"needs_authorization",insufficient_scope:"insufficient_scope",policy_denied:"policy_denied",delegation_expired:"delegation_expired",delegation_not_yet_valid:"delegation_not_yet_valid",delegation_revoked:"delegation_revoked",delegation_invalid:"delegation_invalid",holder_binding_failed:"holder_binding_failed",budget_exceeded:"budget_exceeded",rate_limit_exceeded:"rate_limit_exceeded",invalid_token:"invalid_token",token_expired:"token_expired",mirror_pending:"mirror_pending",claim_failed:"claim_failed",configuration_error:"configuration_error",runtime_error:"runtime_error"};function c(e,t,n){return n?{code:e,message:t,details:n}:{code:e,message:t}}function d(e){const t=m(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof Buffer){if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("Invalid base64url string: contains invalid characters");return Buffer.from(t,"base64").toString("utf-8")}if("undefined"!=typeof atob){const e=atob(t);if("undefined"!=typeof TextDecoder){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return(new TextDecoder).decode(t)}return e}throw new Error("Neither Buffer nor atob is available")}function u(e){const t=m(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}return new Uint8Array(Buffer.from(t,"base64"))}function l(e){if("undefined"!=typeof Buffer)return Buffer.from(e,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");if("undefined"!=typeof btoa){const t=(new TextEncoder).encode(e),n=Array.from(t).map(e=>String.fromCharCode(e)).join("");return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}throw new Error("Neither Buffer nor btoa is available")}function p(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function f(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}return Buffer.from(e).toString("base64")}function h(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const n=(4-t.length%4)%4;if(t+="=".repeat(n),"undefined"!=typeof atob){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}return new Uint8Array(Buffer.from(t,"base64"))}function m(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}const y="https://schema.kya-os.org/v1/protocol/delegation/context/v1.0.0";function g(e,t){const n=(new Date).toISOString(),r=e.constraints.notAfter?new Date(1e3*e.constraints.notAfter).toISOString():t?.expirationDate;let i=t?.issuanceDate||n;!t?.issuanceDate&&e.createdAt&&(i=new Date(e.createdAt).toISOString());const o=t?.scopes||e.constraints.scopes;return{"@context":["https://www.w3.org/2018/credentials/v1",y],id:t?.id||e.vcId||`urn:uuid:${e.id}`,type:["VerifiableCredential","DelegationCredential"],issuer:e.issuerDid,issuanceDate:i,...void 0!==r&&{expirationDate:r},credentialSubject:{id:e.subjectDid,delegation:{id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,...t?.userDid&&{userDid:t.userDid},...t?.userIdentifier&&{userIdentifier:t.userIdentifier},...t?.sessionId&&{sessionId:t.sessionId},...o&&o.length>0&&{scopes:o},...void 0!==e.controller&&{controller:e.controller},...void 0!==e.parentId&&{parentId:e.parentId},constraints:e.constraints,status:e.status,...void 0!==e.createdAt&&{createdAt:e.createdAt},...void 0!==e.metadata&&{metadata:e.metadata}}},...void 0!==t?.credentialStatus&&{credentialStatus:t.credentialStatus}}}function v(e){const t=e?.credentialSubject?.delegation;if(!t||"object"!=typeof t)throw new Error("extractDelegationFromVC: credential is missing credentialSubject.delegation");let n="";if(e.proof){const t=e.proof;n=t.proofValue||t.jws||t.signatureValue||""}return{id:t.id,issuerDid:t.issuerDid,subjectDid:t.subjectDid,controller:t.controller,vcId:e.id||`vc:${t.id}`,parentId:t.parentId,constraints:t.constraints,signature:n,status:t.status,createdAt:t.createdAt,revokedAt:void 0,revokedReason:void 0,metadata:t.metadata}}function w(e){if(e.expirationDate&&new Date(e.expirationDate)<new Date)return!0;const t=e.credentialSubject.delegation;return!!(t.constraints.notAfter&&Math.floor(Date.now()/1e3)>t.constraints.notAfter)}function b(e){const t=e.credentialSubject.delegation;return!!(t.constraints.notBefore&&Math.floor(Date.now()/1e3)<t.constraints.notBefore)}function _(e){if(!e||"object"!=typeof e)return{success:!1,error:{message:"Not an object"}};const t=e;if(!Array.isArray(t["@context"])||0===t["@context"].length)return{success:!1,error:{message:"Missing or invalid @context"}};if("https://www.w3.org/2018/credentials/v1"!==t["@context"][0])return{success:!1,error:{message:"First @context must be W3C VC context"}};if(!Array.isArray(t.type))return{success:!1,error:{message:"Missing type array"}};if(!t.type.includes("VerifiableCredential")||!t.type.includes("DelegationCredential"))return{success:!1,error:{message:"type must include VerifiableCredential and DelegationCredential"}};if(!t.issuer||"string"!=typeof t.issuer&&"object"!=typeof t.issuer)return{success:!1,error:{message:"Missing or invalid issuer"}};if(!t.issuanceDate||"string"!=typeof t.issuanceDate)return{success:!1,error:{message:"Missing issuanceDate"}};const n=t.credentialSubject;if(!n||"object"!=typeof n)return{success:!1,error:{message:"Missing credentialSubject"}};if(!n.id||"string"!=typeof n.id)return{success:!1,error:{message:"credentialSubject.id missing"}};const r=n.delegation;return r&&"object"==typeof r?r.id&&r.issuerDid&&r.subjectDid&&r.constraints?{success:!0,data:e}:{success:!1,error:{message:"delegation fields missing"}}:{success:!1,error:{message:"credentialSubject.delegation missing"}}}const S=30,k=120,E=16,I=12e4,D=6e4;function z(e){return{error:"needs_authorization",...e}}function A(e){return"object"==typeof e&&null!==e&&"needs_authorization"===e.error}function $(e){return{error:"needs_approval",...e}}function T(e){return"object"==typeof e&&null!==e&&"needs_approval"===e.error}const O=/^sha256:[a-f0-9]{64}$/;function x(e){if(!e||"object"!=typeof e)return{success:!1,error:{message:"Not an object"}};const t=e;if("string"!=typeof t.jws||t.jws.length<1)return{success:!1,error:{message:"jws must be a non-empty string"}};const n=t.meta;if(!n||"object"!=typeof n)return{success:!1,error:{message:"meta must be an object"}};const r=n,i=["did","kid","nonce","audience","sessionId"];for(const e of i)if("string"!=typeof r[e]||r[e].length<1)return{success:!1,error:{message:`meta.${e} must be a non-empty string`}};if("number"!=typeof r.ts||!Number.isInteger(r.ts)||r.ts<=0)return{success:!1,error:{message:"meta.ts must be a positive integer"}};if("string"!=typeof r.requestHash||!O.test(r.requestHash))return{success:!1,error:{message:"meta.requestHash must match sha256:<64 hex chars>"}};if(void 0!==r.responseHash&&("string"!=typeof r.responseHash||!O.test(r.responseHash)))return{success:!1,error:{message:"meta.responseHash must match sha256:<64 hex chars> when present"}};const o=["scopeId","delegationRef","clientDid","reason"];for(const e of o)if(void 0!==r[e]&&"string"!=typeof r[e])return{success:!1,error:{message:`meta.${e} must be a string if present`}};return void 0===r.outcome||["allowed","denied","step_up_required","needs_authorization"].includes(r.outcome)?{success:!0,data:e}:{success:!1,error:{message:"meta.outcome must be one of allowed | denied | step_up_required | needs_authorization"}}}var P=n(77753);function N(e){return C(e),(0,P.d)(e)}function C(e,t="$"){if(null!==e&&"boolean"!=typeof e&&"string"!=typeof e)if("number"!=typeof e){if(void 0===e)throw new TypeError(`Cannot canonicalize undefined at ${t}`);if("function"==typeof e)throw new TypeError(`Cannot canonicalize function at ${t}`);if("symbol"==typeof e)throw new TypeError(`Cannot canonicalize symbol at ${t}`);if("bigint"==typeof e)throw new TypeError(`Cannot canonicalize bigint at ${t}`);if(Array.isArray(e))for(let n=0;n<e.length;n++)C(e[n],`${t}[${n}]`);else if("object"!=typeof e);else for(const[n,r]of Object.entries(e))C(r,`${t}.${n}`)}else if(!Number.isFinite(e))throw new TypeError(`Cannot canonicalize non-finite number at ${t}: ${e}`)}function R(e,t={}){const n={alg:"EdDSA",typ:"JWT"};t.keyId&&(n.kid=t.keyId);const r="string"==typeof e.issuer?e.issuer:e.issuer?.id,i=e.credentialSubject?.id;let o,s;e.expirationDate&&"string"==typeof e.expirationDate&&(o=Math.floor(new Date(e.expirationDate).getTime()/1e3)),e.issuanceDate&&"string"==typeof e.issuanceDate&&(s=Math.floor(new Date(e.issuanceDate).getTime()/1e3));const a={...e};delete a.proof;const c={iss:r,vc:a};i&&(c.sub=i),o&&(c.exp=o),s&&(c.iat=s),e.id&&"string"==typeof e.id&&(c.jti=e.id);const d=l(JSON.stringify(n)),u=l(JSON.stringify(c));return{header:n,payload:c,encodedHeader:d,encodedPayload:u,signingInput:`${d}.${u}`}}function j(e,t){return`${e}.${t}`}function M(e){const t=e.split(".");if(3!==t.length)return null;try{const e=d(t[0]),n=d(t[1]);return{header:JSON.parse(e),payload:JSON.parse(n),signature:t[2],signingInput:`${t[0]}.${t[1]}`}}catch{return null}}class Z{identity;signingFunction;constructor(e,t){this.identity=e,this.signingFunction=t}async issueDelegationCredential(e,t={}){let n=g(e,{id:t.id,issuanceDate:t.issuanceDate,expirationDate:t.expirationDate,credentialStatus:t.credentialStatus});if(t.additionalContexts&&t.additionalContexts.length>0){const e=n["@context"];n={...n,"@context":[...e,...t.additionalContexts]}}const r=this.canonicalizeVC(n),i=await this.signingFunction(r,this.identity.getDid(),this.identity.getKeyId());return{...n,proof:i}}async createAndIssueDelegation(e,t={}){const n=Date.now(),r={id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,controller:e.controller,vcId:t.id||`urn:uuid:${e.id}`,parentId:e.parentId,constraints:e.constraints,signature:"",status:e.status||"active",createdAt:n,metadata:e.metadata};return this.issueDelegationCredential(r,t)}canonicalizeVC(e){return N(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}function K(e,t){return new Z(e,t)}const L=["id","delegation"];function U(e,t={}){const n=_(e);if(!n.success)return{valid:!1,reason:`Schema validation failed: ${n.error?.message}`};if(w(e))return{valid:!1,reason:"Delegation credential expired"};if(b(e))return{valid:!1,reason:"Delegation credential not yet valid"};const r=e.credentialSubject.delegation;if("revoked"===r.status)return{valid:!1,reason:"Delegation status is revoked"};if("expired"===r.status)return{valid:!1,reason:"Delegation status is expired"};if(!r.issuerDid||!r.subjectDid)return{valid:!1,reason:"Missing issuer or subject DID"};if((t.requireEmbeddedProof??1)&&!e.proof)return{valid:!1,reason:"Missing proof"};const i=function(e){const t=Object.keys(e.credentialSubject).filter(e=>!L.includes(e));return 0===t.length?{valid:!0}:{valid:!1,reason:`credentialSubject contains non-delegation field(s): ${t.join(", ")}. A DelegationCredential subject MUST carry only 'id' and 'delegation' (KYA-OS §11.6).`}}(e);return i.valid?{valid:!0}:i}async function J(e,t){const n=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,outcome:"revoked",durationMs:Date.now()-n}:{valid:!0,durationMs:Date.now()-n}:{valid:!1,reason:"Credential has credentialStatus but no status list resolver is configured — cannot verify revocation status",outcome:"status_unresolvable",durationMs:Date.now()-n}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,outcome:"status_unresolvable",durationMs:Date.now()-n}}}const H=new TextEncoder,W=new TextDecoder;function F(...e){const t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}function V(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r>127)throw new TypeError("non-ASCII string encountered in encode()");t[n]=r}return t}function B(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function q(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:W.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=W.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return B(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function G(e){let t=e;return"string"==typeof t&&(t=H.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=[];for(let n=0;n<e.length;n+=32768)t.push(String.fromCharCode.apply(null,e.subarray(n,n+32768)));return btoa(t.join(""))}(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class Y extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class X extends Y{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class Q extends Y{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class ee extends Y{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class te extends Y{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;class ne extends Y{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}const re=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},ie=e=>{const t=e.data[e.pos++];if(128&t){const n=127&t;let r=0;for(let t=0;t<n;t++)r=r<<8|e.data[e.pos++];return r}return t},oe=(e,t,n)=>{if(e.data[e.pos++]!==t)throw new Error(n)},se=(e,t)=>{const n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},ae=(e,t,n)=>{const r=((e,t)=>B(e.replace(t,"")))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);let i=n;return t?.startsWith?.("ECDH-ES")&&(i||={},i.getNamedCurve=e=>{const t={data:e,pos:0};return function(e){oe(e,48,"Invalid PKCS#8 structure"),ie(e),oe(e,2,"Expected version field");const t=ie(e);e.pos+=t,oe(e,48,"Expected algorithm identifier");ie(e);e.pos}(t),(e=>{const t=(e=>{oe(e,6,"Expected algorithm OID");const t=ie(e);return se(e,t)})(e);if(re(t,[43,101,110]))return"X25519";if(!re(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");oe(e,6,"Expected curve OID");const n=ie(e),r=se(e,n);for(const{name:e,oid:t}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(re(r,t))return e;throw new Error("Unsupported named curve")})(t)}),(async(e,t,n,r)=>{let i,o;const s="spki"===e,a=()=>s?["verify"]:["sign"];switch(n){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},o=a();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},o=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},o=s?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":case"ES384":case"ES512":i={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[n]},o=a();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{const e=r.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new Q("Invalid or unsupported key format")}o=s?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":i={name:"Ed25519"},o=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:n},o=a();break;default:throw new Q('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,r?.extractable??!!s,o)})("pkcs8",r,t,i)},ce='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function de(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:n}=function(e){let t,n;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},n=e.priv?["sign"]:["verify"];break;default:throw new Q(ce)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Q(ce)}break;case"EC":switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new Q(ce)}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new Q(ce)}break;default:throw new Q('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:n}}(e),r={...e};return"AKP"!==r.kty&&delete r.alg,delete r.use,crypto.subtle.importKey("jwk",r,t,e.ext??(!e.d&&!e.priv),e.key_ops??n)}const ue=e=>"object"==typeof e&&null!==e;function le(e){if(!ue(e)||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function pe(...e){const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let n;for(const e of t){const t=Object.keys(e);if(n&&0!==n.size)for(const e of t){if(n.has(e))return!1;n.add(e)}else n=new Set(t)}return!0}const fe=e=>le(e)&&"string"==typeof e.kty;async function he(e,t,n){if(!le(e))throw new TypeError("JWK must be an object");let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return q(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new Q('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return de({...e,alg:t,ext:r});case"AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return de({...e,ext:r});case"EC":case"OKP":return de({...e,alg:t,ext:r});default:throw new Q('Unsupported "kty" (Key Type) Parameter value')}}const me=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),ye=(e,t)=>e.name===t;function ge(e,t){const n=function(e){return parseInt(e.name.slice(4),10)}(e.hash);if(n!==t)throw me(`SHA-${t}`,"algorithm.hash")}function ve(e,t,n){switch(t){case"HS256":case"HS384":case"HS512":if(!ye(e.algorithm,"HMAC"))throw me("HMAC");ge(e.algorithm,parseInt(t.slice(2),10));break;case"RS256":case"RS384":case"RS512":if(!ye(e.algorithm,"RSASSA-PKCS1-v1_5"))throw me("RSASSA-PKCS1-v1_5");ge(e.algorithm,parseInt(t.slice(2),10));break;case"PS256":case"PS384":case"PS512":if(!ye(e.algorithm,"RSA-PSS"))throw me("RSA-PSS");ge(e.algorithm,parseInt(t.slice(2),10));break;case"Ed25519":case"EdDSA":if(!ye(e.algorithm,"Ed25519"))throw me("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!ye(e.algorithm,t))throw me(t);break;case"ES256":case"ES384":case"ES512":{if(!ye(e.algorithm,"ECDSA"))throw me("ECDSA");const n=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==n)throw me(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}(e,n)}function we(e,t,...n){if((n=n.filter(Boolean)).length>2){const t=n.pop();e+=`one of type ${n.join(", ")}, or ${t}.`}else 2===n.length?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const be=(e,t,...n)=>we(`Key for the ${e} algorithm must be `,t,...n);function _e(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Se(e,t){const n=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:n,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:n,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:n,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:n,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new Q(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function ke(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(we("Key must be ",t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[n])}return ve(t,e,n),t}function Ee(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function Ie(e,t,n){try{return q(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}Symbol();const De=e=>{if("CryptoKey"===e?.[Symbol.toStringTag])return!0;try{return e instanceof CryptoKey}catch{return!1}},ze=e=>"KeyObject"===e?.[Symbol.toStringTag],Ae=e=>De(e)||ze(e),$e=e=>e?.[Symbol.toStringTag],Te=(e,t,n)=>{if(void 0!==t.use){let e;switch(n){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case"sign"===n||"verify"===n:case"dir"===e:case e.includes("CBC-HS"):r=n;break;case e.startsWith("PBES2"):r="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===n?"wrapKey":"unwrapKey":n;break;case"encrypt"===n&&e.startsWith("RSA"):r="wrapKey";break;case"decrypt"===n:r=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(r&&!1===t.key_ops?.includes?.(r))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0};function Oe(e,t,n){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,n)=>{if(!(t instanceof Uint8Array)){if(fe(t)){if((e=>"oct"===e.kty&&"string"==typeof e.k)(t)&&Te(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Ae(t))throw new TypeError(be(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError(`${$e(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,n);break;default:((e,t,n)=>{if(fe(t))switch(n){case"decrypt":case"sign":if((e=>"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d))(t)&&Te(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if((e=>"oct"!==e.kty&&void 0===e.d&&void 0===e.priv)(t)&&Te(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Ae(t))throw new TypeError(be(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError(`${$e(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(n){case"sign":throw new TypeError(`${$e(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${$e(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(n){case"verify":throw new TypeError(`${$e(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${$e(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,n)}}function xe(e,t,n,r,i){if(void 0!==i.crit&&void 0===r?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||void 0===r.crit)return new Set;if(!Array.isArray(r.crit)||0===r.crit.length||r.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of r.crit){if(!o.has(t))throw new Q(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===r[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}const Pe="given KeyObject instance cannot be used for this algorithm";let Ne;const Ce=async(e,t,n,r=!1)=>{Ne||=new WeakMap;let i=Ne.get(e);if(i?.[n])return i[n];const o=await de({...t,alg:n});return r&&Object.freeze(e),i?i[n]=o:Ne.set(e,{[n]:o}),o};async function Re(e,t){if(e instanceof Uint8Array)return e;if(De(e))return e;if(ze(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,t)=>{Ne||=new WeakMap;let n=Ne.get(e);if(n?.[t])return n[t];const r="public"===e.type,i=!!r;let o;if("x25519"===e.asymmetricKeyType){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(Pe)}o=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError(Pe);o=e.toCryptoKey(e.asymmetricKeyType,i,[r?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(Pe);o=e.toCryptoKey(e.asymmetricKeyType,i,[r?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let n;switch(t){case"RSA-OAEP":n="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":n="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":n="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":n="SHA-512";break;default:throw new TypeError(Pe)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:n},i,r?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:n},i,[r?"verify":"sign"])}if("ec"===e.asymmetricKeyType){const n=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw new TypeError(Pe);const s={ES256:"P-256",ES384:"P-384",ES512:"P-521"};s[t]&&n===s[t]&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:n},i,[r?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:n},i,r?[]:["deriveBits"]))}if(!o)throw new TypeError(Pe);return n?n[t]=o:Ne.set(e,{[t]:o}),o})(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return Ce(e,n,t)}if(fe(e))return e.k?q(e.k):Ce(e,e,t,!0);throw new Error("unreachable")}function je(e,t,n){return{valid:!1,reason:e,stage:"basic",metrics:void 0!==n?{basicCheckMs:n,totalMs:Date.now()-t}:{totalMs:Date.now()-t},checks:{basicValid:!1}}}async function Me(e,t,n,r){const i=Date.now(),o=(e,t)=>({valid:e,reason:t,durationMs:Date.now()-i});if(!r)return o(!1,"No DID resolver configured — signature cannot be verified");const s=await r.resolve(t);if(!s)return o(!1,`Could not resolve issuer DID: ${t}`);const a=function(e,t){return t?e.find(e=>e.id===t):e[0]}(s.verificationMethod??[],n);if(!a)return o(!1,n?`Verification method ${n} not found in DID Document`:"DID Document has no verification method");if(!a.publicKeyJwk)return o(!1,"Verification method missing publicKeyJwk");try{const t=await he(a.publicKeyJwk,"EdDSA");return await async function(e,t){if(e instanceof Uint8Array&&(e=W.decode(e)),"string"!=typeof e)throw new ee("Compact JWS must be a string or Uint8Array");const{0:n,1:r,2:i,length:o}=e.split(".");if(3!==o)throw new ee("Invalid Compact JWS");const s=await async function(e,t,n){if(!le(e))throw new ee("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new ee('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new ee("JWS Protected Header incorrect type");if(void 0===e.payload)throw new ee("JWS Payload missing");if("string"!=typeof e.signature)throw new ee("JWS Signature missing or incorrect type");if(void 0!==e.header&&!le(e.header))throw new ee("JWS Unprotected Header incorrect type");let r={};if(e.protected)try{const t=q(e.protected);r=JSON.parse(W.decode(t))}catch{throw new ee("JWS Protected Header is invalid")}if(!pe(r,e.header))throw new ee("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...r,...e.header};let o=!0;if(xe(ee,new Map([["b64",!0]]),n?.crit,r,i).has("b64")&&(o=r.b64,"boolean"!=typeof o))throw new ee('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=i;if("string"!=typeof s||!s)throw new ee('JWS "alg" (Algorithm) Header Parameter missing or invalid');const a=n&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError('"algorithms" option must be an array of strings');if(t)return new Set(t)}(0,n.algorithms);if(a&&!a.has(s))throw new X('"alg" (Algorithm) Header Parameter value not allowed');if(o){if("string"!=typeof e.payload)throw new ee("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new ee("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t&&(t=await t(r,e),c=!0),Oe(s,t,"verify");const d=F(void 0!==e.protected?V(e.protected):new Uint8Array,V("."),"string"==typeof e.payload?o?V(e.payload):H.encode(e.payload):e.payload),u=Ie(e.signature,"signature",ee),l=await Re(t,s),p=await async function(e,t,n,r){const i=await ke(e,t,"verify");_e(e,i);const o=Se(e,i.algorithm);try{return await crypto.subtle.verify(o,i,n,r)}catch{return!1}}(s,l,u,d);if(!p)throw new ne;let f;f=o?Ie(e.payload,"payload",ee):"string"==typeof e.payload?H.encode(e.payload):e.payload;const h={payload:f};return void 0!==e.protected&&(h.protectedHeader=r),void 0!==e.header&&(h.unprotectedHeader=e.header),c?{...h,key:l}:h}({payload:r,protected:n,signature:i},t,{algorithms:["EdDSA"]}),a={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...a,key:s.key}:a}(e,t),o(!0)}catch(e){return o(!1,`JWT envelope signature is not valid: ${function(e){return e instanceof Error?e.message:String(e)}(e)}`)}}class Ze{didResolver;statusListResolver;signatureVerifier;cache=new Map;cacheInsertionOrder=[];cacheTtl;maxCacheSize;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cacheTtl=e?.cacheTtl||6e4,this.maxCacheSize=e?.maxCacheSize??1e3}async verifyDelegationCredential(e,t={}){const n=Date.now();if(!t.skipCache){const t=this.getFromCache(e.id||"");if(t)return{...t,cached:!0}}const r=Date.now(),i=U(e),o=Date.now()-r;if(!i.valid)return{valid:!1,reason:i.reason,stage:"basic",metrics:{basicCheckMs:o,totalMs:Date.now()-n},checks:{basicValid:!1}};const s=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):async function(e,t,n){const r=Date.now();try{const i="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!n)return{valid:!1,reason:"No DID resolver or signature verifier configured — signature cannot be verified",durationMs:Date.now()-r};const o=await t.resolve(i);if(!o)return{valid:!1,reason:`Could not resolve issuer DID: ${i}`,durationMs:Date.now()-r};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-r};const s=e.proof.verificationMethod;if(!s)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-r};const a=function(e,t){return e.verificationMethod?.find(e=>e.id===t)}(o,s);if(!a)return{valid:!1,reason:`Verification method ${s} not found`,durationMs:Date.now()-r};const c=a.publicKeyJwk;if(!c)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-r};const d=await n(e,c);return{valid:d.valid,reason:d.reason,durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}(e,t.didResolver||this.didResolver,this.signatureVerifier),a=!t.skipStatus&&e.credentialStatus?J(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(e,s,a,o,n)}async verifyDelegationJwt(e,t={}){const n=Date.now(),r=function(e,t){const n=M(e);if(!n)return{failure:je("Not a valid VC-JWT (parse failed)",t)};const r=Date.now(),i=n.payload.vc,o=U(i,{requireEmbeddedProof:!1}),s=Date.now()-r;return o.valid?function(e){const t=e.issuer;return"string"==typeof t?t:t&&"object"==typeof t&&"string"==typeof t.id?t.id:void 0}(i)!==n.payload.iss?{failure:je("Credential `issuer` does not match the JWT `iss` (the verified signer)",t,s)}:{vc:i,issuerDid:n.payload.iss,kid:n.header.kid,basicCheckMs:s}:{failure:je(o.reason,t,s)}}(e,n);if("failure"in r)return r.failure;const{vc:i,issuerDid:o,kid:s,basicCheckMs:a}=r;if(!t.skipCache){const e=this.getFromCache(i.id||"");if(e)return{...e,cached:!0}}const c=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):Me(e,o,s,t.didResolver||this.didResolver),d=!t.skipStatus&&i.credentialStatus?J(i.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(i,c,d,a,n)}async finalizeVerification(e,t,n,r,i){const[o,s]=await Promise.all([t,n]),a=function(e,t,n,r){const i=e.valid&&t.valid;return{valid:i,reason:i?void 0:e.reason||t.reason||"Unknown failure",statusOutcome:t.outcome,stage:"complete",metrics:{basicCheckMs:n,signatureCheckMs:e.durationMs||0,statusCheckMs:t.durationMs||0,totalMs:Date.now()-r},checks:{basicValid:!0,signatureValid:e.valid,statusValid:t.valid}}}(o,s,r,i);return a.valid&&e.id&&this.setInCache(e.id,a),a}getFromCache(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.result:null}setInCache(e,t){for(;this.cache.size>=this.maxCacheSize&&this.cacheInsertionOrder.length>0;){const e=this.cacheInsertionOrder.shift();e&&this.cache.delete(e)}this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl}),this.cacheInsertionOrder.push(e)}clearCache(){this.cache.clear(),this.cacheInsertionOrder=[]}clearCacheEntry(e){this.cache.delete(e);const t=this.cacheInsertionOrder.indexOf(e);-1!==t&&this.cacheInsertionOrder.splice(t,1)}}function Ke(e){return new Ze(e)}class Le{storage;constructor(e){this.storage=e}async registerDelegation(e){const t={id:e.id,parentId:e.parentId,children:[],issuerDid:e.issuerDid,subjectDid:e.subjectDid,credentialStatusId:e.credentialStatusId};return await this.storage.setNode(t),e.parentId&&await this.addChildToParent(e.parentId,e.id),t}async addChildToParent(e,t){const n=await this.storage.getNode(e);if(!n)throw new Error(`Parent delegation not found: ${e}`);n.children.includes(t)||(n.children.push(t),await this.storage.setNode(n))}async getNode(e){return this.storage.getNode(e)}async getChildren(e){return this.storage.getChildren(e)}async getDescendants(e){return this.storage.getDescendants(e)}async getChain(e){return this.storage.getChain(e)}async isAncestor(e,t){return(await this.getChain(t)).some(t=>t.id===e)}async getDepth(e){return(await this.getChain(e)).length-1}async validateChain(e){const t=await this.getChain(e);if(0===t.length)return{valid:!1,reason:"Delegation not found"};for(let e=1;e<t.length;e++){const n=t[e-1],r=t[e];if(r.issuerDid!==n.subjectDid)return{valid:!1,reason:`Invalid chain: ${r.id} issued by ${r.issuerDid} but parent ${n.id} subject is ${n.subjectDid}`};if(r.parentId!==n.id)return{valid:!1,reason:`Invalid chain: ${r.id} parentId=${r.parentId} but actual parent is ${n.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const n=await this.storage.getNode(t.parentId);n&&(n.children=n.children.filter(t=>t!==e),await this.storage.setNode(n))}await this.storage.deleteNode(e)}}}function Ue(e){return new Le(e)}const Je=16777216,He="u";class We{compressor;bits;size;constructor(e,t,n){this.compressor=t,this.size=e;const r=Math.ceil(e/8);this.bits=new Uint8Array(r)}setBit(e,t){if(!Number.isInteger(e)||e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const n=Math.floor(e/8),r=e%8;t?this.bits[n]|=128>>r:this.bits[n]&=255^128>>r}getBit(e){if(!Number.isInteger(e)||e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const t=Math.floor(e/8),n=e%8;return!!(this.bits[t]&128>>n)}getSetBits(){const e=[];for(let t=0;t<this.size;t++)this.getBit(t)&&e.push(t);return e}async encode(){const e=await this.compressor.compress(this.bits);return He+this.base64urlEncode(e)}static async decode(e,t,n){const r=await Fe(e,n),i=8*r.length,o=new We(i,t,n);return o.bits=r,o}getRawBits(){return this.bits}getSize(){return this.size}base64urlEncode(e){return this.bytesToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}bytesToBase64(e){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}static fromSetBits(e,t,n,r){const i=new We(e,n,r);for(const e of t)i.setBit(e,!0);return i}}async function Fe(e,t){const n=await t.decompress(function(e){let t=(e[0]===He?e.slice(1):e).replace(/-/g,"+").replace(/_/g,"/");t+="=".repeat((4-t.length%4)%4);const n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}(e));if(n.length>Je)throw new Error(`Status list too large: ${n.length} bytes exceeds ${Je}`);return n}async function Ve(e,t,n){const r=await Fe(e,n),i=Math.floor(t/8),o=t%8;if(!Number.isInteger(t)||t<0||i>=r.length)throw new Error(`Bit index ${t} out of range for the status list`);return!!(r[i]&128>>o)}class Be{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;updateLocks=new Map;constructor(e,t,n,r,i,o){this.storage=e,this.identity=t,this.signingFunction=n,this.compressor=r,this.decompressor=i,this.statusListBaseUrl=o?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=o?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,n=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${n}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:n.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:n}=e,r=(this.updateLocks.get(n)??Promise.resolve()).then(()=>this.doUpdateStatus(e,t));this.updateLocks.set(n,r.catch(()=>{})),await r}async doUpdateStatus(e,t){const{statusListCredential:n,statusListIndex:r}=e,i=await this.storage.getStatusList(n);if(!i)throw new Error(`Status list not found: ${n}`);const o=await We.decode(i.credentialSubject.encodedList,this.compressor,this.decompressor),s=parseInt(r,10);o.setBit(s,t);const a=await o.encode(),c={...i,credentialSubject:{...i.credentialSubject,encodedList:a}},d={...c};delete d.proof;const u=N(d),l=await this.signingFunction(u,this.identity.getDid(),this.identity.getKeyId()),p={...c,proof:l};await this.storage.setStatusList(n,p)}async checkStatus(e){const{statusListCredential:t,statusListIndex:n}=e,r=await this.storage.getStatusList(t);if(!r)throw new Error(`Status list not found: ${t} — cannot determine revocation status`);!function(e,t){if("string"!=typeof e)throw new Error(`status list has no statusPurpose (expected "${t}") — fail-closed`);if(e!==t)throw new Error(`status list statusPurpose mismatch: "${e}" ≠ "${t}"`)}(r.credentialSubject.statusPurpose,e.statusPurpose);const i=await We.decode(r.credentialSubject.encodedList,this.compressor,this.decompressor);if(!/^[0-9]+$/.test(n))throw new Error(`Invalid statusListIndex "${n}" — must be a canonical non-negative decimal`);const o=Number(n);if(!Number.isSafeInteger(o))throw new Error(`statusListIndex "${n}" exceeds the safe integer range`);return i.getBit(o)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await We.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const n=new We(this.defaultListSize,this.compressor,this.decompressor),r=await n.encode(),i={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e,type:["VerifiableCredential","StatusList2021Credential"],issuer:this.identity.getDid(),issuanceDate:(new Date).toISOString(),credentialSubject:{id:`${e}#list`,type:"StatusList2021",statusPurpose:t,encodedList:r}},o=N(i),s=await this.signingFunction(o,this.identity.getDid(),this.identity.getKeyId()),a={...i,proof:s};await this.storage.setStatusList(e,a)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}function qe(e,t,n,r,i,o){return new Be(e,t,n,r,i,o)}class Ge{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const n=t.maxDepth||100,r=[],i=await this.graph.getNode(e);if(!i)throw new Error(`Delegation not found: ${e}`);const o=await this.graph.getDepth(e);if(o>n)throw new Error(`Delegation depth ${o} exceeds maximum ${n}`);const s=await this.revokeNode(i,!0,t.reason,t.dryRun);r.push(s),t.onRevoke&&await t.onRevoke(s);const a=await this.graph.getDescendants(e);for(const n of a){const i=await this.revokeNode(n,!1,`Cascaded from ${e}`,t.dryRun,e);r.push(i),t.onRevoke&&await t.onRevoke(i)}return r}async revokeNode(e,t,n,r,i){const o={delegationId:e.id,isRoot:t,parentId:i,timestamp:Date.now(),reason:n};if(r)return o;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return o}async restoreDelegation(e){const t=await this.graph.getNode(e);if(!t)throw new Error(`Delegation not found: ${e}`);const n={delegationId:t.id,isRoot:!0,timestamp:Date.now(),reason:"Restored"};if(t.credentialStatusId){const e=this.parseCredentialStatus(t.credentialStatusId);e&&await this.statusList.updateStatus(e,!1)}return n}async isRevoked(e){const t=await this.graph.getChain(e);for(const n of t)if(n.credentialStatusId){const t=this.parseCredentialStatus(n.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:n.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:n.id===e?void 0:n.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),n=[];(await this.isRevoked(e)).revoked&&n.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&n.push(e.id);return n}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,n,r]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(r,10).toString(),statusListCredential:n}}async validateDelegation(e){const t=await this.isRevoked(e);if(t.revoked)return{valid:!1,reason:t.revokedAncestor?`Ancestor ${t.revokedAncestor} is revoked`:"Delegation is revoked"};const n=await this.graph.validateChain(e);return n.valid?{valid:!0}:n}}function Ye(e,t){return new Ge(e,t)}function Xe(e,t){if(!e.constraints.audience)return!0;const n=e.constraints.audience;return"string"==typeof n?n===t:n.includes(t)}class Qe{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return Ee(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return Ee(this.#n,"setUnprotectedHeader"),this.#n=e,this}async sign(e,t){if(!this.#t&&!this.#n)throw new ee("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!pe(this.#t,this.#n))throw new ee("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this.#t,...this.#n};let r=!0;if(xe(ee,new Map([["b64",!0]]),t?.crit,this.#t,n).has("b64")&&(r=this.#t.b64,"boolean"!=typeof r))throw new ee('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=n;if("string"!=typeof i||!i)throw new ee('JWS "alg" (Algorithm) Header Parameter missing or invalid');let o,s,a,c;Oe(i,e,"sign"),r?(o=G(this.#e),s=V(o)):(s=this.#e,o=""),this.#t?(a=G(JSON.stringify(this.#t)),c=V(a)):(a="",c=new Uint8Array);const d=F(c,V("."),s),u=await Re(e,i),l=await async function(e,t,n){const r=await ke(e,t,"sign");_e(e,r);const i=await crypto.subtle.sign(Se(e,r.algorithm),r,n);return new Uint8Array(i)}(i,u,d),p={signature:G(l),payload:o};return this.#n&&(p.header=this.#n),this.#t&&(p.protected=a),p}}class et{#r;constructor(e){this.#r=new Qe(e)}setProtectedHeader(e){return this.#r.setProtectedHeader(e),this}async sign(e,t){const n=await this.#r.sign(e,t);if(void 0===n.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}const tt=e=>Math.floor(e.getTime()/1e3),nt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function rt(e){const t=nt.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let r;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":r=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":r=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":r=Math.round(3600*n);break;case"day":case"days":case"d":r=Math.round(86400*n);break;case"week":case"weeks":case"w":r=Math.round(604800*n);break;default:r=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-r:r}function it(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ot{#e;constructor(e){if(!le(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return H.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){"number"==typeof e?this.#e.nbf=it("setNotBefore",e):e instanceof Date?this.#e.nbf=it("setNotBefore",tt(e)):this.#e.nbf=tt(new Date)+rt(e)}set exp(e){"number"==typeof e?this.#e.exp=it("setExpirationTime",e):e instanceof Date?this.#e.exp=it("setExpirationTime",tt(e)):this.#e.exp=tt(new Date)+rt(e)}set iat(e){void 0===e?this.#e.iat=tt(new Date):e instanceof Date?this.#e.iat=it("setIssuedAt",tt(e)):this.#e.iat=it("setIssuedAt","string"==typeof e?tt(new Date)+rt(e):e)}}class st{#t;#i;constructor(e={}){this.#i=new ot(e)}setIssuer(e){return this.#i.iss=e,this}setSubject(e){return this.#i.sub=e,this}setAudience(e){return this.#i.aud=e,this}setJti(e){return this.#i.jti=e,this}setNotBefore(e){return this.#i.nbf=e,this}setExpirationTime(e){return this.#i.exp=e,this}setIssuedAt(e){return this.#i.iat=e,this}setProtectedHeader(e){return this.#t=e,this}async sign(e,t){const n=new et(this.#i.data());if(n.setProtectedHeader(this.#t),Array.isArray(this.#t?.crit)&&this.#t.crit.includes("b64")&&!1===this.#t.b64)throw new te("JWTs MUST NOT use unencoded payload");return n.sign(e,t)}}async function at(e){const{agentDid:t,userDid:n,delegationId:r,delegationChain:i,scopes:o,privateKeyJwk:s,kid:a,targetHostname:c}=e,d=await he(s,"EdDSA"),u=Math.floor(Date.now()/1e3),l=u+60;return await new st({delegation_id:r,delegation_chain:i,scope:o.join(",")}).setProtectedHeader({alg:"EdDSA",kid:a}).setIssuer(t).setSubject(n).setJti(crypto.randomUUID()).setAudience(c).setIssuedAt(u).setExpirationTime(l).sign(d)}function ct(e){return e.id||e.vcId?e.vcId?`${e.vcId}>${e.id}`:e.id:""}const dt="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ut=new Map;for(let e=0;e<dt.length;e++){const t=dt[e];void 0!==t&&ut.set(t,e)}function lt(e){if(0===e.length)return"";let t=BigInt(0);for(let n=0;n<e.length;n++){const r=e[n];void 0!==r&&(t=t*BigInt(256)+BigInt(r))}let n="";for(;t>0;)n=dt[Number(t%BigInt(58))]+n,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)n="1"+n;return n}function pt(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const n of e){const e=ut.get(n);if(void 0===e)throw new Error(`Invalid base58 character: ${n}`);t=t*BigInt(58)+BigInt(e)}const n=[];for(;t>0;)n.unshift(Number(t%BigInt(256))),t/=BigInt(256);let r=0;for(const t of e){if("1"!==t)break;r++}const i=new Uint8Array(r+n.length);return i.set(n,r),i}function ft(e){if(0===e.length)return!0;for(const t of e)if(!ut.has(t))return!1;return!0}function ht(e){return"string"==typeof e&&e.startsWith("did:")}function mt(e){if(!ht(e))return null;const t=e.match(/^did:([^:]+):/);return t?.[1]??null}function yt(e){return e.trim()}function gt(e,t){return yt(e)===yt(t)}function vt(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t}function wt(e){const t=e.split(":");return t[t.length-1]??e}function bt(e){return wt(e)}const _t=new Uint8Array([237,1]);function St(e){const t=new Uint8Array(_t.length+e.length);return t.set(_t),t.set(e,_t.length),`did:key:z${lt(t)}`}function kt(e){return St(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}function Et(e){return e.startsWith("did:key:")?e.slice(8):"keys-1"}const It={debug:10,info:20,warn:30,error:40};function Dt(){let e="info",t=!1;function n(n,...r){if(function(t){return It[t]>=It[e]}(n))if(t)console.error(...r);else switch(n){case"debug":"function"==typeof console.debug?console.debug(...r):console.log(...r);break;case"info":"function"==typeof console.info?console.info(...r):console.log(...r);break;case"warn":"function"==typeof console.warn?console.warn(...r):console.error(...r);break;case"error":console.error(...r)}}return{configure(n={}){n.level&&(e=n.level),!0===n.forceStderr?t=!0:!1===n.forceStderr?t=!1:"stdio"===n.transport?t=!0:"sse"!==n.transport&&"http"!==n.transport||(t=!1)},debug:(...e)=>n("debug",...e),info:(...e)=>n("info",...e),warn:(...e)=>n("warn",...e),error:(...e)=>n("error",...e)}}const zt=Dt(),At=new Uint8Array([237,1]),$t=32;function Tt(e){return e.startsWith("did:key:z6Mk")}function Ot(e){if(!e.startsWith("did:key:z"))return null;try{const t=pt(e.replace("did:key:","").slice(1));return t.length<At.length+$t||t[0]!==At[0]||t[1]!==At[1]?null:t.slice(At.length)}catch(e){return zt.debug("Failed to extract public key from did:key",e),null}}function xt(e){return{kty:"OKP",crv:"Ed25519",x:p(e)}}function Pt(){return{resolve:async e=>{if(!Tt(e))return null;const t=Ot(e);if(!t)return null;const n=xt(t),r=e.replace("did:key:",""),i=Et(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:n,publicKeyMultibase:r}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}}}function Nt(e){if(!Tt(e))return null;const t=Ot(e);if(!t)return null;const n=xt(t),r=e.replace("did:key:",""),i=Et(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:n,publicKeyMultibase:r}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}const Ct={AGENT_DID:"KYA-OS-Agent-DID",DELEGATION_CHAIN:"KYA-OS-Delegation-Chain",SESSION_ID:"KYA-OS-Session-Id",DELEGATION_PROOF:"KYA-OS-Delegation-Proof"};async function Rt(e){const{session:t,delegation:n,serverIdentity:r,targetUrl:i}=e;if(!t.agentDid)throw new Error("Session must have agentDid for outbound delegation");if(!t.sessionId)throw new Error("Session must have sessionId for outbound delegation");if(!n.vcId)throw new Error("Delegation must have vcId for outbound delegation");const o=function(e){try{return new URL(e).hostname}catch{return zt.warn("Failed to parse target URL, using as-is",{url:e}),e}}(i),s=function(e,t){const n=h(e),r=64===n.length?n.subarray(0,32):n;if(!Tt(t))throw new Error(`Server DID must be did:key with Ed25519: ${t}`);const i=Ot(t);if(!i)throw new Error(`Failed to extract public key from DID: ${t}`);return{kty:"OKP",crv:"Ed25519",x:p(i),d:p(r)}}(r.privateKey,r.did),a=await at({agentDid:r.did,userDid:t.agentDid,delegationId:n.id,delegationChain:n.vcId,scopes:["delegation:propagate"],privateKeyJwk:s,kid:r.kid,targetHostname:o});return zt.debug("Built outbound delegation headers",{agentDid:t.agentDid,delegationChain:n.vcId,sessionId:t.sessionId,targetHostname:o}),{"KYA-OS-Agent-DID":t.agentDid,"KYA-OS-Delegation-Chain":n.vcId,"KYA-OS-Session-Id":t.sessionId,"KYA-OS-Delegation-Proof":a}}class jt{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,n){try{return!0===await this.cryptoProvider.verify(e,t,n)}catch(e){return zt.error("[CryptoService] Ed25519 verification error:",e),!1}}parseJWS(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWS format: expected header.payload.signature");const[n,r,i]=t;let o,s,a;try{o=JSON.parse(d(n))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(r)try{s=JSON.parse(d(r))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{a=u(i)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:o,payload:s,signatureBytes:a,signingInput:`${n}.${r}`}}async verifyJWS(e,t,n){try{if(!this.isValidEd25519JWK(t))return zt.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(n?.expectedKid&&t.kid!==n.expectedKid)return zt.error("[CryptoService] Key ID mismatch"),!1;let r;try{r=this.parseJWS(e)}catch(t){if(void 0===n?.detachedPayload)return zt.error("[CryptoService] Invalid JWS format:",t),!1;{const n=e.split(".");if(3!==n.length||""!==n[1])return zt.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=n[0],t=n[2];r={header:JSON.parse(d(e)),payload:void 0,signatureBytes:u(t),signingInput:""}}catch{return zt.error("[CryptoService] Invalid detached JWS format"),!1}}}const i=n?.alg||"EdDSA";if(r.header.alg!==i)return zt.error(`[CryptoService] Unsupported algorithm: ${r.header.alg}, expected ${i}`),!1;let o,s;if(void 0!==n?.detachedPayload){const t=e.split(".")[0];let r;r=n.detachedPayload instanceof Uint8Array?p(n.detachedPayload):p((new TextEncoder).encode(n.detachedPayload)),o=(new TextEncoder).encode(`${t}.${r}`)}else{if(!r.signingInput)return zt.error("[CryptoService] Missing signing input for compact JWS"),!1;o=(new TextEncoder).encode(r.signingInput)}try{s=this.jwkToBase64PublicKey(t)}catch(e){return zt.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(o,r.signatureBytes,s)}catch(e){return zt.error("[CryptoService] JWS verification error:",e),!1}}isValidEd25519JWK(e){return"object"==typeof e&&null!==e&&"kty"in e&&"OKP"===e.kty&&"crv"in e&&"Ed25519"===e.crv&&"x"in e&&"string"==typeof e.x&&e.x.length>0}jwkToBase64PublicKey(e){const t=u(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return f(t)}}const Mt=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),Zt=12,Kt=32,Lt="org.kya-os/proof",Ut="proof";async function Jt(e,t,n){const r={method:e.method,...e.params?{params:e.params}:{}},i=await n((new TextEncoder).encode((0,P.d)(r)));return void 0===t?{requestHash:i}:{requestHash:i,responseHash:await n((new TextEncoder).encode((0,P.d)(t.data)))}}class Ht{identity;cryptoProvider;constructor(e,t){this.identity=e,this.cryptoProvider=t}async generateProof(e,t,n,r={}){const i=await this.generateCanonicalHashes(e,t),o={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:n.nonce,audience:n.audience,sessionId:n.sessionId,requestHash:i.requestHash,...void 0!==i.responseHash?{responseHash:i.responseHash}:{},...r};return{jws:await this.generateJWS(o),meta:o}}async hashRequest(e){return(await this.generateCanonicalHashes(e)).requestHash}async generateCanonicalHashes(e,t){return Jt(e,t,e=>this.cryptoProvider.hash(e))}async resolveSigningKey(){const e=this.identity.privateKey;return"string"==typeof e?async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ae(e,"EdDSA",void 0)}(this.formatPrivateKeyAsPEM(e)):e}async generateJWS(e){try{const t=await this.resolveSigningKey(),n={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,...void 0!==e.responseHash&&{responseHash:e.responseHash},ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid},...e.outcome&&{outcome:e.outcome},...e.reason&&{reason:e.reason}},r=(0,P.d)(n),i=(new TextEncoder).encode(r);return await new et(i).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(t)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=h(e).subarray(0,Kt),n=new Uint8Array(Mt.length+t.length);n.set(Mt),n.set(t,Mt.length);const r=f(n);return"-----BEGIN PRIVATE KEY-----\n"+(r.match(/.{1,64}/g)?.join("\n")??r)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,n){try{const r=await this.generateCanonicalHashes(t,n);if(e.meta.requestHash!==r.requestHash)return!1;if(void 0!==e.meta.responseHash&&(void 0===r.responseHash||e.meta.responseHash!==r.responseHash))return!1;const i=this.base64PublicKeyToJWK(this.identity.publicKey);return new jt(this.cryptoProvider).verifyJWS(e.jws,i,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch{return!1}}base64PublicKeyToJWK(e){const t=h(e);if(t.length!==Kt)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:p(t),kid:this.identity.kid}}}async function Wt(e,t,n,r,i,o={}){const s={data:t},a=new Ht(n,i),c=await a.generateProof(e,s,r,o);return s.meta={proof:c},s}function Ft(e,t){return{request:{method:e.method,...e.params?{params:e.params}:{}},response:t.data}}const Vt="_kyaos";function Bt(e){return e.startsWith(Vt)}function qt(e,t){const n={};for(const[e,r]of Object.entries(t))Bt(e)||(n[e]=r);return{method:e,params:n}}async function Gt(e){const{identity:t,crypto:n,toolName:r,args:i,audience:o,sessionId:s}=e,a=new Ht(t,n),c=qt(r,i),d=p(await n.randomBytes(16)),u=Math.floor(Date.now()/1e3);return a.generateProof(c,void 0,{sessionId:s??"",audience:o,nonce:d,timestamp:u,createdAt:u,lastActivity:u,ttlMinutes:30,identityState:"anonymous"})}const Yt="holder_binding_failed";function Xt(e){return null!==Ot(e)}async function Qt(e){const{proof:t,subjectDid:n,request:r,response:i,expectedAudience:o,proofVerifier:s}=e,a=Ot(n);if(!a)return{status:"not_applicable",reason:`Holder binding (phase 1) covers did:key subjects only; "${mt(n)??"unknown"}" is deferred to cnf-based binding`};if("object"!=typeof t?.meta||null===t.meta)return{status:"unbound",errorCode:Yt,reason:"Malformed proof: missing meta"};if(t.meta.did!==n)return{status:"unbound",errorCode:Yt,reason:"Proof subject does not match the delegation subject"};if(void 0!==o&&!(Array.isArray(o)?o:[o]).includes(t.meta.audience))return{status:"unbound",errorCode:Yt,reason:"Proof audience does not match this server",cause:"audience_mismatch"};const c=xt(a);c.kid=`${n}#${Et(n)}`;const d=await s.verifyProof(t,c,{request:r,...void 0!==i?{response:i}:{}});return d.valid?{status:"bound"}:{status:"unbound",errorCode:Yt,reason:"Request proof is not bound to the delegation subject",...void 0!==d.errorCode?{cause:d.errorCode}:{}}}class en{statusLists=new Map;indexCounters=new Map;async getStatusList(e){return this.statusLists.get(e)||null}async setStatusList(e,t){this.statusLists.set(e,t)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,n=t;return this.indexCounters.set(e,t+1),n}getIndexCount(e){return this.indexCounters.get(e)||0}clear(){this.statusLists.clear(),this.indexCounters.clear()}getAllStatusListIds(){return Array.from(this.statusLists.keys())}}class tn{nodes=new Map;async getNode(e){return this.nodes.get(e)||null}async setNode(e){this.nodes.set(e.id,e)}async getChildren(e){const t=this.nodes.get(e);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>void 0!==e):[]}async getChain(e){const t=[];let n=e;for(;n;){const e=this.nodes.get(n);if(!e)break;t.unshift(e),n=e.parentId}return t}async getDescendants(e){const t=[],n=[e],r=new Set;for(;n.length>0;){const e=n.shift();if(r.has(e))continue;r.add(e);const i=this.nodes.get(e);if(i)for(const e of i.children)if(!r.has(e)){n.push(e);const r=this.nodes.get(e);r&&t.push(r)}}return t}async deleteNode(e){this.nodes.delete(e)}clear(){this.nodes.clear()}getAllNodeIds(){return Array.from(this.nodes.keys())}getStats(){const e=Array.from(this.nodes.values()),t=e.filter(e=>null===e.parentId).length,n=e.filter(e=>0===e.children.length).length;let r=0;for(const t of e){const e=this.getChainSync(t.id);r=Math.max(r,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:n,maxDepth:r}}getChainSync(e){const t=[];let n=e;for(;n;){const e=this.nodes.get(n);if(!e)break;t.unshift(e),n=e.parentId}return t}}function nn(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.id&&0!==t.id.length&&"string"==typeof t.type&&0!==t.type.length&&"string"==typeof t.controller&&0!==t.controller.length}function rn(e){return e.startsWith("did:web:")}function on(e){if(!rn(e))return null;const t=e.slice(8);if(0===t.length)return null;const n=t.split(":"),r=decodeURIComponent(n[0]);return 0===r.length?null:{domain:r,path:n.slice(1).map(e=>decodeURIComponent(e))}}function sn(e){const t=on(e);if(!t)return null;const{domain:n,path:r}=t;let i=`https://${n}`;return 0===r.length?i+="/.well-known/did.json":i+="/"+r.join("/")+"/did.json",i}class an{fetchProvider;cache;cacheTtl;constructor(e,t){this.fetchProvider=e,this.cache=new Map,this.cacheTtl=t?.cacheTtl??3e5}async resolve(e){if(!rn(e))return null;const t=this.cache.get(e);if(t&&Date.now()<t.expiresAt)return t.document;const n=sn(e);if(!n)return zt.warn(`[DidWebResolver] Invalid did:web format: ${e}`),null;try{const t=await this.fetchProvider.fetch(n);if(!t.ok)return zt.warn(`[DidWebResolver] HTTP ${t.status} fetching ${n}`),null;let r;try{r=await t.json()}catch{return zt.warn(`[DidWebResolver] Invalid JSON from ${n}`),null}return function(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.id||0===t.id.length)return!1;if(void 0!==t.verificationMethod){if(!Array.isArray(t.verificationMethod))return!1;for(const e of t.verificationMethod)if(!nn(e))return!1}return!0}(r)?r.id!==e?(zt.warn(`[DidWebResolver] DID Document id mismatch: expected ${e}, got ${r.id}`),null):(this.cache.set(e,{document:r,expiresAt:Date.now()+this.cacheTtl}),r):(zt.warn(`[DidWebResolver] Invalid DID Document structure from ${n}`),null)}catch(t){return zt.warn(`[DidWebResolver] Error resolving ${e}: ${t instanceof Error?t.message:"Unknown error"}`),null}}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}function cn(e,t){return new an(e,t)}const dn=new Uint8Array([237,1]),un=["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/ed25519-2020/v1"];function ln(e,t){const n=Array.isArray(e)?e:[e],r=n[0];if(!r)throw new Error("buildDidWebDocument: at least one identity is required");const i=r.did;if(!rn(i))throw new Error(`buildDidWebDocument: identity.did must be a did:web DID (got "${i}")`);const o=n.map(e=>function(e,t){if(e.did!==t)throw new Error(`buildDidWebDocument: all identities must share one DID; got "${e.did}" alongside "${t}"`);if(!e.kid.startsWith(`${t}#`))throw new Error(`buildDidWebDocument: identity.kid "${e.kid}" does not reference identity.did "${t}"`);const n=function(e){const t=h(e);if(32!==t.length)throw new Error(`buildDidWebDocument: expected 32-byte Ed25519 public key, got ${t.length} bytes after base64 decode`);return t}(e.publicKey);return{id:e.kid,type:"Ed25519VerificationKey2020",controller:t,publicKeyJwk:xt(n),publicKeyMultibase:pn(n)}}(e,i)),s=o.map(e=>e.id);if(new Set(s).size!==s.length)throw new Error("buildDidWebDocument: every key needs a unique verification-method id (kid); got a duplicate");return{"@context":t?.additionalContexts?.length?[...un,...t.additionalContexts]:[...un],id:i,...t?.alsoKnownAs?.length?{alsoKnownAs:[...t.alsoKnownAs]}:{},verificationMethod:o,authentication:s,assertionMethod:s}}function pn(e){const t=new Uint8Array(dn.length+e.length);return t.set(dn),t.set(e,dn.length),`z${lt(t)}`}function fn(e){const t=e.requireBidirectional??!0,n=mn(e.primaryDid),r=mn(e.secondaryDid),i=e.primaryDidDocument,o=e.secondaryDidDocument,s={primaryReferencesSecondary:!1,secondaryReferencesPrimary:!1,primaryDocumentMatches:!1,secondaryDocumentMatches:!1};return yn(i)?yn(o)?(s.primaryDocumentMatches=mn(i.id)===n,s.secondaryDocumentMatches=mn(o.id)===r,s.primaryDocumentMatches&&s.secondaryDocumentMatches?(s.primaryReferencesSecondary=hn(i,r),s.secondaryReferencesPrimary=hn(o,n),t?s.primaryReferencesSecondary&&s.secondaryReferencesPrimary?{valid:!0,checks:s}:{valid:!1,reason:"Bidirectional alsoKnownAs linkage is not present",checks:s}:s.primaryReferencesSecondary||s.secondaryReferencesPrimary?{valid:!0,checks:s}:{valid:!1,reason:"No alsoKnownAs linkage is present",checks:s}):{valid:!1,reason:"DID Document id does not match expected DID",checks:s}):{valid:!1,reason:"Secondary DID Document is missing or malformed",checks:s}:{valid:!1,reason:"Primary DID Document is missing or malformed",checks:s}}function hn(e,t){return(e.alsoKnownAs??[]).some(e=>mn(e)===t)}function mn(e){return e.trim()}function yn(e){return!!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)&&"string"==typeof e.id&&0!==e.id.trim().length&&(void 0===e.alsoKnownAs||Array.isArray(e.alsoKnownAs)&&e.alsoKnownAs.every(e=>"string"==typeof e))}function gn(e,t){const n={};if(!e)return n;for(const[r,i]of Object.entries(e))/^[a-z0-9]+$/.test(r)&&("function"!=typeof i?n[r]=i:t&&(n[r]=i(t)));return n}class vn{tokens=new Map;ttl;constructor(e=6e5){this.ttl=e}async create(e,t,n){const r=new Uint8Array(16);globalThis.crypto.getRandomValues(r);const i=`rt_${Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}`,o=Date.now();return this.tokens.set(i,{agentDid:e,scopes:t,createdAt:o,expiresAt:o+this.ttl,metadata:n,fulfilled:!1}),i}async get(e){const t=this.tokens.get(e);return t?Date.now()>t.expiresAt?(this.tokens.delete(e),null):t.fulfilled?null:{agentDid:t.agentDid,scopes:t.scopes,createdAt:t.createdAt,expiresAt:t.expiresAt,metadata:t.metadata}:null}async fulfill(e){const t=this.tokens.get(e);t&&(t.fulfilled=!0)}clear(){this.tokens.clear()}}async function wn(e,t,n){const r=Date.now();let i,o;if(n.debug&&zt.debug(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),n.reputationService&&void 0!==n.authorization.minReputationScore){const r=n.authorization.unknownAgentPolicy??"require-consent";try{i=await async function(e,t){const n=t.apiUrl.replace(/\/$/,""),r={"Content-Type":"application/json"};let i;if(t.apiKey&&(r["X-API-Key"]=t.apiKey),i="v2"===t.apiFormat?await fetch(`${n}/v1/reputation/${encodeURIComponent(e)}`,{method:"POST",headers:r,body:JSON.stringify({include_details:!1})}):await fetch(`${n}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:r}),!i.ok){if(404===i.status)return{agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`Reputation API error: ${i.status} ${i.statusText}`)}const o=await i.json(),s=o.score??0,a=(o.level??o.riskLevel??"unknown").toLowerCase(),c="low"===a||"medium"===a||"high"===a?a:"unknown";return{agentDid:o.agent_did??o.agentDid??e,score:s,totalInteractions:o.totalInteractions??0,successRate:o.successRate??0,riskLevel:c,updatedAt:o.calculatedAt?new Date(o.calculatedAt).getTime():o.updatedAt??Date.now()}}(e,n.reputationService)}catch(t){zt.error("[AuthHandshake] Reputation service unreachable, treating agent as unknown:",t),i={agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()}}if(n.debug&&zt.debug(`[AuthHandshake] Reputation score: ${i.score}`),null===i.score){if("deny"===r)return{authorized:!1,authError:await bn(e,t,n,"Unknown agent denied by policy"),reputation:i,reason:"Unknown agent — policy: deny"};if("require-consent"===r)return{authorized:!1,authError:await bn(e,t,n,"Unknown agent requires consent"),reputation:i,reason:"Unknown agent — policy: require-consent"};n.debug&&zt.debug("[AuthHandshake] Unknown agent allowed by policy, skipping reputation gate")}if(null!==i.score&&i.score<n.authorization.minReputationScore)return n.debug&&zt.debug(`[AuthHandshake] Reputation ${i.score} < ${n.authorization.minReputationScore}, requiring authorization`),{authorized:!1,authError:await bn(e,t,n,"Agent reputation score below threshold"),reputation:i,reason:"Low reputation score"}}try{o=await n.delegationVerifier.verify(e,t)}catch(r){zt.error("[AuthHandshake] Delegation verification failed:",r);const i=`Delegation verification error: ${r instanceof Error?r.message:"Unknown error"}`;return{authorized:!1,authError:await bn(e,t,n,i),reason:i}}return o.valid&&o.delegation?(n.debug&&zt.debug(`[AuthHandshake] Delegation valid, authorized (${Date.now()-r}ms)`),{authorized:!0,delegation:o.delegation,credential:o.credential,reputation:i,reason:"Valid delegation found"}):(n.debug&&zt.debug(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-r}ms)`),{authorized:!1,authError:await bn(e,t,n,o.reason??"No valid delegation found"),reputation:i,reason:o.reason??"No delegation"})}async function bn(e,t,n,r){const i=await n.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),o=Date.now()+(n.authorization.resumeTokenTtl??6e5),s=new URL(n.authorization.authorizationUrl);s.searchParams.set("agent_did",e),s.searchParams.set("scopes",t.join(",")),s.searchParams.set("resume_token",i);const a={title:"Authorization Required",hint:["link","qr"],authorizationCode:i.substring(0,8).toUpperCase(),qrUrl:`https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(s.toString())}`};return z({message:r,authorizationUrl:s.toString(),resumeToken:i,expiresAt:o,scopes:t,display:a})}function _n(e){const t=["write","delete","admin","payment","transfer","execute","modify"];return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}const Sn={INVALID_PROOF_STRUCTURE:"INVALID_PROOF_STRUCTURE",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",NONCE_REPLAY_DETECTED:"NONCE_REPLAY_DETECTED",TIMESTAMP_SKEW_EXCEEDED:"TIMESTAMP_SKEW_EXCEEDED",TIMESTAMP_INVALID:"TIMESTAMP_INVALID",CONTENT_BINDING_MISMATCH:"CONTENT_BINDING_MISMATCH",INVALID_JWS_SIGNATURE:"INVALID_JWS_SIGNATURE",INVALID_JWS_FORMAT:"INVALID_JWS_FORMAT",INVALID_JWS_HEADER:"INVALID_JWS_HEADER",INVALID_JWS_PAYLOAD:"INVALID_JWS_PAYLOAD",INVALID_JWS_SIGNATURE_BASE64:"INVALID_JWS_SIGNATURE_BASE64",UNSUPPORTED_ALGORITHM:"UNSUPPORTED_ALGORITHM",INVALID_JWK_FORMAT:"INVALID_JWK_FORMAT",INVALID_JWK_KTY:"INVALID_JWK_KTY",INVALID_JWK_CRV:"INVALID_JWK_CRV",INVALID_JWK_X_FIELD:"INVALID_JWK_X_FIELD",INVALID_JWK_KEY_LENGTH:"INVALID_JWK_KEY_LENGTH",JWK_KID_MISMATCH:"JWK_KID_MISMATCH",DID_RESOLUTION_FAILED:"DID_RESOLUTION_FAILED",DID_DOCUMENT_NOT_FOUND:"DID_DOCUMENT_NOT_FOUND",VERIFICATION_METHOD_NOT_FOUND:"VERIFICATION_METHOD_NOT_FOUND",PUBLIC_KEY_NOT_FOUND:"PUBLIC_KEY_NOT_FOUND",UNSUPPORTED_DID_METHOD:"UNSUPPORTED_DID_METHOD",META_POLICY_VIOLATION:"META_POLICY_VIOLATION",VERIFICATION_ERROR:"VERIFICATION_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR"};class kn extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="ProofVerificationError"}}function En(e,t,n){return new kn(e,t,n)}const In=120,Dn=30,zn=600;class An{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;cryptoProvider;constructor(e){this.cryptoService=new jt(e.cryptoProvider),this.cryptoProvider=e.cryptoProvider,this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??In,this.nonceTtlSeconds=e.nonceTtlSeconds??300}setTimestampSkew(e){"number"==typeof e&&Number.isFinite(e)&&(this.timestampSkewSeconds=Math.max(Dn,Math.min(zn,Math.floor(e))))}getTimestampSkew(){return this.timestampSkewSeconds}async verifyProof(e,t,n){try{const r=this.buildCanonicalPayload(e.meta),i=(new TextEncoder).encode(r);return await this.runVerificationPipeline(e,t,i,n)}catch(e){return this.handleVerificationError(e)}}async verifyProofDetached(e,t,n){try{const r=t instanceof Uint8Array?t:(new TextEncoder).encode(t);return await this.runVerificationPipeline(e,n,r)}catch(e){return this.handleVerificationError(e)}}async runVerificationPipeline(e,t,n,r){const i=await this.validateProofStructure(e);if(!i.valid)return i;const o=i.proof,s=await this.validateNonce(o.meta.nonce,o.meta.did);if(!s.valid)return s;const a=await this.validateTimestamp(o.meta.ts);if(!a.valid)return a;const c=await this.verifySignature(o.jws,t,n,o.meta.kid);if(!c.valid)return c;if(void 0!==r){const e=await this.validateContentBinding(o,r);if(!e.valid)return e}return await this.addNonceToCache(o.meta.nonce,o.meta.did),{valid:!0}}async validateContentBinding(e,t){const{requestHash:n,responseHash:r}=await Jt(t.request,t.response,e=>this.cryptoProvider.hash(e));if(e.meta.requestHash!==n)return{valid:!1,reason:"Request hash mismatch: the proof does not bind the request you supplied",errorCode:Sn.CONTENT_BINDING_MISMATCH};const i=void 0!==e.meta.responseHash;return i!==(void 0!==t.response)?{valid:!1,reason:i?"Proof binds a response (responseHash present) but no response was supplied to verify against — pass expected.response":"A response was supplied but the proof binds none — content/proof mismatch",errorCode:Sn.CONTENT_BINDING_MISMATCH}:i&&e.meta.responseHash!==r?{valid:!1,reason:"Response hash mismatch: received content differs from what the server signed (possible substitution / MITM)",errorCode:Sn.CONTENT_BINDING_MISMATCH}:{valid:!0}}handleVerificationError(e){return{valid:!1,reason:"Proof verification error",errorCode:Sn.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}async validateProofStructure(e){const t=x(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:Sn.INVALID_PROOF_STRUCTURE,error:new Error(`Proof validation failed: ${t.error?.message}`),details:{validationError:t.error?.message}}}async validateNonce(e,t){return await this.nonceCache.has(e,t)?{valid:!1,reason:"Nonce already used (replay attack detected)",errorCode:Sn.NONCE_REPLAY_DETECTED,details:{nonce:e,agentDid:t}}:{valid:!0}}async validateTimestamp(e){const t=1e3*e;return this.clock.isWithinSkew(t,this.timestampSkewSeconds)?{valid:!0}:{valid:!1,reason:`Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,errorCode:Sn.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,n,r){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:n,expectedKid:r,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:Sn.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:r,actualKid:t.kid}}}async addNonceToCache(e,t){await this.nonceCache.add(e,this.nonceTtlSeconds,t)}async fetchPublicKeyFromDID(e,t){try{const n=await this.fetch.resolveDID(e);if(!n)throw new kn(Sn.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});const r=n;if(!r.verificationMethod||0===r.verificationMethod.length)throw new kn(Sn.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let i;if(t){const n=t.startsWith("#")?t:`#${t}`;if(i=r.verificationMethod.find(t=>t.id===n||t.id===`${e}${n}`),!i)throw new kn(Sn.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:r.verificationMethod.map(e=>e.id)})}else i=r.verificationMethod[0];if(!i?.publicKeyJwk)throw new kn(Sn.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:i?.id});const o=i.publicKeyJwk;if("OKP"!==o.kty||"Ed25519"!==o.crv||!o.x)throw new kn(Sn.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${o.kty}, crv=${o.crv}`,{did:e,kid:t,jwk:{kty:o.kty,crv:o.crv}});const s=o;return!s.kid&&i.id&&(s.kid=i.id),s}catch(n){if(n instanceof kn)throw n;throw zt.error("[ProofVerifier] Failed to fetch public key from DID",{error:n}),new kn(Sn.DID_RESOLUTION_FAILED,`DID resolution failed: ${n instanceof Error?n.message:String(n)}`,{did:e,kid:t,originalError:n instanceof Error?n.message:String(n)})}}buildCanonicalPayload(e){const t={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,...void 0!==e.responseHash&&{responseHash:e.responseHash},ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid},...e.outcome&&{outcome:e.outcome},...e.reason&&{reason:e.reason}};return(0,P.d)(t)}}const $n=["io.modelcontextprotocol/"],Tn=["traceparent","tracestate","baggage"];function On(e){return Tn.includes(e)||$n.some(t=>e.startsWith(t))}function xn(e,t="strict"){const n=Object.keys(e).filter(e=>e!==Lt&&e!==Ut);return"allow-extensions"===t&&n.length>0?{valid:!0,extraKeys:n}:{valid:!0}}function Pn(e,t="strict"){const n=e[Lt]??e[Ut];if(!n)return{success:!1,reason:"_meta does not contain a proof",errorCode:Sn.MISSING_REQUIRED_FIELD};xn(e,t);const r=x(n);return r.success?{success:!0,proof:r.data}:{success:!1,reason:r.error?.message??"Invalid proof structure",errorCode:Sn.INVALID_PROOF_STRUCTURE}}class Nn{}class Cn{}class Rn{}class jn{}class Mn{}class Zn{}class Kn extends jn{store=new Map;async get(e){return this.store.get(e)??null}async set(e,t){this.store.set(e,t)}async delete(e){this.store.delete(e)}async exists(e){return this.store.has(e)}async list(e){const t=Array.from(this.store.keys());return e?t.filter(t=>t.startsWith(e)):t}}class Ln extends Mn{nonces=new Map;async has(e,t){const n=t?`nonce:${t}:${e}`:`nonce:${e}`,r=this.nonces.get(n);return!(!r||Date.now()>r&&(this.nonces.delete(n),1))}async add(e,t,n){const r=n?`nonce:${n}:${e}`:`nonce:${e}`,i=Date.now()+1e3*t;this.nonces.set(r,i)}async cleanup(){const e=Date.now();for(const[t,n]of this.nonces)e>n&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}class Un extends Zn{identity;cryptoProvider;constructor(e){super(),this.cryptoProvider=e}async getIdentity(){return this.identity||(this.identity=await this.generateIdentity()),this.identity}async saveIdentity(e){this.identity=e}async rotateKeys(){return this.identity=await this.generateIdentity(),this.identity}async deleteIdentity(){this.identity=void 0}async generateIdentity(){if(!this.cryptoProvider)throw new Error("Crypto provider required for identity generation");const e=await this.cryptoProvider.generateKeyPair(),t=this.generateDIDFromPublicKey(e.publicKey);return{did:t,kid:`${t}#${Et(t)}`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return kt(e)}}class Jn{}class Hn extends Jn{sessions=new Map;insertionOrder=[];maxSessions;constructor(e={}){super(),this.maxSessions=e.maxSessions??1e4}async get(e){return this.sessions.get(e)}async set(e,t){this.sessions.has(e)||(this.evictIfNeeded(),this.insertionOrder.push(e)),this.sessions.set(e,t)}async delete(e){this.sessions.delete(e)}async entries(){return[...this.sessions.entries()]}async cleanup(){this.insertionOrder=this.insertionOrder.filter(e=>this.sessions.has(e))}async clear(){this.sessions.clear(),this.insertionOrder=[]}size(){return this.sessions.size}evictIfNeeded(){for(;this.sessions.size>=this.maxSessions&&this.insertionOrder.length>0;){const e=this.insertionOrder.shift();void 0!==e&&this.sessions.delete(e)}}}class Wn{config;cryptoProvider;sessionStore;constructor(e,t={}){this.cryptoProvider=e,this.sessionStore=t.sessionStore??new Hn({maxSessions:t.maxSessions??1e4}),this.config={timestampSkewSeconds:t.timestampSkewSeconds??120,sessionTtlMinutes:t.sessionTtlMinutes??30,nonceCache:t.nonceCache??new Ln,metaPolicy:t.metaPolicy??"strict",...void 0!==t.absoluteSessionLifetime&&{absoluteSessionLifetime:t.absoluteSessionLifetime},...void 0!==t.serverDid&&{serverDid:t.serverDid}},this.config.nonceCache instanceof Ln&&zt.warn("[SessionManager] Using MemoryNonceCacheProvider — not suitable for multi-instance deployments. Use Redis, DynamoDB, or Cloudflare KV for production.")}setServerDid(e){this.config.serverDid=e}async validateHandshake(e){try{const t=Math.floor(Date.now()/1e3),n=Math.abs(t-e.timestamp);if(n>this.config.timestampSkewSeconds)return{success:!1,error:{code:a.handshake_failed,message:`Timestamp outside acceptable range (±${this.config.timestampSkewSeconds}s)`,remediation:`Check NTP sync on client and server. Current server time: ${t}, received: ${e.timestamp}, diff: ${n}s. Adjust timestampSkewSeconds if needed.`}};if(this.config.serverDid&&e.audience!==this.config.serverDid)return{success:!1,error:{code:a.handshake_failed,message:`Audience mismatch: expected ${this.config.serverDid}, got ${e.audience}`}};if(await this.config.nonceCache.has(e.nonce,e.agentDid))return{success:!1,error:{code:a.handshake_failed,message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const r=e.agentDid?I:D,i=Math.ceil(r/1e3);await this.config.nonceCache.add(e.nonce,i,e.agentDid);const o=await this.generateSessionId(),s=await this.buildClientInfo(e),c={sessionId:o,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,identityState:"anonymous",metaPolicy:this.config.metaPolicy,agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid},...s&&{clientInfo:s}};return await this.sessionStore.set(o,c),{success:!0,session:c}}catch(e){return{success:!1,error:{code:a.handshake_failed,message:`Handshake validation failed: ${e instanceof Error?e.message:"Unknown error"}`}}}}async getSession(e){const t=await this.sessionStore.get(e);if(!t)return null;const n=Math.floor(Date.now()/1e3);return n-t.lastActivity>60*t.ttlMinutes||void 0!==this.config.absoluteSessionLifetime&&n-t.createdAt>60*this.config.absoluteSessionLifetime?(await this.sessionStore.delete(e),null):(t.lastActivity=n,await this.sessionStore.set(e,t),t)}async generateSessionId(){const e=await this.cryptoProvider.randomBytes(16);e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("");return`kyaos_${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}async generateClientId(){const e=await this.cryptoProvider.randomBytes(6);return`client_${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}`}normalizeClientInfoString(e){if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0}async buildClientInfo(e){if(!e.clientInfo&&"string"!=typeof e.clientProtocolVersion&&void 0===e.clientCapabilities)return;const t=e.clientInfo;return{name:this.normalizeClientInfoString(t?.name)??"unknown",title:this.normalizeClientInfoString(t?.title),version:this.normalizeClientInfoString(t?.version),platform:this.normalizeClientInfoString(t?.platform),vendor:this.normalizeClientInfoString(t?.vendor),persistentId:this.normalizeClientInfoString(t?.persistentId),clientId:this.normalizeClientInfoString(t?.clientId)??await this.generateClientId(),protocolVersion:this.normalizeClientInfoString(e.clientProtocolVersion),capabilities:e.clientCapabilities}}static generateNonce(){const e=new Uint8Array(16);globalThis.crypto.getRandomValues(e);let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,n]of await this.sessionStore.entries()){let r=e-n.lastActivity>60*n.ttlMinutes;r||void 0===this.config.absoluteSessionLifetime||(r=e-n.createdAt>60*this.config.absoluteSessionLifetime),r&&await this.sessionStore.delete(t)}await this.sessionStore.cleanup(),await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessionStore.size(),config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}async clearSessions(){await this.sessionStore.clear()}}function Fn(e){return{nonce:Wn.generateNonce(),audience:e,timestamp:Math.floor(Date.now()/1e3)}}function Vn(e){return"object"==typeof e&&null!==e&&"string"==typeof e.nonce&&e.nonce.length>0&&"string"==typeof e.audience&&e.audience.length>0&&"number"==typeof e.timestamp&&e.timestamp>0&&Number.isInteger(e.timestamp)}var Bn=n(77598);const qn=Buffer.from("302e020100300506032b657004220420","hex"),Gn=Buffer.from("302a300506032b6570032100","hex");class Yn extends Nn{async sign(e,t){const n=Buffer.from(t,"base64"),r=64===n.length?n.subarray(0,32):n,i=(0,Bn.createPrivateKey)({key:Buffer.concat([qn,r]),format:"der",type:"pkcs8"});return new Uint8Array((0,Bn.sign)(null,Buffer.from(e),i))}async verify(e,t,n){try{const r=(0,Bn.createPublicKey)({key:Buffer.concat([Gn,Buffer.from(n,"base64")]),format:"der",type:"spki"});return(0,Bn.verify)(null,Buffer.from(e),r,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=(0,Bn.generateKeyPairSync)("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{privateKey:t.subarray(16,48).toString("base64"),publicKey:e.subarray(12,44).toString("base64")}}async hash(e){return`sha256:${(0,Bn.createHash)("sha256").update(Buffer.from(e)).digest("hex")}`}async randomBytes(e){return new Uint8Array((0,Bn.randomBytes)(e))}}class Xn extends Cn{now(){return Date.now()}isWithinSkew(e,t){return Math.abs(Date.now()-e)<=1e3*t}hasExpired(e){return Date.now()>e}calculateExpiry(e){return Date.now()+1e3*e}format(e){return new Date(e).toISOString()}}class Qn extends Rn{didKeyResolver=Pt();didWebResolver;didResolvers;allowPrivateNetworkHosts;constructor(e){super(),this.allowPrivateNetworkHosts=e?.allowPrivateNetworkHosts??!1,this.didResolvers=gn(e?.didResolvers,this)}async resolveDID(e){const t=mt(e),n=t?this.didResolvers[t]:void 0;if(n)try{const t=await n.resolve(e);if(t)return t}catch{return null}return e.startsWith("did:key:")?this.didKeyResolver.resolve(e):rn(e)?this.isBlockedTarget(sn(e))?null:(this.didWebResolver||(this.didWebResolver=cn(this)),this.didWebResolver.resolve(e)):null}async fetchStatusList(e){if(this.isBlockedTarget(e))return null;try{const t=await this.fetch(e);if(!t.ok)return null;const n=await t.json();return function(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.type)||!t.type.includes("StatusList2021Credential"))return!1;const n=t.credentialSubject;if("object"!=typeof n||null===n)return!1;const r=n;return"StatusList2021"===r.type&&"string"==typeof r.encodedList}(n)?n:null}catch{return null}}async fetchDelegationChain(e){return[]}async fetch(e,t){if("function"!=typeof globalThis.fetch)throw new Error("Global fetch is not available in this runtime");return globalThis.fetch(e,t)}isBlockedTarget(e){if(this.allowPrivateNetworkHosts||null===e)return!1;let t;try{t=new URL(e).hostname}catch{return!1}return function(e){let t=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),t.includes(":"))return"::1"===t||"::"===t||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd");const n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(!n)return!1;const r=Number(n[1]),i=Number(n[2]);return 127===r||10===r||0===r||169===r&&254===i||192===r&&168===i||172===r&&i>=16&&i<=31}(t)}}class er extends Rn{async resolveDID(e){return null}async fetchStatusList(e){return null}async fetchDelegationChain(e){return[]}async fetch(e,t){throw new Error("fetch unavailable")}}function tr(e){return{version:"audit.v1",ts:Date.now(),session:e.session.sessionId,audience:e.session.audience,did:e.identity.did,kid:e.identity.kid,reqHash:e.requestHash,resHash:e.responseHash??"-",verified:e.verified,scope:e.scopeId??"-"}}class nr{}class rr extends nr{records=[];events=[];loggedSessions=new Set;async logAuditRecord(e){const t=e.session.sessionId;this.loggedSessions.has(t)||(this.loggedSessions.add(t),this.records.push(tr(e)))}async logEvent(e){this.events.push(e)}}class ir extends nr{async logAuditRecord(e){}async logEvent(e){}}class or{}class sr extends or{grants=new Map;now;constructor(e={}){super(),this.now=e.now??(()=>Date.now())}async bind(e){this.grants.set(e.id,{...e})}async getByAgent(e,t){return this.activeGrants().filter(n=>n.agentDid===e&&this.coversScopes(n,t))}async getBySession(e,t){return this.activeGrants().filter(n=>n.sessionId===e&&this.coversScopes(n,t))}async getById(e){const t=this.grants.get(e);return t?{...t}:void 0}async revoke(e,t){const n=this.grants.get(e);n&&(n.status="revoked",void 0!==t&&(n.revocationReason=t))}async cleanup(){const e=this.now();for(const[t,n]of this.grants)void 0!==n.expiresAt&&n.expiresAt<=e&&this.grants.delete(t)}activeGrants(){const e=this.now(),t=[];for(const n of this.grants.values())"revoked"!==n.status&&(void 0!==n.expiresAt&&n.expiresAt<=e||t.push({...n}));return t}coversScopes(e,t){return!t||0===t.length||t.every(t=>e.scopes.includes(t))}}class ar{}class cr extends ar{pending=new Map;now;constructor(e={}){super(),this.now=e.now??(()=>Date.now())}async put(e,t,n){this.pending.set(e,{flow:{...t},expiresAt:this.now()+n})}async get(e){const t=this.pending.get(e);if(t){if(!(t.expiresAt<=this.now()))return{...t.flow};this.pending.delete(e)}}async consume(e){const t=this.pending.get(e);if(t&&(this.pending.delete(e),!(t.expiresAt<=this.now())))return{...t.flow}}async delete(e){this.pending.delete(e)}async cleanup(){const e=this.now();for(const[t,n]of this.pending)n.expiresAt<=e&&this.pending.delete(t)}}function dr(e){const t=new Set;for(const n of e.credentialSubject.delegation.scopes??[])t.add(n);for(const n of e.credentialSubject.delegation.constraints?.scopes??[])t.add(n);return Array.from(t)}function ur(e,t){const n=dr(e),r=dr(t),i=t.credentialSubject.delegation,o=e=>`${e.matcher}\0${e.resource}`,s=new Set((e.credentialSubject.delegation.constraints.crisp?.scopes??[]).map(o)),a=(i.constraints.crisp?.scopes??[]).filter(e=>!s.has(o(e)));if(a.length>0)return{valid:!1,reason:`Delegation ${i.id} introduces crisp scope matcher(s) absent from parent ${e.credentialSubject.delegation.id}: ${a.map(e=>`${e.matcher}:${e.resource}`).join(", ")}`};if(0===n.length)return{valid:!0};if(0===r.length)return{valid:!1,reason:`Delegation ${i.id} omits scopes required to prove attenuation from parent ${e.credentialSubject.delegation.id}`};const c=new Set(n),d=r.filter(e=>!c.has(e));return d.length>0?{valid:!1,reason:`Delegation ${i.id} widens scopes beyond parent ${e.credentialSubject.delegation.id}: ${d.join(", ")}`}:{valid:!0}}const lr=["delete","drop","destroy","remove","terminate","transfer","payment","admin","execute","modify","write","rotate","revoke"],pr=["read","get","list","describe","search","query"];class fr{options;constructor(e={}){this.options=e}classify(e){const t=this.options.hints?.[e.toolName];if(t?.reversibility&&t.blastRadius&&t.severity)return{reversibility:t.reversibility,blastRadius:t.blastRadius,severity:t.severity};const n=hr(e.toolName),r=function(e){const t=hr(e);return t.includes("prod")||t.includes("production")}(e.namespace);let i;return i=n.some(e=>lr.includes(e))?{reversibility:"irreversible",blastRadius:r?"environment":"resource",severity:r?"catastrophic":"high"}:n.some(e=>pr.includes(e))?{reversibility:"reversible",blastRadius:"record",severity:"low"}:{reversibility:"unknown",blastRadius:"unknown",severity:"unknown"},{...i,...mr(t)}}}function hr(e){return e.split(/[.:/_\-\s]+/).flatMap(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/\s+/)).map(e=>e.toLowerCase()).filter(Boolean)}function mr(e){if(!e)return{};const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}class yr{cfg;constructor(e={}){this.cfg=e}async evaluate(e){const{severity:t,reversibility:n,scopeMatched:r,humanApprovals:i}=e.context;if(!r)return{decision:"deny",reason:"scope_not_matched"};if("unknown"===t||"unknown"===n)return{decision:"deny",reason:"unclassified_high_risk"};if("irreversible"===n||"catastrophic"===t||"high"===t){const e=this.cfg.stepUpQuorum??1;return i.length>=e?{decision:"allow"}:{decision:"step_up",quorum:{n:e,approvers:this.cfg.stepUpApprovers??[]},reason:"destructive_action_requires_approval"}}return{decision:"allow"}}}async function gr(e,t,n,r){if(n.n<=0)return{satisfied:!1,reason:"invalid_quorum:n<=0"};const i=new Set;for(const o of e)"approve"===o.decision&&o.requestHash===t&&(n.approvers.length>0&&!n.approvers.includes(o.approverDid)||await r(o)&&i.add(o.approverDid));return i.size>=n.n?{satisfied:!0}:{satisfied:!1,reason:`quorum_not_met:${i.size}/${n.n}`}}function vr(e){return{principal:{agentDid:e.principal.agentDid,...e.principal.responsibleParty?{responsibleParty:e.principal.responsibleParty}:{}},action:{toolName:e.action.toolName},resource:{namespace:e.resource.namespace},context:{delegatedScopes:e.delegatedScopes,scopeMatched:e.scopeMatched,humanApprovals:e.humanApprovals??[],...e.risk,...void 0!==e.budgetRemaining?{budgetRemaining:e.budgetRemaining}:{}}}}function wr(e,t=256){const n="string"==typeof e?e:String(e);let r="";for(const e of n){const t=e.codePointAt(0)??0;r+=t<=31||t>=127&&t<=159?"�":e}return r.length>t?`${r.slice(0,t)}…`:r}const br=256,_r=256,Sr=/\([^()]*[+*?{][^()]*\)\s*[+*{]/;function kr(e,t,n){switch(t){case"exact":return e===n;case"prefix":{const t=e.endsWith("*")?e.slice(0,-1):e;return 0!==t.length&&n.startsWith(t)}case"regex":if(e.length>br||n.length>_r)return!1;if(Sr.test(e))return!1;try{return new RegExp(`^(?:${e})$`).test(n)}catch{return!1}default:return!1}}function Er(e,t){if(function(e){const t=e?.credentialSubject?.delegation;return[...t?.scopes??[],...t?.constraints?.scopes??[]]}(t).includes(e))return{satisfied:!0,usedNonExactMatcher:!1};for(const n of function(e){return e?.credentialSubject?.delegation?.constraints?.crisp?.scopes??[]}(t))if(kr(n.resource,n.matcher,e))return{satisfied:!0,usedNonExactMatcher:"exact"!==n.matcher};return{satisfied:!1,usedNonExactMatcher:!1}}const Ir=["handshake","identity","reputation"];function Dr(e,t){const n={did:e.identity.did,kid:e.identity.kid,privateKey:e.identity.privateKey,publicKey:e.identity.publicKey},r=e.nonceCache??new Ln,i=new Wn(t,{...e.session,serverDid:n.did,nonceCache:r}),o=new Ht(n,t),s=e.delegation,c=e.auditLog??new ir,d=e.emitLegacyProofKey??!0,l=e.grantStore??new sr;e.grantStore||zt.warn("[kya-os] Using MemoryGrantStore — grants are lost on restart and not shared across instances. Inject a Redis / Durable Object / DB-backed GrantStore via config.grantStore for production / multi-instance use.");const h=s?.holderBinding??"off",m={identity:n,config:e,cryptoProvider:t,sessionManager:i,proofGenerator:o,auditLog:c,grantStore:l,delegationConfig:s,holderBindingMode:h,holderBindingVerifier:"off"===h?void 0:new An({cryptoProvider:t,clockProvider:new Xn,nonceCacheProvider:r,fetchProvider:s?.fetchProvider??("function"==typeof globalThis.fetch?new Qn:new er)}),emitLegacyProofKey:d},y=function(e){const{identity:t,config:n,cryptoProvider:r,sessionManager:i,proofGenerator:o,auditLog:s,emitLegacyProofKey:c}=e,d=(e,t)=>({...e,[Lt]:t,...c?{[Ut]:t}:{}});let u;async function l(){if(u&&await i.getSession(u))return i.getStats().activeSessions<=1?u:void zt.warn("[kya-os] Multiple sessions active and no sessionId threaded; skipping proof attribution to avoid signing with another client's session. Thread the sessionId (the auto-proof path is single-session only).");if(!n.autoSession)return;const e=p(await r.randomBytes(16)),o=Math.floor(Date.now()/1e3),s=await i.validateHandshake({nonce:e,audience:t.did,timestamp:o});return s.success&&s.session?(u=s.session.sessionId,u):void 0}return{handleHandshake:async function(e){if(!Vn(e))return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:a.handshake_failed,message:"Invalid handshake format: requires nonce (string), audience (string), and timestamp (positive integer)"}})}],isError:!0};const n=await i.validateHandshake(e);return n.success&&n.session&&(u=n.session.sessionId),{content:[{type:"text",text:JSON.stringify({success:n.success,...n.session&&{sessionId:n.session.sessionId,serverDid:t.did,serverKid:t.kid},...n.error&&{error:n.error}})}],...n.error&&{isError:!0}}},ensureSession:l,wrapWithProof:function(e,n){return async(r,a,c)=>{const u=await n(r,a,c);if(u.isError)return u;const p=a??await l();if(!p)return u;const f=await i.getSession(p);if(!f)return u;try{const n={method:e,params:r},i={data:u.content},a=await o.generateProof(n,i,f,{scopeId:c?.scopeId});u._meta=d({},a);try{await s.logAuditRecord({identity:{did:t.did,kid:t.kid},session:{sessionId:f.sessionId,audience:f.audience},requestHash:a.meta.requestHash,responseHash:a.meta.responseHash,verified:"yes",scopeId:a.meta.scopeId})}catch(t){zt.error("[kya-os] Audit log failed",{tool:e,error:t instanceof Error?t.message:String(t)})}}catch(t){zt.error("[kya-os] Proof generation failed",{tool:e,error:t instanceof Error?t.message:String(t)}),u._meta={proofError:"Proof generation failed — response is unproven"}}return u}},attachOutcomeProof:async(e,t,n,r,s,a="denied",c,u)=>{try{const p=r??await l();if(!p)return e;const f=await i.getSession(p);if(!f)return e;let h;if(void 0!==c)h=c;else{h={};for(const[e,t]of Object.entries(n))"_kyaos_delegation"!==e&&(h[e]=t)}const m={method:t,params:h},y=void 0!==u?{data:u}:void 0,g=await o.generateProof(m,y,f,{outcome:a,reason:wr(s)});e._meta=d(e._meta??{},g)}catch(e){zt.error("[kya-os] Outcome proof generation failed",{tool:t,error:e instanceof Error?e.message:String(e)})}return e}}}(m),g=function(e,t){const{identity:n,config:r,sessionManager:i}=e,{handleHandshake:o}=t;return{handleKyaOs:async function(e){const t="string"==typeof e.action?e.action:void 0;switch(t){case"handshake":return o(e);case"identity":return async function(){return{content:[{type:"text",text:JSON.stringify({did:n.did,kid:n.kid,name:r.identity.agentName??n.did,capabilities:["handshake","signing","verification"],protocolVersion:"1.0.0",clockSkewSeconds:i.getStats().config.timestampSkewSeconds})}]}}();case"reputation":return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:a.runtime_error,message:'action: "reputation" is not yet implemented.'}})}],isError:!0};default:return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:a.invalid_request,message:`Unknown _kyaos action: "${t??"(missing)"}". Valid actions: ${Ir.join(", ")}`}})}],isError:!0}}},handshakeTool:{name:"_kyaos_handshake",description:"KYA-OS identity handshake — establishes a cryptographic session",inputSchema:{type:"object",properties:{nonce:{type:"string",description:"Client-generated unique nonce"},audience:{type:"string",description:"Intended audience (server DID or URL)"},timestamp:{type:"number",description:"Unix epoch seconds"},agentDid:{type:"string",description:"Client agent DID (optional)"}},required:["nonce","audience","timestamp"]}},kyaOsTool:{name:"_kyaos",description:"KYA-OS protocol — identity verification, session handshake, and server metadata",inputSchema:{type:"object",properties:{action:{type:"string",enum:[...Ir],description:"Protocol operation to perform"},nonce:{type:"string",description:"Client-generated unique nonce"},audience:{type:"string",description:"Intended audience (server DID or URL)"},timestamp:{type:"number",description:"Unix epoch seconds"},agentDid:{type:"string",description:"Client agent DID (optional)"}},required:["action"]}}}}(m,{handleHandshake:y.handleHandshake}),{resolveExistingGrant:w,bindGrantOnSuccess:b}=function(e){const{identity:t,cryptoProvider:n,grantStore:r,holderBindingMode:i,holderBindingVerifier:o}=e;async function s(e,t,r){const i=`${e}|${t??""}|${[...r].sort().join(",")}`;return`grant_${(await n.hash((new TextEncoder).encode(i))).replace(/^sha256:/,"")}`}return{resolveExistingGrant:async function(e,n,i,s){const a=await async function(e,n,i,s){if(!o)return;const a=n._kyaos_proof;if(void 0===a)return;let c=a;if("string"==typeof a)try{c=JSON.parse(a)}catch{return}const d=c,u=d?.meta?.did;return"string"==typeof u&&Xt(u)&&"bound"===(await Qt({proof:d,subjectDid:u,request:qt(e,n),expectedAudience:t.did,proofVerifier:o})).status?(await r.getByAgent(u,[s])).find(e=>void 0===e.sessionId||e.sessionId===i):void 0}(e,n,i,s);if(a)return a;if(i){const[e]=await r.getBySession(i,[s]);if(e)return e}},bindGrantOnSuccess:async function(e,t,n,o,a){try{const c=e.credentialSubject?.id;if(!c)return;if("off"===i&&void 0===o)return void zt.debug(`[kya-os] Skipping an unresolvable session-less grant for scope "${a}" (holderBinding 'off', no sessionId).`);let d;try{d=dr(e)}catch{d=[]}const u=Array.from(new Set([a,...d])),l=e.credentialSubject?.delegation?.controller,p=function(e){if(e.expirationDate){const t=Date.parse(e.expirationDate);if(!Number.isNaN(t))return t}const t=e.credentialSubject?.delegation?.constraints?.notAfter;if("number"==typeof t)return 1e3*t}(e),f={id:await s(c,o,u),agentDid:c,...void 0!==l?{userDid:l}:{},scopes:u,...void 0!==o?{sessionId:o}:{},authorization:{type:"delegation"},...n&&"string"==typeof t?{credentialJwt:t}:{},issuedAt:Date.now(),...void 0!==p?{expiresAt:p}:{},status:"active"};await r.bind(f)}catch(e){zt.error("[kya-os] Grant bind failed",{scope:a,error:e instanceof Error?e.message:String(e)})}}}}(m),{wrapWithDelegation:_}=function(e,t){const{identity:n,holderBindingMode:r,holderBindingVerifier:i}=e,{attachOutcomeProof:o,resolveExistingGrant:s,bindGrantOnSuccess:c}=t,{validateDelegationChain:d,buildDelegationErrorResponse:l,buildNeedsAuthorizationChallenge:p}=function(e){const{identity:t,cryptoProvider:n,delegationConfig:r}=e,i=Pt(),o=r?.fetchProvider??("function"==typeof globalThis.fetch?new Qn:void 0),s=o?cn(o):void 0,a=gn(r?.didResolvers,o),c=new Ze({didResolver:{async resolve(e){const t=r?.didResolver;if(t){const n=await t.resolve(e);if(n)return n}const n=mt(e),o=n?a[n]:void 0;if(o)try{const t=await o.resolve(e);if(t)return t}catch{return null}return e.startsWith("did:key:")?i.resolve(e):e.startsWith("did:web:")?s?.resolve(e)??null:null}},signatureVerifier:async(e,t)=>{const r=e.proof;if(!r)return{valid:!1,reason:"Missing proof"};const i=r.proofValue;if(!i)return{valid:!1,reason:"Missing proofValue in proof"};const o=e,s={};for(const[e,t]of Object.entries(o))"proof"!==e&&(s[e]=t);const a=N(s),c=(new TextEncoder).encode(a),d=u(i),l=t;if(!l.x)return{valid:!1,reason:"No x field in publicKeyJwk"};const p=f(u(l.x)),h=await n.verify(c,d,p);return{valid:h,reason:h?void 0:"Signature verification failed"}},statusListResolver:r?.statusListResolver});return{validateDelegationChain:(e,n)=>async function(e,t,n){const r=e?.credentialSubject?.delegation;if(!r||"object"!=typeof r||!r.constraints||"object"!=typeof r.constraints)return{valid:!1,reason:"Malformed delegation credential: missing credentialSubject.delegation or its constraints"};const i=v(e);let o=[e];if(i.parentId){if(!t.resolveDelegationChain)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but no resolveDelegationChain handler is configured`};let n;try{n=await t.resolveDelegationChain(e)}catch(e){return{valid:!1,reason:`Failed to resolve delegation chain: ${e instanceof Error?e.message:"Unknown error"}`}}if(0===n.length)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but the resolved chain is empty`};const r=n.findIndex(e=>e.credentialSubject.delegation.id===i.id);if(-1!==r&&r!==n.length-1)return{valid:!1,reason:`Resolved delegation chain for ${i.id} must end with the leaf credential`};o=-1===r?[...n,e]:n}const s=new Set;let a,c;for(const e of o){const r=v(e);if(s.has(r.id))return{valid:!1,reason:`Delegation chain contains a circular reference at ${r.id}`};if(s.add(r.id),e.credentialStatus&&!t.statusListConfigured)return{valid:!1,reason:`Delegation ${r.id} has credentialStatus but no statusListResolver is configured`};const i=await t.verifier.verifyDelegationCredential(e,{...n?.skipSignature?{skipSignature:!0}:{}});if(!i.valid)return{valid:!1,reason:`Delegation ${r.id} invalid: ${i.reason}`};if(!Xe(r,t.serverDid))return{valid:!1,reason:`Delegation ${r.id} audience does not include server DID ${t.serverDid}`};if(r.parentId&&!r.constraints.audience)return{valid:!1,reason:`Delegation ${r.id} is a re-delegation (parentId: ${r.parentId}) but has no audience constraint. Re-delegations MUST include an audience constraint (KYA-OS §11.6)`};if(!a||!c){if(r.parentId)return{valid:!1,reason:`Resolved delegation chain is incomplete: root delegation ${r.id} still references parent ${r.parentId}`};a=r,c=e;continue}if(r.parentId!==a.id)return{valid:!1,reason:`Delegation ${r.id} references parent ${r.parentId} but expected ${a.id}`};if(r.issuerDid!==a.subjectDid)return{valid:!1,reason:`Delegation ${r.id} issued by ${r.issuerDid} but parent subject is ${a.subjectDid}`};const o=ur(c,e);if(!o.valid)return o;a=r,c=e}const d=v(o[o.length-1]);if(d.id!==i.id)return{valid:!1,reason:`Resolved delegation chain ended at ${d.id} instead of leaf ${i.id}`};if(t.revocationChecker){const e=await t.revocationChecker.isRevoked(i.id);if(e.revoked)return{valid:!1,reason:e.revokedAncestor?`Delegation ${i.id} is revoked via ancestor ${e.revokedAncestor}`:`Delegation ${i.id} is revoked${e.reason?`: ${e.reason}`:""}`}}return{valid:!0}}(e,{serverDid:t.did,verifier:c,resolveDelegationChain:r?.resolveDelegationChain,statusListConfigured:!!r?.statusListResolver,revocationChecker:r?.revocationChecker},n),buildDelegationErrorResponse:(e,t)=>({content:[{type:"text",text:JSON.stringify({error:e,reason:wr(t)})}],isError:!0}),buildNeedsAuthorizationChallenge:async function(e,t){const r=await n.randomBytes(16),i=Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join(""),o=[i.slice(0,8),i.slice(8,12),i.slice(12,16),i.slice(16,20),i.slice(20)].join("-"),s=Math.floor(Date.now()/1e3)+300,a=z({message:`Tool "${e}" requires delegation with scope: ${t.scopeId}`,authorizationUrl:t.consentUrl,resumeToken:o,expiresAt:s,scopes:[t.scopeId]}),c=[{type:"text",text:JSON.stringify(a)}];let d=c;if(t.formatChallenge)try{d=t.formatChallenge(a)}catch(t){zt.error("[kya-os] formatChallenge threw; using the default challenge",{tool:e,error:t instanceof Error?t.message:String(t)}),d=c}return{challengeContent:d,message:a.message}}}}(e);return{wrapWithDelegation:function(e,t,u){return async(f,h)=>{const m=f._kyaos_delegation;if(null==m){if(await s(e,f,h,t.scopeId)){const n={};for(const[e,t]of Object.entries(f))Bt(e)||(n[e]=t);return zt.debug(`[kya-os] Grant resolved for "${e}" (scope "${t.scopeId}") — no re-paste required`),u(n,h,{scopeId:t.scopeId})}const{challengeContent:n,message:r}=await p(e,t);return o({content:n},e,f,h,r,"needs_authorization",void 0,n)}let y,g=!1;if("string"==typeof m){const t=M(m);if(!t||!t.payload.vc)return o(l(a.delegation_invalid,"Invalid VC-JWT format"),e,f,h,"Invalid VC-JWT format");y=t.payload.vc,y.proof||(y={...y,proof:{type:"JwtProof2020",jwt:m}}),g=!0}else y=m;const v=await(async()=>{try{return await d(y,{skipSignature:g})}catch(t){return zt.error("[kya-os] Unexpected error verifying delegation",{tool:e,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),{valid:!1,reason:"Delegation credential could not be verified"}}})();if(!v.valid){const t=v.reason??"Unknown delegation validation error";return zt.warn(`[kya-os] Delegation verification failed for "${e}": ${wr(t)}`),o(l(a.delegation_invalid,t),e,f,h,t)}if("off"!==r&&i){const t=y.credentialSubject?.id;if(t&&Xt(t)){const s=f._kyaos_proof;if(void 0===s){const t="Holder-of-key proof (_kyaos_proof) is required for this delegation subject";if(zt.warn(`[kya-os] Holder binding: "${e}" called without _kyaos_proof`),"enforce"===r)return o(l(a.holder_binding_failed,t),e,f,h,t)}else{let c=s;if("string"==typeof s)try{c=JSON.parse(s)}catch{c={}}const d=await Qt({proof:c,subjectDid:t,request:qt(e,f),expectedAudience:n.did,proofVerifier:i});if("bound"!==d.status){const t=d.reason??"Holder-of-key proof did not bind the delegation subject";if(zt.warn(`[kya-os] Holder binding ${d.status} for "${e}": ${wr(t)}`),"enforce"===r)return o(l(a.holder_binding_failed,t),e,f,h,t)}}}else t&&zt.warn(`[kya-os] Holder binding: subject "${t}" is not did:key; deferring to cnf binding (phase 2)`)}const w=Er(t.scopeId,y);if(w.usedNonExactMatcher&&zt.warn(`[kya-os] Scope "${t.scopeId}" for "${e}" granted via a non-exact (prefix/regex) matcher. Verify this is intended — non-exact matchers widen authority.`),!w.satisfied){const n=`Required scope "${t.scopeId}" not in delegation scopes`;return zt.warn(`[kya-os] Delegation missing required scope "${t.scopeId}" for "${e}"`),o(l(a.insufficient_scope,n),e,f,h,n)}const b={};for(const[e,t]of Object.entries(f))Bt(e)||(b[e]=t);return await c(y,m,g,h,t.scopeId),zt.debug(`[kya-os] Delegation verified for "${e}", scope "${t.scopeId}"`),u(b,h,{scopeId:t.scopeId})}}}}(m,{attachOutcomeProof:y.attachOutcomeProof,resolveExistingGrant:w,bindGrantOnSuccess:b}),{withPolicyGate:S}=function(e,t){const{proofGenerator:n}=e,{attachOutcomeProof:r}=t,i=new fr,o=new yr;return{withPolicyGate:function(e,t,s={}){const c=s.engine??o,d=s.classifier??i,u=s.approvalsArgKey??"_kyaos_approvals",l=s.isValidApprovalSignature??(async()=>!1);return async(i,o)=>{const p={};for(const[e,t]of Object.entries(i))Bt(e)||e===u||(p[e]=t);const f=s.resolveNamespace?.(i)??e,h=d.classify({toolName:e,namespace:f}),m=function(e){if(!e||"object"!=typeof e)return{agentDid:"unknown",delegatedScopes:[]};try{const t=e,n=t.credentialSubject,r=n?.delegation?.subjectDid??n?.id??"unknown",i=n?.delegation?.controller;let o=[];try{o=dr(t)}catch{o=[]}return{agentDid:r,...i?{responsibleParty:i}:{},delegatedScopes:o}}catch{return{agentDid:"unknown",delegatedScopes:[]}}}(i._kyaos_delegation),y=vr({principal:{agentDid:m.agentDid,...m.responsibleParty?{responsibleParty:m.responsibleParty}:{}},action:{toolName:e},resource:{namespace:f},delegatedScopes:m.delegatedScopes,scopeMatched:s.scopeMatched??!1,risk:h}),g=await c.evaluate(y);if("allow"===g.decision)return t(p,o);if("deny"===g.decision){const t={content:[{type:"text",text:JSON.stringify({error:a.policy_denied,reason:wr(g.reason)})}],isError:!0};return r(t,e,i,o,g.reason,"denied",p)}const v=await n.hashRequest({method:e,params:p}),w=Array.isArray(i[u])?i[u]:[];if((await gr(w,v,g.quorum,l)).satisfied)return t(p,o);const b=$({message:`Tool "${e}" requires ${g.quorum.n}-of-N approval before it may proceed (${wr(g.reason)}).`,resumeToken:`step_up:${v}`,expiresAt:Math.floor(Date.now()/1e3)+300,requestHash:v,quorum:g.quorum}),_={content:[{type:"text",text:JSON.stringify(b)}],isError:!0};return r(_,e,i,o,g.reason,"step_up_required",p)}}}}(m,{attachOutcomeProof:y.attachOutcomeProof});return{identity:e.identity,sessionManager:i,proofGenerator:o,kyaOsTool:g.kyaOsTool,handshakeTool:g.handshakeTool,handleKyaOs:g.handleKyaOs,handleHandshake:y.handleHandshake,wrapWithProof:y.wrapWithProof,wrapWithDelegation:_,withPolicyGate:S}}function zr(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:s,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const i=s.prototype,o=Object.keys(i);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=i[t].bind(n))}}const i=n?.Parent??Object;class o extends i{}function s(e){var t;const i=n?.Parent?new o:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}Object.freeze({status:"aborted"}),Symbol("zod_brand");class Ar extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $r extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Tr={};function Or(e){return e&&Object.assign(Tr,e),Tr}function xr(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function Pr(e,t="|"){return e.map(e=>Qr(e)).join(t)}function Nr(e,t){return"bigint"==typeof t?t.toString():t}function Cr(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Rr(e){return null==e}function jr(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const Mr=Symbol("evaluating");function Zr(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Mr)return void 0===r&&(r=Mr,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Kr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Lr(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Ur(e){return JSON.stringify(e)}const Jr="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Hr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Wr=Cr(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Fr(e){if(!1===Hr(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==Hr(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Vr(e){return Fr(e)?{...e}:Array.isArray(e)?[...e]:e}const Br=new Set(["string","number","symbol"]),qr=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Gr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yr(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Xr(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function Qr(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}const ei={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ti={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ni(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function ri(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ii(e){return"string"==typeof e?e:e?.message}function oi(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const i=ii(e.inst?._zod.def?.error?.(e))??ii(t?.error?.(e))??ii(n.customError?.(e))??ii(n.localeError?.(e))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function si(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ai(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ci(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const di=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Nr,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ui=zr("$ZodError",di),li=zr("$ZodError",di,{Parent:Error}),pi=e=>(t,n,r,i)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ar;if(s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>oi(e,o,Or())));throw Jr(t,i?.callee),t}return s.value},fi=pi(li),hi=e=>async(t,n,r,i)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>oi(e,o,Or())));throw Jr(t,i?.callee),t}return s.value},mi=hi(li),yi=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Ar;return o.issues.length?{success:!1,error:new(e??ui)(o.issues.map(e=>oi(e,i,Or())))}:{success:!0,data:o.value}},gi=yi(li),vi=e=>async(t,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>oi(e,i,Or())))}:{success:!0,data:o.value}},wi=vi(li),bi=e=>(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return pi(e)(t,n,i)},_i=e=>(t,n,r)=>pi(e)(t,n,r),Si=e=>async(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return hi(e)(t,n,i)},ki=e=>async(t,n,r)=>hi(e)(t,n,r),Ei=e=>(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return yi(e)(t,n,i)},Ii=e=>(t,n,r)=>yi(e)(t,n,r),Di=e=>async(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return vi(e)(t,n,i)},zi=e=>async(t,n,r)=>vi(e)(t,n,r),Ai=/^[cC][^\s-]{8,}$/,$i=/^[0-9a-z]+$/,Ti=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Oi=/^[0-9a-vA-V]{20}$/,xi=/^[A-Za-z0-9]{27}$/,Pi=/^[a-zA-Z0-9_-]{21}$/,Ni=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ci=/^[-+]?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)?)??$/,Ri=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ji=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Mi=ji(4),Zi=ji(6),Ki=ji(7),Li=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ui=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Ji=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Hi=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Wi=Hi,Fi=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Vi="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Bi(){return new RegExp(Vi,"u")}const qi=/^(?:(?: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])$/,Gi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Yi=e=>{const t=Gr(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Xi=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Qi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,eo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,to=/^[A-Za-z0-9_-]*$/,no=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,ro=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,io=/^\+[1-9]\d{6,14}$/,oo="(?:(?:\\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])))",so=new RegExp(`^${oo}$`);function ao(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function co(e){return new RegExp(`^${ao(e)}$`)}function uo(e){const t=ao({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${oo}T(?:${r})$`)}const lo=e=>new RegExp(`^${e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*"}$`),po=/^-?\d+n?$/,fo=/^-?\d+$/,ho=/^-?\d+(?:\.\d+)?$/,mo=/^(?:true|false)$/i,yo=/^null$/i,go=/^undefined$/i,vo=/^[^A-Z]*$/,wo=/^[^a-z]*$/,bo=/^[0-9a-fA-F]*$/;function _o(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function So(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const ko=/^[0-9a-fA-F]{32}$/,Eo=_o(22,"=="),Io=So(22),Do=/^[0-9a-fA-F]{40}$/,zo=_o(27,"="),Ao=So(27),$o=/^[0-9a-fA-F]{64}$/,To=_o(43,"="),Oo=So(43),xo=/^[0-9a-fA-F]{96}$/,Po=_o(64,""),No=So(64),Co=/^[0-9a-fA-F]{128}$/,Ro=_o(86,"=="),jo=So(86),Mo=zr("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Zo={number:"number",bigint:"bigint",object:"date"},Ko=zr("$ZodCheckLessThan",(e,t)=>{Mo.init(e,t);const n=Zo[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Lo=zr("$ZodCheckGreaterThan",(e,t)=>{Mo.init(e,t);const n=Zo[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Uo=zr("$ZodCheckMultipleOf",(e,t)=>{Mo.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let i=(r.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}const o=n>i?n:i;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Jo=zr("$ZodCheckNumberFormat",(e,t)=>{Mo.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,o]=ei[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=o,n&&(r.pattern=fo)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a))return void s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Ho=zr("$ZodCheckBigIntFormat",(e,t)=>{Mo.init(e,t);const[n,r]=ti[t.format];e._zod.onattach.push(e=>{const i=e._zod.bag;i.format=t.format,i.minimum=n,i.maximum=r}),e._zod.check=i=>{const o=i.value;o<n&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>r&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),Wo=zr("$ZodCheckMaxSize",(e,t)=>{var n;Mo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Rr(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;r.size<=t.maximum||n.issues.push({origin:si(r),code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Fo=zr("$ZodCheckMinSize",(e,t)=>{var n;Mo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Rr(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;r.size>=t.minimum||n.issues.push({origin:si(r),code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Vo=zr("$ZodCheckSizeEquals",(e,t)=>{var n;Mo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Rr(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size}),e._zod.check=n=>{const r=n.value,i=r.size;if(i===t.size)return;const o=i>t.size;n.issues.push({origin:si(r),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Bo=zr("$ZodCheckMaxLength",(e,t)=>{var n;Mo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Rr(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const i=ai(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qo=zr("$ZodCheckMinLength",(e,t)=>{var n;Mo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Rr(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const i=ai(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Go=zr("$ZodCheckLengthEquals",(e,t)=>{var n;Mo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Rr(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,i=r.length;if(i===t.length)return;const o=ai(r),s=i>t.length;n.issues.push({origin:o,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Yo=zr("$ZodCheckStringFormat",(e,t)=>{var n,r;Mo.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Xo=zr("$ZodCheckRegex",(e,t)=>{Yo.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Qo=zr("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vo),Yo.init(e,t)}),es=zr("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=wo),Yo.init(e,t)}),ts=zr("$ZodCheckIncludes",(e,t)=>{Mo.init(e,t);const n=Gr(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),ns=zr("$ZodCheckStartsWith",(e,t)=>{Mo.init(e,t);const n=new RegExp(`^${Gr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),rs=zr("$ZodCheckEndsWith",(e,t)=>{Mo.init(e,t);const n=new RegExp(`.*${Gr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});function is(e,t,n){e.issues.length&&t.issues.push(...ri(n,e.issues))}const os=zr("$ZodCheckProperty",(e,t)=>{Mo.init(e,t),e._zod.check=e=>{const n=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(n=>is(n,e,t.property));is(n,e,t.property)}}),ss=zr("$ZodCheckMimeType",(e,t)=>{Mo.init(e,t);const n=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}}),as=zr("$ZodCheckOverwrite",(e,t)=>{Mo.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class cs{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of r)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const ds={major:4,minor:3,patch:6},us=zr("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ds;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const t of r)for(const n of t._zod.onattach)n(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,i=ni(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===n?.async)throw new Ar;if(r||s instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(i||(i=ni(e,t)))});else{if(e.issues.length===t)continue;i||(i=ni(e,t))}}return r?r.then(()=>e):e},n=(n,i,o)=>{if(ni(n))return n.aborted=!0,n;const s=t(i,r,o);if(s instanceof Promise){if(!1===o.async)throw new Ar;return s.then(t=>e._zod.parse(t,o))}return e._zod.parse(s,o)};e._zod.run=(i,o)=>{if(o.skipChecks)return e._zod.parse(i,o);if("backward"===o.direction){const t=e._zod.parse({value:i.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,o)):n(t,i,o)}const s=e._zod.parse(i,o);if(s instanceof Promise){if(!1===o.async)throw new Ar;return s.then(e=>t(e,r,o))}return t(s,r,o)}}Zr(e,"~standard",()=>({validate:t=>{try{const n=gi(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return wi(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),ls=zr("$ZodString",(e,t)=>{us.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??lo(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),ps=zr("$ZodStringFormat",(e,t)=>{Yo.init(e,t),ls.init(e,t)}),fs=zr("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ri),ps.init(e,t)}),hs=zr("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ji(e))}else t.pattern??(t.pattern=ji());ps.init(e,t)}),ms=zr("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Li),ps.init(e,t)}),ys=zr("$ZodURL",(e,t)=>{ps.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),i=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=i.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),gs=zr("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Bi()),ps.init(e,t)}),vs=zr("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Pi),ps.init(e,t)}),ws=zr("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ai),ps.init(e,t)}),bs=zr("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=$i),ps.init(e,t)}),_s=zr("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ti),ps.init(e,t)}),Ss=zr("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Oi),ps.init(e,t)}),ks=zr("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=xi),ps.init(e,t)}),Es=zr("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=uo(t)),ps.init(e,t)}),Is=zr("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=so),ps.init(e,t)}),Ds=zr("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=co(t)),ps.init(e,t)}),zs=zr("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ni),ps.init(e,t)}),As=zr("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=qi),ps.init(e,t),e._zod.bag.format="ipv4"}),$s=zr("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Gi),ps.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Ts=zr("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Yi(t.delimiter)),ps.init(e,t),e._zod.bag.format="mac"}),Os=zr("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Xi),ps.init(e,t)}),xs=zr("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Qi),ps.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Ps(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Ns=zr("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=eo),ps.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Ps(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Cs=zr("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=to),ps.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!to.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Ps(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Rs=zr("$ZodE164",(e,t)=>{t.pattern??(t.pattern=io),ps.init(e,t)}),js=zr("$ZodJWT",(e,t)=>{ps.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Ms=zr("$ZodCustomStringFormat",(e,t)=>{ps.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),Zs=zr("$ZodNumber",(e,t)=>{us.init(e,t),e._zod.pattern=e._zod.bag.pattern??ho,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Ks=zr("$ZodNumberFormat",(e,t)=>{Jo.init(e,t),Zs.init(e,t)}),Ls=zr("$ZodBoolean",(e,t)=>{us.init(e,t),e._zod.pattern=mo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),Us=zr("$ZodBigInt",(e,t)=>{us.init(e,t),e._zod.pattern=po,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch(e){}return"bigint"==typeof n.value||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),Js=zr("$ZodBigIntFormat",(e,t)=>{Ho.init(e,t),Us.init(e,t)}),Hs=zr("$ZodSymbol",(e,t)=>{us.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return"symbol"==typeof r||t.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),t}}),Ws=zr("$ZodUndefined",(e,t)=>{us.init(e,t),e._zod.pattern=go,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),t}}),Fs=zr("$ZodNull",(e,t)=>{us.init(e,t),e._zod.pattern=yo,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}}),Vs=zr("$ZodAny",(e,t)=>{us.init(e,t),e._zod.parse=e=>e}),Bs=zr("$ZodUnknown",(e,t)=>{us.init(e,t),e._zod.parse=e=>e}),qs=zr("$ZodNever",(e,t)=>{us.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),Gs=zr("$ZodVoid",(e,t)=>{us.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),t}}),Ys=zr("$ZodDate",(e,t)=>{us.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(e){}const i=n.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}});function Xs(e,t,n){e.issues.length&&t.issues.push(...ri(n,e.issues)),t.value[n]=e.value}const Qs=zr("$ZodArray",(e,t)=>{us.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const s=i[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?o.push(a.then(t=>Xs(t,n,e))):Xs(a,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function ea(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...ri(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function ta(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function na(e,t,n,r,i,o){const s=[],a=i.keySet,c=i.catchall._zod,d=c.def.type,u="optional"===c.optout;for(const i in t){if(a.has(i))continue;if("never"===d){s.push(i);continue}const o=c.run({value:t[i],issues:[]},r);o instanceof Promise?e.push(o.then(e=>ea(e,n,i,t,u))):ea(o,n,i,t,u)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const ra=zr("$ZodObject",(e,t)=>{us.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=Cr(()=>ta(t));Zr(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const i=Hr,o=t.catchall;let s;e._zod.parse=(t,n)=>{s??(s=r.value);const a=t.value;if(!i(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],d=s.shape;for(const e of s.keys){const r=d[e],i="optional"===r._zod.optout,o=r._zod.run({value:a[e],issues:[]},n);o instanceof Promise?c.push(o.then(n=>ea(n,t,e,a,i))):ea(o,t,e,a,i)}return o?na(c,a,t,n,r.value,e):c.length?Promise.all(c).then(()=>t):t}}),ia=zr("$ZodObjectJIT",(e,t)=>{ra.init(e,t);const n=e._zod.parse,r=Cr(()=>ta(t));let i;const o=Hr,s=!Tr.jitless,a=s&&Wr.value,c=t.catchall;let d;e._zod.parse=(u,l)=>{d??(d=r.value);const p=u.value;return o(p)?s&&a&&!1===l?.async&&!0!==l.jitless?(i||(i=(e=>{const t=new cs(["shape","payload","ctx"]),n=r.value,i=e=>{const t=Ur(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let s=0;for(const e of n.keys)o[e]="key_"+s++;t.write("const newResult = {};");for(const r of n.keys){const n=o[r],s=Ur(r),a=e[r],c="optional"===a?._zod?.optout;t.write(`const ${n} = ${i(r)};`),c?t.write(`\n if (${n}.issues.length) {\n if (${s} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),u=i(u,l),c?na([],p,u,l,d,e):u):n(u,l):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function oa(e,t,n,r){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const i=e.filter(e=>!ni(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>oi(e,r,Or())))}),t)}const sa=zr("$ZodUnion",(e,t)=>{us.init(e,t),Zr(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Zr(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Zr(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Zr(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>jr(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>oa(t,i,e,o)):oa(a,i,e,o)}});function aa(e,t,n,r){const i=e.filter(e=>0===e.issues.length);return 1===i.length?(t.value=i[0].value,t):(0===i.length?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>oi(e,r,Or())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1}),t)}const ca=zr("$ZodXor",(e,t)=>{sa.init(e,t),t.inclusive=!1;const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);t instanceof Promise?(a.push(t),s=!0):a.push(t)}return s?Promise.all(a).then(t=>aa(t,i,e,o)):aa(a,i,e,o)}}),da=zr("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,sa.init(e,t);const n=e._zod.parse;Zr(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=Cr(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,o)=>{const s=i.value;if(!Hr(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=r.value.get(s?.[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),i)}}),ua=zr("$ZodIntersection",(e,t)=>{us.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,n])=>pa(e,t,n)):pa(e,i,o)}});function la(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Fr(e)&&Fr(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const n of r){const r=la(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=la(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function pa(e,t,n){const r=new Map;let i;for(const n of t.issues)if("unrecognized_keys"===n.code){i??(i=n);for(const e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(const t of n.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);const o=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&i&&e.issues.push({...i,keys:o}),ni(e))return e;const s=la(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const fa=zr("$ZodTuple",(e,t)=>{us.init(e,t);const n=t.items;e._zod.parse=(r,i)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=[];const s=[],a=[...n].reverse().findIndex(e=>"optional"!==e._zod.optin),c=-1===a?0:n.length-a;if(!t.rest){const t=o.length>n.length,i=o.length<c-1;if(t||i)return r.issues.push({...t?{code:"too_big",maximum:n.length,inclusive:!0}:{code:"too_small",minimum:n.length},input:o,inst:e,origin:"array"}),r}let d=-1;for(const e of n){if(d++,d>=o.length&&d>=c)continue;const t=e._zod.run({value:o[d],issues:[]},i);t instanceof Promise?s.push(t.then(e=>ha(e,r,d))):ha(t,r,d)}if(t.rest){const e=o.slice(n.length);for(const n of e){d++;const e=t.rest._zod.run({value:n,issues:[]},i);e instanceof Promise?s.push(e.then(e=>ha(e,r,d))):ha(e,r,d)}}return s.length?Promise.all(s).then(()=>r):r}});function ha(e,t,n){e.issues.length&&t.issues.push(...ri(n,e.issues)),t.value[n]=e.value}const ma=zr("$ZodRecord",(e,t)=>{us.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Fr(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const o=[],s=t.keyType._zod.values;if(s){n.value={};const a=new Set;for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){a.add("number"==typeof e?e.toString():e);const s=t.valueType._zod.run({value:i[e],issues:[]},r);s instanceof Promise?o.push(s.then(t=>{t.issues.length&&n.issues.push(...ri(e,t.issues)),n.value[e]=t.value})):(s.issues.length&&n.issues.push(...ri(e,s.issues)),n.value[e]=s.value)}let c;for(const e in i)a.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{n.value={};for(const s of Reflect.ownKeys(i)){if("__proto__"===s)continue;let a=t.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof s&&ho.test(s)&&a.issues.length){const e=t.keyType._zod.run({value:Number(s),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(a=e)}if(a.issues.length){"loose"===t.mode?n.value[s]=i[s]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>oi(e,r,Or())),input:s,path:[s],inst:e});continue}const c=t.valueType._zod.run({value:i[s],issues:[]},r);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&n.issues.push(...ri(s,e.issues)),n.value[a.value]=e.value})):(c.issues.length&&n.issues.push(...ri(s,c.issues)),n.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),ya=zr("$ZodMap",(e,t)=>{us.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!(i instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),n;const o=[];n.value=new Map;for(const[s,a]of i){const c=t.keyType._zod.run({value:s,issues:[]},r),d=t.valueType._zod.run({value:a,issues:[]},r);c instanceof Promise||d instanceof Promise?o.push(Promise.all([c,d]).then(([t,o])=>{ga(t,o,n,s,i,e,r)})):ga(c,d,n,s,i,e,r)}return o.length?Promise.all(o).then(()=>n):n}});function ga(e,t,n,r,i,o,s){e.issues.length&&(Br.has(typeof r)?n.issues.push(...ri(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map(e=>oi(e,s,Or()))})),t.issues.length&&(Br.has(typeof r)?n.issues.push(...ri(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:r,issues:t.issues.map(e=>oi(e,s,Or()))})),n.value.set(e.value,t.value)}const va=zr("$ZodSet",(e,t)=>{us.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!(i instanceof Set))return n.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),n;const o=[];n.value=new Set;for(const e of i){const i=t.valueType._zod.run({value:e,issues:[]},r);i instanceof Promise?o.push(i.then(e=>wa(e,n))):wa(i,n)}return o.length?Promise.all(o).then(()=>n):n}});function wa(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const ba=zr("$ZodEnum",(e,t)=>{us.init(e,t);const n=xr(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>Br.has(typeof e)).map(e=>"string"==typeof e?Gr(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),_a=zr("$ZodLiteral",(e,t)=>{if(us.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?Gr(e):e?Gr(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),Sa=zr("$ZodFile",(e,t)=>{us.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return r instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:r,inst:e}),t}}),ka=zr("$ZodTransform",(e,t)=>{us.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new $r(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Ar;return n.value=i,n}});function Ea(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Ia=zr("$ZodOptional",(e,t)=>{us.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Zr(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Zr(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${jr(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Ea(t,e.value)):Ea(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Da=zr("$ZodExactOptional",(e,t)=>{Ia.init(e,t),Zr(e._zod,"values",()=>t.innerType._zod.values),Zr(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),za=zr("$ZodNullable",(e,t)=>{us.init(e,t),Zr(e._zod,"optin",()=>t.innerType._zod.optin),Zr(e._zod,"optout",()=>t.innerType._zod.optout),Zr(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${jr(e.source)}|null)$`):void 0}),Zr(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Aa=zr("$ZodDefault",(e,t)=>{us.init(e,t),e._zod.optin="optional",Zr(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>$a(e,t)):$a(r,t)}});function $a(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Ta=zr("$ZodPrefault",(e,t)=>{us.init(e,t),e._zod.optin="optional",Zr(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Oa=zr("$ZodNonOptional",(e,t)=>{us.init(e,t),Zr(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>xa(t,e)):xa(i,e)}});function xa(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Pa=zr("$ZodSuccess",(e,t)=>{us.init(e,t),e._zod.parse=(e,n)=>{if("backward"===n.direction)throw new $r("ZodSuccess");const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===r.issues.length,e)}}),Na=zr("$ZodCatch",(e,t)=>{us.init(e,t),Zr(e._zod,"optin",()=>t.innerType._zod.optin),Zr(e._zod,"optout",()=>t.innerType._zod.optout),Zr(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>oi(e,n,Or()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>oi(e,n,Or()))},input:e.value}),e.issues=[]),e)}}),Ca=zr("$ZodNaN",(e,t)=>{us.init(e,t),e._zod.parse=(t,n)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)}),Ra=zr("$ZodPipe",(e,t)=>{us.init(e,t),Zr(e._zod,"values",()=>t.in._zod.values),Zr(e._zod,"optin",()=>t.in._zod.optin),Zr(e._zod,"optout",()=>t.out._zod.optout),Zr(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>ja(e,t.in,n)):ja(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ja(e,t.out,n)):ja(r,t.out,n)}});function ja(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Ma=zr("$ZodCodec",(e,t)=>{us.init(e,t),Zr(e._zod,"values",()=>t.in._zod.values),Zr(e._zod,"optin",()=>t.in._zod.optin),Zr(e._zod,"optout",()=>t.out._zod.optout),Zr(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("forward"===(n.direction||"forward")){const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Za(e,t,n)):Za(r,t,n)}{const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Za(e,t,n)):Za(r,t,n)}}});function Za(e,t,n){if(e.issues.length)return e.aborted=!0,e;if("forward"===(n.direction||"forward")){const r=t.transform(e.value,e);return r instanceof Promise?r.then(r=>Ka(e,r,t.out,n)):Ka(e,r,t.out,n)}{const r=t.reverseTransform(e.value,e);return r instanceof Promise?r.then(r=>Ka(e,r,t.in,n)):Ka(e,r,t.in,n)}}function Ka(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}const La=zr("$ZodReadonly",(e,t)=>{us.init(e,t),Zr(e._zod,"propValues",()=>t.innerType._zod.propValues),Zr(e._zod,"values",()=>t.innerType._zod.values),Zr(e._zod,"optin",()=>t.innerType?._zod?.optin),Zr(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Ua):Ua(r)}});function Ua(e){return e.value=Object.freeze(e.value),e}const Ja=zr("$ZodTemplateLiteral",(e,t)=>{us.init(e,t);const n=[];for(const e of t.parts)if("object"==typeof e&&null!==e){if(!e._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);const t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw new Error(`Invalid template literal part: ${e._zod.traits}`);const r=t.startsWith("^")?1:0,i=t.endsWith("$")?t.length-1:t.length;n.push(t.slice(r,i))}else{if(null!==e&&!qr.has(typeof e))throw new Error(`Invalid template literal part: ${e}`);n.push(Gr(`${e}`))}e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(n,r)=>"string"!=typeof n.value?(n.issues.push({input:n.value,inst:e,expected:"string",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)}),Ha=zr("$ZodFunction",(e,t)=>(us.init(e,t),e._def=t,e._zod.def=t,e.implement=t=>{if("function"!=typeof t)throw new Error("implement() must be called with a function");return function(...n){const r=e._def.input?fi(e._def.input,n):n,i=Reflect.apply(t,this,r);return e._def.output?fi(e._def.output,i):i}},e.implementAsync=t=>{if("function"!=typeof t)throw new Error("implementAsync() must be called with a function");return async function(...n){const r=e._def.input?await mi(e._def.input,n):n,i=await Reflect.apply(t,this,r);return e._def.output?await mi(e._def.output,i):i}},e._zod.parse=(t,n)=>{if("function"!=typeof t.value)return t.issues.push({code:"invalid_type",expected:"function",input:t.value,inst:e}),t;const r=e._def.output&&"promise"===e._def.output._zod.def.type;return t.value=r?e.implementAsync(t.value):e.implement(t.value),t},e.input=(...t)=>{const n=e.constructor;return Array.isArray(t[0])?new n({type:"function",input:new fa({type:"tuple",items:t[0],rest:t[1]}),output:e._def.output}):new n({type:"function",input:t[0],output:e._def.output})},e.output=t=>new(0,e.constructor)({type:"function",input:e._def.input,output:t}),e)),Wa=zr("$ZodPromise",(e,t)=>{us.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},n))}),Fa=zr("$ZodLazy",(e,t)=>{us.init(e,t),Zr(e._zod,"innerType",()=>t.getter()),Zr(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Zr(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Zr(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Zr(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Va=zr("$ZodCustom",(e,t)=>{Mo.init(e,t),us.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ba(t,n,r,e));Ba(i,n,r,e)}});function Ba(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ci(e))}}var qa;Symbol("ZodOutput"),Symbol("ZodInput");(qa=globalThis).__zod_globalRegistry??(qa.__zod_globalRegistry=new class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const Ga=globalThis.__zod_globalRegistry;function Ya(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Xr(t)})}function Xa(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Xr(t)})}function Qa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Xr(t)})}function ec(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Xr(t)})}function tc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Xr(t)})}function nc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Xr(t)})}function rc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Xr(t)})}function ic(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Xr(t)})}function oc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Xr(t)})}function sc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Xr(t)})}function ac(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Xr(t)})}function cc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Xr(t)})}function dc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Xr(t)})}function uc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Xr(t)})}function lc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Xr(t)})}function pc(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Xr(t)})}function fc(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Xr(t)})}function hc(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Xr(t)})}function mc(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Xr(t)})}function yc(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Xr(t)})}function gc(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Xr(t)})}function vc(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Xr(t)})}function wc(e,t){return new Ko({check:"less_than",...Xr(t),value:e,inclusive:!1})}function bc(e,t){return new Ko({check:"less_than",...Xr(t),value:e,inclusive:!0})}function _c(e,t){return new Lo({check:"greater_than",...Xr(t),value:e,inclusive:!1})}function Sc(e,t){return new Lo({check:"greater_than",...Xr(t),value:e,inclusive:!0})}function kc(e){return _c(0,e)}function Ec(e){return wc(0,e)}function Ic(e){return bc(0,e)}function Dc(e){return Sc(0,e)}function zc(e,t){return new Uo({check:"multiple_of",...Xr(t),value:e})}function Ac(e,t){return new Wo({check:"max_size",...Xr(t),maximum:e})}function $c(e,t){return new Fo({check:"min_size",...Xr(t),minimum:e})}function Tc(e,t){return new Vo({check:"size_equals",...Xr(t),size:e})}function Oc(e,t){return new Bo({check:"max_length",...Xr(t),maximum:e})}function xc(e,t){return new qo({check:"min_length",...Xr(t),minimum:e})}function Pc(e,t){return new Go({check:"length_equals",...Xr(t),length:e})}function Nc(e,t){return new Xo({check:"string_format",format:"regex",...Xr(t),pattern:e})}function Cc(e){return new Qo({check:"string_format",format:"lowercase",...Xr(e)})}function Rc(e){return new es({check:"string_format",format:"uppercase",...Xr(e)})}function jc(e,t){return new ts({check:"string_format",format:"includes",...Xr(t),includes:e})}function Mc(e,t){return new ns({check:"string_format",format:"starts_with",...Xr(t),prefix:e})}function Zc(e,t){return new rs({check:"string_format",format:"ends_with",...Xr(t),suffix:e})}function Kc(e,t,n){return new os({check:"property",property:e,schema:t,...Xr(n)})}function Lc(e,t){return new ss({check:"mime_type",mime:e,...Xr(t)})}function Uc(e){return new as({check:"overwrite",tx:e})}function Jc(e){return Uc(t=>t.normalize(e))}function Hc(){return Uc(e=>e.trim())}function Wc(){return Uc(e=>e.toLowerCase())}function Fc(){return Uc(e=>e.toUpperCase())}function Vc(){return Uc(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e))}function Bc(e,t,n,r={}){const i=Xr(r),o={...Xr(r),check:"string_format",type:"string",format:t,fn:"function"==typeof n?n:e=>n.test(e),...i};return n instanceof RegExp&&(o.pattern=n),new e(o)}function qc(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ga,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Gc(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{const n=s.schema,o=t.processors[i.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);o(e,t,n,r)}const o=e._zod.parent;o&&(s.ref||(s.ref=o),Gc(o,t,r),t.seen.get(o).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(s.schema,c),"input"===t.io&&Qc(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Yc(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}const i=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:i,defId:o}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${i("__shared")}#/${r}/${o}`}}if(t[1]===n)return{ref:"#"};const i=`#/${r}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:i+o}})(t);r.def={...r.schema},o&&(r.defId=o);const s=r.schema;for(const e in s)delete s[e];s.$ref=i};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){i(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){i(n);continue}}const o=e.metadataRegistry.get(n[0])?.id;(o||r.cycle||r.count>1&&"ref"===e.reused)&&i(n)}}function Xc(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const i=n.def??n.schema,o={...i},s=n.ref;if(n.ref=null,s){r(s);const n=e.seen.get(s),a=n.schema;if(!a.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(i,a):(i.allOf=i.allOf??[],i.allOf.push(a)),Object.assign(i,o),t._zod.parent===s)for(const e in i)"$ref"!==e&&"allOf"!==e&&(e in o||delete i[e]);if(a.$ref&&n.def)for(const e in i)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}const a=t._zod.parent;if(a&&a!==s){r(a);const t=e.seen.get(a);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(const e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())r(t[0]);const i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);const o=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?i.$defs=o:i.definitions=o);try{const n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:ed(t,"input",e.processors),output:ed(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function Qc(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return Qc(r.element,n);if("set"===r.type)return Qc(r.valueType,n);if("lazy"===r.type)return Qc(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return Qc(r.innerType,n);if("intersection"===r.type)return Qc(r.left,n)||Qc(r.right,n);if("record"===r.type||"map"===r.type)return Qc(r.keyType,n)||Qc(r.valueType,n);if("pipe"===r.type)return Qc(r.in,n)||Qc(r.out,n);if("object"===r.type){for(const e in r.shape)if(Qc(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(Qc(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(Qc(e,n))return!0;return!(!r.rest||!Qc(r.rest,n))}return!1}const ed=(e,t,n={})=>r=>{const{libraryOptions:i,target:o}=r??{},s=qc({...i??{},target:o,io:t,processors:n});return Gc(e,s),Yc(s,e),Xc(s,e)},td={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},nd=(e,t,n,r)=>{const i=e._zod.def,o=!1===i.inclusive,s=i.options.map((e,n)=>Gc(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=s:n.anyOf=s},rd=(e,t,n,r)=>{const i=e._zod.def;Gc(i.innerType,t,r),t.seen.get(e).ref=i.innerType},id=zr("ZodISODateTime",(e,t)=>{Es.init(e,t),Td.init(e,t)});function od(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Xr(t)})}(id,e)}const sd=zr("ZodISODate",(e,t)=>{Is.init(e,t),Td.init(e,t)});function ad(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...Xr(t)})}(sd,e)}const cd=zr("ZodISOTime",(e,t)=>{Ds.init(e,t),Td.init(e,t)});function dd(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Xr(t)})}(cd,e)}const ud=zr("ZodISODuration",(e,t)=>{zs.init(e,t),Td.init(e,t)});function ld(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Xr(t)})}(ud,e)}const pd=(e,t)=>{ui.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>r({issues:e}));else if("invalid_key"===i.code)r({issues:i.issues});else if("invalid_element"===i.code)r({issues:i.issues});else if(0===i.path.length)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){const n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Nr,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Nr,2)}},isEmpty:{get:()=>0===e.issues.length}})},fd=(zr("ZodError",pd),zr("ZodError",pd,{Parent:Error})),hd=pi(fd),md=hi(fd),yd=yi(fd),gd=vi(fd),vd=bi(fd),wd=_i(fd),bd=Si(fd),_d=ki(fd),Sd=Ei(fd),kd=Ii(fd),Ed=Di(fd),Id=zi(fd),Dd=zr("ZodType",(e,t)=>(us.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ed(e,"input"),output:ed(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=qc({...n,processors:t});return Gc(e,r),Yc(r,e),Xc(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Lr(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>Yr(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>hd(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>yd(e,t,n),e.parseAsync=async(t,n)=>md(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>gd(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>vd(e,t,n),e.decode=(t,n)=>wd(e,t,n),e.encodeAsync=async(t,n)=>bd(e,t,n),e.decodeAsync=async(t,n)=>_d(e,t,n),e.safeEncode=(t,n)=>Sd(e,t,n),e.safeDecode=(t,n)=>kd(e,t,n),e.safeEncodeAsync=async(t,n)=>Ed(e,t,n),e.safeDecodeAsync=async(t,n)=>Id(e,t,n),e.refine=(t,n)=>e.check(wp(t,n)),e.superRefine=t=>e.check(bp(t)),e.overwrite=t=>e.check(Uc(t)),e.optional=()=>Ml(e),e.exactOptional=()=>Kl(e),e.nullable=()=>Ul(e),e.nullish=()=>Ml(Ul(e)),e.nonoptional=t=>ql(e,t),e.array=()=>il(e),e.or=t=>ll([e,t]),e.and=t=>gl(e,t),e.transform=t=>rp(e,Rl(t)),e.default=t=>Wl(e,t),e.prefault=t=>Vl(e,t),e.catch=t=>Ql(e,t),e.pipe=t=>rp(e,t),e.readonly=()=>ap(e),e.describe=t=>{const n=e.clone();return Ga.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>Ga.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Ga.get(e);const n=e.clone();return Ga.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),zd=zr("_ZodString",(e,t)=>{ls.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:i,maximum:o,format:s,patterns:a,contentEncoding:c}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),s&&(r.format=td[s]??s,""===r.format&&delete r.format,"time"===s&&delete r.format),c&&(r.contentEncoding=c),a&&a.size>0){const e=[...a];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Nc(...t)),e.includes=(...t)=>e.check(jc(...t)),e.startsWith=(...t)=>e.check(Mc(...t)),e.endsWith=(...t)=>e.check(Zc(...t)),e.min=(...t)=>e.check(xc(...t)),e.max=(...t)=>e.check(Oc(...t)),e.length=(...t)=>e.check(Pc(...t)),e.nonempty=(...t)=>e.check(xc(1,...t)),e.lowercase=t=>e.check(Cc(t)),e.uppercase=t=>e.check(Rc(t)),e.trim=()=>e.check(Hc()),e.normalize=(...t)=>e.check(Jc(...t)),e.toLowerCase=()=>e.check(Wc()),e.toUpperCase=()=>e.check(Fc()),e.slugify=()=>e.check(Vc())}),Ad=zr("ZodString",(e,t)=>{ls.init(e,t),zd.init(e,t),e.email=t=>e.check(Ya(Od,t)),e.url=t=>e.check(rc(Kd,t)),e.jwt=t=>e.check(vc(wu,t)),e.emoji=t=>e.check(ic(Jd,t)),e.guid=t=>e.check(Xa(Pd,t)),e.uuid=t=>e.check(Qa(Cd,t)),e.uuidv4=t=>e.check(ec(Cd,t)),e.uuidv6=t=>e.check(tc(Cd,t)),e.uuidv7=t=>e.check(nc(Cd,t)),e.nanoid=t=>e.check(oc(Wd,t)),e.guid=t=>e.check(Xa(Pd,t)),e.cuid=t=>e.check(sc(Vd,t)),e.cuid2=t=>e.check(ac(qd,t)),e.ulid=t=>e.check(cc(Yd,t)),e.base64=t=>e.check(mc(fu,t)),e.base64url=t=>e.check(yc(mu,t)),e.xid=t=>e.check(dc(Qd,t)),e.ksuid=t=>e.check(uc(tu,t)),e.ipv4=t=>e.check(lc(ru,t)),e.ipv6=t=>e.check(pc(au,t)),e.cidrv4=t=>e.check(fc(du,t)),e.cidrv6=t=>e.check(hc(lu,t)),e.e164=t=>e.check(gc(gu,t)),e.datetime=t=>e.check(od(t)),e.date=t=>e.check(ad(t)),e.time=t=>e.check(dd(t)),e.duration=t=>e.check(ld(t))});function $d(e){return function(e,t){return new e({type:"string",...Xr(t)})}(Ad,e)}const Td=zr("ZodStringFormat",(e,t)=>{ps.init(e,t),zd.init(e,t)}),Od=zr("ZodEmail",(e,t)=>{ms.init(e,t),Td.init(e,t)});function xd(e){return Ya(Od,e)}const Pd=zr("ZodGUID",(e,t)=>{fs.init(e,t),Td.init(e,t)});function Nd(e){return Xa(Pd,e)}const Cd=zr("ZodUUID",(e,t)=>{hs.init(e,t),Td.init(e,t)});function Rd(e){return Qa(Cd,e)}function jd(e){return ec(Cd,e)}function Md(e){return tc(Cd,e)}function Zd(e){return nc(Cd,e)}const Kd=zr("ZodURL",(e,t)=>{ys.init(e,t),Td.init(e,t)});function Ld(e){return rc(Kd,e)}function Ud(e){return rc(Kd,{protocol:/^https?$/,hostname:ro,...Xr(e)})}const Jd=zr("ZodEmoji",(e,t)=>{gs.init(e,t),Td.init(e,t)});function Hd(e){return ic(Jd,e)}const Wd=zr("ZodNanoID",(e,t)=>{vs.init(e,t),Td.init(e,t)});function Fd(e){return oc(Wd,e)}const Vd=zr("ZodCUID",(e,t)=>{ws.init(e,t),Td.init(e,t)});function Bd(e){return sc(Vd,e)}const qd=zr("ZodCUID2",(e,t)=>{bs.init(e,t),Td.init(e,t)});function Gd(e){return ac(qd,e)}const Yd=zr("ZodULID",(e,t)=>{_s.init(e,t),Td.init(e,t)});function Xd(e){return cc(Yd,e)}const Qd=zr("ZodXID",(e,t)=>{Ss.init(e,t),Td.init(e,t)});function eu(e){return dc(Qd,e)}const tu=zr("ZodKSUID",(e,t)=>{ks.init(e,t),Td.init(e,t)});function nu(e){return uc(tu,e)}const ru=zr("ZodIPv4",(e,t)=>{As.init(e,t),Td.init(e,t)});function iu(e){return lc(ru,e)}const ou=zr("ZodMAC",(e,t)=>{Ts.init(e,t),Td.init(e,t)});function su(e){return function(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...Xr(t)})}(ou,e)}const au=zr("ZodIPv6",(e,t)=>{$s.init(e,t),Td.init(e,t)});function cu(e){return pc(au,e)}const du=zr("ZodCIDRv4",(e,t)=>{Os.init(e,t),Td.init(e,t)});function uu(e){return fc(du,e)}const lu=zr("ZodCIDRv6",(e,t)=>{xs.init(e,t),Td.init(e,t)});function pu(e){return hc(lu,e)}const fu=zr("ZodBase64",(e,t)=>{Ns.init(e,t),Td.init(e,t)});function hu(e){return mc(fu,e)}const mu=zr("ZodBase64URL",(e,t)=>{Cs.init(e,t),Td.init(e,t)});function yu(e){return yc(mu,e)}const gu=zr("ZodE164",(e,t)=>{Rs.init(e,t),Td.init(e,t)});function vu(e){return gc(gu,e)}const wu=zr("ZodJWT",(e,t)=>{js.init(e,t),Td.init(e,t)});function bu(e){return vc(wu,e)}const _u=zr("ZodCustomStringFormat",(e,t)=>{Ms.init(e,t),Td.init(e,t)});function Su(e,t,n={}){return Bc(_u,e,t,n)}function ku(e){return Bc(_u,"hostname",no,e)}function Eu(e){return Bc(_u,"hex",bo,e)}function Iu(e,t){const n=`${e}_${t?.enc??"hex"}`,i=r[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return Bc(_u,n,i,t)}const Du=zr("ZodNumber",(e,t)=>{Zs.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:i,maximum:o,format:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:d}=e._zod.bag;"string"==typeof s&&s.includes("int")?r.type="integer":r.type="number","number"==typeof d&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d),"number"==typeof i&&(r.minimum=i,"number"==typeof d&&"draft-04"!==t.target&&(d>=i?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof c&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c),"number"==typeof o&&(r.maximum=o,"number"==typeof c&&"draft-04"!==t.target&&(c<=o?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof a&&(r.multipleOf=a)})(e,t,n),e.gt=(t,n)=>e.check(_c(t,n)),e.gte=(t,n)=>e.check(Sc(t,n)),e.min=(t,n)=>e.check(Sc(t,n)),e.lt=(t,n)=>e.check(wc(t,n)),e.lte=(t,n)=>e.check(bc(t,n)),e.max=(t,n)=>e.check(bc(t,n)),e.int=t=>e.check($u(t)),e.safe=t=>e.check($u(t)),e.positive=t=>e.check(_c(0,t)),e.nonnegative=t=>e.check(Sc(0,t)),e.negative=t=>e.check(wc(0,t)),e.nonpositive=t=>e.check(bc(0,t)),e.multipleOf=(t,n)=>e.check(zc(t,n)),e.step=(t,n)=>e.check(zc(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function zu(e){return function(e,t){return new e({type:"number",checks:[],...Xr(t)})}(Du,e)}const Au=zr("ZodNumberFormat",(e,t)=>{Ks.init(e,t),Du.init(e,t)});function $u(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Xr(t)})}(Au,e)}function Tu(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...Xr(t)})}(Au,e)}function Ou(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...Xr(t)})}(Au,e)}function xu(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...Xr(t)})}(Au,e)}function Pu(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...Xr(t)})}(Au,e)}const Nu=zr("ZodBoolean",(e,t)=>{Ls.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function Cu(e){return function(e,t){return new e({type:"boolean",...Xr(t)})}(Nu,e)}const Ru=zr("ZodBigInt",(e,t)=>{Us.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema")})(0,e),e.gte=(t,n)=>e.check(Sc(t,n)),e.min=(t,n)=>e.check(Sc(t,n)),e.gt=(t,n)=>e.check(_c(t,n)),e.gte=(t,n)=>e.check(Sc(t,n)),e.min=(t,n)=>e.check(Sc(t,n)),e.lt=(t,n)=>e.check(wc(t,n)),e.lte=(t,n)=>e.check(bc(t,n)),e.max=(t,n)=>e.check(bc(t,n)),e.positive=t=>e.check(_c(BigInt(0),t)),e.negative=t=>e.check(wc(BigInt(0),t)),e.nonpositive=t=>e.check(bc(BigInt(0),t)),e.nonnegative=t=>e.check(Sc(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(zc(t,n));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});function ju(e){return function(e,t){return new e({type:"bigint",...Xr(t)})}(Ru,e)}const Mu=zr("ZodBigIntFormat",(e,t)=>{Js.init(e,t),Ru.init(e,t)});function Zu(e){return function(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...Xr(t)})}(Mu,e)}function Ku(e){return function(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...Xr(t)})}(Mu,e)}const Lu=zr("ZodSymbol",(e,t)=>{Hs.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema")})(0,e)});function Uu(e){return function(e,t){return new e({type:"symbol",...Xr(t)})}(Lu,e)}const Ju=zr("ZodUndefined",(e,t)=>{Ws.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema")})(0,e)});function Hu(e){return function(e,t){return new e({type:"undefined",...Xr(t)})}(Ju,e)}const Wu=zr("ZodNull",(e,t)=>{Fs.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"})(0,e,t)});function Fu(e){return function(e,t){return new e({type:"null",...Xr(t)})}(Wu,e)}const Vu=zr("ZodAny",(e,t)=>{Vs.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Bu(){return new Vu({type:"any"})}const qu=zr("ZodUnknown",(e,t)=>{Bs.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Gu(){return new qu({type:"unknown"})}const Yu=zr("ZodNever",(e,t)=>{qs.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function Xu(e){return function(e,t){return new e({type:"never",...Xr(t)})}(Yu,e)}const Qu=zr("ZodVoid",(e,t)=>{Gs.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Void cannot be represented in JSON Schema")})(0,e)});function el(e){return function(e,t){return new e({type:"void",...Xr(t)})}(Qu,e)}const tl=zr("ZodDate",(e,t)=>{Ys.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")})(0,e),e.min=(t,n)=>e.check(Sc(t,n)),e.max=(t,n)=>e.check(bc(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function nl(e){return function(e,t){return new e({type:"date",...Xr(t)})}(tl,e)}const rl=zr("ZodArray",(e,t)=>{Qs.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a),i.type="array",i.items=Gc(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(xc(t,n)),e.nonempty=t=>e.check(xc(1,t)),e.max=(t,n)=>e.check(Oc(t,n)),e.length=(t,n)=>e.check(Pc(t,n)),e.unwrap=()=>e.element});function il(e,t){return function(e,t,n){return new e({type:"array",element:t,...Xr(n)})}(rl,e,t)}function ol(e){const t=e._zod.def.shape;return $l(Object.keys(t))}const sl=zr("ZodObject",(e,t)=>{ia.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const s=o.shape;for(const e in s)i.properties[e]=Gc(s[e],t,{...r,path:[...r.path,"properties",e]});const a=new Set(Object.keys(s)),c=new Set([...a].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(i.required=Array.from(c)),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Gc(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),Zr(e,"shape",()=>t.shape),e.keyof=()=>$l(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Gu()}),e.loose=()=>e.clone({...e._zod.def,catchall:Gu()}),e.strict=()=>e.clone({...e._zod.def,catchall:Xu()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Fr(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=Lr(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Kr(this,"shape",n),n}});return Yr(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Fr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Lr(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Kr(this,"shape",n),n}});return Yr(e,n)}(e,t),e.merge=t=>function(e,t){const n=Lr(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Kr(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Yr(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return Yr(e,Lr(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Kr(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=Lr(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Kr(this,"shape",r),r},checks:[]});return Yr(e,i)}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=Lr(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Kr(this,"shape",i),i},checks:[]});return Yr(t,i)}(jl,e,t[0]),e.required=(...t)=>function(e,t,n){const r=Lr(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)i[t]=new e({type:"nonoptional",innerType:r[t]});return Kr(this,"shape",i),i}});return Yr(t,r)}(Bl,e,t[0])});function al(e,t){const n={type:"object",shape:e??{},...Xr(t)};return new sl(n)}function cl(e,t){return new sl({type:"object",shape:e,catchall:Xu(),...Xr(t)})}function dl(e,t){return new sl({type:"object",shape:e,catchall:Gu(),...Xr(t)})}const ul=zr("ZodUnion",(e,t)=>{sa.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nd(e,t,n,r),e.options=t.options});function ll(e,t){return new ul({type:"union",options:e,...Xr(t)})}const pl=zr("ZodXor",(e,t)=>{ul.init(e,t),ca.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nd(e,t,n,r),e.options=t.options});function fl(e,t){return new pl({type:"union",options:e,inclusive:!1,...Xr(t)})}const hl=zr("ZodDiscriminatedUnion",(e,t)=>{ul.init(e,t),da.init(e,t)});function ml(e,t,n){return new hl({type:"union",options:t,discriminator:e,...Xr(n)})}const yl=zr("ZodIntersection",(e,t)=>{ua.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Gc(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Gc(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=c})(e,t,n,r)});function gl(e,t){return new yl({type:"intersection",left:e,right:t})}const vl=zr("ZodTuple",(e,t)=>{fa.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="array";const s="draft-2020-12"===t.target?"prefixItems":"items",a="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",c=o.items.map((e,n)=>Gc(e,t,{...r,path:[...r.path,s,n]})),d=o.rest?Gc(o.rest,t,{...r,path:[...r.path,a,..."openapi-3.0"===t.target?[o.items.length]:[]]}):null;"draft-2020-12"===t.target?(i.prefixItems=c,d&&(i.items=d)):"openapi-3.0"===t.target?(i.items={anyOf:c},d&&i.items.anyOf.push(d),i.minItems=c.length,d||(i.maxItems=c.length)):(i.items=c,d&&(i.additionalItems=d));const{minimum:u,maximum:l}=e._zod.bag;"number"==typeof u&&(i.minItems=u),"number"==typeof l&&(i.maxItems=l)})(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function wl(e,t,n){const r=t instanceof us;return new vl({type:"tuple",items:e,rest:r?t:null,...Xr(r?n:t)})}const bl=zr("ZodRecord",(e,t)=>{ma.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object";const s=o.keyType,a=s._zod.bag,c=a?.patterns;if("loose"===o.mode&&c&&c.size>0){const e=Gc(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const t of c)i.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(i.propertyNames=Gc(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Gc(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=s._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function _l(e,t,n){return new bl({type:"record",keyType:e,valueType:t,...Xr(n)})}function Sl(e,t,n){const r=Yr(e);return r._zod.values=void 0,new bl({type:"record",keyType:r,valueType:t,...Xr(n)})}function kl(e,t,n){return new bl({type:"record",keyType:e,valueType:t,mode:"loose",...Xr(n)})}const El=zr("ZodMap",(e,t)=>{ya.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Map cannot be represented in JSON Schema")})(0,e),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...t)=>e.check($c(...t)),e.nonempty=t=>e.check($c(1,t)),e.max=(...t)=>e.check(Ac(...t)),e.size=(...t)=>e.check(Tc(...t))});function Il(e,t,n){return new El({type:"map",keyType:e,valueType:t,...Xr(n)})}const Dl=zr("ZodSet",(e,t)=>{va.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Set cannot be represented in JSON Schema")})(0,e),e.min=(...t)=>e.check($c(...t)),e.nonempty=t=>e.check($c(1,t)),e.max=(...t)=>e.check(Ac(...t)),e.size=(...t)=>e.check(Tc(...t))});function zl(e,t){return new Dl({type:"set",valueType:e,...Xr(t)})}const Al=zr("ZodEnum",(e,t)=>{ba.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=xr(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const r of e){if(!n.has(r))throw new Error(`Key ${r} not found in enum`);i[r]=t.entries[r]}return new Al({...t,checks:[],...Xr(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new Al({...t,checks:[],...Xr(r),entries:i})}});function $l(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Al({type:"enum",entries:n,...Xr(t)})}function Tl(e,t){return new Al({type:"enum",entries:e,...Xr(t)})}const Ol=zr("ZodLiteral",(e,t)=>{_a.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,i=[];for(const e of r.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(e))}else i.push(e);if(0===i.length);else if(1===i.length){const e=i[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),i.every(e=>"boolean"==typeof e)&&(n.type="boolean"),i.every(e=>null===e)&&(n.type="null"),n.enum=i})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function xl(e,t){return new Ol({type:"literal",values:Array.isArray(e)?e:[e],...Xr(t)})}const Pl=zr("ZodFile",(e,t)=>{Sa.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:a}=e._zod.bag;void 0!==o&&(i.minLength=o),void 0!==s&&(i.maxLength=s),a?1===a.length?(i.contentMediaType=a[0],Object.assign(r,i)):(Object.assign(r,i),r.anyOf=a.map(e=>({contentMediaType:e}))):Object.assign(r,i)})(e,0,n),e.min=(t,n)=>e.check($c(t,n)),e.max=(t,n)=>e.check(Ac(t,n)),e.mime=(t,n)=>e.check(Lc(Array.isArray(t)?t:[t],n))});function Nl(e){return function(e,t){return new e({type:"file",...Xr(t)})}(Pl,e)}const Cl=zr("ZodTransform",(e,t)=>{ka.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new $r(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(ci(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(ci(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Rl(e){return new Cl({type:"transform",transform:e})}const jl=zr("ZodOptional",(e,t)=>{Ia.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rd(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Ml(e){return new jl({type:"optional",innerType:e})}const Zl=zr("ZodExactOptional",(e,t)=>{Da.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rd(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Kl(e){return new Zl({type:"optional",innerType:e})}const Ll=zr("ZodNullable",(e,t)=>{za.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Gc(i.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ul(e){return new Ll({type:"nullable",innerType:e})}function Jl(e){return Ml(Ul(e))}const Hl=zr("ZodDefault",(e,t)=>{Aa.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Gc(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Wl(e,t){return new Hl({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():Vr(t)}})}const Fl=zr("ZodPrefault",(e,t)=>{Ta.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Gc(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Vl(e,t){return new Fl({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():Vr(t)}})}const Bl=zr("ZodNonOptional",(e,t)=>{Oa.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Gc(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function ql(e,t){return new Bl({type:"nonoptional",innerType:e,...Xr(t)})}const Gl=zr("ZodSuccess",(e,t)=>{Pa.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t),e.unwrap=()=>e._zod.def.innerType});function Yl(e){return new Gl({type:"success",innerType:e})}const Xl=zr("ZodCatch",(e,t)=>{Na.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;let o;Gc(i.innerType,t,r),t.seen.get(e).ref=i.innerType;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ql(e,t){return new Xl({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const ep=zr("ZodNaN",(e,t)=>{Ca.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema")})(0,e)});function tp(e){return function(e,t){return new e({type:"nan",...Xr(t)})}(ep,e)}const np=zr("ZodPipe",(e,t)=>{Ra.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o="input"===t.io?"transform"===i.in._zod.def.type?i.out:i.in:i.out;Gc(o,t,r),t.seen.get(e).ref=o})(e,t,0,r),e.in=t.in,e.out=t.out});function rp(e,t){return new np({type:"pipe",in:e,out:t})}const ip=zr("ZodCodec",(e,t)=>{np.init(e,t),Ma.init(e,t)});function op(e,t,n){return new ip({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}const sp=zr("ZodReadonly",(e,t)=>{La.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Gc(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ap(e){return new sp({type:"readonly",innerType:e})}const cp=zr("ZodTemplateLiteral",(e,t)=>{Ja.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=i.source})(e,0,n)});function dp(e,t){return new cp({type:"template_literal",parts:e,...Xr(t)})}const up=zr("ZodLazy",(e,t)=>{Fa.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.innerType;Gc(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.unwrap=()=>e._zod.def.getter()});function lp(e){return new up({type:"lazy",getter:e})}const pp=zr("ZodPromise",(e,t)=>{Wa.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Gc(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function fp(e){return new pp({type:"promise",innerType:e})}const hp=zr("ZodFunction",(e,t)=>{Ha.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Function types cannot be represented in JSON Schema")})(0,e)});function mp(e){return new hp({type:"function",input:Array.isArray(e?.input)?wl(e?.input):e?.input??il(Gu()),output:e?.output??Gu()})}const yp=zr("ZodCustom",(e,t)=>{Va.init(e,t),Dd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});function gp(e){const t=new Mo({check:"custom"});return t._zod.check=e,t}function vp(e,t){return function(e,t,n){const r=Xr(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}(yp,e??(()=>!0),t)}function wp(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Xr(n)})}(yp,e,t)}function bp(e){return function(e){const t=function(e){const t=new Mo({check:"custom",...Xr(void 0)});return t._zod.check=e,t}(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(ci(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(ci(r))}},e(n.value,n)));return t}(e)}const _p=function(e){const t=new Mo({check:"describe"});return t._zod.onattach=[t=>{const n=Ga.get(t)??{};Ga.add(t,{...n,description:e})}],t._zod.check=()=>{},t},Sp=function(e){const t=new Mo({check:"meta"});return t._zod.onattach=[t=>{const n=Ga.get(t)??{};Ga.add(t,{...n,...e})}],t._zod.check=()=>{},t};function kp(e,t={}){const n=new yp({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...Xr(t)});return n._zod.bag.Class=e,n._zod.check=t=>{t.value instanceof e||t.issues.push({code:"invalid_type",expected:e.name,input:t.value,inst:n,path:[...n._zod.def.path??[]]})},n}const Ep=(...e)=>function(e,t){const n=Xr(t);let r=n.truthy??["true","1","yes","on","y","enabled"],i=n.falsy??["false","0","no","off","n","disabled"];"sensitive"!==n.case&&(r=r.map(e=>"string"==typeof e?e.toLowerCase():e),i=i.map(e=>"string"==typeof e?e.toLowerCase():e));const o=new Set(r),s=new Set(i),a=e.Codec??Ma,c=e.Boolean??Ls,d=new a({type:"pipe",in:new(e.String??ls)({type:"string",error:n.error}),out:new c({type:"boolean",error:n.error}),transform:(e,t)=>{let r=e;return"sensitive"!==n.case&&(r=r.toLowerCase()),!!o.has(r)||!s.has(r)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:t.value,inst:d,continue:!1}),{})},reverseTransform:(e,t)=>!0===e?r[0]||"true":i[0]||"false",error:n.error});return d}({Codec:ip,Boolean:Nu,String:Ad},...e);function Ip(e){const t=lp(()=>ll([$d(e),zu(),Cu(),Fu(),il(t),_l($d(),t)]));return t}function Dp(e,t){return rp(Rl(e),t)}var zp;async function Ap(e){const t=await e.generateKeyPair(),n=kt(t.publicKey);return{did:n,kid:`${n}#${Et(n)}`,privateKey:t.privateKey,publicKey:t.publicKey}}async function $p(e,t){const n=Dr({identity:t.identity??await Ap(t.crypto),session:t.session,delegation:t.delegation,autoSession:t.autoSession??!0,...t.grantStore?{grantStore:t.grantStore}:{},...void 0!==t.emitLegacyProofKey?{emitLegacyProofKey:t.emitLegacyProofKey}:{}},t.crypto);if("tool"===(t.handshakeExposure??"tool")&&e.registerTool("_kyaos",{description:"KYA-OS protocol — identity verification, session handshake, and server metadata",annotations:{title:"KYA-OS Protocol",readOnlyHint:!0},inputSchema:{action:$l(Ir).describe("Protocol operation to perform"),nonce:$d().optional().describe("Client-generated unique nonce (handshake)"),audience:$d().optional().describe("Intended audience (handshake)"),timestamp:zu().optional().describe("Unix epoch seconds (handshake)"),agentDid:$d().optional().describe("Client agent DID (handshake, optional)")}},async e=>{const t=await n.handleKyaOs(e);return{...t,content:t.content.map(e=>({...e,type:"text"}))}}),!1!==t.proofAllTools){const r=["_kyaos","_kyaos_handshake",...t.excludeTools??[]],i=e.connect.bind(e);e.connect=e=>i(function(e,t,n=["_kyaos","_kyaos_handshake"]){const r=new Map,i={start:()=>e.start(),close:()=>e.close(),set onmessage(t){e.onmessage=t},get onmessage(){return e.onmessage},set onclose(t){e.onclose=t},get onclose(){return e.onclose},set onerror(t){e.onerror=t},get onerror(){return e.onerror},async send(n){const i=n.id,o=void 0!==i?r.get(i):void 0;if(o){r.delete(i);try{const e=n.result;if(e&&!e.isError){const r=async()=>e,i=t.wrapWithProof(o.toolName,r),s=await i(o.args);void 0!==s._meta&&(n={...n,result:s})}}catch(e){zt.error("[kya-os-transport] Proof injection failed",{tool:o.toolName,error:e instanceof Error?e.message:String(e)});const t=n.result;t&&(t._meta={proofError:"Proof generation failed — response is unproven"},n={...n,result:t})}}return e.send(n)}},o=e.start.bind(e);return i.start=async()=>{await o();const t=e.onmessage;e.onmessage=e=>{if("tools/call"===e.method&&void 0!==e.id){const t=e.params,i=t?.name;i&&!n.includes(i)&&r.set(e.id,{toolName:i,args:t?.arguments??{}})}t?.(e)}},i}(e,n,r))}return n}zp||(zp={}),new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]),Or({localeError:(()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{const t=r[e.expected]??e.expected,n=function(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(null===e)return"null";if(Array.isArray(e))return"array";const t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return t}(e.input);return`Invalid input: expected ${t}, received ${r[n]??n}`}case"invalid_value":return 1===e.values.length?`Invalid input: expected ${Qr(e.values[0])}`:`Invalid option: expected one of ${Pr(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${Pr(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}})()})}};