@ably/ai-transport 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +10 -19
  2. package/dist/ably-ai-transport.js +1790 -1091
  3. package/dist/ably-ai-transport.js.map +1 -1
  4. package/dist/ably-ai-transport.umd.cjs +1 -1
  5. package/dist/ably-ai-transport.umd.cjs.map +1 -1
  6. package/dist/constants.d.ts +2 -2
  7. package/dist/core/agent.d.ts +20 -5
  8. package/dist/core/channel-options.d.ts +57 -0
  9. package/dist/core/codec/codec-event.d.ts +9 -0
  10. package/dist/core/codec/decoder.d.ts +4 -1
  11. package/dist/core/codec/define-codec.d.ts +100 -0
  12. package/dist/core/codec/encoder.d.ts +2 -7
  13. package/dist/core/codec/field-bag.d.ts +85 -0
  14. package/dist/core/codec/fields.d.ts +141 -0
  15. package/dist/core/codec/index.d.ts +8 -1
  16. package/dist/core/codec/input-descriptor-decoder.d.ts +19 -0
  17. package/dist/core/codec/input-descriptor-encoder.d.ts +22 -0
  18. package/dist/core/codec/input-descriptors.d.ts +281 -0
  19. package/dist/core/codec/output-descriptor-decoder.d.ts +29 -0
  20. package/dist/core/codec/output-descriptor-encoder.d.ts +31 -0
  21. package/dist/core/codec/output-descriptors.d.ts +237 -0
  22. package/dist/core/codec/types.d.ts +95 -36
  23. package/dist/core/codec/well-known-inputs.d.ts +52 -0
  24. package/dist/core/transport/agent-view.d.ts +296 -0
  25. package/dist/core/transport/decode-fold.d.ts +40 -32
  26. package/dist/core/transport/headers.d.ts +30 -1
  27. package/dist/core/transport/index.d.ts +1 -1
  28. package/dist/core/transport/invocation.d.ts +1 -1
  29. package/dist/core/transport/load-history-pages.d.ts +71 -0
  30. package/dist/core/transport/load-history.d.ts +21 -16
  31. package/dist/core/transport/run-manager.d.ts +9 -11
  32. package/dist/core/transport/session-support.d.ts +55 -0
  33. package/dist/core/transport/tree.d.ts +165 -15
  34. package/dist/core/transport/types/agent.d.ts +120 -98
  35. package/dist/core/transport/types/client.d.ts +45 -12
  36. package/dist/core/transport/types/tree.d.ts +52 -10
  37. package/dist/core/transport/types/view.d.ts +55 -28
  38. package/dist/core/transport/view.d.ts +176 -58
  39. package/dist/core/transport/wire-log.d.ts +102 -0
  40. package/dist/errors.d.ts +10 -4
  41. package/dist/index.d.ts +6 -5
  42. package/dist/react/ably-ai-transport-react.js +784 -415
  43. package/dist/react/ably-ai-transport-react.js.map +1 -1
  44. package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
  45. package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
  46. package/dist/react/contexts/client-session-context.d.ts +2 -1
  47. package/dist/react/contexts/client-session-provider.d.ts +3 -0
  48. package/dist/react/index.d.ts +2 -1
  49. package/dist/react/internal/skipped-session.d.ts +8 -0
  50. package/dist/react/use-view.d.ts +3 -3
  51. package/dist/utils.d.ts +22 -54
  52. package/dist/vercel/ably-ai-transport-vercel.js +2297 -2026
  53. package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
  54. package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
  55. package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
  56. package/dist/vercel/codec/decode-lifecycle.d.ts +9 -0
  57. package/dist/vercel/codec/events.d.ts +1 -2
  58. package/dist/vercel/codec/fields.d.ts +44 -0
  59. package/dist/vercel/codec/fold-content.d.ts +16 -0
  60. package/dist/vercel/codec/fold-data.d.ts +16 -0
  61. package/dist/vercel/codec/fold-input.d.ts +67 -0
  62. package/dist/vercel/codec/fold-lifecycle.d.ts +16 -0
  63. package/dist/vercel/codec/fold-text.d.ts +16 -0
  64. package/dist/vercel/codec/fold-tool-input.d.ts +17 -0
  65. package/dist/vercel/codec/fold-tool-output.d.ts +16 -0
  66. package/dist/vercel/codec/index.d.ts +5 -30
  67. package/dist/vercel/codec/inputs.d.ts +11 -0
  68. package/dist/vercel/codec/outputs.d.ts +11 -0
  69. package/dist/vercel/codec/reducer-state.d.ts +121 -0
  70. package/dist/vercel/codec/reducer.d.ts +20 -102
  71. package/dist/vercel/codec/tool-transitions.d.ts +0 -6
  72. package/dist/vercel/codec/wire-data.d.ts +34 -0
  73. package/dist/vercel/index.d.ts +1 -0
  74. package/dist/vercel/react/ably-ai-transport-vercel-react.js +2013 -9500
  75. package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
  76. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +1 -70
  77. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
  78. package/dist/vercel/react/contexts/chat-transport-context.d.ts +2 -1
  79. package/dist/vercel/run-end-reason.d.ts +66 -11
  80. package/dist/vercel/tool-part.d.ts +21 -0
  81. package/dist/vercel/transport/chat-transport.d.ts +0 -2
  82. package/dist/vercel/transport/index.d.ts +1 -1
  83. package/dist/vercel/transport/run-output-stream.d.ts +6 -8
  84. package/dist/version.d.ts +1 -1
  85. package/package.json +2 -2
  86. package/src/constants.ts +2 -2
  87. package/src/core/agent.ts +43 -19
  88. package/src/core/channel-options.ts +89 -0
  89. package/src/core/codec/codec-event.ts +27 -0
  90. package/src/core/codec/decoder.ts +145 -21
  91. package/src/core/codec/define-codec.ts +432 -0
  92. package/src/core/codec/encoder.ts +13 -54
  93. package/src/core/codec/field-bag.ts +142 -0
  94. package/src/core/codec/fields.ts +193 -0
  95. package/src/core/codec/index.ts +43 -0
  96. package/src/core/codec/input-descriptor-decoder.ts +97 -0
  97. package/src/core/codec/input-descriptor-encoder.ts +150 -0
  98. package/src/core/codec/input-descriptors.ts +373 -0
  99. package/src/core/codec/output-descriptor-decoder.ts +139 -0
  100. package/src/core/codec/output-descriptor-encoder.ts +101 -0
  101. package/src/core/codec/output-descriptors.ts +307 -0
  102. package/src/core/codec/types.ts +99 -36
  103. package/src/core/codec/well-known-inputs.ts +96 -0
  104. package/src/core/transport/agent-session.ts +330 -589
  105. package/src/core/transport/agent-view.ts +738 -0
  106. package/src/core/transport/client-session.ts +74 -69
  107. package/src/core/transport/decode-fold.ts +57 -47
  108. package/src/core/transport/headers.ts +57 -4
  109. package/src/core/transport/index.ts +2 -1
  110. package/src/core/transport/invocation.ts +1 -1
  111. package/src/core/transport/load-history-pages.ts +220 -0
  112. package/src/core/transport/load-history.ts +63 -61
  113. package/src/core/transport/pipe-stream.ts +10 -1
  114. package/src/core/transport/run-manager.ts +25 -31
  115. package/src/core/transport/session-support.ts +96 -0
  116. package/src/core/transport/tree.ts +414 -47
  117. package/src/core/transport/types/agent.ts +129 -102
  118. package/src/core/transport/types/client.ts +49 -13
  119. package/src/core/transport/types/tree.ts +61 -12
  120. package/src/core/transport/types/view.ts +57 -28
  121. package/src/core/transport/view.ts +520 -172
  122. package/src/core/transport/wire-log.ts +189 -0
  123. package/src/errors.ts +10 -3
  124. package/src/index.ts +44 -11
  125. package/src/react/contexts/client-session-context.ts +1 -1
  126. package/src/react/contexts/client-session-provider.tsx +38 -2
  127. package/src/react/index.ts +2 -1
  128. package/src/react/internal/skipped-session.ts +62 -0
  129. package/src/react/use-client-session.ts +7 -30
  130. package/src/react/use-view.ts +3 -3
  131. package/src/utils.ts +31 -97
  132. package/src/vercel/codec/decode-lifecycle.ts +70 -0
  133. package/src/vercel/codec/events.ts +1 -3
  134. package/src/vercel/codec/fields.ts +58 -0
  135. package/src/vercel/codec/fold-content.ts +54 -0
  136. package/src/vercel/codec/fold-data.ts +46 -0
  137. package/src/vercel/codec/fold-input.ts +255 -0
  138. package/src/vercel/codec/fold-lifecycle.ts +85 -0
  139. package/src/vercel/codec/fold-text.ts +55 -0
  140. package/src/vercel/codec/fold-tool-input.ts +86 -0
  141. package/src/vercel/codec/fold-tool-output.ts +79 -0
  142. package/src/vercel/codec/index.ts +23 -63
  143. package/src/vercel/codec/inputs.ts +116 -0
  144. package/src/vercel/codec/outputs.ts +207 -0
  145. package/src/vercel/codec/reducer-state.ts +169 -0
  146. package/src/vercel/codec/reducer.ts +52 -838
  147. package/src/vercel/codec/tool-transitions.ts +1 -12
  148. package/src/vercel/codec/wire-data.ts +64 -0
  149. package/src/vercel/index.ts +1 -0
  150. package/src/vercel/react/contexts/chat-transport-context.ts +1 -1
  151. package/src/vercel/react/use-chat-transport.ts +8 -28
  152. package/src/vercel/react/use-message-sync.ts +5 -10
  153. package/src/vercel/run-end-reason.ts +95 -16
  154. package/src/vercel/tool-part.ts +25 -0
  155. package/src/vercel/transport/chat-transport.ts +10 -22
  156. package/src/vercel/transport/index.ts +1 -1
  157. package/src/vercel/transport/run-output-stream.ts +7 -8
  158. package/src/version.ts +1 -1
  159. package/dist/core/transport/branch-chain.d.ts +0 -43
  160. package/dist/core/transport/load-conversation.d.ts +0 -128
  161. package/dist/vercel/codec/decoder.d.ts +0 -9
  162. package/dist/vercel/codec/encoder.d.ts +0 -11
  163. package/src/core/transport/branch-chain.ts +0 -58
  164. package/src/core/transport/load-conversation.ts +0 -355
  165. package/src/vercel/codec/decoder.ts +0 -696
  166. package/src/vercel/codec/encoder.ts +0 -548
