@babylonjs/mcp-servers 9.12.0 → 9.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/flow-graph-mcp-server.js +1 -1
- package/dist/gui-mcp-server.js +1 -1
- package/dist/nge-mcp-server.js +1 -1
- package/dist/nme-mcp-server.js +1 -1
- package/dist/npe-mcp-server.js +1 -1
- package/dist/nrge-mcp-server.js +1 -1
- package/dist/smart-filters-mcp-server.js +1 -1
- package/package.json +1 -1
package/dist/nge-mcp-server.js
CHANGED
|
@@ -67,7 +67,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
67
67
|
]))`;continue}else if(o[c]==="$"){n+=`($|(?=[\r
|
|
68
68
|
]))`;continue}}if(r.s&&o[c]==="."){n+=a?`${o[c]}\r
|
|
69
69
|
`:`[${o[c]}\r
|
|
70
|
-
]`;continue}n+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return n}function qh(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===te.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((o,n)=>({...o,[n]:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Ye(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===te.ZodString&&e.keyType._def.checks?.length){const{type:o,...n}=Gh(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===te.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===te.ZodBranded&&e.keyType._def.type._def.typeName===te.ZodString&&e.keyType._def.type._def.checks?.length){const{type:o,...n}=Lh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function kS(e,t){if(t.mapStrategy==="record")return qh(e,t);const r=ge(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ye(t),o=ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ye(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function SS(e){const t=e.values,o=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function wS(e){return e.target==="openAi"?void 0:{not:Ye({...e,currentPath:[...e.currentPath,"not"]})}}function IS(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const qo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function OS(e,t){if(t.target==="openApi3")return Jh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(o=>o._def.typeName in qo&&(!o._def.checks||!o._def.checks.length))){const o=r.reduce((n,i)=>{const a=qo[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){const o=r.reduce((n,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(o.length===r.length){const n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return Jh(e,t)}const Jh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>ge(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!t.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function xS(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:qo[e.innerType._def.typeName],nullable:!0}:{type:[qo[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const o=ge(e.innerType._def,{...t,currentPath:[...t.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function TS(e,t){const r={type:"number"};if(!e.checks)return r;for(const o of e.checks)switch(o.kind){case"int":r.type="integer",Mh(r,"type",o.message,t);break;case"min":t.target==="jsonSchema7"?o.inclusive?ye(r,"minimum",o.value,o.message,t):ye(r,"exclusiveMinimum",o.value,o.message,t):(o.inclusive||(r.exclusiveMinimum=!0),ye(r,"minimum",o.value,o.message,t));break;case"max":t.target==="jsonSchema7"?o.inclusive?ye(r,"maximum",o.value,o.message,t):ye(r,"exclusiveMaximum",o.value,o.message,t):(o.inclusive||(r.exclusiveMaximum=!0),ye(r,"maximum",o.value,o.message,t));break;case"multipleOf":ye(r,"multipleOf",o.value,o.message,t);break}return r}function PS(e,t){const r=t.target==="openAi",o={type:"object",properties:{}},n=[],i=e.shape();for(const s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=zS(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=ge(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(o.properties[s]=l,u||n.push(s))}n.length&&(o.required=n);const a=ES(e,t);return a!==void 0&&(o.additionalProperties=a),o}function ES(e,t){if(e.catchall._def.typeName!=="ZodNever")return ge(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function zS(e){try{return e.isOptional()}catch{return!0}}const NS=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ge(e.innerType._def,t);const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ye(t)},r]}:Ye(t)},jS=(e,t)=>{if(t.pipeStrategy==="input")return ge(e.in._def,t);if(t.pipeStrategy==="output")return ge(e.out._def,t);const r=ge(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=ge(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function DS(e,t){return ge(e.type._def,t)}function CS(e,t){const o={type:"array",uniqueItems:!0,items:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ye(o,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ye(o,"maxItems",e.maxSize.value,e.maxSize.message,t),o}function RS(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:ge(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function AS(e){return{not:Ye(e)}}function US(e){return Ye(e)}const ZS=(e,t)=>ge(e.innerType._def,t),MS=(e,t,r)=>{switch(t){case te.ZodString:return Gh(e,r);case te.ZodNumber:return TS(e,r);case te.ZodObject:return PS(e,r);case te.ZodBigInt:return lS(e,r);case te.ZodBoolean:return dS();case te.ZodDate:return Fh(e,r);case te.ZodUndefined:return AS(r);case te.ZodNull:return IS(r);case te.ZodArray:return uS(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return OS(e,r);case te.ZodIntersection:return yS(e,r);case te.ZodTuple:return RS(e,r);case te.ZodRecord:return qh(e,r);case te.ZodLiteral:return _S(e,r);case te.ZodEnum:return gS(e);case te.ZodNativeEnum:return SS(e);case te.ZodNullable:return xS(e,r);case te.ZodOptional:return NS(e,r);case te.ZodMap:return kS(e,r);case te.ZodSet:return CS(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return DS(e,r);case te.ZodNaN:case te.ZodNever:return wS(r);case te.ZodEffects:return hS(e,r);case te.ZodAny:return Ye(r);case te.ZodUnknown:return US(r);case te.ZodDefault:return fS(e,r);case te.ZodBranded:return Lh(e,r);case te.ZodReadonly:return ZS(e,r);case te.ZodCatch:return mS(e,r);case te.ZodPipeline:return jS(e,r);case te.ZodFunction:case te.ZodVoid:case te.ZodSymbol:return;default:return(o=>{})()}};function ge(e,t,r=!1){const o=t.seen.get(e);if(t.override){const s=t.override?.(e,t,o,r);if(s!==aS)return s}if(o&&!r){const s=BS(o,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=MS(e,e.typeName,t),a=typeof i=="function"?ge(i(),t):i;if(a&&LS(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const BS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Bh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ye(t)):t.$refStrategy==="seen"?Ye(t):void 0}},LS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),FS=(e,t)=>{const r=cS(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:ge(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ye(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=ge(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Ye(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[r.openAiAnyTypeName]||(o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function GS(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Hh(e,t){return wt(e)?za(e,{target:GS(t?.target),io:t?.pipeStrategy??"input"}):FS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Kh(e){const r=dr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const o=bh(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Wh(e,t){const r=lr(e,t);if(!r.success)throw r.error;return r.data}const VS=6e4;class qS{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(zs,r=>{this._oncancel(r)}),this.setNotificationHandler(js,r=>{this._onprogress(r)}),this.setRequestHandler(Ns,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ds,async(r,o)=>{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new q(W.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Rs,async(r,o)=>{const n=async()=>{const i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,o.sessionId);){if(s.type==="response"||s.type==="error"){const c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{const d=c,p=new q(d.error.code,d.error.message,d.error.data);l(p)}else{const d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:o.requestId})}}const a=await this._taskStore.getTask(i,o.sessionId);if(!a)throw new q(W.InvalidParams,`Task not found: ${i}`);if(!Wt(a.status))return await this._waitForTaskUpdate(i,o.signal),await n();if(Wt(a.status)){const s=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Kt]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(As,async(r,o)=>{try{const{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new q(W.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Zs,async(r,o)=>{try{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new q(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wt(n.status))throw new q(W.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);const i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new q(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof q?n:new q(W.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,o,n,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),q.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};const n=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{n?.(i,a),Zo(i)||Eb(i)?this._onresponse(i):Oh(i)?this._onrequest(i,a):Pb(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(const o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();const r=q.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const o of t.values())o(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){const o=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,i=t.params?._meta?.[Kt]?.taskId;if(o===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:W.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const s=Tb(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;const d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(a.signal.aborted)throw new q(W.ConnectionClosed,"Request was cancelled");const m={...p,relatedRequestId:t.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});const h=m.relatedTask?.taskId??i;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>o(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(a.signal.aborted)return;const d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:W.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...o}=t.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}i(o)}_onresponse(t){const r=Number(t.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Zo(t))o(t);else{const a=new q(t.error.code,t.error.message,t.error.data);o(a)}return}const n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Zo(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),Zo(t))n(t);else{const a=q.fromError(t.error.code,t.error.message,t.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,o){const{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(t,r,o)}}catch(a){yield{type:"error",error:a instanceof q?a:new q(W.InternalError,String(a))}}return}let i;try{const a=await this.request(t,Mo,o);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new q(W.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:s},Wt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:s.status==="failed"?yield{type:"error",error:new q(W.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new q(W.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof q?a:new q(W.InternalError,String(a))}}}request(t,r,o){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=o??{};return new Promise((u,l)=>{const d=y=>{l(y)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(y){d(y);return}o?.signal?.throwIfAborted();const p=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),s&&(m.params={...m.params,task:s}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Kt]:c}});const h=y=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(y)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));const b=y instanceof q?y:new q(W.RequestTimeout,String(y));l(b)};this._responseHandlers.set(p,y=>{if(!o?.signal?.aborted){if(y instanceof Error)return l(y);try{const b=lr(r,y.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),o?.signal?.addEventListener("abort",()=>{h(o?.signal?.reason)});const $=o?.timeout??VS,g=()=>h(q.fromError(W.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(p,$,o?.maxTotalTimeout,g,o?.resetTimeoutOnProgress??!1);const v=c?.taskId;if(v){const y=b=>{const I=this._responseHandlers.get(p);I?I(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,y),this._enqueueTaskMessage(v,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(y=>{this._cleanupTimeout(p),l(y)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Cs,r)}async getTaskResult(t,r,o){return this.request({method:"tasks/result",params:t},r,o)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Us,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Jb,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const o=r?.relatedTask?.taskId;if(o){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Kt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Kt]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Kt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const o=Kh(t);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{const a=Wh(t,n);return Promise.resolve(r(a,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const o=Kh(t);this._notificationHandlers.set(o,n=>{const i=Wh(t,n);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,o,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const o=await this._taskMessageQueue.dequeueAll(t,r);for(const n of o)if(n.type==="request"&&Oh(n.message)){const i=n.message.id,a=this._requestResolvers.get(i);a?(a(new q(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let o=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,i)=>{if(r.aborted){i(new q(W.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new q(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await o.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const i=await o.getTask(n,r);if(!i)throw new q(W.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,a)=>{await o.storeTaskResult(n,i,a,r);const s=await o.getTask(n,r);if(s){const c=Bo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Wt(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,a)=>{const s=await o.getTask(n,r);if(!s)throw new q(W.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Wt(s.status))throw new q(W.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,a,r);const c=await o.getTask(n,r);if(c){const u=Bo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Wt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}}function Yh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function JS(e,t){const r={...e};for(const o in t){const n=o,i=t[n];if(i===void 0)continue;const a=r[n];Yh(a)&&Yh(i)?r[n]={...a,...i}:r[n]=i}return r}function Xh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var rc={exports:{}},Qh={},Pt={},Yt={},oc={},se={},_r={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class o extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((b,I)=>`${b}${I}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((b,I)=>(I instanceof r&&(b[I.str]=(b[I.str]||0)+1),b),{})}}e._Code=o,e.nil=new o("");function n(v,...y){const b=[v[0]];let I=0;for(;I<y.length;)s(b,y[I]),b.push(v[++I]);return new o(b)}e._=n;const i=new o("+");function a(v,...y){const b=[m(v[0])];let I=0;for(;I<y.length;)b.push(i),s(b,y[I]),b.push(i,m(v[++I]));return c(b),new o(b)}e.str=a;function s(v,y){y instanceof o?v.push(...y._items):y instanceof r?v.push(y):v.push(d(y))}e.addCodeArg=s;function c(v){let y=1;for(;y<v.length-1;){if(v[y]===i){const b=u(v[y-1],v[y+1]);if(b!==void 0){v.splice(y-1,3,b);continue}v[y++]="+"}y++}}function u(v,y){if(y==='""')return v;if(v==='""')return y;if(typeof v=="string")return y instanceof r||v[v.length-1]!=='"'?void 0:typeof y!="string"?`${v.slice(0,-1)}${y}"`:y[0]==='"'?v.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(v instanceof r))return`"${v}${y.slice(1)}`}function l(v,y){return y.emptyStr()?v:v.emptyStr()?y:a`${v}${y}`}e.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:m(Array.isArray(v)?v.join(","):v)}function p(v){return new o(m(v))}e.stringify=p;function m(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=m;function h(v){return typeof v=="string"&&e.IDENTIFIER.test(v)?new o(`.${v}`):n`[${v}]`}e.getProperty=h;function $(v){if(typeof v=="string"&&e.IDENTIFIER.test(v))return new o(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}e.getEsmExportName=$;function g(v){return new o(v.toString())}e.regexpCode=g})(_r);var ic={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=_r;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var o;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(o||(e.UsedValueState=o={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=n;class i extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${d}]`}}e.ValueScopeName=i;const a=(0,t._)`\n`;class s extends n{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?a:t.nil}}get(){return this._scope}name(u){return new i(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:m}=p,h=(d=l.key)!==null&&d!==void 0?d:l.ref;let $=this._values[m];if($){const y=$.get(h);if(y)return y}else $=this._values[m]=new Map;$.set(h,p);const g=this._scope[m]||(this._scope[m]=[]),v=g.length;return g[v]=l.ref,p.setValue(l,{property:m,itemIndex:v}),p}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,t._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,d)}_reduceValues(u,l,d={},p){let m=t.nil;for(const h in u){const $=u[h];if(!$)continue;const g=d[h]=d[h]||new Map;$.forEach(v=>{if(g.has(v))return;g.set(v,o.Started);let y=l(v);if(y){const b=this.opts.es5?e.varKinds.var:e.varKinds.const;m=(0,t._)`${m}${b} ${v} = ${y};${this.opts._n}`}else if(y=p?.(v))m=(0,t._)`${m}${y}${this.opts._n}`;else throw new r(v);g.set(v,o.Completed)})}return m}}e.ValueScope=s})(ic),(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=_r,r=ic;var o=_r;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return o.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return o.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return o.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return o.Name}});var n=ic;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class i{optimizeNodes(){return this}optimizeNames(f,_){return this}}class a extends i{constructor(f,_,E){super(),this.varKind=f,this.name=_,this.rhs=E}render({es5:f,_n:_}){const E=f?r.varKinds.var:this.varKind,L=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${L};`+_}optimizeNames(f,_){if(f[this.name.str])return this.rhs&&(this.rhs=H(this.rhs,f,_)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends i{constructor(f,_,E){super(),this.lhs=f,this.rhs=_,this.sideEffects=E}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,_){if(!(this.lhs instanceof t.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=H(this.rhs,f,_),this}get names(){const f=this.lhs instanceof t.Name?{}:{...this.lhs.names};return Y(f,this.rhs)}}class c extends s{constructor(f,_,E,L){super(f,E,L),this.op=_}render({_n:f}){return`${this.lhs} ${this.op}= ${this.rhs};`+f}}class u extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`${this.label}:`+f}}class l extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`break${this.label?` ${this.label}`:""};`+f}}class d extends i{constructor(f){super(),this.error=f}render({_n:f}){return`throw ${this.error};`+f}get names(){return this.error.names}}class p extends i{constructor(f){super(),this.code=f}render({_n:f}){return`${this.code};`+f}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(f,_){return this.code=H(this.code,f,_),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class m extends i{constructor(f=[]){super(),this.nodes=f}render(f){return this.nodes.reduce((_,E)=>_+E.render(f),"")}optimizeNodes(){const{nodes:f}=this;let _=f.length;for(;_--;){const E=f[_].optimizeNodes();Array.isArray(E)?f.splice(_,1,...E):E?f[_]=E:f.splice(_,1)}return f.length>0?this:void 0}optimizeNames(f,_){const{nodes:E}=this;let L=E.length;for(;L--;){const J=E[L];J.optimizeNames(f,_)||(Ee(f,J.names),E.splice(L,1))}return E.length>0?this:void 0}get names(){return this.nodes.reduce((f,_)=>Q(f,_.names),{})}}class h extends m{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class $ extends m{}class g extends h{}g.kind="else";class v extends h{constructor(f,_){super(_),this.condition=f}render(f){let _=`if(${this.condition})`+super.render(f);return this.else&&(_+="else "+this.else.render(f)),_}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let _=this.else;if(_){const E=_.optimizeNodes();_=this.else=Array.isArray(E)?new g(E):E}if(_)return f===!1?_ instanceof v?_:_.nodes:this.nodes.length?this:new v(it(f),_ instanceof v?[_]:_.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,_){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames(f,_),!!(super.optimizeNames(f,_)||this.else))return this.condition=H(this.condition,f,_),this}get names(){const f=super.names;return Y(f,this.condition),this.else&&Q(f,this.else.names),f}}v.kind="if";class y extends h{}y.kind="for";class b extends y{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iteration=H(this.iteration,f,_),this}get names(){return Q(super.names,this.iteration.names)}}class I extends y{constructor(f,_,E,L){super(),this.varKind=f,this.name=_,this.from=E,this.to=L}render(f){const _=f.es5?r.varKinds.var:this.varKind,{name:E,from:L,to:J}=this;return`for(${_} ${E}=${L}; ${E}<${J}; ${E}++)`+super.render(f)}get names(){const f=Y(super.names,this.from);return Y(f,this.to)}}class P extends y{constructor(f,_,E,L){super(),this.loop=f,this.varKind=_,this.name=E,this.iterable=L}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iterable=H(this.iterable,f,_),this}get names(){return Q(super.names,this.iterable.names)}}class M extends h{constructor(f,_,E){super(),this.name=f,this.args=_,this.async=E}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}M.kind="func";class G extends m{render(f){return"return "+super.render(f)}}G.kind="return";class ue extends h{render(f){let _="try"+super.render(f);return this.catch&&(_+=this.catch.render(f)),this.finally&&(_+=this.finally.render(f)),_}optimizeNodes(){var f,_;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(_=this.finally)===null||_===void 0||_.optimizeNodes(),this}optimizeNames(f,_){var E,L;return super.optimizeNames(f,_),(E=this.catch)===null||E===void 0||E.optimizeNames(f,_),(L=this.finally)===null||L===void 0||L.optimizeNames(f,_),this}get names(){const f=super.names;return this.catch&&Q(f,this.catch.names),this.finally&&Q(f,this.finally.names),f}}class pe extends h{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}pe.kind="catch";class Pe extends h{render(f){return"finally"+super.render(f)}}Pe.kind="finally";class B{constructor(f,_={}){this._values={},this._blockStarts=[],this._constants={},this.opts={..._,_n:_.lines?`
|
|
70
|
+
]`;continue}n+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return n}function qh(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===te.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((o,n)=>({...o,[n]:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Ye(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===te.ZodString&&e.keyType._def.checks?.length){const{type:o,...n}=Gh(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===te.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===te.ZodBranded&&e.keyType._def.type._def.typeName===te.ZodString&&e.keyType._def.type._def.checks?.length){const{type:o,...n}=Lh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function kS(e,t){if(t.mapStrategy==="record")return qh(e,t);const r=ge(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ye(t),o=ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ye(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function SS(e){const t=e.values,o=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function wS(e){return e.target==="openAi"?void 0:{not:Ye({...e,currentPath:[...e.currentPath,"not"]})}}function IS(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const qo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function OS(e,t){if(t.target==="openApi3")return Jh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(o=>o._def.typeName in qo&&(!o._def.checks||!o._def.checks.length))){const o=r.reduce((n,i)=>{const a=qo[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){const o=r.reduce((n,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];default:return n}},[]);if(o.length===r.length){const n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return Jh(e,t)}const Jh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>ge(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!t.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function xS(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:qo[e.innerType._def.typeName],nullable:!0}:{type:[qo[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const o=ge(e.innerType._def,{...t,currentPath:[...t.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function TS(e,t){const r={type:"number"};if(!e.checks)return r;for(const o of e.checks)switch(o.kind){case"int":r.type="integer",Mh(r,"type",o.message,t);break;case"min":t.target==="jsonSchema7"?o.inclusive?ye(r,"minimum",o.value,o.message,t):ye(r,"exclusiveMinimum",o.value,o.message,t):(o.inclusive||(r.exclusiveMinimum=!0),ye(r,"minimum",o.value,o.message,t));break;case"max":t.target==="jsonSchema7"?o.inclusive?ye(r,"maximum",o.value,o.message,t):ye(r,"exclusiveMaximum",o.value,o.message,t):(o.inclusive||(r.exclusiveMaximum=!0),ye(r,"maximum",o.value,o.message,t));break;case"multipleOf":ye(r,"multipleOf",o.value,o.message,t);break}return r}function PS(e,t){const r=t.target==="openAi",o={type:"object",properties:{}},n=[],i=e.shape();for(const s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=zS(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=ge(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(o.properties[s]=l,u||n.push(s))}n.length&&(o.required=n);const a=ES(e,t);return a!==void 0&&(o.additionalProperties=a),o}function ES(e,t){if(e.catchall._def.typeName!=="ZodNever")return ge(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function zS(e){try{return e.isOptional()}catch{return!0}}const NS=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ge(e.innerType._def,t);const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ye(t)},r]}:Ye(t)},jS=(e,t)=>{if(t.pipeStrategy==="input")return ge(e.in._def,t);if(t.pipeStrategy==="output")return ge(e.out._def,t);const r=ge(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=ge(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function DS(e,t){return ge(e.type._def,t)}function CS(e,t){const o={type:"array",uniqueItems:!0,items:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ye(o,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ye(o,"maxItems",e.maxSize.value,e.maxSize.message,t),o}function RS(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:ge(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function AS(e){return{not:Ye(e)}}function US(e){return Ye(e)}const ZS=(e,t)=>ge(e.innerType._def,t),MS=(e,t,r)=>{switch(t){case te.ZodString:return Gh(e,r);case te.ZodNumber:return TS(e,r);case te.ZodObject:return PS(e,r);case te.ZodBigInt:return lS(e,r);case te.ZodBoolean:return dS();case te.ZodDate:return Fh(e,r);case te.ZodUndefined:return AS(r);case te.ZodNull:return IS(r);case te.ZodArray:return uS(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return OS(e,r);case te.ZodIntersection:return yS(e,r);case te.ZodTuple:return RS(e,r);case te.ZodRecord:return qh(e,r);case te.ZodLiteral:return _S(e,r);case te.ZodEnum:return gS(e);case te.ZodNativeEnum:return SS(e);case te.ZodNullable:return xS(e,r);case te.ZodOptional:return NS(e,r);case te.ZodMap:return kS(e,r);case te.ZodSet:return CS(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return DS(e,r);case te.ZodNaN:case te.ZodNever:return wS(r);case te.ZodEffects:return hS(e,r);case te.ZodAny:return Ye(r);case te.ZodUnknown:return US(r);case te.ZodDefault:return fS(e,r);case te.ZodBranded:return Lh(e,r);case te.ZodReadonly:return ZS(e,r);case te.ZodCatch:return mS(e,r);case te.ZodPipeline:return jS(e,r);case te.ZodFunction:case te.ZodVoid:case te.ZodSymbol:return;default:return(o=>{})()}};function ge(e,t,r=!1){const o=t.seen.get(e);if(t.override){const s=t.override?.(e,t,o,r);if(s!==aS)return s}if(o&&!r){const s=BS(o,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=MS(e,e.typeName,t),a=typeof i=="function"?ge(i(),t):i;if(a&&LS(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const BS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Bh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ye(t)):t.$refStrategy==="seen"?Ye(t):void 0}},LS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),FS=(e,t)=>{const r=cS(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:ge(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ye(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=ge(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Ye(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[r.openAiAnyTypeName]||(o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function GS(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Hh(e,t){return wt(e)?za(e,{target:GS(t?.target),io:t?.pipeStrategy??"input"}):FS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Kh(e){const r=dr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const o=bh(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Wh(e,t){const r=lr(e,t);if(!r.success)throw r.error;return r.data}const VS=6e4;class qS{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(zs,r=>{this._oncancel(r)}),this.setNotificationHandler(js,r=>{this._onprogress(r)}),this.setRequestHandler(Ns,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ds,async(r,o)=>{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new q(W.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Rs,async(r,o)=>{const n=async()=>{const i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,o.sessionId);){if(s.type==="response"||s.type==="error"){const c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{const d=c,p=new q(d.error.code,d.error.message,d.error.data);l(p)}else{const d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:o.requestId})}}const a=await this._taskStore.getTask(i,o.sessionId);if(!a)throw new q(W.InvalidParams,`Task not found: ${i}`);if(!Wt(a.status))return await this._waitForTaskUpdate(i,o.signal),await n();if(Wt(a.status)){const s=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Kt]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(As,async(r,o)=>{try{const{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new q(W.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Zs,async(r,o)=>{try{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new q(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wt(n.status))throw new q(W.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);const i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new q(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof q?n:new q(W.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,o,n,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),q.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};const n=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{n?.(i,a),Zo(i)||Eb(i)?this._onresponse(i):Oh(i)?this._onrequest(i,a):Pb(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(const o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();const r=q.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const o of t.values())o(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){const o=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,i=t.params?._meta?.[Kt]?.taskId;if(o===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:W.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const s=Tb(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;const d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(a.signal.aborted)throw new q(W.ConnectionClosed,"Request was cancelled");const m={...p,relatedRequestId:t.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});const h=m.relatedTask?.taskId??i;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>o(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(a.signal.aborted)return;const d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:W.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...o}=t.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}i(o)}_onresponse(t){const r=Number(t.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Zo(t))o(t);else{const a=new q(t.error.code,t.error.message,t.error.data);o(a)}return}const n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Zo(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),Zo(t))n(t);else{const a=q.fromError(t.error.code,t.error.message,t.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,o){const{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(t,r,o)}}catch(a){yield{type:"error",error:a instanceof q?a:new q(W.InternalError,String(a))}}return}let i;try{const a=await this.request(t,Mo,o);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new q(W.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:s},Wt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:s.status==="failed"?yield{type:"error",error:new q(W.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new q(W.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof q?a:new q(W.InternalError,String(a))}}}request(t,r,o){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=o??{};return new Promise((u,l)=>{const d=y=>{l(y)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(y){d(y);return}o?.signal?.throwIfAborted();const p=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),s&&(m.params={...m.params,task:s}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Kt]:c}});const h=y=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(y)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));const b=y instanceof q?y:new q(W.RequestTimeout,String(y));l(b)};this._responseHandlers.set(p,y=>{if(!o?.signal?.aborted){if(y instanceof Error)return l(y);try{const b=lr(r,y.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),o?.signal?.addEventListener("abort",()=>{h(o?.signal?.reason)});const $=o?.timeout??VS,g=()=>h(q.fromError(W.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(p,$,o?.maxTotalTimeout,g,o?.resetTimeoutOnProgress??!1);const v=c?.taskId;if(v){const y=b=>{const I=this._responseHandlers.get(p);I?I(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,y),this._enqueueTaskMessage(v,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(y=>{this._cleanupTimeout(p),l(y)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Cs,r)}async getTaskResult(t,r,o){return this.request({method:"tasks/result",params:t},r,o)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Us,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Jb,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const o=r?.relatedTask?.taskId;if(o){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Kt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Kt]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Kt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const o=Kh(t);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{const a=Wh(t,n);return Promise.resolve(r(a,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const o=Kh(t);this._notificationHandlers.set(o,n=>{const i=Wh(t,n);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,o,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const o=await this._taskMessageQueue.dequeueAll(t,r);for(const n of o)if(n.type==="request"&&Oh(n.message)){const i=n.message.id,a=this._requestResolvers.get(i);a?(a(new q(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let o=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,i)=>{if(r.aborted){i(new q(W.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new q(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await o.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const i=await o.getTask(n,r);if(!i)throw new q(W.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,a)=>{await o.storeTaskResult(n,i,a,r);const s=await o.getTask(n,r);if(s){const c=Bo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Wt(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,a)=>{const s=await o.getTask(n,r);if(!s)throw new q(W.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Wt(s.status))throw new q(W.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,a,r);const c=await o.getTask(n,r);if(c){const u=Bo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Wt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}}function Yh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function JS(e,t){const r={...e};for(const o in t){const n=o,i=t[n];if(i===void 0)continue;const a=r[n];Yh(a)&&Yh(i)?r[n]={...a,...i}:r[n]=i}return r}function Xh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var rc={exports:{}},Qh={},Pt={},Yt={},oc={},se={},_r={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class o extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((b,I)=>`${b}${I}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((b,I)=>(I instanceof r&&(b[I.str]=(b[I.str]||0)+1),b),{})}}e._Code=o,e.nil=new o("");function n(v,...y){const b=[v[0]];let I=0;for(;I<y.length;)s(b,y[I]),b.push(v[++I]);return new o(b)}e._=n;const i=new o("+");function a(v,...y){const b=[m(v[0])];let I=0;for(;I<y.length;)b.push(i),s(b,y[I]),b.push(i,m(v[++I]));return c(b),new o(b)}e.str=a;function s(v,y){y instanceof o?v.push(...y._items):y instanceof r?v.push(y):v.push(d(y))}e.addCodeArg=s;function c(v){let y=1;for(;y<v.length-1;){if(v[y]===i){const b=u(v[y-1],v[y+1]);if(b!==void 0){v.splice(y-1,3,b);continue}v[y++]="+"}y++}}function u(v,y){if(y==='""')return v;if(v==='""')return y;if(typeof v=="string")return y instanceof r||v[v.length-1]!=='"'?void 0:typeof y!="string"?`${v.slice(0,-1)}${y}"`:y[0]==='"'?v.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(v instanceof r))return`"${v}${y.slice(1)}`}function l(v,y){return y.emptyStr()?v:v.emptyStr()?y:a`${v}${y}`}e.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:m(Array.isArray(v)?v.join(","):v)}function p(v){return new o(m(v))}e.stringify=p;function m(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=m;function h(v){return typeof v=="string"&&e.IDENTIFIER.test(v)?new o(`.${v}`):n`[${v}]`}e.getProperty=h;function $(v){if(typeof v=="string"&&e.IDENTIFIER.test(v))return new o(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}e.getEsmExportName=$;function g(v){return new o(v.toString())}e.regexpCode=g})(_r);var ic={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=_r;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var o;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(o||(e.UsedValueState=o={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=n;class i extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${d}]`}}e.ValueScopeName=i;const a=(0,t._)`\n`;class s extends n{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?a:t.nil}}get(){return this._scope}name(u){return new i(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:m}=p,h=(d=l.key)!==null&&d!==void 0?d:l.ref;let $=this._values[m];if($){const y=$.get(h);if(y)return y}else $=this._values[m]=new Map;$.set(h,p);const g=this._scope[m]||(this._scope[m]=[]),v=g.length;return g[v]=l.ref,p.setValue(l,{property:m,itemIndex:v}),p}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,t._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,d)}_reduceValues(u,l,d={},p){let m=t.nil;for(const h in u){const $=u[h];if(!$)continue;const g=d[h]=d[h]||new Map;$.forEach(v=>{if(g.has(v))return;g.set(v,o.Started);let y=l(v);if(y){const b=this.opts.es5?e.varKinds.var:e.varKinds.const;m=(0,t._)`${m}${b} ${v} = ${y};${this.opts._n}`}else if(y=p?.(v))m=(0,t._)`${m}${y}${this.opts._n}`;else throw new r(v);g.set(v,o.Completed)})}return m}}e.ValueScope=s})(ic),(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=_r,r=ic;var o=_r;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return o.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return o.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return o.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return o.Name}});var n=ic;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class i{optimizeNodes(){return this}optimizeNames(f,_){return this}}class a extends i{constructor(f,_,E){super(),this.varKind=f,this.name=_,this.rhs=E}render({es5:f,_n:_}){const E=f?r.varKinds.var:this.varKind,L=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${L};`+_}optimizeNames(f,_){if(f[this.name.str])return this.rhs&&(this.rhs=H(this.rhs,f,_)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends i{constructor(f,_,E){super(),this.lhs=f,this.rhs=_,this.sideEffects=E}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,_){if(!(this.lhs instanceof t.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=H(this.rhs,f,_),this}get names(){const f=this.lhs instanceof t.Name?{}:{...this.lhs.names};return Y(f,this.rhs)}}class c extends s{constructor(f,_,E,L){super(f,E,L),this.op=_}render({_n:f}){return`${this.lhs} ${this.op}= ${this.rhs};`+f}}class u extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`${this.label}:`+f}}class l extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`break${this.label?` ${this.label}`:""};`+f}}class d extends i{constructor(f){super(),this.error=f}render({_n:f}){return`throw ${this.error};`+f}get names(){return this.error.names}}class p extends i{constructor(f){super(),this.code=f}render({_n:f}){return`${this.code};`+f}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(f,_){return this.code=H(this.code,f,_),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class m extends i{constructor(f=[]){super(),this.nodes=f}render(f){return this.nodes.reduce((_,E)=>_+E.render(f),"")}optimizeNodes(){const{nodes:f}=this;let _=f.length;for(;_--;){const E=f[_].optimizeNodes();Array.isArray(E)?f.splice(_,1,...E):E?f[_]=E:f.splice(_,1)}return f.length>0?this:void 0}optimizeNames(f,_){const{nodes:E}=this;let L=E.length;for(;L--;){const J=E[L];J.optimizeNames(f,_)||(Ee(f,J.names),E.splice(L,1))}return E.length>0?this:void 0}get names(){return this.nodes.reduce((f,_)=>Q(f,_.names),{})}}class h extends m{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class $ extends m{}class g extends h{}g.kind="else";class v extends h{constructor(f,_){super(_),this.condition=f}render(f){let _=`if(${this.condition})`+super.render(f);return this.else&&(_+="else "+this.else.render(f)),_}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let _=this.else;if(_){const E=_.optimizeNodes();_=this.else=Array.isArray(E)?new g(E):E}if(_)return f===!1?_ instanceof v?_:_.nodes:this.nodes.length?this:new v(it(f),_ instanceof v?[_]:_.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,_){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames(f,_),!!(super.optimizeNames(f,_)||this.else))return this.condition=H(this.condition,f,_),this}get names(){const f=super.names;return Y(f,this.condition),this.else&&Q(f,this.else.names),f}}v.kind="if";class y extends h{}y.kind="for";class b extends y{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iteration=H(this.iteration,f,_),this}get names(){return Q(super.names,this.iteration.names)}}class I extends y{constructor(f,_,E,L){super(),this.varKind=f,this.name=_,this.from=E,this.to=L}render(f){const _=f.es5?r.varKinds.var:this.varKind,{name:E,from:L,to:J}=this;return`for(${_} ${E}=${L}; ${E}<${J}; ${E}++)`+super.render(f)}get names(){const f=Y(super.names,this.from);return Y(f,this.to)}}class P extends y{constructor(f,_,E,L){super(),this.loop=f,this.varKind=_,this.name=E,this.iterable=L}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iterable=H(this.iterable,f,_),this}get names(){return Q(super.names,this.iterable.names)}}class M extends h{constructor(f,_,E){super(),this.name=f,this.args=_,this.async=E}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}M.kind="func";class G extends m{render(f){return"return "+super.render(f)}}G.kind="return";class ue extends h{render(f){let _="try"+super.render(f);return this.catch&&(_+=this.catch.render(f)),this.finally&&(_+=this.finally.render(f)),_}optimizeNodes(){var f,_;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(_=this.finally)===null||_===void 0||_.optimizeNodes(),this}optimizeNames(f,_){var E,L;return super.optimizeNames(f,_),(E=this.catch)===null||E===void 0||E.optimizeNames(f,_),(L=this.finally)===null||L===void 0||L.optimizeNames(f,_),this}get names(){const f=super.names;return this.catch&&Q(f,this.catch.names),this.finally&&Q(f,this.finally.names),f}}class pe extends h{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}pe.kind="catch";class Pe extends h{render(f){return"finally"+super.render(f)}}Pe.kind="finally";class B{constructor(f,_={}){this._values={},this._blockStarts=[],this._constants={},this.opts={..._,_n:_.lines?`
|
|
71
71
|
`:""},this._extScope=f,this._scope=new r.Scope({parent:f}),this._nodes=[new $]}toString(){return this._root.render(this.opts)}name(f){return this._scope.name(f)}scopeName(f){return this._extScope.name(f)}scopeValue(f,_){const E=this._extScope.value(f,_);return(this._values[E.prefix]||(this._values[E.prefix]=new Set)).add(E),E}getScopeValue(f,_){return this._extScope.getValue(f,_)}scopeRefs(f){return this._extScope.scopeRefs(f,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(f,_,E,L){const J=this._scope.toName(_);return E!==void 0&&L&&(this._constants[J.str]=E),this._leafNode(new a(f,J,E)),J}const(f,_,E){return this._def(r.varKinds.const,f,_,E)}let(f,_,E){return this._def(r.varKinds.let,f,_,E)}var(f,_,E){return this._def(r.varKinds.var,f,_,E)}assign(f,_,E){return this._leafNode(new s(f,_,E))}add(f,_){return this._leafNode(new c(f,e.operators.ADD,_))}code(f){return typeof f=="function"?f():f!==t.nil&&this._leafNode(new p(f)),this}object(...f){const _=["{"];for(const[E,L]of f)_.length>1&&_.push(","),_.push(E),(E!==L||this.opts.es5)&&(_.push(":"),(0,t.addCodeArg)(_,L));return _.push("}"),new t._Code(_)}if(f,_,E){if(this._blockNode(new v(f)),_&&E)this.code(_).else().code(E).endIf();else if(_)this.code(_).endIf();else if(E)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(f){return this._elseNode(new v(f))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(v,g)}_for(f,_){return this._blockNode(f),_&&this.code(_).endFor(),this}for(f,_){return this._for(new b(f),_)}forRange(f,_,E,L,J=this.opts.es5?r.varKinds.var:r.varKinds.let){const fe=this._scope.toName(f);return this._for(new I(J,fe,_,E),()=>L(fe))}forOf(f,_,E,L=r.varKinds.const){const J=this._scope.toName(f);if(this.opts.es5){const fe=_ instanceof t.Name?_:this.var("_arr",_);return this.forRange("_i",0,(0,t._)`${fe}.length`,le=>{this.var(J,(0,t._)`${fe}[${le}]`),E(J)})}return this._for(new P("of",L,J,_),()=>E(J))}forIn(f,_,E,L=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(f,(0,t._)`Object.keys(${_})`,E);const J=this._scope.toName(f);return this._for(new P("in",L,J,_),()=>E(J))}endFor(){return this._endBlockNode(y)}label(f){return this._leafNode(new u(f))}break(f){return this._leafNode(new l(f))}return(f){const _=new G;if(this._blockNode(_),this.code(f),_.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(G)}try(f,_,E){if(!_&&!E)throw new Error('CodeGen: "try" without "catch" and "finally"');const L=new ue;if(this._blockNode(L),this.code(f),_){const J=this.name("e");this._currNode=L.catch=new pe(J),_(J)}return E&&(this._currNode=L.finally=new Pe,this.code(E)),this._endBlockNode(pe,Pe)}throw(f){return this._leafNode(new d(f))}block(f,_){return this._blockStarts.push(this._nodes.length),f&&this.code(f).endBlock(_),this}endBlock(f){const _=this._blockStarts.pop();if(_===void 0)throw new Error("CodeGen: not in self-balancing block");const E=this._nodes.length-_;if(E<0||f!==void 0&&E!==f)throw new Error(`CodeGen: wrong number of nodes: ${E} vs ${f} expected`);return this._nodes.length=_,this}func(f,_=t.nil,E,L){return this._blockNode(new M(f,_,E)),L&&this.code(L).endFunc(),this}endFunc(){return this._endBlockNode(M)}optimize(f=1){for(;f-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(f){return this._currNode.nodes.push(f),this}_blockNode(f){this._currNode.nodes.push(f),this._nodes.push(f)}_endBlockNode(f,_){const E=this._currNode;if(E instanceof f||_&&E instanceof _)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${_?`${f.kind}/${_.kind}`:f.kind}"`)}_elseNode(f){const _=this._currNode;if(!(_ instanceof v))throw new Error('CodeGen: "else" without "if"');return this._currNode=_.else=f,this}get _root(){return this._nodes[0]}get _currNode(){const f=this._nodes;return f[f.length-1]}set _currNode(f){const _=this._nodes;_[_.length-1]=f}}e.CodeGen=B;function Q(T,f){for(const _ in f)T[_]=(T[_]||0)+(f[_]||0);return T}function Y(T,f){return f instanceof t._CodeOrName?Q(T,f.names):T}function H(T,f,_){if(T instanceof t.Name)return E(T);if(!L(T))return T;return new t._Code(T._items.reduce((J,fe)=>(fe instanceof t.Name&&(fe=E(fe)),fe instanceof t._Code?J.push(...fe._items):J.push(fe),J),[]));function E(J){const fe=_[J.str];return fe===void 0||f[J.str]!==1?J:(delete f[J.str],fe)}function L(J){return J instanceof t._Code&&J._items.some(fe=>fe instanceof t.Name&&f[fe.str]===1&&_[fe.str]!==void 0)}}function Ee(T,f){for(const _ in f)T[_]=(T[_]||0)-(f[_]||0)}function it(T){return typeof T=="boolean"||typeof T=="number"||T===null?!T:(0,t._)`!${j(T)}`}e.not=it;const at=O(e.operators.AND);function Lt(...T){return T.reduce(at)}e.and=Lt;const Ot=O(e.operators.OR);function R(...T){return T.reduce(Ot)}e.or=R;function O(T){return(f,_)=>f===t.nil?_:_===t.nil?f:(0,t._)`${j(f)} ${T} ${j(_)}`}function j(T){return T instanceof t.Name?T:(0,t._)`(${T})`}})(se);var Z={};Object.defineProperty(Z,"__esModule",{value:!0}),Z.checkStrictMode=Z.getErrorPath=Z.Type=Z.useFunc=Z.setEvaluated=Z.evaluatedPropsToName=Z.mergeEvaluated=Z.eachItem=Z.unescapeJsonPointer=Z.escapeJsonPointer=Z.escapeFragment=Z.unescapeFragment=Z.schemaRefOrVal=Z.schemaHasRulesButRef=Z.schemaHasRules=Z.checkUnknownRules=Z.alwaysValidSchema=Z.toHash=void 0;const we=se,HS=_r;function KS(e){const t={};for(const r of e)t[r]=!0;return t}Z.toHash=KS;function WS(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(eg(e,t),!tg(t,e.self.RULES.all))}Z.alwaysValidSchema=WS;function eg(e,t=e.schema){const{opts:r,self:o}=e;if(!r.strictSchema||typeof t=="boolean")return;const n=o.RULES.keywords;for(const i in t)n[i]||ag(e,`unknown keyword: "${i}"`)}Z.checkUnknownRules=eg;function tg(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(t[r])return!0;return!1}Z.schemaHasRules=tg;function YS(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}Z.schemaHasRulesButRef=YS;function XS({topSchemaRef:e,schemaPath:t},r,o,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,we._)`${r}`}return(0,we._)`${e}${t}${(0,we.getProperty)(o)}`}Z.schemaRefOrVal=XS;function QS(e){return ng(decodeURIComponent(e))}Z.unescapeFragment=QS;function ew(e){return encodeURIComponent(ac(e))}Z.escapeFragment=ew;function ac(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=ac;function ng(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=ng;function tw(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)}Z.eachItem=tw;function rg({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:o}){return(n,i,a,s)=>{const c=a===void 0?i:a instanceof we.Name?(i instanceof we.Name?e(n,i,a):t(n,i,a),a):i instanceof we.Name?(t(n,a,i),i):r(i,a);return s===we.Name&&!(c instanceof we.Name)?o(n,c):c}}Z.mergeEvaluated={props:rg({mergeNames:(e,t,r)=>e.if((0,we._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,we._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,we._)`${r} || {}`).code((0,we._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,we._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,we._)`${r} || {}`),sc(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:og}),items:rg({mergeNames:(e,t,r)=>e.if((0,we._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,we._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,we._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,we._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function og(e,t){if(t===!0)return e.var("props",!0);const r=e.var("props",(0,we._)`{}`);return t!==void 0&&sc(e,r,t),r}Z.evaluatedPropsToName=og;function sc(e,t,r){Object.keys(r).forEach(o=>e.assign((0,we._)`${t}${(0,we.getProperty)(o)}`,!0))}Z.setEvaluated=sc;const ig={};function nw(e,t){return e.scopeValue("func",{ref:t,code:ig[t.code]||(ig[t.code]=new HS._Code(t.code))})}Z.useFunc=nw;var cc;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(cc||(Z.Type=cc={}));function rw(e,t,r){if(e instanceof we.Name){const o=t===cc.Num;return r?o?(0,we._)`"[" + ${e} + "]"`:(0,we._)`"['" + ${e} + "']"`:o?(0,we._)`"/" + ${e}`:(0,we._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,we.getProperty)(e).toString():"/"+ac(e)}Z.getErrorPath=rw;function ag(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}Z.checkStrictMode=ag;var Jo={},sg;function At(){if(sg)return Jo;sg=1,Object.defineProperty(Jo,"__esModule",{value:!0});const e=se,t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Jo.default=t,Jo}var cg;function Ho(){return cg||(cg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=se,r=Z,o=At();e.keywordError={message:({keyword:g})=>(0,t.str)`must pass "${g}" keyword validation`},e.keyword$DataError={message:({keyword:g,schemaType:v})=>v?(0,t.str)`"${g}" keyword must be ${v} ($data)`:(0,t.str)`"${g}" keyword is invalid ($data)`};function n(g,v=e.keywordError,y,b){const{it:I}=g,{gen:P,compositeRule:M,allErrors:G}=I,ue=d(g,v,y);b??(M||G)?c(P,ue):u(I,(0,t._)`[${ue}]`)}e.reportError=n;function i(g,v=e.keywordError,y){const{it:b}=g,{gen:I,compositeRule:P,allErrors:M}=b,G=d(g,v,y);c(I,G),P||M||u(b,o.default.vErrors)}e.reportExtraError=i;function a(g,v){g.assign(o.default.errors,v),g.if((0,t._)`${o.default.vErrors} !== null`,()=>g.if(v,()=>g.assign((0,t._)`${o.default.vErrors}.length`,v),()=>g.assign(o.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:g,keyword:v,schemaValue:y,data:b,errsCount:I,it:P}){if(I===void 0)throw new Error("ajv implementation error");const M=g.name("err");g.forRange("i",I,o.default.errors,G=>{g.const(M,(0,t._)`${o.default.vErrors}[${G}]`),g.if((0,t._)`${M}.instancePath === undefined`,()=>g.assign((0,t._)`${M}.instancePath`,(0,t.strConcat)(o.default.instancePath,P.errorPath))),g.assign((0,t._)`${M}.schemaPath`,(0,t.str)`${P.errSchemaPath}/${v}`),P.opts.verbose&&(g.assign((0,t._)`${M}.schema`,y),g.assign((0,t._)`${M}.data`,b))})}e.extendErrors=s;function c(g,v){const y=g.const("err",v);g.if((0,t._)`${o.default.vErrors} === null`,()=>g.assign(o.default.vErrors,(0,t._)`[${y}]`),(0,t._)`${o.default.vErrors}.push(${y})`),g.code((0,t._)`${o.default.errors}++`)}function u(g,v){const{gen:y,validateName:b,schemaEnv:I}=g;I.$async?y.throw((0,t._)`new ${g.ValidationError}(${v})`):(y.assign((0,t._)`${b}.errors`,v),y.return(!1))}const l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function d(g,v,y){const{createErrors:b}=g.it;return b===!1?(0,t._)`{}`:p(g,v,y)}function p(g,v,y={}){const{gen:b,it:I}=g,P=[m(I,y),h(g,y)];return $(g,v,P),b.object(...P)}function m({errorPath:g},{instancePath:v}){const y=v?(0,t.str)`${g}${(0,r.getErrorPath)(v,r.Type.Str)}`:g;return[o.default.instancePath,(0,t.strConcat)(o.default.instancePath,y)]}function h({keyword:g,it:{errSchemaPath:v}},{schemaPath:y,parentSchema:b}){let I=b?v:(0,t.str)`${v}/${g}`;return y&&(I=(0,t.str)`${I}${(0,r.getErrorPath)(y,r.Type.Str)}`),[l.schemaPath,I]}function $(g,{params:v,message:y},b){const{keyword:I,data:P,schemaValue:M,it:G}=g,{opts:ue,propertyName:pe,topSchemaRef:Pe,schemaPath:B}=G;b.push([l.keyword,I],[l.params,typeof v=="function"?v(g):v||(0,t._)`{}`]),ue.messages&&b.push([l.message,typeof y=="function"?y(g):y]),ue.verbose&&b.push([l.schema,M],[l.parentSchema,(0,t._)`${Pe}${B}`],[o.default.data,P]),pe&&b.push([l.propertyName,pe])}})(oc)),oc}var ug;function ow(){if(ug)return Yt;ug=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.boolOrEmptySchema=Yt.topBoolOrEmptySchema=void 0;const e=Ho(),t=se,r=At(),o={message:"boolean schema is false"};function n(s){const{gen:c,schema:u,validateName:l}=s;u===!1?a(s,!1):typeof u=="object"&&u.$async===!0?c.return(r.default.data):(c.assign((0,t._)`${l}.errors`,null),c.return(!0))}Yt.topBoolOrEmptySchema=n;function i(s,c){const{gen:u,schema:l}=s;l===!1?(u.var(c,!1),a(s)):u.var(c,!0)}Yt.boolOrEmptySchema=i;function a(s,c){const{gen:u,data:l}=s,d={gen:u,keyword:"false schema",data:l,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:s};(0,e.reportError)(d,o,void 0,c)}return Yt}var De={},Xt={};Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.getRules=Xt.isJSONType=void 0;const iw=["string","number","integer","boolean","null","object","array"],aw=new Set(iw);function sw(e){return typeof e=="string"&&aw.has(e)}Xt.isJSONType=sw;function cw(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Xt.getRules=cw;var Et={},lg;function dg(){if(lg)return Et;lg=1,Object.defineProperty(Et,"__esModule",{value:!0}),Et.shouldUseRule=Et.shouldUseGroup=Et.schemaHasRulesForType=void 0;function e({schema:o,self:n},i){const a=n.RULES.types[i];return a&&a!==!0&&t(o,a)}Et.schemaHasRulesForType=e;function t(o,n){return n.rules.some(i=>r(o,i))}Et.shouldUseGroup=t;function r(o,n){var i;return o[n.keyword]!==void 0||((i=n.definition.implements)===null||i===void 0?void 0:i.some(a=>o[a]!==void 0))}return Et.shouldUseRule=r,Et}Object.defineProperty(De,"__esModule",{value:!0}),De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;const uw=Xt,lw=dg(),dw=Ho(),re=se,mg=Z;var bn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(bn||(De.DataType=bn={}));function mw(e){const t=pg(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}De.getSchemaTypes=mw;function pg(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(uw.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}De.getJSONTypes=pg;function pw(e,t){const{gen:r,data:o,opts:n}=e,i=fw(t,n.coerceTypes),a=t.length>0&&!(i.length===0&&t.length===1&&(0,lw.schemaHasRulesForType)(e,t[0]));if(a){const s=lc(t,o,n.strictNumbers,bn.Wrong);r.if(s,()=>{i.length?hw(e,t,i):dc(e)})}return a}De.coerceAndCheckDataType=pw;const fg=new Set(["string","number","integer","boolean","null"]);function fw(e,t){return t?e.filter(r=>fg.has(r)||t==="array"&&r==="array"):[]}function hw(e,t,r){const{gen:o,data:n,opts:i}=e,a=o.let("dataType",(0,re._)`typeof ${n}`),s=o.let("coerced",(0,re._)`undefined`);i.coerceTypes==="array"&&o.if((0,re._)`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,(0,re._)`${n}[0]`).assign(a,(0,re._)`typeof ${n}`).if(lc(t,n,i.strictNumbers),()=>o.assign(s,n))),o.if((0,re._)`${s} !== undefined`);for(const u of r)(fg.has(u)||u==="array"&&i.coerceTypes==="array")&&c(u);o.else(),dc(e),o.endIf(),o.if((0,re._)`${s} !== undefined`,()=>{o.assign(n,s),gw(e,s)});function c(u){switch(u){case"string":o.elseIf((0,re._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,re._)`"" + ${n}`).elseIf((0,re._)`${n} === null`).assign(s,(0,re._)`""`);return;case"number":o.elseIf((0,re._)`${a} == "boolean" || ${n} === null
|
|
72
72
|
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(s,(0,re._)`+${n}`);return;case"integer":o.elseIf((0,re._)`${a} === "boolean" || ${n} === null
|
|
73
73
|
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(s,(0,re._)`+${n}`);return;case"boolean":o.elseIf((0,re._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(s,!1).elseIf((0,re._)`${n} === "true" || ${n} === 1`).assign(s,!0);return;case"null":o.elseIf((0,re._)`${n} === "" || ${n} === 0 || ${n} === false`),o.assign(s,null);return;case"array":o.elseIf((0,re._)`${a} === "string" || ${a} === "number"
|
package/dist/nme-mcp-server.js
CHANGED
|
@@ -67,7 +67,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
67
67
|
]))`;continue}else if(o[c]==="$"){n+=`($|(?=[\r
|
|
68
68
|
]))`;continue}}if(r.s&&o[c]==="."){n+=a?`${o[c]}\r
|
|
69
69
|
`:`[${o[c]}\r
|
|
70
|
-
]`;continue}n+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return n}function Xh(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===te.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((o,n)=>({...o,[n]:he(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??We(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:he(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===te.ZodString&&e.keyType._def.checks?.length){const{type:o,...n}=Wh(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===te.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===te.ZodBranded&&e.keyType._def.type._def.typeName===te.ZodString&&e.keyType._def.type._def.checks?.length){const{type:o,...n}=Kh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function PS(e,t){if(t.mapStrategy==="record")return Xh(e,t);const r=he(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||We(t),o=he(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||We(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function xS(e){const t=e.values,o=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function NS(e){return e.target==="openAi"?void 0:{not:We({...e,currentPath:[...e.currentPath,"not"]})}}function ES(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const qo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function zS(e,t){if(t.target==="openApi3")return Qh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(o=>o._def.typeName in qo&&(!o._def.checks||!o._def.checks.length))){const o=r.reduce((n,i)=>{const a=qo[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){const o=r.reduce((n,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(o.length===r.length){const n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return Qh(e,t)}const Qh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>he(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!t.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function jS(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:qo[e.innerType._def.typeName],nullable:!0}:{type:[qo[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const o=he(e.innerType._def,{...t,currentPath:[...t.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}const r=he(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function DS(e,t){const r={type:"number"};if(!e.checks)return r;for(const o of e.checks)switch(o.kind){case"int":r.type="integer",Jh(r,"type",o.message,t);break;case"min":t.target==="jsonSchema7"?o.inclusive?ve(r,"minimum",o.value,o.message,t):ve(r,"exclusiveMinimum",o.value,o.message,t):(o.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",o.value,o.message,t));break;case"max":t.target==="jsonSchema7"?o.inclusive?ve(r,"maximum",o.value,o.message,t):ve(r,"exclusiveMaximum",o.value,o.message,t):(o.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",o.value,o.message,t));break;case"multipleOf":ve(r,"multipleOf",o.value,o.message,t);break}return r}function AS(e,t){const r=t.target==="openAi",o={type:"object",properties:{}},n=[],i=e.shape();for(const s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=RS(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=he(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(o.properties[s]=l,u||n.push(s))}n.length&&(o.required=n);const a=CS(e,t);return a!==void 0&&(o.additionalProperties=a),o}function CS(e,t){if(e.catchall._def.typeName!=="ZodNever")return he(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function RS(e){try{return e.isOptional()}catch{return!0}}const US=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return he(e.innerType._def,t);const r=he(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:We(t)},r]}:We(t)},MS=(e,t)=>{if(t.pipeStrategy==="input")return he(e.in._def,t);if(t.pipeStrategy==="output")return he(e.out._def,t);const r=he(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=he(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function BS(e,t){return he(e.type._def,t)}function ZS(e,t){const o={type:"array",uniqueItems:!0,items:he(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ve(o,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ve(o,"maxItems",e.maxSize.value,e.maxSize.message,t),o}function FS(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>he(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:he(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>he(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function VS(e){return{not:We(e)}}function LS(e){return We(e)}const qS=(e,t)=>he(e.innerType._def,t),JS=(e,t,r)=>{switch(t){case te.ZodString:return Wh(e,r);case te.ZodNumber:return DS(e,r);case te.ZodObject:return AS(e,r);case te.ZodBigInt:return gS(e,r);case te.ZodBoolean:return vS();case te.ZodDate:return Gh(e,r);case te.ZodUndefined:return VS(r);case te.ZodNull:return ES(r);case te.ZodArray:return hS(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return zS(e,r);case te.ZodIntersection:return wS(e,r);case te.ZodTuple:return FS(e,r);case te.ZodRecord:return Xh(e,r);case te.ZodLiteral:return IS(e,r);case te.ZodEnum:return kS(e);case te.ZodNativeEnum:return xS(e);case te.ZodNullable:return jS(e,r);case te.ZodOptional:return US(e,r);case te.ZodMap:return PS(e,r);case te.ZodSet:return ZS(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return BS(e,r);case te.ZodNaN:case te.ZodNever:return NS(r);case te.ZodEffects:return bS(e,r);case te.ZodAny:return We(r);case te.ZodUnknown:return LS(r);case te.ZodDefault:return $S(e,r);case te.ZodBranded:return Kh(e,r);case te.ZodReadonly:return qS(e,r);case te.ZodCatch:return yS(e,r);case te.ZodPipeline:return MS(e,r);case te.ZodFunction:case te.ZodVoid:case te.ZodSymbol:return;default:return(o=>{})()}};function he(e,t,r=!1){const o=t.seen.get(e);if(t.override){const s=t.override?.(e,t,o,r);if(s!==mS)return s}if(o&&!r){const s=HS(o,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=JS(e,e.typeName,t),a=typeof i=="function"?he(i(),t):i;if(a&&KS(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const HS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Hh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),We(t)):t.$refStrategy==="seen"?We(t):void 0}},KS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),GS=(e,t)=>{const r=fS(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:he(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??We(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=he(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??We(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[r.openAiAnyTypeName]||(o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function WS(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function eg(e,t){return St(e)?xa(e,{target:WS(t?.target),io:t?.pipeStrategy??"input"}):GS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function tg(e){const r=lr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const o=Th(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function ng(e,t){const r=ur(e,t);if(!r.success)throw r.error;return r.data}const YS=6e4;class XS{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(xs,r=>{this._oncancel(r)}),this.setNotificationHandler(Es,r=>{this._onprogress(r)}),this.setRequestHandler(Ns,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(zs,async(r,o)=>{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new J(W.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ds,async(r,o)=>{const n=async()=>{const i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,o.sessionId);){if(s.type==="response"||s.type==="error"){const c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{const d=c,p=new J(d.error.code,d.error.message,d.error.data);l(p)}else{const d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:o.requestId})}}const a=await this._taskStore.getTask(i,o.sessionId);if(!a)throw new J(W.InvalidParams,`Task not found: ${i}`);if(!Ht(a.status))return await this._waitForTaskUpdate(i,o.signal),await n();if(Ht(a.status)){const s=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Jt]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(As,async(r,o)=>{try{const{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new J(W.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Rs,async(r,o)=>{try{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new J(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ht(n.status))throw new J(W.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);const i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new J(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof J?n:new J(W.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,o,n,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),J.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};const n=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{n?.(i,a),Uo(i)||Cb(i)?this._onresponse(i):zh(i)?this._onrequest(i,a):Ab(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(const o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();const r=J.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const o of t.values())o(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){const o=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,i=t.params?._meta?.[Jt]?.taskId;if(o===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:W.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const s=Db(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;const d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(a.signal.aborted)throw new J(W.ConnectionClosed,"Request was cancelled");const m={...p,relatedRequestId:t.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});const f=m.relatedTask?.taskId??i;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>o(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(a.signal.aborted)return;const d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:W.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...o}=t.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}i(o)}_onresponse(t){const r=Number(t.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Uo(t))o(t);else{const a=new J(t.error.code,t.error.message,t.error.data);o(a)}return}const n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Uo(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),Uo(t))n(t);else{const a=J.fromError(t.error.code,t.error.message,t.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,o){const{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(t,r,o)}}catch(a){yield{type:"error",error:a instanceof J?a:new J(W.InternalError,String(a))}}return}let i;try{const a=await this.request(t,Mo,o);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new J(W.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:s},Ht(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:s.status==="failed"?yield{type:"error",error:new J(W.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new J(W.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof J?a:new J(W.InternalError,String(a))}}}request(t,r,o){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=o??{};return new Promise((u,l)=>{const d=y=>{l(y)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(y){d(y);return}o?.signal?.throwIfAborted();const p=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),s&&(m.params={...m.params,task:s}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Jt]:c}});const f=y=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(y)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));const b=y instanceof J?y:new J(W.RequestTimeout,String(y));l(b)};this._responseHandlers.set(p,y=>{if(!o?.signal?.aborted){if(y instanceof Error)return l(y);try{const b=ur(r,y.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),o?.signal?.addEventListener("abort",()=>{f(o?.signal?.reason)});const _=o?.timeout??YS,g=()=>f(J.fromError(W.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,o?.maxTotalTimeout,g,o?.resetTimeoutOnProgress??!1);const v=c?.taskId;if(v){const y=b=>{const I=this._responseHandlers.get(p);I?I(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,y),this._enqueueTaskMessage(v,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(y=>{this._cleanupTimeout(p),l(y)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},js,r)}async getTaskResult(t,r,o){return this.request({method:"tasks/result",params:t},r,o)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Cs,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Qb,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const o=r?.relatedTask?.taskId;if(o){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Jt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Jt]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Jt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const o=tg(t);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{const a=ng(t,n);return Promise.resolve(r(a,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const o=tg(t);this._notificationHandlers.set(o,n=>{const i=ng(t,n);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,o,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const o=await this._taskMessageQueue.dequeueAll(t,r);for(const n of o)if(n.type==="request"&&zh(n.message)){const i=n.message.id,a=this._requestResolvers.get(i);a?(a(new J(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let o=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,i)=>{if(r.aborted){i(new J(W.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new J(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await o.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const i=await o.getTask(n,r);if(!i)throw new J(W.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,a)=>{await o.storeTaskResult(n,i,a,r);const s=await o.getTask(n,r);if(s){const c=Bo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Ht(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,a)=>{const s=await o.getTask(n,r);if(!s)throw new J(W.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Ht(s.status))throw new J(W.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,a,r);const c=await o.getTask(n,r);if(c){const u=Bo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ht(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}}function rg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function QS(e,t){const r={...e};for(const o in t){const n=o,i=t[n];if(i===void 0)continue;const a=r[n];rg(a)&&rg(i)?r[n]={...a,...i}:r[n]=i}return r}function og(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tc={exports:{}},ig={},Tt={},Kt={},nc={},se={},yr={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class o extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((b,I)=>`${b}${I}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((b,I)=>(I instanceof r&&(b[I.str]=(b[I.str]||0)+1),b),{})}}e._Code=o,e.nil=new o("");function n(v,...y){const b=[v[0]];let I=0;for(;I<y.length;)s(b,y[I]),b.push(v[++I]);return new o(b)}e._=n;const i=new o("+");function a(v,...y){const b=[m(v[0])];let I=0;for(;I<y.length;)b.push(i),s(b,y[I]),b.push(i,m(v[++I]));return c(b),new o(b)}e.str=a;function s(v,y){y instanceof o?v.push(...y._items):y instanceof r?v.push(y):v.push(d(y))}e.addCodeArg=s;function c(v){let y=1;for(;y<v.length-1;){if(v[y]===i){const b=u(v[y-1],v[y+1]);if(b!==void 0){v.splice(y-1,3,b);continue}v[y++]="+"}y++}}function u(v,y){if(y==='""')return v;if(v==='""')return y;if(typeof v=="string")return y instanceof r||v[v.length-1]!=='"'?void 0:typeof y!="string"?`${v.slice(0,-1)}${y}"`:y[0]==='"'?v.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(v instanceof r))return`"${v}${y.slice(1)}`}function l(v,y){return y.emptyStr()?v:v.emptyStr()?y:a`${v}${y}`}e.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:m(Array.isArray(v)?v.join(","):v)}function p(v){return new o(m(v))}e.stringify=p;function m(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=m;function f(v){return typeof v=="string"&&e.IDENTIFIER.test(v)?new o(`.${v}`):n`[${v}]`}e.getProperty=f;function _(v){if(typeof v=="string"&&e.IDENTIFIER.test(v))return new o(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}e.getEsmExportName=_;function g(v){return new o(v.toString())}e.regexpCode=g})(yr);var rc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=yr;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var o;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(o||(e.UsedValueState=o={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=n;class i extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${d}]`}}e.ValueScopeName=i;const a=(0,t._)`\n`;class s extends n{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?a:t.nil}}get(){return this._scope}name(u){return new i(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:m}=p,f=(d=l.key)!==null&&d!==void 0?d:l.ref;let _=this._values[m];if(_){const y=_.get(f);if(y)return y}else _=this._values[m]=new Map;_.set(f,p);const g=this._scope[m]||(this._scope[m]=[]),v=g.length;return g[v]=l.ref,p.setValue(l,{property:m,itemIndex:v}),p}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,t._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,d)}_reduceValues(u,l,d={},p){let m=t.nil;for(const f in u){const _=u[f];if(!_)continue;const g=d[f]=d[f]||new Map;_.forEach(v=>{if(g.has(v))return;g.set(v,o.Started);let y=l(v);if(y){const b=this.opts.es5?e.varKinds.var:e.varKinds.const;m=(0,t._)`${m}${b} ${v} = ${y};${this.opts._n}`}else if(y=p?.(v))m=(0,t._)`${m}${y}${this.opts._n}`;else throw new r(v);g.set(v,o.Completed)})}return m}}e.ValueScope=s})(rc),(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=yr,r=rc;var o=yr;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return o.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return o.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return o.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return o.Name}});var n=rc;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class i{optimizeNodes(){return this}optimizeNames(h,$){return this}}class a extends i{constructor(h,$,N){super(),this.varKind=h,this.name=$,this.rhs=N}render({es5:h,_n:$}){const N=h?r.varKinds.var:this.varKind,F=this.rhs===void 0?"":` = ${this.rhs}`;return`${N} ${this.name}${F};`+$}optimizeNames(h,$){if(h[this.name.str])return this.rhs&&(this.rhs=K(this.rhs,h,$)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends i{constructor(h,$,N){super(),this.lhs=h,this.rhs=$,this.sideEffects=N}render({_n:h}){return`${this.lhs} = ${this.rhs};`+h}optimizeNames(h,$){if(!(this.lhs instanceof t.Name&&!h[this.lhs.str]&&!this.sideEffects))return this.rhs=K(this.rhs,h,$),this}get names(){const h=this.lhs instanceof t.Name?{}:{...this.lhs.names};return Y(h,this.rhs)}}class c extends s{constructor(h,$,N,F){super(h,N,F),this.op=$}render({_n:h}){return`${this.lhs} ${this.op}= ${this.rhs};`+h}}class u extends i{constructor(h){super(),this.label=h,this.names={}}render({_n:h}){return`${this.label}:`+h}}class l extends i{constructor(h){super(),this.label=h,this.names={}}render({_n:h}){return`break${this.label?` ${this.label}`:""};`+h}}class d extends i{constructor(h){super(),this.error=h}render({_n:h}){return`throw ${this.error};`+h}get names(){return this.error.names}}class p extends i{constructor(h){super(),this.code=h}render({_n:h}){return`${this.code};`+h}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(h,$){return this.code=K(this.code,h,$),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class m extends i{constructor(h=[]){super(),this.nodes=h}render(h){return this.nodes.reduce(($,N)=>$+N.render(h),"")}optimizeNodes(){const{nodes:h}=this;let $=h.length;for(;$--;){const N=h[$].optimizeNodes();Array.isArray(N)?h.splice($,1,...N):N?h[$]=N:h.splice($,1)}return h.length>0?this:void 0}optimizeNames(h,$){const{nodes:N}=this;let F=N.length;for(;F--;){const H=N[F];H.optimizeNames(h,$)||(Pe(h,H.names),N.splice(F,1))}return N.length>0?this:void 0}get names(){return this.nodes.reduce((h,$)=>Q(h,$.names),{})}}class f extends m{render(h){return"{"+h._n+super.render(h)+"}"+h._n}}class _ extends m{}class g extends f{}g.kind="else";class v extends f{constructor(h,$){super($),this.condition=h}render(h){let $=`if(${this.condition})`+super.render(h);return this.else&&($+="else "+this.else.render(h)),$}optimizeNodes(){super.optimizeNodes();const h=this.condition;if(h===!0)return this.nodes;let $=this.else;if($){const N=$.optimizeNodes();$=this.else=Array.isArray(N)?new g(N):N}if($)return h===!1?$ instanceof v?$:$.nodes:this.nodes.length?this:new v(ot(h),$ instanceof v?[$]:$.nodes);if(!(h===!1||!this.nodes.length))return this}optimizeNames(h,$){var N;if(this.else=(N=this.else)===null||N===void 0?void 0:N.optimizeNames(h,$),!!(super.optimizeNames(h,$)||this.else))return this.condition=K(this.condition,h,$),this}get names(){const h=super.names;return Y(h,this.condition),this.else&&Q(h,this.else.names),h}}v.kind="if";class y extends f{}y.kind="for";class b extends y{constructor(h){super(),this.iteration=h}render(h){return`for(${this.iteration})`+super.render(h)}optimizeNames(h,$){if(super.optimizeNames(h,$))return this.iteration=K(this.iteration,h,$),this}get names(){return Q(super.names,this.iteration.names)}}class I extends y{constructor(h,$,N,F){super(),this.varKind=h,this.name=$,this.from=N,this.to=F}render(h){const $=h.es5?r.varKinds.var:this.varKind,{name:N,from:F,to:H}=this;return`for(${$} ${N}=${F}; ${N}<${H}; ${N}++)`+super.render(h)}get names(){const h=Y(super.names,this.from);return Y(h,this.to)}}class x extends y{constructor(h,$,N,F){super(),this.loop=h,this.varKind=$,this.name=N,this.iterable=F}render(h){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(h)}optimizeNames(h,$){if(super.optimizeNames(h,$))return this.iterable=K(this.iterable,h,$),this}get names(){return Q(super.names,this.iterable.names)}}class B extends f{constructor(h,$,N){super(),this.name=h,this.args=$,this.async=N}render(h){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(h)}}B.kind="func";class L extends m{render(h){return"return "+super.render(h)}}L.kind="return";class ue extends f{render(h){let $="try"+super.render(h);return this.catch&&($+=this.catch.render(h)),this.finally&&($+=this.finally.render(h)),$}optimizeNodes(){var h,$;return super.optimizeNodes(),(h=this.catch)===null||h===void 0||h.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(h,$){var N,F;return super.optimizeNames(h,$),(N=this.catch)===null||N===void 0||N.optimizeNames(h,$),(F=this.finally)===null||F===void 0||F.optimizeNames(h,$),this}get names(){const h=super.names;return this.catch&&Q(h,this.catch.names),this.finally&&Q(h,this.finally.names),h}}class me extends f{constructor(h){super(),this.error=h}render(h){return`catch(${this.error})`+super.render(h)}}me.kind="catch";class Te extends f{render(h){return"finally"+super.render(h)}}Te.kind="finally";class Z{constructor(h,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
|
|
70
|
+
]`;continue}n+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return n}function Xh(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===te.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((o,n)=>({...o,[n]:he(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??We(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:he(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===te.ZodString&&e.keyType._def.checks?.length){const{type:o,...n}=Wh(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===te.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===te.ZodBranded&&e.keyType._def.type._def.typeName===te.ZodString&&e.keyType._def.type._def.checks?.length){const{type:o,...n}=Kh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function PS(e,t){if(t.mapStrategy==="record")return Xh(e,t);const r=he(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||We(t),o=he(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||We(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function xS(e){const t=e.values,o=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function NS(e){return e.target==="openAi"?void 0:{not:We({...e,currentPath:[...e.currentPath,"not"]})}}function ES(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const qo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function zS(e,t){if(t.target==="openApi3")return Qh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(o=>o._def.typeName in qo&&(!o._def.checks||!o._def.checks.length))){const o=r.reduce((n,i)=>{const a=qo[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){const o=r.reduce((n,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];default:return n}},[]);if(o.length===r.length){const n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return Qh(e,t)}const Qh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>he(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!t.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function jS(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:qo[e.innerType._def.typeName],nullable:!0}:{type:[qo[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const o=he(e.innerType._def,{...t,currentPath:[...t.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}const r=he(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function DS(e,t){const r={type:"number"};if(!e.checks)return r;for(const o of e.checks)switch(o.kind){case"int":r.type="integer",Jh(r,"type",o.message,t);break;case"min":t.target==="jsonSchema7"?o.inclusive?ve(r,"minimum",o.value,o.message,t):ve(r,"exclusiveMinimum",o.value,o.message,t):(o.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",o.value,o.message,t));break;case"max":t.target==="jsonSchema7"?o.inclusive?ve(r,"maximum",o.value,o.message,t):ve(r,"exclusiveMaximum",o.value,o.message,t):(o.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",o.value,o.message,t));break;case"multipleOf":ve(r,"multipleOf",o.value,o.message,t);break}return r}function AS(e,t){const r=t.target==="openAi",o={type:"object",properties:{}},n=[],i=e.shape();for(const s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=RS(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=he(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(o.properties[s]=l,u||n.push(s))}n.length&&(o.required=n);const a=CS(e,t);return a!==void 0&&(o.additionalProperties=a),o}function CS(e,t){if(e.catchall._def.typeName!=="ZodNever")return he(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function RS(e){try{return e.isOptional()}catch{return!0}}const US=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return he(e.innerType._def,t);const r=he(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:We(t)},r]}:We(t)},MS=(e,t)=>{if(t.pipeStrategy==="input")return he(e.in._def,t);if(t.pipeStrategy==="output")return he(e.out._def,t);const r=he(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=he(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function BS(e,t){return he(e.type._def,t)}function ZS(e,t){const o={type:"array",uniqueItems:!0,items:he(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ve(o,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ve(o,"maxItems",e.maxSize.value,e.maxSize.message,t),o}function FS(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>he(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:he(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>he(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function VS(e){return{not:We(e)}}function LS(e){return We(e)}const qS=(e,t)=>he(e.innerType._def,t),JS=(e,t,r)=>{switch(t){case te.ZodString:return Wh(e,r);case te.ZodNumber:return DS(e,r);case te.ZodObject:return AS(e,r);case te.ZodBigInt:return gS(e,r);case te.ZodBoolean:return vS();case te.ZodDate:return Gh(e,r);case te.ZodUndefined:return VS(r);case te.ZodNull:return ES(r);case te.ZodArray:return hS(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return zS(e,r);case te.ZodIntersection:return wS(e,r);case te.ZodTuple:return FS(e,r);case te.ZodRecord:return Xh(e,r);case te.ZodLiteral:return IS(e,r);case te.ZodEnum:return kS(e);case te.ZodNativeEnum:return xS(e);case te.ZodNullable:return jS(e,r);case te.ZodOptional:return US(e,r);case te.ZodMap:return PS(e,r);case te.ZodSet:return ZS(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return BS(e,r);case te.ZodNaN:case te.ZodNever:return NS(r);case te.ZodEffects:return bS(e,r);case te.ZodAny:return We(r);case te.ZodUnknown:return LS(r);case te.ZodDefault:return $S(e,r);case te.ZodBranded:return Kh(e,r);case te.ZodReadonly:return qS(e,r);case te.ZodCatch:return yS(e,r);case te.ZodPipeline:return MS(e,r);case te.ZodFunction:case te.ZodVoid:case te.ZodSymbol:return;default:return(o=>{})()}};function he(e,t,r=!1){const o=t.seen.get(e);if(t.override){const s=t.override?.(e,t,o,r);if(s!==mS)return s}if(o&&!r){const s=HS(o,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=JS(e,e.typeName,t),a=typeof i=="function"?he(i(),t):i;if(a&&KS(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const HS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Hh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),We(t)):t.$refStrategy==="seen"?We(t):void 0}},KS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),GS=(e,t)=>{const r=fS(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:he(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??We(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=he(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??We(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[r.openAiAnyTypeName]||(o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function WS(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function eg(e,t){return St(e)?xa(e,{target:WS(t?.target),io:t?.pipeStrategy??"input"}):GS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function tg(e){const r=lr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const o=Th(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function ng(e,t){const r=ur(e,t);if(!r.success)throw r.error;return r.data}const YS=6e4;class XS{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(xs,r=>{this._oncancel(r)}),this.setNotificationHandler(Es,r=>{this._onprogress(r)}),this.setRequestHandler(Ns,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(zs,async(r,o)=>{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new J(W.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ds,async(r,o)=>{const n=async()=>{const i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,o.sessionId);){if(s.type==="response"||s.type==="error"){const c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{const d=c,p=new J(d.error.code,d.error.message,d.error.data);l(p)}else{const d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:o.requestId})}}const a=await this._taskStore.getTask(i,o.sessionId);if(!a)throw new J(W.InvalidParams,`Task not found: ${i}`);if(!Ht(a.status))return await this._waitForTaskUpdate(i,o.signal),await n();if(Ht(a.status)){const s=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Jt]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(As,async(r,o)=>{try{const{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new J(W.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Rs,async(r,o)=>{try{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new J(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ht(n.status))throw new J(W.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);const i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new J(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof J?n:new J(W.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,o,n,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),J.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};const n=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{n?.(i,a),Uo(i)||Cb(i)?this._onresponse(i):zh(i)?this._onrequest(i,a):Ab(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(const o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();const r=J.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const o of t.values())o(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){const o=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,i=t.params?._meta?.[Jt]?.taskId;if(o===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:W.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const s=Db(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;const d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(a.signal.aborted)throw new J(W.ConnectionClosed,"Request was cancelled");const m={...p,relatedRequestId:t.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});const f=m.relatedTask?.taskId??i;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>o(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(a.signal.aborted)return;const d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:W.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...o}=t.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}i(o)}_onresponse(t){const r=Number(t.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Uo(t))o(t);else{const a=new J(t.error.code,t.error.message,t.error.data);o(a)}return}const n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Uo(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),Uo(t))n(t);else{const a=J.fromError(t.error.code,t.error.message,t.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,o){const{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(t,r,o)}}catch(a){yield{type:"error",error:a instanceof J?a:new J(W.InternalError,String(a))}}return}let i;try{const a=await this.request(t,Mo,o);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new J(W.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:s},Ht(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:s.status==="failed"?yield{type:"error",error:new J(W.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new J(W.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof J?a:new J(W.InternalError,String(a))}}}request(t,r,o){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=o??{};return new Promise((u,l)=>{const d=y=>{l(y)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(y){d(y);return}o?.signal?.throwIfAborted();const p=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),s&&(m.params={...m.params,task:s}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Jt]:c}});const f=y=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(y)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));const b=y instanceof J?y:new J(W.RequestTimeout,String(y));l(b)};this._responseHandlers.set(p,y=>{if(!o?.signal?.aborted){if(y instanceof Error)return l(y);try{const b=ur(r,y.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),o?.signal?.addEventListener("abort",()=>{f(o?.signal?.reason)});const _=o?.timeout??YS,g=()=>f(J.fromError(W.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,o?.maxTotalTimeout,g,o?.resetTimeoutOnProgress??!1);const v=c?.taskId;if(v){const y=b=>{const I=this._responseHandlers.get(p);I?I(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,y),this._enqueueTaskMessage(v,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(y=>{this._cleanupTimeout(p),l(y)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},js,r)}async getTaskResult(t,r,o){return this.request({method:"tasks/result",params:t},r,o)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Cs,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Qb,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const o=r?.relatedTask?.taskId;if(o){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Jt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Jt]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Jt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const o=tg(t);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{const a=ng(t,n);return Promise.resolve(r(a,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const o=tg(t);this._notificationHandlers.set(o,n=>{const i=ng(t,n);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,o,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const o=await this._taskMessageQueue.dequeueAll(t,r);for(const n of o)if(n.type==="request"&&zh(n.message)){const i=n.message.id,a=this._requestResolvers.get(i);a?(a(new J(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let o=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,i)=>{if(r.aborted){i(new J(W.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new J(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await o.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const i=await o.getTask(n,r);if(!i)throw new J(W.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,a)=>{await o.storeTaskResult(n,i,a,r);const s=await o.getTask(n,r);if(s){const c=Bo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Ht(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,a)=>{const s=await o.getTask(n,r);if(!s)throw new J(W.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Ht(s.status))throw new J(W.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,a,r);const c=await o.getTask(n,r);if(c){const u=Bo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ht(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}}function rg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function QS(e,t){const r={...e};for(const o in t){const n=o,i=t[n];if(i===void 0)continue;const a=r[n];rg(a)&&rg(i)?r[n]={...a,...i}:r[n]=i}return r}function og(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tc={exports:{}},ig={},Tt={},Kt={},nc={},se={},yr={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class o extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((b,I)=>`${b}${I}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((b,I)=>(I instanceof r&&(b[I.str]=(b[I.str]||0)+1),b),{})}}e._Code=o,e.nil=new o("");function n(v,...y){const b=[v[0]];let I=0;for(;I<y.length;)s(b,y[I]),b.push(v[++I]);return new o(b)}e._=n;const i=new o("+");function a(v,...y){const b=[m(v[0])];let I=0;for(;I<y.length;)b.push(i),s(b,y[I]),b.push(i,m(v[++I]));return c(b),new o(b)}e.str=a;function s(v,y){y instanceof o?v.push(...y._items):y instanceof r?v.push(y):v.push(d(y))}e.addCodeArg=s;function c(v){let y=1;for(;y<v.length-1;){if(v[y]===i){const b=u(v[y-1],v[y+1]);if(b!==void 0){v.splice(y-1,3,b);continue}v[y++]="+"}y++}}function u(v,y){if(y==='""')return v;if(v==='""')return y;if(typeof v=="string")return y instanceof r||v[v.length-1]!=='"'?void 0:typeof y!="string"?`${v.slice(0,-1)}${y}"`:y[0]==='"'?v.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(v instanceof r))return`"${v}${y.slice(1)}`}function l(v,y){return y.emptyStr()?v:v.emptyStr()?y:a`${v}${y}`}e.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:m(Array.isArray(v)?v.join(","):v)}function p(v){return new o(m(v))}e.stringify=p;function m(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=m;function f(v){return typeof v=="string"&&e.IDENTIFIER.test(v)?new o(`.${v}`):n`[${v}]`}e.getProperty=f;function _(v){if(typeof v=="string"&&e.IDENTIFIER.test(v))return new o(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}e.getEsmExportName=_;function g(v){return new o(v.toString())}e.regexpCode=g})(yr);var rc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=yr;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var o;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(o||(e.UsedValueState=o={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=n;class i extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${d}]`}}e.ValueScopeName=i;const a=(0,t._)`\n`;class s extends n{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?a:t.nil}}get(){return this._scope}name(u){return new i(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:m}=p,f=(d=l.key)!==null&&d!==void 0?d:l.ref;let _=this._values[m];if(_){const y=_.get(f);if(y)return y}else _=this._values[m]=new Map;_.set(f,p);const g=this._scope[m]||(this._scope[m]=[]),v=g.length;return g[v]=l.ref,p.setValue(l,{property:m,itemIndex:v}),p}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,t._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,d)}_reduceValues(u,l,d={},p){let m=t.nil;for(const f in u){const _=u[f];if(!_)continue;const g=d[f]=d[f]||new Map;_.forEach(v=>{if(g.has(v))return;g.set(v,o.Started);let y=l(v);if(y){const b=this.opts.es5?e.varKinds.var:e.varKinds.const;m=(0,t._)`${m}${b} ${v} = ${y};${this.opts._n}`}else if(y=p?.(v))m=(0,t._)`${m}${y}${this.opts._n}`;else throw new r(v);g.set(v,o.Completed)})}return m}}e.ValueScope=s})(rc),(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=yr,r=rc;var o=yr;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return o.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return o.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return o.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return o.Name}});var n=rc;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class i{optimizeNodes(){return this}optimizeNames(h,$){return this}}class a extends i{constructor(h,$,N){super(),this.varKind=h,this.name=$,this.rhs=N}render({es5:h,_n:$}){const N=h?r.varKinds.var:this.varKind,F=this.rhs===void 0?"":` = ${this.rhs}`;return`${N} ${this.name}${F};`+$}optimizeNames(h,$){if(h[this.name.str])return this.rhs&&(this.rhs=K(this.rhs,h,$)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends i{constructor(h,$,N){super(),this.lhs=h,this.rhs=$,this.sideEffects=N}render({_n:h}){return`${this.lhs} = ${this.rhs};`+h}optimizeNames(h,$){if(!(this.lhs instanceof t.Name&&!h[this.lhs.str]&&!this.sideEffects))return this.rhs=K(this.rhs,h,$),this}get names(){const h=this.lhs instanceof t.Name?{}:{...this.lhs.names};return Y(h,this.rhs)}}class c extends s{constructor(h,$,N,F){super(h,N,F),this.op=$}render({_n:h}){return`${this.lhs} ${this.op}= ${this.rhs};`+h}}class u extends i{constructor(h){super(),this.label=h,this.names={}}render({_n:h}){return`${this.label}:`+h}}class l extends i{constructor(h){super(),this.label=h,this.names={}}render({_n:h}){return`break${this.label?` ${this.label}`:""};`+h}}class d extends i{constructor(h){super(),this.error=h}render({_n:h}){return`throw ${this.error};`+h}get names(){return this.error.names}}class p extends i{constructor(h){super(),this.code=h}render({_n:h}){return`${this.code};`+h}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(h,$){return this.code=K(this.code,h,$),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class m extends i{constructor(h=[]){super(),this.nodes=h}render(h){return this.nodes.reduce(($,N)=>$+N.render(h),"")}optimizeNodes(){const{nodes:h}=this;let $=h.length;for(;$--;){const N=h[$].optimizeNodes();Array.isArray(N)?h.splice($,1,...N):N?h[$]=N:h.splice($,1)}return h.length>0?this:void 0}optimizeNames(h,$){const{nodes:N}=this;let F=N.length;for(;F--;){const H=N[F];H.optimizeNames(h,$)||(Pe(h,H.names),N.splice(F,1))}return N.length>0?this:void 0}get names(){return this.nodes.reduce((h,$)=>Q(h,$.names),{})}}class f extends m{render(h){return"{"+h._n+super.render(h)+"}"+h._n}}class _ extends m{}class g extends f{}g.kind="else";class v extends f{constructor(h,$){super($),this.condition=h}render(h){let $=`if(${this.condition})`+super.render(h);return this.else&&($+="else "+this.else.render(h)),$}optimizeNodes(){super.optimizeNodes();const h=this.condition;if(h===!0)return this.nodes;let $=this.else;if($){const N=$.optimizeNodes();$=this.else=Array.isArray(N)?new g(N):N}if($)return h===!1?$ instanceof v?$:$.nodes:this.nodes.length?this:new v(ot(h),$ instanceof v?[$]:$.nodes);if(!(h===!1||!this.nodes.length))return this}optimizeNames(h,$){var N;if(this.else=(N=this.else)===null||N===void 0?void 0:N.optimizeNames(h,$),!!(super.optimizeNames(h,$)||this.else))return this.condition=K(this.condition,h,$),this}get names(){const h=super.names;return Y(h,this.condition),this.else&&Q(h,this.else.names),h}}v.kind="if";class y extends f{}y.kind="for";class b extends y{constructor(h){super(),this.iteration=h}render(h){return`for(${this.iteration})`+super.render(h)}optimizeNames(h,$){if(super.optimizeNames(h,$))return this.iteration=K(this.iteration,h,$),this}get names(){return Q(super.names,this.iteration.names)}}class I extends y{constructor(h,$,N,F){super(),this.varKind=h,this.name=$,this.from=N,this.to=F}render(h){const $=h.es5?r.varKinds.var:this.varKind,{name:N,from:F,to:H}=this;return`for(${$} ${N}=${F}; ${N}<${H}; ${N}++)`+super.render(h)}get names(){const h=Y(super.names,this.from);return Y(h,this.to)}}class x extends y{constructor(h,$,N,F){super(),this.loop=h,this.varKind=$,this.name=N,this.iterable=F}render(h){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(h)}optimizeNames(h,$){if(super.optimizeNames(h,$))return this.iterable=K(this.iterable,h,$),this}get names(){return Q(super.names,this.iterable.names)}}class B extends f{constructor(h,$,N){super(),this.name=h,this.args=$,this.async=N}render(h){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(h)}}B.kind="func";class L extends m{render(h){return"return "+super.render(h)}}L.kind="return";class ue extends f{render(h){let $="try"+super.render(h);return this.catch&&($+=this.catch.render(h)),this.finally&&($+=this.finally.render(h)),$}optimizeNodes(){var h,$;return super.optimizeNodes(),(h=this.catch)===null||h===void 0||h.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(h,$){var N,F;return super.optimizeNames(h,$),(N=this.catch)===null||N===void 0||N.optimizeNames(h,$),(F=this.finally)===null||F===void 0||F.optimizeNames(h,$),this}get names(){const h=super.names;return this.catch&&Q(h,this.catch.names),this.finally&&Q(h,this.finally.names),h}}class me extends f{constructor(h){super(),this.error=h}render(h){return`catch(${this.error})`+super.render(h)}}me.kind="catch";class Te extends f{render(h){return"finally"+super.render(h)}}Te.kind="finally";class Z{constructor(h,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
|
|
71
71
|
`:""},this._extScope=h,this._scope=new r.Scope({parent:h}),this._nodes=[new _]}toString(){return this._root.render(this.opts)}name(h){return this._scope.name(h)}scopeName(h){return this._extScope.name(h)}scopeValue(h,$){const N=this._extScope.value(h,$);return(this._values[N.prefix]||(this._values[N.prefix]=new Set)).add(N),N}getScopeValue(h,$){return this._extScope.getValue(h,$)}scopeRefs(h){return this._extScope.scopeRefs(h,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(h,$,N,F){const H=this._scope.toName($);return N!==void 0&&F&&(this._constants[H.str]=N),this._leafNode(new a(h,H,N)),H}const(h,$,N){return this._def(r.varKinds.const,h,$,N)}let(h,$,N){return this._def(r.varKinds.let,h,$,N)}var(h,$,N){return this._def(r.varKinds.var,h,$,N)}assign(h,$,N){return this._leafNode(new s(h,$,N))}add(h,$){return this._leafNode(new c(h,e.operators.ADD,$))}code(h){return typeof h=="function"?h():h!==t.nil&&this._leafNode(new p(h)),this}object(...h){const $=["{"];for(const[N,F]of h)$.length>1&&$.push(","),$.push(N),(N!==F||this.opts.es5)&&($.push(":"),(0,t.addCodeArg)($,F));return $.push("}"),new t._Code($)}if(h,$,N){if(this._blockNode(new v(h)),$&&N)this.code($).else().code(N).endIf();else if($)this.code($).endIf();else if(N)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(h){return this._elseNode(new v(h))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(v,g)}_for(h,$){return this._blockNode(h),$&&this.code($).endFor(),this}for(h,$){return this._for(new b(h),$)}forRange(h,$,N,F,H=this.opts.es5?r.varKinds.var:r.varKinds.let){const pe=this._scope.toName(h);return this._for(new I(H,pe,$,N),()=>F(pe))}forOf(h,$,N,F=r.varKinds.const){const H=this._scope.toName(h);if(this.opts.es5){const pe=$ instanceof t.Name?$:this.var("_arr",$);return this.forRange("_i",0,(0,t._)`${pe}.length`,le=>{this.var(H,(0,t._)`${pe}[${le}]`),N(H)})}return this._for(new x("of",F,H,$),()=>N(H))}forIn(h,$,N,F=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(h,(0,t._)`Object.keys(${$})`,N);const H=this._scope.toName(h);return this._for(new x("in",F,H,$),()=>N(H))}endFor(){return this._endBlockNode(y)}label(h){return this._leafNode(new u(h))}break(h){return this._leafNode(new l(h))}return(h){const $=new L;if(this._blockNode($),this.code(h),$.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(L)}try(h,$,N){if(!$&&!N)throw new Error('CodeGen: "try" without "catch" and "finally"');const F=new ue;if(this._blockNode(F),this.code(h),$){const H=this.name("e");this._currNode=F.catch=new me(H),$(H)}return N&&(this._currNode=F.finally=new Te,this.code(N)),this._endBlockNode(me,Te)}throw(h){return this._leafNode(new d(h))}block(h,$){return this._blockStarts.push(this._nodes.length),h&&this.code(h).endBlock($),this}endBlock(h){const $=this._blockStarts.pop();if($===void 0)throw new Error("CodeGen: not in self-balancing block");const N=this._nodes.length-$;if(N<0||h!==void 0&&N!==h)throw new Error(`CodeGen: wrong number of nodes: ${N} vs ${h} expected`);return this._nodes.length=$,this}func(h,$=t.nil,N,F){return this._blockNode(new B(h,$,N)),F&&this.code(F).endFunc(),this}endFunc(){return this._endBlockNode(B)}optimize(h=1){for(;h-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(h){return this._currNode.nodes.push(h),this}_blockNode(h){this._currNode.nodes.push(h),this._nodes.push(h)}_endBlockNode(h,$){const N=this._currNode;if(N instanceof h||$&&N instanceof $)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${$?`${h.kind}/${$.kind}`:h.kind}"`)}_elseNode(h){const $=this._currNode;if(!($ instanceof v))throw new Error('CodeGen: "else" without "if"');return this._currNode=$.else=h,this}get _root(){return this._nodes[0]}get _currNode(){const h=this._nodes;return h[h.length-1]}set _currNode(h){const $=this._nodes;$[$.length-1]=h}}e.CodeGen=Z;function Q(P,h){for(const $ in h)P[$]=(P[$]||0)+(h[$]||0);return P}function Y(P,h){return h instanceof t._CodeOrName?Q(P,h.names):P}function K(P,h,$){if(P instanceof t.Name)return N(P);if(!F(P))return P;return new t._Code(P._items.reduce((H,pe)=>(pe instanceof t.Name&&(pe=N(pe)),pe instanceof t._Code?H.push(...pe._items):H.push(pe),H),[]));function N(H){const pe=$[H.str];return pe===void 0||h[H.str]!==1?H:(delete h[H.str],pe)}function F(H){return H instanceof t._Code&&H._items.some(pe=>pe instanceof t.Name&&h[pe.str]===1&&$[pe.str]!==void 0)}}function Pe(P,h){for(const $ in h)P[$]=(P[$]||0)-(h[$]||0)}function ot(P){return typeof P=="boolean"||typeof P=="number"||P===null?!P:(0,t._)`!${j(P)}`}e.not=ot;const it=O(e.operators.AND);function Mt(...P){return P.reduce(it)}e.and=Mt;const wt=O(e.operators.OR);function C(...P){return P.reduce(wt)}e.or=C;function O(P){return(h,$)=>h===t.nil?$:$===t.nil?h:(0,t._)`${j(h)} ${P} ${j($)}`}function j(P){return P instanceof t.Name?P:(0,t._)`(${P})`}})(se);var M={};Object.defineProperty(M,"__esModule",{value:!0}),M.checkStrictMode=M.getErrorPath=M.Type=M.useFunc=M.setEvaluated=M.evaluatedPropsToName=M.mergeEvaluated=M.eachItem=M.unescapeJsonPointer=M.escapeJsonPointer=M.escapeFragment=M.unescapeFragment=M.schemaRefOrVal=M.schemaHasRulesButRef=M.schemaHasRules=M.checkUnknownRules=M.alwaysValidSchema=M.toHash=void 0;const Se=se,ew=yr;function tw(e){const t={};for(const r of e)t[r]=!0;return t}M.toHash=tw;function nw(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(ag(e,t),!sg(t,e.self.RULES.all))}M.alwaysValidSchema=nw;function ag(e,t=e.schema){const{opts:r,self:o}=e;if(!r.strictSchema||typeof t=="boolean")return;const n=o.RULES.keywords;for(const i in t)n[i]||mg(e,`unknown keyword: "${i}"`)}M.checkUnknownRules=ag;function sg(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(t[r])return!0;return!1}M.schemaHasRules=sg;function rw(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}M.schemaHasRulesButRef=rw;function ow({topSchemaRef:e,schemaPath:t},r,o,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Se._)`${r}`}return(0,Se._)`${e}${t}${(0,Se.getProperty)(o)}`}M.schemaRefOrVal=ow;function iw(e){return cg(decodeURIComponent(e))}M.unescapeFragment=iw;function aw(e){return encodeURIComponent(oc(e))}M.escapeFragment=aw;function oc(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}M.escapeJsonPointer=oc;function cg(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}M.unescapeJsonPointer=cg;function sw(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)}M.eachItem=sw;function ug({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:o}){return(n,i,a,s)=>{const c=a===void 0?i:a instanceof Se.Name?(i instanceof Se.Name?e(n,i,a):t(n,i,a),a):i instanceof Se.Name?(t(n,a,i),i):r(i,a);return s===Se.Name&&!(c instanceof Se.Name)?o(n,c):c}}M.mergeEvaluated={props:ug({mergeNames:(e,t,r)=>e.if((0,Se._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,Se._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,Se._)`${r} || {}`).code((0,Se._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,Se._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,Se._)`${r} || {}`),ic(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:lg}),items:ug({mergeNames:(e,t,r)=>e.if((0,Se._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,Se._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,Se._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,Se._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function lg(e,t){if(t===!0)return e.var("props",!0);const r=e.var("props",(0,Se._)`{}`);return t!==void 0&&ic(e,r,t),r}M.evaluatedPropsToName=lg;function ic(e,t,r){Object.keys(r).forEach(o=>e.assign((0,Se._)`${t}${(0,Se.getProperty)(o)}`,!0))}M.setEvaluated=ic;const dg={};function cw(e,t){return e.scopeValue("func",{ref:t,code:dg[t.code]||(dg[t.code]=new ew._Code(t.code))})}M.useFunc=cw;var ac;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ac||(M.Type=ac={}));function uw(e,t,r){if(e instanceof Se.Name){const o=t===ac.Num;return r?o?(0,Se._)`"[" + ${e} + "]"`:(0,Se._)`"['" + ${e} + "']"`:o?(0,Se._)`"/" + ${e}`:(0,Se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Se.getProperty)(e).toString():"/"+oc(e)}M.getErrorPath=uw;function mg(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}M.checkStrictMode=mg;var Jo={},pg;function At(){if(pg)return Jo;pg=1,Object.defineProperty(Jo,"__esModule",{value:!0});const e=se,t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Jo.default=t,Jo}var fg;function Ho(){return fg||(fg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=se,r=M,o=At();e.keywordError={message:({keyword:g})=>(0,t.str)`must pass "${g}" keyword validation`},e.keyword$DataError={message:({keyword:g,schemaType:v})=>v?(0,t.str)`"${g}" keyword must be ${v} ($data)`:(0,t.str)`"${g}" keyword is invalid ($data)`};function n(g,v=e.keywordError,y,b){const{it:I}=g,{gen:x,compositeRule:B,allErrors:L}=I,ue=d(g,v,y);b??(B||L)?c(x,ue):u(I,(0,t._)`[${ue}]`)}e.reportError=n;function i(g,v=e.keywordError,y){const{it:b}=g,{gen:I,compositeRule:x,allErrors:B}=b,L=d(g,v,y);c(I,L),x||B||u(b,o.default.vErrors)}e.reportExtraError=i;function a(g,v){g.assign(o.default.errors,v),g.if((0,t._)`${o.default.vErrors} !== null`,()=>g.if(v,()=>g.assign((0,t._)`${o.default.vErrors}.length`,v),()=>g.assign(o.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:g,keyword:v,schemaValue:y,data:b,errsCount:I,it:x}){if(I===void 0)throw new Error("ajv implementation error");const B=g.name("err");g.forRange("i",I,o.default.errors,L=>{g.const(B,(0,t._)`${o.default.vErrors}[${L}]`),g.if((0,t._)`${B}.instancePath === undefined`,()=>g.assign((0,t._)`${B}.instancePath`,(0,t.strConcat)(o.default.instancePath,x.errorPath))),g.assign((0,t._)`${B}.schemaPath`,(0,t.str)`${x.errSchemaPath}/${v}`),x.opts.verbose&&(g.assign((0,t._)`${B}.schema`,y),g.assign((0,t._)`${B}.data`,b))})}e.extendErrors=s;function c(g,v){const y=g.const("err",v);g.if((0,t._)`${o.default.vErrors} === null`,()=>g.assign(o.default.vErrors,(0,t._)`[${y}]`),(0,t._)`${o.default.vErrors}.push(${y})`),g.code((0,t._)`${o.default.errors}++`)}function u(g,v){const{gen:y,validateName:b,schemaEnv:I}=g;I.$async?y.throw((0,t._)`new ${g.ValidationError}(${v})`):(y.assign((0,t._)`${b}.errors`,v),y.return(!1))}const l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function d(g,v,y){const{createErrors:b}=g.it;return b===!1?(0,t._)`{}`:p(g,v,y)}function p(g,v,y={}){const{gen:b,it:I}=g,x=[m(I,y),f(g,y)];return _(g,v,x),b.object(...x)}function m({errorPath:g},{instancePath:v}){const y=v?(0,t.str)`${g}${(0,r.getErrorPath)(v,r.Type.Str)}`:g;return[o.default.instancePath,(0,t.strConcat)(o.default.instancePath,y)]}function f({keyword:g,it:{errSchemaPath:v}},{schemaPath:y,parentSchema:b}){let I=b?v:(0,t.str)`${v}/${g}`;return y&&(I=(0,t.str)`${I}${(0,r.getErrorPath)(y,r.Type.Str)}`),[l.schemaPath,I]}function _(g,{params:v,message:y},b){const{keyword:I,data:x,schemaValue:B,it:L}=g,{opts:ue,propertyName:me,topSchemaRef:Te,schemaPath:Z}=L;b.push([l.keyword,I],[l.params,typeof v=="function"?v(g):v||(0,t._)`{}`]),ue.messages&&b.push([l.message,typeof y=="function"?y(g):y]),ue.verbose&&b.push([l.schema,B],[l.parentSchema,(0,t._)`${Te}${Z}`],[o.default.data,x]),me&&b.push([l.propertyName,me])}})(nc)),nc}var hg;function lw(){if(hg)return Kt;hg=1,Object.defineProperty(Kt,"__esModule",{value:!0}),Kt.boolOrEmptySchema=Kt.topBoolOrEmptySchema=void 0;const e=Ho(),t=se,r=At(),o={message:"boolean schema is false"};function n(s){const{gen:c,schema:u,validateName:l}=s;u===!1?a(s,!1):typeof u=="object"&&u.$async===!0?c.return(r.default.data):(c.assign((0,t._)`${l}.errors`,null),c.return(!0))}Kt.topBoolOrEmptySchema=n;function i(s,c){const{gen:u,schema:l}=s;l===!1?(u.var(c,!1),a(s)):u.var(c,!0)}Kt.boolOrEmptySchema=i;function a(s,c){const{gen:u,data:l}=s,d={gen:u,keyword:"false schema",data:l,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:s};(0,e.reportError)(d,o,void 0,c)}return Kt}var ze={},Gt={};Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.getRules=Gt.isJSONType=void 0;const dw=["string","number","integer","boolean","null","object","array"],mw=new Set(dw);function pw(e){return typeof e=="string"&&mw.has(e)}Gt.isJSONType=pw;function fw(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Gt.getRules=fw;var Pt={},gg;function vg(){if(gg)return Pt;gg=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.shouldUseRule=Pt.shouldUseGroup=Pt.schemaHasRulesForType=void 0;function e({schema:o,self:n},i){const a=n.RULES.types[i];return a&&a!==!0&&t(o,a)}Pt.schemaHasRulesForType=e;function t(o,n){return n.rules.some(i=>r(o,i))}Pt.shouldUseGroup=t;function r(o,n){var i;return o[n.keyword]!==void 0||((i=n.definition.implements)===null||i===void 0?void 0:i.some(a=>o[a]!==void 0))}return Pt.shouldUseRule=r,Pt}Object.defineProperty(ze,"__esModule",{value:!0}),ze.reportTypeError=ze.checkDataTypes=ze.checkDataType=ze.coerceAndCheckDataType=ze.getJSONTypes=ze.getSchemaTypes=ze.DataType=void 0;const hw=Gt,gw=vg(),vw=Ho(),re=se,yg=M;var _n;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(_n||(ze.DataType=_n={}));function yw(e){const t=_g(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}ze.getSchemaTypes=yw;function _g(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(hw.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ze.getJSONTypes=_g;function _w(e,t){const{gen:r,data:o,opts:n}=e,i=$w(t,n.coerceTypes),a=t.length>0&&!(i.length===0&&t.length===1&&(0,gw.schemaHasRulesForType)(e,t[0]));if(a){const s=cc(t,o,n.strictNumbers,_n.Wrong);r.if(s,()=>{i.length?bw(e,t,i):uc(e)})}return a}ze.coerceAndCheckDataType=_w;const $g=new Set(["string","number","integer","boolean","null"]);function $w(e,t){return t?e.filter(r=>$g.has(r)||t==="array"&&r==="array"):[]}function bw(e,t,r){const{gen:o,data:n,opts:i}=e,a=o.let("dataType",(0,re._)`typeof ${n}`),s=o.let("coerced",(0,re._)`undefined`);i.coerceTypes==="array"&&o.if((0,re._)`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,(0,re._)`${n}[0]`).assign(a,(0,re._)`typeof ${n}`).if(cc(t,n,i.strictNumbers),()=>o.assign(s,n))),o.if((0,re._)`${s} !== undefined`);for(const u of r)($g.has(u)||u==="array"&&i.coerceTypes==="array")&&c(u);o.else(),uc(e),o.endIf(),o.if((0,re._)`${s} !== undefined`,()=>{o.assign(n,s),kw(e,s)});function c(u){switch(u){case"string":o.elseIf((0,re._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,re._)`"" + ${n}`).elseIf((0,re._)`${n} === null`).assign(s,(0,re._)`""`);return;case"number":o.elseIf((0,re._)`${a} == "boolean" || ${n} === null
|
|
72
72
|
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(s,(0,re._)`+${n}`);return;case"integer":o.elseIf((0,re._)`${a} === "boolean" || ${n} === null
|
|
73
73
|
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(s,(0,re._)`+${n}`);return;case"boolean":o.elseIf((0,re._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(s,!1).elseIf((0,re._)`${n} === "true" || ${n} === 1`).assign(s,!0);return;case"null":o.elseIf((0,re._)`${n} === "" || ${n} === 0 || ${n} === false`),o.assign(s,null);return;case"array":o.elseIf((0,re._)`${a} === "string" || ${a} === "number"
|