@web-applets/inspector 0.2.3 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/web/assets/index-Br64umEE.js +326 -0
- package/dist/web/dist/assets/index-BBmcc9L3.js +326 -0
- package/dist/web/dist/assets/index-BJ9SEuhp.js +326 -0
- package/dist/web/dist/assets/index-BnvWkhAG.js +326 -0
- package/dist/web/dist/assets/index-Bu4KyuKN.js +326 -0
- package/dist/web/{assets/index-AMdeMxa5.js → dist/assets/index-COcILV0O.js} +1 -1
- package/dist/web/dist/assets/index-CyrPklJ6.js +326 -0
- package/dist/web/dist/assets/index-DGr96Ien.css +1 -0
- package/dist/web/dist/assets/index-D_CHzArx.js +326 -0
- package/dist/web/dist/assets/index-Dq8R7Wz6.js +326 -0
- package/dist/web/dist/assets/index-Hy6Hlya-.js +326 -0
- package/dist/web/dist/index.html +13 -0
- package/dist/web/index.html +1 -1
- package/package.json +2 -2
@@ -0,0 +1,326 @@
|
|
1
|
+
(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(s){if(s.ep)return;s.ep=!0;const a=r(s);fetch(s.href,a)}})();/**
|
2
|
+
* @license
|
3
|
+
* Copyright 2019 Google LLC
|
4
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
5
|
+
*/const jr=globalThis,ss=jr.ShadowRoot&&(jr.ShadyCSS===void 0||jr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,va=Symbol(),ks=new WeakMap;let ho=class{constructor(e,r,n){if(this._$cssResult$=!0,n!==va)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=r}get styleSheet(){let e=this.o;const r=this.t;if(ss&&e===void 0){const n=r!==void 0&&r.length===1;n&&(e=ks.get(r)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&ks.set(r,e))}return e}toString(){return this.cssText}};const fo=t=>new ho(typeof t=="string"?t:t+"",void 0,va),mo=(t,e)=>{if(ss)t.adoptedStyleSheets=e.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(const r of e){const n=document.createElement("style"),s=jr.litNonce;s!==void 0&&n.setAttribute("nonce",s),n.textContent=r.cssText,t.appendChild(n)}},Es=ss?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let r="";for(const n of e.cssRules)r+=n.cssText;return fo(r)})(t):t;/**
|
6
|
+
* @license
|
7
|
+
* Copyright 2017 Google LLC
|
8
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
9
|
+
*/const{is:go,defineProperty:yo,getOwnPropertyDescriptor:vo,getOwnPropertyNames:_o,getOwnPropertySymbols:bo,getPrototypeOf:wo}=Object,Ve=globalThis,Ts=Ve.trustedTypes,xo=Ts?Ts.emptyScript:"",xn=Ve.reactiveElementPolyfillSupport,Ht=(t,e)=>t,Zr={toAttribute(t,e){switch(e){case Boolean:t=t?xo:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,e){let r=t;switch(e){case Boolean:r=t!==null;break;case Number:r=t===null?null:Number(t);break;case Object:case Array:try{r=JSON.parse(t)}catch{r=null}}return r}},as=(t,e)=>!go(t,e),$s={attribute:!0,type:String,converter:Zr,reflect:!1,hasChanged:as};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ve.litPropertyMetadata??(Ve.litPropertyMetadata=new WeakMap);class yt extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,r=$s){if(r.state&&(r.attribute=!1),this._$Ei(),this.elementProperties.set(e,r),!r.noAccessor){const n=Symbol(),s=this.getPropertyDescriptor(e,n,r);s!==void 0&&yo(this.prototype,e,s)}}static getPropertyDescriptor(e,r,n){const{get:s,set:a}=vo(this.prototype,e)??{get(){return this[r]},set(i){this[r]=i}};return{get(){return s==null?void 0:s.call(this)},set(i){const o=s==null?void 0:s.call(this);a.call(this,i),this.requestUpdate(e,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??$s}static _$Ei(){if(this.hasOwnProperty(Ht("elementProperties")))return;const e=wo(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Ht("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ht("properties"))){const r=this.properties,n=[..._o(r),...bo(r)];for(const s of n)this.createProperty(s,r[s])}const e=this[Symbol.metadata];if(e!==null){const r=litPropertyMetadata.get(e);if(r!==void 0)for(const[n,s]of r)this.elementProperties.set(n,s)}this._$Eh=new Map;for(const[r,n]of this.elementProperties){const s=this._$Eu(r,n);s!==void 0&&this._$Eh.set(s,r)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const r=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const s of n)r.unshift(Es(s))}else e!==void 0&&r.push(Es(e));return r}static _$Eu(e,r){const n=r.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(r=>this.enableUpdating=r),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(r=>r(this))}addController(e){var r;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((r=e.hostConnected)==null||r.call(e))}removeController(e){var r;(r=this._$EO)==null||r.delete(e)}_$E_(){const e=new Map,r=this.constructor.elementProperties;for(const n of r.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return mo(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(r=>{var n;return(n=r.hostConnected)==null?void 0:n.call(r)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(r=>{var n;return(n=r.hostDisconnected)==null?void 0:n.call(r)})}attributeChangedCallback(e,r,n){this._$AK(e,n)}_$EC(e,r){var a;const n=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,n);if(s!==void 0&&n.reflect===!0){const i=(((a=n.converter)==null?void 0:a.toAttribute)!==void 0?n.converter:Zr).toAttribute(r,n.type);this._$Em=e,i==null?this.removeAttribute(s):this.setAttribute(s,i),this._$Em=null}}_$AK(e,r){var a;const n=this.constructor,s=n._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const i=n.getPropertyOptions(s),o=typeof i.converter=="function"?{fromAttribute:i.converter}:((a=i.converter)==null?void 0:a.fromAttribute)!==void 0?i.converter:Zr;this._$Em=s,this[s]=o.fromAttribute(r,i.type),this._$Em=null}}requestUpdate(e,r,n){if(e!==void 0){if(n??(n=this.constructor.getPropertyOptions(e)),!(n.hasChanged??as)(this[e],r))return;this.P(e,r,n)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(e,r,n){this._$AL.has(e)||this._$AL.set(e,r),n.reflect===!0&&this._$Em!==e&&(this._$Ej??(this._$Ej=new Set)).add(e)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(r){Promise.reject(r)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var n;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[a,i]of this._$Ep)this[a]=i;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[a,i]of s)i.wrapped!==!0||this._$AL.has(a)||this[a]===void 0||this.P(a,this[a],i)}let e=!1;const r=this._$AL;try{e=this.shouldUpdate(r),e?(this.willUpdate(r),(n=this._$EO)==null||n.forEach(s=>{var a;return(a=s.hostUpdate)==null?void 0:a.call(s)}),this.update(r)):this._$EU()}catch(s){throw e=!1,this._$EU(),s}e&&this._$AE(r)}willUpdate(e){}_$AE(e){var r;(r=this._$EO)==null||r.forEach(n=>{var s;return(s=n.hostUpdated)==null?void 0:s.call(n)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Ej&&(this._$Ej=this._$Ej.forEach(r=>this._$EC(r,this[r]))),this._$EU()}updated(e){}firstUpdated(e){}}yt.elementStyles=[],yt.shadowRootOptions={mode:"open"},yt[Ht("elementProperties")]=new Map,yt[Ht("finalized")]=new Map,xn==null||xn({ReactiveElement:yt}),(Ve.reactiveElementVersions??(Ve.reactiveElementVersions=[])).push("2.0.4");/**
|
10
|
+
* @license
|
11
|
+
* Copyright 2017 Google LLC
|
12
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
13
|
+
*/const Jt=globalThis,Ur=Jt.trustedTypes,Is=Ur?Ur.createPolicy("lit-html",{createHTML:t=>t}):void 0,_a="$lit$",Me=`lit$${Math.random().toFixed(9).slice(2)}$`,ba="?"+Me,Ao=`<${ba}>`,at=document,Qt=()=>at.createComment(""),er=t=>t===null||typeof t!="object"&&typeof t!="function",is=Array.isArray,So=t=>is(t)||typeof(t==null?void 0:t[Symbol.iterator])=="function",An=`[
|
14
|
+
\f\r]`,Ut=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Cs=/-->/g,Os=/>/g,Ke=RegExp(`>|${An}(?:([^\\s"'>=/]+)(${An}*=${An}*(?:[^
|
15
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Ps=/'/g,Rs=/"/g,wa=/^(?:script|style|textarea|title)$/i,ko=t=>(e,...r)=>({_$litType$:t,strings:e,values:r}),U=ko(1),it=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),js=new WeakMap,tt=at.createTreeWalker(at,129);function xa(t,e){if(!is(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return Is!==void 0?Is.createHTML(e):e}const Eo=(t,e)=>{const r=t.length-1,n=[];let s,a=e===2?"<svg>":e===3?"<math>":"",i=Ut;for(let o=0;o<r;o++){const l=t[o];let c,d,p=-1,g=0;for(;g<l.length&&(i.lastIndex=g,d=i.exec(l),d!==null);)g=i.lastIndex,i===Ut?d[1]==="!--"?i=Cs:d[1]!==void 0?i=Os:d[2]!==void 0?(wa.test(d[2])&&(s=RegExp("</"+d[2],"g")),i=Ke):d[3]!==void 0&&(i=Ke):i===Ke?d[0]===">"?(i=s??Ut,p=-1):d[1]===void 0?p=-2:(p=i.lastIndex-d[2].length,c=d[1],i=d[3]===void 0?Ke:d[3]==='"'?Rs:Ps):i===Rs||i===Ps?i=Ke:i===Cs||i===Os?i=Ut:(i=Ke,s=void 0);const w=i===Ke&&t[o+1].startsWith("/>")?" ":"";a+=i===Ut?l+Ao:p>=0?(n.push(c),l.slice(0,p)+_a+l.slice(p)+Me+w):l+Me+(p===-2?o:w)}return[xa(t,a+(t[r]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class tr{constructor({strings:e,_$litType$:r},n){let s;this.parts=[];let a=0,i=0;const o=e.length-1,l=this.parts,[c,d]=Eo(e,r);if(this.el=tr.createElement(c,n),tt.currentNode=this.el.content,r===2||r===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(s=tt.nextNode())!==null&&l.length<o;){if(s.nodeType===1){if(s.hasAttributes())for(const p of s.getAttributeNames())if(p.endsWith(_a)){const g=d[i++],w=s.getAttribute(p).split(Me),y=/([.?@])?(.*)/.exec(g);l.push({type:1,index:a,name:y[2],strings:w,ctor:y[1]==="."?$o:y[1]==="?"?Io:y[1]==="@"?Co:hn}),s.removeAttribute(p)}else p.startsWith(Me)&&(l.push({type:6,index:a}),s.removeAttribute(p));if(wa.test(s.tagName)){const p=s.textContent.split(Me),g=p.length-1;if(g>0){s.textContent=Ur?Ur.emptyScript:"";for(let w=0;w<g;w++)s.append(p[w],Qt()),tt.nextNode(),l.push({type:2,index:++a});s.append(p[g],Qt())}}}else if(s.nodeType===8)if(s.data===ba)l.push({type:2,index:a});else{let p=-1;for(;(p=s.data.indexOf(Me,p+1))!==-1;)l.push({type:7,index:a}),p+=Me.length-1}a++}}static createElement(e,r){const n=at.createElement("template");return n.innerHTML=e,n}}function Et(t,e,r=t,n){var i,o;if(e===it)return e;let s=n!==void 0?(i=r._$Co)==null?void 0:i[n]:r._$Cl;const a=er(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==a&&((o=s==null?void 0:s._$AO)==null||o.call(s,!1),a===void 0?s=void 0:(s=new a(t),s._$AT(t,r,n)),n!==void 0?(r._$Co??(r._$Co=[]))[n]=s:r._$Cl=s),s!==void 0&&(e=Et(t,s._$AS(t,e.values),s,n)),e}class To{constructor(e,r){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=r}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:r},parts:n}=this._$AD,s=((e==null?void 0:e.creationScope)??at).importNode(r,!0);tt.currentNode=s;let a=tt.nextNode(),i=0,o=0,l=n[0];for(;l!==void 0;){if(i===l.index){let c;l.type===2?c=new Tr(a,a.nextSibling,this,e):l.type===1?c=new l.ctor(a,l.name,l.strings,this,e):l.type===6&&(c=new Oo(a,this,e)),this._$AV.push(c),l=n[++o]}i!==(l==null?void 0:l.index)&&(a=tt.nextNode(),i++)}return tt.currentNode=at,s}p(e){let r=0;for(const n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,r),r+=n.strings.length-2):n._$AI(e[r])),r++}}class Tr{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,r,n,s){this.type=2,this._$AH=F,this._$AN=void 0,this._$AA=e,this._$AB=r,this._$AM=n,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const r=this._$AM;return r!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=r.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,r=this){e=Et(this,e,r),er(e)?e===F||e==null||e===""?(this._$AH!==F&&this._$AR(),this._$AH=F):e!==this._$AH&&e!==it&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):So(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==F&&er(this._$AH)?this._$AA.nextSibling.data=e:this.T(at.createTextNode(e)),this._$AH=e}$(e){var a;const{values:r,_$litType$:n}=e,s=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=tr.createElement(xa(n.h,n.h[0]),this.options)),n);if(((a=this._$AH)==null?void 0:a._$AD)===s)this._$AH.p(r);else{const i=new To(s,this),o=i.u(this.options);i.p(r),this.T(o),this._$AH=i}}_$AC(e){let r=js.get(e.strings);return r===void 0&&js.set(e.strings,r=new tr(e)),r}k(e){is(this._$AH)||(this._$AH=[],this._$AR());const r=this._$AH;let n,s=0;for(const a of e)s===r.length?r.push(n=new Tr(this.O(Qt()),this.O(Qt()),this,this.options)):n=r[s],n._$AI(a),s++;s<r.length&&(this._$AR(n&&n._$AB.nextSibling,s),r.length=s)}_$AR(e=this._$AA.nextSibling,r){var n;for((n=this._$AP)==null?void 0:n.call(this,!1,!0,r);e&&e!==this._$AB;){const s=e.nextSibling;e.remove(),e=s}}setConnected(e){var r;this._$AM===void 0&&(this._$Cv=e,(r=this._$AP)==null||r.call(this,e))}}class hn{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,r,n,s,a){this.type=1,this._$AH=F,this._$AN=void 0,this.element=e,this.name=r,this._$AM=s,this.options=a,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=F}_$AI(e,r=this,n,s){const a=this.strings;let i=!1;if(a===void 0)e=Et(this,e,r,0),i=!er(e)||e!==this._$AH&&e!==it,i&&(this._$AH=e);else{const o=e;let l,c;for(e=a[0],l=0;l<a.length-1;l++)c=Et(this,o[n+l],r,l),c===it&&(c=this._$AH[l]),i||(i=!er(c)||c!==this._$AH[l]),c===F?e=F:e!==F&&(e+=(c??"")+a[l+1]),this._$AH[l]=c}i&&!s&&this.j(e)}j(e){e===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class $o extends hn{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===F?void 0:e}}class Io extends hn{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==F)}}class Co extends hn{constructor(e,r,n,s,a){super(e,r,n,s,a),this.type=5}_$AI(e,r=this){if((e=Et(this,e,r,0)??F)===it)return;const n=this._$AH,s=e===F&&n!==F||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,a=e!==F&&(n===F||s);s&&this.element.removeEventListener(this.name,this,n),a&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var r;typeof this._$AH=="function"?this._$AH.call(((r=this.options)==null?void 0:r.host)??this.element,e):this._$AH.handleEvent(e)}}let Oo=class{constructor(e,r,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=r,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){Et(this,e)}};const Sn=Jt.litHtmlPolyfillSupport;Sn==null||Sn(tr,Tr),(Jt.litHtmlVersions??(Jt.litHtmlVersions=[])).push("3.2.1");const Po=(t,e,r)=>{const n=(r==null?void 0:r.renderBefore)??e;let s=n._$litPart$;if(s===void 0){const a=(r==null?void 0:r.renderBefore)??null;n._$litPart$=s=new Tr(e.insertBefore(Qt(),a),a,void 0,r??{})}return s._$AI(t),s};/**
|
16
|
+
* @license
|
17
|
+
* Copyright 2017 Google LLC
|
18
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
19
|
+
*/let re=class extends yt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var r;const e=super.createRenderRoot();return(r=this.renderOptions).renderBefore??(r.renderBefore=e.firstChild),e}update(e){const r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Po(r,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return it}};var ya;re._$litElement$=!0,re.finalized=!0,(ya=globalThis.litElementHydrateSupport)==null||ya.call(globalThis,{LitElement:re});const kn=globalThis.litElementPolyfillSupport;kn==null||kn({LitElement:re});(globalThis.litElementVersions??(globalThis.litElementVersions=[])).push("4.1.1");/**
|
20
|
+
* @license
|
21
|
+
* Copyright 2017 Google LLC
|
22
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
23
|
+
*/const we=t=>(e,r)=>{r!==void 0?r.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)};/**
|
24
|
+
* @license
|
25
|
+
* Copyright 2017 Google LLC
|
26
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
27
|
+
*/const Ro={attribute:!0,type:String,converter:Zr,reflect:!1,hasChanged:as},jo=(t=Ro,e,r)=>{const{kind:n,metadata:s}=r;let a=globalThis.litPropertyMetadata.get(s);if(a===void 0&&globalThis.litPropertyMetadata.set(s,a=new Map),a.set(r.name,t),n==="accessor"){const{name:i}=r;return{set(o){const l=e.get.call(this);e.set.call(this,o),this.requestUpdate(i,l,t)},init(o){return o!==void 0&&this.P(i,void 0,t),o}}}if(n==="setter"){const{name:i}=r;return function(o){const l=this[i];e.call(this,o),this.requestUpdate(i,l,t)}}throw Error("Unsupported decorator location: "+n)};function ee(t){return(e,r)=>typeof r=="object"?jo(t,e,r):((n,s,a)=>{const i=s.hasOwnProperty(a);return s.constructor.createProperty(a,i?{...n,wrapped:!0}:n),i?Object.getOwnPropertyDescriptor(s,a):void 0})(t,e,r)}/**
|
28
|
+
* @license
|
29
|
+
* Copyright 2017 Google LLC
|
30
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
31
|
+
*/function No(t){return ee({...t,state:!0,attribute:!1})}let De={appletUrl:"",settings:{},settingsDialogOpen:!1};localStorage.getItem("data")&&(De=JSON.parse(localStorage.getItem("data")));const os=new Set;function Mo(t){De={...De,...t},localStorage.setItem("data",JSON.stringify({appletUrl:De.appletUrl,settings:De.settings})),os.forEach(e=>e(De))}function Do(){return De}function Zo(t){return t(De),os.add(t),()=>Aa(t)}function Aa(t){os.delete(t)}const ae={get:Do,update:Mo,subscribe:Zo,unsubscribe:Aa};var Uo=Object.getOwnPropertyDescriptor,Lo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Uo(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let Ns=class extends re{createRenderRoot(){return this}connectedCallback(){super.connectedCallback()}handleKeyDown(e){if(e.key==="Enter"){const r=e.target;r.value&&!r.value.startsWith("http://")&&!r.value.startsWith("https://")&&(r.value=`http://${r.value}`),ae.update({appletUrl:r.value})}}render(){return U`<input
|
32
|
+
value=${ae.get().appletUrl}
|
33
|
+
type="text"
|
34
|
+
placeholder="Enter an applet URL to inspect..."
|
35
|
+
@keydown=${this.handleKeyDown.bind(this)}
|
36
|
+
/>`}};Ns=Lo([we("url-input")],Ns);var Fo=Object.getOwnPropertyDescriptor,Vo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Fo(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let Ms=class extends re{createRenderRoot(){return this}openDialog(){ae.update({settingsDialogOpen:!0})}render(){return U`
|
37
|
+
<button
|
38
|
+
aria-label="open settings"
|
39
|
+
class="menu-button"
|
40
|
+
@click="${this.openDialog}"
|
41
|
+
>
|
42
|
+
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
43
|
+
<path d="M10.0001 16.6667C11.7682 16.6667 13.4639 15.9643 14.7141 14.7141C15.9644 13.4638 16.6667 11.7681 16.6667 10C16.6667 8.23191 15.9644 6.53622 14.7141 5.28598C13.4639 4.03573 11.7682 3.33335 10.0001 3.33335M10.0001 16.6667C8.23197 16.6667 6.53628 15.9643 5.28604 14.7141C4.03579 13.4638 3.33341 11.7681 3.33341 10M10.0001 16.6667V18.3334M10.0001 3.33335C8.23197 3.33335 6.53628 4.03573 5.28604 5.28598C4.03579 6.53622 3.33341 8.23191 3.33341 10M10.0001 3.33335V1.66669M3.33341 10H1.66675M11.6667 10C11.6667 10.442 11.4912 10.866 11.1786 11.1785C10.866 11.4911 10.4421 11.6667 10.0001 11.6667C9.55805 11.6667 9.13413 11.4911 8.82157 11.1785C8.50901 10.866 8.33341 10.442 8.33341 10C8.33341 9.55799 8.50901 9.13407 8.82157 8.82151C9.13413 8.50895 9.55805 8.33335 10.0001 8.33335C10.4421 8.33335 10.866 8.50895 11.1786 8.82151C11.4912 9.13407 11.6667 9.55799 11.6667 10ZM11.6667 10H18.3334M14.1667 17.2166L13.3334 15.775M9.16675 8.55843L5.83341 2.78343M17.2169 14.1667L15.7752 13.3334M2.78328 5.83335L4.22495 6.66669M17.2169 5.83335L15.7752 6.66669M2.78328 14.1667L4.22495 13.3334M14.1667 2.78343L13.3334 4.22509M9.16675 11.4417L5.83341 17.2167" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
|
44
|
+
</svg>
|
45
|
+
</button>
|
46
|
+
`}};Ms=Vo([we("settings-button")],Ms);/**
|
47
|
+
* @license
|
48
|
+
* Copyright 2017 Google LLC
|
49
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
50
|
+
*/const Sa={CHILD:2},ka=t=>(...e)=>({_$litDirective$:t,values:e});class Ea{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,r,n){this._$Ct=e,this._$AM=r,this._$Ci=n}_$AS(e,r){return this.update(e,r)}update(e,r){return this.render(...r)}}/**
|
51
|
+
* @license
|
52
|
+
* Copyright 2017 Google LLC
|
53
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
54
|
+
*/let Fn=class extends Ea{constructor(e){if(super(e),this.it=F,e.type!==Sa.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===F||e==null)return this._t=void 0,this.it=e;if(e===it)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const r=[e];return r.raw=r,this._t={_$litType$:this.constructor.resultType,strings:r,values:[]}}};Fn.directiveName="unsafeHTML",Fn.resultType=1;const zo=ka(Fn);var Bo=Object.defineProperty,qo=Object.getOwnPropertyDescriptor,fn=(t,e,r,n)=>{for(var s=n>1?void 0:n?qo(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&Bo(e,r,s),s};const Ho=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
55
|
+
<path d="M12.5 2.5V17.5M8.33333 12.5L5.83333 10L8.33333 7.5M4.16667 2.5H15.8333C16.7538 2.5 17.5 3.24619 17.5 4.16667V15.8333C17.5 16.7538 16.7538 17.5 15.8333 17.5H4.16667C3.24619 17.5 2.5 16.7538 2.5 15.8333V4.16667C2.5 3.24619 3.24619 2.5 4.16667 2.5Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
|
56
|
+
</svg>
|
57
|
+
`;let rr=class extends re{constructor(){super(...arguments),this.variableName="",this.defaultValue="1fr",this.icon=Ho}createRenderRoot(){return this}toggle(){const t=document.querySelector("main");if(!t){console.error("Main element not found.");return}getComputedStyle(t).getPropertyValue(this.variableName).trim()==="0px"?t.style.setProperty(this.variableName,this.defaultValue):t.style.setProperty(this.variableName,"0px")}render(){return U`
|
58
|
+
<button class="menu-button" @click=${this.toggle}>
|
59
|
+
${zo(this.icon)}
|
60
|
+
</button>
|
61
|
+
`}};fn([ee({type:String})],rr.prototype,"variableName",2);fn([ee({type:String})],rr.prototype,"defaultValue",2);fn([ee({type:String})],rr.prototype,"icon",2);rr=fn([we("toggle-css-variable-button")],rr);var Jo=Object.getOwnPropertyDescriptor,Wo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Jo(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let Ds=class extends re{createRenderRoot(){return this}render(){return U`
|
62
|
+
<toggle-css-variable-button
|
63
|
+
variableName="--sidebar-width"
|
64
|
+
defaultValue="1fr"
|
65
|
+
>
|
66
|
+
</toggle-css-variable-button>
|
67
|
+
<h1>Applet Inspector</h1>
|
68
|
+
<div class="center-group">
|
69
|
+
<url-input></url-input>
|
70
|
+
<settings-button></settings-button>
|
71
|
+
</div>
|
72
|
+
<toggle-css-variable-button
|
73
|
+
variableName="--history-width"
|
74
|
+
defaultValue="1.5fr"
|
75
|
+
icon='<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
76
|
+
<path d="M7.5 2.5V17.5M11.6667 7.5L14.1667 10L11.6667 12.5M4.16667 2.5H15.8333C16.7538 2.5 17.5 3.24619 17.5 4.16667V15.8333C17.5 16.7538 16.7538 17.5 15.8333 17.5H4.16667C3.24619 17.5 2.5 16.7538 2.5 15.8333V4.16667C2.5 3.24619 3.24619 2.5 4.16667 2.5Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
|
77
|
+
</svg>'
|
78
|
+
>
|
79
|
+
</toggle-css-variable-button>
|
80
|
+
`}};Ds=Wo([we("app-header")],Ds);const Zs=10*1e3,Us=10*1e3;class Ls extends Error{constructor(e){super(e),this.name="AppletExecutionError"}}class Go extends Error{constructor(e){super(e),this.name="AppletConnectionError"}}function ls(t){typeof this[`on${t.type}`]=="function"&&this[`on${t.type}`](t),this.dispatchEvent(t)}function Yo(t){return Object.keys(t).length===0}class rt extends Event{constructor(e,r){super(e,{bubbles:r==null?void 0:r.bubbles,composed:r==null?void 0:r.composed,cancelable:r==null?void 0:r.cancelable}),this.data=r==null?void 0:r.data,this.actions=r==null?void 0:r.actions}}function Ko(t,...e){}const Ta={log:Ko};var pe=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},Z=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Pe,_t,Wt,Lr,xt,et,Se,Gt,Fr,Vr,Vn,Fs,En,Tn;class Xo extends EventTarget{constructor(e){super(),Pe.add(this),_t.set(this,void 0),Wt.set(this,{}),Lr.set(this,void 0),xt.set(this,void 0),et.set(this,void 0),Se.set(this,void 0),Gt.set(this,void 0),Fr.set(this,void 0),Vr.set(this,void 0),pe(this,_t,e,"f"),pe(this,et,ls.bind(this),"f"),Z(this,Pe,"m",Vn).call(this);const r=n=>{n.source===Z(this,_t,"f")&&"type"in n.data&&n.data.type==="appletconnect"&&(Ta.log("Applet","Recieved message",n.data),Z(this,Pe,"m",Vn).call(this),this.removeEventListener("message",r))};window.addEventListener("message",r)}async sendAction(e,r){const n={id:crypto.randomUUID(),type:"action",actionId:e,arguments:r};return new Promise((s,a)=>{Z(this,Gt,"f").call(this,n);const i=setTimeout(()=>{a(new Ls(`Applet action handler failed to complete before timeout (${Zs}ms)`))},Zs),o=l=>{const c=l.data;if(["actioncomplete","actionerror"].includes(c.type)&&"id"in c&&c.id===n.id)if(Z(this,Se,"f").removeEventListener("message",o),clearTimeout(i),c.type==="actionerror"){const d=c;a(new Ls(d.message))}else s()};Z(this,Se,"f").addEventListener("message",o)})}get data(){return Z(this,xt,"f")}set data(e){pe(this,xt,e,"f");const r={type:"data",data:e};Z(this,Gt,"f").call(this,r)}get window(){return Z(this,_t,"f")}get manifest(){return Z(this,Lr,"f")}get actions(){return Z(this,Wt,"f")}get width(){return Z(this,Fr,"f")}get height(){return Z(this,Vr,"f")}}_t=new WeakMap,Wt=new WeakMap,Lr=new WeakMap,xt=new WeakMap,et=new WeakMap,Se=new WeakMap,Gt=new WeakMap,Fr=new WeakMap,Vr=new WeakMap,Pe=new WeakSet,Vn=function(){Z(this,Se,"f")&&Z(this,Se,"f").close();const e=new MessageChannel,r={type:"appletconnect"};pe(this,Se,e.port1,"f"),Z(this,Se,"f").onmessage=Z(this,Pe,"m",Fs).bind(this),Z(this,_t,"f").postMessage(r,"*",[e.port2]),pe(this,Gt,Z(this,Se,"f").postMessage.bind(Z(this,Se,"f")),"f")},Fs=function(e){const r=e.data;switch(r.type){case"register":const n=r;pe(this,Lr,n.manifest,"f");const s=new rt("connect");Z(this,et,"f").call(this,s),pe(this,Wt,n.actions,"f"),Z(this,Pe,"m",Tn).call(this,n.actions),pe(this,xt,n.data,"f"),Z(this,Pe,"m",En).call(this,n.data);break;case"data":const a=r;pe(this,xt,a.data,"f"),Z(this,Pe,"m",En).call(this,a.data);break;case"resize":const i=r;pe(this,Fr,i.width,"f"),pe(this,Vr,i.height,"f");const o=new rt("resize");Z(this,et,"f").call(this,o);break;case"actions":const l=r;pe(this,Wt,l.actions,"f"),Z(this,Pe,"m",Tn).call(this,l.actions);break}},En=function(e){const r=new rt("data",{data:e});Z(this,et,"f").call(this,r)},Tn=function(e){const r=new rt("actions",{actions:e});Z(this,et,"f").call(this,r)};var Ee=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},j=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Ze,Ue,At,Fe,Yt,bt,ge,zr,Br,$a,Ia,Vs,zs,Bs,qs;class Qo extends EventTarget{constructor(e){super(),Ze.add(this),Ue.set(this,{}),At.set(this,void 0),Fe.set(this,void 0),Yt.set(this,void 0),bt.set(this,void 0),ge.set(this,void 0),zr.set(this,void 0),Br.set(this,void 0),Ee(this,bt,ls.bind(this),"f"),e&&Ee(this,At,e,"f");const r=s=>{if(s.source===window.parent&&s.data.type==="appletconnect"&&s.ports&&s.ports.length>0){Ta.log("AppletScope","Recieved message",s.data);const a=s.ports[0];Ee(this,ge,a.postMessage.bind(a),"f"),a.onmessage=j(this,Ze,"m",Ia).bind(this),this.removeEventListener("message",r),j(this,Ze,"m",$a).call(this)}};window.addEventListener("message",r);const n={type:"appletconnect"};window.parent.postMessage(n,"*")}setActionHandler(e,r){j(this,Ue,"f")[e]=r}defineAction(e,r){const{handler:n,...s}=r;n&&(j(this,Ue,"f")[e]=n),this.actions={...this.actions,[e]:s}}set actions(e){if(!e)return;Ee(this,Fe,e,"f");const r={type:"actions",actions:j(this,Fe,"f")};j(this,ge,"f")&&j(this,ge,"f").call(this,r);const n=new rt("actions",{actions:e});setTimeout(()=>j(this,bt,"f").call(this,n),1)}get actions(){return j(this,Fe,"f")}get manifest(){return j(this,At,"f")}get actionHandlers(){return j(this,Ue,"f")}set actionHandlers(e){Ee(this,Ue,e,"f")}set data(e){Ee(this,Yt,e,"f");const r={type:"data",data:e};j(this,ge,"f")&&j(this,ge,"f").call(this,r);const n=new rt("data",{data:e});setTimeout(()=>j(this,bt,"f").call(this,n),1)}get data(){return j(this,Yt,"f")}get width(){return j(this,zr,"f")}get height(){return j(this,Br,"f")}}Ue=new WeakMap,At=new WeakMap,Fe=new WeakMap,Yt=new WeakMap,bt=new WeakMap,ge=new WeakMap,zr=new WeakMap,Br=new WeakMap,Ze=new WeakSet,$a=async function(){const e=this.manifest??await j(this,Ze,"m",qs).call(this);Ee(this,At,e||{},"f"),Ee(this,Fe,j(this,Fe,"f")||(e==null?void 0:e.actions)||{},"f");const r={type:"register",manifest:j(this,At,"f"),actions:j(this,Fe,"f"),data:j(this,Yt,"f")};j(this,ge,"f").call(this,r);const n=new rt("connect");j(this,bt,"f").call(this,n),j(this,Ze,"m",zs).call(this)},Ia=function(e){const r=e.data;switch(r.type){case"data":"data"in r&&(this.data=r.data);break;case"action":"type"in r&&r.type==="action"&&"id"in r&&typeof r.id=="string"&&"actionId"in r&&typeof r.actionId=="string"&&"arguments"in r&&j(this,Ze,"m",Vs).call(this,r);break}},Vs=async function(e){const{actionId:r,arguments:n,id:s}=e;if(Object.keys(j(this,Ue,"f")).includes(r))try{await j(this,Ue,"f")[r](n);const a={type:"actioncomplete",id:s};j(this,ge,"f").call(this,a)}catch(a){const i={type:"actionerror",id:s,message:a.message};j(this,ge,"f").call(this,i),console.error(a)}},zs=function(){new ResizeObserver(r=>{for(let n of r)j(this,Ze,"m",Bs).call(this,{width:n.contentRect.width,height:n.contentRect.height})}).observe(document.querySelector("html"))},Bs=function({width:e,height:r}){Ee(this,zr,e,"f"),Ee(this,Br,r,"f");const n={type:"resize",width:e,height:r};j(this,ge,"f").call(this,n)},qs=async function(){const e=document.querySelector('link[rel="manifest"]');if(!e){console.warn("No manifest link found");return}try{const n=await(await fetch(e.href)).json();for(const s in n.actions){const a=n.actions[s];a.params_schema&&Yo(a.params_schema)&&(a.params_schema=void 0)}return n}catch(r){console.warn("Failed to fetch manifest",r.message)}};class el{async connect(e){return new Promise((r,n)=>{const s=new Xo(e),a=setTimeout(()=>{n(new Go(`Applet failed to connect before the timeout was reached (${Us}ms)`))},Us),i=()=>{r(s),s.removeEventListener("connect",i),clearTimeout(a)};s.addEventListener("connect",i)})}register(e){return new Qo(e)}}const tl=new el;var Nr=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},W=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},qr,Vt,Mr,ke,zt,St,Ca,Hs;class Oa extends HTMLElement{constructor(){super(...arguments),qr.add(this),Vt.set(this,void 0),Mr.set(this,void 0),ke.set(this,void 0),zt.set(this,ls.bind(this)),St.set(this,document.createElement("iframe"))}connectedCallback(){Nr(this,Vt,this.attachShadow({mode:"closed"}),"f"),W(this,Vt,"f").appendChild(W(this,St,"f"));const e=document.createElement("style");e.textContent=this.styles,W(this,Vt,"f").appendChild(e),this.src=this.getAttribute("src")}get contentWindow(){return W(this,St,"f").contentWindow}set src(e){Nr(this,Mr,e,"f"),Nr(this,ke,void 0,"f"),W(this,qr,"m",Ca).call(this,e)}get src(){return W(this,Mr,"f")||""}attributeChangedCallback(e,r,n){e==="src"&&(this.src=n)}get applet(){return W(this,ke,"f")}set data(e){if(this.applet)this.applet.data=e;else{const r=()=>{this.applet&&(this.applet.data=e),this.removeEventListener("load",r)};this.addEventListener("load",r)}}get styles(){return`
|
81
|
+
:host {
|
82
|
+
background: white;
|
83
|
+
display: flex;
|
84
|
+
flex-direction: column;
|
85
|
+
height: 350px;
|
86
|
+
}
|
87
|
+
|
88
|
+
iframe {
|
89
|
+
border: none;
|
90
|
+
height: 100%;
|
91
|
+
width: 100%;
|
92
|
+
}
|
93
|
+
`}}Vt=new WeakMap,Mr=new WeakMap,ke=new WeakMap,zt=new WeakMap,St=new WeakMap,qr=new WeakSet,Ca=async function(e){W(this,St,"f").src=e;const r=W(this,St,"f").contentWindow;r&&(Nr(this,ke,await tl.connect(r),"f"),W(this,ke,"f").ondata=n=>{W(this,zt,"f").call(this,n)},W(this,ke,"f").onresize=n=>{W(this,qr,"m",Hs).call(this,{width:W(this,ke,"f").width,height:W(this,ke,"f").height})},W(this,ke,"f").onactions=n=>{W(this,zt,"f").call(this,n)},W(this,zt,"f").call(this,new Event("load")),this.load&&typeof this.load=="function"&&this.onload(new Event("load")))},Hs=function(e){this.style.height=`${e.height}px`};Oa.observedAttributes=["src"];customElements.define("applet-frame",Oa);var rl=Object.defineProperty,nl=Object.getOwnPropertyDescriptor,mn=(t,e,r,n)=>{for(var s=n>1?void 0:n?nl(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&rl(e,r,s),s};let nr=class extends re{constructor(){super(...arguments),this.renderRoot=this,this.appletUrl="",this.mode="gui",this.data={}}connectedCallback(){ae.subscribe(t=>{this.appletUrl=t.appletUrl,t.applet&&(this.data=t.applet.data,t.applet.ondata=()=>this.data=t.applet.data)}),super.connectedCallback()}updated(){const t=document.querySelector("applet-frame");t&&(t.onload=()=>{ae.update({applet:t.applet}),window.applet=t.applet,window.applet.ondata=e=>this.data=e.data})}render(){var e,r,n,s,a;const t=U`<div class="applet-header">
|
94
|
+
${(r=(e=window.applet)==null?void 0:e.manifest)!=null&&r.icons?U`<img
|
95
|
+
src="${this.appletUrl}/${(s=(n=window.applet)==null?void 0:n.manifest.icons[0])==null?void 0:s.src}"
|
96
|
+
class="applet-icon"
|
97
|
+
/>`:""}
|
98
|
+
<div class="applet-title">${(a=window.applet)==null?void 0:a.manifest.name}</div>
|
99
|
+
<div class="toggle">
|
100
|
+
<button
|
101
|
+
data-selected=${this.mode==="gui"}
|
102
|
+
@mousedown=${()=>this.mode="gui"}
|
103
|
+
>
|
104
|
+
GUI
|
105
|
+
</button>
|
106
|
+
<button
|
107
|
+
data-selected=${this.mode==="data"}
|
108
|
+
@mousedown=${()=>this.mode="data"}
|
109
|
+
>
|
110
|
+
Data
|
111
|
+
</button>
|
112
|
+
</div>
|
113
|
+
</div>`;return U`
|
114
|
+
<div class="container">
|
115
|
+
${t}
|
116
|
+
<applet-frame
|
117
|
+
src=${this.appletUrl}
|
118
|
+
class=${this.mode==="gui"?"":"hidden"}
|
119
|
+
></applet-frame>
|
120
|
+
<pre class=${this.mode==="gui"?"hidden":"data-view"}>
|
121
|
+
${JSON.stringify(this.data,null,2)}</pre
|
122
|
+
>
|
123
|
+
</div>
|
124
|
+
`}};mn([ee()],nr.prototype,"appletUrl",2);mn([ee()],nr.prototype,"mode",2);mn([ee({attribute:!1})],nr.prototype,"data",2);nr=mn([we("app-viewer")],nr);function Pa(t){return Object.keys(t).length===0}class sl{constructor(){this.interactions=[],this.subscribers=new Set}addInteraction(e){this.interactions.push(e),this.notify()}getAllInteractions(){return[...this.interactions]}getRecentInteractions(e=10){return this.interactions.slice(-e)}clearHistory(){this.interactions=[],this.notify()}subscribe(e){return this.subscribers.add(e),e([...this.interactions]),()=>{this.subscribers.delete(e)}}notify(){for(const e of this.subscribers)e([...this.interactions])}}const Hr=new sl;var al=Object.defineProperty,il=Object.getOwnPropertyDescriptor,dt=(t,e,r,n)=>{for(var s=n>1?void 0:n?il(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&al(e,r,s),s};let sr=class extends re{constructor(){super(...arguments),this.renderRoot=this,this.selected=0,this.actions={},this.schemaError=""}connectedCallback(){ae.subscribe(t=>{t.applet&&(this.actions=t.applet.actions,t.applet.onactions=e=>this.actions=e.actions)}),super.connectedCallback()}handleSelect(t){const e=t.target;this.selected=e.selectedIndex}handleSchemaChange(t){const e=t.target,r=e.value.trim();if(!r){this.schemaError="",e.setCustomValidity("");return}try{const n=JSON.parse(r),s=JSON.stringify(n,null,2);e.value=s,this.schemaError="",e.setCustomValidity("")}catch(n){this.schemaError=n.message,e.setCustomValidity("Invalid JSON")}}handleSchemaFocus(t){t.target.setCustomValidity("")}async handleSubmit(t){t.preventDefault();const e=t.target,r=new FormData(e),n=r.get("action-id"),s=r.get("params");await window.applet.sendAction(n,JSON.parse(s)),Hr.addInteraction({input:{type:"action",text:n},outputs:[{type:n,...JSON.parse(s)},{type:"data",content:window.applet.data}],timestamp:Date.now()})}render(){if(!this.actions||Pa(this.actions))return U`<p class="status-message">No actions available.</p>`;const t=Object.values(this.actions)[this.selected],e=JSON.stringify(t==null?void 0:t.params_schema,null,2)??"None";return U`
|
125
|
+
<form @submit=${this.handleSubmit.bind(this)}>
|
126
|
+
<fieldset class="select">
|
127
|
+
<label>Select an action</label>
|
128
|
+
<action-select
|
129
|
+
.actions=${this.actions}
|
130
|
+
name="action-id"
|
131
|
+
@change=${this.handleSelect.bind(this)}
|
132
|
+
></action-select>
|
133
|
+
</fieldset>
|
134
|
+
<fieldset>
|
135
|
+
<label>Description</label>
|
136
|
+
<p class="description">${t==null?void 0:t.description}</p>
|
137
|
+
</fieldset>
|
138
|
+
<fieldset>
|
139
|
+
<label>Schema</label>
|
140
|
+
<pre class="schema">${e}</pre>
|
141
|
+
</fieldset>
|
142
|
+
<fieldset>
|
143
|
+
<label>Parameters</label>
|
144
|
+
<textarea
|
145
|
+
rows=${6}
|
146
|
+
name="params"
|
147
|
+
@focus=${this.handleSchemaFocus}
|
148
|
+
@change=${this.handleSchemaChange.bind(this)}
|
149
|
+
>
|
150
|
+
{}</textarea
|
151
|
+
>
|
152
|
+
${this.schemaError?U`<div class="error-message">${this.schemaError}</div>`:""}
|
153
|
+
</fieldset>
|
154
|
+
<fieldset>
|
155
|
+
<input type="submit" value="Dispatch action" />
|
156
|
+
</fieldset>
|
157
|
+
</form>
|
158
|
+
`}};dt([ee({type:Number})],sr.prototype,"selected",2);dt([ee({attribute:!1})],sr.prototype,"actions",2);dt([ee({type:String})],sr.prototype,"schemaError",2);sr=dt([we("app-sidebar")],sr);let Jr=class extends re{constructor(){super(...arguments),this.renderRoot=this}render(){return U`
|
159
|
+
<select name=${this.name}>
|
160
|
+
${Object.keys(this.actions).map(t=>U`<option id="action">${t}</option>`)}
|
161
|
+
</select>
|
162
|
+
`}};dt([ee({type:String})],Jr.prototype,"name",2);dt([ee({attribute:!1})],Jr.prototype,"actions",2);Jr=dt([we("action-select")],Jr);var Ra="vercel.ai.error",ol=Symbol.for(Ra),ja,ll=class Na extends Error{constructor({name:e,message:r,cause:n}){super(r),this[ja]=!0,this.name=e,this.cause=n}static isInstance(e){return Na.hasMarker(e,Ra)}static hasMarker(e,r){const n=Symbol.for(r);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}};ja=ol;var O=ll,Ma="AI_APICallError",Da=`vercel.ai.error.${Ma}`,cl=Symbol.for(Da),Za,Te=class extends O{constructor({message:t,url:e,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:a,cause:i,isRetryable:o=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:Ma,message:t,cause:i}),this[Za]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=a,this.isRetryable=o,this.data=l}static isInstance(t){return O.hasMarker(t,Da)}};Za=cl;var Ua="AI_EmptyResponseBodyError",La=`vercel.ai.error.${Ua}`,ul=Symbol.for(La),Fa,dl=class extends O{constructor({message:t="Empty response body"}={}){super({name:Ua,message:t}),this[Fa]=!0}static isInstance(t){return O.hasMarker(t,La)}};Fa=ul;function Va(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var za="AI_InvalidArgumentError",Ba=`vercel.ai.error.${za}`,pl=Symbol.for(Ba),qa,hl=class extends O{constructor({message:e,cause:r,argument:n}){super({name:za,message:e,cause:r}),this[qa]=!0,this.argument=n}static isInstance(e){return O.hasMarker(e,Ba)}};qa=pl;var Ha="AI_InvalidPromptError",Ja=`vercel.ai.error.${Ha}`,fl=Symbol.for(Ja),Wa,Qe=class extends O{constructor({prompt:t,message:e,cause:r}){super({name:Ha,message:`Invalid prompt: ${e}`,cause:r}),this[Wa]=!0,this.prompt=t}static isInstance(t){return O.hasMarker(t,Ja)}};Wa=fl;var Ga="AI_InvalidResponseDataError",Ya=`vercel.ai.error.${Ga}`,ml=Symbol.for(Ya),Ka,$n=class extends O{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Ga,message:e}),this[Ka]=!0,this.data=t}static isInstance(t){return O.hasMarker(t,Ya)}};Ka=ml;var Xa="AI_JSONParseError",Qa=`vercel.ai.error.${Xa}`,gl=Symbol.for(Qa),ei,ar=class extends O{constructor({text:t,cause:e}){super({name:Xa,message:`JSON parsing failed: Text: ${t}.
|
163
|
+
Error message: ${Va(e)}`,cause:e}),this[ei]=!0,this.text=t}static isInstance(t){return O.hasMarker(t,Qa)}};ei=gl;var ti="AI_LoadAPIKeyError",ri=`vercel.ai.error.${ti}`,yl=Symbol.for(ri),ni,Or=class extends O{constructor({message:t}){super({name:ti,message:t}),this[ni]=!0}static isInstance(t){return O.hasMarker(t,ri)}};ni=yl;var si="AI_TooManyEmbeddingValuesForCallError",ai=`vercel.ai.error.${si}`,vl=Symbol.for(ai),ii,_l=class extends O{constructor(t){super({name:si,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[ii]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return O.hasMarker(t,ai)}};ii=vl;var oi="AI_TypeValidationError",li=`vercel.ai.error.${oi}`,bl=Symbol.for(li),ci,wl=class zn extends O{constructor({value:e,cause:r}){super({name:oi,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
164
|
+
Error message: ${Va(r)}`,cause:r}),this[ci]=!0,this.value=e}static isInstance(e){return O.hasMarker(e,li)}static wrap({value:e,cause:r}){return zn.isInstance(r)&&r.value===e?r:new zn({value:e,cause:r})}};ci=bl;var je=wl,ui="AI_UnsupportedFunctionalityError",di=`vercel.ai.error.${ui}`,xl=Symbol.for(di),pi,G=class extends O{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:ui,message:e}),this[pi]=!0,this.functionality=t}static isInstance(t){return O.hasMarker(t,di)}};pi=xl;function Wr(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?!0:Array.isArray(t)?t.every(Wr):typeof t=="object"?Object.entries(t).every(([e,r])=>typeof e=="string"&&Wr(r)):!1}function Js(t){return Array.isArray(t)&&t.every(Wr)}function Bn(t){return t!=null&&typeof t=="object"&&Object.entries(t).every(([e,r])=>typeof e=="string"&&Wr(r))}let Al=(t,e=21)=>(r=e)=>{let n="",s=r|0;for(;s--;)n+=t[Math.random()*t.length|0];return n};function Sl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Xe={exports:{}},Ws;function kl(){if(Ws)return Xe.exports;Ws=1;const t=typeof Buffer<"u",e=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,r=/"(?: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 n(o,l,c){c==null&&l!==null&&typeof l=="object"&&(c=l,l=void 0),t&&Buffer.isBuffer(o)&&(o=o.toString()),o&&o.charCodeAt(0)===65279&&(o=o.slice(1));const d=JSON.parse(o,l);if(d===null||typeof d!="object")return d;const p=c&&c.protoAction||"error",g=c&&c.constructorAction||"error";if(p==="ignore"&&g==="ignore")return d;if(p!=="ignore"&&g!=="ignore"){if(e.test(o)===!1&&r.test(o)===!1)return d}else if(p!=="ignore"&&g==="ignore"){if(e.test(o)===!1)return d}else if(r.test(o)===!1)return d;return s(d,{protoAction:p,constructorAction:g,safe:c&&c.safe})}function s(o,{protoAction:l="error",constructorAction:c="error",safe:d}={}){let p=[o];for(;p.length;){const g=p;p=[];for(const w of g){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(w,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete w.__proto__}if(c!=="ignore"&&Object.prototype.hasOwnProperty.call(w,"constructor")&&Object.prototype.hasOwnProperty.call(w.constructor,"prototype")){if(d===!0)return null;if(c==="error")throw new SyntaxError("Object contains forbidden prototype property");delete w.constructor}for(const y in w){const m=w[y];m&&typeof m=="object"&&p.push(m)}}}return o}function a(o,l,c){const d=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return n(o,l,c)}finally{Error.stackTraceLimit=d}}function i(o,l){const c=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=c}}return Xe.exports=a,Xe.exports.default=a,Xe.exports.parse=a,Xe.exports.safeParse=i,Xe.exports.scan=s,Xe.exports}var El=kl();const cs=Sl(El);var Tl=Object.defineProperty,$l=(t,e,r)=>e in t?Tl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pr=(t,e,r)=>$l(t,typeof e!="symbol"?e+"":e,r);class Gs extends Error{constructor(e,r){super(e),Pr(this,"type"),Pr(this,"field"),Pr(this,"value"),Pr(this,"line"),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function In(t){}function Il(t){const{onEvent:e=In,onError:r=In,onRetry:n=In,onComment:s}=t;let a="",i=!0,o,l="",c="";function d(m){const v=i?m.replace(/^\xEF\xBB\xBF/,""):m,[A,k]=Cl(`${a}${v}`);for(const T of A)p(T);a=k,i=!1}function p(m){if(m===""){w();return}if(m.startsWith(":")){s&&s(m.slice(m.startsWith(": ")?2:1));return}const v=m.indexOf(":");if(v!==-1){const A=m.slice(0,v),k=m[v+1]===" "?2:1,T=m.slice(v+k);g(A,T,m);return}g(m,"",m)}function g(m,v,A){switch(m){case"event":c=v;break;case"data":l=`${l}${v}
|
165
|
+
`;break;case"id":o=v.includes("\0")?void 0:v;break;case"retry":/^\d+$/.test(v)?n(parseInt(v,10)):r(new Gs(`Invalid \`retry\` value: "${v}"`,{type:"invalid-retry",value:v,line:A}));break;default:r(new Gs(`Unknown field "${m.length>20?`${m.slice(0,20)}…`:m}"`,{type:"unknown-field",field:m,value:v,line:A}));break}}function w(){l.length>0&&e({id:o,event:c||void 0,data:l.endsWith(`
|
166
|
+
`)?l.slice(0,-1):l}),o=void 0,l="",c=""}function y(m={}){a&&m.consume&&p(a),o=void 0,l="",c="",a=""}return{feed:d,reset:y}}function Cl(t){const e=[];let r="";const n=t.length;for(let s=0;s<n;s++){const a=t[s];a==="\r"&&t[s+1]===`
|
167
|
+
`?(e.push(r),r="",s++):a==="\r"||a===`
|
168
|
+
`?(e.push(r),r=""):r+=a}return[e,r]}class Ol extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(a){s=Il({onEvent:i=>{a.enqueue(i)},onError(i){e==="terminate"?a.error(i):typeof e=="function"&&e(i)},onRetry:r,onComment:n})},transform(a){s.feed(a)}})}}var Pl={};function Tt(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function Rl(t){return new ReadableStream({async pull(e){try{const{value:r,done:n}=await t.next();n?e.close():e.enqueue(r)}catch(r){e.error(r)}},cancel(){}})}async function jl(t){return t==null?Promise.resolve():new Promise(e=>setTimeout(e,t))}function gn(t){const e={};return t.headers.forEach((r,n)=>{e[n]=r}),e}var pt=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=Al(r,e);if(t==null)return s;if(r.includes(n))throw new hl({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return a=>`${t}${n}${s(a)}`},Lt=pt();function Nl(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function Ml(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function Dr(t){return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")}function Dl({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Or({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Or({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=Pl[e],t==null)throw new Or({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Or({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}var Gr=Symbol.for("vercel.ai.validator");function Zl(t){return{[Gr]:!0,validate:t}}function Ul(t){return typeof t=="object"&&t!==null&&Gr in t&&t[Gr]===!0&&"validate"in t}function Ll(t){return Ul(t)?t:Fl(t)}function Fl(t){return Zl(e=>{const r=t.safeParse(e);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}})}function Vl({value:t,schema:e}){const r=ot({value:t,schema:e});if(!r.success)throw je.wrap({value:t,cause:r.error});return r.value}function ot({value:t,schema:e}){const r=Ll(e);try{if(r.validate==null)return{success:!0,value:t};const n=r.validate(t);return n.success?n:{success:!1,error:je.wrap({value:t,cause:n.error})}}catch(n){return{success:!1,error:je.wrap({value:t,cause:n})}}}function zl({text:t,schema:e}){try{const r=cs.parse(t);return e==null?r:Vl({value:r,schema:e})}catch(r){throw ar.isInstance(r)||je.isInstance(r)?r:new ar({text:t,cause:r})}}function $t({text:t,schema:e}){try{const r=cs.parse(t);if(e==null)return{success:!0,value:r,rawValue:r};const n=ot({value:r,schema:e});return n.success?{...n,rawValue:r}:n}catch(r){return{success:!1,error:ar.isInstance(r)?r:new ar({text:t,cause:r})}}}function Ys(t){try{return cs.parse(t),!0}catch{return!1}}var Bl=()=>globalThis.fetch,It=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i})=>ql({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i}),ql=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:a,fetch:i=Bl()})=>{try{const o=await i(t,{method:"POST",headers:Ml(e),body:r.content,signal:a}),l=gn(o);if(!o.ok){let c;try{c=await s({response:o,url:t,requestBodyValues:r.values})}catch(d){throw Dr(d)||Te.isInstance(d)?d:new Te({message:"Failed to process error response",cause:d,statusCode:o.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:o,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Dr(c)||Te.isInstance(c))?c:new Te({message:"Failed to process successful response",cause:c,statusCode:o.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(o){if(Dr(o))throw o;if(o instanceof TypeError&&o.message==="fetch failed"){const l=o.cause;if(l!=null)throw new Te({message:`Cannot connect to API: ${l.message}`,cause:l,url:t,requestBodyValues:r.values,isRetryable:!0})}throw o}},Hl=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:a})=>{const i=await n.text(),o=gn(n);if(i.trim()==="")return{responseHeaders:o,value:new Te({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})};try{const l=zl({text:i,schema:t});return{responseHeaders:o,value:new Te({message:e(l),url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,data:l,isRetryable:r==null?void 0:r(n,l)})}}catch{return{responseHeaders:o,value:new Te({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})}}},hi=t=>async({response:e})=>{const r=gn(e);if(e.body==null)throw new dl({});return{responseHeaders:r,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(new Ol).pipeThrough(new TransformStream({transform({data:n},s){n!=="[DONE]"&&s.enqueue($t({text:n,schema:t}))}}))}},yn=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),a=$t({text:s,schema:t}),i=gn(e);if(!a.success)throw new Te({message:"Invalid JSON response",cause:a.error,statusCode:e.status,responseHeaders:i,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}},{btoa:Jl,atob:Wl}=globalThis;function Gl(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=Wl(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function qn(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return Jl(e)}function Yl(t){return t==null?void 0:t.replace(/\/$/,"")}var C;(function(t){t.assertEqual=s=>s;function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const a={};for(const i of s)a[i]=i;return a},t.getValidEnumValues=s=>{const a=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(const o of a)i[o]=s[o];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},t.find=(s,a)=>{for(const i of s)if(a(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(C||(C={}));var Hn;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Hn||(Hn={}));const b=C.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Re=t=>{switch(typeof t){case"undefined":return b.undefined;case"string":return b.string;case"number":return isNaN(t)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(t)?b.array:t===null?b.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?b.promise:typeof Map<"u"&&t instanceof Map?b.map:typeof Set<"u"&&t instanceof Set?b.set:typeof Date<"u"&&t instanceof Date?b.date:b.object;default:return b.unknown}},h=C.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"]),Kl=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class le extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(a){return a.message},n={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(r(i))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof le))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,C.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}le.create=t=>new le(t);const Ct=(t,e)=>{let r;switch(t.code){case h.invalid_type:t.received===b.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case h.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,C.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${C.joinValues(t.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${C.joinValues(t.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${C.joinValues(t.options)}, received '${t.received}'`;break;case h.invalid_arguments:r="Invalid function arguments";break;case h.invalid_return_type:r="Invalid function return type";break;case h.invalid_date:r="Invalid date";break;case h.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:C.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case h.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case h.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case h.custom:r="Invalid input";break;case h.invalid_intersection_types:r="Intersection results could not be merged";break;case h.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case h.not_finite:r="Number must be finite";break;default:r=e.defaultError,C.assertNever(t)}return{message:r}};let fi=Ct;function Xl(t){fi=t}function Yr(){return fi}const Kr=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,a=[...r,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)o=c(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},Ql=[];function _(t,e){const r=Yr(),n=Kr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ct?void 0:Ct].filter(s=>!!s)});t.common.issues.push(n)}class Q{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return S;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const a=await s.key,i=await s.value;n.push({key:a,value:i})}return Q.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return S;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}}const S=Object.freeze({status:"aborted"}),wt=t=>({status:"dirty",value:t}),ne=t=>({status:"valid",value:t}),Jn=t=>t.status==="aborted",Wn=t=>t.status==="dirty",lt=t=>t.status==="valid",ir=t=>typeof Promise<"u"&&t instanceof Promise;function Xr(t,e,r,n){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function mi(t,e,r,n,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,r),r}var x;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(x||(x={}));var Bt,qt;class $e{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ks=(t,e)=>{if(lt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new le(t.common.issues);return this._error=r,this._error}}};function E(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{var l,c;const{message:d}=t;return i.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:(c=d??r)!==null&&c!==void 0?c:o.defaultError}},description:s}}class ${get description(){return this._def.description}_getType(e){return Re(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Q,ctx:{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(ir(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;const s={common:{issues:[],async:(n=r==null?void 0:r.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},a=this._parseSync({data:e,path:s.path,parent:s});return Ks(s,a)}"~validate"(e){var r,n;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:s});return lt(a)?{value:a.value}:{issues:s.common.issues}}catch(a){!((n=(r=a==null?void 0:a.message)===null||r===void 0?void 0:r.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then(a=>lt(a)?{value:a.value}:{issues:s.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(ir(s)?s:Promise.resolve(s));return Ks(n,a)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,a)=>{const i=e(s),o=()=>a.addIssue({code:h.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new be({schema:this,typeName:f.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:r=>this["~validate"](r)}}optional(){return _e.create(this,this._def)}nullable(){return He.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ve.create(this)}promise(){return Pt.create(this,this._def)}or(e){return ur.create([this,e],this._def)}and(e){return dr.create(this,e,this._def)}transform(e){return new be({...E(this._def),schema:this,typeName:f.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new gr({...E(this._def),innerType:this,defaultValue:r,typeName:f.ZodDefault})}brand(){return new us({typeName:f.ZodBranded,type:this,...E(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new yr({...E(this._def),innerType:this,catchValue:r,typeName:f.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return $r.create(this,e)}readonly(){return vr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ec=/^c[^\s-]{8,}$/i,tc=/^[0-9a-z]+$/,rc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nc=/^[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,sc=/^[a-z0-9_-]{21}$/i,ac=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ic=/^[-+]?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)?)??$/,oc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Cn;const cc=/^(?:(?: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])$/,uc=/^(?:(?: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])$/,dc=/^(([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]))$/,pc=/^(([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])$/,hc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gi="((\\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])))",mc=new RegExp(`^${gi}$`);function yi(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function gc(t){return new RegExp(`^${yi(t)}$`)}function vi(t){let e=`${gi}T${yi(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function yc(t,e){return!!((e==="v4"||!e)&&cc.test(t)||(e==="v6"||!e)&&dc.test(t))}function vc(t,e){if(!ac.test(t))return!1;try{const[r]=t.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||!s.typ||!s.alg||e&&s.alg!==e)}catch{return!1}}function _c(t,e){return!!((e==="v4"||!e)&&uc.test(t)||(e==="v6"||!e)&&pc.test(t))}class ye extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==b.string){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_type,expected:b.string,received:a.parsedType}),S}const n=new Q;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?_(s,{code:h.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&_(s,{code:h.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")oc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"email",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Cn||(Cn=new RegExp(lc,"u")),Cn.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"emoji",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")nc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"uuid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")sc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"nanoid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")ec.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cuid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")tc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cuid2",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")rc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"ulid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),_(s,{validation:"url",code:h.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"regex",code:h.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?vi(a).test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?mc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?gc(a).test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?ic.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"duration",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?yc(e.data,a.version)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"ip",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?vc(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"jwt",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?_c(e.data,a.version)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cidr",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?hc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"base64",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?fc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"base64url",code:h.invalid_string,message:a.message}),n.dirty()):C.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:h.invalid_string,...x.errToObj(n)})}_addCheck(e){return new ye({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...x.errToObj(e)})}url(e){return this._addCheck({kind:"url",...x.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...x.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...x.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...x.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...x.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...x.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...x.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...x.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...x.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...x.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...x.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...x.errToObj(e)})}datetime(e){var r,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(r=e==null?void 0:e.offset)!==null&&r!==void 0?r:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...x.errToObj(e==null?void 0: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:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...x.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...x.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...x.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...x.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...x.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...x.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...x.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...x.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...x.errToObj(r)})}nonempty(e){return this.min(1,x.errToObj(e))}trim(){return new ye({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ye({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ye({...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(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ye.create=t=>{var e;return new ye({checks:[],typeName:f.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...E(t)})};function bc(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,a=parseInt(t.toFixed(s).replace(".","")),i=parseInt(e.toFixed(s).replace(".",""));return a%i/Math.pow(10,s)}class ze extends ${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)!==b.number){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_type,expected:b.number,received:a.parsedType}),S}let n;const s=new Q;for(const a of this._def.checks)a.kind==="int"?C.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:h.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?bc(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:h.not_finite,message:a.message}),s.dirty()):C.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,x.toString(r))}gt(e,r){return this.setLimit("min",e,!1,x.toString(r))}lte(e,r){return this.setLimit("max",e,!0,x.toString(r))}lt(e,r){return this.setLimit("max",e,!1,x.toString(r))}setLimit(e,r,n,s){return new ze({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:x.toString(s)}]})}_addCheck(e){return new ze({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:x.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:x.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&C.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}ze.create=t=>new ze({checks:[],typeName:f.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...E(t)});class Be extends ${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)!==b.bigint)return this._getInvalidInput(e);let n;const s=new Q;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):C.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return _(r,{code:h.invalid_type,expected:b.bigint,received:r.parsedType}),S}gte(e,r){return this.setLimit("min",e,!0,x.toString(r))}gt(e,r){return this.setLimit("min",e,!1,x.toString(r))}lte(e,r){return this.setLimit("max",e,!0,x.toString(r))}lt(e,r){return this.setLimit("max",e,!1,x.toString(r))}setLimit(e,r,n,s){return new Be({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:x.toString(s)}]})}_addCheck(e){return new Be({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Be.create=t=>{var e;return new Be({checks:[],typeName:f.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...E(t)})};class or extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==b.boolean){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.boolean,received:n.parsedType}),S}return ne(e.data)}}or.create=t=>new or({typeName:f.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...E(t)});class ct extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==b.date){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_type,expected:b.date,received:a.parsedType}),S}if(isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_date}),S}const n=new Q;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):C.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ct({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:x.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:x.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}ct.create=t=>new ct({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:f.ZodDate,...E(t)});class Qr extends ${_parse(e){if(this._getType(e)!==b.symbol){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.symbol,received:n.parsedType}),S}return ne(e.data)}}Qr.create=t=>new Qr({typeName:f.ZodSymbol,...E(t)});class lr extends ${_parse(e){if(this._getType(e)!==b.undefined){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.undefined,received:n.parsedType}),S}return ne(e.data)}}lr.create=t=>new lr({typeName:f.ZodUndefined,...E(t)});class cr extends ${_parse(e){if(this._getType(e)!==b.null){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.null,received:n.parsedType}),S}return ne(e.data)}}cr.create=t=>new cr({typeName:f.ZodNull,...E(t)});class Ot extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return ne(e.data)}}Ot.create=t=>new Ot({typeName:f.ZodAny,...E(t)});class st extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return ne(e.data)}}st.create=t=>new st({typeName:f.ZodUnknown,...E(t)});class Ne extends ${_parse(e){const r=this._getOrReturnCtx(e);return _(r,{code:h.invalid_type,expected:b.never,received:r.parsedType}),S}}Ne.create=t=>new Ne({typeName:f.ZodNever,...E(t)});class en extends ${_parse(e){if(this._getType(e)!==b.undefined){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.void,received:n.parsedType}),S}return ne(e.data)}}en.create=t=>new en({typeName:f.ZodVoid,...E(t)});class ve extends ${_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==b.array)return _(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),S;if(s.exactLength!==null){const i=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(i||o)&&(_(r,{code:i?h.too_big:h.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(_(r,{code:h.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(_(r,{code:h.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>s.type._parseAsync(new $e(r,i,r.path,o)))).then(i=>Q.mergeArray(n,i));const a=[...r.data].map((i,o)=>s.type._parseSync(new $e(r,i,r.path,o)));return Q.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new ve({...this._def,minLength:{value:e,message:x.toString(r)}})}max(e,r){return new ve({...this._def,maxLength:{value:e,message:x.toString(r)}})}length(e,r){return new ve({...this._def,exactLength:{value:e,message:x.toString(r)}})}nonempty(e){return this.min(1,e)}}ve.create=(t,e)=>new ve({type:t,minLength:null,maxLength:null,exactLength:null,typeName:f.ZodArray,...E(e)});function vt(t){if(t instanceof z){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=_e.create(vt(n))}return new z({...t._def,shape:()=>e})}else return t instanceof ve?new ve({...t._def,type:vt(t.element)}):t instanceof _e?_e.create(vt(t.unwrap())):t instanceof He?He.create(vt(t.unwrap())):t instanceof Ie?Ie.create(t.items.map(e=>vt(e))):t}class z extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=C.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==b.object){const c=this._getOrReturnCtx(e);return _(c,{code:h.invalid_type,expected:b.object,received:c.parsedType}),S}const{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ne&&this._def.unknownKeys==="strip"))for(const c in s.data)i.includes(c)||o.push(c);const l=[];for(const c of i){const d=a[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new $e(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ne){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of o)l.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(c==="strict")o.length>0&&(_(s,{code:h.unrecognized_keys,keys:o}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of o){const p=s.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new $e(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const p=await d.key,g=await d.value;c.push({key:p,value:g,alwaysSet:d.alwaysSet})}return c}).then(c=>Q.mergeObjectSync(n,c)):Q.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return x.errToObj,new z({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var s,a,i,o;const l=(i=(a=(s=this._def).errorMap)===null||a===void 0?void 0:a.call(s,r,n).message)!==null&&i!==void 0?i:n.defaultError;return r.code==="unrecognized_keys"?{message:(o=x.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new z({...this._def,unknownKeys:"strip"})}passthrough(){return new z({...this._def,unknownKeys:"passthrough"})}extend(e){return new z({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new z({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:f.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new z({...this._def,catchall:e})}pick(e){const r={};return C.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new z({...this._def,shape:()=>r})}omit(e){const r={};return C.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new z({...this._def,shape:()=>r})}deepPartial(){return vt(this)}partial(e){const r={};return C.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}),new z({...this._def,shape:()=>r})}required(e){const r={};return C.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof _e;)a=a._def.innerType;r[n]=a}}),new z({...this._def,shape:()=>r})}keyof(){return _i(C.objectKeys(this.shape))}}z.create=(t,e)=>new z({shape:()=>t,unknownKeys:"strip",catchall:Ne.create(),typeName:f.ZodObject,...E(e)});z.strictCreate=(t,e)=>new z({shape:()=>t,unknownKeys:"strict",catchall:Ne.create(),typeName:f.ZodObject,...E(e)});z.lazycreate=(t,e)=>new z({shape:t,unknownKeys:"strip",catchall:Ne.create(),typeName:f.ZodObject,...E(e)});class ur extends ${_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new le(o.ctx.common.issues));return _(r,{code:h.invalid_union,unionErrors:i}),S}if(r.common.async)return Promise.all(n.map(async a=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let a;const i=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},d=l._parseSync({data:r.data,path:r.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!a&&(a={result:d,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(l=>new le(l));return _(r,{code:h.invalid_union,unionErrors:o}),S}}get options(){return this._def.options}}ur.create=(t,e)=>new ur({options:t,typeName:f.ZodUnion,...E(e)});const Oe=t=>t instanceof hr?Oe(t.schema):t instanceof be?Oe(t.innerType()):t instanceof fr?[t.value]:t instanceof qe?t.options:t instanceof mr?C.objectValues(t.enum):t instanceof gr?Oe(t._def.innerType):t instanceof lr?[void 0]:t instanceof cr?[null]:t instanceof _e?[void 0,...Oe(t.unwrap())]:t instanceof He?[null,...Oe(t.unwrap())]:t instanceof us||t instanceof vr?Oe(t.unwrap()):t instanceof yr?Oe(t._def.innerType):[];class vn extends ${_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==b.object)return _(r,{code:h.invalid_type,expected:b.object,received:r.parsedType}),S;const n=this.discriminator,s=r.data[n],a=this.optionsMap.get(s);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(_(r,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const a of r){const i=Oe(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new vn({typeName:f.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...E(n)})}}function Gn(t,e){const r=Re(t),n=Re(e);if(t===e)return{valid:!0,data:t};if(r===b.object&&n===b.object){const s=C.objectKeys(e),a=C.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(const o of a){const l=Gn(t[o],e[o]);if(!l.valid)return{valid:!1};i[o]=l.data}return{valid:!0,data:i}}else if(r===b.array&&n===b.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<t.length;a++){const i=t[a],o=e[a],l=Gn(i,o);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return r===b.date&&n===b.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class dr extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Jn(a)||Jn(i))return S;const o=Gn(a.value,i.value);return o.valid?((Wn(a)||Wn(i))&&r.dirty(),{status:r.value,value:o.data}):(_(n,{code:h.invalid_intersection_types}),S)};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(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}dr.create=(t,e,r)=>new dr({left:t,right:e,typeName:f.ZodIntersection,...E(r)});class Ie extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.array)return _(n,{code:h.invalid_type,expected:b.array,received:n.parsedType}),S;if(n.data.length<this._def.items.length)return _(n,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&n.data.length>this._def.items.length&&(_(n,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const a=[...n.data].map((i,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new $e(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>Q.mergeArray(r,i)):Q.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new Ie({...this._def,rest:e})}}Ie.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ie({items:t,typeName:f.ZodTuple,rest:null,...E(e)})};class pr extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.object)return _(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),S;const s=[],a=this._def.keyType,i=this._def.valueType;for(const o in n.data)s.push({key:a._parse(new $e(n,o,n.path,o)),value:i._parse(new $e(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?Q.mergeObjectAsync(r,s):Q.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof $?new pr({keyType:e,valueType:r,typeName:f.ZodRecord,...E(n)}):new pr({keyType:ye.create(),valueType:e,typeName:f.ZodRecord,...E(r)})}}class tn extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.map)return _(n,{code:h.invalid_type,expected:b.map,received:n.parsedType}),S;const s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,l],c)=>({key:s._parse(new $e(n,o,n.path,[c,"key"])),value:a._parse(new $e(n,l,n.path,[c,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return S;(c.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(c.value,d.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const l of i){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return S;(c.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(c.value,d.value)}return{status:r.value,value:o}}}}tn.create=(t,e,r)=>new tn({valueType:e,keyType:t,typeName:f.ZodMap,...E(r)});class ut extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.set)return _(n,{code:h.invalid_type,expected:b.set,received:n.parsedType}),S;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(_(n,{code:h.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(_(n,{code:h.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const a=this._def.valueType;function i(l){const c=new Set;for(const d of l){if(d.status==="aborted")return S;d.status==="dirty"&&r.dirty(),c.add(d.value)}return{status:r.value,value:c}}const o=[...n.data.values()].map((l,c)=>a._parse(new $e(n,l,n.path,c)));return n.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,r){return new ut({...this._def,minSize:{value:e,message:x.toString(r)}})}max(e,r){return new ut({...this._def,maxSize:{value:e,message:x.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}ut.create=(t,e)=>new ut({valueType:t,minSize:null,maxSize:null,typeName:f.ZodSet,...E(e)});class kt extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==b.function)return _(r,{code:h.invalid_type,expected:b.function,received:r.parsedType}),S;function n(o,l){return Kr({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Yr(),Ct].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function s(o,l){return Kr({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Yr(),Ct].filter(c=>!!c),issueData:{code:h.invalid_return_type,returnTypeError:l}})}const a={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Pt){const o=this;return ne(async function(...l){const c=new le([]),d=await o._def.args.parseAsync(l,a).catch(w=>{throw c.addIssue(n(l,w)),c}),p=await Reflect.apply(i,this,d);return await o._def.returns._def.type.parseAsync(p,a).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{const o=this;return ne(function(...l){const c=o._def.args.safeParse(l,a);if(!c.success)throw new le([n(l,c.error)]);const d=Reflect.apply(i,this,c.data),p=o._def.returns.safeParse(d,a);if(!p.success)throw new le([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new kt({...this._def,args:Ie.create(e).rest(st.create())})}returns(e){return new kt({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new kt({args:e||Ie.create([]).rest(st.create()),returns:r||st.create(),typeName:f.ZodFunction,...E(n)})}}class hr extends ${get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}hr.create=(t,e)=>new hr({getter:t,typeName:f.ZodLazy,...E(e)});class fr extends ${_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return _(r,{received:r.data,code:h.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}fr.create=(t,e)=>new fr({value:t,typeName:f.ZodLiteral,...E(e)});function _i(t,e){return new qe({values:t,typeName:f.ZodEnum,...E(e)})}class qe extends ${constructor(){super(...arguments),Bt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return _(r,{expected:C.joinValues(n),received:r.parsedType,code:h.invalid_type}),S}if(Xr(this,Bt)||mi(this,Bt,new Set(this._def.values)),!Xr(this,Bt).has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return _(r,{received:r.data,code:h.invalid_enum_value,options:n}),S}return ne(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return qe.create(e,{...this._def,...r})}exclude(e,r=this._def){return qe.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}Bt=new WeakMap;qe.create=_i;class mr extends ${constructor(){super(...arguments),qt.set(this,void 0)}_parse(e){const r=C.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){const s=C.objectValues(r);return _(n,{expected:C.joinValues(s),received:n.parsedType,code:h.invalid_type}),S}if(Xr(this,qt)||mi(this,qt,new Set(C.getValidEnumValues(this._def.values))),!Xr(this,qt).has(e.data)){const s=C.objectValues(r);return _(n,{received:n.data,code:h.invalid_enum_value,options:s}),S}return ne(e.data)}get enum(){return this._def.values}}qt=new WeakMap;mr.create=(t,e)=>new mr({values:t,typeName:f.ZodNativeEnum,...E(e)});class Pt extends ${unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==b.promise&&r.common.async===!1)return _(r,{code:h.invalid_type,expected:b.promise,received:r.parsedType}),S;const n=r.parsedType===b.promise?r.data:Promise.resolve(r.data);return ne(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Pt.create=(t,e)=>new Pt({type:t,typeName:f.ZodPromise,...E(e)});class be extends ${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===f.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{_(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return S;const l=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return l.status==="aborted"?S:l.status==="dirty"||r.value==="dirty"?wt(l.value):l});{if(r.value==="aborted")return S;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?S:o.status==="dirty"||r.value==="dirty"?wt(o.value):o}}if(s.type==="refinement"){const i=o=>{const l=s.refinement(o,a);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?S:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?S:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!lt(i))return i;const o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>lt(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:r.value,value:o})):i);C.assertNever(s)}}be.create=(t,e,r)=>new be({schema:t,typeName:f.ZodEffects,effect:e,...E(r)});be.createWithPreprocess=(t,e,r)=>new be({schema:e,effect:{type:"preprocess",transform:t},typeName:f.ZodEffects,...E(r)});class _e extends ${_parse(e){return this._getType(e)===b.undefined?ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_e.create=(t,e)=>new _e({innerType:t,typeName:f.ZodOptional,...E(e)});class He extends ${_parse(e){return this._getType(e)===b.null?ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}He.create=(t,e)=>new He({innerType:t,typeName:f.ZodNullable,...E(e)});class gr extends ${_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===b.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}gr.create=(t,e)=>new gr({innerType:t,typeName:f.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...E(e)});class yr extends ${_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ir(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new le(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new le(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}yr.create=(t,e)=>new yr({innerType:t,typeName:f.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...E(e)});class rn extends ${_parse(e){if(this._getType(e)!==b.nan){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.nan,received:n.parsedType}),S}return{status:"valid",value:e.data}}}rn.create=t=>new rn({typeName:f.ZodNaN,...E(t)});const wc=Symbol("zod_brand");class us extends ${_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class $r extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?S:a.status==="dirty"?(r.dirty(),wt(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?S:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new $r({in:e,out:r,typeName:f.ZodPipeline})}}class vr extends ${_parse(e){const r=this._def.innerType._parse(e),n=s=>(lt(s)&&(s.value=Object.freeze(s.value)),s);return ir(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}vr.create=(t,e)=>new vr({innerType:t,typeName:f.ZodReadonly,...E(e)});function Xs(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function bi(t,e={},r){return t?Ot.create().superRefine((n,s)=>{var a,i;const o=t(n);if(o instanceof Promise)return o.then(l=>{var c,d;if(!l){const p=Xs(e,n),g=(d=(c=p.fatal)!==null&&c!==void 0?c:r)!==null&&d!==void 0?d:!0;s.addIssue({code:"custom",...p,fatal:g})}});if(!o){const l=Xs(e,n),c=(i=(a=l.fatal)!==null&&a!==void 0?a:r)!==null&&i!==void 0?i:!0;s.addIssue({code:"custom",...l,fatal:c})}}):Ot.create()}const xc={object:z.lazycreate};var f;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(f||(f={}));const Ac=(t,e={message:`Input not instance of ${t.name}`})=>bi(r=>r instanceof t,e),wi=ye.create,xi=ze.create,Sc=rn.create,kc=Be.create,Ai=or.create,Ec=ct.create,Tc=Qr.create,$c=lr.create,Ic=cr.create,Cc=Ot.create,Oc=st.create,Pc=Ne.create,Rc=en.create,jc=ve.create,Nc=z.create,Mc=z.strictCreate,Dc=ur.create,Zc=vn.create,Uc=dr.create,Lc=Ie.create,Fc=pr.create,Vc=tn.create,zc=ut.create,Bc=kt.create,qc=hr.create,Hc=fr.create,Jc=qe.create,Wc=mr.create,Gc=Pt.create,Qs=be.create,Yc=_e.create,Kc=He.create,Xc=be.createWithPreprocess,Qc=$r.create,eu=()=>wi().optional(),tu=()=>xi().optional(),ru=()=>Ai().optional(),nu={string:t=>ye.create({...t,coerce:!0}),number:t=>ze.create({...t,coerce:!0}),boolean:t=>or.create({...t,coerce:!0}),bigint:t=>Be.create({...t,coerce:!0}),date:t=>ct.create({...t,coerce:!0})},su=S;var u=Object.freeze({__proto__:null,defaultErrorMap:Ct,setErrorMap:Xl,getErrorMap:Yr,makeIssue:Kr,EMPTY_PATH:Ql,addIssueToContext:_,ParseStatus:Q,INVALID:S,DIRTY:wt,OK:ne,isAborted:Jn,isDirty:Wn,isValid:lt,isAsync:ir,get util(){return C},get objectUtil(){return Hn},ZodParsedType:b,getParsedType:Re,ZodType:$,datetimeRegex:vi,ZodString:ye,ZodNumber:ze,ZodBigInt:Be,ZodBoolean:or,ZodDate:ct,ZodSymbol:Qr,ZodUndefined:lr,ZodNull:cr,ZodAny:Ot,ZodUnknown:st,ZodNever:Ne,ZodVoid:en,ZodArray:ve,ZodObject:z,ZodUnion:ur,ZodDiscriminatedUnion:vn,ZodIntersection:dr,ZodTuple:Ie,ZodRecord:pr,ZodMap:tn,ZodSet:ut,ZodFunction:kt,ZodLazy:hr,ZodLiteral:fr,ZodEnum:qe,ZodNativeEnum:mr,ZodPromise:Pt,ZodEffects:be,ZodTransformer:be,ZodOptional:_e,ZodNullable:He,ZodDefault:gr,ZodCatch:yr,ZodNaN:rn,BRAND:wc,ZodBranded:us,ZodPipeline:$r,ZodReadonly:vr,custom:bi,Schema:$,ZodSchema:$,late:xc,get ZodFirstPartyTypeKind(){return f},coerce:nu,any:Cc,array:jc,bigint:kc,boolean:Ai,date:Ec,discriminatedUnion:Zc,effect:Qs,enum:Jc,function:Bc,instanceof:Ac,intersection:Uc,lazy:qc,literal:Hc,map:Vc,nan:Sc,nativeEnum:Wc,never:Pc,null:Ic,nullable:Kc,number:xi,object:Nc,oboolean:ru,onumber:tu,optional:Yc,ostring:eu,pipeline:Qc,preprocess:Xc,promise:Gc,record:Fc,set:zc,strictObject:Mc,string:wi,symbol:Tc,transformer:Qs,tuple:Lc,undefined:$c,union:Dc,unknown:Oc,void:Rc,NEVER:su,ZodIssueCode:h,quotelessJson:Kl,ZodError:le});function au({prompt:t,useLegacyFunctionCalling:e=!1,systemMessageMode:r="system"}){const n=[];for(const{role:s,content:a}of t)switch(s){case"system":{switch(r){case"system":{n.push({role:"system",content:a});break}case"developer":{n.push({role:"developer",content:a});break}case"remove":break;default:{const i=r;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text});break}n.push({role:"user",content:a.map(i=>{var o,l,c;switch(i.type){case"text":return{type:"text",text:i.text};case"image":return{type:"image_url",image_url:{url:i.image instanceof URL?i.image.toString():`data:${(o=i.mimeType)!=null?o:"image/jpeg"};base64,${qn(i.image)}`,detail:(c=(l=i.providerMetadata)==null?void 0:l.openai)==null?void 0:c.imageDetail}};case"file":{if(i.data instanceof URL)throw new G({functionality:"'File content parts with URL data' functionality not supported."});switch(i.mimeType){case"audio/wav":return{type:"input_audio",input_audio:{data:i.data,format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:i.data,format:"mp3"}};default:throw new G({functionality:`File content part type ${i.mimeType} in user messages`})}}}})});break}case"assistant":{let i="";const o=[];for(const l of a)switch(l.type){case"text":{i+=l.text;break}case"redacted-reasoning":case"reasoning":break;case"tool-call":{o.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.args)}});break}default:{const c=l;throw new Error(`Unsupported part: ${c}`)}}if(e){if(o.length>1)throw new G({functionality:"useLegacyFunctionCalling with multiple tool calls in one message"});n.push({role:"assistant",content:i,function_call:o.length>0?o[0].function:void 0})}else n.push({role:"assistant",content:i,tool_calls:o.length>0?o:void 0});break}case"tool":{for(const i of a)e?n.push({role:"function",name:i.toolName,content:JSON.stringify(i.result)}):n.push({role:"tool",tool_call_id:i.toolCallId,content:JSON.stringify(i.result)});break}default:{const i=s;throw new Error(`Unsupported role: ${i}`)}}return n}function ea(t){var e,r;return(r=(e=t==null?void 0:t.content)==null?void 0:e.map(({token:n,logprob:s,top_logprobs:a})=>({token:n,logprob:s,topLogprobs:a?a.map(({token:i,logprob:o})=>({token:i,logprob:o})):[]})))!=null?r:void 0}function nn(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var ds=u.object({error:u.object({message:u.string(),type:u.string().nullish(),param:u.any().nullish(),code:u.union([u.string(),u.number()]).nullish()})}),Rt=Hl({errorSchema:ds,errorToMessage:t=>t.error.message});function sn({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function iu({mode:t,useLegacyFunctionCalling:e=!1,structuredOutputs:r}){var n;const s=(n=t.tools)!=null&&n.length?t.tools:void 0,a=[];if(s==null)return{tools:void 0,tool_choice:void 0,toolWarnings:a};const i=t.toolChoice;if(e){const c=[];for(const p of s)p.type==="provider-defined"?a.push({type:"unsupported-tool",tool:p}):c.push({name:p.name,description:p.description,parameters:p.parameters});if(i==null)return{functions:c,function_call:void 0,toolWarnings:a};switch(i.type){case"auto":case"none":case void 0:return{functions:c,function_call:void 0,toolWarnings:a};case"required":throw new G({functionality:"useLegacyFunctionCalling and toolChoice: required"});default:return{functions:c,function_call:{name:i.toolName},toolWarnings:a}}}const o=[];for(const c of s)c.type==="provider-defined"?a.push({type:"unsupported-tool",tool:c}):o.push({type:"function",function:{name:c.name,description:c.description,parameters:c.parameters,strict:r?!0:void 0}});if(i==null)return{tools:o,tool_choice:void 0,toolWarnings:a};const l=i.type;switch(l){case"auto":case"none":case"required":return{tools:o,tool_choice:l,toolWarnings:a};case"tool":return{tools:o,tool_choice:{type:"function",function:{name:i.toolName}},toolWarnings:a};default:{const c=l;throw new G({functionality:`Unsupported tool choice type: ${c}`})}}}var ou=class{constructor(t,e,r){this.specificationVersion="v1",this.modelId=t,this.settings=e,this.config=r}get supportsStructuredOutputs(){var t;return(t=this.settings.structuredOutputs)!=null?t:Yn(this.modelId)}get defaultObjectGenerationMode(){return uu(this.modelId)?"tool":this.supportsStructuredOutputs?"json":"tool"}get provider(){return this.config.provider}get supportsImageUrls(){return!this.settings.downloadImages}getArgs({mode:t,prompt:e,maxTokens:r,temperature:n,topP:s,topK:a,frequencyPenalty:i,presencePenalty:o,stopSequences:l,responseFormat:c,seed:d,providerMetadata:p}){var g,w,y,m,v,A,k,T;const P=t.type,R=[];a!=null&&R.push({type:"unsupported-setting",setting:"topK"}),(c==null?void 0:c.type)==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&R.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const B=this.settings.useLegacyFunctionCalling;if(B&&this.settings.parallelToolCalls===!0)throw new G({functionality:"useLegacyFunctionCalling with parallelToolCalls"});if(B&&this.supportsStructuredOutputs)throw new G({functionality:"structuredOutputs with useLegacyFunctionCalling"});ta(this.modelId)==="remove"&&e.some(Y=>Y.role==="system")&&R.push({type:"other",message:"system messages are removed for this model"});const I={model:this.modelId,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===!0||typeof this.settings.logprobs=="number"?!0:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:r,temperature:n,top_p:s,frequency_penalty:i,presence_penalty:o,response_format:(c==null?void 0:c.type)==="json"?this.supportsStructuredOutputs&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:!0,name:(g=c.name)!=null?g:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,max_completion_tokens:(w=p==null?void 0:p.openai)==null?void 0:w.maxCompletionTokens,store:(y=p==null?void 0:p.openai)==null?void 0:y.store,metadata:(m=p==null?void 0:p.openai)==null?void 0:m.metadata,prediction:(v=p==null?void 0:p.openai)==null?void 0:v.prediction,reasoning_effort:(k=(A=p==null?void 0:p.openai)==null?void 0:A.reasoningEffort)!=null?k:this.settings.reasoningEffort,messages:au({prompt:e,useLegacyFunctionCalling:B,systemMessageMode:ta(this.modelId)})};switch(Yn(this.modelId)&&(I.temperature!=null&&(I.temperature=void 0,R.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,R.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,R.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,R.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,R.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,R.push({type:"other",message:"logprobs is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,R.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),I.max_tokens!=null&&(I.max_completion_tokens==null&&(I.max_completion_tokens=I.max_tokens),I.max_tokens=void 0)),P){case"regular":{const{tools:Y,tool_choice:ht,functions:Je,function_call:We,toolWarnings:Ge}=iu({mode:t,useLegacyFunctionCalling:B,structuredOutputs:this.supportsStructuredOutputs});return{args:{...I,tools:Y,tool_choice:ht,functions:Je,function_call:We},warnings:[...R,...Ge]}}case"object-json":return{args:{...I,response_format:this.supportsStructuredOutputs&&t.schema!=null?{type:"json_schema",json_schema:{schema:t.schema,strict:!0,name:(T=t.name)!=null?T:"response",description:t.description}}:{type:"json_object"}},warnings:R};case"object-tool":return{args:B?{...I,function_call:{name:t.tool.name},functions:[{name:t.tool.name,description:t.tool.description,parameters:t.tool.parameters}]}:{...I,tool_choice:{type:"function",function:{name:t.tool.name}},tools:[{type:"function",function:{name:t.tool.name,description:t.tool.description,parameters:t.tool.parameters,strict:this.supportsStructuredOutputs?!0:void 0}}]},warnings:R};default:{const Y=P;throw new Error(`Unsupported type: ${Y}`)}}}async doGenerate(t){var e,r,n,s,a,i,o,l;const{args:c,warnings:d}=this.getArgs(t),{responseHeaders:p,value:g,rawValue:w}=await It({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Tt(this.config.headers(),t.headers),body:c,failedResponseHandler:Rt,successfulResponseHandler:yn(lu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{messages:y,...m}=c,v=g.choices[0],A=(e=g.usage)==null?void 0:e.completion_tokens_details,k=(r=g.usage)==null?void 0:r.prompt_tokens_details,T={openai:{}};return(A==null?void 0:A.reasoning_tokens)!=null&&(T.openai.reasoningTokens=A==null?void 0:A.reasoning_tokens),(A==null?void 0:A.accepted_prediction_tokens)!=null&&(T.openai.acceptedPredictionTokens=A==null?void 0:A.accepted_prediction_tokens),(A==null?void 0:A.rejected_prediction_tokens)!=null&&(T.openai.rejectedPredictionTokens=A==null?void 0:A.rejected_prediction_tokens),(k==null?void 0:k.cached_tokens)!=null&&(T.openai.cachedPromptTokens=k==null?void 0:k.cached_tokens),{text:(n=v.message.content)!=null?n:void 0,toolCalls:this.settings.useLegacyFunctionCalling&&v.message.function_call?[{toolCallType:"function",toolCallId:Lt(),toolName:v.message.function_call.name,args:v.message.function_call.arguments}]:(s=v.message.tool_calls)==null?void 0:s.map(P=>{var R;return{toolCallType:"function",toolCallId:(R=P.id)!=null?R:Lt(),toolName:P.function.name,args:P.function.arguments}}),finishReason:nn(v.finish_reason),usage:{promptTokens:(i=(a=g.usage)==null?void 0:a.prompt_tokens)!=null?i:NaN,completionTokens:(l=(o=g.usage)==null?void 0:o.completion_tokens)!=null?l:NaN},rawCall:{rawPrompt:y,rawSettings:m},rawResponse:{headers:p,body:w},request:{body:JSON.stringify(c)},response:sn(g),warnings:d,logprobs:ea(v.logprobs),providerMetadata:T}}async doStream(t){if(this.settings.simulateStreaming){const m=await this.doGenerate(t);return{stream:new ReadableStream({start(A){if(A.enqueue({type:"response-metadata",...m.response}),m.text&&A.enqueue({type:"text-delta",textDelta:m.text}),m.toolCalls)for(const k of m.toolCalls)A.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:k.toolCallId,toolName:k.toolName,argsTextDelta:k.args}),A.enqueue({type:"tool-call",...k});A.enqueue({type:"finish",finishReason:m.finishReason,usage:m.usage,logprobs:m.logprobs,providerMetadata:m.providerMetadata}),A.close()}}),rawCall:m.rawCall,rawResponse:m.rawResponse,warnings:m.warnings}}const{args:e,warnings:r}=this.getArgs(t),n={...e,stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await It({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Tt(this.config.headers(),t.headers),body:n,failedResponseHandler:Rt,successfulResponseHandler:hi(cu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{messages:i,...o}=e,l=[];let c="unknown",d={promptTokens:void 0,completionTokens:void 0},p,g=!0;const{useLegacyFunctionCalling:w}=this.settings,y={openai:{}};return{stream:a.pipeThrough(new TransformStream({transform(m,v){var A,k,T,P,R,B,I,Y,ht,Je,We,Ge;if(!m.success){c="error",v.enqueue({type:"error",error:m.error});return}const Ce=m.value;if("error"in Ce){c="error",v.enqueue({type:"error",error:Ce.error});return}if(g&&(g=!1,v.enqueue({type:"response-metadata",...sn(Ce)})),Ce.usage!=null){const{prompt_tokens:V,completion_tokens:se,prompt_tokens_details:H,completion_tokens_details:D}=Ce.usage;d={promptTokens:V??void 0,completionTokens:se??void 0},(D==null?void 0:D.reasoning_tokens)!=null&&(y.openai.reasoningTokens=D==null?void 0:D.reasoning_tokens),(D==null?void 0:D.accepted_prediction_tokens)!=null&&(y.openai.acceptedPredictionTokens=D==null?void 0:D.accepted_prediction_tokens),(D==null?void 0:D.rejected_prediction_tokens)!=null&&(y.openai.rejectedPredictionTokens=D==null?void 0:D.rejected_prediction_tokens),(H==null?void 0:H.cached_tokens)!=null&&(y.openai.cachedPromptTokens=H==null?void 0:H.cached_tokens)}const ie=Ce.choices[0];if((ie==null?void 0:ie.finish_reason)!=null&&(c=nn(ie.finish_reason)),(ie==null?void 0:ie.delta)==null)return;const xe=ie.delta;xe.content!=null&&v.enqueue({type:"text-delta",textDelta:xe.content});const ce=ea(ie==null?void 0:ie.logprobs);ce!=null&&ce.length&&(p===void 0&&(p=[]),p.push(...ce));const ft=w&&xe.function_call!=null?[{type:"function",id:Lt(),function:xe.function_call,index:0}]:xe.tool_calls;if(ft!=null)for(const V of ft){const se=V.index;if(l[se]==null){if(V.type!=="function")throw new $n({data:V,message:"Expected 'function' type."});if(V.id==null)throw new $n({data:V,message:"Expected 'id' to be a string."});if(((A=V.function)==null?void 0:A.name)==null)throw new $n({data:V,message:"Expected 'function.name' to be a string."});l[se]={id:V.id,type:"function",function:{name:V.function.name,arguments:(k=V.function.arguments)!=null?k:""},hasFinished:!1};const D=l[se];((T=D.function)==null?void 0:T.name)!=null&&((P=D.function)==null?void 0:P.arguments)!=null&&(D.function.arguments.length>0&&v.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:D.id,toolName:D.function.name,argsTextDelta:D.function.arguments}),Ys(D.function.arguments)&&(v.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(R=D.id)!=null?R:Lt(),toolName:D.function.name,args:D.function.arguments}),D.hasFinished=!0));continue}const H=l[se];H.hasFinished||(((B=V.function)==null?void 0:B.arguments)!=null&&(H.function.arguments+=(Y=(I=V.function)==null?void 0:I.arguments)!=null?Y:""),v.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:H.id,toolName:H.function.name,argsTextDelta:(ht=V.function.arguments)!=null?ht:""}),((Je=H.function)==null?void 0:Je.name)!=null&&((We=H.function)==null?void 0:We.arguments)!=null&&Ys(H.function.arguments)&&(v.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(Ge=H.id)!=null?Ge:Lt(),toolName:H.function.name,args:H.function.arguments}),H.hasFinished=!0))}},flush(m){var v,A;m.enqueue({type:"finish",finishReason:c,logprobs:p,usage:{promptTokens:(v=d.promptTokens)!=null?v:NaN,completionTokens:(A=d.completionTokens)!=null?A:NaN},...y!=null?{providerMetadata:y}:{}})}})),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:s},request:{body:JSON.stringify(n)},warnings:r}}},Si=u.object({prompt_tokens:u.number().nullish(),completion_tokens:u.number().nullish(),prompt_tokens_details:u.object({cached_tokens:u.number().nullish()}).nullish(),completion_tokens_details:u.object({reasoning_tokens:u.number().nullish(),accepted_prediction_tokens:u.number().nullish(),rejected_prediction_tokens:u.number().nullish()}).nullish()}).nullish(),lu=u.object({id:u.string().nullish(),created:u.number().nullish(),model:u.string().nullish(),choices:u.array(u.object({message:u.object({role:u.literal("assistant").nullish(),content:u.string().nullish(),function_call:u.object({arguments:u.string(),name:u.string()}).nullish(),tool_calls:u.array(u.object({id:u.string().nullish(),type:u.literal("function"),function:u.object({name:u.string(),arguments:u.string()})})).nullish()}),index:u.number(),logprobs:u.object({content:u.array(u.object({token:u.string(),logprob:u.number(),top_logprobs:u.array(u.object({token:u.string(),logprob:u.number()}))})).nullable()}).nullish(),finish_reason:u.string().nullish()})),usage:Si}),cu=u.union([u.object({id:u.string().nullish(),created:u.number().nullish(),model:u.string().nullish(),choices:u.array(u.object({delta:u.object({role:u.enum(["assistant"]).nullish(),content:u.string().nullish(),function_call:u.object({name:u.string().optional(),arguments:u.string().optional()}).nullish(),tool_calls:u.array(u.object({index:u.number(),id:u.string().nullish(),type:u.literal("function").optional(),function:u.object({name:u.string().nullish(),arguments:u.string().nullish()})})).nullish()}).nullish(),logprobs:u.object({content:u.array(u.object({token:u.string(),logprob:u.number(),top_logprobs:u.array(u.object({token:u.string(),logprob:u.number()}))})).nullable()}).nullish(),finish_reason:u.string().nullable().optional(),index:u.number()})),usage:Si}),ds]);function Yn(t){return t==="o1"||t.startsWith("o1-")||t==="o3"||t.startsWith("o3-")}function uu(t){return t.startsWith("gpt-4o-audio-preview")}function ta(t){var e,r;return Yn(t)?(r=(e=du[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}var du={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"}};function pu({prompt:t,inputFormat:e,user:r="user",assistant:n="assistant"}){if(e==="prompt"&&t.length===1&&t[0].role==="user"&&t[0].content.length===1&&t[0].content[0].type==="text")return{prompt:t[0].content[0].text};let s="";t[0].role==="system"&&(s+=`${t[0].content}
|
169
|
+
|
170
|
+
`,t=t.slice(1));for(const{role:a,content:i}of t)switch(a){case"system":throw new Qe({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const o=i.map(l=>{switch(l.type){case"text":return l.text;case"image":throw new G({functionality:"images"})}}).join("");s+=`${r}:
|
171
|
+
${o}
|
172
|
+
|
173
|
+
`;break}case"assistant":{const o=i.map(l=>{switch(l.type){case"text":return l.text;case"tool-call":throw new G({functionality:"tool-call messages"})}}).join("");s+=`${n}:
|
174
|
+
${o}
|
175
|
+
|
176
|
+
`;break}case"tool":throw new G({functionality:"tool messages"});default:{const o=a;throw new Error(`Unsupported role: ${o}`)}}return s+=`${n}:
|
177
|
+
`,{prompt:s,stopSequences:[`
|
178
|
+
${r}:`]}}function ra(t){return t==null?void 0:t.tokens.map((e,r)=>({token:e,logprob:t.token_logprobs[r],topLogprobs:t.top_logprobs?Object.entries(t.top_logprobs[r]).map(([n,s])=>({token:n,logprob:s})):[]}))}var hu=class{constructor(t,e,r){this.specificationVersion="v1",this.defaultObjectGenerationMode=void 0,this.modelId=t,this.settings=e,this.config=r}get provider(){return this.config.provider}getArgs({mode:t,inputFormat:e,prompt:r,maxTokens:n,temperature:s,topP:a,topK:i,frequencyPenalty:o,presencePenalty:l,stopSequences:c,responseFormat:d,seed:p}){var g;const w=t.type,y=[];i!=null&&y.push({type:"unsupported-setting",setting:"topK"}),d!=null&&d.type!=="text"&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:m,stopSequences:v}=pu({prompt:r,inputFormat:e}),A=[...v??[],...c??[]],k={model:this.modelId,echo:this.settings.echo,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:n,temperature:s,top_p:a,frequency_penalty:o,presence_penalty:l,seed:p,prompt:m,stop:A.length>0?A:void 0};switch(w){case"regular":{if((g=t.tools)!=null&&g.length)throw new G({functionality:"tools"});if(t.toolChoice)throw new G({functionality:"toolChoice"});return{args:k,warnings:y}}case"object-json":throw new G({functionality:"object-json mode"});case"object-tool":throw new G({functionality:"object-tool mode"});default:{const T=w;throw new Error(`Unsupported type: ${T}`)}}}async doGenerate(t){const{args:e,warnings:r}=this.getArgs(t),{responseHeaders:n,value:s,rawValue:a}=await It({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Tt(this.config.headers(),t.headers),body:e,failedResponseHandler:Rt,successfulResponseHandler:yn(fu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{prompt:i,...o}=e,l=s.choices[0];return{text:l.text,usage:{promptTokens:s.usage.prompt_tokens,completionTokens:s.usage.completion_tokens},finishReason:nn(l.finish_reason),logprobs:ra(l.logprobs),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:n,body:a},response:sn(s),warnings:r,request:{body:JSON.stringify(e)}}}async doStream(t){const{args:e,warnings:r}=this.getArgs(t),n={...e,stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await It({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Tt(this.config.headers(),t.headers),body:n,failedResponseHandler:Rt,successfulResponseHandler:hi(mu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{prompt:i,...o}=e;let l="unknown",c={promptTokens:Number.NaN,completionTokens:Number.NaN},d,p=!0;return{stream:a.pipeThrough(new TransformStream({transform(g,w){if(!g.success){l="error",w.enqueue({type:"error",error:g.error});return}const y=g.value;if("error"in y){l="error",w.enqueue({type:"error",error:y.error});return}p&&(p=!1,w.enqueue({type:"response-metadata",...sn(y)})),y.usage!=null&&(c={promptTokens:y.usage.prompt_tokens,completionTokens:y.usage.completion_tokens});const m=y.choices[0];(m==null?void 0:m.finish_reason)!=null&&(l=nn(m.finish_reason)),(m==null?void 0:m.text)!=null&&w.enqueue({type:"text-delta",textDelta:m.text});const v=ra(m==null?void 0:m.logprobs);v!=null&&v.length&&(d===void 0&&(d=[]),d.push(...v))},flush(g){g.enqueue({type:"finish",finishReason:l,logprobs:d,usage:c})}})),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:s},warnings:r,request:{body:JSON.stringify(n)}}}},fu=u.object({id:u.string().nullish(),created:u.number().nullish(),model:u.string().nullish(),choices:u.array(u.object({text:u.string(),finish_reason:u.string(),logprobs:u.object({tokens:u.array(u.string()),token_logprobs:u.array(u.number()),top_logprobs:u.array(u.record(u.string(),u.number())).nullable()}).nullish()})),usage:u.object({prompt_tokens:u.number(),completion_tokens:u.number()})}),mu=u.union([u.object({id:u.string().nullish(),created:u.number().nullish(),model:u.string().nullish(),choices:u.array(u.object({text:u.string(),finish_reason:u.string().nullish(),index:u.number(),logprobs:u.object({tokens:u.array(u.string()),token_logprobs:u.array(u.number()),top_logprobs:u.array(u.record(u.string(),u.number())).nullable()}).nullish()})),usage:u.object({prompt_tokens:u.number(),completion_tokens:u.number()}).nullish()}),ds]),gu=class{constructor(t,e,r){this.specificationVersion="v1",this.modelId=t,this.settings=e,this.config=r}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var t;return(t=this.settings.maxEmbeddingsPerCall)!=null?t:2048}get supportsParallelCalls(){var t;return(t=this.settings.supportsParallelCalls)!=null?t:!0}async doEmbed({values:t,headers:e,abortSignal:r}){if(t.length>this.maxEmbeddingsPerCall)throw new _l({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:n,value:s}=await It({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Tt(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:this.settings.dimensions,user:this.settings.user},failedResponseHandler:Rt,successfulResponseHandler:yn(yu),abortSignal:r,fetch:this.config.fetch});return{embeddings:s.data.map(a=>a.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,rawResponse:{headers:n}}}},yu=u.object({data:u.array(u.object({embedding:u.array(u.number())})),usage:u.object({prompt_tokens:u.number()}).nullish()}),vu={"dall-e-3":1,"dall-e-2":10},_u=class{constructor(t,e,r){this.modelId=t,this.settings=e,this.config=r,this.specificationVersion="v1"}get maxImagesPerCall(){var t,e;return(e=(t=this.settings.maxImagesPerCall)!=null?t:vu[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:a,headers:i,abortSignal:o}){var l,c,d,p;const g=[];n!=null&&g.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&g.push({type:"unsupported-setting",setting:"seed"});const w=(d=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?d:new Date,{value:y,responseHeaders:m}=await It({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Tt(this.config.headers(),i),body:{model:this.modelId,prompt:t,n:e,size:r,...(p=a.openai)!=null?p:{},response_format:"b64_json"},failedResponseHandler:Rt,successfulResponseHandler:yn(bu),abortSignal:o,fetch:this.config.fetch});return{images:y.data.map(v=>v.b64_json),warnings:g,response:{timestamp:w,modelId:this.modelId,headers:m}}}},bu=u.object({data:u.array(u.object({b64_json:u.string()}))});function ki(t={}){var e,r,n;const s=(e=Yl(t.baseURL))!=null?e:"https://api.openai.com/v1",a=(r=t.compatibility)!=null?r:"compatible",i=(n=t.name)!=null?n:"openai",o=()=>({Authorization:`Bearer ${Dl({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers}),l=(y,m={})=>new ou(y,m,{provider:`${i}.chat`,url:({path:v})=>`${s}${v}`,headers:o,compatibility:a,fetch:t.fetch}),c=(y,m={})=>new hu(y,m,{provider:`${i}.completion`,url:({path:v})=>`${s}${v}`,headers:o,compatibility:a,fetch:t.fetch}),d=(y,m={})=>new gu(y,m,{provider:`${i}.embedding`,url:({path:v})=>`${s}${v}`,headers:o,fetch:t.fetch}),p=(y,m={})=>new _u(y,m,{provider:`${i}.image`,url:({path:v})=>`${s}${v}`,headers:o,fetch:t.fetch}),g=(y,m)=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return y==="gpt-3.5-turbo-instruct"?c(y,m):l(y,m)},w=function(y,m){return g(y,m)};return w.languageModel=g,w.chat=l,w.completion=c,w.embedding=d,w.textEmbedding=d,w.textEmbeddingModel=d,w.image=p,w.imageModel=p,w}ki({compatibility:"strict"});const wu=Symbol("Let zodToJsonSchema decide on which parser to use"),na={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},xu=t=>typeof t=="string"?{...na,name:t}:{...na,...t},Au=t=>{const e=xu(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Ei(t,e,r,n){n!=null&&n.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function M(t,e,r,n,s){t[e]=r,Ei(t,e,n,s)}function Su(){return{}}function ku(t,e){var n,s,a;const r={type:"array"};return(n=t.type)!=null&&n._def&&((a=(s=t.type)==null?void 0:s._def)==null?void 0:a.typeName)!==f.ZodAny&&(r.items=N(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&M(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&M(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(M(r,"minItems",t.exactLength.value,t.exactLength.message,e),M(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Eu(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?M(r,"minimum",n.value,n.message,e):M(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?M(r,"maximum",n.value,n.message,e):M(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",n.value,n.message,e));break;case"multipleOf":M(r,"multipleOf",n.value,n.message,e);break}return r}function Tu(){return{type:"boolean"}}function Ti(t,e){return N(t.type._def,e)}const $u=(t,e)=>N(t.innerType._def,e);function $i(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,a)=>$i(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Iu(t,e)}}const Iu=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":M(r,"minimum",n.value,n.message,e);break;case"max":M(r,"maximum",n.value,n.message,e);break}return r};function Cu(t,e){return{...N(t.innerType._def,e),default:t.defaultValue()}}function Ou(t,e){return e.effectStrategy==="input"?N(t.schema._def,e):{}}function Pu(t){return{type:"string",enum:Array.from(t.values)}}const Ru=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function ju(t,e){const r=[N(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),N(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(a=>{if(Ru(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...l}=a;i=l}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function Nu(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let On;const fe={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:()=>(On===void 0&&(On=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),On),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 Ii(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":me(r,"email",n.message,e);break;case"format:idn-email":me(r,"idn-email",n.message,e);break;case"pattern:zod":te(r,fe.email,n.message,e);break}break;case"url":me(r,"uri",n.message,e);break;case"uuid":me(r,"uuid",n.message,e);break;case"regex":te(r,n.regex,n.message,e);break;case"cuid":te(r,fe.cuid,n.message,e);break;case"cuid2":te(r,fe.cuid2,n.message,e);break;case"startsWith":te(r,RegExp(`^${Pn(n.value,e)}`),n.message,e);break;case"endsWith":te(r,RegExp(`${Pn(n.value,e)}$`),n.message,e);break;case"datetime":me(r,"date-time",n.message,e);break;case"date":me(r,"date",n.message,e);break;case"time":me(r,"time",n.message,e);break;case"duration":me(r,"duration",n.message,e);break;case"length":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{te(r,RegExp(Pn(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&me(r,"ipv4",n.message,e),n.version!=="v4"&&me(r,"ipv6",n.message,e);break}case"base64url":te(r,fe.base64url,n.message,e);break;case"jwt":te(r,fe.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&te(r,fe.ipv4Cidr,n.message,e),n.version!=="v4"&&te(r,fe.ipv6Cidr,n.message,e);break}case"emoji":te(r,fe.emoji(),n.message,e);break;case"ulid":{te(r,fe.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{me(r,"binary",n.message,e);break}case"contentEncoding:base64":{M(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{te(r,fe.base64,n.message,e);break}}break}case"nanoid":te(r,fe.nanoid,n.message,e)}return r}function Pn(t,e){return e.patternStrategy==="escape"?Du(t):t}const Mu=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Du(t){let e="";for(let r=0;r<t.length;r++)Mu.has(t[r])||(e+="\\"),e+=t[r];return e}function me(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):M(t,"format",e,r,n)}function te(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:sa(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):M(t,"pattern",sa(e,n),r,n)}function sa(t,e){var l;if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(a){s+=n[c],a=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&((l=n[c+2])!=null&&l.match(/[a-z]/))?(s+=n[c],o=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
179
|
+
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
180
|
+
]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
|
181
|
+
`:`[${n[c]}\r
|
182
|
+
]`;continue}s+=n[c],n[c]==="\\"?a=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Ci(t,e){var n,s,a,i,o,l;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((n=t.keyType)==null?void 0:n._def.typeName)===f.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((c,d)=>({...c,[d]:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",d]})??{}}),{}),additionalProperties:!1};const r={type:"object",additionalProperties:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(((s=t.keyType)==null?void 0:s._def.typeName)===f.ZodString&&((a=t.keyType._def.checks)!=null&&a.length)){const{type:c,...d}=Ii(t.keyType._def,e);return{...r,propertyNames:d}}else{if(((i=t.keyType)==null?void 0:i._def.typeName)===f.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===f.ZodBranded&&t.keyType._def.type._def.typeName===f.ZodString&&((l=t.keyType._def.type._def.checks)!=null&&l.length)){const{type:c,...d}=Ti(t.keyType._def,e);return{...r,propertyNames:d}}}return r}function Zu(t,e){if(e.mapStrategy==="record")return Ci(t,e);const r=N(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=N(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Uu(t){const e=t.values,n=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(n.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function Lu(){return{not:{}}}function Fu(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const an={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Vu(t,e){if(e.target==="openApi3")return aa(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in an&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,a)=>{const i=an[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:r.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(a=>!n.includes(a))],[])};return aa(t,e)}const aa=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>N(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function zu(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:an[t.innerType._def.typeName],nullable:!0}:{type:[an[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=N(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Bu(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",Ei(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?M(r,"minimum",n.value,n.message,e):M(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?M(r,"maximum",n.value,n.message,e):M(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",n.value,n.message,e));break;case"multipleOf":M(r,"multipleOf",n.value,n.message,e);break}return r}function qu(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":N(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":N(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Hu(t,e){const r=e.target==="openAi",n={type:"object",...Object.entries(t.shape()).reduce((s,[a,i])=>{if(i===void 0||i._def===void 0)return s;let o=i.isOptional();o&&r&&(i instanceof _e&&(i=i._def.innerType),i.isNullable()||(i=i.nullable()),o=!1);const l=N(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});return l===void 0?s:{properties:{...s.properties,[a]:l},required:o?s.required:[...s.required,a]}},{properties:{},required:[]}),additionalProperties:qu(t,e)};return n.required.length||delete n.required,n}const Ju=(t,e)=>{var n;if(e.currentPath.toString()===((n=e.propertyPath)==null?void 0:n.toString()))return N(t.innerType._def,e);const r=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},Wu=(t,e)=>{if(e.pipeStrategy==="input")return N(t.in._def,e);if(e.pipeStrategy==="output")return N(t.out._def,e);const r=N(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=N(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function Gu(t,e){return N(t.type._def,e)}function Yu(t,e){const n={type:"array",uniqueItems:!0,items:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&M(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&M(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Ku(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:N(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Xu(){return{not:{}}}function Qu(){return{}}const ed=(t,e)=>N(t.innerType._def,e),td=(t,e,r)=>{switch(e){case f.ZodString:return Ii(t,r);case f.ZodNumber:return Bu(t,r);case f.ZodObject:return Hu(t,r);case f.ZodBigInt:return Eu(t,r);case f.ZodBoolean:return Tu();case f.ZodDate:return $i(t,r);case f.ZodUndefined:return Xu();case f.ZodNull:return Fu(r);case f.ZodArray:return ku(t,r);case f.ZodUnion:case f.ZodDiscriminatedUnion:return Vu(t,r);case f.ZodIntersection:return ju(t,r);case f.ZodTuple:return Ku(t,r);case f.ZodRecord:return Ci(t,r);case f.ZodLiteral:return Nu(t,r);case f.ZodEnum:return Pu(t);case f.ZodNativeEnum:return Uu(t);case f.ZodNullable:return zu(t,r);case f.ZodOptional:return Ju(t,r);case f.ZodMap:return Zu(t,r);case f.ZodSet:return Yu(t,r);case f.ZodLazy:return()=>t.getter()._def;case f.ZodPromise:return Gu(t,r);case f.ZodNaN:case f.ZodNever:return Lu();case f.ZodEffects:return Ou(t,r);case f.ZodAny:return Su();case f.ZodUnknown:return Qu();case f.ZodDefault:return Cu(t,r);case f.ZodBranded:return Ti(t,r);case f.ZodReadonly:return ed(t,r);case f.ZodCatch:return $u(t,r);case f.ZodPipeline:return Wu(t,r);case f.ZodFunction:case f.ZodVoid:case f.ZodSymbol:return;default:return(n=>{})()}};function N(t,e,r=!1){var o;const n=e.seen.get(t);if(e.override){const l=(o=e.override)==null?void 0:o.call(e,t,e,n,r);if(l!==wu)return l}if(n&&!r){const l=rd(n,e);if(l!==void 0)return l}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const a=td(t,t.typeName,e),i=typeof a=="function"?N(a(),e):a;if(i&&sd(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return s.jsonSchema=i,l}return s.jsonSchema=i,i}const rd=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:nd(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},nd=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},sd=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),ad=(t,e)=>{const r=Au(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,d])=>({...l,[c]:N(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,a=N(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const o=s===void 0?n?{...a,[r.definitionPath]:n}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:a}};return r.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};var _r={code:"0",name:"text",parse:t=>{if(typeof t!="string")throw new Error('"text" parts expect a string value.');return{type:"text",value:t}}},br={code:"3",name:"error",parse:t=>{if(typeof t!="string")throw new Error('"error" parts expect a string value.');return{type:"error",value:t}}},wr={code:"4",name:"assistant_message",parse:t=>{if(t==null||typeof t!="object"||!("id"in t)||!("role"in t)||!("content"in t)||typeof t.id!="string"||typeof t.role!="string"||t.role!=="assistant"||!Array.isArray(t.content)||!t.content.every(e=>e!=null&&typeof e=="object"&&"type"in e&&e.type==="text"&&"text"in e&&e.text!=null&&typeof e.text=="object"&&"value"in e.text&&typeof e.text.value=="string"))throw new Error('"assistant_message" parts expect an object with an "id", "role", and "content" property.');return{type:"assistant_message",value:t}}},xr={code:"5",name:"assistant_control_data",parse:t=>{if(t==null||typeof t!="object"||!("threadId"in t)||!("messageId"in t)||typeof t.threadId!="string"||typeof t.messageId!="string")throw new Error('"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.');return{type:"assistant_control_data",value:{threadId:t.threadId,messageId:t.messageId}}}},Ar={code:"6",name:"data_message",parse:t=>{if(t==null||typeof t!="object"||!("role"in t)||!("data"in t)||typeof t.role!="string"||t.role!=="data")throw new Error('"data_message" parts expect an object with a "role" and "data" property.');return{type:"data_message",value:t}}},id=[_r,br,wr,xr,Ar];_r.code+"",br.code+"",wr.code+"",xr.code+"",Ar.code+"";_r.name+"",_r.code,br.name+"",br.code,wr.name+"",wr.code,xr.name+"",xr.code,Ar.name+"",Ar.code;id.map(t=>t.code);function od(t){const e=["ROOT"];let r=-1,n=null;function s(l,c,d){switch(l){case'"':{r=c,e.pop(),e.push(d),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,e.pop(),e.push(d),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(d),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(d),e.push("INSIDE_ARRAY_START");break}}}function a(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function i(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){const c=t[l];switch(e[e.length-1]){case"ROOT":s(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{a(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;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":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const p=t.substring(n,l+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?a(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l)):r=l;break}}}let o=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{o+='"';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":{o+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{o+="]";break}case"INSIDE_LITERAL":{const d=t.substring(n,t.length);"true".startsWith(d)?o+="true".slice(d.length):"false".startsWith(d)?o+="false".slice(d.length):"null".startsWith(d)&&(o+="null".slice(d.length))}}return o}function ld(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=$t({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=$t({text:od(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var cd={code:"0",name:"text",parse:t=>{if(typeof t!="string")throw new Error('"text" parts expect a string value.');return{type:"text",value:t}}},ud={code:"2",name:"data",parse:t=>{if(!Array.isArray(t))throw new Error('"data" parts expect an array value.');return{type:"data",value:t}}},dd={code:"3",name:"error",parse:t=>{if(typeof t!="string")throw new Error('"error" parts expect a string value.');return{type:"error",value:t}}},pd={code:"8",name:"message_annotations",parse:t=>{if(!Array.isArray(t))throw new Error('"message_annotations" parts expect an array value.');return{type:"message_annotations",value:t}}},hd={code:"9",name:"tool_call",parse:t=>{if(t==null||typeof t!="object"||!("toolCallId"in t)||typeof t.toolCallId!="string"||!("toolName"in t)||typeof t.toolName!="string"||!("args"in t)||typeof t.args!="object")throw new Error('"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.');return{type:"tool_call",value:t}}},fd={code:"a",name:"tool_result",parse:t=>{if(t==null||typeof t!="object"||!("toolCallId"in t)||typeof t.toolCallId!="string"||!("result"in t))throw new Error('"tool_result" parts expect an object with a "toolCallId" and a "result" property.');return{type:"tool_result",value:t}}},md={code:"b",name:"tool_call_streaming_start",parse:t=>{if(t==null||typeof t!="object"||!("toolCallId"in t)||typeof t.toolCallId!="string"||!("toolName"in t)||typeof t.toolName!="string")throw new Error('"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.');return{type:"tool_call_streaming_start",value:t}}},gd={code:"c",name:"tool_call_delta",parse:t=>{if(t==null||typeof t!="object"||!("toolCallId"in t)||typeof t.toolCallId!="string"||!("argsTextDelta"in t)||typeof t.argsTextDelta!="string")throw new Error('"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.');return{type:"tool_call_delta",value:t}}},yd={code:"d",name:"finish_message",parse:t=>{if(t==null||typeof t!="object"||!("finishReason"in t)||typeof t.finishReason!="string")throw new Error('"finish_message" parts expect an object with a "finishReason" property.');const e={finishReason:t.finishReason};return"usage"in t&&t.usage!=null&&typeof t.usage=="object"&&"promptTokens"in t.usage&&"completionTokens"in t.usage&&(e.usage={promptTokens:typeof t.usage.promptTokens=="number"?t.usage.promptTokens:Number.NaN,completionTokens:typeof t.usage.completionTokens=="number"?t.usage.completionTokens:Number.NaN}),{type:"finish_message",value:e}}},vd={code:"e",name:"finish_step",parse:t=>{if(t==null||typeof t!="object"||!("finishReason"in t)||typeof t.finishReason!="string")throw new Error('"finish_step" parts expect an object with a "finishReason" property.');const e={finishReason:t.finishReason,isContinued:!1};return"usage"in t&&t.usage!=null&&typeof t.usage=="object"&&"promptTokens"in t.usage&&"completionTokens"in t.usage&&(e.usage={promptTokens:typeof t.usage.promptTokens=="number"?t.usage.promptTokens:Number.NaN,completionTokens:typeof t.usage.completionTokens=="number"?t.usage.completionTokens:Number.NaN}),"isContinued"in t&&typeof t.isContinued=="boolean"&&(e.isContinued=t.isContinued),{type:"finish_step",value:e}}},_d={code:"f",name:"start_step",parse:t=>{if(t==null||typeof t!="object"||!("messageId"in t)||typeof t.messageId!="string")throw new Error('"start_step" parts expect an object with an "id" property.');return{type:"start_step",value:{messageId:t.messageId}}}},bd={code:"g",name:"reasoning",parse:t=>{if(typeof t!="string")throw new Error('"reasoning" parts expect a string value.');return{type:"reasoning",value:t}}},wd={code:"h",name:"source",parse:t=>{if(t==null||typeof t!="object")throw new Error('"source" parts expect a Source object.');return{type:"source",value:t}}},xd={code:"i",name:"redacted_reasoning",parse:t=>{if(t==null||typeof t!="object"||!("data"in t)||typeof t.data!="string")throw new Error('"redacted_reasoning" parts expect an object with a "data" property.');return{type:"redacted_reasoning",value:{data:t.data}}}},Ad={code:"j",name:"reasoning_signature",parse:t=>{if(t==null||typeof t!="object"||!("signature"in t)||typeof t.signature!="string")throw new Error('"reasoning_signature" parts expect an object with a "signature" property.');return{type:"reasoning_signature",value:{signature:t.signature}}}},_n=[cd,ud,dd,pd,hd,fd,md,gd,yd,vd,_d,bd,wd,xd,Ad];Object.fromEntries(_n.map(t=>[t.code,t]));Object.fromEntries(_n.map(t=>[t.name,t.code]));_n.map(t=>t.code);function Oi(t,e){const r=_n.find(n=>n.name===t);if(!r)throw new Error(`Invalid stream part type: ${t}`);return`${r.code}:${JSON.stringify(e)}
|
183
|
+
`}function Sd(t,e){var r;const n=(r=void 0)!=null?r:!1;return Xn(ad(t,{$refStrategy:n?"root":"none",target:"jsonSchema7"}),{validate:s=>{const a=t.safeParse(s);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}var Kn=Symbol.for("vercel.ai.schema");function Xn(t,{validate:e}={}){return{[Kn]:!0,_type:void 0,[Gr]:!0,jsonSchema:t,validate:e}}function kd(t){return typeof t=="object"&&t!==null&&Kn in t&&t[Kn]===!0&&"jsonSchema"in t&&"validate"in t}function Qn(t){return kd(t)?t:Sd(t)}var Ed=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},nt="1.9.0",ia=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Td(t){var e=new Set([t]),r=new Set,n=t.match(ia);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(l){return l===t};function a(o){return r.add(o),!1}function i(o){return e.add(o),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(ia);if(!c)return a(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||s.major!==d.major?a(l):s.major===0?s.minor===d.minor&&s.patch<=d.patch?i(l):a(l):s.minor<=d.minor?i(l):a(l)}}var $d=Td(nt),Id=nt.split(".")[0],Sr=Symbol.for("opentelemetry.js.api."+Id),kr=Ed;function ps(t,e,r,n){var s;n===void 0&&(n=!1);var a=kr[Sr]=(s=kr[Sr])!==null&&s!==void 0?s:{version:nt};if(!n&&a[t]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(i.stack||i.message),!1}if(a.version!==nt){var i=new Error("@opentelemetry/api: Registration of version v"+a.version+" for "+t+" does not match previously registered API v"+nt);return r.error(i.stack||i.message),!1}return a[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+nt+"."),!0}function Er(t){var e,r,n=(e=kr[Sr])===null||e===void 0?void 0:e.version;if(!(!n||!$d(n)))return(r=kr[Sr])===null||r===void 0?void 0:r[t]}function hs(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+nt+".");var r=kr[Sr];r&&delete r[t]}var Cd=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},Od=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,a;n<s;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Pd=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Ft("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Ft("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Ft("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Ft("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Ft("verbose",this._namespace,e)},t}();function Ft(t,e,r){var n=Er("diag");if(n)return r.unshift(e),n[t].apply(n,Od([],Cd(r),!1))}var oe;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(oe||(oe={}));function Rd(t,e){t<oe.NONE?t=oe.NONE:t>oe.ALL&&(t=oe.ALL),e=e||{};function r(n,s){var a=e[n];return typeof a=="function"&&t>=s?a.bind(e):function(){}}return{error:r("error",oe.ERROR),warn:r("warn",oe.WARN),info:r("info",oe.INFO),debug:r("debug",oe.DEBUG),verbose:r("verbose",oe.VERBOSE)}}var jd=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},Nd=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,a;n<s;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Md="diag",on=function(){function t(){function e(s){return function(){for(var a=[],i=0;i<arguments.length;i++)a[i]=arguments[i];var o=Er("diag");if(o)return o[s].apply(o,Nd([],jd(a),!1))}}var r=this,n=function(s,a){var i,o,l;if(a===void 0&&(a={logLevel:oe.INFO}),s===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof a=="number"&&(a={logLevel:a});var d=Er("diag"),p=Rd((o=a.logLevel)!==null&&o!==void 0?o:oe.INFO,s);if(d&&!a.suppressOverrideMessage){var g=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+g),p.warn("Current logger will overwrite one already registered from "+g)}return ps("diag",p,r,!0)};r.setLogger=n,r.disable=function(){hs(Md,r)},r.createComponentLogger=function(s){return new Pd(s)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}();function Dd(t){return Symbol.for(t)}var Zd=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var a=new t(r._currentContext);return a._currentContext.set(n,s),a},r.deleteValue=function(n){var s=new t(r._currentContext);return s._currentContext.delete(n),s}}return t}(),Ud=new Zd,Ld=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},Fd=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,a;n<s;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Vd=function(){function t(){}return t.prototype.active=function(){return Ud},t.prototype.with=function(e,r,n){for(var s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return r.call.apply(r,Fd([n],Ld(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),zd=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},Bd=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,a;n<s;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Rn="context",qd=new Vd,Pi=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return ps(Rn,e,on.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var s,a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return(s=this._getContextManager()).with.apply(s,Bd([e,r,n],zd(a),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Er(Rn)||qd},t.prototype.disable=function(){this._getContextManager().disable(),hs(Rn,on.instance())},t}(),es;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(es||(es={}));var Ri="0000000000000000",ji="00000000000000000000000000000000",Hd={traceId:ji,spanId:Ri,traceFlags:es.NONE},Kt=function(){function t(e){e===void 0&&(e=Hd),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t}(),fs=Dd("OpenTelemetry Context Key SPAN");function ms(t){return t.getValue(fs)||void 0}function Jd(){return ms(Pi.getInstance().active())}function gs(t,e){return t.setValue(fs,e)}function Wd(t){return t.deleteValue(fs)}function Gd(t,e){return gs(t,new Kt(e))}function Ni(t){var e;return(e=ms(t))===null||e===void 0?void 0:e.spanContext()}var Yd=/^([0-9a-f]{32})$/i,Kd=/^[0-9a-f]{16}$/i;function Xd(t){return Yd.test(t)&&t!==ji}function Qd(t){return Kd.test(t)&&t!==Ri}function Mi(t){return Xd(t.traceId)&&Qd(t.spanId)}function ep(t){return new Kt(t)}var jn=Pi.getInstance(),Di=function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=jn.active());var s=!!(r!=null&&r.root);if(s)return new Kt;var a=n&&Ni(n);return tp(a)&&Mi(a)?new Kt(a):new Kt},t.prototype.startActiveSpan=function(e,r,n,s){var a,i,o;if(!(arguments.length<2)){arguments.length===2?o=r:arguments.length===3?(a=r,o=n):(a=r,i=n,o=s);var l=i??jn.active(),c=this.startSpan(e,a,l),d=gs(l,c);return jn.with(d,o,void 0,c)}},t}();function tp(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var rp=new Di,np=function(){function t(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,s){var a=this._getTracer();return Reflect.apply(a.startActiveSpan,a,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):rp},t}(),sp=function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new Di},t}(),ap=new sp,oa=function(){function t(){}return t.prototype.getTracer=function(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new np(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:ap},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)},t}(),ln;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(ln||(ln={}));var Nn="trace",ip=function(){function t(){this._proxyTracerProvider=new oa,this.wrapSpanContext=ep,this.isSpanContextValid=Mi,this.deleteSpan=Wd,this.getSpan=ms,this.getActiveSpan=Jd,this.getSpanContext=Ni,this.setSpan=gs,this.setSpanContext=Gd}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=ps(Nn,this._proxyTracerProvider,on.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return Er(Nn)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){hs(Nn,on.instance()),this._proxyTracerProvider=new oa},t}(),op=ip.getInstance(),lp=Object.defineProperty,ys=(t,e)=>{for(var r in e)lp(t,r,{get:e[r],enumerable:!0})};function vs(t,{contentType:e,dataStreamVersion:r}){const n=new Headers(t??{});return n.has("Content-Type")||n.set("Content-Type",e),r!==void 0&&n.set("X-Vercel-AI-Data-Stream",r),n}var Zi="AI_InvalidArgumentError",Ui=`vercel.ai.error.${Zi}`,cp=Symbol.for(Ui),Li,L=class extends O{constructor({parameter:t,value:e,message:r}){super({name:Zi,message:`Invalid argument for parameter ${t}: ${r}`}),this[Li]=!0,this.parameter=t,this.value=e}static isInstance(t){return O.hasMarker(t,Ui)}};Li=cp;var Fi="AI_RetryError",Vi=`vercel.ai.error.${Fi}`,up=Symbol.for(Vi),zi,la=class extends O{constructor({message:t,reason:e,errors:r}){super({name:Fi,message:t}),this[zi]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return O.hasMarker(t,Vi)}};zi=up;var dp=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2}={})=>async n=>Bi(n,{maxRetries:t,delayInMs:e,backoffFactor:r});async function Bi(t,{maxRetries:e,delayInMs:r,backoffFactor:n},s=[]){try{return await t()}catch(a){if(Dr(a)||e===0)throw a;const i=Nl(a),o=[...s,a],l=o.length;if(l>e)throw new la({message:`Failed after ${l} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:o});if(a instanceof Error&&Te.isInstance(a)&&a.isRetryable===!0&&l<=e)return await jl(r),Bi(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n},o);throw l===1?a:new la({message:`Failed after ${l} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:o})}}function pp({maxRetries:t}){if(t!=null){if(!Number.isInteger(t))throw new L({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new L({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const e=t??2;return{maxRetries:e,retry:dp({maxRetries:e})}}function Mn({operationId:t,telemetry:e}){return{"operation.name":`${t}${(e==null?void 0:e.functionId)!=null?` ${e.functionId}`:""}`,"resource.name":e==null?void 0:e.functionId,"ai.operationId":t,"ai.telemetry.functionId":e==null?void 0:e.functionId}}function hp({model:t,settings:e,telemetry:r,headers:n}){var s;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((a,[i,o])=>(a[`ai.settings.${i}`]=o,a),{}),...Object.entries((s=r==null?void 0:r.metadata)!=null?s:{}).reduce((a,[i,o])=>(a[`ai.telemetry.metadata.${i}`]=o,a),{}),...Object.entries(n??{}).reduce((a,[i,o])=>(o!==void 0&&(a[`ai.request.headers.${i}`]=o),a),{})}}var fp={startSpan(){return Rr},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(Rr);if(typeof r=="function")return r(Rr);if(typeof n=="function")return n(Rr)}},Rr={spanContext(){return mp},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},mp={traceId:"",spanId:"",traceFlags:0};function gp({isEnabled:t=!1,tracer:e}={}){return t?e||op.getTracer("ai"):fp}function Dn({name:t,tracer:e,attributes:r,fn:n,endWhenDone:s=!0}){return e.startActiveSpan(t,{attributes:r},async a=>{try{const i=await n(a);return s&&a.end(),i}catch(i){try{i instanceof Error?(a.recordException({name:i.name,message:i.message,stack:i.stack}),a.setStatus({code:ln.ERROR,message:i.message})):a.setStatus({code:ln.ERROR})}finally{a.end()}throw i}})}function mt({telemetry:t,attributes:e}){return(t==null?void 0:t.isEnabled)!==!0?{}:Object.entries(e).reduce((r,[n,s])=>{if(s===void 0)return r;if(typeof s=="object"&&"input"in s&&typeof s.input=="function"){if((t==null?void 0:t.recordInputs)===!1)return r;const a=s.input();return a===void 0?r:{...r,[n]:a}}if(typeof s=="object"&&"output"in s&&typeof s.output=="function"){if((t==null?void 0:t.recordOutputs)===!1)return r;const a=s.output();return a===void 0?r:{...r,[n]:a}}return{...r,[n]:s}},{})}var qi="AI_NoObjectGeneratedError",Hi=`vercel.ai.error.${qi}`,yp=Symbol.for(Hi),Ji,Le=class extends O{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:s}){super({name:qi,message:t,cause:e}),this[Ji]=!0,this.text=r,this.response=n,this.usage=s}static isInstance(t){return O.hasMarker(t,Hi)}};Ji=yp;var Wi="AI_DownloadError",Gi=`vercel.ai.error.${Wi}`,vp=Symbol.for(Gi),Yi,Zn=class extends O{constructor({url:t,statusCode:e,statusText:r,cause:n,message:s=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:Wi,message:s,cause:n}),this[Yi]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return O.hasMarker(t,Gi)}};Yi=vp;async function _p({url:t,fetchImplementation:e=fetch}){var r;const n=t.toString();try{const s=await e(n);if(!s.ok)throw new Zn({url:n,statusCode:s.status,statusText:s.statusText});return{data:new Uint8Array(await s.arrayBuffer()),mimeType:(r=s.headers.get("content-type"))!=null?r:void 0}}catch(s){throw Zn.isInstance(s)?s:new Zn({url:n,cause:s})}}var bp=[{mimeType:"image/gif",bytes:[71,73,70]},{mimeType:"image/png",bytes:[137,80,78,71]},{mimeType:"image/jpeg",bytes:[255,216]},{mimeType:"image/webp",bytes:[82,73,70,70]}];function wp(t){for(const{bytes:e,mimeType:r}of bp)if(t.length>=e.length&&e.every((n,s)=>t[s]===n))return r}var Ki="AI_InvalidDataContentError",Xi=`vercel.ai.error.${Ki}`,xp=Symbol.for(Xi),Qi,ca=class extends O{constructor({content:t,cause:e,message:r=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof t}.`}){super({name:Ki,message:r,cause:e}),this[Qi]=!0,this.content=t}static isInstance(t){return O.hasMarker(t,Xi)}};Qi=xp;var eo=u.union([u.string(),u.instanceof(Uint8Array),u.instanceof(ArrayBuffer),u.custom(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function Ap(t){return typeof t=="string"?t:t instanceof ArrayBuffer?qn(new Uint8Array(t)):qn(t)}function cn(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")try{return Gl(t)}catch(e){throw new ca({message:"Invalid data content. Content string is not a base64-encoded media.",content:t,cause:e})}if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new ca({content:t})}function Sp(t){try{return new TextDecoder().decode(t)}catch{throw new Error("Error decoding Uint8Array to text")}}var to="AI_InvalidMessageRoleError",ro=`vercel.ai.error.${to}`,kp=Symbol.for(ro),no,Ep=class extends O{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:to,message:e}),this[no]=!0,this.role=t}static isInstance(t){return O.hasMarker(t,ro)}};no=kp;function Tp(t){try{const[e,r]=t.split(",");return{mimeType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mimeType:void 0,base64Content:void 0}}}async function ua({prompt:t,modelSupportsImageUrls:e=!0,modelSupportsUrl:r=()=>!1,downloadImplementation:n=_p}){const s=await Ip(t.messages,n,e,r);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(a=>$p(a,s))]}function $p(t,e){var r,n,s,a,i,o;const l=t.role;switch(l){case"system":return{role:"system",content:t.content,providerMetadata:(r=t.providerOptions)!=null?r:t.experimental_providerMetadata};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerMetadata:(n=t.providerOptions)!=null?n:t.experimental_providerMetadata}:{role:"user",content:t.content.map(c=>Cp(c,e)).filter(c=>c.type!=="text"||c.text!==""),providerMetadata:(s=t.providerOptions)!=null?s:t.experimental_providerMetadata};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerMetadata:(a=t.providerOptions)!=null?a:t.experimental_providerMetadata}:{role:"assistant",content:t.content.filter(c=>c.type!=="text"||c.text!=="").map(c=>{const{experimental_providerMetadata:d,providerOptions:p,...g}=c;return{...g,providerMetadata:p??d}}),providerMetadata:(i=t.providerOptions)!=null?i:t.experimental_providerMetadata};case"tool":return{role:"tool",content:t.content.map(c=>{var d;return{type:"tool-result",toolCallId:c.toolCallId,toolName:c.toolName,result:c.result,content:c.experimental_content,isError:c.isError,providerMetadata:(d=c.providerOptions)!=null?d:c.experimental_providerMetadata}}),providerMetadata:(o=t.providerOptions)!=null?o:t.experimental_providerMetadata};default:{const c=l;throw new Ep({role:c})}}}async function Ip(t,e,r,n){const s=t.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").filter(i=>!(i.type==="image"&&r===!0)).map(i=>i.type==="image"?i.image:i.data).map(i=>typeof i=="string"&&(i.startsWith("http:")||i.startsWith("https:"))?new URL(i):i).filter(i=>i instanceof URL).filter(i=>!n(i)),a=await Promise.all(s.map(async i=>({url:i,data:await e({url:i})})));return Object.fromEntries(a.map(({url:i,data:o})=>[i.toString(),o]))}function Cp(t,e){var r,n,s,a;if(t.type==="text")return{type:"text",text:t.text,providerMetadata:(r=t.providerOptions)!=null?r:t.experimental_providerMetadata};let i=t.mimeType,o,l,c;const d=t.type;switch(d){case"image":o=t.image;break;case"file":o=t.data;break;default:throw new Error(`Unsupported part type: ${d}`)}try{l=typeof o=="string"?new URL(o):o}catch{l=o}if(l instanceof URL)if(l.protocol==="data:"){const{mimeType:p,base64Content:g}=Tp(l.toString());if(p==null||g==null)throw new Error(`Invalid data URL format in part ${d}`);i=p,c=cn(g)}else{const p=e[l.toString()];p?(c=p.data,i??(i=p.mimeType)):c=l}else c=cn(l);switch(d){case"image":return c instanceof Uint8Array&&(i=(n=wp(c))!=null?n:i),{type:"image",image:c,mimeType:i,providerMetadata:(s=t.providerOptions)!=null?s:t.experimental_providerMetadata};case"file":{if(i==null)throw new Error("Mime type is missing for file part");return{type:"file",data:c instanceof Uint8Array?Ap(c):c,mimeType:i,providerMetadata:(a=t.providerOptions)!=null?a:t.experimental_providerMetadata}}}}function da({maxTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:a,stopSequences:i,seed:o}){if(t!=null){if(!Number.isInteger(t))throw new L({parameter:"maxTokens",value:t,message:"maxTokens must be an integer"});if(t<1)throw new L({parameter:"maxTokens",value:t,message:"maxTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new L({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new L({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new L({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new L({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(a!=null&&typeof a!="number")throw new L({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new L({parameter:"seed",value:o,message:"seed must be an integer"});return{maxTokens:t,temperature:e??0,topP:r,topK:n,presencePenalty:s,frequencyPenalty:a,stopSequences:i!=null&&i.length>0?i:void 0,seed:o}}function Op(t){var e,r,n;const s=[];for(const a of t){let i;try{i=new URL(a.url)}catch{throw new Error(`Invalid URL: ${a.url}`)}switch(i.protocol){case"http:":case"https:":{if((e=a.contentType)!=null&&e.startsWith("image/"))s.push({type:"image",image:i});else{if(!a.contentType)throw new Error("If the attachment is not an image, it must specify a content type");s.push({type:"file",data:i,mimeType:a.contentType})}break}case"data:":{let o,l,c;try{[o,l]=a.url.split(","),c=o.split(";")[0].split(":")[1]}catch{throw new Error(`Error processing data URL: ${a.url}`)}if(c==null||l==null)throw new Error(`Invalid data URL format: ${a.url}`);if((r=a.contentType)!=null&&r.startsWith("image/"))s.push({type:"image",image:cn(l)});else if((n=a.contentType)!=null&&n.startsWith("text/"))s.push({type:"text",text:Sp(cn(l))});else{if(!a.contentType)throw new Error("If the attachment is not an image or text, it must specify a content type");s.push({type:"file",data:l,mimeType:a.contentType})}break}default:throw new Error(`Unsupported URL protocol: ${i.protocol}`)}}return s}var so="AI_MessageConversionError",ao=`vercel.ai.error.${so}`,Pp=Symbol.for(ao),io,Un=class extends O{constructor({originalMessage:t,message:e}){super({name:so,message:e}),this[io]=!0,this.originalMessage=t}static isInstance(t){return O.hasMarker(t,ao)}};io=Pp;function Rp(t,e){var r,n;const s=(r=e==null?void 0:e.tools)!=null?r:{},a=[];for(let i=0;i<t.length;i++){const o=t[i],l=i===t.length-1,{role:c,content:d,experimental_attachments:p}=o;switch(c){case"system":{a.push({role:"system",content:d});break}case"user":{a.push({role:"user",content:p?[{type:"text",text:d},...Op(p)]:d});break}case"assistant":{if(o.parts!=null){let y=function(){const k=[];for(const P of A)switch(P.type){case"text":k.push({type:"text",text:P.text});break;case"reasoning":{for(const R of P.details)switch(R.type){case"text":k.push({type:"reasoning",text:R.text,signature:R.signature});break;case"redacted":k.push({type:"redacted-reasoning",data:R.data});break}break}case"tool-invocation":k.push({type:"tool-call",toolCallId:P.toolInvocation.toolCallId,toolName:P.toolInvocation.toolName,args:P.toolInvocation.args});break;default:{const R=P;throw new Error(`Unsupported part: ${R}`)}}a.push({role:"assistant",content:k});const T=A.filter(P=>P.type==="tool-invocation").map(P=>P.toolInvocation);T.length>0&&a.push({role:"tool",content:T.map(P=>{if(!("result"in P))throw new Un({originalMessage:o,message:"ToolInvocation must have a result: "+JSON.stringify(P)});const{toolCallId:R,toolName:B,result:I}=P,Y=s[B];return(Y==null?void 0:Y.experimental_toToolResultContent)!=null?{type:"tool-result",toolCallId:R,toolName:B,result:Y.experimental_toToolResultContent(I),experimental_content:Y.experimental_toToolResultContent(I)}:{type:"tool-result",toolCallId:R,toolName:B,result:I}})}),A=[],v=!1,m++},m=0,v=!1,A=[];for(const k of o.parts)switch(k.type){case"reasoning":A.push(k);break;case"text":{v&&y(),A.push(k);break}case"tool-invocation":{((n=k.toolInvocation.step)!=null?n:0)!==m&&y(),A.push(k),v=!0;break}}y();break}const g=o.toolInvocations;if(g==null||g.length===0){a.push({role:"assistant",content:d});break}const w=g.reduce((y,m)=>{var v;return Math.max(y,(v=m.step)!=null?v:0)},0);for(let y=0;y<=w;y++){const m=g.filter(v=>{var A;return((A=v.step)!=null?A:0)===y});m.length!==0&&(a.push({role:"assistant",content:[...l&&d&&y===0?[{type:"text",text:d}]:[],...m.map(({toolCallId:v,toolName:A,args:k})=>({type:"tool-call",toolCallId:v,toolName:A,args:k}))]}),a.push({role:"tool",content:m.map(v=>{if(!("result"in v))throw new Un({originalMessage:o,message:"ToolInvocation must have a result: "+JSON.stringify(v)});const{toolCallId:A,toolName:k,result:T}=v,P=s[k];return(P==null?void 0:P.experimental_toToolResultContent)!=null?{type:"tool-result",toolCallId:A,toolName:k,result:P.experimental_toToolResultContent(T),experimental_content:P.experimental_toToolResultContent(T)}:{type:"tool-result",toolCallId:A,toolName:k,result:T}})}))}d&&!l&&a.push({role:"assistant",content:d});break}case"data":break;default:{const g=c;throw new Un({originalMessage:o,message:`Unsupported role: ${g}`})}}}return a}function jp(t){if(!Array.isArray(t))return"other";if(t.length===0)return"messages";const e=t.map(Np);return e.some(r=>r==="has-ui-specific-parts")?"ui-messages":e.every(r=>r==="has-core-specific-parts"||r==="message")?"messages":"other"}function Np(t){return typeof t=="object"&&t!==null&&(t.role==="function"||t.role==="data"||"toolInvocations"in t||"experimental_attachments"in t)?"has-ui-specific-parts":typeof t=="object"&&t!==null&&"content"in t&&(Array.isArray(t.content)||"experimental_providerMetadata"in t||"providerOptions"in t)?"has-core-specific-parts":typeof t=="object"&&t!==null&&"role"in t&&"content"in t&&typeof t.content=="string"&&["system","user","assistant","tool"].includes(t.role)?"message":"other"}var ts=u.lazy(()=>u.union([u.null(),u.string(),u.number(),u.boolean(),u.record(u.string(),ts),u.array(ts)])),q=u.record(u.string(),u.record(u.string(),ts)),Mp=u.array(u.union([u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("image"),data:u.string(),mimeType:u.string().optional()})])),oo=u.object({type:u.literal("text"),text:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Dp=u.object({type:u.literal("image"),image:u.union([eo,u.instanceof(URL)]),mimeType:u.string().optional(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Zp=u.object({type:u.literal("file"),data:u.union([eo,u.instanceof(URL)]),mimeType:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Up=u.object({type:u.literal("reasoning"),text:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Lp=u.object({type:u.literal("redacted-reasoning"),data:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Fp=u.object({type:u.literal("tool-call"),toolCallId:u.string(),toolName:u.string(),args:u.unknown(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Vp=u.object({type:u.literal("tool-result"),toolCallId:u.string(),toolName:u.string(),result:u.unknown(),content:Mp.optional(),isError:u.boolean().optional(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),zp=u.object({role:u.literal("system"),content:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Bp=u.object({role:u.literal("user"),content:u.union([u.string(),u.array(u.union([oo,Dp,Zp]))]),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),qp=u.object({role:u.literal("assistant"),content:u.union([u.string(),u.array(u.union([oo,Up,Lp,Fp]))]),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Hp=u.object({role:u.literal("tool"),content:u.array(Vp),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Jp=u.union([zp,Bp,qp,Hp]);function pa({prompt:t,tools:e}){if(t.prompt==null&&t.messages==null)throw new Qe({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Qe({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new Qe({prompt:t,message:"system must be a string"});if(t.prompt!=null){if(typeof t.prompt!="string")throw new Qe({prompt:t,message:"prompt must be a string"});return{type:"prompt",system:t.system,messages:[{role:"user",content:t.prompt}]}}if(t.messages!=null){const r=jp(t.messages);if(r==="other")throw new Qe({prompt:t,message:"messages must be an array of CoreMessage or UIMessage"});const n=r==="ui-messages"?Rp(t.messages,{tools:e}):t.messages,s=ot({value:n,schema:u.array(Jp)});if(!s.success)throw new Qe({prompt:t,message:"messages must be an array of CoreMessage or UIMessage",cause:s.error});return{type:"messages",messages:n,system:t.system}}throw new Error("unreachable")}function gt({promptTokens:t,completionTokens:e}){return{promptTokens:t,completionTokens:e,totalTokens:t+e}}var Wp="JSON schema:",Gp="You MUST answer with a JSON object that matches the JSON schema above.",Yp="You MUST answer with JSON.";function rs({prompt:t,schema:e,schemaPrefix:r=e!=null?Wp:void 0,schemaSuffix:n=e!=null?Gp:Yp}){return[t!=null&&t.length>0?t:void 0,t!=null&&t.length>0?"":void 0,r,e!=null?JSON.stringify(e):void 0,n].filter(s=>s!=null).join(`
|
184
|
+
`)}function Kp(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=()=>{const r=e.getReader();return{async next(){const{done:n,value:s}=await r.read();return n?{done:!0,value:void 0}:{done:!1,value:s}}}},e}var Xp={type:"no-schema",jsonSchema:void 0,validatePartialResult({value:t,textDelta:e}){return{success:!0,value:{partial:t,textDelta:e}}},validateFinalResult(t,e){return t===void 0?{success:!1,error:new Le({message:"No object generated: response did not match schema.",text:e.text,response:e.response,usage:e.usage})}:{success:!0,value:t}},createElementStream(){throw new G({functionality:"element streams in no-schema mode"})}},Qp=t=>({type:"object",jsonSchema:t.jsonSchema,validatePartialResult({value:e,textDelta:r}){return{success:!0,value:{partial:e,textDelta:r}}},validateFinalResult(e){return ot({value:e,schema:t})},createElementStream(){throw new G({functionality:"element streams in object mode"})}}),eh=t=>{const{$schema:e,...r}=t.jsonSchema;return{type:"enum",jsonSchema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:r}},required:["elements"],additionalProperties:!1},validatePartialResult({value:n,latestObject:s,isFirstDelta:a,isFinalDelta:i}){var o;if(!Bn(n)||!Js(n.elements))return{success:!1,error:new je({value:n,cause:"value must be an object that contains an array of elements"})};const l=n.elements,c=[];for(let g=0;g<l.length;g++){const w=l[g],y=ot({value:w,schema:t});if(!(g===l.length-1&&!i)){if(!y.success)return y;c.push(y.value)}}const d=(o=s==null?void 0:s.length)!=null?o:0;let p="";return a&&(p+="["),d>0&&(p+=","),p+=c.slice(d).map(g=>JSON.stringify(g)).join(","),i&&(p+="]"),{success:!0,value:{partial:c,textDelta:p}}},validateFinalResult(n){if(!Bn(n)||!Js(n.elements))return{success:!1,error:new je({value:n,cause:"value must be an object that contains an array of elements"})};const s=n.elements;for(const a of s){const i=ot({value:a,schema:t});if(!i.success)return i}return{success:!0,value:s}},createElementStream(n){let s=0;return Kp(n.pipeThrough(new TransformStream({transform(a,i){switch(a.type){case"object":{const o=a.object;for(;s<o.length;s++)i.enqueue(o[s]);break}case"text-delta":case"finish":case"error":break;default:{const o=a;throw new Error(`Unsupported chunk type: ${o}`)}}}})))}}},th=t=>({type:"enum",jsonSchema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:t}},required:["result"],additionalProperties:!1},validateFinalResult(e){if(!Bn(e)||typeof e.result!="string")return{success:!1,error:new je({value:e,cause:'value must be an object that contains a string in the "result" property.'})};const r=e.result;return t.includes(r)?{success:!0,value:r}:{success:!1,error:new je({value:e,cause:"value must be a string in the enum"})}},validatePartialResult(){throw new G({functionality:"partial results in enum mode"})},createElementStream(){throw new G({functionality:"element streams in enum mode"})}});function rh({output:t,schema:e,enumValues:r}){switch(t){case"object":return Qp(Qn(e));case"array":return eh(Qn(e));case"enum":return th(r);case"no-schema":return Xp;default:{const n=t;throw new Error(`Unsupported output: ${n}`)}}}function nh({output:t,mode:e,schema:r,schemaName:n,schemaDescription:s,enumValues:a}){if(t!=null&&t!=="object"&&t!=="array"&&t!=="enum"&&t!=="no-schema")throw new L({parameter:"output",value:t,message:"Invalid output type."});if(t==="no-schema"){if(e==="auto"||e==="tool")throw new L({parameter:"mode",value:e,message:'Mode must be "json" for no-schema output.'});if(r!=null)throw new L({parameter:"schema",value:r,message:"Schema is not supported for no-schema output."});if(s!=null)throw new L({parameter:"schemaDescription",value:s,message:"Schema description is not supported for no-schema output."});if(n!=null)throw new L({parameter:"schemaName",value:n,message:"Schema name is not supported for no-schema output."});if(a!=null)throw new L({parameter:"enumValues",value:a,message:"Enum values are not supported for no-schema output."})}if(t==="object"){if(r==null)throw new L({parameter:"schema",value:r,message:"Schema is required for object output."});if(a!=null)throw new L({parameter:"enumValues",value:a,message:"Enum values are not supported for object output."})}if(t==="array"){if(r==null)throw new L({parameter:"schema",value:r,message:"Element schema is required for array output."});if(a!=null)throw new L({parameter:"enumValues",value:a,message:"Enum values are not supported for array output."})}if(t==="enum"){if(r!=null)throw new L({parameter:"schema",value:r,message:"Schema is not supported for enum output."});if(s!=null)throw new L({parameter:"schemaDescription",value:s,message:"Schema description is not supported for enum output."});if(n!=null)throw new L({parameter:"schemaName",value:n,message:"Schema name is not supported for enum output."});if(a==null)throw new L({parameter:"enumValues",value:a,message:"Enum values are required for enum output."});for(const i of a)if(typeof i!="string")throw new L({parameter:"enumValues",value:i,message:"Enum values must be strings."})}}var sh=pt({prefix:"aiobj",size:24});async function ah({model:t,enum:e,schema:r,schemaName:n,schemaDescription:s,mode:a,output:i="object",system:o,prompt:l,messages:c,maxRetries:d,abortSignal:p,headers:g,experimental_repairText:w,experimental_telemetry:y,experimental_providerMetadata:m,providerOptions:v=m,_internal:{generateId:A=sh,currentDate:k=()=>new Date}={},...T}){nh({output:i,mode:a,schema:r,schemaName:n,schemaDescription:s,enumValues:e});const{maxRetries:P,retry:R}=pp({maxRetries:d}),B=rh({output:i,schema:r,enumValues:e});B.type==="no-schema"&&a===void 0&&(a="json");const I=hp({model:t,telemetry:y,headers:g,settings:{...T,maxRetries:P}}),Y=gp(y);return Dn({name:"ai.generateObject",attributes:mt({telemetry:y,attributes:{...Mn({operationId:"ai.generateObject",telemetry:y}),...I,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:l,messages:c})},"ai.schema":B.jsonSchema!=null?{input:()=>JSON.stringify(B.jsonSchema)}:void 0,"ai.schema.name":n,"ai.schema.description":s,"ai.settings.output":B.type,"ai.settings.mode":a}}),tracer:Y,fn:async ht=>{var Je,We,Ge,Ce;(a==="auto"||a==null)&&(a=t.defaultObjectGenerationMode);let ie,xe,ce,ft,V,se,H,D,bn;switch(a){case"json":{const J=pa({prompt:{system:B.jsonSchema==null?rs({prompt:o}):t.supportsStructuredOutputs?o:rs({prompt:o,schema:B.jsonSchema}),prompt:l,messages:c},tools:void 0}),ue=await ua({prompt:J,modelSupportsImageUrls:t.supportsImageUrls,modelSupportsUrl:(Je=t.supportsUrl)==null?void 0:Je.bind(t)}),X=await R(()=>Dn({name:"ai.generateObject.doGenerate",attributes:mt({telemetry:y,attributes:{...Mn({operationId:"ai.generateObject.doGenerate",telemetry:y}),...I,"ai.prompt.format":{input:()=>J.type},"ai.prompt.messages":{input:()=>JSON.stringify(ue)},"ai.settings.mode":a,"gen_ai.system":t.provider,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.temperature":T.temperature,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:Y,fn:async he=>{var Cr,jt,Nt,Mt,Dt,Zt;const K=await t.doGenerate({mode:{type:"object-json",schema:B.jsonSchema,name:n,description:s},...da(T),inputFormat:J.type,prompt:ue,providerMetadata:v,abortSignal:p,headers:g}),Ae={id:(jt=(Cr=K.response)==null?void 0:Cr.id)!=null?jt:A(),timestamp:(Mt=(Nt=K.response)==null?void 0:Nt.timestamp)!=null?Mt:k(),modelId:(Zt=(Dt=K.response)==null?void 0:Dt.modelId)!=null?Zt:t.modelId};if(K.text===void 0)throw new Le({message:"No object generated: the model did not return a response.",response:Ae,usage:gt(K.usage)});return he.setAttributes(mt({telemetry:y,attributes:{"ai.response.finishReason":K.finishReason,"ai.response.object":{output:()=>K.text},"ai.response.id":Ae.id,"ai.response.model":Ae.modelId,"ai.response.timestamp":Ae.timestamp.toISOString(),"ai.usage.promptTokens":K.usage.promptTokens,"ai.usage.completionTokens":K.usage.completionTokens,"gen_ai.response.finish_reasons":[K.finishReason],"gen_ai.response.id":Ae.id,"gen_ai.response.model":Ae.modelId,"gen_ai.usage.prompt_tokens":K.usage.promptTokens,"gen_ai.usage.completion_tokens":K.usage.completionTokens}})),{...K,objectText:K.text,responseData:Ae}}}));ie=X.objectText,xe=X.finishReason,ce=X.usage,ft=X.warnings,V=X.rawResponse,D=X.logprobs,bn=X.providerMetadata,H=(We=X.request)!=null?We:{},se=X.responseData;break}case"tool":{const J=pa({prompt:{system:o,prompt:l,messages:c},tools:void 0}),ue=await ua({prompt:J,modelSupportsImageUrls:t.supportsImageUrls,modelSupportsUrl:(Ge=t.supportsUrl)==null?void 0:Ge.bind(t)}),X=J.type,he=await R(()=>Dn({name:"ai.generateObject.doGenerate",attributes:mt({telemetry:y,attributes:{...Mn({operationId:"ai.generateObject.doGenerate",telemetry:y}),...I,"ai.prompt.format":{input:()=>X},"ai.prompt.messages":{input:()=>JSON.stringify(ue)},"ai.settings.mode":a,"gen_ai.system":t.provider,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.temperature":T.temperature,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:Y,fn:async Cr=>{var jt,Nt,Mt,Dt,Zt,K,Ae,Ss;const de=await t.doGenerate({mode:{type:"object-tool",tool:{type:"function",name:n??"json",description:s??"Respond with a JSON object.",parameters:B.jsonSchema}},...da(T),inputFormat:X,prompt:ue,providerMetadata:v,abortSignal:p,headers:g}),wn=(Nt=(jt=de.toolCalls)==null?void 0:jt[0])==null?void 0:Nt.args,Ye={id:(Dt=(Mt=de.response)==null?void 0:Mt.id)!=null?Dt:A(),timestamp:(K=(Zt=de.response)==null?void 0:Zt.timestamp)!=null?K:k(),modelId:(Ss=(Ae=de.response)==null?void 0:Ae.modelId)!=null?Ss:t.modelId};if(wn===void 0)throw new Le({message:"No object generated: the tool was not called.",response:Ye,usage:gt(de.usage)});return Cr.setAttributes(mt({telemetry:y,attributes:{"ai.response.finishReason":de.finishReason,"ai.response.object":{output:()=>wn},"ai.response.id":Ye.id,"ai.response.model":Ye.modelId,"ai.response.timestamp":Ye.timestamp.toISOString(),"ai.usage.promptTokens":de.usage.promptTokens,"ai.usage.completionTokens":de.usage.completionTokens,"gen_ai.response.finish_reasons":[de.finishReason],"gen_ai.response.id":Ye.id,"gen_ai.response.model":Ye.modelId,"gen_ai.usage.input_tokens":de.usage.promptTokens,"gen_ai.usage.output_tokens":de.usage.completionTokens}})),{...de,objectText:wn,responseData:Ye}}}));ie=he.objectText,xe=he.finishReason,ce=he.usage,ft=he.warnings,V=he.rawResponse,D=he.logprobs,bn=he.providerMetadata,H=(Ce=he.request)!=null?Ce:{},se=he.responseData;break}case void 0:throw new Error("Model does not have a default object generation mode.");default:{const J=a;throw new Error(`Unsupported mode: ${J}`)}}function As(J){const ue=$t({text:J});if(!ue.success)throw new Le({message:"No object generated: could not parse the response.",cause:ue.error,text:J,response:se,usage:gt(ce)});const X=B.validateFinalResult(ue.value,{text:J,response:se,usage:gt(ce)});if(!X.success)throw new Le({message:"No object generated: response did not match schema.",cause:X.error,text:J,response:se,usage:gt(ce)});return X.value}let Ir;try{Ir=As(ie)}catch(J){if(w!=null&&Le.isInstance(J)&&(ar.isInstance(J.cause)||je.isInstance(J.cause))){const ue=await w({text:ie,error:J.cause});if(ue===null)throw J;Ir=As(ue)}else throw J}return ht.setAttributes(mt({telemetry:y,attributes:{"ai.response.finishReason":xe,"ai.response.object":{output:()=>JSON.stringify(Ir)},"ai.usage.promptTokens":ce.promptTokens,"ai.usage.completionTokens":ce.completionTokens}})),new ih({object:Ir,finishReason:xe,usage:gt(ce),warnings:ft,request:H,response:{...se,headers:V==null?void 0:V.headers,body:V==null?void 0:V.body},logprobs:D,providerMetadata:bn})}})}var ih=class{constructor(t){this.object=t.object,this.finishReason=t.finishReason,this.usage=t.usage,this.warnings=t.warnings,this.providerMetadata=t.providerMetadata,this.experimental_providerMetadata=t.providerMetadata,this.response=t.response,this.request=t.request,this.logprobs=t.logprobs}toJsonResponse(t){var e;return new Response(JSON.stringify(this.object),{status:(e=t==null?void 0:t.status)!=null?e:200,headers:vs(t==null?void 0:t.headers,{contentType:"application/json; charset=utf-8"})})}};pt({prefix:"aiobj",size:24});pt({prefix:"aitxt",size:24});pt({prefix:"msg",size:24});var oh={};ys(oh,{object:()=>ch,text:()=>lh});var lh=()=>({type:"text",responseFormat:()=>({type:"text"}),injectIntoSystemPrompt({system:t}){return t},parsePartial({text:t}){return{partial:t}},parseOutput({text:t}){return t}}),ch=({schema:t})=>{const e=Qn(t);return{type:"object",responseFormat:({model:r})=>({type:"json",schema:r.supportsStructuredOutputs?e.jsonSchema:void 0}),injectIntoSystemPrompt({system:r,model:n}){return n.supportsStructuredOutputs?r:rs({prompt:r,schema:e.jsonSchema})},parsePartial({text:r}){const n=ld(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},parseOutput({text:r},n){const s=$t({text:r});if(!s.success)throw new Le({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage});const a=ot({value:s.value,schema:e});if(!a.success)throw new Le({message:"No object generated: response did not match schema.",cause:a.error,text:r,response:n.response,usage:n.usage});return a.value}}};function lo(t,e){const r=t.getReader(),n=e.getReader();let s,a,i=!1,o=!1;async function l(d){try{s==null&&(s=r.read());const p=await s;s=void 0,p.done?d.close():d.enqueue(p.value)}catch(p){d.error(p)}}async function c(d){try{a==null&&(a=n.read());const p=await a;a=void 0,p.done?d.close():d.enqueue(p.value)}catch(p){d.error(p)}}return new ReadableStream({async pull(d){try{if(i){await c(d);return}if(o){await l(d);return}s==null&&(s=r.read()),a==null&&(a=n.read());const{result:p,reader:g}=await Promise.race([s.then(w=>({result:w,reader:r})),a.then(w=>({result:w,reader:n}))]);p.done||d.enqueue(p.value),g===r?(s=void 0,p.done&&(await c(d),i=!0)):(a=void 0,p.done&&(o=!0,await l(d)))}catch(p){d.error(p)}},cancel(){r.cancel(),n.cancel()}})}pt({prefix:"aitxt",size:24});pt({prefix:"msg",size:24});var uh={};ys(uh,{mergeIntoDataStream:()=>hh,toDataStream:()=>dh,toDataStreamResponse:()=>ph});function co(t={}){const e=new TextEncoder;let r="";return new TransformStream({async start(){t.onStart&&await t.onStart()},async transform(n,s){s.enqueue(e.encode(n)),r+=n,t.onToken&&await t.onToken(n),t.onText&&typeof n=="string"&&await t.onText(n)},async flush(){t.onCompletion&&await t.onCompletion(r),t.onFinal&&await t.onFinal(r)}})}function _s(t,e){return t.pipeThrough(new TransformStream({transform:async(r,n)=>{var s;if(typeof r=="string"){n.enqueue(r);return}if("event"in r){r.event==="on_chat_model_stream"&&ha((s=r.data)==null?void 0:s.chunk,n);return}ha(r,n)}})).pipeThrough(co(e)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(r,n)=>{n.enqueue(Oi("text",r))}}))}function dh(t,e){return _s(t,e).pipeThrough(new TextEncoderStream)}function ph(t,e){var r;const n=_s(t,e==null?void 0:e.callbacks).pipeThrough(new TextEncoderStream),s=e==null?void 0:e.data,a=e==null?void 0:e.init,i=s?lo(s.stream,n):n;return new Response(i,{status:(r=a==null?void 0:a.status)!=null?r:200,statusText:a==null?void 0:a.statusText,headers:vs(a==null?void 0:a.headers,{contentType:"text/plain; charset=utf-8",dataStreamVersion:"v1"})})}function hh(t,e){e.dataStream.merge(_s(t,e.callbacks))}function ha(t,e){if(typeof t.content=="string")e.enqueue(t.content);else{const r=t.content;for(const n of r)n.type==="text"&&e.enqueue(n.text)}}var fh={};ys(fh,{mergeIntoDataStream:()=>yh,toDataStream:()=>mh,toDataStreamResponse:()=>gh});function bs(t,e){const r=vh();return Rl(t[Symbol.asyncIterator]()).pipeThrough(new TransformStream({async transform(n,s){s.enqueue(r(n.delta))}})).pipeThrough(co(e)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(n,s)=>{s.enqueue(Oi("text",n))}}))}function mh(t,e){return bs(t,e).pipeThrough(new TextEncoderStream)}function gh(t,e={}){var r;const{init:n,data:s,callbacks:a}=e,i=bs(t,a).pipeThrough(new TextEncoderStream),o=s?lo(s.stream,i):i;return new Response(o,{status:(r=n==null?void 0:n.status)!=null?r:200,statusText:n==null?void 0:n.statusText,headers:vs(n==null?void 0:n.headers,{contentType:"text/plain; charset=utf-8",dataStreamVersion:"v1"})})}function yh(t,e){e.dataStream.merge(bs(t,e.callbacks))}function vh(){let t=!0;return e=>(t&&(e=e.trimStart(),e&&(t=!1)),e)}function _h(t){return t?` In this environment you have access to a set of tools. Here are the functions available in JSONSchema format:
|
185
|
+
${JSON.stringify(t.actions)}
|
186
|
+
This is the start data that the tools have provided: ${JSON.stringify(t.data)}
|
187
|
+
Choose to respond as text and/or one or more functions to call to respond to the user's query.
|
188
|
+
`:void 0}function bh(t){if(!t)return Xn({type:"object",properties:{text:{type:"string"}},additionalProperties:!1});const e={type:"object",properties:{text:{type:"string"},tools:{type:"array",items:{anyOf:Object.keys(t.actions).map(r=>{const n=t.actions[r],s={type:"object",properties:{id:{type:"string",enum:[r]}},additionalProperties:!1,required:["id"]};return n.params_schema&&!Pa(n.params_schema.properties)&&(s.properties.arguments=n.params_schema,s.properties.arguments.required||(s.properties.arguments.required=Object.keys(s.properties.arguments.properties)),s.properties.arguments.additionalProperties=!1,s.required.push("arguments")),s})},additionalProperties:!1}},additionalProperties:!1};return Xn(e)}async function wh(t,e,r){var p;const n=JSON.stringify(e),s=n?`${n}
|
189
|
+
${t}`:t,a=(p=ae.get().settings)==null?void 0:p.openAIAPIToken,o=ki({apiKey:a,compatibility:"strict"})("gpt-4o-mini"),l=_h(r),c=bh(r),{object:d}=await ah({model:o,prompt:s,system:l,schema:c});return d}const xh={getModelResponse:wh};var Ah=Object.defineProperty,Sh=Object.getOwnPropertyDescriptor,ws=(t,e,r,n)=>{for(var s=n>1?void 0:n?Sh(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&Ah(e,r,s),s};let un=class extends re{constructor(){super(...arguments),this.openAIAPIToken="",this.promptState="idle"}createRenderRoot(){return this}connectedCallback(){ae.subscribe(t=>{var e;this.openAIAPIToken=(e=t.settings)==null?void 0:e.openAIAPIToken}),super.connectedCallback()}async onSubmit(t){t.preventDefault();const r=t.target.elements.namedItem("prompt"),n=r.value.trim();if(!n)return;const s=Hr.getRecentInteractions();this.promptState="thinking",r.value="";const a=await xh.getModelResponse(n,s,window.applet),i=[];a.text&&i.push({type:"text",content:a.text}),a.tools&&a.tools.length>0&&await Promise.all(a.tools.map(async o=>{await window.applet.sendAction(o.id,o.arguments),i.push({type:o.id,arguments:o.arguments}),window.applet.data&&i.push({type:"data",content:window.applet.data})})),Hr.addInteraction({input:{type:"command",text:n},outputs:i,timestamp:Date.now()}),this.promptState="idle",setTimeout(()=>document.getElementById("prompt").focus())}render(){return U`
|
190
|
+
<form @submit="${this.onSubmit}">
|
191
|
+
<input
|
192
|
+
autocomplete="off"
|
193
|
+
id="prompt"
|
194
|
+
name="prompt"
|
195
|
+
autofocus
|
196
|
+
.disabled="${!this.openAIAPIToken||this.promptState==="thinking"}"
|
197
|
+
placeholder="${this.openAIAPIToken?this.promptState==="thinking"?"Thinking…":"Start typing to interact…":"Update your OpenAI API key in the settings dialog to interact via the prompt."}"
|
198
|
+
/>
|
199
|
+
${this.promptState==="thinking"?U`
|
200
|
+
<svg
|
201
|
+
xmlns="http://www.w3.org/2000/svg"
|
202
|
+
width="24"
|
203
|
+
height="24"
|
204
|
+
viewBox="0 0 24 24"
|
205
|
+
fill="none"
|
206
|
+
stroke="currentColor"
|
207
|
+
stroke-width="1"
|
208
|
+
stroke-linecap="round"
|
209
|
+
stroke-linejoin="round"
|
210
|
+
class="loader"
|
211
|
+
>
|
212
|
+
<circle cx="12" cy="12" r="9" />
|
213
|
+
</svg>
|
214
|
+
`:F}
|
215
|
+
</form>
|
216
|
+
`}};ws([ee({type:String})],un.prototype,"openAIAPIToken",2);ws([ee({type:String})],un.prototype,"promptState",2);un=ws([we("app-prompt")],un);var kh=Object.defineProperty,Eh=Object.getOwnPropertyDescriptor,uo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Eh(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&kh(e,r,s),s};let ns=class extends re{constructor(){super(...arguments),this.interactions=[]}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.unsubscribe=Hr.subscribe(t=>{this.interactions=[...t]})}disconnectedCallback(){this.unsubscribe&&this.unsubscribe(),super.disconnectedCallback()}render(){const t=e=>Object.entries(e).filter(([r])=>r!=="type").map(([r,n])=>typeof n=="object"&&n!==null?`${r}: ${JSON.stringify(n)}`:`${r}: ${n}`).join(", ");return U`
|
217
|
+
<div class="history">
|
218
|
+
${this.interactions.length<=0?U`
|
219
|
+
<div class="action-output">
|
220
|
+
<span class="status-message">Enter a message below to interact</span>
|
221
|
+
</div>
|
222
|
+
`:U``}
|
223
|
+
${this.interactions.map(e=>{const r=e.input.type==="command"?U`
|
224
|
+
<div class="bubble-container user-bubble-container">
|
225
|
+
<div class="bubble user">
|
226
|
+
<strong>You:</strong>
|
227
|
+
<span>${e.input.text}</span>
|
228
|
+
</div>
|
229
|
+
</div>
|
230
|
+
`:U``,n=e.outputs.filter(s=>s.type!=="data").map(s=>e.input.type==="command"?s.type==="text"?U`
|
231
|
+
<div class="bubble-container assistant-bubble-container">
|
232
|
+
<div class="bubble assistant">
|
233
|
+
<strong>Assistant:</strong>
|
234
|
+
<span>${s.content}</span>
|
235
|
+
</div>
|
236
|
+
</div>
|
237
|
+
`:U`
|
238
|
+
<div class="action-output">
|
239
|
+
<strong>Action: ${s.type}</strong>
|
240
|
+
<span>${t(s)}</span>
|
241
|
+
</div>
|
242
|
+
`:e.input.type==="action"?U`
|
243
|
+
<div class="action-output">
|
244
|
+
<strong>Action: ${e.input.text}</strong>
|
245
|
+
<span>{${t(s)}}</span>
|
246
|
+
</div>
|
247
|
+
`:U``);return U`${r}${n}`})}
|
248
|
+
</div>
|
249
|
+
`}};uo([No()],ns.prototype,"interactions",2);ns=uo([we("app-history")],ns);/**
|
250
|
+
* @license
|
251
|
+
* Copyright 2020 Google LLC
|
252
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
253
|
+
*/const Th=t=>t.strings===void 0;/**
|
254
|
+
* @license
|
255
|
+
* Copyright 2017 Google LLC
|
256
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
257
|
+
*/const Xt=(t,e)=>{var n;const r=t._$AN;if(r===void 0)return!1;for(const s of r)(n=s._$AO)==null||n.call(s,e,!1),Xt(s,e);return!0},dn=t=>{let e,r;do{if((e=t._$AM)===void 0)break;r=e._$AN,r.delete(t),t=e}while((r==null?void 0:r.size)===0)},po=t=>{for(let e;e=t._$AM;t=e){let r=e._$AN;if(r===void 0)e._$AN=r=new Set;else if(r.has(t))break;r.add(t),Ch(e)}};function $h(t){this._$AN!==void 0?(dn(this),this._$AM=t,po(this)):this._$AM=t}function Ih(t,e=!1,r=0){const n=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(e)if(Array.isArray(n))for(let a=r;a<n.length;a++)Xt(n[a],!1),dn(n[a]);else n!=null&&(Xt(n,!1),dn(n));else Xt(this,t)}const Ch=t=>{t.type==Sa.CHILD&&(t._$AP??(t._$AP=Ih),t._$AQ??(t._$AQ=$h))};class Oh extends Ea{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,r,n){super._$AT(e,r,n),po(this),this.isConnected=e._$AU}_$AO(e,r=!0){var n,s;e!==this.isConnected&&(this.isConnected=e,e?(n=this.reconnected)==null||n.call(this):(s=this.disconnected)==null||s.call(this)),r&&(Xt(this,e),dn(this))}setValue(e){if(Th(this._$Ct))this._$Ct._$AI(e,this);else{const r=[...this._$Ct._$AH];r[this._$Ci]=e,this._$Ct._$AI(r,this,0)}}disconnected(){}reconnected(){}}/**
|
258
|
+
* @license
|
259
|
+
* Copyright 2020 Google LLC
|
260
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
261
|
+
*/const fa=()=>new Ph;class Ph{}const Ln=new WeakMap,ma=ka(class extends Oh{render(t){return F}update(t,[e]){var n;const r=e!==this.Y;return r&&this.Y!==void 0&&this.rt(void 0),(r||this.lt!==this.ct)&&(this.Y=e,this.ht=(n=t.options)==null?void 0:n.host,this.rt(this.ct=t.element)),F}rt(t){if(this.isConnected||(t=void 0),typeof this.Y=="function"){const e=this.ht??globalThis;let r=Ln.get(e);r===void 0&&(r=new WeakMap,Ln.set(e,r)),r.get(this.Y)!==void 0&&this.Y.call(this.ht,void 0),r.set(this.Y,t),t!==void 0&&this.Y.call(this.ht,t)}else this.Y.value=t}get lt(){var t,e;return typeof this.Y=="function"?(t=Ln.get(this.ht??globalThis))==null?void 0:t.get(this.Y):(e=this.Y)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var Rh=Object.defineProperty,jh=Object.getOwnPropertyDescriptor,xs=(t,e,r,n)=>{for(var s=n>1?void 0:n?jh(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&Rh(e,r,s),s};let pn=class extends re{constructor(){super(...arguments),this.open=!1,this.openAIAPIToken="",this.dialogRef=fa(),this.formRef=fa()}createRenderRoot(){return this}connectedCallback(){ae.subscribe(t=>{var e;this.openAIAPIToken=(e=t.settings)==null?void 0:e.openAIAPIToken,this.open=t.settingsDialogOpen}),super.connectedCallback()}updated(t){var e,r;t.has("open")&&(this.open?(e=this.dialogRef.value)==null||e.showModal():(r=this.dialogRef.value)==null||r.close())}onSave(t){t.preventDefault();const n=t.target.elements.namedItem("openAIAPIToken").value,s=ae.get().settings;ae.update({settings:{openAIAPIToken:n,...s}}),this.onDismiss()}onClear(t){t.preventDefault();const e=ae.get().settings;delete e.openAIAPIToken,ae.update({settings:e})}onDismiss(){var t;(t=this.formRef.value)==null||t.reset(),ae.update({settingsDialogOpen:!1})}render(){return U`
|
262
|
+
<dialog ${ma(this.dialogRef)}>
|
263
|
+
<div class="dialog-header">
|
264
|
+
<h2>Settings</h2>
|
265
|
+
<button
|
266
|
+
aria-label="close dialog"
|
267
|
+
class="close-dialog-button"
|
268
|
+
@click="${this.onDismiss}"
|
269
|
+
>
|
270
|
+
<svg
|
271
|
+
focusable="false"
|
272
|
+
xmlns="http://www.w3.org/2000/svg"
|
273
|
+
width="24"
|
274
|
+
height="24"
|
275
|
+
viewBox="0 0 24 24"
|
276
|
+
fill="none"
|
277
|
+
stroke="currentColor"
|
278
|
+
stroke-width="1"
|
279
|
+
stroke-linecap="round"
|
280
|
+
stroke-linejoin="round"
|
281
|
+
>
|
282
|
+
<path d="M18 6 6 18" />
|
283
|
+
<path d="m6 6 12 12" />
|
284
|
+
</svg>
|
285
|
+
</button>
|
286
|
+
</div>
|
287
|
+
<div class="dialog-content">
|
288
|
+
<form
|
289
|
+
${ma(this.formRef)}
|
290
|
+
id="settings-form"
|
291
|
+
class="settings-form"
|
292
|
+
@submit="${this.onSave}"
|
293
|
+
>
|
294
|
+
<fieldset .disabled=${!!this.openAIAPIToken}>
|
295
|
+
<label for="openAIAPIToken">OpenAI API token</label>
|
296
|
+
|
297
|
+
<input
|
298
|
+
id="openAIAPIToken"
|
299
|
+
name="openAIAPIToken"
|
300
|
+
placeholder="${this.openAIAPIToken?"••••••••••••••••••••":""}"
|
301
|
+
/>
|
302
|
+
</fieldset>
|
303
|
+
${this.openAIAPIToken?U`<button
|
304
|
+
class="clear-button"
|
305
|
+
?disabled=${!1}
|
306
|
+
@click="${this.onClear}"
|
307
|
+
>
|
308
|
+
Clear
|
309
|
+
</button>`:F}
|
310
|
+
</form>
|
311
|
+
</div>
|
312
|
+
<div class="dialog-footer">
|
313
|
+
<button type="submit" form="settings-form">Save</button>
|
314
|
+
<button @click="${this.onDismiss}">Cancel</button>
|
315
|
+
</div>
|
316
|
+
</dialog>
|
317
|
+
`}};xs([ee({type:Boolean})],pn.prototype,"open",2);xs([ee({type:String})],pn.prototype,"openAIAPIToken",2);pn=xs([we("settings-dialog")],pn);var Nh=Object.getOwnPropertyDescriptor,Mh=(t,e,r,n)=>{for(var s=n>1?void 0:n?Nh(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let ga=class extends re{createRenderRoot(){return this}render(){return U`
|
318
|
+
<app-header></app-header>
|
319
|
+
<main>
|
320
|
+
<app-sidebar></app-sidebar>
|
321
|
+
<app-viewer></app-viewer>
|
322
|
+
<app-history></app-history>
|
323
|
+
<app-prompt></app-prompt>
|
324
|
+
</main>
|
325
|
+
<settings-dialog></settings-dialog>
|
326
|
+
`}};ga=Mh([we("app-root")],ga);
|