@@ -1,71 +1,2 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`react`),require(`ably`),require(`ably/react`),require(`react/jsx-runtime`)):typeof define==`function`&&define.amd?define([`exports`,`react`,`ably`,`ably/react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.AblyAiTransportVercelReact={},e.React,e.Ably,e.AblyReact,e.ReactJsxRuntime))})(this,function(e,t,n,r,i){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var a=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,c=Object.getOwnPropertyNames,l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=c(t),a=0,l=i.length,d;a<l;a++)d=i[a],!u.call(e,d)&&d!==n&&o(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=s(t,d))||r.enumerable});return e};n=((e,t,n)=>(n=e==null?{}:a(l(e)),d(t||!e||!e.__esModule?o(n,`default`,{value:e,enumerable:!0}):n,e)))(n,1);var f=`stream`,p=`status`,ee=`stream-id`,m=`discrete`,h=`run-id`,te=`invocation-id`,ne=`event-id`,g=`codec-message-id`,re=`run-client-id`,ie=`input-client-id`,ae=`role`,oe=`parent`,se=`fork-of`,ce=`msg-regenerate`,le=`input-codec-message-id`,ue=`error-code`,de=`ai-cancel`,_=`ai-output`,fe=`ai-input`,v=function(e){return e[e.BadRequest=4e4]=`BadRequest`,e[e.InvalidArgument=40003]=`InvalidArgument`,e[e.InsufficientCapability=40160]=`InsufficientCapability`,e[e.EncoderRecoveryFailed=104e3]=`EncoderRecoveryFailed`,e[e.SessionSubscriptionError=104001]=`SessionSubscriptionError`,e[e.CancelListenerError=104002]=`CancelListenerError`,e[e.RunLifecycleError=104003]=`RunLifecycleError`,e[e.SessionClosed=104004]=`SessionClosed`,e[e.SessionSendFailed=104005]=`SessionSendFailed`,e[e.ChannelContinuityLost=104006]=`ChannelContinuityLost`,e[e.ChannelNotReady=104007]=`ChannelNotReady`,e[e.StreamError=104008]=`StreamError`,e[e.InputEventNotFound=104010]=`InputEventNotFound`,e}({}),pe=(e,t)=>e.code===t,me=e=>({logAction:(t,n,r)=>{e.error(n,{detail:r})},shouldLog:()=>!0}),he=n.Realtime.EventEmitter,ge=class extends he{constructor(e){super(me(e))}},_e=function(e){return e.Trace=`trace`,e.Debug=`debug`,e.Info=`info`,e.Warn=`warn`,e.Error=`error`,e.Silent=`silent`,e}({}),ve=(e,t,n)=>{let r=n?`, context: ${JSON.stringify(n)}`:``,i=`[${new Date().toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;switch(t){case`trace`:case`debug`:console.log(i);break;case`info`:console.info(i);break;case`warn`:console.warn(i);break;case`error`:console.error(i);break;case`silent`:break}},ye=e=>new xe(e.logHandler??ve,e.logLevel),be=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4],[`silent`,5]]),xe=class e{constructor(e,t,r){this._handler=e,this._context=r;let i=be.get(t);if(i===void 0)throw new n.ErrorInfo(`unable to create logger; invalid log level: ${t}`,v.InvalidArgument,400);this._levelNumber=i}trace(e,t){this._write(e,`trace`,0,t)}debug(e,t){this._write(e,`debug`,1,t)}info(e,t){this._write(e,`info`,2,t)}warn(e,t){this._write(e,`warn`,3,t)}error(e,t){this._write(e,`error`,4,t)}withContext(t){let n=[...be.entries()].find(([,e])=>e===this._levelNumber)?.[0]??`error`;return new e(this._handler,n,this._mergeContext(t))}_write(e,t,n,r){n>=this._levelNumber&&this._handler(e,t,this._mergeContext(r))}_mergeContext(e){return this._context?e?{...this._context,...e}:this._context:e??void 0}},Se=(e,t)=>{let n=e.extras;if(!n||typeof n!=`object`)return{};let r=n.ai;if(!r||typeof r!=`object`)return{};let i=r[t];return!i||typeof i!=`object`?{}:i},Ce=e=>Se(e,`transport`),we=e=>Se(e,`codec`),Te=e=>{if(e!==void 0)try{return JSON.parse(e)}catch{return}},Ee=(e,t)=>({...e,...t}),De=e=>{if(e!==void 0)return e===`true`},Oe=(e,t)=>e[t],y=e=>{let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==void 0&&(t[n]=e[n]);return t},ke=e=>({str:t=>Oe(e,t),strOr:(t,n)=>Oe(e,t)??n,bool:t=>De(Oe(e,t)),json:t=>Te(Oe(e,t))}),b=()=>{let e={},t={str:(n,r)=>(r!==void 0&&(e[n]=r),t),bool:(n,r)=>(r!==void 0&&(e[n]=String(r)),t),json:(n,r)=>(r!=null&&(e[n]=JSON.stringify(r)),t),build:()=>e};return t},Ae=`0.2.0`,je=`ai-transport-js`,Me=(e,t)=>{let n=e;return n.options.agents={...n.options.agents,...t},{params:{agent:Object.entries(t).map(([e,t])=>`${e}/${t}`).join(` `)}}},Ne=(e,t)=>{let n=t?.adapterTag,r={[je]:Ae};return n&&(r[n]=Ae),Me(e,r)},Pe=e=>{let t={[ae]:e.role,[g]:e.codecMessageId};return e.runId!==void 0&&(t[h]=e.runId),e.runClientId!==void 0&&(t[re]=e.runClientId),e.parent&&(t[oe]=e.parent),e.forkOf&&(t[se]=e.forkOf),e.regenerates&&(t[ce]=e.regenerates),e.invocationId&&(t[te]=e.invocationId),e.inputClientId!==void 0&&(t[ie]=e.inputClientId),e.inputCodecMessageId!==void 0&&(t[le]=e.inputCodecMessageId),e.inputEventId&&(t[ne]=e.inputEventId),t},Fe=e=>e===`ai-run-start`||e===`ai-run-suspend`||e===`ai-run-resume`||e===`ai-run-end`,Ie=(e,t,n)=>{let r=t[h];if(!r)return;let i=t[`run-client-id`]??``;if(e===`ai-run-start`){let e=t[oe],a=t[se],o=t[ce];return{type:`start`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``,...e!==void 0&&{parent:e},...a!==void 0&&{forkOf:a},...o!==void 0&&{regenerates:o}}}if(e===`ai-run-suspend`)return{type:`suspend`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``};if(e===`ai-run-resume`)return{type:`resume`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``};if(e===`ai-run-end`){let e=t[`run-reason`]??`complete`;return{type:`end`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``,reason:e}}},Le=(e,t,n)=>{let r=Ce(n),i=n.serial;if(Fe(n.name)){let t=Ie(n.name,r,i);return t&&e.applyRunLifecycle(t),t}let{inputs:a,outputs:o}=t.decode(n);(a.length>0||o.length>0||r[`run-id`])&&e.applyMessage({inputs:a,outputs:o},r,i)},Re=class e{constructor(e){this.inputEventId=e.inputEventId,this.sessionName=e.sessionName}static fromJSON(t){return new e(t)}toJSON(){return{inputEventId:this.inputEventId,sessionName:this.sessionName}}},x=e=>e.kind===`run`?e.runId:e.codecMessageId,ze=e=>e.kind===`run`?e.startSerial:e.serial,Be=(e,t,n)=>{let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)},Ve=(e,t,n)=>{let r=e.get(t);r&&(r.delete(n),r.size===0&&e.delete(t))},He=class{constructor(e,t){this._nodeIndex=new Map,this._codecMessageIdToNodeKey=new Map,this._sortedNodes=[],this._parentIndex=new Map,this._replyRunsByInput=new Map,this._seqCounter=0,this._structuralVersion=0,this._siblingCache=new Map,this._siblingCacheVersion=-1,this._codec=e,this._logger=t,this._emitter=new ge(t)}_compareNodes(e,t){let n=ze(e.node),r=ze(t.node);return n===void 0&&r===void 0?e.insertSeq-t.insertSeq:n===void 0?1:r===void 0||n<r?-1:n>r?1:e.insertSeq-t.insertSeq}_insertSortedNode(e){if(ze(e.node)===void 0){this._sortedNodes.push(e);return}let t=0,n=this._sortedNodes.length;for(;t<n;){let r=t+n>>>1,i=this._sortedNodes[r];if(!i)break;this._compareNodes(i,e)<=0?t=r+1:n=r}this._sortedNodes.splice(t,0,e)}_removeSortedNode(e){let t=this._sortedNodes.indexOf(e);t!==-1&&this._sortedNodes.splice(t,1)}_insertNode(e,t,n){this._nodeIndex.set(e,t),this._addToParentIndex(n,e),this._insertSortedNode(t),this._structuralVersion++}_promoteSerial(e){this._removeSortedNode(e),this._insertSortedNode(e),this._structuralVersion++}_foldInto(e,t,n,r){for(let i of t)try{e.node.projection=this._codec.fold(e.node.projection,i,{serial:n??``,messageId:r})}catch(t){this._logger.error(`Tree._foldInto(); fold threw`,{key:x(e.node),messageId:r,err:t})}}_addToParentIndex(e,t){Be(this._parentIndex,e,t)}_removeFromParentIndex(e,t){Ve(this._parentIndex,e,t)}_parentKeyOf(e){let t=e.parentCodecMessageId;return t===void 0?void 0:this._codecMessageIdToNodeKey.get(t)}_inputGroupRoot(e){let t=e,n=new Set([x(t)]);for(;t.forkOf!==void 0&&!n.has(t.forkOf);){let e=this._nodeIndex.get(t.forkOf);if(e?.node.kind!==`input`||e.node.parentCodecMessageId!==t.parentCodecMessageId)break;t=e.node,n.add(x(t))}return t}_getSiblingGroup(e){this._siblingCacheVersion!==this._structuralVersion&&(this._siblingCache.clear(),this._siblingCacheVersion=this._structuralVersion);let t=this._siblingCache.get(e);if(t)return t;let n=this._nodeIndex.get(e);if(!n)return[];let r=n.node;r.kind===`input`&&(r=this._inputGroupRoot(r));let i=r.parentCodecMessageId,a=[],o=this._parentIndex.get(i);if(o)for(let e of o){let t=this._nodeIndex.get(e);t&&this._isSiblingOf(t.node,r)&&a.push(t)}a.sort((e,t)=>this._compareNodes(e,t));for(let e of a)this._siblingCache.set(x(e.node),a);return this._siblingCache.set(e,a),a}_isSiblingOf(e,t){if(e.kind!==t.kind||e.parentCodecMessageId!==t.parentCodecMessageId)return!1;if(e.kind===`run`)return!0;let n=x(t);if(x(e)===n)return!0;let r=e,i=new Set([x(r)]);for(;r.kind===`input`&&r.forkOf!==void 0;){if(r.forkOf===n)return!0;if(i.has(r.forkOf))break;let e=this._nodeIndex.get(r.forkOf);if(!e)break;r=e.node,i.add(x(r))}return!1}getGroupRoot(e){let t=this._nodeIndex.get(e);if(!t)return e;if(t.node.kind===`input`)return x(this._inputGroupRoot(t.node));let n=this._getSiblingGroup(e)[0]?.node;return n?x(n):e}visibleNodes(e=new Map){this._logger.trace(`DefaultTree.visibleNodes();`);let t=[],n=new Set,r=new Map;for(let i of this._sortedNodes){let a=i.node,o=x(a),s=this._parentKeyOf(a);if(s!==void 0&&!n.has(s))continue;let c=this._getSiblingGroup(o);if(c.length>1){let t=this.getGroupRoot(o),n=r.get(t);if(n===void 0){let i=e.get(t);if(i!==void 0&&c.some(e=>x(e.node)===i))n=i;else{let e=c.at(-1);if(!e)break;n=x(e.node)}r.set(t,n)}if(o!==n)continue}n.add(o),t.push(a)}return t}getRunNode(e){this._logger.trace(`DefaultTree.getRunNode();`,{runId:e});let t=this._nodeIndex.get(e)?.node;return t?.kind===`run`?t:void 0}getNode(e){return this._logger.trace(`DefaultTree.getNode();`,{key:e}),this._nodeIndex.get(e)?.node}getNodeByCodecMessageId(e){this._logger.trace(`DefaultTree.getNodeByCodecMessageId();`,{codecMessageId:e});let t=this._codecMessageIdToNodeKey.get(e);return t===void 0?void 0:this._nodeIndex.get(t)?.node}getReplyRuns(e){let t=this._replyRunsByInput.get(e);if(!t)return[];let n=[];for(let e of t){let t=this._nodeIndex.get(e)?.node;t?.kind===`run`&&n.push(t)}return n}getSiblingNodes(e){return this._logger.trace(`DefaultTree.getSiblingNodes();`,{key:e}),this._getSiblingGroup(e).map(e=>e.node)}applyMessage(e,t,n){let r=t[h],i=t[g],a=r===void 0&&i!==void 0&&t.role===`user`&&e.inputs.length>0?i:void 0;if(r===void 0&&a===void 0){this._logger.warn(`Tree.applyMessage(); message has no run-id and is not a user input; skipping`);return}let o=[...e.inputs,...e.outputs],s=a??r;if(o.length===0&&s!==void 0&&!this._nodeIndex.has(s))return;let c=this._structuralVersion;a===void 0?r!==void 0&&this._applyRunMessage(r,e,t,n):this._applyInputMessage(a,t,n,o),this._structuralVersion!==c&&this._emitter.emit(`update`)}_applyInputMessage(e,t,n,r){let i=this._nodeIndex.get(e);i?i.node.kind===`input`&&n&&!i.node.serial&&(this._logger.debug(`Tree.applyMessage(); promoting input serial`,{codecMessageId:e,serial:n}),i.node.serial=n,this._promoteSerial(i)):(i=this._createInputNodeFromHeaders(e,t,n),this._insertNode(e,i,i.node.parentCodecMessageId),this._codecMessageIdToNodeKey.set(e,e),this._logger.debug(`Tree.applyMessage(); created input node`,{codecMessageId:e})),this._foldInto(i,r,n,e),this._emitter.emit(`output`,{runId:void 0,inputCodecMessageId:e,codecMessageId:e,serial:n,events:[]})}_applyRunMessage(e,t,n,r){let i=n[g],a=n[le],o=[...t.inputs,...t.outputs],s=t.outputs,c=this._nodeIndex.get(e);if(!c&&i!==void 0){let e=this._codecMessageIdToNodeKey.get(i),t=e===void 0?void 0:this._nodeIndex.get(e);t?.node.kind===`run`&&t.node.startSerial===void 0&&(c=t)}c?r&&c.node.kind===`run`&&!c.node.startSerial&&(this._logger.debug(`Tree.applyMessage(); promoting startSerial`,{runId:e,serial:r}),c.node.startSerial=r,this._promoteSerial(c)):(c=this._createRunFromHeaders(e,n,r),this._insertNode(e,c,c.node.parentCodecMessageId),this._indexReplyRun(c.node,e),this._logger.debug(`Tree.applyMessage(); created new Run`,{runId:e}));let l=x(c.node);i&&this._codecMessageIdToNodeKey.set(i,l),this._foldInto(c,o,r,i),this._emitter.emit(`output`,{runId:l,inputCodecMessageId:a,codecMessageId:i,serial:r,events:s})}_indexReplyRun(e,t){e.parentCodecMessageId!==void 0&&Be(this._replyRunsByInput,e.parentCodecMessageId,t)}applyRunLifecycle(e){this._logger.trace(`DefaultTree.applyRunLifecycle();`,{type:e.type,runId:e.runId});let t=this._structuralVersion;switch(e.type){case`start`:this._applyRunStart(e);break;case`suspend`:this._applyRunSuspend(e);break;case`resume`:this._applyRunResume(e);break;case`end`:this._applyRunEnd(e);break}this._emitter.emit(`run`,e),this._structuralVersion!==t&&this._emitter.emit(`update`)}_applyRunStart(e){let t=this._nodeIndex.get(e.runId);if(t?.node.kind===`run`){let n=t.node;if(n.status!==`active`&&(n.status=`active`),e.serial&&!n.startSerial&&(n.startSerial=e.serial,this._promoteSerial(t)),n.parentCodecMessageId===void 0&&e.parent!==void 0&&(n.parentCodecMessageId=e.parent,this._removeFromParentIndex(void 0,e.runId),this._addToParentIndex(n.parentCodecMessageId,e.runId),this._indexReplyRun(n,e.runId),this._structuralVersion++),n.forkOf===void 0&&e.forkOf!==void 0){let t=this._codecMessageIdToNodeKey.get(e.forkOf);t!==void 0&&t!==e.runId&&(n.forkOf=t,this._structuralVersion++)}n.regeneratesCodecMessageId===void 0&&e.regenerates!==void 0&&(n.regeneratesCodecMessageId=e.regenerates,this._structuralVersion++),n.invocationId===``&&e.invocationId!==``&&(n.invocationId=e.invocationId)}else if(!t){let t=this._createRunFromLifecycle(e);this._insertNode(e.runId,t,t.node.parentCodecMessageId),this._indexReplyRun(t.node,e.runId)}}_applyRunSuspend(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.status=`suspended`,t.node.endSerial=e.serial)}_applyRunResume(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&t.node.status===`suspended`&&(t.node.status=`active`)}_applyRunEnd(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.status=e.reason,t.node.endSerial=e.serial)}delete(e){let t=this._nodeIndex.get(e);t&&(this._logger.debug(`Tree.delete();`,{key:e}),this._removeFromParentIndex(t.node.parentCodecMessageId,e),this._removeSortedNode(t),this._nodeIndex.delete(e),t.node.kind===`run`&&t.node.parentCodecMessageId!==void 0&&Ve(this._replyRunsByInput,t.node.parentCodecMessageId,e),this._structuralVersion++,this._emitter.emit(`update`))}_createRunFromHeaders(e,t,n){let r=t[se];return this._buildRunNode({runId:e,parentCodecMessageId:t[oe],forkOf:r?this._codecMessageIdToNodeKey.get(r):void 0,regeneratesCodecMessageId:t[ce],clientId:t[`run-client-id`]??``,invocationId:t[`invocation-id`]??``,startSerial:n})}_buildRunNode(e){return{node:{kind:`run`,runId:e.runId,parentCodecMessageId:e.parentCodecMessageId,forkOf:e.forkOf,regeneratesCodecMessageId:e.regeneratesCodecMessageId,clientId:e.clientId,invocationId:e.invocationId,status:`active`,projection:this._codec.init(),startSerial:e.startSerial,endSerial:void 0},insertSeq:this._seqCounter++}}_createInputNodeFromHeaders(e,t,n){let r=t[se];return{node:{kind:`input`,codecMessageId:e,parentCodecMessageId:t[oe],forkOf:r,projection:this._codec.init(),serial:n},insertSeq:this._seqCounter++}}_createRunFromLifecycle(e){let t=e.forkOf;return this._buildRunNode({runId:e.runId,parentCodecMessageId:e.parent,forkOf:t?this._codecMessageIdToNodeKey.get(t):void 0,regeneratesCodecMessageId:e.regenerates,clientId:e.clientId,invocationId:e.invocationId,startSerial:e.serial})}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}emitAblyMessage(e){this._logger.trace(`DefaultTree.emitAblyMessage();`),this._emitter.emit(`ably-message`,e)}},Ue=(e,t)=>new He(e,t),We=(e,t)=>{for(let n of t){let t=Ce(n),r=t[g];if(!r)continue;let i=n.action,a=i===`message.create`&&`discrete`in t,o=t.stream===`true`&&(i===`message.create`||i===`message.update`||i===`message.append`),s=t[p],c=s===`complete`||s===`cancelled`;(a||o)&&e.startedCodecMessageIds.add(r),(a||c)&&e.terminatedCodecMessageIds.add(r),e.startedCodecMessageIds.has(r)&&e.terminatedCodecMessageIds.has(r)&&e.completedCodecMessageIds.add(r)}},Ge=async(e,t,n)=>{e.rawMessages.push(...t.items),e.lastAblyPage=t,We(e,t.items);let r=e.returnedCount+n;for(;e.completedCodecMessageIds.size<r&&t.hasNext();){e.logger.debug(`loadHistory.fetchUntilLimit(); fetching next page`,{collected:e.rawMessages.length,completed:e.completedCodecMessageIds.size});let n=await t.next();if(!n)break;t=n,e.rawMessages.push(...n.items),e.lastAblyPage=n,We(e,n.items)}},Ke=(e,t)=>{let n=e.completedCodecMessageIds.size,r=Math.min(t,Math.max(0,n-e.returnedCount));e.returnedCount+=r;let i=n>e.returnedCount,a=e.lastAblyPage?.hasNext()??!1,o=e.rawMessages.length-e.returnedRawCount>0?e.rawMessages.slice(e.returnedRawCount).toReversed():[];return e.returnedRawCount=e.rawMessages.length,{rawMessages:o,hasNext:()=>i||a,next:async()=>{if(i)return Ke(e,t);if(!a||!e.lastAblyPage)return;let n=await e.lastAblyPage.next();if(n)return await Ge(e,n,t),Ke(e,t)}}},qe=async(e,t,n)=>{let r=t?.limit??100,i={rawMessages:[],returnedCount:0,returnedRawCount:0,lastAblyPage:void 0,startedCodecMessageIds:new Set,terminatedCodecMessageIds:new Set,completedCodecMessageIds:new Set,logger:n};n.trace(`loadHistory();`,{limit:r});let a=r*10;return await e.attach(),await Ge(i,await e.history({untilAttach:!0,limit:a}),r),Ke(i,r)},Je=e=>Array.isArray(e)?e:[e],Ye=3,Xe=e=>({runId:e.runId,clientId:e.clientId,status:e.status,invocationId:e.invocationId}),Ze=class{constructor(e){this._branchSelections=new Map,this._regenSelections=new Map,this._withheldRunIds=new Set,this._lastVisibleNodeKeys=[],this._lastVisibleProjections=[],this._lastVisibleMessagePairs=[],this._lastVisibleNodeKeySet=new Set,this._hasMoreHistory=!1,this._withheldBuffer=[],this._unsubs=[],this._cachedNodes=[],this._loadingOlder=!1,this._processingHistory=!1,this._closed=!1,this._tree=e.tree,this._channel=e.channel,this._codec=e.codec,this._sendDelegate=e.sendDelegate,this._onClose=e.onClose,this._logger=e.logger.withContext({component:`View`}),this._logger.trace(`DefaultView();`),this._emitter=new ge(this._logger),this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._unsubs.push(this._tree.on(`update`,()=>{this._onTreeUpdate()}),this._tree.on(`ably-message`,e=>{this._onTreeAblyMessage(e)}),this._tree.on(`run`,e=>{this._onTreeRun(e)}),this._tree.on(`output`,e=>{this._onTreeOutput(e)}))}_onTreeOutput(e){this._processingHistory||(e.runId!==void 0&&this._lastVisibleNodeKeySet.has(e.runId)||e.inputCodecMessageId!==void 0&&this._lastVisibleNodeKeySet.has(e.inputCodecMessageId))&&(this._lastVisibleProjections=this._cachedNodes.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(this._cachedNodes),this._emitter.emit(`update`))}getMessages(){return this._lastVisibleMessagePairs}runs(){return this._cachedNodes.filter(e=>e.kind===`run`).map(e=>Xe(e))}_computeFlatNodes(){let e=this._treeVisibleNodes();return this._withheldRunIds.size===0?e:e.filter(e=>!this._withheldRunIds.has(x(e)))}_recomputeAndEmit(){this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._emitter.emit(`update`)}_recomputeAndEmitIfChanged(){let e=this._computeFlatNodes();this._visibleChanged(e)&&(this._cachedNodes=e,this._updateVisibleSnapshot(e),this._emitter.emit(`update`))}_runByCodecMessageId(e){let t=this._tree.getNodeByCodecMessageId(e);return t?.kind===`run`?t:void 0}_extractMessages(e){let t=[];for(let n of e)for(let e of this._codec.getMessages(n.projection))t.push(e);return t}hasOlder(){return this._withheldBuffer.length>0||this._hasMoreHistory}async loadOlder(e=100){if(!(this._closed||this._loadingOlder)){this._loadingOlder=!0,this._logger.trace(`DefaultView.loadOlder();`,{limit:e});try{if(this._withheldBuffer.length>0){let t=this._withheldBuffer.splice(-e,e);this._releaseWithheld(t);return}if(!this._hasMoreHistory&&!this._lastHistoryPage){await this._loadFirstPage(e);return}if(!this._hasMoreHistory)return;if(!this._lastHistoryPage?.hasNext()){this._hasMoreHistory=!1;return}let t=await this._lastHistoryPage.next();if(this._closed||!t){t||(this._hasMoreHistory=!1);return}await this._revealFromPage(t,e)}catch(e){throw this._logger.error(`DefaultView.loadOlder(); failed`,{error:e}),e}finally{this._loadingOlder=!1}}}runOf(e){this._logger.trace(`DefaultView.runOf();`,{codecMessageId:e});let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`run`)return Xe(t);let n=this._selectedReplyRun(t.codecMessageId);return n?Xe(n):void 0}_selectedReplyRun(e){let t=this._tree.getReplyRuns(e);if(t.length===0)return;if(t.length===1)return t[0];let n=this._tree.getGroupRoot(t[0]?.runId??``),r=this._regenSelections.get(n),i=r&&r.kind!==`pending`?r.selectedRunId:void 0;if(i!==void 0){let e=t.find(e=>e.runId===i);if(e)return e}return t.toSorted((e,t)=>(e.startSerial??`￿`).localeCompare(t.startSerial??`￿`)).at(-1)}run(e){this._logger.trace(`DefaultView.run();`,{runId:e});let t=this._tree.getRunNode(e);return t?Xe(t):void 0}branchSelection(e){let t=this._resolveMessageBranchPoint(e);if(t){let e=t.siblings.flatMap(e=>{let t=this._codec.getMessages(e.projection).at(0);return t?[t.message]:[]});if(e.length>0){let n=this._resolveSelectedIndex(t),r=Math.max(0,Math.min(n,e.length-1)),i=e[r];return{hasSiblings:e.length>1,siblings:e,index:r,selected:i}}}let n=this._tree.getNodeByCodecMessageId(e);if(n){let t=this._codec.getMessages(n.projection).find(t=>t.codecMessageId===e);if(t!==void 0)return{hasSiblings:!1,siblings:[t.message],index:0,selected:t.message}}return{hasSiblings:!1,siblings:[],index:0,selected:void 0}}selectSibling(e,t){this._logger.trace(`DefaultView.selectSibling();`,{codecMessageId:e,index:t});let n=this._resolveMessageBranchPoint(e);if(!n)return;let r=Math.max(0,Math.min(t,n.siblings.length-1)),i=n.siblings[r];i&&(n.kind===`fork-of`?(this._branchSelections.set(n.groupRoot,{kind:`user`,selectedKey:x(i)}),this._logger.debug(`DefaultView.selectSibling(); fork-of`,{codecMessageId:e,index:r,selectedKey:x(i)})):(this._regenSelections.set(n.groupRoot,{kind:`user`,selectedRunId:x(i)}),this._logger.debug(`DefaultView.selectSibling(); regenerate`,{codecMessageId:e,index:r,selectedRunId:x(i),groupRoot:n.groupRoot})),this._recomputeAndEmit())}_resolveSelectedIndex(e){if(e.kind===`fork-of`){let t=this._branchSelections.get(e.groupRoot);if(!t)return e.siblings.length-1;let n=e.siblings.findIndex(e=>x(e)===t.selectedKey);return n===-1?e.siblings.length-1:n}let t=this._regenSelections.get(e.groupRoot);if(!t||t.kind===`pending`)return e.siblings.length-1;let n=e.siblings.findIndex(e=>x(e)===t.selectedRunId);return n===-1?e.siblings.length-1:n}_resolveMessageBranchPoint(e){let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`input`){let e=this._tree.getSiblingNodes(t.codecMessageId);return e.length>1?{kind:`fork-of`,groupRoot:this._tree.getGroupRoot(t.codecMessageId),siblings:e}:void 0}let n=this._tree.getSiblingNodes(t.runId);if(n.length>1&&this._codec.getMessages(t.projection).at(0)?.codecMessageId===e)return{kind:`regen`,groupRoot:this._tree.getGroupRoot(t.runId),siblings:n}}async send(e,t){if(this._logger.trace(`DefaultView.send();`),this._closed)throw new n.ErrorInfo(`unable to send; view is closed`,v.InvalidArgument,400);let r=Je(e),i=this._lastVisibleMessagePairs.at(-1)?.codecMessageId,a=await this._sendDelegate(r,t,i);return this._applyForkAutoSelect(a,t),a}_applyForkAutoSelect(e,t){if(!t?.forkOf)return;let n=e.optimisticCodecMessageIds.at(0);if(n===void 0)return;let r=this._tree.getGroupRoot(n);this._branchSelections.set(r,{kind:`auto`,selectedKey:n}),this._recomputeAndEmit()}_applyRegenerateAutoSelect(e,t){let n=this._runByCodecMessageId(t);if(!n)return;let r=this._tree.getGroupRoot(n.runId);this._regenSelections.set(r,{kind:`pending`,carrierCodecMessageId:e.inputCodecMessageId}),this._logger.debug(`DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection`,{anchorCodecMessageId:t,groupRoot:r,carrier:e.inputCodecMessageId}),this._resolvePendingRegenSelections(),this._recomputeAndEmitIfChanged()}async regenerate(e,t){if(this._logger.trace(`DefaultView.regenerate();`,{messageId:e}),this._closed)throw new n.ErrorInfo(`unable to regenerate; view is closed`,v.InvalidArgument,400);let r=this._runByCodecMessageId(e);if(!r)throw new n.ErrorInfo(`unable to regenerate; message not found in tree: ${e}`,v.InvalidArgument,400);let i=this._findParentMsgId(r,e);if(!i)throw new n.ErrorInfo(`unable to regenerate; parent user message not found for ${e}`,v.InvalidArgument,400);let a=e;r.regeneratesCodecMessageId!==void 0&&this._codec.getMessages(r.projection).at(0)?.codecMessageId===e&&(a=r.regeneratesCodecMessageId);let o={...t,parent:i},s=this._codec.createRegenerate(a,i),c=await this._sendDelegate([s],o,i);return this._applyRegenerateAutoSelect(c,a),c}async edit(e,t,r){if(this._logger.trace(`DefaultView.edit();`,{messageId:e}),this._closed)throw new n.ErrorInfo(`unable to edit; view is closed`,v.InvalidArgument,400);let i=this._tree.getNodeByCodecMessageId(e);if(!i)throw new n.ErrorInfo(`unable to edit; message not found in tree: ${e}`,v.InvalidArgument,400);let a=this._findParentMsgId(i,e);return this.send(t,{...r,forkOf:e,parent:a})}_findParentMsgId(e,t){let n=this._lastVisibleMessagePairs,r=n.findIndex(e=>e.codecMessageId===t);if(r>0)return n[r-1]?.codecMessageId;if(r===0)return;let i=this._codec.getMessages(e.projection),a=i.findIndex(e=>e.codecMessageId===t);if(a>0)return i[a-1]?.codecMessageId;if(a===0&&e.parentCodecMessageId!==void 0){let t=this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);if(t)return this._codec.getMessages(t.projection).at(-1)?.codecMessageId}}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}close(){if(!this._closed){this._logger.info(`DefaultView.close();`),this._closed=!0,this._loadingOlder=!1;for(let e of this._unsubs)e();this._unsubs.length=0,this._emitter.off(),this._branchSelections.clear(),this._regenSelections.clear(),this._withheldRunIds.clear(),this._withheldBuffer.length=0,this._onClose?.()}}async _loadFirstPage(e){let t=e*Ye,n=await qe(this._channel,{limit:t},this._logger);this._closed||await this._revealFromPage(n,e)}async _revealFromPage(e,t){let n=new Set(this._treeVisibleNodes().map(e=>x(e))),{newVisible:r,lastPage:i}=await this._loadUntilVisible(e,t,n);this._closed||(this._lastHistoryPage=i,this._hasMoreHistory=i.hasNext(),this._splitReveal(r,t))}_splitReveal(e,t){let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){if(e[i]?.kind===`run`){if(n===t)break;n++}r=i}let i=e.slice(r),a=e.slice(0,r);for(let e of a)this._withheldRunIds.add(x(e));this._withheldBuffer.push(...a),this._releaseWithheld(i)}_processHistoryPage(e){this._processingHistory=!0;try{let t=this._codec.createDecoder();for(let n of e.rawMessages)Le(this._tree,t,n);for(let t of e.rawMessages)this._tree.emitAblyMessage(t)}finally{this._processingHistory=!1}}async _loadUntilVisible(e,t,n){this._processHistoryPage(e);let r=e,i=()=>{let e=0;for(let t of this._treeVisibleNodes())t.kind===`run`&&!n.has(x(t))&&e++;return e};for(;i()<t&&r.hasNext();){let e=await r.next();if(!e||this._closed)break;this._processHistoryPage(e),r=e}return{newVisible:this._treeVisibleNodes().filter(e=>!n.has(x(e))),lastPage:r}}_releaseWithheld(e){for(let t of e)this._withheldRunIds.delete(x(t));e.length>0&&this._recomputeAndEmit()}_updateVisibleSnapshot(e){let t=e??this._cachedNodes;this._lastVisibleNodeKeys=t.map(e=>x(e)),this._lastVisibleNodeKeySet=new Set(this._lastVisibleNodeKeys),this._lastVisibleProjections=t.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(t)}_onTreeUpdate(){this._processingHistory||(this._pinBranchSelections(),this._resolvePendingRegenSelections(),this._recomputeAndEmitIfChanged())}_resolveSelections(){let e=new Map;for(let[t,n]of this._branchSelections)e.set(t,n.selectedKey);for(let[t,n]of this._regenSelections)n.kind!==`pending`&&e.set(t,n.selectedRunId);return e}_treeVisibleNodes(){return this._tree.visibleNodes(this._resolveSelections())}_pinBranchSelections(){for(let e of this._lastVisibleNodeKeys){if(this._tree.getNode(e)?.kind!==`input`||this._tree.getSiblingNodes(e).length<=1)continue;let t=this._tree.getGroupRoot(e);this._branchSelections.get(t)||this._branchSelections.set(t,{kind:`pinned`,selectedKey:e})}}_resolvePendingRegenSelections(){for(let[e,t]of this._regenSelections){if(t.kind===`user`)continue;let n=this._tree.getSiblingNodes(e).filter(e=>e.kind===`run`);if(n.length<=1)continue;let r=n.at(-1);r&&this._regenSelections.set(e,{kind:`auto`,selectedRunId:r.runId})}}_onTreeAblyMessage(e){let t=Ce(e),n=t[g],r=t[h];if(!n&&!r){this._emitter.emit(`ably-message`,e);return}r&&this._lastVisibleNodeKeySet.has(r)&&this._emitter.emit(`ably-message`,e)}_onTreeRun(e){if(this._lastVisibleNodeKeySet.has(e.runId)){this._emitter.emit(`run`,e);return}e.type===`start`&&this._isRunStartVisible(e)&&(this._lastVisibleNodeKeySet.add(e.runId),this._emitter.emit(`run`,e))}_isRunStartVisible(e){let{parent:t}=e;if(t===void 0)return!0;let n=this._tree.getNodeByCodecMessageId(t);return n?this._lastVisibleNodeKeySet.has(x(n)):!0}_visibleChanged(e){if(e.length!==this._lastVisibleNodeKeys.length)return!0;for(let[t,n]of e.entries())if(x(n)!==this._lastVisibleNodeKeys[t]||n.projection!==this._lastVisibleProjections[t])return!0;return!1}},Qe=e=>new Ze(e),$e=()=>{},et=class{constructor(e){this._views=new Set,this._state=`ready`,this._pendingRunStarts=new Map;let t=Ne(e.client,e.codec);if(this._channel=e.client.channels.get(e.channelName,t),this._codec=e.codec,this._clientId=e.clientId,this._logger=(e.logger??ye({logLevel:_e.Silent})).withContext({component:`ClientSession`}),this._emitter=new ge(this._logger),this._hasAttachedOnce=this._channel.state===`attached`,this._tree=Ue(this._codec,this._logger),this._view=Qe({tree:this._tree,channel:this._channel,codec:this._codec,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(this._view)}),this._decoder=this._codec.createDecoder(),this._encoder=this._codec.createEncoder(this._channel,this._clientId===void 0?void 0:{clientId:this._clientId}),this._views.add(this._view),this.tree=this._tree,this.view=this._view,e.messages){let t;for(let n of e.messages){let e=crypto.randomUUID(),r={[g]:e,[ae]:`user`};t&&(r[oe]=t),this._tree.applyMessage({inputs:[this._codec.createUserMessage(n)],outputs:[]},r),t=e}}this._onMessage=e=>{this._handleMessage(e)},this._onChannelStateChange=e=>{this._handleChannelStateChange(e)},this._channel.on(this._onChannelStateChange)}connect(){return this._state===`closed`?Promise.reject(new n.ErrorInfo(`unable to connect; session is closed`,v.SessionClosed,400)):this._connectPromise?this._connectPromise:(this._logger.trace(`DefaultClientSession.connect();`),this._connectPromise=this._channel.subscribe(this._onMessage).then(()=>{this._logger.debug(`DefaultClientSession.connect(); subscribed and attached`)},e=>{let t=new n.ErrorInfo(`unable to subscribe to channel; ${e instanceof Error?e.message:String(e)}`,v.SessionSubscriptionError,500,e instanceof n.ErrorInfo?e:void 0);throw this._logger.error(`DefaultClientSession.connect(); subscribe failed`),this._emitter.emit(`error`,t),t}),this._connectPromise)}async _requireConnected(e){if(!this._connectPromise)throw new n.ErrorInfo(`unable to ${e}; connect() must be called before ${e}()`,v.InvalidArgument,400);return this._connectPromise}_handleMessage(e){if(this._state!==`closed`)try{if(e.name===`ai-run-end`){let t=Ce(e);if((t[`run-reason`]??`complete`)===`error`){let e=t[ue],r=e===void 0?NaN:Number(e),i=Number.isFinite(r)?r:v.SessionSubscriptionError,a=t[`error-message`]??`agent reported an error`,o=i>=1e4&&i<6e4?Math.floor(i/100):500,s=new n.ErrorInfo(a,i,o);this._logger.error(`ClientSession._handleMessage(); agent error received`,{runId:t[h],invocationId:t[te],code:i}),this._emitter.emit(`error`,s)}}let t=Le(this._tree,this._decoder,e);if(t&&(t.type===`start`||t.type===`resume`)){let n=Ce(e)[le];if(n!==void 0){let e=this._pendingRunStarts.get(n);e&&(this._pendingRunStarts.delete(n),e.resolve(t.runId))}}this._tree.emitAblyMessage(e)}catch(e){let t=e instanceof n.ErrorInfo?e:void 0;this._emitter.emit(`error`,new n.ErrorInfo(`unable to process channel message; ${e instanceof Error?e.message:String(e)}`,v.SessionSubscriptionError,500,t))}}_handleChannelStateChange(e){if(this._state===`closed`)return;let{current:t,resumed:r}=e;if(t===`attached`&&!this._hasAttachedOnce){this._hasAttachedOnce=!0;return}if(!(t===`failed`||t===`suspended`||t===`detached`||t===`attached`&&!r))return;this._logger.error(`ClientSession._handleChannelStateChange(); channel continuity lost`,{current:t,resumed:r,previous:e.previous});let i=new n.ErrorInfo(`unable to deliver events; channel continuity lost (${t}${t===`attached`?`, resumed: false`:``})`,v.ChannelContinuityLost,500,e.reason);this._emitter.emit(`error`,i)}_cleanupFailedSend(e){for(let t of e){let e=this._tree.getNodeByCodecMessageId(t);e?.kind===`input`&&e.serial===void 0&&this._tree.delete(e.codecMessageId)}}createView(){if(this._state===`closed`)throw new n.ErrorInfo(`unable to create view; session is closed`,v.SessionClosed,400);this._logger.trace(`DefaultClientSession.createView();`);let e=Qe({tree:this._tree,channel:this._channel,codec:this._codec,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(e)});return this._views.add(e),e}async _internalSend(e,t,r){if(this._state===`closed`||(await this._requireConnected(`send`),this._state===`closed`))throw new n.ErrorInfo(`unable to send; session is closed`,v.SessionClosed,400);let i=this._channel.state;if(i!==`attached`&&i!==`attaching`)throw new n.ErrorInfo(`unable to send; channel is ${i}`,v.ChannelNotReady,400);this._logger.trace(`ClientSession._internalSend();`);let a=t?.runId!==void 0,o=t?.runId,s;t?.parent===void 0&&!t?.forkOf&&(s=r);let c=new Set,l=[];for(let n of e){let e=crypto.randomUUID(),r=n.codecMessageId??crypto.randomUUID();c.add(r);let i=n.kind!==`user-message`&&(n.kind===`regenerate`||n.codecMessageId!==void 0),a=n.parent??(t?.parent===void 0?s:t.parent),u=t?.forkOf,d=n.kind===`regenerate`?n.target:void 0,f=Pe({role:`user`,runId:o,codecMessageId:r,runClientId:this._clientId,...a!==void 0&&{parent:a},...u!==void 0&&{forkOf:u},...d!==void 0&&{regenerates:d},inputEventId:e});i||this._tree.applyMessage({inputs:[n],outputs:[]},f),l.push({input:n,codecMessageId:r,inputEventId:e,headers:f,isWireOnly:i}),!i&&t?.parent===void 0&&!t?.forkOf&&n.parent===void 0&&(s=r)}let u=l.at(-1);if(u===void 0)throw new n.ErrorInfo(`unable to send; inputs array is empty (include at least one input)`,v.InvalidArgument,400);let d=u.inputEventId,f=u.codecMessageId,p=new Promise((e,t)=>{this._pendingRunStarts.set(f,{resolve:e,reject:t})});return p.catch(()=>{}),await(async()=>{try{for(let e of l)await this._encoder.publishInput(e.input,{extras:{headers:e.headers},messageId:e.codecMessageId,...this._clientId!==void 0&&{clientId:this._clientId}})}catch(e){let t=e instanceof n.ErrorInfo?e:void 0,r=t?.statusCode===401||t?.statusCode===403,i=new n.ErrorInfo(r?`unable to publish events; missing publish capability on the channel`:`unable to publish events; ${e instanceof Error?e.message:String(e)}`,r?v.InsufficientCapability:v.SessionSendFailed,r?401:500,t);throw this._emitter.emit(`error`,i),this._pendingRunStarts.delete(f),a||this._cleanupFailedSend([...c]),i}})(),{inputCodecMessageId:f,runId:p,inputEventId:d,cancel:async()=>{await this._publishCancel({inputCodecMessageId:f,...o!==void 0&&{runId:o}})},optimisticCodecMessageIds:[...c],toInvocation:()=>Re.fromJSON({inputEventId:d,sessionName:this._channel.name})}}async cancel(e){return this._publishCancel({runId:e})}async _publishCancel(e){if(this._state===`closed`||(await this._requireConnected(`cancel`),this._state===`closed`))return;this._logger.debug(`ClientSession._publishCancel();`,{runId:e.runId,inputCodecMessageId:e.inputCodecMessageId});let t={[ne]:crypto.randomUUID()};e.runId!==void 0&&(t[h]=e.runId),e.inputCodecMessageId!==void 0&&(t[le]=e.inputCodecMessageId),await this._channel.publish({name:de,extras:{ai:{transport:t}}})}on(e,t){if(this._state===`closed`)return $e;let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}async close(){if(this._state!==`closed`){this._state=`closed`,this._logger.info(`ClientSession.close();`),this._connectPromise&&this._channel.unsubscribe(this._onMessage),this._channel.off(this._onChannelStateChange),this._emitter.off();for(let e of this._views)e.close();if(this._views.clear(),this._pendingRunStarts.size>0){let e=new n.ErrorInfo(`unable to await run-start; session closed`,v.SessionClosed,400);for(let t of this._pendingRunStarts.values())t.reject(e);this._pendingRunStarts.clear()}try{await this._encoder.close()}catch{}if(this._connectPromise)try{await this._channel.detach()}catch(e){this._logger.debug(`ClientSession.close(); channel detach failed`,{error:e})}}}},tt=e=>new et(e),nt=(0,t.createContext)({nearest:void 0,providers:{}}),rt=({children:e,...a})=>{let o=(0,r.useAbly)(),{channelName:s}=a,c=(0,t.useRef)(void 0),l=(0,t.useRef)(s),u=(0,t.useRef)([]),d=(0,t.useRef)(!1),f=(0,t.useRef)(void 0);if(!(c.current||f.current)||l.current!==s){l.current=s,c.current&&u.current.push(c.current);try{c.current=tt({...a,client:o}),f.current=void 0}catch(e){c.current=void 0,f.current=e instanceof n.ErrorInfo?e:new n.ErrorInfo(`Unknown error while creating client session`,v.BadRequest,400)}}let p=(0,t.useContext)(nt),ee=c.current,m=f.current,h=(0,t.useMemo)(()=>({session:ee,sessionError:m}),[ee,m]),te=(0,t.useMemo)(()=>({nearest:h,providers:{...p.providers,[s]:h}}),[s,p,h]);return(0,t.useEffect)(()=>()=>{for(let e of u.current)e.close()},[s]),(0,t.useEffect)(()=>{c.current?.connect()},[s]),(0,t.useEffect)(()=>(d.current=!1,()=>{d.current=!0,Promise.resolve().then(()=>{d.current&&c.current?.close()})}),[]),(0,i.jsx)(nt.Provider,{value:te,children:e})},it=({session:e,skip:n}={})=>{let{nearest:r}=(0,t.useContext)(nt),i=r?.session;if(!n&&e!==null)return e??i},at=({session:e,skip:n}={})=>{let r=it({session:e,skip:n}),[i,a]=(0,t.useState)([]),o=(0,t.useRef)([]);return(0,t.useEffect)(()=>{if(o.current=[],a([]),r)return r.tree.on(`ably-message`,e=>{let t=[...o.current,e];o.current=t,a(t)})},[r]),i},ot={get tree(){throw new n.ErrorInfo(`unable to access tree; hook is skipped`,v.InvalidArgument,400)},get view(){throw new n.ErrorInfo(`unable to access view; hook is skipped`,v.InvalidArgument,400)},connect:()=>{throw new n.ErrorInfo(`unable to connect; hook is skipped`,v.InvalidArgument,400)},createView:()=>{throw new n.ErrorInfo(`unable to create view; hook is skipped`,v.InvalidArgument,400)},cancel:()=>{throw new n.ErrorInfo(`unable to cancel; hook is skipped`,v.InvalidArgument,400)},on:()=>{throw new n.ErrorInfo(`unable to subscribe; hook is skipped`,v.InvalidArgument,400)},close:()=>{throw new n.ErrorInfo(`unable to close; hook is skipped`,v.InvalidArgument,400)}},st=({channelName:e,skip:r,onError:i}={})=>{let{nearest:a,providers:o}=(0,t.useContext)(nt),s=(0,t.useRef)(i);s.current=i;let c=r?void 0:e===void 0?a?.session:o[e]?.session;if((0,t.useEffect)(()=>{if(c)return c.on(`error`,e=>{s.current?.(e)})},[c]),r)return{session:ot};if(e!==void 0){let t=o[e];return t?t.session?{session:t.session}:{session:ot,sessionError:t.sessionError}:{session:ot,sessionError:new n.ErrorInfo(`unable to use session; no ClientSessionProvider found for channelName "${e}"`,v.BadRequest,400)}}return a?a.session?{session:a.session}:{session:ot,sessionError:a.sessionError}:{session:ot,sessionError:new n.ErrorInfo(`unable to use session; no ClientSessionProvider found in the tree`,v.BadRequest,400)}},ct={hasSiblings:!1,siblings:[],index:0,selected:void 0},lt=({session:e,view:r,limit:i,skip:a}={})=>{let o=it({session:e,skip:a}),s=a?void 0:r??o?.view,[c,l]=(0,t.useState)(()=>s?.getMessages()??[]),[u,d]=(0,t.useState)(()=>s?.hasOlder()??!1),[f,p]=(0,t.useState)(!1),[ee,m]=(0,t.useState)(),h=(0,t.useRef)(!1),te=i!==void 0,ne=(0,t.useRef)(!1);(0,t.useEffect)(()=>{if(!s){l([]),d(!1),m(void 0);return}return ne.current=!1,l(s.getMessages()),d(s.hasOlder()),m(void 0),s.on(`update`,()=>{l(s.getMessages()),d(s.hasOlder())})},[s]);let g=(0,t.useCallback)(async()=>{if(!(!s||h.current)){h.current=!0,p(!0);try{await s.loadOlder(i),m(void 0)}catch(e){e instanceof n.ErrorInfo?m(e):m(new n.ErrorInfo(`Unknown error loading older messages`,v.BadRequest,400))}finally{h.current=!1,p(!1)}}},[s,i]);return(0,t.useEffect)(()=>{!te||ne.current||!s||(ne.current=!0,g())},[te,s,g]),{messages:c,hasOlder:u,loading:f,loadError:ee,loadOlder:g,runOf:(0,t.useCallback)(e=>s?.runOf(e),[s]),run:(0,t.useCallback)(e=>s?.run(e),[s]),runs:(0,t.useCallback)(()=>s?.runs()??[],[s]),branchSelection:(0,t.useCallback)(e=>s?.branchSelection(e)??ct,[s]),selectSibling:(0,t.useCallback)((e,t)=>{s?.selectSibling(e,t)},[s]),send:(0,t.useCallback)(async(e,t)=>{if(!s)throw new n.ErrorInfo(`unable to send; view is not available`,v.InvalidArgument,400);return s.send(e,t)},[s]),regenerate:(0,t.useCallback)(async(e,t)=>{if(!s)throw new n.ErrorInfo(`unable to regenerate; view is not available`,v.InvalidArgument,400);return s.regenerate(e,t)},[s]),edit:(0,t.useCallback)(async(e,t,r)=>{if(!s)throw new n.ErrorInfo(`unable to edit; view is not available`,v.InvalidArgument,400);return s.edit(e,t,r)},[s])}},ut=({session:e,limit:n,skip:r}={})=>{let i=it({session:e,skip:r}),[a,o]=(0,t.useState)();return(0,t.useEffect)(()=>{if(!i){o(void 0);return}let e=i.createView();return o(e),()=>{e.close()}},[i]),lt({view:a,limit:n,skip:r})},dt=({session:e}={})=>{let n=it({session:e});return{getRunNode:(0,t.useCallback)(e=>n?.tree.getRunNode(e),[n]),getNodeByCodecMessageId:(0,t.useCallback)(e=>n?.tree.getNodeByCodecMessageId(e),[n]),getSiblingNodes:(0,t.useCallback)(e=>n?.tree.getSiblingNodes(e)??[],[n])}},ft=()=>({ClientSessionProvider:rt,useClientSession:e=>st(e??{}),useView:e=>lt(e??{}),useTree:e=>dt(e??{}),useAblyMessages:e=>at(e??{}),useCreateView:e=>ut(e??{})}),pt=class{constructor(e,t={}){this._serialState=new Map,this._hooks=e,this._onStreamUpdate=t.onStreamUpdate,this._onStreamDelete=t.onStreamDelete,this._logger=t.logger?.withContext({component:`DecoderCore`})}decode(e){let t=e.action;switch(this._logger?.trace(`DefaultDecoderCore.decode();`,{action:t,serial:e.serial,name:e.name}),t){case`message.create`:{let t=this._toPayload(e);return t.transportHeaders?.stream===`true`?this._decodeStreamedCreate(t,e.serial):this._hooks.decodeDiscrete(t)}case`message.append`:return this._decodeAppend(e);case`message.update`:return this._decodeUpdate(e);case`message.delete`:return this._decodeDelete(e);default:return[]}}_toPayload(e){return{name:e.name??``,data:e.data,transportHeaders:Ce(e),codecHeaders:we(e)}}_stringData(e){return typeof e.data==`string`?e.data:``}_invokeOnStreamUpdate(e){if(this._onStreamUpdate)try{this._onStreamUpdate(e)}catch(e){this._logger?.error(`DefaultDecoderCore._invokeOnStreamUpdate(); callback threw`,{error:e})}}_invokeOnStreamDelete(e,t){if(this._onStreamDelete)try{this._onStreamDelete(e,t)}catch(e){this._logger?.error(`DefaultDecoderCore._invokeOnStreamDelete(); callback threw`,{error:e})}}_decodeStreamedCreate(e,t){if(!t)return[];let n=e.transportHeaders?.[`stream-id`]??``,r={name:e.name,streamId:n,accumulated:``,codecHeaders:{...e.codecHeaders},transportHeaders:{...e.transportHeaders},closed:!1};return this._serialState.set(t,r),this._logger?.debug(`DefaultDecoderCore._decodeStreamedCreate(); new stream`,{name:e.name,streamId:n,serial:t}),this._hooks.buildStartEvents(r)}_decodeAppend(e){let t=e.serial;if(!t)return[];let n=this._serialState.get(t);if(!n)return this._decodeUpdate(e);let r=Ce(e),i=we(e),a=typeof e.data==`string`?e.data:``,o=r[p],s=[];return a.length>0&&(n.accumulated+=a,s.push(...this._hooks.buildDeltaEvents(n,a))),o===`complete`&&!n.closed?(n.closed=!0,s.push(...this._hooks.buildEndEvents(n,i)),this._logger?.debug(`DefaultDecoderCore._decodeAppend(); stream complete`,{streamId:n.streamId})):o===`cancelled`&&!n.closed&&(n.closed=!0,this._logger?.debug(`DefaultDecoderCore._decodeAppend(); stream cancelled`,{streamId:n.streamId})),s}_decodeUpdate(e){let t=e.serial;if(!t)return[];let n=this._toPayload(e),r=n.transportHeaders??{},i=n.codecHeaders??{},a=r[f]===`true`,o=r[p],s=this._serialState.get(t);if(!s)return this._decodeFirstContact(n,a,o,t);let c=this._stringData(e);if(c.startsWith(s.accumulated)){let e=c.slice(s.accumulated.length),t=[];return e.length>0&&(s.accumulated=c,t.push(...this._hooks.buildDeltaEvents(s,e))),o===`complete`&&!s.closed?(s.closed=!0,t.push(...this._hooks.buildEndEvents(s,i))):o===`cancelled`&&!s.closed&&(s.closed=!0),t}return s.accumulated=c,s.codecHeaders={...i},s.transportHeaders={...r},this._invokeOnStreamUpdate(s),[]}_decodeFirstContact(e,t,n,r){if(!t)return this._hooks.decodeDiscrete(e);let i=e.transportHeaders?.[`stream-id`]??``,a=e.codecHeaders??{},o=typeof e.data==`string`?e.data:``;this._logger?.debug(`DefaultDecoderCore._decodeFirstContact(); first-contact stream`,{name:e.name,streamId:i,serial:r});let s={name:e.name,streamId:i,accumulated:o,codecHeaders:{...a},transportHeaders:{...e.transportHeaders},closed:n===`complete`||n===`cancelled`};this._serialState.set(r,s);let c=this._hooks.buildStartEvents(s);return o.length>0&&c.push(...this._hooks.buildDeltaEvents(s,o)),n===`complete`&&c.push(...this._hooks.buildEndEvents(s,a)),c}_decodeDelete(e){let t=e.serial;if(!t)return[];let n=this._serialState.get(t);return this._invokeOnStreamDelete(t,n),n&&(n.accumulated=``,n.closed=!0),this._logger?.debug(`DefaultDecoderCore._decodeDelete();`,{serial:t}),[]}},mt=(e,t={})=>new pt(e,t),ht=class{constructor(e){this._emitted=new Map,this._phases=e}ensurePhases(e,t){let n=this._getOrCreate(e),r=[];for(let e of this._phases)n.has(e.key)||(n.add(e.key),r.push(...e.build(t)));return r}markEmitted(e,t){this._getOrCreate(e).add(t)}resetPhase(e,t){this._emitted.get(e)?.delete(t)}clearScope(e){this._emitted.delete(e)}_getOrCreate(e){let t=this._emitted.get(e);return t||(t=new Set,this._emitted.set(e,t)),t}},gt=e=>new ht(e),_t=e=>{let t=ke(e);return{...t,providerMetadata:()=>t.json(`providerMetadata`)}},vt=(e,t)=>e===`stop`||e===`length`||e===`content-filter`||e===`tool-calls`||e===`error`||e===`other`?e:t,yt=e=>e.startsWith(`data-`),bt=e=>{if(e)try{return JSON.parse(e)}catch{return e}},xt=e=>_t(e.codecHeaders).strOr(`type`,``),St=e=>{let t=_t(e.codecHeaders);switch(xt(e)){case`text`:return y({type:`text-start`,id:e.streamId,providerMetadata:t.providerMetadata()});case`reasoning`:return y({type:`reasoning-start`,id:e.streamId,providerMetadata:t.providerMetadata()});case`tool-input`:return y({type:`tool-input-start`,toolCallId:e.streamId,toolName:t.strOr(`toolName`,``),dynamic:t.bool(`dynamic`),title:t.str(`title`),providerExecuted:t.bool(`providerExecuted`),providerMetadata:t.providerMetadata()});default:return{type:`text-start`,id:e.streamId}}},Ct=(e,t)=>{switch(xt(e)){case`text`:return{type:`text-delta`,id:e.streamId,delta:t};case`reasoning`:return{type:`reasoning-delta`,id:e.streamId,delta:t};case`tool-input`:return{type:`tool-input-delta`,toolCallId:e.streamId,inputTextDelta:t};default:return{type:`text-delta`,id:e.streamId,delta:t}}},wt=(e,t)=>{let n=_t(t);switch(xt(e)){case`text`:return y({type:`text-end`,id:e.streamId,providerMetadata:n.providerMetadata()});case`reasoning`:return y({type:`reasoning-end`,id:e.streamId,providerMetadata:n.providerMetadata()});case`tool-input`:return y({type:`tool-input-available`,toolCallId:e.streamId,toolName:n.strOr(`toolName`,_t(e.codecHeaders).strOr(`toolName`,``)),input:bt(e.accumulated),providerMetadata:n.providerMetadata()});default:return{type:`text-end`,id:e.streamId}}},Tt=()=>gt([{key:`start`,build:e=>[y({type:`start`,messageId:e.messageId})]},{key:`start-step`,build:()=>[{type:`start-step`}]}]),Et=(e,t,n)=>(n.markEmitted(t,`start`),[y({type:`start`,messageId:e.str(`messageId`),messageMetadata:e.json(`messageMetadata`)})]),Dt=(e,t)=>(t.markEmitted(e,`start-step`),[{type:`start-step`}]),Ot=(e,t)=>(t.resetPhase(e,`start-step`),[{type:`finish-step`}]),kt=(e,t,n)=>(n.clearScope(t),[y({type:`finish`,finishReason:vt(e.str(`finishReason`),`stop`),messageMetadata:e.json(`messageMetadata`)})]),At=(e,t,n)=>(n.clearScope(t),[{type:`error`,errorText:typeof e==`string`?e:``}]),jt=(e,t,n)=>(n.clearScope(t),[y({type:`abort`,reason:typeof e==`string`&&e?e:void 0})]),Mt=e=>[{type:`message-metadata`,messageMetadata:e.json(`messageMetadata`)}],Nt=(e,t)=>[y({type:`file`,url:typeof t==`string`?t:``,mediaType:e.strOr(`mediaType`,``),providerMetadata:e.providerMetadata()})],Pt=(e,t)=>[y({type:`source-url`,sourceId:e.strOr(`sourceId`,``),url:typeof t==`string`?t:``,title:e.str(`title`),providerMetadata:e.providerMetadata()})],Ft=e=>[y({type:`source-document`,sourceId:e.strOr(`sourceId`,``),mediaType:e.strOr(`mediaType`,``),title:e.strOr(`title`,``),filename:e.str(`filename`),providerMetadata:e.providerMetadata()})],It=(e,t)=>{let n=t;return[y({type:`tool-input-error`,toolCallId:e.strOr(`toolCallId`,``),toolName:e.strOr(`toolName`,``),errorText:n?.errorText??``,input:n?.input,dynamic:e.bool(`dynamic`),title:e.str(`title`),providerExecuted:e.bool(`providerExecuted`),providerMetadata:e.providerMetadata()})]},Lt=(e,t)=>{let n=t;return[y({type:`tool-output-available`,toolCallId:e.strOr(`toolCallId`,``),output:n?.output,dynamic:e.bool(`dynamic`),providerExecuted:e.bool(`providerExecuted`),preliminary:e.bool(`preliminary`)})]},Rt=(e,t)=>{let n=t;return[y({type:`tool-output-error`,toolCallId:e.strOr(`toolCallId`,``),errorText:n?.errorText??``,dynamic:e.bool(`dynamic`),providerExecuted:e.bool(`providerExecuted`)})]},zt=e=>[{type:`tool-approval-request`,toolCallId:e.strOr(`toolCallId`,``),approvalId:e.strOr(`approvalId`,``)}],Bt=e=>[{type:`tool-output-denied`,toolCallId:e.strOr(`toolCallId`,``)}],Vt=(e,t,n)=>[y({type:e,data:n,id:t.str(`id`),transient:t.bool(`transient`)})],Ht=(e,t,n,r)=>[...r.ensurePhases(n,{messageId:e.str(`messageId`)}),y({type:`tool-input-start`,toolCallId:e.strOr(`toolCallId`,``),toolName:e.strOr(`toolName`,``),dynamic:e.bool(`dynamic`),title:e.str(`title`),providerExecuted:e.bool(`providerExecuted`),providerMetadata:e.providerMetadata()}),y({type:`tool-input-available`,toolCallId:e.strOr(`toolCallId`,``),toolName:e.strOr(`toolName`,``),input:t,providerMetadata:e.providerMetadata()})],Ut=e=>{let t=_t(e.codecHeaders??{}),n=e.transportHeaders?.role??`user`,r=t.str(`messageId`)??``,i=t.strOr(`type`,``),a;switch(i){case`text`:a={type:`text`,text:typeof e.data==`string`?e.data:``};break;case`file`:a={type:`file`,mediaType:t.strOr(`mediaType`,``),url:typeof e.data==`string`?e.data:``};break;default:yt(i)&&(a=y({type:i,id:t.str(`id`),data:e.data}));break}return a?[{kind:`user-message`,message:{id:r,role:n,parts:[a]}}]:[]},Wt=(e,t)=>(e===`text`||e===`file`||yt(e))&&`discrete`in t,Gt=(e,t,n)=>{let r=n;return[{kind:`tool-result`,codecMessageId:e,payload:{toolCallId:t.strOr(`toolCallId`,``),output:r?.output}}]},Kt=(e,t,n)=>{let r=n;return[{kind:`tool-result-error`,codecMessageId:e,payload:{toolCallId:t.strOr(`toolCallId`,``),message:r?.message??``}}]},qt=(e,t)=>[{kind:`tool-approval-response`,codecMessageId:e,payload:y({toolCallId:t.strOr(`toolCallId`,``),approved:t.bool(`approved`)??!1,reason:t.str(`reason`)})}],Jt=(e,t,n,r,i)=>{switch(e){case`start`:return Et(t,r,i);case`start-step`:return Dt(r,i);case`finish-step`:return Ot(r,i);case`finish`:return kt(t,r,i);case`error`:return At(n,r,i);case`abort`:return jt(n,r,i);case`message-metadata`:return Mt(t);case`file`:return Nt(t,n);case`source-url`:return Pt(t,n);case`source-document`:return Ft(t);case`tool-input`:return Ht(t,n,r,i);case`tool-input-error`:return It(t,n);case`tool-output-available`:return Lt(t,n);case`tool-output-error`:return Rt(t,n);case`tool-approval-request`:return zt(t);case`tool-output-denied`:return Bt(t);default:return yt(e)?Vt(e,t,n):[]}},Yt=(e,t,n)=>{if(Wt(e,t.transportHeaders??{}))return Ut(t);let r=t.transportHeaders?.[`codec-message-id`]??``;switch(e){case`tool-result`:return Gt(r,n,t.data);case`tool-result-error`:return Kt(r,n,t.data);case`tool-approval-response`:return qt(r,n);case`regenerate`:return[];default:return[]}},Xt=(e,t)=>{let n=_t(e.codecHeaders??{}),r=e.transportHeaders?.[`run-id`]??``,i=n.strOr(`type`,``);return e.name===`ai-input`?Yt(i,e,n):e.name===`ai-output`?Jt(i,n,e.data,r,t):[]},Zt=e=>({buildStartEvents:t=>{let n=t.transportHeaders[`run-id`]??``,r=_t(t.codecHeaders).str(`messageId`);return[...e.ensurePhases(n,{messageId:r}),St(t)]},buildDeltaEvents:(e,t)=>[Ct(e,t)],buildEndEvents:(e,t)=>[wt(e,t)],decodeDiscrete:t=>Xt(t,e)}),Qt=e=>`kind`in e,$t=class{constructor(e={}){this._core=mt(Zt(Tt()),e)}decode(e){let t=this._core.decode(e),n=[],r=[];for(let e of t)Qt(e)?n.push(e):r.push(e);return{inputs:n,outputs:r}}},en=(e={})=>new $t(e),tn=`vercel.ai.error`,nn=Symbol.for(tn),rn,an,on=class e extends (an=Error,rn=nn,an){constructor({name:e,message:t,cause:n}){super(t),this[rn]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,tn)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};function sn(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var cn=`AI_InvalidArgumentError`,ln=`vercel.ai.error.${cn}`,un=Symbol.for(ln),dn,fn,pn=class extends (fn=on,dn=un,fn){constructor({message:e,cause:t,argument:n}){super({name:cn,message:e,cause:t}),this[dn]=!0,this.argument=n}static isInstance(e){return on.hasMarker(e,ln)}},mn=`AI_JSONParseError`,hn=`vercel.ai.error.${mn}`,gn=Symbol.for(hn),_n,vn,yn=class extends (vn=on,_n=gn,vn){constructor({text:e,cause:t}){super({name:mn,message:`JSON parsing failed: Text: ${e}.
2
- Error message: ${sn(t)}`,cause:t}),this[_n]=!0,this.text=e}static isInstance(e){return on.hasMarker(e,hn)}},bn=`AI_TypeValidationError`,xn=`vercel.ai.error.${bn}`,Sn=Symbol.for(xn),Cn,wn,Tn=class e extends (wn=on,Cn=Sn,wn){constructor({value:e,cause:t,context:n}){let r=`Type validation failed`;if(n?.field&&(r+=` for ${n.field}`),n?.entityName||n?.entityId){r+=` (`;let e=[];n.entityName&&e.push(n.entityName),n.entityId&&e.push(`id: "${n.entityId}"`),r+=e.join(`, `),r+=`)`}super({name:bn,message:`${r}: Value: ${JSON.stringify(e)}.
3
- Error message: ${sn(t)}`,cause:t}),this[Cn]=!0,this.value=e,this.context=n}static isInstance(e){return on.hasMarker(e,xn)}static wrap({value:t,cause:n,context:r}){return e.isInstance(n)&&n.value===t&&n.context?.field===r?.field&&n.context?.entityName===r?.entityName&&n.context?.entityId===r?.entityId?n:new e({value:t,cause:n,context:r})}},En;function S(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,`_zod`,{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var Dn=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},On=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(En=globalThis).__zod_globalConfig??(En.__zod_globalConfig={});var kn=globalThis.__zod_globalConfig;function An(e){return e&&Object.assign(kn,e),kn}function jn(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Mn(e,t){return typeof t==`bigint`?t.toString():t}function Nn(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function Pn(e){return e==null}function Fn(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function In(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}var Ln=Symbol(`evaluating`);function C(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Ln)return r===void 0&&(r=Ln,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Rn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function zn(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function Bn(e){return JSON.stringify(e)}function Vn(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var Hn=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Wn=Nn(()=>{if(kn.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Gn(e){if(Un(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Un(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Kn(e){return Gn(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var qn=new Set([`string`,`number`,`symbol`]);function Jn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Yn(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function w(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Xn(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var Zn={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Qn(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Yn(e,zn(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Rn(this,`shape`,e),e},checks:[]}))}function $n(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Yn(e,zn(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Rn(this,`shape`,r),r},checks:[]}))}function er(e,t){if(!Gn(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Yn(e,zn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Rn(this,`shape`,n),n}}))}function tr(e,t){if(!Gn(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Yn(e,zn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Rn(this,`shape`,n),n}}))}function nr(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Yn(e,zn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Rn(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function rr(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Yn(t,zn(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Rn(this,`shape`,i),i},checks:[]}))}function ir(e,t,n){return Yn(t,zn(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Rn(this,`shape`,i),i}}))}function ar(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function or(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function sr(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function cr(e){return typeof e==`string`?e:e?.message}function lr(e,t,n){let r=e.message?e.message:cr(e.inst?._zod.def?.error?.(e))??cr(t?.error?.(e))??cr(n.customError?.(e))??cr(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function ur(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function dr(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var fr=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,Mn,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},pr=S(`$ZodError`,fr),mr=S(`$ZodError`,fr,{Parent:Error});function hr(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function gr(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}var _r=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Dn;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>lr(e,a,An())));throw Hn(t,i?.callee),t}return o.value},vr=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>lr(e,a,An())));throw Hn(t,i?.callee),t}return o.value},yr=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Dn;return a.issues.length?{success:!1,error:new(e??pr)(a.issues.map(e=>lr(e,i,An())))}:{success:!0,data:a.value}},br=yr(mr),xr=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>lr(e,i,An())))}:{success:!0,data:a.value}},Sr=xr(mr),Cr=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _r(e)(t,n,i)},wr=e=>(t,n,r)=>_r(e)(t,n,r),Tr=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return vr(e)(t,n,i)},Er=e=>async(t,n,r)=>vr(e)(t,n,r),Dr=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return yr(e)(t,n,i)},Or=e=>(t,n,r)=>yr(e)(t,n,r),kr=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return xr(e)(t,n,i)},Ar=e=>async(t,n,r)=>xr(e)(t,n,r),jr=/^[cC][0-9a-z]{6,}$/,Mr=/^[0-9a-z]+$/,Nr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Pr=/^[0-9a-vA-V]{20}$/,Fr=/^[A-Za-z0-9]{27}$/,Ir=/^[a-zA-Z0-9_-]{21}$/,Lr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Rr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,zr=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Br=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Vr=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function Hr(){return new RegExp(Vr,`u`)}var Ur=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Wr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Gr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Kr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Jr=/^[A-Za-z0-9_-]*$/,Yr=/^https?$/,Xr=/^\+[1-9]\d{6,14}$/,Zr=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Qr=RegExp(`^${Zr}$`);function $r(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ei(e){return RegExp(`^${$r(e)}$`)}function ti(e){let t=$r({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${Zr}T(?:${r})$`)}var ni=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},ri=/^-?\d+$/,ii=/^-?\d+(?:\.\d+)?$/,ai=/^(?:true|false)$/i,oi=/^null$/i,si=/^[^A-Z]*$/,ci=/^[^a-z]*$/,T=S(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),li={number:`number`,bigint:`bigint`,object:`date`},ui=S(`$ZodCheckLessThan`,(e,t)=>{T.init(e,t);let n=li[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),di=S(`$ZodCheckGreaterThan`,(e,t)=>{T.init(e,t);let n=li[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),fi=S(`$ZodCheckMultipleOf`,(e,t)=>{T.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):In(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),pi=S(`$ZodCheckNumberFormat`,(e,t)=>{T.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Zn[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=ri)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),mi=S(`$ZodCheckMaxLength`,(e,t)=>{var n;T.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Pn(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=ur(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),hi=S(`$ZodCheckMinLength`,(e,t)=>{var n;T.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Pn(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=ur(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),gi=S(`$ZodCheckLengthEquals`,(e,t)=>{var n;T.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Pn(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=ur(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),_i=S(`$ZodCheckStringFormat`,(e,t)=>{var n,r;T.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),vi=S(`$ZodCheckRegex`,(e,t)=>{_i.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),yi=S(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=si,_i.init(e,t)}),bi=S(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=ci,_i.init(e,t)}),xi=S(`$ZodCheckIncludes`,(e,t)=>{T.init(e,t);let n=Jn(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Si=S(`$ZodCheckStartsWith`,(e,t)=>{T.init(e,t);let n=RegExp(`^${Jn(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ci=S(`$ZodCheckEndsWith`,(e,t)=>{T.init(e,t);let n=RegExp(`.*${Jn(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),wi=S(`$ZodCheckOverwrite`,(e,t)=>{T.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Ti=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
4
- `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
5
- `))}},Ei={major:4,minor:4,patch:3},E=S(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ei;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=ar(e),i;for(let a of t){if(a._zod.def.when){if(or(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Dn;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=ar(e,t))});else{if(e.issues.length===t)continue;r||=ar(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(ar(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Dn;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Dn;return o.then(e=>t(e,r,a))}return t(o,r,a)}}C(e,`~standard`,()=>({validate:t=>{try{let n=br(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Sr(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Di=S(`$ZodString`,(e,t)=>{E.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ni(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),D=S(`$ZodStringFormat`,(e,t)=>{_i.init(e,t),Di.init(e,t)}),Oi=S(`$ZodGUID`,(e,t)=>{t.pattern??=Rr,D.init(e,t)}),ki=S(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=zr(e)}else t.pattern??=zr();D.init(e,t)}),Ai=S(`$ZodEmail`,(e,t)=>{t.pattern??=Br,D.init(e,t)}),ji=S(`$ZodURL`,(e,t)=>{D.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Yr.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Mi=S(`$ZodEmoji`,(e,t)=>{t.pattern??=Hr(),D.init(e,t)}),Ni=S(`$ZodNanoID`,(e,t)=>{t.pattern??=Ir,D.init(e,t)}),Pi=S(`$ZodCUID`,(e,t)=>{t.pattern??=jr,D.init(e,t)}),Fi=S(`$ZodCUID2`,(e,t)=>{t.pattern??=Mr,D.init(e,t)}),Ii=S(`$ZodULID`,(e,t)=>{t.pattern??=Nr,D.init(e,t)}),Li=S(`$ZodXID`,(e,t)=>{t.pattern??=Pr,D.init(e,t)}),Ri=S(`$ZodKSUID`,(e,t)=>{t.pattern??=Fr,D.init(e,t)}),zi=S(`$ZodISODateTime`,(e,t)=>{t.pattern??=ti(t),D.init(e,t)}),Bi=S(`$ZodISODate`,(e,t)=>{t.pattern??=Qr,D.init(e,t)}),Vi=S(`$ZodISOTime`,(e,t)=>{t.pattern??=ei(t),D.init(e,t)}),Hi=S(`$ZodISODuration`,(e,t)=>{t.pattern??=Lr,D.init(e,t)}),Ui=S(`$ZodIPv4`,(e,t)=>{t.pattern??=Ur,D.init(e,t),e._zod.bag.format=`ipv4`}),Wi=S(`$ZodIPv6`,(e,t)=>{t.pattern??=Wr,D.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Gi=S(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Gr,D.init(e,t)}),Ki=S(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Kr,D.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function qi(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Ji=S(`$ZodBase64`,(e,t)=>{t.pattern??=qr,D.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{qi(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Yi(e){if(!Jr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return qi(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Xi=S(`$ZodBase64URL`,(e,t)=>{t.pattern??=Jr,D.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Yi(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Zi=S(`$ZodE164`,(e,t)=>{t.pattern??=Xr,D.init(e,t)});function Qi(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var $i=S(`$ZodJWT`,(e,t)=>{D.init(e,t),e._zod.check=n=>{Qi(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),ea=S(`$ZodNumber`,(e,t)=>{E.init(e,t),e._zod.pattern=e._zod.bag.pattern??ii,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),ta=S(`$ZodNumberFormat`,(e,t)=>{pi.init(e,t),ea.init(e,t)}),na=S(`$ZodBoolean`,(e,t)=>{E.init(e,t),e._zod.pattern=ai,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),ra=S(`$ZodNull`,(e,t)=>{E.init(e,t),e._zod.pattern=oi,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),ia=S(`$ZodUnknown`,(e,t)=>{E.init(e,t),e._zod.parse=e=>e}),aa=S(`$ZodNever`,(e,t)=>{E.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function oa(e,t,n){e.issues.length&&t.issues.push(...sr(n,e.issues)),t.value[n]=e.value}var sa=S(`$ZodArray`,(e,t)=>{E.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>oa(t,n,e))):oa(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function ca(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...sr(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function la(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Xn(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function ua(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>ca(e,n,i,t,u,d))):ca(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var da=S(`$ZodObject`,(e,t)=>{if(E.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let n={...e};return Object.defineProperty(t,`shape`,{value:n}),n}})}let n=Nn(()=>la(t));C(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Un,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>ca(n,t,e,s,r,i))):ca(a,t,e,s,r,i)}return i?ua(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),fa=S(`$ZodObjectJIT`,(e,t)=>{da.init(e,t);let n=e._zod.parse,r=Nn(()=>la(t)),i=e=>{let t=new Ti([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Bn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Bn(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
6
- if (${n}.issues.length) {
7
- if (${o} in input) {
8
- payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
9
- ...iss,
10
- path: iss.path ? [${o}, ...iss.path] : [${o}]
11
- })));
12
- }
13
- }
14
-
15
- if (${n}.value === undefined) {
16
- if (${o} in input) {
17
- newResult[${o}] = undefined;
18
- }
19
- } else {
20
- newResult[${o}] = ${n}.value;
21
- }
22
-
23
- `):c?t.write(`
24
- if (${n}.issues.length) {
25
- payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
26
- ...iss,
27
- path: iss.path ? [${o}, ...iss.path] : [${o}]
28
- })));
29
- }
30
-
31
- if (${n}.value === undefined) {
32
- if (${o} in input) {
33
- newResult[${o}] = undefined;
34
- }
35
- } else {
36
- newResult[${o}] = ${n}.value;
37
- }
38
-
39
- `):t.write(`
40
- const ${n}_present = ${o} in input;
41
- if (${n}.issues.length) {
42
- payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
43
- ...iss,
44
- path: iss.path ? [${o}, ...iss.path] : [${o}]
45
- })));
46
- }
47
- if (!${n}_present && !${n}.issues.length) {
48
- payload.issues.push({
49
- code: "invalid_type",
50
- expected: "nonoptional",
51
- input: undefined,
52
- path: [${o}]
53
- });
54
- }
55
-
56
- if (${n}_present) {
57
- if (${n}.value === undefined) {
58
- newResult[${o}] = undefined;
59
- } else {
60
- newResult[${o}] = ${n}.value;
61
- }
62
- }
63
-
64
- `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Un,s=!kn.jitless,c=s&&Wn.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?ua([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function pa(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ar(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>lr(e,r,An())))}),t)}var ma=S(`$ZodUnion`,(e,t)=>{E.init(e,t),C(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),C(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),C(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),C(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Fn(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>pa(t,r,e,i)):pa(o,r,e,i)}}),ha=S(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,ma.init(e,t);let n=e._zod.parse;C(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=Nn(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Un(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),ga=S(`$ZodIntersection`,(e,t)=>{E.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>va(e,t,n)):va(e,i,a)}});function _a(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Gn(e)&&Gn(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=_a(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=_a(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function va(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ar(e))return e;let o=_a(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var ya=S(`$ZodRecord`,(e,t)=>{E.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Gn(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>lr(e,r,An())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...sr(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...sr(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&ii.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>lr(e,r,An())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...sr(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...sr(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),ba=S(`$ZodEnum`,(e,t)=>{E.init(e,t);let n=jn(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>qn.has(typeof e)).map(e=>typeof e==`string`?Jn(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),xa=S(`$ZodLiteral`,(e,t)=>{if(E.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?Jn(e):e?Jn(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Sa=S(`$ZodTransform`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new On(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Dn;return n.value=i,n.fallback=!0,n}});function Ca(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var wa=S(`$ZodOptional`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,C(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),C(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Fn(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Ca(e,r)):Ca(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Ta=S(`$ZodExactOptional`,(e,t)=>{wa.init(e,t),C(e._zod,`values`,()=>t.innerType._zod.values),C(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Ea=S(`$ZodNullable`,(e,t)=>{E.init(e,t),C(e._zod,`optin`,()=>t.innerType._zod.optin),C(e._zod,`optout`,()=>t.innerType._zod.optout),C(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Fn(e.source)}|null)$`):void 0}),C(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Da=S(`$ZodDefault`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,C(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Oa(e,t)):Oa(r,t)}});function Oa(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var ka=S(`$ZodPrefault`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,C(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Aa=S(`$ZodNonOptional`,(e,t)=>{E.init(e,t),C(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>ja(t,e)):ja(i,e)}});function ja(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var Ma=S(`$ZodCatch`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,C(e._zod,`optout`,()=>t.innerType._zod.optout),C(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>lr(e,n,An()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>lr(e,n,An()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Na=S(`$ZodPipe`,(e,t)=>{E.init(e,t),C(e._zod,`values`,()=>t.in._zod.values),C(e._zod,`optin`,()=>t.in._zod.optin),C(e._zod,`optout`,()=>t.out._zod.optout),C(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Pa(e,t.in,n)):Pa(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Pa(e,t.out,n)):Pa(r,t.out,n)}});function Pa(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Fa=S(`$ZodReadonly`,(e,t)=>{E.init(e,t),C(e._zod,`propValues`,()=>t.innerType._zod.propValues),C(e._zod,`values`,()=>t.innerType._zod.values),C(e._zod,`optin`,()=>t.innerType?._zod?.optin),C(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Ia):Ia(r)}});function Ia(e){return e.value=Object.freeze(e.value),e}var La=S(`$ZodLazy`,(e,t)=>{E.init(e,t),C(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),C(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),C(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),C(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),C(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Ra=S(`$ZodCustom`,(e,t)=>{T.init(e,t),E.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>za(t,n,r,e));za(i,n,r,e)}});function za(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(dr(e))}}var Ba,Va=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ha(){return new Va}(Ba=globalThis).__zod_globalRegistry??(Ba.__zod_globalRegistry=Ha());var Ua=globalThis.__zod_globalRegistry;function Wa(e,t){return new e({type:`string`,...w(t)})}function Ga(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...w(t)})}function Ka(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...w(t)})}function qa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...w(t)})}function Ja(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...w(t)})}function Ya(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...w(t)})}function Xa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...w(t)})}function Za(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...w(t)})}function Qa(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...w(t)})}function $a(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...w(t)})}function eo(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...w(t)})}function to(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...w(t)})}function no(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...w(t)})}function ro(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...w(t)})}function io(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...w(t)})}function ao(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...w(t)})}function oo(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...w(t)})}function so(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...w(t)})}function co(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...w(t)})}function lo(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...w(t)})}function uo(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...w(t)})}function fo(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...w(t)})}function po(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...w(t)})}function mo(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...w(t)})}function ho(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...w(t)})}function go(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...w(t)})}function _o(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...w(t)})}function vo(e,t){return new e({type:`number`,checks:[],...w(t)})}function yo(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...w(t)})}function bo(e,t){return new e({type:`boolean`,...w(t)})}function xo(e,t){return new e({type:`null`,...w(t)})}function So(e){return new e({type:`unknown`})}function Co(e,t){return new e({type:`never`,...w(t)})}function wo(e,t){return new ui({check:`less_than`,...w(t),value:e,inclusive:!1})}function To(e,t){return new ui({check:`less_than`,...w(t),value:e,inclusive:!0})}function Eo(e,t){return new di({check:`greater_than`,...w(t),value:e,inclusive:!1})}function Do(e,t){return new di({check:`greater_than`,...w(t),value:e,inclusive:!0})}function Oo(e,t){return new fi({check:`multiple_of`,...w(t),value:e})}function ko(e,t){return new mi({check:`max_length`,...w(t),maximum:e})}function Ao(e,t){return new hi({check:`min_length`,...w(t),minimum:e})}function jo(e,t){return new gi({check:`length_equals`,...w(t),length:e})}function Mo(e,t){return new vi({check:`string_format`,format:`regex`,...w(t),pattern:e})}function No(e){return new yi({check:`string_format`,format:`lowercase`,...w(e)})}function Po(e){return new bi({check:`string_format`,format:`uppercase`,...w(e)})}function Fo(e,t){return new xi({check:`string_format`,format:`includes`,...w(t),includes:e})}function Io(e,t){return new Si({check:`string_format`,format:`starts_with`,...w(t),prefix:e})}function Lo(e,t){return new Ci({check:`string_format`,format:`ends_with`,...w(t),suffix:e})}function Ro(e){return new wi({check:`overwrite`,tx:e})}function zo(e){return Ro(t=>t.normalize(e))}function Bo(){return Ro(e=>e.trim())}function Vo(){return Ro(e=>e.toLowerCase())}function Ho(){return Ro(e=>e.toUpperCase())}function Uo(){return Ro(e=>Vn(e))}function Wo(e,t,n){return new e({type:`array`,element:t,...w(n)})}function Go(e,t,n){let r=w(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function Ko(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...w(n)})}function qo(e,t){let n=Jo(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(dr(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(dr(r))}},e(t.value,t)),t);return n}function Jo(e,t){let n=new T({check:`custom`,...w(t)});return n._zod.check=e,n}function Yo(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Ua,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function O(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,O(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&k(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Xo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
65
-
66
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Zo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:$o(t,`input`,e.processors),output:$o(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function k(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return k(r.element,n);if(r.type===`set`)return k(r.valueType,n);if(r.type===`lazy`)return k(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return k(r.innerType,n);if(r.type===`intersection`)return k(r.left,n)||k(r.right,n);if(r.type===`record`||r.type===`map`)return k(r.keyType,n)||k(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:k(r.in,n)||k(r.out,n);if(r.type===`object`){for(let e in r.shape)if(k(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(k(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(k(e,n))return!0;return!!(r.rest&&k(r.rest,n))}return!1}var Qo=(e,t={})=>n=>{let r=Yo({...n,processors:t});return O(e,r),Xo(r,e),Zo(r,e)},$o=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Yo({...i??{},target:a,io:t,processors:n});return O(e,o),Xo(o,e),Zo(o,e)},es={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ts=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=es[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},ns=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},rs=(e,t,n,r)=>{n.type=`boolean`},is=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},as=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},os=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ss=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},cs=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},ls=(e,t,n,r)=>{n.not={}},us=(e,t,n,r)=>{},ds=(e,t,n,r)=>{},fs=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},ps=(e,t,n,r)=>{let i=e._zod.def,a=jn(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},ms=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},hs=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},gs=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},_s=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},vs=(e,t,n,r)=>{n.type=`boolean`},ys=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},bs=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},xs=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ss=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},Cs=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},ws=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=O(a.element,t,{...r,path:[...r.path,`items`]})},Ts=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=O(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=O(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Es=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>O(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ds=(e,t,n,r)=>{let i=e._zod.def,a=O(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=O(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Os=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>O(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?O(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},ks=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=O(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=O(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=O(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},As=(e,t,n,r)=>{let i=e._zod.def,a=O(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},js=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ms=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Ns=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Ps=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Fs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;O(o,t,r);let s=t.seen.get(e);s.ref=o},Is=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ls=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Rs=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},zs=(e,t,n,r)=>{let i=e._zod.innerType;O(i,t,r);let a=t.seen.get(e);a.ref=i},Bs={string:ts,number:ns,boolean:rs,bigint:is,symbol:as,null:os,undefined:ss,void:cs,never:ls,any:us,unknown:ds,date:fs,enum:ps,literal:ms,nan:hs,template_literal:gs,file:_s,success:vs,custom:ys,function:bs,transform:xs,map:Ss,set:Cs,array:ws,object:Ts,union:Es,intersection:Ds,tuple:Os,record:ks,nullable:As,nonoptional:js,default:Ms,prefault:Ns,catch:Ps,pipe:Fs,readonly:Is,promise:Ls,optional:Rs,lazy:zs};function Vs(e,t){if(`_idmap`in e){let n=e,r=Yo({...t,processors:Bs}),i={};for(let e of n._idmap.entries()){let[t,n]=e;O(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;Xo(r,n),a[t]=Zo(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=Yo({...t,processors:Bs});return O(e,n),Xo(n,e),Zo(n,e)}var Hs=S(`ZodISODateTime`,(e,t)=>{zi.init(e,t),N.init(e,t)});function Us(e){return mo(Hs,e)}var Ws=S(`ZodISODate`,(e,t)=>{Bi.init(e,t),N.init(e,t)});function Gs(e){return ho(Ws,e)}var Ks=S(`ZodISOTime`,(e,t)=>{Vi.init(e,t),N.init(e,t)});function qs(e){return go(Ks,e)}var Js=S(`ZodISODuration`,(e,t)=>{Hi.init(e,t),N.init(e,t)});function Ys(e){return _o(Js,e)}var A=S(`ZodError`,(e,t)=>{pr.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>gr(e,t)},flatten:{value:t=>hr(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Mn,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Mn,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Xs=_r(A),Zs=vr(A),Qs=yr(A),$s=xr(A),ec=Cr(A),tc=wr(A),nc=Tr(A),rc=Er(A),ic=Dr(A),ac=Or(A),oc=kr(A),sc=Ar(A),cc=new WeakMap;function lc(e,t,n){let r=Object.getPrototypeOf(e),i=cc.get(r);if(i||(i=new Set,cc.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var j=S(`ZodType`,(e,t)=>(E.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:$o(e,`input`),output:$o(e,`output`)}}),e.toJSONSchema=Qo(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>Xs(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Qs(e,t,n),e.parseAsync=async(t,n)=>Zs(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>$s(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>ec(e,t,n),e.decode=(t,n)=>tc(e,t,n),e.encodeAsync=async(t,n)=>nc(e,t,n),e.decodeAsync=async(t,n)=>rc(e,t,n),e.safeEncode=(t,n)=>ic(e,t,n),e.safeDecode=(t,n)=>ac(e,t,n),e.safeEncodeAsync=async(t,n)=>oc(e,t,n),e.safeDecodeAsync=async(t,n)=>sc(e,t,n),lc(e,`ZodType`,{check(...e){let t=this.def;return this.clone(zn(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Yn(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(El(e,t))},superRefine(e,t){return this.check(Dl(e,t))},overwrite(e){return this.check(Ro(e))},optional(){return al(this)},exactOptional(){return sl(this)},nullable(){return ll(this)},nullish(){return al(ll(this))},nonoptional(e){return hl(this,e)},array(){return Wc(this)},or(e){return F([this,e])},and(e){return Xc(this,e)},transform(e){return yl(this,rl(e))},default(e){return dl(this,e)},prefault(e){return pl(this,e)},catch(e){return _l(this,e)},pipe(e){return yl(this,e)},readonly(){return xl(this)},describe(e){let t=this.clone();return Ua.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ua.get(this);let t=this.clone();return Ua.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return Ua.get(e)?.description},configurable:!0}),e)),uc=S(`_ZodString`,(e,t)=>{Di.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,lc(e,`_ZodString`,{regex(...e){return this.check(Mo(...e))},includes(...e){return this.check(Fo(...e))},startsWith(...e){return this.check(Io(...e))},endsWith(...e){return this.check(Lo(...e))},min(...e){return this.check(Ao(...e))},max(...e){return this.check(ko(...e))},length(...e){return this.check(jo(...e))},nonempty(...e){return this.check(Ao(1,...e))},lowercase(e){return this.check(No(e))},uppercase(e){return this.check(Po(e))},trim(){return this.check(Bo())},normalize(...e){return this.check(zo(...e))},toLowerCase(){return this.check(Vo())},toUpperCase(){return this.check(Ho())},slugify(){return this.check(Uo())}})}),dc=S(`ZodString`,(e,t)=>{Di.init(e,t),uc.init(e,t),e.email=t=>e.check(Ga(fc,t)),e.url=t=>e.check(Za(hc,t)),e.jwt=t=>e.check(po(Ac,t)),e.emoji=t=>e.check(Qa(gc,t)),e.guid=t=>e.check(Ka(pc,t)),e.uuid=t=>e.check(qa(mc,t)),e.uuidv4=t=>e.check(Ja(mc,t)),e.uuidv6=t=>e.check(Ya(mc,t)),e.uuidv7=t=>e.check(Xa(mc,t)),e.nanoid=t=>e.check($a(_c,t)),e.guid=t=>e.check(Ka(pc,t)),e.cuid=t=>e.check(eo(vc,t)),e.cuid2=t=>e.check(to(yc,t)),e.ulid=t=>e.check(no(bc,t)),e.base64=t=>e.check(lo(Dc,t)),e.base64url=t=>e.check(uo(Oc,t)),e.xid=t=>e.check(ro(xc,t)),e.ksuid=t=>e.check(io(Sc,t)),e.ipv4=t=>e.check(ao(Cc,t)),e.ipv6=t=>e.check(oo(wc,t)),e.cidrv4=t=>e.check(so(Tc,t)),e.cidrv6=t=>e.check(co(Ec,t)),e.e164=t=>e.check(fo(kc,t)),e.datetime=t=>e.check(Us(t)),e.date=t=>e.check(Gs(t)),e.time=t=>e.check(qs(t)),e.duration=t=>e.check(Ys(t))});function M(e){return Wa(dc,e)}var N=S(`ZodStringFormat`,(e,t)=>{D.init(e,t),uc.init(e,t)}),fc=S(`ZodEmail`,(e,t)=>{Ai.init(e,t),N.init(e,t)}),pc=S(`ZodGUID`,(e,t)=>{Oi.init(e,t),N.init(e,t)}),mc=S(`ZodUUID`,(e,t)=>{ki.init(e,t),N.init(e,t)}),hc=S(`ZodURL`,(e,t)=>{ji.init(e,t),N.init(e,t)}),gc=S(`ZodEmoji`,(e,t)=>{Mi.init(e,t),N.init(e,t)}),_c=S(`ZodNanoID`,(e,t)=>{Ni.init(e,t),N.init(e,t)}),vc=S(`ZodCUID`,(e,t)=>{Pi.init(e,t),N.init(e,t)}),yc=S(`ZodCUID2`,(e,t)=>{Fi.init(e,t),N.init(e,t)}),bc=S(`ZodULID`,(e,t)=>{Ii.init(e,t),N.init(e,t)}),xc=S(`ZodXID`,(e,t)=>{Li.init(e,t),N.init(e,t)}),Sc=S(`ZodKSUID`,(e,t)=>{Ri.init(e,t),N.init(e,t)}),Cc=S(`ZodIPv4`,(e,t)=>{Ui.init(e,t),N.init(e,t)}),wc=S(`ZodIPv6`,(e,t)=>{Wi.init(e,t),N.init(e,t)}),Tc=S(`ZodCIDRv4`,(e,t)=>{Gi.init(e,t),N.init(e,t)}),Ec=S(`ZodCIDRv6`,(e,t)=>{Ki.init(e,t),N.init(e,t)}),Dc=S(`ZodBase64`,(e,t)=>{Ji.init(e,t),N.init(e,t)}),Oc=S(`ZodBase64URL`,(e,t)=>{Xi.init(e,t),N.init(e,t)}),kc=S(`ZodE164`,(e,t)=>{Zi.init(e,t),N.init(e,t)}),Ac=S(`ZodJWT`,(e,t)=>{$i.init(e,t),N.init(e,t)}),jc=S(`ZodNumber`,(e,t)=>{ea.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),lc(e,`ZodNumber`,{gt(e,t){return this.check(Eo(e,t))},gte(e,t){return this.check(Do(e,t))},min(e,t){return this.check(Do(e,t))},lt(e,t){return this.check(wo(e,t))},lte(e,t){return this.check(To(e,t))},max(e,t){return this.check(To(e,t))},int(e){return this.check(Pc(e))},safe(e){return this.check(Pc(e))},positive(e){return this.check(Eo(0,e))},nonnegative(e){return this.check(Do(0,e))},negative(e){return this.check(wo(0,e))},nonpositive(e){return this.check(To(0,e))},multipleOf(e,t){return this.check(Oo(e,t))},step(e,t){return this.check(Oo(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Mc(e){return vo(jc,e)}var Nc=S(`ZodNumberFormat`,(e,t)=>{ta.init(e,t),jc.init(e,t)});function Pc(e){return yo(Nc,e)}var Fc=S(`ZodBoolean`,(e,t)=>{na.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r)});function Ic(e){return bo(Fc,e)}var Lc=S(`ZodNull`,(e,t)=>{ra.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r)});function Rc(e){return xo(Lc,e)}var zc=S(`ZodUnknown`,(e,t)=>{ia.init(e,t),j.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Bc(){return So(zc)}var Vc=S(`ZodNever`,(e,t)=>{aa.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ls(e,t,n,r)});function Hc(e){return Co(Vc,e)}var Uc=S(`ZodArray`,(e,t)=>{sa.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ws(e,t,n,r),e.element=t.element,lc(e,`ZodArray`,{min(e,t){return this.check(Ao(e,t))},nonempty(e){return this.check(Ao(1,e))},max(e,t){return this.check(ko(e,t))},length(e,t){return this.check(jo(e,t))},unwrap(){return this.element}})});function Wc(e,t){return Wo(Uc,e,t)}var Gc=S(`ZodObject`,(e,t)=>{fa.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ts(e,t,n,r),C(e,`shape`,()=>t.shape),lc(e,`ZodObject`,{keyof(){return el(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Bc()})},loose(){return this.clone({...this._zod.def,catchall:Bc()})},strict(){return this.clone({...this._zod.def,catchall:Hc()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return er(this,e)},safeExtend(e){return tr(this,e)},merge(e){return nr(this,e)},pick(e){return Qn(this,e)},omit(e){return $n(this,e)},partial(...e){return rr(il,this,e[0])},required(...e){return ir(ml,this,e[0])}})});function P(e,t){return new Gc({type:`object`,shape:e??{},...w(t)})}var Kc=S(`ZodUnion`,(e,t)=>{ma.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Es(e,t,n,r),e.options=t.options});function F(e,t){return new Kc({type:`union`,options:e,...w(t)})}var qc=S(`ZodDiscriminatedUnion`,(e,t)=>{Kc.init(e,t),ha.init(e,t)});function Jc(e,t,n){return new qc({type:`union`,options:t,discriminator:e,...w(n)})}var Yc=S(`ZodIntersection`,(e,t)=>{ga.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ds(e,t,n,r)});function Xc(e,t){return new Yc({type:`intersection`,left:e,right:t})}var Zc=S(`ZodRecord`,(e,t)=>{ya.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ks(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Qc(e,t,n){return!t||!t._zod?new Zc({type:`record`,keyType:M(),valueType:e,...w(t)}):new Zc({type:`record`,keyType:e,valueType:t,...w(n)})}var $c=S(`ZodEnum`,(e,t)=>{ba.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ps(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new $c({...t,checks:[],...w(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new $c({...t,checks:[],...w(r),entries:i})}});function el(e,t){return new $c({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...w(t)})}var tl=S(`ZodLiteral`,(e,t)=>{xa.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ms(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function I(e,t){return new tl({type:`literal`,values:Array.isArray(e)?e:[e],...w(t)})}var nl=S(`ZodTransform`,(e,t)=>{Sa.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new On(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(dr(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(dr(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function rl(e){return new nl({type:`transform`,transform:e})}var il=S(`ZodOptional`,(e,t)=>{wa.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function al(e){return new il({type:`optional`,innerType:e})}var ol=S(`ZodExactOptional`,(e,t)=>{Ta.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function sl(e){return new ol({type:`optional`,innerType:e})}var cl=S(`ZodNullable`,(e,t)=>{Ea.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>As(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ll(e){return new cl({type:`nullable`,innerType:e})}var ul=S(`ZodDefault`,(e,t)=>{Da.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ms(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function dl(e,t){return new ul({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Kn(t)}})}var fl=S(`ZodPrefault`,(e,t)=>{ka.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function pl(e,t){return new fl({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Kn(t)}})}var ml=S(`ZodNonOptional`,(e,t)=>{Aa.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>js(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function hl(e,t){return new ml({type:`nonoptional`,innerType:e,...w(t)})}var gl=S(`ZodCatch`,(e,t)=>{Ma.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ps(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _l(e,t){return new gl({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var vl=S(`ZodPipe`,(e,t)=>{Na.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fs(e,t,n,r),e.in=t.in,e.out=t.out});function yl(e,t){return new vl({type:`pipe`,in:e,out:t})}var bl=S(`ZodReadonly`,(e,t)=>{Fa.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function xl(e){return new bl({type:`readonly`,innerType:e})}var Sl=S(`ZodLazy`,(e,t)=>{La.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zs(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Cl(e){return new Sl({type:`lazy`,getter:e})}var wl=S(`ZodCustom`,(e,t)=>{Ra.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r)});function Tl(e,t){return Go(wl,e??(()=>!0),t)}function El(e,t={}){return Ko(wl,e,t)}function Dl(e,t){return qo(e,t)}function Ol(e,t={}){let n=new wl({type:`custom`,check:`custom`,fn:t=>t instanceof e,abort:!0,...w(t)});return n._zod.bag.Class=e,n._zod.check=t=>{t.value instanceof e||t.issues.push({code:`invalid_type`,expected:e.name,input:t.value,inst:n,path:[...n._zod.def.path??[]]})},n}var L;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(L||={});var kl;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(kl||={});var R=L.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Al=e=>{switch(typeof e){case`undefined`:return R.undefined;case`string`:return R.string;case`number`:return Number.isNaN(e)?R.nan:R.number;case`boolean`:return R.boolean;case`function`:return R.function;case`bigint`:return R.bigint;case`symbol`:return R.symbol;case`object`:return Array.isArray(e)?R.array:e===null?R.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?R.promise:typeof Map<`u`&&e instanceof Map?R.map:typeof Set<`u`&&e instanceof Set?R.set:typeof Date<`u`&&e instanceof Date?R.date:R.object;default:return R.unknown}},z=L.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),jl=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};jl.create=e=>new jl(e);var Ml=(e,t)=>{let n;switch(e.code){case z.invalid_type:n=e.received===R.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,L.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,`, `)}`;break;case z.invalid_union:n=`Invalid input`;break;case z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case z.invalid_enum_value:n=`Invalid enum value. Expected ${L.joinValues(e.options)}, received '${e.received}'`;break;case z.invalid_arguments:n=`Invalid function arguments`;break;case z.invalid_return_type:n=`Invalid function return type`;break;case z.invalid_date:n=`Invalid date`;break;case z.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:L.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case z.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case z.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case z.custom:n=`Invalid input`;break;case z.invalid_intersection_types:n=`Intersection results could not be merged`;break;case z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case z.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,L.assertNever(e)}return{message:n}},Nl=Ml;function Pl(){return Nl}var Fl=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function B(e,t){let n=Pl(),r=Fl({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ml?void 0:Ml].filter(e=>!!e)});e.common.issues.push(r)}var V=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return H;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return H;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},H=Object.freeze({status:`aborted`}),Il=e=>({status:`dirty`,value:e}),U=e=>({status:`valid`,value:e}),Ll=e=>e.status===`aborted`,Rl=e=>e.status===`dirty`,zl=e=>e.status===`valid`,Bl=e=>typeof Promise<`u`&&e instanceof Promise,W;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(W||={});var Vl=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Hl=(e,t)=>{if(zl(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new jl(e.common.issues);return this._error=t,this._error}}};function G(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var K=class{get description(){return this._def.description}_getType(e){return Al(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Al(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new V,ctx:{common:e.parent.common,data:e.data,parsedType:Al(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Bl(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Al(e)};return Hl(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Al(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return zl(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>zl(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Al(e)},r=this._parse({data:e,path:n.path,parent:n});return Hl(n,await(Bl(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:z.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new Wu({schema:this,typeName:J.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return Gu.create(this,this._def)}nullable(){return Ku.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Eu.create(this)}promise(){return Uu.create(this,this._def)}or(e){return Ou.create([this,e],this._def)}and(e){return Mu.create(this,e,this._def)}transform(e){return new Wu({...G(this._def),schema:this,typeName:J.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new qu({...G(this._def),innerType:this,defaultValue:t,typeName:J.ZodDefault})}brand(){return new Xu({typeName:J.ZodBranded,type:this,...G(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Ju({...G(this._def),innerType:this,catchValue:t,typeName:J.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Zu.create(this,e)}readonly(){return Qu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ul=/^c[^\s-]{8,}$/i,Wl=/^[0-9a-z]+$/,Gl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Kl=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ql=/^[a-z0-9_-]{21}$/i,Jl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yl=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Xl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Zl=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,Ql,$l=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,eu=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,tu=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,nu=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ru=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,iu=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,au=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,ou=RegExp(`^${au}$`);function su(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function cu(e){return RegExp(`^${su(e)}$`)}function lu(e){let t=`${au}T${su(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function uu(e,t){return!!((t===`v4`||!t)&&$l.test(e)||(t===`v6`||!t)&&tu.test(e))}function du(e,t){if(!Jl.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function fu(e,t){return!!((t===`v4`||!t)&&eu.test(e)||(t===`v6`||!t)&&nu.test(e))}var pu=class e extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.string,received:t.parsedType}),H}let t=new V,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),B(n,{code:z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),B(n,{code:z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?B(n,{code:z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&B(n,{code:z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Xl.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`email`,code:z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Ql||=new RegExp(Zl,`u`),Ql.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`emoji`,code:z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Kl.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`uuid`,code:z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)ql.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`nanoid`,code:z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Ul.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`cuid`,code:z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Wl.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`cuid2`,code:z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Gl.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`ulid`,code:z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),B(n,{validation:`url`,code:z.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`regex`,code:z.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),B(n,{code:z.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),B(n,{code:z.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),B(n,{code:z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?lu(r).test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ou.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?cu(r).test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Yl.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`duration`,code:z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?uu(e.data,r.version)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`ip`,code:z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?du(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`jwt`,code:z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?fu(e.data,r.version)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`cidr`,code:z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?ru.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`base64`,code:z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?iu.test(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{validation:`base64url`,code:z.invalid_string,message:r.message}),t.dirty()):L.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:z.invalid_string,...W.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...W.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...W.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...W.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...W.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...W.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...W.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...W.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...W.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...W.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...W.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...W.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...W.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...W.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...W.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...W.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...W.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...W.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...W.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...W.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...W.errToObj(t)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};pu.create=e=>new pu({checks:[],typeName:J.ZodString,coerce:e?.coerce??!1,...G(e)});function mu(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var hu=class e extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.number,received:t.parsedType}),H}let t,n=new V;for(let r of this._def.checks)r.kind===`int`?L.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),B(t,{code:z.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),B(t,{code:z.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),B(t,{code:z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?mu(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),B(t,{code:z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),B(t,{code:z.not_finite,message:r.message}),n.dirty()):L.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,W.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,W.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,W.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,W.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:W.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:W.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:W.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:W.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:W.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&L.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};hu.create=e=>new hu({checks:[],typeName:J.ZodNumber,coerce:e?.coerce||!1,...G(e)});var gu=class e extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let t,n=new V;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),B(t,{code:z.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),B(t,{code:z.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),B(t,{code:z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):L.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.bigint,received:t.parsedType}),H}gte(e,t){return this.setLimit(`min`,e,!0,W.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,W.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,W.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,W.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:W.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};gu.create=e=>new gu({checks:[],typeName:J.ZodBigInt,coerce:e?.coerce??!1,...G(e)});var _u=class extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.boolean,received:t.parsedType}),H}return U(e.data)}};_u.create=e=>new _u({typeName:J.ZodBoolean,coerce:e?.coerce||!1,...G(e)});var vu=class e extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.date,received:t.parsedType}),H}if(Number.isNaN(e.data.getTime()))return B(this._getOrReturnCtx(e),{code:z.invalid_date}),H;let t=new V,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),B(n,{code:z.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),B(n,{code:z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):L.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:W.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:W.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};vu.create=e=>new vu({checks:[],coerce:e?.coerce||!1,typeName:J.ZodDate,...G(e)});var yu=class extends K{_parse(e){if(this._getType(e)!==R.symbol){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.symbol,received:t.parsedType}),H}return U(e.data)}};yu.create=e=>new yu({typeName:J.ZodSymbol,...G(e)});var bu=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.undefined,received:t.parsedType}),H}return U(e.data)}};bu.create=e=>new bu({typeName:J.ZodUndefined,...G(e)});var xu=class extends K{_parse(e){if(this._getType(e)!==R.null){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.null,received:t.parsedType}),H}return U(e.data)}};xu.create=e=>new xu({typeName:J.ZodNull,...G(e)});var Su=class extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return U(e.data)}};Su.create=e=>new Su({typeName:J.ZodAny,...G(e)});var Cu=class extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return U(e.data)}};Cu.create=e=>new Cu({typeName:J.ZodUnknown,...G(e)});var wu=class extends K{_parse(e){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.never,received:t.parsedType}),H}};wu.create=e=>new wu({typeName:J.ZodNever,...G(e)});var Tu=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.void,received:t.parsedType}),H}return U(e.data)}};Tu.create=e=>new Tu({typeName:J.ZodVoid,...G(e)});var Eu=class e extends K{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==R.array)return B(t,{code:z.invalid_type,expected:R.array,received:t.parsedType}),H;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(B(t,{code:e?z.too_big:z.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(B(t,{code:z.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(B(t,{code:z.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Vl(t,e,t.path,n)))).then(e=>V.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Vl(t,e,t.path,n)));return V.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:W.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:W.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:W.toString(n)}})}nonempty(e){return this.min(1,e)}};Eu.create=(e,t)=>new Eu({type:e,minLength:null,maxLength:null,exactLength:null,typeName:J.ZodArray,...G(t)});function Du(e){if(e instanceof q){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Gu.create(Du(r))}return new q({...e._def,shape:()=>t})}else if(e instanceof Eu)return new Eu({...e._def,type:Du(e.element)});else if(e instanceof Gu)return Gu.create(Du(e.unwrap()));else if(e instanceof Ku)return Ku.create(Du(e.unwrap()));else if(e instanceof Nu)return Nu.create(e.items.map(e=>Du(e)));else return e}var q=class e extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=L.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.object,received:t.parsedType}),H}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof wu&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Vl(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof wu){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(B(n,{code:z.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Vl(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>V.mergeObjectSync(t,e)):V.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return W.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:W.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:J.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of L.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of L.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Du(this)}partial(t){let n={};for(let e of L.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of L.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Gu;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Bu(L.objectKeys(this.shape))}};q.create=(e,t)=>new q({shape:()=>e,unknownKeys:`strip`,catchall:wu.create(),typeName:J.ZodObject,...G(t)}),q.strictCreate=(e,t)=>new q({shape:()=>e,unknownKeys:`strict`,catchall:wu.create(),typeName:J.ZodObject,...G(t)}),q.lazycreate=(e,t)=>new q({shape:e,unknownKeys:`strip`,catchall:wu.create(),typeName:J.ZodObject,...G(t)});var Ou=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new jl(e.ctx.common.issues));return B(t,{code:z.invalid_union,unionErrors:n}),H}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new jl(e));return B(t,{code:z.invalid_union,unionErrors:i}),H}}get options(){return this._def.options}};Ou.create=(e,t)=>new Ou({options:e,typeName:J.ZodUnion,...G(t)});var ku=e=>e instanceof Ru?ku(e.schema):e instanceof Wu?ku(e.innerType()):e instanceof zu?[e.value]:e instanceof Vu?e.options:e instanceof Hu?L.objectValues(e.enum):e instanceof qu?ku(e._def.innerType):e instanceof bu?[void 0]:e instanceof xu?[null]:e instanceof Gu?[void 0,...ku(e.unwrap())]:e instanceof Ku?[null,...ku(e.unwrap())]:e instanceof Xu||e instanceof Qu?ku(e.unwrap()):e instanceof Ju?ku(e._def.innerType):[],Au=class e extends K{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return B(t,{code:z.invalid_type,expected:R.object,received:t.parsedType}),H;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(B(t,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),H)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=ku(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:J.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...G(r)})}};function ju(e,t){let n=Al(e),r=Al(t);if(e===t)return{valid:!0,data:e};if(n===R.object&&r===R.object){let n=L.objectKeys(t),r=L.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=ju(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===R.array&&r===R.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=ju(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===R.date&&r===R.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Mu=class extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Ll(e)||Ll(r))return H;let i=ju(e.value,r.value);return i.valid?((Rl(e)||Rl(r))&&t.dirty(),{status:t.value,value:i.data}):(B(n,{code:z.invalid_intersection_types}),H)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Mu.create=(e,t,n)=>new Mu({left:e,right:t,typeName:J.ZodIntersection,...G(n)});var Nu=class e extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return B(n,{code:z.invalid_type,expected:R.array,received:n.parsedType}),H;if(n.data.length<this._def.items.length)return B(n,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),H;!this._def.rest&&n.data.length>this._def.items.length&&(B(n,{code:z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Vl(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>V.mergeArray(t,e)):V.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Nu.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Nu({items:e,typeName:J.ZodTuple,rest:null,...G(t)})};var Pu=class e extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return B(n,{code:z.invalid_type,expected:R.object,received:n.parsedType}),H;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Vl(n,e,n.path,e)),value:a._parse(new Vl(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?V.mergeObjectAsync(t,r):V.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof K?new e({keyType:t,valueType:n,typeName:J.ZodRecord,...G(r)}):new e({keyType:pu.create(),valueType:t,typeName:J.ZodRecord,...G(n)})}},Fu=class extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return B(n,{code:z.invalid_type,expected:R.map,received:n.parsedType}),H;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Vl(n,e,n.path,[a,`key`])),value:i._parse(new Vl(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return H;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return H;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Fu.create=(e,t,n)=>new Fu({valueType:t,keyType:e,typeName:J.ZodMap,...G(n)});var Iu=class e extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return B(n,{code:z.invalid_type,expected:R.set,received:n.parsedType}),H;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(B(n,{code:z.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(B(n,{code:z.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return H;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Vl(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:W.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:W.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Iu.create=(e,t)=>new Iu({valueType:e,minSize:null,maxSize:null,typeName:J.ZodSet,...G(t)});var Lu=class e extends K{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return B(t,{code:z.invalid_type,expected:R.function,received:t.parsedType}),H;function n(e,n){return Fl({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Pl(),Ml].filter(e=>!!e),issueData:{code:z.invalid_arguments,argumentsError:n}})}function r(e,n){return Fl({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Pl(),Ml].filter(e=>!!e),issueData:{code:z.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Uu){let e=this;return U(async function(...t){let o=new jl([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return U(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new jl([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new jl([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Nu.create(t).rest(Cu.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Nu.create([]).rest(Cu.create()),returns:n||Cu.create(),typeName:J.ZodFunction,...G(r)})}},Ru=class extends K{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ru.create=(e,t)=>new Ru({getter:e,typeName:J.ZodLazy,...G(t)});var zu=class extends K{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return B(t,{received:t.data,code:z.invalid_literal,expected:this._def.value}),H}return{status:`valid`,value:e.data}}get value(){return this._def.value}};zu.create=(e,t)=>new zu({value:e,typeName:J.ZodLiteral,...G(t)});function Bu(e,t){return new Vu({values:e,typeName:J.ZodEnum,...G(t)})}var Vu=class e extends K{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return B(t,{expected:L.joinValues(n),received:t.parsedType,code:z.invalid_type}),H}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return B(t,{received:t.data,code:z.invalid_enum_value,options:n}),H}return U(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Vu.create=Bu;var Hu=class extends K{_parse(e){let t=L.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let e=L.objectValues(t);return B(n,{expected:L.joinValues(e),received:n.parsedType,code:z.invalid_type}),H}if(this._cache||=new Set(L.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=L.objectValues(t);return B(n,{received:n.data,code:z.invalid_enum_value,options:e}),H}return U(e.data)}get enum(){return this._def.values}};Hu.create=(e,t)=>new Hu({values:e,typeName:J.ZodNativeEnum,...G(t)});var Uu=class extends K{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==R.promise&&t.common.async===!1?(B(t,{code:z.invalid_type,expected:R.promise,received:t.parsedType}),H):U((t.parsedType===R.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Uu.create=(e,t)=>new Uu({type:e,typeName:J.ZodPromise,...G(t)});var Wu=class extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===J.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{B(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return H;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?H:r.status===`dirty`||t.value===`dirty`?Il(r.value):r});{if(t.value===`aborted`)return H;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?H:r.status===`dirty`||t.value===`dirty`?Il(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?H:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?H:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!zl(e))return H;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>zl(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):H);L.assertNever(r)}};Wu.create=(e,t,n)=>new Wu({schema:e,typeName:J.ZodEffects,effect:t,...G(n)}),Wu.createWithPreprocess=(e,t,n)=>new Wu({schema:t,effect:{type:`preprocess`,transform:e},typeName:J.ZodEffects,...G(n)});var Gu=class extends K{_parse(e){return this._getType(e)===R.undefined?U(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Gu.create=(e,t)=>new Gu({innerType:e,typeName:J.ZodOptional,...G(t)});var Ku=class extends K{_parse(e){return this._getType(e)===R.null?U(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ku.create=(e,t)=>new Ku({innerType:e,typeName:J.ZodNullable,...G(t)});var qu=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};qu.create=(e,t)=>new qu({innerType:e,typeName:J.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...G(t)});var Ju=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Bl(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new jl(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new jl(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ju.create=(e,t)=>new Ju({innerType:e,typeName:J.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...G(t)});var Yu=class extends K{_parse(e){if(this._getType(e)!==R.nan){let t=this._getOrReturnCtx(e);return B(t,{code:z.invalid_type,expected:R.nan,received:t.parsedType}),H}return{status:`valid`,value:e.data}}};Yu.create=e=>new Yu({typeName:J.ZodNaN,...G(e)});var Xu=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Zu=class e extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?H:e.status===`dirty`?(t.dirty(),Il(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?H:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:J.ZodPipeline})}},Qu=class extends K{_parse(e){let t=this._def.innerType._parse(e),n=e=>(zl(e)&&(e.value=Object.freeze(e.value)),e);return Bl(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Qu.create=(e,t)=>new Qu({innerType:e,typeName:J.ZodReadonly,...G(t)}),q.lazycreate;var J;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(J||={}),pu.create,hu.create,Yu.create,gu.create,_u.create,vu.create,yu.create,bu.create,xu.create,Su.create,Cu.create,wu.create,Tu.create,Eu.create,q.create,q.strictCreate,Ou.create,Au.create,Mu.create,Nu.create,Pu.create,Fu.create,Iu.create,Lu.create,Ru.create,zu.create,Vu.create,Hu.create,Uu.create,Wu.create,Gu.create,Ku.create,Wu.createWithPreprocess,Zu.create;var{btoa:$u,atob:ed}=globalThis,td=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new pn({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`};td();var nd=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,rd=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function id(e){let t=JSON.parse(e);return typeof t!=`object`||!t||nd.test(e)===!1&&rd.test(e)===!1?t:ad(t)}function ad(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&n.constructor!==null&&typeof n.constructor==`object`&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function od(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return id(e)}try{return id(e)}finally{Error.stackTraceLimit=t}}function sd(e){if(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)){e.additionalProperties=!1;let{properties:t}=e;if(t!=null)for(let e of Object.keys(t))t[e]=cd(t[e])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(cd):cd(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(cd)),e.allOf!=null&&(e.allOf=e.allOf.map(cd)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(cd));let{definitions:t}=e;if(t!=null)for(let e of Object.keys(t))t[e]=cd(t[e]);return e}function cd(e){return typeof e==`boolean`?e:sd(e)}var ld=Symbol(`Let zodToJsonSchema decide on which parser to use`),ud={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`},dd=e=>typeof e==`string`?{...ud,name:e}:{...ud,...e};function Y(){return{}}function fd(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==J.ZodAny&&(n.items=Q(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&(n.minItems=e.minLength.value),e.maxLength&&(n.maxItems=e.maxLength.value),e.exactLength&&(n.minItems=e.exactLength.value,n.maxItems=e.exactLength.value),n}function pd(e){let t={type:`integer`,format:`int64`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function md(){return{type:`boolean`}}function hd(e,t){return Q(e.type._def,t)}var gd=(e,t)=>Q(e.innerType._def,t);function _d(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>_d(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return vd(e)}}var vd=e=>{let t={type:`integer`,format:`unix-time`};for(let n of e.checks)switch(n.kind){case`min`:t.minimum=n.value;break;case`max`:t.maximum=n.value;break}return t};function yd(e,t){return{...Q(e.innerType._def,t),default:e.defaultValue()}}function bd(e,t){return t.effectStrategy===`input`?Q(e.schema._def,t):Y()}function xd(e){return{type:`string`,enum:Array.from(e.values)}}var Sd=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Cd(e,t){let n=[Q(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Q(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=[];return n.forEach(e=>{if(Sd(e))r.push(...e.allOf);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}r.push(t)}}),r.length?{allOf:r}:void 0}function wd(e){let t=typeof e.value;return t!==`bigint`&&t!==`number`&&t!==`boolean`&&t!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:{type:t===`bigint`?`integer`:t,const:e.value}}var Td=void 0,X={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Td===void 0&&(Td=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Td),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ed(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value;break;case`max`:n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`email`:switch(t.emailStrategy){case`format:email`:Ad(n,`email`,r.message,t);break;case`format:idn-email`:Ad(n,`idn-email`,r.message,t);break;case`pattern:zod`:Z(n,X.email,r.message,t);break}break;case`url`:Ad(n,`uri`,r.message,t);break;case`uuid`:Ad(n,`uuid`,r.message,t);break;case`regex`:Z(n,r.regex,r.message,t);break;case`cuid`:Z(n,X.cuid,r.message,t);break;case`cuid2`:Z(n,X.cuid2,r.message,t);break;case`startsWith`:Z(n,RegExp(`^${Dd(r.value,t)}`),r.message,t);break;case`endsWith`:Z(n,RegExp(`${Dd(r.value,t)}$`),r.message,t);break;case`datetime`:Ad(n,`date-time`,r.message,t);break;case`date`:Ad(n,`date`,r.message,t);break;case`time`:Ad(n,`time`,r.message,t);break;case`duration`:Ad(n,`duration`,r.message,t);break;case`length`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`includes`:Z(n,RegExp(Dd(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Ad(n,`ipv4`,r.message,t),r.version!==`v4`&&Ad(n,`ipv6`,r.message,t);break;case`base64url`:Z(n,X.base64url,r.message,t);break;case`jwt`:Z(n,X.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&Z(n,X.ipv4Cidr,r.message,t),r.version!==`v4`&&Z(n,X.ipv6Cidr,r.message,t);break;case`emoji`:Z(n,X.emoji(),r.message,t);break;case`ulid`:Z(n,X.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Ad(n,`binary`,r.message,t);break;case`contentEncoding:base64`:n.contentEncoding=`base64`;break;case`pattern:zod`:Z(n,X.base64,r.message,t);break}break;case`nanoid`:Z(n,X.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}function Dd(e,t){return t.patternStrategy===`escape`?kd(e):e}var Od=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function kd(e){let t=``;for(let n=0;n<e.length;n++)Od.has(e[n])||(t+=`\\`),t+=e[n];return t}function Ad(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function Z(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:jd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=jd(t,r)}function jd(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
67
- ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
68
- ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r
69
- `:`[${r[e]}\r
70
- ]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}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 i}function Md(e,t){let n={type:`object`,additionalProperties:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===J.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Ed(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===J.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===J.ZodBranded&&e.keyType._def.type._def.typeName===J.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=hd(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Nd(e,t){return t.mapStrategy===`record`?Md(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Q(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Y(),Q(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Y()],minItems:2,maxItems:2}}}function Pd(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function Fd(){return{not:Y()}}function Id(){return{type:`null`}}var Ld={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Rd(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Ld&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Ld[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return zd(e,t)}var zd=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Q(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Bd(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Ld[e.innerType._def.typeName],`null`]};let n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Vd(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function Hd(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=Wd(a),s=Q(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=Ud(e,t);return a!==void 0&&(n.additionalProperties=a),n}function Ud(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Q(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 Wd(e){try{return e.isOptional()}catch{return!0}}var Gd=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Q(e.innerType._def,t);let n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Y()},n]}:Y()},Kd=(e,t)=>{if(t.pipeStrategy===`input`)return Q(e.in._def,t);if(t.pipeStrategy===`output`)return Q(e.out._def,t);let n=Q(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Q(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function qd(e,t){return Q(e.type._def,t)}function Jd(e,t){let n={type:`array`,uniqueItems:!0,items:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function Yd(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Q(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Q(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Q(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Xd(){return{not:Y()}}function Zd(){return Y()}var Qd=(e,t)=>Q(e.innerType._def,t),$d=(e,t,n)=>{switch(t){case J.ZodString:return Ed(e,n);case J.ZodNumber:return Vd(e);case J.ZodObject:return Hd(e,n);case J.ZodBigInt:return pd(e);case J.ZodBoolean:return md();case J.ZodDate:return _d(e,n);case J.ZodUndefined:return Xd();case J.ZodNull:return Id();case J.ZodArray:return fd(e,n);case J.ZodUnion:case J.ZodDiscriminatedUnion:return Rd(e,n);case J.ZodIntersection:return Cd(e,n);case J.ZodTuple:return Yd(e,n);case J.ZodRecord:return Md(e,n);case J.ZodLiteral:return wd(e);case J.ZodEnum:return xd(e);case J.ZodNativeEnum:return Pd(e);case J.ZodNullable:return Bd(e,n);case J.ZodOptional:return Gd(e,n);case J.ZodMap:return Nd(e,n);case J.ZodSet:return Jd(e,n);case J.ZodLazy:return()=>e.getter()._def;case J.ZodPromise:return qd(e,n);case J.ZodNaN:case J.ZodNever:return Fd();case J.ZodEffects:return bd(e,n);case J.ZodAny:return Y();case J.ZodUnknown:return Zd();case J.ZodDefault:return yd(e,n);case J.ZodBranded:return hd(e,n);case J.ZodReadonly:return Qd(e,n);case J.ZodCatch:return gd(e,n);case J.ZodPipeline:return Kd(e,n);case J.ZodFunction:case J.ZodVoid:case J.ZodSymbol:return;default:return(e=>void 0)(t)}},ef=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function Q(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==ld)return i}if(r&&!n){let e=tf(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=$d(e,e.typeName,t),o=typeof a==`function`?Q(a(),t):a;if(o&&nf(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var tf=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:ef(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Y()):t.$refStrategy===`seen`?Y():void 0}},nf=(e,t,n)=>(e.description&&(n.description=e.description),n),rf=e=>{let t=dd(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},af=(e,t)=>{let n=rf(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Q(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Y()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Q(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Y(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},of=Symbol.for(`vercel.ai.schema`);function sf(e,{validate:t}={}){return{[of]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function cf(e){return typeof e==`object`&&!!e&&of in e&&e[of]===!0&&`jsonSchema`in e&&`validate`in e}function lf(e){return e==null?sf({properties:{},additionalProperties:!1}):cf(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?mf(e):uf(e):e()}function uf(e){return sf(()=>sd(e[`~standard`].jsonSchema.input({target:`draft-07`})),{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new Tn({value:t,cause:n.issues})}}})}function df(e,t){let n=t?.useReferences??!1;return sf(()=>af(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function ff(e,t){let n=t?.useReferences??!1;return sf(()=>sd(Vs(e,{target:`draft-7`,io:`input`,reused:n?`ref`:`inline`})),{validate:async t=>{let n=await $s(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function pf(e){return`_zod`in e}function mf(e,t){return pf(e)?ff(e,t):df(e,t)}async function hf({value:e,schema:t,context:n}){let r=lf(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Tn.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:Tn.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function gf({text:e,schema:t}){try{let n=od(e);return t==null?{success:!0,value:n,rawValue:n}:await hf({value:n,schema:t})}catch(t){return{success:!1,error:yn.isInstance(t)?t:new yn({text:e,cause:t}),rawValue:void 0}}}async function _f(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var vf=Object.defineProperty,yf=(e,t)=>{for(var n in t)vf(e,n,{get:t[n],enumerable:!0})},bf=`AI_NoObjectGeneratedError`,xf=`vercel.ai.error.${bf}`,Sf=Symbol.for(xf),Cf,wf=class extends on{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:bf,message:e,cause:t}),this[Cf]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return on.hasMarker(e,xf)}};Cf=Sf;var Tf=F([M(),Ol(Uint8Array),Ol(ArrayBuffer),Tl(e=>globalThis.Buffer?.isBuffer(e)??!1,{message:`Must be a Buffer`})]),Ef=Cl(()=>F([Rc(),M(),Mc(),Ic(),Qc(M(),Ef.optional()),Wc(Ef)])),$=Qc(M(),Qc(M(),Ef.optional())),Df=P({type:I(`text`),text:M(),providerOptions:$.optional()}),Of=P({type:I(`image`),image:F([Tf,Ol(URL)]),mediaType:M().optional(),providerOptions:$.optional()}),kf=P({type:I(`file`),data:F([Tf,Ol(URL)]),filename:M().optional(),mediaType:M(),providerOptions:$.optional()}),Af=P({type:I(`reasoning`),text:M(),providerOptions:$.optional()}),jf=P({type:I(`tool-call`),toolCallId:M(),toolName:M(),input:Bc(),providerOptions:$.optional(),providerExecuted:Ic().optional()}),Mf=Jc(`type`,[P({type:I(`text`),value:M(),providerOptions:$.optional()}),P({type:I(`json`),value:Ef,providerOptions:$.optional()}),P({type:I(`execution-denied`),reason:M().optional(),providerOptions:$.optional()}),P({type:I(`error-text`),value:M(),providerOptions:$.optional()}),P({type:I(`error-json`),value:Ef,providerOptions:$.optional()}),P({type:I(`content`),value:Wc(F([P({type:I(`text`),text:M(),providerOptions:$.optional()}),P({type:I(`media`),data:M(),mediaType:M()}),P({type:I(`file-data`),data:M(),mediaType:M(),filename:M().optional(),providerOptions:$.optional()}),P({type:I(`file-url`),url:M(),providerOptions:$.optional()}),P({type:I(`file-id`),fileId:F([M(),Qc(M(),M())]),providerOptions:$.optional()}),P({type:I(`image-data`),data:M(),mediaType:M(),providerOptions:$.optional()}),P({type:I(`image-url`),url:M(),providerOptions:$.optional()}),P({type:I(`image-file-id`),fileId:F([M(),Qc(M(),M())]),providerOptions:$.optional()}),P({type:I(`custom`),providerOptions:$.optional()})]))})]),Nf=P({type:I(`tool-result`),toolCallId:M(),toolName:M(),output:Mf,providerOptions:$.optional()}),Pf=P({type:I(`tool-approval-request`),approvalId:M(),toolCallId:M()}),Ff=P({type:I(`tool-approval-response`),approvalId:M(),approved:Ic(),reason:M().optional()});F([P({role:I(`system`),content:M(),providerOptions:$.optional()}),P({role:I(`user`),content:F([M(),Wc(F([Df,Of,kf]))]),providerOptions:$.optional()}),P({role:I(`assistant`),content:F([M(),Wc(F([Df,kf,Af,jf,Nf,Pf]))]),providerOptions:$.optional()}),P({role:I(`tool`),content:Wc(F([Nf,Ff])),providerOptions:$.optional()})]),yf({},{array:()=>Bf,choice:()=>Vf,json:()=>Hf,object:()=>zf,text:()=>Rf});function If(e){let t=[`ROOT`],n=-1,r=null;function i(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`);break}}function a(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function o(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let s=0;s<e.length;s++){let c=e[s];switch(t[t.length-1]){case`ROOT`:i(c,s,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=s,t.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break}break;case`INSIDE_OBJECT_KEY`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(c){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:i(c,s,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:a(c,s);break;case`INSIDE_STRING`:switch(c){case`"`:t.pop(),n=s;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=s}break;case`INSIDE_ARRAY_START`:switch(c){case`]`:n=s,t.pop();break;default:n=s,i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(c){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=s,t.pop();break;default:n=s;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),n=s;break;case`INSIDE_NUMBER`:switch(c){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=s;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,s+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?a(c,s):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s)):n=s;break}}}let s=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:s+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:s+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:s+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?s+=`true`.slice(t.length):`false`.startsWith(t)?s+=`false`.slice(t.length):`null`.startsWith(t)&&(s+=`null`.slice(t.length))}}return s}async function Lf(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await gf({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await gf({text:If(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var Rf=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),zf=({schema:e,name:t,description:n})=>{let r=lf(e);return{name:`object`,responseFormat:_f(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await gf({text:e});if(!n.success)throw new wf({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await hf({value:n.value,schema:r});if(!i.success)throw new wf({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await Lf(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},Bf=({element:e,name:t,description:n})=>{let r=lf(e);return{name:`array`,responseFormat:_f(r.jsonSchema).then(e=>{let{$schema:r,...i}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{elements:{type:`array`,items:i}},required:[`elements`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:e},t){let n=await gf({text:e});if(!n.success)throw new wf({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=n.value;if(typeof i!=`object`||!i||!(`elements`in i)||!Array.isArray(i.elements))throw new wf({message:`No object generated: response did not match schema.`,cause:new Tn({value:i,cause:`response must be an object with an elements array`}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});for(let n of i.elements){let i=await hf({value:n,schema:r});if(!i.success)throw new wf({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason})}return i.elements},async parsePartialOutput({text:e}){let t=await Lf(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,i=[];for(let e of n){let t=await hf({value:e,schema:r});t.success&&i.push(t.value)}return{partial:i}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},n){if(t!=null)for(;e<t.length;e++)n.enqueue(t[e])}})}}},Vf=({options:e,name:t,description:n})=>({name:`choice`,responseFormat:Promise.resolve({type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await gf({text:t});if(!r.success)throw new wf({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new wf({message:`No object generated: response did not match schema.`,cause:new Tn({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await Lf(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),Hf=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await gf({text:e});if(!n.success)throw new wf({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await Lf(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});td({prefix:`aitxt`,size:24}),TransformStream,Qc(M(),Ef.optional());function Uf(e){return e.type.startsWith(`data-`)}td({prefix:`aitxt`,size:24}),Qc(M(),Ef.optional()),td({prefix:`aiobj`,size:24}),td({prefix:`aiobj`,size:24});var Wf=class{constructor(e,t={}){this._trackers=new Map,this._pending=[],this._closed=!1,this._writer=e,this._defaultClientId=t.clientId,this._defaultExtras=t.extras,this._onMessageHook=t.onMessage??(()=>{}),this._logger=t.logger?.withContext({component:`EncoderCore`})}async publishDiscrete(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.publishDiscrete();`,{name:e.name});let n=this._buildDiscreteMessage(e,t);return this._writer.publish(n)}async publishDiscreteBatch(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.publishDiscreteBatch();`,{count:e.length});let n=e.map(e=>this._buildDiscreteMessage(e,t,!0));return this._writer.publish(n)}async startStream(e,t,r){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.startStream();`,{name:t.name,streamId:e});let i=this._buildTransport(t.transportHeaders,r);i[f]=`true`,i[p]=`streaming`,i[ee]=e;let a=t.codecHeaders??{},o=this._resolveClientId(r),s={name:t.name,data:t.data,extras:{ai:this._aiExtras(i,a)},...o?{clientId:o}:{}};this._invokeOnMessage(s);let c=(await this._writer.publish(s)).serials[0];if(!c)throw new n.ErrorInfo(`unable to start stream; no serial returned for stream '${t.name}' (streamId: ${e})`,v.BadRequest,400);this._trackers.set(e,{serial:c,name:t.name,streamId:e,accumulated:t.data,persistentTransport:i,persistentCodec:a,cancelled:!1}),this._logger?.debug(`DefaultEncoderCore.startStream(); stream started`,{name:t.name,streamId:e,serial:c})}appendStream(e,t){this._assertNotClosed();let r=this._trackers.get(e);if(!r)throw new n.ErrorInfo(`unable to append to stream; no active stream for streamId '${e}'`,v.InvalidArgument,400);r.accumulated+=t;let i={serial:r.serial,data:t,extras:{ai:this._aiExtras({...r.persistentTransport},{...r.persistentCodec})}};this._invokeOnMessage(i);let a=this._writer.appendMessage(i);this._pending.push({promise:a,streamId:e})}async closeStream(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.closeStream();`,{streamId:e});let r=this._trackers.get(e);if(!r)throw new n.ErrorInfo(`unable to close stream; no active stream for streamId '${e}'`,v.InvalidArgument,400);r.accumulated+=t.data;let{transport:i,codec:a}=this._buildClosing(r,t);i[p]=`complete`;let o={serial:r.serial,data:t.data,extras:{ai:this._aiExtras(i,a)}};this._invokeOnMessage(o);let s=this._writer.appendMessage(o);this._pending.push({promise:s,streamId:e}),await this._flushPending(),this._logger?.debug(`DefaultEncoderCore.closeStream(); stream closed`,{streamId:e})}async cancelStream(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.cancelStream();`,{streamId:e});let r=this._trackers.get(e);if(!r)throw new n.ErrorInfo(`unable to cancel stream; no active stream for streamId '${e}'`,v.InvalidArgument,400);r.cancelled=!0;let{transport:i,codec:a}=this._buildClosing(r,void 0,t);i[p]=`cancelled`;let o={serial:r.serial,data:``,extras:{ai:this._aiExtras(i,a)}};this._invokeOnMessage(o);let s=this._writer.appendMessage(o);this._pending.push({promise:s,streamId:e}),await this._flushPending(),this._logger?.debug(`DefaultEncoderCore.cancelStream(); stream cancelled`,{streamId:e})}async cancelAllStreams(e){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.cancelAllStreams();`,{streamCount:this._trackers.size});for(let t of this._trackers.values()){t.cancelled=!0;let{transport:n,codec:r}=this._buildClosing(t,void 0,e);n[p]=`cancelled`;let i={serial:t.serial,data:``,extras:{ai:this._aiExtras(n,r)}};this._invokeOnMessage(i);let a=this._writer.appendMessage(i);this._pending.push({promise:a,streamId:t.streamId})}await this._flushPending()}async _flushPending(){if(this._flushPromise)return this._flushPromise;let e=this._pending;if(this._pending=[],e.length!==0){this._logger?.trace(`DefaultEncoderCore._flushPending();`,{count:e.length}),this._flushPromise=this._doFlush(e);try{await this._flushPromise}finally{this._flushPromise=void 0}}}async _doFlush(e){let t=await Promise.allSettled(e.map(async e=>e.promise)),r=new Set;for(let[n,i]of t.entries()){let t=e[n];t&&i.status===`rejected`&&r.add(t.streamId)}if(r.size===0){this._logger?.debug(`DefaultEncoderCore._flushPending(); all appends succeeded`);return}this._logger?.warn(`DefaultEncoderCore._flushPending(); recovering failed appends`,{failedStreams:[...r]});let i=[];for(let e of r){let t=this._trackers.get(e);if(!t)continue;let n=t.cancelled?`cancelled`:`complete`,r={serial:t.serial,data:t.accumulated,extras:{ai:this._aiExtras({...t.persistentTransport,[p]:n},{...t.persistentCodec})}};try{await this._writer.updateMessage(r)}catch(t){i.push({streamId:e,error:t})}}if(i.length>0){let e=i.map(e=>e.streamId).join(`, `);throw this._logger?.error(`DefaultEncoderCore._flushPending(); recovery failed`,{failedStreams:e}),new n.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${e}`,v.EncoderRecoveryFailed,500)}}async close(){if(!this._closed){this._logger?.trace(`DefaultEncoderCore.close();`),this._closed=!0;try{await this._flushPending()}finally{this._trackers.clear()}this._logger?.debug(`DefaultEncoderCore.close(); encoder closed`)}}_invokeOnMessage(e){try{this._onMessageHook(e)}catch(e){this._logger?.error(`DefaultEncoderCore._invokeOnMessage(); hook threw`,{error:e})}}_assertNotClosed(){if(this._closed)throw new n.ErrorInfo(`unable to write to encoder; encoder has been closed`,v.InvalidArgument,400)}_resolveClientId(e){return e?.clientId??this._defaultClientId}_buildTransport(e,t){let n={...Ee(this._defaultExtras?.headers,t?.extras?.headers),...e};return t?.messageId!==void 0&&(n[g]=t.messageId),n}_aiExtras(e,t){return Object.keys(t).length>0?{transport:e,codec:t}:{transport:e}}_buildDiscreteMessage(e,t,n=!1){let r=this._buildTransport(e.transportHeaders,t);r[f]=`false`,n&&(r[m]=`true`);let i=this._resolveClientId(t),a={name:e.name,data:e.data,extras:{ai:this._aiExtras(r,e.codecHeaders??{}),...e.ephemeral?{ephemeral:!0}:{}},...i?{clientId:i}:{}};return this._invokeOnMessage(a),a}_buildClosing(e,t,n){let r=Ee(this._defaultExtras?.headers,n?.extras?.headers);return{transport:{...e.persistentTransport,...r,...t?.transportHeaders},codec:{...e.persistentCodec,...t?.codecHeaders}}}},Gf=(e,t={})=>new Wf(e,t),Kf=class{constructor(e,t={}){this._cancelled=!1,this._core=Gf(e,t),this._messageId=t.messageId}async publishInput(e,t){switch(e.kind){case`user-message`:await this._publishUserMessage(e,t);return;case`regenerate`:await this._publishRegenerate(t);return;case`tool-result`:await this._publishToolResult(e,t);return;case`tool-result-error`:await this._publishToolResultError(e,t);return;case`tool-approval-response`:await this._publishToolApprovalResponse(e,t);return}}async publishOutput(e,t){await this._publishChunk(e,t)}async cancel(e){this._cancelled||(this._cancelled=!0,await this._core.cancelAllStreams(),await this._core.publishDiscrete({name:_,data:e??``,codecHeaders:b().str(`type`,`abort`).build(),transportHeaders:{[p]:`cancelled`}}))}async close(){await this._core.close()}async _publishChunk(e,t){switch(e.type){case`text-start`:{let n=b().str(`type`,`text`).str(`id`,e.id).json(`providerMetadata`,e.providerMetadata).build();await this._core.startStream(e.id,{name:_,data:``,codecHeaders:n},t);return}case`reasoning-start`:{let n=b().str(`type`,`reasoning`).str(`id`,e.id).json(`providerMetadata`,e.providerMetadata).build();await this._core.startStream(e.id,{name:_,data:``,codecHeaders:n},t);return}case`tool-input-start`:{let n=b().str(`type`,`tool-input`).str(`toolCallId`,e.toolCallId).str(`toolName`,e.toolName).bool(`dynamic`,e.dynamic).str(`title`,e.title).bool(`providerExecuted`,e.providerExecuted).json(`providerMetadata`,e.providerMetadata).build();await this._core.startStream(e.toolCallId,{name:_,data:``,codecHeaders:n},t);return}case`text-delta`:this._core.appendStream(e.id,e.delta);return;case`reasoning-delta`:this._core.appendStream(e.id,e.delta);return;case`tool-input-delta`:this._core.appendStream(e.toolCallId,e.inputTextDelta);return;case`text-end`:{let t=b().str(`type`,`text`).str(`id`,e.id).json(`providerMetadata`,e.providerMetadata).build();await this._core.closeStream(e.id,{name:_,data:``,codecHeaders:t});return}case`reasoning-end`:{let t=b().str(`type`,`reasoning`).str(`id`,e.id).json(`providerMetadata`,e.providerMetadata).build();await this._core.closeStream(e.id,{name:_,data:``,codecHeaders:t});return}case`tool-input-available`:try{let t=b().str(`type`,`tool-input`).str(`toolCallId`,e.toolCallId).str(`toolName`,e.toolName).json(`providerMetadata`,e.providerMetadata).build();await this._core.closeStream(e.toolCallId,{name:_,data:``,codecHeaders:t})}catch(t){if(!(t instanceof n.ErrorInfo&&pe(t,v.InvalidArgument)))throw t;let r=b().str(`type`,`tool-input`).str(`toolCallId`,e.toolCallId).str(`toolName`,e.toolName).bool(`dynamic`,e.dynamic).str(`title`,e.title).bool(`providerExecuted`,e.providerExecuted).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:_,data:e.input,codecHeaders:r})}return;case`start`:{let n=b().str(`type`,`start`).str(`messageId`,e.messageId??this._messageId).json(`messageMetadata`,e.messageMetadata).build();await this._core.publishDiscrete({name:_,data:``,codecHeaders:n},t);return}case`start-step`:{let e=b().str(`type`,`start-step`).build();await this._core.publishDiscrete({name:_,data:``,codecHeaders:e},t);return}case`finish-step`:{let e=b().str(`type`,`finish-step`).build();await this._core.publishDiscrete({name:_,data:``,codecHeaders:e},t);return}case`finish`:{let n=b().str(`type`,`finish`).str(`finishReason`,e.finishReason).json(`messageMetadata`,e.messageMetadata).build();await this._core.publishDiscrete({name:_,data:``,codecHeaders:n},t);return}case`error`:{let n=b().str(`type`,`error`).build();await this._core.publishDiscrete({name:_,data:e.errorText,codecHeaders:n},t);return}case`abort`:this._cancelled=!0,await this._core.cancelAllStreams(t),await this._core.publishDiscrete({name:_,data:e.reason??``,codecHeaders:b().str(`type`,`abort`).build(),transportHeaders:{[p]:`cancelled`}},t);return;case`message-metadata`:{let n=b().str(`type`,`message-metadata`).json(`messageMetadata`,e.messageMetadata).build();await this._core.publishDiscrete({name:_,data:``,codecHeaders:n},t);return}case`tool-input-error`:{let n=b().str(`type`,`tool-input-error`).str(`toolCallId`,e.toolCallId).str(`toolName`,e.toolName).bool(`dynamic`,e.dynamic).str(`title`,e.title).bool(`providerExecuted`,e.providerExecuted).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:_,data:{errorText:e.errorText,input:e.input},codecHeaders:n},t);return}case`tool-output-available`:case`tool-output-error`:case`tool-approval-request`:case`tool-output-denied`:await this._core.publishDiscrete(qf(e),t);return;case`file`:{let n=b().str(`type`,`file`).str(`mediaType`,e.mediaType).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:_,data:e.url,codecHeaders:n},t);return}case`source-url`:{let n=b().str(`type`,`source-url`).str(`sourceId`,e.sourceId).str(`title`,e.title).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:_,data:e.url,codecHeaders:n},t);return}case`source-document`:{let n=b().str(`type`,`source-document`).str(`sourceId`,e.sourceId).str(`mediaType`,e.mediaType).str(`title`,e.title).str(`filename`,e.filename).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:_,data:``,codecHeaders:n},t);return}default:if(e.type.startsWith(`data-`)){let n=e,r=b().str(`type`,n.type).str(`id`,n.id).bool(`transient`,n.transient).build(),i=n.transient===!0;await this._core.publishDiscrete({name:_,data:n.data,codecHeaders:r,ephemeral:i},t);return}throw new n.ErrorInfo(`unable to publish output; unsupported chunk type '${e.type}'`,v.InvalidArgument,400)}}async _publishUserMessage(e,t){let n=Jf(e.message);for(let e of n)e.transportHeaders={...e.transportHeaders,[ae]:`user`};await this._core.publishDiscreteBatch(n,t)}async _publishRegenerate(e){let t=b().str(`type`,`regenerate`).build();await this._core.publishDiscrete({name:fe,data:``,codecHeaders:t},e)}async _publishToolResult(e,t){let n=b().str(`type`,`tool-result`).str(`toolCallId`,e.payload.toolCallId).build();await this._core.publishDiscrete({name:fe,data:{output:e.payload.output},codecHeaders:n},t)}async _publishToolResultError(e,t){let n=b().str(`type`,`tool-result-error`).str(`toolCallId`,e.payload.toolCallId).build();await this._core.publishDiscrete({name:fe,data:{message:e.payload.message},codecHeaders:n},t)}async _publishToolApprovalResponse(e,t){let n=b().str(`type`,`tool-approval-response`).str(`toolCallId`,e.payload.toolCallId).bool(`approved`,e.payload.approved).str(`reason`,e.payload.reason).build();await this._core.publishDiscrete({name:fe,data:``,codecHeaders:n},t)}},qf=e=>{switch(e.type){case`tool-output-available`:{let t=b().str(`type`,`tool-output-available`).str(`toolCallId`,e.toolCallId).bool(`dynamic`,e.dynamic).bool(`providerExecuted`,e.providerExecuted).bool(`preliminary`,e.preliminary).build();return{name:_,data:{output:e.output},codecHeaders:t}}case`tool-output-error`:{let t=b().str(`type`,`tool-output-error`).str(`toolCallId`,e.toolCallId).bool(`dynamic`,e.dynamic).bool(`providerExecuted`,e.providerExecuted).build();return{name:_,data:{errorText:e.errorText},codecHeaders:t}}case`tool-approval-request`:return{name:_,data:``,codecHeaders:b().str(`type`,`tool-approval-request`).str(`toolCallId`,e.toolCallId).str(`approvalId`,e.approvalId).build()};case`tool-output-denied`:return{name:_,data:``,codecHeaders:b().str(`type`,`tool-output-denied`).str(`toolCallId`,e.toolCallId).build()}}},Jf=e=>{let t=e.id,n=[];for(let r of e.parts)switch(r.type){case`text`:n.push({name:fe,data:r.text,codecHeaders:b().str(`type`,`text`).str(`messageId`,t).build()});break;case`file`:n.push({name:fe,data:r.url,codecHeaders:b().str(`type`,`file`).str(`messageId`,t).str(`mediaType`,r.mediaType).build()});break;default:Uf(r)&&n.push({name:fe,data:r.data,codecHeaders:b().str(`type`,r.type).str(`messageId`,t).str(`id`,r.id).build()});break}return n.length===0&&n.push({name:fe,data:``,codecHeaders:b().str(`type`,`text`).str(`messageId`,t).build()}),n},Yf=(e,t={})=>new Kf(e,t),Xf=e=>y({type:`dynamic-tool`,toolCallId:e.toolCallId,toolName:e.toolName,title:e.title,providerExecuted:e.providerExecuted}),Zf=(e,t)=>{let n=Xf(e);switch(t.type){case`tool-output-available`:return y({...n,state:`output-available`,input:e.input,output:t.output,preliminary:t.preliminary});case`tool-output-error`:return{...n,state:`output-error`,input:e.input,errorText:t.errorText};case`tool-output-denied`:return{...n,state:`output-denied`,input:e.input,approval:{id:``,approved:!1}};case`tool-approval-request`:return{...n,state:`approval-requested`,input:e.input,approval:{id:t.approvalId}}}},Qf=()=>({messages:[],conflictSerials:new Map,trackers:new Map,pendingToolResolutions:[]}),$f=(e,t,n)=>{if(n.serial){let r=tp(t,n);if(r!==void 0){let t=e.conflictSerials.get(r);if(t!==void 0&&n.serial<=t)return e;e.conflictSerials.set(r,n.serial)}}if(ep(t))switch(t.kind){case`user-message`:np(e,t.message,n);break;case`regenerate`:break;case`tool-result`:rp(e,t,n);break;case`tool-result-error`:ip(e,t,n);break;case`tool-approval-response`:ap(e,t,n);break}else up(e,t,n);return e.pendingToolResolutions.length>0&&lp(e),e},ep=e=>`kind`in e,tp=(e,t)=>{if(ep(e))switch(e.kind){case`user-message`:return t.messageId===void 0?void 0:`user-msg:${t.messageId}`;case`tool-approval-response`:return`tool-approval:${e.payload.toolCallId}`;case`tool-result`:case`tool-result-error`:return`tool-output:${e.payload.toolCallId}`;case`regenerate`:return}switch(e.type){case`tool-input-start`:case`tool-input-available`:case`tool-input-error`:return`${e.type}:${e.toolCallId}`;case`tool-output-available`:case`tool-output-error`:case`tool-output-denied`:case`tool-approval-request`:return`tool-output:${e.toolCallId}`;case`text-start`:case`text-end`:case`reasoning-start`:case`reasoning-end`:return`${e.type}:${t.messageId??``}:${e.id}`;case`finish`:case`message-metadata`:return`${e.type}:${t.messageId??``}`;default:return}},np=(e,t,n)=>{let r=n.messageId;if(r===void 0)return e.messages.push({codecMessageId:t.id,message:t}),e;let i=e.messages.findIndex(e=>e.codecMessageId===r);return i===-1?e.messages.push({codecMessageId:r,message:t}):e.messages[i]={codecMessageId:r,message:t},e},rp=(e,t,n)=>{let{toolCallId:r,output:i}=t.payload,a=op(e,t.codecMessageId,r);return a?(a.message.parts[a.tracker.partIndex]=Zf(a.part,{type:`tool-output-available`,toolCallId:r,output:i}),e):(e.pendingToolResolutions.push({targetCodecMessageId:t.codecMessageId,toolCallId:r,serial:n.serial,resolution:{kind:`tool-result`,output:i}}),e)},ip=(e,t,n)=>{let{toolCallId:r,message:i}=t.payload,a=op(e,t.codecMessageId,r);return a?(a.message.parts[a.tracker.partIndex]=Zf(a.part,{type:`tool-output-error`,toolCallId:r,errorText:i}),e):(e.pendingToolResolutions.push({targetCodecMessageId:t.codecMessageId,toolCallId:r,serial:n.serial,resolution:{kind:`tool-result-error`,message:i}}),e)},ap=(e,t,n)=>{let{toolCallId:r,approved:i,reason:a}=t.payload,o=op(e,t.codecMessageId,r);return o?(o.message.parts[o.tracker.partIndex]=cp(o.part,i,a),e):(e.pendingToolResolutions.push({targetCodecMessageId:t.codecMessageId,toolCallId:r,serial:n.serial,resolution:{kind:`tool-approval-response`,approved:i,...a===void 0?{}:{reason:a}}}),e)},op=(e,t,n)=>{let r=e.messages.find(e=>e.codecMessageId===t);if(!r)return;let i=fp(e,t),a=pp(r.message,i,n);if(a)return{message:r.message,tracker:a.tracker,part:a.part}},sp=(e,t)=>{for(let n of e.messages){let r=e.trackers.get(n.codecMessageId);if(!r)continue;let i=pp(n.message,r,t);if(i)return{message:n.message,tracker:i.tracker,part:i.part}}},cp=(e,t,n)=>t?{...Xf(e),state:`approval-responded`,input:`input`in e?e.input:void 0,approval:{id:`approval`in e&&e.approval?e.approval.id:``,approved:!0,...n===void 0?{}:{reason:n}}}:Zf(e,{type:`tool-output-denied`,toolCallId:e.toolCallId,...n===void 0?{}:{reason:n}}),lp=e=>{let t=[];for(let n of e.pendingToolResolutions){let r=op(e,n.targetCodecMessageId,n.toolCallId);if(!r){t.push(n);continue}switch(n.resolution.kind){case`tool-result`:r.message.parts[r.tracker.partIndex]=Zf(r.part,{type:`tool-output-available`,toolCallId:n.toolCallId,output:n.resolution.output});break;case`tool-result-error`:r.message.parts[r.tracker.partIndex]=Zf(r.part,{type:`tool-output-error`,toolCallId:n.toolCallId,errorText:n.resolution.message});break;case`tool-approval-response`:r.message.parts[r.tracker.partIndex]=cp(r.part,n.resolution.approved,n.resolution.reason);break}}e.pendingToolResolutions=t},up=(e,t,n)=>{let r=n.messageId;if(r===void 0)return e;switch(t.type){case`start`:case`start-step`:case`finish-step`:case`finish`:case`abort`:case`error`:case`message-metadata`:return mp(e,t,r);case`text-start`:case`text-delta`:case`text-end`:case`reasoning-start`:case`reasoning-delta`:case`reasoning-end`:return hp(e,t,r);case`tool-input-start`:case`tool-input-delta`:case`tool-input-available`:case`tool-input-error`:return gp(e,t,r);case`tool-output-available`:case`tool-output-error`:case`tool-output-denied`:case`tool-approval-request`:return _p(e,t,r);case`file`:case`source-url`:case`source-document`:return vp(e,t,r);default:return t.type.startsWith(`data-`)?yp(e,t,r):e}},dp=(e,t)=>{let n=e.messages.find(e=>e.codecMessageId===t);return n||(n={codecMessageId:t,message:{id:t,role:`assistant`,parts:[]}},e.messages.push(n)),n.message},fp=(e,t)=>{let n=e.trackers.get(t);return n||(n={text:new Map,reasoning:new Map,tools:new Map},e.trackers.set(t,n)),n},pp=(e,t,n)=>{let r=t.tools.get(n);if(!r)return;let i=e.parts[r.partIndex];if(i?.type===`dynamic-tool`)return{tracker:r,part:i}},mp=(e,t,n)=>{switch(t.type){case`start`:{let r=dp(e,n);return t.messageId!==void 0&&(r.id=t.messageId),t.messageMetadata!==void 0&&(r.metadata=t.messageMetadata),e}case`start-step`:return dp(e,n).parts.push({type:`step-start`}),e;case`finish-step`:{let t=e.trackers.get(n);return t&&(t.text.clear(),t.reasoning.clear()),e}case`finish`:{let r=e.messages.find(e=>e.codecMessageId===n)?.message;return r&&t.messageMetadata!==void 0&&(r.metadata=t.messageMetadata),e}case`abort`:case`error`:return e;case`message-metadata`:{let r=e.messages.find(e=>e.codecMessageId===n)?.message;return r&&t.messageMetadata!==void 0&&(r.metadata=t.messageMetadata),e}}},hp=(e,t,n)=>{let r=dp(e,n),i=fp(e,n),a=t.type.startsWith(`text-`),o=a?`text`:`reasoning`,s=a?i.text:i.reasoning;switch(t.type){case`text-start`:case`reasoning-start`:return s.set(t.id,r.parts.length),r.parts.push({type:o,text:``}),e;case`text-delta`:case`reasoning-delta`:{let n=s.get(t.id);if(n===void 0)return e;let i=r.parts[n];return i?.type===o&&(i.text+=t.delta),e}case`text-end`:case`reasoning-end`:return s.delete(t.id),e}},gp=(e,t,n)=>{let r=dp(e,n),i=fp(e,n);switch(t.type){case`tool-input-start`:{let n=r.parts.length;return r.parts.push({...Xf(t),state:`input-streaming`,input:void 0}),i.tools.set(t.toolCallId,{partIndex:n,inputText:``}),e}case`tool-input-delta`:{let n=i.tools.get(t.toolCallId);if(!n)return e;n.inputText+=t.inputTextDelta;let a;try{a=JSON.parse(n.inputText)}catch{a=void 0}let o=pp(r,i,t.toolCallId);return o&&(r.parts[o.tracker.partIndex]={...Xf(o.part),state:`input-streaming`,input:a}),e}case`tool-input-available`:{let n=pp(r,i,t.toolCallId);return n&&(r.parts[n.tracker.partIndex]={...Xf(n.part),state:`input-available`,input:t.input}),e}case`tool-input-error`:{let n=pp(r,i,t.toolCallId);if(n)r.parts[n.tracker.partIndex]={...Xf(n.part),state:`output-error`,input:t.input,errorText:t.errorText};else{let e=r.parts.length;r.parts.push({...Xf(t),state:`output-error`,input:t.input,errorText:t.errorText}),i.tools.set(t.toolCallId,{partIndex:e,inputText:``})}return e}}},_p=(e,t,n)=>{if(t.type===`tool-output-available`||t.type===`tool-output-error`){let n=sp(e,t.toolCallId);return n&&(n.message.parts[n.tracker.partIndex]=Zf(n.part,t)),e}let r=dp(e,n),i=pp(r,fp(e,n),t.toolCallId);return i&&(r.parts[i.tracker.partIndex]=Zf(i.part,t)),e},vp=(e,t,n)=>{let r=dp(e,n);switch(t.type){case`file`:return r.parts.push({type:`file`,mediaType:t.mediaType,url:t.url}),e;case`source-url`:return r.parts.push(y({type:`source-url`,sourceId:t.sourceId,url:t.url,title:t.title})),e;case`source-document`:return r.parts.push(y({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title,filename:t.filename})),e}},yp=(e,t,n)=>{if(t.transient)return e;let r=dp(e,n),i=y({type:t.type,id:t.id,data:t.data});if(t.id!==void 0){let n=r.parts.findIndex(e=>e.type===t.type&&`id`in e&&e.id===t.id);if(n!==-1)return r.parts[n]=i,e}return r.parts.push(i),e},bp={adapterTag:`vercel-ai-sdk-ui-message`,init:Qf,fold:$f,createEncoder:Yf,createDecoder:en,getMessages:e=>e.messages,createUserMessage:e=>({kind:`user-message`,message:e}),createRegenerate:(e,t)=>({kind:`regenerate`,target:e,parent:t}),createToolResult:(e,t)=>({kind:`tool-result`,codecMessageId:e,payload:t}),createToolResultError:(e,t)=>({kind:`tool-result-error`,codecMessageId:e,payload:t}),createToolApprovalResponse:(e,t)=>({kind:`tool-approval-response`,codecMessageId:e,payload:t})},xp=e=>e.type===`finish`||e.type===`error`||e.type===`abort`,Sp=(e,t,r)=>{let i={},a=[],o=new ReadableStream({start:e=>{i.controller=e},cancel:()=>{u()}}),{controller:s}=i;if(!s)throw new n.ErrorInfo(`unable to create run stream; ReadableStream start() was not called synchronously`,v.SessionSubscriptionError,500);let c;t.then(e=>{c=e},()=>{});let l=!1,u=()=>{for(let e of a)e();a.length=0},d=e=>{if(!l){l=!0;try{e()}catch{}u()}},f=()=>{d(()=>{s.close()})},p=e=>{d(()=>{s.error(e)})};return a.push(e.tree.on(`output`,e=>{if(e.inputCodecMessageId===r)for(let t of e.events){try{s.enqueue(t)}catch{f();return}if(xp(t)){f();return}}}),e.tree.on(`run`,e=>{e.type===`end`&&c!==void 0&&e.runId===c&&f()}),e.on(`error`,e=>{p(e)})),{stream:o,close:f,error:p}},Cp=e=>{let t,n=new Promise(e=>{t=e}),r=new TransformStream({flush:()=>{t()}}),i=new AbortController;return e.pipeTo(r.writable,{signal:i.signal,preventCancel:!0}).catch(()=>{t()}),{stream:r.readable,done:n,fail:e=>{i.abort(e)}}},wp=e=>(e.type===`dynamic-tool`||e.type.startsWith(`tool-`))&&`toolCallId`in e&&`state`in e,Tp=e=>e.role===`assistant`&&e.parts.some(e=>wp(e)&&(e.state===`input-streaming`||e.state===`input-available`||e.state===`approval-requested`)),Ep=new Set([`input-streaming`,`input-available`,`approval-requested`]),Dp=(e,t)=>{let n=[];for(let r of t){if(r.role!==`assistant`)continue;let t=e.find(e=>e.message.id===r.id);if(!t)continue;let{codecMessageId:i,message:a}=t;for(let e of r.parts){if(!wp(e))continue;let t=a.parts.find(t=>wp(t)&&t.toolCallId===e.toolCallId);if(e.state===`approval-responded`&&(!t||t.state===`approval-requested`)){n.push(bp.createToolApprovalResponse(i,{toolCallId:e.toolCallId,approved:e.approval.approved,...e.approval.reason===void 0?{}:{reason:e.approval.reason}}));continue}e.state!==`output-available`&&e.state!==`output-error`||t&&!Ep.has(t.state)||(e.state===`output-available`?n.push(bp.createToolResult(i,{toolCallId:e.toolCallId,output:e.output})):n.push(bp.createToolResultError(i,{toolCallId:e.toolCallId,message:e.errorText})))}}return n},Op=(e,t)=>{let n=e.findIndex(e=>e.message.id===t);if(!(n<=0))return e[n-1]?.codecMessageId},kp=(e,t)=>{let r=t?.api??`/api/chat`,i=t?.fetch??globalThis.fetch.bind(globalThis),a=t?.credentials,o=!1,s=new ge(ye({logLevel:_e.Silent})),c=e=>{o=e,s.emit(`streaming`,e)};return{sendMessages:async o=>{let{messages:s,abortSignal:l,trigger:u,messageId:d}=o,f=e.view.getMessages(),p=new Map(f.map(e=>[e.message.id,e.codecMessageId])),ee=e=>p.get(e),m=s.at(-1),h=!!m&&p.has(m.id),te=u===`submit-message`&&m?.role===`assistant`&&h,ne=u===`submit-message`&&!d&&m?.role===`user`?s.at(-2):void 0,g=ne&&Tp(ne)&&p.has(ne.id)?ne.id:void 0,re,ie;if(u===`regenerate-message`||te)re=[],ie=s;else{if(s.length===0)throw new n.ErrorInfo(`unable to send messages; messages array is empty for submit-message trigger`,v.InvalidArgument,400);re=[s.at(-1)],ie=g?s.slice(0,-2):s.slice(0,-1)}let ae,oe;u===`submit-message`&&d&&!te?(ae=ee(d),oe=Op(f,d)):g&&(ae=ee(g),oe=Op(f,g));let se,ce;if(t?.prepareSendMessagesRequest){let e=t.prepareSendMessagesRequest({chatId:o.chatId,trigger:u,messageId:d,history:ie,messages:re,forkOf:ae,parent:oe});se=e.body??{},ce=e.headers}else se={},ce=void 0;let le={};if(ae!==void 0&&(le.forkOf=ae),oe!==void 0&&(le.parent=oe),te){let t=ee(m.id),n=t===void 0?void 0:e.view.runOf(t);n&&(le.runId=n.runId)}let ue;if(te){let t=Dp(f,s);ue=await e.view.send(t,le)}else if(u===`regenerate-message`){if(d===void 0)throw new n.ErrorInfo(`unable to regenerate; regenerate-message trigger fired without messageId`,v.InvalidArgument,400);let t=ee(d);if(t===void 0)throw new n.ErrorInfo(`unable to regenerate; message not visible: ${d}`,v.InvalidArgument,400);ue=await e.view.regenerate(t,le)}else{let t=re.map(e=>bp.createUserMessage(e));ue=await e.view.send(t,le)}let de=Sp(e,ue.runId,ue.inputCodecMessageId);if(l){let e=()=>{ue.cancel(),de.close()};l.aborted?e():l.addEventListener(`abort`,e,{once:!0})}let{stream:_,done:fe,fail:pe}=Cp(de.stream);c(!0),fe.then(()=>{c(!1)});let me={...se,...ue.toInvocation().toJSON()};return i(r,{method:`POST`,headers:{"Content-Type":`application/json`,...ce},body:JSON.stringify(me),...a?{credentials:a}:{}}).then(e=>{e.ok||pe(new n.ErrorInfo(`unable to send; HTTP POST to ${r} returned ${String(e.status)} ${e.statusText}`,v.SessionSendFailed,e.status))}).catch(e=>{let t=e instanceof n.ErrorInfo?e:void 0;pe(new n.ErrorInfo(`unable to send; HTTP POST to ${r} failed: ${e instanceof Error?e.message:String(e)}`,v.SessionSendFailed,500,t))}),_},reconnectToStream:()=>Promise.resolve(null),close:async()=>e.close(),get streaming(){return o},onStreamingChange:e=>(s.on(`streaming`,e),()=>{s.off(`streaming`,e)})}},Ap=(0,t.createContext)({nearest:void 0,providers:{}}),{ClientSessionProvider:jp,useAblyMessages:Mp,useClientSession:Np,useCreateView:Pp,useTree:Fp,useView:Ip}=ft(),Lp=({channelName:e,chatTransportOptions:n,children:r})=>{let{session:a,sessionError:o}=Np(),{providers:s}=(0,t.useContext)(Ap),c=(0,t.useMemo)(()=>kp(a,n),[a,n]),l=(0,t.useMemo)(()=>{let t={session:a,sessionError:o,chatTransport:c};return{nearest:t,providers:{...s,[e]:t}}},[e,s,c,a,o]);return(0,i.jsx)(Ap.Provider,{value:l,children:r})},Rp=({api:e,credentials:n,fetch:r,chatOptions:a,children:o,...s})=>{let c=(0,t.useMemo)(()=>({...a,...e!==void 0&&{api:e},...n!==void 0&&{credentials:n},...r!==void 0&&{fetch:r}}),[e,n,r,a]);return(0,i.jsx)(jp,{...s,codec:bp,children:(0,i.jsx)(Lp,{channelName:s.channelName,chatTransportOptions:c,children:o})})},zp={get tree(){throw new n.ErrorInfo(`unable to access tree; hook is skipped`,v.InvalidArgument,400)},get view(){throw new n.ErrorInfo(`unable to access view; hook is skipped`,v.InvalidArgument,400)},connect:()=>{throw new n.ErrorInfo(`unable to connect; hook is skipped`,v.InvalidArgument,400)},createView:()=>{throw new n.ErrorInfo(`unable to create view; hook is skipped`,v.InvalidArgument,400)},cancel:()=>{throw new n.ErrorInfo(`unable to cancel; hook is skipped`,v.InvalidArgument,400)},on:()=>{throw new n.ErrorInfo(`unable to subscribe; hook is skipped`,v.InvalidArgument,400)},close:()=>{throw new n.ErrorInfo(`unable to close; hook is skipped`,v.InvalidArgument,400)}},Bp={sendMessages:()=>{throw new n.ErrorInfo(`unable to send messages; hook is skipped`,v.InvalidArgument,400)},reconnectToStream:()=>{throw new n.ErrorInfo(`unable to reconnect to stream; hook is skipped`,v.InvalidArgument,400)},close:()=>{throw new n.ErrorInfo(`unable to close; hook is skipped`,v.InvalidArgument,400)},get streaming(){throw new n.ErrorInfo(`unable to access streaming; hook is skipped`,v.InvalidArgument,400)},onStreamingChange:()=>{throw new n.ErrorInfo(`unable to subscribe to streaming changes; hook is skipped`,v.InvalidArgument,400)}},Vp=({channelName:e,skip:r}={})=>{let{nearest:i,providers:a}=(0,t.useContext)(Ap);if(r)return{session:zp,chatTransport:Bp};if(e!==void 0){let t=a[e];return t?{session:t.session,chatTransport:t.chatTransport,sessionError:t.sessionError}:{session:zp,chatTransport:Bp,sessionError:new n.ErrorInfo(`unable to use client session; no ClientSessionProvider found for channelName "${e}"`,v.BadRequest,400),chatTransportError:new n.ErrorInfo(`unable to use chat transport; no ChatTransportProvider found for channelName "${e}"`,v.BadRequest,400)}}return i?{session:i.session,chatTransport:i.chatTransport,sessionError:i.sessionError}:{session:zp,chatTransport:Bp,sessionError:new n.ErrorInfo(`unable to use session; no ClientSessionProvider found in the tree`,v.BadRequest,400),chatTransportError:new n.ErrorInfo(`unable to use chat transport; no ChatTransportProvider found in the tree`,v.BadRequest,400)}},Hp=new Set([`output-available`,`output-error`,`approval-responded`,`output-denied`]),Up=e=>(e.type===`dynamic-tool`||e.type.startsWith(`tool-`))&&`toolCallId`in e&&`state`in e,Wp=(e,t)=>{let n=new Map;for(let e of t.parts)Up(e)&&n.set(e.toolCallId,e);if(n.size===0)return e;let r=e.parts.map(e=>{if(!Up(e)||Hp.has(e.state))return e;let t=n.get(e.toolCallId);return!t||!Hp.has(t.state)?e:{...t,type:e.type}});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e},Gp=(e,t)=>{if(t.length===0)return e;let n=new Map(t.map(e=>[e.id,e]));return e.map(e=>{if(e.role!==`assistant`)return e;let t=n.get(e.id);return t?Wp(e,t):e})};e.ChatTransportProvider=Rp,e.ClientSessionProvider=jp,e.useAblyMessages=Mp,e.useChatTransport=Vp,e.useClientSession=Np,e.useCreateView=Pp,e.useMessageSync=({setMessages:e,channelName:n,skip:r})=>{let{session:i,chatTransport:a,chatTransportError:o}=Vp({channelName:n,skip:r}),s=!r&&!o,c=s?i.view:void 0,l=s?a:void 0,[u,d]=(0,t.useState)(!1);(0,t.useEffect)(()=>{if(!l){d(!1);return}return d(l.streaming),l.onStreamingChange(d)},[l]),(0,t.useEffect)(()=>{if(!c||u)return;let t=()=>{e(e=>Gp(c.getMessages().map(e=>e.message),e))};return t(),c.on(`update`,t)},[c,e,u])},e.useTree=Fp,e.useView=Ip});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`react`),require(`ably`),require(`ably/react`),require(`react/jsx-runtime`)):typeof define==`function`&&define.amd?define([`exports`,`react`,`ably`,`ably/react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.AblyAiTransportVercelReact={},e.React,e.Ably,e.AblyReact,e.ReactJsxRuntime))})(this,function(e,t,n,r,i){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var a=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,c=Object.getOwnPropertyNames,l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=c(t),a=0,l=i.length,d;a<l;a++)d=i[a],!u.call(e,d)&&d!==n&&o(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=s(t,d))||r.enumerable});return e};n=((e,t,n)=>(n=e==null?{}:a(l(e)),d(t||!e||!e.__esModule?o(n,`default`,{value:e,enumerable:!0}):n,e)))(n,1);var f=[`PUBLISH`,`SUBSCRIBE`,`PRESENCE`,`PRESENCE_SUBSCRIBE`,`ANNOTATION_PUBLISH`],p=[`PUBLISH`,`SUBSCRIBE`,`PRESENCE`,`PRESENCE_SUBSCRIBE`,`OBJECT_PUBLISH`,`OBJECT_SUBSCRIBE`,`ANNOTATION_PUBLISH`,`ANNOTATION_SUBSCRIBE`],m=e=>{if(e===void 0||e.length===0)return;let t=new Set([...f,...e]),n=p.filter(e=>t.has(e)),r=[...t].filter(e=>!p.includes(e)).toSorted();return[...n,...r]},h=`0.3.0`,g=`ai-transport-js`,_=(e,t)=>{let n=e;return n.options.agents={...n.options.agents,...t},{params:{agent:y(t)}}},v=e=>{let t=e?.adapterTag,n={[g]:h};return t&&(n[t]=h),n},y=e=>Object.entries(e).map(([e,t])=>`${e}/${t}`).join(` `),b=e=>y(v(e)),ee=(e,t)=>_(e,v(t)),x=`stream`,S=`status`,te=`stream-id`,ne=`discrete`,C=`run-id`,w=`invocation-id`,T=`event-id`,E=`codec-message-id`,re=`run-client-id`,ie=`input-client-id`,ae=`role`,D=`parent`,oe=`fork-of`,se=`msg-regenerate`,ce=`input-codec-message-id`,le=`error-code`,ue=`ai-cancel`,de=`ai-output`,fe=`ai-input`,O=function(e){return e[e.BadRequest=4e4]=`BadRequest`,e[e.InvalidArgument=40003]=`InvalidArgument`,e[e.InsufficientCapability=40160]=`InsufficientCapability`,e[e.EncoderRecoveryFailed=104e3]=`EncoderRecoveryFailed`,e[e.SessionSubscriptionError=104001]=`SessionSubscriptionError`,e[e.CancelListenerError=104002]=`CancelListenerError`,e[e.RunLifecycleError=104003]=`RunLifecycleError`,e[e.SessionClosed=104004]=`SessionClosed`,e[e.SessionSendFailed=104005]=`SessionSendFailed`,e[e.ChannelContinuityLost=104006]=`ChannelContinuityLost`,e[e.ChannelNotReady=104007]=`ChannelNotReady`,e[e.StreamError=104008]=`StreamError`,e[e.InputEventNotFound=104010]=`InputEventNotFound`,e[e.HistoryFetchFailed=104011]=`HistoryFetchFailed`,e}({}),pe=(e,t)=>e.code===t,me=e=>({logAction:(t,n,r)=>{e.error(n,{detail:r})},shouldLog:()=>!0}),he=n.Realtime.EventEmitter,ge=class extends he{constructor(e){super(me(e))}},_e=function(e){return e.Trace=`trace`,e.Debug=`debug`,e.Info=`info`,e.Warn=`warn`,e.Error=`error`,e.Silent=`silent`,e}({}),ve=(e,t,n)=>{let r=n?`, context: ${JSON.stringify(n)}`:``,i=`[${new Date().toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;switch(t){case`trace`:case`debug`:console.log(i);break;case`info`:console.info(i);break;case`warn`:console.warn(i);break;case`error`:console.error(i);break;case`silent`:break}},ye=e=>new xe(e.logHandler??ve,e.logLevel),be=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4],[`silent`,5]]),xe=class e{constructor(e,t,r){this._handler=e,this._context=r;let i=be.get(t);if(i===void 0)throw new n.ErrorInfo(`unable to create logger; invalid log level: ${t}`,O.InvalidArgument,400);this._levelNumber=i}trace(e,t){this._write(e,`trace`,0,t)}debug(e,t){this._write(e,`debug`,1,t)}info(e,t){this._write(e,`info`,2,t)}warn(e,t){this._write(e,`warn`,3,t)}error(e,t){this._write(e,`error`,4,t)}withContext(t){let n=[...be.entries()].find(([,e])=>e===this._levelNumber)?.[0]??`error`;return new e(this._handler,n,this._mergeContext(t))}_write(e,t,n,r){n>=this._levelNumber&&this._handler(e,t,this._mergeContext(r))}_mergeContext(e){return this._context?e?{...this._context,...e}:this._context:e??void 0}},k=e=>e instanceof Error?e.message:String(e),A=e=>e instanceof n.ErrorInfo?e:void 0,Se=(e,t)=>{let n=e.extras;if(!n||typeof n!=`object`)return{};let r=n.ai;if(!r||typeof r!=`object`)return{};let i=r[t];return!i||typeof i!=`object`?{}:i},j=e=>Se(e,`transport`),Ce=e=>Se(e,`codec`),we=e=>{if(e!==void 0)try{return JSON.parse(e)}catch{return}},Te=e=>{if(e)try{return JSON.parse(e)}catch{return e}},Ee=(e,t)=>({...e,...t}),De=e=>{if(e!==void 0)return e===`true`},M=e=>{let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==void 0&&(t[n]=e[n]);return t},Oe=e=>{let t={[ae]:e.role,[E]:e.codecMessageId};return e.runId!==void 0&&(t[C]=e.runId),e.runClientId!==void 0&&(t[re]=e.runClientId),e.parent&&(t[D]=e.parent),e.forkOf&&(t[oe]=e.forkOf),e.regenerates&&(t[se]=e.regenerates),e.invocationId&&(t[w]=e.invocationId),e.inputClientId!==void 0&&(t[ie]=e.inputClientId),e.inputCodecMessageId!==void 0&&(t[ce]=e.inputCodecMessageId),e.inputEventId&&(t[T]=e.inputEventId),t},ke=e=>e===`ai-run-start`||e===`ai-run-suspend`||e===`ai-run-resume`||e===`ai-run-end`,Ae=e=>{let t=e[le],r=t===void 0?NaN:Number(t),i=Number.isFinite(r)?r:O.SessionSubscriptionError,a=e[`error-message`]??`agent reported an error`,o=i>=1e4&&i<6e4?Math.floor(i/100):500;return new n.ErrorInfo(a,i,o)},je=(e,t,n,r)=>{let i=t[C];if(!i)return;let a=t[`run-client-id`]??``,o=r===void 0?{}:{timestamp:r};if(e===`ai-run-start`){let e=t[D],r=t[oe],s=t[se];return{type:`start`,runId:i,clientId:a,serial:n,invocationId:t[`invocation-id`]??``,...o,...e!==void 0&&{parent:e},...r!==void 0&&{forkOf:r},...s!==void 0&&{regenerates:s}}}if(e===`ai-run-suspend`)return{type:`suspend`,runId:i,clientId:a,serial:n,invocationId:t[`invocation-id`]??``,...o};if(e===`ai-run-resume`)return{type:`resume`,runId:i,clientId:a,serial:n,invocationId:t[`invocation-id`]??``,...o};if(e===`ai-run-end`){let e=t[`run-reason`]??`complete`,r=t[`invocation-id`]??``;return e===`error`?{type:`end`,runId:i,clientId:a,serial:n,invocationId:r,reason:e,...o,error:Ae(t)}:{type:`end`,runId:i,clientId:a,serial:n,invocationId:r,reason:e,...o}}},Me=(e,t,n)=>{let r=j(n),i=n.serial,a=n.timestamp;if(ke(n.name)){let t=je(n.name,r,i,a);return t&&e.applyRunLifecycle(t),t}let{inputs:o,outputs:s}=t.decode(n);(o.length>0||s.length>0||r[`run-id`])&&e.applyMessage({inputs:o,outputs:s},r,i,a,n.version.serial)},Ne=(e,t)=>({apply:n=>Me(e,t,n)}),Pe=class e{constructor(e){this.inputEventId=e.inputEventId,this.sessionName=e.sessionName}static fromJSON(t){return new e(t)}toJSON(){return{inputEventId:this.inputEventId,sessionName:this.sessionName}}},Fe=async(e,t)=>{if(!e)throw new n.ErrorInfo(`unable to ${t}; connect() must be called before ${t}()`,O.InvalidArgument,400);return e},Ie=async(e,t,n,r)=>{if(t!==void 0)try{await e.detach()}catch(e){n?.debug(`${r}.close(); channel detach failed`,{error:e})}},Le=e=>{let{current:t,resumed:n}=e;return t===`failed`||t===`suspended`||t===`detached`||t===`attached`&&!n},Re=(e,t)=>{let{current:r}=e;return new n.ErrorInfo(`unable to ${t}; channel continuity lost (${r}${r===`attached`?`, resumed: false`:``})`,O.ChannelContinuityLost,500,e.reason)},ze=e=>[...e.inputs.map(e=>({direction:`input`,event:e})),...e.outputs.map(e=>({direction:`output`,event:e}))],Be=class{constructor(){this._entries=[],this._swept=!1}get swept(){return this._swept}record(e,t,n,r,i){let a=this._recordEntry(e,t,this._swept?[]:n,r,i);return a===void 0?`dropped`:this._swept||a===this._entries.length-1?`incremental`:`refold`}replay(e){for(let t of this._entries)for(let n of t.events)e(n,t.serial,t.messageId)}sweep(){this._swept=!0;for(let e of this._entries)e.events.length=0}_recordEntry(e,t,n,r,i){for(let a=this._entries.length-1;a>=0;a--){let o=this._entries[a];if(!o)break;if(o.serial===e)return r!==void 0&&(r<=o.decodedThrough||!i)?void 0:(o.events.push(...n),r!==void 0&&(o.decodedThrough=r),a);if(o.serial<e)return this._entries.splice(a+1,0,{serial:e,messageId:t,events:[...n],decodedThrough:r??e}),a+1}return this._entries.unshift({serial:e,messageId:t,events:[...n],decodedThrough:r??e}),0}},N=e=>e.kind===`run`?e.runId:e.codecMessageId,Ve=e=>e.kind===`run`?e.startSerial:e.serial,He=(e,t,n)=>{let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)},Ue=(e,t,n)=>{let r=e.get(t);r&&(r.delete(n),r.size===0&&e.delete(t))},We=class{constructor(e,t){this._nodeIndex=new Map,this._codecMessageIdToNodeKey=new Map,this._sortedNodes=[],this._parentIndex=new Map,this._replyRunsByInput=new Map,this._seqCounter=0,this._structuralVersion=0,this._siblingCache=new Map,this._siblingCacheVersion=-1,this._eventIdIndex=new Map,this._clock=0,this._sweepQueue=[],this._codec=e,this._logger=t,this._emitter=new ge(t)}_compareNodes(e,t){let n=Ve(e.node),r=Ve(t.node);return n===void 0&&r===void 0?e.insertSeq-t.insertSeq:n===void 0?1:r===void 0||n<r?-1:n>r?1:e.insertSeq-t.insertSeq}_insertSortedNode(e){if(Ve(e.node)===void 0){this._sortedNodes.push(e);return}let t=0,n=this._sortedNodes.length;for(;t<n;){let r=t+n>>>1,i=this._sortedNodes[r];if(!i)break;this._compareNodes(i,e)<=0?t=r+1:n=r}this._sortedNodes.splice(t,0,e)}_removeSortedNode(e){let t=this._sortedNodes.indexOf(e);t!==-1&&this._sortedNodes.splice(t,1)}_insertNode(e,t,n){this._nodeIndex.set(e,t),this._addToParentIndex(n,e),this._insertSortedNode(t),this._structuralVersion++}_promoteSerial(e){this._removeSortedNode(e),this._insertSortedNode(e),this._structuralVersion++}_foldInto(e,t,n,r){for(let i of t)try{e.node.projection=this._codec.fold(e.node.projection,i,{serial:n??``,messageId:r})}catch(t){this._logger.error(`Tree._foldInto(); fold threw`,{key:N(e.node),messageId:r,err:t})}}_recordAndFold(e,t,n,r,i,a){if(n===void 0||t.length===0){n===void 0&&t.length>0&&(e.optimistic=!0),this._foldInto(e,t,n,r);return}let o=e.log.record(n,r,t,i,a);if(o===`dropped`){this._logger.debug(`Tree._recordAndFold(); version guard dropped re-delivered wire`,{key:N(e.node),serial:n,version:i,swept:e.log.swept});return}if(e.optimistic&&!e.log.swept){e.optimistic=!1,this._refold(e);return}if(o===`refold`){this._refold(e);return}e.log.swept&&this._logger.warn(`Tree._recordAndFold(); late wire after log retention window; folding in arrival order`,{key:N(e.node),serial:n}),this._foldInto(e,t,n,r)}_refold(e){let t=this._codec.init();e.log.replay((n,r,i)=>{try{t=this._codec.fold(t,n,{serial:r,messageId:i})}catch(t){this._logger.error(`Tree._refold(); fold threw`,{key:N(e.node),messageId:i,err:t})}}),e.node.projection=t}_recordActivity(e,t){t!==void 0&&(t>e.lastActivityTs&&(e.lastActivityTs=t),t>this._clock&&(this._clock=t,this._drainSweepQueue()))}_maybeQueueSweep(e){let t=e.node;t.kind===`run`&&(e.log.swept||e.sweepQueued||e.runStartSeen&&(t.state.status===`active`||t.state.status===`suspended`||(e.sweepQueued=!0,this._sweepQueue.push(t.runId))))}_drainSweepQueue(){for(;this._sweepQueue.length>0;){let e=this._sweepQueue[0],t=e===void 0?void 0:this._nodeIndex.get(e);if(!t||t.log.swept){this._sweepQueue.shift();continue}if(t.lastActivityTs+12e4>=this._clock)return;this._sweepQueue.shift(),t.sweepQueued=!1,t.log.sweep(),this._logger.debug(`Tree._drainSweepQueue(); dropped event-log payloads, kept replay keys`,{key:e,lastActivityTs:t.lastActivityTs})}}_addToParentIndex(e,t){He(this._parentIndex,e,t)}_removeFromParentIndex(e,t){Ue(this._parentIndex,e,t)}_parentKeyOf(e){let t=e.parentCodecMessageId;return t===void 0?void 0:this._codecMessageIdToNodeKey.get(t)}_inputGroupRoot(e){let t=e,n=new Set([N(t)]);for(;t.forkOf!==void 0&&!n.has(t.forkOf);){let e=this._nodeIndex.get(t.forkOf);if(e?.node.kind!==`input`||e.node.parentCodecMessageId!==t.parentCodecMessageId)break;t=e.node,n.add(N(t))}return t}_getSiblingGroup(e){this._siblingCacheVersion!==this._structuralVersion&&(this._siblingCache.clear(),this._siblingCacheVersion=this._structuralVersion);let t=this._siblingCache.get(e);if(t)return t;let n=this._nodeIndex.get(e);if(!n)return[];let r=n.node;r.kind===`input`&&(r=this._inputGroupRoot(r));let i=r.parentCodecMessageId,a=[],o=this._parentIndex.get(i);if(o)for(let e of o){let t=this._nodeIndex.get(e);t&&this._isSiblingOf(t.node,r)&&a.push(t)}a.sort((e,t)=>this._compareNodes(e,t));for(let e of a)this._siblingCache.set(N(e.node),a);return this._siblingCache.set(e,a),a}_isSiblingOf(e,t){if(e.kind!==t.kind||e.parentCodecMessageId!==t.parentCodecMessageId)return!1;if(e.kind===`run`)return!0;let n=N(t);if(N(e)===n)return!0;let r=e,i=new Set([N(r)]);for(;r.kind===`input`&&r.forkOf!==void 0;){if(r.forkOf===n)return!0;if(i.has(r.forkOf))break;let e=this._nodeIndex.get(r.forkOf);if(!e)break;r=e.node,i.add(N(r))}return!1}getGroupRoot(e){let t=this._nodeIndex.get(e);if(!t)return e;if(t.node.kind===`input`)return N(this._inputGroupRoot(t.node));let n=this._getSiblingGroup(e)[0]?.node;return n?N(n):e}visibleNodes(e=new Map){this._logger.trace(`DefaultTree.visibleNodes();`);let t=[],n=new Set,r=new Map;for(let i of this._sortedNodes){let a=i.node,o=N(a),s=this._parentKeyOf(a);if(s!==void 0&&!n.has(s))continue;let c=this._getSiblingGroup(o);if(c.length>1){let t=this.getGroupRoot(o),n=r.get(t);if(n===void 0){let i=e.get(t);if(i!==void 0&&c.some(e=>N(e.node)===i))n=i;else{let e=c.at(-1);if(!e)break;n=N(e.node)}r.set(t,n)}if(o!==n)continue}n.add(o),t.push(a)}return t}getRunNode(e){this._logger.trace(`DefaultTree.getRunNode();`,{runId:e});let t=this._nodeIndex.get(e)?.node;return t?.kind===`run`?t:void 0}getNode(e){return this._logger.trace(`DefaultTree.getNode();`,{key:e}),this._nodeIndex.get(e)?.node}getNodeByCodecMessageId(e){this._logger.trace(`DefaultTree.getNodeByCodecMessageId();`,{codecMessageId:e});let t=this._codecMessageIdToNodeKey.get(e);return t===void 0?void 0:this._nodeIndex.get(t)?.node}getReplyRuns(e){let t=this._replyRunsByInput.get(e);if(!t)return[];let n=[];for(let e of t){let t=this._nodeIndex.get(e)?.node;t?.kind===`run`&&n.push(t)}return n}getSiblingNodes(e){return this._logger.trace(`DefaultTree.getSiblingNodes();`,{key:e}),this._getSiblingGroup(e).map(e=>e.node)}applyMessage(e,t,n,r,i){let a=t[C],o=t[E],s=a===void 0&&o!==void 0&&t.role===`user`&&e.inputs.length>0?o:void 0;if(a===void 0&&s===void 0){this._logger.warn(`Tree.applyMessage(); message has no run-id and is not a user input; skipping`);return}let c=ze(e),l=s??a;if(c.length===0&&l!==void 0&&!this._nodeIndex.has(l))return;let u=this._structuralVersion;s===void 0?a!==void 0&&this._applyRunMessage(a,e,t,n,r,i):this._applyInputMessage(s,t,n,r,i,c),this._structuralVersion!==u&&this._emitter.emit(`update`)}_applyInputMessage(e,t,n,r,i,a){let o=this._nodeIndex.get(e);o?o.node.kind===`input`&&n&&!o.node.serial&&(this._logger.debug(`Tree.applyMessage(); promoting input serial`,{codecMessageId:e,serial:n}),o.node.serial=n,this._promoteSerial(o)):(o=this._createInputNodeFromHeaders(e,t,n),this._insertNode(e,o,o.node.parentCodecMessageId),this._codecMessageIdToNodeKey.set(e,e),this._logger.debug(`Tree.applyMessage(); created input node`,{codecMessageId:e})),this._recordActivity(o,r),this._recordAndFold(o,a,n,e,i,t[x]===`true`),this._emitter.emit(`output`,{runId:void 0,inputCodecMessageId:e,codecMessageId:e,serial:n,events:[]})}_applyRunMessage(e,t,n,r,i,a){let o=n[E],s=n[ce],c=ze(t),l=t.outputs,u=this._nodeIndex.get(e);if(!u&&o!==void 0){let e=this._codecMessageIdToNodeKey.get(o),t=e===void 0?void 0:this._nodeIndex.get(e);t?.node.kind===`run`&&t.node.startSerial===void 0&&(u=t)}u?r&&u.node.kind===`run`&&!u.node.startSerial&&(this._logger.debug(`Tree.applyMessage(); promoting startSerial`,{runId:e,serial:r}),u.node.startSerial=r,this._promoteSerial(u)):(u=this._createRunFromHeaders(e,n,r),this._insertNode(e,u,u.node.parentCodecMessageId),this._indexReplyRun(u.node,e),this._logger.debug(`Tree.applyMessage(); created new Run`,{runId:e}));let d=N(u.node);o&&this._codecMessageIdToNodeKey.set(o,d),this._recordActivity(u,i),this._recordAndFold(u,c,r,o,a,n[x]===`true`),this._emitter.emit(`output`,{runId:d,inputCodecMessageId:s,codecMessageId:o,serial:r,events:l})}_indexReplyRun(e,t){e.parentCodecMessageId!==void 0&&He(this._replyRunsByInput,e.parentCodecMessageId,t)}applyRunLifecycle(e){this._logger.trace(`DefaultTree.applyRunLifecycle();`,{type:e.type,runId:e.runId});let t=this._structuralVersion;switch(e.type){case`start`:this._applyRunStart(e);break;case`suspend`:this._applyRunSuspend(e);break;case`resume`:this._applyRunResume(e);break;case`end`:this._applyRunEnd(e);break}this._emitter.emit(`run`,e),this._structuralVersion!==t&&this._emitter.emit(`update`)}_applyRunStart(e){let t=this._nodeIndex.get(e.runId);if(t?.node.kind===`run`){let n=t.node;if(n.state.status===`suspended`&&(n.state={status:`active`}),e.serial&&!n.startSerial&&(n.startSerial=e.serial,this._promoteSerial(t)),n.parentCodecMessageId===void 0&&e.parent!==void 0&&(n.parentCodecMessageId=e.parent,this._removeFromParentIndex(void 0,e.runId),this._addToParentIndex(n.parentCodecMessageId,e.runId),this._indexReplyRun(n,e.runId),this._structuralVersion++),n.forkOf===void 0&&e.forkOf!==void 0){let t=this._codecMessageIdToNodeKey.get(e.forkOf);t!==void 0&&t!==e.runId&&(n.forkOf=t,this._structuralVersion++)}n.regeneratesCodecMessageId===void 0&&e.regenerates!==void 0&&(n.regeneratesCodecMessageId=e.regenerates,this._structuralVersion++),n.invocationId===``&&e.invocationId!==``&&(n.invocationId=e.invocationId),t.runStartSeen=!0,this._recordActivity(t,e.timestamp),this._maybeQueueSweep(t)}else if(!t){let t=this._createRunFromLifecycle(e);this._insertNode(e.runId,t,t.node.parentCodecMessageId),this._indexReplyRun(t.node,e.runId),this._recordActivity(t,e.timestamp)}}_applyRunSuspend(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.state={status:`suspended`},t.node.endSerial=e.serial,this._recordActivity(t,e.timestamp))}_applyRunResume(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&t.node.state.status===`suspended`&&(t.node.state={status:`active`},this._recordActivity(t,e.timestamp))}_applyRunEnd(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.state=e.reason===`error`?{status:`error`,error:e.error}:{status:e.reason},t.node.endSerial=e.serial,this._recordActivity(t,e.timestamp),this._maybeQueueSweep(t))}delete(e){let t=this._nodeIndex.get(e);t&&(this._logger.debug(`Tree.delete();`,{key:e}),this._removeFromParentIndex(t.node.parentCodecMessageId,e),this._removeSortedNode(t),this._nodeIndex.delete(e),t.node.kind===`run`&&t.node.parentCodecMessageId!==void 0&&Ue(this._replyRunsByInput,t.node.parentCodecMessageId,e),this._structuralVersion++,this._emitter.emit(`update`))}_createRunFromHeaders(e,t,n){let r=t[oe];return this._buildRunNode({runId:e,parentCodecMessageId:t[D],forkOf:r?this._codecMessageIdToNodeKey.get(r):void 0,regeneratesCodecMessageId:t[se],clientId:t[`run-client-id`]??``,invocationId:t[`invocation-id`]??``,startSerial:n,runStartSeen:!1})}_wrapNode(e,t=!1){return{node:e,insertSeq:this._seqCounter++,log:new Be,lastActivityTs:0,runStartSeen:t,sweepQueued:!1,optimistic:!1}}_buildRunNode(e){let t={kind:`run`,runId:e.runId,parentCodecMessageId:e.parentCodecMessageId,forkOf:e.forkOf,regeneratesCodecMessageId:e.regeneratesCodecMessageId,clientId:e.clientId,invocationId:e.invocationId,state:{status:`active`},projection:this._codec.init(),startSerial:e.startSerial,endSerial:void 0};return this._wrapNode(t,e.runStartSeen)}_createInputNodeFromHeaders(e,t,n){let r=t[oe],i={kind:`input`,codecMessageId:e,parentCodecMessageId:t[D],forkOf:r,projection:this._codec.init(),serial:n};return this._wrapNode(i)}_createRunFromLifecycle(e){let t=e.forkOf;return this._buildRunNode({runId:e.runId,parentCodecMessageId:e.parent,forkOf:t?this._codecMessageIdToNodeKey.get(t):void 0,regeneratesCodecMessageId:e.regenerates,clientId:e.clientId,invocationId:e.invocationId,startSerial:e.serial,runStartSeen:!0})}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}emitAblyMessage(e){this._logger.trace(`DefaultTree.emitAblyMessage();`);let t=j(e)[T];t!==void 0&&!this._eventIdIndex.has(t)&&this._eventIdIndex.set(t,e),this._emitter.emit(`ably-message`,e)}findAblyMessageByEventId(e){return this._eventIdIndex.get(e)}},Ge=(e,t)=>new We(e,t),Ke=(e,t)=>new Promise((r,i)=>{if(t?.aborted){i(new n.ErrorInfo(`unable to wait; signal aborted`,O.InvalidArgument,400));return}let a=setTimeout(()=>{t?.removeEventListener(`abort`,o),r()},e);typeof a==`object`&&a.unref();let o=()=>{clearTimeout(a),i(new n.ErrorInfo(`unable to wait; signal aborted`,O.InvalidArgument,400))};t?.addEventListener(`abort`,o,{once:!0})}),qe=async(e,t,r,i,a)=>{let o;for(let s=0;s<=t;s++){if(i?.aborted)throw new n.ErrorInfo(`unable to fetch history page; signal aborted`,O.InvalidArgument,400,A(o));try{return await e()}catch(e){if(o=e,s===t)break;let n=r*2**s;a?.debug(`loadHistoryPages.fetchPageWithRetry(); page fetch failed, retrying`,{attempt:s+1,maxRetries:t,backoff:n}),await Ke(n,i)}}throw new n.ErrorInfo(`unable to fetch history page; ${k(o)}`,O.HistoryFetchFailed,500,A(o))},Je=async(e,t)=>{let{pageLimit:r,untilAttach:i=!0,signal:a,maxRetries:o=3,retryBackoffMs:s=100,logger:c}=t;if(a?.aborted)throw new n.ErrorInfo(`unable to load history; signal aborted`,O.InvalidArgument,400);await e.attach();let l={limit:r,untilAttach:i},u=await qe(()=>e.history(l),o,s,a,c),d=!1;return{hasNext:()=>u===void 0||a?.aborted?!1:d?u.hasNext():!0,next:async()=>{if(u===void 0)return;if(a?.aborted)throw new n.ErrorInfo(`unable to load history; signal aborted`,O.InvalidArgument,400);if(!d)return d=!0,u.items;if(!u.hasNext()){u=void 0;return}let e=await qe(async()=>await u?.next()??void 0,o,s,a,c);if(!e){u=void 0;return}return u=e,e.items}}},Ye=(e,t)=>{for(let n of t){let t=j(n),r=t[E];if(!r)continue;let i=n.action,a=i===`message.create`&&`discrete`in t,o=t.stream===`true`&&(i===`message.create`||i===`message.update`||i===`message.append`),s=t[S],c=s===`complete`||s===`cancelled`;(a||o)&&e.startedCodecMessageIds.add(r),(a||c)&&e.terminatedCodecMessageIds.add(r),e.startedCodecMessageIds.has(r)&&e.terminatedCodecMessageIds.has(r)&&e.completedCodecMessageIds.add(r)}},Xe=async(e,t)=>{let n=e.returnedCount+t;for(;e.completedCodecMessageIds.size<n&&e.cursor.hasNext();){e.logger.debug(`loadHistory.fetchUntilLimit(); pulling next page`,{collected:e.rawMessages.length,completed:e.completedCodecMessageIds.size});let t=await e.cursor.next();if(!t)break;e.rawMessages.push(...t),Ye(e,t)}},Ze=(e,t)=>{let n=e.completedCodecMessageIds.size,r=Math.min(t,Math.max(0,n-e.returnedCount));e.returnedCount+=r;let i=n>e.returnedCount,a=e.cursor.hasNext(),o=e.rawMessages.length-e.returnedRawCount>0?e.rawMessages.slice(e.returnedRawCount).toReversed():[];return e.returnedRawCount=e.rawMessages.length,{rawMessages:o,hasNext:()=>i||a,next:async()=>{if(i)return Ze(e,t);if(a)return await Xe(e,t),Ze(e,t)}}},Qe=async(e,t,n)=>{let r=t?.limit??100;n.trace(`loadHistory();`,{limit:r});let i={cursor:await Je(e,{pageLimit:r*10,untilAttach:!0,logger:n}),rawMessages:[],returnedCount:0,returnedRawCount:0,startedCodecMessageIds:new Set,terminatedCodecMessageIds:new Set,completedCodecMessageIds:new Set,logger:n};return await Xe(i,r),Ze(i,r)},$e=e=>Array.isArray(e)?e:[e],et=e=>({runId:e.runId,clientId:e.clientId,invocationId:e.invocationId,...e.state}),tt=class{constructor(e){this._branchSelections=new Map,this._regenSelections=new Map,this._nonHeadRegenSelections=new Map,this._withheldRunIds=new Set,this._lastVisibleNodeKeys=[],this._lastVisibleProjections=[],this._lastVisibleMessagePairs=[],this._lastVisibleNodeKeySet=new Set,this._hasMoreHistory=!1,this._withheldBuffer=[],this._hiddenMessageCount=0,this._unsubs=[],this._cachedNodes=[],this._loadingOlder=!1,this._processingHistory=!1,this._closed=!1,this._tree=e.tree,this._channel=e.channel,this._codec=e.codec,this._applier=e.applier,this._sendDelegate=e.sendDelegate,this._onClose=e.onClose,this._logger=e.logger.withContext({component:`View`}),this._logger.trace(`DefaultView();`),this._emitter=new ge(this._logger),this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._unsubs.push(this._tree.on(`update`,()=>{this._onTreeUpdate()}),this._tree.on(`ably-message`,e=>{this._onTreeAblyMessage(e)}),this._tree.on(`run`,e=>{this._onTreeRun(e)}),this._tree.on(`output`,e=>{this._onTreeOutput(e)}))}_onTreeOutput(e){this._processingHistory||(e.runId!==void 0&&this._lastVisibleNodeKeySet.has(e.runId)||e.inputCodecMessageId!==void 0&&this._lastVisibleNodeKeySet.has(e.inputCodecMessageId))&&(this._lastVisibleProjections=this._cachedNodes.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(this._cachedNodes).slice(this._hiddenMessageCount),this._emitter.emit(`update`))}getMessages(){return this._lastVisibleMessagePairs}runs(){return this._cachedNodes.filter(e=>e.kind===`run`).map(e=>et(e))}_computeFlatNodes(){let e=this._treeVisibleNodes();return this._withheldRunIds.size===0?e:e.filter(e=>!this._withheldRunIds.has(N(e)))}_recomputeAndEmit(){this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._emitter.emit(`update`)}_recomputeAndEmitIfChanged(){let e=this._computeFlatNodes();this._visibleChanged(e)&&(this._cachedNodes=e,this._updateVisibleSnapshot(e),this._emitter.emit(`update`))}_runByCodecMessageId(e){let t=this._tree.getNodeByCodecMessageId(e);return t?.kind===`run`?t:void 0}_nonHeadRegenerators(e,t){return this._tree.getReplyRuns(t).filter(t=>t.regeneratesCodecMessageId===e).toSorted((e,t)=>(e.startSerial??`￿`).localeCompare(t.startSerial??`￿`))}_selectedNonHeadMember(e,t,n){let r=this._nonHeadRegenSelections.get(e);return r&&r.kind!==`pending`&&[t,...n.map(e=>e.runId)].includes(r.selectedRunId)?r.selectedRunId:n.at(-1)?.runId??t}_extractMessages(e){let t=[],n=new Set;for(let r of e)r.kind===`run`&&n.has(r.runId)||this._emitNodeMessages(r,t,n);return t}_emitNodeMessages(e,t,n){let r=this._codec.getMessages(e.projection);if(e.kind!==`run`){t.push(...r);return}for(let i=0;i<r.length;i++){let a=r[i];if(!a)continue;let o=i>0?r[i-1]?.codecMessageId:void 0;if(o!==void 0){let r=this._nonHeadRegenerators(a.codecMessageId,o);if(r.length>0){for(let e of r)n.add(e.runId);let i=this._selectedNonHeadMember(a.codecMessageId,e.runId,r);if(i!==e.runId){let e=r.find(e=>e.runId===i);if(e){this._emitNodeMessages(e,t,n);return}}}}t.push(a)}}hasOlder(){return this._hiddenMessageCount>0||this._withheldBuffer.length>0||this._hasMoreHistory}async loadOlder(e=10){if(!(this._closed||this._loadingOlder)){this._loadingOlder=!0,this._logger.trace(`DefaultView.loadOlder();`,{limit:e});try{if(this._hiddenMessageCount>=e){this._hiddenMessageCount-=e,this._recomputeAndEmit();return}let t=e-this._hiddenMessageCount,n=this._extractMessages(this._computeFlatNodes()).length,r=()=>this._extractMessages(this._computeFlatNodes()).length-n;if(this._withheldBuffer.length>0){let e=this._messageTailSplitIndex(this._withheldBuffer,t),n=this._withheldBuffer.splice(e);this._releaseWithheld(n)}if(r()<t&&(await this._fetchOlder(t-r()),this._closed))return;let i=this._extractMessages(this._computeFlatNodes()).length;this._hiddenMessageCount=Math.max(0,this._hiddenMessageCount+(i-n)-e),this._recomputeAndEmit()}catch(e){throw this._logger.error(`DefaultView.loadOlder(); failed`,{error:e}),e}finally{this._loadingOlder=!1}}}async _fetchOlder(e){if(!this._hasMoreHistory&&!this._lastHistoryPage){await this._loadFirstPage(e);return}if(!this._hasMoreHistory)return;if(!this._lastHistoryPage?.hasNext()){this._hasMoreHistory=!1;return}let t=await this._lastHistoryPage.next();if(this._closed||!t){t||(this._hasMoreHistory=!1);return}await this._revealFromPage(t,e)}_messageTailSplitIndex(e,t){let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];if(i&&(n+=this._codec.getMessages(i.projection).length,n>=t))return r}return 0}runOf(e){this._logger.trace(`DefaultView.runOf();`,{codecMessageId:e});let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`run`)return et(t);let n=this._selectedReplyRun(t.codecMessageId);return n?et(n):void 0}_selectedReplyRun(e){let t=this._tree.getReplyRuns(e);if(t.length===0)return;if(t.length===1)return t[0];let n=this._tree.getGroupRoot(t[0]?.runId??``),r=this._regenSelections.get(n),i=r&&r.kind!==`pending`?r.selectedRunId:void 0;if(i!==void 0){let e=t.find(e=>e.runId===i);if(e)return e}return t.toSorted((e,t)=>(e.startSerial??`￿`).localeCompare(t.startSerial??`￿`)).at(-1)}run(e){this._logger.trace(`DefaultView.run();`,{runId:e});let t=this._tree.getRunNode(e);return t?et(t):void 0}branchSelection(e){let t=this._resolveMessageBranchPoint(e);if(t){let e=t.members.flatMap(e=>{let t=this._tree.getNodeByCodecMessageId(e.representativeCodecMessageId);if(!t)return[];let n=this._codec.getMessages(t.projection).find(t=>t.codecMessageId===e.representativeCodecMessageId);return n?[n.message]:[]});if(e.length>0){let n=this._resolveSelectedIndex(t),r=Math.max(0,Math.min(n,e.length-1)),i=e[r];return{hasSiblings:e.length>1,siblings:e,index:r,selected:i}}}let n=this._tree.getNodeByCodecMessageId(e);if(n){let t=this._codec.getMessages(n.projection).find(t=>t.codecMessageId===e);if(t!==void 0)return{hasSiblings:!1,siblings:[t.message],index:0,selected:t.message}}return{hasSiblings:!1,siblings:[],index:0,selected:void 0}}selectSibling(e,t){this._logger.trace(`DefaultView.selectSibling();`,{codecMessageId:e,index:t});let n=this._resolveMessageBranchPoint(e);if(!n)return;let r=Math.max(0,Math.min(t,n.members.length-1)),i=n.members[r];i&&(n.kind===`fork-of`?(this._branchSelections.set(n.groupRoot,{kind:`user`,selectedKey:i.memberNodeKey}),this._logger.debug(`DefaultView.selectSibling(); fork-of`,{codecMessageId:e,index:r,selectedKey:i.memberNodeKey})):n.kind===`non-head-regen`?(this._nonHeadRegenSelections.set(n.groupRoot,{kind:`user`,selectedRunId:i.memberNodeKey}),this._logger.debug(`DefaultView.selectSibling(); non-head-regen`,{codecMessageId:e,index:r,selectedRunId:i.memberNodeKey,anchor:n.groupRoot})):(this._regenSelections.set(n.groupRoot,{kind:`user`,selectedRunId:i.memberNodeKey}),this._logger.debug(`DefaultView.selectSibling(); regenerate`,{codecMessageId:e,index:r,selectedRunId:i.memberNodeKey,groupRoot:n.groupRoot})),this._recomputeAndEmit())}_resolveSelectedIndex(e){if(e.kind===`fork-of`){let t=this._branchSelections.get(e.groupRoot);if(!t)return e.members.length-1;let n=e.members.findIndex(e=>e.memberNodeKey===t.selectedKey);return n===-1?e.members.length-1:n}let t=e.kind===`non-head-regen`?this._nonHeadRegenSelections.get(e.groupRoot):this._regenSelections.get(e.groupRoot);if(!t||t.kind===`pending`)return e.members.length-1;let n=e.members.findIndex(e=>e.memberNodeKey===t.selectedRunId);return n===-1?e.members.length-1:n}_resolveMessageBranchPoint(e){let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`input`){let e=this._tree.getSiblingNodes(t.codecMessageId);return e.length>1?{kind:`fork-of`,groupRoot:this._tree.getGroupRoot(t.codecMessageId),members:this._nodeHeadMembers(e)}:void 0}let n=this._codec.getMessages(t.projection),r=this._resolveNonHeadBranchPoint(t,n,e);if(r)return r;let i=this._tree.getSiblingNodes(t.runId);if(i.length>1&&n.at(0)?.codecMessageId===e)return{kind:`regen`,groupRoot:this._tree.getGroupRoot(t.runId),members:this._nodeHeadMembers(i)}}_resolveNonHeadBranchPoint(e,t,n){if(t.at(0)?.codecMessageId===n&&e.regeneratesCodecMessageId!==void 0){let t=e.regeneratesCodecMessageId,n=this._runByCodecMessageId(t);if(n){let e=this._codec.getMessages(n.projection),r=e.findIndex(e=>e.codecMessageId===t),i=r>0?e[r-1]?.codecMessageId:void 0;if(i!==void 0)return this._buildNonHeadGroup(t,n.runId,i)}return}let r=t.findIndex(e=>e.codecMessageId===n),i=r>0?t[r-1]?.codecMessageId:void 0;if(i!==void 0)return this._buildNonHeadGroup(n,e.runId,i)}_buildNonHeadGroup(e,t,n){let r=this._nonHeadRegenerators(e,n);if(r.length===0)return;let i=[{memberNodeKey:t,representativeCodecMessageId:e}];for(let e of r){let t=this._codec.getMessages(e.projection).at(0);t&&i.push({memberNodeKey:e.runId,representativeCodecMessageId:t.codecMessageId})}return{kind:`non-head-regen`,groupRoot:e,members:i}}_nodeHeadMembers(e){let t=[];for(let n of e){let e=this._codec.getMessages(n.projection).at(0);e&&t.push({memberNodeKey:N(n),representativeCodecMessageId:e.codecMessageId})}return t}async send(e,t){if(this._logger.trace(`DefaultView.send();`),this._closed)throw new n.ErrorInfo(`unable to send; view is closed`,O.InvalidArgument,400);let r=$e(e),i=this._lastVisibleMessagePairs.at(-1)?.codecMessageId,a=await this._sendDelegate(r,t,i);return this._applyForkAutoSelect(a,t),a}_applyForkAutoSelect(e,t){if(!t?.forkOf)return;let n=e.optimisticCodecMessageIds.at(0);if(n===void 0)return;let r=this._tree.getGroupRoot(n);this._branchSelections.set(r,{kind:`auto`,selectedKey:n}),this._recomputeAndEmit()}_applyRegenerateAutoSelect(e,t){let n=this._runByCodecMessageId(t);if(!n)return;if(this._codec.getMessages(n.projection).at(0)?.codecMessageId!==t){this._nonHeadRegenSelections.set(t,{kind:`pending`,carrierCodecMessageId:e.inputCodecMessageId}),this._logger.debug(`DefaultView._applyRegenerateAutoSelect(); deferring non-head regenerate selection`,{anchorCodecMessageId:t,carrier:e.inputCodecMessageId}),this._resolvePendingNonHeadRegenSelections(),this._recomputeAndEmitIfChanged();return}let r=this._tree.getGroupRoot(n.runId);this._regenSelections.set(r,{kind:`pending`,carrierCodecMessageId:e.inputCodecMessageId}),this._logger.debug(`DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection`,{anchorCodecMessageId:t,groupRoot:r,carrier:e.inputCodecMessageId}),this._resolvePendingRegenSelections(),this._recomputeAndEmitIfChanged()}async regenerate(e,t){if(this._logger.trace(`DefaultView.regenerate();`,{messageId:e}),this._closed)throw new n.ErrorInfo(`unable to regenerate; view is closed`,O.InvalidArgument,400);let r=this._runByCodecMessageId(e);if(!r)throw new n.ErrorInfo(`unable to regenerate; message not found in tree: ${e}`,O.InvalidArgument,400);let i=this._findParentMsgId(r,e);if(!i)throw new n.ErrorInfo(`unable to regenerate; parent user message not found for ${e}`,O.InvalidArgument,400);let a=e;r.regeneratesCodecMessageId!==void 0&&this._codec.getMessages(r.projection).at(0)?.codecMessageId===e&&(a=r.regeneratesCodecMessageId);let o={...t,parent:i},s=this._codec.createRegenerate(a,i),c=await this._sendDelegate([s],o,i);return this._applyRegenerateAutoSelect(c,a),c}async edit(e,t,r){if(this._logger.trace(`DefaultView.edit();`,{messageId:e}),this._closed)throw new n.ErrorInfo(`unable to edit; view is closed`,O.InvalidArgument,400);let i=this._tree.getNodeByCodecMessageId(e);if(!i)throw new n.ErrorInfo(`unable to edit; message not found in tree: ${e}`,O.InvalidArgument,400);let a=this._findParentMsgId(i,e);return this.send(t,{...r,forkOf:e,parent:a})}_findParentMsgId(e,t){let n=this._lastVisibleMessagePairs,r=n.findIndex(e=>e.codecMessageId===t);if(r>0)return n[r-1]?.codecMessageId;if(r===0)return;let i=this._codec.getMessages(e.projection),a=i.findIndex(e=>e.codecMessageId===t);if(a>0)return i[a-1]?.codecMessageId;if(a===0&&e.parentCodecMessageId!==void 0){let t=this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);if(t)return this._codec.getMessages(t.projection).at(-1)?.codecMessageId}}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}close(){if(!this._closed){this._logger.info(`DefaultView.close();`),this._closed=!0,this._loadingOlder=!1;for(let e of this._unsubs)e();this._unsubs.length=0,this._emitter.off(),this._branchSelections.clear(),this._regenSelections.clear(),this._nonHeadRegenSelections.clear(),this._withheldRunIds.clear(),this._withheldBuffer.length=0,this._hiddenMessageCount=0,this._onClose?.()}}async _loadFirstPage(e){let t=await Qe(this._channel,{limit:e},this._logger);this._closed||await this._revealFromPage(t,e)}async _revealFromPage(e,t){let n=new Set(this._treeVisibleNodes().map(e=>N(e))),{newVisible:r,lastPage:i}=await this._loadUntilVisible(e,t,n);this._closed||(this._lastHistoryPage=i,this._hasMoreHistory=i.hasNext(),this._splitReveal(r,t))}_splitReveal(e,t){let n=this._messageTailSplitIndex(e,t),r=e.slice(n),i=e.slice(0,n);for(let e of i)this._withheldRunIds.add(N(e));this._withheldBuffer.push(...i),this._releaseWithheld(r)}_processHistoryPage(e){this._processingHistory=!0;try{for(let t of e.rawMessages)this._applier.apply(t);for(let t of e.rawMessages)this._tree.emitAblyMessage(t)}finally{this._processingHistory=!1}}async _loadUntilVisible(e,t,n){this._processHistoryPage(e);let r=e,i=()=>{let e=0;for(let t of this._treeVisibleNodes())n.has(N(t))||(e+=this._codec.getMessages(t.projection).length);return e};for(;i()<t&&r.hasNext();){let e=await r.next();if(!e||this._closed)break;this._processHistoryPage(e),r=e}return{newVisible:this._treeVisibleNodes().filter(e=>!n.has(N(e))),lastPage:r}}_releaseWithheld(e){for(let t of e)this._withheldRunIds.delete(N(t));e.length>0&&this._recomputeAndEmit()}_updateVisibleSnapshot(e){let t=e??this._cachedNodes;this._lastVisibleNodeKeys=t.map(e=>N(e)),this._lastVisibleNodeKeySet=new Set(this._lastVisibleNodeKeys),this._lastVisibleProjections=t.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(t).slice(this._hiddenMessageCount)}_onTreeUpdate(){this._processingHistory||(this._pinBranchSelections(),this._resolvePendingRegenSelections(),this._resolvePendingNonHeadRegenSelections(),this._recomputeAndEmitIfChanged())}_resolveSelections(){let e=new Map;for(let[t,n]of this._branchSelections)e.set(t,n.selectedKey);for(let[t,n]of this._regenSelections)n.kind!==`pending`&&e.set(t,n.selectedRunId);return e}_treeVisibleNodes(){return this._tree.visibleNodes(this._resolveSelections())}_pinBranchSelections(){for(let e of this._lastVisibleNodeKeys){if(this._tree.getNode(e)?.kind!==`input`||this._tree.getSiblingNodes(e).length<=1)continue;let t=this._tree.getGroupRoot(e);this._branchSelections.get(t)||this._branchSelections.set(t,{kind:`pinned`,selectedKey:e})}}_resolvePendingRegenSelections(){for(let[e,t]of this._regenSelections){if(t.kind===`user`)continue;let n=this._tree.getSiblingNodes(e).filter(e=>e.kind===`run`);if(n.length<=1)continue;let r=n.at(-1);r&&this._regenSelections.set(e,{kind:`auto`,selectedRunId:r.runId})}}_resolvePendingNonHeadRegenSelections(){for(let[e,t]of this._nonHeadRegenSelections){if(t.kind===`user`)continue;let n=this._runByCodecMessageId(e);if(!n)continue;let r=this._codec.getMessages(n.projection),i=r.findIndex(t=>t.codecMessageId===e),a=i>0?r[i-1]?.codecMessageId:void 0;if(a===void 0)continue;let o=this._nonHeadRegenerators(e,a).at(-1);o&&this._nonHeadRegenSelections.set(e,{kind:`auto`,selectedRunId:o.runId})}}_onTreeAblyMessage(e){let t=j(e),n=t[E],r=t[C];if(!n&&!r){this._emitter.emit(`ably-message`,e);return}r&&this._lastVisibleNodeKeySet.has(r)&&this._emitter.emit(`ably-message`,e)}_onTreeRun(e){if(this._lastVisibleNodeKeySet.has(e.runId)){this._emitter.emit(`run`,e);return}e.type===`start`&&this._isRunStartVisible(e)&&(this._lastVisibleNodeKeySet.add(e.runId),this._emitter.emit(`run`,e))}_isRunStartVisible(e){let{parent:t}=e;if(t===void 0)return!0;let n=this._tree.getNodeByCodecMessageId(t);return n?this._lastVisibleNodeKeySet.has(N(n)):!0}_visibleChanged(e){if(e.length!==this._lastVisibleNodeKeys.length)return!0;for(let[t,n]of e.entries())if(N(n)!==this._lastVisibleNodeKeys[t]||n.projection!==this._lastVisibleProjections[t])return!0;return!1}},nt=e=>new tt(e),rt=()=>{},it=class{constructor(e){this._views=new Set,this._state=`ready`,this._pendingRunStarts=new Map;let t=ee(e.client,e.codec),n=m(e.channelModes);if(n&&(t.modes=n),this._channel=e.client.channels.get(e.channelName,t),this._client=e.client,this._codec=e.codec,this._logger=(e.logger??ye({logLevel:_e.Silent})).withContext({component:`ClientSession`}),this._emitter=new ge(this._logger),this._hasAttachedOnce=this._channel.state===`attached`,this._tree=Ge(this._codec,this._logger),this._applier=Ne(this._tree,this._codec.createDecoder()),this._view=nt({tree:this._tree,channel:this._channel,codec:this._codec,applier:this._applier,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(this._view)}),this._encoder=this._codec.createEncoder(this._channel),this._views.add(this._view),this.tree=this._tree,this.view=this._view,e.messages){let t;for(let n of e.messages){let e=crypto.randomUUID(),r={[E]:e,[ae]:`user`};t&&(r[D]=t),this._tree.applyMessage({inputs:[this._codec.createUserMessage(n)],outputs:[]},r),t=e}}this._onMessage=e=>{this._handleMessage(e)},this._onChannelStateChange=e=>{this._handleChannelStateChange(e)},this._channel.on(this._onChannelStateChange)}get presence(){return this._channel.presence}get object(){return this._channel.object}connect(){return this._state===`closed`?Promise.reject(new n.ErrorInfo(`unable to connect; session is closed`,O.SessionClosed,400)):this._connectPromise?this._connectPromise:(this._logger.trace(`DefaultClientSession.connect();`),this._connectPromise=this._channel.subscribe(this._onMessage).then(()=>{this._logger.debug(`DefaultClientSession.connect(); subscribed and attached`)},e=>{let t=new n.ErrorInfo(`unable to subscribe to channel; ${k(e)}`,O.SessionSubscriptionError,500,A(e));throw this._logger.error(`DefaultClientSession.connect(); subscribe failed`),this._emitter.emit(`error`,t),t}),this._connectPromise)}_resolveClientId(){let e=this._client.auth.clientId;return e&&e!==`*`?e:void 0}async _requireConnected(e){return Fe(this._connectPromise,e)}_handleMessage(e){if(this._state!==`closed`)try{if(e.name===`ai-run-end`){let t=j(e);if((t[`run-reason`]??`complete`)===`error`){let e=Ae(t);this._logger.error(`ClientSession._handleMessage(); agent error received`,{runId:t[C],invocationId:t[w],code:e.code}),this._emitter.emit(`error`,e)}}let t=this._applier.apply(e);if(t&&(t.type===`start`||t.type===`resume`)){let n=j(e)[ce];if(n!==void 0){let e=this._pendingRunStarts.get(n);e&&(this._pendingRunStarts.delete(n),e.resolve(t.runId))}}this._tree.emitAblyMessage(e)}catch(e){this._emitter.emit(`error`,new n.ErrorInfo(`unable to process channel message; ${k(e)}`,O.SessionSubscriptionError,500,A(e)))}}_handleChannelStateChange(e){if(this._state===`closed`)return;let{current:t,resumed:n}=e;if(t===`attached`&&!this._hasAttachedOnce){this._hasAttachedOnce=!0;return}if(!Le(e))return;this._logger.error(`ClientSession._handleChannelStateChange(); channel continuity lost`,{current:t,resumed:n,previous:e.previous});let r=Re(e,`deliver events`);this._emitter.emit(`error`,r)}_cleanupFailedSend(e){for(let t of e){let e=this._tree.getNodeByCodecMessageId(t);e?.kind===`input`&&e.serial===void 0&&this._tree.delete(e.codecMessageId)}}createView(){if(this._state===`closed`)throw new n.ErrorInfo(`unable to create view; session is closed`,O.SessionClosed,400);this._logger.trace(`DefaultClientSession.createView();`);let e=nt({tree:this._tree,channel:this._channel,codec:this._codec,applier:this._applier,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(e)});return this._views.add(e),e}async _internalSend(e,t,r){if(this._state===`closed`||(await this._requireConnected(`send`),this._state===`closed`))throw new n.ErrorInfo(`unable to send; session is closed`,O.SessionClosed,400);let i=this._channel.state;if(i!==`attached`&&i!==`attaching`)throw new n.ErrorInfo(`unable to send; channel is ${i}`,O.ChannelNotReady,400);this._logger.trace(`ClientSession._internalSend();`);let a=t?.runId!==void 0,o=t?.runId,s;t?.parent===void 0&&!t?.forkOf&&(s=r);let c=new Set,l=[];for(let n of e){let e=crypto.randomUUID(),r=n.codecMessageId??crypto.randomUUID();c.add(r);let i=n.kind!==`user-message`&&(n.kind===`regenerate`||n.codecMessageId!==void 0),a=n.parent??(t?.parent===void 0?s:t.parent),u=t?.forkOf,d=n.kind===`regenerate`?n.target:void 0,f=Oe({role:`user`,runId:o,codecMessageId:r,runClientId:this._resolveClientId(),...a!==void 0&&{parent:a},...u!==void 0&&{forkOf:u},...d!==void 0&&{regenerates:d},inputEventId:e});i||this._tree.applyMessage({inputs:[n],outputs:[]},f),l.push({input:n,codecMessageId:r,inputEventId:e,headers:f,isWireOnly:i}),!i&&t?.parent===void 0&&!t?.forkOf&&n.parent===void 0&&(s=r)}let u=l.at(-1);if(u===void 0)throw new n.ErrorInfo(`unable to send; inputs array is empty (include at least one input)`,O.InvalidArgument,400);let d=u.inputEventId,f=u.codecMessageId,p=new Promise((e,t)=>{this._pendingRunStarts.set(f,{resolve:e,reject:t})});return p.catch(()=>{}),await(async()=>{try{for(let e of l)await this._encoder.publishInput(e.input,{extras:{headers:e.headers},messageId:e.codecMessageId})}catch(e){let t=A(e),r=t?.statusCode===401||t?.statusCode===403,i=new n.ErrorInfo(r?`unable to publish events; missing publish capability on the channel`:`unable to publish events; ${k(e)}`,r?O.InsufficientCapability:O.SessionSendFailed,r?401:500,t);throw this._emitter.emit(`error`,i),this._pendingRunStarts.delete(f),a||this._cleanupFailedSend([...c]),i}})(),{inputCodecMessageId:f,runId:p,inputEventId:d,cancel:async()=>{await this._publishCancel({inputCodecMessageId:f,...o!==void 0&&{runId:o}})},optimisticCodecMessageIds:[...c],toInvocation:()=>Pe.fromJSON({inputEventId:d,sessionName:this._channel.name})}}async cancel(e){return this._publishCancel({runId:e})}async _publishCancel(e){if(this._state===`closed`||(await this._requireConnected(`cancel`),this._state===`closed`))return;this._logger.debug(`ClientSession._publishCancel();`,{runId:e.runId,inputCodecMessageId:e.inputCodecMessageId});let t={[T]:crypto.randomUUID()};e.runId!==void 0&&(t[C]=e.runId),e.inputCodecMessageId!==void 0&&(t[ce]=e.inputCodecMessageId),await this._channel.publish({name:ue,extras:{ai:{transport:t}}})}on(e,t){if(this._state===`closed`)return rt;let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}async close(){if(this._state!==`closed`){this._state=`closed`,this._logger.info(`ClientSession.close();`),this._connectPromise&&this._channel.unsubscribe(this._onMessage),this._channel.off(this._onChannelStateChange),this._emitter.off();for(let e of this._views)e.close();if(this._views.clear(),this._pendingRunStarts.size>0){let e=new n.ErrorInfo(`unable to await run-start; session closed`,O.SessionClosed,400);for(let t of this._pendingRunStarts.values())t.reject(e);this._pendingRunStarts.clear()}try{await this._encoder.close()}catch{}await Ie(this._channel,this._connectPromise,this._logger,`ClientSession`)}}},at=e=>new it(e),ot=(0,t.createContext)({nearest:void 0,providers:{}}),st=({children:e,...a})=>{let o=(0,r.useAbly)(),{channelName:s}=a,c=(0,t.useMemo)(()=>{let e={params:{agent:b(a.codec)}},t=m(a.channelModes);return t&&(e.modes=t),e},[a.codec,a.channelModes]),l=(0,t.useRef)(void 0),u=(0,t.useRef)(s),d=(0,t.useRef)([]),f=(0,t.useRef)(!1),p=(0,t.useRef)(void 0);if(!(l.current||p.current)||u.current!==s){u.current=s,l.current&&d.current.push(l.current);try{l.current=at({...a,client:o}),p.current=void 0}catch(e){l.current=void 0,p.current=e instanceof n.ErrorInfo?e:new n.ErrorInfo(`Unknown error while creating client session`,O.BadRequest,400)}}let h=(0,t.useContext)(ot),g=l.current,_=p.current,v=(0,t.useMemo)(()=>({session:g,sessionError:_}),[g,_]),y=(0,t.useMemo)(()=>({nearest:v,providers:{...h.providers,[s]:v}}),[s,h,v]);return(0,t.useEffect)(()=>()=>{for(let e of d.current)e.close()},[s]),(0,t.useEffect)(()=>{l.current?.connect()},[s]),(0,t.useEffect)(()=>(f.current=!1,()=>{f.current=!0,Promise.resolve().then(()=>{f.current&&l.current?.close()})}),[]),(0,i.jsx)(ot.Provider,{value:y,children:(0,i.jsx)(r.ChannelProvider,{channelName:s,options:c,children:e})})},ct=({session:e,skip:n}={})=>{let{nearest:r}=(0,t.useContext)(ot),i=r?.session;if(!n&&e!==null)return e??i},lt=({session:e,skip:n}={})=>{let r=ct({session:e,skip:n}),[i,a]=(0,t.useState)([]),o=(0,t.useRef)([]);return(0,t.useEffect)(()=>{if(o.current=[],a([]),r)return r.tree.on(`ably-message`,e=>{let t=[...o.current,e];o.current=t,a(t)})},[r]),i},P=e=>new n.ErrorInfo(`unable to ${e}; hook is skipped`,O.InvalidArgument,400),F=()=>({get tree(){throw P(`access tree`)},get view(){throw P(`access view`)},get presence(){throw P(`access presence`)},get object(){throw P(`access object`)},connect:()=>{throw P(`connect`)},createView:()=>{throw P(`create view`)},cancel:()=>{throw P(`cancel`)},on:()=>{throw P(`subscribe`)},close:()=>{throw P(`close`)}}),ut=({channelName:e,skip:r,onError:i}={})=>{let{nearest:a,providers:o}=(0,t.useContext)(ot),s=(0,t.useRef)(i);s.current=i;let c=r?void 0:e===void 0?a?.session:o[e]?.session;if((0,t.useEffect)(()=>{if(c)return c.on(`error`,e=>{s.current?.(e)})},[c]),r)return{session:F()};if(e!==void 0){let t=o[e];return t?t.session?{session:t.session}:{session:F(),sessionError:t.sessionError}:{session:F(),sessionError:new n.ErrorInfo(`unable to use session; no ClientSessionProvider found for channelName "${e}"`,O.BadRequest,400)}}return a?a.session?{session:a.session}:{session:F(),sessionError:a.sessionError}:{session:F(),sessionError:new n.ErrorInfo(`unable to use session; no ClientSessionProvider found in the tree`,O.BadRequest,400)}},dt={hasSiblings:!1,siblings:[],index:0,selected:void 0},ft=({session:e,view:r,limit:i,skip:a}={})=>{let o=ct({session:e,skip:a}),s=a?void 0:r??o?.view,[c,l]=(0,t.useState)(()=>s?.getMessages()??[]),[u,d]=(0,t.useState)(()=>s?.hasOlder()??!1),[f,p]=(0,t.useState)(!1),[m,h]=(0,t.useState)(),g=(0,t.useRef)(!1),_=i!==void 0,v=(0,t.useRef)(!1);(0,t.useEffect)(()=>{if(!s){l([]),d(!1),h(void 0);return}return v.current=!1,l(s.getMessages()),d(s.hasOlder()),h(void 0),s.on(`update`,()=>{l(s.getMessages()),d(s.hasOlder())})},[s]);let y=(0,t.useCallback)(async()=>{if(!(!s||g.current)){g.current=!0,p(!0);try{await s.loadOlder(i),h(void 0)}catch(e){e instanceof n.ErrorInfo?h(e):h(new n.ErrorInfo(`Unknown error loading older messages`,O.BadRequest,400))}finally{g.current=!1,p(!1)}}},[s,i]);return(0,t.useEffect)(()=>{!_||v.current||!s||(v.current=!0,y())},[_,s,y]),{messages:c,hasOlder:u,loading:f,loadError:m,loadOlder:y,runOf:(0,t.useCallback)(e=>s?.runOf(e),[s]),run:(0,t.useCallback)(e=>s?.run(e),[s]),runs:(0,t.useCallback)(()=>s?.runs()??[],[s]),branchSelection:(0,t.useCallback)(e=>s?.branchSelection(e)??dt,[s]),selectSibling:(0,t.useCallback)((e,t)=>{s?.selectSibling(e,t)},[s]),send:(0,t.useCallback)(async(e,t)=>{if(!s)throw new n.ErrorInfo(`unable to send; view is not available`,O.InvalidArgument,400);return s.send(e,t)},[s]),regenerate:(0,t.useCallback)(async(e,t)=>{if(!s)throw new n.ErrorInfo(`unable to regenerate; view is not available`,O.InvalidArgument,400);return s.regenerate(e,t)},[s]),edit:(0,t.useCallback)(async(e,t,r)=>{if(!s)throw new n.ErrorInfo(`unable to edit; view is not available`,O.InvalidArgument,400);return s.edit(e,t,r)},[s])}},pt=({session:e,limit:n,skip:r}={})=>{let i=ct({session:e,skip:r}),[a,o]=(0,t.useState)();return(0,t.useEffect)(()=>{if(!i){o(void 0);return}let e=i.createView();return o(e),()=>{e.close()}},[i]),ft({view:a,limit:n,skip:r})},mt=({session:e}={})=>{let n=ct({session:e});return{getRunNode:(0,t.useCallback)(e=>n?.tree.getRunNode(e),[n]),getNodeByCodecMessageId:(0,t.useCallback)(e=>n?.tree.getNodeByCodecMessageId(e),[n]),getSiblingNodes:(0,t.useCallback)(e=>n?.tree.getSiblingNodes(e)??[],[n])}},ht=()=>({ClientSessionProvider:st,useClientSession:e=>ut(e??{}),useView:e=>ft(e??{}),useTree:e=>mt(e??{}),useAblyMessages:e=>lt(e??{}),useCreateView:e=>pt(e??{})}),gt=class{constructor(e,t={}){this._trackers=new Map,this._pending=[],this._closed=!1,this._writer=e,this._defaultExtras=t.extras,this._onMessageHook=t.onMessage??(()=>{}),this._logger=t.logger?.withContext({component:`EncoderCore`})}async publishDiscrete(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.publishDiscrete();`,{name:e.name});let n=this._buildDiscreteMessage(e,t);return this._writer.publish(n)}async publishDiscreteBatch(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.publishDiscreteBatch();`,{count:e.length});let n=e.map(e=>this._buildDiscreteMessage(e,t,!0));return this._writer.publish(n)}async startStream(e,t,r){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.startStream();`,{name:t.name,streamId:e});let i=this._buildTransport(t.transportHeaders,r);i[x]=`true`,i[S]=`streaming`,i[te]=e;let a=t.codecHeaders??{},o={name:t.name,data:t.data,extras:{ai:this._aiExtras(i,a)}};this._invokeOnMessage(o);let s=(await this._writer.publish(o)).serials[0];if(!s)throw new n.ErrorInfo(`unable to start stream; no serial returned for stream '${t.name}' (streamId: ${e})`,O.BadRequest,400);this._trackers.set(e,{serial:s,name:t.name,streamId:e,accumulated:t.data,persistentTransport:i,persistentCodec:a,cancelled:!1,completed:!1}),this._logger?.debug(`DefaultEncoderCore.startStream(); stream started`,{name:t.name,streamId:e,serial:s})}appendStream(e,t){this._assertNotClosed();let r=this._trackers.get(e);if(!r)throw new n.ErrorInfo(`unable to append to stream; no active stream for streamId '${e}'`,O.InvalidArgument,400);r.accumulated+=t;let i={serial:r.serial,data:t,extras:{ai:this._aiExtras({...r.persistentTransport},{...r.persistentCodec})}};this._invokeOnMessage(i);let a=this._writer.appendMessage(i);this._pending.push({promise:a,streamId:e})}async closeStream(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.closeStream();`,{streamId:e});let r=this._trackers.get(e);if(!r)throw new n.ErrorInfo(`unable to close stream; no active stream for streamId '${e}'`,O.InvalidArgument,400);r.accumulated+=t.data,r.completed=!0;let{transport:i,codec:a}=this._buildClosing(r,t);i[S]=`complete`;let o={serial:r.serial,data:t.data,extras:{ai:this._aiExtras(i,a)}};this._invokeOnMessage(o);let s=this._writer.appendMessage(o);this._pending.push({promise:s,streamId:e}),await this._flushPending(),this._logger?.debug(`DefaultEncoderCore.closeStream(); stream closed`,{streamId:e})}async cancelAllStreams(e){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.cancelAllStreams();`,{streamCount:this._trackers.size});for(let t of this._trackers.values()){if(t.cancelled||t.completed)continue;t.cancelled=!0;let{transport:n,codec:r}=this._buildClosing(t,void 0,e);n[S]=`cancelled`;let i={serial:t.serial,data:``,extras:{ai:this._aiExtras(n,r)}};this._invokeOnMessage(i);let a=this._writer.appendMessage(i);this._pending.push({promise:a,streamId:t.streamId})}await this._flushPending()}async _flushPending(){if(this._flushPromise)return this._flushPromise;let e=this._pending;if(this._pending=[],e.length!==0){this._logger?.trace(`DefaultEncoderCore._flushPending();`,{count:e.length}),this._flushPromise=this._doFlush(e);try{await this._flushPromise}finally{this._flushPromise=void 0}}}async _doFlush(e){let t=await Promise.allSettled(e.map(async e=>e.promise)),r=new Set;for(let[n,i]of t.entries()){let t=e[n];t&&i.status===`rejected`&&r.add(t.streamId)}if(r.size===0){this._logger?.debug(`DefaultEncoderCore._flushPending(); all appends succeeded`);return}this._logger?.warn(`DefaultEncoderCore._flushPending(); recovering failed appends`,{failedStreams:[...r]});let i=[];for(let e of r){let t=this._trackers.get(e);if(!t)continue;let n=t.cancelled?`cancelled`:`complete`,r={serial:t.serial,data:t.accumulated,extras:{ai:this._aiExtras({...t.persistentTransport,[S]:n},{...t.persistentCodec})}};try{await this._writer.updateMessage(r)}catch(t){i.push({streamId:e,error:t})}}if(i.length>0){let e=i.map(e=>e.streamId).join(`, `);throw this._logger?.error(`DefaultEncoderCore._flushPending(); recovery failed`,{failedStreams:e}),new n.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${e}`,O.EncoderRecoveryFailed,500)}}async close(){if(!this._closed){this._logger?.trace(`DefaultEncoderCore.close();`),this._closed=!0;try{await this._flushPending()}finally{this._trackers.clear()}this._logger?.debug(`DefaultEncoderCore.close(); encoder closed`)}}_invokeOnMessage(e){try{this._onMessageHook(e)}catch(e){this._logger?.error(`DefaultEncoderCore._invokeOnMessage(); hook threw`,{error:e})}}_assertNotClosed(){if(this._closed)throw new n.ErrorInfo(`unable to write to encoder; encoder has been closed`,O.InvalidArgument,400)}_buildTransport(e,t){let n={...Ee(this._defaultExtras?.headers,t?.extras?.headers),...e};return t?.messageId!==void 0&&(n[E]=t.messageId),n}_aiExtras(e,t){return Object.keys(t).length>0?{transport:e,codec:t}:{transport:e}}_buildDiscreteMessage(e,t,n=!1){let r=this._buildTransport(e.transportHeaders,t);r[x]=`false`,n&&(r[ne]=`true`);let i={name:e.name,data:e.data,extras:{ai:this._aiExtras(r,e.codecHeaders??{}),...e.ephemeral?{ephemeral:!0}:{}}};return this._invokeOnMessage(i),i}_buildClosing(e,t,n){let r=Ee(this._defaultExtras?.headers,n?.extras?.headers);return{transport:{...e.persistentTransport,...r,...t?.transportHeaders},codec:{...e.persistentCodec,...t?.codecHeaders}}}},_t=(e,t={})=>new gt(e,t),vt=class{constructor(e,t={}){this._serialState=new Map,this._hooks=e,this._onStreamUpdate=t.onStreamUpdate,this._onStreamDelete=t.onStreamDelete,this._logger=t.logger?.withContext({component:`DecoderCore`})}decode(e){let t=e.action;switch(this._logger?.trace(`DefaultDecoderCore.decode();`,{action:t,serial:e.serial,name:e.name}),t){case`message.create`:{let t=this._toPayload(e);return t.transportHeaders?.stream===`true`?this._decodeStreamedCreate(t,e.serial,e.version.serial):this._hooks.decodeDiscrete(t)}case`message.append`:return this._decodeAppend(e);case`message.update`:return this._decodeUpdate(e);case`message.delete`:return this._decodeDelete(e);default:return[]}}_toPayload(e){return{name:e.name??``,data:e.data,transportHeaders:j(e),codecHeaders:Ce(e)}}_stringData(e){return typeof e.data==`string`?e.data:``}_invokeOnStreamUpdate(e){if(this._onStreamUpdate)try{this._onStreamUpdate(e)}catch(e){this._logger?.error(`DefaultDecoderCore._invokeOnStreamUpdate(); callback threw`,{error:e})}}_invokeOnStreamDelete(e,t){if(this._onStreamDelete)try{this._onStreamDelete(e,t)}catch(e){this._logger?.error(`DefaultDecoderCore._invokeOnStreamDelete(); callback threw`,{error:e})}}_alreadyIncorporated(e,t,n,r){return r!==void 0&&r<=n.version?(this._logger?.debug(`DefaultDecoderCore.${e}(); delivery already incorporated`,{serial:t,version:r,trackerVersion:n.version}),!0):n.closed?(this._logger?.debug(`DefaultDecoderCore.${e}(); stream closed, dropping delivery`,{serial:t,version:r}),!0):(r!==void 0&&(n.version=r),!1)}_closeTracker(e){e.closed=!0,e.accumulated=``}_applyTerminalStatus(e,t,n,r){return t===`complete`?(r.push(...this._hooks.buildEndEvents(e,n)),this._closeTracker(e),!0):t===`cancelled`?(this._closeTracker(e),!0):!1}_decodeStreamedCreate(e,t,n){if(!t)return[];if(this._serialState.get(t))return this._logger?.debug(`DefaultDecoderCore._decodeStreamedCreate(); duplicate create for tracked stream`,{serial:t}),[];let r=e.transportHeaders?.[`stream-id`]??``,i={name:e.name,streamId:r,accumulated:``,codecHeaders:{...e.codecHeaders},transportHeaders:{...e.transportHeaders},version:n??t,closed:!1};return this._serialState.set(t,i),this._logger?.debug(`DefaultDecoderCore._decodeStreamedCreate(); new stream`,{name:e.name,streamId:r,serial:t}),this._hooks.buildStartEvents(i)}_decodeAppend(e){let t=e.serial;if(!t)return[];let n=this._serialState.get(t);if(!n)return this._logger?.warn(`DefaultDecoderCore._decodeAppend(); append with no tracker, treating as first contact`,{serial:t}),this._decodeUpdate(e);if(this._alreadyIncorporated(`_decodeAppend`,t,n,e.version.serial))return[];let r=j(e),i=Ce(e),a=typeof e.data==`string`?e.data:``,o=r[S],s=[];return a.length>0&&(n.accumulated+=a,s.push(...this._hooks.buildDeltaEvents(n,a))),this._applyTerminalStatus(n,o,i,s)&&this._logger?.debug(`DefaultDecoderCore._decodeAppend(); stream ${o===`complete`?`complete`:`cancelled`}`,{streamId:n.streamId}),s}_decodeUpdate(e){let t=e.serial;if(!t)return[];let n=this._toPayload(e),r=n.transportHeaders??{},i=n.codecHeaders??{},a=r[x]===`true`,o=r[S],s=this._serialState.get(t);if(!s)return this._decodeFirstContact(n,a,o,t,e.version.serial);if(this._alreadyIncorporated(`_decodeUpdate`,t,s,e.version.serial))return[];let c=this._stringData(e);if(c.startsWith(s.accumulated)){let e=c.slice(s.accumulated.length),t=[];return e.length>0&&(s.accumulated=c,t.push(...this._hooks.buildDeltaEvents(s,e))),this._applyTerminalStatus(s,o,i,t),t}return s.accumulated=c,s.codecHeaders={...i},s.transportHeaders={...r},this._invokeOnStreamUpdate(s),[]}_decodeFirstContact(e,t,n,r,i){if(!t)return this._hooks.decodeDiscrete(e);let a=e.transportHeaders?.[`stream-id`]??``,o=e.codecHeaders??{},s=typeof e.data==`string`?e.data:``;this._logger?.debug(`DefaultDecoderCore._decodeFirstContact(); first-contact stream`,{name:e.name,streamId:a,serial:r});let c={name:e.name,streamId:a,accumulated:s,codecHeaders:{...o},transportHeaders:{...e.transportHeaders},version:i??r,closed:!1};this._serialState.set(r,c);let l=this._hooks.buildStartEvents(c);return s.length>0&&l.push(...this._hooks.buildDeltaEvents(c,s)),n===`complete`&&l.push(...this._hooks.buildEndEvents(c,o)),(n===`complete`||n===`cancelled`)&&this._closeTracker(c),l}_decodeDelete(e){let t=e.serial;if(!t)return[];let n=this._serialState.get(t);return this._invokeOnStreamDelete(t,n),n&&this._closeTracker(n),this._logger?.debug(`DefaultDecoderCore._decodeDelete();`,{serial:t}),[]}},yt=(e,t={})=>new vt(e,t),bt=class{constructor(e){this._emitted=new Map,this._phases=e}ensurePhases(e,t){let n=this._getOrCreate(e),r=[];for(let e of this._phases)n.has(e.key)||(n.add(e.key),r.push(...e.build(t)));return r}markEmitted(e,t){this._getOrCreate(e).add(t)}resetPhase(e,t){this._emitted.get(e)?.delete(t)}clearScope(e){this._emitted.delete(e)}_getOrCreate(e){let t=this._emitted.get(e);return t||(t=new Set,this._emitted.set(e,t)),t}},xt=e=>new bt(e);function I(e,t){return{key:e,read:n=>n[e]??t,write:(t,n)=>{typeof n==`string`&&(t[e]=n)}}}function L(e,t){return{key:e,read:n=>De(n[e])??t,write:(t,n)=>{typeof n==`boolean`&&(t[e]=String(n))}}}var St=e=>({key:e,read:t=>we(t[e]),write:(t,n)=>{n!=null&&(t[e]=JSON.stringify(n))}}),Ct=(e,t,n)=>({key:e,read:r=>{let i=r[e];return t.find(e=>e===i)??n},write:(t,n)=>{typeof n==`string`&&(t[e]=n)}}),wt=`kind`,Tt=`-*`,Et=e=>e.endsWith(Tt)?t=>t.startsWith(e.slice(0,-1)):void 0,Dt=`partType`,Ot=(e,t)=>e[t],kt=(e,t,n,r)=>{let i={[wt]:t};for(let t of e)r&&!r.includes(t.key)||t.write(i,Ot(n,t.key));return i},At=(e,t)=>e.find(e=>!e.match&&e.partType===t)??e.find(e=>e.match?.(t)),jt=e=>{let t=new Map,n=[];for(let r of e)r.construct===`event`&&(r.match?n.push(r):t.set(r.type,r));return{discreteByType:t,wildcards:n}},R=(e,t)=>{let n={};for(let r of e){let e=r.read(t);e!==void 0&&(n[r.key]=e)}return n},Mt=e=>{let t=new Map;for(let n of e)t.set(n.kind,n);let n=(e,t)=>{if(e.wireOnly)return[];let n=R(e.fields,t.codecHeaders);e.data&&Object.assign(n,e.data.decode(t.data));let r=t.transportHeaders[`codec-message-id`]??``;return[{kind:e.kind,codecMessageId:r,payload:M(n)}]},r=(e,t)=>{let n=t.codecHeaders.partType??``,r=At(e.parts,n);if(!r)return[];let i=R(r.fields,t.codecHeaders);r.data&&Object.assign(i,r.data.decode(t.data)),i.type=n;let a=e.assemble(M(i),{codecHeaders:t.codecHeaders,transportHeaders:t.transportHeaders});return[{kind:e.kind,...a}]};return{decode:e=>{let i=t.get(e.codecKind);return i?i.construct===`event`?n(i,e):r(i,e):[]}}},Nt=(e,t)=>t?.transportHeaders===void 0?e:{...e,transportHeaders:{...e.transportHeaders,...t.transportHeaders}},Pt=(e,t)=>{let r=new Map;for(let t of e)r.set(t.kind,t);let i=async(e,r,i,a)=>{if(e.wireOnly){await i.publishDiscrete({name:t,data:``,codecHeaders:{[wt]:e.kind}},a.opts);return}let o=Ot(r,`payload`);if(typeof o!=`object`||!o)throw new n.ErrorInfo(`unable to encode input; event '${e.kind}' carries no payload object — declare it wireOnly or use an encode escape hatch`,O.InvalidArgument,400);let s=kt(e.fields,e.kind,o),c=e.data?e.data.encode(o):``;await i.publishDiscrete({name:t,data:c,codecHeaders:s},a.opts)},a=async(e,n,r,i)=>{let a=e.messageHeaders?.(n),o=[];for(let r of e.explode(n)){let n=e.partTypeOf(r),i=At(e.parts,n);if(!i)continue;let s=r,c={...kt(i.fields,e.kind,s),...a?.codecHeaders,[Dt]:n},l=i.data?i.data.encode(r):``;o.push(Nt({name:t,data:l,codecHeaders:c},a))}o.length===0&&o.push(Nt({name:t,data:``,codecHeaders:{[wt]:e.kind,...a?.codecHeaders}},a)),await r.publishDiscreteBatch(o,i.opts)};return{encode:async(e,t,o)=>{let s=r.get(e.kind);if(!s)throw new n.ErrorInfo(`unable to publish; unsupported input kind '${e.kind}'`,O.InvalidArgument,400);await(s.construct===`event`?i(s,e,t,o):a(s,e,t,o))}}},Ft=()=>{let e=(e,t)=>{let n=Et(e);return{partType:e,...n?{match:n}:{},fields:t.fields??[],data:t.data}};return{event:(e,t)=>{let n=t;return{construct:`event`,kind:e,fields:n?.fields??[],data:n?.data,wireOnly:n?.wireOnly??!1}},batch:(t,n)=>{let r=n.parts(e);return{construct:`batch`,kind:t,explode:n.explode,partTypeOf:n.partTypeOf,parts:r,messageHeaders:n.messageHeaders,assemble:n.assemble}}}},It=`type`,Lt=e=>{let{discreteByType:t,wildcards:n}=jt(e),r=new Map;for(let t of e)t.construct===`stream`&&r.set(t.kind,t);let i=(e,t)=>(t[It]=e,M(t)),a=(e,t,n)=>{let r=R(e.fields,n.codecHeaders);return e.data&&Object.assign(r,e.data.decode(n.data)),[i(t,r)]},o=e=>r.get(e.codecHeaders.kind??``);return{buildStart:e=>{let t=o(e);if(!t)return[];let n=R(t.fields,e.codecHeaders);return n[t.idField]=e.streamId,[i(t.start,n)]},buildDelta:(e,t)=>{let n=o(e);if(!n)return[];let r={[n.idField]:e.streamId,[n.deltaField]:t};return[i(n.delta,r)]},buildEnd:(e,t)=>{let n=o(e);if(!n)return[];if(n.decodeEnd)return n.decodeEnd({streamId:e.streamId,accumulated:e.accumulated,codecHeaders:e.codecHeaders,closingCodecHeaders:t});let r=R(n.fields,t);return r[n.idField]=e.streamId,[i(n.end,r)]},decodeDiscrete:(e,i,o,s)=>{let c={codecKind:e,codecHeaders:i,transportHeaders:o,data:s},l=t.get(e);if(l)return a(l,e,c);let u=r.get(e);if(u?.decodeDiscrete)return u.decodeDiscrete(c);let d=n.find(t=>t.match?.(e));return d?a(d,e,c):[]}}},Rt=(e,t)=>{let{discreteByType:r,wildcards:i}=jt(e),a=new Map;for(let t of e)t.construct===`stream`&&(a.set(t.start,{descriptor:t,phase:`start`}),a.set(t.delta,{descriptor:t,phase:`delta`}),a.set(t.end,{descriptor:t,phase:`end`}));return{encode:async(e,o,s)=>{let{type:c}=e,l=a.get(c);if(l){let{descriptor:n,phase:r}=l,i=(e,t)=>kt(n.fields,n.kind,e,t),a=Ot(e,n.idField);r===`start`?await o.startStream(a,{name:t,data:``,codecHeaders:i(e)},s.opts):r===`delta`?o.appendStream(a,Ot(e,n.deltaField)):n.onEnd?await n.onEnd(e,o,{h:i,name:t,messageId:s.messageId,opts:s.opts}):await o.closeStream(a,{name:t,data:``,codecHeaders:i(e)});return}let u=r.get(c)??i.find(e=>e.match?.(c));if(!u)throw new n.ErrorInfo(`unable to publish; unsupported event type '${c}'`,O.InvalidArgument,400);let d=(e,t)=>kt(u.fields,e.type,e,t);if(u.encode){await u.encode(e,o,{h:d,name:t,messageId:s.messageId,opts:s.opts});return}let f=u.data?u.data.encode(e):``;await o.publishDiscrete({name:t,data:f,codecHeaders:d(e),ephemeral:u.ephemeral?.(e)},s.opts)}}},zt=()=>({event:(e,t)=>({construct:`event`,type:e,fields:t?.fields??[],data:t?.data,ephemeral:t?.ephemeral,match:Et(e),encode:t?.encode}),stream:(e,t)=>({construct:`stream`,kind:e,...t})}),Bt=()=>({createUserMessage:e=>({kind:`user-message`,message:e}),createRegenerate:(e,t)=>({kind:`regenerate`,target:e,parent:t}),createToolResult:(e,t)=>({kind:`tool-result`,codecMessageId:e,payload:t}),createToolResultError:(e,t)=>({kind:`tool-result-error`,codecMessageId:e,payload:t}),createToolApprovalResponse:(e,t)=>({kind:`tool-approval-response`,codecMessageId:e,payload:t})}),Vt=class{constructor(e,t,n,r){this._core=_t(e,t),this._messageId=t.messageId,this._outputEncoder=n,this._inputEncoder=r}async publishInput(e,t){await this._inputEncoder.encode(e,this._core,{opts:t})}async publishOutput(e,t){await this._outputEncoder.encode(e,this._core,{messageId:this._messageId,opts:t})}async cancelStreams(){await this._core.cancelAllStreams()}async close(){await this._core.close()}},Ht=(e,t,n,r)=>{let i=e.codecHeaders??{},a=e.transportHeaders??{},o=i.kind??``;if(e.name===`ai-input`)return n.decode({codecKind:o,data:e.data,codecHeaders:i,transportHeaders:a});if(e.name===`ai-output`){let n=a[`run-id`]??``,s=r?.onDiscrete;return[...(s!==void 0&&Object.hasOwn(s,o)?s[o]:void 0)?.(n,{codecHeaders:i})??[],...t.decodeDiscrete(o,i,a,e.data)]}return[]},Ut=e=>e.name===de,Wt=(e,t,n)=>({buildStartEvents:t=>{if(!Ut(t))return[];let r=t.transportHeaders[`run-id`]??``;return[...n?.onStreamStart?.(r,t)??[],...e.buildStart(t)]},buildDeltaEvents:(t,n)=>Ut(t)?e.buildDelta(t,n):[],buildEndEvents:(t,n)=>Ut(t)?e.buildEnd(t,n):[],decodeDiscrete:r=>Ht(r,e,t,n)}),Gt=class{constructor(e){this._core=e}decode(e){let t=this._core.decode(e);return e.name===`ai-input`?{inputs:t,outputs:[]}:{inputs:[],outputs:t}}},z=(e,t,r)=>{let i=e.get(t);if(i!==void 0)throw new n.ErrorInfo(`unable to define codec; dispatch literal '${t}' is declared by both ${i} and ${r}`,O.InvalidArgument,400);e.set(t,r)},B=(e,t)=>{for(let r of e)if(r.key===`kind`||r.key===`partType`)throw new n.ErrorInfo(`unable to define codec; ${t} binds the driver-reserved header key '${r.key}'`,O.InvalidArgument,400)},Kt=(e,t)=>{let n=new Map,r=new Map;for(let t of e)if(t.construct===`event`){let e=`output event '${t.type}'`;z(n,t.type,e),z(r,t.type,e),B(t.fields,e)}else{let e=`output stream '${t.kind}'`;z(r,t.kind,e);for(let r of[t.start,t.delta,t.end])z(n,r,e);B(t.fields,e)}let i=new Map;for(let e of t){let t=`input ${e.construct} '${e.kind}'`;if(z(i,e.kind,t),e.construct===`event`)B(e.fields,t);else{let n=new Map;for(let r of e.parts){let e=`${t} part '${r.partType}'`;z(n,r.partType,e),B(r.fields,e)}}}},qt=()=>e=>{let{reducer:t,decodeLifecycle:n}=e,r=e.output(zt()),i=e.input(Ft());Kt(r,i);let a=Rt(r,de),o=Pt(i,fe),s=Lt(r),c=Mt(i);return{...e.adapterTag===void 0?{}:{adapterTag:e.adapterTag},init:t.init,fold:t.fold,getMessages:t.getMessages,createEncoder:(e,t={})=>new Vt(e,t,a,o),createDecoder:()=>new Gt(yt(Wt(s,c,n?.()),{})),...Bt()}},Jt=I(`id`),V=St(`providerMetadata`),H=I(`toolCallId`,``),U=I(`toolName`,``),W=L(`dynamic`),Yt=I(`title`),G=L(`providerExecuted`),Xt=I(`mediaType`,``),Zt=I(`sourceId`,``),K=I(`messageId`),Qt=L(`approved`,!1),$t=I(`reason`),en=Ct(`finishReason`,[`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`],`stop`),tn=()=>xt([{key:`start`,build:e=>[M({type:`start`,messageId:e.messageId})]},{key:`start-step`,build:()=>[{type:`start-step`}]}]),nn=()=>{let e=tn();return{onDiscrete:{start:t=>(e.markEmitted(t,`start`),[]),"start-step":t=>(e.markEmitted(t,`start-step`),[]),"finish-step":t=>(e.resetPhase(t,`start-step`),[]),finish:t=>(e.clearScope(t),[]),error:t=>(e.clearScope(t),[]),abort:t=>(e.clearScope(t),[]),"tool-input":(t,n)=>e.ensurePhases(t,{messageId:K.read(n.codecHeaders)})},onStreamStart:(t,n)=>e.ensurePhases(t,{messageId:K.read(n.codecHeaders)})}},rn=e=>typeof e==`object`&&!!e,an=(e,t)=>rn(e)&&(e[t]===void 0||typeof e[t]==`string`),q=e=>typeof e==`string`?e:``,on=e=>an(e,`errorText`),sn=e=>rn(e),cn=e=>an(e,`errorText`),ln=e=>an(e,`message`),un=[{type:`text`,text:``}],dn=e=>e.type===`text`||e.type===`file`||e.type.startsWith(`data-`),fn=({event:e,batch:t})=>[e(`tool-result`,{fields:[H],data:{encode:e=>({output:e.output}),decode:e=>({output:sn(e)?e.output:void 0})}}),e(`tool-result-error`,{fields:[H],data:{encode:e=>({message:e.message}),decode:e=>({message:ln(e)?e.message??``:``})}}),e(`tool-approval-response`,{fields:[H,Qt,$t]}),e(`regenerate`,{wireOnly:!0}),t(`user-message`,{explode:e=>{let t=e.message.parts.filter(e=>dn(e));return t.length>0?t:un},partTypeOf:e=>e.type,parts:e=>[e(`text`,{data:{encode:e=>e.text,decode:e=>({text:q(e)})}}),e(`file`,{fields:[Xt],data:{encode:e=>e.url,decode:e=>({url:q(e)})}}),e(`data-*`,{fields:[Jt],data:{encode:e=>e.data,decode:e=>({data:e})}})],messageHeaders:e=>{let t={};return K.write(t,e.message.id),{codecHeaders:t,transportHeaders:{[ae]:e.message.role}}},assemble:(e,{codecHeaders:t,transportHeaders:n})=>{let r=n.role??`user`;return{message:{id:K.read(t)??``,role:r,parts:[e]}}}})],pn=({event:e,stream:t})=>[t(`text`,{start:`text-start`,delta:`text-delta`,end:`text-end`,idField:`id`,deltaField:`delta`,fields:[Jt,V]}),t(`reasoning`,{start:`reasoning-start`,delta:`reasoning-delta`,end:`reasoning-end`,idField:`id`,deltaField:`delta`,fields:[Jt,V]}),t(`tool-input`,{start:`tool-input-start`,delta:`tool-input-delta`,end:`tool-input-available`,idField:`toolCallId`,deltaField:`inputTextDelta`,fields:[H,U,W,Yt,G,V],onEnd:async(e,t,{h:r,name:i})=>{try{await t.closeStream(e.toolCallId,{name:i,data:``,codecHeaders:r(e,[`toolCallId`,`toolName`,`providerMetadata`])})}catch(a){if(!(a instanceof n.ErrorInfo&&pe(a,O.InvalidArgument)))throw a;await t.publishDiscrete({name:i,data:e.input,codecHeaders:r(e)})}},decodeEnd:({streamId:e,accumulated:t,codecHeaders:n,closingCodecHeaders:r})=>[M({type:`tool-input-available`,toolCallId:e,toolName:U.read(r)||U.read(n),input:Te(t),providerMetadata:V.read(r)})],decodeDiscrete:({codecHeaders:e,data:t})=>[M({type:`tool-input-start`,toolCallId:H.read(e),toolName:U.read(e),dynamic:W.read(e),title:Yt.read(e),providerExecuted:G.read(e),providerMetadata:V.read(e)}),M({type:`tool-input-available`,toolCallId:H.read(e),toolName:U.read(e),input:t,providerMetadata:V.read(e)})]}),e(`start`,{fields:[K,St(`messageMetadata`)],encode:async(e,t,{h:n,name:r,messageId:i,opts:a})=>{await t.publishDiscrete({name:r,data:``,codecHeaders:n({...e,messageId:e.messageId??i})},a)}}),e(`start-step`),e(`finish-step`),e(`finish`,{fields:[en,St(`messageMetadata`)]}),e(`message-metadata`,{fields:[St(`messageMetadata`)]}),e(`error`,{data:{encode:e=>e.errorText,decode:e=>({errorText:q(e)})}}),e(`abort`,{data:{encode:e=>e.reason??``,decode:e=>typeof e==`string`&&e?{reason:e}:{}}}),e(`file`,{fields:[Xt,V],data:{encode:e=>e.url,decode:e=>({url:q(e)})}}),e(`source-url`,{fields:[Zt,Yt,V],data:{encode:e=>e.url,decode:e=>({url:q(e)})}}),e(`source-document`,{fields:[Zt,Xt,I(`title`,``),I(`filename`),V]}),e(`tool-input-error`,{fields:[H,U,W,Yt,G,V],data:{encode:e=>({errorText:e.errorText,input:e.input}),decode:e=>on(e)?{errorText:e.errorText??``,input:e.input}:{errorText:``}}}),e(`tool-output-available`,{fields:[H,W,G,L(`preliminary`)],data:{encode:e=>({output:e.output}),decode:e=>sn(e)?{output:e.output}:{}}}),e(`tool-output-error`,{fields:[H,W,G],data:{encode:e=>({errorText:e.errorText}),decode:e=>({errorText:cn(e)?e.errorText??``:``})}}),e(`tool-approval-request`,{fields:[H,I(`approvalId`,``)]}),e(`tool-output-denied`,{fields:[H]}),e(`data-*`,{fields:[Jt,L(`transient`)],ephemeral:e=>e.transient===!0,data:{encode:e=>e.data,decode:e=>({data:e})}})],mn=()=>({messages:[],trackers:new Map,pendingToolResolutions:[]}),J=(e,t)=>{let n=e.messages.find(e=>e.codecMessageId===t);return n||(n={codecMessageId:t,message:{id:t,role:`assistant`,parts:[]}},e.messages.push(n)),n.message},hn=(e,t)=>{let n=e.trackers.get(t);return n||(n={text:new Map,reasoning:new Map,tools:new Map},e.trackers.set(t,n)),n},Y=(e,t,n)=>{let r=t.tools.get(n);if(!r)return;let i=e.parts[r.partIndex];if(i?.type===`dynamic-tool`)return{tracker:r,part:i}},gn=(e,t,n)=>{let r=J(e,n);switch(t.type){case`file`:return r.parts.push({type:`file`,mediaType:t.mediaType,url:t.url}),e;case`source-url`:return r.parts.push(M({type:`source-url`,sourceId:t.sourceId,url:t.url,title:t.title})),e;case`source-document`:return r.parts.push(M({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title,filename:t.filename})),e}},_n=(e,t,n)=>{if(t.transient)return e;let r=J(e,n),i=M({type:t.type,id:t.id,data:t.data});if(t.id!==void 0){let n=r.parts.findIndex(e=>e.type===t.type&&`id`in e&&e.id===t.id);if(n!==-1)return r.parts[n]=i,e}return r.parts.push(i),e},X=e=>M({type:`dynamic-tool`,toolCallId:e.toolCallId,toolName:e.toolName,title:e.title,providerExecuted:e.providerExecuted}),Z=(e,t)=>{let n=X(e);switch(t.type){case`tool-output-available`:return M({...n,state:`output-available`,input:e.input,output:t.output,preliminary:t.preliminary});case`tool-output-error`:return{...n,state:`output-error`,input:e.input,errorText:t.errorText};case`tool-output-denied`:return{...n,state:`output-denied`,input:e.input,approval:{id:``,approved:!1}};case`tool-approval-request`:return{...n,state:`approval-requested`,input:e.input,approval:{id:t.approvalId}}}},vn=(e,t,n)=>{let r=n.messageId;if(r===void 0)return e.messages.push({codecMessageId:t.id,message:t}),e;let i=e.messages.find(e=>e.codecMessageId===r);return i===void 0?e.messages.push({codecMessageId:r,message:t}):i.message.parts.push(...t.parts),e},yn=(e,t)=>{let{toolCallId:n,output:r}=t.payload;return Sn(e,t.codecMessageId,n,{kind:`tool-result`,output:r})},bn=(e,t)=>{let{toolCallId:n,message:r}=t.payload;return Sn(e,t.codecMessageId,n,{kind:`tool-result-error`,message:r})},xn=(e,t)=>{let{toolCallId:n,approved:r,reason:i}=t.payload;return Sn(e,t.codecMessageId,n,{kind:`tool-approval-response`,approved:r,...i===void 0?{}:{reason:i}})},Sn=(e,t,n,r)=>{let i=Tn(e,t,n);return i?Cn(i,n,r):e.pendingToolResolutions.push({targetCodecMessageId:t,toolCallId:n,resolution:r}),e},Cn=(e,t,n)=>{switch(n.kind){case`tool-result`:e.message.parts[e.tracker.partIndex]=Z(e.part,{type:`tool-output-available`,toolCallId:t,output:n.output});break;case`tool-result-error`:e.message.parts[e.tracker.partIndex]=Z(e.part,{type:`tool-output-error`,toolCallId:t,errorText:n.message});break;case`tool-approval-response`:e.message.parts[e.tracker.partIndex]=En(e.part,n.approved,n.reason);break}},wn=e=>{let t=[];for(let n of e.pendingToolResolutions){let r=Tn(e,n.targetCodecMessageId,n.toolCallId);if(!r){t.push(n);continue}Cn(r,n.toolCallId,n.resolution)}e.pendingToolResolutions=t},Tn=(e,t,n)=>{let r=e.messages.find(e=>e.codecMessageId===t);if(!r)return;let i=hn(e,t),a=Y(r.message,i,n);if(a)return{message:r.message,tracker:a.tracker,part:a.part}},En=(e,t,n)=>t?{...X(e),state:`approval-responded`,input:`input`in e?e.input:void 0,approval:{id:`approval`in e&&e.approval?e.approval.id:``,approved:!0,...n===void 0?{}:{reason:n}}}:Z(e,{type:`tool-output-denied`,toolCallId:e.toolCallId,...n===void 0?{}:{reason:n}}),Dn=(e,t,n)=>{if(n===void 0)return;let r=e.messages.find(e=>e.codecMessageId===t)?.message;r&&(r.metadata=n)},On=(e,t,n)=>{switch(t.type){case`start`:{let r=J(e,n);return t.messageId!==void 0&&(r.id=t.messageId),t.messageMetadata!==void 0&&(r.metadata=t.messageMetadata),e}case`start-step`:return J(e,n).parts.push({type:`step-start`}),e;case`finish-step`:{let t=e.trackers.get(n);return t&&(t.text.clear(),t.reasoning.clear()),e}case`finish`:return Dn(e,n,t.messageMetadata),e;case`abort`:case`error`:return e;case`message-metadata`:return Dn(e,n,t.messageMetadata),e}},kn=(e,t,n)=>{let r=J(e,n),i=hn(e,n),a=t.type.startsWith(`text-`),o=a?`text`:`reasoning`,s=a?i.text:i.reasoning;switch(t.type){case`text-start`:case`reasoning-start`:return s.set(t.id,r.parts.length),r.parts.push({type:o,text:``}),e;case`text-delta`:case`reasoning-delta`:{let n=s.get(t.id);if(n===void 0)return e;let i=r.parts[n];return i?.type===o&&(i.text+=t.delta),e}case`text-end`:case`reasoning-end`:return s.delete(t.id),e}},An=(e,t,n)=>{let r=J(e,n),i=hn(e,n);switch(t.type){case`tool-input-start`:{let n=r.parts.length;return r.parts.push({...X(t),state:`input-streaming`,input:void 0}),i.tools.set(t.toolCallId,{partIndex:n,inputText:``}),e}case`tool-input-delta`:{let n=i.tools.get(t.toolCallId);if(!n)return e;n.inputText+=t.inputTextDelta;let a=we(n.inputText),o=Y(r,i,t.toolCallId);return o&&(r.parts[o.tracker.partIndex]={...X(o.part),state:`input-streaming`,input:a}),e}case`tool-input-available`:{let n=Y(r,i,t.toolCallId);return n&&(r.parts[n.tracker.partIndex]={...X(n.part),state:`input-available`,input:t.input}),e}case`tool-input-error`:{let n=Y(r,i,t.toolCallId);if(n)r.parts[n.tracker.partIndex]={...X(n.part),state:`output-error`,input:t.input,errorText:t.errorText};else{let e=r.parts.length;r.parts.push({...X(t),state:`output-error`,input:t.input,errorText:t.errorText}),i.tools.set(t.toolCallId,{partIndex:e,inputText:``})}return e}}},jn=(e,t)=>{for(let n of e.messages){let r=e.trackers.get(n.codecMessageId);if(!r)continue;let i=Y(n.message,r,t);if(i)return{message:n.message,tracker:i.tracker,part:i.part}}},Mn=(e,t,n)=>{if(t.type===`tool-output-available`||t.type===`tool-output-error`){let n=jn(e,t.toolCallId);return n&&(n.message.parts[n.tracker.partIndex]=Z(n.part,t)),e}let r=J(e,n),i=Y(r,hn(e,n),t.toolCallId);return i&&(r.parts[i.tracker.partIndex]=Z(i.part,t)),e},Nn=(e,t,n)=>{if(t.direction===`input`){let r=t.event;switch(r.kind){case`user-message`:vn(e,r.message,n);break;case`regenerate`:break;case`tool-result`:yn(e,r);break;case`tool-result-error`:bn(e,r);break;case`tool-approval-response`:xn(e,r);break}}else Pn(e,t.event,n);return e.pendingToolResolutions.length>0&&wn(e),e},Pn=(e,t,n)=>{let r=n.messageId;if(r===void 0)return e;switch(t.type){case`start`:case`start-step`:case`finish-step`:case`finish`:case`abort`:case`error`:case`message-metadata`:return On(e,t,r);case`text-start`:case`text-delta`:case`text-end`:case`reasoning-start`:case`reasoning-delta`:case`reasoning-end`:return kn(e,t,r);case`tool-input-start`:case`tool-input-delta`:case`tool-input-available`:case`tool-input-error`:return An(e,t,r);case`tool-output-available`:case`tool-output-error`:case`tool-output-denied`:case`tool-approval-request`:return Mn(e,t,r);case`file`:case`source-url`:case`source-document`:return gn(e,t,r);default:return t.type.startsWith(`data-`)?_n(e,t,r):e}},Q=qt()({adapterTag:`vercel-ai-sdk-ui-message`,reducer:{init:mn,fold:Nn,getMessages:e=>e.messages},output:pn,input:fn,decodeLifecycle:nn}),$=e=>(e.type===`dynamic-tool`||e.type.startsWith(`tool-`))&&`toolCallId`in e&&`state`in e,Fn=e=>e.type===`finish`||e.type===`error`||e.type===`abort`,In=(e,t,r)=>{let i={},a=[],o=new ReadableStream({start:e=>{i.controller=e},cancel:()=>{u()}}),{controller:s}=i;if(!s)throw new n.ErrorInfo(`unable to create run stream; ReadableStream start() was not called synchronously`,O.SessionSubscriptionError,500);let c;t.then(e=>{c=e},()=>{});let l=!1,u=()=>{for(let e of a)e();a.length=0},d=e=>{if(!l){l=!0;try{e()}catch{}u()}},f=()=>{d(()=>{s.close()})},p=e=>{d(()=>{s.error(e)})};return a.push(e.tree.on(`output`,e=>{if(e.inputCodecMessageId===r)for(let t of e.events){try{s.enqueue(t)}catch{f();return}if(Fn(t)){f();return}}}),e.tree.on(`run`,e=>{e.type===`end`&&c!==void 0&&e.runId===c&&f()}),e.on(`error`,e=>{p(e)})),{stream:o,close:f}},Ln=`/api/chat`,Rn=e=>{let t,n=new Promise(e=>{t=e}),r=new TransformStream({flush:()=>{t()}}),i=new AbortController;return e.pipeTo(r.writable,{signal:i.signal,preventCancel:!0}).catch(()=>{t()}),{stream:r.readable,done:n,fail:e=>{i.abort(e)}}},zn=e=>e.role===`assistant`&&e.parts.some(e=>$(e)&&(e.state===`input-streaming`||e.state===`input-available`||e.state===`approval-requested`)),Bn=new Set([`input-streaming`,`input-available`,`approval-requested`]),Vn=(e,t)=>{let n=[];for(let r of t){if(r.role!==`assistant`)continue;let t=e.find(e=>e.message.id===r.id);if(!t)continue;let{codecMessageId:i,message:a}=t;for(let e of r.parts){if(!$(e))continue;let t=a.parts.find(t=>$(t)&&t.toolCallId===e.toolCallId);if(e.state===`approval-responded`&&(!t||t.state===`approval-requested`)){n.push(Q.createToolApprovalResponse(i,{toolCallId:e.toolCallId,approved:e.approval.approved,...e.approval.reason===void 0?{}:{reason:e.approval.reason}}));continue}e.state!==`output-available`&&e.state!==`output-error`||t&&!Bn.has(t.state)||(e.state===`output-available`?n.push(Q.createToolResult(i,{toolCallId:e.toolCallId,output:e.output})):n.push(Q.createToolResultError(i,{toolCallId:e.toolCallId,message:e.errorText})))}}return n},Hn=(e,t)=>{let n=e.findIndex(e=>e.message.id===t);if(!(n<=0))return e[n-1]?.codecMessageId},Un=(e,t)=>{let r=t?.api??Ln,i=t?.fetch??globalThis.fetch.bind(globalThis),a=t?.credentials,o=!1,s=new ge(ye({logLevel:_e.Silent})),c=e=>{o=e,s.emit(`streaming`,e)};return{sendMessages:async o=>{let{messages:s,abortSignal:l,trigger:u,messageId:d}=o,f=e.view.getMessages(),p=new Map(f.map(e=>[e.message.id,e.codecMessageId])),m=e=>p.get(e),h=s.at(-1),g=!!h&&p.has(h.id),_=u===`submit-message`&&h?.role===`assistant`&&g,v=u===`submit-message`&&!d&&h?.role===`user`?s.at(-2):void 0,y=v&&zn(v)&&p.has(v.id)?v.id:void 0,b,ee;if(u===`regenerate-message`||_)b=[],ee=s;else{if(s.length===0)throw new n.ErrorInfo(`unable to send messages; messages array is empty for submit-message trigger`,O.InvalidArgument,400);b=[s.at(-1)],ee=y?s.slice(0,-2):s.slice(0,-1)}let x,S;u===`submit-message`&&d&&!_?(x=m(d),S=Hn(f,d)):y&&(x=m(y),S=Hn(f,y));let te,ne;if(t?.prepareSendMessagesRequest){let e=t.prepareSendMessagesRequest({chatId:o.chatId,trigger:u,messageId:d,history:ee,messages:b,forkOf:x,parent:S});te=e.body??{},ne=e.headers}else te={},ne=void 0;let C={};if(x!==void 0&&(C.forkOf=x),S!==void 0&&(C.parent=S),_){let t=m(h.id),n=t===void 0?void 0:e.view.runOf(t);n&&(C.runId=n.runId)}let w;if(_){let t=Vn(f,s);w=await e.view.send(t,C)}else if(u===`regenerate-message`){if(d===void 0)throw new n.ErrorInfo(`unable to regenerate; regenerate-message trigger fired without messageId`,O.InvalidArgument,400);let t=m(d);if(t===void 0)throw new n.ErrorInfo(`unable to regenerate; message not visible: ${d}`,O.InvalidArgument,400);w=await e.view.regenerate(t,C)}else{let t=b.map(e=>Q.createUserMessage(e));w=await e.view.send(t,C)}let T=In(e,w.runId,w.inputCodecMessageId);if(l){let e=()=>{w.cancel(),T.close()};l.aborted?e():l.addEventListener(`abort`,e,{once:!0})}let{stream:E,done:re,fail:ie}=Rn(T.stream);c(!0),re.then(()=>{c(!1)});let ae={...te,...w.toInvocation().toJSON()};return i(r,{method:`POST`,headers:{"Content-Type":`application/json`,...ne},body:JSON.stringify(ae),...a?{credentials:a}:{}}).then(e=>{e.ok||ie(new n.ErrorInfo(`unable to send; HTTP POST to ${r} returned ${String(e.status)} ${e.statusText}`,O.SessionSendFailed,e.status))}).catch(e=>{ie(new n.ErrorInfo(`unable to send; HTTP POST to ${r} failed: ${k(e)}`,O.SessionSendFailed,500,A(e)))}),E},reconnectToStream:()=>Promise.resolve(null),close:async()=>e.close(),get streaming(){return o},onStreamingChange:e=>(s.on(`streaming`,e),()=>{s.off(`streaming`,e)})}},Wn=(0,t.createContext)({nearest:void 0,providers:{}}),{ClientSessionProvider:Gn,useAblyMessages:Kn,useClientSession:qn,useCreateView:Jn,useTree:Yn,useView:Xn}=ht(),Zn=({channelName:e,chatTransportOptions:n,children:r})=>{let{session:a,sessionError:o}=qn(),{providers:s}=(0,t.useContext)(Wn),c=(0,t.useMemo)(()=>Un(a,n),[a,n]),l=(0,t.useMemo)(()=>{let t={session:a,sessionError:o,chatTransport:c};return{nearest:t,providers:{...s,[e]:t}}},[e,s,c,a,o]);return(0,i.jsx)(Wn.Provider,{value:l,children:r})},Qn=({api:e,credentials:n,fetch:r,chatOptions:a,children:o,...s})=>{let c=(0,t.useMemo)(()=>({...a,...e!==void 0&&{api:e},...n!==void 0&&{credentials:n},...r!==void 0&&{fetch:r}}),[e,n,r,a]);return(0,i.jsx)(Gn,{...s,codec:Q,children:(0,i.jsx)(Zn,{channelName:s.channelName,chatTransportOptions:c,children:o})})},$n={sendMessages:()=>{throw new n.ErrorInfo(`unable to send messages; hook is skipped`,O.InvalidArgument,400)},reconnectToStream:()=>{throw new n.ErrorInfo(`unable to reconnect to stream; hook is skipped`,O.InvalidArgument,400)},close:()=>{throw new n.ErrorInfo(`unable to close; hook is skipped`,O.InvalidArgument,400)},get streaming(){throw new n.ErrorInfo(`unable to access streaming; hook is skipped`,O.InvalidArgument,400)},onStreamingChange:()=>{throw new n.ErrorInfo(`unable to subscribe to streaming changes; hook is skipped`,O.InvalidArgument,400)}},er=({channelName:e,skip:r}={})=>{let{nearest:i,providers:a}=(0,t.useContext)(Wn);if(r)return{session:F(),chatTransport:$n};if(e!==void 0){let t=a[e];return t?{session:t.session,chatTransport:t.chatTransport,sessionError:t.sessionError}:{session:F(),chatTransport:$n,sessionError:new n.ErrorInfo(`unable to use client session; no ClientSessionProvider found for channelName "${e}"`,O.BadRequest,400),chatTransportError:new n.ErrorInfo(`unable to use chat transport; no ChatTransportProvider found for channelName "${e}"`,O.BadRequest,400)}}return i?{session:i.session,chatTransport:i.chatTransport,sessionError:i.sessionError}:{session:F(),chatTransport:$n,sessionError:new n.ErrorInfo(`unable to use session; no ClientSessionProvider found in the tree`,O.BadRequest,400),chatTransportError:new n.ErrorInfo(`unable to use chat transport; no ChatTransportProvider found in the tree`,O.BadRequest,400)}},tr=new Set([`output-available`,`output-error`,`approval-responded`,`output-denied`]),nr=(e,t)=>{let n=new Map;for(let e of t.parts)$(e)&&n.set(e.toolCallId,e);if(n.size===0)return e;let r=e.parts.map(e=>{if(!$(e)||tr.has(e.state))return e;let t=n.get(e.toolCallId);return!t||!tr.has(t.state)?e:{...t,type:e.type}});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e},rr=(e,t)=>{if(t.length===0)return e;let n=new Map(t.map(e=>[e.id,e]));return e.map(e=>{if(e.role!==`assistant`)return e;let t=n.get(e.id);return t?nr(e,t):e})};e.ChatTransportProvider=Qn,e.ClientSessionProvider=Gn,e.useAblyMessages=Kn,e.useChatTransport=er,e.useClientSession=qn,e.useCreateView=Jn,e.useMessageSync=({setMessages:e,channelName:n,skip:r})=>{let{session:i,chatTransport:a,chatTransportError:o}=er({channelName:n,skip:r}),s=!r&&!o,c=s?i.view:void 0,l=s?a:void 0,[u,d]=(0,t.useState)(!1);(0,t.useEffect)(()=>{if(!l){d(!1);return}return d(l.streaming),l.onStreamingChange(d)},[l]),(0,t.useEffect)(()=>{if(!c||u)return;let t=()=>{e(e=>rr(c.getMessages().map(e=>e.message),e))};return t(),c.on(`update`,t)},[c,e,u])},e.useTree=Yn,e.useView=Xn});
71
2
  //# sourceMappingURL=ably-ai-transport-vercel-react.umd.cjs.map