@babylonjs/mcp-servers 9.12.0 → 9.12.1
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
|
@@ -67,7 +67,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
67
67
|
]))`;continue}else if(i[c]==="$"){n+=`($|(?=[\r
|
|
68
68
|
]))`;continue}}if(r.s&&i[c]==="."){n+=a?`${i[c]}\r
|
|
69
69
|
`:`[${i[c]}\r
|
|
70
|
-
]`;continue}n+=i[c],i[c]==="\\"?o=!0:a&&i[c]==="]"?a=!1:!a&&i[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 Mh(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===ee.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((i,n)=>({...i,[n]:pe(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Ge(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:pe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ee.ZodString&&e.keyType._def.checks?.length){const{type:i,...n}=Ch(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===ee.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ee.ZodBranded&&e.keyType._def.type._def.typeName===ee.ZodString&&e.keyType._def.type._def.checks?.length){const{type:i,...n}=Uh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function sS(e,t){if(t.mapStrategy==="record")return Mh(e,t);const r=pe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ge(t),i=pe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ge(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function cS(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),n=Array.from(new Set(i.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:i}}function uS(e){return e.target==="openAi"?void 0:{not:Ge({...e,currentPath:[...e.currentPath,"not"]})}}function lS(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Fi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function dS(e,t){if(t.target==="openApi3")return Fh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(i=>i._def.typeName in Fi&&(!i._def.checks||!i._def.checks.length))){const i=r.reduce((n,o)=>{const a=Fi[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:i.length>1?i:i[0]}}else if(r.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=r.reduce((n,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(i.length===r.length){const n=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:n.length>1?n:n[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((i,n)=>[...i,...n._def.values.filter(o=>!i.includes(o))],[])};return Fh(e,t)}const Fh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,n)=>pe(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return r.length?{anyOf:r}:void 0};function fS(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:Fi[e.innerType._def.typeName],nullable:!0}:{type:[Fi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const i=pe(e.innerType._def,{...t,currentPath:[...t.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}const r=pe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function mS(e,t){const r={type:"number"};if(!e.checks)return r;for(const i of e.checks)switch(i.kind){case"int":r.type="integer",Dh(r,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?ge(r,"minimum",i.value,i.message,t):ge(r,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(r.exclusiveMinimum=!0),ge(r,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?ge(r,"maximum",i.value,i.message,t):ge(r,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(r.exclusiveMaximum=!0),ge(r,"maximum",i.value,i.message,t));break;case"multipleOf":ge(r,"multipleOf",i.value,i.message,t);break}return r}function pS(e,t){const r=t.target==="openAi",i={type:"object",properties:{}},n=[],o=e.shape();for(const s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let u=gS(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=pe(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,u||n.push(s))}n.length&&(i.required=n);const a=hS(e,t);return a!==void 0&&(i.additionalProperties=a),i}function hS(e,t){if(e.catchall._def.typeName!=="ZodNever")return pe(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 gS(e){try{return e.isOptional()}catch{return!0}}const vS=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return pe(e.innerType._def,t);const r=pe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ge(t)},r]}:Ge(t)},_S=(e,t)=>{if(t.pipeStrategy==="input")return pe(e.in._def,t);if(t.pipeStrategy==="output")return pe(e.out._def,t);const r=pe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=pe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function yS(e,t){return pe(e.type._def,t)}function $S(e,t){const i={type:"array",uniqueItems:!0,items:pe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ge(i,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ge(i,"maxItems",e.maxSize.value,e.maxSize.message,t),i}function bS(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,i)=>pe(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:pe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,i)=>pe(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function kS(e){return{not:Ge(e)}}function SS(e){return Ge(e)}const wS=(e,t)=>pe(e.innerType._def,t),IS=(e,t,r)=>{switch(t){case ee.ZodString:return Ch(e,r);case ee.ZodNumber:return mS(e,r);case ee.ZodObject:return pS(e,r);case ee.ZodBigInt:return Gk(e,r);case ee.ZodBoolean:return Wk();case ee.ZodDate:return Ah(e,r);case ee.ZodUndefined:return kS(r);case ee.ZodNull:return lS(r);case ee.ZodArray:return Kk(e,r);case ee.ZodUnion:case ee.ZodDiscriminatedUnion:return dS(e,r);case ee.ZodIntersection:return rS(e,r);case ee.ZodTuple:return bS(e,r);case ee.ZodRecord:return Mh(e,r);case ee.ZodLiteral:return iS(e,r);case ee.ZodEnum:return tS(e);case ee.ZodNativeEnum:return cS(e);case ee.ZodNullable:return fS(e,r);case ee.ZodOptional:return vS(e,r);case ee.ZodMap:return sS(e,r);case ee.ZodSet:return $S(e,r);case ee.ZodLazy:return()=>e.getter()._def;case ee.ZodPromise:return yS(e,r);case ee.ZodNaN:case ee.ZodNever:return uS(r);case ee.ZodEffects:return eS(e,r);case ee.ZodAny:return Ge(r);case ee.ZodUnknown:return SS(r);case ee.ZodDefault:return Qk(e,r);case ee.ZodBranded:return Uh(e,r);case ee.ZodReadonly:return wS(e,r);case ee.ZodCatch:return Xk(e,r);case ee.ZodPipeline:return _S(e,r);case ee.ZodFunction:case ee.ZodVoid:case ee.ZodSymbol:return;default:return(i=>{})()}};function pe(e,t,r=!1){const i=t.seen.get(e);if(t.override){const s=t.override?.(e,t,i,r);if(s!==Vk)return s}if(i&&!r){const s=TS(i,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const o=IS(e,e.typeName,t),a=typeof o=="function"?pe(o(),t):o;if(a&&PS(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const TS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Rh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,i)=>t.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ge(t)):t.$refStrategy==="seen"?Ge(t):void 0}},PS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),zS=(e,t)=>{const r=Hk(t);let i=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:pe(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ge(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=pe(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Ge(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[r.openAiAnyTypeName]||(i[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?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};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 ES(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Lh(e,t){return St(e)?Pa(e,{target:ES(t?.target),io:t?.pipeStrategy??"input"}):zS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function qh(e){const r=ur(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const i=hh(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function Bh(e,t){const r=cr(e,t);if(!r.success)throw r.error;return r.data}const xS=6e4;class OS{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(xs,r=>{this._onprogress(r)}),this.setRequestHandler(Es,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Os,async(r,i)=>{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new V(G.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ns,async(r,i)=>{const n=async()=>{const o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.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,m=new V(d.error.code,d.error.message,d.error.data);l(m)}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:i.requestId})}}const a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new V(G.InvalidParams,`Task not found: ${o}`);if(!Ht(a.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(Ht(a.status)){const s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Jt]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Ds,async(r,i)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,i.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new V(G.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Us,async(r,i)=>{try{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new V(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ht(n.status))throw new V(G.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!o)throw new V(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof V?n:new V(G.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,i,n,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),V.fromError(G.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});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 i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{n?.(o,a),Di(o)||hb(o)?this._onresponse(o):$h(o)?this._onrequest(o,a):pb(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(const i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();const r=V.fromError(G.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const i of t.values())i(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(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,r){const i=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,o=t.params?._meta?.[Jt]?.taskId;if(i===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:G.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{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=mb(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};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new V(G.ConnectionClosed,"Request was cancelled");const f={...m,relatedRequestId:t.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});const h=f.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>i(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{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:G.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{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,...i}=t.params,n=Number(r),o=this._progressHandlers.get(n);if(!o){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}o(i)}_onresponse(t){const r=Number(t.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),Di(t))i(t);else{const a=new V(t.error.code,t.error.message,t.error.data);i(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 o=!1;if(Di(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"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),Di(t))n(t);else{const a=V.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,i){const{task:n}=i??{};if(!n){try{yield{type:"result",result:await this.request(t,r,i)}}catch(a){yield{type:"error",error:a instanceof V?a:new V(G.InternalError,String(a))}}return}let o;try{const a=await this.request(t,Ri,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new V(G.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Ht(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new V(G.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new V(G.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof V?a:new V(G.InternalError,String(a))}}}request(t,r,i){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=i??{};return new Promise((u,l)=>{const d=_=>{l(_)};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(_){d(_);return}i?.signal?.throwIfAborted();const m=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:m}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Jt]:c}});const h=_=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(_)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(z=>this._onerror(new Error(`Failed to send cancellation: ${z}`)));const w=_ instanceof V?_:new V(G.RequestTimeout,String(_));l(w)};this._responseHandlers.set(m,_=>{if(!i?.signal?.aborted){if(_ instanceof Error)return l(_);try{const w=cr(r,_.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});const $=i?.timeout??xS,y=()=>h(V.fromError(G.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(m,$,i?.maxTotalTimeout,y,i?.resetTimeoutOnProgress??!1);const v=c?.taskId;if(v){const _=w=>{const z=this._responseHandlers.get(m);z?z(w):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,_),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(m),l(w)})}else this._transport.send(f,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(_=>{this._cleanupTimeout(m),l(_)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},js,r)}async getTaskResult(t,r,i){return this.request({method:"tasks/result",params:t},r,i)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Rs,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 i=r?.relatedTask?.taskId;if(i){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Jt]:r.relatedTask}}};await this._enqueueTaskMessage(i,{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 i=qh(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{const a=Bh(t,n);return Promise.resolve(r(a,o))})}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 i=qh(t);this._notificationHandlers.set(i,n=>{const o=Bh(t,n);return Promise.resolve(r(o))})}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,i){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,i,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const i=await this._taskMessageQueue.dequeueAll(t,r);for(const n of i)if(n.type==="request"&&$h(n.message)){const o=n.message.id,a=this._requestResolvers.get(o);a?(a(new V(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let i=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(i=n.pollInterval)}catch{}return new Promise((n,o)=>{if(r.aborted){o(new V(G.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(a),o(new V(G.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await i.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const o=await i.getTask(n,r);if(!o)throw new V(G.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,a)=>{await i.storeTaskResult(n,o,a,r);const s=await i.getTask(n,r);if(s){const c=Ui.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Ht(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>i.getTaskResult(n,r),updateTaskStatus:async(n,o,a)=>{const s=await i.getTask(n,r);if(!s)throw new V(G.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Ht(s.status))throw new V(G.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(n,o,a,r);const c=await i.getTask(n,r);if(c){const u=Ui.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ht(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}}function Vh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function jS(e,t){const r={...e};for(const i in t){const n=i,o=t[n];if(o===void 0)continue;const a=r[n];Vh(a)&&Vh(o)?r[n]={...a,...o}:r[n]=o}return r}function Jh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ec={exports:{}},Hh={},Pt={},Kt={},tc={},se={},vr={};(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(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class i extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((w,z)=>`${w}${z}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((w,z)=>(z instanceof r&&(w[z.str]=(w[z.str]||0)+1),w),{})}}e._Code=i,e.nil=new i("");function n(v,..._){const w=[v[0]];let z=0;for(;z<_.length;)s(w,_[z]),w.push(v[++z]);return new i(w)}e._=n;const o=new i("+");function a(v,..._){const w=[f(v[0])];let z=0;for(;z<_.length;)w.push(o),s(w,_[z]),w.push(o,f(v[++z]));return c(w),new i(w)}e.str=a;function s(v,_){_ instanceof i?v.push(..._._items):_ instanceof r?v.push(_):v.push(d(_))}e.addCodeArg=s;function c(v){let _=1;for(;_<v.length-1;){if(v[_]===o){const w=u(v[_-1],v[_+1]);if(w!==void 0){v.splice(_-1,3,w);continue}v[_++]="+"}_++}}function u(v,_){if(_==='""')return v;if(v==='""')return _;if(typeof v=="string")return _ instanceof r||v[v.length-1]!=='"'?void 0:typeof _!="string"?`${v.slice(0,-1)}${_}"`:_[0]==='"'?v.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(v instanceof r))return`"${v}${_.slice(1)}`}function l(v,_){return _.emptyStr()?v:v.emptyStr()?_:a`${v}${_}`}e.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:f(Array.isArray(v)?v.join(","):v)}function m(v){return new i(f(v))}e.stringify=m;function f(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function h(v){return typeof v=="string"&&e.IDENTIFIER.test(v)?new i(`.${v}`):n`[${v}]`}e.getProperty=h;function $(v){if(typeof v=="string"&&e.IDENTIFIER.test(v))return new i(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}e.getEsmExportName=$;function y(v){return new i(v.toString())}e.regexpCode=y})(vr);var nc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=vr;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var i;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(i||(e.UsedValueState=i={})),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 o 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=o;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 o(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 m=this.toName(u),{prefix:f}=m,h=(d=l.key)!==null&&d!==void 0?d:l.ref;let $=this._values[f];if($){const _=$.get(h);if(_)return _}else $=this._values[f]=new Map;$.set(h,m);const y=this._scope[f]||(this._scope[f]=[]),v=y.length;return y[v]=l.ref,m.setValue(l,{property:f,itemIndex:v}),m}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,m=>{if(m.value===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return m.value.code},l,d)}_reduceValues(u,l,d={},m){let f=t.nil;for(const h in u){const $=u[h];if(!$)continue;const y=d[h]=d[h]||new Map;$.forEach(v=>{if(y.has(v))return;y.set(v,i.Started);let _=l(v);if(_){const w=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${w} ${v} = ${_};${this.opts._n}`}else if(_=m?.(v))f=(0,t._)`${f}${_}${this.opts._n}`;else throw new r(v);y.set(v,i.Completed)})}return f}}e.ValueScope=s})(nc),(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=vr,r=nc;var i=vr;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return i.Name}});var n=nc;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 o{optimizeNodes(){return this}optimizeNames(p,g){return this}}class a extends o{constructor(p,g,E){super(),this.varKind=p,this.name=g,this.rhs=E}render({es5:p,_n:g}){const E=p?r.varKinds.var:this.varKind,F=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${F};`+g}optimizeNames(p,g){if(p[this.name.str])return this.rhs&&(this.rhs=K(this.rhs,p,g)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends o{constructor(p,g,E){super(),this.lhs=p,this.rhs=g,this.sideEffects=E}render({_n:p}){return`${this.lhs} = ${this.rhs};`+p}optimizeNames(p,g){if(!(this.lhs instanceof t.Name&&!p[this.lhs.str]&&!this.sideEffects))return this.rhs=K(this.rhs,p,g),this}get names(){const p=this.lhs instanceof t.Name?{}:{...this.lhs.names};return te(p,this.rhs)}}class c extends s{constructor(p,g,E,F){super(p,E,F),this.op=g}render({_n:p}){return`${this.lhs} ${this.op}= ${this.rhs};`+p}}class u extends o{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`${this.label}:`+p}}class l extends o{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`break${this.label?` ${this.label}`:""};`+p}}class d extends o{constructor(p){super(),this.error=p}render({_n:p}){return`throw ${this.error};`+p}get names(){return this.error.names}}class m extends o{constructor(p){super(),this.code=p}render({_n:p}){return`${this.code};`+p}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(p,g){return this.code=K(this.code,p,g),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends o{constructor(p=[]){super(),this.nodes=p}render(p){return this.nodes.reduce((g,E)=>g+E.render(p),"")}optimizeNodes(){const{nodes:p}=this;let g=p.length;for(;g--;){const E=p[g].optimizeNodes();Array.isArray(E)?p.splice(g,1,...E):E?p[g]=E:p.splice(g,1)}return p.length>0?this:void 0}optimizeNames(p,g){const{nodes:E}=this;let F=E.length;for(;F--;){const J=E[F];J.optimizeNames(p,g)||(ze(p,J.names),E.splice(F,1))}return E.length>0?this:void 0}get names(){return this.nodes.reduce((p,g)=>X(p,g.names),{})}}class h extends f{render(p){return"{"+p._n+super.render(p)+"}"+p._n}}class $ extends f{}class y extends h{}y.kind="else";class v extends h{constructor(p,g){super(g),this.condition=p}render(p){let g=`if(${this.condition})`+super.render(p);return this.else&&(g+="else "+this.else.render(p)),g}optimizeNodes(){super.optimizeNodes();const p=this.condition;if(p===!0)return this.nodes;let g=this.else;if(g){const E=g.optimizeNodes();g=this.else=Array.isArray(E)?new y(E):E}if(g)return p===!1?g instanceof v?g:g.nodes:this.nodes.length?this:new v(rt(p),g instanceof v?[g]:g.nodes);if(!(p===!1||!this.nodes.length))return this}optimizeNames(p,g){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames(p,g),!!(super.optimizeNames(p,g)||this.else))return this.condition=K(this.condition,p,g),this}get names(){const p=super.names;return te(p,this.condition),this.else&&X(p,this.else.names),p}}v.kind="if";class _ extends h{}_.kind="for";class w extends _{constructor(p){super(),this.iteration=p}render(p){return`for(${this.iteration})`+super.render(p)}optimizeNames(p,g){if(super.optimizeNames(p,g))return this.iteration=K(this.iteration,p,g),this}get names(){return X(super.names,this.iteration.names)}}class z extends _{constructor(p,g,E,F){super(),this.varKind=p,this.name=g,this.from=E,this.to=F}render(p){const g=p.es5?r.varKinds.var:this.varKind,{name:E,from:F,to:J}=this;return`for(${g} ${E}=${F}; ${E}<${J}; ${E}++)`+super.render(p)}get names(){const p=te(super.names,this.from);return te(p,this.to)}}class O extends _{constructor(p,g,E,F){super(),this.loop=p,this.varKind=g,this.name=E,this.iterable=F}render(p){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(p)}optimizeNames(p,g){if(super.optimizeNames(p,g))return this.iterable=K(this.iterable,p,g),this}get names(){return X(super.names,this.iterable.names)}}class q extends h{constructor(p,g,E){super(),this.name=p,this.args=g,this.async=E}render(p){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(p)}}q.kind="func";class Y extends f{render(p){return"return "+super.render(p)}}Y.kind="return";class de extends h{render(p){let g="try"+super.render(p);return this.catch&&(g+=this.catch.render(p)),this.finally&&(g+=this.finally.render(p)),g}optimizeNodes(){var p,g;return super.optimizeNodes(),(p=this.catch)===null||p===void 0||p.optimizeNodes(),(g=this.finally)===null||g===void 0||g.optimizeNodes(),this}optimizeNames(p,g){var E,F;return super.optimizeNames(p,g),(E=this.catch)===null||E===void 0||E.optimizeNames(p,g),(F=this.finally)===null||F===void 0||F.optimizeNames(p,g),this}get names(){const p=super.names;return this.catch&&X(p,this.catch.names),this.finally&&X(p,this.finally.names),p}}class we extends h{constructor(p){super(),this.error=p}render(p){return`catch(${this.error})`+super.render(p)}}we.kind="catch";class Pe extends h{render(p){return"finally"+super.render(p)}}Pe.kind="finally";class M{constructor(p,g={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...g,_n:g.lines?`
|
|
70
|
+
]`;continue}n+=i[c],i[c]==="\\"?o=!0:a&&i[c]==="]"?a=!1:!a&&i[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 Mh(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===ee.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((i,n)=>({...i,[n]:pe(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Ge(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:pe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ee.ZodString&&e.keyType._def.checks?.length){const{type:i,...n}=Ch(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===ee.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ee.ZodBranded&&e.keyType._def.type._def.typeName===ee.ZodString&&e.keyType._def.type._def.checks?.length){const{type:i,...n}=Uh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function sS(e,t){if(t.mapStrategy==="record")return Mh(e,t);const r=pe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ge(t),i=pe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ge(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function cS(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),n=Array.from(new Set(i.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:i}}function uS(e){return e.target==="openAi"?void 0:{not:Ge({...e,currentPath:[...e.currentPath,"not"]})}}function lS(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Fi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function dS(e,t){if(t.target==="openApi3")return Fh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(i=>i._def.typeName in Fi&&(!i._def.checks||!i._def.checks.length))){const i=r.reduce((n,o)=>{const a=Fi[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:i.length>1?i:i[0]}}else if(r.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=r.reduce((n,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(i.length===r.length){const n=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:n.length>1?n:n[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((i,n)=>[...i,...n._def.values.filter(o=>!i.includes(o))],[])};return Fh(e,t)}const Fh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,n)=>pe(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return r.length?{anyOf:r}:void 0};function fS(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:Fi[e.innerType._def.typeName],nullable:!0}:{type:[Fi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const i=pe(e.innerType._def,{...t,currentPath:[...t.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}const r=pe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function mS(e,t){const r={type:"number"};if(!e.checks)return r;for(const i of e.checks)switch(i.kind){case"int":r.type="integer",Dh(r,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?ge(r,"minimum",i.value,i.message,t):ge(r,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(r.exclusiveMinimum=!0),ge(r,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?ge(r,"maximum",i.value,i.message,t):ge(r,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(r.exclusiveMaximum=!0),ge(r,"maximum",i.value,i.message,t));break;case"multipleOf":ge(r,"multipleOf",i.value,i.message,t);break}return r}function pS(e,t){const r=t.target==="openAi",i={type:"object",properties:{}},n=[],o=e.shape();for(const s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let u=gS(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=pe(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,u||n.push(s))}n.length&&(i.required=n);const a=hS(e,t);return a!==void 0&&(i.additionalProperties=a),i}function hS(e,t){if(e.catchall._def.typeName!=="ZodNever")return pe(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 gS(e){try{return e.isOptional()}catch{return!0}}const vS=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return pe(e.innerType._def,t);const r=pe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ge(t)},r]}:Ge(t)},_S=(e,t)=>{if(t.pipeStrategy==="input")return pe(e.in._def,t);if(t.pipeStrategy==="output")return pe(e.out._def,t);const r=pe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=pe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function yS(e,t){return pe(e.type._def,t)}function $S(e,t){const i={type:"array",uniqueItems:!0,items:pe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ge(i,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ge(i,"maxItems",e.maxSize.value,e.maxSize.message,t),i}function bS(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,i)=>pe(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:pe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,i)=>pe(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function kS(e){return{not:Ge(e)}}function SS(e){return Ge(e)}const wS=(e,t)=>pe(e.innerType._def,t),IS=(e,t,r)=>{switch(t){case ee.ZodString:return Ch(e,r);case ee.ZodNumber:return mS(e,r);case ee.ZodObject:return pS(e,r);case ee.ZodBigInt:return Gk(e,r);case ee.ZodBoolean:return Wk();case ee.ZodDate:return Ah(e,r);case ee.ZodUndefined:return kS(r);case ee.ZodNull:return lS(r);case ee.ZodArray:return Kk(e,r);case ee.ZodUnion:case ee.ZodDiscriminatedUnion:return dS(e,r);case ee.ZodIntersection:return rS(e,r);case ee.ZodTuple:return bS(e,r);case ee.ZodRecord:return Mh(e,r);case ee.ZodLiteral:return iS(e,r);case ee.ZodEnum:return tS(e);case ee.ZodNativeEnum:return cS(e);case ee.ZodNullable:return fS(e,r);case ee.ZodOptional:return vS(e,r);case ee.ZodMap:return sS(e,r);case ee.ZodSet:return $S(e,r);case ee.ZodLazy:return()=>e.getter()._def;case ee.ZodPromise:return yS(e,r);case ee.ZodNaN:case ee.ZodNever:return uS(r);case ee.ZodEffects:return eS(e,r);case ee.ZodAny:return Ge(r);case ee.ZodUnknown:return SS(r);case ee.ZodDefault:return Qk(e,r);case ee.ZodBranded:return Uh(e,r);case ee.ZodReadonly:return wS(e,r);case ee.ZodCatch:return Xk(e,r);case ee.ZodPipeline:return _S(e,r);case ee.ZodFunction:case ee.ZodVoid:case ee.ZodSymbol:return;default:return(i=>{})()}};function pe(e,t,r=!1){const i=t.seen.get(e);if(t.override){const s=t.override?.(e,t,i,r);if(s!==Vk)return s}if(i&&!r){const s=TS(i,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const o=IS(e,e.typeName,t),a=typeof o=="function"?pe(o(),t):o;if(a&&PS(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const TS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Rh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,i)=>t.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ge(t)):t.$refStrategy==="seen"?Ge(t):void 0}},PS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),zS=(e,t)=>{const r=Hk(t);let i=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:pe(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ge(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=pe(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Ge(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[r.openAiAnyTypeName]||(i[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?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};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 ES(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Lh(e,t){return St(e)?Pa(e,{target:ES(t?.target),io:t?.pipeStrategy??"input"}):zS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function qh(e){const r=ur(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const i=hh(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function Bh(e,t){const r=cr(e,t);if(!r.success)throw r.error;return r.data}const xS=6e4;class OS{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(xs,r=>{this._onprogress(r)}),this.setRequestHandler(Es,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Os,async(r,i)=>{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new V(G.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ns,async(r,i)=>{const n=async()=>{const o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.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,m=new V(d.error.code,d.error.message,d.error.data);l(m)}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:i.requestId})}}const a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new V(G.InvalidParams,`Task not found: ${o}`);if(!Ht(a.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(Ht(a.status)){const s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Jt]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Ds,async(r,i)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,i.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new V(G.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Us,async(r,i)=>{try{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new V(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ht(n.status))throw new V(G.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!o)throw new V(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof V?n:new V(G.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,i,n,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),V.fromError(G.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});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 i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{n?.(o,a),Di(o)||hb(o)?this._onresponse(o):$h(o)?this._onrequest(o,a):pb(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(const i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();const r=V.fromError(G.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const i of t.values())i(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(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,r){const i=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,o=t.params?._meta?.[Jt]?.taskId;if(i===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:G.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{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=mb(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};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new V(G.ConnectionClosed,"Request was cancelled");const f={...m,relatedRequestId:t.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});const h=f.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>i(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{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:G.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{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,...i}=t.params,n=Number(r),o=this._progressHandlers.get(n);if(!o){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}o(i)}_onresponse(t){const r=Number(t.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),Di(t))i(t);else{const a=new V(t.error.code,t.error.message,t.error.data);i(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 o=!1;if(Di(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"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),Di(t))n(t);else{const a=V.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,i){const{task:n}=i??{};if(!n){try{yield{type:"result",result:await this.request(t,r,i)}}catch(a){yield{type:"error",error:a instanceof V?a:new V(G.InternalError,String(a))}}return}let o;try{const a=await this.request(t,Ri,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new V(G.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Ht(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new V(G.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new V(G.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof V?a:new V(G.InternalError,String(a))}}}request(t,r,i){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=i??{};return new Promise((u,l)=>{const d=_=>{l(_)};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(_){d(_);return}i?.signal?.throwIfAborted();const m=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:m}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Jt]:c}});const h=_=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(_)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(z=>this._onerror(new Error(`Failed to send cancellation: ${z}`)));const w=_ instanceof V?_:new V(G.RequestTimeout,String(_));l(w)};this._responseHandlers.set(m,_=>{if(!i?.signal?.aborted){if(_ instanceof Error)return l(_);try{const w=cr(r,_.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});const $=i?.timeout??xS,y=()=>h(V.fromError(G.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(m,$,i?.maxTotalTimeout,y,i?.resetTimeoutOnProgress??!1);const v=c?.taskId;if(v){const _=w=>{const z=this._responseHandlers.get(m);z?z(w):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,_),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(m),l(w)})}else this._transport.send(f,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(_=>{this._cleanupTimeout(m),l(_)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},js,r)}async getTaskResult(t,r,i){return this.request({method:"tasks/result",params:t},r,i)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Rs,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 i=r?.relatedTask?.taskId;if(i){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Jt]:r.relatedTask}}};await this._enqueueTaskMessage(i,{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 i=qh(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{const a=Bh(t,n);return Promise.resolve(r(a,o))})}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 i=qh(t);this._notificationHandlers.set(i,n=>{const o=Bh(t,n);return Promise.resolve(r(o))})}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,i){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,i,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const i=await this._taskMessageQueue.dequeueAll(t,r);for(const n of i)if(n.type==="request"&&$h(n.message)){const o=n.message.id,a=this._requestResolvers.get(o);a?(a(new V(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let i=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(i=n.pollInterval)}catch{}return new Promise((n,o)=>{if(r.aborted){o(new V(G.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(a),o(new V(G.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await i.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const o=await i.getTask(n,r);if(!o)throw new V(G.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,a)=>{await i.storeTaskResult(n,o,a,r);const s=await i.getTask(n,r);if(s){const c=Ui.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Ht(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>i.getTaskResult(n,r),updateTaskStatus:async(n,o,a)=>{const s=await i.getTask(n,r);if(!s)throw new V(G.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Ht(s.status))throw new V(G.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(n,o,a,r);const c=await i.getTask(n,r);if(c){const u=Ui.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ht(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}}function Vh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function jS(e,t){const r={...e};for(const i in t){const n=i,o=t[n];if(o===void 0)continue;const a=r[n];Vh(a)&&Vh(o)?r[n]={...a,...o}:r[n]=o}return r}function Jh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ec={exports:{}},Hh={},Pt={},Kt={},tc={},se={},vr={};(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(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class i extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((w,z)=>`${w}${z}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((w,z)=>(z instanceof r&&(w[z.str]=(w[z.str]||0)+1),w),{})}}e._Code=i,e.nil=new i("");function n(v,..._){const w=[v[0]];let z=0;for(;z<_.length;)s(w,_[z]),w.push(v[++z]);return new i(w)}e._=n;const o=new i("+");function a(v,..._){const w=[f(v[0])];let z=0;for(;z<_.length;)w.push(o),s(w,_[z]),w.push(o,f(v[++z]));return c(w),new i(w)}e.str=a;function s(v,_){_ instanceof i?v.push(..._._items):_ instanceof r?v.push(_):v.push(d(_))}e.addCodeArg=s;function c(v){let _=1;for(;_<v.length-1;){if(v[_]===o){const w=u(v[_-1],v[_+1]);if(w!==void 0){v.splice(_-1,3,w);continue}v[_++]="+"}_++}}function u(v,_){if(_==='""')return v;if(v==='""')return _;if(typeof v=="string")return _ instanceof r||v[v.length-1]!=='"'?void 0:typeof _!="string"?`${v.slice(0,-1)}${_}"`:_[0]==='"'?v.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(v instanceof r))return`"${v}${_.slice(1)}`}function l(v,_){return _.emptyStr()?v:v.emptyStr()?_:a`${v}${_}`}e.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:f(Array.isArray(v)?v.join(","):v)}function m(v){return new i(f(v))}e.stringify=m;function f(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function h(v){return typeof v=="string"&&e.IDENTIFIER.test(v)?new i(`.${v}`):n`[${v}]`}e.getProperty=h;function $(v){if(typeof v=="string"&&e.IDENTIFIER.test(v))return new i(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}e.getEsmExportName=$;function y(v){return new i(v.toString())}e.regexpCode=y})(vr);var nc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=vr;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var i;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(i||(e.UsedValueState=i={})),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 o 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=o;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 o(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 m=this.toName(u),{prefix:f}=m,h=(d=l.key)!==null&&d!==void 0?d:l.ref;let $=this._values[f];if($){const _=$.get(h);if(_)return _}else $=this._values[f]=new Map;$.set(h,m);const y=this._scope[f]||(this._scope[f]=[]),v=y.length;return y[v]=l.ref,m.setValue(l,{property:f,itemIndex:v}),m}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,m=>{if(m.value===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return m.value.code},l,d)}_reduceValues(u,l,d={},m){let f=t.nil;for(const h in u){const $=u[h];if(!$)continue;const y=d[h]=d[h]||new Map;$.forEach(v=>{if(y.has(v))return;y.set(v,i.Started);let _=l(v);if(_){const w=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${w} ${v} = ${_};${this.opts._n}`}else if(_=m?.(v))f=(0,t._)`${f}${_}${this.opts._n}`;else throw new r(v);y.set(v,i.Completed)})}return f}}e.ValueScope=s})(nc),(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=vr,r=nc;var i=vr;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return i.Name}});var n=nc;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 o{optimizeNodes(){return this}optimizeNames(p,g){return this}}class a extends o{constructor(p,g,E){super(),this.varKind=p,this.name=g,this.rhs=E}render({es5:p,_n:g}){const E=p?r.varKinds.var:this.varKind,F=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${F};`+g}optimizeNames(p,g){if(p[this.name.str])return this.rhs&&(this.rhs=K(this.rhs,p,g)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends o{constructor(p,g,E){super(),this.lhs=p,this.rhs=g,this.sideEffects=E}render({_n:p}){return`${this.lhs} = ${this.rhs};`+p}optimizeNames(p,g){if(!(this.lhs instanceof t.Name&&!p[this.lhs.str]&&!this.sideEffects))return this.rhs=K(this.rhs,p,g),this}get names(){const p=this.lhs instanceof t.Name?{}:{...this.lhs.names};return te(p,this.rhs)}}class c extends s{constructor(p,g,E,F){super(p,E,F),this.op=g}render({_n:p}){return`${this.lhs} ${this.op}= ${this.rhs};`+p}}class u extends o{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`${this.label}:`+p}}class l extends o{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`break${this.label?` ${this.label}`:""};`+p}}class d extends o{constructor(p){super(),this.error=p}render({_n:p}){return`throw ${this.error};`+p}get names(){return this.error.names}}class m extends o{constructor(p){super(),this.code=p}render({_n:p}){return`${this.code};`+p}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(p,g){return this.code=K(this.code,p,g),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends o{constructor(p=[]){super(),this.nodes=p}render(p){return this.nodes.reduce((g,E)=>g+E.render(p),"")}optimizeNodes(){const{nodes:p}=this;let g=p.length;for(;g--;){const E=p[g].optimizeNodes();Array.isArray(E)?p.splice(g,1,...E):E?p[g]=E:p.splice(g,1)}return p.length>0?this:void 0}optimizeNames(p,g){const{nodes:E}=this;let F=E.length;for(;F--;){const J=E[F];J.optimizeNames(p,g)||(ze(p,J.names),E.splice(F,1))}return E.length>0?this:void 0}get names(){return this.nodes.reduce((p,g)=>X(p,g.names),{})}}class h extends f{render(p){return"{"+p._n+super.render(p)+"}"+p._n}}class $ extends f{}class y extends h{}y.kind="else";class v extends h{constructor(p,g){super(g),this.condition=p}render(p){let g=`if(${this.condition})`+super.render(p);return this.else&&(g+="else "+this.else.render(p)),g}optimizeNodes(){super.optimizeNodes();const p=this.condition;if(p===!0)return this.nodes;let g=this.else;if(g){const E=g.optimizeNodes();g=this.else=Array.isArray(E)?new y(E):E}if(g)return p===!1?g instanceof v?g:g.nodes:this.nodes.length?this:new v(rt(p),g instanceof v?[g]:g.nodes);if(!(p===!1||!this.nodes.length))return this}optimizeNames(p,g){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames(p,g),!!(super.optimizeNames(p,g)||this.else))return this.condition=K(this.condition,p,g),this}get names(){const p=super.names;return te(p,this.condition),this.else&&X(p,this.else.names),p}}v.kind="if";class _ extends h{}_.kind="for";class w extends _{constructor(p){super(),this.iteration=p}render(p){return`for(${this.iteration})`+super.render(p)}optimizeNames(p,g){if(super.optimizeNames(p,g))return this.iteration=K(this.iteration,p,g),this}get names(){return X(super.names,this.iteration.names)}}class z extends _{constructor(p,g,E,F){super(),this.varKind=p,this.name=g,this.from=E,this.to=F}render(p){const g=p.es5?r.varKinds.var:this.varKind,{name:E,from:F,to:J}=this;return`for(${g} ${E}=${F}; ${E}<${J}; ${E}++)`+super.render(p)}get names(){const p=te(super.names,this.from);return te(p,this.to)}}class O extends _{constructor(p,g,E,F){super(),this.loop=p,this.varKind=g,this.name=E,this.iterable=F}render(p){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(p)}optimizeNames(p,g){if(super.optimizeNames(p,g))return this.iterable=K(this.iterable,p,g),this}get names(){return X(super.names,this.iterable.names)}}class q extends h{constructor(p,g,E){super(),this.name=p,this.args=g,this.async=E}render(p){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(p)}}q.kind="func";class Y extends f{render(p){return"return "+super.render(p)}}Y.kind="return";class de extends h{render(p){let g="try"+super.render(p);return this.catch&&(g+=this.catch.render(p)),this.finally&&(g+=this.finally.render(p)),g}optimizeNodes(){var p,g;return super.optimizeNodes(),(p=this.catch)===null||p===void 0||p.optimizeNodes(),(g=this.finally)===null||g===void 0||g.optimizeNodes(),this}optimizeNames(p,g){var E,F;return super.optimizeNames(p,g),(E=this.catch)===null||E===void 0||E.optimizeNames(p,g),(F=this.finally)===null||F===void 0||F.optimizeNames(p,g),this}get names(){const p=super.names;return this.catch&&X(p,this.catch.names),this.finally&&X(p,this.finally.names),p}}class we extends h{constructor(p){super(),this.error=p}render(p){return`catch(${this.error})`+super.render(p)}}we.kind="catch";class Pe extends h{render(p){return"finally"+super.render(p)}}Pe.kind="finally";class M{constructor(p,g={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...g,_n:g.lines?`
|
|
71
71
|
`:""},this._extScope=p,this._scope=new r.Scope({parent:p}),this._nodes=[new $]}toString(){return this._root.render(this.opts)}name(p){return this._scope.name(p)}scopeName(p){return this._extScope.name(p)}scopeValue(p,g){const E=this._extScope.value(p,g);return(this._values[E.prefix]||(this._values[E.prefix]=new Set)).add(E),E}getScopeValue(p,g){return this._extScope.getValue(p,g)}scopeRefs(p){return this._extScope.scopeRefs(p,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(p,g,E,F){const J=this._scope.toName(g);return E!==void 0&&F&&(this._constants[J.str]=E),this._leafNode(new a(p,J,E)),J}const(p,g,E){return this._def(r.varKinds.const,p,g,E)}let(p,g,E){return this._def(r.varKinds.let,p,g,E)}var(p,g,E){return this._def(r.varKinds.var,p,g,E)}assign(p,g,E){return this._leafNode(new s(p,g,E))}add(p,g){return this._leafNode(new c(p,e.operators.ADD,g))}code(p){return typeof p=="function"?p():p!==t.nil&&this._leafNode(new m(p)),this}object(...p){const g=["{"];for(const[E,F]of p)g.length>1&&g.push(","),g.push(E),(E!==F||this.opts.es5)&&(g.push(":"),(0,t.addCodeArg)(g,F));return g.push("}"),new t._Code(g)}if(p,g,E){if(this._blockNode(new v(p)),g&&E)this.code(g).else().code(E).endIf();else if(g)this.code(g).endIf();else if(E)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(p){return this._elseNode(new v(p))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(v,y)}_for(p,g){return this._blockNode(p),g&&this.code(g).endFor(),this}for(p,g){return this._for(new w(p),g)}forRange(p,g,E,F,J=this.opts.es5?r.varKinds.var:r.varKinds.let){const fe=this._scope.toName(p);return this._for(new z(J,fe,g,E),()=>F(fe))}forOf(p,g,E,F=r.varKinds.const){const J=this._scope.toName(p);if(this.opts.es5){const fe=g instanceof t.Name?g:this.var("_arr",g);return this.forRange("_i",0,(0,t._)`${fe}.length`,le=>{this.var(J,(0,t._)`${fe}[${le}]`),E(J)})}return this._for(new O("of",F,J,g),()=>E(J))}forIn(p,g,E,F=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(p,(0,t._)`Object.keys(${g})`,E);const J=this._scope.toName(p);return this._for(new O("in",F,J,g),()=>E(J))}endFor(){return this._endBlockNode(_)}label(p){return this._leafNode(new u(p))}break(p){return this._leafNode(new l(p))}return(p){const g=new Y;if(this._blockNode(g),this.code(p),g.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Y)}try(p,g,E){if(!g&&!E)throw new Error('CodeGen: "try" without "catch" and "finally"');const F=new de;if(this._blockNode(F),this.code(p),g){const J=this.name("e");this._currNode=F.catch=new we(J),g(J)}return E&&(this._currNode=F.finally=new Pe,this.code(E)),this._endBlockNode(we,Pe)}throw(p){return this._leafNode(new d(p))}block(p,g){return this._blockStarts.push(this._nodes.length),p&&this.code(p).endBlock(g),this}endBlock(p){const g=this._blockStarts.pop();if(g===void 0)throw new Error("CodeGen: not in self-balancing block");const E=this._nodes.length-g;if(E<0||p!==void 0&&E!==p)throw new Error(`CodeGen: wrong number of nodes: ${E} vs ${p} expected`);return this._nodes.length=g,this}func(p,g=t.nil,E,F){return this._blockNode(new q(p,g,E)),F&&this.code(F).endFunc(),this}endFunc(){return this._endBlockNode(q)}optimize(p=1){for(;p-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(p){return this._currNode.nodes.push(p),this}_blockNode(p){this._currNode.nodes.push(p),this._nodes.push(p)}_endBlockNode(p,g){const E=this._currNode;if(E instanceof p||g&&E instanceof g)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${g?`${p.kind}/${g.kind}`:p.kind}"`)}_elseNode(p){const g=this._currNode;if(!(g instanceof v))throw new Error('CodeGen: "else" without "if"');return this._currNode=g.else=p,this}get _root(){return this._nodes[0]}get _currNode(){const p=this._nodes;return p[p.length-1]}set _currNode(p){const g=this._nodes;g[g.length-1]=p}}e.CodeGen=M;function X(P,p){for(const g in p)P[g]=(P[g]||0)+(p[g]||0);return P}function te(P,p){return p instanceof t._CodeOrName?X(P,p.names):P}function K(P,p,g){if(P instanceof t.Name)return E(P);if(!F(P))return P;return new t._Code(P._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=g[J.str];return fe===void 0||p[J.str]!==1?J:(delete p[J.str],fe)}function F(J){return J instanceof t._Code&&J._items.some(fe=>fe instanceof t.Name&&p[fe.str]===1&&g[fe.str]!==void 0)}}function ze(P,p){for(const g in p)P[g]=(P[g]||0)-(p[g]||0)}function rt(P){return typeof P=="boolean"||typeof P=="number"||P===null?!P:(0,t._)`!${N(P)}`}e.not=rt;const it=I(e.operators.AND);function Zt(...P){return P.reduce(it)}e.and=Zt;const wt=I(e.operators.OR);function U(...P){return P.reduce(wt)}e.or=U;function I(P){return(p,g)=>p===t.nil?g:g===t.nil?p:(0,t._)`${N(p)} ${P} ${N(g)}`}function N(P){return P instanceof t.Name?P:(0,t._)`(${P})`}})(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 Se=se,NS=vr;function DS(e){const t={};for(const r of e)t[r]=!0;return t}Z.toHash=DS;function RS(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Kh(e,t),!Gh(t,e.self.RULES.all))}Z.alwaysValidSchema=RS;function Kh(e,t=e.schema){const{opts:r,self:i}=e;if(!r.strictSchema||typeof t=="boolean")return;const n=i.RULES.keywords;for(const o in t)n[o]||eg(e,`unknown keyword: "${o}"`)}Z.checkUnknownRules=Kh;function Gh(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(t[r])return!0;return!1}Z.schemaHasRules=Gh;function US(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=US;function AS({topSchemaRef:e,schemaPath:t},r,i,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)(i)}`}Z.schemaRefOrVal=AS;function CS(e){return Wh(decodeURIComponent(e))}Z.unescapeFragment=CS;function ZS(e){return encodeURIComponent(rc(e))}Z.escapeFragment=ZS;function rc(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=rc;function Wh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=Wh;function MS(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)}Z.eachItem=MS;function Xh({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,o,a,s)=>{const c=a===void 0?o:a instanceof Se.Name?(o instanceof Se.Name?e(n,o,a):t(n,o,a),a):o instanceof Se.Name?(t(n,a,o),o):r(o,a);return s===Se.Name&&!(c instanceof Se.Name)?i(n,c):c}}Z.mergeEvaluated={props:Xh({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:Yh}),items:Xh({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 Yh(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}Z.evaluatedPropsToName=Yh;function ic(e,t,r){Object.keys(r).forEach(i=>e.assign((0,Se._)`${t}${(0,Se.getProperty)(i)}`,!0))}Z.setEvaluated=ic;const Qh={};function FS(e,t){return e.scopeValue("func",{ref:t,code:Qh[t.code]||(Qh[t.code]=new NS._Code(t.code))})}Z.useFunc=FS;var oc;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(oc||(Z.Type=oc={}));function LS(e,t,r){if(e instanceof Se.Name){const i=t===oc.Num;return r?i?(0,Se._)`"[" + ${e} + "]"`:(0,Se._)`"['" + ${e} + "']"`:i?(0,Se._)`"/" + ${e}`:(0,Se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Se.getProperty)(e).toString():"/"+rc(e)}Z.getErrorPath=LS;function eg(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=eg;var Li={},tg;function Rt(){if(tg)return Li;tg=1,Object.defineProperty(Li,"__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 Li.default=t,Li}var ng;function qi(){return ng||(ng=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,i=Rt();e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:v})=>v?(0,t.str)`"${y}" keyword must be ${v} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function n(y,v=e.keywordError,_,w){const{it:z}=y,{gen:O,compositeRule:q,allErrors:Y}=z,de=d(y,v,_);w??(q||Y)?c(O,de):u(z,(0,t._)`[${de}]`)}e.reportError=n;function o(y,v=e.keywordError,_){const{it:w}=y,{gen:z,compositeRule:O,allErrors:q}=w,Y=d(y,v,_);c(z,Y),O||q||u(w,i.default.vErrors)}e.reportExtraError=o;function a(y,v){y.assign(i.default.errors,v),y.if((0,t._)`${i.default.vErrors} !== null`,()=>y.if(v,()=>y.assign((0,t._)`${i.default.vErrors}.length`,v),()=>y.assign(i.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:y,keyword:v,schemaValue:_,data:w,errsCount:z,it:O}){if(z===void 0)throw new Error("ajv implementation error");const q=y.name("err");y.forRange("i",z,i.default.errors,Y=>{y.const(q,(0,t._)`${i.default.vErrors}[${Y}]`),y.if((0,t._)`${q}.instancePath === undefined`,()=>y.assign((0,t._)`${q}.instancePath`,(0,t.strConcat)(i.default.instancePath,O.errorPath))),y.assign((0,t._)`${q}.schemaPath`,(0,t.str)`${O.errSchemaPath}/${v}`),O.opts.verbose&&(y.assign((0,t._)`${q}.schema`,_),y.assign((0,t._)`${q}.data`,w))})}e.extendErrors=s;function c(y,v){const _=y.const("err",v);y.if((0,t._)`${i.default.vErrors} === null`,()=>y.assign(i.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${i.default.vErrors}.push(${_})`),y.code((0,t._)`${i.default.errors}++`)}function u(y,v){const{gen:_,validateName:w,schemaEnv:z}=y;z.$async?_.throw((0,t._)`new ${y.ValidationError}(${v})`):(_.assign((0,t._)`${w}.errors`,v),_.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(y,v,_){const{createErrors:w}=y.it;return w===!1?(0,t._)`{}`:m(y,v,_)}function m(y,v,_={}){const{gen:w,it:z}=y,O=[f(z,_),h(y,_)];return $(y,v,O),w.object(...O)}function f({errorPath:y},{instancePath:v}){const _=v?(0,t.str)`${y}${(0,r.getErrorPath)(v,r.Type.Str)}`:y;return[i.default.instancePath,(0,t.strConcat)(i.default.instancePath,_)]}function h({keyword:y,it:{errSchemaPath:v}},{schemaPath:_,parentSchema:w}){let z=w?v:(0,t.str)`${v}/${y}`;return _&&(z=(0,t.str)`${z}${(0,r.getErrorPath)(_,r.Type.Str)}`),[l.schemaPath,z]}function $(y,{params:v,message:_},w){const{keyword:z,data:O,schemaValue:q,it:Y}=y,{opts:de,propertyName:we,topSchemaRef:Pe,schemaPath:M}=Y;w.push([l.keyword,z],[l.params,typeof v=="function"?v(y):v||(0,t._)`{}`]),de.messages&&w.push([l.message,typeof _=="function"?_(y):_]),de.verbose&&w.push([l.schema,q],[l.parentSchema,(0,t._)`${Pe}${M}`],[i.default.data,O]),we&&w.push([l.propertyName,we])}})(tc)),tc}var rg;function qS(){if(rg)return Kt;rg=1,Object.defineProperty(Kt,"__esModule",{value:!0}),Kt.boolOrEmptySchema=Kt.topBoolOrEmptySchema=void 0;const e=qi(),t=se,r=Rt(),i={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 o(s,c){const{gen:u,schema:l}=s;l===!1?(u.var(c,!1),a(s)):u.var(c,!0)}Kt.boolOrEmptySchema=o;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,i,void 0,c)}return Kt}var je={},Gt={};Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.getRules=Gt.isJSONType=void 0;const BS=["string","number","integer","boolean","null","object","array"],VS=new Set(BS);function JS(e){return typeof e=="string"&&VS.has(e)}Gt.isJSONType=JS;function HS(){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=HS;var zt={},ig;function og(){if(ig)return zt;ig=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.shouldUseRule=zt.shouldUseGroup=zt.schemaHasRulesForType=void 0;function e({schema:i,self:n},o){const a=n.RULES.types[o];return a&&a!==!0&&t(i,a)}zt.schemaHasRulesForType=e;function t(i,n){return n.rules.some(o=>r(i,o))}zt.shouldUseGroup=t;function r(i,n){var o;return i[n.keyword]!==void 0||((o=n.definition.implements)===null||o===void 0?void 0:o.some(a=>i[a]!==void 0))}return zt.shouldUseRule=r,zt}Object.defineProperty(je,"__esModule",{value:!0}),je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;const KS=Gt,GS=og(),WS=qi(),ie=se,ag=Z;var _n;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(_n||(je.DataType=_n={}));function XS(e){const t=sg(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}je.getSchemaTypes=XS;function sg(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(KS.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}je.getJSONTypes=sg;function YS(e,t){const{gen:r,data:i,opts:n}=e,o=QS(t,n.coerceTypes),a=t.length>0&&!(o.length===0&&t.length===1&&(0,GS.schemaHasRulesForType)(e,t[0]));if(a){const s=sc(t,i,n.strictNumbers,_n.Wrong);r.if(s,()=>{o.length?ew(e,t,o):cc(e)})}return a}je.coerceAndCheckDataType=YS;const cg=new Set(["string","number","integer","boolean","null"]);function QS(e,t){return t?e.filter(r=>cg.has(r)||t==="array"&&r==="array"):[]}function ew(e,t,r){const{gen:i,data:n,opts:o}=e,a=i.let("dataType",(0,ie._)`typeof ${n}`),s=i.let("coerced",(0,ie._)`undefined`);o.coerceTypes==="array"&&i.if((0,ie._)`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,(0,ie._)`${n}[0]`).assign(a,(0,ie._)`typeof ${n}`).if(sc(t,n,o.strictNumbers),()=>i.assign(s,n))),i.if((0,ie._)`${s} !== undefined`);for(const u of r)(cg.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);i.else(),cc(e),i.endIf(),i.if((0,ie._)`${s} !== undefined`,()=>{i.assign(n,s),tw(e,s)});function c(u){switch(u){case"string":i.elseIf((0,ie._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,ie._)`"" + ${n}`).elseIf((0,ie._)`${n} === null`).assign(s,(0,ie._)`""`);return;case"number":i.elseIf((0,ie._)`${a} == "boolean" || ${n} === null
|
|
72
72
|
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(s,(0,ie._)`+${n}`);return;case"integer":i.elseIf((0,ie._)`${a} === "boolean" || ${n} === null
|
|
73
73
|
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(s,(0,ie._)`+${n}`);return;case"boolean":i.elseIf((0,ie._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(s,!1).elseIf((0,ie._)`${n} === "true" || ${n} === 1`).assign(s,!0);return;case"null":i.elseIf((0,ie._)`${n} === "" || ${n} === 0 || ${n} === false`),i.assign(s,null);return;case"array":i.elseIf((0,ie._)`${a} === "string" || ${a} === "number"
|