@reqvire-org/ads 0.3.37 → 0.3.39

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.
Files changed (72) hide show
  1. package/README.md +5 -1
  2. package/dist/bootstrap-ds/README.md +2 -2
  3. package/dist/bootstrap-ds/ds.config.json +2 -0
  4. package/dist/bootstrap-ds/package.json +1 -1
  5. package/dist/cli.mjs +16 -5
  6. package/dist/config.mjs +13 -6
  7. package/dist/mcp/context.mjs +4 -3
  8. package/dist/mcp/drafts.mjs +126 -10
  9. package/dist/mcp/execution-results.mjs +2 -2
  10. package/dist/mcp/mutations.mjs +3 -2
  11. package/dist/mcp/preview-owner-guard.mjs +7 -4
  12. package/dist/mcp/preview-widget.bundle.js +46 -47
  13. package/dist/mcp/project-widget.bundle.js +45 -46
  14. package/dist/mcp/server.mjs +20 -7
  15. package/dist/mcp/widget.bundle.js +47 -48
  16. package/dist/preview-bun.mjs +5 -2
  17. package/dist/resource-limits.mjs +146 -0
  18. package/dist/runtime-requirements.mjs +21 -0
  19. package/dist/scenarios-compiler.mjs +4 -3
  20. package/dist/showcase/client.bundle.js +56 -57
  21. package/dist/showcase/sandbox.bundle.js +1 -1
  22. package/dist/skills/ads-break-ui/SKILL.md +3 -2
  23. package/dist/skills/ads-break-ui/references/behaviors.md +8 -4
  24. package/dist/skills/ads-break-ui/references/drafts.md +26 -5
  25. package/dist/skills/ads-break-ui/references/guarded-editing.md +4 -2
  26. package/dist/skills/ads-break-ui/references/runtimes.md +89 -4
  27. package/dist/skills/ads-break-ui/references/validation.md +43 -25
  28. package/dist/skills/ads-break-ui/references/workflows.md +4 -3
  29. package/dist/skills/ads-designer/SKILL.md +10 -5
  30. package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +2 -2
  31. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +2 -0
  32. package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +1 -1
  33. package/dist/skills/ads-designer/references/behaviors.md +8 -4
  34. package/dist/skills/ads-designer/references/cli.md +3 -3
  35. package/dist/skills/ads-designer/references/drafts.md +26 -5
  36. package/dist/skills/ads-designer/references/guarded-editing.md +4 -2
  37. package/dist/skills/ads-designer/references/runtimes.md +89 -4
  38. package/dist/skills/ads-designer/references/validation.md +43 -25
  39. package/dist/skills/ads-designer/references/workflows.md +4 -3
  40. package/dist/skills/ads-import/SKILL.md +3 -2
  41. package/dist/skills/ads-import/references/behaviors.md +8 -4
  42. package/dist/skills/ads-import/references/cli.md +3 -3
  43. package/dist/skills/ads-import/references/drafts.md +26 -5
  44. package/dist/skills/ads-import/references/guarded-editing.md +4 -2
  45. package/dist/skills/ads-import/references/runtimes.md +89 -4
  46. package/dist/skills/ads-import/references/validation.md +43 -25
  47. package/dist/skills/ads-import/references/workflows.md +4 -3
  48. package/dist/skills/ads-motion/SKILL.md +3 -2
  49. package/dist/skills/ads-motion/references/behaviors.md +8 -4
  50. package/dist/skills/ads-motion/references/drafts.md +26 -5
  51. package/dist/skills/ads-motion/references/guarded-editing.md +4 -2
  52. package/dist/skills/ads-motion/references/runtimes.md +89 -4
  53. package/dist/skills/ads-motion/references/validation.md +43 -25
  54. package/dist/skills/ads-motion/references/workflows.md +4 -3
  55. package/dist/skills/ads-port/SKILL.md +3 -2
  56. package/dist/skills/ads-port/references/behaviors.md +8 -4
  57. package/dist/skills/ads-port/references/cli.md +3 -3
  58. package/dist/skills/ads-port/references/drafts.md +26 -5
  59. package/dist/skills/ads-port/references/guarded-editing.md +4 -2
  60. package/dist/skills/ads-port/references/runtimes.md +89 -4
  61. package/dist/skills/ads-port/references/validation.md +43 -25
  62. package/dist/skills/ads-port/references/workflows.md +4 -3
  63. package/dist/units.mjs +1 -1
  64. package/dist/validation-checks.mjs +10 -5
  65. package/dist/validation.mjs +16 -31
  66. package/dist/verification/browser.mjs +8 -8
  67. package/docs/ARCHITECTURE.md +8 -4
  68. package/docs/BEHAVIORS.md +6 -3
  69. package/docs/CHANGELOG.md +70 -13
  70. package/docs/GUIDE.md +13 -7
  71. package/docs/MCP.md +49 -17
  72. package/package.json +2 -2
@@ -1,90 +1,89 @@
1
- var vM=Object.defineProperty;var yM=(H)=>H;function hM(H,W){this[H]=yM.bind(null,W)}var o0=(H,W)=>{for(var Q in W)vM(H,Q,{get:W[Q],enumerable:!0,configurable:!0,set:hM.bind(W,Q)})};var{create:fM,defineProperty:L4,getOwnPropertyDescriptor:uM,getOwnPropertyNames:lM,getPrototypeOf:mM}=Object,cM=Object.prototype.hasOwnProperty,M2=(H,W)=>()=>(W||H((W={exports:{}}).exports,W),W.exports),q2=(H,W)=>{let Q={};for(var X in H)L4(Q,X,{get:H[X],enumerable:!0});if(W)L4(Q,Symbol.toStringTag,{value:"Module"});return Q},pM=(H,W,Q,X)=>{if(W&&typeof W==="object"||typeof W==="function"){for(var Y=lM(W),J=0,N=Y.length,B;J<N;J++)if(B=Y[J],!cM.call(H,B)&&B!==Q)L4(H,B,{get:((G)=>W[G]).bind(null,B),enumerable:!(X=uM(W,B))||X.enumerable})}return H},_2=(H,W,Q)=>(Q=H!=null?fM(mM(H)):{},pM(W||!H||!H.__esModule?L4(Q,"default",{value:H,enumerable:!0}):Q,H));var dM=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),F2=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),iM=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),oM=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function E2(H){return typeof H==="string"&&F2.has(H.replace(/#$/,""))}function A2(H,W){if(!("$schema"in H)||typeof H.$schema!=="string")return"2020-12";let Q=H.$schema.replace(/#$/,"");if(dM.has(Q))return"2020-12";if(F2.has(Q))return"2019-09";if(iM.has(Q)||oM.has(Q))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${H.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${W}`)}var q={};o0(q,{xor:()=>fK,xid:()=>MK,void:()=>xK,uuidv7:()=>YK,uuidv6:()=>XK,uuidv4:()=>QK,uuid:()=>WK,util:()=>s,url:()=>K1,uppercase:()=>o8,unknown:()=>h,union:()=>S,undefined:()=>gK,ulid:()=>DK,uint64:()=>SK,uint32:()=>$K,tuple:()=>j7,trim:()=>e8,treeifyError:()=>VJ,transform:()=>X9,toUpperCase:()=>W1,toLowerCase:()=>H1,toJSONSchema:()=>W8,templateLiteral:()=>sK,symbol:()=>kK,superRefine:()=>e7,success:()=>oK,stringbool:()=>JG,stringFormat:()=>ZK,string:()=>K,strictObject:()=>hK,startsWith:()=>r8,slugify:()=>Q1,size:()=>aW,setErrorMap:()=>C_,set:()=>cK,safeParseAsync:()=>J7,safeParse:()=>aQ,safeEncodeAsync:()=>q7,safeEncode:()=>D7,safeDecodeAsync:()=>_7,safeDecode:()=>M7,registry:()=>H6,regexes:()=>W0,regex:()=>d8,refine:()=>a7,record:()=>T,readonly:()=>o7,property:()=>I6,promise:()=>aK,prettifyError:()=>UJ,preprocess:()=>s0,prefault:()=>f7,positive:()=>z6,pipe:()=>x6,partialRecord:()=>uK,parseAsync:()=>Y7,parse:()=>X7,overwrite:()=>E0,optional:()=>f,object:()=>E,number:()=>b,nullish:()=>iK,nullable:()=>HX,null:()=>g0,normalize:()=>a8,nonpositive:()=>P6,nonoptional:()=>u7,nonnegative:()=>b6,never:()=>Q9,negative:()=>Z6,nativeEnum:()=>pK,nanoid:()=>BK,nan:()=>nK,multipleOf:()=>VW,minSize:()=>S0,minLength:()=>r0,mime:()=>s8,meta:()=>XG,maxSize:()=>UW,maxLength:()=>eW,map:()=>mK,mac:()=>FK,lte:()=>Q0,lt:()=>R0,lowercase:()=>i8,looseRecord:()=>lK,looseObject:()=>l,locales:()=>nQ,literal:()=>U,length:()=>H8,lazy:()=>bW,ksuid:()=>qK,keyof:()=>yK,jwt:()=>zK,json:()=>NG,iso:()=>X0,ipv6:()=>EK,ipv4:()=>_K,invertCodec:()=>tK,intersection:()=>A0,int64:()=>CK,int32:()=>TK,int:()=>g6,instanceof:()=>YG,includes:()=>n8,httpUrl:()=>JK,hostname:()=>PK,hex:()=>bK,hash:()=>IK,guid:()=>HK,gte:()=>lH,gt:()=>C0,globalRegistry:()=>LH,getErrorMap:()=>S_,function:()=>eK,fromJSONSchema:()=>KG,formatError:()=>uQ,float64:()=>jK,float32:()=>LK,flattenError:()=>fQ,file:()=>dK,exactOptional:()=>g7,enum:()=>t,endsWith:()=>t8,encodeAsync:()=>K7,encode:()=>N7,emoji:()=>NK,email:()=>h6,e164:()=>wK,discriminatedUnion:()=>PW,describe:()=>QG,decodeAsync:()=>G7,decode:()=>B7,date:()=>vK,custom:()=>WG,cuid2:()=>GK,cuid:()=>KK,core:()=>t0,config:()=>AH,coerce:()=>GX,codec:()=>rK,clone:()=>fH,cidrv6:()=>OK,cidrv4:()=>AK,check:()=>HG,catch:()=>c7,boolean:()=>R,bigint:()=>RK,base64url:()=>UK,base64:()=>VK,array:()=>V,any:()=>W9,_function:()=>eK,_default:()=>y7,_ZodString:()=>v6,ZodXor:()=>P7,ZodXID:()=>p6,ZodVoid:()=>z7,ZodUnknown:()=>U7,ZodUnion:()=>JX,ZodUndefined:()=>A7,ZodUUID:()=>k0,ZodURL:()=>QX,ZodULID:()=>c6,ZodType:()=>HH,ZodTuple:()=>L7,ZodTransform:()=>S7,ZodTemplateLiteral:()=>n7,ZodSymbol:()=>E7,ZodSuccess:()=>l7,ZodStringFormat:()=>KH,ZodString:()=>B1,ZodSet:()=>$7,ZodRecord:()=>J1,ZodRealError:()=>nH,ZodReadonly:()=>i7,ZodPromise:()=>t7,ZodPreprocess:()=>d7,ZodPrefault:()=>h7,ZodPipe:()=>NX,ZodOptional:()=>Y9,ZodObject:()=>YX,ZodNumberFormat:()=>Q8,ZodNumber:()=>D1,ZodNullable:()=>x7,ZodNull:()=>O7,ZodNonOptional:()=>J9,ZodNever:()=>w7,ZodNanoID:()=>u6,ZodNaN:()=>p7,ZodMap:()=>T7,ZodMAC:()=>F7,ZodLiteral:()=>R7,ZodLazy:()=>r7,ZodKSUID:()=>d6,ZodJWT:()=>e6,ZodIssueCode:()=>WB,ZodIntersection:()=>I7,ZodISOTime:()=>S6,ZodISODuration:()=>k6,ZodISODateTime:()=>R6,ZodISODate:()=>C6,ZodIPv6:()=>o6,ZodIPv4:()=>i6,ZodGUID:()=>eQ,ZodFunction:()=>s7,ZodFirstPartyTypeKind:()=>HB,ZodFile:()=>C7,ZodExactOptional:()=>k7,ZodError:()=>$_,ZodEnum:()=>N1,ZodEmoji:()=>f6,ZodEmail:()=>y6,ZodE164:()=>a6,ZodDiscriminatedUnion:()=>b7,ZodDefault:()=>v7,ZodDate:()=>XX,ZodCustomStringFormat:()=>G1,ZodCustom:()=>KX,ZodCodec:()=>BX,ZodCatch:()=>m7,ZodCUID2:()=>m6,ZodCUID:()=>l6,ZodCIDRv6:()=>r6,ZodCIDRv4:()=>n6,ZodBoolean:()=>M1,ZodBigIntFormat:()=>H9,ZodBigInt:()=>q1,ZodBase64URL:()=>s6,ZodBase64:()=>t6,ZodArray:()=>Z7,ZodAny:()=>V7,TimePrecision:()=>SN,NEVER:()=>CQ,$output:()=>LN,$input:()=>jN,$brand:()=>NJ});var t0={};o0(t0,{version:()=>E3,util:()=>s,treeifyError:()=>VJ,toJSONSchema:()=>W8,toDotPath:()=>P2,safeParseAsync:()=>zJ,safeParse:()=>wJ,safeEncodeAsync:()=>Lq,safeEncode:()=>bq,safeDecodeAsync:()=>jq,safeDecode:()=>Iq,registry:()=>H6,regexes:()=>W0,process:()=>YH,prettifyError:()=>UJ,parseAsync:()=>S4,parse:()=>C4,meta:()=>q5,locales:()=>nQ,isValidJWT:()=>d2,isValidBase64URL:()=>p2,isValidBase64:()=>y3,initializeContext:()=>wW,globalRegistry:()=>LH,globalConfig:()=>oW,formatError:()=>uQ,flattenError:()=>fQ,finalize:()=>ZW,extractDefs:()=>zW,encodeAsync:()=>Zq,encode:()=>wq,describe:()=>M5,decodeAsync:()=>Pq,decode:()=>zq,createToJSONSchemaMethod:()=>F5,createStandardJSONSchemaMethod:()=>Y1,config:()=>AH,clone:()=>fH,_xor:()=>J_,_xid:()=>M6,_void:()=>Q5,_uuidv7:()=>J6,_uuidv6:()=>Y6,_uuidv4:()=>X6,_uuid:()=>Q6,_url:()=>tQ,_uppercase:()=>o8,_unknown:()=>H5,_union:()=>Y_,_undefined:()=>sN,_ulid:()=>D6,_uint64:()=>rN,_uint32:()=>cN,_tuple:()=>K_,_trim:()=>e8,_transform:()=>E_,_toUpperCase:()=>W1,_toLowerCase:()=>H1,_templateLiteral:()=>b_,_symbol:()=>tN,_superRefine:()=>D5,_success:()=>w_,_stringbool:()=>_5,_stringFormat:()=>X1,_string:()=>$N,_startsWith:()=>r8,_slugify:()=>Q1,_size:()=>aW,_set:()=>M_,_safeParseAsync:()=>c8,_safeParse:()=>m8,_safeEncodeAsync:()=>f4,_safeEncode:()=>y4,_safeDecodeAsync:()=>u4,_safeDecode:()=>h4,_regex:()=>d8,_refine:()=>G5,_record:()=>G_,_readonly:()=>P_,_property:()=>I6,_promise:()=>L_,_positive:()=>z6,_pipe:()=>Z_,_parseAsync:()=>l8,_parse:()=>u8,_overwrite:()=>E0,_optional:()=>A_,_number:()=>yN,_nullable:()=>O_,_null:()=>aN,_normalize:()=>a8,_nonpositive:()=>P6,_nonoptional:()=>U_,_nonnegative:()=>b6,_never:()=>W5,_negative:()=>Z6,_nativeEnum:()=>__,_nanoid:()=>B6,_nan:()=>J5,_multipleOf:()=>VW,_minSize:()=>S0,_minLength:()=>r0,_min:()=>lH,_mime:()=>s8,_maxSize:()=>UW,_maxLength:()=>eW,_max:()=>Q0,_map:()=>D_,_mac:()=>CN,_lte:()=>Q0,_lt:()=>R0,_lowercase:()=>i8,_literal:()=>F_,_length:()=>H8,_lazy:()=>I_,_ksuid:()=>q6,_jwt:()=>w6,_isoTime:()=>xN,_isoDuration:()=>vN,_isoDateTime:()=>kN,_isoDate:()=>gN,_ipv6:()=>F6,_ipv4:()=>_6,_intersection:()=>B_,_int64:()=>nN,_int32:()=>mN,_int:()=>fN,_includes:()=>n8,_guid:()=>rQ,_gte:()=>lH,_gt:()=>C0,_float64:()=>lN,_float32:()=>uN,_file:()=>B5,_enum:()=>q_,_endsWith:()=>t8,_encodeAsync:()=>x4,_encode:()=>k4,_emoji:()=>N6,_email:()=>W6,_e164:()=>U6,_discriminatedUnion:()=>N_,_default:()=>V_,_decodeAsync:()=>v4,_decode:()=>g4,_date:()=>X5,_custom:()=>K5,_cuid2:()=>G6,_cuid:()=>K6,_coercedString:()=>RN,_coercedNumber:()=>hN,_coercedDate:()=>Y5,_coercedBoolean:()=>dN,_coercedBigint:()=>oN,_cidrv6:()=>A6,_cidrv4:()=>E6,_check:()=>t2,_catch:()=>z_,_boolean:()=>pN,_bigint:()=>iN,_base64url:()=>V6,_base64:()=>O6,_array:()=>N5,_any:()=>eN,TimePrecision:()=>SN,NEVER:()=>CQ,JSONSchemaGenerator:()=>a5,JSONSchema:()=>s2,Doc:()=>p4,$output:()=>LN,$input:()=>jN,$constructor:()=>O,$brand:()=>NJ,$ZodXor:()=>WN,$ZodXID:()=>L3,$ZodVoid:()=>s3,$ZodUnknown:()=>r3,$ZodUnion:()=>dQ,$ZodUndefined:()=>i3,$ZodUUID:()=>V3,$ZodURL:()=>w3,$ZodULID:()=>I3,$ZodType:()=>a,$ZodTuple:()=>s4,$ZodTransform:()=>DN,$ZodTemplateLiteral:()=>zN,$ZodSymbol:()=>d3,$ZodSuccess:()=>AN,$ZodStringFormat:()=>BH,$ZodString:()=>sW,$ZodSet:()=>NN,$ZodRegistry:()=>TN,$ZodRecord:()=>YN,$ZodRealError:()=>oH,$ZodReadonly:()=>wN,$ZodPromise:()=>PN,$ZodPreprocess:()=>UN,$ZodPrefault:()=>FN,$ZodPipe:()=>e4,$ZodOptional:()=>a4,$ZodObjectJIT:()=>HN,$ZodObject:()=>n2,$ZodNumberFormat:()=>c3,$ZodNumber:()=>r4,$ZodNullable:()=>qN,$ZodNull:()=>o3,$ZodNonOptional:()=>EN,$ZodNever:()=>t3,$ZodNanoID:()=>Z3,$ZodNaN:()=>VN,$ZodMap:()=>JN,$ZodMAC:()=>g3,$ZodLiteral:()=>KN,$ZodLazy:()=>bN,$ZodKSUID:()=>j3,$ZodJWT:()=>l3,$ZodIntersection:()=>XN,$ZodISOTime:()=>R3,$ZodISODuration:()=>C3,$ZodISODateTime:()=>T3,$ZodISODate:()=>$3,$ZodIPv6:()=>k3,$ZodIPv4:()=>S3,$ZodGUID:()=>O3,$ZodFunction:()=>ZN,$ZodFile:()=>GN,$ZodExactOptional:()=>MN,$ZodError:()=>hQ,$ZodEnum:()=>BN,$ZodEncodeError:()=>nW,$ZodEmoji:()=>z3,$ZodEmail:()=>U3,$ZodE164:()=>u3,$ZodDiscriminatedUnion:()=>QN,$ZodDefault:()=>_N,$ZodDate:()=>a3,$ZodCustomStringFormat:()=>m3,$ZodCustom:()=>IN,$ZodCodec:()=>iQ,$ZodCheckUpperCase:()=>K3,$ZodCheckStringFormat:()=>p8,$ZodCheckStartsWith:()=>D3,$ZodCheckSizeEquals:()=>Q3,$ZodCheckRegex:()=>N3,$ZodCheckProperty:()=>q3,$ZodCheckOverwrite:()=>F3,$ZodCheckNumberFormat:()=>aJ,$ZodCheckMultipleOf:()=>sJ,$ZodCheckMinSize:()=>W3,$ZodCheckMinLength:()=>Y3,$ZodCheckMimeType:()=>_3,$ZodCheckMaxSize:()=>H3,$ZodCheckMaxLength:()=>X3,$ZodCheckLowerCase:()=>B3,$ZodCheckLessThan:()=>m4,$ZodCheckLengthEquals:()=>J3,$ZodCheckIncludes:()=>G3,$ZodCheckGreaterThan:()=>c4,$ZodCheckEndsWith:()=>M3,$ZodCheckBigIntFormat:()=>eJ,$ZodCheck:()=>GH,$ZodCatch:()=>ON,$ZodCUID2:()=>b3,$ZodCUID:()=>P3,$ZodCIDRv6:()=>v3,$ZodCIDRv4:()=>x3,$ZodBoolean:()=>pQ,$ZodBigIntFormat:()=>p3,$ZodBigInt:()=>t4,$ZodBase64URL:()=>f3,$ZodBase64:()=>h3,$ZodAsyncError:()=>$0,$ZodArray:()=>e3,$ZodAny:()=>n3});var O2,CQ=Object.freeze({status:"aborted"});function O(H,W,Q){function X(B,G){if(!B._zod)Object.defineProperty(B,"_zod",{value:{def:G,constr:N,traits:new Set},enumerable:!1});if(B._zod.traits.has(H))return;B._zod.traits.add(H),W(B,G);let D=N.prototype,M=Object.keys(D);for(let _=0;_<M.length;_++){let F=M[_];if(!(F in B))B[F]=D[F].bind(B)}}let Y=Q?.Parent??Object;class J extends Y{}Object.defineProperty(J,"name",{value:H});function N(B){var G;let D=Q?.Parent?new J:this;X(D,B),(G=D._zod).deferred??(G.deferred=[]);for(let M of D._zod.deferred)M();return D}return Object.defineProperty(N,"init",{value:X}),Object.defineProperty(N,Symbol.hasInstance,{value:(B)=>{if(Q?.Parent&&B instanceof Q.Parent)return!0;return B?._zod?.traits?.has(H)}}),Object.defineProperty(N,"name",{value:H}),N}var NJ=Symbol("zod_brand");class $0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class nW extends Error{constructor(H){super(`Encountered unidirectional transform during encode: ${H}`);this.name="ZodEncodeError"}}(O2=globalThis).__zod_globalConfig??(O2.__zod_globalConfig={});var oW=globalThis.__zod_globalConfig;function AH(H){if(H)Object.assign(oW,H);return oW}var s={};o0(s,{unwrapMessage:()=>SQ,uint8ArrayToHex:()=>Vq,uint8ArrayToBase64url:()=>Aq,uint8ArrayToBase64:()=>w2,stringifyPrimitive:()=>R4,slugify:()=>GJ,shallowClone:()=>MJ,safeExtend:()=>Dq,required:()=>_q,randomString:()=>Xq,propertyKeyTypes:()=>xQ,promiseAllObject:()=>Qq,primitiveTypes:()=>qJ,prefixIssues:()=>iH,pick:()=>Bq,partial:()=>qq,parsedType:()=>OJ,optionalKeys:()=>_J,omit:()=>Kq,objectClone:()=>eM,numKeys:()=>Yq,nullish:()=>FW,normalizeParams:()=>L,mergeDefs:()=>n0,merge:()=>Mq,jsonStringifyReplacer:()=>y8,joinValues:()=>j4,issue:()=>f8,isPlainObject:()=>AW,isObject:()=>rW,hexToUint8Array:()=>Oq,getSizableOrigin:()=>vQ,getParsedType:()=>Jq,getLengthableOrigin:()=>yQ,getEnumValues:()=>kQ,getElementAtPath:()=>Wq,floatSafeRemainder:()=>KJ,finalizeIssue:()=>uH,extend:()=>Gq,explicitlyAborted:()=>AJ,escapeRegex:()=>G0,esc:()=>T4,defineLazy:()=>QH,createTransparentProxy:()=>Nq,cloneDef:()=>Hq,clone:()=>fH,cleanRegex:()=>gQ,cleanEnum:()=>Fq,captureStackTrace:()=>$4,cached:()=>h8,base64urlToUint8Array:()=>Eq,base64ToUint8Array:()=>U2,assignProp:()=>EW,assertNotEqual:()=>rM,assertNever:()=>sM,assertIs:()=>tM,assertEqual:()=>nM,assert:()=>aM,allowsEval:()=>DJ,aborted:()=>OW,NUMBER_FORMAT_RANGES:()=>FJ,Class:()=>z2,BIGINT_FORMAT_RANGES:()=>EJ});function nM(H){return H}function rM(H){return H}function tM(H){}function sM(H){throw Error("Unexpected value in exhaustive check")}function aM(H){}function kQ(H){let W=Object.values(H).filter((X)=>typeof X==="number");return Object.entries(H).filter(([X,Y])=>W.indexOf(+X)===-1).map(([X,Y])=>Y)}function j4(H,W="|"){return H.map((Q)=>R4(Q)).join(W)}function y8(H,W){if(typeof W==="bigint")return W.toString();return W}function h8(H){return{get value(){{let Q=H();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function FW(H){return H===null||H===void 0}function gQ(H){let W=H.startsWith("^")?1:0,Q=H.endsWith("$")?H.length-1:H.length;return H.slice(W,Q)}function KJ(H,W){let Q=H/W,X=Math.round(Q),Y=Number.EPSILON*Math.max(Math.abs(Q),1);if(Math.abs(Q-X)<Y)return 0;return Q-X}var V2=Symbol("evaluating");function QH(H,W,Q){let X=void 0;Object.defineProperty(H,W,{get(){if(X===V2)return;if(X===void 0)X=V2,X=Q();return X},set(Y){Object.defineProperty(H,W,{value:Y})},configurable:!0})}function eM(H){return Object.create(Object.getPrototypeOf(H),Object.getOwnPropertyDescriptors(H))}function EW(H,W,Q){Object.defineProperty(H,W,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function n0(...H){let W={};for(let Q of H){let X=Object.getOwnPropertyDescriptors(Q);Object.assign(W,X)}return Object.defineProperties({},W)}function Hq(H){return n0(H._zod.def)}function Wq(H,W){if(!W)return H;return W.reduce((Q,X)=>Q?.[X],H)}function Qq(H){let W=Object.keys(H),Q=W.map((X)=>H[X]);return Promise.all(Q).then((X)=>{let Y={};for(let J=0;J<W.length;J++)Y[W[J]]=X[J];return Y})}function Xq(H=10){let Q="";for(let X=0;X<H;X++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function T4(H){return JSON.stringify(H)}function GJ(H){return H.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var $4="captureStackTrace"in Error?Error.captureStackTrace:(...H)=>{};function rW(H){return typeof H==="object"&&H!==null&&!Array.isArray(H)}var DJ=h8(()=>{if(oW.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(H){return!1}});function AW(H){if(rW(H)===!1)return!1;let W=H.constructor;if(W===void 0)return!0;if(typeof W!=="function")return!0;let Q=W.prototype;if(rW(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function MJ(H){if(AW(H))return{...H};if(Array.isArray(H))return[...H];if(H instanceof Map)return new Map(H);if(H instanceof Set)return new Set(H);return H}function Yq(H){let W=0;for(let Q in H)if(Object.prototype.hasOwnProperty.call(H,Q))W++;return W}var Jq=(H)=>{let W=typeof H;switch(W){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(H)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(H))return"array";if(H===null)return"null";if(H.then&&typeof H.then==="function"&&H.catch&&typeof H.catch==="function")return"promise";if(typeof Map<"u"&&H instanceof Map)return"map";if(typeof Set<"u"&&H instanceof Set)return"set";if(typeof Date<"u"&&H instanceof Date)return"date";if(typeof File<"u"&&H instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${W}`)}},xQ=new Set(["string","number","symbol"]),qJ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function G0(H){return H.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fH(H,W,Q){let X=new H._zod.constr(W??H._zod.def);if(!W||Q?.parent)X._zod.parent=H;return X}function L(H){let W=H;if(!W)return{};if(typeof W==="string")return{error:()=>W};if(W?.message!==void 0){if(W?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");W.error=W.message}if(delete W.message,typeof W.error==="string")return{...W,error:()=>W.error};return W}function Nq(H){let W;return new Proxy({},{get(Q,X,Y){return W??(W=H()),Reflect.get(W,X,Y)},set(Q,X,Y,J){return W??(W=H()),Reflect.set(W,X,Y,J)},has(Q,X){return W??(W=H()),Reflect.has(W,X)},deleteProperty(Q,X){return W??(W=H()),Reflect.deleteProperty(W,X)},ownKeys(Q){return W??(W=H()),Reflect.ownKeys(W)},getOwnPropertyDescriptor(Q,X){return W??(W=H()),Reflect.getOwnPropertyDescriptor(W,X)},defineProperty(Q,X,Y){return W??(W=H()),Reflect.defineProperty(W,X,Y)}})}function R4(H){if(typeof H==="bigint")return H.toString()+"n";if(typeof H==="string")return`"${H}"`;return`${H}`}function _J(H){return Object.keys(H).filter((W)=>{return H[W]._zod.optin==="optional"&&H[W]._zod.optout==="optional"})}var FJ={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},EJ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Bq(H,W){let Q=H._zod.def,X=Q.checks;if(X&&X.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let J=n0(H._zod.def,{get shape(){let N={};for(let B in W){if(!(B in Q.shape))throw Error(`Unrecognized key: "${B}"`);if(!W[B])continue;N[B]=Q.shape[B]}return EW(this,"shape",N),N},checks:[]});return fH(H,J)}function Kq(H,W){let Q=H._zod.def,X=Q.checks;if(X&&X.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let J=n0(H._zod.def,{get shape(){let N={...H._zod.def.shape};for(let B in W){if(!(B in Q.shape))throw Error(`Unrecognized key: "${B}"`);if(!W[B])continue;delete N[B]}return EW(this,"shape",N),N},checks:[]});return fH(H,J)}function Gq(H,W){if(!AW(W))throw Error("Invalid input to extend: expected a plain object");let Q=H._zod.def.checks;if(Q&&Q.length>0){let J=H._zod.def.shape;for(let N in W)if(Object.getOwnPropertyDescriptor(J,N)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let Y=n0(H._zod.def,{get shape(){let J={...H._zod.def.shape,...W};return EW(this,"shape",J),J}});return fH(H,Y)}function Dq(H,W){if(!AW(W))throw Error("Invalid input to safeExtend: expected a plain object");let Q=n0(H._zod.def,{get shape(){let X={...H._zod.def.shape,...W};return EW(this,"shape",X),X}});return fH(H,Q)}function Mq(H,W){if(H._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let Q=n0(H._zod.def,{get shape(){let X={...H._zod.def.shape,...W._zod.def.shape};return EW(this,"shape",X),X},get catchall(){return W._zod.def.catchall},checks:W._zod.def.checks??[]});return fH(H,Q)}function qq(H,W,Q){let Y=W._zod.def.checks;if(Y&&Y.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let N=n0(W._zod.def,{get shape(){let B=W._zod.def.shape,G={...B};if(Q)for(let D in Q){if(!(D in B))throw Error(`Unrecognized key: "${D}"`);if(!Q[D])continue;G[D]=H?new H({type:"optional",innerType:B[D]}):B[D]}else for(let D in B)G[D]=H?new H({type:"optional",innerType:B[D]}):B[D];return EW(this,"shape",G),G},checks:[]});return fH(W,N)}function _q(H,W,Q){let X=n0(W._zod.def,{get shape(){let Y=W._zod.def.shape,J={...Y};if(Q)for(let N in Q){if(!(N in J))throw Error(`Unrecognized key: "${N}"`);if(!Q[N])continue;J[N]=new H({type:"nonoptional",innerType:Y[N]})}else for(let N in Y)J[N]=new H({type:"nonoptional",innerType:Y[N]});return EW(this,"shape",J),J}});return fH(W,X)}function OW(H,W=0){if(H.aborted===!0)return!0;for(let Q=W;Q<H.issues.length;Q++)if(H.issues[Q]?.continue!==!0)return!0;return!1}function AJ(H,W=0){if(H.aborted===!0)return!0;for(let Q=W;Q<H.issues.length;Q++)if(H.issues[Q]?.continue===!1)return!0;return!1}function iH(H,W){return W.map((Q)=>{var X;return(X=Q).path??(X.path=[]),Q.path.unshift(H),Q})}function SQ(H){return typeof H==="string"?H:H?.message}function uH(H,W,Q){let X=H.message?H.message:SQ(H.inst?._zod.def?.error?.(H))??SQ(W?.error?.(H))??SQ(Q.customError?.(H))??SQ(Q.localeError?.(H))??"Invalid input",{inst:Y,continue:J,input:N,...B}=H;if(B.path??(B.path=[]),B.message=X,W?.reportInput)B.input=N;return B}function vQ(H){if(H instanceof Set)return"set";if(H instanceof Map)return"map";if(H instanceof File)return"file";return"unknown"}function yQ(H){if(Array.isArray(H))return"array";if(typeof H==="string")return"string";return"unknown"}function OJ(H){let W=typeof H;switch(W){case"number":return Number.isNaN(H)?"nan":"number";case"object":{if(H===null)return"null";if(Array.isArray(H))return"array";let Q=H;if(Q&&Object.getPrototypeOf(Q)!==Object.prototype&&"constructor"in Q&&Q.constructor)return Q.constructor.name}}return W}function f8(...H){let[W,Q,X]=H;if(typeof W==="string")return{message:W,code:"custom",input:Q,inst:X};return{...W}}function Fq(H){return Object.entries(H).filter(([W,Q])=>{return Number.isNaN(Number.parseInt(W,10))}).map((W)=>W[1])}function U2(H){let W=atob(H),Q=new Uint8Array(W.length);for(let X=0;X<W.length;X++)Q[X]=W.charCodeAt(X);return Q}function w2(H){let W="";for(let Q=0;Q<H.length;Q++)W+=String.fromCharCode(H[Q]);return btoa(W)}function Eq(H){let W=H.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-W.length%4)%4);return U2(W+Q)}function Aq(H){return w2(H).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Oq(H){let W=H.replace(/^0x/,"");if(W.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(W.length/2);for(let X=0;X<W.length;X+=2)Q[X/2]=Number.parseInt(W.slice(X,X+2),16);return Q}function Vq(H){return Array.from(H).map((W)=>W.toString(16).padStart(2,"0")).join("")}class z2{constructor(...H){}}var Z2=(H,W)=>{H.name="$ZodError",Object.defineProperty(H,"_zod",{value:H._zod,enumerable:!1}),Object.defineProperty(H,"issues",{value:W,enumerable:!1}),H.message=JSON.stringify(W,y8,2),Object.defineProperty(H,"toString",{value:()=>H.message,enumerable:!1})},hQ=O("$ZodError",Z2),oH=O("$ZodError",Z2,{Parent:Error});function fQ(H,W=(Q)=>Q.message){let Q={},X=[];for(let Y of H.issues)if(Y.path.length>0)Q[Y.path[0]]=Q[Y.path[0]]||[],Q[Y.path[0]].push(W(Y));else X.push(W(Y));return{formErrors:X,fieldErrors:Q}}function uQ(H,W=(Q)=>Q.message){let Q={_errors:[]},X=(Y,J=[])=>{for(let N of Y.issues)if(N.code==="invalid_union"&&N.errors.length)N.errors.map((B)=>X({issues:B},[...J,...N.path]));else if(N.code==="invalid_key")X({issues:N.issues},[...J,...N.path]);else if(N.code==="invalid_element")X({issues:N.issues},[...J,...N.path]);else{let B=[...J,...N.path];if(B.length===0)Q._errors.push(W(N));else{let G=Q,D=0;while(D<B.length){let M=B[D];if(D!==B.length-1)G[M]=G[M]||{_errors:[]};else G[M]=G[M]||{_errors:[]},G[M]._errors.push(W(N));G=G[M],D++}}}};return X(H),Q}function VJ(H,W=(Q)=>Q.message){let Q={errors:[]},X=(Y,J=[])=>{var N,B;for(let G of Y.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((D)=>X({issues:D},[...J,...G.path]));else if(G.code==="invalid_key")X({issues:G.issues},[...J,...G.path]);else if(G.code==="invalid_element")X({issues:G.issues},[...J,...G.path]);else{let D=[...J,...G.path];if(D.length===0){Q.errors.push(W(G));continue}let M=Q,_=0;while(_<D.length){let F=D[_],A=_===D.length-1;if(typeof F==="string")M.properties??(M.properties={}),(N=M.properties)[F]??(N[F]={errors:[]}),M=M.properties[F];else M.items??(M.items=[]),(B=M.items)[F]??(B[F]={errors:[]}),M=M.items[F];if(A)M.errors.push(W(G));_++}}};return X(H),Q}function P2(H){let W=[],Q=H.map((X)=>typeof X==="object"?X.key:X);for(let X of Q)if(typeof X==="number")W.push(`[${X}]`);else if(typeof X==="symbol")W.push(`[${JSON.stringify(String(X))}]`);else if(/[^\w$]/.test(X))W.push(`[${JSON.stringify(X)}]`);else{if(W.length)W.push(".");W.push(X)}return W.join("")}function UJ(H){let W=[],Q=[...H.issues].sort((X,Y)=>(X.path??[]).length-(Y.path??[]).length);for(let X of Q)if(W.push(`✖ ${X.message}`),X.path?.length)W.push(` → at ${P2(X.path)}`);return W.join(`
2
- `)}var u8=(H)=>(W,Q,X,Y)=>{let J=X?{...X,async:!1}:{async:!1},N=W._zod.run({value:Q,issues:[]},J);if(N instanceof Promise)throw new $0;if(N.issues.length){let B=new(Y?.Err??H)(N.issues.map((G)=>uH(G,J,AH())));throw $4(B,Y?.callee),B}return N.value},C4=u8(oH),l8=(H)=>async(W,Q,X,Y)=>{let J=X?{...X,async:!0}:{async:!0},N=W._zod.run({value:Q,issues:[]},J);if(N instanceof Promise)N=await N;if(N.issues.length){let B=new(Y?.Err??H)(N.issues.map((G)=>uH(G,J,AH())));throw $4(B,Y?.callee),B}return N.value},S4=l8(oH),m8=(H)=>(W,Q,X)=>{let Y=X?{...X,async:!1}:{async:!1},J=W._zod.run({value:Q,issues:[]},Y);if(J instanceof Promise)throw new $0;return J.issues.length?{success:!1,error:new(H??hQ)(J.issues.map((N)=>uH(N,Y,AH())))}:{success:!0,data:J.value}},wJ=m8(oH),c8=(H)=>async(W,Q,X)=>{let Y=X?{...X,async:!0}:{async:!0},J=W._zod.run({value:Q,issues:[]},Y);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new H(J.issues.map((N)=>uH(N,Y,AH())))}:{success:!0,data:J.value}},zJ=c8(oH),k4=(H)=>(W,Q,X)=>{let Y=X?{...X,direction:"backward"}:{direction:"backward"};return u8(H)(W,Q,Y)},wq=k4(oH),g4=(H)=>(W,Q,X)=>{return u8(H)(W,Q,X)},zq=g4(oH),x4=(H)=>async(W,Q,X)=>{let Y=X?{...X,direction:"backward"}:{direction:"backward"};return l8(H)(W,Q,Y)},Zq=x4(oH),v4=(H)=>async(W,Q,X)=>{return l8(H)(W,Q,X)},Pq=v4(oH),y4=(H)=>(W,Q,X)=>{let Y=X?{...X,direction:"backward"}:{direction:"backward"};return m8(H)(W,Q,Y)},bq=y4(oH),h4=(H)=>(W,Q,X)=>{return m8(H)(W,Q,X)},Iq=h4(oH),f4=(H)=>async(W,Q,X)=>{let Y=X?{...X,direction:"backward"}:{direction:"backward"};return c8(H)(W,Q,Y)},Lq=f4(oH),u4=(H)=>async(W,Q,X)=>{return c8(H)(W,Q,X)},jq=u4(oH);var W0={};o0(W0,{xid:()=>IJ,uuid7:()=>Cq,uuid6:()=>Rq,uuid4:()=>$q,uuid:()=>tW,uppercase:()=>tJ,unicodeEmail:()=>b2,undefined:()=>nJ,ulid:()=>bJ,time:()=>lJ,string:()=>cJ,sha512_hex:()=>aq,sha512_base64url:()=>H_,sha512_base64:()=>eq,sha384_hex:()=>rq,sha384_base64url:()=>sq,sha384_base64:()=>tq,sha256_hex:()=>iq,sha256_base64url:()=>nq,sha256_base64:()=>oq,sha1_hex:()=>cq,sha1_base64url:()=>dq,sha1_base64:()=>pq,rfc5322Email:()=>kq,number:()=>lQ,null:()=>oJ,nanoid:()=>jJ,md5_hex:()=>uq,md5_base64url:()=>mq,md5_base64:()=>lq,mac:()=>gJ,lowercase:()=>rJ,ksuid:()=>LJ,ipv6:()=>kJ,ipv4:()=>SJ,integer:()=>dJ,idnEmail:()=>gq,httpProtocol:()=>hJ,html5Email:()=>Sq,hostname:()=>yq,hex:()=>fq,guid:()=>$J,extendedDuration:()=>Tq,emoji:()=>CJ,email:()=>RJ,e164:()=>fJ,duration:()=>TJ,domain:()=>hq,datetime:()=>mJ,date:()=>uJ,cuid2:()=>PJ,cuid:()=>ZJ,cidrv6:()=>vJ,cidrv4:()=>xJ,browserEmail:()=>xq,boolean:()=>iJ,bigint:()=>pJ,base64url:()=>l4,base64:()=>yJ});var ZJ=/^[cC][0-9a-z]{6,}$/,PJ=/^[0-9a-z]+$/,bJ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,IJ=/^[0-9a-vA-V]{20}$/,LJ=/^[A-Za-z0-9]{27}$/,jJ=/^[a-zA-Z0-9_-]{21}$/,TJ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Tq=/^[-+]?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)?)??$/,$J=/^([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})$/,tW=(H)=>{if(!H)return/^([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)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${H}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},$q=tW(4),Rq=tW(6),Cq=tW(7),RJ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Sq=/^[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])?)*$/,kq=/^(([^<>()\[\]\\.,;:\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,}))$/,b2=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,gq=b2,xq=/^[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])?)*$/,vq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function CJ(){return new RegExp(vq,"u")}var SJ=/^(?:(?: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])$/,kJ=/^(([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}|:))$/,gJ=(H)=>{let W=G0(H??":");return new RegExp(`^(?:[0-9A-F]{2}${W}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${W}){5}[0-9a-f]{2}$`)},xJ=/^((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])$/,vJ=/^(([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])$/,yJ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,l4=/^[A-Za-z0-9_-]*$/,yq=/^(?=.{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])?)*\.?$/,hq=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,hJ=/^https?$/,fJ=/^\+[1-9]\d{6,14}$/,I2="(?:(?:\\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])))",uJ=new RegExp(`^${I2}$`);function L2(H){return typeof H.precision==="number"?H.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":H.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${H.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function lJ(H){return new RegExp(`^${L2(H)}$`)}function mJ(H){let W=L2({precision:H.precision}),Q=["Z"];if(H.local)Q.push("");if(H.offset)Q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let X=`${W}(?:${Q.join("|")})`;return new RegExp(`^${I2}T(?:${X})$`)}var cJ=(H)=>{let W=H?`[\\s\\S]{${H?.minimum??0},${H?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${W}$`)},pJ=/^-?\d+n?$/,dJ=/^-?\d+$/,lQ=/^-?\d+(?:\.\d+)?$/,iJ=/^(?:true|false)$/i,oJ=/^null$/i;var nJ=/^undefined$/i;var rJ=/^[^A-Z]*$/,tJ=/^[^a-z]*$/,fq=/^[0-9a-fA-F]*$/;function mQ(H,W){return new RegExp(`^[A-Za-z0-9+/]{${H}}${W}$`)}function cQ(H){return new RegExp(`^[A-Za-z0-9_-]{${H}}$`)}var uq=/^[0-9a-fA-F]{32}$/,lq=mQ(22,"=="),mq=cQ(22),cq=/^[0-9a-fA-F]{40}$/,pq=mQ(27,"="),dq=cQ(27),iq=/^[0-9a-fA-F]{64}$/,oq=mQ(43,"="),nq=cQ(43),rq=/^[0-9a-fA-F]{96}$/,tq=mQ(64,""),sq=cQ(64),aq=/^[0-9a-fA-F]{128}$/,eq=mQ(86,"=="),H_=cQ(86);var GH=O("$ZodCheck",(H,W)=>{var Q;H._zod??(H._zod={}),H._zod.def=W,(Q=H._zod).onattach??(Q.onattach=[])}),T2={number:"number",bigint:"bigint",object:"date"},m4=O("$ZodCheckLessThan",(H,W)=>{GH.init(H,W);let Q=T2[typeof W.value];H._zod.onattach.push((X)=>{let Y=X._zod.bag,J=(W.inclusive?Y.maximum:Y.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(W.value<J)if(W.inclusive)Y.maximum=W.value;else Y.exclusiveMaximum=W.value}),H._zod.check=(X)=>{if(W.inclusive?X.value<=W.value:X.value<W.value)return;X.issues.push({origin:Q,code:"too_big",maximum:typeof W.value==="object"?W.value.getTime():W.value,input:X.value,inclusive:W.inclusive,inst:H,continue:!W.abort})}}),c4=O("$ZodCheckGreaterThan",(H,W)=>{GH.init(H,W);let Q=T2[typeof W.value];H._zod.onattach.push((X)=>{let Y=X._zod.bag,J=(W.inclusive?Y.minimum:Y.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(W.value>J)if(W.inclusive)Y.minimum=W.value;else Y.exclusiveMinimum=W.value}),H._zod.check=(X)=>{if(W.inclusive?X.value>=W.value:X.value>W.value)return;X.issues.push({origin:Q,code:"too_small",minimum:typeof W.value==="object"?W.value.getTime():W.value,input:X.value,inclusive:W.inclusive,inst:H,continue:!W.abort})}}),sJ=O("$ZodCheckMultipleOf",(H,W)=>{GH.init(H,W),H._zod.onattach.push((Q)=>{var X;(X=Q._zod.bag).multipleOf??(X.multipleOf=W.value)}),H._zod.check=(Q)=>{if(typeof Q.value!==typeof W.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof Q.value==="bigint"?Q.value%W.value===BigInt(0):KJ(Q.value,W.value)===0)return;Q.issues.push({origin:typeof Q.value,code:"not_multiple_of",divisor:W.value,input:Q.value,inst:H,continue:!W.abort})}}),aJ=O("$ZodCheckNumberFormat",(H,W)=>{GH.init(H,W),W.format=W.format||"float64";let Q=W.format?.includes("int"),X=Q?"int":"number",[Y,J]=FJ[W.format];H._zod.onattach.push((N)=>{let B=N._zod.bag;if(B.format=W.format,B.minimum=Y,B.maximum=J,Q)B.pattern=dJ}),H._zod.check=(N)=>{let B=N.value;if(Q){if(!Number.isInteger(B)){N.issues.push({expected:X,format:W.format,code:"invalid_type",continue:!1,input:B,inst:H});return}if(!Number.isSafeInteger(B)){if(B>0)N.issues.push({input:B,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:H,origin:X,inclusive:!0,continue:!W.abort});else N.issues.push({input:B,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:H,origin:X,inclusive:!0,continue:!W.abort});return}}if(B<Y)N.issues.push({origin:"number",input:B,code:"too_small",minimum:Y,inclusive:!0,inst:H,continue:!W.abort});if(B>J)N.issues.push({origin:"number",input:B,code:"too_big",maximum:J,inclusive:!0,inst:H,continue:!W.abort})}}),eJ=O("$ZodCheckBigIntFormat",(H,W)=>{GH.init(H,W);let[Q,X]=EJ[W.format];H._zod.onattach.push((Y)=>{let J=Y._zod.bag;J.format=W.format,J.minimum=Q,J.maximum=X}),H._zod.check=(Y)=>{let J=Y.value;if(J<Q)Y.issues.push({origin:"bigint",input:J,code:"too_small",minimum:Q,inclusive:!0,inst:H,continue:!W.abort});if(J>X)Y.issues.push({origin:"bigint",input:J,code:"too_big",maximum:X,inclusive:!0,inst:H,continue:!W.abort})}}),H3=O("$ZodCheckMaxSize",(H,W)=>{var Q;GH.init(H,W),(Q=H._zod.def).when??(Q.when=(X)=>{let Y=X.value;return!FW(Y)&&Y.size!==void 0}),H._zod.onattach.push((X)=>{let Y=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(W.maximum<Y)X._zod.bag.maximum=W.maximum}),H._zod.check=(X)=>{let Y=X.value;if(Y.size<=W.maximum)return;X.issues.push({origin:vQ(Y),code:"too_big",maximum:W.maximum,inclusive:!0,input:Y,inst:H,continue:!W.abort})}}),W3=O("$ZodCheckMinSize",(H,W)=>{var Q;GH.init(H,W),(Q=H._zod.def).when??(Q.when=(X)=>{let Y=X.value;return!FW(Y)&&Y.size!==void 0}),H._zod.onattach.push((X)=>{let Y=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(W.minimum>Y)X._zod.bag.minimum=W.minimum}),H._zod.check=(X)=>{let Y=X.value;if(Y.size>=W.minimum)return;X.issues.push({origin:vQ(Y),code:"too_small",minimum:W.minimum,inclusive:!0,input:Y,inst:H,continue:!W.abort})}}),Q3=O("$ZodCheckSizeEquals",(H,W)=>{var Q;GH.init(H,W),(Q=H._zod.def).when??(Q.when=(X)=>{let Y=X.value;return!FW(Y)&&Y.size!==void 0}),H._zod.onattach.push((X)=>{let Y=X._zod.bag;Y.minimum=W.size,Y.maximum=W.size,Y.size=W.size}),H._zod.check=(X)=>{let Y=X.value,J=Y.size;if(J===W.size)return;let N=J>W.size;X.issues.push({origin:vQ(Y),...N?{code:"too_big",maximum:W.size}:{code:"too_small",minimum:W.size},inclusive:!0,exact:!0,input:X.value,inst:H,continue:!W.abort})}}),X3=O("$ZodCheckMaxLength",(H,W)=>{var Q;GH.init(H,W),(Q=H._zod.def).when??(Q.when=(X)=>{let Y=X.value;return!FW(Y)&&Y.length!==void 0}),H._zod.onattach.push((X)=>{let Y=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(W.maximum<Y)X._zod.bag.maximum=W.maximum}),H._zod.check=(X)=>{let Y=X.value;if(Y.length<=W.maximum)return;let N=yQ(Y);X.issues.push({origin:N,code:"too_big",maximum:W.maximum,inclusive:!0,input:Y,inst:H,continue:!W.abort})}}),Y3=O("$ZodCheckMinLength",(H,W)=>{var Q;GH.init(H,W),(Q=H._zod.def).when??(Q.when=(X)=>{let Y=X.value;return!FW(Y)&&Y.length!==void 0}),H._zod.onattach.push((X)=>{let Y=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(W.minimum>Y)X._zod.bag.minimum=W.minimum}),H._zod.check=(X)=>{let Y=X.value;if(Y.length>=W.minimum)return;let N=yQ(Y);X.issues.push({origin:N,code:"too_small",minimum:W.minimum,inclusive:!0,input:Y,inst:H,continue:!W.abort})}}),J3=O("$ZodCheckLengthEquals",(H,W)=>{var Q;GH.init(H,W),(Q=H._zod.def).when??(Q.when=(X)=>{let Y=X.value;return!FW(Y)&&Y.length!==void 0}),H._zod.onattach.push((X)=>{let Y=X._zod.bag;Y.minimum=W.length,Y.maximum=W.length,Y.length=W.length}),H._zod.check=(X)=>{let Y=X.value,J=Y.length;if(J===W.length)return;let N=yQ(Y),B=J>W.length;X.issues.push({origin:N,...B?{code:"too_big",maximum:W.length}:{code:"too_small",minimum:W.length},inclusive:!0,exact:!0,input:X.value,inst:H,continue:!W.abort})}}),p8=O("$ZodCheckStringFormat",(H,W)=>{var Q,X;if(GH.init(H,W),H._zod.onattach.push((Y)=>{let J=Y._zod.bag;if(J.format=W.format,W.pattern)J.patterns??(J.patterns=new Set),J.patterns.add(W.pattern)}),W.pattern)(Q=H._zod).check??(Q.check=(Y)=>{if(W.pattern.lastIndex=0,W.pattern.test(Y.value))return;Y.issues.push({origin:"string",code:"invalid_format",format:W.format,input:Y.value,...W.pattern?{pattern:W.pattern.toString()}:{},inst:H,continue:!W.abort})});else(X=H._zod).check??(X.check=()=>{})}),N3=O("$ZodCheckRegex",(H,W)=>{p8.init(H,W),H._zod.check=(Q)=>{if(W.pattern.lastIndex=0,W.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:"regex",input:Q.value,pattern:W.pattern.toString(),inst:H,continue:!W.abort})}}),B3=O("$ZodCheckLowerCase",(H,W)=>{W.pattern??(W.pattern=rJ),p8.init(H,W)}),K3=O("$ZodCheckUpperCase",(H,W)=>{W.pattern??(W.pattern=tJ),p8.init(H,W)}),G3=O("$ZodCheckIncludes",(H,W)=>{GH.init(H,W);let Q=G0(W.includes),X=new RegExp(typeof W.position==="number"?`^.{${W.position}}${Q}`:Q);W.pattern=X,H._zod.onattach.push((Y)=>{let J=Y._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(X)}),H._zod.check=(Y)=>{if(Y.value.includes(W.includes,W.position))return;Y.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:W.includes,input:Y.value,inst:H,continue:!W.abort})}}),D3=O("$ZodCheckStartsWith",(H,W)=>{GH.init(H,W);let Q=new RegExp(`^${G0(W.prefix)}.*`);W.pattern??(W.pattern=Q),H._zod.onattach.push((X)=>{let Y=X._zod.bag;Y.patterns??(Y.patterns=new Set),Y.patterns.add(Q)}),H._zod.check=(X)=>{if(X.value.startsWith(W.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:W.prefix,input:X.value,inst:H,continue:!W.abort})}}),M3=O("$ZodCheckEndsWith",(H,W)=>{GH.init(H,W);let Q=new RegExp(`.*${G0(W.suffix)}$`);W.pattern??(W.pattern=Q),H._zod.onattach.push((X)=>{let Y=X._zod.bag;Y.patterns??(Y.patterns=new Set),Y.patterns.add(Q)}),H._zod.check=(X)=>{if(X.value.endsWith(W.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:W.suffix,input:X.value,inst:H,continue:!W.abort})}});function j2(H,W,Q){if(H.issues.length)W.issues.push(...iH(Q,H.issues))}var q3=O("$ZodCheckProperty",(H,W)=>{GH.init(H,W),H._zod.check=(Q)=>{let X=W.schema._zod.run({value:Q.value[W.property],issues:[]},{});if(X instanceof Promise)return X.then((Y)=>j2(Y,Q,W.property));j2(X,Q,W.property);return}}),_3=O("$ZodCheckMimeType",(H,W)=>{GH.init(H,W);let Q=new Set(W.mime);H._zod.onattach.push((X)=>{X._zod.bag.mime=W.mime}),H._zod.check=(X)=>{if(Q.has(X.value.type))return;X.issues.push({code:"invalid_value",values:W.mime,input:X.value.type,inst:H,continue:!W.abort})}}),F3=O("$ZodCheckOverwrite",(H,W)=>{GH.init(H,W),H._zod.check=(Q)=>{Q.value=W.tx(Q.value)}});class p4{constructor(H=[]){if(this.content=[],this.indent=0,this)this.args=H}indented(H){this.indent+=1,H(this),this.indent-=1}write(H){if(typeof H==="function"){H(this,{execution:"sync"}),H(this,{execution:"async"});return}let Q=H.split(`
3
- `).filter((J)=>J),X=Math.min(...Q.map((J)=>J.length-J.trimStart().length)),Y=Q.map((J)=>J.slice(X)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of Y)this.content.push(J)}compile(){let H=Function,W=this?.args,X=[...(this?.content??[""]).map((Y)=>` ${Y}`)];return new H(...W,X.join(`
4
- `))}}var E3={major:4,minor:4,patch:3};var a=O("$ZodType",(H,W)=>{var Q;H??(H={}),H._zod.def=W,H._zod.bag=H._zod.bag||{},H._zod.version=E3;let X=[...H._zod.def.checks??[]];if(H._zod.traits.has("$ZodCheck"))X.unshift(H);for(let Y of X)for(let J of Y._zod.onattach)J(H);if(X.length===0)(Q=H._zod).deferred??(Q.deferred=[]),H._zod.deferred?.push(()=>{H._zod.run=H._zod.parse});else{let Y=(N,B,G)=>{let D=OW(N),M;for(let _ of B){if(_._zod.def.when){if(AJ(N))continue;if(!_._zod.def.when(N))continue}else if(D)continue;let F=N.issues.length,A=_._zod.check(N);if(A instanceof Promise&&G?.async===!1)throw new $0;if(M||A instanceof Promise)M=(M??Promise.resolve()).then(async()=>{if(await A,N.issues.length===F)return;if(!D)D=OW(N,F)});else{if(N.issues.length===F)continue;if(!D)D=OW(N,F)}}if(M)return M.then(()=>{return N});return N},J=(N,B,G)=>{if(OW(N))return N.aborted=!0,N;let D=Y(B,X,G);if(D instanceof Promise){if(G.async===!1)throw new $0;return D.then((M)=>H._zod.parse(M,G))}return H._zod.parse(D,G)};H._zod.run=(N,B)=>{if(B.skipChecks)return H._zod.parse(N,B);if(B.direction==="backward"){let D=H._zod.parse({value:N.value,issues:[]},{...B,skipChecks:!0});if(D instanceof Promise)return D.then((M)=>{return J(M,N,B)});return J(D,N,B)}let G=H._zod.parse(N,B);if(G instanceof Promise){if(B.async===!1)throw new $0;return G.then((D)=>Y(D,X,B))}return Y(G,X,B)}}QH(H,"~standard",()=>({validate:(Y)=>{try{let J=wJ(H,Y);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return zJ(H,Y).then((N)=>N.success?{value:N.data}:{issues:N.error?.issues})}},vendor:"zod",version:1}))}),sW=O("$ZodString",(H,W)=>{a.init(H,W),H._zod.pattern=[...H?._zod.bag?.patterns??[]].pop()??cJ(H._zod.bag),H._zod.parse=(Q,X)=>{if(W.coerce)try{Q.value=String(Q.value)}catch(Y){}if(typeof Q.value==="string")return Q;return Q.issues.push({expected:"string",code:"invalid_type",input:Q.value,inst:H}),Q}}),BH=O("$ZodStringFormat",(H,W)=>{p8.init(H,W),sW.init(H,W)}),O3=O("$ZodGUID",(H,W)=>{W.pattern??(W.pattern=$J),BH.init(H,W)}),V3=O("$ZodUUID",(H,W)=>{if(W.version){let X={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[W.version];if(X===void 0)throw Error(`Invalid UUID version: "${W.version}"`);W.pattern??(W.pattern=tW(X))}else W.pattern??(W.pattern=tW());BH.init(H,W)}),U3=O("$ZodEmail",(H,W)=>{W.pattern??(W.pattern=RJ),BH.init(H,W)}),w3=O("$ZodURL",(H,W)=>{BH.init(H,W),H._zod.check=(Q)=>{try{let X=Q.value.trim();if(!W.normalize&&W.protocol?.source===hJ.source){if(!/^https?:\/\//i.test(X)){Q.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:Q.value,inst:H,continue:!W.abort});return}}let Y=new URL(X);if(W.hostname){if(W.hostname.lastIndex=0,!W.hostname.test(Y.hostname))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:W.hostname.source,input:Q.value,inst:H,continue:!W.abort})}if(W.protocol){if(W.protocol.lastIndex=0,!W.protocol.test(Y.protocol.endsWith(":")?Y.protocol.slice(0,-1):Y.protocol))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:W.protocol.source,input:Q.value,inst:H,continue:!W.abort})}if(W.normalize)Q.value=Y.href;else Q.value=X;return}catch(X){Q.issues.push({code:"invalid_format",format:"url",input:Q.value,inst:H,continue:!W.abort})}}}),z3=O("$ZodEmoji",(H,W)=>{W.pattern??(W.pattern=CJ()),BH.init(H,W)}),Z3=O("$ZodNanoID",(H,W)=>{W.pattern??(W.pattern=jJ),BH.init(H,W)}),P3=O("$ZodCUID",(H,W)=>{W.pattern??(W.pattern=ZJ),BH.init(H,W)}),b3=O("$ZodCUID2",(H,W)=>{W.pattern??(W.pattern=PJ),BH.init(H,W)}),I3=O("$ZodULID",(H,W)=>{W.pattern??(W.pattern=bJ),BH.init(H,W)}),L3=O("$ZodXID",(H,W)=>{W.pattern??(W.pattern=IJ),BH.init(H,W)}),j3=O("$ZodKSUID",(H,W)=>{W.pattern??(W.pattern=LJ),BH.init(H,W)}),T3=O("$ZodISODateTime",(H,W)=>{W.pattern??(W.pattern=mJ(W)),BH.init(H,W)}),$3=O("$ZodISODate",(H,W)=>{W.pattern??(W.pattern=uJ),BH.init(H,W)}),R3=O("$ZodISOTime",(H,W)=>{W.pattern??(W.pattern=lJ(W)),BH.init(H,W)}),C3=O("$ZodISODuration",(H,W)=>{W.pattern??(W.pattern=TJ),BH.init(H,W)}),S3=O("$ZodIPv4",(H,W)=>{W.pattern??(W.pattern=SJ),BH.init(H,W),H._zod.bag.format="ipv4"}),k3=O("$ZodIPv6",(H,W)=>{W.pattern??(W.pattern=kJ),BH.init(H,W),H._zod.bag.format="ipv6",H._zod.check=(Q)=>{try{new URL(`http://[${Q.value}]`)}catch{Q.issues.push({code:"invalid_format",format:"ipv6",input:Q.value,inst:H,continue:!W.abort})}}}),g3=O("$ZodMAC",(H,W)=>{W.pattern??(W.pattern=gJ(W.delimiter)),BH.init(H,W),H._zod.bag.format="mac"}),x3=O("$ZodCIDRv4",(H,W)=>{W.pattern??(W.pattern=xJ),BH.init(H,W)}),v3=O("$ZodCIDRv6",(H,W)=>{W.pattern??(W.pattern=vJ),BH.init(H,W),H._zod.check=(Q)=>{let X=Q.value.split("/");try{if(X.length!==2)throw Error();let[Y,J]=X;if(!J)throw Error();let N=Number(J);if(`${N}`!==J)throw Error();if(N<0||N>128)throw Error();new URL(`http://[${Y}]`)}catch{Q.issues.push({code:"invalid_format",format:"cidrv6",input:Q.value,inst:H,continue:!W.abort})}}});function y3(H){if(H==="")return!0;if(/\s/.test(H))return!1;if(H.length%4!==0)return!1;try{return atob(H),!0}catch{return!1}}var h3=O("$ZodBase64",(H,W)=>{W.pattern??(W.pattern=yJ),BH.init(H,W),H._zod.bag.contentEncoding="base64",H._zod.check=(Q)=>{if(y3(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64",input:Q.value,inst:H,continue:!W.abort})}});function p2(H){if(!l4.test(H))return!1;let W=H.replace(/[-_]/g,(X)=>X==="-"?"+":"/"),Q=W.padEnd(Math.ceil(W.length/4)*4,"=");return y3(Q)}var f3=O("$ZodBase64URL",(H,W)=>{W.pattern??(W.pattern=l4),BH.init(H,W),H._zod.bag.contentEncoding="base64url",H._zod.check=(Q)=>{if(p2(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64url",input:Q.value,inst:H,continue:!W.abort})}}),u3=O("$ZodE164",(H,W)=>{W.pattern??(W.pattern=fJ),BH.init(H,W)});function d2(H,W=null){try{let Q=H.split(".");if(Q.length!==3)return!1;let[X]=Q;if(!X)return!1;let Y=JSON.parse(atob(X));if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(W&&(!("alg"in Y)||Y.alg!==W))return!1;return!0}catch{return!1}}var l3=O("$ZodJWT",(H,W)=>{BH.init(H,W),H._zod.check=(Q)=>{if(d2(Q.value,W.alg))return;Q.issues.push({code:"invalid_format",format:"jwt",input:Q.value,inst:H,continue:!W.abort})}}),m3=O("$ZodCustomStringFormat",(H,W)=>{BH.init(H,W),H._zod.check=(Q)=>{if(W.fn(Q.value))return;Q.issues.push({code:"invalid_format",format:W.format,input:Q.value,inst:H,continue:!W.abort})}}),r4=O("$ZodNumber",(H,W)=>{a.init(H,W),H._zod.pattern=H._zod.bag.pattern??lQ,H._zod.parse=(Q,X)=>{if(W.coerce)try{Q.value=Number(Q.value)}catch(N){}let Y=Q.value;if(typeof Y==="number"&&!Number.isNaN(Y)&&Number.isFinite(Y))return Q;let J=typeof Y==="number"?Number.isNaN(Y)?"NaN":!Number.isFinite(Y)?"Infinity":void 0:void 0;return Q.issues.push({expected:"number",code:"invalid_type",input:Y,inst:H,...J?{received:J}:{}}),Q}}),c3=O("$ZodNumberFormat",(H,W)=>{aJ.init(H,W),r4.init(H,W)}),pQ=O("$ZodBoolean",(H,W)=>{a.init(H,W),H._zod.pattern=iJ,H._zod.parse=(Q,X)=>{if(W.coerce)try{Q.value=Boolean(Q.value)}catch(J){}let Y=Q.value;if(typeof Y==="boolean")return Q;return Q.issues.push({expected:"boolean",code:"invalid_type",input:Y,inst:H}),Q}}),t4=O("$ZodBigInt",(H,W)=>{a.init(H,W),H._zod.pattern=pJ,H._zod.parse=(Q,X)=>{if(W.coerce)try{Q.value=BigInt(Q.value)}catch(Y){}if(typeof Q.value==="bigint")return Q;return Q.issues.push({expected:"bigint",code:"invalid_type",input:Q.value,inst:H}),Q}}),p3=O("$ZodBigIntFormat",(H,W)=>{eJ.init(H,W),t4.init(H,W)}),d3=O("$ZodSymbol",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{let Y=Q.value;if(typeof Y==="symbol")return Q;return Q.issues.push({expected:"symbol",code:"invalid_type",input:Y,inst:H}),Q}}),i3=O("$ZodUndefined",(H,W)=>{a.init(H,W),H._zod.pattern=nJ,H._zod.values=new Set([void 0]),H._zod.parse=(Q,X)=>{let Y=Q.value;if(typeof Y>"u")return Q;return Q.issues.push({expected:"undefined",code:"invalid_type",input:Y,inst:H}),Q}}),o3=O("$ZodNull",(H,W)=>{a.init(H,W),H._zod.pattern=oJ,H._zod.values=new Set([null]),H._zod.parse=(Q,X)=>{let Y=Q.value;if(Y===null)return Q;return Q.issues.push({expected:"null",code:"invalid_type",input:Y,inst:H}),Q}}),n3=O("$ZodAny",(H,W)=>{a.init(H,W),H._zod.parse=(Q)=>Q}),r3=O("$ZodUnknown",(H,W)=>{a.init(H,W),H._zod.parse=(Q)=>Q}),t3=O("$ZodNever",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{return Q.issues.push({expected:"never",code:"invalid_type",input:Q.value,inst:H}),Q}}),s3=O("$ZodVoid",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{let Y=Q.value;if(typeof Y>"u")return Q;return Q.issues.push({expected:"void",code:"invalid_type",input:Y,inst:H}),Q}}),a3=O("$ZodDate",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{if(W.coerce)try{Q.value=new Date(Q.value)}catch(B){}let Y=Q.value,J=Y instanceof Date;if(J&&!Number.isNaN(Y.getTime()))return Q;return Q.issues.push({expected:"date",code:"invalid_type",input:Y,...J?{received:"Invalid Date"}:{},inst:H}),Q}});function R2(H,W,Q){if(H.issues.length)W.issues.push(...iH(Q,H.issues));W.value[Q]=H.value}var e3=O("$ZodArray",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{let Y=Q.value;if(!Array.isArray(Y))return Q.issues.push({expected:"array",code:"invalid_type",input:Y,inst:H}),Q;Q.value=Array(Y.length);let J=[];for(let N=0;N<Y.length;N++){let B=Y[N],G=W.element._zod.run({value:B,issues:[]},X);if(G instanceof Promise)J.push(G.then((D)=>R2(D,Q,N)));else R2(G,Q,N)}if(J.length)return Promise.all(J).then(()=>Q);return Q}});function n4(H,W,Q,X,Y,J){let N=Q in X;if(H.issues.length){if(Y&&J&&!N)return;W.issues.push(...iH(Q,H.issues))}if(!N&&!Y){if(!H.issues.length)W.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[Q]});return}if(H.value===void 0){if(N)W.value[Q]=void 0}else W.value[Q]=H.value}function i2(H){let W=Object.keys(H.shape);for(let X of W)if(!H.shape?.[X]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${X}": expected a Zod schema`);let Q=_J(H.shape);return{...H,keys:W,keySet:new Set(W),numKeys:W.length,optionalKeys:new Set(Q)}}function o2(H,W,Q,X,Y,J){let N=[],B=Y.keySet,G=Y.catchall._zod,D=G.def.type,M=G.optin==="optional",_=G.optout==="optional";for(let F in W){if(F==="__proto__")continue;if(B.has(F))continue;if(D==="never"){N.push(F);continue}let A=G.run({value:W[F],issues:[]},X);if(A instanceof Promise)H.push(A.then((w)=>n4(w,Q,F,W,M,_)));else n4(A,Q,F,W,M,_)}if(N.length)Q.issues.push({code:"unrecognized_keys",keys:N,input:W,inst:J});if(!H.length)return Q;return Promise.all(H).then(()=>{return Q})}var n2=O("$ZodObject",(H,W)=>{if(a.init(H,W),!Object.getOwnPropertyDescriptor(W,"shape")?.get){let B=W.shape;Object.defineProperty(W,"shape",{get:()=>{let G={...B};return Object.defineProperty(W,"shape",{value:G}),G}})}let X=h8(()=>i2(W));QH(H._zod,"propValues",()=>{let B=W.shape,G={};for(let D in B){let M=B[D]._zod;if(M.values){G[D]??(G[D]=new Set);for(let _ of M.values)G[D].add(_)}}return G});let Y=rW,J=W.catchall,N;H._zod.parse=(B,G)=>{N??(N=X.value);let D=B.value;if(!Y(D))return B.issues.push({expected:"object",code:"invalid_type",input:D,inst:H}),B;B.value={};let M=[],_=N.shape;for(let F of N.keys){let A=_[F],w=A._zod.optin==="optional",z=A._zod.optout==="optional",Z=A._zod.run({value:D[F],issues:[]},G);if(Z instanceof Promise)M.push(Z.then((u)=>n4(u,B,F,D,w,z)));else n4(Z,B,F,D,w,z)}if(!J)return M.length?Promise.all(M).then(()=>B):B;return o2(M,D,B,G,X.value,H)}}),HN=O("$ZodObjectJIT",(H,W)=>{n2.init(H,W);let Q=H._zod.parse,X=h8(()=>i2(W)),Y=(F)=>{let A=new p4(["shape","payload","ctx"]),w=X.value,z=(j)=>{let m=T4(j);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};A.write("const input = payload.value;");let Z=Object.create(null),u=0;for(let j of w.keys)Z[j]=`key_${u++}`;A.write("const newResult = {};");for(let j of w.keys){let m=Z[j],I=T4(j),P=F[j],c=P?._zod?.optin==="optional",XH=P?._zod?.optout==="optional";if(A.write(`const ${m} = ${z(j)};`),c&&XH)A.write(`
5
- if (${m}.issues.length) {
6
- if (${I} in input) {
7
- payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
1
+ var{create:qS,defineProperty:pa,getOwnPropertyDescriptor:AS,getOwnPropertyNames:MS,getPrototypeOf:jS}=Object,LS=Object.prototype.hasOwnProperty,rd=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),od=(e,t)=>{let r={};for(var o in e)pa(r,o,{get:e[o],enumerable:!0});if(t)pa(r,Symbol.toStringTag,{value:"Module"});return r},US=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var n=MS(t),s=0,i=n.length,a;s<i;s++)if(a=n[s],!LS.call(e,a)&&a!==r)pa(e,a,{get:((l)=>t[l]).bind(null,a),enumerable:!(o=AS(t,a))||o.enumerable})}return e},nd=(e,t,r)=>(r=e!=null?qS(jS(e)):{},US(t||!e||!e.__esModule?pa(r,"default",{value:e,enumerable:!0}):r,e));var ZS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),sd=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),DS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),FS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function id(e){return typeof e==="string"&&sd.has(e.replace(/#$/,""))}function ad(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(ZS.has(r))return"2020-12";if(sd.has(r))return"2019-09";if(DS.has(r)||FS.has(r))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var cd,Ac=Object.freeze({status:"aborted"});function _(e,t,r){function o(a,l){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=i.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){let f=d[m];if(!(f in a))a[f]=u[f].bind(a)}}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:e});function i(a){var l;let u=r?.Parent?new s:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:o}),Object.defineProperty(i,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(i,"name",{value:e}),i}var HS=Symbol("zod_brand");class kt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class On extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(cd=globalThis).__zod_globalConfig??(cd.__zod_globalConfig={});var io=globalThis.__zod_globalConfig;function je(e){if(e)Object.assign(io,e);return io}function ma(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function jc(e,t="|"){return e.map((r)=>Dc(r)).join(t)}function Nn(e,t){if(typeof t==="bigint")return t.toString();return t}function qn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function fa(e){return e===null||e===void 0}function ga(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ud(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var ld=Symbol("evaluating");function Q(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===ld)return;if(o===void 0)o=ld,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function yr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Lc(e){return JSON.stringify(e)}function dd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Uc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ao(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var pd=qn(()=>{if(io.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function vr(e){if(ao(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(ao(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Zc(e){if(vr(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var hd=new Set(["string","number","symbol"]);function Kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function M(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Dc(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function md(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var fd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function VS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;i[a]=r.shape[a]}return yr(this,"shape",i),i},checks:[]});return rt(e,s)}function JS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete i[a]}return yr(this,"shape",i),i},checks:[]});return rt(e,s)}function BS(e,t){if(!vr(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Wt(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return yr(this,"shape",s),s}});return rt(e,n)}function WS(e,t){if(!vr(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return yr(this,"shape",o),o}});return rt(e,r)}function KS(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return yr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return rt(e,r)}function GS(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=Wt(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(r)for(let u in r){if(!(u in a))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;l[u]=e?new e({type:"optional",innerType:a[u]}):a[u]}else for(let u in a)l[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return yr(this,"shape",l),l},checks:[]});return rt(t,i)}function YS(e,t,r){let o=Wt(t._zod.def,{get shape(){let n=t._zod.def.shape,s={...n};if(r)for(let i in r){if(!(i in s))throw Error(`Unrecognized key: "${i}"`);if(!r[i])continue;s[i]=new e({type:"nonoptional",innerType:n[i]})}else for(let i in n)s[i]=new e({type:"nonoptional",innerType:n[i]});return yr(this,"shape",s),s}});return rt(t,o)}function zr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function gd(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Gt(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function ha(e){return typeof e==="string"?e:e?.message}function ot(e,t,r){let o=e.message?e.message:ha(e.inst?._zod.def?.error?.(e))??ha(t?.error?.(e))??ha(r.customError?.(e))??ha(r.localeError?.(e))??"Invalid input",{inst:n,continue:s,input:i,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=i;return a}function Sa(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Sd(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function wr(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}var _d=(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,Nn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_a=_("$ZodError",_d),Fc=_("$ZodError",_d,{Parent:Error});function Hc(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function Vc(e,t=(r)=>r.message){let r={_errors:[]},o=(n,s=[])=>{for(let i of n.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>o({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")o({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")o({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(t(i));else{let l=r,u=0;while(u<a.length){let d=a[u];if(u!==a.length-1)l[d]=l[d]||{_errors:[]};else l[d]=l[d]||{_errors:[]},l[d]._errors.push(t(i));l=l[d],u++}}}};return o(e),r}var ba=(e)=>(t,r,o,n)=>{let s=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new kt;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map((l)=>ot(l,s,je())));throw Uc(a,n?.callee),a}return i.value};var ya=(e)=>async(t,r,o,n)=>{let s=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)i=await i;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map((l)=>ot(l,s,je())));throw Uc(a,n?.callee),a}return i.value};var An=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new kt;return s.issues.length?{success:!1,error:new(e??_a)(s.issues.map((i)=>ot(i,n,je())))}:{success:!0,data:s.value}},bd=An(Fc),Mn=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((i)=>ot(i,n,je())))}:{success:!0,data:s.value}},yd=Mn(Fc),vd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ba(e)(t,r,n)};var zd=(e)=>(t,r,o)=>ba(e)(t,r,o);var wd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ya(e)(t,r,n)};var Rd=(e)=>async(t,r,o)=>ya(e)(t,r,o);var xd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return An(e)(t,r,n)};var Pd=(e)=>(t,r,o)=>An(e)(t,r,o);var Td=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Mn(e)(t,r,n)};var Ed=(e)=>async(t,r,o)=>Mn(e)(t,r,o);var kd=/^[cC][0-9a-z]{6,}$/,$d=/^[0-9a-z]+$/,Cd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Id=/^[0-9a-vA-V]{20}$/,Od=/^[A-Za-z0-9]{27}$/,Nd=/^[a-zA-Z0-9_-]{21}$/,qd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ad=/^([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})$/,Jc=(e)=>{if(!e)return/^([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)$/;return 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})$`)};var Md=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var QS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jd(){return new RegExp(QS,"u")}var Ld=/^(?:(?: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])$/,Ud=/^(([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}|:))$/;var Zd=/^((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])$/,Dd=/^(([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])$/,Fd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Bc=/^[A-Za-z0-9_-]*$/;var Hd=/^https?$/,Vd=/^\+[1-9]\d{6,14}$/,Jd="(?:(?:\\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])))",Bd=new RegExp(`^${Jd}$`);function Wd(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Kd(e){return new RegExp(`^${Wd(e)}$`)}function Gd(e){let t=Wd({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${Jd}T(?:${o})$`)}var Yd=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Xd=/^-?\d+$/,Wc=/^-?\d+(?:\.\d+)?$/,Qd=/^(?:true|false)$/i,ep=/^null$/i;var tp=/^undefined$/i;var rp=/^[^A-Z]*$/,op=/^[^a-z]*$/;var ze=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),np={number:"number",bigint:"bigint",object:"date"},Kc=_("$ZodCheckLessThan",(e,t)=>{ze.init(e,t);let r=np[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Gc=_("$ZodCheckGreaterThan",(e,t)=>{ze.init(e,t);let r=np[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sp=_("$ZodCheckMultipleOf",(e,t)=>{ze.init(e,t),e._zod.onattach.push((r)=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):ud(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ip=_("$ZodCheckNumberFormat",(e,t)=>{ze.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,s]=fd[t.format];e._zod.onattach.push((i)=>{let a=i._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=s,r)a.pattern=Xd}),e._zod.check=(i)=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(a<n)i.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(a>s)i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var ap=_("$ZodCheckMaxLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!fa(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.length<=t.maximum)return;let i=Sa(n);o.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),cp=_("$ZodCheckMinLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!fa(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.length>=t.minimum)return;let i=Sa(n);o.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),lp=_("$ZodCheckLengthEquals",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!fa(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(o)=>{let n=o.value,s=n.length;if(s===t.length)return;let i=Sa(n),a=s>t.length;o.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Ln=_("$ZodCheckStringFormat",(e,t)=>{var r,o;if(ze.init(e,t),e._zod.onattach.push((n)=>{let s=n._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;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})});else(o=e._zod).check??(o.check=()=>{})}),up=_("$ZodCheckRegex",(e,t)=>{Ln.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),dp=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=rp),Ln.init(e,t)}),pp=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=op),Ln.init(e,t)}),hp=_("$ZodCheckIncludes",(e,t)=>{ze.init(e,t);let r=Kt(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),mp=_("$ZodCheckStartsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`^${Kt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),fp=_("$ZodCheckEndsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`.*${Kt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var gp=_("$ZodCheckOverwrite",(e,t)=>{ze.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class Yc{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
2
+ `).filter((s)=>s),o=Math.min(...r.map((s)=>s.length-s.trimStart().length)),n=r.map((s)=>s.slice(o)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of n)this.content.push(s)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((n)=>` ${n}`)];return new e(...t,o.join(`
3
+ `))}}var _p={major:4,minor:4,patch:3};var re=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=_p;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let s of n._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(i,a,l)=>{let u=zr(i),d;for(let m of a){if(m._zod.def.when){if(gd(i))continue;if(!m._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,S=m._zod.check(i);if(S instanceof Promise&&l?.async===!1)throw new kt;if(d||S instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await S,i.issues.length===f)return;if(!u)u=zr(i,f)});else{if(i.issues.length===f)continue;if(!u)u=zr(i,f)}}if(d)return d.then(()=>i);return i},s=(i,a,l)=>{if(zr(i))return i.aborted=!0,i;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new kt;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>s(d,i,a));return s(u,i,a)}let l=e._zod.parse(i,a);if(l instanceof Promise){if(a.async===!1)throw new kt;return l.then((u)=>n(u,o,a))}return n(l,o,a)}}Q(e,"~standard",()=>({validate:(n)=>{try{let s=bd(e,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return yd(e,n).then((i)=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),wa=_("$ZodString",(e,t)=>{re.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Yd(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ie=_("$ZodStringFormat",(e,t)=>{Ln.init(e,t),wa.init(e,t)}),Tp=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ad),ie.init(e,t)}),Ep=_("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Jc(o))}else t.pattern??(t.pattern=Jc());ie.init(e,t)}),kp=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Md),ie.init(e,t)}),$p=_("$ZodURL",(e,t)=>{ie.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===Hd.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Cp=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=jd()),ie.init(e,t)}),Ip=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Nd),ie.init(e,t)}),Op=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=kd),ie.init(e,t)}),Np=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=$d),ie.init(e,t)}),qp=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Cd),ie.init(e,t)}),Ap=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Id),ie.init(e,t)}),Mp=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Od),ie.init(e,t)}),jp=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Gd(t)),ie.init(e,t)}),Lp=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Bd),ie.init(e,t)}),Up=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Kd(t)),ie.init(e,t)}),Zp=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=qd),ie.init(e,t)}),Dp=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ld),ie.init(e,t),e._zod.bag.format="ipv4"}),Fp=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ud),ie.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Hp=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Zd),ie.init(e,t)}),Vp=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Dd),ie.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,s]=o;if(!s)throw Error();let i=Number(s);if(`${i}`!==s)throw Error();if(i<0||i>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Jp(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Bp=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Fd),ie.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(Jp(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function e_(e){if(!Bc.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Jp(r)}var Wp=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Bc),ie.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(e_(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Kp=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Vd),ie.init(e,t)});function t_(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var Gp=_("$ZodJWT",(e,t)=>{ie.init(e,t),e._zod.check=(r)=>{if(t_(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Qc=_("$ZodNumber",(e,t)=>{re.init(e,t),e._zod.pattern=e._zod.bag.pattern??Wc,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let s=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...s?{received:s}:{}}),r}}),Yp=_("$ZodNumberFormat",(e,t)=>{ip.init(e,t),Qc.init(e,t)}),Xp=_("$ZodBoolean",(e,t)=>{re.init(e,t),e._zod.pattern=Qd,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}});var Qp=_("$ZodUndefined",(e,t)=>{re.init(e,t),e._zod.pattern=tp,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),eh=_("$ZodNull",(e,t)=>{re.init(e,t),e._zod.pattern=ep,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),th=_("$ZodAny",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),rh=_("$ZodUnknown",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),oh=_("$ZodNever",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function bp(e,t,r){if(e.issues.length)t.issues.push(...Gt(r,e.issues));t.value[r]=e.value}var nh=_("$ZodArray",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let s=[];for(let i=0;i<n.length;i++){let a=n[i],l=t.element._zod.run({value:a,issues:[]},o);if(l instanceof Promise)s.push(l.then((u)=>bp(u,r,i)));else bp(l,r,i)}if(s.length)return Promise.all(s).then(()=>r);return r}});function za(e,t,r,o,n,s){let i=r in o;if(e.issues.length){if(n&&s&&!i)return;t.issues.push(...Gt(r,e.issues))}if(!i&&!n){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(i)t.value[r]=void 0}else t.value[r]=e.value}function sh(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=md(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ih(e,t,r,o,n,s){let i=[],a=n.keySet,l=n.catchall._zod,u=l.def.type,d=l.optin==="optional",m=l.optout==="optional";for(let f in t){if(f==="__proto__")continue;if(a.has(f))continue;if(u==="never"){i.push(f);continue}let S=l.run({value:t[f],issues:[]},o);if(S instanceof Promise)e.push(S.then((b)=>za(b,r,f,t,d,m)));else za(S,r,f,t,d,m)}if(i.length)r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s});if(!e.length)return r;return Promise.all(e).then(()=>r)}var r_=_("$ZodObject",(e,t)=>{if(re.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=qn(()=>sh(t));Q(e._zod,"propValues",()=>{let a=t.shape,l={};for(let u in a){let d=a[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let m of d.values)l[u].add(m)}}return l});let n=ao,s=t.catchall,i;e._zod.parse=(a,l)=>{i??(i=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],m=i.shape;for(let f of i.keys){let S=m[f],b=S._zod.optin==="optional",y=S._zod.optout==="optional",v=S._zod.run({value:u[f],issues:[]},l);if(v instanceof Promise)d.push(v.then((L)=>za(L,a,f,u,b,y)));else za(v,a,f,u,b,y)}if(!s)return d.length?Promise.all(d).then(()=>a):a;return ih(d,u,a,l,o.value,e)}}),ah=_("$ZodObjectJIT",(e,t)=>{r_.init(e,t);let r=e._zod.parse,o=qn(()=>sh(t)),n=(f)=>{let S=new Yc(["shape","payload","ctx"]),b=o.value,y=(x)=>{let U=Lc(x);return`shape[${U}]._zod.run({ value: input[${U}], issues: [] }, ctx)`};S.write("const input = payload.value;");let v=Object.create(null),L=0;for(let x of b.keys)v[x]=`key_${L++}`;S.write("const newResult = {};");for(let x of b.keys){let U=v[x],R=Lc(x),w=f[x],Z=w?._zod?.optin==="optional",X=w?._zod?.optout==="optional";if(S.write(`const ${U} = ${y(x)};`),Z&&X)S.write(`
4
+ if (${U}.issues.length) {
5
+ if (${R} in input) {
6
+ payload.issues = payload.issues.concat(${U}.issues.map(iss => ({
8
7
  ...iss,
9
- path: iss.path ? [${I}, ...iss.path] : [${I}]
8
+ path: iss.path ? [${R}, ...iss.path] : [${R}]
10
9
  })));
11
10
  }
12
11
  }
13
12
 
14
- if (${m}.value === undefined) {
15
- if (${I} in input) {
16
- newResult[${I}] = undefined;
13
+ if (${U}.value === undefined) {
14
+ if (${R} in input) {
15
+ newResult[${R}] = undefined;
17
16
  }
18
17
  } else {
19
- newResult[${I}] = ${m}.value;
18
+ newResult[${R}] = ${U}.value;
20
19
  }
21
20
 
22
- `);else if(!c)A.write(`
23
- const ${m}_present = ${I} in input;
24
- if (${m}.issues.length) {
25
- payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
21
+ `);else if(!Z)S.write(`
22
+ const ${U}_present = ${R} in input;
23
+ if (${U}.issues.length) {
24
+ payload.issues = payload.issues.concat(${U}.issues.map(iss => ({
26
25
  ...iss,
27
- path: iss.path ? [${I}, ...iss.path] : [${I}]
26
+ path: iss.path ? [${R}, ...iss.path] : [${R}]
28
27
  })));
29
28
  }
30
- if (!${m}_present && !${m}.issues.length) {
29
+ if (!${U}_present && !${U}.issues.length) {
31
30
  payload.issues.push({
32
31
  code: "invalid_type",
33
32
  expected: "nonoptional",
34
33
  input: undefined,
35
- path: [${I}]
34
+ path: [${R}]
36
35
  });
37
36
  }
38
37
 
39
- if (${m}_present) {
40
- if (${m}.value === undefined) {
41
- newResult[${I}] = undefined;
38
+ if (${U}_present) {
39
+ if (${U}.value === undefined) {
40
+ newResult[${R}] = undefined;
42
41
  } else {
43
- newResult[${I}] = ${m}.value;
42
+ newResult[${R}] = ${U}.value;
44
43
  }
45
44
  }
46
45
 
47
- `);else A.write(`
48
- if (${m}.issues.length) {
49
- payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
46
+ `);else S.write(`
47
+ if (${U}.issues.length) {
48
+ payload.issues = payload.issues.concat(${U}.issues.map(iss => ({
50
49
  ...iss,
51
- path: iss.path ? [${I}, ...iss.path] : [${I}]
50
+ path: iss.path ? [${R}, ...iss.path] : [${R}]
52
51
  })));
53
52
  }
54
53
 
55
- if (${m}.value === undefined) {
56
- if (${I} in input) {
57
- newResult[${I}] = undefined;
54
+ if (${U}.value === undefined) {
55
+ if (${R} in input) {
56
+ newResult[${R}] = undefined;
58
57
  }
59
58
  } else {
60
- newResult[${I}] = ${m}.value;
59
+ newResult[${R}] = ${U}.value;
61
60
  }
62
61
 
63
- `)}A.write("payload.value = newResult;"),A.write("return payload;");let p=A.compile();return(j,m)=>p(F,j,m)},J,N=rW,B=!oW.jitless,D=B&&DJ.value,M=W.catchall,_;H._zod.parse=(F,A)=>{_??(_=X.value);let w=F.value;if(!N(w))return F.issues.push({expected:"object",code:"invalid_type",input:w,inst:H}),F;if(B&&D&&A?.async===!1&&A.jitless!==!0){if(!J)J=Y(W.shape);if(F=J(F,A),!M)return F;return o2([],w,F,A,_,H)}return Q(F,A)}});function C2(H,W,Q,X){for(let J of H)if(J.issues.length===0)return W.value=J.value,W;let Y=H.filter((J)=>!OW(J));if(Y.length===1)return W.value=Y[0].value,Y[0];return W.issues.push({code:"invalid_union",input:W.value,inst:Q,errors:H.map((J)=>J.issues.map((N)=>uH(N,X,AH())))}),W}var dQ=O("$ZodUnion",(H,W)=>{a.init(H,W),QH(H._zod,"optin",()=>W.options.some((X)=>X._zod.optin==="optional")?"optional":void 0),QH(H._zod,"optout",()=>W.options.some((X)=>X._zod.optout==="optional")?"optional":void 0),QH(H._zod,"values",()=>{if(W.options.every((X)=>X._zod.values))return new Set(W.options.flatMap((X)=>Array.from(X._zod.values)));return}),QH(H._zod,"pattern",()=>{if(W.options.every((X)=>X._zod.pattern)){let X=W.options.map((Y)=>Y._zod.pattern);return new RegExp(`^(${X.map((Y)=>gQ(Y.source)).join("|")})$`)}return});let Q=W.options.length===1?W.options[0]._zod.run:null;H._zod.parse=(X,Y)=>{if(Q)return Q(X,Y);let J=!1,N=[];for(let B of W.options){let G=B._zod.run({value:X.value,issues:[]},Y);if(G instanceof Promise)N.push(G),J=!0;else{if(G.issues.length===0)return G;N.push(G)}}if(!J)return C2(N,X,H,Y);return Promise.all(N).then((B)=>{return C2(B,X,H,Y)})}});function S2(H,W,Q,X){let Y=H.filter((J)=>J.issues.length===0);if(Y.length===1)return W.value=Y[0].value,W;if(Y.length===0)W.issues.push({code:"invalid_union",input:W.value,inst:Q,errors:H.map((J)=>J.issues.map((N)=>uH(N,X,AH())))});else W.issues.push({code:"invalid_union",input:W.value,inst:Q,errors:[],inclusive:!1});return W}var WN=O("$ZodXor",(H,W)=>{dQ.init(H,W),W.inclusive=!1;let Q=W.options.length===1?W.options[0]._zod.run:null;H._zod.parse=(X,Y)=>{if(Q)return Q(X,Y);let J=!1,N=[];for(let B of W.options){let G=B._zod.run({value:X.value,issues:[]},Y);if(G instanceof Promise)N.push(G),J=!0;else N.push(G)}if(!J)return S2(N,X,H,Y);return Promise.all(N).then((B)=>{return S2(B,X,H,Y)})}}),QN=O("$ZodDiscriminatedUnion",(H,W)=>{W.inclusive=!1,dQ.init(H,W);let Q=H._zod.parse;QH(H._zod,"propValues",()=>{let Y={};for(let J of W.options){let N=J._zod.propValues;if(!N||Object.keys(N).length===0)throw Error(`Invalid discriminated union option at index "${W.options.indexOf(J)}"`);for(let[B,G]of Object.entries(N)){if(!Y[B])Y[B]=new Set;for(let D of G)Y[B].add(D)}}return Y});let X=h8(()=>{let Y=W.options,J=new Map;for(let N of Y){let B=N._zod.propValues?.[W.discriminator];if(!B||B.size===0)throw Error(`Invalid discriminated union option at index "${W.options.indexOf(N)}"`);for(let G of B){if(J.has(G))throw Error(`Duplicate discriminator value "${String(G)}"`);J.set(G,N)}}return J});H._zod.parse=(Y,J)=>{let N=Y.value;if(!rW(N))return Y.issues.push({code:"invalid_type",expected:"object",input:N,inst:H}),Y;let B=X.value.get(N?.[W.discriminator]);if(B)return B._zod.run(Y,J);if(W.unionFallback||J.direction==="backward")return Q(Y,J);return Y.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:W.discriminator,options:Array.from(X.value.keys()),input:N,path:[W.discriminator],inst:H}),Y}}),XN=O("$ZodIntersection",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{let Y=Q.value,J=W.left._zod.run({value:Y,issues:[]},X),N=W.right._zod.run({value:Y,issues:[]},X);if(J instanceof Promise||N instanceof Promise)return Promise.all([J,N]).then(([G,D])=>{return k2(Q,G,D)});return k2(Q,J,N)}});function A3(H,W){if(H===W)return{valid:!0,data:H};if(H instanceof Date&&W instanceof Date&&+H===+W)return{valid:!0,data:H};if(AW(H)&&AW(W)){let Q=Object.keys(W),X=Object.keys(H).filter((J)=>Q.indexOf(J)!==-1),Y={...H,...W};for(let J of X){let N=A3(H[J],W[J]);if(!N.valid)return{valid:!1,mergeErrorPath:[J,...N.mergeErrorPath]};Y[J]=N.data}return{valid:!0,data:Y}}if(Array.isArray(H)&&Array.isArray(W)){if(H.length!==W.length)return{valid:!1,mergeErrorPath:[]};let Q=[];for(let X=0;X<H.length;X++){let Y=H[X],J=W[X],N=A3(Y,J);if(!N.valid)return{valid:!1,mergeErrorPath:[X,...N.mergeErrorPath]};Q.push(N.data)}return{valid:!0,data:Q}}return{valid:!1,mergeErrorPath:[]}}function k2(H,W,Q){let X=new Map,Y;for(let B of W.issues)if(B.code==="unrecognized_keys"){Y??(Y=B);for(let G of B.keys){if(!X.has(G))X.set(G,{});X.get(G).l=!0}}else H.issues.push(B);for(let B of Q.issues)if(B.code==="unrecognized_keys")for(let G of B.keys){if(!X.has(G))X.set(G,{});X.get(G).r=!0}else H.issues.push(B);let J=[...X].filter(([,B])=>B.l&&B.r).map(([B])=>B);if(J.length&&Y)H.issues.push({...Y,keys:J});if(OW(H))return H;let N=A3(W.value,Q.value);if(!N.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(N.mergeErrorPath)}`);return H.value=N.data,H}var s4=O("$ZodTuple",(H,W)=>{a.init(H,W);let Q=W.items;H._zod.parse=(X,Y)=>{let J=X.value;if(!Array.isArray(J))return X.issues.push({input:J,inst:H,expected:"tuple",code:"invalid_type"}),X;X.value=[];let N=[],B=g2(Q,"optin"),G=g2(Q,"optout");if(!W.rest){if(J.length<B)return X.issues.push({code:"too_small",minimum:B,inclusive:!0,input:J,inst:H,origin:"array"}),X;if(J.length>Q.length)X.issues.push({code:"too_big",maximum:Q.length,inclusive:!0,input:J,inst:H,origin:"array"})}let D=Array(Q.length);for(let M=0;M<Q.length;M++){let _=Q[M]._zod.run({value:J[M],issues:[]},Y);if(_ instanceof Promise)N.push(_.then((F)=>{D[M]=F}));else D[M]=_}if(W.rest){let M=Q.length-1,_=J.slice(Q.length);for(let F of _){M++;let A=W.rest._zod.run({value:F,issues:[]},Y);if(A instanceof Promise)N.push(A.then((w)=>x2(w,X,M)));else x2(A,X,M)}}if(N.length)return Promise.all(N).then(()=>v2(D,X,Q,J,G));return v2(D,X,Q,J,G)}});function g2(H,W){for(let Q=H.length-1;Q>=0;Q--)if(H[Q]._zod[W]!=="optional")return Q+1;return 0}function x2(H,W,Q){if(H.issues.length)W.issues.push(...iH(Q,H.issues));W.value[Q]=H.value}function v2(H,W,Q,X,Y){for(let J=0;J<Q.length;J++){let N=H[J],B=J<X.length;if(N.issues.length){if(!B&&J>=Y){W.value.length=J;break}W.issues.push(...iH(J,N.issues))}W.value[J]=N.value}for(let J=W.value.length-1;J>=X.length;J--)if(Q[J]._zod.optout==="optional"&&W.value[J]===void 0)W.value.length=J;else break;return W}var YN=O("$ZodRecord",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{let Y=Q.value;if(!AW(Y))return Q.issues.push({expected:"record",code:"invalid_type",input:Y,inst:H}),Q;let J=[],N=W.keyType._zod.values;if(N){Q.value={};let B=new Set;for(let D of N)if(typeof D==="string"||typeof D==="number"||typeof D==="symbol"){B.add(typeof D==="number"?D.toString():D);let M=W.keyType._zod.run({value:D,issues:[]},X);if(M instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(M.issues.length){Q.issues.push({code:"invalid_key",origin:"record",issues:M.issues.map((A)=>uH(A,X,AH())),input:D,path:[D],inst:H});continue}let _=M.value,F=W.valueType._zod.run({value:Y[D],issues:[]},X);if(F instanceof Promise)J.push(F.then((A)=>{if(A.issues.length)Q.issues.push(...iH(D,A.issues));Q.value[_]=A.value}));else{if(F.issues.length)Q.issues.push(...iH(D,F.issues));Q.value[_]=F.value}}let G;for(let D in Y)if(!B.has(D))G=G??[],G.push(D);if(G&&G.length>0)Q.issues.push({code:"unrecognized_keys",input:Y,inst:H,keys:G})}else{Q.value={};for(let B of Reflect.ownKeys(Y)){if(B==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(Y,B))continue;let G=W.keyType._zod.run({value:B,issues:[]},X);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof B==="string"&&lQ.test(B)&&G.issues.length){let _=W.keyType._zod.run({value:Number(B),issues:[]},X);if(_ instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(_.issues.length===0)G=_}if(G.issues.length){if(W.mode==="loose")Q.value[B]=Y[B];else Q.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((_)=>uH(_,X,AH())),input:B,path:[B],inst:H});continue}let M=W.valueType._zod.run({value:Y[B],issues:[]},X);if(M instanceof Promise)J.push(M.then((_)=>{if(_.issues.length)Q.issues.push(...iH(B,_.issues));Q.value[G.value]=_.value}));else{if(M.issues.length)Q.issues.push(...iH(B,M.issues));Q.value[G.value]=M.value}}}if(J.length)return Promise.all(J).then(()=>Q);return Q}}),JN=O("$ZodMap",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{let Y=Q.value;if(!(Y instanceof Map))return Q.issues.push({expected:"map",code:"invalid_type",input:Y,inst:H}),Q;let J=[];Q.value=new Map;for(let[N,B]of Y){let G=W.keyType._zod.run({value:N,issues:[]},X),D=W.valueType._zod.run({value:B,issues:[]},X);if(G instanceof Promise||D instanceof Promise)J.push(Promise.all([G,D]).then(([M,_])=>{y2(M,_,Q,N,Y,H,X)}));else y2(G,D,Q,N,Y,H,X)}if(J.length)return Promise.all(J).then(()=>Q);return Q}});function y2(H,W,Q,X,Y,J,N){if(H.issues.length)if(xQ.has(typeof X))Q.issues.push(...iH(X,H.issues));else Q.issues.push({code:"invalid_key",origin:"map",input:Y,inst:J,issues:H.issues.map((B)=>uH(B,N,AH()))});if(W.issues.length)if(xQ.has(typeof X))Q.issues.push(...iH(X,W.issues));else Q.issues.push({origin:"map",code:"invalid_element",input:Y,inst:J,key:X,issues:W.issues.map((B)=>uH(B,N,AH()))});Q.value.set(H.value,W.value)}var NN=O("$ZodSet",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{let Y=Q.value;if(!(Y instanceof Set))return Q.issues.push({input:Y,inst:H,expected:"set",code:"invalid_type"}),Q;let J=[];Q.value=new Set;for(let N of Y){let B=W.valueType._zod.run({value:N,issues:[]},X);if(B instanceof Promise)J.push(B.then((G)=>h2(G,Q)));else h2(B,Q)}if(J.length)return Promise.all(J).then(()=>Q);return Q}});function h2(H,W){if(H.issues.length)W.issues.push(...H.issues);W.value.add(H.value)}var BN=O("$ZodEnum",(H,W)=>{a.init(H,W);let Q=kQ(W.entries),X=new Set(Q);H._zod.values=X,H._zod.pattern=new RegExp(`^(${Q.filter((Y)=>xQ.has(typeof Y)).map((Y)=>typeof Y==="string"?G0(Y):Y.toString()).join("|")})$`),H._zod.parse=(Y,J)=>{let N=Y.value;if(X.has(N))return Y;return Y.issues.push({code:"invalid_value",values:Q,input:N,inst:H}),Y}}),KN=O("$ZodLiteral",(H,W)=>{if(a.init(H,W),W.values.length===0)throw Error("Cannot create literal schema with no valid values");let Q=new Set(W.values);H._zod.values=Q,H._zod.pattern=new RegExp(`^(${W.values.map((X)=>typeof X==="string"?G0(X):X?G0(X.toString()):String(X)).join("|")})$`),H._zod.parse=(X,Y)=>{let J=X.value;if(Q.has(J))return X;return X.issues.push({code:"invalid_value",values:W.values,input:J,inst:H}),X}}),GN=O("$ZodFile",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{let Y=Q.value;if(Y instanceof File)return Q;return Q.issues.push({expected:"file",code:"invalid_type",input:Y,inst:H}),Q}}),DN=O("$ZodTransform",(H,W)=>{a.init(H,W),H._zod.optin="optional",H._zod.parse=(Q,X)=>{if(X.direction==="backward")throw new nW(H.constructor.name);let Y=W.transform(Q.value,Q);if(X.async)return(Y instanceof Promise?Y:Promise.resolve(Y)).then((N)=>{return Q.value=N,Q.fallback=!0,Q});if(Y instanceof Promise)throw new $0;return Q.value=Y,Q.fallback=!0,Q}});function f2(H,W){if(W===void 0&&(H.issues.length||H.fallback))return{issues:[],value:void 0};return H}var a4=O("$ZodOptional",(H,W)=>{a.init(H,W),H._zod.optin="optional",H._zod.optout="optional",QH(H._zod,"values",()=>{return W.innerType._zod.values?new Set([...W.innerType._zod.values,void 0]):void 0}),QH(H._zod,"pattern",()=>{let Q=W.innerType._zod.pattern;return Q?new RegExp(`^(${gQ(Q.source)})?$`):void 0}),H._zod.parse=(Q,X)=>{if(W.innerType._zod.optin==="optional"){let Y=Q.value,J=W.innerType._zod.run(Q,X);if(J instanceof Promise)return J.then((N)=>f2(N,Y));return f2(J,Y)}if(Q.value===void 0)return Q;return W.innerType._zod.run(Q,X)}}),MN=O("$ZodExactOptional",(H,W)=>{a4.init(H,W),QH(H._zod,"values",()=>W.innerType._zod.values),QH(H._zod,"pattern",()=>W.innerType._zod.pattern),H._zod.parse=(Q,X)=>{return W.innerType._zod.run(Q,X)}}),qN=O("$ZodNullable",(H,W)=>{a.init(H,W),QH(H._zod,"optin",()=>W.innerType._zod.optin),QH(H._zod,"optout",()=>W.innerType._zod.optout),QH(H._zod,"pattern",()=>{let Q=W.innerType._zod.pattern;return Q?new RegExp(`^(${gQ(Q.source)}|null)$`):void 0}),QH(H._zod,"values",()=>{return W.innerType._zod.values?new Set([...W.innerType._zod.values,null]):void 0}),H._zod.parse=(Q,X)=>{if(Q.value===null)return Q;return W.innerType._zod.run(Q,X)}}),_N=O("$ZodDefault",(H,W)=>{a.init(H,W),H._zod.optin="optional",QH(H._zod,"values",()=>W.innerType._zod.values),H._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);if(Q.value===void 0)return Q.value=W.defaultValue,Q;let Y=W.innerType._zod.run(Q,X);if(Y instanceof Promise)return Y.then((J)=>u2(J,W));return u2(Y,W)}});function u2(H,W){if(H.value===void 0)H.value=W.defaultValue;return H}var FN=O("$ZodPrefault",(H,W)=>{a.init(H,W),H._zod.optin="optional",QH(H._zod,"values",()=>W.innerType._zod.values),H._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);if(Q.value===void 0)Q.value=W.defaultValue;return W.innerType._zod.run(Q,X)}}),EN=O("$ZodNonOptional",(H,W)=>{a.init(H,W),QH(H._zod,"values",()=>{let Q=W.innerType._zod.values;return Q?new Set([...Q].filter((X)=>X!==void 0)):void 0}),H._zod.parse=(Q,X)=>{let Y=W.innerType._zod.run(Q,X);if(Y instanceof Promise)return Y.then((J)=>l2(J,H));return l2(Y,H)}});function l2(H,W){if(!H.issues.length&&H.value===void 0)H.issues.push({code:"invalid_type",expected:"nonoptional",input:H.value,inst:W});return H}var AN=O("$ZodSuccess",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{if(X.direction==="backward")throw new nW("ZodSuccess");let Y=W.innerType._zod.run(Q,X);if(Y instanceof Promise)return Y.then((J)=>{return Q.value=J.issues.length===0,Q});return Q.value=Y.issues.length===0,Q}}),ON=O("$ZodCatch",(H,W)=>{a.init(H,W),H._zod.optin="optional",QH(H._zod,"optout",()=>W.innerType._zod.optout),QH(H._zod,"values",()=>W.innerType._zod.values),H._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);let Y=W.innerType._zod.run(Q,X);if(Y instanceof Promise)return Y.then((J)=>{if(Q.value=J.value,J.issues.length)Q.value=W.catchValue({...Q,error:{issues:J.issues.map((N)=>uH(N,X,AH()))},input:Q.value}),Q.issues=[],Q.fallback=!0;return Q});if(Q.value=Y.value,Y.issues.length)Q.value=W.catchValue({...Q,error:{issues:Y.issues.map((J)=>uH(J,X,AH()))},input:Q.value}),Q.issues=[],Q.fallback=!0;return Q}}),VN=O("$ZodNaN",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{if(typeof Q.value!=="number"||!Number.isNaN(Q.value))return Q.issues.push({input:Q.value,inst:H,expected:"nan",code:"invalid_type"}),Q;return Q}}),e4=O("$ZodPipe",(H,W)=>{a.init(H,W),QH(H._zod,"values",()=>W.in._zod.values),QH(H._zod,"optin",()=>W.in._zod.optin),QH(H._zod,"optout",()=>W.out._zod.optout),QH(H._zod,"propValues",()=>W.in._zod.propValues),H._zod.parse=(Q,X)=>{if(X.direction==="backward"){let J=W.out._zod.run(Q,X);if(J instanceof Promise)return J.then((N)=>d4(N,W.in,X));return d4(J,W.in,X)}let Y=W.in._zod.run(Q,X);if(Y instanceof Promise)return Y.then((J)=>d4(J,W.out,X));return d4(Y,W.out,X)}});function d4(H,W,Q){if(H.issues.length)return H.aborted=!0,H;return W._zod.run({value:H.value,issues:H.issues,fallback:H.fallback},Q)}var iQ=O("$ZodCodec",(H,W)=>{a.init(H,W),QH(H._zod,"values",()=>W.in._zod.values),QH(H._zod,"optin",()=>W.in._zod.optin),QH(H._zod,"optout",()=>W.out._zod.optout),QH(H._zod,"propValues",()=>W.in._zod.propValues),H._zod.parse=(Q,X)=>{if((X.direction||"forward")==="forward"){let J=W.in._zod.run(Q,X);if(J instanceof Promise)return J.then((N)=>i4(N,W,X));return i4(J,W,X)}else{let J=W.out._zod.run(Q,X);if(J instanceof Promise)return J.then((N)=>i4(N,W,X));return i4(J,W,X)}}});function i4(H,W,Q){if(H.issues.length)return H.aborted=!0,H;if((Q.direction||"forward")==="forward"){let Y=W.transform(H.value,H);if(Y instanceof Promise)return Y.then((J)=>o4(H,J,W.out,Q));return o4(H,Y,W.out,Q)}else{let Y=W.reverseTransform(H.value,H);if(Y instanceof Promise)return Y.then((J)=>o4(H,J,W.in,Q));return o4(H,Y,W.in,Q)}}function o4(H,W,Q,X){if(H.issues.length)return H.aborted=!0,H;return Q._zod.run({value:W,issues:H.issues},X)}var UN=O("$ZodPreprocess",(H,W)=>{e4.init(H,W)}),wN=O("$ZodReadonly",(H,W)=>{a.init(H,W),QH(H._zod,"propValues",()=>W.innerType._zod.propValues),QH(H._zod,"values",()=>W.innerType._zod.values),QH(H._zod,"optin",()=>W.innerType?._zod?.optin),QH(H._zod,"optout",()=>W.innerType?._zod?.optout),H._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);let Y=W.innerType._zod.run(Q,X);if(Y instanceof Promise)return Y.then(m2);return m2(Y)}});function m2(H){return H.value=Object.freeze(H.value),H}var zN=O("$ZodTemplateLiteral",(H,W)=>{a.init(H,W);let Q=[];for(let X of W.parts)if(typeof X==="object"&&X!==null){if(!X._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...X._zod.traits].shift()}`);let Y=X._zod.pattern instanceof RegExp?X._zod.pattern.source:X._zod.pattern;if(!Y)throw Error(`Invalid template literal part: ${X._zod.traits}`);let J=Y.startsWith("^")?1:0,N=Y.endsWith("$")?Y.length-1:Y.length;Q.push(Y.slice(J,N))}else if(X===null||qJ.has(typeof X))Q.push(G0(`${X}`));else throw Error(`Invalid template literal part: ${X}`);H._zod.pattern=new RegExp(`^${Q.join("")}$`),H._zod.parse=(X,Y)=>{if(typeof X.value!=="string")return X.issues.push({input:X.value,inst:H,expected:"string",code:"invalid_type"}),X;if(H._zod.pattern.lastIndex=0,!H._zod.pattern.test(X.value))return X.issues.push({input:X.value,inst:H,code:"invalid_format",format:W.format??"template_literal",pattern:H._zod.pattern.source}),X;return X}}),ZN=O("$ZodFunction",(H,W)=>{return a.init(H,W),H._def=W,H._zod.def=W,H.implement=(Q)=>{if(typeof Q!=="function")throw Error("implement() must be called with a function");return function(...X){let Y=H._def.input?C4(H._def.input,X):X,J=Reflect.apply(Q,this,Y);if(H._def.output)return C4(H._def.output,J);return J}},H.implementAsync=(Q)=>{if(typeof Q!=="function")throw Error("implementAsync() must be called with a function");return async function(...X){let Y=H._def.input?await S4(H._def.input,X):X,J=await Reflect.apply(Q,this,Y);if(H._def.output)return await S4(H._def.output,J);return J}},H._zod.parse=(Q,X)=>{if(typeof Q.value!=="function")return Q.issues.push({code:"invalid_type",expected:"function",input:Q.value,inst:H}),Q;if(H._def.output&&H._def.output._zod.def.type==="promise")Q.value=H.implementAsync(Q.value);else Q.value=H.implement(Q.value);return Q},H.input=(...Q)=>{let X=H.constructor;if(Array.isArray(Q[0]))return new X({type:"function",input:new s4({type:"tuple",items:Q[0],rest:Q[1]}),output:H._def.output});return new X({type:"function",input:Q[0],output:H._def.output})},H.output=(Q)=>{return new H.constructor({type:"function",input:H._def.input,output:Q})},H}),PN=O("$ZodPromise",(H,W)=>{a.init(H,W),H._zod.parse=(Q,X)=>{return Promise.resolve(Q.value).then((Y)=>W.innerType._zod.run({value:Y,issues:[]},X))}}),bN=O("$ZodLazy",(H,W)=>{a.init(H,W),QH(H._zod,"innerType",()=>{let Q=W;if(!Q._cachedInner)Q._cachedInner=W.getter();return Q._cachedInner}),QH(H._zod,"pattern",()=>H._zod.innerType?._zod?.pattern),QH(H._zod,"propValues",()=>H._zod.innerType?._zod?.propValues),QH(H._zod,"optin",()=>H._zod.innerType?._zod?.optin??void 0),QH(H._zod,"optout",()=>H._zod.innerType?._zod?.optout??void 0),H._zod.parse=(Q,X)=>{return H._zod.innerType._zod.run(Q,X)}}),IN=O("$ZodCustom",(H,W)=>{GH.init(H,W),a.init(H,W),H._zod.parse=(Q,X)=>{return Q},H._zod.check=(Q)=>{let X=Q.value,Y=W.fn(X);if(Y instanceof Promise)return Y.then((J)=>c2(J,Q,X,H));c2(Y,Q,X,H);return}});function c2(H,W,Q,X){if(!H){let Y={code:"custom",input:Q,inst:X,path:[...X._zod.def.path??[]],continue:!X._zod.def.abort};if(X._zod.def.params)Y.params=X._zod.def.params;W.issues.push(f8(Y))}}var nQ={};o0(nQ,{en:()=>oQ});var Q_=()=>{let H={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 W(Y){return H[Y]??null}let Q={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"},X={nan:"NaN"};return(Y)=>{switch(Y.code){case"invalid_type":{let J=X[Y.expected]??Y.expected,N=OJ(Y.input),B=X[N]??N;return`Invalid input: expected ${J}, received ${B}`}case"invalid_value":if(Y.values.length===1)return`Invalid input: expected ${R4(Y.values[0])}`;return`Invalid option: expected one of ${j4(Y.values,"|")}`;case"too_big":{let J=Y.inclusive?"<=":"<",N=W(Y.origin);if(N)return`Too big: expected ${Y.origin??"value"} to have ${J}${Y.maximum.toString()} ${N.unit??"elements"}`;return`Too big: expected ${Y.origin??"value"} to be ${J}${Y.maximum.toString()}`}case"too_small":{let J=Y.inclusive?">=":">",N=W(Y.origin);if(N)return`Too small: expected ${Y.origin} to have ${J}${Y.minimum.toString()} ${N.unit}`;return`Too small: expected ${Y.origin} to be ${J}${Y.minimum.toString()}`}case"invalid_format":{let J=Y;if(J.format==="starts_with")return`Invalid string: must start with "${J.prefix}"`;if(J.format==="ends_with")return`Invalid string: must end with "${J.suffix}"`;if(J.format==="includes")return`Invalid string: must include "${J.includes}"`;if(J.format==="regex")return`Invalid string: must match pattern ${J.pattern}`;return`Invalid ${Q[J.format]??Y.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${Y.divisor}`;case"unrecognized_keys":return`Unrecognized key${Y.keys.length>1?"s":""}: ${j4(Y.keys,", ")}`;case"invalid_key":return`Invalid key in ${Y.origin}`;case"invalid_union":if(Y.options&&Array.isArray(Y.options)&&Y.options.length>0)return`Invalid discriminator value. Expected ${Y.options.map((N)=>`'${N}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${Y.origin}`;default:return"Invalid input"}}};function oQ(){return{localeError:Q_()}}var r2,LN=Symbol("ZodOutput"),jN=Symbol("ZodInput");class TN{constructor(){this._map=new WeakMap,this._idmap=new Map}add(H,...W){let Q=W[0];if(this._map.set(H,Q),Q&&typeof Q==="object"&&"id"in Q)this._idmap.set(Q.id,H);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(H){let W=this._map.get(H);if(W&&typeof W==="object"&&"id"in W)this._idmap.delete(W.id);return this._map.delete(H),this}get(H){let W=H._zod.parent;if(W){let Q={...this.get(W)??{}};delete Q.id;let X={...Q,...this._map.get(H)};return Object.keys(X).length?X:void 0}return this._map.get(H)}has(H){return this._map.has(H)}}function H6(){return new TN}(r2=globalThis).__zod_globalRegistry??(r2.__zod_globalRegistry=H6());var LH=globalThis.__zod_globalRegistry;function $N(H,W){return new H({type:"string",...L(W)})}function RN(H,W){return new H({type:"string",coerce:!0,...L(W)})}function W6(H,W){return new H({type:"string",format:"email",check:"string_format",abort:!1,...L(W)})}function rQ(H,W){return new H({type:"string",format:"guid",check:"string_format",abort:!1,...L(W)})}function Q6(H,W){return new H({type:"string",format:"uuid",check:"string_format",abort:!1,...L(W)})}function X6(H,W){return new H({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(W)})}function Y6(H,W){return new H({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(W)})}function J6(H,W){return new H({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(W)})}function tQ(H,W){return new H({type:"string",format:"url",check:"string_format",abort:!1,...L(W)})}function N6(H,W){return new H({type:"string",format:"emoji",check:"string_format",abort:!1,...L(W)})}function B6(H,W){return new H({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(W)})}function K6(H,W){return new H({type:"string",format:"cuid",check:"string_format",abort:!1,...L(W)})}function G6(H,W){return new H({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(W)})}function D6(H,W){return new H({type:"string",format:"ulid",check:"string_format",abort:!1,...L(W)})}function M6(H,W){return new H({type:"string",format:"xid",check:"string_format",abort:!1,...L(W)})}function q6(H,W){return new H({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(W)})}function _6(H,W){return new H({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(W)})}function F6(H,W){return new H({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(W)})}function CN(H,W){return new H({type:"string",format:"mac",check:"string_format",abort:!1,...L(W)})}function E6(H,W){return new H({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(W)})}function A6(H,W){return new H({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(W)})}function O6(H,W){return new H({type:"string",format:"base64",check:"string_format",abort:!1,...L(W)})}function V6(H,W){return new H({type:"string",format:"base64url",check:"string_format",abort:!1,...L(W)})}function U6(H,W){return new H({type:"string",format:"e164",check:"string_format",abort:!1,...L(W)})}function w6(H,W){return new H({type:"string",format:"jwt",check:"string_format",abort:!1,...L(W)})}var SN={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function kN(H,W){return new H({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(W)})}function gN(H,W){return new H({type:"string",format:"date",check:"string_format",...L(W)})}function xN(H,W){return new H({type:"string",format:"time",check:"string_format",precision:null,...L(W)})}function vN(H,W){return new H({type:"string",format:"duration",check:"string_format",...L(W)})}function yN(H,W){return new H({type:"number",checks:[],...L(W)})}function hN(H,W){return new H({type:"number",coerce:!0,checks:[],...L(W)})}function fN(H,W){return new H({type:"number",check:"number_format",abort:!1,format:"safeint",...L(W)})}function uN(H,W){return new H({type:"number",check:"number_format",abort:!1,format:"float32",...L(W)})}function lN(H,W){return new H({type:"number",check:"number_format",abort:!1,format:"float64",...L(W)})}function mN(H,W){return new H({type:"number",check:"number_format",abort:!1,format:"int32",...L(W)})}function cN(H,W){return new H({type:"number",check:"number_format",abort:!1,format:"uint32",...L(W)})}function pN(H,W){return new H({type:"boolean",...L(W)})}function dN(H,W){return new H({type:"boolean",coerce:!0,...L(W)})}function iN(H,W){return new H({type:"bigint",...L(W)})}function oN(H,W){return new H({type:"bigint",coerce:!0,...L(W)})}function nN(H,W){return new H({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...L(W)})}function rN(H,W){return new H({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...L(W)})}function tN(H,W){return new H({type:"symbol",...L(W)})}function sN(H,W){return new H({type:"undefined",...L(W)})}function aN(H,W){return new H({type:"null",...L(W)})}function eN(H){return new H({type:"any"})}function H5(H){return new H({type:"unknown"})}function W5(H,W){return new H({type:"never",...L(W)})}function Q5(H,W){return new H({type:"void",...L(W)})}function X5(H,W){return new H({type:"date",...L(W)})}function Y5(H,W){return new H({type:"date",coerce:!0,...L(W)})}function J5(H,W){return new H({type:"nan",...L(W)})}function R0(H,W){return new m4({check:"less_than",...L(W),value:H,inclusive:!1})}function Q0(H,W){return new m4({check:"less_than",...L(W),value:H,inclusive:!0})}function C0(H,W){return new c4({check:"greater_than",...L(W),value:H,inclusive:!1})}function lH(H,W){return new c4({check:"greater_than",...L(W),value:H,inclusive:!0})}function z6(H){return C0(0,H)}function Z6(H){return R0(0,H)}function P6(H){return Q0(0,H)}function b6(H){return lH(0,H)}function VW(H,W){return new sJ({check:"multiple_of",...L(W),value:H})}function UW(H,W){return new H3({check:"max_size",...L(W),maximum:H})}function S0(H,W){return new W3({check:"min_size",...L(W),minimum:H})}function aW(H,W){return new Q3({check:"size_equals",...L(W),size:H})}function eW(H,W){return new X3({check:"max_length",...L(W),maximum:H})}function r0(H,W){return new Y3({check:"min_length",...L(W),minimum:H})}function H8(H,W){return new J3({check:"length_equals",...L(W),length:H})}function d8(H,W){return new N3({check:"string_format",format:"regex",...L(W),pattern:H})}function i8(H){return new B3({check:"string_format",format:"lowercase",...L(H)})}function o8(H){return new K3({check:"string_format",format:"uppercase",...L(H)})}function n8(H,W){return new G3({check:"string_format",format:"includes",...L(W),includes:H})}function r8(H,W){return new D3({check:"string_format",format:"starts_with",...L(W),prefix:H})}function t8(H,W){return new M3({check:"string_format",format:"ends_with",...L(W),suffix:H})}function I6(H,W,Q){return new q3({check:"property",property:H,schema:W,...L(Q)})}function s8(H,W){return new _3({check:"mime_type",mime:H,...L(W)})}function E0(H){return new F3({check:"overwrite",tx:H})}function a8(H){return E0((W)=>W.normalize(H))}function e8(){return E0((H)=>H.trim())}function H1(){return E0((H)=>H.toLowerCase())}function W1(){return E0((H)=>H.toUpperCase())}function Q1(){return E0((H)=>GJ(H))}function N5(H,W,Q){return new H({type:"array",element:W,...L(Q)})}function Y_(H,W,Q){return new H({type:"union",options:W,...L(Q)})}function J_(H,W,Q){return new H({type:"union",options:W,inclusive:!1,...L(Q)})}function N_(H,W,Q,X){return new H({type:"union",options:Q,discriminator:W,...L(X)})}function B_(H,W,Q){return new H({type:"intersection",left:W,right:Q})}function K_(H,W,Q,X){let Y=Q instanceof a;return new H({type:"tuple",items:W,rest:Y?Q:null,...L(Y?X:Q)})}function G_(H,W,Q,X){return new H({type:"record",keyType:W,valueType:Q,...L(X)})}function D_(H,W,Q,X){return new H({type:"map",keyType:W,valueType:Q,...L(X)})}function M_(H,W,Q){return new H({type:"set",valueType:W,...L(Q)})}function q_(H,W,Q){let X=Array.isArray(W)?Object.fromEntries(W.map((Y)=>[Y,Y])):W;return new H({type:"enum",entries:X,...L(Q)})}function __(H,W,Q){return new H({type:"enum",entries:W,...L(Q)})}function F_(H,W,Q){return new H({type:"literal",values:Array.isArray(W)?W:[W],...L(Q)})}function B5(H,W){return new H({type:"file",...L(W)})}function E_(H,W){return new H({type:"transform",transform:W})}function A_(H,W){return new H({type:"optional",innerType:W})}function O_(H,W){return new H({type:"nullable",innerType:W})}function V_(H,W,Q){return new H({type:"default",innerType:W,get defaultValue(){return typeof Q==="function"?Q():MJ(Q)}})}function U_(H,W,Q){return new H({type:"nonoptional",innerType:W,...L(Q)})}function w_(H,W){return new H({type:"success",innerType:W})}function z_(H,W,Q){return new H({type:"catch",innerType:W,catchValue:typeof Q==="function"?Q:()=>Q})}function Z_(H,W,Q){return new H({type:"pipe",in:W,out:Q})}function P_(H,W){return new H({type:"readonly",innerType:W})}function b_(H,W,Q){return new H({type:"template_literal",parts:W,...L(Q)})}function I_(H,W){return new H({type:"lazy",getter:W})}function L_(H,W){return new H({type:"promise",innerType:W})}function K5(H,W,Q){let X=L(Q);return X.abort??(X.abort=!0),new H({type:"custom",check:"custom",fn:W,...X})}function G5(H,W,Q){return new H({type:"custom",check:"custom",fn:W,...L(Q)})}function D5(H,W){let Q=t2((X)=>{return X.addIssue=(Y)=>{if(typeof Y==="string")X.issues.push(f8(Y,X.value,Q._zod.def));else{let J=Y;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=X.value),J.inst??(J.inst=Q),J.continue??(J.continue=!Q._zod.def.abort),X.issues.push(f8(J))}},H(X.value,X)},W);return Q}function t2(H,W){let Q=new GH({check:"custom",...L(W)});return Q._zod.check=H,Q}function M5(H){let W=new GH({check:"describe"});return W._zod.onattach=[(Q)=>{let X=LH.get(Q)??{};LH.add(Q,{...X,description:H})}],W._zod.check=()=>{},W}function q5(H){let W=new GH({check:"meta"});return W._zod.onattach=[(Q)=>{let X=LH.get(Q)??{};LH.add(Q,{...X,...H})}],W._zod.check=()=>{},W}function _5(H,W){let Q=L(W),X=Q.truthy??["true","1","yes","on","y","enabled"],Y=Q.falsy??["false","0","no","off","n","disabled"];if(Q.case!=="sensitive")X=X.map((A)=>typeof A==="string"?A.toLowerCase():A),Y=Y.map((A)=>typeof A==="string"?A.toLowerCase():A);let J=new Set(X),N=new Set(Y),B=H.Codec??iQ,G=H.Boolean??pQ,M=new(H.String??sW)({type:"string",error:Q.error}),_=new G({type:"boolean",error:Q.error}),F=new B({type:"pipe",in:M,out:_,transform:(A,w)=>{let z=A;if(Q.case!=="sensitive")z=z.toLowerCase();if(J.has(z))return!0;else if(N.has(z))return!1;else return w.issues.push({code:"invalid_value",expected:"stringbool",values:[...J,...N],input:w.value,inst:F,continue:!1}),{}},reverseTransform:(A,w)=>{if(A===!0)return X[0]||"true";else return Y[0]||"false"},error:Q.error});return F}function X1(H,W,Q,X={}){let Y=L(X),J={...L(X),check:"string_format",type:"string",format:W,fn:typeof Q==="function"?Q:(B)=>Q.test(B),...Y};if(Q instanceof RegExp)J.pattern=Q;return new H(J)}function wW(H){let W=H?.target??"draft-2020-12";if(W==="draft-4")W="draft-04";if(W==="draft-7")W="draft-07";return{processors:H.processors??{},metadataRegistry:H?.metadata??LH,target:W,unrepresentable:H?.unrepresentable??"throw",override:H?.override??(()=>{}),io:H?.io??"output",counter:0,seen:new Map,cycles:H?.cycles??"ref",reused:H?.reused??"inline",external:H?.external??void 0}}function YH(H,W,Q={path:[],schemaPath:[]}){var X;let Y=H._zod.def,J=W.seen.get(H);if(J){if(J.count++,Q.schemaPath.includes(H))J.cycle=Q.path;return J.schema}let N={schema:{},count:1,cycle:void 0,path:Q.path};W.seen.set(H,N);let B=H._zod.toJSONSchema?.();if(B)N.schema=B;else{let M={...Q,schemaPath:[...Q.schemaPath,H],path:Q.path};if(H._zod.processJSONSchema)H._zod.processJSONSchema(W,N.schema,M);else{let F=N.schema,A=W.processors[Y.type];if(!A)throw Error(`[toJSONSchema]: Non-representable type encountered: ${Y.type}`);A(H,W,F,M)}let _=H._zod.parent;if(_){if(!N.ref)N.ref=_;YH(_,W,M),W.seen.get(_).isParent=!0}}let G=W.metadataRegistry.get(H);if(G)Object.assign(N.schema,G);if(W.io==="input"&&mH(H))delete N.schema.examples,delete N.schema.default;if(W.io==="input"&&"_prefault"in N.schema)(X=N.schema).default??(X.default=N.schema._prefault);return delete N.schema._prefault,W.seen.get(H).schema}function zW(H,W){let Q=H.seen.get(W);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let X=new Map;for(let N of H.seen.entries()){let B=H.metadataRegistry.get(N[0])?.id;if(B){let G=X.get(B);if(G&&G!==N[0])throw Error(`Duplicate schema id "${B}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);X.set(B,N[0])}}let Y=(N)=>{let B=H.target==="draft-2020-12"?"$defs":"definitions";if(H.external){let _=H.external.registry.get(N[0])?.id,F=H.external.uri??((w)=>w);if(_)return{ref:F(_)};let A=N[1].defId??N[1].schema.id??`schema${H.counter++}`;return N[1].defId=A,{defId:A,ref:`${F("__shared")}#/${B}/${A}`}}if(N[1]===Q)return{ref:"#"};let D=`${"#"}/${B}/`,M=N[1].schema.id??`__schema${H.counter++}`;return{defId:M,ref:D+M}},J=(N)=>{if(N[1].schema.$ref)return;let B=N[1],{ref:G,defId:D}=Y(N);if(B.def={...B.schema},D)B.defId=D;let M=B.schema;for(let _ in M)delete M[_];M.$ref=G};if(H.cycles==="throw")for(let N of H.seen.entries()){let B=N[1];if(B.cycle)throw Error(`Cycle detected: #/${B.cycle?.join("/")}/<root>
62
+ `)}S.write("payload.value = newResult;"),S.write("return payload;");let F=S.compile();return(x,U)=>F(f,x,U)},s,i=ao,a=!io.jitless,u=a&&pd.value,d=t.catchall,m;e._zod.parse=(f,S)=>{m??(m=o.value);let b=f.value;if(!i(b))return f.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),f;if(a&&u&&S?.async===!1&&S.jitless!==!0){if(!s)s=n(t.shape);if(f=s(f,S),!d)return f;return ih([],b,f,S,m,e)}return r(f,S)}});function yp(e,t,r,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let n=e.filter((s)=>!zr(s));if(n.length===1)return t.value=n[0].value,n[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>ot(i,o,je())))}),t}var el=_("$ZodUnion",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),Q(e._zod,"optout",()=>t.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),Q(e._zod,"values",()=>{if(t.options.every((o)=>o._zod.values))return new Set(t.options.flatMap((o)=>Array.from(o._zod.values)));return}),Q(e._zod,"pattern",()=>{if(t.options.every((o)=>o._zod.pattern)){let o=t.options.map((n)=>n._zod.pattern);return new RegExp(`^(${o.map((n)=>ga(n.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)i.push(l),s=!0;else{if(l.issues.length===0)return l;i.push(l)}}if(!s)return yp(i,o,e,n);return Promise.all(i).then((a)=>yp(a,o,e,n))}});var ch=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,el.init(e,t);let r=e._zod.parse;Q(e._zod,"propValues",()=>{let n={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,l]of Object.entries(i)){if(!n[a])n[a]=new Set;for(let u of l)n[a].add(u)}}return n});let o=qn(()=>{let n=t.options,s=new Map;for(let i of n){let a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let l of a){if(s.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(n,s)=>{let i=n.value;if(!ao(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),n;let a=o.value.get(i?.[t.discriminator]);if(a)return a._zod.run(n,s);if(t.unionFallback||s.direction==="backward")return r(n,s);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:i,path:[t.discriminator],inst:e}),n}}),lh=_("$ZodIntersection",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,s=t.left._zod.run({value:n,issues:[]},o),i=t.right._zod.run({value:n,issues:[]},o);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([l,u])=>vp(r,l,u));return vp(r,s,i)}});function Xc(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(vr(e)&&vr(t)){let r=Object.keys(t),o=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),n={...e,...t};for(let s of o){let i=Xc(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],s=t[o],i=Xc(n,s);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function vp(e,t,r){let o=new Map,n;for(let a of t.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).r=!0}else e.issues.push(a);let s=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&n)e.issues.push({...n,keys:s});if(zr(e))return e;let i=Xc(t.value,r.value);if(!i.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var uh=_("$ZodRecord",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!vr(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let s=[],i=t.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){a.add(typeof u==="number"?u.toString():u);let d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((S)=>ot(S,o,je())),input:u,path:[u],inst:e});continue}let m=d.value,f=t.valueType._zod.run({value:n[u],issues:[]},o);if(f instanceof Promise)s.push(f.then((S)=>{if(S.issues.length)r.issues.push(...Gt(u,S.issues));r.value[m]=S.value}));else{if(f.issues.length)r.issues.push(...Gt(u,f.issues));r.value[m]=f.value}}let l;for(let u in n)if(!a.has(u))l=l??[],l.push(u);if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&Wc.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)l=m}if(l.issues.length){if(t.mode==="loose")r.value[a]=n[a];else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>ot(m,o,je())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);if(d instanceof Promise)s.push(d.then((m)=>{if(m.issues.length)r.issues.push(...Gt(a,m.issues));r.value[l.value]=m.value}));else{if(d.issues.length)r.issues.push(...Gt(a,d.issues));r.value[l.value]=d.value}}}if(s.length)return Promise.all(s).then(()=>r);return r}});var dh=_("$ZodEnum",(e,t)=>{re.init(e,t);let r=ma(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter((n)=>hd.has(typeof n)).map((n)=>typeof n==="string"?Kt(n):n.toString()).join("|")})$`),e._zod.parse=(n,s)=>{let i=n.value;if(o.has(i))return n;return n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),ph=_("$ZodLiteral",(e,t)=>{if(re.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((o)=>typeof o==="string"?Kt(o):o?Kt(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let s=o.value;if(r.has(s))return o;return o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}});var hh=_("$ZodTransform",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((i)=>(r.value=i,r.fallback=!0,r));if(n instanceof Promise)throw new kt;return r.value=n,r.fallback=!0,r}});function zp(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var tl=_("$ZodOptional",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ga(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,s=t.innerType._zod.run(r,o);if(s instanceof Promise)return s.then((i)=>zp(i,n));return zp(s,n)}if(r.value===void 0)return r;return t.innerType._zod.run(r,o)}}),mh=_("$ZodExactOptional",(e,t)=>{tl.init(e,t),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),fh=_("$ZodNullable",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ga(r.source)}|null)$`):void 0}),Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>{if(r.value===null)return r;return t.innerType._zod.run(r,o)}}),gh=_("$ZodDefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>wp(s,t));return wp(n,t)}});function wp(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Sh=_("$ZodPrefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,o)}}),_h=_("$ZodNonOptional",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>Rp(s,e));return Rp(n,e)}});function Rp(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var bh=_("$ZodCatch",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>{if(r.value=s.value,s.issues.length)r.value=t.catchValue({...r,error:{issues:s.issues.map((i)=>ot(i,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=n.value,n.issues.length)r.value=t.catchValue({...r,error:{issues:n.issues.map((s)=>ot(s,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var rl=_("$ZodPipe",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>t.in._zod.values),Q(e._zod,"optin",()=>t.in._zod.optin),Q(e._zod,"optout",()=>t.out._zod.optout),Q(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let s=t.out._zod.run(r,o);if(s instanceof Promise)return s.then((i)=>va(i,t.in,o));return va(s,t.in,o)}let n=t.in._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>va(s,t.out,o));return va(n,t.out,o)}});function va(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var yh=_("$ZodPreprocess",(e,t)=>{rl.init(e,t)}),vh=_("$ZodReadonly",(e,t)=>{re.init(e,t),Q(e._zod,"propValues",()=>t.innerType._zod.propValues),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"optin",()=>t.innerType?._zod?.optin),Q(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then(xp);return xp(n)}});function xp(e){return e.value=Object.freeze(e.value),e}var zh=_("$ZodLazy",(e,t)=>{re.init(e,t),Q(e._zod,"innerType",()=>{let r=t;if(!r._cachedInner)r._cachedInner=t.getter();return r._cachedInner}),Q(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Q(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Q(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Q(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),wh=_("$ZodCustom",(e,t)=>{ze.init(e,t),re.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=(r)=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then((s)=>Pp(s,r,o,e));Pp(n,r,o,e);return}});function Pp(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)n.params=o._zod.def.params;t.issues.push(wr(n))}}var o_=()=>{let 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(n){return e[n]??null}let r={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"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let s=o[n.expected]??n.expected,i=Sd(n.input),a=o[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${Dc(n.values[0])}`;return`Invalid option: expected one of ${jc(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=t(n.origin);if(i)return`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${i.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",i=t(n.origin);if(i)return`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${i.unit}`;return`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${jc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":if(n.options&&Array.isArray(n.options)&&n.options.length>0)return`Invalid discriminator value. Expected ${n.options.map((i)=>`'${i}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function ol(){return{localeError:o_()}}var Rh,n_=Symbol("ZodOutput"),s_=Symbol("ZodInput");class xh{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Ph(){return new xh}(Rh=globalThis).__zod_globalRegistry??(Rh.__zod_globalRegistry=Ph());var Yt=globalThis.__zod_globalRegistry;function Th(e,t){return new e({type:"string",...M(t)})}function nl(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function sl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function Eh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function kh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function $h(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function Ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function il(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function Ih(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function Oh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function Nh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function qh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function Ah(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function Mh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function jh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function Lh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function Uh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function Zh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function Dh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function Fh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function Hh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function Vh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function Jh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}function Bh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function Wh(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Kh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Gh(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function Yh(e,t){return new e({type:"number",checks:[],...M(t)})}function Xh(e,t){return new e({type:"number",coerce:!0,checks:[],...M(t)})}function Qh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function em(e,t){return new e({type:"boolean",...M(t)})}function tm(e,t){return new e({type:"undefined",...M(t)})}function rm(e,t){return new e({type:"null",...M(t)})}function om(e){return new e({type:"any"})}function nm(e){return new e({type:"unknown"})}function sm(e,t){return new e({type:"never",...M(t)})}function Ra(e,t){return new Kc({check:"less_than",...M(t),value:e,inclusive:!1})}function Un(e,t){return new Kc({check:"less_than",...M(t),value:e,inclusive:!0})}function xa(e,t){return new Gc({check:"greater_than",...M(t),value:e,inclusive:!1})}function Zn(e,t){return new Gc({check:"greater_than",...M(t),value:e,inclusive:!0})}function Pa(e,t){return new sp({check:"multiple_of",...M(t),value:e})}function Ta(e,t){return new ap({check:"max_length",...M(t),maximum:e})}function co(e,t){return new cp({check:"min_length",...M(t),minimum:e})}function Ea(e,t){return new lp({check:"length_equals",...M(t),length:e})}function al(e,t){return new up({check:"string_format",format:"regex",...M(t),pattern:e})}function cl(e){return new dp({check:"string_format",format:"lowercase",...M(e)})}function ll(e){return new pp({check:"string_format",format:"uppercase",...M(e)})}function ul(e,t){return new hp({check:"string_format",format:"includes",...M(t),includes:e})}function dl(e,t){return new mp({check:"string_format",format:"starts_with",...M(t),prefix:e})}function pl(e,t){return new fp({check:"string_format",format:"ends_with",...M(t),suffix:e})}function Xt(e){return new gp({check:"overwrite",tx:e})}function hl(e){return Xt((t)=>t.normalize(e))}function ml(){return Xt((e)=>e.trim())}function fl(){return Xt((e)=>e.toLowerCase())}function gl(){return Xt((e)=>e.toUpperCase())}function Sl(){return Xt((e)=>dd(e))}function im(e,t,r){return new e({type:"array",element:t,...M(r)})}function am(e,t,r){return new e({type:"custom",check:"custom",fn:t,...M(r)})}function cm(e,t){let r=i_((o)=>(o.addIssue=(n)=>{if(typeof n==="string")o.issues.push(wr(n,o.value,r._zod.def));else{let s=n;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=o.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),o.issues.push(wr(s))}},e(o.value,o)),t);return r}function i_(e,t){let r=new ze({check:"custom",...M(t)});return r._zod.check=e,r}function Fn(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Yt,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 oe(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let f=i.schema,S=t.processors[n.type];if(!S)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);S(e,t,f,d)}let m=e._zod.parent;if(m){if(!i.ref)i.ref=m;oe(m,t,d),t.seen.get(m).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(i.schema,l);if(t.io==="input"&&Ne(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(o=i.schema).default??(o.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Hn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let l=o.get(a);if(l&&l!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,i[0])}}let n=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(i[0])?.id,f=e.external.uri??((b)=>b);if(m)return{ref:f(m)};let S=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=S,{defId:S,ref:`${f("__shared")}#/${a}/${S}`}}if(i[1]===r)return{ref:"#"};let u=`${"#"}/${a}/`,d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:l,defId:u}=n(i);if(a.def={...a.schema},u)a.defId=u;let d=a.schema;for(let m in d)delete d[m];d.$ref=l};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
64
63
 
65
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let N of H.seen.entries()){let B=N[1];if(W===N[0]){J(N);continue}if(H.external){let D=H.external.registry.get(N[0])?.id;if(W!==N[0]&&D){J(N);continue}}if(H.metadataRegistry.get(N[0])?.id){J(N);continue}if(B.cycle){J(N);continue}if(B.count>1){if(H.reused==="ref"){J(N);continue}}}}function ZW(H,W){let Q=H.seen.get(W);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let X=(B)=>{let G=H.seen.get(B);if(G.ref===null)return;let D=G.def??G.schema,M={...D},_=G.ref;if(G.ref=null,_){X(_);let A=H.seen.get(_),w=A.schema;if(w.$ref&&(H.target==="draft-07"||H.target==="draft-04"||H.target==="openapi-3.0"))D.allOf=D.allOf??[],D.allOf.push(w);else Object.assign(D,w);if(Object.assign(D,M),B._zod.parent===_)for(let Z in D){if(Z==="$ref"||Z==="allOf")continue;if(!(Z in M))delete D[Z]}if(w.$ref&&A.def)for(let Z in D){if(Z==="$ref"||Z==="allOf")continue;if(Z in A.def&&JSON.stringify(D[Z])===JSON.stringify(A.def[Z]))delete D[Z]}}let F=B._zod.parent;if(F&&F!==_){X(F);let A=H.seen.get(F);if(A?.schema.$ref){if(D.$ref=A.schema.$ref,A.def)for(let w in D){if(w==="$ref"||w==="allOf")continue;if(w in A.def&&JSON.stringify(D[w])===JSON.stringify(A.def[w]))delete D[w]}}}H.override({zodSchema:B,jsonSchema:D,path:G.path??[]})};for(let B of[...H.seen.entries()].reverse())X(B[0]);let Y={};if(H.target==="draft-2020-12")Y.$schema="https://json-schema.org/draft/2020-12/schema";else if(H.target==="draft-07")Y.$schema="http://json-schema.org/draft-07/schema#";else if(H.target==="draft-04")Y.$schema="http://json-schema.org/draft-04/schema#";else if(H.target==="openapi-3.0");if(H.external?.uri){let B=H.external.registry.get(W)?.id;if(!B)throw Error("Schema is missing an `id` property");Y.$id=H.external.uri(B)}Object.assign(Y,Q.def??Q.schema);let J=H.metadataRegistry.get(W)?.id;if(J!==void 0&&Y.id===J)delete Y.id;let N=H.external?.defs??{};for(let B of H.seen.entries()){let G=B[1];if(G.def&&G.defId){if(G.def.id===G.defId)delete G.def.id;N[G.defId]=G.def}}if(H.external);else if(Object.keys(N).length>0)if(H.target==="draft-2020-12")Y.$defs=N;else Y.definitions=N;try{let B=JSON.parse(JSON.stringify(Y));return Object.defineProperty(B,"~standard",{value:{...W["~standard"],jsonSchema:{input:Y1(W,"input",H.processors),output:Y1(W,"output",H.processors)}},enumerable:!1,writable:!1}),B}catch(B){throw Error("Error converting schema to JSON.")}}function mH(H,W){let Q=W??{seen:new Set};if(Q.seen.has(H))return!1;Q.seen.add(H);let X=H._zod.def;if(X.type==="transform")return!0;if(X.type==="array")return mH(X.element,Q);if(X.type==="set")return mH(X.valueType,Q);if(X.type==="lazy")return mH(X.getter(),Q);if(X.type==="promise"||X.type==="optional"||X.type==="nonoptional"||X.type==="nullable"||X.type==="readonly"||X.type==="default"||X.type==="prefault")return mH(X.innerType,Q);if(X.type==="intersection")return mH(X.left,Q)||mH(X.right,Q);if(X.type==="record"||X.type==="map")return mH(X.keyType,Q)||mH(X.valueType,Q);if(X.type==="pipe"){if(H._zod.traits.has("$ZodCodec"))return!0;return mH(X.in,Q)||mH(X.out,Q)}if(X.type==="object"){for(let Y in X.shape)if(mH(X.shape[Y],Q))return!0;return!1}if(X.type==="union"){for(let Y of X.options)if(mH(Y,Q))return!0;return!1}if(X.type==="tuple"){for(let Y of X.items)if(mH(Y,Q))return!0;if(X.rest&&mH(X.rest,Q))return!0;return!1}return!1}var F5=(H,W={})=>(Q)=>{let X=wW({...Q,processors:W});return YH(H,X),zW(X,H),ZW(X,H)},Y1=(H,W,Q={})=>(X)=>{let{libraryOptions:Y,target:J}=X??{},N=wW({...Y??{},target:J,io:W,processors:Q});return YH(H,N),zW(N,H),ZW(N,H)};var j_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},E5=(H,W,Q,X)=>{let Y=Q;Y.type="string";let{minimum:J,maximum:N,format:B,patterns:G,contentEncoding:D}=H._zod.bag;if(typeof J==="number")Y.minLength=J;if(typeof N==="number")Y.maxLength=N;if(B){if(Y.format=j_[B]??B,Y.format==="")delete Y.format;if(B==="time")delete Y.format}if(D)Y.contentEncoding=D;if(G&&G.size>0){let M=[...G];if(M.length===1)Y.pattern=M[0].source;else if(M.length>1)Y.allOf=[...M.map((_)=>({...W.target==="draft-07"||W.target==="draft-04"||W.target==="openapi-3.0"?{type:"string"}:{},pattern:_.source}))]}},A5=(H,W,Q,X)=>{let Y=Q,{minimum:J,maximum:N,format:B,multipleOf:G,exclusiveMaximum:D,exclusiveMinimum:M}=H._zod.bag;if(typeof B==="string"&&B.includes("int"))Y.type="integer";else Y.type="number";let _=typeof M==="number"&&M>=(J??Number.NEGATIVE_INFINITY),F=typeof D==="number"&&D<=(N??Number.POSITIVE_INFINITY),A=W.target==="draft-04"||W.target==="openapi-3.0";if(_)if(A)Y.minimum=M,Y.exclusiveMinimum=!0;else Y.exclusiveMinimum=M;else if(typeof J==="number")Y.minimum=J;if(F)if(A)Y.maximum=D,Y.exclusiveMaximum=!0;else Y.exclusiveMaximum=D;else if(typeof N==="number")Y.maximum=N;if(typeof G==="number")Y.multipleOf=G},O5=(H,W,Q,X)=>{Q.type="boolean"},V5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},U5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},w5=(H,W,Q,X)=>{if(W.target==="openapi-3.0")Q.type="string",Q.nullable=!0,Q.enum=[null];else Q.type="null"},z5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},Z5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},P5=(H,W,Q,X)=>{Q.not={}},b5=(H,W,Q,X)=>{},I5=(H,W,Q,X)=>{},L5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},j5=(H,W,Q,X)=>{let Y=H._zod.def,J=kQ(Y.entries);if(J.every((N)=>typeof N==="number"))Q.type="number";if(J.every((N)=>typeof N==="string"))Q.type="string";Q.enum=J},T5=(H,W,Q,X)=>{let Y=H._zod.def,J=[];for(let N of Y.values)if(N===void 0){if(W.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof N==="bigint")if(W.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else J.push(Number(N));else J.push(N);if(J.length===0);else if(J.length===1){let N=J[0];if(Q.type=N===null?"null":typeof N,W.target==="draft-04"||W.target==="openapi-3.0")Q.enum=[N];else Q.const=N}else{if(J.every((N)=>typeof N==="number"))Q.type="number";if(J.every((N)=>typeof N==="string"))Q.type="string";if(J.every((N)=>typeof N==="boolean"))Q.type="boolean";if(J.every((N)=>N===null))Q.type="null";Q.enum=J}},$5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},R5=(H,W,Q,X)=>{let Y=Q,J=H._zod.pattern;if(!J)throw Error("Pattern not found in template literal");Y.type="string",Y.pattern=J.source},C5=(H,W,Q,X)=>{let Y=Q,J={type:"string",format:"binary",contentEncoding:"binary"},{minimum:N,maximum:B,mime:G}=H._zod.bag;if(N!==void 0)J.minLength=N;if(B!==void 0)J.maxLength=B;if(G)if(G.length===1)J.contentMediaType=G[0],Object.assign(Y,J);else Object.assign(Y,J),Y.anyOf=G.map((D)=>({contentMediaType:D}));else Object.assign(Y,J)},S5=(H,W,Q,X)=>{Q.type="boolean"},k5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},g5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},x5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},v5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},y5=(H,W,Q,X)=>{if(W.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},h5=(H,W,Q,X)=>{let Y=Q,J=H._zod.def,{minimum:N,maximum:B}=H._zod.bag;if(typeof N==="number")Y.minItems=N;if(typeof B==="number")Y.maxItems=B;Y.type="array",Y.items=YH(J.element,W,{...X,path:[...X.path,"items"]})},f5=(H,W,Q,X)=>{let Y=Q,J=H._zod.def;Y.type="object",Y.properties={};let N=J.shape;for(let D in N)Y.properties[D]=YH(N[D],W,{...X,path:[...X.path,"properties",D]});let B=new Set(Object.keys(N)),G=new Set([...B].filter((D)=>{let M=J.shape[D]._zod;if(W.io==="input")return M.optin===void 0;else return M.optout===void 0}));if(G.size>0)Y.required=Array.from(G);if(J.catchall?._zod.def.type==="never")Y.additionalProperties=!1;else if(!J.catchall){if(W.io==="output")Y.additionalProperties=!1}else if(J.catchall)Y.additionalProperties=YH(J.catchall,W,{...X,path:[...X.path,"additionalProperties"]})},j6=(H,W,Q,X)=>{let Y=H._zod.def,J=Y.inclusive===!1,N=Y.options.map((B,G)=>YH(B,W,{...X,path:[...X.path,J?"oneOf":"anyOf",G]}));if(J)Q.oneOf=N;else Q.anyOf=N},u5=(H,W,Q,X)=>{let Y=H._zod.def,J=YH(Y.left,W,{...X,path:[...X.path,"allOf",0]}),N=YH(Y.right,W,{...X,path:[...X.path,"allOf",1]}),B=(D)=>("allOf"in D)&&Object.keys(D).length===1,G=[...B(J)?J.allOf:[J],...B(N)?N.allOf:[N]];Q.allOf=G},l5=(H,W,Q,X)=>{let Y=Q,J=H._zod.def;Y.type="array";let N=W.target==="draft-2020-12"?"prefixItems":"items",B=W.target==="draft-2020-12"?"items":W.target==="openapi-3.0"?"items":"additionalItems",G=J.items.map((F,A)=>YH(F,W,{...X,path:[...X.path,N,A]})),D=J.rest?YH(J.rest,W,{...X,path:[...X.path,B,...W.target==="openapi-3.0"?[J.items.length]:[]]}):null;if(W.target==="draft-2020-12"){if(Y.prefixItems=G,D)Y.items=D}else if(W.target==="openapi-3.0"){if(Y.items={anyOf:G},D)Y.items.anyOf.push(D);if(Y.minItems=G.length,!D)Y.maxItems=G.length}else if(Y.items=G,D)Y.additionalItems=D;let{minimum:M,maximum:_}=H._zod.bag;if(typeof M==="number")Y.minItems=M;if(typeof _==="number")Y.maxItems=_},m5=(H,W,Q,X)=>{let Y=Q,J=H._zod.def;Y.type="object";let N=J.keyType,G=N._zod.bag?.patterns;if(J.mode==="loose"&&G&&G.size>0){let M=YH(J.valueType,W,{...X,path:[...X.path,"patternProperties","*"]});Y.patternProperties={};for(let _ of G)Y.patternProperties[_.source]=M}else{if(W.target==="draft-07"||W.target==="draft-2020-12")Y.propertyNames=YH(J.keyType,W,{...X,path:[...X.path,"propertyNames"]});Y.additionalProperties=YH(J.valueType,W,{...X,path:[...X.path,"additionalProperties"]})}let D=N._zod.values;if(D){let M=[...D].filter((_)=>typeof _==="string"||typeof _==="number");if(M.length>0)Y.required=M}},c5=(H,W,Q,X)=>{let Y=H._zod.def,J=YH(Y.innerType,W,X),N=W.seen.get(H);if(W.target==="openapi-3.0")N.ref=Y.innerType,Q.nullable=!0;else Q.anyOf=[J,{type:"null"}]},p5=(H,W,Q,X)=>{let Y=H._zod.def;YH(Y.innerType,W,X);let J=W.seen.get(H);J.ref=Y.innerType},d5=(H,W,Q,X)=>{let Y=H._zod.def;YH(Y.innerType,W,X);let J=W.seen.get(H);J.ref=Y.innerType,Q.default=JSON.parse(JSON.stringify(Y.defaultValue))},i5=(H,W,Q,X)=>{let Y=H._zod.def;YH(Y.innerType,W,X);let J=W.seen.get(H);if(J.ref=Y.innerType,W.io==="input")Q._prefault=JSON.parse(JSON.stringify(Y.defaultValue))},o5=(H,W,Q,X)=>{let Y=H._zod.def;YH(Y.innerType,W,X);let J=W.seen.get(H);J.ref=Y.innerType;let N;try{N=Y.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}Q.default=N},n5=(H,W,Q,X)=>{let Y=H._zod.def,J=Y.in._zod.traits.has("$ZodTransform"),N=W.io==="input"?J?Y.out:Y.in:Y.out;YH(N,W,X);let B=W.seen.get(H);B.ref=N},r5=(H,W,Q,X)=>{let Y=H._zod.def;YH(Y.innerType,W,X);let J=W.seen.get(H);J.ref=Y.innerType,Q.readOnly=!0},t5=(H,W,Q,X)=>{let Y=H._zod.def;YH(Y.innerType,W,X);let J=W.seen.get(H);J.ref=Y.innerType},T6=(H,W,Q,X)=>{let Y=H._zod.def;YH(Y.innerType,W,X);let J=W.seen.get(H);J.ref=Y.innerType},s5=(H,W,Q,X)=>{let Y=H._zod.innerType;YH(Y,W,X);let J=W.seen.get(H);J.ref=Y},L6={string:E5,number:A5,boolean:O5,bigint:V5,symbol:U5,null:w5,undefined:z5,void:Z5,never:P5,any:b5,unknown:I5,date:L5,enum:j5,literal:T5,nan:$5,template_literal:R5,file:C5,success:S5,custom:k5,function:g5,transform:x5,map:v5,set:y5,array:h5,object:f5,union:j6,intersection:u5,tuple:l5,record:m5,nullable:c5,nonoptional:p5,default:d5,prefault:i5,catch:o5,pipe:n5,readonly:r5,promise:t5,optional:T6,lazy:s5};function W8(H,W){if("_idmap"in H){let X=H,Y=wW({...W,processors:L6}),J={};for(let G of X._idmap.entries()){let[D,M]=G;YH(M,Y)}let N={},B={registry:X,uri:W?.uri,defs:J};Y.external=B;for(let G of X._idmap.entries()){let[D,M]=G;zW(Y,M),N[D]=ZW(Y,M)}if(Object.keys(J).length>0){let G=Y.target==="draft-2020-12"?"$defs":"definitions";N.__shared={[G]:J}}return{schemas:N}}let Q=wW({...W,processors:L6});return YH(H,Q),zW(Q,H),ZW(Q,H)}class a5{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(H){this.ctx.counter=H}get seen(){return this.ctx.seen}constructor(H){let W=H?.target??"draft-2020-12";if(W==="draft-4")W="draft-04";if(W==="draft-7")W="draft-07";this.ctx=wW({processors:L6,target:W,...H?.metadata&&{metadata:H.metadata},...H?.unrepresentable&&{unrepresentable:H.unrepresentable},...H?.override&&{override:H.override},...H?.io&&{io:H.io}})}process(H,W={path:[],schemaPath:[]}){return YH(H,this.ctx,W)}emit(H,W){if(W){if(W.cycles)this.ctx.cycles=W.cycles;if(W.reused)this.ctx.reused=W.reused;if(W.external)this.ctx.external=W.external}zW(this.ctx,H);let Q=ZW(this.ctx,H),{"~standard":X,...Y}=Q;return Y}}var s2={};var sQ={};o0(sQ,{xor:()=>fK,xid:()=>MK,void:()=>xK,uuidv7:()=>YK,uuidv6:()=>XK,uuidv4:()=>QK,uuid:()=>WK,url:()=>K1,unknown:()=>h,union:()=>S,undefined:()=>gK,ulid:()=>DK,uint64:()=>SK,uint32:()=>$K,tuple:()=>j7,transform:()=>X9,templateLiteral:()=>sK,symbol:()=>kK,superRefine:()=>e7,success:()=>oK,stringbool:()=>JG,stringFormat:()=>ZK,string:()=>K,strictObject:()=>hK,set:()=>cK,refine:()=>a7,record:()=>T,readonly:()=>o7,promise:()=>aK,preprocess:()=>s0,prefault:()=>f7,pipe:()=>x6,partialRecord:()=>uK,optional:()=>f,object:()=>E,number:()=>b,nullish:()=>iK,nullable:()=>HX,null:()=>g0,nonoptional:()=>u7,never:()=>Q9,nativeEnum:()=>pK,nanoid:()=>BK,nan:()=>nK,meta:()=>XG,map:()=>mK,mac:()=>FK,looseRecord:()=>lK,looseObject:()=>l,literal:()=>U,lazy:()=>bW,ksuid:()=>qK,keyof:()=>yK,jwt:()=>zK,json:()=>NG,ipv6:()=>EK,ipv4:()=>_K,invertCodec:()=>tK,intersection:()=>A0,int64:()=>CK,int32:()=>TK,int:()=>g6,instanceof:()=>YG,httpUrl:()=>JK,hostname:()=>PK,hex:()=>bK,hash:()=>IK,guid:()=>HK,function:()=>eK,float64:()=>jK,float32:()=>LK,file:()=>dK,exactOptional:()=>g7,enum:()=>t,emoji:()=>NK,email:()=>h6,e164:()=>wK,discriminatedUnion:()=>PW,describe:()=>QG,date:()=>vK,custom:()=>WG,cuid2:()=>GK,cuid:()=>KK,codec:()=>rK,cidrv6:()=>OK,cidrv4:()=>AK,check:()=>HG,catch:()=>c7,boolean:()=>R,bigint:()=>RK,base64url:()=>UK,base64:()=>VK,array:()=>V,any:()=>W9,_function:()=>eK,_default:()=>y7,_ZodString:()=>v6,ZodXor:()=>P7,ZodXID:()=>p6,ZodVoid:()=>z7,ZodUnknown:()=>U7,ZodUnion:()=>JX,ZodUndefined:()=>A7,ZodUUID:()=>k0,ZodURL:()=>QX,ZodULID:()=>c6,ZodType:()=>HH,ZodTuple:()=>L7,ZodTransform:()=>S7,ZodTemplateLiteral:()=>n7,ZodSymbol:()=>E7,ZodSuccess:()=>l7,ZodStringFormat:()=>KH,ZodString:()=>B1,ZodSet:()=>$7,ZodRecord:()=>J1,ZodReadonly:()=>i7,ZodPromise:()=>t7,ZodPreprocess:()=>d7,ZodPrefault:()=>h7,ZodPipe:()=>NX,ZodOptional:()=>Y9,ZodObject:()=>YX,ZodNumberFormat:()=>Q8,ZodNumber:()=>D1,ZodNullable:()=>x7,ZodNull:()=>O7,ZodNonOptional:()=>J9,ZodNever:()=>w7,ZodNanoID:()=>u6,ZodNaN:()=>p7,ZodMap:()=>T7,ZodMAC:()=>F7,ZodLiteral:()=>R7,ZodLazy:()=>r7,ZodKSUID:()=>d6,ZodJWT:()=>e6,ZodIntersection:()=>I7,ZodIPv6:()=>o6,ZodIPv4:()=>i6,ZodGUID:()=>eQ,ZodFunction:()=>s7,ZodFile:()=>C7,ZodExactOptional:()=>k7,ZodEnum:()=>N1,ZodEmoji:()=>f6,ZodEmail:()=>y6,ZodE164:()=>a6,ZodDiscriminatedUnion:()=>b7,ZodDefault:()=>v7,ZodDate:()=>XX,ZodCustomStringFormat:()=>G1,ZodCustom:()=>KX,ZodCodec:()=>BX,ZodCatch:()=>m7,ZodCUID2:()=>m6,ZodCUID:()=>l6,ZodCIDRv6:()=>r6,ZodCIDRv4:()=>n6,ZodBoolean:()=>M1,ZodBigIntFormat:()=>H9,ZodBigInt:()=>q1,ZodBase64URL:()=>s6,ZodBase64:()=>t6,ZodArray:()=>Z7,ZodAny:()=>V7});var $6={};o0($6,{uppercase:()=>o8,trim:()=>e8,toUpperCase:()=>W1,toLowerCase:()=>H1,startsWith:()=>r8,slugify:()=>Q1,size:()=>aW,regex:()=>d8,property:()=>I6,positive:()=>z6,overwrite:()=>E0,normalize:()=>a8,nonpositive:()=>P6,nonnegative:()=>b6,negative:()=>Z6,multipleOf:()=>VW,minSize:()=>S0,minLength:()=>r0,mime:()=>s8,maxSize:()=>UW,maxLength:()=>eW,lte:()=>Q0,lt:()=>R0,lowercase:()=>i8,length:()=>H8,includes:()=>n8,gte:()=>lH,gt:()=>C0,endsWith:()=>t8});var X0={};o0(X0,{time:()=>W7,duration:()=>Q7,datetime:()=>e5,date:()=>H7,ZodISOTime:()=>S6,ZodISODuration:()=>k6,ZodISODateTime:()=>R6,ZodISODate:()=>C6});var R6=O("ZodISODateTime",(H,W)=>{T3.init(H,W),KH.init(H,W)});function e5(H){return kN(R6,H)}var C6=O("ZodISODate",(H,W)=>{$3.init(H,W),KH.init(H,W)});function H7(H){return gN(C6,H)}var S6=O("ZodISOTime",(H,W)=>{R3.init(H,W),KH.init(H,W)});function W7(H){return xN(S6,H)}var k6=O("ZodISODuration",(H,W)=>{C3.init(H,W),KH.init(H,W)});function Q7(H){return vN(k6,H)}var a2=(H,W)=>{hQ.init(H,W),H.name="ZodError",Object.defineProperties(H,{format:{value:(Q)=>uQ(H,Q)},flatten:{value:(Q)=>fQ(H,Q)},addIssue:{value:(Q)=>{H.issues.push(Q),H.message=JSON.stringify(H.issues,y8,2)}},addIssues:{value:(Q)=>{H.issues.push(...Q),H.message=JSON.stringify(H.issues,y8,2)}},isEmpty:{get(){return H.issues.length===0}}})},$_=O("ZodError",a2),nH=O("ZodError",a2,{Parent:Error});var X7=u8(nH),Y7=l8(nH),aQ=m8(nH),J7=c8(nH),N7=k4(nH),B7=g4(nH),K7=x4(nH),G7=v4(nH),D7=y4(nH),M7=h4(nH),q7=f4(nH),_7=u4(nH);var e2=new WeakMap;function WX(H,W,Q){let X=Object.getPrototypeOf(H),Y=e2.get(X);if(!Y)Y=new Set,e2.set(X,Y);if(Y.has(W))return;Y.add(W);for(let J in Q){let N=Q[J];Object.defineProperty(X,J,{configurable:!0,enumerable:!1,get(){let B=N.bind(this);return Object.defineProperty(this,J,{configurable:!0,writable:!0,enumerable:!0,value:B}),B},set(B){Object.defineProperty(this,J,{configurable:!0,writable:!0,enumerable:!0,value:B})}})}}var HH=O("ZodType",(H,W)=>{return a.init(H,W),Object.assign(H["~standard"],{jsonSchema:{input:Y1(H,"input"),output:Y1(H,"output")}}),H.toJSONSchema=F5(H,{}),H.def=W,H.type=W.type,Object.defineProperty(H,"_def",{value:W}),H.parse=(Q,X)=>X7(H,Q,X,{callee:H.parse}),H.safeParse=(Q,X)=>aQ(H,Q,X),H.parseAsync=async(Q,X)=>Y7(H,Q,X,{callee:H.parseAsync}),H.safeParseAsync=async(Q,X)=>J7(H,Q,X),H.spa=H.safeParseAsync,H.encode=(Q,X)=>N7(H,Q,X),H.decode=(Q,X)=>B7(H,Q,X),H.encodeAsync=async(Q,X)=>K7(H,Q,X),H.decodeAsync=async(Q,X)=>G7(H,Q,X),H.safeEncode=(Q,X)=>D7(H,Q,X),H.safeDecode=(Q,X)=>M7(H,Q,X),H.safeEncodeAsync=async(Q,X)=>q7(H,Q,X),H.safeDecodeAsync=async(Q,X)=>_7(H,Q,X),WX(H,"ZodType",{check(...Q){let X=this.def;return this.clone(s.mergeDefs(X,{checks:[...X.checks??[],...Q.map((Y)=>typeof Y==="function"?{_zod:{check:Y,def:{check:"custom"},onattach:[]}}:Y)]}),{parent:!0})},with(...Q){return this.check(...Q)},clone(Q,X){return fH(this,Q,X)},brand(){return this},register(Q,X){return Q.add(this,X),this},refine(Q,X){return this.check(a7(Q,X))},superRefine(Q,X){return this.check(e7(Q,X))},overwrite(Q){return this.check(E0(Q))},optional(){return f(this)},exactOptional(){return g7(this)},nullable(){return HX(this)},nullish(){return f(HX(this))},nonoptional(Q){return u7(this,Q)},array(){return V(this)},or(Q){return S([this,Q])},and(Q){return A0(this,Q)},transform(Q){return x6(this,X9(Q))},default(Q){return y7(this,Q)},prefault(Q){return f7(this,Q)},catch(Q){return c7(this,Q)},pipe(Q){return x6(this,Q)},readonly(){return o7(this)},describe(Q){let X=this.clone();return LH.add(X,{description:Q}),X},meta(...Q){if(Q.length===0)return LH.get(this);let X=this.clone();return LH.add(X,Q[0]),X},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(Q){return Q(this)}}),Object.defineProperty(H,"description",{get(){return LH.get(H)?.description},configurable:!0}),H}),v6=O("_ZodString",(H,W)=>{sW.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(X,Y,J)=>E5(H,X,Y,J);let Q=H._zod.bag;H.format=Q.format??null,H.minLength=Q.minimum??null,H.maxLength=Q.maximum??null,WX(H,"_ZodString",{regex(...X){return this.check(d8(...X))},includes(...X){return this.check(n8(...X))},startsWith(...X){return this.check(r8(...X))},endsWith(...X){return this.check(t8(...X))},min(...X){return this.check(r0(...X))},max(...X){return this.check(eW(...X))},length(...X){return this.check(H8(...X))},nonempty(...X){return this.check(r0(1,...X))},lowercase(X){return this.check(i8(X))},uppercase(X){return this.check(o8(X))},trim(){return this.check(e8())},normalize(...X){return this.check(a8(...X))},toLowerCase(){return this.check(H1())},toUpperCase(){return this.check(W1())},slugify(){return this.check(Q1())}})}),B1=O("ZodString",(H,W)=>{sW.init(H,W),v6.init(H,W),H.email=(Q)=>H.check(W6(y6,Q)),H.url=(Q)=>H.check(tQ(QX,Q)),H.jwt=(Q)=>H.check(w6(e6,Q)),H.emoji=(Q)=>H.check(N6(f6,Q)),H.guid=(Q)=>H.check(rQ(eQ,Q)),H.uuid=(Q)=>H.check(Q6(k0,Q)),H.uuidv4=(Q)=>H.check(X6(k0,Q)),H.uuidv6=(Q)=>H.check(Y6(k0,Q)),H.uuidv7=(Q)=>H.check(J6(k0,Q)),H.nanoid=(Q)=>H.check(B6(u6,Q)),H.guid=(Q)=>H.check(rQ(eQ,Q)),H.cuid=(Q)=>H.check(K6(l6,Q)),H.cuid2=(Q)=>H.check(G6(m6,Q)),H.ulid=(Q)=>H.check(D6(c6,Q)),H.base64=(Q)=>H.check(O6(t6,Q)),H.base64url=(Q)=>H.check(V6(s6,Q)),H.xid=(Q)=>H.check(M6(p6,Q)),H.ksuid=(Q)=>H.check(q6(d6,Q)),H.ipv4=(Q)=>H.check(_6(i6,Q)),H.ipv6=(Q)=>H.check(F6(o6,Q)),H.cidrv4=(Q)=>H.check(E6(n6,Q)),H.cidrv6=(Q)=>H.check(A6(r6,Q)),H.e164=(Q)=>H.check(U6(a6,Q)),H.datetime=(Q)=>H.check(e5(Q)),H.date=(Q)=>H.check(H7(Q)),H.time=(Q)=>H.check(W7(Q)),H.duration=(Q)=>H.check(Q7(Q))});function K(H){return $N(B1,H)}var KH=O("ZodStringFormat",(H,W)=>{BH.init(H,W),v6.init(H,W)}),y6=O("ZodEmail",(H,W)=>{U3.init(H,W),KH.init(H,W)});function h6(H){return W6(y6,H)}var eQ=O("ZodGUID",(H,W)=>{O3.init(H,W),KH.init(H,W)});function HK(H){return rQ(eQ,H)}var k0=O("ZodUUID",(H,W)=>{V3.init(H,W),KH.init(H,W)});function WK(H){return Q6(k0,H)}function QK(H){return X6(k0,H)}function XK(H){return Y6(k0,H)}function YK(H){return J6(k0,H)}var QX=O("ZodURL",(H,W)=>{w3.init(H,W),KH.init(H,W)});function K1(H){return tQ(QX,H)}function JK(H){return tQ(QX,{protocol:W0.httpProtocol,hostname:W0.domain,...s.normalizeParams(H)})}var f6=O("ZodEmoji",(H,W)=>{z3.init(H,W),KH.init(H,W)});function NK(H){return N6(f6,H)}var u6=O("ZodNanoID",(H,W)=>{Z3.init(H,W),KH.init(H,W)});function BK(H){return B6(u6,H)}var l6=O("ZodCUID",(H,W)=>{P3.init(H,W),KH.init(H,W)});function KK(H){return K6(l6,H)}var m6=O("ZodCUID2",(H,W)=>{b3.init(H,W),KH.init(H,W)});function GK(H){return G6(m6,H)}var c6=O("ZodULID",(H,W)=>{I3.init(H,W),KH.init(H,W)});function DK(H){return D6(c6,H)}var p6=O("ZodXID",(H,W)=>{L3.init(H,W),KH.init(H,W)});function MK(H){return M6(p6,H)}var d6=O("ZodKSUID",(H,W)=>{j3.init(H,W),KH.init(H,W)});function qK(H){return q6(d6,H)}var i6=O("ZodIPv4",(H,W)=>{S3.init(H,W),KH.init(H,W)});function _K(H){return _6(i6,H)}var F7=O("ZodMAC",(H,W)=>{g3.init(H,W),KH.init(H,W)});function FK(H){return CN(F7,H)}var o6=O("ZodIPv6",(H,W)=>{k3.init(H,W),KH.init(H,W)});function EK(H){return F6(o6,H)}var n6=O("ZodCIDRv4",(H,W)=>{x3.init(H,W),KH.init(H,W)});function AK(H){return E6(n6,H)}var r6=O("ZodCIDRv6",(H,W)=>{v3.init(H,W),KH.init(H,W)});function OK(H){return A6(r6,H)}var t6=O("ZodBase64",(H,W)=>{h3.init(H,W),KH.init(H,W)});function VK(H){return O6(t6,H)}var s6=O("ZodBase64URL",(H,W)=>{f3.init(H,W),KH.init(H,W)});function UK(H){return V6(s6,H)}var a6=O("ZodE164",(H,W)=>{u3.init(H,W),KH.init(H,W)});function wK(H){return U6(a6,H)}var e6=O("ZodJWT",(H,W)=>{l3.init(H,W),KH.init(H,W)});function zK(H){return w6(e6,H)}var G1=O("ZodCustomStringFormat",(H,W)=>{m3.init(H,W),KH.init(H,W)});function ZK(H,W,Q={}){return X1(G1,H,W,Q)}function PK(H){return X1(G1,"hostname",W0.hostname,H)}function bK(H){return X1(G1,"hex",W0.hex,H)}function IK(H,W){let Q=W?.enc??"hex",X=`${H}_${Q}`,Y=W0[X];if(!Y)throw Error(`Unrecognized hash format: ${X}`);return X1(G1,X,Y,W)}var D1=O("ZodNumber",(H,W)=>{r4.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(X,Y,J)=>A5(H,X,Y,J),WX(H,"ZodNumber",{gt(X,Y){return this.check(C0(X,Y))},gte(X,Y){return this.check(lH(X,Y))},min(X,Y){return this.check(lH(X,Y))},lt(X,Y){return this.check(R0(X,Y))},lte(X,Y){return this.check(Q0(X,Y))},max(X,Y){return this.check(Q0(X,Y))},int(X){return this.check(g6(X))},safe(X){return this.check(g6(X))},positive(X){return this.check(C0(0,X))},nonnegative(X){return this.check(lH(0,X))},negative(X){return this.check(R0(0,X))},nonpositive(X){return this.check(Q0(0,X))},multipleOf(X,Y){return this.check(VW(X,Y))},step(X,Y){return this.check(VW(X,Y))},finite(){return this}});let Q=H._zod.bag;H.minValue=Math.max(Q.minimum??Number.NEGATIVE_INFINITY,Q.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,H.maxValue=Math.min(Q.maximum??Number.POSITIVE_INFINITY,Q.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,H.isInt=(Q.format??"").includes("int")||Number.isSafeInteger(Q.multipleOf??0.5),H.isFinite=!0,H.format=Q.format??null});function b(H){return yN(D1,H)}var Q8=O("ZodNumberFormat",(H,W)=>{c3.init(H,W),D1.init(H,W)});function g6(H){return fN(Q8,H)}function LK(H){return uN(Q8,H)}function jK(H){return lN(Q8,H)}function TK(H){return mN(Q8,H)}function $K(H){return cN(Q8,H)}var M1=O("ZodBoolean",(H,W)=>{pQ.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>O5(H,Q,X,Y)});function R(H){return pN(M1,H)}var q1=O("ZodBigInt",(H,W)=>{t4.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(X,Y,J)=>V5(H,X,Y,J),H.gte=(X,Y)=>H.check(lH(X,Y)),H.min=(X,Y)=>H.check(lH(X,Y)),H.gt=(X,Y)=>H.check(C0(X,Y)),H.gte=(X,Y)=>H.check(lH(X,Y)),H.min=(X,Y)=>H.check(lH(X,Y)),H.lt=(X,Y)=>H.check(R0(X,Y)),H.lte=(X,Y)=>H.check(Q0(X,Y)),H.max=(X,Y)=>H.check(Q0(X,Y)),H.positive=(X)=>H.check(C0(BigInt(0),X)),H.negative=(X)=>H.check(R0(BigInt(0),X)),H.nonpositive=(X)=>H.check(Q0(BigInt(0),X)),H.nonnegative=(X)=>H.check(lH(BigInt(0),X)),H.multipleOf=(X,Y)=>H.check(VW(X,Y));let Q=H._zod.bag;H.minValue=Q.minimum??null,H.maxValue=Q.maximum??null,H.format=Q.format??null});function RK(H){return iN(q1,H)}var H9=O("ZodBigIntFormat",(H,W)=>{p3.init(H,W),q1.init(H,W)});function CK(H){return nN(H9,H)}function SK(H){return rN(H9,H)}var E7=O("ZodSymbol",(H,W)=>{d3.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>U5(H,Q,X,Y)});function kK(H){return tN(E7,H)}var A7=O("ZodUndefined",(H,W)=>{i3.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>z5(H,Q,X,Y)});function gK(H){return sN(A7,H)}var O7=O("ZodNull",(H,W)=>{o3.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>w5(H,Q,X,Y)});function g0(H){return aN(O7,H)}var V7=O("ZodAny",(H,W)=>{n3.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>b5(H,Q,X,Y)});function W9(){return eN(V7)}var U7=O("ZodUnknown",(H,W)=>{r3.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>I5(H,Q,X,Y)});function h(){return H5(U7)}var w7=O("ZodNever",(H,W)=>{t3.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>P5(H,Q,X,Y)});function Q9(H){return W5(w7,H)}var z7=O("ZodVoid",(H,W)=>{s3.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>Z5(H,Q,X,Y)});function xK(H){return Q5(z7,H)}var XX=O("ZodDate",(H,W)=>{a3.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(X,Y,J)=>L5(H,X,Y,J),H.min=(X,Y)=>H.check(lH(X,Y)),H.max=(X,Y)=>H.check(Q0(X,Y));let Q=H._zod.bag;H.minDate=Q.minimum?new Date(Q.minimum):null,H.maxDate=Q.maximum?new Date(Q.maximum):null});function vK(H){return X5(XX,H)}var Z7=O("ZodArray",(H,W)=>{e3.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>h5(H,Q,X,Y),H.element=W.element,WX(H,"ZodArray",{min(Q,X){return this.check(r0(Q,X))},nonempty(Q){return this.check(r0(1,Q))},max(Q,X){return this.check(eW(Q,X))},length(Q,X){return this.check(H8(Q,X))},unwrap(){return this.element}})});function V(H,W){return N5(Z7,H,W)}function yK(H){let W=H._zod.def.shape;return t(Object.keys(W))}var YX=O("ZodObject",(H,W)=>{HN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>f5(H,Q,X,Y),s.defineLazy(H,"shape",()=>{return W.shape}),WX(H,"ZodObject",{keyof(){return t(Object.keys(this._zod.def.shape))},catchall(Q){return this.clone({...this._zod.def,catchall:Q})},passthrough(){return this.clone({...this._zod.def,catchall:h()})},loose(){return this.clone({...this._zod.def,catchall:h()})},strict(){return this.clone({...this._zod.def,catchall:Q9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(Q){return s.extend(this,Q)},safeExtend(Q){return s.safeExtend(this,Q)},merge(Q){return s.merge(this,Q)},pick(Q){return s.pick(this,Q)},omit(Q){return s.omit(this,Q)},partial(...Q){return s.partial(Y9,this,Q[0])},required(...Q){return s.required(J9,this,Q[0])}})});function E(H,W){let Q={type:"object",shape:H??{},...s.normalizeParams(W)};return new YX(Q)}function hK(H,W){return new YX({type:"object",shape:H,catchall:Q9(),...s.normalizeParams(W)})}function l(H,W){return new YX({type:"object",shape:H,catchall:h(),...s.normalizeParams(W)})}var JX=O("ZodUnion",(H,W)=>{dQ.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>j6(H,Q,X,Y),H.options=W.options});function S(H,W){return new JX({type:"union",options:H,...s.normalizeParams(W)})}var P7=O("ZodXor",(H,W)=>{JX.init(H,W),WN.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>j6(H,Q,X,Y),H.options=W.options});function fK(H,W){return new P7({type:"union",options:H,inclusive:!1,...s.normalizeParams(W)})}var b7=O("ZodDiscriminatedUnion",(H,W)=>{JX.init(H,W),QN.init(H,W)});function PW(H,W,Q){return new b7({type:"union",options:W,discriminator:H,...s.normalizeParams(Q)})}var I7=O("ZodIntersection",(H,W)=>{XN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>u5(H,Q,X,Y)});function A0(H,W){return new I7({type:"intersection",left:H,right:W})}var L7=O("ZodTuple",(H,W)=>{s4.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>l5(H,Q,X,Y),H.rest=(Q)=>H.clone({...H._zod.def,rest:Q})});function j7(H,W,Q){let X=W instanceof a,Y=X?Q:W;return new L7({type:"tuple",items:H,rest:X?W:null,...s.normalizeParams(Y)})}var J1=O("ZodRecord",(H,W)=>{YN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>m5(H,Q,X,Y),H.keyType=W.keyType,H.valueType=W.valueType});function T(H,W,Q){if(!W||!W._zod)return new J1({type:"record",keyType:K(),valueType:H,...s.normalizeParams(W)});return new J1({type:"record",keyType:H,valueType:W,...s.normalizeParams(Q)})}function uK(H,W,Q){let X=fH(H);return X._zod.values=void 0,new J1({type:"record",keyType:X,valueType:W,...s.normalizeParams(Q)})}function lK(H,W,Q){return new J1({type:"record",keyType:H,valueType:W,mode:"loose",...s.normalizeParams(Q)})}var T7=O("ZodMap",(H,W)=>{JN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>v5(H,Q,X,Y),H.keyType=W.keyType,H.valueType=W.valueType,H.min=(...Q)=>H.check(S0(...Q)),H.nonempty=(Q)=>H.check(S0(1,Q)),H.max=(...Q)=>H.check(UW(...Q)),H.size=(...Q)=>H.check(aW(...Q))});function mK(H,W,Q){return new T7({type:"map",keyType:H,valueType:W,...s.normalizeParams(Q)})}var $7=O("ZodSet",(H,W)=>{NN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>y5(H,Q,X,Y),H.min=(...Q)=>H.check(S0(...Q)),H.nonempty=(Q)=>H.check(S0(1,Q)),H.max=(...Q)=>H.check(UW(...Q)),H.size=(...Q)=>H.check(aW(...Q))});function cK(H,W){return new $7({type:"set",valueType:H,...s.normalizeParams(W)})}var N1=O("ZodEnum",(H,W)=>{BN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(X,Y,J)=>j5(H,X,Y,J),H.enum=W.entries,H.options=Object.values(W.entries);let Q=new Set(Object.keys(W.entries));H.extract=(X,Y)=>{let J={};for(let N of X)if(Q.has(N))J[N]=W.entries[N];else throw Error(`Key ${N} not found in enum`);return new N1({...W,checks:[],...s.normalizeParams(Y),entries:J})},H.exclude=(X,Y)=>{let J={...W.entries};for(let N of X)if(Q.has(N))delete J[N];else throw Error(`Key ${N} not found in enum`);return new N1({...W,checks:[],...s.normalizeParams(Y),entries:J})}});function t(H,W){let Q=Array.isArray(H)?Object.fromEntries(H.map((X)=>[X,X])):H;return new N1({type:"enum",entries:Q,...s.normalizeParams(W)})}function pK(H,W){return new N1({type:"enum",entries:H,...s.normalizeParams(W)})}var R7=O("ZodLiteral",(H,W)=>{KN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>T5(H,Q,X,Y),H.values=new Set(W.values),Object.defineProperty(H,"value",{get(){if(W.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return W.values[0]}})});function U(H,W){return new R7({type:"literal",values:Array.isArray(H)?H:[H],...s.normalizeParams(W)})}var C7=O("ZodFile",(H,W)=>{GN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>C5(H,Q,X,Y),H.min=(Q,X)=>H.check(S0(Q,X)),H.max=(Q,X)=>H.check(UW(Q,X)),H.mime=(Q,X)=>H.check(s8(Array.isArray(Q)?Q:[Q],X))});function dK(H){return B5(C7,H)}var S7=O("ZodTransform",(H,W)=>{DN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>x5(H,Q,X,Y),H._zod.parse=(Q,X)=>{if(X.direction==="backward")throw new nW(H.constructor.name);Q.addIssue=(J)=>{if(typeof J==="string")Q.issues.push(s.issue(J,Q.value,W));else{let N=J;if(N.fatal)N.continue=!1;N.code??(N.code="custom"),N.input??(N.input=Q.value),N.inst??(N.inst=H),Q.issues.push(s.issue(N))}};let Y=W.transform(Q.value,Q);if(Y instanceof Promise)return Y.then((J)=>{return Q.value=J,Q.fallback=!0,Q});return Q.value=Y,Q.fallback=!0,Q}});function X9(H){return new S7({type:"transform",transform:H})}var Y9=O("ZodOptional",(H,W)=>{a4.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>T6(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType});function f(H){return new Y9({type:"optional",innerType:H})}var k7=O("ZodExactOptional",(H,W)=>{MN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>T6(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType});function g7(H){return new k7({type:"optional",innerType:H})}var x7=O("ZodNullable",(H,W)=>{qN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>c5(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType});function HX(H){return new x7({type:"nullable",innerType:H})}function iK(H){return f(HX(H))}var v7=O("ZodDefault",(H,W)=>{_N.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>d5(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType,H.removeDefault=H.unwrap});function y7(H,W){return new v7({type:"default",innerType:H,get defaultValue(){return typeof W==="function"?W():s.shallowClone(W)}})}var h7=O("ZodPrefault",(H,W)=>{FN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>i5(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType});function f7(H,W){return new h7({type:"prefault",innerType:H,get defaultValue(){return typeof W==="function"?W():s.shallowClone(W)}})}var J9=O("ZodNonOptional",(H,W)=>{EN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>p5(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType});function u7(H,W){return new J9({type:"nonoptional",innerType:H,...s.normalizeParams(W)})}var l7=O("ZodSuccess",(H,W)=>{AN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>S5(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType});function oK(H){return new l7({type:"success",innerType:H})}var m7=O("ZodCatch",(H,W)=>{ON.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>o5(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType,H.removeCatch=H.unwrap});function c7(H,W){return new m7({type:"catch",innerType:H,catchValue:typeof W==="function"?W:()=>W})}var p7=O("ZodNaN",(H,W)=>{VN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>$5(H,Q,X,Y)});function nK(H){return J5(p7,H)}var NX=O("ZodPipe",(H,W)=>{e4.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>n5(H,Q,X,Y),H.in=W.in,H.out=W.out});function x6(H,W){return new NX({type:"pipe",in:H,out:W})}var BX=O("ZodCodec",(H,W)=>{NX.init(H,W),iQ.init(H,W)});function rK(H,W,Q){return new BX({type:"pipe",in:H,out:W,transform:Q.decode,reverseTransform:Q.encode})}function tK(H){let W=H._zod.def;return new BX({type:"pipe",in:W.out,out:W.in,transform:W.reverseTransform,reverseTransform:W.transform})}var d7=O("ZodPreprocess",(H,W)=>{NX.init(H,W),UN.init(H,W)}),i7=O("ZodReadonly",(H,W)=>{wN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>r5(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType});function o7(H){return new i7({type:"readonly",innerType:H})}var n7=O("ZodTemplateLiteral",(H,W)=>{zN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>R5(H,Q,X,Y)});function sK(H,W){return new n7({type:"template_literal",parts:H,...s.normalizeParams(W)})}var r7=O("ZodLazy",(H,W)=>{bN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>s5(H,Q,X,Y),H.unwrap=()=>H._zod.def.getter()});function bW(H){return new r7({type:"lazy",getter:H})}var t7=O("ZodPromise",(H,W)=>{PN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>t5(H,Q,X,Y),H.unwrap=()=>H._zod.def.innerType});function aK(H){return new t7({type:"promise",innerType:H})}var s7=O("ZodFunction",(H,W)=>{ZN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>g5(H,Q,X,Y)});function eK(H){return new s7({type:"function",input:Array.isArray(H?.input)?j7(H?.input):H?.input??V(h()),output:H?.output??h()})}var KX=O("ZodCustom",(H,W)=>{IN.init(H,W),HH.init(H,W),H._zod.processJSONSchema=(Q,X,Y)=>k5(H,Q,X,Y)});function HG(H){let W=new GH({check:"custom"});return W._zod.check=H,W}function WG(H,W){return K5(KX,H??(()=>!0),W)}function a7(H,W={}){return G5(KX,H,W)}function e7(H,W){return D5(H,W)}var QG=M5,XG=q5;function YG(H,W={}){let Q=new KX({type:"custom",check:"custom",fn:(X)=>X instanceof H,abort:!0,...s.normalizeParams(W)});return Q._zod.bag.Class=H,Q._zod.check=(X)=>{if(!(X.value instanceof H))X.issues.push({code:"invalid_type",expected:H.name,input:X.value,inst:Q,path:[...Q._zod.def.path??[]]})},Q}var JG=(...H)=>_5({Codec:BX,Boolean:M1,String:B1},...H);function NG(H){let W=bW(()=>{return S([K(H),b(),R(),g0(),V(W),T(K(),W)])});return W}function s0(H,W){return new d7({type:"pipe",in:X9(H),out:W})}var WB={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function C_(H){AH({customError:H})}function S_(){return AH().customError}var HB;(function(H){})(HB||(HB={}));var C={...sQ,...$6,iso:X0},k_=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"]);function g_(H,W){let Q=H.$schema;if(Q==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(Q==="http://json-schema.org/draft-07/schema#")return"draft-7";if(Q==="http://json-schema.org/draft-04/schema#")return"draft-4";return W??"draft-2020-12"}function x_(H,W){if(!H.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let Q=H.slice(1).split("/").filter(Boolean);if(Q.length===0)return W.rootSchema;let X=W.version==="draft-2020-12"?"$defs":"definitions";if(Q[0]===X){let Y=Q[1];if(!Y||!W.defs[Y])throw Error(`Reference not found: ${H}`);return W.defs[Y]}throw Error(`Reference not found: ${H}`)}function BG(H,W){if(H.not!==void 0){if(typeof H.not==="object"&&Object.keys(H.not).length===0)return C.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(H.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(H.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(H.if!==void 0||H.then!==void 0||H.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(H.dependentSchemas!==void 0||H.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(H.$ref){let Y=H.$ref;if(W.refs.has(Y))return W.refs.get(Y);if(W.processing.has(Y))return C.lazy(()=>{if(!W.refs.has(Y))throw Error(`Circular reference not resolved: ${Y}`);return W.refs.get(Y)});W.processing.add(Y);let J=x_(Y,W),N=CH(J,W);return W.refs.set(Y,N),W.processing.delete(Y),N}if(H.enum!==void 0){let Y=H.enum;if(W.version==="openapi-3.0"&&H.nullable===!0&&Y.length===1&&Y[0]===null)return C.null();if(Y.length===0)return C.never();if(Y.length===1)return C.literal(Y[0]);if(Y.every((N)=>typeof N==="string"))return C.enum(Y);let J=Y.map((N)=>C.literal(N));if(J.length<2)return J[0];return C.union([J[0],J[1],...J.slice(2)])}if(H.const!==void 0)return C.literal(H.const);let Q=H.type;if(Array.isArray(Q)){let Y=Q.map((J)=>{let N={...H,type:J};return BG(N,W)});if(Y.length===0)return C.never();if(Y.length===1)return Y[0];return C.union(Y)}if(!Q)return C.any();let X;switch(Q){case"string":{let Y=C.string();if(H.format){let J=H.format;if(J==="email")Y=Y.check(C.email());else if(J==="uri"||J==="uri-reference")Y=Y.check(C.url());else if(J==="uuid"||J==="guid")Y=Y.check(C.uuid());else if(J==="date-time")Y=Y.check(C.iso.datetime());else if(J==="date")Y=Y.check(C.iso.date());else if(J==="time")Y=Y.check(C.iso.time());else if(J==="duration")Y=Y.check(C.iso.duration());else if(J==="ipv4")Y=Y.check(C.ipv4());else if(J==="ipv6")Y=Y.check(C.ipv6());else if(J==="mac")Y=Y.check(C.mac());else if(J==="cidr")Y=Y.check(C.cidrv4());else if(J==="cidr-v6")Y=Y.check(C.cidrv6());else if(J==="base64")Y=Y.check(C.base64());else if(J==="base64url")Y=Y.check(C.base64url());else if(J==="e164")Y=Y.check(C.e164());else if(J==="jwt")Y=Y.check(C.jwt());else if(J==="emoji")Y=Y.check(C.emoji());else if(J==="nanoid")Y=Y.check(C.nanoid());else if(J==="cuid")Y=Y.check(C.cuid());else if(J==="cuid2")Y=Y.check(C.cuid2());else if(J==="ulid")Y=Y.check(C.ulid());else if(J==="xid")Y=Y.check(C.xid());else if(J==="ksuid")Y=Y.check(C.ksuid())}if(typeof H.minLength==="number")Y=Y.min(H.minLength);if(typeof H.maxLength==="number")Y=Y.max(H.maxLength);if(H.pattern)Y=Y.regex(new RegExp(H.pattern));X=Y;break}case"number":case"integer":{let Y=Q==="integer"?C.number().int():C.number();if(typeof H.minimum==="number")Y=Y.min(H.minimum);if(typeof H.maximum==="number")Y=Y.max(H.maximum);if(typeof H.exclusiveMinimum==="number")Y=Y.gt(H.exclusiveMinimum);else if(H.exclusiveMinimum===!0&&typeof H.minimum==="number")Y=Y.gt(H.minimum);if(typeof H.exclusiveMaximum==="number")Y=Y.lt(H.exclusiveMaximum);else if(H.exclusiveMaximum===!0&&typeof H.maximum==="number")Y=Y.lt(H.maximum);if(typeof H.multipleOf==="number")Y=Y.multipleOf(H.multipleOf);X=Y;break}case"boolean":{X=C.boolean();break}case"null":{X=C.null();break}case"object":{let Y={},J=H.properties||{},N=new Set(H.required||[]);for(let[G,D]of Object.entries(J)){let M=CH(D,W);Y[G]=N.has(G)?M:M.optional()}if(H.propertyNames){let G=CH(H.propertyNames,W),D=H.additionalProperties&&typeof H.additionalProperties==="object"?CH(H.additionalProperties,W):C.any();if(Object.keys(Y).length===0){X=C.record(G,D);break}let M=C.object(Y).passthrough(),_=C.looseRecord(G,D);X=C.intersection(M,_);break}if(H.patternProperties){let G=H.patternProperties,D=Object.keys(G),M=[];for(let F of D){let A=CH(G[F],W),w=C.string().regex(new RegExp(F));M.push(C.looseRecord(w,A))}let _=[];if(Object.keys(Y).length>0)_.push(C.object(Y).passthrough());if(_.push(...M),_.length===0)X=C.object({}).passthrough();else if(_.length===1)X=_[0];else{let F=C.intersection(_[0],_[1]);for(let A=2;A<_.length;A++)F=C.intersection(F,_[A]);X=F}break}let B=C.object(Y);if(H.additionalProperties===!1)X=B.strict();else if(typeof H.additionalProperties==="object")X=B.catchall(CH(H.additionalProperties,W));else X=B.passthrough();break}case"array":{let{prefixItems:Y,items:J}=H;if(Y&&Array.isArray(Y)){let N=Y.map((G)=>CH(G,W)),B=J&&typeof J==="object"&&!Array.isArray(J)?CH(J,W):void 0;if(B)X=C.tuple(N).rest(B);else X=C.tuple(N);if(typeof H.minItems==="number")X=X.check(C.minLength(H.minItems));if(typeof H.maxItems==="number")X=X.check(C.maxLength(H.maxItems))}else if(Array.isArray(J)){let N=J.map((G)=>CH(G,W)),B=H.additionalItems&&typeof H.additionalItems==="object"?CH(H.additionalItems,W):void 0;if(B)X=C.tuple(N).rest(B);else X=C.tuple(N);if(typeof H.minItems==="number")X=X.check(C.minLength(H.minItems));if(typeof H.maxItems==="number")X=X.check(C.maxLength(H.maxItems))}else if(J!==void 0){let N=CH(J,W),B=C.array(N);if(typeof H.minItems==="number")B=B.min(H.minItems);if(typeof H.maxItems==="number")B=B.max(H.maxItems);X=B}else X=C.array(C.any());break}default:throw Error(`Unsupported type: ${Q}`)}return X}function CH(H,W){if(typeof H==="boolean")return H?C.any():C.never();let Q=BG(H,W),X=H.type||H.enum!==void 0||H.const!==void 0;if(H.anyOf&&Array.isArray(H.anyOf)){let B=H.anyOf.map((D)=>CH(D,W)),G=C.union(B);Q=X?C.intersection(Q,G):G}if(H.oneOf&&Array.isArray(H.oneOf)){let B=H.oneOf.map((D)=>CH(D,W)),G=C.xor(B);Q=X?C.intersection(Q,G):G}if(H.allOf&&Array.isArray(H.allOf))if(H.allOf.length===0)Q=X?Q:C.any();else{let B=X?Q:CH(H.allOf[0],W),G=X?0:1;for(let D=G;D<H.allOf.length;D++)B=C.intersection(B,CH(H.allOf[D],W));Q=B}if(H.nullable===!0&&W.version==="openapi-3.0")Q=C.nullable(Q);if(H.readOnly===!0)Q=C.readonly(Q);if(H.default!==void 0)Q=Q.default(H.default);let Y={},J=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let B of J)if(B in H)Y[B]=H[B];let N=["contentEncoding","contentMediaType","contentSchema"];for(let B of N)if(B in H)Y[B]=H[B];for(let B of Object.keys(H))if(!k_.has(B))Y[B]=H[B];if(Object.keys(Y).length>0)W.registry.add(Q,Y);if(H.description)Q=Q.describe(H.description);return Q}function KG(H,W){if(typeof H==="boolean")return H?C.any():C.never();let Q;try{Q=JSON.parse(JSON.stringify(H))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let X=g_(Q,W?.defaultTarget),Y=Q.$defs||Q.definitions||{},J={version:X,defs:Y,refs:new Map,processing:new Set,rootSchema:Q,registry:W?.registry??LH};return CH(Q,J)}var GX={};o0(GX,{string:()=>v_,number:()=>y_,date:()=>u_,boolean:()=>h_,bigint:()=>f_});function v_(H){return RN(B1,H)}function y_(H){return hN(D1,H)}function h_(H){return dN(M1,H)}function f_(H){return oN(q1,H)}function u_(H){return Y5(XX,H)}AH(oQ());var _1="2025-11-25";var N9=[_1,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],B9="io.modelcontextprotocol/related-task",e0="io.modelcontextprotocol/protocolVersion",F1="io.modelcontextprotocol/clientInfo",HW="io.modelcontextprotocol/serverInfo",X8="io.modelcontextprotocol/clientCapabilities",DX="io.modelcontextprotocol/subscriptionId",E1="io.modelcontextprotocol/logLevel";var Y8="2.0";var a0=bW(()=>S([K(),b(),R(),g0(),T(K(),a0),V(a0)])),qH=T(K(),a0),K9=V(a0),A1=S([K(),b().int()]),O1=K(),MX=E({ttl:b().optional()}),qX=E({taskId:K()}),V1=l({progressToken:A1.optional(),[B9]:qX.optional()}),bH=E({_meta:V1.optional()}),LW=bH.extend({task:MX.optional()}),_H=E({method:K(),params:bH.loose().optional()}),SH=E({_meta:V1.optional()}),jH=E({method:K(),params:SH.loose().optional()}),U1=l({get[HW](){return v0.optional().catch(void 0)}}),FH=l({_meta:U1.optional()}),O0=S([K(),b().int()]),w1=E({jsonrpc:U(Y8),id:O0,..._H.shape}).strict(),z1=E({jsonrpc:U(Y8),...jH.shape}).strict(),J8=E({jsonrpc:U(Y8),id:O0,result:FH}).strict(),N8=E({jsonrpc:U(Y8),id:O0.optional(),error:E({code:b().int(),message:K(),data:h().optional()})}).strict(),V0=S([w1,z1,J8,N8]),G9=S([J8,N8]),jW=FH.strict(),_X=SH.extend({requestId:O0.optional(),reason:K().optional()}),Z1=jH.extend({method:U("notifications/cancelled"),params:_X}),FX=E({src:K(),mimeType:K().optional(),sizes:V(K()).optional(),theme:t(["light","dark"]).optional()}),WW=E({icons:V(FX).optional()}),x0=E({name:K(),title:K().optional()}),v0=x0.extend({...x0.shape,...WW.shape,version:K(),websiteUrl:K().optional(),description:K().optional()}),m_=A0(E({applyDefaults:R().optional()}),qH),c_=s0((H)=>{if(H&&typeof H==="object"&&!Array.isArray(H)&&Object.keys(H).length===0)return{form:{}};return H},A0(E({form:m_.optional(),url:qH.optional()}),qH.optional())),D9=l({list:qH.optional(),cancel:qH.optional(),requests:l({sampling:l({createMessage:qH.optional()}).optional(),elicitation:l({create:qH.optional()}).optional()}).optional()}),M9=l({list:qH.optional(),cancel:qH.optional(),requests:l({tools:l({call:qH.optional()}).optional()}).optional()}),EX=E({experimental:T(K(),qH).optional(),sampling:E({context:qH.optional(),tools:qH.optional()}).optional(),elicitation:c_.optional(),roots:E({listChanged:R().optional()}).optional(),tasks:D9.optional(),extensions:T(K(),qH).optional()}),AX=bH.extend({protocolVersion:K(),capabilities:EX,clientInfo:v0}),P1=_H.extend({method:U("initialize"),params:AX}),b1=E({experimental:T(K(),qH).optional(),logging:qH.optional(),completions:qH.optional(),prompts:E({listChanged:R().optional()}).optional(),resources:E({subscribe:R().optional(),listChanged:R().optional()}).optional(),tools:E({listChanged:R().optional()}).optional(),tasks:M9.optional(),extensions:T(K(),qH).optional()}),OX=FH.extend({protocolVersion:K(),capabilities:b1,serverInfo:v0,instructions:K().optional()}),I1=jH.extend({method:U("notifications/initialized"),params:SH.optional()}),VX=_H.extend({method:U("server/discover"),params:bH.optional()}),TW=FH.extend({supportedVersions:V(K()),capabilities:b1,instructions:K().optional()}),L1=_H.extend({method:U("ping"),params:bH.optional()}),UX=E({progress:b(),total:f(b()),message:f(K())}),wX=E({...SH.shape,...UX.shape,progressToken:A1}),j1=jH.extend({method:U("notifications/progress"),params:wX}),zX=bH.extend({cursor:O1.optional()}),QW=_H.extend({params:zX.optional()}),XW=FH.extend({nextCursor:O1.optional()}),T1=E({uri:K(),mimeType:f(K()),_meta:T(K(),h()).optional()}),$1=T1.extend({text:K()}),XB=K().refine((H)=>{try{return atob(H),!0}catch{return!1}},{message:"Invalid Base64 string"}),R1=T1.extend({blob:XB}),YW=t(["user","assistant"]),y0=E({audience:V(YW).optional(),priority:b().min(0).max(1).optional(),lastModified:X0.datetime({offset:!0}).optional()}),C1=E({...x0.shape,...WW.shape,uri:K(),description:f(K()),mimeType:f(K()),size:f(b()),annotations:y0.optional(),_meta:f(l({}))}),ZX=E({...x0.shape,...WW.shape,uriTemplate:K(),description:f(K()),mimeType:f(K()),annotations:y0.optional(),_meta:f(l({}))}),PX=QW.extend({method:U("resources/list")}),bX=XW.extend({resources:V(C1)}),IX=QW.extend({method:U("resources/templates/list")}),LX=XW.extend({resourceTemplates:V(ZX)}),B8=bH.extend({uri:K()}),jX=B8,TX=_H.extend({method:U("resources/read"),params:jX}),$X=FH.extend({contents:V(S([$1,R1]))}),RX=jH.extend({method:U("notifications/resources/list_changed"),params:SH.optional()}),CX=B8,SX=_H.extend({method:U("resources/subscribe"),params:CX}),kX=B8,gX=_H.extend({method:U("resources/unsubscribe"),params:kX}),S1=E({toolsListChanged:R().optional(),promptsListChanged:R().optional(),resourcesListChanged:R().optional(),resourceSubscriptions:V(K()).optional()}),xX=bH.extend({notifications:S1}),vX=_H.extend({method:U("subscriptions/listen"),params:xX}),yX=SH.extend({notifications:S1}),hX=jH.extend({method:U("notifications/subscriptions/acknowledged"),params:yX}),fX=U1.extend({[DX]:O0}),uX=FH.extend({_meta:fX}),lX=SH.extend({uri:K()}),mX=jH.extend({method:U("notifications/resources/updated"),params:lX}),cX=E({name:K(),description:f(K()),required:f(R())}),pX=E({...x0.shape,...WW.shape,description:f(K()),arguments:f(V(cX)),_meta:f(l({}))}),dX=QW.extend({method:U("prompts/list")}),iX=XW.extend({prompts:V(pX)}),oX=bH.extend({name:K(),arguments:T(K(),K()).optional()}),nX=_H.extend({method:U("prompts/get"),params:oX}),K8=E({type:U("text"),text:K(),annotations:y0.optional(),_meta:T(K(),h()).optional()}),G8=E({type:U("image"),data:XB,mimeType:K(),annotations:y0.optional(),_meta:T(K(),h()).optional()}),D8=E({type:U("audio"),data:XB,mimeType:K(),annotations:y0.optional(),_meta:T(K(),h()).optional()}),rX=E({type:U("tool_use"),name:K(),id:K(),input:T(K(),h()),_meta:T(K(),h()).optional()}),M8=E({type:U("resource"),resource:S([$1,R1]),annotations:y0.optional(),_meta:T(K(),h()).optional()}),q8=C1.extend({type:U("resource_link")}),h0=S([K8,G8,D8,q8,M8]),tX=E({role:YW,content:h0}),sX=FH.extend({description:K().optional(),messages:V(tX)}),aX=jH.extend({method:U("notifications/prompts/list_changed"),params:SH.optional()}),eX=E({title:K().optional(),readOnlyHint:R().optional(),destructiveHint:R().optional(),idempotentHint:R().optional(),openWorldHint:R().optional()}),HY=E({taskSupport:t(["required","optional","forbidden"]).optional()}),$W=E({...x0.shape,...WW.shape,description:K().optional(),inputSchema:E({type:U("object"),properties:T(K(),a0).optional(),required:V(K()).optional()}).catchall(h()),outputSchema:l({$schema:K().optional()}).optional(),annotations:eX.optional(),execution:HY.optional(),_meta:T(K(),h()).optional()}),WY=QW.extend({method:U("tools/list")}),QY=XW.extend({tools:V($W)}),RW=FH.extend({content:V(h0).default([]),structuredContent:h().optional(),isError:R().optional()}),q9=RW.or(FH.extend({toolResult:h()})),XY=LW.extend({name:K(),arguments:T(K(),h()).optional()}),YY=_H.extend({method:U("tools/call"),params:XY}),JY=jH.extend({method:U("notifications/tools/list_changed"),params:SH.optional()}),NY=E({autoRefresh:R().default(!0),debounceMs:b().int().nonnegative().default(300)}),k1=t(["debug","info","notice","warning","error","critical","alert","emergency"]),BY=bH.extend({level:k1}),KY=_H.extend({method:U("logging/setLevel"),params:BY}),GY=SH.extend({level:k1,logger:K().optional(),data:h()}),_8=jH.extend({method:U("notifications/message"),params:GY}),DY=E({name:K().optional()}),MY=E({hints:V(DY).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),qY=E({mode:t(["auto","required","none"]).optional()}),_Y=E({type:U("tool_result"),toolUseId:K().describe("The unique identifier for the corresponding tool call."),content:V(h0),structuredContent:h().optional(),isError:R().optional(),_meta:T(K(),h()).optional()}),FY=PW("type",[K8,G8,D8]),IW=PW("type",[K8,G8,D8,rX,_Y]),EY=E({role:YW,content:S([IW,V(IW)]),_meta:T(K(),h()).optional()}),AY=LW.extend({messages:V(EY),modelPreferences:MY.optional(),systemPrompt:K().optional(),includeContext:t(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:V(K()).optional(),metadata:qH.optional(),tools:V($W).optional(),toolChoice:qY.optional()}),OY=_H.extend({method:U("sampling/createMessage"),params:AY}),VY=FH.extend({model:K(),stopReason:f(t(["endTurn","stopSequence","maxTokens"]).or(K())),role:YW,content:FY}),UY=FH.extend({model:K(),stopReason:f(t(["endTurn","stopSequence","maxTokens","toolUse"]).or(K())),role:YW,content:S([IW,V(IW)])}),g1=E({type:U("boolean"),title:K().optional(),description:K().optional(),default:R().optional()}),F8=E({type:U("string"),title:K().optional(),description:K().optional(),minLength:b().optional(),maxLength:b().optional(),format:t(["email","uri","date","date-time"]).optional(),default:K().optional()}),E8=E({type:t(["number","integer"]),title:K().optional(),description:K().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),x1=E({type:U("string"),title:K().optional(),description:K().optional(),enum:V(K()),default:K().optional()}),v1=E({type:U("string"),title:K().optional(),description:K().optional(),oneOf:V(E({const:K(),title:K()})),default:K().optional()}),y1=E({type:U("string"),title:K().optional(),description:K().optional(),enum:V(K()),enumNames:V(K()).optional(),default:K().optional()}),wY=S([x1,v1]),h1=E({type:U("array"),title:K().optional(),description:K().optional(),minItems:b().optional(),maxItems:b().optional(),items:E({type:U("string"),enum:V(K())}),default:V(K()).optional()}),f1=E({type:U("array"),title:K().optional(),description:K().optional(),minItems:b().optional(),maxItems:b().optional(),items:E({anyOf:V(E({const:K(),title:K()}))}),default:V(K()).optional()}),zY=S([h1,f1]),ZY=S([y1,wY,zY]),u1=S([ZY,g1,F8,E8]),A8=LW.extend({mode:U("form").optional(),message:K(),requestedSchema:E({type:U("object"),properties:T(K(),u1),required:V(K()).optional()}).catchall(h())}),PY=LW.extend({mode:U("url"),message:K(),elicitationId:K(),url:K().url()}),bY=S([A8,PY]),IY=_H.extend({method:U("elicitation/create"),params:bY}),LY=SH.extend({elicitationId:K()}),jY=jH.extend({method:U("notifications/elicitation/complete"),params:LY}),TY=FH.extend({action:t(["accept","decline","cancel"]),content:s0((H)=>H===null?void 0:H,T(K(),S([K(),b(),R(),V(K())])).optional())}),$Y=E({type:U("ref/resource"),uri:K()}),RY=E({type:U("ref/prompt"),name:K()}),CY=bH.extend({ref:S([RY,$Y]),argument:E({name:K(),value:K()}),context:E({arguments:T(K(),K()).optional()}).optional()}),SY=_H.extend({method:U("completion/complete"),params:CY}),kY=FH.extend({completion:l({values:V(K()).max(100),total:f(b().int()),hasMore:f(R())})}),gY=E({uri:K().startsWith("file://"),name:K().optional(),_meta:T(K(),h()).optional()}),xY=_H.extend({method:U("roots/list"),params:bH.optional()}),vY=FH.extend({roots:V(gY)}),yY=jH.extend({method:U("notifications/roots/list_changed"),params:SH.optional()}),_9=l({ttl:b().optional(),pollInterval:b().optional()}),hY=t(["working","input_required","completed","failed","cancelled"]),JW=E({taskId:K(),status:hY,ttl:S([b(),g0()]),createdAt:K(),lastUpdatedAt:K(),pollInterval:f(b()),statusMessage:f(K())}),F9=FH.extend({task:JW}),fY=SH.merge(JW),E9=jH.extend({method:U("notifications/tasks/status"),params:fY}),A9=_H.extend({method:U("tasks/get"),params:bH.extend({taskId:K()})}),O9=FH.merge(JW),V9=_H.extend({method:U("tasks/result"),params:bH.extend({taskId:K()})}),U9=FH.loose(),w9=QW.extend({method:U("tasks/list")}),z9=XW.extend({tasks:V(JW)}),Z9=_H.extend({method:U("tasks/cancel"),params:bH.extend({taskId:K()})}),P9=FH.merge(JW),b9=S([L1,P1,VX,SY,KY,nX,dX,PX,IX,TX,SX,gX,vX,YY,WY]),I9=S([Z1,j1,I1,yY]),L9=S([jW,VY,UY,TY,vY]),j9=S([L1,OY,IY,xY]),T9=S([Z1,j1,_8,mX,RX,JY,aX,hX,jY]),$9=S([jW,OX,TW,kY,sX,iX,bX,LX,$X,RW,QY,uX]),PH=K1().superRefine((H,W)=>{if(!URL.canParse(H))return W.addIssue({code:WB.custom,message:"URL must be parseable",fatal:!0}),CQ}).refine((H)=>{let W=new URL(H);return W.protocol!=="javascript:"&&W.protocol!=="data:"&&W.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),l1=l({resource:K().url(),authorization_servers:V(PH).optional(),jwks_uri:K().url().optional(),scopes_supported:V(K()).optional(),bearer_methods_supported:V(K()).optional(),resource_signing_alg_values_supported:V(K()).optional(),resource_name:K().optional(),resource_documentation:K().optional(),resource_policy_uri:K().url().optional(),resource_tos_uri:K().url().optional(),tls_client_certificate_bound_access_tokens:R().optional(),authorization_details_types_supported:V(K()).optional(),dpop_signing_alg_values_supported:V(K()).optional(),dpop_bound_access_tokens_required:R().optional()}),O8=l({issuer:K(),authorization_endpoint:PH,token_endpoint:PH,registration_endpoint:PH.optional(),scopes_supported:V(K()).optional(),response_types_supported:V(K()),response_modes_supported:V(K()).optional(),grant_types_supported:V(K()).optional(),token_endpoint_auth_methods_supported:V(K()).optional(),token_endpoint_auth_signing_alg_values_supported:V(K()).optional(),service_documentation:PH.optional(),revocation_endpoint:PH.optional(),revocation_endpoint_auth_methods_supported:V(K()).optional(),revocation_endpoint_auth_signing_alg_values_supported:V(K()).optional(),introspection_endpoint:K().optional(),introspection_endpoint_auth_methods_supported:V(K()).optional(),introspection_endpoint_auth_signing_alg_values_supported:V(K()).optional(),code_challenge_methods_supported:V(K()).optional(),client_id_metadata_document_supported:R().optional(),authorization_response_iss_parameter_supported:R().optional().catch(void 0),dpop_signing_alg_values_supported:V(K()).optional()}),uY=l({issuer:K(),authorization_endpoint:PH,token_endpoint:PH,userinfo_endpoint:PH.optional(),jwks_uri:PH,registration_endpoint:PH.optional(),scopes_supported:V(K()).optional(),response_types_supported:V(K()),response_modes_supported:V(K()).optional(),grant_types_supported:V(K()).optional(),acr_values_supported:V(K()).optional(),subject_types_supported:V(K()),id_token_signing_alg_values_supported:V(K()),id_token_encryption_alg_values_supported:V(K()).optional(),id_token_encryption_enc_values_supported:V(K()).optional(),userinfo_signing_alg_values_supported:V(K()).optional(),userinfo_encryption_alg_values_supported:V(K()).optional(),userinfo_encryption_enc_values_supported:V(K()).optional(),request_object_signing_alg_values_supported:V(K()).optional(),request_object_encryption_alg_values_supported:V(K()).optional(),request_object_encryption_enc_values_supported:V(K()).optional(),token_endpoint_auth_methods_supported:V(K()).optional(),token_endpoint_auth_signing_alg_values_supported:V(K()).optional(),display_values_supported:V(K()).optional(),claim_types_supported:V(K()).optional(),claims_supported:V(K()).optional(),service_documentation:K().optional(),claims_locales_supported:V(K()).optional(),ui_locales_supported:V(K()).optional(),claims_parameter_supported:R().optional(),request_parameter_supported:R().optional(),request_uri_parameter_supported:R().optional(),require_request_uri_registration:R().optional(),op_policy_uri:PH.optional(),op_tos_uri:PH.optional(),client_id_metadata_document_supported:R().optional(),authorization_response_iss_parameter_supported:R().optional().catch(void 0)}),m1=E({...uY.shape,...O8.pick({code_challenge_methods_supported:!0}).shape}),c1=E({access_token:K(),id_token:K().optional(),token_type:K(),expires_in:GX.number().optional(),scope:K().optional(),refresh_token:K().optional(),issuer:K().optional().catch(void 0)}).strip(),lY=E({issued_token_type:U("urn:ietf:params:oauth:token-type:id-jag"),access_token:K(),token_type:K().optional(),expires_in:b().optional(),scope:K().optional()}).strip(),p1=E({error:K(),error_description:K().optional(),error_uri:K().optional()}),QB=PH.optional().or(U("").transform(()=>{return})),mY=E({redirect_uris:V(PH),token_endpoint_auth_method:K().optional(),grant_types:V(K()).optional(),response_types:V(K()).optional(),application_type:K().optional(),client_name:K().optional(),client_uri:PH.optional(),logo_uri:QB,scope:K().optional(),contacts:V(K()).optional(),tos_uri:QB,policy_uri:K().optional(),jwks_uri:PH.optional(),jwks:W9().optional(),software_id:K().optional(),software_version:K().optional(),software_statement:K().optional()}).strip(),cY=E({client_id:K(),client_secret:K().optional(),client_id_issued_at:b().optional(),client_secret_expires_at:b().optional(),issuer:K().optional().catch(void 0)}).strip(),d1=mY.merge(cY),R9=E({error:K(),error_description:K().optional()}).strip(),C9=E({token:K(),token_type_hint:K().optional()}).strip();var KB=Symbol.for("mcp.sdk.errorBrands");function V8(H,W){let Q=new Set,X=W;while(typeof X==="function"){let Y=X.mcpBrand;if(Object.prototype.hasOwnProperty.call(X,"mcpBrand")&&typeof Y==="string")Q.add(Y);X=Object.getPrototypeOf(X)}if(Q.size===0)return;Object.defineProperty(H,KB,{value:Q,enumerable:!1,configurable:!0})}function Y0(H,W){try{if(typeof W==="object"&&W!==null&&Object.prototype.hasOwnProperty.call(H,"mcpBrand")&&typeof H.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(W,KB)){let Q=W[KB];if(Q&&typeof Q.has==="function"&&Q.has(H.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(H,W)}var BW=function(H){return H.InvalidRequest="invalid_request",H.InvalidClient="invalid_client",H.InvalidGrant="invalid_grant",H.UnauthorizedClient="unauthorized_client",H.UnsupportedGrantType="unsupported_grant_type",H.InvalidScope="invalid_scope",H.AccessDenied="access_denied",H.ServerError="server_error",H.TemporarilyUnavailable="temporarily_unavailable",H.UnsupportedResponseType="unsupported_response_type",H.UnsupportedTokenType="unsupported_token_type",H.InvalidToken="invalid_token",H.MethodNotAllowed="method_not_allowed",H.TooManyRequests="too_many_requests",H.InvalidClientMetadata="invalid_client_metadata",H.InvalidRedirectUri="invalid_redirect_uri",H.InsufficientScope="insufficient_scope",H.InvalidTarget="invalid_target",H.InvalidDpopProof="invalid_dpop_proof",H.UseDpopNonce="use_dpop_nonce",H}({}),U8=class H extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](W){return Y0(this,W)}static isInstance(W){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Y0(this,W)}constructor(W,Q,X){super(Q);this.code=W,this.errorUri=X,this.name="OAuthError",V8(this,new.target)}toResponseObject(){let W={error:this.code,error_description:this.message};if(this.errorUri)W.error_uri=this.errorUri;return W}static fromResponse(W){return new H(W.error,W.error_description??W.error,W.error_uri)}},x=function(H){return H.NotConnected="NOT_CONNECTED",H.AlreadyConnected="ALREADY_CONNECTED",H.NotInitialized="NOT_INITIALIZED",H.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",H.RequestTimeout="REQUEST_TIMEOUT",H.ConnectionClosed="CONNECTION_CLOSED",H.SendFailed="SEND_FAILED",H.InvalidResult="INVALID_RESULT",H.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",H.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",H.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",H.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",H.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",H.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",H.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",H.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",H.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",H.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",H.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",H}({}),v=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](H){return Y0(this,H)}static isInstance(H){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Y0(this,H)}constructor(H,W,Q,X){super(W,X);this.code=H,this.data=Q,this.name="SdkError",V8(this,new.target)}},f0=class extends v{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(H,W,Q,X){super(H,W,Q,X);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function SG(H){let W=typeof H==="string"?new URL(H):new URL(H.href);return W.hash="",W}function _B(H){if(typeof H!=="object"||H===null||Array.isArray(H))return H;let W={...H};return delete W.issuer,W}function kG({requestedResource:H,configuredResource:W}){let Q=typeof H==="string"?new URL(H):new URL(H.href),X=typeof W==="string"?new URL(W):new URL(W.href);if(Q.origin!==X.origin)return!1;if(Q.pathname.length<X.pathname.length)return!1;let Y=Q.pathname.endsWith("/")?Q.pathname:Q.pathname+"/",J=X.pathname.endsWith("/")?X.pathname:X.pathname+"/";return Y.startsWith(J)}var gG="2026-07-28",FB=[gG];function KW(H){return H>=gG}function EB(H){return H.filter((W)=>!KW(W))}function rY(H){return H.filter((W)=>KW(W))}function xG(H){let W=H.structuredContent;if(W===void 0)return H;if(!(typeof W!=="object"||W===null||Array.isArray(W)))return H;if(H.content?.some((Q)=>Q.type==="text")??!1)return H;return{...H,content:[...H.content??[],{type:"text",text:JSON.stringify(W)}]}}var vG=["task","inputRequests","requestState"];function p_(H){if(H===null||typeof H!=="object"||Array.isArray(H)||H.content!==void 0||vG.some((W)=>(W in H)))return H;return{...H,content:[]}}function d_(){let H=bW(()=>S([K(),b(),R(),g0(),T(K(),H),V(H)])),W=T(K(),H),Q=S([K(),b().int()]),X=K(),Y=E({ttl:b().optional()}),J=E({taskId:K()}),N=l({progressToken:Q.optional(),"io.modelcontextprotocol/related-task":J.optional()}),B=E({_meta:N.optional()}),G=B.extend({task:Y.optional()}),D=E({method:K(),params:B.loose().optional()}),M=E({_meta:N.optional()}),_=E({method:K(),params:M.loose().optional()}),F=l({_meta:N.optional()}),A=S([K(),b().int()]),w=F.strict(),z=M.extend({requestId:A.optional(),reason:K().optional()}),Z=_.extend({method:U("notifications/cancelled"),params:z}),u=E({src:K(),mimeType:K().optional(),sizes:V(K()).optional(),theme:t(["light","dark"]).optional()}),p=E({icons:V(u).optional()}),j=E({name:K(),title:K().optional()}),m=j.extend({...j.shape,...p.shape,version:K(),websiteUrl:K().optional(),description:K().optional()}),I=A0(E({applyDefaults:R().optional()}),W),P=s0((RH)=>{if(RH&&typeof RH==="object"&&!Array.isArray(RH)&&Object.keys(RH).length===0)return{form:{}};return RH},A0(E({form:I.optional(),url:W.optional()}),W.optional())),c=l({list:W.optional(),cancel:W.optional(),requests:l({sampling:l({createMessage:W.optional()}).optional(),elicitation:l({create:W.optional()}).optional()}).optional()}),XH=l({list:W.optional(),cancel:W.optional(),requests:l({tools:l({call:W.optional()}).optional()}).optional()}),WH=E({experimental:T(K(),W).optional(),sampling:E({context:W.optional(),tools:W.optional()}).optional(),elicitation:P.optional(),roots:E({listChanged:R().optional()}).optional(),tasks:c.optional(),extensions:T(K(),W).optional()}),MH=B.extend({protocolVersion:K(),capabilities:WH,clientInfo:m}),kH=D.extend({method:U("initialize"),params:MH}),NH=E({experimental:T(K(),W).optional(),logging:W.optional(),completions:W.optional(),prompts:E({listChanged:R().optional()}).optional(),resources:E({subscribe:R().optional(),listChanged:R().optional()}).optional(),tools:E({listChanged:R().optional()}).optional(),tasks:XH.optional(),extensions:T(K(),W).optional()}),DH=F.extend({protocolVersion:K(),capabilities:NH,serverInfo:m,instructions:K().optional()}),IH=_.extend({method:U("notifications/initialized"),params:M.optional()}),gH=D.extend({method:U("ping"),params:B.optional()}),z0=E({progress:b(),total:f(b()),message:f(K())}),cH=E({...M.shape,...z0.shape,progressToken:Q}),J0=_.extend({method:U("notifications/progress"),params:cH}),Z0=B.extend({cursor:X.optional()}),tH=D.extend({params:Z0.optional()}),xH=F.extend({nextCursor:X.optional()}),d0=E({uri:K(),mimeType:f(K()),_meta:T(K(),h()).optional()}),i0=d0.extend({text:K()}),P0=K().refine((RH)=>{try{return atob(RH),!0}catch{return!1}},{message:"Invalid Base64 string"}),TH=d0.extend({blob:P0}),vH=t(["user","assistant"]),yH=E({audience:V(vH).optional(),priority:b().min(0).max(1).optional(),lastModified:X0.datetime({offset:!0}).optional()}),_0=E({...j.shape,...p.shape,uri:K(),description:f(K()),mimeType:f(K()),size:f(b()),annotations:yH.optional(),_meta:f(l({}))}),vW=E({...j.shape,...p.shape,uriTemplate:K(),description:f(K()),mimeType:f(K()),annotations:yH.optional(),_meta:f(l({}))}),sH=tH.extend({method:U("resources/list")}),aH=xH.extend({resources:V(_0)}),pH=tH.extend({method:U("resources/templates/list")}),N0=xH.extend({resourceTemplates:V(vW)}),B0=B.extend({uri:K()}),b0=B0,I0=D.extend({method:U("resources/read"),params:b0}),DW=F.extend({contents:V(S([i0,TH]))}),L0=_.extend({method:U("notifications/resources/list_changed"),params:M.optional()}),yW=B0,k=D.extend({method:U("resources/subscribe"),params:yW}),j0=B0,d=D.extend({method:U("resources/unsubscribe"),params:j0}),y=M.extend({uri:K()}),e=_.extend({method:U("notifications/resources/updated"),params:y}),g=E({name:K(),description:f(K()),required:f(R())}),$=E({...j.shape,...p.shape,description:f(K()),arguments:f(V(g)),_meta:f(l({}))}),n=tH.extend({method:U("prompts/list")}),o=xH.extend({prompts:V($)}),wH=B.extend({name:K(),arguments:T(K(),K()).optional()}),hW=D.extend({method:U("prompts/get"),params:wH}),T0=E({type:U("text"),text:K(),annotations:yH.optional(),_meta:T(K(),h()).optional()}),fW=E({type:U("image"),data:P0,mimeType:K(),annotations:yH.optional(),_meta:T(K(),h()).optional()}),uW=E({type:U("audio"),data:P0,mimeType:K(),annotations:yH.optional(),_meta:T(K(),h()).optional()}),XQ=E({type:U("tool_use"),name:K(),id:K(),input:T(K(),h()),_meta:T(K(),h()).optional()}),MW=E({type:U("resource"),resource:S([i0,TH]),annotations:yH.optional(),_meta:T(K(),h()).optional()}),YQ=_0.extend({type:U("resource_link")}),K0=S([T0,fW,uW,YQ,MW]),L8=E({role:vH,content:K0}),j8=F.extend({description:K().optional(),messages:V(L8)}),lW=_.extend({method:U("notifications/prompts/list_changed"),params:M.optional()}),JQ=E({title:K().optional(),readOnlyHint:R().optional(),destructiveHint:R().optional(),idempotentHint:R().optional(),openWorldHint:R().optional()}),T8=E({taskSupport:t(["required","optional","forbidden"]).optional()}),mW=E({...j.shape,...p.shape,description:K().optional(),inputSchema:E({type:U("object"),properties:T(K(),H).optional(),required:V(K()).optional()}).catchall(h()),outputSchema:E({type:U("object"),properties:T(K(),H).optional(),required:V(K()).optional()}).catchall(h()).optional(),annotations:JQ.optional(),execution:T8.optional(),_meta:T(K(),h()).optional()}),$8=tH.extend({method:U("tools/list")}),R8=xH.extend({tools:V(mW)}),C8=F.extend({content:V(K0),structuredContent:T(K(),h()).optional(),isError:R().optional()}),$H=G.extend({name:K(),arguments:T(K(),h()).optional()}),NQ=D.extend({method:U("tools/call"),params:$H}),D4=_.extend({method:U("notifications/tools/list_changed"),params:M.optional()}),S8=t(["debug","info","notice","warning","error","critical","alert","emergency"]),BQ=B.extend({level:S8}),KQ=D.extend({method:U("logging/setLevel"),params:BQ}),GQ=M.extend({level:S8,logger:K().optional(),data:h()}),DQ=_.extend({method:U("notifications/message"),params:GQ}),MQ=E({name:K().optional()}),qQ=E({hints:V(MQ).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),_Q=E({mode:t(["auto","required","none"]).optional()}),M4=E({type:U("tool_result"),toolUseId:K().describe("The unique identifier for the corresponding tool call."),content:V(K0),structuredContent:E({}).loose().optional(),isError:R().optional(),_meta:T(K(),h()).optional()}),FQ=PW("type",[T0,fW,uW]),qW=PW("type",[T0,fW,uW,XQ,M4]),EQ=E({role:vH,content:S([qW,V(qW)]),_meta:T(K(),h()).optional()}),AQ=G.extend({messages:V(EQ),modelPreferences:qQ.optional(),systemPrompt:K().optional(),includeContext:t(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:V(K()).optional(),metadata:W.optional(),tools:V(mW).optional(),toolChoice:_Q.optional()}),OQ=D.extend({method:U("sampling/createMessage"),params:AQ}),VQ=F.extend({model:K(),stopReason:f(t(["endTurn","stopSequence","maxTokens"]).or(K())),role:vH,content:FQ}),UQ=F.extend({model:K(),stopReason:f(t(["endTurn","stopSequence","maxTokens","toolUse"]).or(K())),role:vH,content:S([qW,V(qW)])}),wQ=E({type:U("boolean"),title:K().optional(),description:K().optional(),default:R().optional()}),zQ=E({type:U("string"),title:K().optional(),description:K().optional(),minLength:b().optional(),maxLength:b().optional(),format:t(["email","uri","date","date-time"]).optional(),default:K().optional()}),ZQ=E({type:t(["number","integer"]),title:K().optional(),description:K().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),PQ=E({type:U("string"),title:K().optional(),description:K().optional(),enum:V(K()),default:K().optional()}),bQ=E({type:U("string"),title:K().optional(),description:K().optional(),oneOf:V(E({const:K(),title:K()})),default:K().optional()}),IQ=E({type:U("string"),title:K().optional(),description:K().optional(),enum:V(K()),enumNames:V(K()).optional(),default:K().optional()}),LQ=S([PQ,bQ]),cW=E({type:U("array"),title:K().optional(),description:K().optional(),minItems:b().optional(),maxItems:b().optional(),items:E({type:U("string"),enum:V(K())}),default:V(K()).optional()}),pW=E({type:U("array"),title:K().optional(),description:K().optional(),minItems:b().optional(),maxItems:b().optional(),items:E({anyOf:V(E({const:K(),title:K()}))}),default:V(K()).optional()}),q4=S([cW,pW]),_4=S([IQ,LQ,q4]),eH=S([_4,wQ,zQ,ZQ]),H0=G.extend({mode:U("form").optional(),message:K(),requestedSchema:E({type:U("object"),properties:T(K(),eH),required:V(K()).optional()}).catchall(h())}),jQ=G.extend({mode:U("url"),message:K(),elicitationId:K(),url:K().url()}),F0=S([H0,jQ]),F4=D.extend({method:U("elicitation/create"),params:F0}),E4=M.extend({elicitationId:K()}),A4=_.extend({method:U("notifications/elicitation/complete"),params:E4}),O4=F.extend({action:t(["accept","decline","cancel"]),content:s0((RH)=>RH===null?void 0:RH,T(K(),S([K(),b(),R(),V(K())])).optional())}),V4=E({type:U("ref/resource"),uri:K()}),U4=E({type:U("ref/prompt"),name:K()}),w4=B.extend({ref:S([U4,V4]),argument:E({name:K(),value:K()}),context:E({arguments:T(K(),K()).optional()}).optional()}),TQ=D.extend({method:U("completion/complete"),params:w4}),z4=F.extend({completion:l({values:V(K()).max(100),total:f(b().int()),hasMore:f(R())})}),Z4=E({uri:K().startsWith("file://"),name:K().optional(),_meta:T(K(),h()).optional()}),k8=D.extend({method:U("roots/list"),params:B.optional()}),$Q=F.extend({roots:V(Z4)}),P4=_.extend({method:U("notifications/roots/list_changed"),params:M.optional()}),b4=l({ttl:b().optional(),pollInterval:b().optional()}),RQ=t(["working","input_required","completed","failed","cancelled"]),_W=E({taskId:K(),status:RQ,ttl:S([b(),g0()]),createdAt:K(),lastUpdatedAt:K(),pollInterval:f(b()),statusMessage:f(K())}),dH=F.extend({task:_W}),I4=M.merge(_W),dW=_.extend({method:U("notifications/tasks/status"),params:I4}),g8=D.extend({method:U("tasks/get"),params:B.extend({taskId:K()})}),x8=F.merge(_W),v8=D.extend({method:U("tasks/result"),params:B.extend({taskId:K()})}),JJ=F.loose(),hH=tH.extend({method:U("tasks/list")}),VH=xH.extend({tasks:V(_W)}),iW=D.extend({method:U("tasks/cancel"),params:B.extend({taskId:K()})});return{JSONValueSchema:H,JSONObjectSchema:W,ProgressTokenSchema:Q,CursorSchema:X,TaskMetadataSchema:Y,RelatedTaskMetadataSchema:J,RequestMetaSchema:N,BaseRequestParamsSchema:B,TaskAugmentedRequestParamsSchema:G,RequestSchema:D,NotificationsParamsSchema:M,NotificationSchema:_,ResultSchema:F,RequestIdSchema:A,EmptyResultSchema:w,CancelledNotificationParamsSchema:z,CancelledNotificationSchema:Z,IconSchema:u,IconsSchema:p,BaseMetadataSchema:j,ImplementationSchema:m,ClientTasksCapabilitySchema:c,ServerTasksCapabilitySchema:XH,ClientCapabilitiesSchema:WH,InitializeRequestParamsSchema:MH,InitializeRequestSchema:kH,ServerCapabilitiesSchema:NH,InitializeResultSchema:DH,InitializedNotificationSchema:IH,PingRequestSchema:gH,ProgressSchema:z0,ProgressNotificationParamsSchema:cH,ProgressNotificationSchema:J0,PaginatedRequestParamsSchema:Z0,PaginatedRequestSchema:tH,PaginatedResultSchema:xH,ResourceContentsSchema:d0,TextResourceContentsSchema:i0,BlobResourceContentsSchema:TH,RoleSchema:vH,AnnotationsSchema:yH,ResourceSchema:_0,ResourceTemplateSchema:vW,ListResourcesRequestSchema:sH,ListResourcesResultSchema:aH,ListResourceTemplatesRequestSchema:pH,ListResourceTemplatesResultSchema:N0,ResourceRequestParamsSchema:B0,ReadResourceRequestParamsSchema:b0,ReadResourceRequestSchema:I0,ReadResourceResultSchema:DW,ResourceListChangedNotificationSchema:L0,SubscribeRequestParamsSchema:yW,SubscribeRequestSchema:k,UnsubscribeRequestParamsSchema:j0,UnsubscribeRequestSchema:d,ResourceUpdatedNotificationParamsSchema:y,ResourceUpdatedNotificationSchema:e,PromptArgumentSchema:g,PromptSchema:$,ListPromptsRequestSchema:n,ListPromptsResultSchema:o,GetPromptRequestParamsSchema:wH,GetPromptRequestSchema:hW,TextContentSchema:T0,ImageContentSchema:fW,AudioContentSchema:uW,ToolUseContentSchema:XQ,EmbeddedResourceSchema:MW,ResourceLinkSchema:YQ,ContentBlockSchema:K0,PromptMessageSchema:L8,GetPromptResultSchema:j8,PromptListChangedNotificationSchema:lW,ToolAnnotationsSchema:JQ,ToolExecutionSchema:T8,ToolSchema:mW,ListToolsRequestSchema:$8,ListToolsResultSchema:R8,CallToolResultSchema:C8,CallToolRequestParamsSchema:$H,CallToolRequestSchema:NQ,ToolListChangedNotificationSchema:D4,LoggingLevelSchema:S8,SetLevelRequestParamsSchema:BQ,SetLevelRequestSchema:KQ,LoggingMessageNotificationParamsSchema:GQ,LoggingMessageNotificationSchema:DQ,ModelHintSchema:MQ,ModelPreferencesSchema:qQ,ToolChoiceSchema:_Q,ToolResultContentSchema:M4,SamplingContentSchema:FQ,SamplingMessageContentBlockSchema:qW,SamplingMessageSchema:EQ,CreateMessageRequestParamsSchema:AQ,CreateMessageRequestSchema:OQ,CreateMessageResultSchema:VQ,CreateMessageResultWithToolsSchema:UQ,BooleanSchemaSchema:wQ,StringSchemaSchema:zQ,NumberSchemaSchema:ZQ,UntitledSingleSelectEnumSchemaSchema:PQ,TitledSingleSelectEnumSchemaSchema:bQ,LegacyTitledEnumSchemaSchema:IQ,SingleSelectEnumSchemaSchema:LQ,UntitledMultiSelectEnumSchemaSchema:cW,TitledMultiSelectEnumSchemaSchema:pW,MultiSelectEnumSchemaSchema:q4,EnumSchemaSchema:_4,PrimitiveSchemaDefinitionSchema:eH,ElicitRequestFormParamsSchema:H0,ElicitRequestURLParamsSchema:jQ,ElicitRequestParamsSchema:F0,ElicitRequestSchema:F4,ElicitationCompleteNotificationParamsSchema:E4,ElicitationCompleteNotificationSchema:A4,ElicitResultSchema:O4,ResourceTemplateReferenceSchema:V4,PromptReferenceSchema:U4,CompleteRequestParamsSchema:w4,CompleteRequestSchema:TQ,CompleteResultSchema:z4,RootSchema:Z4,ListRootsRequestSchema:k8,ListRootsResultSchema:$Q,RootsListChangedNotificationSchema:P4,TaskCreationParamsSchema:b4,TaskStatusSchema:RQ,TaskSchema:_W,CreateTaskResultSchema:dH,TaskStatusNotificationParamsSchema:I4,TaskStatusNotificationSchema:dW,GetTaskRequestSchema:g8,GetTaskResultSchema:x8,GetTaskPayloadRequestSchema:v8,GetTaskPayloadResultSchema:JJ,ListTasksRequestSchema:hH,ListTasksResultSchema:VH,CancelTaskRequestSchema:iW,CancelTaskResultSchema:F.merge(_W),ClientRequestSchema:S([gH,kH,TQ,KQ,hW,n,sH,pH,I0,k,d,NQ,$8,g8,v8,hH,iW]),ClientNotificationSchema:S([Z,J0,IH,P4,dW]),ClientResultSchema:S([w,VQ,UQ,O4,$Q,x8,VH,dH]),ServerRequestSchema:S([gH,OQ,F4,k8,g8,v8,hH,iW]),ServerNotificationSchema:S([Z,J0,DQ,e,L0,D4,lW,dW,A4]),ServerResultSchema:S([w,DH,z4,j8,o,aH,N0,DW,C8,R8,x8,VH,dH]),CallToolResultWireSchema:h().superRefine((RH,xM)=>{if(typeof RH!=="object"||RH===null||Array.isArray(RH)||RH.content!==void 0)return;for(let D2 of vG)if(D2 in RH){xM.addIssue({code:"custom",message:`content is required when the body carries '${D2}' — another result family cannot default into an empty tools/call success`});return}}).transform(p_).pipe(C8)}}var i_;function yG(){return i_??=d_()}function hG(H){return H.type!=="object"}var o_=new Set(["const","enum","default","examples"]),n_=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function VG(H){return H!==void 0&&!(typeof H==="string"&&H.startsWith("#"))}function r_(H){let W=typeof H.$schema==="string"?H.$schema:void 0;if(VG(H.$id))return{...W!==void 0&&{$schema:W},type:"object",properties:{result:H},required:["result"]};let Q=E2(H.$schema)&&H.$recursiveAnchor!==!0,X=(Y,J)=>{if(Array.isArray(Y))return Y.map((G)=>X(G,!1));if(Y===null||typeof Y!=="object")return Y;if(!J&&VG(Y.$id))return Y;let N={},B=!1;for(let[G,D]of Object.entries(Y))if(J)N[G]=X(D,!1);else if((G==="$ref"||G==="$dynamicRef")&&typeof D==="string")N[G]=D==="#"?"#/properties/result":D.startsWith("#/")?`#/properties/result${D.slice(1)}`:D;else if(G==="$recursiveRef"&&D==="#"&&Q)B=!0;else if(o_.has(G))N[G]=D;else if(n_.has(G))N[G]=X(D,!0);else N[G]=X(D,!1);if(B)if("$ref"in N)N.allOf=[...Array.isArray(N.allOf)?N.allOf:[],{$ref:"#/properties/result"}];else N.$ref="#/properties/result";return N};return{...W!==void 0&&{$schema:W},type:"object",properties:{result:X(H,!1)},required:["result"]}}var fG={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},uG={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},t_={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},S9;function AB(){if(S9)return S9;let H=yG();return S9={requestSchemas:{ping:H.PingRequestSchema,initialize:H.InitializeRequestSchema,"completion/complete":H.CompleteRequestSchema,"logging/setLevel":H.SetLevelRequestSchema,"prompts/get":H.GetPromptRequestSchema,"prompts/list":H.ListPromptsRequestSchema,"resources/list":H.ListResourcesRequestSchema,"resources/templates/list":H.ListResourceTemplatesRequestSchema,"resources/read":H.ReadResourceRequestSchema,"resources/subscribe":H.SubscribeRequestSchema,"resources/unsubscribe":H.UnsubscribeRequestSchema,"tools/call":H.CallToolRequestSchema,"tools/list":H.ListToolsRequestSchema,"tasks/get":H.GetTaskRequestSchema,"tasks/result":H.GetTaskPayloadRequestSchema,"tasks/list":H.ListTasksRequestSchema,"tasks/cancel":H.CancelTaskRequestSchema,"sampling/createMessage":H.CreateMessageRequestSchema,"elicitation/create":H.ElicitRequestSchema,"roots/list":H.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":H.CancelledNotificationSchema,"notifications/progress":H.ProgressNotificationSchema,"notifications/initialized":H.InitializedNotificationSchema,"notifications/roots/list_changed":H.RootsListChangedNotificationSchema,"notifications/tasks/status":H.TaskStatusNotificationSchema,"notifications/message":H.LoggingMessageNotificationSchema,"notifications/resources/updated":H.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":H.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":H.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":H.PromptListChangedNotificationSchema,"notifications/elicitation/complete":H.ElicitationCompleteNotificationSchema},resultSchemas:{ping:H.EmptyResultSchema,initialize:H.InitializeResultSchema,"completion/complete":H.CompleteResultSchema,"logging/setLevel":H.EmptyResultSchema,"prompts/get":H.GetPromptResultSchema,"prompts/list":H.ListPromptsResultSchema,"resources/list":H.ListResourcesResultSchema,"resources/templates/list":H.ListResourceTemplatesResultSchema,"resources/read":H.ReadResourceResultSchema,"resources/subscribe":H.EmptyResultSchema,"resources/unsubscribe":H.EmptyResultSchema,"tools/call":H.CallToolResultWireSchema,"tools/list":H.ListToolsResultSchema,"sampling/createMessage":H.CreateMessageResultWithToolsSchema,"elicitation/create":H.ElicitResultSchema,"roots/list":H.ListRootsResultSchema}},S9}function lG(H){return Object.prototype.hasOwnProperty.call(fG,H)}function mG(H){return Object.prototype.hasOwnProperty.call(uG,H)}function s_(H){return Object.prototype.hasOwnProperty.call(t_,H)}function a_(H){return s_(H)?AB().resultSchemas[H]:void 0}function e_(H){return lG(H)?AB().requestSchemas[H]:void 0}function HF(H){return mG(H)?AB().notificationSchemas[H]:void 0}var WU=Object.keys(fG),QU=Object.keys(uG);function GB(H){return H!==null&&typeof H==="object"&&!Array.isArray(H)}function k9(H,W){if(H===void 0)return{ok:!1,reason:"not-in-era"};let Q=H.safeParse(W);return Q.success?{ok:!0,value:Q.data}:{ok:!1,reason:"invalid",message:String(Q.error)}}var UG={ok:!1,reason:"not-in-era"};function wG(H){return GB(H)&&GB(H.outputSchema)&&hG(H.outputSchema)}function zG(H){return H}var OB={era:"2025-11-25",hasRequestMethod:lG,hasNotificationMethod:mG,validateRequest:(H,W)=>k9(e_(H),W),validateResult:(H,W)=>k9(a_(H),W),validateNotification:(H,W)=>k9(HF(H),W),hasInputRequestMethod:()=>!1,validateInputRequest:()=>UG,validateInputResponse:()=>UG,samplingResultVariant:(H,W)=>{let Q=yG();return k9(H?Q.CreateMessageResultWithToolsSchema:Q.CreateMessageResultSchema,W)},outboundEnvelope:(H)=>{return},validateEnvelopeMeta:(H)=>[],projectCallToolResult(H,W){let Q=xG(H),X=Q.structuredContent;if(X===void 0)return Q;let Y=typeof X!=="object"||X===null||Array.isArray(X),J=W!==void 0&&hG(W);if(!Y&&!J)return Q;return{...Q,structuredContent:{result:X}}},decodeResult(H,W){if(GB(W)&&"resultType"in W){let Q={...W};return delete Q.resultType,{kind:"complete",result:zG(Q)}}return{kind:"complete",result:zG(W)}},encodeResult(H,W){if(H!=="tools/list")return W;let Q=W.tools;if(!Array.isArray(Q)||!Q.some((X)=>wG(X)))return W;return{...W,tools:Q.map((X)=>wG(X)?{...X,outputSchema:r_(X.outputSchema)}:X)}},encodeErrorCode:(H)=>H===-32002?-32602:H,checkInboundEnvelope:(H)=>{return}};function WF(){let H=bW(()=>S([K(),b(),R(),g0(),T(K(),H),V(H)])),W=T(K(),H),Q=S([K(),b().int()]),X=K(),Y=S([K(),b().int()]),J=t(["user","assistant"]),N=t(["debug","info","notice","warning","error","critical","alert","emergency"]),B=K().refine((VH)=>{try{return atob(VH),!0}catch{return!1}},{message:"Invalid Base64 string"}),G=E({ttl:b().optional()}),D=E({taskId:K()}),M=l({progressToken:Q.optional(),"io.modelcontextprotocol/related-task":D.optional()}),_=E({_meta:M.optional()}),F=_.extend({task:G.optional()}),A=E({_meta:M.optional()}),w=E({method:K(),params:A.loose().optional()}),z=E({src:K(),mimeType:K().optional(),sizes:V(K()).optional(),theme:t(["light","dark"]).optional()}),Z=E({icons:V(z).optional()}),u=E({name:K(),title:K().optional()}),p=u.extend({...u.shape,...Z.shape,version:K(),websiteUrl:K().optional(),description:K().optional()}),j=A0(E({applyDefaults:R().optional()}),W),m=s0((VH)=>{if(VH&&typeof VH==="object"&&!Array.isArray(VH)&&Object.keys(VH).length===0)return{form:{}};return VH},A0(E({form:j.optional(),url:W.optional()}),W.optional())),I=l({list:W.optional(),cancel:W.optional(),requests:l({sampling:l({createMessage:W.optional()}).optional(),elicitation:l({create:W.optional()}).optional()}).optional()}),P=l({list:W.optional(),cancel:W.optional(),requests:l({tools:l({call:W.optional()}).optional()}).optional()}),c=E({experimental:T(K(),W).optional(),sampling:E({context:W.optional(),tools:W.optional()}).optional(),elicitation:m.optional(),roots:E({listChanged:R().optional()}).optional(),tasks:I.optional(),extensions:T(K(),W).optional()}),XH=E({experimental:T(K(),W).optional(),logging:W.optional(),completions:W.optional(),prompts:E({listChanged:R().optional()}).optional(),resources:E({subscribe:R().optional(),listChanged:R().optional()}).optional(),tools:E({listChanged:R().optional()}).optional(),tasks:P.optional(),extensions:T(K(),W).optional()}),WH=E({progress:b(),total:f(b()),message:f(K())}),MH=E({...A.shape,...WH.shape,progressToken:Q}),kH=w.extend({method:U("notifications/progress"),params:MH}),NH=A.extend({level:N,logger:K().optional(),data:h()}),DH=w.extend({method:U("notifications/message"),params:NH}),IH=E({uri:K(),mimeType:f(K()),_meta:T(K(),h()).optional()}),gH=IH.extend({text:K()}),z0=IH.extend({blob:B}),cH=E({audience:V(J).optional(),priority:b().min(0).max(1).optional(),lastModified:X0.datetime({offset:!0}).optional()}),J0=E({...u.shape,...Z.shape,uri:K(),description:f(K()),mimeType:f(K()),size:f(b()),annotations:cH.optional(),_meta:f(l({}))}),Z0=E({...u.shape,...Z.shape,uriTemplate:K(),description:f(K()),mimeType:f(K()),annotations:cH.optional(),_meta:f(l({}))}),tH=w.extend({method:U("notifications/resources/list_changed"),params:A.optional()}),xH=A.extend({uri:K()}),d0=w.extend({method:U("notifications/resources/updated"),params:xH}),i0=E({name:K(),description:f(K()),required:f(R())}),P0=E({...u.shape,...Z.shape,description:f(K()),arguments:f(V(i0)),_meta:f(l({}))}),TH=w.extend({method:U("notifications/prompts/list_changed"),params:A.optional()}),vH=E({type:U("text"),text:K(),annotations:cH.optional(),_meta:T(K(),h()).optional()}),yH=E({type:U("image"),data:B,mimeType:K(),annotations:cH.optional(),_meta:T(K(),h()).optional()}),_0=E({type:U("audio"),data:B,mimeType:K(),annotations:cH.optional(),_meta:T(K(),h()).optional()}),vW=E({type:U("tool_use"),name:K(),id:K(),input:T(K(),h()),_meta:T(K(),h()).optional()}),sH=E({type:U("resource"),resource:S([gH,z0]),annotations:cH.optional(),_meta:T(K(),h()).optional()}),aH=J0.extend({type:U("resource_link")}),pH=S([vH,yH,_0,aH,sH]),N0=E({role:J,content:pH}),B0=E({title:K().optional(),readOnlyHint:R().optional(),destructiveHint:R().optional(),idempotentHint:R().optional(),openWorldHint:R().optional()}),b0=w.extend({method:U("notifications/tools/list_changed"),params:A.optional()}),I0=E({name:K().optional()}),DW=E({hints:V(I0).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),L0=E({mode:t(["auto","required","none"]).optional()}),yW=E({type:U("boolean"),title:K().optional(),description:K().optional(),default:R().optional()}),k=E({type:U("string"),title:K().optional(),description:K().optional(),minLength:b().optional(),maxLength:b().optional(),format:t(["email","uri","date","date-time"]).optional(),default:K().optional()}),j0=E({type:t(["number","integer"]),title:K().optional(),description:K().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),d=E({type:U("string"),title:K().optional(),description:K().optional(),enum:V(K()),default:K().optional()}),y=E({type:U("string"),title:K().optional(),description:K().optional(),oneOf:V(E({const:K(),title:K()})),default:K().optional()}),e=E({type:U("string"),title:K().optional(),description:K().optional(),enum:V(K()),enumNames:V(K()).optional(),default:K().optional()}),g=S([d,y]),$=E({type:U("array"),title:K().optional(),description:K().optional(),minItems:b().optional(),maxItems:b().optional(),items:E({type:U("string"),enum:V(K())}),default:V(K()).optional()}),n=E({type:U("array"),title:K().optional(),description:K().optional(),minItems:b().optional(),maxItems:b().optional(),items:E({anyOf:V(E({const:K(),title:K()}))}),default:V(K()).optional()}),o=S([$,n]),wH=S([e,g,o]),hW=S([wH,yW,k,j0]),T0=F.extend({mode:U("form").optional(),message:K(),requestedSchema:E({type:U("object"),properties:T(K(),hW),required:V(K()).optional()}).catchall(h())}),fW=E({type:U("ref/resource"),uri:K()}),uW=E({type:U("ref/prompt"),name:K()}),XQ=E({uri:K().startsWith("file://"),name:K().optional(),_meta:T(K(),h()).optional()}),MW=c.shape,YQ=E({experimental:MW.experimental,sampling:MW.sampling,elicitation:MW.elicitation,roots:MW.roots,extensions:MW.extensions}),K0=XH.shape,L8=E({experimental:K0.experimental,logging:K0.logging,completions:K0.completions,prompts:K0.prompts,resources:K0.resources,tools:K0.tools,extensions:K0.extensions}),j8=l({progressToken:Q.optional(),[e0]:K(),[F1]:p.optional(),[X8]:YQ,[E1]:N.optional()}),lW=E({...u.shape,...Z.shape,description:K().optional(),inputSchema:l({$schema:K().optional(),type:U("object")}),outputSchema:l({$schema:K().optional()}).optional(),annotations:B0.optional(),_meta:T(K(),h()).optional()}),JQ=E({type:U("tool_result"),toolUseId:K(),content:V(pH),structuredContent:h().optional(),isError:R().optional(),_meta:T(K(),h()).optional()}),T8=S([vH,yH,_0,vW,JQ]),mW=E({role:J,content:S([T8,V(T8)]),_meta:T(K(),h()).optional()}),$8=K(),R8=l({[HW]:p.optional().catch(void 0)}),C8=R8.optional();function $H(VH){return l({_meta:C8,resultType:$8.default("complete"),...VH})}let NQ=$H({}),D4=$H({nextCursor:X.optional()}),S8=$H({content:V(pH),structuredContent:h().optional(),isError:R().optional()}),BQ=$H({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),tools:V(lW),nextCursor:X.optional()}),KQ=$H({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),prompts:V(P0),nextCursor:X.optional()}),GQ=$H({description:K().optional(),messages:V(N0)}),DQ=$H({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),resources:V(J0),nextCursor:X.optional()}),MQ=$H({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),resourceTemplates:V(Z0),nextCursor:X.optional()}),qQ=$H({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),contents:V(S([gH,z0]))}),_Q=$H({completion:E({values:V(K()).max(100),total:b().int().optional(),hasMore:R().optional()}).loose()}),M4=$H({ttlMs:b().int().min(0),cacheScope:t(["public","private"])}),FQ=$H({ttlMs:b().int().min(0).catch(0),cacheScope:t(["public","private"]).catch("private"),supportedVersions:V(K()),capabilities:L8,instructions:K().optional()}),qW=E({messages:V(mW),modelPreferences:DW.optional(),systemPrompt:K().optional(),includeContext:t(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:V(K()).optional(),metadata:W.optional(),tools:V(lW).optional(),toolChoice:L0.optional()}),EQ=E({method:U("sampling/createMessage"),params:qW}),AQ=E({method:U("roots/list"),params:E({_meta:T(K(),h()).optional()}).optional()}),OQ=E({...mW.shape,model:K(),stopReason:K().optional()}),VQ=E({roots:V(XQ)}),UQ=E({action:t(["accept","decline","cancel"]),content:T(K(),S([K(),b(),R(),V(K())])).optional()}),wQ=E({mode:U("url"),message:K(),url:K().url()}),zQ=S([T0,wQ]),ZQ=E({method:U("elicitation/create"),params:zQ}),PQ=S([EQ,AQ,ZQ]),bQ=S([OQ,VQ,UQ]),IQ=T(K(),PQ),LQ=T(K(),bQ),cW=$H({inputRequests:IQ.optional(),requestState:K().optional()}),pW={inputResponses:LQ.optional(),requestState:K().optional()},q4=E({_meta:j8,...pW}),_4=l({progressToken:Q.optional()});function eH(VH,iW){return E({method:U(VH),params:E({_meta:j8,...iW})})}function H0(VH,iW){return E({method:U(VH),params:E({_meta:_4.optional(),...iW}).optional()})}let jQ={name:K(),arguments:T(K(),h()).optional(),...pW},F0={cursor:X.optional()},F4=eH("tools/call",jQ),E4=eH("tools/list",F0),A4=eH("prompts/list",F0),O4=eH("prompts/get",{name:K(),arguments:T(K(),K()).optional(),...pW}),V4=eH("resources/list",F0),U4=eH("resources/templates/list",F0),w4=eH("resources/read",{uri:K(),...pW}),TQ={ref:S([uW,fW]),argument:E({name:K(),value:K()}),context:E({arguments:T(K(),K()).optional()}).optional()},z4=eH("completion/complete",TQ),Z4=eH("server/discover",{}),k8=E({toolsListChanged:R().optional(),promptsListChanged:R().optional(),resourcesListChanged:R().optional(),resourceSubscriptions:V(K()).optional()}),$Q={notifications:k8},P4=eH("subscriptions/listen",$Q),b4=R8.extend({"io.modelcontextprotocol/subscriptionId":Y}),RQ=l({_meta:b4,resultType:$8.default("complete")}),_W={"tools/call":H0("tools/call",jQ),"tools/list":H0("tools/list",F0),"prompts/get":H0("prompts/get",{name:K(),arguments:T(K(),K()).optional()}),"prompts/list":H0("prompts/list",F0),"resources/list":H0("resources/list",F0),"resources/templates/list":H0("resources/templates/list",F0),"resources/read":H0("resources/read",{uri:K()}),"completion/complete":H0("completion/complete",TQ),"server/discover":H0("server/discover",{}),"subscriptions/listen":H0("subscriptions/listen",$Q)};function dH(VH){return l({_meta:C8,...VH})}let I4={"tools/call":dH({content:V(pH),structuredContent:h().optional(),isError:R().optional()}),"tools/list":dH({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),tools:V(lW),nextCursor:X.optional()}),"prompts/get":dH({description:K().optional(),messages:V(N0)}),"prompts/list":dH({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),prompts:V(P0),nextCursor:X.optional()}),"resources/list":dH({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),resources:V(J0),nextCursor:X.optional()}),"resources/templates/list":dH({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),resourceTemplates:V(Z0),nextCursor:X.optional()}),"resources/read":dH({ttlMs:b().int().min(0),cacheScope:t(["public","private"]),contents:V(S([gH,z0]))}),"completion/complete":dH({completion:E({values:V(K()).max(100),total:b().int().optional(),hasMore:R().optional()}).loose()}),"server/discover":dH({ttlMs:b().int().min(0).catch(0),cacheScope:t(["public","private"]).catch("private"),supportedVersions:V(K()),capabilities:L8,instructions:K().optional()}),"subscriptions/listen":dH({})},dW=l({"io.modelcontextprotocol/subscriptionId":Y.optional()}),g8=E({method:U("notifications/subscriptions/acknowledged"),params:E({_meta:dW.optional(),notifications:k8})}),x8=E({_meta:dW.optional(),requestId:Y,reason:K().optional()}),v8=E({method:U("notifications/cancelled"),params:x8}),JJ={"notifications/cancelled":v8,"notifications/progress":kH,"notifications/message":DH,"notifications/resources/updated":d0,"notifications/resources/list_changed":tH,"notifications/tools/list_changed":b0,"notifications/prompts/list_changed":TH,"notifications/subscriptions/acknowledged":g8},hH=(VH)=>E({jsonrpc:U("2.0"),id:S([K(),b().int()]),result:VH}).strict();return{JSONValueSchema:H,JSONObjectSchema:W,ProgressTokenSchema:Q,CursorSchema:X,RequestIdSchema:Y,RoleSchema:J,LoggingLevelSchema:N,TaskMetadataSchema:G,RelatedTaskMetadataSchema:D,RequestMetaSchema:M,BaseRequestParamsSchema:_,TaskAugmentedRequestParamsSchema:F,NotificationsParamsSchema:A,NotificationSchema:w,IconSchema:z,IconsSchema:Z,BaseMetadataSchema:u,ImplementationSchema:p,ClientTasksCapabilitySchema:I,ServerTasksCapabilitySchema:P,ClientCapabilitiesSchema:c,ServerCapabilitiesSchema:XH,ProgressSchema:WH,ProgressNotificationParamsSchema:MH,ProgressNotificationSchema:kH,LoggingMessageNotificationParamsSchema:NH,LoggingMessageNotificationSchema:DH,ResourceContentsSchema:IH,TextResourceContentsSchema:gH,BlobResourceContentsSchema:z0,AnnotationsSchema:cH,ResourceSchema:J0,ResourceTemplateSchema:Z0,ResourceListChangedNotificationSchema:tH,ResourceUpdatedNotificationParamsSchema:xH,ResourceUpdatedNotificationSchema:d0,PromptArgumentSchema:i0,PromptSchema:P0,PromptListChangedNotificationSchema:TH,TextContentSchema:vH,ImageContentSchema:yH,AudioContentSchema:_0,ToolUseContentSchema:vW,EmbeddedResourceSchema:sH,ResourceLinkSchema:aH,ContentBlockSchema:pH,PromptMessageSchema:N0,ToolAnnotationsSchema:B0,ToolListChangedNotificationSchema:b0,ModelHintSchema:I0,ModelPreferencesSchema:DW,ToolChoiceSchema:L0,BooleanSchemaSchema:yW,StringSchemaSchema:k,NumberSchemaSchema:j0,UntitledSingleSelectEnumSchemaSchema:d,TitledSingleSelectEnumSchemaSchema:y,LegacyTitledEnumSchemaSchema:e,SingleSelectEnumSchemaSchema:g,UntitledMultiSelectEnumSchemaSchema:$,TitledMultiSelectEnumSchemaSchema:n,MultiSelectEnumSchemaSchema:o,EnumSchemaSchema:wH,PrimitiveSchemaDefinitionSchema:hW,ElicitRequestFormParamsSchema:T0,ResourceTemplateReferenceSchema:fW,PromptReferenceSchema:uW,RootSchema:XQ,ClientCapabilities2026Schema:YQ,ServerCapabilities2026Schema:L8,RequestMetaEnvelopeSchema:j8,ToolSchema:lW,ToolResultContentSchema:JQ,SamplingMessageContentBlockSchema:T8,SamplingMessageSchema:mW,ResultTypeSchema:$8,ResultMetaSchema:R8,ResultSchema:NQ,PaginatedResultSchema:D4,CallToolResultSchema:S8,ListToolsResultSchema:BQ,ListPromptsResultSchema:KQ,GetPromptResultSchema:GQ,ListResourcesResultSchema:DQ,ListResourceTemplatesResultSchema:MQ,ReadResourceResultSchema:qQ,CompleteResultSchema:_Q,CacheableResultSchema:M4,DiscoverResultSchema:FQ,CreateMessageRequestParamsSchema:qW,CreateMessageRequestSchema:EQ,ListRootsRequestSchema:AQ,CreateMessageResultSchema:OQ,ListRootsResultSchema:VQ,ElicitResultSchema:UQ,ElicitRequestURLParamsSchema:wQ,ElicitRequestParamsSchema:zQ,ElicitRequestSchema:ZQ,InputRequestSchema:PQ,InputResponseSchema:bQ,InputRequestsSchema:IQ,InputResponsesSchema:LQ,InputRequiredResultSchema:cW,InputResponseRequestParamsSchema:q4,CallToolRequestSchema:F4,ListToolsRequestSchema:E4,ListPromptsRequestSchema:A4,GetPromptRequestSchema:O4,ListResourcesRequestSchema:V4,ListResourceTemplatesRequestSchema:U4,ReadResourceRequestSchema:w4,CompleteRequestSchema:z4,DiscoverRequestSchema:Z4,SubscriptionFilterSchema:k8,SubscriptionsListenRequestSchema:P4,SubscriptionsListenResultMetaSchema:b4,SubscriptionsListenResultSchema:RQ,dispatchRequestSchemas:_W,dispatchResultSchemas:I4,NotificationMetaSchema:dW,SubscriptionsAcknowledgedNotificationSchema:g8,CancelledNotificationParamsSchema:x8,CancelledNotificationSchema:v8,notificationSchemas2026:JJ,JSONRPCResultResponseSchema:hH(NQ),CallToolResultResponseSchema:hH(S([S8,cW])),ListToolsResultResponseSchema:hH(BQ),ListPromptsResultResponseSchema:hH(KQ),GetPromptResultResponseSchema:hH(S([GQ,cW])),ListResourcesResultResponseSchema:hH(DQ),ListResourceTemplatesResultResponseSchema:hH(MQ),ReadResourceResultResponseSchema:hH(S([qQ,cW])),CompleteResultResponseSchema:hH(_Q),DiscoverResultResponseSchema:hH(FQ),SubscriptionsListenResultResponseSchema:hH(RQ)}}var QF;function CW(){return QF??=WF()}var XF=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function YF(H){return XF.includes(H)}var VB=Symbol("modelcontextprotocol.resultCacheHintFallback");function JF(H){return H[VB]}function cG(H){return typeof H==="number"&&Number.isSafeInteger(H)&&H>=0}function pG(H){return H==="public"||H==="private"}var r=function(H){return H[H.ParseError=-32700]="ParseError",H[H.InvalidRequest=-32600]="InvalidRequest",H[H.MethodNotFound=-32601]="MethodNotFound",H[H.InvalidParams=-32602]="InvalidParams",H[H.InternalError=-32603]="InternalError",H[H.ResourceNotFound=-32002]="ResourceNotFound",H[H.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",H[H.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",H[H.UrlElicitationRequired=-32042]="UrlElicitationRequired",H}({}),JH=class H extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](W){return Y0(this,W)}static isInstance(W){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Y0(this,W)}constructor(W,Q,X){super(Q);this.code=W,this.data=X,this.name="ProtocolError",V8(this,new.target)}static fromError(W,Q,X){if(W===r.UrlElicitationRequired&&X){let Y=X;if(Y.elicitations)return new iG(Y.elicitations,Q)}if(W===r.UnsupportedProtocolVersion&&X){let Y=X;if(Array.isArray(Y.supported)&&typeof Y.requested==="string")return new h9({supported:Y.supported,requested:Y.requested},Q)}if(W===r.InvalidParams||W===r.ResourceNotFound){let Y=X;if(typeof Y?.uri==="string"&&(W===r.ResourceNotFound||Object.keys(Y).length===1))return new dG(Y.uri,Q)}if(W===r.MissingRequiredClientCapability&&X){let Y=X;if(Y.requiredCapabilities!==null&&typeof Y.requiredCapabilities==="object"&&!Array.isArray(Y.requiredCapabilities))return new oG({requiredCapabilities:Y.requiredCapabilities},Q)}return new H(W,Q,X)}},dG=class extends JH{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(H,W=`Resource not found: ${H}`){super(r.InvalidParams,W,{uri:H})}get uri(){return this.data.uri}},iG=class extends JH{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(H,W=`URL elicitation${H.length>1?"s":""} required`){super(r.UrlElicitationRequired,W,{elicitations:H})}get elicitations(){return this.data?.elicitations??[]}},h9=class extends JH{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(H,W=`Unsupported protocol version: ${H.requested}`){super(r.UnsupportedProtocolVersion,W,H)}get supported(){return this.data.supported}get requested(){return this.data.requested}},oG=class extends JH{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(H,W=`Missing required client capabilities: ${Object.keys(H.requiredCapabilities).join(", ")}`){super(r.MissingRequiredClientCapability,W,H)}get requiredCapabilities(){return this.data.requiredCapabilities}},NF=0,BF="private",KF=["tools/call","prompts/get","resources/read"];function GF(H,W){let Q=W.resultType;if(Q===void 0)return{...W,resultType:"complete"};if(Q==="complete")return W;if(KF.includes(H))return W;throw new JH(r.InternalError,`Handler for ${H} returned resultType '${String(Q)}', but results of ${H} only support 'complete' on protocol revision 2026-07-28`)}function DF(H,W){let Q=JF(W);if(W.resultType!=="complete"||!YF(H))return Q===void 0?W:EF(W);let X=W,Y=cG(X.ttlMs)?X.ttlMs:_F(Q),J=pG(X.cacheScope)?X.cacheScope:FF(Q),N={...X,ttlMs:Y,cacheScope:J};return delete N[VB],N}function MF(H){return H!==null&&typeof H==="object"&&!Array.isArray(H)}function qF(H,W){if(W===void 0)return H;let Q=H._meta;if(Q===void 0)return{...H,_meta:{[HW]:W}};if(!MF(Q))return H;if(Q[HW]!==void 0)return H;return{...H,_meta:{...Q,[HW]:W}}}function _F(H){return H!==void 0&&cG(H.ttlMs)?H.ttlMs:NF}function FF(H){return H!==void 0&&pG(H.cacheScope)?H.cacheScope:BF}function EF(H){let W={...H};return delete W[VB],W}var AF=["elicitation/create","sampling/createMessage","roots/list"],g9;function nG(){if(g9)return g9;let H=CW();return g9={request:{"elicitation/create":E({method:U("elicitation/create"),params:H.ElicitRequestParamsSchema}),"sampling/createMessage":E({method:U("sampling/createMessage"),params:H.CreateMessageRequestParamsSchema}),"roots/list":E({method:U("roots/list"),params:l({}).optional()})},response:{"elicitation/create":H.ElicitResultSchema,"sampling/createMessage":H.CreateMessageResultSchema,"roots/list":H.ListRootsResultSchema}},g9}function rG(H){return AF.includes(H)}function YB(H){return rG(H)?nG().request[H]:void 0}function OF(H){return rG(H)?nG().response[H]:void 0}var UB={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},tG={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function sG(H){return Object.prototype.hasOwnProperty.call(UB,H)}function aG(H){return Object.prototype.hasOwnProperty.call(tG,H)}function VF(H){return Object.prototype.hasOwnProperty.call(UB,H)}function UF(H){return sG(H)?CW().dispatchRequestSchemas[H]:void 0}function wF(H){return VF(H)?CW().dispatchResultSchemas[H]:void 0}function zF(H){return aG(H)?CW().notificationSchemas2026[H]:void 0}var XU=Object.keys(UB),YU=Object.keys(tG);function iY(H){return H!==null&&typeof H==="object"&&!Array.isArray(H)}function pY(H,W){if(H===void 0)return{ok:!1,reason:"not-in-era"};let Q=H.safeParse(W);return Q.success?{ok:!0,value:Q.data}:{ok:!1,reason:"invalid",message:String(Q.error)}}var ZF={ok:!1,reason:"not-in-era"},PF=[e0,X8];function bF(H,W){let Q=W,X=!1,Y=()=>{if(!X)Q={...Q},X=!0;return Q},J=W.tools;if(H==="tools/list"&&Array.isArray(J)&&J.some((B)=>iY(B)&&("execution"in B)))Y().tools=J.map((B)=>{if(!iY(B)||!("execution"in B))return B;let G={...B};return delete G.execution,G});let N=W.capabilities;if(iY(N)&&"tasks"in N){let B={...N};delete B.tasks,Y().capabilities=B}return Q}var wB={era:"2026-07-28",hasRequestMethod:sG,hasNotificationMethod:aG,hasInputRequestMethod:(H)=>YB(H)!==void 0,validateRequest:(H,W)=>pY(UF(H),W),validateResult:(H,W)=>pY(wF(H),W),validateNotification:(H,W)=>pY(zF(H),W),validateInputRequest:(H,W)=>pY(YB(H),W),validateInputResponse:(H,W)=>pY(OF(H),W),samplingResultVariant:()=>ZF,outboundEnvelope(H){return{[e0]:H.protocolVersion,[F1]:H.clientInfo,[X8]:H.clientCapabilities,...H.logLevel!==void 0&&{[E1]:H.logLevel}}},validateEnvelopeMeta(H){let W=[];for(let X of PF)if(!(X in H))W.push({key:X,problem:"missing"});let Q=CW().RequestMetaEnvelopeSchema.safeParse(H);if(!Q.success)for(let X of Q.error.issues){let Y=X.path.map(String),J=Y.length>0?Y.join("."):"_meta";if(Y.length===1&&W.some((N)=>N.key===J&&N.problem==="missing"))continue;W.push({key:J,problem:X.message})}return W},projectCallToolResult:(H)=>xG(H),inputRequestSchema:YB,decodeResult(H,W){if(!iY(W))return{kind:"invalid",error:new v(x.InvalidResult,`Invalid result for ${H}: not an object`,{method:H})};let Q=W.resultType;if(Q===void 0)return{kind:"invalid",error:new v(x.InvalidResult,`Invalid result for ${H}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:H,violation:"missing-resultType"})};if(typeof Q!=="string")return{kind:"invalid",error:new v(x.InvalidResult,`Invalid result for ${H}: non-string resultType`,{method:H,resultType:Q})};if(Q==="input_required"){let N=W.inputRequests,B=iY(N)?N:{},G=W.requestState,D=W._meta===void 0?void 0:CW().ResultMetaSchema.safeParse(W._meta),M=D?.success?D.data:void 0;if(Object.keys(B).length===0&&typeof G!=="string")return{kind:"invalid",error:new v(x.InvalidResult,`Invalid result for ${H}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:H,violation:"input-required-missing-both"})};return{kind:"input_required",inputRequests:B,...typeof G==="string"&&{requestState:G},...M!==void 0&&{_meta:M}}}if(Q!=="complete")return{kind:"invalid",error:new v(x.UnsupportedResultType,`Unsupported result type '${Q}' for ${H}`,{resultType:Q,method:H})};let X=IF(),Y=Object.hasOwn(X,H)?X[H]:void 0;if(Y!==void 0){let N=Y.safeParse(W);if(!N.success)return{kind:"invalid",error:new v(x.InvalidResult,`Invalid result for ${H}: ${N.error}`,{method:H})}}let J={...W};return delete J.resultType,{kind:"complete",result:J}},encodeResult(H,W,Q){return qF(DF(H,GF(H,bF(H,W))),Q)},encodeErrorCode:(H)=>H===-32002?-32602:H,checkInboundEnvelope(H){if(H.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let W=CW().RequestMetaEnvelopeSchema.safeParse(H.envelope);if(!W.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${W.error.issues.map((Q)=>Q.message).join("; ")}`}},x9;function IF(){if(x9)return x9;let H=CW();return x9={"tools/call":H.CallToolResultSchema,"tools/list":H.ListToolsResultSchema,"prompts/get":H.GetPromptResultSchema,"prompts/list":H.ListPromptsResultSchema,"resources/list":H.ListResourcesResultSchema,"resources/templates/list":H.ListResourceTemplatesResultSchema,"resources/read":H.ReadResourceResultSchema,"completion/complete":H.CompleteResultSchema,"server/discover":H.DiscoverResultSchema},x9}var f9="2026-07-28";function NW(H){return H!==void 0&&KW(H)?wB:OB}function ZG(H){if(H.revision!==void 0)return NW(H.revision).era;return H.era==="modern"?wB.era:OB.era}function JB(H){return eG.some((W)=>W.hasRequestMethod(H))}function NB(H){return eG.some((W)=>W.hasNotificationMethod(H))}function PG(H){return H==="tasks/get"||H==="tasks/cancel"}var eG=[OB,wB],LF=q2({AnnotationsSchema:()=>y0,AudioContentSchema:()=>D8,BaseMetadataSchema:()=>x0,BaseRequestParamsSchema:()=>bH,BlobResourceContentsSchema:()=>R1,BooleanSchemaSchema:()=>g1,CallToolRequestParamsSchema:()=>XY,CallToolRequestSchema:()=>YY,CallToolResultSchema:()=>RW,CancelTaskRequestSchema:()=>Z9,CancelTaskResultSchema:()=>P9,CancelledNotificationParamsSchema:()=>_X,CancelledNotificationSchema:()=>Z1,ClientCapabilitiesSchema:()=>EX,ClientNotificationSchema:()=>I9,ClientRequestSchema:()=>b9,ClientResultSchema:()=>L9,ClientTasksCapabilitySchema:()=>D9,CompatibilityCallToolResultSchema:()=>q9,CompleteRequestParamsSchema:()=>CY,CompleteRequestSchema:()=>SY,CompleteResultSchema:()=>kY,ContentBlockSchema:()=>h0,CreateMessageRequestParamsSchema:()=>AY,CreateMessageRequestSchema:()=>OY,CreateMessageResultSchema:()=>VY,CreateMessageResultWithToolsSchema:()=>UY,CreateTaskResultSchema:()=>F9,CursorSchema:()=>O1,DiscoverRequestSchema:()=>VX,DiscoverResultSchema:()=>TW,ElicitRequestFormParamsSchema:()=>A8,ElicitRequestParamsSchema:()=>bY,ElicitRequestSchema:()=>IY,ElicitRequestURLParamsSchema:()=>PY,ElicitResultSchema:()=>TY,ElicitationCompleteNotificationParamsSchema:()=>LY,ElicitationCompleteNotificationSchema:()=>jY,EmbeddedResourceSchema:()=>M8,EmptyResultSchema:()=>jW,EnumSchemaSchema:()=>ZY,GetPromptRequestParamsSchema:()=>oX,GetPromptRequestSchema:()=>nX,GetPromptResultSchema:()=>sX,GetTaskPayloadRequestSchema:()=>V9,GetTaskPayloadResultSchema:()=>U9,GetTaskRequestSchema:()=>A9,GetTaskResultSchema:()=>O9,IconSchema:()=>FX,IconsSchema:()=>WW,ImageContentSchema:()=>G8,ImplementationSchema:()=>v0,InitializeRequestParamsSchema:()=>AX,InitializeRequestSchema:()=>P1,InitializeResultSchema:()=>OX,InitializedNotificationSchema:()=>I1,JSONArraySchema:()=>K9,JSONObjectSchema:()=>qH,JSONRPCErrorResponseSchema:()=>N8,JSONRPCMessageSchema:()=>V0,JSONRPCNotificationSchema:()=>z1,JSONRPCRequestSchema:()=>w1,JSONRPCResponseSchema:()=>G9,JSONRPCResultResponseSchema:()=>J8,JSONValueSchema:()=>a0,LegacyTitledEnumSchemaSchema:()=>y1,ListChangedOptionsBaseSchema:()=>NY,ListPromptsRequestSchema:()=>dX,ListPromptsResultSchema:()=>iX,ListResourceTemplatesRequestSchema:()=>IX,ListResourceTemplatesResultSchema:()=>LX,ListResourcesRequestSchema:()=>PX,ListResourcesResultSchema:()=>bX,ListRootsRequestSchema:()=>xY,ListRootsResultSchema:()=>vY,ListTasksRequestSchema:()=>w9,ListTasksResultSchema:()=>z9,ListToolsRequestSchema:()=>WY,ListToolsResultSchema:()=>QY,LoggingLevelSchema:()=>k1,LoggingMessageNotificationParamsSchema:()=>GY,LoggingMessageNotificationSchema:()=>_8,ModelHintSchema:()=>DY,ModelPreferencesSchema:()=>MY,MultiSelectEnumSchemaSchema:()=>zY,NotificationSchema:()=>jH,NotificationsParamsSchema:()=>SH,NumberSchemaSchema:()=>E8,PaginatedRequestParamsSchema:()=>zX,PaginatedRequestSchema:()=>QW,PaginatedResultSchema:()=>XW,PingRequestSchema:()=>L1,PrimitiveSchemaDefinitionSchema:()=>u1,ProgressNotificationParamsSchema:()=>wX,ProgressNotificationSchema:()=>j1,ProgressSchema:()=>UX,ProgressTokenSchema:()=>A1,PromptArgumentSchema:()=>cX,PromptListChangedNotificationSchema:()=>aX,PromptMessageSchema:()=>tX,PromptReferenceSchema:()=>RY,PromptSchema:()=>pX,ReadResourceRequestParamsSchema:()=>jX,ReadResourceRequestSchema:()=>TX,ReadResourceResultSchema:()=>$X,RelatedTaskMetadataSchema:()=>qX,RequestIdSchema:()=>O0,RequestMetaSchema:()=>V1,RequestSchema:()=>_H,ResourceContentsSchema:()=>T1,ResourceLinkSchema:()=>q8,ResourceListChangedNotificationSchema:()=>RX,ResourceRequestParamsSchema:()=>B8,ResourceSchema:()=>C1,ResourceTemplateReferenceSchema:()=>$Y,ResourceTemplateSchema:()=>ZX,ResourceUpdatedNotificationParamsSchema:()=>lX,ResourceUpdatedNotificationSchema:()=>mX,ResultMetaObjectSchema:()=>U1,ResultSchema:()=>FH,RoleSchema:()=>YW,RootSchema:()=>gY,RootsListChangedNotificationSchema:()=>yY,SamplingContentSchema:()=>FY,SamplingMessageContentBlockSchema:()=>IW,SamplingMessageSchema:()=>EY,ServerCapabilitiesSchema:()=>b1,ServerNotificationSchema:()=>T9,ServerRequestSchema:()=>j9,ServerResultSchema:()=>$9,ServerTasksCapabilitySchema:()=>M9,SetLevelRequestParamsSchema:()=>BY,SetLevelRequestSchema:()=>KY,SingleSelectEnumSchemaSchema:()=>wY,StringSchemaSchema:()=>F8,SubscribeRequestParamsSchema:()=>CX,SubscribeRequestSchema:()=>SX,SubscriptionFilterSchema:()=>S1,SubscriptionsAcknowledgedNotificationParamsSchema:()=>yX,SubscriptionsAcknowledgedNotificationSchema:()=>hX,SubscriptionsListenRequestParamsSchema:()=>xX,SubscriptionsListenRequestSchema:()=>vX,SubscriptionsListenResultMetaSchema:()=>fX,SubscriptionsListenResultSchema:()=>uX,TaskAugmentedRequestParamsSchema:()=>LW,TaskCreationParamsSchema:()=>_9,TaskMetadataSchema:()=>MX,TaskSchema:()=>JW,TaskStatusNotificationParamsSchema:()=>fY,TaskStatusNotificationSchema:()=>E9,TaskStatusSchema:()=>hY,TextContentSchema:()=>K8,TextResourceContentsSchema:()=>$1,TitledMultiSelectEnumSchemaSchema:()=>f1,TitledSingleSelectEnumSchemaSchema:()=>v1,ToolAnnotationsSchema:()=>eX,ToolChoiceSchema:()=>qY,ToolExecutionSchema:()=>HY,ToolListChangedNotificationSchema:()=>JY,ToolResultContentSchema:()=>_Y,ToolSchema:()=>$W,ToolUseContentSchema:()=>rX,UnsubscribeRequestParamsSchema:()=>kX,UnsubscribeRequestSchema:()=>gX,UntitledMultiSelectEnumSchemaSchema:()=>h1,UntitledSingleSelectEnumSchemaSchema:()=>x1});var w8=(H)=>w1.safeParse(H).success,HD=(H)=>z1.safeParse(H).success,o1=(H)=>J8.safeParse(H).success,n1=(H)=>N8.safeParse(H).success;var WD=(H)=>typeof H==="object"&&H!==null&&!Array.isArray(H)&&H.resultType==="input_required";var zB=(H)=>P1.safeParse(H).success,QD=(H)=>I1.safeParse(H).success;var jF="Mcp-Param-",bG="x-mcp-header",TF=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,$F=new Set(["string","integer","boolean","number"]);function ZB(H){let W=[],Q=new Map,X=(J,N,B)=>{if(J===null||typeof J!=="object")return;let G=J;if(bG in G){if(!B||N.length===0)return`${v9(N)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let M=G[bG];if(typeof M!=="string"||M.length===0)return`${v9(N)}: x-mcp-header MUST be a non-empty string`;if(!TF.test(M))return`${v9(N)}: x-mcp-header '${M}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let _=typeof G.type==="string"?G.type:void 0;if(_===void 0||!$F.has(_))return`${v9(N)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${_??"<none>"}`;let F=M.toLowerCase(),A=Q.get(F);if(A!==void 0)return`x-mcp-header '${M}' is not case-insensitively unique (also declared as '${A}')`;Q.set(F,M),W.push({path:N,headerName:M,type:_})}let D=G.properties;if(D!==null&&typeof D==="object")for(let[M,_]of Object.entries(D)){let F=X(_,[...N,M],B);if(F!==void 0)return F}for(let M of RF){let _=G[M];if(_===void 0)continue;let F=Array.isArray(_)?_:_!==null&&typeof _==="object"&&CF.has(M)?Object.values(_):[_];for(let A of F){let w=X(A,[...N,`<${M}>`],!1);if(w!==void 0)return w}}},Y=X(H,[],!0);return Y===void 0?{valid:!0,declarations:W}:{valid:!1,reason:Y}}var RF=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],CF=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function v9(H){return H.length===0?"<root>":H.join(".")}var XD="=?base64?",YD="?=";function SF(H){if(typeof H==="string")return H;if(typeof H==="boolean")return H?"true":"false";if(typeof H==="number"){if(!Number.isFinite(H))return;if(Number.isInteger(H)&&!Number.isSafeInteger(H))return;return String(H)}}function kF(H){if(H.length===0)return!0;if(H.startsWith(XD)&&H.endsWith(YD))return!0;if(H!==H.trim())return!0;for(let W=0;W<H.length;W++){let Q=H.codePointAt(W);if(Q===9||Q>=32&&Q<=126)continue;return!0}return!1}function gF(H){let W=new TextEncoder().encode(H),Q="";for(let X of W)Q+=String.fromCodePoint(X);return btoa(Q)}function PB(H){return kF(H)?`${XD}${gF(H)}${YD}`:H}function xF(H,W){let Q=H;for(let X of W){if(Q===null||typeof Q!=="object")return;Q=Q[X]}return Q}function JD(H,W){let Q={};for(let X of H){let Y=xF(W,X.path);if(Y===void 0||Y===null)continue;let J=SF(Y);if(J===void 0)continue;Q[`${jF}${X.headerName}`]=PB(J)}return Q}var i1=-32020,JU=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[r.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[i1,r.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[r.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[r.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[r.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[i1],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half — including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[r.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[i1],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],NU={[r.ParseError]:400,[r.InvalidRequest]:400,[r.MethodNotFound]:404,[r.UnsupportedProtocolVersion]:400,[r.MissingRequiredClientCapability]:400,[i1]:400},IG={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function ND(H,W){let Q=Object.hasOwn(IG,H)?IG[H]:void 0;if(Q===void 0)return;let X=vF(W)?W[Q]:void 0;return{field:Q,value:typeof X==="string"?X:void 0}}function vF(H){return H!==null&&typeof H==="object"&&!Array.isArray(H)}function u9(H,W){return aQ(H,W)}function dY(H){return new Set(H.flatMap((W)=>Object.keys(W.shape)))}function DB(H){if(H==null)return!1;let W=typeof H;if(W!=="object"&&W!=="function")return!1;if(!("~standard"in H))return!1;return typeof H["~standard"]?.validate==="function"}var LG=!1,MB="draft-2020-12";function yF(H,W="input"){let Q=H["~standard"],X;if(Q.jsonSchema)X=Q.jsonSchema[W]({target:MB});else if(Q.vendor==="zod"){if(!("_zod"in H))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");if(!LG)LG=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.");X=W8(H,{target:MB,io:W})}else throw Error(`Schema library "${Q.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(W==="output"){if(X.type!==void 0)return X;return BD(X)?{type:"object",...X}:X}if(X.type!==void 0&&X.type!=="object")throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(X.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...X}}function BD(H){if("properties"in H||"patternProperties"in H||"additionalProperties"in H||"required"in H)return!0;for(let W of["oneOf","anyOf","allOf"]){let Q=H[W];if(Array.isArray(Q)&&Q.length>0)return Q.every((X)=>X!==null&&typeof X==="object"&&(X.type==="object"||BD(X)))}return!1}function hF(H){if(!H.path?.length)return H.message;return`${H.path.map((W)=>String(typeof W==="object"?W.key:W)).join(".")}: ${H.message}`}async function BB(H,W){let Q=await H["~standard"].validate(W);if(Q.issues&&Q.issues.length>0)return{success:!1,error:Q.issues.map((X)=>hF(X)).join(", ")};return{success:!0,data:Q.value}}function fF(H){let W=W8(H,{target:MB,io:"input"});return typeof W.pattern==="string"?W.pattern:void 0}var uF=/\\\.\\d\{(\d+)\}/;function lF(H){let W=uF.exec(H),Q=[void 0,-1,0];if(W)Q.push(Number(W[1]));return[!1,!0].flatMap((X)=>[!1,!0].flatMap((Y)=>Q.map((J)=>X0.datetime({local:X,offset:Y,precision:J}))))}function mF(H,W){let Q;switch(H){case"email":Q=[h6()];break;case"uri":Q=[K1()];break;case"date":Q=[X0.date()];break;case"date-time":Q=lF(W);break}return new Set(Q.map((X)=>fF(X)).filter((X)=>X!==void 0))}function cF(H,W,Q){if(Q!=="zod")return!0;return mF(H,W).has(W)}function nY(H){return typeof H==="object"&&H!==null&&!Array.isArray(H)}function pF(H){try{return yF(H,"input")}catch(W){let Q=W instanceof Error?W.message:String(W);throw new JH(r.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${Q}`)}}var dF=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function bB(H){return dF.has(H)||H.startsWith("x-")}var iF=new Set(["$schema",...Object.keys(A8.shape.requestedSchema.shape)]),jG={string:dY([F8,x1,v1,y1]),number:dY([E8]),integer:dY([E8]),boolean:dY([g1]),array:dY([h1,f1])},oF=new Set(F8.shape.format.unwrap().options);function nF(H,W,Q,X){if(!nY(H))return H;let Y=typeof H.type==="string"&&Object.hasOwn(jG,H.type)?jG[H.type]:void 0;if(Y===void 0)return H;let J={};for(let[N,B]of Object.entries(H))if(Y.has(N)||bB(N))J[N]=B;else if(N==="pattern"&&H.type==="string"&&typeof H.format==="string"){if(!oF.has(H.format))J[N]=B;else if(typeof B!=="string"||!cF(H.format,B,Q))X.push(`${W}.${N}`)}else X.push(`${W}.${N}`);return J}function rF(H,W){let Q={},X=[];for(let[Y,J]of Object.entries(H))if(Y==="properties"&&nY(J))Q[Y]=Object.fromEntries(Object.entries(J).map(([N,B])=>[N,nF(B,`properties.${N}`,W,X)]));else if(iF.has(Y))Q[Y]=J;else if(!bB(Y))X.push(Y);if(X.length>0)throw new JH(r.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${X.join(", ")}`);return Q}function tF(H,W){if(!nY(H.properties))return W;let Q=Object.entries(H.properties).filter(([,X])=>!u9(u1,X).success).map(([X])=>`properties.${X}`);return Q.length>0?Q.join(", "):W}function qB(H,W,Q=""){if(Array.isArray(H)&&Array.isArray(W))return H.flatMap((X,Y)=>qB(X,W[Y],`${Q}[${Y}]`));if(!nY(H)||!nY(W))return[];return Object.entries(H).flatMap(([X,Y])=>{let J=Q?`${Q}.${X}`:X;if(!Object.prototype.hasOwnProperty.call(W,X))return bB(X)?[]:[J];return qB(Y,W[X],J)})}function sF(H){if(!DB(H.requestedSchema))return{...H,mode:"form",requestedSchema:H.requestedSchema};let W=H.requestedSchema["~standard"].vendor,Q=rF(pF(H.requestedSchema),W),X=u9(A8.shape.requestedSchema,Q);if(!X.success)throw new JH(r.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${tF(Q,X.error.message)}`);let Y=qB(Q,X.data);if(Y.length>0)throw new JH(r.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${Y.join(", ")}`);let J=(X.data.required??[]).filter((N)=>!Object.prototype.hasOwnProperty.call(X.data.properties,N));if(J.length>0)throw new JH(r.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${J.join(", ")}`);return{...H,mode:"form",requestedSchema:X.data}}function aF(H){let W=H.inputRequests!==void 0&&Object.keys(H.inputRequests).length>0,Q=typeof H.requestState==="string";if(!W&&!Q)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...H.inputRequests!==void 0&&{inputRequests:H.inputRequests},...H.requestState!==void 0&&{requestState:H.requestState}}}var BU=Object.assign(aF,{elicit(H){try{return{method:"elicitation/create",params:sF(H)}}catch(W){throw W instanceof JH?TypeError(W.message,{cause:W}):W}},elicitUrl(H){return{method:"elicitation/create",params:{...H,mode:"url"}}},createMessage(H){return{method:"sampling/createMessage",params:H}},listRoots(){return{method:"roots/list"}}});var eF=!0,HE=10,WE=250;function KD(H){return{autoFulfill:H?.autoFulfill??eF,maxRounds:H?.maxRounds??HE}}function QE(H,W,Q){let X=W!==void 0&&Object.keys(W).length>0;if(!X&&Q===void 0)return H;return{...H,...X&&{inputResponses:W},...Q!==void 0&&{requestState:Q}}}function XE(H,W){return`Multi-round-trip request '${H}' still required input after ${W} rounds (inputRequired.maxRounds)`}function YE(H,W){return new Promise((Q,X)=>{if(W?.aborted){X(W.reason instanceof v?W.reason:new v(x.RequestTimeout,String(W.reason)));return}let Y=setTimeout(()=>{W?.removeEventListener("abort",J),Q()},H),J=()=>{clearTimeout(Y),X(W?.reason instanceof v?W.reason:new v(x.RequestTimeout,String(W?.reason)))};W?.addEventListener("abort",J,{once:!0})})}function JE(H){let W=new AbortController,Q=()=>W.abort(H?.reason);if(H?.addEventListener("abort",Q,{once:!0}),H?.aborted)W.abort(H.reason);return{signal:W.signal,abort:(X)=>W.abort(X),dispose:()=>H?.removeEventListener("abort",Q)}}async function NE(H){let{config:W,method:Q,originalParams:X,requestOptions:Y,hooks:J,signal:N}=H,B=H.flowStartedAt??Date.now(),G=H.firstPayload,D=0;while(!0){if(D+=1,D>W.maxRounds)throw new v(x.InputRequiredRoundsExceeded,XE(Q,W.maxRounds),{rounds:W.maxRounds,lastResult:{inputRequests:G.inputRequests,...G.requestState!==void 0&&{requestState:G.requestState}}});Y.onprogress?.({progress:D,message:`Fulfilling input required by '${Q}' (round ${D})`});let M=Object.entries(G.inputRequests??{}),_;if(M.length>0){let w=JE(N);try{let z=await Promise.all(M.map(async([Z,u])=>{try{return[Z,await J.dispatchInputRequest(Z,u,w.signal)]}catch(p){throw w.abort(p),p}}));_=Object.fromEntries(z)}finally{w.dispose()}}else await YE(WE,N);let F={...Y.timeout!==void 0&&{timeout:Y.timeout}};if(Y.maxTotalTimeout!==void 0){let w=Date.now()-B,z=Y.maxTotalTimeout-w;if(z<=0)throw new v(x.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:w});F.maxTotalTimeout=z}let A=await J.retry(QE(X,_,G.requestState),F);if(WD(A)){G={inputRequests:A.inputRequests??{},...A.requestState!==void 0&&{requestState:A.requestState}};continue}return A}}var BE=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],KE={IdJagTokenExchangeResponseSchema:lY,OAuthClientInformationFullSchema:d1,OAuthClientInformationSchema:cY,OAuthClientMetadataSchema:mY,OAuthClientRegistrationErrorSchema:R9,OAuthErrorResponseSchema:p1,OAuthMetadataSchema:O8,OAuthProtectedResourceMetadataSchema:l1,OAuthTokenRevocationRequestSchema:C9,OAuthTokensSchema:c1,OpenIdProviderDiscoveryMetadataSchema:m1,OpenIdProviderMetadataSchema:uY},GD={},DD={};function MD(H,W){let Q=H.slice(0,-6);GD[Q]=W,DD[Q]=(X)=>W.safeParse(X).success}for(let H of BE)MD(H,LF[H]);for(let[H,W]of Object.entries(KE))MD(H,W);var GE=Object.freeze(GD),qD=Object.freeze(DD);function DE(H){switch(H){case"initialize":case"notifications/initialized":return NW(void 0);case"server/discover":return NW(f9);default:return}}var l9=60000,ME=[e0,F1,X8,E1],qE=["inputResponses","requestState"];function TG(H,W){let Q=H.params;if(!oY(Q))return{message:H,lifted:{}};let X=Q._meta,Y=oY(X)?ME.filter((G)=>(G in X)):[],J=W==="request"?qE.filter((G)=>(G in Q)):[];if(Y.length===0&&J.length===0)return{message:H,lifted:{}};let N={},B={...Q};if(Y.length>0&&oY(X)){let G={},D={...X};for(let M of Y)G[M]=X[M],delete D[M];if(N.envelope=G,Object.keys(D).length>0)B._meta=D;else delete B._meta}for(let G of J){if(G==="inputResponses")N.inputResponses=B[G];if(G==="requestState")N.requestState=B[G];delete B[G]}return{message:{...H,params:B},lifted:N}}function $G(H,W){let Q=H.validateResult(W,void 0);if(!Q.ok&&Q.reason==="not-in-era")return;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(X){let Y=H.validateResult(W,X);if(Y.ok)return{value:Y.value};return{issues:[{message:Y.reason==="invalid"?Y.message:`not-in-era: ${W}`}]}}}}}function IB(H){return()=>H}var _E=IB(void 0),FE,m9=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{FE=(H,W)=>{H._negotiatedProtocolVersion=W}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(H){this._options=H,this._supportedProtocolVersions=H?.supportedProtocolVersions??N9,this.setNotificationHandler("notifications/cancelled",(W)=>{this._oncancel(W)}),this.setNotificationHandler("notifications/progress",(W)=>{this._onprogress(W)}),this.setRequestHandler("ping",(W)=>({}))}_shouldDropInbound(H){}_outboundMetaEnvelope(){}_envelopeOutbound(H){let W=this._outboundMetaEnvelope();if(W===void 0)return H;let Q=H.params??{};return{...H,params:{...Q,_meta:{...W,...Q._meta}}}}_resolveNonCompleteResult(H,W){return Promise.reject(new v(x.UnsupportedResultType,`Unsupported result type '${H.kind}' for ${W.request.method}`,{resultType:H.kind,method:W.request.method}))}_getRequestHandler(H){return this._requestHandlers.get(H)}async _oncancel(H){if(H.params.requestId===void 0)return;this._requestHandlerAbortControllers.get(H.params.requestId)?.abort(H.params.reason)}_setupTimeout(H,W,Q,X,Y=!1){this._timeoutInfo.set(H,{timeoutId:setTimeout(X,W),startTime:Date.now(),timeout:W,maxTotalTimeout:Q,resetTimeoutOnProgress:Y,onTimeout:X})}_resetTimeout(H){let W=this._timeoutInfo.get(H);if(!W)return!1;let Q=Date.now()-W.startTime;if(W.maxTotalTimeout&&Q>=W.maxTotalTimeout)throw this._timeoutInfo.delete(H),new v(x.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:W.maxTotalTimeout,totalElapsed:Q});return clearTimeout(W.timeoutId),W.timeoutId=setTimeout(W.onTimeout,W.timeout),!0}_cleanupTimeout(H){let W=this._timeoutInfo.get(H);if(W)clearTimeout(W.timeoutId),this._timeoutInfo.delete(H)}async connect(H){this._transport=H;let W=this.transport?.onclose;this._transport.onclose=()=>{try{W?.()}finally{this._onclose()}};let Q=this.transport?.onerror;this._transport.onerror=(Y)=>{Q?.(Y),this._onerror(Y)};let X=this._transport?.onmessage;this._transport.onmessage=(Y,J)=>{if(X?.(Y,J),o1(Y)||n1(Y))this._onresponse(Y);else if(w8(Y))this._onrequest(Y,J);else if(HD(Y))this._onnotification(Y,J);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Y)}`))},H.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let H=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let X of this._timeoutInfo.values())clearTimeout(X.timeoutId);this._timeoutInfo.clear();let W=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let Q=new v(x.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let X of H.values())X(Q);for(let X of W.values())X.abort(Q)}}_onerror(H){this.onerror?.(H)}_onnotification(H,W){let{message:Q}=TG(H,"notification"),X=this._negotiatedWireCodec();if(W?.classification===void 0&&this._shouldDropInbound(H)==="drop")return;if(W?.classification!==void 0){let N=ZG(W.classification);if(N!==X.era){this._onerror(Error(`Era mismatch on inbound notification '${Q.method}': classified as ${N} but this instance serves ${X.era}`));return}}if(NB(Q.method)&&!X.hasNotificationMethod(Q.method))return;let Y=this._notificationHandlers.get(Q.method),J=this.fallbackNotificationHandler;if(Y===void 0&&J===void 0)return;Promise.resolve().then(()=>Y===void 0?J(Q):Y(Q,X)).catch((N)=>this._onerror(Error(`Uncaught error in notification handler: ${N}`)))}_onrequest(H,W){let{message:Q,lifted:X}=TG(H,"request"),Y=this._negotiatedWireCodec();if(W?.classification===void 0&&this._shouldDropInbound(H)==="drop"){this._onerror(Error(`Dropped inbound request '${H.method}': not servable on this connection's protocol era`));return}let J=this._transport,N=(z,Z,u)=>{let p={jsonrpc:"2.0",id:Q.id,error:{code:z,message:Z,...u!==void 0&&{data:u}}};J?.send(p).catch((j)=>this._onerror(Error(`Failed to send an error response: ${j}`)))};if(W?.classification!==void 0){let z=ZG(W.classification);if(z!==Y.era){this._onerror(Error(`Era mismatch on inbound request '${Q.method}': classified as ${z} but this instance serves ${Y.era}`));let Z=W.classification.revision??z;N(r.UnsupportedProtocolVersion,`Unsupported protocol version: ${Z}`,{supported:this._supportedProtocolVersions,requested:Z});return}}if(JB(Q.method)&&!Y.hasRequestMethod(Q.method)&&!(PG(Q.method)&&this._customSchemaRequestMethods.has(Q.method))){N(r.MethodNotFound,"Method not found");return}let B=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler;if(B===void 0){N(r.MethodNotFound,"Method not found");return}let G=Y.checkInboundEnvelope(X);if(G!==void 0){N(r.InvalidParams,G);return}let D=(z,Z)=>this._notificationViaCodec(this._resolveOutboundCodec(z.method),z,{...Z,relatedRequestId:Q.id}),M=(z,Z,u)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(z.method),z,Z,{...u,relatedRequestId:Q.id}),_=new AbortController;this._requestHandlerAbortControllers.set(Q.id,_);let F=X.inputResponses===void 0?void 0:EE(X.inputResponses),A={sessionId:J?.sessionId,mcpReq:{id:Q.id,method:Q.method,_meta:Q.params?._meta,...X.envelope!==void 0&&{envelope:X.envelope},...F!==void 0&&{inputResponses:F.accepted},...F!==void 0&&F.droppedKeys.length>0&&{droppedInputResponseKeys:F.droppedKeys},requestState:X.requestState===void 0?_E:IB(X.requestState),signal:_.signal,send:(z,Z,u)=>{let p=this._resolveOutboundCodec(z.method);if(this._assertOutboundRequestInEra(p,z.method),DB(Z))return M(z,Z,u);let j=$G(p,z.method);if(j===void 0)throw TypeError(`'${z.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return M(z,j,Z)},notify:D},http:W?.authInfo?{authInfo:W.authInfo}:void 0},w=this.buildContext(A,W);Promise.resolve().then(()=>B(Q,w)).then(async(z)=>{if(_.signal.aborted)return;let Z;try{Z=Y.encodeResult(Q.method,z,this._outboundServerInfo())}catch(p){this._onerror(Error(`Failed to encode result for ${Q.method}: ${p}`)),N(r.InternalError,"Internal error");return}let u={result:Z,jsonrpc:"2.0",id:Q.id};await J?.send(u)},async(z)=>{if(_.signal.aborted)return;let Z=Number.isSafeInteger(z.code)?z.code:r.InternalError,u={jsonrpc:"2.0",id:Q.id,error:{code:Y.encodeErrorCode(Z),message:z.message??"Internal error",...z.data!==void 0&&{data:z.data}}};await J?.send(u)}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(Q.id)===_)this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(H){let{progressToken:W,...Q}=H.params,X=Number(W),Y=this._progressHandlers.get(X);if(!Y){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(H)}`));return}let J=this._responseHandlers.get(X),N=this._timeoutInfo.get(X);if(N&&J&&N.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(B){this._responseHandlers.delete(X),this._progressHandlers.delete(X),this._cleanupTimeout(X),J(B);return}Y(Q)}_onresponse(H){let W=Number(H.id),Q=this._responseHandlers.get(W);if(Q===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(H)}`));return}if(this._responseHandlers.delete(W),this._cleanupTimeout(W),this._progressHandlers.delete(W),o1(H))Q(H);else Q(JH.fromError(H.error.code,H.error.message,H.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(H,W,Q){let X=this._resolveOutboundCodec(H.method);if(DB(W)){if(!PG(H.method))this._assertOutboundRequestInEra(X,H.method);return this._requestWithSchemaViaCodec(X,H,W,Q)}this._assertOutboundRequestInEra(X,H.method);let Y=$G(X,H.method);if(Y===void 0)throw TypeError(`'${H.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(X,H,Y,W)}_negotiatedWireCodec(){return NW(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(H){if(this._negotiatedProtocolVersion===void 0){let W=DE(H);if(W)return W}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(H,W){if(JB(W)&&!H.hasRequestMethod(W))throw new v(x.MethodNotSupportedByProtocolVersion,`Method '${W}' is not supported by the negotiated protocol version (wire era ${H.era})`,{method:W,era:H.era})}_requestWithSchema(H,W,Q){let X=this._resolveOutboundCodec(H.method);return this._assertOutboundRequestInEra(X,H.method),this._requestWithSchemaViaCodec(X,H,W,Q)}_requestWithSchemaViaCodec(H,W,Q,X){let{relatedRequestId:Y,resumptionToken:J,onresumptiontoken:N,headers:B}=X??{},G=Date.now(),D,M;return new Promise((_,F)=>{let A=(P)=>{F(P)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(W.method)}catch(P){A(P);return}if(X?.signal?.aborted){let P=X.signal.reason;throw P instanceof v?P:new v(x.RequestTimeout,String(P))}let w=H.era===f9&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,z=this._requestMessageId++;M=z;let Z={...W,jsonrpc:"2.0",id:z};if(X?.onprogress)this._progressHandlers.set(z,X.onprogress),Z.params={...W.params,_meta:{...W.params?._meta,progressToken:z}};let u=this._envelopeOutbound(Z),p=!1,j=(P)=>{if(p)return;if(this._progressHandlers.delete(z),w===void 0){if(W.method!=="initialize")this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:z,reason:String(P)}}),{relatedRequestId:Y,resumptionToken:J,onresumptiontoken:N}).catch((c)=>this._onerror(Error(`Failed to send cancellation: ${c}`)))}else w.abort();F(P instanceof v?P:new v(x.RequestTimeout,String(P)))};this._responseHandlers.set(z,(P)=>{if(X?.signal?.aborted)return;if(p=!0,P instanceof Error)return F(P);let c;try{c=H.decodeResult(W.method,P.result)}catch(WH){return F(WH instanceof Error?WH:Error(String(WH)))}if(c.kind==="invalid")return F(c.error);if(c.kind==="input_required"){if(X?.allowInputRequired===!0)return _(UE(c));let WH={codec:H,request:W,resultSchema:Q,options:X,flowStartedAt:G,retry:(MH,kH)=>this._requestWithSchemaViaCodec(H,MH===void 0?{method:W.method}:{method:W.method,params:MH},Q,kH)};return _(this._resolveNonCompleteResult(c,WH))}let XH=c.result;BB(Q,XH).then((WH)=>{if(WH.success)_(WH.data);else F(new v(x.InvalidResult,`Invalid result for ${W.method}: ${WH.error}`))},F)}),D=()=>j(X?.signal?.reason),X?.signal?.addEventListener("abort",D,{once:!0});let m=X?.timeout??l9,I=()=>j(new v(x.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(z,m,X?.maxTotalTimeout,I,X?.resetTimeoutOnProgress??!1),this._transport.send(u,{relatedRequestId:Y,resumptionToken:J,onresumptiontoken:N,headers:B,requestSignal:w?.signal}).catch((P)=>{this._progressHandlers.delete(z),F(P)})}).finally(()=>{if(D)X?.signal?.removeEventListener("abort",D);if(M!==void 0)this._responseHandlers.delete(M),this._cleanupTimeout(M)})}async notification(H,W){return await this._notificationViaCodec(this._resolveOutboundCodec(H.method),H,W)}async _notificationViaCodec(H,W,Q){if(!this._transport)throw new v(x.NotConnected,"Not connected");if(NB(W.method)&&!H.hasNotificationMethod(W.method))throw new v(x.MethodNotSupportedByProtocolVersion,`Notification '${W.method}' is not supported by the negotiated protocol version (wire era ${H.era})`,{method:W.method,era:H.era});this.assertNotificationCapability(W.method);let X=this._envelopeOutbound({jsonrpc:"2.0",...W});if((this._options?.debouncedNotificationMethods??[]).includes(W.method)&&!W.params&&Q?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(W.method))return;this._pendingDebouncedNotifications.add(W.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(W.method),!this._transport)return;this._transport?.send(X,Q).catch((Y)=>this._onerror(Y))});return}await this._transport.send(X,Q)}setRequestHandler(H,W,Q){this.assertRequestHandlerCapability(H);let X;if(typeof W==="function"){if(!JB(H))throw TypeError(`'${H}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);X=(Y,J)=>{let N=this._negotiatedWireCodec(),B=N.validateRequest(H,Y);if(!B.ok&&B.reason==="not-in-era")B=N.validateInputRequest(H,Y);if(!B.ok){if(B.reason==="not-in-era")throw new JH(r.InternalError,`No wire schema for ${H} in the resolved era`);throw Error(B.message)}return Promise.resolve(W(B.value,J))}}else if(Q)X=async(Y,J)=>{let N=await BB(W.params,{...Y.params});if(!N.success)throw new JH(r.InvalidParams,`Invalid params for ${H}: ${N.error}`);return Q(N.data,J)};else throw TypeError("setRequestHandler: handler is required");if(typeof W==="function")this._customSchemaRequestMethods.delete(H);else this._customSchemaRequestMethods.add(H);this._requestHandlers.set(H,this._wrapHandler(H,X))}_wrapHandler(H,W){return W}_outboundServerInfo(){}removeRequestHandler(H){this._requestHandlers.delete(H),this._customSchemaRequestMethods.delete(H)}assertCanSetRequestHandler(H){if(this._requestHandlers.has(H))throw Error(`A request handler for ${H} already exists, which would be overridden`)}setNotificationHandler(H,W,Q){if(typeof W==="function"){if(!NB(H))throw TypeError(`'${H}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(H,(X,Y)=>{let J=Y.validateNotification(H,X);if(!J.ok){if(J.reason==="not-in-era")throw new JH(r.InternalError,`No wire schema for ${H} in the resolved era`);throw Error(J.message)}return Promise.resolve(W(J.value))});return}if(!Q)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(H,async(X)=>{let Y=await BB(W.params,{...X.params});if(!Y.success)throw new JH(r.InvalidParams,`Invalid params for notification ${H}: ${Y.error}`);await Q(Y.data,X)})}removeNotificationHandler(H){this._notificationHandlers.delete(H)}};function oY(H){return H!==null&&typeof H==="object"&&!Array.isArray(H)}function _D(H,W){let Q={...H};for(let X in W){let Y=X,J=W[Y];if(J===void 0)continue;let N=Q[Y];Q[Y]=oY(N)&&oY(J)?{...N,...J}:J}return Q}function y9(H){return typeof H==="object"&&H!==null&&!Array.isArray(H)}function EE(H){let W={},Q=[];if(!y9(H))return{accepted:W,droppedKeys:Q};for(let[X,Y]of Object.entries(H)){if(!y9(Y)||"method"in Y||"result"in Y){Q.push(X);continue}W[X]=Y}return{accepted:W,droppedKeys:Q}}function RG(H){throw new v(x.SendFailed,`ctx.mcpReq.${H} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function AE(H,W,Q,X,Y){return{sessionId:Y,mcpReq:{id:H,method:W,_meta:Q?._meta,requestState:IB(void 0),signal:X,send:()=>RG("send"),notify:()=>RG("notify")}}}async function OE(H,W,Q,X,Y){if(!y9(X)||typeof X.method!=="string")throw new v(x.InvalidResult,`Invalid input request '${Q}': each inputRequests entry must be an embedded request object with a method`,{key:Q});let J=X.method;if(!W.hasInputRequestMethod(J))throw new v(x.InvalidResult,`Invalid input request '${Q}': '${J}' is not an embedded request the ${W.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:Q,method:J});let N=H.getRequestHandler(J);if(N===void 0)throw new v(x.CapabilityNotSupported,`Cannot fulfil input request '${Q}': no handler is registered for '${J}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:Q,method:J});let B=y9(X.params)?X.params:void 0;return await N({jsonrpc:"2.0",id:Q,method:J,...B!==void 0&&{params:B}},H.buildContext(AE(Q,J,B,Y,H.sessionId)))}function VE(H,W){return{...H?.signal!==void 0&&{signal:H.signal},...H?.onprogress!==void 0&&{onprogress:H.onprogress},...H?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:H.resetTimeoutOnProgress},...H?.headers!==void 0&&{headers:H.headers},...W.timeout!==void 0&&{timeout:W.timeout},...W.maxTotalTimeout!==void 0&&{maxTotalTimeout:W.maxTotalTimeout},allowInputRequired:!0}}function FD(H,W,Q,X){let{codec:Y,request:J,options:N,flowStartedAt:B}=X,G={inputRequests:Q.inputRequests,...Q.requestState!==void 0&&{requestState:Q.requestState}},D={dispatchInputRequest:(M,_,F)=>OE(H,Y,M,_,F),retry:(M,_)=>X.retry(M,VE(N,_))};return NE({config:W,method:J.method,originalParams:J.params,firstPayload:G,flowStartedAt:B,signal:N?.signal,requestOptions:{...N?.timeout!==void 0&&{timeout:N.timeout},...N?.maxTotalTimeout!==void 0&&{maxTotalTimeout:N.maxTotalTimeout},...N?.onprogress!==void 0&&{onprogress:N.onprogress}},hooks:D})}function UE(H){return{resultType:"input_required",inputRequests:H.inputRequests,...H.requestState!==void 0&&{requestState:H.requestState},...H._meta!==void 0&&{_meta:H._meta}}}/*!
64
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref"){s(i);continue}}}}function Vn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let u=l.def??l.schema,d={...u},m=l.ref;if(l.ref=null,m){o(m);let S=e.seen.get(m),b=S.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(b);else Object.assign(u,b);if(Object.assign(u,d),a._zod.parent===m)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(!(v in d))delete u[v]}if(b.$ref&&S.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in S.def&&JSON.stringify(u[v])===JSON.stringify(S.def[v]))delete u[v]}}let f=a._zod.parent;if(f&&f!==m){o(f);let S=e.seen.get(f);if(S?.schema.$ref){if(u.$ref=S.schema.$ref,S.def)for(let b in u){if(b==="$ref"||b==="allOf")continue;if(b in S.def&&JSON.stringify(u[b])===JSON.stringify(S.def[b]))delete u[b]}}}e.override({zodSchema:a,jsonSchema:u,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&n.id===s)delete n.id;let i=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;i[l.defId]=l.def}}if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")n.$defs=i;else n.definitions=i;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dn(t,"input",e.processors),output:Dn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Ne(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Ne(o.element,r);if(o.type==="set")return Ne(o.valueType,r);if(o.type==="lazy")return Ne(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Ne(o.innerType,r);if(o.type==="intersection")return Ne(o.left,r)||Ne(o.right,r);if(o.type==="record"||o.type==="map")return Ne(o.keyType,r)||Ne(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Ne(o.in,r)||Ne(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(Ne(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Ne(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Ne(n,r))return!0;if(o.rest&&Ne(o.rest,r))return!0;return!1}return!1}var lm=(e,t={})=>(r)=>{let o=Fn({...r,processors:t});return oe(e,o),Hn(o,e),Vn(o,e)},Dn=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:s}=o??{},i=Fn({...n??{},target:s,io:t,processors:r});return oe(e,i),Hn(i,e),Vn(i,e)};var a_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_l=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof s==="number")n.minLength=s;if(typeof i==="number")n.maxLength=i;if(a){if(n.format=a_[a]??a,n.format==="")delete n.format;if(a==="time")delete n.format}if(u)n.contentEncoding=u;if(l&&l.size>0){let d=[...l];if(d.length===1)n.pattern=d[0].source;else if(d.length>1)n.allOf=[...d.map((m)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))]}},bl=(e,t,r,o)=>{let n=r,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))n.type="integer";else n.type="number";let m=typeof d==="number"&&d>=(s??Number.NEGATIVE_INFINITY),f=typeof u==="number"&&u<=(i??Number.POSITIVE_INFINITY),S=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(S)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof s==="number")n.minimum=s;if(f)if(S)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof i==="number")n.maximum=i;if(typeof l==="number")n.multipleOf=l},yl=(e,t,r,o)=>{r.type="boolean"},dm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},pm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},vl=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},zl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},hm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},wl=(e,t,r,o)=>{r.not={}},Rl=(e,t,r,o)=>{},xl=(e,t,r,o)=>{},mm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Pl=(e,t,r,o)=>{let n=e._zod.def,s=ma(n.entries);if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s},Tl=(e,t,r,o)=>{let n=e._zod.def,s=[];for(let i of n.values)if(i===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(i));else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[i];else r.const=i}else{if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";if(s.every((i)=>typeof i==="boolean"))r.type="boolean";if(s.every((i)=>i===null))r.type="null";r.enum=s}},fm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},gm=(e,t,r,o)=>{let n=r,s=e._zod.pattern;if(!s)throw Error("Pattern not found in template literal");n.type="string",n.pattern=s.source},Sm=(e,t,r,o)=>{let n=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:a,mime:l}=e._zod.bag;if(i!==void 0)s.minLength=i;if(a!==void 0)s.maxLength=a;if(l)if(l.length===1)s.contentMediaType=l[0],Object.assign(n,s);else Object.assign(n,s),n.anyOf=l.map((u)=>({contentMediaType:u}));else Object.assign(n,s)},_m=(e,t,r,o)=>{r.type="boolean"},El=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},bm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},kl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},ym=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},vm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},$l=(e,t,r,o)=>{let n=r,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;if(typeof i==="number")n.minItems=i;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=oe(s.element,t,{...o,path:[...o.path,"items"]})},Cl=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object",n.properties={};let i=s.shape;for(let u in i)n.properties[u]=oe(i[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(i)),l=new Set([...a].filter((u)=>{let d=s.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(l.size>0)n.required=Array.from(l);if(s.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")n.additionalProperties=!1}else if(s.catchall)n.additionalProperties=oe(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Il=(e,t,r,o)=>{let n=e._zod.def,s=n.inclusive===!1,i=n.options.map((a,l)=>oe(a,t,{...o,path:[...o.path,s?"oneOf":"anyOf",l]}));if(s)r.oneOf=i;else r.anyOf=i},Ol=(e,t,r,o)=>{let n=e._zod.def,s=oe(n.left,t,{...o,path:[...o.path,"allOf",0]}),i=oe(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=l},zm=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=s.items.map((f,S)=>oe(f,t,{...o,path:[...o.path,i,S]})),u=s.rest?oe(s.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(n.prefixItems=l,u)n.items=u}else if(t.target==="openapi-3.0"){if(n.items={anyOf:l},u)n.items.anyOf.push(u);if(n.minItems=l.length,!u)n.maxItems=l.length}else if(n.items=l,u)n.additionalItems=u;let{minimum:d,maximum:m}=e._zod.bag;if(typeof d==="number")n.minItems=d;if(typeof m==="number")n.maxItems=m},Nl=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object";let i=s.keyType,l=i._zod.bag?.patterns;if(s.mode==="loose"&&l&&l.size>0){let d=oe(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let m of l)n.patternProperties[m.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")n.propertyNames=oe(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=oe(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=i._zod.values;if(u){let d=[...u].filter((m)=>typeof m==="string"||typeof m==="number");if(d.length>0)n.required=d}},ql=(e,t,r,o)=>{let n=e._zod.def,s=oe(n.innerType,t,o),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=n.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},Al=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Ml=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},jl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);if(s.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},Ll=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType;let i;try{i=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Ul=(e,t,r,o)=>{let n=e._zod.def,s=n.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?n.out:n.in:n.out;oe(i,t,o);let a=t.seen.get(e);a.ref=i},Zl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.readOnly=!0},wm=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},ka=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Dl=(e,t,r,o)=>{let n=e._zod.innerType;oe(n,t,o);let s=t.seen.get(e);s.ref=n},um={string:_l,number:bl,boolean:yl,bigint:dm,symbol:pm,null:vl,undefined:zl,void:hm,never:wl,any:Rl,unknown:xl,date:mm,enum:Pl,literal:Tl,nan:fm,template_literal:gm,file:Sm,success:_m,custom:El,function:bm,transform:kl,map:ym,set:vm,array:$l,object:Cl,union:Il,intersection:Ol,tuple:zm,record:Nl,nullable:ql,nonoptional:Al,default:Ml,prefault:jl,catch:Ll,pipe:Ul,readonly:Zl,promise:wm,optional:ka,lazy:Dl};function $a(e,t){if("_idmap"in e){let o=e,n=Fn({...t,processors:um}),s={};for(let l of o._idmap.entries()){let[u,d]=l;oe(d,n)}let i={},a={registry:o,uri:t?.uri,defs:s};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Hn(n,d),i[u]=Vn(n,d)}if(Object.keys(s).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[l]:s}}return{schemas:i}}let r=Fn({...t,processors:um});return oe(e,r),Hn(r,e),Vn(r,e)}var f_=_("ZodISODateTime",(e,t)=>{jp.init(e,t),ae.init(e,t)});function uo(e){return Bh(f_,e)}var g_=_("ZodISODate",(e,t)=>{Lp.init(e,t),ae.init(e,t)});function Fl(e){return Wh(g_,e)}var S_=_("ZodISOTime",(e,t)=>{Up.init(e,t),ae.init(e,t)});function Rm(e){return Kh(S_,e)}var __=_("ZodISODuration",(e,t)=>{Zp.init(e,t),ae.init(e,t)});function xm(e){return Gh(__,e)}var b_=(e,t)=>{_a.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Vc(e,r)},flatten:{value:(r)=>Hc(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Nn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Nn,2)}},isEmpty:{get(){return e.issues.length===0}}})};var Je=_("ZodError",b_,{Parent:Error});var Tm=ba(Je),Em=ya(Je),Ia=An(Je),km=Mn(Je),$m=vd(Je),Cm=zd(Je),Im=wd(Je),Om=Rd(Je),Nm=xd(Je),qm=Pd(Je),Am=Td(Je),Mm=Ed(Je);var jm=new WeakMap;function Jn(e,t,r){let o=Object.getPrototypeOf(e),n=jm.get(o);if(!n)n=new Set,jm.set(o,n);if(n.has(t))return;n.add(t);for(let s in r){let i=r[s];Object.defineProperty(o,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var ne=_("ZodType",(e,t)=>(re.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dn(e,"input"),output:Dn(e,"output")}}),e.toJSONSchema=lm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>Tm(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Ia(e,r,o),e.parseAsync=async(r,o)=>Em(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>km(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>$m(e,r,o),e.decode=(r,o)=>Cm(e,r,o),e.encodeAsync=async(r,o)=>Im(e,r,o),e.decodeAsync=async(r,o)=>Om(e,r,o),e.safeEncode=(r,o)=>Nm(e,r,o),e.safeDecode=(r,o)=>qm(e,r,o),e.safeEncodeAsync=async(r,o)=>Am(e,r,o),e.safeDecodeAsync=async(r,o)=>Mm(e,r,o),Jn(e,"ZodType",{check(...r){let o=this.def;return this.clone(Wt(o,{checks:[...o.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return rt(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(cb(r,o))},superRefine(r,o){return this.check(lb(r,o))},overwrite(r){return this.check(Xt(r))},optional(){return j(this)},exactOptional(){return W_(this)},nullable(){return Dm(this)},nullish(){return j(Dm(this))},nonoptional(r){return eb(this,r)},array(){return g(this)},or(r){return T([this,r])},and(r){return $t(this,r)},transform(r){return Fm(this,Xm(r))},default(r){return Y_(this,r)},prefault(r){return Q_(this,r)},catch(r){return rb(this,r)},pipe(r){return Fm(this,r)},readonly(){return sb(this)},describe(r){let o=this.clone();return Yt.add(o,{description:r}),o},meta(...r){if(r.length===0)return Yt.get(this);let o=this.clone();return Yt.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Yt.get(e)?.description},configurable:!0}),e)),Hm=_("_ZodString",(e,t)=>{wa.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>_l(e,o,n,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Jn(e,"_ZodString",{regex(...o){return this.check(al(...o))},includes(...o){return this.check(ul(...o))},startsWith(...o){return this.check(dl(...o))},endsWith(...o){return this.check(pl(...o))},min(...o){return this.check(co(...o))},max(...o){return this.check(Ta(...o))},length(...o){return this.check(Ea(...o))},nonempty(...o){return this.check(co(1,...o))},lowercase(o){return this.check(cl(o))},uppercase(o){return this.check(ll(o))},trim(){return this.check(ml())},normalize(...o){return this.check(hl(...o))},toLowerCase(){return this.check(fl())},toUpperCase(){return this.check(gl())},slugify(){return this.check(Sl())}})}),Vm=_("ZodString",(e,t)=>{wa.init(e,t),Hm.init(e,t),e.email=(r)=>e.check(nl(Jm,r)),e.url=(r)=>e.check(il(Wm,r)),e.jwt=(r)=>e.check(Jh(q_,r)),e.emoji=(r)=>e.check(Ih(v_,r)),e.guid=(r)=>e.check(sl(Lm,r)),e.uuid=(r)=>e.check(Eh(Oa,r)),e.uuidv4=(r)=>e.check(kh(Oa,r)),e.uuidv6=(r)=>e.check($h(Oa,r)),e.uuidv7=(r)=>e.check(Ch(Oa,r)),e.nanoid=(r)=>e.check(Oh(z_,r)),e.guid=(r)=>e.check(sl(Lm,r)),e.cuid=(r)=>e.check(Nh(w_,r)),e.cuid2=(r)=>e.check(qh(R_,r)),e.ulid=(r)=>e.check(Ah(x_,r)),e.base64=(r)=>e.check(Fh(I_,r)),e.base64url=(r)=>e.check(Hh(O_,r)),e.xid=(r)=>e.check(Mh(P_,r)),e.ksuid=(r)=>e.check(jh(T_,r)),e.ipv4=(r)=>e.check(Lh(E_,r)),e.ipv6=(r)=>e.check(Uh(k_,r)),e.cidrv4=(r)=>e.check(Zh($_,r)),e.cidrv6=(r)=>e.check(Dh(C_,r)),e.e164=(r)=>e.check(Vh(N_,r)),e.datetime=(r)=>e.check(uo(r)),e.date=(r)=>e.check(Fl(r)),e.time=(r)=>e.check(Rm(r)),e.duration=(r)=>e.check(xm(r))});function c(e){return Th(Vm,e)}var ae=_("ZodStringFormat",(e,t)=>{ie.init(e,t),Hm.init(e,t)}),Jm=_("ZodEmail",(e,t)=>{kp.init(e,t),ae.init(e,t)});function Bm(e){return nl(Jm,e)}var Lm=_("ZodGUID",(e,t)=>{Tp.init(e,t),ae.init(e,t)});var Oa=_("ZodUUID",(e,t)=>{Ep.init(e,t),ae.init(e,t)});var Wm=_("ZodURL",(e,t)=>{$p.init(e,t),ae.init(e,t)});function Na(e){return il(Wm,e)}var v_=_("ZodEmoji",(e,t)=>{Cp.init(e,t),ae.init(e,t)});var z_=_("ZodNanoID",(e,t)=>{Ip.init(e,t),ae.init(e,t)});var w_=_("ZodCUID",(e,t)=>{Op.init(e,t),ae.init(e,t)});var R_=_("ZodCUID2",(e,t)=>{Np.init(e,t),ae.init(e,t)});var x_=_("ZodULID",(e,t)=>{qp.init(e,t),ae.init(e,t)});var P_=_("ZodXID",(e,t)=>{Ap.init(e,t),ae.init(e,t)});var T_=_("ZodKSUID",(e,t)=>{Mp.init(e,t),ae.init(e,t)});var E_=_("ZodIPv4",(e,t)=>{Dp.init(e,t),ae.init(e,t)});var k_=_("ZodIPv6",(e,t)=>{Fp.init(e,t),ae.init(e,t)});var $_=_("ZodCIDRv4",(e,t)=>{Hp.init(e,t),ae.init(e,t)});var C_=_("ZodCIDRv6",(e,t)=>{Vp.init(e,t),ae.init(e,t)});var I_=_("ZodBase64",(e,t)=>{Bp.init(e,t),ae.init(e,t)});var O_=_("ZodBase64URL",(e,t)=>{Wp.init(e,t),ae.init(e,t)});var N_=_("ZodE164",(e,t)=>{Kp.init(e,t),ae.init(e,t)});var q_=_("ZodJWT",(e,t)=>{Gp.init(e,t),ae.init(e,t)});var qa=_("ZodNumber",(e,t)=>{Qc.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>bl(e,o,n,s),Jn(e,"ZodNumber",{gt(o,n){return this.check(xa(o,n))},gte(o,n){return this.check(Zn(o,n))},min(o,n){return this.check(Zn(o,n))},lt(o,n){return this.check(Ra(o,n))},lte(o,n){return this.check(Un(o,n))},max(o,n){return this.check(Un(o,n))},int(o){return this.check(Um(o))},safe(o){return this.check(Um(o))},positive(o){return this.check(xa(0,o))},nonnegative(o){return this.check(Zn(0,o))},negative(o){return this.check(Ra(0,o))},nonpositive(o){return this.check(Un(0,o))},multipleOf(o,n){return this.check(Pa(o,n))},step(o,n){return this.check(Pa(o,n))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function z(e){return Yh(qa,e)}var A_=_("ZodNumberFormat",(e,t)=>{Yp.init(e,t),qa.init(e,t)});function Um(e){return Qh(A_,e)}var Km=_("ZodBoolean",(e,t)=>{Xp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yl(e,r,o,n)});function E(e){return em(Km,e)}var M_=_("ZodUndefined",(e,t)=>{Qp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(e,r,o,n)});function Vl(e){return tm(M_,e)}var j_=_("ZodNull",(e,t)=>{eh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vl(e,r,o,n)});function Rr(e){return rm(j_,e)}var L_=_("ZodAny",(e,t)=>{th.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Aa(){return om(L_)}var U_=_("ZodUnknown",(e,t)=>{rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n)});function A(){return nm(U_)}var Z_=_("ZodNever",(e,t)=>{oh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wl(e,r,o,n)});function Jl(e){return sm(Z_,e)}var D_=_("ZodArray",(e,t)=>{nh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$l(e,r,o,n),e.element=t.element,Jn(e,"ZodArray",{min(r,o){return this.check(co(r,o))},nonempty(r){return this.check(co(1,r))},max(r,o){return this.check(Ta(r,o))},length(r,o){return this.check(Ea(r,o))},unwrap(){return this.element}})});function g(e,t){return im(D_,e,t)}var Gm=_("ZodObject",(e,t)=>{ah.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n),Q(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:A()})},loose(){return this.clone({...this._zod.def,catchall:A()})},strict(){return this.clone({...this._zod.def,catchall:Jl()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return BS(this,r)},safeExtend(r){return WS(this,r)},merge(r){return KS(this,r)},pick(r){return VS(this,r)},omit(r){return JS(this,r)},partial(...r){return GS(Qm,this,r[0])},required(...r){return YS(ef,this,r[0])}})});function p(e,t){let r={type:"object",shape:e??{},...M(t)};return new Gm(r)}function D(e,t){return new Gm({type:"object",shape:e,catchall:A(),...M(t)})}var Ym=_("ZodUnion",(e,t)=>{el.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n),e.options=t.options});function T(e,t){return new Ym({type:"union",options:e,...M(t)})}var F_=_("ZodDiscriminatedUnion",(e,t)=>{Ym.init(e,t),ch.init(e,t)});function po(e,t,r){return new F_({type:"union",options:t,discriminator:e,...M(r)})}var H_=_("ZodIntersection",(e,t)=>{lh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n)});function $t(e,t){return new H_({type:"intersection",left:e,right:t})}var Zm=_("ZodRecord",(e,t)=>{uh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,r){if(!t||!t._zod)return new Zm({type:"record",keyType:c(),valueType:e,...M(t)});return new Zm({type:"record",keyType:e,valueType:t,...M(r)})}var Hl=_("ZodEnum",(e,t)=>{dh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>Pl(e,o,n,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Hl({...t,checks:[],...M(n),entries:s})},e.exclude=(o,n)=>{let s={...t.entries};for(let i of o)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Hl({...t,checks:[],...M(n),entries:s})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new Hl({type:"enum",entries:r,...M(t)})}var V_=_("ZodLiteral",(e,t)=>{ph.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Tl(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function h(e,t){return new V_({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var J_=_("ZodTransform",(e,t)=>{hh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(wr(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(wr(i))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((s)=>(r.value=s,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function Xm(e){return new J_({type:"transform",transform:e})}var Qm=_("ZodOptional",(e,t)=>{tl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ka(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function j(e){return new Qm({type:"optional",innerType:e})}var B_=_("ZodExactOptional",(e,t)=>{mh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ka(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function W_(e){return new B_({type:"optional",innerType:e})}var K_=_("ZodNullable",(e,t)=>{fh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Dm(e){return new K_({type:"nullable",innerType:e})}var G_=_("ZodDefault",(e,t)=>{gh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Y_(e,t){return new G_({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Zc(t)}})}var X_=_("ZodPrefault",(e,t)=>{Sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Q_(e,t){return new X_({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Zc(t)}})}var ef=_("ZodNonOptional",(e,t)=>{_h.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function eb(e,t){return new ef({type:"nonoptional",innerType:e,...M(t)})}var tb=_("ZodCatch",(e,t)=>{bh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function rb(e,t){return new tb({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var tf=_("ZodPipe",(e,t)=>{rl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.in=t.in,e.out=t.out});function Fm(e,t){return new tf({type:"pipe",in:e,out:t})}var ob=_("ZodPreprocess",(e,t)=>{tf.init(e,t),yh.init(e,t)}),nb=_("ZodReadonly",(e,t)=>{vh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function sb(e){return new nb({type:"readonly",innerType:e})}var ib=_("ZodLazy",(e,t)=>{zh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Bn(e){return new ib({type:"lazy",getter:e})}var ab=_("ZodCustom",(e,t)=>{wh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n)});function cb(e,t={}){return am(ab,e,t)}function lb(e,t){return cm(e,t)}function xr(e,t){return new ob({type:"pipe",in:Xm(e),out:t})}var of={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var rf;(function(e){})(rf||(rf={}));function ub(e){return Xh(qa,e)}je(ol());var ho="2025-11-25";var Ma=[ho,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ja="io.modelcontextprotocol/related-task",It="io.modelcontextprotocol/protocolVersion",mo="io.modelcontextprotocol/clientInfo",Ot="io.modelcontextprotocol/serverInfo",Pr="io.modelcontextprotocol/clientCapabilities",Wn="io.modelcontextprotocol/subscriptionId",fo="io.modelcontextprotocol/logLevel";var Tr="2.0";var Ct=Bn(()=>T([c(),z(),E(),Rr(),P(c(),Ct),g(Ct)])),le=P(c(),Ct),La=g(Ct),go=T([c(),z().int()]),So=c(),Kn=p({ttl:z().optional()}),Gn=p({taskId:c()}),_o=D({progressToken:go.optional(),[ja]:Gn.optional()}),ye=p({_meta:_o.optional()}),er=ye.extend({task:Kn.optional()}),ue=p({method:c(),params:ye.loose().optional()}),Te=p({_meta:_o.optional()}),we=p({method:c(),params:Te.loose().optional()}),bo=D({get[Ot](){return _t.optional().catch(void 0)}}),de=D({_meta:bo.optional()}),nt=T([c(),z().int()]),yo=p({jsonrpc:h(Tr),id:nt,...ue.shape}).strict(),vo=p({jsonrpc:h(Tr),...we.shape}).strict(),Er=p({jsonrpc:h(Tr),id:nt,result:de}).strict(),kr=p({jsonrpc:h(Tr),id:nt.optional(),error:p({code:z().int(),message:c(),data:A().optional()})}).strict(),st=T([yo,vo,Er,kr]),Ua=T([Er,kr]),tr=de.strict(),Yn=Te.extend({requestId:nt.optional(),reason:c().optional()}),zo=we.extend({method:h("notifications/cancelled"),params:Yn}),Xn=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),Nt=p({icons:g(Xn).optional()}),St=p({name:c(),title:c().optional()}),_t=St.extend({...St.shape,...Nt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),pb=$t(p({applyDefaults:E().optional()}),le),hb=xr((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{form:{}};return e},$t(p({form:pb.optional(),url:le.optional()}),le.optional())),Za=D({list:le.optional(),cancel:le.optional(),requests:D({sampling:D({createMessage:le.optional()}).optional(),elicitation:D({create:le.optional()}).optional()}).optional()}),Da=D({list:le.optional(),cancel:le.optional(),requests:D({tools:D({call:le.optional()}).optional()}).optional()}),Qn=p({experimental:P(c(),le).optional(),sampling:p({context:le.optional(),tools:le.optional()}).optional(),elicitation:hb.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Za.optional(),extensions:P(c(),le).optional()}),es=ye.extend({protocolVersion:c(),capabilities:Qn,clientInfo:_t}),wo=ue.extend({method:h("initialize"),params:es}),Ro=p({experimental:P(c(),le).optional(),logging:le.optional(),completions:le.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:Da.optional(),extensions:P(c(),le).optional()}),ts=de.extend({protocolVersion:c(),capabilities:Ro,serverInfo:_t,instructions:c().optional()}),xo=we.extend({method:h("notifications/initialized"),params:Te.optional()}),rs=ue.extend({method:h("server/discover"),params:ye.optional()}),rr=de.extend({supportedVersions:g(c()),capabilities:Ro,instructions:c().optional()}),Po=ue.extend({method:h("ping"),params:ye.optional()}),os=p({progress:z(),total:j(z()),message:j(c())}),ns=p({...Te.shape,...os.shape,progressToken:go}),To=we.extend({method:h("notifications/progress"),params:ns}),ss=ye.extend({cursor:So.optional()}),qt=ue.extend({params:ss.optional()}),At=de.extend({nextCursor:So.optional()}),Eo=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ko=Eo.extend({text:c()}),Wl=c().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),$o=Eo.extend({blob:Wl}),Mt=K(["user","assistant"]),bt=p({audience:g(Mt).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),Co=p({...St.shape,...Nt.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:bt.optional(),_meta:j(D({}))}),is=p({...St.shape,...Nt.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:bt.optional(),_meta:j(D({}))}),as=qt.extend({method:h("resources/list")}),cs=At.extend({resources:g(Co)}),ls=qt.extend({method:h("resources/templates/list")}),us=At.extend({resourceTemplates:g(is)}),$r=ye.extend({uri:c()}),ds=$r,ps=ue.extend({method:h("resources/read"),params:ds}),hs=de.extend({contents:g(T([ko,$o]))}),ms=we.extend({method:h("notifications/resources/list_changed"),params:Te.optional()}),fs=$r,gs=ue.extend({method:h("resources/subscribe"),params:fs}),Ss=$r,_s=ue.extend({method:h("resources/unsubscribe"),params:Ss}),Io=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),bs=ye.extend({notifications:Io}),ys=ue.extend({method:h("subscriptions/listen"),params:bs}),vs=Te.extend({notifications:Io}),zs=we.extend({method:h("notifications/subscriptions/acknowledged"),params:vs}),ws=bo.extend({[Wn]:nt}),Rs=de.extend({_meta:ws}),xs=Te.extend({uri:c()}),Ps=we.extend({method:h("notifications/resources/updated"),params:xs}),Ts=p({name:c(),description:j(c()),required:j(E())}),Es=p({...St.shape,...Nt.shape,description:j(c()),arguments:j(g(Ts)),_meta:j(D({}))}),ks=qt.extend({method:h("prompts/list")}),$s=At.extend({prompts:g(Es)}),Cs=ye.extend({name:c(),arguments:P(c(),c()).optional()}),Is=ue.extend({method:h("prompts/get"),params:Cs}),Cr=p({type:h("text"),text:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Ir=p({type:h("image"),data:Wl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Or=p({type:h("audio"),data:Wl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Os=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Nr=p({type:h("resource"),resource:T([ko,$o]),annotations:bt.optional(),_meta:P(c(),A()).optional()}),qr=Co.extend({type:h("resource_link")}),yt=T([Cr,Ir,Or,qr,Nr]),Ns=p({role:Mt,content:yt}),qs=de.extend({description:c().optional(),messages:g(Ns)}),As=we.extend({method:h("notifications/prompts/list_changed"),params:Te.optional()}),Ms=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),js=p({taskSupport:K(["required","optional","forbidden"]).optional()}),or=p({...St.shape,...Nt.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),Ct).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:D({$schema:c().optional()}).optional(),annotations:Ms.optional(),execution:js.optional(),_meta:P(c(),A()).optional()}),Ls=qt.extend({method:h("tools/list")}),Us=At.extend({tools:g(or)}),nr=de.extend({content:g(yt).default([]),structuredContent:A().optional(),isError:E().optional()}),Fa=nr.or(de.extend({toolResult:A()})),Zs=er.extend({name:c(),arguments:P(c(),A()).optional()}),Ds=ue.extend({method:h("tools/call"),params:Zs}),Fs=we.extend({method:h("notifications/tools/list_changed"),params:Te.optional()}),Hs=p({autoRefresh:E().default(!0),debounceMs:z().int().nonnegative().default(300)}),Oo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Vs=ye.extend({level:Oo}),Js=ue.extend({method:h("logging/setLevel"),params:Vs}),Bs=Te.extend({level:Oo,logger:c().optional(),data:A()}),Ar=we.extend({method:h("notifications/message"),params:Bs}),Ws=p({name:c().optional()}),Ks=p({hints:g(Ws).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),Gs=p({mode:K(["auto","required","none"]).optional()}),Ys=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(yt),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Xs=po("type",[Cr,Ir,Or]),Qt=po("type",[Cr,Ir,Or,Os,Ys]),Qs=p({role:Mt,content:T([Qt,g(Qt)]),_meta:P(c(),A()).optional()}),ei=er.extend({messages:g(Qs),modelPreferences:Ks.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:le.optional(),tools:g(or).optional(),toolChoice:Gs.optional()}),ti=ue.extend({method:h("sampling/createMessage"),params:ei}),ri=de.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Mt,content:Xs}),oi=de.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Mt,content:T([Qt,g(Qt)])}),No=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Mr=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),jr=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),qo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Ao=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Mo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),ni=T([qo,Ao]),jo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Lo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),si=T([jo,Lo]),ii=T([Mo,ni,si]),Uo=T([ii,No,Mr,jr]),Lr=er.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Uo),required:g(c()).optional()}).catchall(A())}),ai=er.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),ci=T([Lr,ai]),li=ue.extend({method:h("elicitation/create"),params:ci}),ui=Te.extend({elicitationId:c()}),di=we.extend({method:h("notifications/elicitation/complete"),params:ui}),pi=de.extend({action:K(["accept","decline","cancel"]),content:xr((e)=>e===null?void 0:e,P(c(),T([c(),z(),E(),g(c())])).optional())}),hi=p({type:h("ref/resource"),uri:c()}),mi=p({type:h("ref/prompt"),name:c()}),fi=ye.extend({ref:T([mi,hi]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),gi=ue.extend({method:h("completion/complete"),params:fi}),Si=de.extend({completion:D({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),_i=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),bi=ue.extend({method:h("roots/list"),params:ye.optional()}),yi=de.extend({roots:g(_i)}),vi=we.extend({method:h("notifications/roots/list_changed"),params:Te.optional()}),Ha=D({ttl:z().optional(),pollInterval:z().optional()}),zi=K(["working","input_required","completed","failed","cancelled"]),jt=p({taskId:c(),status:zi,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Va=de.extend({task:jt}),wi=Te.merge(jt),Ja=we.extend({method:h("notifications/tasks/status"),params:wi}),Ba=ue.extend({method:h("tasks/get"),params:ye.extend({taskId:c()})}),Wa=de.merge(jt),Ka=ue.extend({method:h("tasks/result"),params:ye.extend({taskId:c()})}),Ga=de.loose(),Ya=qt.extend({method:h("tasks/list")}),Xa=At.extend({tasks:g(jt)}),Qa=ue.extend({method:h("tasks/cancel"),params:ye.extend({taskId:c()})}),ec=de.merge(jt),tc=T([Po,wo,rs,gi,Js,Is,ks,as,ls,ps,gs,_s,ys,Ds,Ls]),rc=T([zo,To,xo,vi]),oc=T([tr,ri,oi,pi,yi]),nc=T([Po,ti,li,bi]),sc=T([zo,To,Ar,Ps,ms,Fs,As,zs,di]),ic=T([tr,ts,rr,Si,qs,$s,cs,us,hs,nr,Us,Rs]),be=Na().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:of.custom,message:"URL must be parseable",fatal:!0}),Ac}).refine((e)=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Zo=D({resource:c().url(),authorization_servers:g(be).optional(),jwks_uri:c().url().optional(),scopes_supported:g(c()).optional(),bearer_methods_supported:g(c()).optional(),resource_signing_alg_values_supported:g(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:E().optional(),authorization_details_types_supported:g(c()).optional(),dpop_signing_alg_values_supported:g(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),Ur=D({issuer:c(),authorization_endpoint:be,token_endpoint:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),service_documentation:be.optional(),revocation_endpoint:be.optional(),revocation_endpoint_auth_methods_supported:g(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:g(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:g(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:g(c()).optional(),code_challenge_methods_supported:g(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:g(c()).optional()}),Ri=D({issuer:c(),authorization_endpoint:be,token_endpoint:be,userinfo_endpoint:be.optional(),jwks_uri:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),acr_values_supported:g(c()).optional(),subject_types_supported:g(c()),id_token_signing_alg_values_supported:g(c()),id_token_encryption_alg_values_supported:g(c()).optional(),id_token_encryption_enc_values_supported:g(c()).optional(),userinfo_signing_alg_values_supported:g(c()).optional(),userinfo_encryption_alg_values_supported:g(c()).optional(),userinfo_encryption_enc_values_supported:g(c()).optional(),request_object_signing_alg_values_supported:g(c()).optional(),request_object_encryption_alg_values_supported:g(c()).optional(),request_object_encryption_enc_values_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),display_values_supported:g(c()).optional(),claim_types_supported:g(c()).optional(),claims_supported:g(c()).optional(),service_documentation:c().optional(),claims_locales_supported:g(c()).optional(),ui_locales_supported:g(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:be.optional(),op_tos_uri:be.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Do=p({...Ri.shape,...Ur.pick({code_challenge_methods_supported:!0}).shape}),Fo=p({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:ub().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),xi=p({issued_token_type:h("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:z().optional(),scope:c().optional()}).strip(),Ho=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),Bl=be.optional().or(h("").transform(()=>{return})),Pi=p({redirect_uris:g(be),token_endpoint_auth_method:c().optional(),grant_types:g(c()).optional(),response_types:g(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:be.optional(),logo_uri:Bl,scope:c().optional(),contacts:g(c()).optional(),tos_uri:Bl,policy_uri:c().optional(),jwks_uri:be.optional(),jwks:Aa().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ti=p({client_id:c(),client_secret:c().optional(),client_id_issued_at:z().optional(),client_secret_expires_at:z().optional(),issuer:c().optional().catch(void 0)}).strip(),Vo=Pi.merge(Ti),ac=p({error:c(),error_description:c().optional()}).strip(),cc=p({token:c(),token_type_hint:c().optional()}).strip();var Ql=Symbol.for("mcp.sdk.errorBrands");function Zr(e,t){let r=new Set,o=t;while(typeof o==="function"){let n=o.mcpBrand;if(Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof n==="string")r.add(n);o=Object.getPrototypeOf(o)}if(r.size===0)return;Object.defineProperty(e,Ql,{value:r,enumerable:!1,configurable:!0})}function Be(e,t){try{if(typeof t==="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(t,Ql)){let r=t[Ql];if(r&&typeof r.has==="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Ut=function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e}({}),Dr=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.errorUri=o,this.name="OAuthError",Zr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};if(this.errorUri)t.error_uri=this.errorUri;return t}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},O=function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e}({}),N=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r,o){super(t,o);this.code=e,this.data=r,this.name="SdkError",Zr(this,new.target)}},vt=class extends N{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function $f(e){let t=typeof e==="string"?new URL(e):new URL(e.href);return t.hash="",t}function nu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Cf({requestedResource:e,configuredResource:t}){let r=typeof e==="string"?new URL(e):new URL(e.href),o=typeof t==="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}var If="2026-07-28",su=[If];function Zt(e){return e>=If}function iu(e){return e.filter((t)=>!Zt(t))}function Oi(e){return e.filter((t)=>Zt(t))}function Of(e){let t=e.structuredContent;if(t===void 0)return e;if(!(typeof t!=="object"||t===null||Array.isArray(t)))return e;if(e.content?.some((r)=>r.type==="text")??!1)return e;return{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Nf=["task","inputRequests","requestState"];function mb(e){if(e===null||typeof e!=="object"||Array.isArray(e)||e.content!==void 0||Nf.some((t)=>(t in e)))return e;return{...e,content:[]}}function fb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=p({ttl:z().optional()}),s=p({taskId:c()}),i=D({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=p({_meta:i.optional()}),l=a.extend({task:n.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:i.optional()}),m=p({method:c(),params:d.loose().optional()}),f=D({_meta:i.optional()}),S=T([c(),z().int()]),b=f.strict(),y=d.extend({requestId:S.optional(),reason:c().optional()}),v=m.extend({method:h("notifications/cancelled"),params:y}),L=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),F=p({icons:g(L).optional()}),x=p({name:c(),title:c().optional()}),U=x.extend({...x.shape,...F.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),R=$t(p({applyDefaults:E().optional()}),t),w=xr((Pe)=>{if(Pe&&typeof Pe==="object"&&!Array.isArray(Pe)&&Object.keys(Pe).length===0)return{form:{}};return Pe},$t(p({form:R.optional(),url:t.optional()}),t.optional())),Z=D({list:t.optional(),cancel:t.optional(),requests:D({sampling:D({createMessage:t.optional()}).optional(),elicitation:D({create:t.optional()}).optional()}).optional()}),X=D({list:t.optional(),cancel:t.optional(),requests:D({tools:D({call:t.optional()}).optional()}).optional()}),Y=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Z.optional(),extensions:P(c(),t).optional()}),ce=a.extend({protocolVersion:c(),capabilities:Y,clientInfo:U}),Ee=u.extend({method:h("initialize"),params:ce}),te=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:X.optional(),extensions:P(c(),t).optional()}),se=f.extend({protocolVersion:c(),capabilities:te,serverInfo:U,instructions:c().optional()}),ve=m.extend({method:h("notifications/initialized"),params:d.optional()}),ke=u.extend({method:h("ping"),params:a.optional()}),ct=p({progress:z(),total:j(z()),message:j(c())}),qe=p({...d.shape,...ct.shape,progressToken:r}),We=m.extend({method:h("notifications/progress"),params:qe}),lt=a.extend({cursor:o.optional()}),Ze=u.extend({params:lt.optional()}),$e=f.extend({nextCursor:o.optional()}),Tt=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),Et=Tt.extend({text:c()}),ut=c().refine((Pe)=>{try{return atob(Pe),!0}catch{return!1}},{message:"Invalid Base64 string"}),Re=Tt.extend({blob:ut}),Ce=K(["user","assistant"]),Ie=p({audience:g(Ce).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),et=p({...x.shape,...F.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:Ie.optional(),_meta:j(D({}))}),lr=p({...x.shape,...F.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:Ie.optional(),_meta:j(D({}))}),De=Ze.extend({method:h("resources/list")}),Fe=$e.extend({resources:g(et)}),Ae=Ze.extend({method:h("resources/templates/list")}),Ke=$e.extend({resourceTemplates:g(lr)}),Ge=a.extend({uri:c()}),dt=Ge,pt=u.extend({method:h("resources/read"),params:dt}),Ht=f.extend({contents:g(T([Et,Re]))}),ht=m.extend({method:h("notifications/resources/list_changed"),params:d.optional()}),ur=Ge,C=u.extend({method:h("resources/subscribe"),params:ur}),mt=Ge,H=u.extend({method:h("resources/unsubscribe"),params:mt}),q=d.extend({uri:c()}),G=m.extend({method:h("notifications/resources/updated"),params:q}),I=p({name:c(),description:j(c()),required:j(E())}),k=p({...x.shape,...F.shape,description:j(c()),arguments:j(g(I)),_meta:j(D({}))}),B=Ze.extend({method:h("prompts/list")}),J=$e.extend({prompts:g(k)}),ge=a.extend({name:c(),arguments:P(c(),c()).optional()}),dr=u.extend({method:h("prompts/get"),params:ge}),ft=p({type:h("text"),text:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),pr=p({type:h("image"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),hr=p({type:h("audio"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),nn=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Vt=p({type:h("resource"),resource:T([Et,Re]),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),sn=et.extend({type:h("resource_link")}),Ye=T([ft,pr,hr,sn,Vt]),Kr=p({role:Ce,content:Ye}),Gr=f.extend({description:c().optional(),messages:g(Kr)}),mr=m.extend({method:h("notifications/prompts/list_changed"),params:d.optional()}),an=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Yr=p({taskSupport:K(["required","optional","forbidden"]).optional()}),fr=p({...x.shape,...F.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()).optional(),annotations:an.optional(),execution:Yr.optional(),_meta:P(c(),A()).optional()}),Xr=Ze.extend({method:h("tools/list")}),Qr=$e.extend({tools:g(fr)}),eo=f.extend({content:g(Ye),structuredContent:P(c(),A()).optional(),isError:E().optional()}),xe=l.extend({name:c(),arguments:P(c(),A()).optional()}),cn=u.extend({method:h("tools/call"),params:xe}),Gi=m.extend({method:h("notifications/tools/list_changed"),params:d.optional()}),to=K(["debug","info","notice","warning","error","critical","alert","emergency"]),ln=a.extend({level:to}),un=u.extend({method:h("logging/setLevel"),params:ln}),dn=d.extend({level:to,logger:c().optional(),data:A()}),pn=m.extend({method:h("notifications/message"),params:dn}),hn=p({name:c().optional()}),mn=p({hints:g(hn).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),fn=p({mode:K(["auto","required","none"]).optional()}),Yi=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(Ye),structuredContent:p({}).loose().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),gn=po("type",[ft,pr,hr]),Jt=po("type",[ft,pr,hr,nn,Yi]),Sn=p({role:Ce,content:T([Jt,g(Jt)]),_meta:P(c(),A()).optional()}),_n=l.extend({messages:g(Sn),modelPreferences:mn.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(fr).optional(),toolChoice:fn.optional()}),bn=u.extend({method:h("sampling/createMessage"),params:_n}),yn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Ce,content:gn}),vn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Ce,content:T([Jt,g(Jt)])}),zn=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),wn=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Rn=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),xn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Pn=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Tn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),En=T([xn,Pn]),gr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Sr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),Xi=T([gr,Sr]),Qi=T([Tn,En,Xi]),He=T([Qi,zn,wn,Rn]),Ve=l.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),He),required:g(c()).optional()}).catchall(A())}),kn=l.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),tt=T([Ve,kn]),ea=u.extend({method:h("elicitation/create"),params:tt}),ta=d.extend({elicitationId:c()}),ra=m.extend({method:h("notifications/elicitation/complete"),params:ta}),oa=f.extend({action:K(["accept","decline","cancel"]),content:xr((Pe)=>Pe===null?void 0:Pe,P(c(),T([c(),z(),E(),g(c())])).optional())}),na=p({type:h("ref/resource"),uri:c()}),sa=p({type:h("ref/prompt"),name:c()}),ia=a.extend({ref:T([sa,na]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),$n=u.extend({method:h("completion/complete"),params:ia}),aa=f.extend({completion:D({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),ca=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),ro=u.extend({method:h("roots/list"),params:a.optional()}),Cn=f.extend({roots:g(ca)}),la=m.extend({method:h("notifications/roots/list_changed"),params:d.optional()}),ua=D({ttl:z().optional(),pollInterval:z().optional()}),In=K(["working","input_required","completed","failed","cancelled"]),Bt=p({taskId:c(),status:In,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Me=f.extend({task:Bt}),da=d.merge(Bt),_r=m.extend({method:h("notifications/tasks/status"),params:da}),oo=u.extend({method:h("tasks/get"),params:a.extend({taskId:c()})}),no=f.merge(Bt),so=u.extend({method:h("tasks/result"),params:a.extend({taskId:c()})}),qc=f.loose(),Oe=Ze.extend({method:h("tasks/list")}),fe=$e.extend({tasks:g(Bt)}),br=u.extend({method:h("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:s,RequestMetaSchema:i,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:b,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:L,IconsSchema:F,BaseMetadataSchema:x,ImplementationSchema:U,ClientTasksCapabilitySchema:Z,ServerTasksCapabilitySchema:X,ClientCapabilitiesSchema:Y,InitializeRequestParamsSchema:ce,InitializeRequestSchema:Ee,ServerCapabilitiesSchema:te,InitializeResultSchema:se,InitializedNotificationSchema:ve,PingRequestSchema:ke,ProgressSchema:ct,ProgressNotificationParamsSchema:qe,ProgressNotificationSchema:We,PaginatedRequestParamsSchema:lt,PaginatedRequestSchema:Ze,PaginatedResultSchema:$e,ResourceContentsSchema:Tt,TextResourceContentsSchema:Et,BlobResourceContentsSchema:Re,RoleSchema:Ce,AnnotationsSchema:Ie,ResourceSchema:et,ResourceTemplateSchema:lr,ListResourcesRequestSchema:De,ListResourcesResultSchema:Fe,ListResourceTemplatesRequestSchema:Ae,ListResourceTemplatesResultSchema:Ke,ResourceRequestParamsSchema:Ge,ReadResourceRequestParamsSchema:dt,ReadResourceRequestSchema:pt,ReadResourceResultSchema:Ht,ResourceListChangedNotificationSchema:ht,SubscribeRequestParamsSchema:ur,SubscribeRequestSchema:C,UnsubscribeRequestParamsSchema:mt,UnsubscribeRequestSchema:H,ResourceUpdatedNotificationParamsSchema:q,ResourceUpdatedNotificationSchema:G,PromptArgumentSchema:I,PromptSchema:k,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:ge,GetPromptRequestSchema:dr,TextContentSchema:ft,ImageContentSchema:pr,AudioContentSchema:hr,ToolUseContentSchema:nn,EmbeddedResourceSchema:Vt,ResourceLinkSchema:sn,ContentBlockSchema:Ye,PromptMessageSchema:Kr,GetPromptResultSchema:Gr,PromptListChangedNotificationSchema:mr,ToolAnnotationsSchema:an,ToolExecutionSchema:Yr,ToolSchema:fr,ListToolsRequestSchema:Xr,ListToolsResultSchema:Qr,CallToolResultSchema:eo,CallToolRequestParamsSchema:xe,CallToolRequestSchema:cn,ToolListChangedNotificationSchema:Gi,LoggingLevelSchema:to,SetLevelRequestParamsSchema:ln,SetLevelRequestSchema:un,LoggingMessageNotificationParamsSchema:dn,LoggingMessageNotificationSchema:pn,ModelHintSchema:hn,ModelPreferencesSchema:mn,ToolChoiceSchema:fn,ToolResultContentSchema:Yi,SamplingContentSchema:gn,SamplingMessageContentBlockSchema:Jt,SamplingMessageSchema:Sn,CreateMessageRequestParamsSchema:_n,CreateMessageRequestSchema:bn,CreateMessageResultSchema:yn,CreateMessageResultWithToolsSchema:vn,BooleanSchemaSchema:zn,StringSchemaSchema:wn,NumberSchemaSchema:Rn,UntitledSingleSelectEnumSchemaSchema:xn,TitledSingleSelectEnumSchemaSchema:Pn,LegacyTitledEnumSchemaSchema:Tn,SingleSelectEnumSchemaSchema:En,UntitledMultiSelectEnumSchemaSchema:gr,TitledMultiSelectEnumSchemaSchema:Sr,MultiSelectEnumSchemaSchema:Xi,EnumSchemaSchema:Qi,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ve,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:tt,ElicitRequestSchema:ea,ElicitationCompleteNotificationParamsSchema:ta,ElicitationCompleteNotificationSchema:ra,ElicitResultSchema:oa,ResourceTemplateReferenceSchema:na,PromptReferenceSchema:sa,CompleteRequestParamsSchema:ia,CompleteRequestSchema:$n,CompleteResultSchema:aa,RootSchema:ca,ListRootsRequestSchema:ro,ListRootsResultSchema:Cn,RootsListChangedNotificationSchema:la,TaskCreationParamsSchema:ua,TaskStatusSchema:In,TaskSchema:Bt,CreateTaskResultSchema:Me,TaskStatusNotificationParamsSchema:da,TaskStatusNotificationSchema:_r,GetTaskRequestSchema:oo,GetTaskResultSchema:no,GetTaskPayloadRequestSchema:so,GetTaskPayloadResultSchema:qc,ListTasksRequestSchema:Oe,ListTasksResultSchema:fe,CancelTaskRequestSchema:br,CancelTaskResultSchema:f.merge(Bt),ClientRequestSchema:T([ke,Ee,$n,un,dr,B,De,Ae,pt,C,H,cn,Xr,oo,so,Oe,br]),ClientNotificationSchema:T([v,We,ve,la,_r]),ClientResultSchema:T([b,yn,vn,oa,Cn,no,fe,Me]),ServerRequestSchema:T([ke,bn,ea,ro,oo,so,Oe,br]),ServerNotificationSchema:T([v,We,pn,G,ht,Gi,mr,_r,ra]),ServerResultSchema:T([b,se,aa,Gr,J,Fe,Ke,Ht,eo,Qr,no,fe,Me]),CallToolResultWireSchema:A().superRefine((Pe,NS)=>{if(typeof Pe!=="object"||Pe===null||Array.isArray(Pe)||Pe.content!==void 0)return;for(let td of Nf)if(td in Pe){NS.addIssue({code:"custom",message:`content is required when the body carries '${td}' — another result family cannot default into an empty tools/call success`});return}}).transform(mb).pipe(eo)}}var gb;function qf(){return gb??=fb()}function Af(e){return e.type!=="object"}var Sb=new Set(["const","enum","default","examples"]),_b=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function gf(e){return e!==void 0&&!(typeof e==="string"&&e.startsWith("#"))}function bb(e){let t=typeof e.$schema==="string"?e.$schema:void 0;if(gf(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=id(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,s)=>{if(Array.isArray(n))return n.map((l)=>o(l,!1));if(n===null||typeof n!=="object")return n;if(!s&&gf(n.$id))return n;let i={},a=!1;for(let[l,u]of Object.entries(n))if(s)i[l]=o(u,!1);else if((l==="$ref"||l==="$dynamicRef")&&typeof u==="string")i[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u;else if(l==="$recursiveRef"&&u==="#"&&r)a=!0;else if(Sb.has(l))i[l]=u;else if(_b.has(l))i[l]=o(u,!0);else i[l]=o(u,!1);if(a)if("$ref"in i)i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}];else i.$ref="#/properties/result";return i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Mf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},jf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},yb={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},lc;function au(){if(lc)return lc;let e=qf();return lc={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},lc}function Lf(e){return Object.prototype.hasOwnProperty.call(Mf,e)}function Uf(e){return Object.prototype.hasOwnProperty.call(jf,e)}function vb(e){return Object.prototype.hasOwnProperty.call(yb,e)}function zb(e){return vb(e)?au().resultSchemas[e]:void 0}function wb(e){return Lf(e)?au().requestSchemas[e]:void 0}function Rb(e){return Uf(e)?au().notificationSchemas[e]:void 0}var Px=Object.keys(Mf),Tx=Object.keys(jf);function eu(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function uc(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Sf={ok:!1,reason:"not-in-era"};function _f(e){return eu(e)&&eu(e.outputSchema)&&Af(e.outputSchema)}function bf(e){return e}var cu={era:"2025-11-25",hasRequestMethod:Lf,hasNotificationMethod:Uf,validateRequest:(e,t)=>uc(wb(e),t),validateResult:(e,t)=>uc(zb(e),t),validateNotification:(e,t)=>uc(Rb(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Sf,validateInputResponse:()=>Sf,samplingResultVariant:(e,t)=>{let r=qf();return uc(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:(e)=>{return},validateEnvelopeMeta:(e)=>[],projectCallToolResult(e,t){let r=Of(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!=="object"||o===null||Array.isArray(o),s=t!==void 0&&Af(t);if(!n&&!s)return r;return{...r,structuredContent:{result:o}}},decodeResult(e,t){if(eu(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:bf(r)}}return{kind:"complete",result:bf(t)}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;if(!Array.isArray(r)||!r.some((o)=>_f(o)))return t;return{...t,tools:r.map((o)=>_f(o)?{...o,outputSchema:bb(o.outputSchema)}:o)}},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope:(e)=>{return}};function xb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=T([c(),z().int()]),s=K(["user","assistant"]),i=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine((fe)=>{try{return atob(fe),!0}catch{return!1}},{message:"Invalid Base64 string"}),l=p({ttl:z().optional()}),u=p({taskId:c()}),d=D({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),m=p({_meta:d.optional()}),f=m.extend({task:l.optional()}),S=p({_meta:d.optional()}),b=p({method:c(),params:S.loose().optional()}),y=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),v=p({icons:g(y).optional()}),L=p({name:c(),title:c().optional()}),F=L.extend({...L.shape,...v.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=$t(p({applyDefaults:E().optional()}),t),U=xr((fe)=>{if(fe&&typeof fe==="object"&&!Array.isArray(fe)&&Object.keys(fe).length===0)return{form:{}};return fe},$t(p({form:x.optional(),url:t.optional()}),t.optional())),R=D({list:t.optional(),cancel:t.optional(),requests:D({sampling:D({createMessage:t.optional()}).optional(),elicitation:D({create:t.optional()}).optional()}).optional()}),w=D({list:t.optional(),cancel:t.optional(),requests:D({tools:D({call:t.optional()}).optional()}).optional()}),Z=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:U.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:R.optional(),extensions:P(c(),t).optional()}),X=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:w.optional(),extensions:P(c(),t).optional()}),Y=p({progress:z(),total:j(z()),message:j(c())}),ce=p({...S.shape,...Y.shape,progressToken:r}),Ee=b.extend({method:h("notifications/progress"),params:ce}),te=S.extend({level:i,logger:c().optional(),data:A()}),se=b.extend({method:h("notifications/message"),params:te}),ve=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ke=ve.extend({text:c()}),ct=ve.extend({blob:a}),qe=p({audience:g(s).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),We=p({...L.shape,...v.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:qe.optional(),_meta:j(D({}))}),lt=p({...L.shape,...v.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:qe.optional(),_meta:j(D({}))}),Ze=b.extend({method:h("notifications/resources/list_changed"),params:S.optional()}),$e=S.extend({uri:c()}),Tt=b.extend({method:h("notifications/resources/updated"),params:$e}),Et=p({name:c(),description:j(c()),required:j(E())}),ut=p({...L.shape,...v.shape,description:j(c()),arguments:j(g(Et)),_meta:j(D({}))}),Re=b.extend({method:h("notifications/prompts/list_changed"),params:S.optional()}),Ce=p({type:h("text"),text:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Ie=p({type:h("image"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),et=p({type:h("audio"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),lr=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),De=p({type:h("resource"),resource:T([ke,ct]),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Fe=We.extend({type:h("resource_link")}),Ae=T([Ce,Ie,et,Fe,De]),Ke=p({role:s,content:Ae}),Ge=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),dt=b.extend({method:h("notifications/tools/list_changed"),params:S.optional()}),pt=p({name:c().optional()}),Ht=p({hints:g(pt).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),ht=p({mode:K(["auto","required","none"]).optional()}),ur=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),C=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),mt=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),H=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),q=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),G=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),I=T([H,q]),k=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),B=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),J=T([k,B]),ge=T([G,I,J]),dr=T([ge,ur,C,mt]),ft=f.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),dr),required:g(c()).optional()}).catchall(A())}),pr=p({type:h("ref/resource"),uri:c()}),hr=p({type:h("ref/prompt"),name:c()}),nn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),Vt=Z.shape,sn=p({experimental:Vt.experimental,sampling:Vt.sampling,elicitation:Vt.elicitation,roots:Vt.roots,extensions:Vt.extensions}),Ye=X.shape,Kr=p({experimental:Ye.experimental,logging:Ye.logging,completions:Ye.completions,prompts:Ye.prompts,resources:Ye.resources,tools:Ye.tools,extensions:Ye.extensions}),Gr=D({progressToken:r.optional(),[It]:c(),[mo]:F.optional(),[Pr]:sn,[fo]:i.optional()}),mr=p({...L.shape,...v.shape,description:c().optional(),inputSchema:D({$schema:c().optional(),type:h("object")}),outputSchema:D({$schema:c().optional()}).optional(),annotations:Ge.optional(),_meta:P(c(),A()).optional()}),an=p({type:h("tool_result"),toolUseId:c(),content:g(Ae),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Yr=T([Ce,Ie,et,lr,an]),fr=p({role:s,content:T([Yr,g(Yr)]),_meta:P(c(),A()).optional()}),Xr=c(),Qr=D({[Ot]:F.optional().catch(void 0)}),eo=Qr.optional();function xe(fe){return D({_meta:eo,resultType:Xr.default("complete"),...fe})}let cn=xe({}),Gi=xe({nextCursor:o.optional()}),to=xe({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),ln=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),un=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),dn=xe({description:c().optional(),messages:g(Ke)}),pn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),hn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),mn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),fn=xe({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),Yi=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"])}),gn=xe({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),Jt=p({messages:g(fr),modelPreferences:Ht.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(mr).optional(),toolChoice:ht.optional()}),Sn=p({method:h("sampling/createMessage"),params:Jt}),_n=p({method:h("roots/list"),params:p({_meta:P(c(),A()).optional()}).optional()}),bn=p({...fr.shape,model:c(),stopReason:c().optional()}),yn=p({roots:g(nn)}),vn=p({action:K(["accept","decline","cancel"]),content:P(c(),T([c(),z(),E(),g(c())])).optional()}),zn=p({mode:h("url"),message:c(),url:c().url()}),wn=T([ft,zn]),Rn=p({method:h("elicitation/create"),params:wn}),xn=T([Sn,_n,Rn]),Pn=T([bn,yn,vn]),Tn=P(c(),xn),En=P(c(),Pn),gr=xe({inputRequests:Tn.optional(),requestState:c().optional()}),Sr={inputResponses:En.optional(),requestState:c().optional()},Xi=p({_meta:Gr,...Sr}),Qi=D({progressToken:r.optional()});function He(fe,br){return p({method:h(fe),params:p({_meta:Gr,...br})})}function Ve(fe,br){return p({method:h(fe),params:p({_meta:Qi.optional(),...br}).optional()})}let kn={name:c(),arguments:P(c(),A()).optional(),...Sr},tt={cursor:o.optional()},ea=He("tools/call",kn),ta=He("tools/list",tt),ra=He("prompts/list",tt),oa=He("prompts/get",{name:c(),arguments:P(c(),c()).optional(),...Sr}),na=He("resources/list",tt),sa=He("resources/templates/list",tt),ia=He("resources/read",{uri:c(),...Sr}),$n={ref:T([hr,pr]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()},aa=He("completion/complete",$n),ca=He("server/discover",{}),ro=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),Cn={notifications:ro},la=He("subscriptions/listen",Cn),ua=Qr.extend({"io.modelcontextprotocol/subscriptionId":n}),In=D({_meta:ua,resultType:Xr.default("complete")}),Bt={"tools/call":Ve("tools/call",kn),"tools/list":Ve("tools/list",tt),"prompts/get":Ve("prompts/get",{name:c(),arguments:P(c(),c()).optional()}),"prompts/list":Ve("prompts/list",tt),"resources/list":Ve("resources/list",tt),"resources/templates/list":Ve("resources/templates/list",tt),"resources/read":Ve("resources/read",{uri:c()}),"completion/complete":Ve("completion/complete",$n),"server/discover":Ve("server/discover",{}),"subscriptions/listen":Ve("subscriptions/listen",Cn)};function Me(fe){return D({_meta:eo,...fe})}let da={"tools/call":Me({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),"tools/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),"prompts/get":Me({description:c().optional(),messages:g(Ke)}),"prompts/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),"resources/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),"resources/templates/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),"resources/read":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),"completion/complete":Me({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Me({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),"subscriptions/listen":Me({})},_r=D({"io.modelcontextprotocol/subscriptionId":n.optional()}),oo=p({method:h("notifications/subscriptions/acknowledged"),params:p({_meta:_r.optional(),notifications:ro})}),no=p({_meta:_r.optional(),requestId:n,reason:c().optional()}),so=p({method:h("notifications/cancelled"),params:no}),qc={"notifications/cancelled":so,"notifications/progress":Ee,"notifications/message":se,"notifications/resources/updated":Tt,"notifications/resources/list_changed":Ze,"notifications/tools/list_changed":dt,"notifications/prompts/list_changed":Re,"notifications/subscriptions/acknowledged":oo},Oe=(fe)=>p({jsonrpc:h("2.0"),id:T([c(),z().int()]),result:fe}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:s,LoggingLevelSchema:i,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:S,NotificationSchema:b,IconSchema:y,IconsSchema:v,BaseMetadataSchema:L,ImplementationSchema:F,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:Z,ServerCapabilitiesSchema:X,ProgressSchema:Y,ProgressNotificationParamsSchema:ce,ProgressNotificationSchema:Ee,LoggingMessageNotificationParamsSchema:te,LoggingMessageNotificationSchema:se,ResourceContentsSchema:ve,TextResourceContentsSchema:ke,BlobResourceContentsSchema:ct,AnnotationsSchema:qe,ResourceSchema:We,ResourceTemplateSchema:lt,ResourceListChangedNotificationSchema:Ze,ResourceUpdatedNotificationParamsSchema:$e,ResourceUpdatedNotificationSchema:Tt,PromptArgumentSchema:Et,PromptSchema:ut,PromptListChangedNotificationSchema:Re,TextContentSchema:Ce,ImageContentSchema:Ie,AudioContentSchema:et,ToolUseContentSchema:lr,EmbeddedResourceSchema:De,ResourceLinkSchema:Fe,ContentBlockSchema:Ae,PromptMessageSchema:Ke,ToolAnnotationsSchema:Ge,ToolListChangedNotificationSchema:dt,ModelHintSchema:pt,ModelPreferencesSchema:Ht,ToolChoiceSchema:ht,BooleanSchemaSchema:ur,StringSchemaSchema:C,NumberSchemaSchema:mt,UntitledSingleSelectEnumSchemaSchema:H,TitledSingleSelectEnumSchemaSchema:q,LegacyTitledEnumSchemaSchema:G,SingleSelectEnumSchemaSchema:I,UntitledMultiSelectEnumSchemaSchema:k,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:ge,PrimitiveSchemaDefinitionSchema:dr,ElicitRequestFormParamsSchema:ft,ResourceTemplateReferenceSchema:pr,PromptReferenceSchema:hr,RootSchema:nn,ClientCapabilities2026Schema:sn,ServerCapabilities2026Schema:Kr,RequestMetaEnvelopeSchema:Gr,ToolSchema:mr,ToolResultContentSchema:an,SamplingMessageContentBlockSchema:Yr,SamplingMessageSchema:fr,ResultTypeSchema:Xr,ResultMetaSchema:Qr,ResultSchema:cn,PaginatedResultSchema:Gi,CallToolResultSchema:to,ListToolsResultSchema:ln,ListPromptsResultSchema:un,GetPromptResultSchema:dn,ListResourcesResultSchema:pn,ListResourceTemplatesResultSchema:hn,ReadResourceResultSchema:mn,CompleteResultSchema:fn,CacheableResultSchema:Yi,DiscoverResultSchema:gn,CreateMessageRequestParamsSchema:Jt,CreateMessageRequestSchema:Sn,ListRootsRequestSchema:_n,CreateMessageResultSchema:bn,ListRootsResultSchema:yn,ElicitResultSchema:vn,ElicitRequestURLParamsSchema:zn,ElicitRequestParamsSchema:wn,ElicitRequestSchema:Rn,InputRequestSchema:xn,InputResponseSchema:Pn,InputRequestsSchema:Tn,InputResponsesSchema:En,InputRequiredResultSchema:gr,InputResponseRequestParamsSchema:Xi,CallToolRequestSchema:ea,ListToolsRequestSchema:ta,ListPromptsRequestSchema:ra,GetPromptRequestSchema:oa,ListResourcesRequestSchema:na,ListResourceTemplatesRequestSchema:sa,ReadResourceRequestSchema:ia,CompleteRequestSchema:aa,DiscoverRequestSchema:ca,SubscriptionFilterSchema:ro,SubscriptionsListenRequestSchema:la,SubscriptionsListenResultMetaSchema:ua,SubscriptionsListenResultSchema:In,dispatchRequestSchemas:Bt,dispatchResultSchemas:da,NotificationMetaSchema:_r,SubscriptionsAcknowledgedNotificationSchema:oo,CancelledNotificationParamsSchema:no,CancelledNotificationSchema:so,notificationSchemas2026:qc,JSONRPCResultResponseSchema:Oe(cn),CallToolResultResponseSchema:Oe(T([to,gr])),ListToolsResultResponseSchema:Oe(ln),ListPromptsResultResponseSchema:Oe(un),GetPromptResultResponseSchema:Oe(T([dn,gr])),ListResourcesResultResponseSchema:Oe(pn),ListResourceTemplatesResultResponseSchema:Oe(hn),ReadResourceResultResponseSchema:Oe(T([mn,gr])),CompleteResultResponseSchema:Oe(fn),DiscoverResultResponseSchema:Oe(gn),SubscriptionsListenResultResponseSchema:Oe(In)}}var Pb;function sr(){return Pb??=xb()}var Tb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Eb(e){return Tb.includes(e)}var lu=Symbol("modelcontextprotocol.resultCacheHintFallback");function kb(e){return e[lu]}function Zf(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function Df(e){return e==="public"||e==="private"}var W=function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e}({}),ee=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.data=o,this.name="ProtocolError",Zr(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Hf(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested==="string")return new fc({supported:n.supported,requested:n.requested},r)}if(t===W.InvalidParams||t===W.ResourceNotFound){let n=o;if(typeof n?.uri==="string"&&(t===W.ResourceNotFound||Object.keys(n).length===1))return new Ff(n.uri,r)}if(t===W.MissingRequiredClientCapability&&o){let n=o;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities==="object"&&!Array.isArray(n.requiredCapabilities))return new Vf({requiredCapabilities:n.requiredCapabilities},r)}return new e(t,r,o)}},Ff=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(W.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Hf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},fc=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(W.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Vf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(W.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},$b=0,Cb="private",Ib=["tools/call","prompts/get","resources/read"];function Ob(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete")return t;if(Ib.includes(e))return t;throw new ee(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Nb(e,t){let r=kb(t);if(t.resultType!=="complete"||!Eb(e))return r===void 0?t:Lb(t);let o=t,n=Zf(o.ttlMs)?o.ttlMs:Mb(r),s=Df(o.cacheScope)?o.cacheScope:jb(r),i={...o,ttlMs:n,cacheScope:s};return delete i[lu],i}function qb(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ab(e,t){if(t===void 0)return e;let r=e._meta;if(r===void 0)return{...e,_meta:{[Ot]:t}};if(!qb(r))return e;if(r[Ot]!==void 0)return e;return{...e,_meta:{...r,[Ot]:t}}}function Mb(e){return e!==void 0&&Zf(e.ttlMs)?e.ttlMs:$b}function jb(e){return e!==void 0&&Df(e.cacheScope)?e.cacheScope:Cb}function Lb(e){let t={...e};return delete t[lu],t}var Ub=["elicitation/create","sampling/createMessage","roots/list"],dc;function Jf(){if(dc)return dc;let e=sr();return dc={request:{"elicitation/create":p({method:h("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":p({method:h("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":p({method:h("roots/list"),params:D({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},dc}function Bf(e){return Ub.includes(e)}function Kl(e){return Bf(e)?Jf().request[e]:void 0}function Zb(e){return Bf(e)?Jf().response[e]:void 0}var uu={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Wf={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Kf(e){return Object.prototype.hasOwnProperty.call(uu,e)}function Gf(e){return Object.prototype.hasOwnProperty.call(Wf,e)}function Db(e){return Object.prototype.hasOwnProperty.call(uu,e)}function Fb(e){return Kf(e)?sr().dispatchRequestSchemas[e]:void 0}function Hb(e){return Db(e)?sr().dispatchResultSchemas[e]:void 0}function Vb(e){return Gf(e)?sr().notificationSchemas2026[e]:void 0}var Ex=Object.keys(uu),kx=Object.keys(Wf);function $i(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ei(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Jb={ok:!1,reason:"not-in-era"},Bb=[It,Pr];function Wb(e,t){let r=t,o=!1,n=()=>{if(!o)r={...r},o=!0;return r},s=t.tools;if(e==="tools/list"&&Array.isArray(s)&&s.some((a)=>$i(a)&&("execution"in a)))n().tools=s.map((a)=>{if(!$i(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l});let i=t.capabilities;if($i(i)&&"tasks"in i){let a={...i};delete a.tasks,n().capabilities=a}return r}var du={era:"2026-07-28",hasRequestMethod:Kf,hasNotificationMethod:Gf,hasInputRequestMethod:(e)=>Kl(e)!==void 0,validateRequest:(e,t)=>Ei(Fb(e),t),validateResult:(e,t)=>Ei(Hb(e),t),validateNotification:(e,t)=>Ei(Vb(e),t),validateInputRequest:(e,t)=>Ei(Kl(e),t),validateInputResponse:(e,t)=>Ei(Zb(e),t),samplingResultVariant:()=>Jb,outboundEnvelope(e){return{[It]:e.protocolVersion,[mo]:e.clientInfo,[Pr]:e.clientCapabilities,...e.logLevel!==void 0&&{[fo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of Bb)if(!(o in e))t.push({key:o,problem:"missing"});let r=sr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),s=n.length>0?n.join("."):"_meta";if(n.length===1&&t.some((i)=>i.key===s&&i.problem==="missing"))continue;t.push({key:s,problem:o.message})}return t},projectCallToolResult:(e)=>Of(e),inputRequestSchema:Kl,decodeResult(e,t){if(!$i(t))return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!=="string")return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let i=t.inputRequests,a=$i(i)?i:{},l=t.requestState,u=t._meta===void 0?void 0:sr().ResultMetaSchema.safeParse(t._meta),d=u?.success?u.data:void 0;if(Object.keys(a).length===0&&typeof l!=="string")return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})};return{kind:"input_required",inputRequests:a,...typeof l==="string"&&{requestState:l},...d!==void 0&&{_meta:d}}}if(r!=="complete")return{kind:"invalid",error:new N(O.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Kb(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let i=n.safeParse(t);if(!i.success)return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: ${i.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return Ab(Nb(e,Ob(e,Wb(e,t))),r)},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=sr().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map((r)=>r.message).join("; ")}`}},pc;function Kb(){if(pc)return pc;let e=sr();return pc={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},pc}var gc="2026-07-28";function Lt(e){return e!==void 0&&Zt(e)?du:cu}function yf(e){if(e.revision!==void 0)return Lt(e.revision).era;return e.era==="modern"?du.era:cu.era}function Gl(e){return Yf.some((t)=>t.hasRequestMethod(e))}function Yl(e){return Yf.some((t)=>t.hasNotificationMethod(e))}function vf(e){return e==="tasks/get"||e==="tasks/cancel"}var Yf=[cu,du],Gb=od({AnnotationsSchema:()=>bt,AudioContentSchema:()=>Or,BaseMetadataSchema:()=>St,BaseRequestParamsSchema:()=>ye,BlobResourceContentsSchema:()=>$o,BooleanSchemaSchema:()=>No,CallToolRequestParamsSchema:()=>Zs,CallToolRequestSchema:()=>Ds,CallToolResultSchema:()=>nr,CancelTaskRequestSchema:()=>Qa,CancelTaskResultSchema:()=>ec,CancelledNotificationParamsSchema:()=>Yn,CancelledNotificationSchema:()=>zo,ClientCapabilitiesSchema:()=>Qn,ClientNotificationSchema:()=>rc,ClientRequestSchema:()=>tc,ClientResultSchema:()=>oc,ClientTasksCapabilitySchema:()=>Za,CompatibilityCallToolResultSchema:()=>Fa,CompleteRequestParamsSchema:()=>fi,CompleteRequestSchema:()=>gi,CompleteResultSchema:()=>Si,ContentBlockSchema:()=>yt,CreateMessageRequestParamsSchema:()=>ei,CreateMessageRequestSchema:()=>ti,CreateMessageResultSchema:()=>ri,CreateMessageResultWithToolsSchema:()=>oi,CreateTaskResultSchema:()=>Va,CursorSchema:()=>So,DiscoverRequestSchema:()=>rs,DiscoverResultSchema:()=>rr,ElicitRequestFormParamsSchema:()=>Lr,ElicitRequestParamsSchema:()=>ci,ElicitRequestSchema:()=>li,ElicitRequestURLParamsSchema:()=>ai,ElicitResultSchema:()=>pi,ElicitationCompleteNotificationParamsSchema:()=>ui,ElicitationCompleteNotificationSchema:()=>di,EmbeddedResourceSchema:()=>Nr,EmptyResultSchema:()=>tr,EnumSchemaSchema:()=>ii,GetPromptRequestParamsSchema:()=>Cs,GetPromptRequestSchema:()=>Is,GetPromptResultSchema:()=>qs,GetTaskPayloadRequestSchema:()=>Ka,GetTaskPayloadResultSchema:()=>Ga,GetTaskRequestSchema:()=>Ba,GetTaskResultSchema:()=>Wa,IconSchema:()=>Xn,IconsSchema:()=>Nt,ImageContentSchema:()=>Ir,ImplementationSchema:()=>_t,InitializeRequestParamsSchema:()=>es,InitializeRequestSchema:()=>wo,InitializeResultSchema:()=>ts,InitializedNotificationSchema:()=>xo,JSONArraySchema:()=>La,JSONObjectSchema:()=>le,JSONRPCErrorResponseSchema:()=>kr,JSONRPCMessageSchema:()=>st,JSONRPCNotificationSchema:()=>vo,JSONRPCRequestSchema:()=>yo,JSONRPCResponseSchema:()=>Ua,JSONRPCResultResponseSchema:()=>Er,JSONValueSchema:()=>Ct,LegacyTitledEnumSchemaSchema:()=>Mo,ListChangedOptionsBaseSchema:()=>Hs,ListPromptsRequestSchema:()=>ks,ListPromptsResultSchema:()=>$s,ListResourceTemplatesRequestSchema:()=>ls,ListResourceTemplatesResultSchema:()=>us,ListResourcesRequestSchema:()=>as,ListResourcesResultSchema:()=>cs,ListRootsRequestSchema:()=>bi,ListRootsResultSchema:()=>yi,ListTasksRequestSchema:()=>Ya,ListTasksResultSchema:()=>Xa,ListToolsRequestSchema:()=>Ls,ListToolsResultSchema:()=>Us,LoggingLevelSchema:()=>Oo,LoggingMessageNotificationParamsSchema:()=>Bs,LoggingMessageNotificationSchema:()=>Ar,ModelHintSchema:()=>Ws,ModelPreferencesSchema:()=>Ks,MultiSelectEnumSchemaSchema:()=>si,NotificationSchema:()=>we,NotificationsParamsSchema:()=>Te,NumberSchemaSchema:()=>jr,PaginatedRequestParamsSchema:()=>ss,PaginatedRequestSchema:()=>qt,PaginatedResultSchema:()=>At,PingRequestSchema:()=>Po,PrimitiveSchemaDefinitionSchema:()=>Uo,ProgressNotificationParamsSchema:()=>ns,ProgressNotificationSchema:()=>To,ProgressSchema:()=>os,ProgressTokenSchema:()=>go,PromptArgumentSchema:()=>Ts,PromptListChangedNotificationSchema:()=>As,PromptMessageSchema:()=>Ns,PromptReferenceSchema:()=>mi,PromptSchema:()=>Es,ReadResourceRequestParamsSchema:()=>ds,ReadResourceRequestSchema:()=>ps,ReadResourceResultSchema:()=>hs,RelatedTaskMetadataSchema:()=>Gn,RequestIdSchema:()=>nt,RequestMetaSchema:()=>_o,RequestSchema:()=>ue,ResourceContentsSchema:()=>Eo,ResourceLinkSchema:()=>qr,ResourceListChangedNotificationSchema:()=>ms,ResourceRequestParamsSchema:()=>$r,ResourceSchema:()=>Co,ResourceTemplateReferenceSchema:()=>hi,ResourceTemplateSchema:()=>is,ResourceUpdatedNotificationParamsSchema:()=>xs,ResourceUpdatedNotificationSchema:()=>Ps,ResultMetaObjectSchema:()=>bo,ResultSchema:()=>de,RoleSchema:()=>Mt,RootSchema:()=>_i,RootsListChangedNotificationSchema:()=>vi,SamplingContentSchema:()=>Xs,SamplingMessageContentBlockSchema:()=>Qt,SamplingMessageSchema:()=>Qs,ServerCapabilitiesSchema:()=>Ro,ServerNotificationSchema:()=>sc,ServerRequestSchema:()=>nc,ServerResultSchema:()=>ic,ServerTasksCapabilitySchema:()=>Da,SetLevelRequestParamsSchema:()=>Vs,SetLevelRequestSchema:()=>Js,SingleSelectEnumSchemaSchema:()=>ni,StringSchemaSchema:()=>Mr,SubscribeRequestParamsSchema:()=>fs,SubscribeRequestSchema:()=>gs,SubscriptionFilterSchema:()=>Io,SubscriptionsAcknowledgedNotificationParamsSchema:()=>vs,SubscriptionsAcknowledgedNotificationSchema:()=>zs,SubscriptionsListenRequestParamsSchema:()=>bs,SubscriptionsListenRequestSchema:()=>ys,SubscriptionsListenResultMetaSchema:()=>ws,SubscriptionsListenResultSchema:()=>Rs,TaskAugmentedRequestParamsSchema:()=>er,TaskCreationParamsSchema:()=>Ha,TaskMetadataSchema:()=>Kn,TaskSchema:()=>jt,TaskStatusNotificationParamsSchema:()=>wi,TaskStatusNotificationSchema:()=>Ja,TaskStatusSchema:()=>zi,TextContentSchema:()=>Cr,TextResourceContentsSchema:()=>ko,TitledMultiSelectEnumSchemaSchema:()=>Lo,TitledSingleSelectEnumSchemaSchema:()=>Ao,ToolAnnotationsSchema:()=>Ms,ToolChoiceSchema:()=>Gs,ToolExecutionSchema:()=>js,ToolListChangedNotificationSchema:()=>Fs,ToolResultContentSchema:()=>Ys,ToolSchema:()=>or,ToolUseContentSchema:()=>Os,UnsubscribeRequestParamsSchema:()=>Ss,UnsubscribeRequestSchema:()=>_s,UntitledMultiSelectEnumSchemaSchema:()=>jo,UntitledSingleSelectEnumSchemaSchema:()=>qo});var Fr=(e)=>yo.safeParse(e).success,Xf=(e)=>vo.safeParse(e).success,Bo=(e)=>Er.safeParse(e).success,Wo=(e)=>kr.safeParse(e).success;var Qf=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var pu=(e)=>wo.safeParse(e).success,eg=(e)=>xo.safeParse(e).success;var Yb="Mcp-Param-",zf="x-mcp-header",Xb=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Qb=new Set(["string","integer","boolean","number"]);function hu(e){let t=[],r=new Map,o=(s,i,a)=>{if(s===null||typeof s!=="object")return;let l=s;if(zf in l){if(!a||i.length===0)return`${hc(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[zf];if(typeof d!=="string"||d.length===0)return`${hc(i)}: x-mcp-header MUST be a non-empty string`;if(!Xb.test(d))return`${hc(i)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let m=typeof l.type==="string"?l.type:void 0;if(m===void 0||!Qb.has(m))return`${hc(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let f=d.toLowerCase(),S=r.get(f);if(S!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${S}')`;r.set(f,d),t.push({path:i,headerName:d,type:m})}let u=l.properties;if(u!==null&&typeof u==="object")for(let[d,m]of Object.entries(u)){let f=o(m,[...i,d],a);if(f!==void 0)return f}for(let d of ey){let m=l[d];if(m===void 0)continue;let f=Array.isArray(m)?m:m!==null&&typeof m==="object"&&ty.has(d)?Object.values(m):[m];for(let S of f){let b=o(S,[...i,`<${d}>`],!1);if(b!==void 0)return b}}},n=o(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var ey=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],ty=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function hc(e){return e.length===0?"<root>":e.join(".")}var tg="=?base64?",rg="?=";function ry(e){if(typeof e==="string")return e;if(typeof e==="boolean")return e?"true":"false";if(typeof e==="number"){if(!Number.isFinite(e))return;if(Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}function oy(e){if(e.length===0)return!0;if(e.startsWith(tg)&&e.endsWith(rg))return!0;if(e!==e.trim())return!0;for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r===9||r>=32&&r<=126)continue;return!0}return!1}function ny(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function mu(e){return oy(e)?`${tg}${ny(e)}${rg}`:e}function sy(e,t){let r=e;for(let o of t){if(r===null||typeof r!=="object")return;r=r[o]}return r}function og(e,t){let r={};for(let o of e){let n=sy(t,o.path);if(n===void 0||n===null)continue;let s=ry(n);if(s===void 0)continue;r[`${Yb}${o.headerName}`]=mu(s)}return r}var Jo=-32020,$x=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[W.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Jo,W.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[W.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[W.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[W.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half — including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[W.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],Cx={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Jo]:400},wf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function ng(e,t){let r=Object.hasOwn(wf,e)?wf[e]:void 0;if(r===void 0)return;let o=iy(t)?t[r]:void 0;return{field:r,value:typeof o==="string"?o:void 0}}function iy(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Sc(e,t){return Ia(e,t)}function ki(e){return new Set(e.flatMap((t)=>Object.keys(t.shape)))}function tu(e){if(e==null)return!1;let t=typeof e;if(t!=="object"&&t!=="function")return!1;if(!("~standard"in e))return!1;return typeof e["~standard"]?.validate==="function"}var Rf=!1,ru="draft-2020-12";function ay(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:ru});else if(r.vendor==="zod"){if(!("_zod"in e))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");if(!Rf)Rf=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.");o=$a(e,{target:ru,io:t})}else throw Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output"){if(o.type!==void 0)return o;return sg(o)?{type:"object",...o}:o}if(o.type!==void 0&&o.type!=="object")throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function sg(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every((o)=>o!==null&&typeof o==="object"&&(o.type==="object"||sg(o)))}return!1}function cy(e){if(!e.path?.length)return e.message;return`${e.path.map((t)=>String(typeof t==="object"?t.key:t)).join(".")}: ${e.message}`}async function Xl(e,t){let r=await e["~standard"].validate(t);if(r.issues&&r.issues.length>0)return{success:!1,error:r.issues.map((o)=>cy(o)).join(", ")};return{success:!0,data:r.value}}function ly(e){let t=$a(e,{target:ru,io:"input"});return typeof t.pattern==="string"?t.pattern:void 0}var uy=/\\\.\\d\{(\d+)\}/;function dy(e){let t=uy.exec(e),r=[void 0,-1,0];if(t)r.push(Number(t[1]));return[!1,!0].flatMap((o)=>[!1,!0].flatMap((n)=>r.map((s)=>uo({local:o,offset:n,precision:s}))))}function py(e,t){let r;switch(e){case"email":r=[Bm()];break;case"uri":r=[Na()];break;case"date":r=[Fl()];break;case"date-time":r=dy(t);break}return new Set(r.map((o)=>ly(o)).filter((o)=>o!==void 0))}function hy(e,t,r){if(r!=="zod")return!0;return py(e,t).has(t)}function Ii(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function my(e){try{return ay(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ee(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var fy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function fu(e){return fy.has(e)||e.startsWith("x-")}var gy=new Set(["$schema",...Object.keys(Lr.shape.requestedSchema.shape)]),xf={string:ki([Mr,qo,Ao,Mo]),number:ki([jr]),integer:ki([jr]),boolean:ki([No]),array:ki([jo,Lo])},Sy=new Set(Mr.shape.format.unwrap().options);function _y(e,t,r,o){if(!Ii(e))return e;let n=typeof e.type==="string"&&Object.hasOwn(xf,e.type)?xf[e.type]:void 0;if(n===void 0)return e;let s={};for(let[i,a]of Object.entries(e))if(n.has(i)||fu(i))s[i]=a;else if(i==="pattern"&&e.type==="string"&&typeof e.format==="string"){if(!Sy.has(e.format))s[i]=a;else if(typeof a!=="string"||!hy(e.format,a,r))o.push(`${t}.${i}`)}else o.push(`${t}.${i}`);return s}function by(e,t){let r={},o=[];for(let[n,s]of Object.entries(e))if(n==="properties"&&Ii(s))r[n]=Object.fromEntries(Object.entries(s).map(([i,a])=>[i,_y(a,`properties.${i}`,t,o)]));else if(gy.has(n))r[n]=s;else if(!fu(n))o.push(n);if(o.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function yy(e,t){if(!Ii(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Sc(Uo,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function ou(e,t,r=""){if(Array.isArray(e)&&Array.isArray(t))return e.flatMap((o,n)=>ou(o,t[n],`${r}[${n}]`));if(!Ii(e)||!Ii(t))return[];return Object.entries(e).flatMap(([o,n])=>{let s=r?`${r}.${o}`:o;if(!Object.prototype.hasOwnProperty.call(t,o))return fu(o)?[]:[s];return ou(n,t[o],s)})}function vy(e){if(!tu(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=by(my(e.requestedSchema),t),o=Sc(Lr.shape.requestedSchema,r);if(!o.success)throw new ee(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${yy(r,o.error.message)}`);let n=ou(r,o.data);if(n.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let s=(o.data.required??[]).filter((i)=>!Object.prototype.hasOwnProperty.call(o.data.properties,i));if(s.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function zy(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState==="string";if(!t&&!r)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var Ix=Object.assign(zy,{elicit(e){try{return{method:"elicitation/create",params:vy(e)}}catch(t){throw t instanceof ee?TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var wy=!0,Ry=10,xy=250;function ig(e){return{autoFulfill:e?.autoFulfill??wy,maxRounds:e?.maxRounds??Ry}}function Py(e,t,r){let o=t!==void 0&&Object.keys(t).length>0;if(!o&&r===void 0)return e;return{...e,...o&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function Ty(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Ey(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(n),o(t?.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",s,{once:!0})})}function ky(e){let t=new AbortController,r=()=>t.abort(e?.reason);if(e?.addEventListener("abort",r,{once:!0}),e?.aborted)t.abort(e.reason);return{signal:t.signal,abort:(o)=>t.abort(o),dispose:()=>e?.removeEventListener("abort",r)}}async function $y(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:s,signal:i}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;while(!0){if(u+=1,u>t.maxRounds)throw new N(O.InputRequiredRoundsExceeded,Ty(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:l.inputRequests,...l.requestState!==void 0&&{requestState:l.requestState}}});n.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let d=Object.entries(l.inputRequests??{}),m;if(d.length>0){let b=ky(i);try{let y=await Promise.all(d.map(async([v,L])=>{try{return[v,await s.dispatchInputRequest(v,L,b.signal)]}catch(F){throw b.abort(F),F}}));m=Object.fromEntries(y)}finally{b.dispose()}}else await Ey(xy,i);let f={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let b=Date.now()-a,y=n.maxTotalTimeout-b;if(y<=0)throw new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:b});f.maxTotalTimeout=y}let S=await s.retry(Py(o,m,l.requestState),f);if(Qf(S)){l={inputRequests:S.inputRequests??{},...S.requestState!==void 0&&{requestState:S.requestState}};continue}return S}}var Cy=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],Iy={IdJagTokenExchangeResponseSchema:xi,OAuthClientInformationFullSchema:Vo,OAuthClientInformationSchema:Ti,OAuthClientMetadataSchema:Pi,OAuthClientRegistrationErrorSchema:ac,OAuthErrorResponseSchema:Ho,OAuthMetadataSchema:Ur,OAuthProtectedResourceMetadataSchema:Zo,OAuthTokenRevocationRequestSchema:cc,OAuthTokensSchema:Fo,OpenIdProviderDiscoveryMetadataSchema:Do,OpenIdProviderMetadataSchema:Ri},ag={},cg={};function lg(e,t){let r=e.slice(0,-6);ag[r]=t,cg[r]=(o)=>t.safeParse(o).success}for(let e of Cy)lg(e,Gb[e]);for(let[e,t]of Object.entries(Iy))lg(e,t);var Oy=Object.freeze(ag),ug=Object.freeze(cg);function Ny(e){switch(e){case"initialize":case"notifications/initialized":return Lt(void 0);case"server/discover":return Lt(gc);default:return}}var _c=60000,qy=[It,mo,Pr,fo],Ay=["inputResponses","requestState"];function Pf(e,t){let r=e.params;if(!Ci(r))return{message:e,lifted:{}};let o=r._meta,n=Ci(o)?qy.filter((l)=>(l in o)):[],s=t==="request"?Ay.filter((l)=>(l in r)):[];if(n.length===0&&s.length===0)return{message:e,lifted:{}};let i={},a={...r};if(n.length>0&&Ci(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];if(i.envelope=l,Object.keys(u).length>0)a._meta=u;else delete a._meta}for(let l of s){if(l==="inputResponses")i.inputResponses=a[l];if(l==="requestState")i.requestState=a[l];delete a[l]}return{message:{...e,params:a},lifted:i}}function Tf(e,t){let r=e.validateResult(t,void 0);if(!r.ok&&r.reason==="not-in-era")return;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let n=e.validateResult(t,o);if(n.ok)return{value:n.value};return{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function gu(e){return()=>e}var My=gu(void 0),jy,bc=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{jy=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ma,this.setNotificationHandler("notifications/cancelled",(t)=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",(t)=>{this._onprogress(t)}),this.setRequestHandler("ping",(t)=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new N(O.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){if(e.params.requestId===void 0)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,s)=>{if(o?.(n,s),Bo(n)||Wo(n))this._onresponse(n);else if(Fr(n))this._onrequest(n,s);else if(Xf(n))this._onnotification(n,s);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new N(O.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Pf(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let i=yf(t.classification);if(i!==o.era){this._onerror(Error(`Era mismatch on inbound notification '${r.method}': classified as ${i} but this instance serves ${o.era}`));return}}if(Yl(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;if(n===void 0&&s===void 0)return;Promise.resolve().then(()=>n===void 0?s(r):n(r,o)).catch((i)=>this._onerror(Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){let{message:r,lifted:o}=Pf(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let s=this._transport,i=(y,v,L)=>{let F={jsonrpc:"2.0",id:r.id,error:{code:y,message:v,...L!==void 0&&{data:L}}};s?.send(F).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(t?.classification!==void 0){let y=yf(t.classification);if(y!==n.era){this._onerror(Error(`Era mismatch on inbound request '${r.method}': classified as ${y} but this instance serves ${n.era}`));let v=t.classification.revision??y;i(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${v}`,{supported:this._supportedProtocolVersions,requested:v});return}}if(Gl(r.method)&&!n.hasRequestMethod(r.method)&&!(vf(r.method)&&this._customSchemaRequestMethods.has(r.method))){i(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){i(W.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){i(W.InvalidParams,l);return}let u=(y,v)=>this._notificationViaCodec(this._resolveOutboundCodec(y.method),y,{...v,relatedRequestId:r.id}),d=(y,v,L)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(y.method),y,v,{...L,relatedRequestId:r.id}),m=new AbortController;this._requestHandlerAbortControllers.set(r.id,m);let f=o.inputResponses===void 0?void 0:Ly(o.inputResponses),S={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:o.requestState===void 0?My:gu(o.requestState),signal:m.signal,send:(y,v,L)=>{let F=this._resolveOutboundCodec(y.method);if(this._assertOutboundRequestInEra(F,y.method),tu(v))return d(y,v,L);let x=Tf(F,y.method);if(x===void 0)throw TypeError(`'${y.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(y,x,v)},notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(S,t);Promise.resolve().then(()=>a(r,b)).then(async(y)=>{if(m.signal.aborted)return;let v;try{v=n.encodeResult(r.method,y,this._outboundServerInfo())}catch(F){this._onerror(Error(`Failed to encode result for ${r.method}: ${F}`)),i(W.InternalError,"Internal error");return}let L={result:v,jsonrpc:"2.0",id:r.id};await s?.send(L)},async(y)=>{if(m.signal.aborted)return;let v=Number.isSafeInteger(y.code)?y.code:W.InternalError,L={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(v),message:y.message??"Internal error",...y.data!==void 0&&{data:y.data}}};await s?.send(L)}).catch((y)=>this._onerror(Error(`Failed to send response: ${y}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(r.id)===m)this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Bo(e))r(e);else r(ee.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(tu(t)){if(!vf(e.method))this._assertOutboundRequestInEra(o,e.method);return this._requestWithSchemaViaCodec(o,e,t,r)}this._assertOutboundRequestInEra(o,e.method);let n=Tf(o,e.method);if(n===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,n,t)}_negotiatedWireCodec(){return Lt(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Ny(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Gl(t)&&!e.hasRequestMethod(t))throw new N(O.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,f)=>{let S=(w)=>{f(w)};if(!this._transport){S(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){S(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof N?w:new N(O.RequestTimeout,String(w))}let b=e.era===gc&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,y=this._requestMessageId++;d=y;let v={...t,jsonrpc:"2.0",id:y};if(o?.onprogress)this._progressHandlers.set(y,o.onprogress),v.params={...t.params,_meta:{...t.params?._meta,progressToken:y}};let L=this._envelopeOutbound(v),F=!1,x=(w)=>{if(F)return;if(this._progressHandlers.delete(y),b===void 0){if(t.method!=="initialize")this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(w)}}),{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch((Z)=>this._onerror(Error(`Failed to send cancellation: ${Z}`)))}else b.abort();f(w instanceof N?w:new N(O.RequestTimeout,String(w)))};this._responseHandlers.set(y,(w)=>{if(o?.signal?.aborted)return;if(F=!0,w instanceof Error)return f(w);let Z;try{Z=e.decodeResult(t.method,w.result)}catch(Y){return f(Y instanceof Error?Y:Error(String(Y)))}if(Z.kind==="invalid")return f(Z.error);if(Z.kind==="input_required"){if(o?.allowInputRequired===!0)return m(Fy(Z));let Y={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(ce,Ee)=>this._requestWithSchemaViaCodec(e,ce===void 0?{method:t.method}:{method:t.method,params:ce},r,Ee)};return m(this._resolveNonCompleteResult(Z,Y))}let X=Z.result;Xl(r,X).then((Y)=>{if(Y.success)m(Y.data);else f(new N(O.InvalidResult,`Invalid result for ${t.method}: ${Y.error}`))},f)}),u=()=>x(o?.signal?.reason),o?.signal?.addEventListener("abort",u,{once:!0});let U=o?.timeout??_c,R=()=>x(new N(O.RequestTimeout,"Request timed out",{timeout:U}));this._setupTimeout(y,U,o?.maxTotalTimeout,R,o?.resetTimeoutOnProgress??!1),this._transport.send(L,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a,requestSignal:b?.signal}).catch((w)=>{this._progressHandlers.delete(y),f(w)})}).finally(()=>{if(u)o?.signal?.removeEventListener("abort",u);if(d!==void 0)this._responseHandlers.delete(d),this._cleanupTimeout(d)})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new N(O.NotConnected,"Not connected");if(Yl(t.method)&&!e.hasNotificationMethod(t.method))throw new N(O.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;this._transport?.send(o,r).catch((n)=>this._onerror(n))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t==="function"){if(!Gl(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,s)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era")a=i.validateInputRequest(e,n);if(!a.ok){if(a.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(a.message)}return Promise.resolve(t(a.value,s))}}else if(r)o=async(n,s)=>{let i=await Xl(t.params,{...n.params});if(!i.success)throw new ee(W.InvalidParams,`Invalid params for ${e}: ${i.error}`);return r(i.data,s)};else throw TypeError("setRequestHandler: handler is required");if(typeof t==="function")this._customSchemaRequestMethods.delete(e);else this._customSchemaRequestMethods.add(e);this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t==="function"){if(!Yl(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,n)=>{let s=n.validateNotification(e,o);if(!s.ok){if(s.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(s.message)}return Promise.resolve(t(s.value))});return}if(!r)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async(o)=>{let n=await Xl(t.params,{...o.params});if(!n.success)throw new ee(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ci(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function dg(e,t){let r={...e};for(let o in t){let n=o,s=t[n];if(s===void 0)continue;let i=r[n];r[n]=Ci(i)&&Ci(s)?{...i,...s}:s}return r}function mc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ly(e){let t={},r=[];if(!mc(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!mc(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function Ef(e){throw new N(O.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function Uy(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:gu(void 0),signal:o,send:()=>Ef("send"),notify:()=>Ef("notify")}}}async function Zy(e,t,r,o,n){if(!mc(o)||typeof o.method!=="string")throw new N(O.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let s=o.method;if(!t.hasInputRequestMethod(s))throw new N(O.InvalidResult,`Invalid input request '${r}': '${s}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:s});let i=e.getRequestHandler(s);if(i===void 0)throw new N(O.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${s}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:s});let a=mc(o.params)?o.params:void 0;return await i({jsonrpc:"2.0",id:r,method:s,...a!==void 0&&{params:a}},e.buildContext(Uy(r,s,a,n,e.sessionId)))}function Dy(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function pg(e,t,r,o){let{codec:n,request:s,options:i,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,f)=>Zy(e,n,d,m,f),retry:(d,m)=>o.retry(d,Dy(i,m))};return $y({config:t,method:s.method,originalParams:s.params,firstPayload:l,flowStartedAt:a,signal:i?.signal,requestOptions:{...i?.timeout!==void 0&&{timeout:i.timeout},...i?.maxTotalTimeout!==void 0&&{maxTotalTimeout:i.maxTotalTimeout},...i?.onprogress!==void 0&&{onprogress:i.onprogress}},hooks:u})}function Fy(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}/*!
66
65
  * content-type
67
66
  * Copyright(c) 2015 Douglas Christopher Wilson
68
67
  * MIT Licensed
69
- */var wE=M2((H)=>{var W=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,Q=/\\([\u000b\u0020-\u00ff])/g,X=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;H.parse=Y;function Y(B){if(!B)throw TypeError("argument string is required");var G=typeof B==="object"?J(B):B;if(typeof G!=="string")throw TypeError("argument string is required to be a string");var D=G.indexOf(";"),M=D!==-1?G.slice(0,D).trim():G.trim();if(!X.test(M))throw TypeError("invalid media type");var _=new N(M.toLowerCase());if(D!==-1){var F,A,w;W.lastIndex=D;while(A=W.exec(G)){if(A.index!==D)throw TypeError("invalid parameter format");if(D+=A[0].length,F=A[1].toLowerCase(),w=A[2],w.charCodeAt(0)===34){if(w=w.slice(1,-1),w.indexOf("\\")!==-1)w=w.replace(Q,"$1")}_.parameters[F]=w}if(D!==G.length)throw TypeError("invalid parameter format")}return _}function J(B){var G;if(typeof B.getHeader==="function")G=B.getHeader("content-type");else if(typeof B.headers==="object")G=B.headers&&B.headers["content-type"];if(typeof G!=="string")throw TypeError("content-type header is missing from object");return G}function N(B){this.parameters=Object.create(null),this.type=B}}),zE=_2(wE(),1);function ED(H){if(!H)return;try{return zE.parse(H).type}catch{let W=(H.split(";",1)[0]??"").trim().toLowerCase();if(W===""||H.slice(W.length).includes(","))return;return W}}function CG(H){if(!H)return{};if(H instanceof Headers)return Object.fromEntries(H.entries());if(Array.isArray(H))return Object.fromEntries(H);return{...H}}function AD(H=fetch,W){if(!W)return H;return async(Q,X)=>{return H(Q,{...W,...X,headers:X?.headers?{...CG(W.headers),...CG(X.headers)}:W.headers})}}var ZE=new Set([301,302,303,307,308]),PE=5;function bE(H,W){if(H.protocol===W.protocol&&H.host===W.host)return!0;return H.protocol==="http:"&&W.protocol==="https:"&&H.hostname===W.hostname&&!H.port&&!W.port}function OD(H,W){let Q=ZE.has(W.status)?W.headers?.get("location"):void 0;if(!Q)return;try{return new URL(Q,H)}catch{return}}var VD=new WeakSet;function UD(H){let W=(Q,X)=>H(Q,X);return VD.add(W),W}function tY(H){if(VD.has(H))return H;return async(W,Q)=>{if(Q?.redirect==="error"||Q?.redirect==="manual")return H(W,Q);let X=(Q?.method??"GET").toUpperCase(),Y=W;for(let J=0;;J++){let N=await H(Y,{...Q,redirect:"manual"}),B=OD(Y,N);if(!B||J===PE)return N;let G=new URL(Y),D=X==="GET"||N.status===307||N.status===308,M=!(B.username||B.password)||B.username===G.username&&B.password===G.password;if(!D||!M||!bE(G,B))return N;await N.text?.().catch(()=>{}),Y=B}}}function wD(H,W){if(W.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let Q=OD(W.url||H,W);if(!Q)return;if(Q.username=Q.password=Q.search=Q.hash="",Q.protocol==="http:"&&new URL(W.url||H).protocol==="https:")return Q.protocol="https:",`Redirect from https to plain http not followed; try ${Q.href} as the endpoint`;return`Redirect to ${Q.href} not followed; use that URL as the endpoint if it is the intended server`}function sY(H,W){let Q=typeof H;if(Q!==typeof W)return!1;if(Array.isArray(H)){if(!Array.isArray(W))return!1;let X=H.length;if(X!==W.length)return!1;for(let Y=0;Y<X;Y++)if(!sY(H[Y],W[Y]))return!1;return!0}if(Q==="object"){if(!H||!W)return H===W;let X=Object.keys(H),Y=Object.keys(W);if(X.length!==Y.length)return!1;for(let J of X)if(!sY(H[J],W[J]))return!1;return!0}return H===W}function U0(H){return encodeURI(IE(H))}function IE(H){return H.replace(/~/g,"~0").replace(/\//g,"~1")}var LE={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},jE={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},TE={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},$E=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function z8(H,W=Object.create(null),Q=$E,X=""){if(H&&typeof H==="object"&&!Array.isArray(H)){let J=H.$id||H.id;if(J){let N=new URL(J,Q.href);if(N.hash.length>1)W[N.href]=H;else if(N.hash="",X==="")Q=N;else z8(H,W,Q)}}else if(H!==!0&&H!==!1)return W;let Y=Q.href+(X?"#"+X:"");if(W[Y]!==void 0)throw Error(`Duplicate schema URI "${Y}".`);if(W[Y]=H,H===!0||H===!1)return W;if(H.__absolute_uri__===void 0)Object.defineProperty(H,"__absolute_uri__",{enumerable:!1,value:Y});if(H.$ref&&H.__absolute_ref__===void 0){let J=new URL(H.$ref,Q.href);J.hash=J.hash,Object.defineProperty(H,"__absolute_ref__",{enumerable:!1,value:J.href})}if(H.$recursiveRef&&H.__absolute_recursive_ref__===void 0){let J=new URL(H.$recursiveRef,Q.href);J.hash=J.hash,Object.defineProperty(H,"__absolute_recursive_ref__",{enumerable:!1,value:J.href})}if(H.$anchor){let J=new URL("#"+H.$anchor,Q.href);W[J.href]=H}for(let J in H){if(TE[J])continue;let N=`${X}/${U0(J)}`,B=H[J];if(Array.isArray(B)){if(LE[J]){let G=B.length;for(let D=0;D<G;D++)z8(B[D],W,Q,`${N}/${D}`)}}else if(jE[J])for(let G in B)z8(B[G],W,Q,`${N}/${U0(G)}`);else z8(B,W,Q,N)}return W}var RE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,CE=[0,31,28,31,30,31,30,31,31,30,31,30,31],SE=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,kE=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,gE=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,xE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,vE=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,yE=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,hE=/^(?:\/(?:[^~/]|~0|~1)*)*$/,fE=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,uE=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,lE=(H)=>{if(H[0]==='"')return!1;let[W,Q,...X]=H.split("@");if(!W||!Q||X.length!==0||W.length>64||Q.length>253)return!1;if(W[0]==="."||W.endsWith(".")||W.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(Q)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(W))return!1;return Q.split(".").every((Y)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(Y))},mE=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,cE=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,pE=(H)=>H.length>1&&H.length<80&&(/^P\d+([.,]\d+)?W$/.test(H)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(H)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(H));function u0(H){return H.test.bind(H)}var zD={date:ZD,time:PD.bind(void 0,!1),"date-time":oE,duration:pE,uri:tE,"uri-reference":u0(gE),"uri-template":u0(xE),url:u0(vE),email:lE,hostname:u0(kE),ipv4:u0(mE),ipv6:u0(cE),regex:aE,uuid:u0(yE),"json-pointer":u0(hE),"json-pointer-uri-fragment":u0(fE),"relative-json-pointer":u0(uE)};function dE(H){return H%4===0&&(H%100!==0||H%400===0)}function ZD(H){let W=H.match(RE);if(!W)return!1;let Q=+W[1],X=+W[2],Y=+W[3];return X>=1&&X<=12&&Y>=1&&Y<=(X==2&&dE(Q)?29:CE[X])}function PD(H,W){let Q=W.match(SE);if(!Q)return!1;let X=+Q[1],Y=+Q[2],J=+Q[3],N=!!Q[5];return(X<=23&&Y<=59&&J<=59||X==23&&Y==59&&J==60)&&(!H||N)}var iE=/t|\s/i;function oE(H){let W=H.split(iE);return W.length==2&&ZD(W[0])&&PD(!0,W[1])}var nE=/\/|:/,rE=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function tE(H){return nE.test(H)&&rE.test(H)}var sE=/[^\\]\\Z/;function aE(H){if(sE.test(H))return!1;try{return new RegExp(H,"u"),!0}catch(W){return!1}}function eE(H){let W=0,Q=H.length,X=0,Y;while(X<Q)if(W++,Y=H.charCodeAt(X++),Y>=55296&&Y<=56319&&X<Q){if(Y=H.charCodeAt(X),(Y&64512)==56320)X++}return W}function EH(H,W,Q="2019-09",X=z8(W),Y=!0,J=null,N="#",B="#",G=Object.create(null)){if(W===!0)return{valid:!0,errors:[]};if(W===!1)return{valid:!1,errors:[{instanceLocation:N,keyword:"false",keywordLocation:N,error:"False boolean schema."}]};let D=typeof H,M;switch(D){case"boolean":case"number":case"string":M=D;break;case"object":if(H===null)M="null";else if(Array.isArray(H))M="array";else M="object";break;default:throw Error(`Instances of "${D}" type are not supported.`)}let{$ref:_,$recursiveRef:F,$recursiveAnchor:A,type:w,const:z,enum:Z,required:u,not:p,anyOf:j,allOf:m,oneOf:I,if:P,then:c,else:XH,format:WH,properties:MH,patternProperties:kH,additionalProperties:NH,unevaluatedProperties:DH,minProperties:IH,maxProperties:gH,propertyNames:z0,dependentRequired:cH,dependentSchemas:J0,dependencies:Z0,prefixItems:tH,items:xH,additionalItems:d0,unevaluatedItems:i0,contains:P0,minContains:TH,maxContains:vH,minItems:yH,maxItems:_0,uniqueItems:vW,minimum:sH,maximum:aH,exclusiveMinimum:pH,exclusiveMaximum:N0,multipleOf:B0,minLength:b0,maxLength:I0,pattern:DW,__absolute_ref__:L0,__absolute_recursive_ref__:yW}=W,k=[];if(A===!0&&J===null)J=W;if(F==="#"){let d=J===null?X[yW]:J,y=`${B}/$recursiveRef`,e=EH(H,J===null?W:J,Q,X,Y,d,N,y,G);if(!e.valid)k.push({instanceLocation:N,keyword:"$recursiveRef",keywordLocation:y,error:"A subschema had errors."},...e.errors)}if(_!==void 0){let d=X[L0||_];if(d===void 0){let g=`Unresolved $ref "${_}".`;if(L0&&L0!==_)g+=` Absolute URI "${L0}".`;throw g+=`
68
+ */var Hy=rd((e)=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(a){if(!a)throw TypeError("argument string is required");var l=typeof a==="object"?s(a):a;if(typeof l!=="string")throw TypeError("argument string is required to be a string");var u=l.indexOf(";"),d=u!==-1?l.slice(0,u).trim():l.trim();if(!o.test(d))throw TypeError("invalid media type");var m=new i(d.toLowerCase());if(u!==-1){var f,S,b;t.lastIndex=u;while(S=t.exec(l)){if(S.index!==u)throw TypeError("invalid parameter format");if(u+=S[0].length,f=S[1].toLowerCase(),b=S[2],b.charCodeAt(0)===34){if(b=b.slice(1,-1),b.indexOf("\\")!==-1)b=b.replace(r,"$1")}m.parameters[f]=b}if(u!==l.length)throw TypeError("invalid parameter format")}return m}function s(a){var l;if(typeof a.getHeader==="function")l=a.getHeader("content-type");else if(typeof a.headers==="object")l=a.headers&&a.headers["content-type"];if(typeof l!=="string")throw TypeError("content-type header is missing from object");return l}function i(a){this.parameters=Object.create(null),this.type=a}}),Vy=nd(Hy(),1);function hg(e){if(!e)return;try{return Vy.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function kf(e){if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e))return Object.fromEntries(e);return{...e}}function mg(e=fetch,t){if(!t)return e;return async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...kf(t.headers),...kf(o.headers)}:t.headers})}var Jy=new Set([301,302,303,307,308]),By=5;function Wy(e,t){if(e.protocol===t.protocol&&e.host===t.host)return!0;return e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function fg(e,t){let r=Jy.has(t.status)?t.headers?.get("location"):void 0;if(!r)return;try{return new URL(r,e)}catch{return}}var gg=new WeakSet;function Sg(e){let t=(r,o)=>e(r,o);return gg.add(t),t}function Ni(e){if(gg.has(e))return e;return async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),n=t;for(let s=0;;s++){let i=await e(n,{...r,redirect:"manual"}),a=fg(n,i);if(!a||s===By)return i;let l=new URL(n),u=o==="GET"||i.status===307||i.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!Wy(l,a))return i;await i.text?.().catch(()=>{}),n=a}}}function _g(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=fg(t.url||e,t);if(!r)return;if(r.username=r.password=r.search=r.hash="",r.protocol==="http:"&&new URL(t.url||e).protocol==="https:")return r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`;return`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}function qi(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=e.length;if(o!==t.length)return!1;for(let n=0;n<o;n++)if(!qi(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;for(let s of o)if(!qi(e[s],t[s]))return!1;return!0}return e===t}function it(e){return encodeURI(Ky(e))}function Ky(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Gy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Yy={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Xy={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Qy=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Hr(e,t=Object.create(null),r=Qy,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let i=new URL(s,r.href);if(i.hash.length>1)t[i.href]=e;else if(i.hash="",o==="")r=i;else Hr(e,t,r)}}else if(e!==!0&&e!==!1)return t;let n=r.href+(o?"#"+o:"");if(t[n]!==void 0)throw Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n});if(e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(Xy[s])continue;let i=`${o}/${it(s)}`,a=e[s];if(Array.isArray(a)){if(Gy[s]){let l=a.length;for(let u=0;u<l;u++)Hr(a[u],t,r,`${i}/${u}`)}}else if(Yy[s])for(let l in a)Hr(a[l],t,r,`${i}/${it(l)}`);else Hr(a,t,r,i)}return t}var ev=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,tv=[0,31,28,31,30,31,30,31,31,30,31,30,31],rv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,ov=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,nv=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,sv=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,iv=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,av=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,cv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,lv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,uv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,dv=(e)=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");if(!t||!r||o.length!==0||t.length>64||r.length>253)return!1;if(t[0]==="."||t.endsWith(".")||t.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))return!1;return r.split(".").every((n)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},pv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,hv=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,mv=(e)=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function zt(e){return e.test.bind(e)}var bg={date:yg,time:vg.bind(void 0,!1),"date-time":Sv,duration:mv,uri:yv,"uri-reference":zt(nv),"uri-template":zt(sv),url:zt(iv),email:dv,hostname:zt(ov),ipv4:zt(pv),ipv6:zt(hv),regex:zv,uuid:zt(av),"json-pointer":zt(cv),"json-pointer-uri-fragment":zt(lv),"relative-json-pointer":zt(uv)};function fv(e){return e%4===0&&(e%100!==0||e%400===0)}function yg(e){let t=e.match(ev);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&fv(r)?29:tv[o])}function vg(e,t){let r=t.match(rv);if(!r)return!1;let o=+r[1],n=+r[2],s=+r[3],i=!!r[5];return(o<=23&&n<=59&&s<=59||o==23&&n==59&&s==60)&&(!e||i)}var gv=/t|\s/i;function Sv(e){let t=e.split(gv);return t.length==2&&yg(t[0])&&vg(!0,t[1])}var _v=/\/|:/,bv=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function yv(e){return _v.test(e)&&bv.test(e)}var vv=/[^\\]\\Z/;function zv(e){if(vv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function wv(e){let t=0,r=e.length,o=0,n;while(o<r)if(t++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<r){if(n=e.charCodeAt(o),(n&64512)==56320)o++}return t}function pe(e,t,r="2019-09",o=Hr(t),n=!0,s=null,i="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":if(e===null)d="null";else if(Array.isArray(e))d="array";else d="object";break;default:throw Error(`Instances of "${u}" type are not supported.`)}let{$ref:m,$recursiveRef:f,$recursiveAnchor:S,type:b,const:y,enum:v,required:L,not:F,anyOf:x,allOf:U,oneOf:R,if:w,then:Z,else:X,format:Y,properties:ce,patternProperties:Ee,additionalProperties:te,unevaluatedProperties:se,minProperties:ve,maxProperties:ke,propertyNames:ct,dependentRequired:qe,dependentSchemas:We,dependencies:lt,prefixItems:Ze,items:$e,additionalItems:Tt,unevaluatedItems:Et,contains:ut,minContains:Re,maxContains:Ce,minItems:Ie,maxItems:et,uniqueItems:lr,minimum:De,maximum:Fe,exclusiveMinimum:Ae,exclusiveMaximum:Ke,multipleOf:Ge,minLength:dt,maxLength:pt,pattern:Ht,__absolute_ref__:ht,__absolute_recursive_ref__:ur}=t,C=[];if(S===!0&&s===null)s=t;if(f==="#"){let H=s===null?o[ur]:s,q=`${a}/$recursiveRef`,G=pe(e,s===null?t:s,r,o,n,H,i,q,l);if(!G.valid)C.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:q,error:"A subschema had errors."},...G.errors)}if(m!==void 0){let H=o[ht||m];if(H===void 0){let I=`Unresolved $ref "${m}".`;if(ht&&ht!==m)I+=` Absolute URI "${ht}".`;throw I+=`
70
69
  Known schemas:
71
- - ${Object.keys(X).join(`
72
- - `)}`,Error(g)}let y=`${B}/$ref`,e=EH(H,d,Q,X,Y,J,N,y,G);if(!e.valid)k.push({instanceLocation:N,keyword:"$ref",keywordLocation:y,error:"A subschema had errors."},...e.errors);if(Q==="4"||Q==="7")return{valid:k.length===0,errors:k}}if(Array.isArray(w)){let d=w.length,y=!1;for(let e=0;e<d;e++)if(M===w[e]||w[e]==="integer"&&M==="number"&&H%1===0&&H===H){y=!0;break}if(!y)k.push({instanceLocation:N,keyword:"type",keywordLocation:`${B}/type`,error:`Instance type "${M}" is invalid. Expected "${w.join('", "')}".`})}else if(w==="integer"){if(M!=="number"||H%1||H!==H)k.push({instanceLocation:N,keyword:"type",keywordLocation:`${B}/type`,error:`Instance type "${M}" is invalid. Expected "${w}".`})}else if(w!==void 0&&M!==w)k.push({instanceLocation:N,keyword:"type",keywordLocation:`${B}/type`,error:`Instance type "${M}" is invalid. Expected "${w}".`});if(z!==void 0){if(M==="object"||M==="array"){if(!sY(H,z))k.push({instanceLocation:N,keyword:"const",keywordLocation:`${B}/const`,error:`Instance does not match ${JSON.stringify(z)}.`})}else if(H!==z)k.push({instanceLocation:N,keyword:"const",keywordLocation:`${B}/const`,error:`Instance does not match ${JSON.stringify(z)}.`})}if(Z!==void 0){if(M==="object"||M==="array"){if(!Z.some((d)=>sY(H,d)))k.push({instanceLocation:N,keyword:"enum",keywordLocation:`${B}/enum`,error:`Instance does not match any of ${JSON.stringify(Z)}.`})}else if(!Z.some((d)=>H===d))k.push({instanceLocation:N,keyword:"enum",keywordLocation:`${B}/enum`,error:`Instance does not match any of ${JSON.stringify(Z)}.`})}if(p!==void 0){let d=`${B}/not`;if(EH(H,p,Q,X,Y,J,N,d).valid)k.push({instanceLocation:N,keyword:"not",keywordLocation:d,error:'Instance matched "not" schema.'})}let j0=[];if(j!==void 0){let d=`${B}/anyOf`,y=k.length,e=!1;for(let g=0;g<j.length;g++){let $=j[g],n=Object.create(G),o=EH(H,$,Q,X,Y,A===!0?J:null,N,`${d}/${g}`,n);if(k.push(...o.errors),e=e||o.valid,o.valid)j0.push(n)}if(e)k.length=y;else k.splice(y,0,{instanceLocation:N,keyword:"anyOf",keywordLocation:d,error:"Instance does not match any subschemas."})}if(m!==void 0){let d=`${B}/allOf`,y=k.length,e=!0;for(let g=0;g<m.length;g++){let $=m[g],n=Object.create(G),o=EH(H,$,Q,X,Y,A===!0?J:null,N,`${d}/${g}`,n);if(k.push(...o.errors),e=e&&o.valid,o.valid)j0.push(n)}if(e)k.length=y;else k.splice(y,0,{instanceLocation:N,keyword:"allOf",keywordLocation:d,error:"Instance does not match every subschema."})}if(I!==void 0){let d=`${B}/oneOf`,y=k.length,e=I.filter((g,$)=>{let n=Object.create(G),o=EH(H,g,Q,X,Y,A===!0?J:null,N,`${d}/${$}`,n);if(k.push(...o.errors),o.valid)j0.push(n);return o.valid}).length;if(e===1)k.length=y;else k.splice(y,0,{instanceLocation:N,keyword:"oneOf",keywordLocation:d,error:`Instance does not match exactly one subschema (${e} matches).`})}if(M==="object"||M==="array")Object.assign(G,...j0);if(P!==void 0){let d=`${B}/if`;if(EH(H,P,Q,X,Y,J,N,d,G).valid){if(c!==void 0){let y=EH(H,c,Q,X,Y,J,N,`${B}/then`,G);if(!y.valid)k.push({instanceLocation:N,keyword:"if",keywordLocation:d,error:'Instance does not match "then" schema.'},...y.errors)}}else if(XH!==void 0){let y=EH(H,XH,Q,X,Y,J,N,`${B}/else`,G);if(!y.valid)k.push({instanceLocation:N,keyword:"if",keywordLocation:d,error:'Instance does not match "else" schema.'},...y.errors)}}if(M==="object"){if(u!==void 0){for(let g of u)if(!(g in H))k.push({instanceLocation:N,keyword:"required",keywordLocation:`${B}/required`,error:`Instance does not have required property "${g}".`})}let d=Object.keys(H);if(IH!==void 0&&d.length<IH)k.push({instanceLocation:N,keyword:"minProperties",keywordLocation:`${B}/minProperties`,error:`Instance does not have at least ${IH} properties.`});if(gH!==void 0&&d.length>gH)k.push({instanceLocation:N,keyword:"maxProperties",keywordLocation:`${B}/maxProperties`,error:`Instance does not have at least ${gH} properties.`});if(z0!==void 0){let g=`${B}/propertyNames`;for(let $ in H){let n=`${N}/${U0($)}`,o=EH($,z0,Q,X,Y,J,n,g);if(!o.valid)k.push({instanceLocation:N,keyword:"propertyNames",keywordLocation:g,error:`Property name "${$}" does not match schema.`},...o.errors)}}if(cH!==void 0){let g=`${B}/dependantRequired`;for(let $ in cH)if($ in H){let n=cH[$];for(let o of n)if(!(o in H))k.push({instanceLocation:N,keyword:"dependentRequired",keywordLocation:g,error:`Instance has "${$}" but does not have "${o}".`})}}if(J0!==void 0)for(let g in J0){let $=`${B}/dependentSchemas`;if(g in H){let n=EH(H,J0[g],Q,X,Y,J,N,`${$}/${U0(g)}`,G);if(!n.valid)k.push({instanceLocation:N,keyword:"dependentSchemas",keywordLocation:$,error:`Instance has "${g}" but does not match dependant schema.`},...n.errors)}}if(Z0!==void 0){let g=`${B}/dependencies`;for(let $ in Z0)if($ in H){let n=Z0[$];if(Array.isArray(n)){for(let o of n)if(!(o in H))k.push({instanceLocation:N,keyword:"dependencies",keywordLocation:g,error:`Instance has "${$}" but does not have "${o}".`})}else{let o=EH(H,n,Q,X,Y,J,N,`${g}/${U0($)}`);if(!o.valid)k.push({instanceLocation:N,keyword:"dependencies",keywordLocation:g,error:`Instance has "${$}" but does not match dependant schema.`},...o.errors)}}}let y=Object.create(null),e=!1;if(MH!==void 0){let g=`${B}/properties`;for(let $ in MH){if(!($ in H))continue;let n=`${N}/${U0($)}`,o=EH(H[$],MH[$],Q,X,Y,J,n,`${g}/${U0($)}`);if(o.valid)G[$]=y[$]=!0;else if(e=Y,k.push({instanceLocation:N,keyword:"properties",keywordLocation:g,error:`Property "${$}" does not match schema.`},...o.errors),e)break}}if(!e&&kH!==void 0){let g=`${B}/patternProperties`;for(let $ in kH){let n=new RegExp($,"u"),o=kH[$];for(let wH in H){if(!n.test(wH))continue;let hW=`${N}/${U0(wH)}`,T0=EH(H[wH],o,Q,X,Y,J,hW,`${g}/${U0($)}`);if(T0.valid)G[wH]=y[wH]=!0;else e=Y,k.push({instanceLocation:N,keyword:"patternProperties",keywordLocation:g,error:`Property "${wH}" matches pattern "${$}" but does not match associated schema.`},...T0.errors)}}}if(!e&&NH!==void 0){let g=`${B}/additionalProperties`;for(let $ in H){if(y[$])continue;let n=`${N}/${U0($)}`,o=EH(H[$],NH,Q,X,Y,J,n,g);if(o.valid)G[$]=!0;else e=Y,k.push({instanceLocation:N,keyword:"additionalProperties",keywordLocation:g,error:`Property "${$}" does not match additional properties schema.`},...o.errors)}}else if(!e&&DH!==void 0){let g=`${B}/unevaluatedProperties`;for(let $ in H)if(!G[$]){let n=`${N}/${U0($)}`,o=EH(H[$],DH,Q,X,Y,J,n,g);if(o.valid)G[$]=!0;else k.push({instanceLocation:N,keyword:"unevaluatedProperties",keywordLocation:g,error:`Property "${$}" does not match unevaluated properties schema.`},...o.errors)}}}else if(M==="array"){if(_0!==void 0&&H.length>_0)k.push({instanceLocation:N,keyword:"maxItems",keywordLocation:`${B}/maxItems`,error:`Array has too many items (${H.length} > ${_0}).`});if(yH!==void 0&&H.length<yH)k.push({instanceLocation:N,keyword:"minItems",keywordLocation:`${B}/minItems`,error:`Array has too few items (${H.length} < ${yH}).`});let d=H.length,y=0,e=!1;if(tH!==void 0){let g=`${B}/prefixItems`,$=Math.min(tH.length,d);for(;y<$;y++){let n=EH(H[y],tH[y],Q,X,Y,J,`${N}/${y}`,`${g}/${y}`);if(G[y]=!0,!n.valid){if(e=Y,k.push({instanceLocation:N,keyword:"prefixItems",keywordLocation:g,error:"Items did not match schema."},...n.errors),e)break}}}if(xH!==void 0){let g=`${B}/items`;if(Array.isArray(xH)){let $=Math.min(xH.length,d);for(;y<$;y++){let n=EH(H[y],xH[y],Q,X,Y,J,`${N}/${y}`,`${g}/${y}`);if(G[y]=!0,!n.valid){if(e=Y,k.push({instanceLocation:N,keyword:"items",keywordLocation:g,error:"Items did not match schema."},...n.errors),e)break}}}else for(;y<d;y++){let $=EH(H[y],xH,Q,X,Y,J,`${N}/${y}`,g);if(G[y]=!0,!$.valid){if(e=Y,k.push({instanceLocation:N,keyword:"items",keywordLocation:g,error:"Items did not match schema."},...$.errors),e)break}}if(!e&&d0!==void 0){let $=`${B}/additionalItems`;for(;y<d;y++){let n=EH(H[y],d0,Q,X,Y,J,`${N}/${y}`,$);if(G[y]=!0,!n.valid)e=Y,k.push({instanceLocation:N,keyword:"additionalItems",keywordLocation:$,error:"Items did not match additional items schema."},...n.errors)}}}if(P0!==void 0)if(d===0&&TH===void 0)k.push({instanceLocation:N,keyword:"contains",keywordLocation:`${B}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(TH!==void 0&&d<TH)k.push({instanceLocation:N,keyword:"minContains",keywordLocation:`${B}/minContains`,error:`Array has less items (${d}) than minContains (${TH}).`});else{let g=`${B}/contains`,$=k.length,n=0;for(let o=0;o<d;o++){let wH=EH(H[o],P0,Q,X,Y,J,`${N}/${o}`,g);if(wH.valid)G[o]=!0,n++;else k.push(...wH.errors)}if(n>=(TH||0))k.length=$;if(TH===void 0&&vH===void 0&&n===0)k.splice($,0,{instanceLocation:N,keyword:"contains",keywordLocation:g,error:"Array does not contain item matching schema."});else if(TH!==void 0&&n<TH)k.push({instanceLocation:N,keyword:"minContains",keywordLocation:`${B}/minContains`,error:`Array must contain at least ${TH} items matching schema. Only ${n} items were found.`});else if(vH!==void 0&&n>vH)k.push({instanceLocation:N,keyword:"maxContains",keywordLocation:`${B}/maxContains`,error:`Array may contain at most ${vH} items matching schema. ${n} items were found.`})}if(!e&&i0!==void 0){let g=`${B}/unevaluatedItems`;for(;y<d;y++){if(G[y])continue;let $=EH(H[y],i0,Q,X,Y,J,`${N}/${y}`,g);if(G[y]=!0,!$.valid)k.push({instanceLocation:N,keyword:"unevaluatedItems",keywordLocation:g,error:"Items did not match unevaluated items schema."},...$.errors)}}if(vW)for(let g=0;g<d;g++){let $=H[g],n=typeof $==="object"&&$!==null;for(let o=0;o<d;o++){if(g===o)continue;let wH=H[o];if($===wH||n&&typeof wH==="object"&&wH!==null&&sY($,wH))k.push({instanceLocation:N,keyword:"uniqueItems",keywordLocation:`${B}/uniqueItems`,error:`Duplicate items at indexes ${g} and ${o}.`}),g=Number.MAX_SAFE_INTEGER,o=Number.MAX_SAFE_INTEGER}}}else if(M==="number"){if(Q==="4"){if(sH!==void 0&&(pH===!0&&H<=sH||H<sH))k.push({instanceLocation:N,keyword:"minimum",keywordLocation:`${B}/minimum`,error:`${H} is less than ${pH?"or equal to ":""} ${sH}.`});if(aH!==void 0&&(N0===!0&&H>=aH||H>aH))k.push({instanceLocation:N,keyword:"maximum",keywordLocation:`${B}/maximum`,error:`${H} is greater than ${N0?"or equal to ":""} ${aH}.`})}else{if(sH!==void 0&&H<sH)k.push({instanceLocation:N,keyword:"minimum",keywordLocation:`${B}/minimum`,error:`${H} is less than ${sH}.`});if(aH!==void 0&&H>aH)k.push({instanceLocation:N,keyword:"maximum",keywordLocation:`${B}/maximum`,error:`${H} is greater than ${aH}.`});if(pH!==void 0&&H<=pH)k.push({instanceLocation:N,keyword:"exclusiveMinimum",keywordLocation:`${B}/exclusiveMinimum`,error:`${H} is less than ${pH}.`});if(N0!==void 0&&H>=N0)k.push({instanceLocation:N,keyword:"exclusiveMaximum",keywordLocation:`${B}/exclusiveMaximum`,error:`${H} is greater than or equal to ${N0}.`})}if(B0!==void 0){let d=H%B0;if(Math.abs(0-d)>=0.00000011920929&&Math.abs(B0-d)>=0.00000011920929)k.push({instanceLocation:N,keyword:"multipleOf",keywordLocation:`${B}/multipleOf`,error:`${H} is not a multiple of ${B0}.`})}}else if(M==="string"){let d=b0===void 0&&I0===void 0?0:eE(H);if(b0!==void 0&&d<b0)k.push({instanceLocation:N,keyword:"minLength",keywordLocation:`${B}/minLength`,error:`String is too short (${d} < ${b0}).`});if(I0!==void 0&&d>I0)k.push({instanceLocation:N,keyword:"maxLength",keywordLocation:`${B}/maxLength`,error:`String is too long (${d} > ${I0}).`});if(DW!==void 0&&!new RegExp(DW,"u").test(H))k.push({instanceLocation:N,keyword:"pattern",keywordLocation:`${B}/pattern`,error:"String does not match pattern."});if(WH!==void 0&&zD[WH]&&!zD[WH](H))k.push({instanceLocation:N,keyword:"format",keywordLocation:`${B}/format`,error:`String does not match format "${WH}".`})}return{valid:k.length===0,errors:k}}var HA=class{schema;draft;shortCircuit;lookup;constructor(H,W="2019-09",Q=!0){this.schema=H,this.draft=W,this.shortCircuit=Q,this.lookup=z8(H)}validate(H){return EH(H,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(H,W){if(W)H={...H,$id:W};z8(H,this.lookup)}},LB=class{shortcircuit;draft;constructor(H){this.shortcircuit=H?.shortcircuit??!0,this.draft=H?.draft}_draftFor(H){let W=A2(H,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return W==="draft-7"?"7":W}getValidator(H){let W=new HA(H,this.draft??this._draftFor(H),this.shortcircuit);return(Q)=>{let X=W.validate(Q);return X.valid?{valid:!0,data:Q,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:X.errors.map((Y)=>`${Y.instanceLocation}: ${Y.error}`).join("; ")}}}};var bD=!0;var jB;jB=globalThis.crypto;async function WA(H){return(await jB).getRandomValues(new Uint8Array(H))}async function QA(H){let Q=Math.pow(2,8)-Math.pow(2,8)%66,X="";while(X.length<H){let Y=await WA(H-X.length);for(let J of Y)if(J<Q)X+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[J%66]}return X}async function XA(H){return await QA(H)}async function YA(H){let W=await(await jB).subtle.digest("SHA-256",new TextEncoder().encode(H));return btoa(String.fromCharCode(...new Uint8Array(W))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function TB(H){if(!H)H=43;if(H<43||H>128)throw`Expected a length between 43 and 128. Received ${H}.`;let W=await XA(H),Q=await YA(W);return{code_verifier:W,code_challenge:Q}}class c9 extends Error{constructor(H,W){super(H),this.name="ParseError",this.type=W.type,this.field=W.field,this.value=W.value,this.line=W.line}}var ID=10,JA=13,Z8=32;function $B(H){}function TD(H){if(typeof H=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:W=$B,onError:Q=$B,onRetry:X=$B,onComment:Y,maxBufferSize:J}=H,N=[],B=0,G=!0,D,M="",_=0,F,A=!1;function w(I){if(A)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(G&&(G=!1,I.charCodeAt(0)===239&&I.charCodeAt(1)===187&&I.charCodeAt(2)===191&&(I=I.slice(3))),N.length===0){let XH=Z(I);XH!==""&&(N.push(XH),B=XH.length),z();return}if(I.indexOf(`
73
- `)===-1&&I.indexOf("\r")===-1){N.push(I),B+=I.length,z();return}N.push(I);let P=N.join("");N.length=0,B=0;let c=Z(P);c!==""&&(N.push(c),B=c.length),z()}function z(){J!==void 0&&(B+M.length<=J||(A=!0,N.length=0,B=0,D=void 0,M="",_=0,F=void 0,Q(new c9(`Buffered data exceeded max buffer size of ${J} characters`,{type:"max-buffer-size-exceeded"}))))}function Z(I){let P=0;if(I.indexOf("\r")===-1){let c=I.indexOf(`
74
- `,P);for(;c!==-1;){if(P===c){_>0&&W({id:D,event:F,data:M}),D=void 0,M="",_=0,F=void 0,P=c+1,c=I.indexOf(`
75
- `,P);continue}let XH=I.charCodeAt(P);if(LD(I,P,XH)){let WH=I.charCodeAt(P+5)===Z8?P+6:P+5,MH=I.slice(WH,c);if(_===0&&I.charCodeAt(c+1)===ID){W({id:D,event:F,data:MH}),D=void 0,M="",F=void 0,P=c+2,c=I.indexOf(`
76
- `,P);continue}M=_===0?MH:`${M}
77
- ${MH}`,_++}else jD(I,P,XH)?F=I.slice(I.charCodeAt(P+6)===Z8?P+7:P+6,c)||void 0:u(I,P,c);P=c+1,c=I.indexOf(`
78
- `,P)}return I.slice(P)}for(;P<I.length;){let c=I.indexOf("\r",P),XH=I.indexOf(`
79
- `,P),WH=-1;if(c!==-1&&XH!==-1?WH=c<XH?c:XH:c!==-1?c===I.length-1?WH=-1:WH=c:XH!==-1&&(WH=XH),WH===-1)break;u(I,P,WH),P=WH+1,I.charCodeAt(P-1)===JA&&I.charCodeAt(P)===ID&&P++}return I.slice(P)}function u(I,P,c){if(P===c){j();return}let XH=I.charCodeAt(P);if(LD(I,P,XH)){let IH=I.charCodeAt(P+5)===Z8?P+6:P+5,gH=I.slice(IH,c);M=_===0?gH:`${M}
80
- ${gH}`,_++;return}if(jD(I,P,XH)){F=I.slice(I.charCodeAt(P+6)===Z8?P+7:P+6,c)||void 0;return}if(XH===105&&I.charCodeAt(P+1)===100&&I.charCodeAt(P+2)===58){let IH=I.slice(I.charCodeAt(P+3)===Z8?P+4:P+3,c);IH.includes("\x00")||(D=IH);return}if(XH===58){if(Y){let IH=I.slice(P,c);Y(IH.slice(I.charCodeAt(P+1)===Z8?2:1))}return}let WH=I.slice(P,c),MH=WH.indexOf(":");if(MH===-1){p(WH,"",WH);return}let kH=WH.slice(0,MH),NH=WH.charCodeAt(MH+1)===Z8?2:1,DH=WH.slice(MH+NH);p(kH,DH,WH)}function p(I,P,c){switch(I){case"event":F=P||void 0;break;case"data":M=_===0?P:`${M}
81
- ${P}`,_++;break;case"id":P.includes("\x00")||(D=P);break;case"retry":/^\d+$/.test(P)?X(parseInt(P,10)):Q(new c9(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:c}));break;default:Q(new c9(`Unknown field "${I.length>20?`${I.slice(0,20)}…`:I}"`,{type:"unknown-field",field:I,value:P,line:c}));break}}function j(){_>0&&W({id:D,event:F,data:M}),D=void 0,M="",_=0,F=void 0}function m(I={}){if(I.consume&&N.length>0){let P=N.join("");u(P,0,P.length)}G=!0,D=void 0,M="",_=0,F=void 0,N.length=0,B=0,A=!1}return{feed:w,reset:m}}function LD(H,W,Q){return Q===100&&H.charCodeAt(W+1)===97&&H.charCodeAt(W+2)===116&&H.charCodeAt(W+3)===97&&H.charCodeAt(W+4)===58}function jD(H,W,Q){return Q===101&&H.charCodeAt(W+1)===118&&H.charCodeAt(W+2)===101&&H.charCodeAt(W+3)===110&&H.charCodeAt(W+4)===116&&H.charCodeAt(W+5)===58}class RB extends TransformStream{constructor({onError:H,onRetry:W,onComment:Q,maxBufferSize:X}={}){let Y;super({start(J){Y=TD({onEvent:(N)=>{J.enqueue(N)},onError(N){typeof H=="function"&&H(N),(H==="terminate"||N.type==="max-buffer-size-exceeded")&&J.error(N)},onRetry:W,onComment:Q,maxBufferSize:X})},transform(J){Y.feed(J)}})}}var eY=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](H){return Y0(this,H)}static isInstance(H){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Y0(this,H)}constructor(H){super(H);this.name=new.target.name,V8(this,new.target)}},yB=class extends eY{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(H,W,Q){super(`Issuer mismatch in ${H==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(W)}, received ${JSON.stringify(Q)}`);this.kind=H,this.expected=W,this.received=Q}},NA=class extends eY{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(H){super(`Dynamic Client Registration rejected (HTTP ${H.status}): ${H.body}`);this.status=H.status,this.body=H.body,this.submittedMetadata=H.submittedMetadata}},lD=class extends eY{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(H){super(`Refusing to send credentials to non-https token endpoint '${H}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=H}},i9=class extends eY{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(H,W){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(H)} but this call resolved ${JSON.stringify(W)}; refusing to present them to a different authorization server`);this.recordedIssuer=H,this.currentIssuer=W}},$D=class extends eY{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(H){super(`Insufficient scope${H.requiredScope?`: required "${H.requiredScope}"`:""}`);this.requiredScope=H.requiredScope,this.resourceMetadataUrl=H.resourceMetadataUrl,this.errorDescription=H.errorDescription}};function hB(H,W,Q){if(!H)return;if(typeof H.issuer!=="string"){if(Q?.canPersistStamp!==!1)console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.");return H.issuer===void 0?H:{...H,issuer:void 0}}return mD(H.issuer,W)?H:void 0}function mD(H,W){return H===W||H.endsWith("/")&&H.slice(0,-1)===W||W.endsWith("/")&&W.slice(0,-1)===H}function BA(H){if(H==null)return!1;let W=H;return typeof W.tokens==="function"&&typeof W.clientInformation==="function"}async function KA(H,W,Q){let{resourceMetadataUrl:X,scope:Y}=aY(W.response);if(await fB(H,{serverUrl:W.serverUrl,resourceMetadataUrl:X,scope:Y,fetchFn:W.fetchFn,...Q})!=="AUTHORIZED")throw new l0}function GA(H,W){return{token:async()=>{return(await H.tokens())?.access_token},onUnauthorized:async(Q)=>KA(H,Q,W)}}var l0=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](H){return Y0(this,H)}static isInstance(H){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Y0(this,H)}constructor(H){super(H??"Unauthorized");this.name="UnauthorizedError",V8(this,new.target)}};function lB(H){return H?.authorization_response_iss_parameter_supported===!0}function mB({iss:H,expectedIssuer:W,issParameterSupported:Q}){if(W===void 0)return;if(H===void 0){if(Q)throw new yB("authorization_response",W,void 0);return}if(H!==W)throw new yB("authorization_response",W,H)}function CB(...H){let W=new Set;for(let Q of H){if(!Q)continue;for(let X of Q.split(/\s+/))if(X)W.add(X)}return W.size>0?[...W].join(" "):void 0}function DA(H,W){if(!H)return!1;let Q=new Set((W??"").split(/\s+/).filter(Boolean));for(let X of H.split(/\s+/))if(X&&!Q.has(X))return!0;return!1}async function MA(H,W,Q,X,Y){if(typeof H==="string")return{authorizationCode:H,iss:W};let J=H.get("iss")??void 0,N=H.get("code");if(N)return{authorizationCode:N,iss:J};let B=(await Q.discoveryState?.())?.authorizationServerMetadata;if(!B)try{B=(await oD(X,Y)).authorizationServerMetadata}catch{B=void 0}if(!B)throw new l0("Authorization callback failed and the issuer could not be verified");mB({iss:J,expectedIssuer:B.issuer,issParameterSupported:lB(B)});let G=H.get("error");if(G)throw new U8(G,H.get("error_description")??G,H.get("error_uri")??void 0);throw new l0("Authorization callback contained neither `code` nor `error`")}function qA(H){return["client_secret_basic","client_secret_post","none"].includes(H)}var SB="code",kB="S256";function _A(H,W){let Q=H.client_secret!==void 0;if("token_endpoint_auth_method"in H&&H.token_endpoint_auth_method&&qA(H.token_endpoint_auth_method)&&(W.length===0||W.includes(H.token_endpoint_auth_method)))return H.token_endpoint_auth_method;if(W.length===0)return Q?"client_secret_basic":"none";if(Q&&W.includes("client_secret_basic"))return"client_secret_basic";if(Q&&W.includes("client_secret_post"))return"client_secret_post";if(W.includes("none"))return"none";return Q?"client_secret_post":"none"}function FA(H,W,Q,X){let{client_id:Y,client_secret:J}=W;switch(H){case"client_secret_basic":EA(Y,J,Q);return;case"client_secret_post":AA(Y,J,X);return;case"none":OA(Y,X);return;default:throw Error(`Unsupported client authentication method: ${H}`)}}function EA(H,W,Q){if(!W)throw Error("client_secret_basic authentication requires a client_secret");let X=btoa(`${H}:${W}`);Q.set("Authorization",`Basic ${X}`)}function AA(H,W,Q){if(Q.set("client_id",H),W)Q.set("client_secret",W)}function OA(H,W){W.set("client_id",H)}function cD(H){return H==="localhost"||H.endsWith(".localhost")||H==="127.0.0.1"||H==="[::1]"||H==="::1"}function VA(H){let W=new URL(String(H));if(W.protocol!=="https:"&&!cD(W.hostname))throw new lD(W.href);return W}function UA(H){for(let W of H??[]){let Q;try{Q=new URL(W)}catch{continue}if(Q.protocol!=="http:"&&Q.protocol!=="https:")return"native";if(cD(Q.hostname))return"native"}return"web"}function wA(H){let W=H.clientMetadata;return{...W,grant_types:W.grant_types??(H.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:W.application_type??UA(W.redirect_uris)}}async function RD(H){let W=H instanceof Response?H.status:void 0,Q=H instanceof Response?await H.text():H;try{let X=p1.parse(JSON.parse(Q));return U8.fromResponse(X)}catch(X){let Y=`${W?`HTTP ${W}: `:""}Invalid OAuth error response: ${X}. Raw body: ${Q}`;return new U8(BW.ServerError,Y)}}function CD(H,W,Q){let X=H.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${Q} (provider implements no invalidateCredentials())`:`invalidating the stored ${Q} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(W.code)} — ${X}. Cause: ${JSON.stringify(W.message)}`)}async function fB(H,W){try{return await gB(H,W)}catch(Q){if(Q instanceof U8){if(Q.code===BW.InvalidClient||Q.code===BW.UnauthorizedClient)return CD(H,Q,"client credentials and tokens"),await H.invalidateCredentials?.("client"),await H.invalidateCredentials?.("tokens"),await gB(H,W);else if(Q.code===BW.InvalidGrant||Q.code===BW.InvalidDpopProof)return CD(H,Q,"tokens"),await H.invalidateCredentials?.("tokens"),await gB(H,W)}throw Q}}function zA(H){let{requestedScope:W,resourceMetadata:Q,authServerMetadata:X,clientMetadata:Y}=H,J=W||Q?.scopes_supported?.join(" ")||Y.scope;if(J&&X?.scopes_supported?.includes("offline_access")&&!J.split(" ").includes("offline_access")&&Y.grant_types?.includes("refresh_token"))J=`${J} offline_access`;return J}async function gB(H,{serverUrl:W,authorizationCode:Q,iss:X,scope:Y,resourceMetadataUrl:J,fetchFn:N,skipIssuerMetadataValidation:B,forceReauthorization:G}){let D=wA(H),M=await H.discoveryState?.(),_,F,A,w,z=J;if(!z&&M?.resourceMetadataUrl)z=new URL(M.resourceMetadataUrl);if(M?.authorizationServerUrl){if(F=M.authorizationServerUrl,_=M.resourceMetadata,A=M.authorizationServerMetadata??await iD(F,{fetchFn:N,skipIssuerValidation:B}),!_)try{_=await pD(W,{resourceMetadataUrl:z},N)}catch(NH){if(NH instanceof TypeError)throw NH}if(A!==M.authorizationServerMetadata||_!==M.resourceMetadata)await H.saveDiscoveryState?.({authorizationServerUrl:String(F),resourceMetadataUrl:z?.toString(),resourceMetadata:_,authorizationServerMetadata:A})}else{let NH=await oD(W,{resourceMetadataUrl:z,fetchFn:N,skipIssuerMetadataValidation:B});F=NH.authorizationServerUrl,A=NH.authorizationServerMetadata,_=NH.resourceMetadata,w={authorizationServerUrl:String(F),resourceMetadataUrl:z?.toString(),resourceMetadata:_,authorizationServerMetadata:A}}let Z=A?.issuer??String(F),u={issuer:Z};if(await H.saveAuthorizationServerUrl?.(Z),Q!==void 0){let NH=M?.authorizationServerMetadata?.issuer??M?.authorizationServerUrl;if(NH===void 0){if(H.saveDiscoveryState!==void 0)throw new i9("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",Z);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.")}else if(!mD(NH,Z))throw new i9(NH,Z)}if(w)await H.saveDiscoveryState?.(w);let p=await PA(W,H,_),j=p&&_&&!H.validateResourceURL?_.resource:p;if(j)await H.saveResourceUrl?.(cB(j));let m=zA({requestedScope:Y,resourceMetadata:_,authServerMetadata:A,clientMetadata:H.clientMetadata}),I=await Promise.resolve(H.clientInformation(u)),P=hB(I,Z,{canPersistStamp:H.saveClientInformation!==void 0});if(P===void 0&&I?.issuer&&H.saveClientInformation===void 0)throw new i9(I.issuer,Z);if(P&&P.issuer===void 0)P={...P,issuer:Z},await H.saveClientInformation?.(P,u);if(!P){if(Q!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let NH=A?.client_id_metadata_document_supported===!0,DH=H.clientMetadataUrl;if(DH&&!ZA(DH))throw new U8(BW.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${DH}`);if(NH&&DH)P={client_id:DH,issuer:Z},await H.saveClientInformation?.(P,u);else{if(!H.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");P={...await kA(F,{metadata:A,clientMetadata:D,scope:m,fetchFn:N}),issuer:Z},await H.saveClientInformation(P,u)}}let c=!H.redirectUrl;if(Q!==void 0||c){if(Q!==void 0)mB({iss:X,expectedIssuer:A?.issuer,issParameterSupported:lB(A)});let NH=await SA(H,F,{metadata:A,resource:j,authorizationCode:Q,iss:X,scope:m,fetchFn:N});return await H.saveTokens({...NH,issuer:Z},u),"AUTHORIZED"}let XH=hB(await H.tokens(u),Z);if(XH&&XH.issuer===void 0)XH={...XH,issuer:Z},await H.saveTokens(XH,u);if(XH?.refresh_token&&!G){let NH;try{NH=await CA(F,{metadata:A,clientInformation:P,refreshToken:XH.refresh_token,resource:j,addClientAuthentication:H.addClientAuthentication,dpop:await H.dpop?.(),fetchFn:N})}catch(DH){if(DH instanceof lD)throw DH;if(!(DH instanceof U8)||DH.code===BW.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(DH instanceof Error?DH.message:String(DH))}`);else throw DH}if(NH)return await H.saveTokens({...NH,issuer:Z},u),"AUTHORIZED"}let WH=H.state?await H.state():void 0,{authorizationUrl:MH,codeVerifier:kH}=await $A(F,{metadata:A,clientInformation:P,state:WH,redirectUrl:H.redirectUrl,scope:m,resource:j});return await H.saveCodeVerifier(kH),await H.redirectToAuthorization(MH),"REDIRECT"}function ZA(H){if(!H)return!1;try{let W=new URL(H);return W.protocol==="https:"&&W.pathname!=="/"}catch{return!1}}async function PA(H,W,Q){let X=SG(H);if(W.validateResourceURL)return await W.validateResourceURL(X,Q?.resource);if(!Q)return;if(!kG({requestedResource:X,configuredResource:Q.resource}))throw Error(`Protected resource ${Q.resource} does not match expected ${X} (or origin)`);return new URL(Q.resource)}var bA=new Set(["bearer","dpop"]);function aY(H){let W=H.headers.get("WWW-Authenticate");if(!W)return{};let[Q,X]=W.split(" ");if(!Q||!bA.has(Q.toLowerCase())||!X)return{};let Y=p9(H,"resource_metadata")||void 0,J;if(Y)try{J=new URL(Y)}catch{}let N=p9(H,"scope")||void 0,B=p9(H,"error")||void 0,G=p9(H,"error_description")||void 0;return{resourceMetadataUrl:J,scope:N,error:B,errorDescription:G}}function p9(H,W){let Q=H.headers.get("WWW-Authenticate");if(!Q)return null;let X=new RegExp(String.raw`${W}=(?:"([^"]+)"|([^\s,]+))`),Y=Q.match(X);if(Y){let J=Y[1]||Y[2];if(J)return J}return null}async function pD(H,W,Q=fetch){let X=await jA(H,"oauth-protected-resource",Q,{protocolVersion:W?.protocolVersion,metadataUrl:W?.resourceMetadataUrl});if(!X||X.status===404)throw await X?.text?.().catch(()=>{}),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!X.ok)throw await X.text?.().catch(()=>{}),Error(`HTTP ${X.status} trying to load well-known OAuth protected resource metadata.`);return l1.parse(await X.json())}async function dD(H,W,Q=fetch){let X=tY(Q);try{return await X(H,{headers:W})}catch(Y){if(!(Y instanceof TypeError)||!bD)throw Y;if(W)try{return await X(H,{})}catch(J){if(!(J instanceof TypeError))throw J;return}return}}function IA(H,W="",Q={}){if(W.endsWith("/"))W=W.slice(0,-1);return Q.prependPathname?`${W}/.well-known/${H}`:`/.well-known/${H}${W}`}async function SD(H,W,Q=fetch){return await dD(H,{"MCP-Protocol-Version":W},Q)}function LA(H,W){if(!H)return!0;if(W==="/")return!1;return!H.ok&&H.status<500||H.status===502}async function jA(H,W,Q,X){let Y=new URL(H),J=X?.protocolVersion??_1,N;if(X?.metadataUrl)N=new URL(X.metadataUrl);else{let G=IA(W,Y.pathname);N=new URL(G,X?.metadataServerUrl??Y),N.search=Y.search}let B=await SD(N,J,Q);if(!X?.metadataUrl&&LA(B,Y.pathname))B=await SD(new URL(`/.well-known/${W}`,Y),J,Q);return B}function TA(H){let W=typeof H==="string"?new URL(H):H,Q=W.pathname!=="/",X=[];if(!Q)return X.push({url:new URL("/.well-known/oauth-authorization-server",W.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",W.origin),type:"oidc"}),X;let Y=W.pathname;if(Y.endsWith("/"))Y=Y.slice(0,-1);return X.push({url:new URL(`/.well-known/oauth-authorization-server${Y}`,W.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${Y}`,W.origin),type:"oidc"},{url:new URL(`${Y}/.well-known/openid-configuration`,W.origin),type:"oidc"}),X}async function iD(H,{fetchFn:W=fetch,protocolVersion:Q=_1,skipIssuerValidation:X=!1}={}){let Y={"MCP-Protocol-Version":Q,Accept:"application/json"},J=TA(H);for(let{url:N,type:B}of J){let G=await dD(N,Y,W);if(!G)continue;if(!G.ok){if(await G.text?.().catch(()=>{}),G.status<500||G.status===502)continue;throw Error(`HTTP ${G.status} trying to load ${B==="oauth"?"OAuth":"OpenID provider"} metadata from ${N}`)}let D=B==="oauth"?O8.parse(await G.json()):m1.parse(await G.json());if(!X){let M=typeof H==="string"?H:H.href;if(!(D.issuer===M||M.endsWith("/")&&D.issuer===M.slice(0,-1)))throw new yB("metadata",M,D.issuer)}return D}}async function oD(H,W){let Q,X;try{if(Q=await pD(H,{resourceMetadataUrl:W?.resourceMetadataUrl},W?.fetchFn),Q.authorization_servers&&Q.authorization_servers.length>0)X=Q.authorization_servers[0]}catch(J){if(J instanceof TypeError)throw J}if(!X)X=String(new URL("/",H));let Y=await iD(X,{fetchFn:W?.fetchFn,skipIssuerValidation:W?.skipIssuerMetadataValidation});return{authorizationServerUrl:X,authorizationServerMetadata:Y,resourceMetadata:Q}}function cB(H){return typeof H==="string"?H:H.href}async function $A(H,{metadata:W,clientInformation:Q,redirectUrl:X,scope:Y,state:J,resource:N}){let B;if(W){if(B=new URL(W.authorization_endpoint),!W.response_types_supported.includes(SB))throw Error(`Incompatible auth server: does not support response type ${SB}`);if(W.code_challenge_methods_supported&&!W.code_challenge_methods_supported.includes(kB))throw Error(`Incompatible auth server: does not support code challenge method ${kB}`)}else B=new URL("/authorize",H);let G=await TB(),D=G.code_verifier,M=G.code_challenge;if(B.searchParams.set("response_type",SB),B.searchParams.set("client_id",Q.client_id),B.searchParams.set("code_challenge",M),B.searchParams.set("code_challenge_method",kB),B.searchParams.set("redirect_uri",String(X)),J)B.searchParams.set("state",J);if(Y)B.searchParams.set("scope",Y);if(Y?.split(" ").includes("offline_access"))B.searchParams.append("prompt","consent");if(N)B.searchParams.set("resource",cB(N));return{authorizationUrl:B,codeVerifier:D}}function RA(H,W,Q){return new URLSearchParams({grant_type:"authorization_code",code:H,code_verifier:W,redirect_uri:String(Q)})}async function nD(H,{metadata:W,tokenRequestParams:Q,clientInformation:X,addClientAuthentication:Y,resource:J,dpop:N,fetchFn:B}){let G=VA(W?.token_endpoint??new URL("/token",H)),D=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(J)Q.set("resource",cB(J));if(!Y&&X)FA(_A(X,W?.token_endpoint_auth_methods_supported??[]),X,D,Q);let M=async()=>{let A=new Headers(D);if(Y)await Y(A,Q,G,W);if(N)A.set("DPoP",await N.buildProof({htm:"POST",htu:G}));return tY(B??fetch)(G,{method:"POST",headers:A,body:Q})},_=await M();if(N&&_.status===400){if((await _.clone().json().catch(()=>{}))?.error===BW.UseDpopNonce)N.observeNonce(_,G),_=await M()}if(N?.observeNonce(_,G),!_.ok)throw await RD(_);let F=await _.json();try{return c1.parse(_B(F))}catch(A){if(typeof F==="object"&&F!==null&&"error"in F)throw await RD(JSON.stringify(F));throw A}}async function CA(H,{metadata:W,clientInformation:Q,refreshToken:X,resource:Y,addClientAuthentication:J,dpop:N,fetchFn:B}){return{refresh_token:X,...await nD(H,{metadata:W,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:X}),clientInformation:Q,addClientAuthentication:J,resource:Y,dpop:N,fetchFn:B})}}async function SA(H,W,{metadata:Q,resource:X,authorizationCode:Y,iss:J,scope:N,fetchFn:B}={}){if(Y!==void 0)mB({iss:J,expectedIssuer:Q?.issuer,issParameterSupported:lB(Q)});let G=Q?.issuer??String(W),D=async()=>{let A=await H.clientInformation({issuer:G}),w=hB(A,G,{canPersistStamp:!1});if(A&&w===void 0)throw new i9(String(A.issuer),G);return w},M=await D(),_=N??H.clientMetadata.scope,F;if(H.prepareTokenRequest)F=await H.prepareTokenRequest(_);if(!F){if(!Y)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!H.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");F=RA(Y,await H.codeVerifier(),H.redirectUrl)}return M??=await D(),nD(W,{metadata:Q,tokenRequestParams:F,clientInformation:M,addClientAuthentication:H.addClientAuthentication,resource:X,dpop:await H.dpop?.(),fetchFn:B})}async function kA(H,{metadata:W,clientMetadata:Q,scope:X,fetchFn:Y}){let J;if(W){if(!W.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");J=new URL(W.registration_endpoint)}else J=new URL("/register",H);let N={...Q,...X===void 0?{}:{scope:X}},B=await tY(Y??fetch)(J,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!B.ok)throw new NA({status:B.status,body:await B.text(),submittedMetadata:N});return d1.parse(_B(await B.json()))}var d9=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),gA=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(H){this._maxEntries=H?.maxEntries??512}get size(){return this._entries.size}get(H){return this._entries.get(xB(H))}set(H,W){let Q=xB(H),X=d9.has(H.method),Y=!this._entries.has(Q);if(!X&&Y&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let N of this._entries.keys())if(!d9.has(N.slice(0,N.indexOf("\x00")))){this._entries.delete(N),this._cappedSize--;break}}let J=++this._stamp;if(this._entries.set(Q,{...W,stamp:J}),Y&&!X)this._cappedSize++;return J}delete(H){if(this._entries.delete(xB(H))&&!d9.has(H.method))this._cappedSize--}evict(H){let W=`${H}\x00`,Q=d9.has(H);for(let X of this._entries.keys())if(X.startsWith(W)){if(this._entries.delete(X),!Q)this._cappedSize--}}clear(){this._entries.clear(),this._cappedSize=0}};function xB(H){return`${H.method}\x00${JSON.stringify([H.partition??"",H.params??""])}`}function vB(H,W){return W===void 0?H:`${H}\x00${W}`}var xA=86400000,vA=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(H,W,Q=()=>{},X="",Y=Date.now){this._store=H,this._isUserSupplied=W,this._reportError=Q,this._cachePartition=X,this._now=Y}now(){return this._now()}setServerIdentity(H){this._serverIdentity=H}_partitionFor(H){return JSON.stringify([this._serverIdentity,H==="public"?"":this._cachePartition])}async _probe(H,W){let Q={method:H,params:W??""},X=this._partitionFor("private"),Y=await this._store.get({...Q,partition:X});if(Y!==void 0)return Y;let J=this._partitionFor("public");if(J===X)return;let N=await this._store.get({...Q,partition:J});return N?.scope==="public"?N:void 0}async evict(H){this._evictionGeneration.set(H,(this._evictionGeneration.get(H)??0)+1),await this._deleteBoth(H,"")}async _deleteBoth(H,W){let Q=this._partitionFor("private"),X=this._partitionFor("public");try{await this._store.delete({method:H,params:W,partition:Q})}catch(Y){this._reportError(Y)}if(X!==Q)try{await this._store.delete({method:H,params:W,partition:X})}catch(Y){this._reportError(Y)}}async evictKey(H,W){let Q=vB(H,W),X=this._evictionGeneration.get(Q);if(X!==void 0)this._evictionGeneration.set(Q,X+1);await this._deleteBoth(H,W)}captureGeneration(H,W){let Q=vB(H,W),X=this._evictionGeneration.get(Q)??0;return this._evictionGeneration.set(Q,X),X}async write(H,W,Q,X){if((this._evictionGeneration.get(vB(H,X?.params))??0)!==Q)return;let Y=X?.params??"",J=this._partitionFor("private"),N=this._partitionFor("public"),B=(X?.scope??"private")==="public"?N:J;try{await this._store.set({method:H,params:Y,partition:B},{value:yA(W),expiresAt:X?.expiresAt,scope:X?.scope})}catch(G){this._reportError(G)}if(N!==J)try{await this._store.delete({method:H,params:Y,partition:B===J?N:J})}catch(G){this._reportError(G)}}async read(H,W){let Q=await this._probe(H,W);if(Q?.expiresAt===void 0||!(Q.expiresAt>this.now()))return;try{let X=JSON.parse(Q.value);if(typeof X!=="object"||X===null||Array.isArray(X))throw TypeError("cached document is not an object");return{value:X}}catch(X){this._reportError(X),await this._deleteBoth(H,W??"");return}}resetForReconnect(){if(!this._isUserSupplied)this._store.clear();this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(H){let W=await this._probe("tools/list");if(W===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==W.stamp){let Q=this._decodeListTools(W),X=new Map;if(Q!==void 0)for(let Y of Q.tools)X.set(Y.name,Y);this._toolIndex={stamp:W.stamp,byName:X}}return this._toolIndex.byName.get(H)}async outputValidator(H,W){let Q=await this._probe("tools/list");if(Q===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==Q.stamp){let X=this._decodeListTools(Q)??{tools:[]},Y=new Map;for(let J of X.tools){let N=W(J);if(N!==void 0)Y.set(J.name,N)}this._toolOutputValidatorIndex={stamp:Q.stamp,byName:Y}}return this._toolOutputValidatorIndex.byName.get(H)}_decodeListTools(H){try{let W=JSON.parse(H.value);if(!Array.isArray(W?.tools)||!W.tools.every((Q)=>Q!==null&&typeof Q==="object"))throw TypeError("cached tools/list document has a malformed tools array");return W}catch(W){this._reportError(W);return}}};function yA(H){let W;try{W=JSON.stringify(H)}catch(Q){throw TypeError(`cache value is not JSON-serializable: ${Q instanceof Error?Q.message:String(Q)}`)}if(typeof W!=="string")throw TypeError("cache value is not JSON-serializable: it has no JSON representation");return W}var rD=Symbol.for("mcp.authSeamEscape");function D0(H){if(typeof H==="object"&&H!==null||typeof H==="function")try{Object.defineProperty(H,rD,{value:!0,configurable:!0})}catch{}return H}function hA(H){return(typeof H==="object"&&H!==null||typeof H==="function")&&H[rD]===!0}var fA=-32022,uA=new Set([-32001,-32020,-32021]);function lA(H,W){switch(H.kind){case"result":return mA(H.result,W);case"rpc-error":return tD(H,W);case"http-error":return cA(H,W);case"network-error":return kD(H.error,W);case"unusable-reply":return{kind:"error",error:new v(x.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${sD(H.error)})`,{cause:H.error},{cause:H.error})};case"auth-required":return{kind:"error",error:H.error};case"closed":if(W.transportKind==="stdio")return{kind:"legacy"};return kD(Error("Connection closed during the version negotiation probe"),W);case"timeout":if(W.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new v(x.RequestTimeout,`Version negotiation probe timed out after ${H.timeoutMs}ms`,{timeout:H.timeoutMs})}}}function mA(H,W){let Q=NW(f9).validateResult("server/discover",H);if(!Q.ok)return{kind:"legacy"};let X=Q.value.supportedVersions,Y=W.clientModernVersions.find((J)=>X.includes(J));if(Y!==void 0)return{kind:"modern",version:Y,discover:Q.value};if(W.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new h9({supported:[...X],requested:W.requestedVersion})}}function tD(H,W){let{code:Q,message:X,data:Y}=H;if(Q===fA){let J=dA(Y);if(J===void 0)return{kind:"legacy"};let N=new h9({supported:J,requested:iA(Y)??W.requestedVersion},X),B=rY(J),G=W.clientModernVersions.find((D)=>B.includes(D));if(G!==void 0)return{kind:"corrective",version:G,error:N};if(B.length>0)return{kind:"error",error:N};return W.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:N}}if(uA.has(Q))return{kind:"legacy"};return{kind:"legacy"}}function cA(H,W){if(H.status===401||H.status===403){let X=H.status===403;return{kind:"error",error:new f0(X?x.ClientHttpForbidden:x.ClientHttpAuthentication,`Version negotiation failed: ${X?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:H.status,statusText:H.statusText,text:H.body})}}if(H.status>=500)return{kind:"error",error:new f0(x.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${H.status}`,{status:H.status,statusText:H.statusText,text:H.body})};let Q=oA(H.body);if(Q!==void 0)return tD(Q,W);return{kind:"legacy"}}function kD(H,W){if(W.environment==="browser"&&pA(H))return{kind:"legacy"};return{kind:"error",error:new v(x.EraNegotiationFailed,`Version negotiation probe failed: ${sD(H)}`,{cause:H},{cause:H})}}function pA(H){return H instanceof TypeError||H instanceof Error&&H.name==="TypeError"}function sD(H){return H instanceof Error?H.message:String(H)}function dA(H){if(typeof H!=="object"||H===null)return;let W=H.supported;if(!Array.isArray(W)||W.length===0||!W.every((Q)=>typeof Q==="string"))return;return W}function iA(H){if(typeof H!=="object"||H===null)return;let W=H.requested;return typeof W==="string"?W:void 0}function oA(H){if(H===void 0||H==="")return;let W;try{W=JSON.parse(H)}catch{return}if(typeof W!=="object"||W===null)return;let Q=W.error;if(typeof Q!=="object"||Q===null)return;let{code:X,message:Y,data:J}=Q;if(typeof X!=="number")return;return{code:X,message:typeof Y==="string"?Y:"",data:J}}var nA="legacy";function rA(H,W){let Q=H?.mode??nA;if(Q==="legacy")return{kind:"legacy"};let X=H?.probe??{};if(typeof Q==="object"){if(!KW(Q.pin))throw TypeError(`versionNegotiation: { pin: '${Q.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:Q.pin,probe:X}}let Y=W?rY(W):[];return{kind:"auto",modernVersions:Y.length>0?Y:[...FB],fallbackAvailable:W?EB(W).length>0:!0,probe:X}}function gD(){let H=globalThis;return H.window!==void 0&&H.document!==void 0?"browser":"node"}function xD(H){return"stderr"in H&&"pid"in H?"stdio":"http"}var tA=class H{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(W){this._transport=W,this._savedOnMessage=W.onmessage,this._savedOnError=W.onerror,this._savedOnClose=W.onclose}static async open(W){let Q=new H(W);W.onmessage=(X)=>{let Y=Q._pending;if(Y!==void 0&&(o1(X)||n1(X))&&X.id===Y.id){if(Q._pending=void 0,o1(X))Y.resolve({kind:"response",result:X.result});else Y.resolve({kind:"response",error:X.error});return}},W.onerror=(X)=>{Q._savedOnError?.(X)},W.onclose=()=>{let X=Q._pending;if(X!==void 0)Q._pending=void 0,X.resolve({kind:"closed"});Q._closeDelivered=!0,Q._savedOnClose?.()};try{await W.start()}catch(X){throw Q.detach(),X}return Q}async exchange(W,Q){let X=`server-discover-probe-${++this._probeCounter}`;return new Promise((Y)=>{let J=!1,N=(G)=>{if(J)return;if(J=!0,clearTimeout(B),this._pending?.id===X)this._pending=void 0;Y(G)},B=setTimeout(()=>N({kind:"timeout"}),Q);this._pending={id:X,resolve:N},this._transport.send(W(X)).catch((G)=>N({kind:"send-error",error:G}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let W=this._savedOnClose,Q=this._transport,X=!1,Y=()=>{if(!X){X=!0;return}W()};Q.onclose=Y,uB.set(Q,()=>{if(Q.onclose===Y)Q.onclose=W})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let W=this._transport,Q=W.start,X=!0;W.start=async function(){if(X){X=!1,W.start=Q;return}return Q.call(W)}}},uB=new WeakMap;function vD(H){let W=uB.get(H);uB.delete(H),W?.()}function sA(H,W,Q,X){return{jsonrpc:"2.0",id:H,method:"server/discover",params:{_meta:NW(W).outboundEnvelope({protocolVersion:W,clientInfo:Q,clientCapabilities:X})}}}function aA(H){if(H instanceof v&&H.code===x.ClientHttpUnexpectedContent)return!0;return H instanceof Error&&H.name==="SyntaxError"}function eA(H,W){switch(H.kind){case"response":return H.error===void 0?{kind:"result",result:H.result}:{kind:"rpc-error",...H.error};case"send-error":{let Q=H.error;if(hA(Q)||Q instanceof l0||Q instanceof Error&&Q.name==="UnauthorizedError")return{kind:"auth-required",error:Q};if(Q instanceof f0){let X=Q.data?.text;return{kind:"http-error",status:Q.data.status,body:typeof X==="string"?X:void 0,statusText:Q.data.statusText}}if(aA(Q))return{kind:"unusable-reply",error:Q};return{kind:"network-error",error:Q}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:W}}}async function aD(H,W){let Q=H.probe.timeoutMs??W.defaultTimeoutMs,X=Math.max(0,H.probe.maxRetries??0),Y=H.kind==="pin"?[H.version]:H.modernVersions,J=H.kind==="auto"&&H.fallbackAvailable,N=await tA.open(W.transport),B=async()=>{let D=Y[0],M=!1,_=X;for(;;){let F=await N.exchange((z)=>sA(z,D,W.clientInfo,W.capabilities),Q);if(F.kind==="timeout"&&_>0){_--;continue}let A=eA(F,Q),w=lA(A,{clientModernVersions:Y,requestedVersion:D,fallbackAvailable:J,environment:W.environment,transportKind:W.transportKind});switch(w.kind){case"modern":return{era:"modern",version:w.version,discover:w.discover};case"corrective":if(M)throw w.error;M=!0,D=w.version;continue;case"legacy":{let z=A.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(H.kind==="pin")throw new v(x.EraNegotiationFailed,z===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${H.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${z} before the server offered pinned protocol version ${H.version} (no fallback in pin mode)`);if(!H.fallbackAvailable)throw new v(x.EraNegotiationFailed,z===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${z} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(z!==void 0&&W.disposableProbe!==!0)throw new v(x.EraNegotiationFailed,`Version negotiation failed: ${z} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw w.error}}},G;try{G=await B()}catch(D){throw N.detach(),D}return N.release(),G}function HO(H){let W=Object.getPrototypeOf(H);if(W===null||!Object.prototype.hasOwnProperty.call(W,"_dispose"))return;let Q=H._serverParams;return typeof Q==="object"&&Q!==null&&typeof Q.command==="string"?Q:void 0}async function WO(H,W,Q,X){let J=new W.constructor({...Q,stderr:"ignore"}),N=W.close,B=!1,G,D=new Promise((_,F)=>{G=()=>F(yD())});W.close=async function(){return B=!0,G?.(),N.call(W)};let M;try{let _=aD(H,{...X,transport:J,transportKind:"stdio",disposableProbe:!0});_.catch(()=>{}),M=await Promise.race([_,D])}finally{await QO(J),W.close=N}if(B)throw yD();return M}function yD(){return new v(x.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function QO(H){try{let W=H._dispose;await(typeof W==="function"?W.call(H):H.close())}catch{}}function hD(H){let W=H._meta?.[HW];return qD.Implementation(W)?W:void 0}function o9(H,W){if(!H||W===null||typeof W!=="object")return;if(H.type==="object"&&H.properties&&typeof H.properties==="object"){let Q=W,X=H.properties;for(let Y of Object.keys(X)){let J=X[Y];if(Q[Y]===void 0&&Object.prototype.hasOwnProperty.call(J,"default"))Q[Y]=J.default;if(Q[Y]!==void 0)o9(J,Q[Y])}}if(Array.isArray(H.anyOf)){for(let Q of H.anyOf)if(typeof Q!=="boolean")o9(Q,W)}if(Array.isArray(H.oneOf)){for(let Q of H.oneOf)if(typeof Q!=="boolean")o9(Q,W)}}function XO(H){if(!H)return{supportsFormMode:!1,supportsUrlMode:!1};let W=H.form!==void 0,Q=H.url!==void 0;return{supportsFormMode:W||!W&&!Q,supportsUrlMode:Q}}function YO(H){if(typeof H==="object"&&H!==null){if(H.kind==="legacy"&&!("supportedVersions"in H)&&!("discover"in H))return H;if(H.kind==="modern"&&TW.safeParse(H.discover).success)return H}throw new v(x.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var fD={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},JO=64,eD=class extends m9{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let H=new v(x.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let W of this._listenState.values())W.settle({cause:"remote",error:H})}this._listenState.clear();for(let H of this._listChangedDebounceTimers.values())clearTimeout(H);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(H,W){super(W);if(this._clientInfo=H,this._capabilities=W?.capabilities?{...W.capabilities}:{},this._jsonSchemaValidator=W?.jsonSchemaValidator??new LB,this._enforceStrictCapabilities=W?.enforceStrictCapabilities??!1,this._versionNegotiation=W?.versionNegotiation,this._supportedProtocolVersionsOption=W?.supportedProtocolVersions,this._inputRequiredDriverConfig=KD(W?.inputRequired),this._cache=new vA(W?.responseCacheStore??new gA,W?.responseCacheStore!==void 0,(Q)=>this._reportStoreError(Q),W?.cachePartition??""),this._defaultCacheTtlMs=W?.defaultCacheTtlMs??0,this._listMaxPages=W?.listMaxPages??JO,W?.listChanged)this._listChangedConfig=W.listChanged}buildContext(H,W){return H}_shouldDropInbound(H){if(this._negotiatedProtocolVersion!==void 0&&KW(this._negotiatedProtocolVersion)&&w8(H))return"drop"}_outboundMetaEnvelope(){let H=this._negotiatedProtocolVersion;if(H===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:H,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(H,W){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new v(x.UnsupportedResultType,`Unsupported result type 'input_required' for ${W.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:W.request.method}));return FD({getRequestHandler:(Q)=>this._getRequestHandler(Q),buildContext:(Q)=>this.buildContext(Q,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,H,W)}_setupListChangedHandlers(H){if(H.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",H.tools,async()=>{return(await this.listTools(void 0,{cacheMode:"refresh"})).tools});if(H.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",H.prompts,async()=>{return(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts});if(H.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources","notifications/resources/list_changed",H.resources,async()=>{return(await this.listResources(void 0,{cacheMode:"refresh"})).resources})}registerCapabilities(H){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=_D(this._capabilities,H)}setVersionNegotiation(H){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=H}_wrapHandler(H,W){if(H==="elicitation/create")return async(Q,X)=>{let Y=NW(this._negotiatedProtocolVersion),J=Y.validateRequest("elicitation/create",Q);if(!J.ok&&J.reason==="not-in-era")J=Y.validateInputRequest("elicitation/create",Q);if(!J.ok)throw new JH(J.reason==="not-in-era"?r.InternalError:r.InvalidParams,J.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${J.message}`);let{params:N}=J.value;N.mode=N.mode??"form";let{supportsFormMode:B,supportsUrlMode:G}=XO(this._capabilities.elicitation);if(N.mode==="form"&&!B)throw new JH(r.InvalidParams,"Client does not support form-mode elicitation requests");if(N.mode==="url"&&!G)throw new JH(r.InvalidParams,"Client does not support URL-mode elicitation requests");let D=await W(Q,X),M=Y.validateResult("elicitation/create",D);if(!M.ok&&M.reason==="not-in-era")M=Y.validateInputResponse("elicitation/create",D);if(!M.ok)throw new JH(M.reason==="not-in-era"?r.InternalError:r.InvalidParams,M.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${M.message}`);let _=M.value,F=N.mode==="form"?N.requestedSchema:void 0;if(N.mode==="form"&&_.action==="accept"&&_.content&&F&&this._capabilities.elicitation?.form?.applyDefaults)try{o9(F,_.content)}catch{}return _};if(H==="sampling/createMessage")return async(Q,X)=>{let Y=NW(this._negotiatedProtocolVersion),J=Y.validateRequest("sampling/createMessage",Q);if(!J.ok&&J.reason==="not-in-era")J=Y.validateInputRequest("sampling/createMessage",Q);if(!J.ok)throw new JH(J.reason==="not-in-era"?r.InternalError:r.InvalidParams,J.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${J.message}`);let{params:N}=J.value,B=await W(Q,X),G=Boolean(N.tools||N.toolChoice),D=Y.samplingResultVariant(G,B);if(!D.ok&&D.reason==="not-in-era")D=Y.validateInputResponse("sampling/createMessage",B);if(!D.ok)throw new JH(D.reason==="not-in-era"?r.InternalError:r.InvalidParams,D.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${D.message}`);return D.value};return W}assertCapability(H,W){if(!this._serverCapabilities?.[H])throw new v(x.CapabilityNotSupported,`Server does not support ${H} (required for ${W})`)}async connect(H,W){if(W?.prior!=null)return this._connectFromPrior(H,YO(W.prior),W);let Q=rA(this._versionNegotiation,this._supportedProtocolVersionsOption);if(Q.kind!=="legacy")return this._connectNegotiated(H,Q,W);return this._connectPlainLegacy(H,W)}async _connectPlainLegacy(H,W){if(await super.connect(H),H.sessionId!==void 0){let Q=this._negotiatedProtocolVersion;if(Q!==void 0)H.setProtocolVersion?.(Q);return}this._resetConnectionState(),await this._legacyHandshake(H,W)}async _legacyHandshake(H,W){let Q=EB(this._supportedProtocolVersions);try{let X=Q[0];if(X===void 0)throw new v(x.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let Y=await this.request({method:"initialize",params:{protocolVersion:X,capabilities:this._capabilities,clientInfo:this._clientInfo}},W);if(Y===void 0)throw Error(`Server sent invalid initialize result: ${Y}`);if(!Q.includes(Y.protocolVersion))throw Error(`Server's protocol version is not supported: ${Y.protocolVersion}`);if(this._serverCapabilities=Y.capabilities,this._serverVersion=Y.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(H)),H.setProtocolVersion)H.setProtocolVersion(Y.protocolVersion);if(this._instructions=Y.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=Y.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(X){throw this.close(),X}}async _connectNegotiated(H,W,Q){if(H.sessionId!==void 0){await super.connect(H);let Y=this._negotiatedProtocolVersion;if(Y!==void 0&&H.setProtocolVersion)H.setProtocolVersion(Y);return}this._resetConnectionState();let X;try{let Y=xD(H),J={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:gD(),defaultTimeoutMs:Q?.timeout??l9},N=Y==="stdio"?HO(H):void 0;X=N===void 0?await aD(W,{...J,transport:H,transportKind:Y}):await WO(W,H,N,J)}catch(Y){throw await H.close().catch(()=>{}),vD(H),Y}if(vD(H),await super.connect(H),X.era==="legacy"){await this._legacyHandshake(H,Q);return}if(this._serverCapabilities=X.discover.capabilities,this._serverVersion=hD(X.discover),this._cache.setServerIdentity(this._deriveServerIdentity(H)),this._instructions=X.discover.instructions,this._discoverResult=X.discover,this._negotiatedProtocolVersion=X.version,H.setProtocolVersion)H.setProtocolVersion(X.version);if(this._listChangedConfig){let Y=this._listChangedConfig,J=this._serverCapabilities,N={...Y.tools&&J?.tools?.listChanged&&{tools:Y.tools},...Y.prompts&&J?.prompts?.listChanged&&{prompts:Y.prompts},...Y.resources&&J?.resources?.listChanged&&{resources:Y.resources}},B=!0;try{this._setupListChangedHandlers(N)}catch(D){B=!1,this.onerror?.(D instanceof Error?D:Error(String(D)))}let G=B?{...N.tools&&{toolsListChanged:!0},...N.prompts&&{promptsListChanged:!0},...N.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(G).length>0){let D=new AbortController,M=()=>D.abort(Q?.signal?.reason);if(Q?.signal?.aborted)M();Q?.signal?.addEventListener("abort",M);try{this._autoOpenedSubscription=await this.listen(G,{timeout:Q?.timeout,signal:D.signal})}catch(_){if(Q?.signal?.aborted)throw await this.close().catch(()=>{}),_;this.onerror?.(_ instanceof Error?_:Error(String(_)))}finally{Q?.signal?.removeEventListener("abort",M)}}}}async _connectFromPrior(H,W,Q){if(W.kind==="legacy")return this._connectPlainLegacy(H,Q);let X=W.discover;this._resetConnectionState();let Y=this._supportedProtocolVersionsOption,J=(Y&&rY(Y).length>0?rY(Y):FB).find((N)=>X.supportedVersions.includes(N));if(J===void 0)throw new v(x.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(H),this._discoverResult=X,this._serverCapabilities=X.capabilities,this._serverVersion=hD(X),this._cache.setServerIdentity(this._deriveServerIdentity(H)),this._instructions=X.instructions,this._negotiatedProtocolVersion=J,H.setProtocolVersion?.(J),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(N){this.onerror?.(N instanceof Error?N:Error(String(N)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(H){let W=this._serverVersion;if(W!==void 0)return`${W.name}@${W.version}`;return H.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let H=this._negotiatedProtocolVersion;if(H===void 0)return;return KW(H)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(H){switch(H){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new v(x.CapabilityNotSupported,`Server does not support logging (required for ${H})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new v(x.CapabilityNotSupported,`Server does not support prompts (required for ${H})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new v(x.CapabilityNotSupported,`Server does not support resources (required for ${H})`);if(H==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new v(x.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${H})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new v(x.CapabilityNotSupported,`Server does not support tools (required for ${H})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new v(x.CapabilityNotSupported,`Server does not support completions (required for ${H})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(H){switch(H){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new v(x.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${H})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(H){switch(H){case"sampling/createMessage":if(!this._capabilities.sampling)throw new v(x.CapabilityNotSupported,`Client does not support sampling capability (required for ${H})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new v(x.CapabilityNotSupported,`Client does not support elicitation capability (required for ${H})`);break;case"roots/list":if(!this._capabilities.roots)throw new v(x.CapabilityNotSupported,`Client does not support roots capability (required for ${H})`);break;case"ping":break}}async ping(H){return this.request({method:"ping"},H)}async discover(H){let W=await this._requestWithSchema({method:"server/discover"},TW,H);return this._discoverResult=W,W}async complete(H,W){return this.request({method:"completion/complete",params:H},W)}async setLoggingLevel(H,W){return this.request({method:"logging/setLevel",params:{level:H}},W)}async getPrompt(H,W){return this.request({method:"prompts/get",params:H},W)}async listPrompts(H,W){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(H?.cursor!==void 0)return this.request({method:"prompts/list",params:H},W);let Q=await this._serveFromCache("prompts/list",void 0,W);if(Q!==void 0)return Q;return this._listAllPages("prompts/list",H,W,(X)=>X.prompts)}async listResources(H,W){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(H?.cursor!==void 0)return this.request({method:"resources/list",params:H},W);let Q=await this._serveFromCache("resources/list",void 0,W);if(Q!==void 0)return Q;return this._listAllPages("resources/list",H,W,(X)=>X.resources)}async listResourceTemplates(H,W){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(H?.cursor!==void 0)return this.request({method:"resources/templates/list",params:H},W);let Q=await this._serveFromCache("resources/templates/list",void 0,W);if(Q!==void 0)return Q;return this._listAllPages("resources/templates/list",H,W,(X)=>X.resourceTemplates)}async _listAllPages(H,W,Q,X,Y){let J=Q?.cacheMode==="bypass",N=this._cache.captureGeneration(H),B=await this.request({method:H,...W&&{params:{...W}}},Q),G=B.nextCursor,D=B,M=1;while(G!==void 0){if(this._listMaxPages!==0&&M>=this._listMaxPages)throw new v(x.ListPaginationExceeded,`${H}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:H,listMaxPages:this._listMaxPages});let _=await this.request({method:H,params:{...W,cursor:G}},Q);if(_.nextCursor===G&&JSON.stringify(X(_))===JSON.stringify(X(D)))break;X(B).push(...X(_)),D=_,G=_.nextCursor,M++}if(delete B.nextCursor,Y?.(B),J)return B;return await this._cache.write(H,B,N,this._freshness(B)),B}_freshness(H,W){let Q=H,X=typeof Q.ttlMs==="number"?Q.ttlMs:this._defaultCacheTtlMs,Y=Q.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,X),xA),scope:Y,params:W}}async _serveFromCache(H,W,Q){if(Q?.cacheMode==="bypass"||Q?.cacheMode==="refresh")return;let X=await this._cache.read(H,W).catch((Y)=>void this._reportStoreError(Y));if(X!==void 0){if(Q?.signal?.aborted){let Y=Q.signal.reason;throw Y instanceof v?Y:new v(x.RequestTimeout,String(Y))}return X.value}}_reportStoreError(H){this.onerror?.(H instanceof Error?H:Error(String(H)))}_compileOutputValidator(H){if(!H.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(H.outputSchema)}}catch(W){return{ok:!1,compileError:W}}}async _resolveXMcpHeaderScan(H,W){let Q=W??await this._cache.toolDefinition(H);return Q===void 0?void 0:ZB(Q.inputSchema)}async readResource(H,W){let Q=await this._serveFromCache("resources/read",H.uri,W);if(Q!==void 0)return Q;let X=this._cache.captureGeneration("resources/read",H.uri),Y=await this.request({method:"resources/read",params:H},W);if(W?.cacheMode!=="bypass"){let J=this._freshness(Y,H.uri);if(J.expiresAt>this._cache.now())await this._cache.write("resources/read",Y,X,J);else if(W?.cacheMode==="refresh")await this._cache.evictKey("resources/read",H.uri)}return Y}async subscribeResource(H,W){return this.request({method:"resources/subscribe",params:H},W)}async unsubscribeResource(H,W){return this.request({method:"resources/unsubscribe",params:H},W)}async listen(H,W){if(this.transport===void 0)throw new v(x.NotConnected,"Not connected");let Q=this._negotiatedProtocolVersion;if(Q===void 0||!KW(Q))throw new v(x.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${Q??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:Q});if(W?.signal?.aborted){let j=W.signal.reason;throw j instanceof v?j:new v(x.RequestTimeout,String(j))}let X=new AbortController,Y=`listen:${this._nextListenId++}`,J="opening",N,B,G,D,M=new Promise((j,m)=>{G=j,D=m}),_,F=new Promise((j)=>{_=j}),A=(j)=>{if(J==="closed")return;let m=J==="opening";if(N!==void 0)clearTimeout(N),N=void 0;if("ack"in j){J="open",G(j.ack);return}if(J="closed",B!==void 0)W?.signal?.removeEventListener("abort",B);if(this._listenState.delete(Y),X.abort(),_(j.cause),m)D(j.error??new v(x.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},w=async()=>{X.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:Y}}).catch(()=>{})},z=async()=>{if(J==="closed")return;A({cause:"local"}),await w()};this._listenState.set(Y,{settle:A});let Z=W?.timeout??l9;if(N=setTimeout(()=>{A({cause:"remote",error:new v(x.RequestTimeout,"subscriptions/listen ack timed out",{timeout:Z})}),w().catch(()=>{})},Z),W?.signal){let j=W.signal;B=()=>{if(J==="closed")return;let m=j.reason;A({cause:"local",error:m instanceof Error?m:Error(String(m??"Aborted"))}),w().catch(()=>{})},j.addEventListener("abort",B,{once:!0})}let u={jsonrpc:"2.0",id:Y,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:H}},p=(j)=>{A({cause:"remote",error:j instanceof Error?j:Error(String(j))})};try{this.transport.send(u,{requestSignal:X.signal,onRequestStreamEnd:()=>A({cause:"remote",error:Error("subscriptions/listen: stream ended")})}).catch(p)}catch(j){p(j)}return{honoredFilter:await M,close:z,closed:F}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(H,W){let Q=Object.hasOwn(fD,H.method)?fD[H.method]:void 0;if(H.method==="notifications/resources/updated"){let X=H.params?.uri;if(typeof X==="string")this._cache.evictKey("resources/read",X)}else if(Q!==void 0)for(let X of Q)this._cache.evict(X);if(H.method==="notifications/subscriptions/acknowledged"){let X=H.params?._meta?.[DX],Y=typeof X==="string"?this._listenState.get(X):void 0;if(Y!==void 0){let J=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",H);Y.settle({ack:J.ok?J.value.params.notifications:{}});return}}if(H.method==="notifications/cancelled"){let X=H.params?.requestId,Y=typeof X==="string"?this._listenState.get(X):void 0;if(Y!==void 0){Y.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(H,W)}_onresponse(H){let W=H.id,Q=typeof W==="string"?this._listenState.get(W):void 0;if(Q!==void 0){if(n1(H))Q.settle({cause:"remote",error:JH.fromError(H.error.code,H.error.message,H.error.data)});else Q.settle({cause:"graceful",error:new v(x.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(H)}_onclose(){if(this._listenState.size>0){let H=new v(x.ConnectionClosed,"Connection closed");for(let W of this._listenState.values())W.settle({cause:"remote",error:H});this._listenState.clear()}super._onclose()}async callTool(H,W){let Q=this.getProtocolEra()==="modern"&&gD()!=="browser",X=async()=>{if(!Q)return W;let G;try{G=await this._resolveXMcpHeaderScan(H.name,W?.toolDefinition)}catch(M){this._reportStoreError(M)}if(!G?.valid||G.declarations.length===0)return W;let D=JD(G.declarations,H.arguments);return Object.keys(D).length===0?W:{...W,headers:{...W?.headers,...D}}},Y=W?.toolDefinition===void 0?await this._cache.outputValidator(H.name,(G)=>this._compileOutputValidator(G)).catch((G)=>void this._reportStoreError(G)):this._compileOutputValidator(W.toolDefinition),J=()=>{if(Y===void 0||Y.ok)return;let G=Y.compileError,D=(G instanceof Error?G.message:String(G)).slice(0,200);throw new JH(r.InvalidParams,`Tool '${H.name}' has an invalid outputSchema: ${D}`)};J();let N;try{N=await this.request({method:"tools/call",params:H},await X())}catch(G){let D=G instanceof JH&&G.code===i1;if(!Q||!D||W?.toolDefinition!==void 0)throw G;let M={signal:W?.signal,timeout:W?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,M).catch((_)=>this._reportStoreError(_)),Y=await this._cache.outputValidator(H.name,(_)=>this._compileOutputValidator(_)).catch((_)=>void this._reportStoreError(_)),J(),N=await this.request({method:"tools/call",params:H},await X())}let B=Y!==void 0&&Y.ok?Y.validator:void 0;if(B){if(N.structuredContent===void 0&&!N.isError)throw new JH(r.InvalidRequest,`Tool ${H.name} has an output schema but did not return structured content`);if(N.structuredContent!==void 0&&!N.isError)try{let G=B(N.structuredContent);if(!G.valid)throw new JH(r.InvalidParams,`Structured content does not match the tool's output schema: ${G.errorMessage}`)}catch(G){if(G instanceof JH)throw G;throw new JH(r.InvalidParams,`Failed to validate structured content: ${G instanceof Error?G.message:String(G)}`)}}return N}async listTools(H,W){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(H?.cursor!==void 0){let X=await this.request({method:"tools/list",params:H},W);return this._excludeInvalidXMcpHeaderTools(X),X}let Q=await this._serveFromCache("tools/list",void 0,W);if(Q!==void 0)return Q;return this._listAllPages("tools/list",H,W,(X)=>X.tools,(X)=>this._excludeInvalidXMcpHeaderTools(X))}_excludeInvalidXMcpHeaderTools(H){if(this.getProtocolEra()!=="modern"||!this.transport||xD(this.transport)==="stdio")return;let W=H.tools.filter((Q)=>{let X=ZB(Q.inputSchema);if(!X.valid)return console.warn(`[mcp-sdk] excluding tool '${Q.name}' from tools/list: invalid x-mcp-header declaration — ${X.reason}`),!1;return!0});if(W.length!==H.tools.length)H.tools=W}_setupListChangedHandler(H,W,Q,X){let Y=u9(NY,Q);if(!Y.success)throw Error(`Invalid ${H} listChanged options: ${Y.error.message}`);if(typeof Q.onChanged!=="function")throw TypeError(`Invalid ${H} listChanged options: onChanged must be a function`);let{autoRefresh:J,debounceMs:N}=Y.data,{onChanged:B}=Q,G=async()=>{if(!J){B(null,null);return}try{B(null,await X())}catch(M){B(M instanceof Error?M:Error(String(M)),null)}},D=()=>{if(N){let M=this._listChangedDebounceTimers.get(H);if(M)clearTimeout(M);let _=setTimeout(G,N);this._listChangedDebounceTimers.set(H,_)}else G()};this.setNotificationHandler(W,D)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function NO(H){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(H)}function BO(H){if(H.status!==401)return!1;let W=H.headers.get("www-authenticate")??"";return NO(W)&&/use_dpop_nonce/i.test(W)}var KO=(H,W)=>(Q)=>{let X=typeof H==="function"?H:()=>H;return async(Y,J)=>{let N=(J?.method??"GET").toUpperCase(),B=new URL(Y.toString()),G=await X();if(!G)return Q(Y,J);let D=async()=>{let _=await W();if(!_)return Q(Y,J);let F=new Headers(J?.headers),A=await G.buildProof({htm:N,htu:B,accessToken:_});return F.set("Authorization",`DPoP ${_}`),F.set("DPoP",A),Q(Y,{...J,headers:F})},M=await D();if(BO(M)&&M.headers.has("dpop-nonce"))G.observeNonce(M,B),await M.text?.().catch(()=>{}),M=await D();return G.observeNonce(M,B),M}},GO=(H)=>KO(async()=>{try{return await H.dpop?.()}catch(W){throw D0(W)}},async()=>{let W;try{W=await H.tokens()}catch(Q){throw D0(Q)}return W?.token_type?.toLowerCase()==="dpop"?W.access_token:void 0});var oU=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](H){return Y0(this,H)}static isInstance(H){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Y0(this,H)}constructor(H,W,Q){super(`SSE error: ${W}`);this.code=H,this.event=Q,V8(this,new.target)}};var DO=1,MO={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},qO=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function uD(H,W){if(typeof AbortSignal.any==="function")return AbortSignal.any([H,W]);let Q=new AbortController;if(H.aborted)return Q.abort(H.reason),Q.signal;if(W.aborted)return Q.abort(W.reason),Q.signal;let X=()=>{H.removeEventListener("abort",Y),W.removeEventListener("abort",J)};function Y(){X(),Q.abort(H.reason)}function J(){X(),Q.abort(W.reason)}return H.addEventListener("abort",Y,{once:!0}),W.addEventListener("abort",J,{once:!0}),Q.signal}var HM=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(H,W){if(this._url=H,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=W?.requestInit,this._skipIssuerMetadataValidation=W?.skipIssuerMetadataValidation,this._fetch=W?.fetch,BA(W?.authProvider)){if(this._oauthProvider=W.authProvider,this._authProvider=GA(W.authProvider,{skipIssuerMetadataValidation:W.skipIssuerMetadataValidation}),W.authProvider.dpop)this._fetch=GO(W.authProvider)(W.fetch??fetch)}else this._authProvider=W?.authProvider;if(this._redirectPolicy=W?.redirectPolicy,this._fetchWithInit=AD(W?.fetch,W?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=UD(this._fetchWithInit);this._sessionId=W?.sessionId,this._protocolVersion=W?.protocolVersion,this._reconnectionOptions=W?.reconnectionOptions??MO,this._reconnectionScheduler=W?.reconnectionScheduler,this._onInsufficientScope=W?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,W?.maxStepUpRetries??DO)}async _stepUpAuthorize(H,W){try{return await this._stepUpAuthorizeInner(H,W)}catch(Q){throw D0(Q)}}async _stepUpAuthorizeInner(H,W){if(this._onInsufficientScope==="throw")throw new $D({requiredScope:H.scope,resourceMetadataUrl:H.resourceMetadataUrl,errorDescription:H.errorDescription});if(!this._oauthProvider)throw new $D({requiredScope:H.scope,resourceMetadataUrl:H.resourceMetadataUrl,errorDescription:H.errorDescription});if(W>=this._maxStepUpRetries)throw new f0(x.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:H.statusText??"Forbidden",text:H.text});if(H.resourceMetadataUrl)this._resourceMetadataUrl=H.resourceMetadataUrl;let Q=await this._oauthProvider.tokens(),X=CB(this._scope,Q?.scope,H.scope);this._scope=X;let Y=DA(X,Q?.scope);return fB(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:X,forceReauthorization:Y,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(H){return this._redirectPolicy==="follow"?H:tY(H)}_unfollowedRedirect(H,W){let Q=this._redirectPolicy==="follow"?void 0:wD(H,W);return Q&&`${Q} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let H=new Headers(this._requestInit?.headers||void 0),W;try{W=await this._authProvider?.token()}catch(Q){throw D0(Q)}if(W)H.set("Authorization",`Bearer ${W}`);if(this._sessionId)H.set("mcp-session-id",this._sessionId);if(this._protocolVersion)H.set("mcp-protocol-version",this._protocolVersion);return H}_applyBodyDerivedHeaders(H,W){if(Array.isArray(W)||!w8(W))return;let Q=W.params?._meta?.[e0];if(typeof Q!=="string")return;H.set("mcp-protocol-version",Q),H.set("mcp-method",W.method);let X=ND(W.method,W.params);if(X?.value!==void 0)H.set("mcp-name",PB(X.value))}_isModernEnvelopedRequest(H){if(Array.isArray(H)||!w8(H))return!1;let W=H.params?._meta?.[e0];return typeof W==="string"&&KW(W)}async _startOrAuthSse(H,W=!1,Q=0){let{resumptionToken:X,requestSignal:Y}=H,J=()=>this._abortController?.signal.aborted===!0||Y?.aborted===!0;try{let N=await this._commonHeaders(),B=[...N.get("accept")?.split(",").map((_)=>_.trim().toLowerCase())??[],"text/event-stream"];if(N.set("accept",[...new Set(B)].join(", ")),X)N.set("last-event-id",X);let G=this._abortController?.signal,D=Y!==void 0&&G!==void 0?uD(G,Y):Y??G,M=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:N,signal:D});if(!M.ok){if(M.status===401&&this._authProvider){if(M.headers.has("www-authenticate")){let{resourceMetadataUrl:F,scope:A}=aY(M);this._resourceMetadataUrl=F,this._scope=CB(this._scope,A)}if(this._authProvider.onUnauthorized&&!W){try{await this._authProvider.onUnauthorized({response:M,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(F){throw D0(F)}return await M.text?.().catch(()=>{}),this._startOrAuthSse(H,!0,Q)}if(await M.text?.().catch(()=>{}),W)throw D0(new f0(x.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:M.statusText}));throw D0(new l0)}if(M.status===403){let{resourceMetadataUrl:F,scope:A,error:w,errorDescription:z}=aY(M);if(w==="insufficient_scope"){let Z=await M.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:A,resourceMetadataUrl:F,errorDescription:z,statusText:M.statusText,text:Z},Q)!=="AUTHORIZED")throw D0(new l0);return this._startOrAuthSse(H,W,Q+1)}}if(await M.text?.().catch(()=>{}),M.status===405){H.onRequestStreamEnd?.();return}let _=this._unfollowedRedirect(this._url,M)??M.statusText;throw new f0(x.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${_}`,{status:M.status,statusText:M.statusText})}this._handleSseStream(M.body,H,!0)}catch(N){if(!J())this.onerror?.(N);throw N}}_getNextReconnectionDelay(H){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let W=this._reconnectionOptions.initialReconnectionDelay,Q=this._reconnectionOptions.reconnectionDelayGrowFactor,X=this._reconnectionOptions.maxReconnectionDelay;return Math.min(W*Math.pow(Q,H),X)}_scheduleReconnection(H,W=0){let Q=this._reconnectionOptions.maxRetries;if(W>=Q){this.onerror?.(Error(`Maximum reconnection attempts (${Q}) exceeded.`)),H.onRequestStreamEnd?.();return}let X=this._getNextReconnectionDelay(W),Y=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||H.requestSignal?.aborted)return;this._startOrAuthSse(H).catch((J)=>{if(this._abortController?.signal.aborted||H.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${J instanceof Error?J.message:String(J)}`));try{this._scheduleReconnection(H,W+1)}catch(N){this.onerror?.(N instanceof Error?N:Error(String(N)))}})};if(this._reconnectionScheduler){let J=this._reconnectionScheduler(Y,X,W);this._cancelReconnection=typeof J==="function"?J:void 0}else{let J=setTimeout(Y,X);this._cancelReconnection=()=>clearTimeout(J)}}_handleSseStream(H,W,Q){if(!H){W.onRequestStreamEnd?.();return}let{onresumptiontoken:X,replayMessageId:Y,requestSignal:J,onRequestStreamEnd:N}=W,B=()=>this._abortController?.signal.aborted===!0||J?.aborted===!0,G,D=!1,M=!1;(async()=>{try{let F=H.pipeThrough(new TextDecoderStream).pipeThrough(new RB({onRetry:(A)=>{this._serverRetryMs=A}})).getReader();while(!0){let{value:A,done:w}=await F.read();if(w)break;if(A.id)G=A.id,D=!0,X?.(A.id);if(!A.data)continue;if(!A.event||A.event==="message")try{let z=V0.parse(JSON.parse(A.data));if(o1(z)||n1(z)){if(M=!0,Y!==void 0)z.id=Y}this.onmessage?.(z)}catch(z){this.onerror?.(z)}}if((Q||D)&&!M&&this._abortController&&!B())this._scheduleReconnection({resumptionToken:G,onresumptiontoken:X,replayMessageId:Y,requestSignal:J,onRequestStreamEnd:N},0);else if(!B())N?.()}catch(F){if(B())return;if(this.onerror?.(Error(`SSE stream disconnected: ${F}`)),(Q||D)&&!M&&this._abortController&&!B())try{this._scheduleReconnection({resumptionToken:G,onresumptiontoken:X,replayMessageId:Y,requestSignal:J,onRequestStreamEnd:N},0)}catch(A){this.onerror?.(Error(`Failed to reconnect: ${A instanceof Error?A.message:String(A)}`)),N?.()}else N?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(H,W){if(!this._oauthProvider)throw new l0("finishAuth requires an OAuthClientProvider");let{authorizationCode:Q,iss:X}=await MA(H,W,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await fB(this._oauthProvider,{serverUrl:this._url,authorizationCode:Q,iss:X,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new l0("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(H,W){return this._send(H,W,!1)}async _send(H,W,Q,X=0){try{let{resumptionToken:Y,onresumptiontoken:J}=W||{};if(Y){this._startOrAuthSse({resumptionToken:Y,replayMessageId:w8(H)?H.id:void 0,requestSignal:W?.requestSignal}).catch((Z)=>this.onerror?.(Z));return}let N=await this._commonHeaders();this._applyBodyDerivedHeaders(N,H);let B=Array.isArray(H)?H.some((Z)=>zB(Z)):zB(H);if(B)N.delete("mcp-session-id");if(W?.headers!==void 0)for(let[Z,u]of Object.entries(W.headers)){if(qO.has(Z.toLowerCase()))continue;N.set(Z,u)}N.set("content-type","application/json");let G=[...N.get("accept")?.split(",").map((Z)=>Z.trim().toLowerCase())??[],"application/json","text/event-stream"];N.set("accept",[...new Set(G)].join(", "));let D=this._abortController?.signal,M=W?.requestSignal!==void 0&&D!==void 0?uD(D,W.requestSignal):W?.requestSignal??D,_={...this._requestInit,method:"POST",headers:N,body:JSON.stringify(H),signal:M},F=await this._redirects(this._fetch??fetch)(this._url,_);if(B&&F.ok)this._sessionId=F.headers.get("mcp-session-id")||void 0;if(!F.ok){if(F.status===401&&this._authProvider){if(F.headers.has("www-authenticate")){let{resourceMetadataUrl:p,scope:j}=aY(F);this._resourceMetadataUrl=p,this._scope=CB(this._scope,j)}if(this._authProvider.onUnauthorized&&!Q){try{await this._authProvider.onUnauthorized({response:F,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(p){throw D0(p)}return await F.text?.().catch(()=>{}),this._send(H,W,!0,X)}if(await F.text?.().catch(()=>{}),Q)throw D0(new f0(x.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:F.statusText}));throw D0(new l0)}let Z=await F.text?.().catch(()=>null);if(F.status===403){let{resourceMetadataUrl:p,scope:j,error:m,errorDescription:I}=aY(F);if(m==="insufficient_scope"){if(await this._stepUpAuthorize({scope:j,resourceMetadataUrl:p,errorDescription:I,statusText:F.statusText,text:Z},X)!=="AUTHORIZED")throw D0(new l0);return this._send(H,W,Q,X+1)}}if(F.status===400&&typeof Z==="string"&&this._isModernEnvelopedRequest(H))try{let p=V0.parse(JSON.parse(Z)),j=(Array.isArray(H)?H:[H]).filter((m)=>w8(m));if(n1(p)&&j.some((m)=>m.id===p.id)){this.onmessage?.(p);return}}catch{}let u=this._unfollowedRedirect(this._url,F)??Z;throw new f0(x.ClientHttpNotImplemented,`Error POSTing to endpoint: ${u}`,{status:F.status,statusText:F.statusText,text:Z})}if(F.status===202){if(await F.text?.().catch(()=>{}),QD(H))this._startOrAuthSse({resumptionToken:void 0}).catch((Z)=>this.onerror?.(Z));return}let A=(Array.isArray(H)?H:[H]).some((Z)=>("method"in Z)&&("id"in Z)&&Z.id!==void 0),w=F.headers.get("content-type"),z=ED(w);if(A)if(z==="text/event-stream")this._handleSseStream(F.body,{onresumptiontoken:J,requestSignal:W?.requestSignal,onRequestStreamEnd:W?.onRequestStreamEnd},!1);else if(z==="application/json"){let Z=await F.json(),u=Array.isArray(Z)?Z.map((p)=>V0.parse(p)):[V0.parse(Z)];for(let p of u)this.onmessage?.(p)}else throw await F.text?.().catch(()=>{}),new v(x.ClientHttpUnexpectedContent,`Unexpected content type: ${w}`,{contentType:w});else await F.text?.().catch(()=>{})}catch(Y){if(W?.requestSignal?.aborted!==!0)this.onerror?.(Y);throw Y}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let H=await this._commonHeaders(),W={...this._requestInit,method:"DELETE",headers:H,signal:this._abortController?.signal},Q=await this._redirects(this._fetch??fetch)(this._url,W);if(await Q.text?.().catch(()=>{}),!Q.ok&&Q.status!==405)throw new f0(x.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,Q)??Q.statusText}`,{status:Q.status,statusText:Q.statusText});this._sessionId=void 0}catch(H){throw this.onerror?.(H),H}}setProtocolVersion(H){this._protocolVersion=H}get protocolVersion(){return this._protocolVersion}async resumeStream(H,W){await this._startOrAuthSse({resumptionToken:H,onresumptiontoken:W?.onresumptiontoken})}};class NM{_eventSlots=new Map;setHandler(H,W){let Q=this._ensureEventSlot(H);if(Q.onHandler&&W)console.warn(`[MCP Apps] on${String(H)} handler replaced. Use addEventListener("${String(H)}", …) to add multiple listeners without replacing.`);Q.onHandler=W}getHandler(H){return this._eventSlots.get(H)?.onHandler}addEventListener(H,W){this._ensureEventSlot(H).listeners.push(W)}removeEventListener(H,W){let Q=this._eventSlots.get(H);if(!Q)return;let X=Q.listeners.indexOf(W);if(X!==-1)Q.listeners.splice(X,1)}dispatch(H,W){let Q=this._eventSlots.get(H);if(!Q)return;Q.onHandler?.(W);for(let X of[...Q.listeners])X(W)}_ensureEventSlot(H){let W=this._eventSlots.get(H);if(!W)W={listeners:[]},this._eventSlots.set(H,W);return W}}class BM{_methods=new Set;claim(H,W){if(this._methods.has(H))throw Error(`Handler for "${H}" already registered (via ${W}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(H)}replace(H){this._methods.add(H)}release(H){this._methods.delete(H)}has(H){return this._methods.has(H)}}var WM=new Set;function QM(H,W){let[Q,X]=W,Y=Q?.shape;if(typeof Y?.method?.value!=="string")return;let J=Y.method.value,N=H==="request"?"setRequestHandler":"setNotificationHandler";if(!WM.has(N))WM.add(N),console.warn(`[ext-apps] ${N}(Schema, handler) is deprecated; use ${N}("${J}", { params: Schema.shape.params }, handler).`);let B=X;return[J,{params:Y.params},H==="request"?(G,D)=>B({method:J,params:G},_O(D)):(G)=>B({method:J,params:G})]}function _O(H){return{signal:H.mcpReq.signal,requestId:H.mcpReq.id,sessionId:H.sessionId,_meta:H.mcpReq._meta,sendRequest:H.mcpReq.send,sendNotification:H.mcpReq.notify,authInfo:H.http?.authInfo}}var KM="2026-01-26";var FO="ui/notifications/tool-input-partial";var EO=q.union([q.literal("light"),q.literal("dark")]).describe("Color theme preference for the host environment."),H4=q.union([q.literal("inline"),q.literal("fullscreen"),q.literal("pip")]).describe("Display mode for UI presentation."),AO=q.union([q.literal("--color-background-primary"),q.literal("--color-background-secondary"),q.literal("--color-background-tertiary"),q.literal("--color-background-inverse"),q.literal("--color-background-ghost"),q.literal("--color-background-info"),q.literal("--color-background-danger"),q.literal("--color-background-success"),q.literal("--color-background-warning"),q.literal("--color-background-disabled"),q.literal("--color-text-primary"),q.literal("--color-text-secondary"),q.literal("--color-text-tertiary"),q.literal("--color-text-inverse"),q.literal("--color-text-ghost"),q.literal("--color-text-info"),q.literal("--color-text-danger"),q.literal("--color-text-success"),q.literal("--color-text-warning"),q.literal("--color-text-disabled"),q.literal("--color-border-primary"),q.literal("--color-border-secondary"),q.literal("--color-border-tertiary"),q.literal("--color-border-inverse"),q.literal("--color-border-ghost"),q.literal("--color-border-info"),q.literal("--color-border-danger"),q.literal("--color-border-success"),q.literal("--color-border-warning"),q.literal("--color-border-disabled"),q.literal("--color-ring-primary"),q.literal("--color-ring-secondary"),q.literal("--color-ring-inverse"),q.literal("--color-ring-info"),q.literal("--color-ring-danger"),q.literal("--color-ring-success"),q.literal("--color-ring-warning"),q.literal("--font-sans"),q.literal("--font-mono"),q.literal("--font-weight-normal"),q.literal("--font-weight-medium"),q.literal("--font-weight-semibold"),q.literal("--font-weight-bold"),q.literal("--font-text-xs-size"),q.literal("--font-text-sm-size"),q.literal("--font-text-md-size"),q.literal("--font-text-lg-size"),q.literal("--font-heading-xs-size"),q.literal("--font-heading-sm-size"),q.literal("--font-heading-md-size"),q.literal("--font-heading-lg-size"),q.literal("--font-heading-xl-size"),q.literal("--font-heading-2xl-size"),q.literal("--font-heading-3xl-size"),q.literal("--font-text-xs-line-height"),q.literal("--font-text-sm-line-height"),q.literal("--font-text-md-line-height"),q.literal("--font-text-lg-line-height"),q.literal("--font-heading-xs-line-height"),q.literal("--font-heading-sm-line-height"),q.literal("--font-heading-md-line-height"),q.literal("--font-heading-lg-line-height"),q.literal("--font-heading-xl-line-height"),q.literal("--font-heading-2xl-line-height"),q.literal("--font-heading-3xl-line-height"),q.literal("--border-radius-xs"),q.literal("--border-radius-sm"),q.literal("--border-radius-md"),q.literal("--border-radius-lg"),q.literal("--border-radius-xl"),q.literal("--border-radius-full"),q.literal("--border-width-regular"),q.literal("--shadow-hairline"),q.literal("--shadow-sm"),q.literal("--shadow-md"),q.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),OO=q.record(AO.describe(`Style variables for theming MCP apps.
70
+ - ${Object.keys(o).join(`
71
+ - `)}`,Error(I)}let q=`${a}/$ref`,G=pe(e,H,r,o,n,s,i,q,l);if(!G.valid)C.push({instanceLocation:i,keyword:"$ref",keywordLocation:q,error:"A subschema had errors."},...G.errors);if(r==="4"||r==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(b)){let H=b.length,q=!1;for(let G=0;G<H;G++)if(d===b[G]||b[G]==="integer"&&d==="number"&&e%1===0&&e===e){q=!0;break}if(!q)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b.join('", "')}".`})}else if(b==="integer"){if(d!=="number"||e%1||e!==e)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`})}else if(b!==void 0&&d!==b)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`});if(y!==void 0){if(d==="object"||d==="array"){if(!qi(e,y))C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}else if(e!==y)C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}if(v!==void 0){if(d==="object"||d==="array"){if(!v.some((H)=>qi(e,H)))C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}else if(!v.some((H)=>e===H))C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}if(F!==void 0){let H=`${a}/not`;if(pe(e,F,r,o,n,s,i,H).valid)C.push({instanceLocation:i,keyword:"not",keywordLocation:H,error:'Instance matched "not" schema.'})}let mt=[];if(x!==void 0){let H=`${a}/anyOf`,q=C.length,G=!1;for(let I=0;I<x.length;I++){let k=x[I],B=Object.create(l),J=pe(e,k,r,o,n,S===!0?s:null,i,`${H}/${I}`,B);if(C.push(...J.errors),G=G||J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:H,error:"Instance does not match any subschemas."})}if(U!==void 0){let H=`${a}/allOf`,q=C.length,G=!0;for(let I=0;I<U.length;I++){let k=U[I],B=Object.create(l),J=pe(e,k,r,o,n,S===!0?s:null,i,`${H}/${I}`,B);if(C.push(...J.errors),G=G&&J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"allOf",keywordLocation:H,error:"Instance does not match every subschema."})}if(R!==void 0){let H=`${a}/oneOf`,q=C.length,G=R.filter((I,k)=>{let B=Object.create(l),J=pe(e,I,r,o,n,S===!0?s:null,i,`${H}/${k}`,B);if(C.push(...J.errors),J.valid)mt.push(B);return J.valid}).length;if(G===1)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:H,error:`Instance does not match exactly one subschema (${G} matches).`})}if(d==="object"||d==="array")Object.assign(l,...mt);if(w!==void 0){let H=`${a}/if`;if(pe(e,w,r,o,n,s,i,H,l).valid){if(Z!==void 0){let q=pe(e,Z,r,o,n,s,i,`${a}/then`,l);if(!q.valid)C.push({instanceLocation:i,keyword:"if",keywordLocation:H,error:'Instance does not match "then" schema.'},...q.errors)}}else if(X!==void 0){let q=pe(e,X,r,o,n,s,i,`${a}/else`,l);if(!q.valid)C.push({instanceLocation:i,keyword:"if",keywordLocation:H,error:'Instance does not match "else" schema.'},...q.errors)}}if(d==="object"){if(L!==void 0){for(let I of L)if(!(I in e))C.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${I}".`})}let H=Object.keys(e);if(ve!==void 0&&H.length<ve)C.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${ve} properties.`});if(ke!==void 0&&H.length>ke)C.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${ke} properties.`});if(ct!==void 0){let I=`${a}/propertyNames`;for(let k in e){let B=`${i}/${it(k)}`,J=pe(k,ct,r,o,n,s,B,I);if(!J.valid)C.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:I,error:`Property name "${k}" does not match schema.`},...J.errors)}}if(qe!==void 0){let I=`${a}/dependantRequired`;for(let k in qe)if(k in e){let B=qe[k];for(let J of B)if(!(J in e))C.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}}if(We!==void 0)for(let I in We){let k=`${a}/dependentSchemas`;if(I in e){let B=pe(e,We[I],r,o,n,s,i,`${k}/${it(I)}`,l);if(!B.valid)C.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${I}" but does not match dependant schema.`},...B.errors)}}if(lt!==void 0){let I=`${a}/dependencies`;for(let k in lt)if(k in e){let B=lt[k];if(Array.isArray(B)){for(let J of B)if(!(J in e))C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}else{let J=pe(e,B,r,o,n,s,i,`${I}/${it(k)}`);if(!J.valid)C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not match dependant schema.`},...J.errors)}}}let q=Object.create(null),G=!1;if(ce!==void 0){let I=`${a}/properties`;for(let k in ce){if(!(k in e))continue;let B=`${i}/${it(k)}`,J=pe(e[k],ce[k],r,o,n,s,B,`${I}/${it(k)}`);if(J.valid)l[k]=q[k]=!0;else if(G=n,C.push({instanceLocation:i,keyword:"properties",keywordLocation:I,error:`Property "${k}" does not match schema.`},...J.errors),G)break}}if(!G&&Ee!==void 0){let I=`${a}/patternProperties`;for(let k in Ee){let B=new RegExp(k,"u"),J=Ee[k];for(let ge in e){if(!B.test(ge))continue;let dr=`${i}/${it(ge)}`,ft=pe(e[ge],J,r,o,n,s,dr,`${I}/${it(k)}`);if(ft.valid)l[ge]=q[ge]=!0;else G=n,C.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:I,error:`Property "${ge}" matches pattern "${k}" but does not match associated schema.`},...ft.errors)}}}if(!G&&te!==void 0){let I=`${a}/additionalProperties`;for(let k in e){if(q[k])continue;let B=`${i}/${it(k)}`,J=pe(e[k],te,r,o,n,s,B,I);if(J.valid)l[k]=!0;else G=n,C.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:I,error:`Property "${k}" does not match additional properties schema.`},...J.errors)}}else if(!G&&se!==void 0){let I=`${a}/unevaluatedProperties`;for(let k in e)if(!l[k]){let B=`${i}/${it(k)}`,J=pe(e[k],se,r,o,n,s,B,I);if(J.valid)l[k]=!0;else C.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:I,error:`Property "${k}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){if(et!==void 0&&e.length>et)C.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${et}).`});if(Ie!==void 0&&e.length<Ie)C.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ie}).`});let H=e.length,q=0,G=!1;if(Ze!==void 0){let I=`${a}/prefixItems`,k=Math.min(Ze.length,H);for(;q<k;q++){let B=pe(e[q],Ze[q],r,o,n,s,`${i}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}if($e!==void 0){let I=`${a}/items`;if(Array.isArray($e)){let k=Math.min($e.length,H);for(;q<k;q++){let B=pe(e[q],$e[q],r,o,n,s,`${i}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}else for(;q<H;q++){let k=pe(e[q],$e,r,o,n,s,`${i}/${q}`,I);if(l[q]=!0,!k.valid){if(G=n,C.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...k.errors),G)break}}if(!G&&Tt!==void 0){let k=`${a}/additionalItems`;for(;q<H;q++){let B=pe(e[q],Tt,r,o,n,s,`${i}/${q}`,k);if(l[q]=!0,!B.valid)G=n,C.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:k,error:"Items did not match additional items schema."},...B.errors)}}}if(ut!==void 0)if(H===0&&Re===void 0)C.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Re!==void 0&&H<Re)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${H}) than minContains (${Re}).`});else{let I=`${a}/contains`,k=C.length,B=0;for(let J=0;J<H;J++){let ge=pe(e[J],ut,r,o,n,s,`${i}/${J}`,I);if(ge.valid)l[J]=!0,B++;else C.push(...ge.errors)}if(B>=(Re||0))C.length=k;if(Re===void 0&&Ce===void 0&&B===0)C.splice(k,0,{instanceLocation:i,keyword:"contains",keywordLocation:I,error:"Array does not contain item matching schema."});else if(Re!==void 0&&B<Re)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Re} items matching schema. Only ${B} items were found.`});else if(Ce!==void 0&&B>Ce)C.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${B} items were found.`})}if(!G&&Et!==void 0){let I=`${a}/unevaluatedItems`;for(;q<H;q++){if(l[q])continue;let k=pe(e[q],Et,r,o,n,s,`${i}/${q}`,I);if(l[q]=!0,!k.valid)C.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:I,error:"Items did not match unevaluated items schema."},...k.errors)}}if(lr)for(let I=0;I<H;I++){let k=e[I],B=typeof k==="object"&&k!==null;for(let J=0;J<H;J++){if(I===J)continue;let ge=e[J];if(k===ge||B&&typeof ge==="object"&&ge!==null&&qi(k,ge))C.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${I} and ${J}.`}),I=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER}}}else if(d==="number"){if(r==="4"){if(De!==void 0&&(Ae===!0&&e<=De||e<De))C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Ae?"or equal to ":""} ${De}.`});if(Fe!==void 0&&(Ke===!0&&e>=Fe||e>Fe))C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ke?"or equal to ":""} ${Fe}.`})}else{if(De!==void 0&&e<De)C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${De}.`});if(Fe!==void 0&&e>Fe)C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Fe}.`});if(Ae!==void 0&&e<=Ae)C.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Ae}.`});if(Ke!==void 0&&e>=Ke)C.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ke}.`})}if(Ge!==void 0){let H=e%Ge;if(Math.abs(0-H)>=0.00000011920929&&Math.abs(Ge-H)>=0.00000011920929)C.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Ge}.`})}}else if(d==="string"){let H=dt===void 0&&pt===void 0?0:wv(e);if(dt!==void 0&&H<dt)C.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${H} < ${dt}).`});if(pt!==void 0&&H>pt)C.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${H} > ${pt}).`});if(Ht!==void 0&&!new RegExp(Ht,"u").test(e))C.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(Y!==void 0&&bg[Y]&&!bg[Y](e))C.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${Y}".`})}return{valid:C.length===0,errors:C}}var Rv=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Hr(e)}validate(e){return pe(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};Hr(e,this.lookup)}},Su=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=ad(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Rv(e,this.draft??this._draftFor(e),this.shortcircuit);return(r)=>{let o=t.validate(r);return o.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map((n)=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var zg=!0;var _u;_u=globalThis.crypto;async function xv(e){return(await _u).getRandomValues(new Uint8Array(e))}async function Pv(e){let r=Math.pow(2,8)-Math.pow(2,8)%66,o="";while(o.length<e){let n=await xv(e-o.length);for(let s of n)if(s<r)o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[s%66]}return o}async function Tv(e){return await Pv(e)}async function Ev(e){let t=await(await _u).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function bu(e){if(!e)e=43;if(e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Tv(e),r=await Ev(t);return{code_verifier:t,code_challenge:r}}class yc extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}var wg=10,kv=13,Vr=32;function yu(e){}function Pg(e){if(typeof e=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=yu,onError:r=yu,onRetry:o=yu,onComment:n,maxBufferSize:s}=e,i=[],a=0,l=!0,u,d="",m=0,f,S=!1;function b(R){if(S)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,R.charCodeAt(0)===239&&R.charCodeAt(1)===187&&R.charCodeAt(2)===191&&(R=R.slice(3))),i.length===0){let X=v(R);X!==""&&(i.push(X),a=X.length),y();return}if(R.indexOf(`
72
+ `)===-1&&R.indexOf("\r")===-1){i.push(R),a+=R.length,y();return}i.push(R);let w=i.join("");i.length=0,a=0;let Z=v(w);Z!==""&&(i.push(Z),a=Z.length),y()}function y(){s!==void 0&&(a+d.length<=s||(S=!0,i.length=0,a=0,u=void 0,d="",m=0,f=void 0,r(new yc(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function v(R){let w=0;if(R.indexOf("\r")===-1){let Z=R.indexOf(`
73
+ `,w);for(;Z!==-1;){if(w===Z){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0,w=Z+1,Z=R.indexOf(`
74
+ `,w);continue}let X=R.charCodeAt(w);if(Rg(R,w,X)){let Y=R.charCodeAt(w+5)===Vr?w+6:w+5,ce=R.slice(Y,Z);if(m===0&&R.charCodeAt(Z+1)===wg){t({id:u,event:f,data:ce}),u=void 0,d="",f=void 0,w=Z+2,Z=R.indexOf(`
75
+ `,w);continue}d=m===0?ce:`${d}
76
+ ${ce}`,m++}else xg(R,w,X)?f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,Z)||void 0:L(R,w,Z);w=Z+1,Z=R.indexOf(`
77
+ `,w)}return R.slice(w)}for(;w<R.length;){let Z=R.indexOf("\r",w),X=R.indexOf(`
78
+ `,w),Y=-1;if(Z!==-1&&X!==-1?Y=Z<X?Z:X:Z!==-1?Z===R.length-1?Y=-1:Y=Z:X!==-1&&(Y=X),Y===-1)break;L(R,w,Y),w=Y+1,R.charCodeAt(w-1)===kv&&R.charCodeAt(w)===wg&&w++}return R.slice(w)}function L(R,w,Z){if(w===Z){x();return}let X=R.charCodeAt(w);if(Rg(R,w,X)){let ve=R.charCodeAt(w+5)===Vr?w+6:w+5,ke=R.slice(ve,Z);d=m===0?ke:`${d}
79
+ ${ke}`,m++;return}if(xg(R,w,X)){f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,Z)||void 0;return}if(X===105&&R.charCodeAt(w+1)===100&&R.charCodeAt(w+2)===58){let ve=R.slice(R.charCodeAt(w+3)===Vr?w+4:w+3,Z);ve.includes("\x00")||(u=ve);return}if(X===58){if(n){let ve=R.slice(w,Z);n(ve.slice(R.charCodeAt(w+1)===Vr?2:1))}return}let Y=R.slice(w,Z),ce=Y.indexOf(":");if(ce===-1){F(Y,"",Y);return}let Ee=Y.slice(0,ce),te=Y.charCodeAt(ce+1)===Vr?2:1,se=Y.slice(ce+te);F(Ee,se,Y)}function F(R,w,Z){switch(R){case"event":f=w||void 0;break;case"data":d=m===0?w:`${d}
80
+ ${w}`,m++;break;case"id":w.includes("\x00")||(u=w);break;case"retry":/^\d+$/.test(w)?o(parseInt(w,10)):r(new yc(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:Z}));break;default:r(new yc(`Unknown field "${R.length>20?`${R.slice(0,20)}…`:R}"`,{type:"unknown-field",field:R,value:w,line:Z}));break}}function x(){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0}function U(R={}){if(R.consume&&i.length>0){let w=i.join("");L(w,0,w.length)}l=!0,u=void 0,d="",m=0,f=void 0,i.length=0,a=0,S=!1}return{feed:b,reset:U}}function Rg(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function xg(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class vu extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:o}={}){let n;super({start(s){n=Pg({onEvent:(i)=>{s.enqueue(i)},onError(i){typeof e=="function"&&e(i),(e==="terminate"||i.type==="max-buffer-size-exceeded")&&s.error(i)},onRetry:t,onComment:r,maxBufferSize:o})},transform(s){n.feed(s)}})}}var Mi=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e);this.name=new.target.name,Zr(this,new.target)}},Eu=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`);this.kind=e,this.expected=t,this.received=r}},$v=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`);this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Lg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=e}},wc=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`);this.recordedIssuer=e,this.currentIssuer=t}},Tg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`);this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function ku(e,t,r){if(!e)return;if(typeof e.issuer!=="string"){if(r?.canPersistStamp!==!1)console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.");return e.issuer===void 0?e:{...e,issuer:void 0}}return Ug(e.issuer,t)?e:void 0}function Ug(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Cv(e){if(e==null)return!1;let t=e;return typeof t.tokens==="function"&&typeof t.clientInformation==="function"}async function Iv(e,t,r){let{resourceMetadataUrl:o,scope:n}=Ai(t.response);if(await $u(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new wt}function Ov(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async(r)=>Iv(e,r,t)}}var wt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",Zr(this,new.target)}};function Iu(e){return e?.authorization_response_iss_parameter_supported===!0}function Ou({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t===void 0)return;if(e===void 0){if(r)throw new Eu("authorization_response",t,void 0);return}if(e!==t)throw new Eu("authorization_response",t,e)}function zu(...e){let t=new Set;for(let r of e){if(!r)continue;for(let o of r.split(/\s+/))if(o)t.add(o)}return t.size>0?[...t].join(" "):void 0}function Nv(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let o of e.split(/\s+/))if(o&&!r.has(o))return!0;return!1}async function qv(e,t,r,o,n){if(typeof e==="string")return{authorizationCode:e,iss:t};let s=e.get("iss")??void 0,i=e.get("code");if(i)return{authorizationCode:i,iss:s};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await Vg(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new wt("Authorization callback failed and the issuer could not be verified");Ou({iss:s,expectedIssuer:a.issuer,issParameterSupported:Iu(a)});let l=e.get("error");if(l)throw new Dr(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new wt("Authorization callback contained neither `code` nor `error`")}function Av(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var wu="code",Ru="S256";function Mv(e,t){let r=e.client_secret!==void 0;if("token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Av(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method)))return e.token_endpoint_auth_method;if(t.length===0)return r?"client_secret_basic":"none";if(r&&t.includes("client_secret_basic"))return"client_secret_basic";if(r&&t.includes("client_secret_post"))return"client_secret_post";if(t.includes("none"))return"none";return r?"client_secret_post":"none"}function jv(e,t,r,o){let{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":Lv(n,s,r);return;case"client_secret_post":Uv(n,s,o);return;case"none":Zv(n,o);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Lv(e,t,r){if(!t)throw Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function Uv(e,t,r){if(r.set("client_id",e),t)r.set("client_secret",t)}function Zv(e,t){t.set("client_id",e)}function Zg(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Dv(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Zg(t.hostname))throw new Lg(t.href);return t}function Fv(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:")return"native";if(Zg(r.hostname))return"native"}return"web"}function Hv(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??Fv(t.redirect_uris)}}async function Eg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Ho.parse(JSON.parse(r));return Dr.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Dr(Ut.ServerError,n)}}function kg(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${o}. Cause: ${JSON.stringify(t.message)}`)}async function $u(e,t){try{return await xu(e,t)}catch(r){if(r instanceof Dr){if(r.code===Ut.InvalidClient||r.code===Ut.UnauthorizedClient)return kg(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await xu(e,t);else if(r.code===Ut.InvalidGrant||r.code===Ut.InvalidDpopProof)return kg(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await xu(e,t)}throw r}}function Vv(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,s=t||r?.scopes_supported?.join(" ")||n.scope;if(s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token"))s=`${s} offline_access`;return s}async function xu(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:s,fetchFn:i,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=Hv(e),d=await e.discoveryState?.(),m,f,S,b,y=s;if(!y&&d?.resourceMetadataUrl)y=new URL(d.resourceMetadataUrl);if(d?.authorizationServerUrl){if(f=d.authorizationServerUrl,m=d.resourceMetadata,S=d.authorizationServerMetadata??await Hg(f,{fetchFn:i,skipIssuerValidation:a}),!m)try{m=await Dg(t,{resourceMetadataUrl:y},i)}catch(te){if(te instanceof TypeError)throw te}if(S!==d.authorizationServerMetadata||m!==d.resourceMetadata)await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S})}else{let te=await Vg(t,{resourceMetadataUrl:y,fetchFn:i,skipIssuerMetadataValidation:a});f=te.authorizationServerUrl,S=te.authorizationServerMetadata,m=te.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S}}let v=S?.issuer??String(f),L={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let te=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(te===void 0){if(e.saveDiscoveryState!==void 0)throw new wc("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",v);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.")}else if(!Ug(te,v))throw new wc(te,v)}if(b)await e.saveDiscoveryState?.(b);let F=await Bv(t,e,m),x=F&&m&&!e.validateResourceURL?m.resource:F;if(x)await e.saveResourceUrl?.(Nu(x));let U=Vv({requestedScope:n,resourceMetadata:m,authServerMetadata:S,clientMetadata:e.clientMetadata}),R=await Promise.resolve(e.clientInformation(L)),w=ku(R,v,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&R?.issuer&&e.saveClientInformation===void 0)throw new wc(R.issuer,v);if(w&&w.issuer===void 0)w={...w,issuer:v},await e.saveClientInformation?.(w,L);if(!w){if(r!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let te=S?.client_id_metadata_document_supported===!0,se=e.clientMetadataUrl;if(se&&!Jv(se))throw new Dr(Ut.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${se}`);if(te&&se)w={client_id:se,issuer:v},await e.saveClientInformation?.(w,L);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");w={...await oz(f,{metadata:S,clientMetadata:u,scope:U,fetchFn:i}),issuer:v},await e.saveClientInformation(w,L)}}let Z=!e.redirectUrl;if(r!==void 0||Z){if(r!==void 0)Ou({iss:o,expectedIssuer:S?.issuer,issParameterSupported:Iu(S)});let te=await rz(e,f,{metadata:S,resource:x,authorizationCode:r,iss:o,scope:U,fetchFn:i});return await e.saveTokens({...te,issuer:v},L),"AUTHORIZED"}let X=ku(await e.tokens(L),v);if(X&&X.issuer===void 0)X={...X,issuer:v},await e.saveTokens(X,L);if(X?.refresh_token&&!l){let te;try{te=await tz(f,{metadata:S,clientInformation:w,refreshToken:X.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:i})}catch(se){if(se instanceof Lg)throw se;if(!(se instanceof Dr)||se.code===Ut.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(se instanceof Error?se.message:String(se))}`);else throw se}if(te)return await e.saveTokens({...te,issuer:v},L),"AUTHORIZED"}let Y=e.state?await e.state():void 0,{authorizationUrl:ce,codeVerifier:Ee}=await Qv(f,{metadata:S,clientInformation:w,state:Y,redirectUrl:e.redirectUrl,scope:U,resource:x});return await e.saveCodeVerifier(Ee),await e.redirectToAuthorization(ce),"REDIRECT"}function Jv(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Bv(e,t,r){let o=$f(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!Cf({requestedResource:o,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}var Wv=new Set(["bearer","dpop"]);function Ai(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!Wv.has(r.toLowerCase())||!o)return{};let n=vc(e,"resource_metadata")||void 0,s;if(n)try{s=new URL(n)}catch{}let i=vc(e,"scope")||void 0,a=vc(e,"error")||void 0,l=vc(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:i,error:a,errorDescription:l}}function vc(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=r.match(o);if(n){let s=n[1]||n[2];if(s)return s}return null}async function Dg(e,t,r=fetch){let o=await Yv(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Zo.parse(await o.json())}async function Fg(e,t,r=fetch){let o=Ni(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!zg)throw n;if(t)try{return await o(e,{})}catch(s){if(!(s instanceof TypeError))throw s;return}return}}function Kv(e,t="",r={}){if(t.endsWith("/"))t=t.slice(0,-1);return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function $g(e,t,r=fetch){return await Fg(e,{"MCP-Protocol-Version":t},r)}function Gv(e,t){if(!e)return!0;if(t==="/")return!1;return!e.ok&&e.status<500||e.status===502}async function Yv(e,t,r,o){let n=new URL(e),s=o?.protocolVersion??ho,i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{let l=Kv(t,n.pathname);i=new URL(l,o?.metadataServerUrl??n),i.search=n.search}let a=await $g(i,s,r);if(!o?.metadataUrl&&Gv(a,n.pathname))a=await $g(new URL(`/.well-known/${t}`,n),s,r);return a}function Xv(e){let t=typeof e==="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;if(n.endsWith("/"))n=n.slice(0,-1);return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Hg(e,{fetchFn:t=fetch,protocolVersion:r=ho,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},s=Xv(e);for(let{url:i,type:a}of s){let l=await Fg(i,n,t);if(!l)continue;if(!l.ok){if(await l.text?.().catch(()=>{}),l.status<500||l.status===502)continue;throw Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}let u=a==="oauth"?Ur.parse(await l.json()):Do.parse(await l.json());if(!o){let d=typeof e==="string"?e:e.href;if(!(u.issuer===d||d.endsWith("/")&&u.issuer===d.slice(0,-1)))throw new Eu("metadata",d,u.issuer)}return u}}async function Vg(e,t){let r,o;try{if(r=await Dg(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0)o=r.authorization_servers[0]}catch(s){if(s instanceof TypeError)throw s}if(!o)o=String(new URL("/",e));let n=await Hg(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function Nu(e){return typeof e==="string"?e:e.href}async function Qv(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(wu))throw Error(`Incompatible auth server: does not support response type ${wu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ru))throw Error(`Incompatible auth server: does not support code challenge method ${Ru}`)}else a=new URL("/authorize",e);let l=await bu(),{code_verifier:u,code_challenge:d}=l;if(a.searchParams.set("response_type",wu),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Ru),a.searchParams.set("redirect_uri",String(o)),s)a.searchParams.set("state",s);if(n)a.searchParams.set("scope",n);if(n?.split(" ").includes("offline_access"))a.searchParams.append("prompt","consent");if(i)a.searchParams.set("resource",Nu(i));return{authorizationUrl:a,codeVerifier:u}}function ez(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Jg(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,dpop:i,fetchFn:a}){let l=Dv(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s)r.set("resource",Nu(s));if(!n&&o)jv(Mv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let S=new Headers(u);if(n)await n(S,r,l,t);if(i)S.set("DPoP",await i.buildProof({htm:"POST",htu:l}));return Ni(a??fetch)(l,{method:"POST",headers:S,body:r})},m=await d();if(i&&m.status===400){if((await m.clone().json().catch(()=>{}))?.error===Ut.UseDpopNonce)i.observeNonce(m,l),m=await d()}if(i?.observeNonce(m,l),!m.ok)throw await Eg(m);let f=await m.json();try{return Fo.parse(nu(f))}catch(S){if(typeof f==="object"&&f!==null&&"error"in f)throw await Eg(JSON.stringify(f));throw S}}async function tz(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,dpop:i,fetchFn:a}){return{refresh_token:o,...await Jg(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:n,dpop:i,fetchFn:a})}}async function rz(e,t,{metadata:r,resource:o,authorizationCode:n,iss:s,scope:i,fetchFn:a}={}){if(n!==void 0)Ou({iss:s,expectedIssuer:r?.issuer,issParameterSupported:Iu(r)});let l=r?.issuer??String(t),u=async()=>{let S=await e.clientInformation({issuer:l}),b=ku(S,l,{canPersistStamp:!1});if(S&&b===void 0)throw new wc(String(S.issuer),l);return b},d=await u(),m=i??e.clientMetadata.scope,f;if(e.prepareTokenRequest)f=await e.prepareTokenRequest(m);if(!f){if(!n)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");f=ez(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),Jg(t,{metadata:r,tokenRequestParams:f,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function oz(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let s;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let i={...r,...o===void 0?{}:{scope:o}},a=await Ni(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new $v({status:a.status,body:await a.text(),submittedMetadata:i});return Vo.parse(nu(await a.json()))}var zc=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),nz=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(Pu(e))}set(e,t){let r=Pu(e),o=zc.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let i of this._entries.keys())if(!zc.has(i.slice(0,i.indexOf("\x00")))){this._entries.delete(i),this._cappedSize--;break}}let s=++this._stamp;if(this._entries.set(r,{...t,stamp:s}),n&&!o)this._cappedSize++;return s}delete(e){if(this._entries.delete(Pu(e))&&!zc.has(e.method))this._cappedSize--}evict(e){let t=`${e}\x00`,r=zc.has(e);for(let o of this._entries.keys())if(o.startsWith(t)){if(this._entries.delete(o),!r)this._cappedSize--}}clear(){this._entries.clear(),this._cappedSize=0}};function Pu(e){return`${e.method}\x00${JSON.stringify([e.partition??"",e.params??""])}`}function Tu(e,t){return t===void 0?e:`${e}\x00${t}`}var sz=86400000,iz=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},o="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=o,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},o=this._partitionFor("private"),n=await this._store.get({...r,partition:o});if(n!==void 0)return n;let s=this._partitionFor("public");if(s===o)return;let i=await this._store.get({...r,partition:s});return i?.scope==="public"?i:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(n){this._reportError(n)}if(o!==r)try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}}async evictKey(e,t){let r=Tu(e,t),o=this._evictionGeneration.get(r);if(o!==void 0)this._evictionGeneration.set(r,o+1);await this._deleteBoth(e,t)}captureGeneration(e,t){let r=Tu(e,t),o=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,o),o}async write(e,t,r,o){if((this._evictionGeneration.get(Tu(e,o?.params))??0)!==r)return;let n=o?.params??"",s=this._partitionFor("private"),i=this._partitionFor("public"),a=(o?.scope??"private")==="public"?i:s;try{await this._store.set({method:e,params:n,partition:a},{value:az(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(i!==s)try{await this._store.delete({method:e,params:n,partition:a===s?i:s})}catch(l){this._reportError(l)}}async read(e,t){let r=await this._probe(e,t);if(r?.expiresAt===void 0||!(r.expiresAt>this.now()))return;try{let o=JSON.parse(r.value);if(typeof o!=="object"||o===null||Array.isArray(o))throw TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){if(!this._isUserSupplied)this._store.clear();this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),o=new Map;if(r!==void 0)for(let n of r.tools)o.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let o=this._decodeListTools(r)??{tools:[]},n=new Map;for(let s of o.tools){let i=t(s);if(i!==void 0)n.set(s.name,i)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every((r)=>r!==null&&typeof r==="object"))throw TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function az(e){let t;try{t=JSON.stringify(e)}catch(r){throw TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!=="string")throw TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var Bg=Symbol.for("mcp.authSeamEscape");function Xe(e){if(typeof e==="object"&&e!==null||typeof e==="function")try{Object.defineProperty(e,Bg,{value:!0,configurable:!0})}catch{}return e}function cz(e){return(typeof e==="object"&&e!==null||typeof e==="function")&&e[Bg]===!0}var lz=-32022,uz=new Set([-32001,-32020,-32021]);function dz(e,t){switch(e.kind){case"result":return pz(e.result,t);case"rpc-error":return Wg(e,t);case"http-error":return hz(e,t);case"network-error":return Cg(e.error,t);case"unusable-reply":return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${Kg(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":if(t.transportKind==="stdio")return{kind:"legacy"};return Cg(Error("Connection closed during the version negotiation probe"),t);case"timeout":if(t.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new N(O.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function pz(e,t){let r=Lt(gc).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find((s)=>o.includes(s));if(n!==void 0)return{kind:"modern",version:n,discover:r.value};if(t.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new fc({supported:[...o],requested:t.requestedVersion})}}function Wg(e,t){let{code:r,message:o,data:n}=e;if(r===lz){let s=fz(n);if(s===void 0)return{kind:"legacy"};let i=new fc({supported:s,requested:gz(n)??t.requestedVersion},o),a=Oi(s),l=t.clientModernVersions.find((u)=>a.includes(u));if(l!==void 0)return{kind:"corrective",version:l,error:i};if(a.length>0)return{kind:"error",error:i};return t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:i}}if(uz.has(r))return{kind:"legacy"};return{kind:"legacy"}}function hz(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new vt(o?O.ClientHttpForbidden:O.ClientHttpAuthentication,`Version negotiation failed: ${o?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new vt(O.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=Sz(e.body);if(r!==void 0)return Wg(r,t);return{kind:"legacy"}}function Cg(e,t){if(t.environment==="browser"&&mz(e))return{kind:"legacy"};return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: ${Kg(e)}`,{cause:e},{cause:e})}}function mz(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function Kg(e){return e instanceof Error?e.message:String(e)}function fz(e){if(typeof e!=="object"||e===null)return;let t=e.supported;if(!Array.isArray(t)||t.length===0||!t.every((r)=>typeof r==="string"))return;return t}function gz(e){if(typeof e!=="object"||e===null)return;let t=e.requested;return typeof t==="string"?t:void 0}function Sz(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=="object"||t===null)return;let r=t.error;if(typeof r!=="object"||r===null)return;let{code:o,message:n,data:s}=r;if(typeof o!=="number")return;return{code:o,message:typeof n==="string"?n:"",data:s}}var _z="legacy";function bz(e,t){let r=e?.mode??_z;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r==="object"){if(!Zt(r.pin))throw TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:o}}let n=t?Oi(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...su],fallbackAvailable:t?iu(t).length>0:!0,probe:o}}function Ig(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Og(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var yz=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new e(t);t.onmessage=(o)=>{let n=r._pending;if(n!==void 0&&(Bo(o)||Wo(o))&&o.id===n.id){if(r._pending=void 0,Bo(o))n.resolve({kind:"response",result:o.result});else n.resolve({kind:"response",error:o.error});return}},t.onerror=(o)=>{r._savedOnError?.(o)},t.onclose=()=>{let o=r._pending;if(o!==void 0)r._pending=void 0,o.resolve({kind:"closed"});r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(o){throw r.detach(),o}return r}async exchange(t,r){let o=`server-discover-probe-${++this._probeCounter}`;return new Promise((n)=>{let s=!1,i=(l)=>{if(s)return;if(s=!0,clearTimeout(a),this._pending?.id===o)this._pending=void 0;n(l)},a=setTimeout(()=>i({kind:"timeout"}),r);this._pending={id:o,resolve:i},this._transport.send(t(o)).catch((l)=>i({kind:"send-error",error:l}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,o=!1,n=()=>{if(!o){o=!0;return}t()};r.onclose=n,Cu.set(r,()=>{if(r.onclose===n)r.onclose=t})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,o=!0;t.start=async function(){if(o){o=!1,t.start=r;return}return r.call(t)}}},Cu=new WeakMap;function Ng(e){let t=Cu.get(e);Cu.delete(e),t?.()}function vz(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Lt(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function zz(e){if(e instanceof N&&e.code===O.ClientHttpUnexpectedContent)return!0;return e instanceof Error&&e.name==="SyntaxError"}function wz(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(cz(r)||r instanceof wt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof vt){let o=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof o==="string"?o:void 0,statusText:r.data.statusText}}if(zz(r))return{kind:"unusable-reply",error:r};return{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Gg(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,s=e.kind==="auto"&&e.fallbackAvailable,i=await yz.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let f=await i.exchange((y)=>vz(y,u,t.clientInfo,t.capabilities),r);if(f.kind==="timeout"&&m>0){m--;continue}let S=wz(f,r),b=dz(S,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:s,environment:t.environment,transportKind:t.transportKind});switch(b.kind){case"modern":return{era:"modern",version:b.version,discover:b.discover};case"corrective":if(d)throw b.error;d=!0,u=b.version;continue;case"legacy":{let y=S.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new N(O.EraNegotiationFailed,y===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${y} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new N(O.EraNegotiationFailed,y===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${y} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(y!==void 0&&t.disposableProbe!==!0)throw new N(O.EraNegotiationFailed,`Version negotiation failed: ${y} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw b.error}}},l;try{l=await a()}catch(u){throw i.detach(),u}return i.release(),l}function Rz(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r==="object"&&r!==null&&typeof r.command==="string"?r:void 0}async function xz(e,t,r,o){let s=new t.constructor({...r,stderr:"ignore"}),i=t.close,a=!1,l,u=new Promise((m,f)=>{l=()=>f(qg())});t.close=async function(){return a=!0,l?.(),i.call(t)};let d;try{let m=Gg(e,{...o,transport:s,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await Pz(s),t.close=i}if(a)throw qg();return d}function qg(){return new N(O.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Pz(e){try{let t=e._dispose;await(typeof t==="function"?t.call(e):e.close())}catch{}}function Ag(e){let t=e._meta?.[Ot];return ug.Implementation(t)?t:void 0}function Rc(e,t){if(!e||t===null||typeof t!=="object")return;if(e.type==="object"&&e.properties&&typeof e.properties==="object"){let r=t,o=e.properties;for(let n of Object.keys(o)){let s=o[n];if(r[n]===void 0&&Object.prototype.hasOwnProperty.call(s,"default"))r[n]=s.default;if(r[n]!==void 0)Rc(s,r[n])}}if(Array.isArray(e.anyOf)){for(let r of e.anyOf)if(typeof r!=="boolean")Rc(r,t)}if(Array.isArray(e.oneOf)){for(let r of e.oneOf)if(typeof r!=="boolean")Rc(r,t)}}function Tz(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function Ez(e){if(typeof e==="object"&&e!==null){if(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e))return e;if(e.kind==="modern"&&rr.safeParse(e.discover).success)return e}throw new N(O.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Mg={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},kz=64,Yg=class extends bc{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new N(O.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t);if(this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Su,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=ig(t?.inputRequired),this._cache=new iz(t?.responseCacheStore??new nz,t?.responseCacheStore!==void 0,(r)=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??kz,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Zt(this._negotiatedProtocolVersion)&&Fr(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new N(O.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}));return pg({getRequestHandler:(r)=>this._getRequestHandler(r),buildContext:(r)=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t)}_setupListChangedHandlers(e){if(e.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools);if(e.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts);if(e.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=dg(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){if(e==="elicitation/create")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),s=n.validateRequest("elicitation/create",r);if(!s.ok&&s.reason==="not-in-era")s=n.validateInputRequest("elicitation/create",r);if(!s.ok)throw new ee(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${s.message}`);let{params:i}=s.value;i.mode=i.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=Tz(this._capabilities.elicitation);if(i.mode==="form"&&!a)throw new ee(W.InvalidParams,"Client does not support form-mode elicitation requests");if(i.mode==="url"&&!l)throw new ee(W.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,o),d=n.validateResult("elicitation/create",u);if(!d.ok&&d.reason==="not-in-era")d=n.validateInputResponse("elicitation/create",u);if(!d.ok)throw new ee(d.reason==="not-in-era"?W.InternalError:W.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let m=d.value,f=i.mode==="form"?i.requestedSchema:void 0;if(i.mode==="form"&&m.action==="accept"&&m.content&&f&&this._capabilities.elicitation?.form?.applyDefaults)try{Rc(f,m.content)}catch{}return m};if(e==="sampling/createMessage")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),s=n.validateRequest("sampling/createMessage",r);if(!s.ok&&s.reason==="not-in-era")s=n.validateInputRequest("sampling/createMessage",r);if(!s.ok)throw new ee(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${s.message}`);let{params:i}=s.value,a=await t(r,o),l=Boolean(i.tools||i.toolChoice),u=n.samplingResultVariant(l,a);if(!u.ok&&u.reason==="not-in-era")u=n.validateInputResponse("sampling/createMessage",a);if(!u.ok)throw new ee(u.reason==="not-in-era"?W.InternalError:W.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value};return t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new N(O.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,Ez(t.prior),t);let r=bz(this._versionNegotiation,this._supportedProtocolVersionsOption);if(r.kind!=="legacy")return this._connectNegotiated(e,r,t);return this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;if(r!==void 0)e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=iu(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new N(O.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!r.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);if(this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion)e.setProtocolVersion(n.protocolVersion);if(this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;if(n!==void 0&&e.setProtocolVersion)e.setProtocolVersion(n);return}this._resetConnectionState();let o;try{let n=Og(e),s={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Ig(),defaultTimeoutMs:r?.timeout??_c},i=n==="stdio"?Rz(e):void 0;o=i===void 0?await Gg(t,{...s,transport:e,transportKind:n}):await xz(t,e,i,s)}catch(n){throw await e.close().catch(()=>{}),Ng(e),n}if(Ng(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=Ag(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion)e.setProtocolVersion(o.version);if(this._listChangedConfig){let n=this._listChangedConfig,s=this._serverCapabilities,i={...n.tools&&s?.tools?.listChanged&&{tools:n.tools},...n.prompts&&s?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&s?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(i)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let l=a?{...i.tools&&{toolsListChanged:!0},...i.prompts&&{promptsListChanged:!0},...i.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(l).length>0){let u=new AbortController,d=()=>u.abort(r?.signal?.reason);if(r?.signal?.aborted)d();r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(l,{timeout:r?.timeout,signal:u.signal})}catch(m){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),m;this.onerror?.(m instanceof Error?m:Error(String(m)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let o=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,s=(n&&Oi(n).length>0?Oi(n):su).find((i)=>o.supportedVersions.includes(i));if(s===void 0)throw new N(O.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=o,this._serverCapabilities=o.capabilities,this._serverVersion=Ag(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=s,e.setProtocolVersion?.(s),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(i){this.onerror?.(i instanceof Error?i:Error(String(i)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;if(t!==void 0)return`${t.name}@${t.version}`;return e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return Zt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new N(O.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new N(O.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new N(O.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new N(O.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new N(O.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new N(O.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new N(O.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new N(O.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new N(O.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new N(O.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},rr,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("prompts/list",e,t,(o)=>o.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/list",e,t,(o)=>o.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/templates/list",e,t,(o)=>o.resourceTemplates)}async _listAllPages(e,t,r,o,n){let s=r?.cacheMode==="bypass",i=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},r),l=a.nextCursor,u=a,d=1;while(l!==void 0){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new N(O.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let m=await this.request({method:e,params:{...t,cursor:l}},r);if(m.nextCursor===l&&JSON.stringify(o(m))===JSON.stringify(o(u)))break;o(a).push(...o(m)),u=m,l=m.nextCursor,d++}if(delete a.nextCursor,n?.(a),s)return a;return await this._cache.write(e,a,i,this._freshness(a)),a}_freshness(e,t){let r=e,o=typeof r.ttlMs==="number"?r.ttlMs:this._defaultCacheTtlMs,n=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),sz),scope:n,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let o=await this._cache.read(e,t).catch((n)=>void this._reportStoreError(n));if(o!==void 0){if(r?.signal?.aborted){let n=r.signal.reason;throw n instanceof N?n:new N(O.RequestTimeout,String(n))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(!e.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:hu(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let o=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let s=this._freshness(n,e.uri);if(s.expiresAt>this._cache.now())await this._cache.write("resources/read",n,o,s);else if(t?.cacheMode==="refresh")await this._cache.evictKey("resources/read",e.uri)}return n}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new N(O.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Zt(r))throw new N(O.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let x=t.signal.reason;throw x instanceof N?x:new N(O.RequestTimeout,String(x))}let o=new AbortController,n=`listen:${this._nextListenId++}`,s="opening",i,a,l,u,d=new Promise((x,U)=>{l=x,u=U}),m,f=new Promise((x)=>{m=x}),S=(x)=>{if(s==="closed")return;let U=s==="opening";if(i!==void 0)clearTimeout(i),i=void 0;if("ack"in x){s="open",l(x.ack);return}if(s="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(n),o.abort(),m(x.cause),U)u(x.error??new N(O.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},b=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},y=async()=>{if(s==="closed")return;S({cause:"local"}),await b()};this._listenState.set(n,{settle:S});let v=t?.timeout??_c;if(i=setTimeout(()=>{S({cause:"remote",error:new N(O.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),b().catch(()=>{})},v),t?.signal){let x=t.signal;a=()=>{if(s==="closed")return;let U=x.reason;S({cause:"local",error:U instanceof Error?U:Error(String(U??"Aborted"))}),b().catch(()=>{})},x.addEventListener("abort",a,{once:!0})}let L={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},F=(x)=>{S({cause:"remote",error:x instanceof Error?x:Error(String(x))})};try{this.transport.send(L,{requestSignal:o.signal,onRequestStreamEnd:()=>S({cause:"remote",error:Error("subscriptions/listen: stream ended")})}).catch(F)}catch(x){F(x)}return{honoredFilter:await d,close:y,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(Mg,e.method)?Mg[e.method]:void 0;if(e.method==="notifications/resources/updated"){let o=e.params?.uri;if(typeof o==="string")this._cache.evictKey("resources/read",o)}else if(r!==void 0)for(let o of r)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){let o=e.params?._meta?.[Wn],n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){let s=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:s.ok?s.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let o=e.params?.requestId,n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){n.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t==="string"?this._listenState.get(t):void 0;if(r!==void 0){if(Wo(e))r.settle({cause:"remote",error:ee.fromError(e.error.code,e.error.message,e.error.data)});else r.settle({cause:"graceful",error:new N(O.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new N(O.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&Ig()!=="browser",o=async()=>{if(!r)return t;let l;try{l=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!l?.valid||l.declarations.length===0)return t;let u=og(l.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,(l)=>this._compileOutputValidator(l)).catch((l)=>void this._reportStoreError(l)):this._compileOutputValidator(t.toolDefinition),s=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new ee(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};s();let i;try{i=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof ee&&l.code===Jo;if(!r||!u||t?.toolDefinition!==void 0)throw l;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch((m)=>this._reportStoreError(m)),n=await this._cache.outputValidator(e.name,(m)=>this._compileOutputValidator(m)).catch((m)=>void this._reportStoreError(m)),s(),i=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(i.structuredContent===void 0&&!i.isError)throw new ee(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent!==void 0&&!i.isError)try{let l=a(i.structuredContent);if(!l.valid)throw new ee(W.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){if(l instanceof ee)throw l;throw new ee(W.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return i}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}let r=await this._serveFromCache("tools/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("tools/list",e,t,(o)=>o.tools,(o)=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||Og(this.transport)==="stdio")return;let t=e.tools.filter((r)=>{let o=hu(r.inputSchema);if(!o.valid)return console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration — ${o.reason}`),!1;return!0});if(t.length!==e.tools.length)e.tools=t}_setupListChangedHandler(e,t,r,o){let n=Sc(Hs,r);if(!n.success)throw Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof r.onChanged!=="function")throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:i}=n.data,{onChanged:a}=r,l=async()=>{if(!s){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:Error(String(d)),null)}},u=()=>{if(i){let d=this._listChangedDebounceTimers.get(e);if(d)clearTimeout(d);let m=setTimeout(l,i);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function $z(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Cz(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return $z(t)&&/use_dpop_nonce/i.test(t)}var Iz=(e,t)=>(r)=>{let o=typeof e==="function"?e:()=>e;return async(n,s)=>{let i=(s?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,s);let u=async()=>{let m=await t();if(!m)return r(n,s);let f=new Headers(s?.headers),S=await l.buildProof({htm:i,htu:a,accessToken:m});return f.set("Authorization",`DPoP ${m}`),f.set("DPoP",S),r(n,{...s,headers:f})},d=await u();if(Cz(d)&&d.headers.has("dpop-nonce"))l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u();return l.observeNonce(d,a),d}},Oz=(e)=>Iz(async()=>{try{return await e.dpop?.()}catch(t){throw Xe(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw Xe(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var _P=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r){super(`SSE error: ${t}`);this.code=e,this.event=r,Zr(this,new.target)}};var Nz=1,qz={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},Az=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function jg(e,t){if(typeof AbortSignal.any==="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",s)};function n(){o(),r.abort(e.reason)}function s(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",s,{once:!0}),r.signal}var Xg=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Cv(t?.authProvider)){if(this._oauthProvider=t.authProvider,this._authProvider=Ov(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop)this._fetch=Oz(t.authProvider)(t.fetch??fetch)}else this._authProvider=t?.authProvider;if(this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=mg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=Sg(this._fetchWithInit);this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??qz,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Nz)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw Xe(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Tg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Tg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new vt(O.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});if(e.resourceMetadataUrl)this._resourceMetadataUrl=e.resourceMetadataUrl;let r=await this._oauthProvider.tokens(),o=zu(this._scope,r?.scope,e.scope);this._scope=o;let n=Nv(o,r?.scope);return $u(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Ni(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:_g(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(r){throw Xe(r)}if(t)e.set("Authorization",`Bearer ${t}`);if(this._sessionId)e.set("mcp-session-id",this._sessionId);if(this._protocolVersion)e.set("mcp-protocol-version",this._protocolVersion);return e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Fr(t))return;let r=t.params?._meta?.[It];if(typeof r!=="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=ng(t.method,t.params);if(o?.value!==void 0)e.set("mcp-name",mu(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Fr(e))return!1;let t=e.params?._meta?.[It];return typeof t==="string"&&Zt(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,s=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let i=await this._commonHeaders(),a=[...i.get("accept")?.split(",").map((m)=>m.trim().toLowerCase())??[],"text/event-stream"];if(i.set("accept",[...new Set(a)].join(", ")),o)i.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?jg(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:i,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:S}=Ai(d);this._resourceMetadataUrl=f,this._scope=zu(this._scope,S)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(f){throw Xe(f)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await d.text?.().catch(()=>{}),t)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}));throw Xe(new wt)}if(d.status===403){let{resourceMetadataUrl:f,scope:S,error:b,errorDescription:y}=Ai(d);if(b==="insufficient_scope"){let v=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:S,resourceMetadataUrl:f,errorDescription:y,statusText:d.statusText,text:v},r)!=="AUTHORIZED")throw Xe(new wt);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let m=this._unfollowedRedirect(this._url,d)??d.statusText;throw new vt(O.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(i){if(!s())this.onerror?.(i);throw i}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),n=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this._startOrAuthSse(e).catch((s)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`));try{this._scheduleReconnection(e,t+1)}catch(i){this.onerror?.(i instanceof Error?i:Error(String(i)))}})};if(this._reconnectionScheduler){let s=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof s==="function"?s:void 0}else{let s=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(s)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i}=t,a=()=>this._abortController?.signal.aborted===!0||s?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let f=e.pipeThrough(new TextDecoderStream).pipeThrough(new vu({onRetry:(S)=>{this._serverRetryMs=S}})).getReader();while(!0){let{value:S,done:b}=await f.read();if(b)break;if(S.id)l=S.id,u=!0,o?.(S.id);if(!S.data)continue;if(!S.event||S.event==="message")try{let y=st.parse(JSON.parse(S.data));if(Bo(y)||Wo(y)){if(d=!0,n!==void 0)y.id=n}this.onmessage?.(y)}catch(y){this.onerror?.(y)}}if((r||u)&&!d&&this._abortController&&!a())this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0);else if(!a())i?.()}catch(f){if(a())return;if(this.onerror?.(Error(`SSE stream disconnected: ${f}`)),(r||u)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0)}catch(S){this.onerror?.(Error(`Failed to reconnect: ${S instanceof Error?S.message:String(S)}`)),i?.()}else i?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new wt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await qv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await $u(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new wt("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,o=0){try{let{resumptionToken:n,onresumptiontoken:s}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Fr(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((v)=>this.onerror?.(v));return}let i=await this._commonHeaders();this._applyBodyDerivedHeaders(i,e);let a=Array.isArray(e)?e.some((v)=>pu(v)):pu(e);if(a)i.delete("mcp-session-id");if(t?.headers!==void 0)for(let[v,L]of Object.entries(t.headers)){if(Az.has(v.toLowerCase()))continue;i.set(v,L)}i.set("content-type","application/json");let l=[...i.get("accept")?.split(",").map((v)=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];i.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?jg(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:d},f=await this._redirects(this._fetch??fetch)(this._url,m);if(a&&f.ok)this._sessionId=f.headers.get("mcp-session-id")||void 0;if(!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has("www-authenticate")){let{resourceMetadataUrl:F,scope:x}=Ai(f);this._resourceMetadataUrl=F,this._scope=zu(this._scope,x)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(F){throw Xe(F)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await f.text?.().catch(()=>{}),r)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:f.statusText}));throw Xe(new wt)}let v=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:F,scope:x,error:U,errorDescription:R}=Ai(f);if(U==="insufficient_scope"){if(await this._stepUpAuthorize({scope:x,resourceMetadataUrl:F,errorDescription:R,statusText:f.statusText,text:v},o)!=="AUTHORIZED")throw Xe(new wt);return this._send(e,t,r,o+1)}}if(f.status===400&&typeof v==="string"&&this._isModernEnvelopedRequest(e))try{let F=st.parse(JSON.parse(v)),x=(Array.isArray(e)?e:[e]).filter((U)=>Fr(U));if(Wo(F)&&x.some((U)=>U.id===F.id)){this.onmessage?.(F);return}}catch{}let L=this._unfollowedRedirect(this._url,f)??v;throw new vt(O.ClientHttpNotImplemented,`Error POSTing to endpoint: ${L}`,{status:f.status,statusText:f.statusText,text:v})}if(f.status===202){if(await f.text?.().catch(()=>{}),eg(e))this._startOrAuthSse({resumptionToken:void 0}).catch((v)=>this.onerror?.(v));return}let S=(Array.isArray(e)?e:[e]).some((v)=>("method"in v)&&("id"in v)&&v.id!==void 0),b=f.headers.get("content-type"),y=hg(b);if(S)if(y==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:s,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await f.json(),L=Array.isArray(v)?v.map((F)=>st.parse(F)):[st.parse(v)];for(let F of L)this.onmessage?.(F)}else throw await f.text?.().catch(()=>{}),new N(O.ClientHttpUnexpectedContent,`Unexpected content type: ${b}`,{contentType:b});else await f.text?.().catch(()=>{})}catch(n){if(t?.requestSignal?.aborted!==!0)this.onerror?.(n);throw n}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new vt(O.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};class nS{_eventSlots=new Map;setHandler(e,t){let r=this._ensureEventSlot(e);if(r.onHandler&&t)console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`);r.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let r=this._eventSlots.get(e);if(!r)return;let o=r.listeners.indexOf(t);if(o!==-1)r.listeners.splice(o,1)}dispatch(e,t){let r=this._eventSlots.get(e);if(!r)return;r.onHandler?.(t);for(let o of[...r.listeners])o(t)}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t)t={listeners:[]},this._eventSlots.set(e,t);return t}}class sS{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}}var Qg=new Set;function eS(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!=="string")return;let s=n.method.value,i=e==="request"?"setRequestHandler":"setNotificationHandler";if(!Qg.has(i))Qg.add(i),console.warn(`[ext-apps] ${i}(Schema, handler) is deprecated; use ${i}("${s}", { params: Schema.shape.params }, handler).`);let a=o;return[s,{params:n.params},e==="request"?(l,u)=>a({method:s,params:l},Mz(u)):(l)=>a({method:s,params:l})]}function Mz(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var iS="2026-01-26";var jz="ui/notifications/tool-input-partial";var Lz=T([h("light"),h("dark")]).describe("Color theme preference for the host environment."),ji=T([h("inline"),h("fullscreen"),h("pip")]).describe("Display mode for UI presentation."),Uz=T([h("--color-background-primary"),h("--color-background-secondary"),h("--color-background-tertiary"),h("--color-background-inverse"),h("--color-background-ghost"),h("--color-background-info"),h("--color-background-danger"),h("--color-background-success"),h("--color-background-warning"),h("--color-background-disabled"),h("--color-text-primary"),h("--color-text-secondary"),h("--color-text-tertiary"),h("--color-text-inverse"),h("--color-text-ghost"),h("--color-text-info"),h("--color-text-danger"),h("--color-text-success"),h("--color-text-warning"),h("--color-text-disabled"),h("--color-border-primary"),h("--color-border-secondary"),h("--color-border-tertiary"),h("--color-border-inverse"),h("--color-border-ghost"),h("--color-border-info"),h("--color-border-danger"),h("--color-border-success"),h("--color-border-warning"),h("--color-border-disabled"),h("--color-ring-primary"),h("--color-ring-secondary"),h("--color-ring-inverse"),h("--color-ring-info"),h("--color-ring-danger"),h("--color-ring-success"),h("--color-ring-warning"),h("--font-sans"),h("--font-mono"),h("--font-weight-normal"),h("--font-weight-medium"),h("--font-weight-semibold"),h("--font-weight-bold"),h("--font-text-xs-size"),h("--font-text-sm-size"),h("--font-text-md-size"),h("--font-text-lg-size"),h("--font-heading-xs-size"),h("--font-heading-sm-size"),h("--font-heading-md-size"),h("--font-heading-lg-size"),h("--font-heading-xl-size"),h("--font-heading-2xl-size"),h("--font-heading-3xl-size"),h("--font-text-xs-line-height"),h("--font-text-sm-line-height"),h("--font-text-md-line-height"),h("--font-text-lg-line-height"),h("--font-heading-xs-line-height"),h("--font-heading-sm-line-height"),h("--font-heading-md-line-height"),h("--font-heading-lg-line-height"),h("--font-heading-xl-line-height"),h("--font-heading-2xl-line-height"),h("--font-heading-3xl-line-height"),h("--border-radius-xs"),h("--border-radius-sm"),h("--border-radius-md"),h("--border-radius-lg"),h("--border-radius-xl"),h("--border-radius-full"),h("--border-width-regular"),h("--shadow-hairline"),h("--shadow-sm"),h("--shadow-md"),h("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Zz=P(Uz.describe(`Style variables for theming MCP apps.
82
81
 
83
82
  Individual style keys are optional - hosts may provide any subset of these values.
84
83
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
85
84
 
86
85
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
87
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),q.union([q.string(),q.undefined()]).describe(`Style variables for theming MCP apps.
86
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),T([c(),Vl()]).describe(`Style variables for theming MCP apps.
88
87
 
89
88
  Individual style keys are optional - hosts may provide any subset of these values.
90
89
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -96,10 +95,10 @@ Individual style keys are optional - hosts may provide any subset of these value
96
95
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
97
96
 
98
97
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
99
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),VO=q.object({method:q.literal("ui/open-link"),params:q.object({url:q.string().describe("URL to open in the host's browser")})}),UO=q.object({isError:q.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),wO=q.object({isError:q.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),zO=q.object({isError:q.boolean().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),ZO=q.object({method:q.literal("ui/notifications/sandbox-proxy-ready"),params:q.object({})}),pB=q.object({connectDomains:q.array(q.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
98
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Dz=p({method:h("ui/open-link"),params:p({url:c().describe("URL to open in the host's browser")})}),Fz=p({isError:E().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),Hz=p({isError:E().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),Vz=p({isError:E().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),Jz=p({method:h("ui/notifications/sandbox-proxy-ready"),params:p({})}),qu=p({connectDomains:g(c()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
100
99
 
101
100
  - Maps to CSP \`connect-src\` directive
102
- - Empty or omitted → no network connections (secure default)`),resourceDomains:q.array(q.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:q.array(q.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:q.array(q.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),dB=q.object({camera:q.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:q.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:q.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:q.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),PO=q.object({method:q.literal("ui/notifications/size-changed"),params:q.object({width:q.number().optional().describe("New width in pixels."),height:q.number().optional().describe("New height in pixels.")})}),_w=q.object({method:q.literal("ui/notifications/tool-input"),params:q.object({arguments:q.record(q.string(),q.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),Fw=q.object({method:q.literal("ui/notifications/tool-input-partial"),params:q.object({arguments:q.record(q.string(),q.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),Ew=q.object({method:q.literal("ui/notifications/tool-cancelled"),params:q.object({reason:q.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),bO=q.object({fonts:q.string().optional()}),IO=q.object({variables:OO.optional().describe("CSS variables for theming the app."),css:bO.optional().describe("CSS blocks that apps can inject.")}),Aw=q.object({method:q.literal("ui/resource-teardown"),params:q.object({})}),LO=q.record(q.string(),q.unknown()),XM=q.object({text:q.object({}).optional().describe("Host supports text content blocks."),image:q.object({}).optional().describe("Host supports image content blocks."),audio:q.object({}).optional().describe("Host supports audio content blocks."),resource:q.object({}).optional().describe("Host supports resource content blocks."),resourceLink:q.object({}).optional().describe("Host supports resource link content blocks."),structuredContent:q.object({}).optional().describe("Host supports structured content.")}),jO=q.object({method:q.literal("ui/notifications/request-teardown"),params:q.object({}).optional()}),TO=q.object({experimental:q.record(q.string(),q.record(q.string(),q.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:q.object({}).optional().describe("Host supports opening external URLs."),downloadFile:q.object({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:q.object({listChanged:q.boolean().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:q.object({listChanged:q.boolean().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:q.object({}).optional().describe("Host accepts log messages."),sandbox:q.object({permissions:dB.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:pB.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:XM.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:XM.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:q.object({tools:q.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),$O=q.object({experimental:q.record(q.string(),q.record(q.string(),q.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:q.object({listChanged:q.boolean().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:q.array(H4).optional().describe("Display modes the app supports.")}),RO=q.object({method:q.literal("ui/notifications/initialized"),params:q.object({}).optional()}),Ow=q.object({csp:pB.optional().describe("Content Security Policy configuration for UI resources."),permissions:dB.optional().describe("Sandbox permissions requested by the UI resource."),domain:q.string().optional().describe(`Dedicated origin for view sandbox.
101
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:g(c()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:g(c()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:g(c()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Au=p({camera:p({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:p({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:p({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:p({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Bz=p({method:h("ui/notifications/size-changed"),params:p({width:z().optional().describe("New width in pixels."),height:z().optional().describe("New height in pixels.")})}),jP=p({method:h("ui/notifications/tool-input"),params:p({arguments:P(c(),A().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),LP=p({method:h("ui/notifications/tool-input-partial"),params:p({arguments:P(c(),A().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),UP=p({method:h("ui/notifications/tool-cancelled"),params:p({reason:c().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),Wz=p({fonts:c().optional()}),Kz=p({variables:Zz.optional().describe("CSS variables for theming the app."),css:Wz.optional().describe("CSS blocks that apps can inject.")}),ZP=p({method:h("ui/resource-teardown"),params:p({})}),Gz=P(c(),A()),tS=p({text:p({}).optional().describe("Host supports text content blocks."),image:p({}).optional().describe("Host supports image content blocks."),audio:p({}).optional().describe("Host supports audio content blocks."),resource:p({}).optional().describe("Host supports resource content blocks."),resourceLink:p({}).optional().describe("Host supports resource link content blocks."),structuredContent:p({}).optional().describe("Host supports structured content.")}),Yz=p({method:h("ui/notifications/request-teardown"),params:p({}).optional()}),Xz=p({experimental:P(c(),P(c(),Aa()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:p({}).optional().describe("Host supports opening external URLs."),downloadFile:p({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:p({listChanged:E().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:p({listChanged:E().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:p({}).optional().describe("Host accepts log messages."),sandbox:p({permissions:Au.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:qu.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:tS.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:tS.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:p({tools:p({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),Qz=p({experimental:P(c(),P(c(),Aa()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:p({listChanged:E().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:g(ji).optional().describe("Display modes the app supports.")}),ew=p({method:h("ui/notifications/initialized"),params:p({}).optional()}),DP=p({csp:qu.optional().describe("Content Security Policy configuration for UI resources."),permissions:Au.optional().describe("Sandbox permissions requested by the UI resource."),domain:c().optional().describe(`Dedicated origin for view sandbox.
103
102
 
104
103
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
105
104
 
@@ -107,18 +106,18 @@ Useful when views need stable, dedicated origins for OAuth callbacks, CORS polic
107
106
  - Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
108
107
  - URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)
109
108
 
110
- If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:q.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.
109
+ If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:E().optional().describe(`Visual boundary preference - true if view prefers a visible border.
111
110
 
112
111
  Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.
113
112
 
114
113
  - \`true\`: request visible border + background
115
114
  - \`false\`: request no visible border + background
116
- - omitted: host decides border`)}),YM=q.object({method:q.literal("ui/request-display-mode"),params:q.object({mode:H4.describe("The display mode being requested.")})}),JM=q.object({mode:H4.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),CO=q.union([q.literal("model"),q.literal("app")]).describe("Tool visibility scope - who can access the tool."),Vw=q.object({resourceUri:q.string().optional(),visibility:q.array(CO).optional().describe(`Who can access this tool. Default: ["model", "app"]
115
+ - omitted: host decides border`)}),rS=p({method:h("ui/request-display-mode"),params:p({mode:ji.describe("The display mode being requested.")})}),oS=p({mode:ji.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),tw=T([h("model"),h("app")]).describe("Tool visibility scope - who can access the tool."),FP=p({resourceUri:c().optional(),visibility:g(tw).optional().describe(`Who can access this tool. Default: ["model", "app"]
117
116
  - "model": Tool visible to and callable by the agent
118
- - "app": Tool callable by the app from this server only`),csp:q.never().optional(),permissions:q.never().optional()}),Uw=q.object({mimeTypes:q.array(q.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),SO=q.object({method:q.literal("ui/download-file"),params:q.object({contents:q.array(q.union([M8,q8])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),kO=q.object({method:q.literal("ui/message"),params:q.object({role:q.literal("user").describe('Message role, currently only "user" is supported.'),content:q.array(h0).describe("Message content blocks (text, image, etc.).")})}),ww=q.object({method:q.literal("ui/notifications/sandbox-resource-ready"),params:q.object({html:q.string().describe("HTML content to load into the inner iframe."),sandbox:q.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:pB.optional().describe("CSP configuration from resource metadata."),permissions:dB.optional().describe("Sandbox permissions from resource metadata.")})}),zw=q.object({method:q.literal("ui/notifications/tool-result"),params:RW.describe("Standard MCP tool execution result.")}),GM=q.object({toolInfo:q.object({id:O0.optional().describe("JSON-RPC id of the tools/call request."),tool:$W.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:EO.optional().describe("Current color theme preference."),styles:IO.optional().describe("Style configuration for theming the app."),displayMode:H4.optional().describe("How the UI is currently displayed."),availableDisplayModes:q.array(H4).optional().describe("Display modes the host supports."),containerDimensions:q.union([q.object({height:q.number().describe("Fixed container height in pixels.")}),q.object({maxHeight:q.union([q.number(),q.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(q.union([q.object({width:q.number().describe("Fixed container width in pixels.")}),q.object({maxWidth:q.union([q.number(),q.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
119
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:q.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:q.string().optional().describe("User's timezone in IANA format."),userAgent:q.string().optional().describe("Host application identifier."),platform:q.union([q.literal("web"),q.literal("desktop"),q.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:q.object({touch:q.boolean().optional().describe("Whether the device supports touch input."),hover:q.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:q.object({top:q.number().describe("Top safe area inset in pixels."),right:q.number().describe("Right safe area inset in pixels."),bottom:q.number().describe("Bottom safe area inset in pixels."),left:q.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),Zw=q.object({method:q.literal("ui/notifications/host-context-changed"),params:GM.describe("Partial context update containing only changed fields.")}),gO=q.object({method:q.literal("ui/update-model-context"),params:q.object({content:q.array(h0).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:q.record(q.string(),q.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),xO=q.object({method:q.literal("ui/initialize"),params:q.object({appInfo:v0.describe("App identification (name and version)."),appCapabilities:$O.describe("Features and capabilities this app provides."),protocolVersion:q.string().describe("Protocol version this app supports.")})}),vO=q.object({protocolVersion:q.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:v0.describe("Host application identification and version."),hostCapabilities:TO.describe("Features and capabilities provided by the host."),hostContext:GM.describe("Rich context about the host environment.")}).passthrough();class W4{eventTarget;eventSource;messageListener;constructor(H=window.parent,W){this.eventTarget=H,this.eventSource=W,this.messageListener=(Q)=>{if(W&&Q.source!==this.eventSource){console.debug("Ignoring message from unknown source",Q);return}let X=V0.safeParse(Q.data);if(X.success)console.debug("Parsed message",X.data),this.onmessage?.(X.data);else if(Q.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",X.error.message,Q);else console.error("Failed to parse message",X.error.message,Q),this.onerror?.(Error("Invalid JSON-RPC message received: "+X.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(H,W){if(H.method!==FO)console.debug("Sending message",H);this.eventTarget.postMessage(H,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var yO=[KM];class Q4 extends m9{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new NM;_methods=new BM;setRequestHandler=(...H)=>{let[W,...Q]=QM("request",H)??H;this._methods.claim(W,"setRequestHandler"),super.setRequestHandler.call(this,W,...Q)};setNotificationHandler=(...H)=>{let[W,...Q]=QM("notification",H)??H;this._methods.claim(W,"setNotificationHandler"),super.setNotificationHandler.call(this,W,...Q)};removeRequestHandler=(H)=>{this._methods.release(H),super.removeRequestHandler(H)};removeNotificationHandler=(H)=>{this._methods.release(H),super.removeNotificationHandler(H)};replaceRequestHandler=(H,...W)=>{this._methods.replace(H),super.setRequestHandler.call(this,H,...W)};_wrapHandler(H,W){let Q=super._wrapHandler(H,W);if(H==="ui/initialize"||H==="ping")return Q;return async(X,Y)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${H}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return Q(X,Y)}}eventSchemas={sizechange:PO,sandboxready:ZO,initialized:RO,requestteardown:jO,loggingmessage:_8};setEventHandler(H,W){this._ensureEventSlot(H),this._events.setHandler(H,W)}getEventHandler(H){return this._events.getHandler(H)}addEventListener(H,W){this._ensureEventSlot(H),this._events.addEventListener(H,W)}removeEventListener(H,W){this._events.removeEventListener(H,W)}_ensureEventSlot(H){if(this._registeredEvents.has(H))return;let W=this.eventSchemas[H];if(!W)throw Error(`Unknown event: ${String(H)}`);let Q=(X)=>{if(H==="initialized")this._initializedReceived=!0;this._events.dispatch(H,X)};if(H==="loggingmessage")this.setNotificationHandler("notifications/message",(X)=>{Q(X.params)});else this.setNotificationHandler(W.shape.method.value,{params:W.shape.params},(X)=>Q(X));this._registeredEvents.add(H)}warnIfRequestHandlerReplaced(H,W,Q){if(W&&Q)console.warn(`[MCP Apps] ${H} handler replaced. Previous handler will no longer be called.`)}constructor(H,W,Q,X){super(X);this._client=H,this._hostInfo=W,this._hostCapabilities=Q,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=X?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:xO.shape.params,result:vO},(Y)=>this._onAppsInitialize(Y)),this.replaceRequestHandler("ping",(Y,J)=>{return this.onping?.(Y.params,J),{}}),this.replaceRequestHandler("ui/request-display-mode",{params:YM.shape.params,result:JM},()=>{return{mode:this._hostContext.displayMode??"inline"}})}buildContext(H){return H}assertCapabilityForMethod(H){}assertRequestHandlerCapability(H){}assertNotificationCapability(H){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(H){this.setEventHandler("sizechange",H)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(H){this.setEventHandler("sandboxready",H)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(H){this.setEventHandler("initialized",H)}_onmessage;get onmessage(){return this._onmessage}set onmessage(H){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,H),this._onmessage=H,this.replaceRequestHandler("ui/message",{params:kO.shape.params,result:zO},async(W,Q)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(W,Q)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(H){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,H),this._onopenlink=H,this.replaceRequestHandler("ui/open-link",{params:VO.shape.params,result:UO},async(W,Q)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(W,Q)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(H){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,H),this._ondownloadfile=H,this.replaceRequestHandler("ui/download-file",{params:SO.shape.params,result:wO},async(W,Q)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(W,Q)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(H){this.setEventHandler("requestteardown",H)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(H){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,H),this._onrequestdisplaymode=H,this.replaceRequestHandler("ui/request-display-mode",{params:YM.shape.params,result:JM},async(W,Q)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(W,Q)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(H){this.setEventHandler("loggingmessage",H)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(H){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,H),this._onupdatemodelcontext=H,this.replaceRequestHandler("ui/update-model-context",{params:gO.shape.params,result:jW},async(W,Q)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(W,Q)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(H){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,H),this._oncalltool=H,this.replaceRequestHandler("tools/call",async(W,Q)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(W.params,Q)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(H){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,H),this._oncreatesamplingmessage=H,this.replaceRequestHandler("sampling/createMessage",async(W,Q)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(W.params,Q)})}sendToolListChanged(H={}){return this.notification({method:"notifications/tools/list_changed",params:H})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(H){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,H),this._onlistresources=H,this.replaceRequestHandler("resources/list",async(W,Q)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(W.params,Q)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(H){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,H),this._onlistresourcetemplates=H,this.replaceRequestHandler("resources/templates/list",async(W,Q)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(W.params,Q)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(H){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,H),this._onreadresource=H,this.replaceRequestHandler("resources/read",async(W,Q)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(W.params,Q)})}sendResourceListChanged(H={}){return this.notification({method:"notifications/resources/list_changed",params:H})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(H){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,H),this._onlistprompts=H,this.replaceRequestHandler("prompts/list",async(W,Q)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(W.params,Q)})}sendPromptListChanged(H={}){return this.notification({method:"notifications/prompts/list_changed",params:H})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(H){let W=H.protocolVersion;if(this._appInfo!==void 0)console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.");return this._appCapabilities=H.appCapabilities,this._appInfo=H.appInfo,{protocolVersion:yO.includes(W)?W:KM,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(H){let W={},Q=!1;for(let X of Object.keys(H)){let Y=this._hostContext[X],J=H[X];if(hO(Y,J))continue;W[X]=J,Q=!0}if(Q)this._hostContext=H,this.sendHostContextChange(W)}sendHostContextChange(H){return this.notification({method:"ui/notifications/host-context-changed",params:H})}sendToolInput(H){return this.notification({method:"ui/notifications/tool-input",params:H})}sendToolInputPartial(H){return this.notification({method:"ui/notifications/tool-input-partial",params:H})}sendToolResult(H){return this.notification({method:"ui/notifications/tool-result",params:H})}sendToolCancelled(H){return this.notification({method:"ui/notifications/tool-cancelled",params:H})}sendSandboxResourceReady(H){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:H})}teardownResource(H,W){return this.request({method:"ui/resource-teardown",params:H},LO,W)}sendResourceTeardown=this.teardownResource;callTool(H,W){return this.request({method:"tools/call",params:H},W)}listTools(H,W){return this.request({method:"tools/list",params:H},W)}async connect(H){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let W=this._client.getServerCapabilities();if(!W)throw Error("Client server capabilities not available");if(W.tools){if(this.oncalltool=async(Q,X)=>{return this._client.request({method:"tools/call",params:Q},{signal:X.mcpReq.signal})},W.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(Q)=>this.sendToolListChanged(Q.params))}if(W.resources){if(this.onlistresources=async(Q,X)=>{return this._client.request({method:"resources/list",params:Q},{signal:X.mcpReq.signal})},this.onlistresourcetemplates=async(Q,X)=>{return this._client.request({method:"resources/templates/list",params:Q},{signal:X.mcpReq.signal})},this.onreadresource=async(Q,X)=>{return this._client.request({method:"resources/read",params:Q},{signal:X.mcpReq.signal})},W.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(Q)=>this.sendResourceListChanged(Q.params))}if(W.prompts){if(this.onlistprompts=async(Q,X)=>{return this._client.request({method:"prompts/list",params:Q},{signal:X.mcpReq.signal})},W.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(Q)=>this.sendPromptListChanged(Q.params))}}return super.connect(H)}}function hO(H,W){return JSON.stringify(H)===JSON.stringify(W)}var DM=[200,800],fO=(H)=>H?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(H.message);function uO(H,W){return new Promise((Q,X)=>{W?.throwIfAborted();let J=setTimeout(()=>{W?.removeEventListener("abort",N),Q()},H),N=()=>{clearTimeout(J),W.removeEventListener("abort",N),X(W.reason)};W?.addEventListener("abort",N,{once:!0})})}function MM(H,{signal:W,onDiagnostic:Q,wait:X=uO}={}){return async(Y)=>{for(let J=1;;J++){W?.throwIfAborted();try{let N=await H(Y);if(W?.throwIfAborted(),J>1)Q?.({state:"recovered",uri:Y.uri,attempt:J});return N}catch(N){if(W?.throwIfAborted(),!fO(N))throw N;if(J>DM.length)throw Q?.({state:"exhausted",uri:Y.uri,attempt:J,message:N.message}),Object.assign(Error(`MCP resource transport failed for ${Y.uri} after ${J} attempts: ${N.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:N}),{code:"ADS_RESOURCE_TRANSPORT"});let B=DM[J-1];Q?.({state:"retry",uri:Y.uri,attempt:J,nextAttempt:J+1,delayMs:B,message:N.message}),await X(B,W)}}}}function qM(H){let W=[],Q=new Map;for(let X of H){if(!X.group){W.push(X);continue}if(!Q.has(X.group))Q.set(X.group,[]);Q.get(X.group).push(X)}return[...W.length?[{label:null,entries:W}]:[],...[...Q].sort(([X],[Y])=>X.localeCompare(Y)).map(([X,Y])=>({label:X,entries:Y}))]}async function FM({slot:H,title:W,sandboxUrl:Q,resourceUri:X,result:Y,readResource:J,callTool:N,context:B,onError:G,onState:D}){let M={slot:H,title:W,sandboxUrl:Q,resourceUri:X,readResource:J,callTool:N,context:B,onError:G,onState:D},_=Y,F,A,w,z=!1;function Z(){if(z||w)return;D?.({state:"loading"}),w=Promise.resolve().then(async()=>{if(await A,await F?.close(),z)return;A=_M({...M,result:_,onReopen:Z});try{F=await A}finally{A=void 0}}).catch((u)=>{if(!z)G(u)}).finally(()=>{w=void 0})}A=_M({...M,result:_,onReopen:Z});try{F=await A}finally{A=void 0}return{async updateResult(u){if(_=u,await w,!z)await F.updateResult(_)},refreshContext(){if(!z&&!w)F.refreshContext()},async close(){z=!0,await w,await F?.close()}}}async function _M({slot:H,title:W,sandboxUrl:Q,resourceUri:X,result:Y,readResource:J,callTool:N,context:B,onError:G,onState:D,onReopen:M}){let _=!1,A=(await J({uri:X})).contents.find((j)=>j.mimeType==="text/html;profile=mcp-app"&&typeof j.text==="string");if(!A)throw Error("Comparison preview App is unavailable.");let w=document.createElement("iframe");w.title=W,w.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),w.src=Q,H.append(w);let z=new Q4(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:B(w)});z.onreadresource=J,z.oncalltool=N,z.onerror=(j)=>{if(!_)G(j)},z.onloggingmessage=(j)=>{if(_||j.logger!=="ads-preview")return;if(j.data?.code==="ADS_PREVIEW_REOPEN"){M();return}if(D?.(j.data),j.data?.state==="error")G(Error(j.data.message))};let Z,u=new Promise((j,m)=>{Z=setTimeout(()=>m(Error("Comparison App initialization timed out.")),15000),z.oninitialized=()=>{clearTimeout(Z),j()}});z.onsandboxready=()=>z.sendSandboxResourceReady({html:A.text,csp:A._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let p=new ResizeObserver(()=>z.setHostContext(B(w)));try{await Promise.all([z.connect(new W4(w.contentWindow,w.contentWindow)),u]),p.observe(w),await z.sendToolInput({arguments:{}}),await z.sendToolResult(Y)}catch(j){throw p.disconnect(),w.remove(),await z.close(),j}finally{clearTimeout(Z)}return{updateResult:(j)=>z.sendToolResult(j),refreshContext:()=>z.setHostContext(B(w)),async close(){_=!0,p.disconnect();try{await z.teardownResource({},{timeout:500})}catch{}await z.close(),w.remove()}}}function iB(H,W){return W===H||W.startsWith(H+"/")||W.startsWith(H+".")}function EM(H,W,Q,X=new Map){let Y=new Map(Q.map(({id:G,title:D,revision:M,state:_,preview:F})=>[G,{id:G,title:D,revision:M,state:_,...F?{preview:F}:{}}])),J=new Map(H.map((G)=>[G.id,{...G,drafts:(G.drafts??[]).flatMap((D)=>Y.has(D.id)?[Y.get(D.id)]:[])}]));for(let G of W){let D=J.get(G.id);J.set(G.id,{...D,...G,kind:"tokens",drafts:D?.drafts??[]})}let N=(G,D)=>G==="tokens"&&D.kind==="tokens"||(D.unit?D.unit===G:iB(G,D.id)),B=(G,D)=>{if(!G.drafts.some((M)=>M.id===D.id))G.drafts.push(Y.get(D.id))};for(let G of Q){let D=X.get(G.id);for(let M of D?.scenarios??[]){if(!G.units.some((F)=>N(F,M)))continue;let _=J.get(M.id);if(!_)_={...M,draftOnly:!0,drafts:[]},J.set(M.id,_);B(_,G)}}for(let G of Q)for(let D of G.units){let M=D.split("/")[0];if(!["tokens","components","patterns","composition"].includes(M))continue;let _=[...J.values()].filter((F)=>N(D,F));if(_.length)for(let F of _)B(F,G);else J.set(D,{id:D,unit:D,title:D.split("/").at(-1),kind:M,draftOnly:!0,pendingDraftScenario:!0,drafts:[Y.get(G.id)]})}return{scenarios:[...J.values()],categories:[...J.values()].filter((G)=>G.kind==="tokens")}}function AM(H,W,Q){let X=H.drafts?.find((G)=>G.id===Q)??H.drafts?.[0],Y=X&&(W?.drafts?.find((G)=>G.id===X.id)??X.preview),J=X?Y?.scenarios?.find((G)=>G.id===H.id)??Y:W?.previews?.find((G)=>G.id===H.id)??H.build,N=J?.state==="error"?"error":J?.state==="checking"||J?.live?"checking":J?.building||["queued","building"].includes(J?.state)?"building":J?.current?"ready":J?.stale?"stale":"unreported";return{state:N,label:`${X?"Draft · ":""}${{error:"Preview build failed",checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"}[N]}${X&&N==="ready"?" · unaccepted":""}`}}var OM={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var i=(H)=>document.getElementById(H),w0=new URLSearchParams(location.search),VM=w0.get("scenario")??w0.get("category"),lO=["tokens","components","patterns","composition"],s1=[],ZH,s9=w0.get("draft"),H2=[],zM=[],W2=new Map,HQ=w0.get("split")==="1",rB,WQ=[],GW=0,HJ;async function WJ(){let H=WQ;WQ=[],await Promise.allSettled(H.map((W)=>W.close()))}var q0=document.createElement("button");q0.id="split-view";q0.setAttribute("aria-label","Split view");q0.setAttribute("aria-pressed","false");q0.disabled=!0;q0.title="Select a draft with an accepted version to compare";q0.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';i("viewport").before(q0);var UH="tokens",M0={},UM=new Map,n9=!0,Q2=[],X2=[],QJ=[],t1,XJ,OH,rH,r1,a1,tB,X4,m0=0,e1=w0.get("capture")!=="1"&&w0.get("viewport")==="phone",kW=w0.get("capture")==="1"&&w0.get("theme")==="dark"?"dark":"light";if(w0.get("capture")==="1")document.documentElement.dataset.capture="true";document.documentElement.dataset.theme=kW;var oB,ZM=!0,r9=!1,a9,sB,YJ=!1,J4=!1,P8,SW,nB=0,Y4,I8=new AbortController,c0=new eD({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),PM=(H,W={},Q={})=>c0.callTool({name:H,arguments:W},{signal:I8.signal,...Q}),e9=MM((H)=>c0.readResource(H,{signal:I8.signal}),{signal:I8.signal,onDiagnostic:(H)=>{if(H.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",H)}}),bM=async(H)=>JSON.parse((await e9({uri:H})).contents.find((W)=>typeof W.text==="string").text);function IM(H){let W=QJ.find((Q)=>Q.name===H.name);if(!W||!(W._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return c0.callTool(H)}function zH(H,W=!1,Q=W?"error":H?"checking":"ready"){let X=H||"Preview is up to date.";if(i("preview-error").hidden=!W,i("preview-error-message").textContent=W?X:"",i("status").textContent=X,i("status").dataset.error=String(W),W)i("status").removeAttribute("role");else i("status").setAttribute("role","status");i("preview-status").dataset.phase=Q,i("preview-status").title=X,i("preview-status").setAttribute("aria-label",`Preview status: ${X.split(`
120
- `)[0]}`),LM()}function LM(){let H=XJ?.warmup,W=H?`Background views: ${H.completed}/${H.total} compiled${H.failed?`; ${H.failed} failed`:""}.`:"";i("warmup-status").hidden=!H,i("warmup-status").textContent=W,i("preview-status").dataset.warmup=H?.state??"disabled",i("preview-status").title=[i("status").textContent,W].filter(Boolean).join(`
121
- `)}function jM(){zH(OH?"Updating preview…":"Opening preview…",!1,"reloading")}function QQ(){return B4().find((H)=>H.id===M0[UH])}function N4(H=QQ()){let W=s1.find((Q)=>Q.id===s9&&W2.get(Q.id)?.scenario===H?.id);return H?.drafts?.find((Q)=>Q.id===s9)??W??H?.drafts?.[0]}function TM(){return Boolean(N4()&&(QQ()?.draftOnly||HQ))}function Y2(){return`${UH}:${M0[UH]}${TM()?`:draft:${N4().id}`:""}`}function t9(H=OH){return H?.key===Y2()}function $M(){({scenarios:X2,categories:Q2}=EM(H2,zM,s1,W2))}function mO(H){W2.set(H.structuredContent.id,H.structuredContent),$M()}async function aB(H,W,Q=I8.signal){let X=(t1?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await PM(H,W,{signal:AbortSignal.any([I8.signal,Q]),timeout:X})}catch(Y){if(Y.code!=="REQUEST_TIMEOUT")throw Y;throw Object.assign(Error(`The preview request timed out after ${Math.ceil(X/1000)} seconds. No preview result was received. Retry the preview.`,{cause:Y}),{code:"ADS_PREVIEW_REQUEST_TIMEOUT",category:"transport"})}}async function J2(H,W,Q){let X=QQ()?.id===W&&QQ().pendingDraftScenario||H.units?.includes(W)&&!H2.some((J)=>J.id===W),Y=await aB("ads_show_draft",{id:H.id,...!X&&W?{scenario:W}:{}},Q);if(Y.isError)throw Error(Y.content?.find((J)=>J.type==="text")?.text??"Draft preview failed.");if(X){let J=Y.structuredContent.scenarios.find((N)=>W==="tokens"?N.kind==="tokens":N.unit?N.unit===W:iB(W,N.id));if(!J)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(J.id!==Y.structuredContent.scenario)Y=await aB("ads_show_draft",{id:H.id,scenario:J.id},Q);if(Y.isError)throw Error(Y.content?.find((N)=>N.type==="text")?.text??"Draft preview failed.")}return mO(Y),Y}function gW(H=!1){if(H)X4=OH?.key;a1=void 0,i("loader").hidden=!0,i("preview").setAttribute("aria-busy","false")}function wM(H){let W=new URL(location.href);for(let Y of["scenario","category","draft","split"])W.searchParams.delete(Y);if(H)W.searchParams.set("scenario",H);let Q=B4().find((Y)=>Y.id===H),X=N4(Q);if(X&&(Q.draftOnly||HQ)){if(W.searchParams.set("draft",X.id),!Q.draftOnly)W.searchParams.set("split","1")}return W.pathname+W.search+W.hash}function B4(){return UH==="tokens"?Q2:X2.filter((H)=>H.kind===UH)}function RM(H,W){let{state:Q,label:X}=AM(W,XJ,s9),Y=H.querySelector(".entry-preview");if(!Y)Y=document.createElement("span"),Y.className="entry-preview",Y.setAttribute("aria-hidden","true"),H.append(Y);Y.dataset.state=Q,Y.title=X,Y.innerHTML=`<svg viewBox="0 0 16 16">${OM[Q]}</svg>`,H.dataset.buildState=Q,H.setAttribute("aria-description",X)}function N2(){return{theme:kW,displayMode:"inline",containerDimensions:{width:i("frame-slot").clientWidth,height:i("frame-slot").clientHeight}}}function K4(){let H=B4();if(!H.some((X)=>X.id===M0[UH]))M0[UH]=H[0]?.id??null;history.replaceState(null,"",wM(M0[UH]));let W=i("sidebar").scrollTop;i("entries").setAttribute("aria-label",UH[0].toUpperCase()+UH.slice(1));let Q=(X)=>{let Y=document.createElement("a");if(Y.textContent=X.title,X.drafts?.length){let J=document.createElement("span");J.className="draft-badge",J.textContent=X.drafts.length>1?`Drafts ${X.drafts.length}`:"Draft",J.title=X.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",Y.append(" ",J)}if(Y.href=wM(X.id),Y.dataset.scenario=X.id,RM(Y,X),X.id===M0[UH])Y.setAttribute("aria-current","page");return Y.addEventListener("click",(J)=>{if(J.button||J.metaKey||J.ctrlKey||J.shiftKey||J.altKey)return;J.preventDefault(),M0[UH]=X.id,K4(),xW().catch(p0)}),Y};i("entries").replaceChildren(...qM(H).flatMap((X)=>{if(!X.label)return X.entries.map(Q);let Y=`${UH}:${X.label}`,J=document.createElement("details");J.className="entry-group",J.open=UM.get(Y)??!0;let N=document.createElement("summary");N.textContent=X.label;let B=document.createElement("div");return B.setAttribute("role","group"),B.setAttribute("aria-label",X.label),B.append(...X.entries.map(Q)),J.append(N,B),J.addEventListener("toggle",()=>{if(J.isConnected)UM.set(Y,J.open)}),[J]})),i("sidebar").scrollTop=W;for(let X of i("sections").querySelectorAll("button"))if(X.dataset.section===UH)X.setAttribute("aria-current","page");else X.removeAttribute("aria-current");eB()}function p0(H){if(!YJ&&!J4)gW(),i("status").dataset.errorCategory=H.category??(H.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),i("status").dataset.errorCode=H.code??"ADS_HOST_STARTUP",zH(`${H.message}${OH?`
122
- The retained preview is not verified against the current source.`:""}`,!0)}async function b8(H){if(!H)return;try{await H.teardownResource({},{timeout:500})}catch{}await H.close()}function CM(){if(YJ||J4)return;J4=!0,I8.abort(),++m0,clearTimeout(a9),gW(),zH("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let H=rH;rH=void 0,b8(H),++GW,WJ()}async function B2(){let H=await bM("ads://project/explorer");t1=H.status,XJ=t1.build,QJ=H.tools,zM=H.categories,H2=H.scenarios,s1=H.drafts,i("title").textContent=(t1.drafts?.previewOnly?"Draft · ":"")+t1.project.showcase.title,i("title").title=t1.projectRoot,$M();let W=n9?VM:M0[UH],Q=n9&&s1.find((J)=>J.id===s9),X=OH?.draft&&s1.find((J)=>J.id===OH.draftId);if(Q||X&&ZH&&(X.revision!==ZH.revision||ZH.discovery?.state==="pending")){let J=await J2(Q||X,Q?VM:ZH.scenario);if(Q)W=J.structuredContent.scenario;if(OH?.draft&&X){ZH=J.structuredContent,HJ=J;for(let N of WQ)if(N.side==="draft")await N.updateResult(J)}}let Y=X2.find((J)=>J.id===W);if(Y&&lO.includes(Y.kind))UH=Y.kind,M0[UH]=Y.id;else if(n9&&Q2.some((J)=>J.id===W))M0.tokens=W;n9=!1,K4()}function xW({force:H=!1}={}){if(J4)return Promise.resolve();let W=M0[UH],Q=Y2();if(r1?.key===Q)return r1.promise;if(!H&&!r1&&OH?.key===Q)return Promise.resolve();let X={key:Q};return r1=X,X.promise=cO(W,Q,UH==="tokens").finally(()=>{if(r1===X)r1=void 0}),X.promise}async function cO(H,W,Q){tB?.abort();let X=tB=new AbortController,Y=++m0;a1=!0,i("loader").hidden=W===X4,i("preview").setAttribute("aria-busy","true");try{if(++GW,await WJ(),Y!==m0)return;if(TM()){await b8(rH),rH=void 0,P8=void 0,SW=void 0;let D=N4(),M=await J2(D,H,X.signal);if(Y!==m0)return;if(ZH=M.structuredContent,HJ=M,QQ()?.pendingDraftScenario||!B4().some((_)=>_.id===H))M0[UH]=ZH.scenario;OH={key:Y2(),id:ZH.scenario,draftId:D.id,generation:Y,draft:!0},eB(),await iO(),K4(),gW(!0),zH("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(ZH=void 0,eB(),!H&&!Q){if(await b8(rH),Y!==m0)return;rH=void 0,OH=void 0,X4=void 0,P8=void 0,SW=void 0,i("frame-slot").replaceChildren(),gW(),zH("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let J=QJ.find((D)=>D.name===(Q?"ads_show_tokens":"ads_show_scenario"));if(!J?._meta?.ui?.resourceUri)throw Error("The server did not expose a preview App tool.");let N=Q?H?{category:H}:{}:{id:H};if(J.inputSchema?.properties?.waitFor)N.waitFor=w0.get("capture")==="1"||w0.get("waitFor")==="verified"?"verified":"compiled";jM();let B=await aB(J.name,N,X.signal);if(Y!==m0)return;if(B.isError)throw Object.assign(Error(B.content?.find((D)=>D.type==="text")?.text??"Preview build failed."),B.structuredContent?.failure);OH={key:W,id:H,generation:Y,token:Q&&!B.structuredContent?.scenario,build:B.structuredContent?.build,manifestRevision:B.structuredContent?.manifestRevision};let G=await pO(J._meta.ui.resourceUri);if(Y!==m0)return;if(P8==="ui://ads/preview"&&!OH.manifestRevision)throw Error("The resource preview has no manifest revision.");if(X4!==W)X4=void 0;if(await G.sendToolInput({arguments:N}),await G.sendToolResult(B),Y===m0&&!B.structuredContent?.manifestUri)gW(!0),zH("")}catch(J){if(Y===m0)p0(J)}}async function pO(H){if(P8===H&&SW)return SW;let W=++nB,Q=rH;rH=void 0,P8=H,SW=(async()=>{await b8(Q);let X=await e9({uri:H});if(W!==nB||YJ||J4)throw Error("Preview opening was superseded.");let Y=X.contents.find((D)=>D.mimeType==="text/html;profile=mcp-app"&&typeof D.text==="string");if(!Y)throw Error("The preview resource contains no MCP App.");let J=document.createElement("iframe");J.title="Design-system preview",J.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),J.src=Y4,i("frame-slot").replaceChildren(J);let N=new Q4(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:N2()});rH=N,N.onreadresource=(D)=>e9(D),N.oncalltool=IM,N.onloggingmessage=(D)=>{if(N!==rH||D.logger!=="ads-preview"||OH?.generation!==m0||!t9()||D.data?.id!==OH?.id)return;let M=D.data.revision===OH.manifestRevision||D.data.selectionRevision===OH.manifestRevision;if(D.data.state==="ready"&&M)OH.manifestRevision=D.data.revision,gW(!0),zH("");else if(D.data.state==="checking"&&(!a1||M))gW(!0),zH("Checking changes…");else if(D.data.state==="loading")zH("Updating preview…",!1,"reloading");else if(D.data.state==="reverting")zH("Restoring the last verified preview…",!1,"reverting");else if(D.data.code==="ADS_PREVIEW_REOPEN")rH=void 0,P8=void 0,SW=void 0,jM(),b8(N).then(()=>xW({force:!0})).catch(p0);else if(D.data.state==="error")gW(),zH(D.data.message,!0)},N.onerror=p0;let B,G=new Promise((D,M)=>{B=setTimeout(()=>M(Error("MCP App initialization timed out.")),15000),N.oninitialized=()=>{clearTimeout(B),D()}});N.onsandboxready=()=>N.sendSandboxResourceReady({html:Y.text,csp:Y._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([N.connect(new W4(J.contentWindow,J.contentWindow)),G])}catch(D){throw await b8(N),D}finally{clearTimeout(B)}return N})();try{return await SW}catch(X){if(W===nB)P8=void 0,SW=void 0;throw X}}async function dO(){let H=OH,W=await bM("ads://project/build");XJ=W,LM();for(let X of i("entries").querySelectorAll("a[data-scenario]")){let Y=B4().find((J)=>J.id===X.dataset.scenario);if(Y)RM(X,Y)}if(!H||H.token||a1||!t9(H))return;if(H.draft){let X=W.drafts?.find((N)=>N.id===H.draftId),Y=X?.scenarios?.find((N)=>N.id===ZH?.scenario)??X,J=Y&&JSON.stringify([X?.session,Y.revision,Y.live?.revision,Y.current]);if(Y&&(Y.current||Y.live)&&H.buildSignature!==J){H.buildSignature=J;let N=s1.find((B)=>B.id===H.draftId);if(N){let B=await J2(N,ZH.scenario);if(OH!==H||a1||!t9(H))return;ZH=B.structuredContent,HJ=B;for(let G of WQ)if(G.side==="draft")await G.updateResult(B)}}if(Y?.state==="error")zH("Draft preview build failed. Showing the previous preview.",!0);else if(Y?.building)zH(Y.live||Y.state==="checking"?"Draft preview compiled; checking changes…":"Building draft preview… Showing the previous preview.",!1,Y.live||Y.state==="checking"?"checking":"compiling");else if(Y?.current&&rB?.state==="ready")zH("Draft preview ready · unaccepted.");return}if(OH!==H||a1||!t9(H))return;let Q=W.previews.find((X)=>X.id===H.id);if(!Q){zH("The selected scenario is no longer registered.",!0);return}if(["idle","building"].includes(Q.state)&&H.build?.current&&Q.session===H.build.session&&Q.revision<=H.build.revision)return;if(Q.state==="error"){zH(`Preview build failed. Showing an earlier view.
123
- ${Q.diagnostics.map((X)=>`${X.file??""}${X.line?`:${X.line}`:""}: ${X.message}`).join(`
124
- `)}`,!0);return}if(["idle","building"].includes(Q.state)){zH(Q.live?"Checking changes…":"Compiling changes… The current view is the previous preview.",!1,Q.live?"checking":"compiling");return}if(Q.current&&(Q.revision!==H.build?.revision||Q.session!==H.build?.session))await xW({force:!0})}function G4(H=!1,W=!1){if(r9||=H,W&&OH?.token)OH.key="invalidated";if(clearTimeout(a9),ZM)return;a9=setTimeout(()=>{if(oB){G4(H,W);return}oB=(async()=>{if(r9)r9=!1,await B2();await xW(),await dO()})().catch(p0).finally(()=>{oB=void 0})},150)}async function iO(){if(!ZH)return;let H=ZH,W=HJ;rB=void 0;let Q=++GW;if(await WJ(),Q!==GW)return;let X=HQ&&H.acceptedExists;q0.setAttribute("aria-pressed",String(X));let Y=document.createElement("div");Y.className="draft-comparison",Y.dataset.split=String(X);for(let J of X?["accepted","draft"]:["draft"]){let N=document.createElement("section");N.className="draft-version";let B=document.createElement("h2");B.dataset.version=J,B.textContent=J==="accepted"?"Accepted":"Draft · unaccepted";let G=document.createElement("div");G.className="draft-stage",G.dataset.version=J,N.append(B,G),Y.append(N)}i("frame-slot").replaceChildren(Y),await Promise.all([...Y.querySelectorAll(".draft-stage")].map(async(J)=>{let N=J.dataset.version,B=N==="draft"?W:await PM("ads_show_scenario",{id:H.scenario,waitFor:"compiled"});if(B.isError)throw Error(B.content?.find((M)=>M.type==="text")?.text??"Comparison build failed.");if(Q!==GW)return;let G=QJ.find((M)=>M.name===(N==="draft"?"ads_show_draft":"ads_show_scenario")),D=await FM({slot:J,title:N==="draft"?"Draft version":"Accepted version",sandboxUrl:Y4,resourceUri:G._meta.ui.resourceUri,result:B,readResource:e9,callTool:IM,context:(M)=>({theme:kW,displayMode:"inline",containerDimensions:{width:M.clientWidth,height:M.clientHeight}}),onError:(M)=>{if(Q===GW)p0(M)},onState:(M)=>{if(Q!==GW||N!=="draft")return;if(rB=M,M.state==="ready")zH("Draft preview ready · unaccepted.");else if(M.state==="checking")zH("Draft preview compiled; checking changes…",!1,"checking");else if(["loading","reverting"].includes(M.state))zH("Updating draft preview…",!1,"reloading")}});if(Q!==GW)await D.close();else WQ.push({...D,side:N})}))}function eB(){let H=QQ(),W=Boolean(N4(H))&&!H?.draftOnly;q0.disabled=!W,q0.title=H?.draftOnly?"No accepted version yet":W?"Compare accepted and draft versions":"No draft for this entry",q0.setAttribute("aria-pressed",String(W&&HQ));let Q=document.querySelector('.draft-version h2[data-version="draft"]');if(Q&&ZH){let X={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};Q.textContent=`Draft · ${X[ZH.state]??ZH.state}`,Q.title=ZH.dependencies?.length?`Draft dependencies: ${ZH.dependencies.join(", ")}`:""}}q0.addEventListener("click",()=>{HQ=!HQ,K4(),xW().catch(p0)});for(let H of i("sections").querySelectorAll("button"))H.addEventListener("click",()=>{UH=H.dataset.section,K4(),xW().catch(p0)});var K2=window.matchMedia("(max-width: 760px)");function SM(H){document.body.classList.toggle("collapsed",H),i("pane-toggle").setAttribute("aria-expanded",String(!H)),i("pane-toggle").setAttribute("aria-label",H?"Show navigation pane":"Hide navigation pane"),i("pane-toggle").title=H?"Show navigation pane":"Hide navigation pane",i("pane-toggle").querySelector("path").setAttribute("d",H?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var G2=()=>SM(i("header").hidden||K2.matches);G2();K2.addEventListener("change",G2);i("pane-toggle").addEventListener("click",()=>SM(!document.body.classList.contains("collapsed")));function kM(){document.documentElement.dataset.viewport=e1?"phone":"auto",i("viewport").setAttribute("aria-pressed",String(e1)),i("viewport").title=e1?"Use available preview width":"Preview at phone width (390 px)"}kM();i("viewport").addEventListener("click",()=>{e1=!e1,kM();let H=new URL(location.href);if(e1)H.searchParams.set("viewport","phone");else H.searchParams.delete("viewport");history.replaceState(null,"",H.pathname+H.search+H.hash)});i("theme").addEventListener("click",()=>{kW=kW==="light"?"dark":"light",document.documentElement.dataset.theme=kW,i("theme").setAttribute("aria-label",kW==="dark"?"Use light theme":"Use dark theme"),i("theme").title=i("theme").getAttribute("aria-label"),i("theme").querySelector("svg").innerHTML=kW==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>',rH?.setHostContext(N2())});i("theme").addEventListener("click",()=>{for(let H of WQ)H.refreshContext()});i("minimize").addEventListener("click",()=>{i("header").hidden=!0,document.body.classList.add("collapsed")});var gM=new ResizeObserver(()=>rH?.setHostContext(N2()));gM.observe(i("frame-slot"));i("retry-preview").addEventListener("click",()=>{(async()=>{await B2(),await xW({force:!0})})().catch(p0)});window.addEventListener("pagehide",()=>{YJ=!0,tB?.abort(),I8.abort(),clearTimeout(a9),gM.disconnect(),K2.removeEventListener("change",G2),b8(rH),++GW,WJ(),sB?.close(),c0.close()},{once:!0});c0.onclose=CM;c0.setNotificationHandler("notifications/resources/list_changed",()=>G4(!0));c0.setNotificationHandler("notifications/tools/list_changed",()=>G4(!0));c0.setNotificationHandler("notifications/resources/updated",({params:H})=>G4(H.uri==="ads://project/explorer",H.uri==="ads://project/tokens"));try{if(Y4=(await fetch("/host.json").then((H)=>H.json())).sandboxUrl,!Y4||new URL(Y4).origin===location.origin)throw Error("The separate-origin MCP App sandbox is unavailable.");if(await c0.connect(new HM(new URL("/mcp",location.href))),sB=await c0.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/explorer"]}),sB.closed.then((H)=>{if(H!=="local")CM()}),await B2(),ZM=!1,await xW(),r9)G4()}catch(H){p0(H)}
117
+ - "app": Tool callable by the app from this server only`),csp:Jl().optional(),permissions:Jl().optional()}),HP=p({mimeTypes:g(c()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),rw=p({method:h("ui/download-file"),params:p({contents:g(T([Nr,qr])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),ow=p({method:h("ui/message"),params:p({role:h("user").describe('Message role, currently only "user" is supported.'),content:g(yt).describe("Message content blocks (text, image, etc.).")})}),VP=p({method:h("ui/notifications/sandbox-resource-ready"),params:p({html:c().describe("HTML content to load into the inner iframe."),sandbox:c().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:qu.optional().describe("CSP configuration from resource metadata."),permissions:Au.optional().describe("Sandbox permissions from resource metadata.")})}),JP=p({method:h("ui/notifications/tool-result"),params:nr.describe("Standard MCP tool execution result.")}),aS=p({toolInfo:p({id:nt.optional().describe("JSON-RPC id of the tools/call request."),tool:or.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:Lz.optional().describe("Current color theme preference."),styles:Kz.optional().describe("Style configuration for theming the app."),displayMode:ji.optional().describe("How the UI is currently displayed."),availableDisplayModes:g(ji).optional().describe("Display modes the host supports."),containerDimensions:T([p({height:z().describe("Fixed container height in pixels.")}),p({maxHeight:T([z(),Vl()]).optional().describe("Maximum container height in pixels.")})]).and(T([p({width:z().describe("Fixed container width in pixels.")}),p({maxWidth:T([z(),Vl()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
118
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:c().optional().describe("User's language and region preference in BCP 47 format."),timeZone:c().optional().describe("User's timezone in IANA format."),userAgent:c().optional().describe("Host application identifier."),platform:T([h("web"),h("desktop"),h("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:E().optional().describe("Whether the device supports touch input."),hover:E().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:z().describe("Top safe area inset in pixels."),right:z().describe("Right safe area inset in pixels."),bottom:z().describe("Bottom safe area inset in pixels."),left:z().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),BP=p({method:h("ui/notifications/host-context-changed"),params:aS.describe("Partial context update containing only changed fields.")}),nw=p({method:h("ui/update-model-context"),params:p({content:g(yt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),A().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),sw=p({method:h("ui/initialize"),params:p({appInfo:_t.describe("App identification (name and version)."),appCapabilities:Qz.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),iw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:_t.describe("Host application identification and version."),hostCapabilities:Xz.describe("Features and capabilities provided by the host."),hostContext:aS.describe("Rich context about the host environment.")}).passthrough();class Li{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(r)=>{if(t&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=st.safeParse(r.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(r.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,r);else console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==jz)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var aw=[iS];class Ui extends bc{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new nS;_methods=new sS;setRequestHandler=(...e)=>{let[t,...r]=eS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=eS("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);if(e==="ui/initialize"||e==="ping")return r;return async(o,n)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return r(o,n)}}eventSchemas={sizechange:Bz,sandboxready:Jz,initialized:ew,requestteardown:Yz,loggingmessage:Ar};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=(o)=>{if(e==="initialized")this._initializedReceived=!0;this._events.dispatch(e,o)};if(e==="loggingmessage")this.setNotificationHandler("notifications/message",(o)=>{r(o.params)});else this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>r(o));this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,r,o){super(o);this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=o?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:sw.shape.params,result:iw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,s)=>(this.onping?.(n.params,s),{})),this.replaceRequestHandler("ui/request-display-mode",{params:rS.shape.params,result:oS},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:ow.shape.params,result:Vz},async(t,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:Dz.shape.params,result:Fz},async(t,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:rw.shape.params,result:Hz},async(t,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:rS.shape.params,result:oS},async(t,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:nw.shape.params,result:tr},async(t,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(t,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(t.params,r)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(t,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(t,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(t,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,r)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(t,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,r)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;if(this._appInfo!==void 0)console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.");return this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:aw.includes(t)?t:iS,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){let n=this._hostContext[o],s=e[o];if(cw(n,s))continue;t[o]=s,r=!0}if(r)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},Gz,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},{signal:o.mcpReq.signal}),t.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(r)=>this.sendToolListChanged(r.params))}if(t.resources){if(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},{signal:o.mcpReq.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},{signal:o.mcpReq.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},{signal:o.mcpReq.signal}),t.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(r)=>this.sendResourceListChanged(r.params))}if(t.prompts){if(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},{signal:o.mcpReq.signal}),t.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(r)=>this.sendPromptListChanged(r.params))}}return super.connect(e)}}function cw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var cS=[200,800],lw=(e)=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function uw(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let s=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(s),t.removeEventListener("abort",i),o(t.reason)};t?.addEventListener("abort",i,{once:!0})})}function lS(e,{signal:t,onDiagnostic:r,wait:o=uw}={}){return async(n)=>{for(let s=1;;s++){t?.throwIfAborted();try{let i=await e(n);if(t?.throwIfAborted(),s>1)r?.({state:"recovered",uri:n.uri,attempt:s});return i}catch(i){if(t?.throwIfAborted(),!lw(i))throw i;if(s>cS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:s,message:i.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${s} attempts: ${i.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:i}),{code:"ADS_RESOURCE_TRANSPORT"});let a=cS[s-1];r?.({state:"retry",uri:n.uri,attempt:s,nextAttempt:s+1,delayMs:a,message:i.message}),await o(a,t)}}}}function uS(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}if(!r.has(o.group))r.set(o.group,[]);r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function pS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:s,callTool:i,context:a,onError:l,onState:u},m=n,f,S,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await S,await f?.close(),y)return;S=dS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}}).catch((L)=>{if(!y)l(L)}).finally(()=>{b=void 0})}S=dS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}return{async updateResult(L){if(m=L,await b,!y)await f.updateResult(m)},refreshContext(){if(!y&&!b)f.refreshContext()},async close(){y=!0,await b,await f?.close()}}}async function dS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:l,onState:u,onReopen:d}){let m=!1,S=(await s({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!S)throw Error("Comparison preview App is unavailable.");let b=document.createElement("iframe");b.title=t,b.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),b.src=r,e.append(b);let y=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=s,y.oncalltool=i,y.onerror=(x)=>{if(!m)l(x)},y.onloggingmessage=(x)=>{if(m||x.logger!=="ads-preview")return;if(x.data?.code==="ADS_PREVIEW_REOPEN"){d();return}if(u?.(x.data),x.data?.state==="error")l(Error(x.data.message))};let v,L=new Promise((x,U)=>{v=setTimeout(()=>U(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:S.text,csp:S._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let F=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Li(b.contentWindow,b.contentWindow)),L]),F.observe(b),await y.sendToolInput({arguments:{}}),await y.sendToolResult(n)}catch(x){throw F.disconnect(),b.remove(),await y.close(),x}finally{clearTimeout(v)}return{updateResult:(x)=>y.sendToolResult(x),refreshContext:()=>y.setHostContext(a(b)),async close(){m=!0,F.disconnect();try{await y.teardownResource({},{timeout:500})}catch{}await y.close(),b.remove()}}}function Mu(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function hS(e,t,r,o=new Map){let n=new Map(r.map(({id:l,title:u,revision:d,state:m,preview:f})=>[l,{id:l,title:u,revision:d,state:m,...f?{preview:f}:{}}])),s=new Map(e.map((l)=>[l.id,{...l,drafts:(l.drafts??[]).flatMap((u)=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let l of t){let u=s.get(l.id);s.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let i=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:Mu(l,u.id)),a=(l,u)=>{if(!l.drafts.some((d)=>d.id===u.id))l.drafts.push(n.get(u.id))};for(let l of r){let u=o.get(l.id);for(let d of u?.scenarios??[]){if(!l.units.some((f)=>i(f,d)))continue;let m=s.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},s.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["tokens","components","patterns","composition"].includes(d))continue;let m=[...s.values()].filter((f)=>i(u,f));if(m.length)for(let f of m)a(f,l);else s.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...s.values()],categories:[...s.values()].filter((l)=>l.kind==="tokens")}}function mS(e,t,r){let o=e.drafts?.find((l)=>l.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find((l)=>l.id===o.id)??o.preview),s=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,i=s?.state==="error"?"error":s?.state==="checking"||s?.live?"checking":s?.building||["queued","building"].includes(s?.state)?"building":s?.current?"ready":s?.stale?"stale":"unreported";return{state:i,label:`${o?"Draft · ":""}${{error:"Preview build failed",checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"}[i]}${o&&i==="ready"?" · unaccepted":""}`}}var fS={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var V=(e)=>document.getElementById(e),at=new URLSearchParams(location.search),gS=at.get("scenario")??at.get("category"),dw=["tokens","components","patterns","composition"],Yo=[],_e,Ec=at.get("draft"),Vu=[],bS=[],Ju=new Map,en=at.get("split")==="1",Uu,tn=[],Dt=0,Cc;async function Ic(){let e=tn;tn=[],await Promise.allSettled(e.map((t)=>t.close()))}var Qe=document.createElement("button");Qe.id="split-view";Qe.setAttribute("aria-label","Split view");Qe.setAttribute("aria-pressed","false");Qe.disabled=!0;Qe.title="Select a draft with an accepted version to compare";Qe.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';V("viewport").before(Qe);var he="tokens",Le={},SS=new Map,xc=!0,Bu=[],Wu=[],Oc=[],Go,Ji,me,Ue,Ko,Fi,Xo,Zu,Zi,Rt=0,Qo=at.get("capture")!=="1"&&at.get("viewport")==="phone",ar=at.get("capture")==="1"&&at.get("theme")==="dark"?"dark":"light";if(at.get("capture")==="1")document.documentElement.dataset.capture="true";document.documentElement.dataset.theme=ar;var ju,yS=!0,Pc=!1,kc,Du,Nc=!1,Hi=!1,Jr,ir,Lu=0,Di,Wr=new AbortController,xt=new Yg({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),vS=(e,t={},r={})=>xt.callTool({name:e,arguments:t},{signal:Wr.signal,...r}),$c=lS((e)=>xt.readResource(e,{signal:Wr.signal}),{signal:Wr.signal,onDiagnostic:(e)=>{if(e.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",e)}}),zS=async(e)=>JSON.parse((await $c({uri:e})).contents.find((t)=>typeof t.text==="string").text);function wS(e){let t=Oc.find((r)=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return xt.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(V("preview-error").hidden=!t,V("preview-error-message").textContent=t?o:"",V("status").textContent=o,V("status").dataset.error=String(t),t)V("status").removeAttribute("role");else V("status").setAttribute("role","status");V("preview-status").dataset.phase=r,V("preview-status").title=o,V("preview-status").setAttribute("aria-label",`Preview status: ${o.split(`
119
+ `)[0]}`),RS()}function RS(){let e=Ji?.warmup,t=e?`Background views: ${e.completed}/${e.total} compiled${e.failed?`; ${e.failed} failed`:""}.`:"";V("warmup-status").hidden=!e,V("warmup-status").textContent=t,V("preview-status").dataset.warmup=e?.state??"disabled",V("preview-status").title=[V("status").textContent,t].filter(Boolean).join(`
120
+ `)}function xS(){Se(me?"Updating preview…":"Opening preview…",!1,"reloading")}function rn(){return Bi().find((e)=>e.id===Le[he])}function on(e=rn()){let t=Yo.find((r)=>r.id===Ec&&Ju.get(r.id)?.scenario===e?.id);return e?.drafts?.find((r)=>r.id===Ec)??t??e?.drafts?.[0]}function Ku(){return Boolean(on()&&(rn()?.draftOnly||en))}function Vi(){return`${he}:${Le[he]}${Ku()?`:draft:${on().id}`:""}`}function Tc(e=me){return e?.key===Vi()}function PS(e=Ji){if(Ku()){let t=e?.drafts?.find((r)=>r.id===on()?.id);return t?.scenarios?.find((r)=>r.id===Le[he])??t}return e?.previews?.find((t)=>t.id===Le[he])}var TS=(e)=>JSON.stringify(e&&[e.session,e.revision,e.current,e.live]);function ES(){({scenarios:Wu,categories:Bu}=hS(Vu,bS,Yo,Ju))}function pw(e){Ju.set(e.structuredContent.id,e.structuredContent),ES()}async function Fu(e,t,r=Wr.signal){let o=(Go?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await vS(e,t,{signal:AbortSignal.any([Wr.signal,r]),timeout:o})}catch(n){if(n.code!=="REQUEST_TIMEOUT")throw n;throw Object.assign(Error(`The preview request timed out after ${Math.ceil(o/1000)} seconds. No preview result was received. Retry the preview.`,{cause:n}),{code:"ADS_PREVIEW_REQUEST_TIMEOUT",category:"transport"})}}async function Gu(e,t,r){let o=rn()?.id===t&&rn().pendingDraftScenario||e.units?.includes(t)&&!Vu.some((s)=>s.id===t),n=await Fu("ads_show_draft",{id:e.id,...!o&&t?{scenario:t}:{}},r);if(n.isError)throw Error(n.content?.find((s)=>s.type==="text")?.text??"Draft preview failed.");if(o){let s=n.structuredContent.scenarios.find((i)=>t==="tokens"?i.kind==="tokens":i.unit?i.unit===t:Mu(t,i.id));if(!s)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(s.id!==n.structuredContent.scenario)n=await Fu("ads_show_draft",{id:e.id,scenario:s.id},r);if(n.isError)throw Error(n.content?.find((i)=>i.type==="text")?.text??"Draft preview failed.")}return pw(n),n}function cr(e=!1){if(e)Zi=me?.key;Xo=void 0,V("loader").hidden=!0,V("preview").setAttribute("aria-busy","false")}function _S(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split"])t.searchParams.delete(n);if(e)t.searchParams.set("scenario",e);let r=Bi().find((n)=>n.id===e),o=on(r);if(o&&(r.draftOnly||en)){if(t.searchParams.set("draft",o.id),!r.draftOnly)t.searchParams.set("split","1")}return t.pathname+t.search+t.hash}function Bi(){return he==="tokens"?Bu:Wu.filter((e)=>e.kind===he)}function kS(e,t){let{state:r,label:o}=mS(t,Ji,Ec),n=e.querySelector(".entry-preview");if(!n)n=document.createElement("span"),n.className="entry-preview",n.setAttribute("aria-hidden","true"),e.append(n);n.dataset.state=r,n.title=o,n.innerHTML=`<svg viewBox="0 0 16 16">${fS[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}function Yu(){return{theme:ar,displayMode:"inline",containerDimensions:{width:V("frame-slot").clientWidth,height:V("frame-slot").clientHeight}}}function Wi(){let e=Bi();if(!e.some((o)=>o.id===Le[he]))Le[he]=e[0]?.id??null;history.replaceState(null,"",_S(Le[he]));let t=V("sidebar").scrollTop;V("entries").setAttribute("aria-label",he[0].toUpperCase()+he.slice(1));let r=(o)=>{let n=document.createElement("a");if(n.textContent=o.title,o.drafts?.length){let s=document.createElement("span");s.className="draft-badge",s.textContent=o.drafts.length>1?`Drafts ${o.drafts.length}`:"Draft",s.title=o.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",n.append(" ",s)}if(n.href=_S(o.id),n.dataset.scenario=o.id,kS(n,o),o.id===Le[he])n.setAttribute("aria-current","page");return n.addEventListener("click",(s)=>{if(s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey)return;s.preventDefault(),Le[he]=o.id,Wi(),Ft().catch(Pt)}),n};V("entries").replaceChildren(...uS(e).flatMap((o)=>{if(!o.label)return o.entries.map(r);let n=`${he}:${o.label}`,s=document.createElement("details");s.className="entry-group",s.open=SS.get(n)??!0;let i=document.createElement("summary");i.textContent=o.label;let a=document.createElement("div");return a.setAttribute("role","group"),a.setAttribute("aria-label",o.label),a.append(...o.entries.map(r)),s.append(i,a),s.addEventListener("toggle",()=>{if(s.isConnected)SS.set(n,s.open)}),[s]})),V("sidebar").scrollTop=t;for(let o of V("sections").querySelectorAll("button"))if(o.dataset.section===he)o.setAttribute("aria-current","page");else o.removeAttribute("aria-current");Hu()}function Pt(e){if(!Nc&&!Hi)cr(),V("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),V("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Se(`${e.message}${me?`
121
+ The retained preview is not verified against the current source.`:""}`,!0)}async function Br(e){if(!e)return;try{await e.teardownResource({},{timeout:500})}catch{}await e.close()}function $S(){if(Nc||Hi)return;Hi=!0,Wr.abort(),++Rt,clearTimeout(kc),cr(),Se("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let e=Ue;Ue=void 0,Br(e),++Dt,Ic()}async function Xu(){let e=await zS("ads://project/explorer");Go=e.status,Ji=Go.build,Oc=e.tools,bS=e.categories,Vu=e.scenarios,Yo=e.drafts,V("title").textContent=(Go.drafts?.previewOnly?"Draft · ":"")+Go.project.showcase.title,V("title").title=Go.projectRoot,ES();let t=xc?gS:Le[he],r=xc&&Yo.find((s)=>s.id===Ec),o=me?.draft&&Yo.find((s)=>s.id===me.draftId);if(r||o&&_e&&(o.revision!==_e.revision||_e.discovery?.state==="pending")){let s=await Gu(r||o,r?gS:_e.scenario);if(r)t=s.structuredContent.scenario;if(me?.draft&&o){_e=s.structuredContent,Cc=s;for(let i of tn)if(i.side==="draft")await i.updateResult(s)}}let n=Wu.find((s)=>s.id===t);if(n&&dw.includes(n.kind))he=n.kind,Le[he]=n.id;else if(xc&&Bu.some((s)=>s.id===t))Le.tokens=t;xc=!1,Wi()}function Ft({force:e=!1}={}){if(Hi)return Promise.resolve();let t=Le[he],r=Vi();if(Ko?.key===r)return Ko.promise;if(!e&&Fi?.key===r)return Promise.resolve();if(!e&&!Ko&&me?.key===r)return Promise.resolve();Fi=void 0;let o={key:r};return Ko=o,o.promise=hw(t,r,he==="tokens").finally(()=>{if(Ko===o)Ko=void 0}),o.promise}async function hw(e,t,r){Zu?.abort();let o=Zu=new AbortController,n=++Rt;Xo=!0,V("loader").hidden=t===Zi,V("preview").setAttribute("aria-busy","true");try{if(++Dt,await Ic(),n!==Rt)return;if(Ku()){await Br(Ue),Ue=void 0,Jr=void 0,ir=void 0;let u=on(),d=await Gu(u,e,o.signal);if(n!==Rt)return;if(_e=d.structuredContent,Cc=d,rn()?.pendingDraftScenario||!Bi().some((m)=>m.id===e))Le[he]=_e.scenario;me={key:Vi(),id:_e.scenario,draftId:u.id,generation:n,draft:!0},Hu(),await gw(),Wi(),cr(!0),Se("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(_e=void 0,Hu(),!e&&!r){if(await Br(Ue),n!==Rt)return;Ue=void 0,me=void 0,Zi=void 0,Jr=void 0,ir=void 0,V("frame-slot").replaceChildren(),cr(),Se("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let s=Oc.find((u)=>u.name===(r?"ads_show_tokens":"ads_show_scenario"));if(!s?._meta?.ui?.resourceUri)throw Error("The server did not expose a preview App tool.");let i=r?e?{category:e}:{}:{id:e};if(s.inputSchema?.properties?.waitFor)i.waitFor=at.get("capture")==="1"||at.get("waitFor")==="verified"?"verified":"compiled";xS();let a=await Fu(s.name,i,o.signal);if(n!==Rt)return;if(a.isError)throw Object.assign(Error(a.content?.find((u)=>u.type==="text")?.text??"Preview build failed."),a.structuredContent?.failure);me={key:t,id:e,generation:n,token:r&&!a.structuredContent?.scenario,build:a.structuredContent?.build,manifestRevision:a.structuredContent?.manifestRevision};let l=await mw(s._meta.ui.resourceUri);if(n!==Rt)return;if(Jr==="ui://ads/preview"&&!me.manifestRevision)throw Error("The resource preview has no manifest revision.");if(Zi!==t)Zi=void 0;if(await l.sendToolInput({arguments:i}),await l.sendToolResult(a),n===Rt&&!a.structuredContent?.manifestUri)cr(!0),Se("")}catch(s){if(n===Rt)Fi={key:Vi(),build:TS(PS())},Pt(s)}}async function mw(e){if(Jr===e&&ir)return ir;let t=++Lu,r=Ue;Ue=void 0,Jr=e,ir=(async()=>{await Br(r);let o=await $c({uri:e});if(t!==Lu||Nc||Hi)throw Error("Preview opening was superseded.");let n=o.contents.find((u)=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text==="string");if(!n)throw Error("The preview resource contains no MCP App.");let s=document.createElement("iframe");s.title="Design-system preview",s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),s.src=Di,V("frame-slot").replaceChildren(s);let i=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:Yu()});Ue=i,i.onreadresource=(u)=>$c(u),i.oncalltool=wS,i.onloggingmessage=(u)=>{if(i!==Ue||u.logger!=="ads-preview"||me?.generation!==Rt||!Tc()||u.data?.id!==me?.id)return;let d=u.data.revision===me.manifestRevision||u.data.selectionRevision===me.manifestRevision;if(u.data.state==="ready"&&d)me.manifestRevision=u.data.revision,cr(!0),Se("");else if(u.data.state==="checking"&&(!Xo||d))cr(!0),Se("Checking changes…");else if(u.data.state==="loading")Se("Updating preview…",!1,"reloading");else if(u.data.state==="reverting")Se("Restoring the last verified preview…",!1,"reverting");else if(u.data.code==="ADS_PREVIEW_REOPEN")Ue=void 0,Jr=void 0,ir=void 0,xS(),Br(i).then(()=>Ft({force:!0})).catch(Pt);else if(u.data.state==="error")cr(),Se(u.data.message,!0)},i.onerror=Pt;let a,l=new Promise((u,d)=>{a=setTimeout(()=>d(Error("MCP App initialization timed out.")),15000),i.oninitialized=()=>{clearTimeout(a),u()}});i.onsandboxready=()=>i.sendSandboxResourceReady({html:n.text,csp:n._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([i.connect(new Li(s.contentWindow,s.contentWindow)),l])}catch(u){throw await Br(i),u}finally{clearTimeout(a)}return i})();try{return await ir}catch(o){if(t===Lu)Jr=void 0,ir=void 0;throw o}}async function fw(){let e=me,t=await zS("ads://project/build");Ji=t,RS();for(let o of V("entries").querySelectorAll("a[data-scenario]")){let n=Bi().find((s)=>s.id===o.dataset.scenario);if(n)kS(o,n)}if(Fi?.key===Vi()){let o=PS(t);if(o&&(o.current||o.live)&&TS(o)!==Fi.build)await Ft({force:!0});return}if(!e||e.token||Xo||!Tc(e))return;if(e.draft){let o=t.drafts?.find((i)=>i.id===e.draftId),n=o?.scenarios?.find((i)=>i.id===_e?.scenario)??o,s=n&&JSON.stringify([o?.session,n.revision,n.live?.revision,n.current]);if(n&&(n.current||n.live)&&e.buildSignature!==s){e.buildSignature=s;let i=Yo.find((a)=>a.id===e.draftId);if(i){let a=await Gu(i,_e.scenario);if(me!==e||Xo||!Tc(e))return;_e=a.structuredContent,Cc=a;for(let l of tn)if(l.side==="draft")await l.updateResult(a)}}if(n?.state==="error")Se("Draft preview build failed. Showing the previous preview.",!0);else if(n?.building)Se(n.live||n.state==="checking"?"Draft preview compiled; checking changes…":"Building draft preview… Showing the previous preview.",!1,n.live||n.state==="checking"?"checking":"compiling");else if(n?.current&&Uu?.state==="ready")Se("Draft preview ready · unaccepted.");return}if(me!==e||Xo||!Tc(e))return;let r=t.previews.find((o)=>o.id===e.id);if(!r){Se("The selected scenario is no longer registered.",!0);return}if(["idle","building"].includes(r.state)&&e.build?.current&&r.session===e.build.session&&r.revision<=e.build.revision)return;if(r.state==="error"){Se(`Preview build failed. Showing an earlier view.
122
+ ${r.diagnostics.map((o)=>`${o.file??""}${o.line?`:${o.line}`:""}: ${o.message}`).join(`
123
+ `)}`,!0);return}if(["idle","building"].includes(r.state)){Se(r.live?"Checking changes…":"Compiling changes… The current view is the previous preview.",!1,r.live?"checking":"compiling");return}if(r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session))await Ft({force:!0})}function Ki(e=!1,t=!1){if(Pc||=e,t&&me?.token)me.key="invalidated";if(clearTimeout(kc),yS)return;kc=setTimeout(()=>{if(ju){Ki(e,t);return}ju=(async()=>{if(Pc)Pc=!1,await Xu();await Ft(),await fw()})().catch(Pt).finally(()=>{ju=void 0})},150)}async function gw(){if(!_e)return;let e=_e,t=Cc;Uu=void 0;let r=++Dt;if(await Ic(),r!==Dt)return;let o=en&&e.acceptedExists;Qe.setAttribute("aria-pressed",String(o));let n=document.createElement("div");n.className="draft-comparison",n.dataset.split=String(o);for(let s of o?["accepted","draft"]:["draft"]){let i=document.createElement("section");i.className="draft-version";let a=document.createElement("h2");a.dataset.version=s,a.textContent=s==="accepted"?"Accepted":"Draft · unaccepted";let l=document.createElement("div");l.className="draft-stage",l.dataset.version=s,i.append(a,l),n.append(i)}V("frame-slot").replaceChildren(n),await Promise.all([...n.querySelectorAll(".draft-stage")].map(async(s)=>{let i=s.dataset.version,a=i==="draft"?t:await vS("ads_show_scenario",{id:e.scenario,waitFor:"compiled"});if(a.isError)throw Error(a.content?.find((d)=>d.type==="text")?.text??"Comparison build failed.");if(r!==Dt)return;let l=Oc.find((d)=>d.name===(i==="draft"?"ads_show_draft":"ads_show_scenario")),u=await pS({slot:s,title:i==="draft"?"Draft version":"Accepted version",sandboxUrl:Di,resourceUri:l._meta.ui.resourceUri,result:a,readResource:$c,callTool:wS,context:(d)=>({theme:ar,displayMode:"inline",containerDimensions:{width:d.clientWidth,height:d.clientHeight}}),onError:(d)=>{if(r===Dt)Pt(d)},onState:(d)=>{if(r!==Dt||i!=="draft")return;if(Uu=d,d.state==="ready")Se("Draft preview ready · unaccepted.");else if(d.state==="checking")Se("Draft preview compiled; checking changes…",!1,"checking");else if(["loading","reverting"].includes(d.state))Se("Updating draft preview…",!1,"reloading")}});if(r!==Dt)await u.close();else tn.push({...u,side:i})}))}function Hu(){let e=rn(),t=Boolean(on(e))&&!e?.draftOnly;Qe.disabled=!t,Qe.title=e?.draftOnly?"No accepted version yet":t?"Compare accepted and draft versions":"No draft for this entry",Qe.setAttribute("aria-pressed",String(t&&en));let r=document.querySelector('.draft-version h2[data-version="draft"]');if(r&&_e){let o={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};r.textContent=`Draft · ${o[_e.state]??_e.state}`,r.title=_e.dependencies?.length?`Draft dependencies: ${_e.dependencies.join(", ")}`:""}}Qe.addEventListener("click",()=>{en=!en,Wi(),Ft().catch(Pt)});for(let e of V("sections").querySelectorAll("button"))e.addEventListener("click",()=>{he=e.dataset.section,Wi(),Ft().catch(Pt)});var Qu=window.matchMedia("(max-width: 760px)");function CS(e){document.body.classList.toggle("collapsed",e),V("pane-toggle").setAttribute("aria-expanded",String(!e)),V("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),V("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",V("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var ed=()=>CS(V("header").hidden||Qu.matches);ed();Qu.addEventListener("change",ed);V("pane-toggle").addEventListener("click",()=>CS(!document.body.classList.contains("collapsed")));function IS(){document.documentElement.dataset.viewport=Qo?"phone":"auto",V("viewport").setAttribute("aria-pressed",String(Qo)),V("viewport").title=Qo?"Use available preview width":"Preview at phone width (390 px)"}IS();V("viewport").addEventListener("click",()=>{Qo=!Qo,IS();let e=new URL(location.href);if(Qo)e.searchParams.set("viewport","phone");else e.searchParams.delete("viewport");history.replaceState(null,"",e.pathname+e.search+e.hash)});V("theme").addEventListener("click",()=>{ar=ar==="light"?"dark":"light",document.documentElement.dataset.theme=ar,V("theme").setAttribute("aria-label",ar==="dark"?"Use light theme":"Use dark theme"),V("theme").title=V("theme").getAttribute("aria-label"),V("theme").querySelector("svg").innerHTML=ar==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>',Ue?.setHostContext(Yu())});V("theme").addEventListener("click",()=>{for(let e of tn)e.refreshContext()});V("minimize").addEventListener("click",()=>{V("header").hidden=!0,document.body.classList.add("collapsed")});var OS=new ResizeObserver(()=>Ue?.setHostContext(Yu()));OS.observe(V("frame-slot"));V("retry-preview").addEventListener("click",()=>{(async()=>{await Xu(),await Ft({force:!0})})().catch(Pt)});window.addEventListener("pagehide",()=>{Nc=!0,Zu?.abort(),Wr.abort(),clearTimeout(kc),OS.disconnect(),Qu.removeEventListener("change",ed),Br(Ue),++Dt,Ic(),Du?.close(),xt.close()},{once:!0});xt.onclose=$S;xt.setNotificationHandler("notifications/resources/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/tools/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/resources/updated",({params:e})=>Ki(e.uri==="ads://project/explorer",e.uri==="ads://project/tokens"));try{if(Di=(await fetch("/host.json").then((e)=>e.json())).sandboxUrl,!Di||new URL(Di).origin===location.origin)throw Error("The separate-origin MCP App sandbox is unavailable.");if(await xt.connect(new Xg(new URL("/mcp",location.href))),Du=await xt.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/explorer"]}),Du.closed.then((e)=>{if(e!=="local")$S()}),await Xu(),yS=!1,await Ft(),Pc)Ki()}catch(e){Pt(e)}