@gram-ai/elements 1.16.4 → 1.16.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/contexts/ElementsProvider.d.ts +1 -1
- package/dist/elements.cjs +120 -33
- package/dist/elements.js +29508 -9126
- package/dist/hooks/useMCPTools.d.ts +11 -0
- package/dist/hooks/useSession.d.ts +13 -0
- package/dist/{index-SAJg5Cz7.js → index-Bjdy_BPv.js} +378 -385
- package/dist/{index-C6vUoNWt.cjs → index-CqzaiyM-.cjs} +2 -2
- package/dist/lib/tools.d.ts +6 -0
- package/dist/lib/utils.d.ts +1 -1
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.js +1 -1
- package/dist/server.cjs +1 -29
- package/dist/server.d.ts +32 -4
- package/dist/server.js +21 -4069
- package/dist/types/index.d.ts +23 -11
- package/package.json +3 -1
- package/dist/index-BqoFmyxX.cjs +0 -60
- package/dist/index-CVZt-xeH.js +0 -14913
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const $=require("react/jsx-runtime"),A=require("react"),De=require("@assistant-ui/react"),oe=require("vega"),Ce=A.createContext(void 0),ie=()=>{const e=A.useContext(Ce);if(!e)throw new Error("useElements must be used within a ElementsProvider");return e},qe={compact:{"p-xs":"p-1","p-sm":"p-1.5","p-md":"p-2","p-lg":"p-2.5","p-xl":"p-3","px-xs":"px-1","px-sm":"px-1.5","px-md":"px-2","px-lg":"px-2.5","px-xl":"px-3","py-xs":"py-1","py-sm":"py-1.5","py-md":"py-2","py-lg":"py-2.5","py-xl":"py-3","gap-sm":"gap-1","gap-md":"gap-1.5","gap-lg":"gap-2","gap-xl":"gap-2.5","h-header":"h-10","h-input":"min-h-10","text-base":"text-sm","text-title":"text-xl","text-subtitle":"text-sm"},normal:{"p-xs":"p-1","p-sm":"p-2","p-md":"p-3","p-lg":"p-4","p-xl":"p-6","px-xs":"px-1","px-sm":"px-2","px-md":"px-3","px-lg":"px-4","px-xl":"px-6","py-xs":"py-1","py-sm":"py-2","py-md":"py-3","py-lg":"py-4","py-xl":"py-6","gap-sm":"gap-1.5","gap-md":"gap-2","gap-lg":"gap-3","gap-xl":"gap-4","h-header":"h-12","h-input":"min-h-12","text-base":"text-base","text-title":"text-2xl","text-subtitle":"text-base"},spacious:{"p-xs":"p-2","p-sm":"p-3","p-md":"p-4","p-lg":"p-6","p-xl":"p-10","px-xs":"px-2","px-sm":"px-3","px-md":"px-4","px-lg":"px-6","px-xl":"px-10","py-xs":"py-2","py-sm":"py-3","py-md":"py-4","py-lg":"py-6","py-xl":"py-10","gap-sm":"gap-2","gap-md":"gap-3","gap-lg":"gap-4","gap-xl":"gap-6","h-header":"h-14","h-input":"min-h-16","text-base":"text-lg","text-title":"text-3xl","text-subtitle":"text-lg"}},ze=()=>{const{config:e}=ie(),r=e.theme?.density??"normal";return t=>qe[r][t]},Je={sharp:{sm:"rounded-sm",md:"rounded",lg:"rounded-md",xl:"rounded-lg",full:"rounded-lg"},soft:{sm:"rounded",md:"rounded-lg",lg:"rounded-xl",xl:"rounded-2xl",full:"rounded-full"},round:{sm:"rounded-lg",md:"rounded-xl",lg:"rounded-2xl",xl:"rounded-3xl",full:"rounded-full"}},Ae=()=>{const{config:e}=ie(),r=e.theme?.radius??"soft";return t=>Je[r][t]};function Se(e){var r,t,o="";if(typeof e=="string"||typeof e=="number")o+=e;else if(typeof e=="object")if(Array.isArray(e)){var a=e.length;for(r=0;r<a;r++)e[r]&&(t=Se(e[r]))&&(o&&(o+=" "),o+=t)}else for(t in e)e[t]&&(o&&(o+=" "),o+=t);return o}function Re(){for(var e,r,t=0,o="",a=arguments.length;t<a;t++)(e=arguments[t])&&(r=Se(e))&&(o&&(o+=" "),o+=r);return o}const Ye=(e,r)=>{const t=new Array(e.length+r.length);for(let o=0;o<e.length;o++)t[o]=e[o];for(let o=0;o<r.length;o++)t[e.length+o]=r[o];return t},Xe=(e,r)=>({classGroupId:e,validator:r}),Ee=(e=new Map,r=null,t)=>({nextPart:e,validators:r,classGroupId:t}),Q="-",he=[],Ze="arbitrary..",He=e=>{const r=Qe(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:o}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return Ke(i);const m=i.split(Q),c=m[0]===""&&m.length>1?1:0;return Ie(m,c,r)},getConflictingClassGroupIds:(i,m)=>{if(m){const c=o[i],g=t[i];return c?g?Ye(g,c):c:g||he}return t[i]||he}}},Ie=(e,r,t)=>{if(e.length-r===0)return t.classGroupId;const a=e[r],l=t.nextPart.get(a);if(l){const g=Ie(e,r+1,l);if(g)return g}const i=t.validators;if(i===null)return;const m=r===0?e.join(Q):e.slice(r).join(Q),c=i.length;for(let g=0;g<c;g++){const f=i[g];if(f.validator(m))return f.classGroupId}},Ke=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const r=e.slice(1,-1),t=r.indexOf(":"),o=r.slice(0,t);return o?Ze+o:void 0})(),Qe=e=>{const{theme:r,classGroups:t}=e;return et(t,r)},et=(e,r)=>{const t=Ee();for(const o in e){const a=e[o];le(a,t,o,r)}return t},le=(e,r,t,o)=>{const a=e.length;for(let l=0;l<a;l++){const i=e[l];tt(i,r,t,o)}},tt=(e,r,t,o)=>{if(typeof e=="string"){rt(e,r,t);return}if(typeof e=="function"){ot(e,r,t,o);return}st(e,r,t,o)},rt=(e,r,t)=>{const o=e===""?r:Ne(r,e);o.classGroupId=t},ot=(e,r,t,o)=>{if(nt(e)){le(e(o),r,t,o);return}r.validators===null&&(r.validators=[]),r.validators.push(Xe(t,e))},st=(e,r,t,o)=>{const a=Object.entries(e),l=a.length;for(let i=0;i<l;i++){const[m,c]=a[i];le(c,Ne(r,m),t,o)}},Ne=(e,r)=>{let t=e;const o=r.split(Q),a=o.length;for(let l=0;l<a;l++){const i=o[l];let m=t.nextPart.get(i);m||(m=Ee(),t.nextPart.set(i,m)),t=m}return t},nt=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,at=e=>{if(e<1)return{get:()=>{},set:()=>{}};let r=0,t=Object.create(null),o=Object.create(null);const a=(l,i)=>{t[l]=i,r++,r>e&&(r=0,o=t,t=Object.create(null))};return{get(l){let i=t[l];if(i!==void 0)return i;if((i=o[l])!==void 0)return a(l,i),i},set(l,i){l in t?t[l]=i:a(l,i)}}},ae="!",xe=":",it=[],ye=(e,r,t,o,a)=>({modifiers:e,hasImportantModifier:r,baseClassName:t,maybePostfixModifierPosition:o,isExternal:a}),lt=e=>{const{prefix:r,experimentalParseClassName:t}=e;let o=a=>{const l=[];let i=0,m=0,c=0,g;const f=a.length;for(let z=0;z<f;z++){const w=a[z];if(i===0&&m===0){if(w===xe){l.push(a.slice(c,z)),c=z+1;continue}if(w==="/"){g=z;continue}}w==="["?i++:w==="]"?i--:w==="("?m++:w===")"&&m--}const v=l.length===0?a:a.slice(c);let x=v,C=!1;v.endsWith(ae)?(x=v.slice(0,-1),C=!0):v.startsWith(ae)&&(x=v.slice(1),C=!0);const S=g&&g>c?g-c:void 0;return ye(l,C,x,S)};if(r){const a=r+xe,l=o;o=i=>i.startsWith(a)?l(i.slice(a.length)):ye(it,!1,i,void 0,!0)}if(t){const a=o;o=l=>t({className:l,parseClassName:a})}return o},ct=e=>{const r=new Map;return e.orderSensitiveModifiers.forEach((t,o)=>{r.set(t,1e6+o)}),t=>{const o=[];let a=[];for(let l=0;l<t.length;l++){const i=t[l],m=i[0]==="[",c=r.has(i);m||c?(a.length>0&&(a.sort(),o.push(...a),a=[]),o.push(i)):a.push(i)}return a.length>0&&(a.sort(),o.push(...a)),o}},dt=e=>({cache:at(e.cacheSize),parseClassName:lt(e),sortModifiers:ct(e),...He(e)}),pt=/\s+/,mt=(e,r)=>{const{parseClassName:t,getClassGroupId:o,getConflictingClassGroupIds:a,sortModifiers:l}=r,i=[],m=e.trim().split(pt);let c="";for(let g=m.length-1;g>=0;g-=1){const f=m[g],{isExternal:v,modifiers:x,hasImportantModifier:C,baseClassName:S,maybePostfixModifierPosition:z}=t(f);if(v){c=f+(c.length>0?" "+c:c);continue}let w=!!z,M=o(w?S.substring(0,z):S);if(!M){if(!w){c=f+(c.length>0?" "+c:c);continue}if(M=o(S),!M){c=f+(c.length>0?" "+c:c);continue}w=!1}const D=x.length===0?"":x.length===1?x[0]:l(x).join(":"),_=C?D+ae:D,j=_+M;if(i.indexOf(j)>-1)continue;i.push(j);const G=a(M,w);for(let O=0;O<G.length;++O){const U=G[O];i.push(_+U)}c=f+(c.length>0?" "+c:c)}return c},ut=(...e)=>{let r=0,t,o,a="";for(;r<e.length;)(t=e[r++])&&(o=Me(t))&&(a&&(a+=" "),a+=o);return a},Me=e=>{if(typeof e=="string")return e;let r,t="";for(let o=0;o<e.length;o++)e[o]&&(r=Me(e[o]))&&(t&&(t+=" "),t+=r);return t},gt=(e,...r)=>{let t,o,a,l;const i=c=>{const g=r.reduce((f,v)=>v(f),e());return t=dt(g),o=t.cache.get,a=t.cache.set,l=m,m(c)},m=c=>{const g=o(c);if(g)return g;const f=mt(c,t);return a(c,f),f};return l=i,(...c)=>l(ut(...c))},ft=[],b=e=>{const r=t=>t[e]||ft;return r.isThemeGetter=!0,r},Oe=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Te=/^\((?:(\w[\w-]*):)?(.+)\)$/i,bt=/^\d+\/\d+$/,ht=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,xt=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,yt=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,wt=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,kt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,V=e=>bt.test(e),u=e=>!!e&&!Number.isNaN(Number(e)),N=e=>!!e&&Number.isInteger(Number(e)),se=e=>e.endsWith("%")&&u(e.slice(0,-1)),I=e=>ht.test(e),vt=()=>!0,Ct=e=>xt.test(e)&&!yt.test(e),Pe=()=>!1,zt=e=>wt.test(e),At=e=>kt.test(e),St=e=>!s(e)&&!n(e),Rt=e=>F(e,Le,Pe),s=e=>Oe.test(e),P=e=>F(e,Ve,Ct),ne=e=>F(e,Ot,u),we=e=>F(e,je,Pe),Et=e=>F(e,Ge,At),H=e=>F(e,Fe,zt),n=e=>Te.test(e),B=e=>W(e,Ve),It=e=>W(e,Tt),ke=e=>W(e,je),Nt=e=>W(e,Le),Mt=e=>W(e,Ge),K=e=>W(e,Fe,!0),F=(e,r,t)=>{const o=Oe.exec(e);return o?o[1]?r(o[1]):t(o[2]):!1},W=(e,r,t=!1)=>{const o=Te.exec(e);return o?o[1]?r(o[1]):t:!1},je=e=>e==="position"||e==="percentage",Ge=e=>e==="image"||e==="url",Le=e=>e==="length"||e==="size"||e==="bg-size",Ve=e=>e==="length",Ot=e=>e==="number",Tt=e=>e==="family-name",Fe=e=>e==="shadow",Pt=()=>{const e=b("color"),r=b("font"),t=b("text"),o=b("font-weight"),a=b("tracking"),l=b("leading"),i=b("breakpoint"),m=b("container"),c=b("spacing"),g=b("radius"),f=b("shadow"),v=b("inset-shadow"),x=b("text-shadow"),C=b("drop-shadow"),S=b("blur"),z=b("perspective"),w=b("aspect"),M=b("ease"),D=b("animate"),_=()=>["auto","avoid","all","avoid-page","page","left","right","column"],j=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],G=()=>[...j(),n,s],O=()=>["auto","hidden","clip","visible","scroll"],U=()=>["auto","contain","none"],p=()=>[n,s,c],R=()=>[V,"full","auto",...p()],ce=()=>[N,"none","subgrid",n,s],de=()=>["auto",{span:["full",N,n,s]},N,n,s],q=()=>[N,"auto",n,s],pe=()=>["auto","min","max","fr",n,s],ee=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],L=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...p()],T=()=>[V,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...p()],d=()=>[e,n,s],me=()=>[...j(),ke,we,{position:[n,s]}],ue=()=>["no-repeat",{repeat:["","x","y","space","round"]}],ge=()=>["auto","cover","contain",Nt,Rt,{size:[n,s]}],te=()=>[se,B,P],y=()=>["","none","full",g,n,s],k=()=>["",u,B,P],J=()=>["solid","dashed","dotted","double"],fe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],h=()=>[u,se,ke,we],be=()=>["","none",S,n,s],Y=()=>["none",u,n,s],X=()=>["none",u,n,s],re=()=>[u,n,s],Z=()=>[V,"full",...p()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[I],breakpoint:[I],color:[vt],container:[I],"drop-shadow":[I],ease:["in","out","in-out"],font:[St],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[I],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[I],shadow:[I],spacing:["px",u],text:[I],"text-shadow":[I],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",V,s,n,w]}],container:["container"],columns:[{columns:[u,s,n,m]}],"break-after":[{"break-after":_()}],"break-before":[{"break-before":_()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:G()}],overflow:[{overflow:O()}],"overflow-x":[{"overflow-x":O()}],"overflow-y":[{"overflow-y":O()}],overscroll:[{overscroll:U()}],"overscroll-x":[{"overscroll-x":U()}],"overscroll-y":[{"overscroll-y":U()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:R()}],"inset-x":[{"inset-x":R()}],"inset-y":[{"inset-y":R()}],start:[{start:R()}],end:[{end:R()}],top:[{top:R()}],right:[{right:R()}],bottom:[{bottom:R()}],left:[{left:R()}],visibility:["visible","invisible","collapse"],z:[{z:[N,"auto",n,s]}],basis:[{basis:[V,"full","auto",m,...p()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[u,V,"auto","initial","none",s]}],grow:[{grow:["",u,n,s]}],shrink:[{shrink:["",u,n,s]}],order:[{order:[N,"first","last","none",n,s]}],"grid-cols":[{"grid-cols":ce()}],"col-start-end":[{col:de()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":ce()}],"row-start-end":[{row:de()}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":pe()}],"auto-rows":[{"auto-rows":pe()}],gap:[{gap:p()}],"gap-x":[{"gap-x":p()}],"gap-y":[{"gap-y":p()}],"justify-content":[{justify:[...ee(),"normal"]}],"justify-items":[{"justify-items":[...L(),"normal"]}],"justify-self":[{"justify-self":["auto",...L()]}],"align-content":[{content:["normal",...ee()]}],"align-items":[{items:[...L(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...L(),{baseline:["","last"]}]}],"place-content":[{"place-content":ee()}],"place-items":[{"place-items":[...L(),"baseline"]}],"place-self":[{"place-self":["auto",...L()]}],p:[{p:p()}],px:[{px:p()}],py:[{py:p()}],ps:[{ps:p()}],pe:[{pe:p()}],pt:[{pt:p()}],pr:[{pr:p()}],pb:[{pb:p()}],pl:[{pl:p()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":p()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":p()}],"space-y-reverse":["space-y-reverse"],size:[{size:T()}],w:[{w:[m,"screen",...T()]}],"min-w":[{"min-w":[m,"screen","none",...T()]}],"max-w":[{"max-w":[m,"screen","none","prose",{screen:[i]},...T()]}],h:[{h:["screen","lh",...T()]}],"min-h":[{"min-h":["screen","lh","none",...T()]}],"max-h":[{"max-h":["screen","lh",...T()]}],"font-size":[{text:["base",t,B,P]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,n,ne]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",se,s]}],"font-family":[{font:[It,s,r]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[a,n,s]}],"line-clamp":[{"line-clamp":[u,"none",n,ne]}],leading:[{leading:[l,...p()]}],"list-image":[{"list-image":["none",n,s]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",n,s]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:d()}],"text-color":[{text:d()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[u,"from-font","auto",n,P]}],"text-decoration-color":[{decoration:d()}],"underline-offset":[{"underline-offset":[u,"auto",n,s]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:p()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",n,s]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",n,s]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:me()}],"bg-repeat":[{bg:ue()}],"bg-size":[{bg:ge()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},N,n,s],radial:["",n,s],conic:[N,n,s]},Mt,Et]}],"bg-color":[{bg:d()}],"gradient-from-pos":[{from:te()}],"gradient-via-pos":[{via:te()}],"gradient-to-pos":[{to:te()}],"gradient-from":[{from:d()}],"gradient-via":[{via:d()}],"gradient-to":[{to:d()}],rounded:[{rounded:y()}],"rounded-s":[{"rounded-s":y()}],"rounded-e":[{"rounded-e":y()}],"rounded-t":[{"rounded-t":y()}],"rounded-r":[{"rounded-r":y()}],"rounded-b":[{"rounded-b":y()}],"rounded-l":[{"rounded-l":y()}],"rounded-ss":[{"rounded-ss":y()}],"rounded-se":[{"rounded-se":y()}],"rounded-ee":[{"rounded-ee":y()}],"rounded-es":[{"rounded-es":y()}],"rounded-tl":[{"rounded-tl":y()}],"rounded-tr":[{"rounded-tr":y()}],"rounded-br":[{"rounded-br":y()}],"rounded-bl":[{"rounded-bl":y()}],"border-w":[{border:k()}],"border-w-x":[{"border-x":k()}],"border-w-y":[{"border-y":k()}],"border-w-s":[{"border-s":k()}],"border-w-e":[{"border-e":k()}],"border-w-t":[{"border-t":k()}],"border-w-r":[{"border-r":k()}],"border-w-b":[{"border-b":k()}],"border-w-l":[{"border-l":k()}],"divide-x":[{"divide-x":k()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":k()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:d()}],"border-color-x":[{"border-x":d()}],"border-color-y":[{"border-y":d()}],"border-color-s":[{"border-s":d()}],"border-color-e":[{"border-e":d()}],"border-color-t":[{"border-t":d()}],"border-color-r":[{"border-r":d()}],"border-color-b":[{"border-b":d()}],"border-color-l":[{"border-l":d()}],"divide-color":[{divide:d()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[u,n,s]}],"outline-w":[{outline:["",u,B,P]}],"outline-color":[{outline:d()}],shadow:[{shadow:["","none",f,K,H]}],"shadow-color":[{shadow:d()}],"inset-shadow":[{"inset-shadow":["none",v,K,H]}],"inset-shadow-color":[{"inset-shadow":d()}],"ring-w":[{ring:k()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:d()}],"ring-offset-w":[{"ring-offset":[u,P]}],"ring-offset-color":[{"ring-offset":d()}],"inset-ring-w":[{"inset-ring":k()}],"inset-ring-color":[{"inset-ring":d()}],"text-shadow":[{"text-shadow":["none",x,K,H]}],"text-shadow-color":[{"text-shadow":d()}],opacity:[{opacity:[u,n,s]}],"mix-blend":[{"mix-blend":[...fe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":fe()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[u]}],"mask-image-linear-from-pos":[{"mask-linear-from":h()}],"mask-image-linear-to-pos":[{"mask-linear-to":h()}],"mask-image-linear-from-color":[{"mask-linear-from":d()}],"mask-image-linear-to-color":[{"mask-linear-to":d()}],"mask-image-t-from-pos":[{"mask-t-from":h()}],"mask-image-t-to-pos":[{"mask-t-to":h()}],"mask-image-t-from-color":[{"mask-t-from":d()}],"mask-image-t-to-color":[{"mask-t-to":d()}],"mask-image-r-from-pos":[{"mask-r-from":h()}],"mask-image-r-to-pos":[{"mask-r-to":h()}],"mask-image-r-from-color":[{"mask-r-from":d()}],"mask-image-r-to-color":[{"mask-r-to":d()}],"mask-image-b-from-pos":[{"mask-b-from":h()}],"mask-image-b-to-pos":[{"mask-b-to":h()}],"mask-image-b-from-color":[{"mask-b-from":d()}],"mask-image-b-to-color":[{"mask-b-to":d()}],"mask-image-l-from-pos":[{"mask-l-from":h()}],"mask-image-l-to-pos":[{"mask-l-to":h()}],"mask-image-l-from-color":[{"mask-l-from":d()}],"mask-image-l-to-color":[{"mask-l-to":d()}],"mask-image-x-from-pos":[{"mask-x-from":h()}],"mask-image-x-to-pos":[{"mask-x-to":h()}],"mask-image-x-from-color":[{"mask-x-from":d()}],"mask-image-x-to-color":[{"mask-x-to":d()}],"mask-image-y-from-pos":[{"mask-y-from":h()}],"mask-image-y-to-pos":[{"mask-y-to":h()}],"mask-image-y-from-color":[{"mask-y-from":d()}],"mask-image-y-to-color":[{"mask-y-to":d()}],"mask-image-radial":[{"mask-radial":[n,s]}],"mask-image-radial-from-pos":[{"mask-radial-from":h()}],"mask-image-radial-to-pos":[{"mask-radial-to":h()}],"mask-image-radial-from-color":[{"mask-radial-from":d()}],"mask-image-radial-to-color":[{"mask-radial-to":d()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":j()}],"mask-image-conic-pos":[{"mask-conic":[u]}],"mask-image-conic-from-pos":[{"mask-conic-from":h()}],"mask-image-conic-to-pos":[{"mask-conic-to":h()}],"mask-image-conic-from-color":[{"mask-conic-from":d()}],"mask-image-conic-to-color":[{"mask-conic-to":d()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:me()}],"mask-repeat":[{mask:ue()}],"mask-size":[{mask:ge()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",n,s]}],filter:[{filter:["","none",n,s]}],blur:[{blur:be()}],brightness:[{brightness:[u,n,s]}],contrast:[{contrast:[u,n,s]}],"drop-shadow":[{"drop-shadow":["","none",C,K,H]}],"drop-shadow-color":[{"drop-shadow":d()}],grayscale:[{grayscale:["",u,n,s]}],"hue-rotate":[{"hue-rotate":[u,n,s]}],invert:[{invert:["",u,n,s]}],saturate:[{saturate:[u,n,s]}],sepia:[{sepia:["",u,n,s]}],"backdrop-filter":[{"backdrop-filter":["","none",n,s]}],"backdrop-blur":[{"backdrop-blur":be()}],"backdrop-brightness":[{"backdrop-brightness":[u,n,s]}],"backdrop-contrast":[{"backdrop-contrast":[u,n,s]}],"backdrop-grayscale":[{"backdrop-grayscale":["",u,n,s]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u,n,s]}],"backdrop-invert":[{"backdrop-invert":["",u,n,s]}],"backdrop-opacity":[{"backdrop-opacity":[u,n,s]}],"backdrop-saturate":[{"backdrop-saturate":[u,n,s]}],"backdrop-sepia":[{"backdrop-sepia":["",u,n,s]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":p()}],"border-spacing-x":[{"border-spacing-x":p()}],"border-spacing-y":[{"border-spacing-y":p()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",n,s]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[u,"initial",n,s]}],ease:[{ease:["linear","initial",M,n,s]}],delay:[{delay:[u,n,s]}],animate:[{animate:["none",D,n,s]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[z,n,s]}],"perspective-origin":[{"perspective-origin":G()}],rotate:[{rotate:Y()}],"rotate-x":[{"rotate-x":Y()}],"rotate-y":[{"rotate-y":Y()}],"rotate-z":[{"rotate-z":Y()}],scale:[{scale:X()}],"scale-x":[{"scale-x":X()}],"scale-y":[{"scale-y":X()}],"scale-z":[{"scale-z":X()}],"scale-3d":["scale-3d"],skew:[{skew:re()}],"skew-x":[{"skew-x":re()}],"skew-y":[{"skew-y":re()}],transform:[{transform:[n,s,"","none","gpu","cpu"]}],"transform-origin":[{origin:G()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Z()}],"translate-x":[{"translate-x":Z()}],"translate-y":[{"translate-y":Z()}],"translate-z":[{"translate-z":Z()}],"translate-none":["translate-none"],accent:[{accent:d()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:d()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",n,s]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":p()}],"scroll-mx":[{"scroll-mx":p()}],"scroll-my":[{"scroll-my":p()}],"scroll-ms":[{"scroll-ms":p()}],"scroll-me":[{"scroll-me":p()}],"scroll-mt":[{"scroll-mt":p()}],"scroll-mr":[{"scroll-mr":p()}],"scroll-mb":[{"scroll-mb":p()}],"scroll-ml":[{"scroll-ml":p()}],"scroll-p":[{"scroll-p":p()}],"scroll-px":[{"scroll-px":p()}],"scroll-py":[{"scroll-py":p()}],"scroll-ps":[{"scroll-ps":p()}],"scroll-pe":[{"scroll-pe":p()}],"scroll-pt":[{"scroll-pt":p()}],"scroll-pr":[{"scroll-pr":p()}],"scroll-pb":[{"scroll-pb":p()}],"scroll-pl":[{"scroll-pl":p()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",n,s]}],fill:[{fill:["none",...d()]}],"stroke-w":[{stroke:[u,B,P,ne]}],stroke:[{stroke:["none",...d()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},jt=gt(Pt);function We(...e){return jt(Re(e))}function Gt(e){throw new Error(`Unexpected value: ${e}`)}const Lt=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Vt=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(r,t,o)=>o?o.toUpperCase():t.toLowerCase()),ve=e=>{const r=Vt(e);return r.charAt(0).toUpperCase()+r.slice(1)},_e=(...e)=>e.filter((r,t,o)=>!!r&&r.trim()!==""&&o.indexOf(r)===t).join(" ").trim(),Ft=e=>{for(const r in e)if(r.startsWith("aria-")||r==="role"||r==="title")return!0};var Wt={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const _t=A.forwardRef(({color:e="currentColor",size:r=24,strokeWidth:t=2,absoluteStrokeWidth:o,className:a="",children:l,iconNode:i,...m},c)=>A.createElement("svg",{ref:c,...Wt,width:r,height:r,stroke:e,strokeWidth:o?Number(t)*24/Number(r):t,className:_e("lucide",a),...!l&&!Ft(m)&&{"aria-hidden":"true"},...m},[...i.map(([g,f])=>A.createElement(g,f)),...Array.isArray(l)?l:[l]]));const Ue=(e,r)=>{const t=A.forwardRef(({className:o,...a},l)=>A.createElement(_t,{ref:l,iconNode:r,className:_e(`lucide-${Lt(ve(e))}`,`lucide-${e}`,o),...a}));return t.displayName=ve(e),t};const Ut=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],$e=Ue("circle-alert",Ut),$t=({code:e})=>{const r=De.useAssistantState(({message:f})=>f),t=A.useRef(null),[o,a]=A.useState(!0),[l,i]=A.useState(null),m=r.status?.type==="complete",c=Ae(),g=ze();return A.useEffect(()=>{if(!m||!t.current)return;let f=null;return(async()=>{try{let x;try{x=JSON.parse(e)}catch(S){throw new Error(`Invalid JSON syntax: ${S instanceof Error?S.message:"Unable to parse"}`)}const C=oe.parse(x);f=new oe.View(C,{container:t.current??void 0,renderer:"svg",hover:!0,logLevel:oe.Warn}),await f.runAsync(),a(!1)}catch(x){console.error("Failed to render chart:",x);const C=x instanceof Error?x.message:"Failed to render chart";i(C),a(!1)}})(),()=>{f&&f.finalize()}},[m,e]),$.jsxs("div",{className:We("relative flex min-h-[400px] w-fit max-w-full min-w-[400px] items-center justify-center border p-6 after:hidden",c("lg"),g("p-lg")),children:[(o||!m)&&$.jsx("div",{className:"shimmer text-muted-foreground bg-background/80 absolute inset-0 z-10 flex items-center justify-center",children:"Rendering chart..."}),l&&$.jsxs("div",{className:"bg-background absolute inset-0 z-10 flex items-center justify-center gap-2 text-rose-500",children:[$.jsx($e,{name:"alert-circle",className:"h-4 w-4"}),"Error rendering chart"]}),$.jsx("div",{ref:t,className:o?"hidden":"block"})]})},Be={language:"vega",prompt:`When a user requests a chart or visualization, respond with a valid Vega specification (https://vega.github.io/vega/) in a code block with language 'vega'.
|
|
1
|
+
"use strict";const B=require("react/jsx-runtime"),C=require("react"),De=require("@assistant-ui/react"),oe=require("vega"),Ce=C.createContext(void 0),ie=()=>{const e=C.useContext(Ce);if(!e)throw new Error("useElements must be used within a ElementsProvider");return e},qe={compact:{"p-xs":"p-1","p-sm":"p-1.5","p-md":"p-2","p-lg":"p-2.5","p-xl":"p-3","px-xs":"px-1","px-sm":"px-1.5","px-md":"px-2","px-lg":"px-2.5","px-xl":"px-3","py-xs":"py-1","py-sm":"py-1.5","py-md":"py-2","py-lg":"py-2.5","py-xl":"py-3","gap-sm":"gap-1","gap-md":"gap-1.5","gap-lg":"gap-2","gap-xl":"gap-2.5","h-header":"h-10","h-input":"min-h-10","text-base":"text-sm","text-title":"text-xl","text-subtitle":"text-sm"},normal:{"p-xs":"p-1","p-sm":"p-2","p-md":"p-3","p-lg":"p-4","p-xl":"p-6","px-xs":"px-1","px-sm":"px-2","px-md":"px-3","px-lg":"px-4","px-xl":"px-6","py-xs":"py-1","py-sm":"py-2","py-md":"py-3","py-lg":"py-4","py-xl":"py-6","gap-sm":"gap-1.5","gap-md":"gap-2","gap-lg":"gap-3","gap-xl":"gap-4","h-header":"h-12","h-input":"min-h-12","text-base":"text-base","text-title":"text-2xl","text-subtitle":"text-base"},spacious:{"p-xs":"p-2","p-sm":"p-3","p-md":"p-4","p-lg":"p-6","p-xl":"p-10","px-xs":"px-2","px-sm":"px-3","px-md":"px-4","px-lg":"px-6","px-xl":"px-10","py-xs":"py-2","py-sm":"py-3","py-md":"py-4","py-lg":"py-6","py-xl":"py-10","gap-sm":"gap-2","gap-md":"gap-3","gap-lg":"gap-4","gap-xl":"gap-6","h-header":"h-14","h-input":"min-h-16","text-base":"text-lg","text-title":"text-3xl","text-subtitle":"text-lg"}},ze=()=>{const{config:e}=ie(),r=e.theme?.density??"normal";return o=>qe[r][o]},Je={sharp:{sm:"rounded-sm",md:"rounded",lg:"rounded-md",xl:"rounded-lg",full:"rounded-lg"},soft:{sm:"rounded",md:"rounded-lg",lg:"rounded-xl",xl:"rounded-2xl",full:"rounded-full"},round:{sm:"rounded-lg",md:"rounded-xl",lg:"rounded-2xl",xl:"rounded-3xl",full:"rounded-full"}},Ae=()=>{const{config:e}=ie(),r=e.theme?.radius??"soft";return o=>Je[r][o]};function Se(e){var r,o,t="";if(typeof e=="string"||typeof e=="number")t+=e;else if(typeof e=="object")if(Array.isArray(e)){var a=e.length;for(r=0;r<a;r++)e[r]&&(o=Se(e[r]))&&(t&&(t+=" "),t+=o)}else for(o in e)e[o]&&(t&&(t+=" "),t+=o);return t}function Re(){for(var e,r,o=0,t="",a=arguments.length;o<a;o++)(e=arguments[o])&&(r=Se(e))&&(t&&(t+=" "),t+=r);return t}const Ye=(e,r)=>{const o=new Array(e.length+r.length);for(let t=0;t<e.length;t++)o[t]=e[t];for(let t=0;t<r.length;t++)o[e.length+t]=r[t];return o},Xe=(e,r)=>({classGroupId:e,validator:r}),Ie=(e=new Map,r=null,o)=>({nextPart:e,validators:r,classGroupId:o}),Q="-",he=[],Ze="arbitrary..",He=e=>{const r=Qe(e),{conflictingClassGroups:o,conflictingClassGroupModifiers:t}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return Ke(i);const u=i.split(Q),c=u[0]===""&&u.length>1?1:0;return Ne(u,c,r)},getConflictingClassGroupIds:(i,u)=>{if(u){const c=t[i],g=o[i];return c?g?Ye(g,c):c:g||he}return o[i]||he}}},Ne=(e,r,o)=>{if(e.length-r===0)return o.classGroupId;const a=e[r],l=o.nextPart.get(a);if(l){const g=Ne(e,r+1,l);if(g)return g}const i=o.validators;if(i===null)return;const u=r===0?e.join(Q):e.slice(r).join(Q),c=i.length;for(let g=0;g<c;g++){const f=i[g];if(f.validator(u))return f.classGroupId}},Ke=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const r=e.slice(1,-1),o=r.indexOf(":"),t=r.slice(0,o);return t?Ze+t:void 0})(),Qe=e=>{const{theme:r,classGroups:o}=e;return et(o,r)},et=(e,r)=>{const o=Ie();for(const t in e){const a=e[t];le(a,o,t,r)}return o},le=(e,r,o,t)=>{const a=e.length;for(let l=0;l<a;l++){const i=e[l];tt(i,r,o,t)}},tt=(e,r,o,t)=>{if(typeof e=="string"){rt(e,r,o);return}if(typeof e=="function"){ot(e,r,o,t);return}st(e,r,o,t)},rt=(e,r,o)=>{const t=e===""?r:Ee(r,e);t.classGroupId=o},ot=(e,r,o,t)=>{if(nt(e)){le(e(t),r,o,t);return}r.validators===null&&(r.validators=[]),r.validators.push(Xe(o,e))},st=(e,r,o,t)=>{const a=Object.entries(e),l=a.length;for(let i=0;i<l;i++){const[u,c]=a[i];le(c,Ee(r,u),o,t)}},Ee=(e,r)=>{let o=e;const t=r.split(Q),a=t.length;for(let l=0;l<a;l++){const i=t[l];let u=o.nextPart.get(i);u||(u=Ie(),o.nextPart.set(i,u)),o=u}return o},nt=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,at=e=>{if(e<1)return{get:()=>{},set:()=>{}};let r=0,o=Object.create(null),t=Object.create(null);const a=(l,i)=>{o[l]=i,r++,r>e&&(r=0,t=o,o=Object.create(null))};return{get(l){let i=o[l];if(i!==void 0)return i;if((i=t[l])!==void 0)return a(l,i),i},set(l,i){l in o?o[l]=i:a(l,i)}}},ae="!",xe=":",it=[],ye=(e,r,o,t,a)=>({modifiers:e,hasImportantModifier:r,baseClassName:o,maybePostfixModifierPosition:t,isExternal:a}),lt=e=>{const{prefix:r,experimentalParseClassName:o}=e;let t=a=>{const l=[];let i=0,u=0,c=0,g;const f=a.length;for(let z=0;z<f;z++){const k=a[z];if(i===0&&u===0){if(k===xe){l.push(a.slice(c,z)),c=z+1;continue}if(k==="/"){g=z;continue}}k==="["?i++:k==="]"?i--:k==="("?u++:k===")"&&u--}const x=l.length===0?a:a.slice(c);let y=x,A=!1;x.endsWith(ae)?(y=x.slice(0,-1),A=!0):x.startsWith(ae)&&(y=x.slice(1),A=!0);const E=g&&g>c?g-c:void 0;return ye(l,A,y,E)};if(r){const a=r+xe,l=t;t=i=>i.startsWith(a)?l(i.slice(a.length)):ye(it,!1,i,void 0,!0)}if(o){const a=t;t=l=>o({className:l,parseClassName:a})}return t},ct=e=>{const r=new Map;return e.orderSensitiveModifiers.forEach((o,t)=>{r.set(o,1e6+t)}),o=>{const t=[];let a=[];for(let l=0;l<o.length;l++){const i=o[l],u=i[0]==="[",c=r.has(i);u||c?(a.length>0&&(a.sort(),t.push(...a),a=[]),t.push(i)):a.push(i)}return a.length>0&&(a.sort(),t.push(...a)),t}},dt=e=>({cache:at(e.cacheSize),parseClassName:lt(e),sortModifiers:ct(e),...He(e)}),pt=/\s+/,mt=(e,r)=>{const{parseClassName:o,getClassGroupId:t,getConflictingClassGroupIds:a,sortModifiers:l}=r,i=[],u=e.trim().split(pt);let c="";for(let g=u.length-1;g>=0;g-=1){const f=u[g],{isExternal:x,modifiers:y,hasImportantModifier:A,baseClassName:E,maybePostfixModifierPosition:z}=o(f);if(x){c=f+(c.length>0?" "+c:c);continue}let k=!!z,M=t(k?E.substring(0,z):E);if(!M){if(!k){c=f+(c.length>0?" "+c:c);continue}if(M=t(E),!M){c=f+(c.length>0?" "+c:c);continue}k=!1}const D=y.length===0?"":y.length===1?y[0]:l(y).join(":"),_=A?D+ae:D,j=_+M;if(i.indexOf(j)>-1)continue;i.push(j);const G=a(M,k);for(let O=0;O<G.length;++O){const U=G[O];i.push(_+U)}c=f+(c.length>0?" "+c:c)}return c},ut=(...e)=>{let r=0,o,t,a="";for(;r<e.length;)(o=e[r++])&&(t=Me(o))&&(a&&(a+=" "),a+=t);return a},Me=e=>{if(typeof e=="string")return e;let r,o="";for(let t=0;t<e.length;t++)e[t]&&(r=Me(e[t]))&&(o&&(o+=" "),o+=r);return o},gt=(e,...r)=>{let o,t,a,l;const i=c=>{const g=r.reduce((f,x)=>x(f),e());return o=dt(g),t=o.cache.get,a=o.cache.set,l=u,u(c)},u=c=>{const g=t(c);if(g)return g;const f=mt(c,o);return a(c,f),f};return l=i,(...c)=>l(ut(...c))},ft=[],b=e=>{const r=o=>o[e]||ft;return r.isThemeGetter=!0,r},Oe=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Te=/^\((?:(\w[\w-]*):)?(.+)\)$/i,bt=/^\d+\/\d+$/,ht=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,xt=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,yt=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,wt=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,kt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,V=e=>bt.test(e),m=e=>!!e&&!Number.isNaN(Number(e)),N=e=>!!e&&Number.isInteger(Number(e)),se=e=>e.endsWith("%")&&m(e.slice(0,-1)),I=e=>ht.test(e),vt=()=>!0,Ct=e=>xt.test(e)&&!yt.test(e),Pe=()=>!1,zt=e=>wt.test(e),At=e=>kt.test(e),St=e=>!s(e)&&!n(e),Rt=e=>F(e,Le,Pe),s=e=>Oe.test(e),P=e=>F(e,Ve,Ct),ne=e=>F(e,Ot,m),we=e=>F(e,je,Pe),It=e=>F(e,Ge,At),H=e=>F(e,Fe,zt),n=e=>Te.test(e),$=e=>W(e,Ve),Nt=e=>W(e,Tt),ke=e=>W(e,je),Et=e=>W(e,Le),Mt=e=>W(e,Ge),K=e=>W(e,Fe,!0),F=(e,r,o)=>{const t=Oe.exec(e);return t?t[1]?r(t[1]):o(t[2]):!1},W=(e,r,o=!1)=>{const t=Te.exec(e);return t?t[1]?r(t[1]):o:!1},je=e=>e==="position"||e==="percentage",Ge=e=>e==="image"||e==="url",Le=e=>e==="length"||e==="size"||e==="bg-size",Ve=e=>e==="length",Ot=e=>e==="number",Tt=e=>e==="family-name",Fe=e=>e==="shadow",Pt=()=>{const e=b("color"),r=b("font"),o=b("text"),t=b("font-weight"),a=b("tracking"),l=b("leading"),i=b("breakpoint"),u=b("container"),c=b("spacing"),g=b("radius"),f=b("shadow"),x=b("inset-shadow"),y=b("text-shadow"),A=b("drop-shadow"),E=b("blur"),z=b("perspective"),k=b("aspect"),M=b("ease"),D=b("animate"),_=()=>["auto","avoid","all","avoid-page","page","left","right","column"],j=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],G=()=>[...j(),n,s],O=()=>["auto","hidden","clip","visible","scroll"],U=()=>["auto","contain","none"],p=()=>[n,s,c],S=()=>[V,"full","auto",...p()],ce=()=>[N,"none","subgrid",n,s],de=()=>["auto",{span:["full",N,n,s]},N,n,s],q=()=>[N,"auto",n,s],pe=()=>["auto","min","max","fr",n,s],ee=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],L=()=>["start","end","center","stretch","center-safe","end-safe"],R=()=>["auto",...p()],T=()=>[V,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...p()],d=()=>[e,n,s],me=()=>[...j(),ke,we,{position:[n,s]}],ue=()=>["no-repeat",{repeat:["","x","y","space","round"]}],ge=()=>["auto","cover","contain",Et,Rt,{size:[n,s]}],te=()=>[se,$,P],w=()=>["","none","full",g,n,s],v=()=>["",m,$,P],J=()=>["solid","dashed","dotted","double"],fe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],h=()=>[m,se,ke,we],be=()=>["","none",E,n,s],Y=()=>["none",m,n,s],X=()=>["none",m,n,s],re=()=>[m,n,s],Z=()=>[V,"full",...p()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[I],breakpoint:[I],color:[vt],container:[I],"drop-shadow":[I],ease:["in","out","in-out"],font:[St],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[I],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[I],shadow:[I],spacing:["px",m],text:[I],"text-shadow":[I],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",V,s,n,k]}],container:["container"],columns:[{columns:[m,s,n,u]}],"break-after":[{"break-after":_()}],"break-before":[{"break-before":_()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:G()}],overflow:[{overflow:O()}],"overflow-x":[{"overflow-x":O()}],"overflow-y":[{"overflow-y":O()}],overscroll:[{overscroll:U()}],"overscroll-x":[{"overscroll-x":U()}],"overscroll-y":[{"overscroll-y":U()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:S()}],"inset-x":[{"inset-x":S()}],"inset-y":[{"inset-y":S()}],start:[{start:S()}],end:[{end:S()}],top:[{top:S()}],right:[{right:S()}],bottom:[{bottom:S()}],left:[{left:S()}],visibility:["visible","invisible","collapse"],z:[{z:[N,"auto",n,s]}],basis:[{basis:[V,"full","auto",u,...p()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[m,V,"auto","initial","none",s]}],grow:[{grow:["",m,n,s]}],shrink:[{shrink:["",m,n,s]}],order:[{order:[N,"first","last","none",n,s]}],"grid-cols":[{"grid-cols":ce()}],"col-start-end":[{col:de()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":ce()}],"row-start-end":[{row:de()}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":pe()}],"auto-rows":[{"auto-rows":pe()}],gap:[{gap:p()}],"gap-x":[{"gap-x":p()}],"gap-y":[{"gap-y":p()}],"justify-content":[{justify:[...ee(),"normal"]}],"justify-items":[{"justify-items":[...L(),"normal"]}],"justify-self":[{"justify-self":["auto",...L()]}],"align-content":[{content:["normal",...ee()]}],"align-items":[{items:[...L(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...L(),{baseline:["","last"]}]}],"place-content":[{"place-content":ee()}],"place-items":[{"place-items":[...L(),"baseline"]}],"place-self":[{"place-self":["auto",...L()]}],p:[{p:p()}],px:[{px:p()}],py:[{py:p()}],ps:[{ps:p()}],pe:[{pe:p()}],pt:[{pt:p()}],pr:[{pr:p()}],pb:[{pb:p()}],pl:[{pl:p()}],m:[{m:R()}],mx:[{mx:R()}],my:[{my:R()}],ms:[{ms:R()}],me:[{me:R()}],mt:[{mt:R()}],mr:[{mr:R()}],mb:[{mb:R()}],ml:[{ml:R()}],"space-x":[{"space-x":p()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":p()}],"space-y-reverse":["space-y-reverse"],size:[{size:T()}],w:[{w:[u,"screen",...T()]}],"min-w":[{"min-w":[u,"screen","none",...T()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[i]},...T()]}],h:[{h:["screen","lh",...T()]}],"min-h":[{"min-h":["screen","lh","none",...T()]}],"max-h":[{"max-h":["screen","lh",...T()]}],"font-size":[{text:["base",o,$,P]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[t,n,ne]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",se,s]}],"font-family":[{font:[Nt,s,r]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[a,n,s]}],"line-clamp":[{"line-clamp":[m,"none",n,ne]}],leading:[{leading:[l,...p()]}],"list-image":[{"list-image":["none",n,s]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",n,s]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:d()}],"text-color":[{text:d()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[m,"from-font","auto",n,P]}],"text-decoration-color":[{decoration:d()}],"underline-offset":[{"underline-offset":[m,"auto",n,s]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:p()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",n,s]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",n,s]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:me()}],"bg-repeat":[{bg:ue()}],"bg-size":[{bg:ge()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},N,n,s],radial:["",n,s],conic:[N,n,s]},Mt,It]}],"bg-color":[{bg:d()}],"gradient-from-pos":[{from:te()}],"gradient-via-pos":[{via:te()}],"gradient-to-pos":[{to:te()}],"gradient-from":[{from:d()}],"gradient-via":[{via:d()}],"gradient-to":[{to:d()}],rounded:[{rounded:w()}],"rounded-s":[{"rounded-s":w()}],"rounded-e":[{"rounded-e":w()}],"rounded-t":[{"rounded-t":w()}],"rounded-r":[{"rounded-r":w()}],"rounded-b":[{"rounded-b":w()}],"rounded-l":[{"rounded-l":w()}],"rounded-ss":[{"rounded-ss":w()}],"rounded-se":[{"rounded-se":w()}],"rounded-ee":[{"rounded-ee":w()}],"rounded-es":[{"rounded-es":w()}],"rounded-tl":[{"rounded-tl":w()}],"rounded-tr":[{"rounded-tr":w()}],"rounded-br":[{"rounded-br":w()}],"rounded-bl":[{"rounded-bl":w()}],"border-w":[{border:v()}],"border-w-x":[{"border-x":v()}],"border-w-y":[{"border-y":v()}],"border-w-s":[{"border-s":v()}],"border-w-e":[{"border-e":v()}],"border-w-t":[{"border-t":v()}],"border-w-r":[{"border-r":v()}],"border-w-b":[{"border-b":v()}],"border-w-l":[{"border-l":v()}],"divide-x":[{"divide-x":v()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":v()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:d()}],"border-color-x":[{"border-x":d()}],"border-color-y":[{"border-y":d()}],"border-color-s":[{"border-s":d()}],"border-color-e":[{"border-e":d()}],"border-color-t":[{"border-t":d()}],"border-color-r":[{"border-r":d()}],"border-color-b":[{"border-b":d()}],"border-color-l":[{"border-l":d()}],"divide-color":[{divide:d()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[m,n,s]}],"outline-w":[{outline:["",m,$,P]}],"outline-color":[{outline:d()}],shadow:[{shadow:["","none",f,K,H]}],"shadow-color":[{shadow:d()}],"inset-shadow":[{"inset-shadow":["none",x,K,H]}],"inset-shadow-color":[{"inset-shadow":d()}],"ring-w":[{ring:v()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:d()}],"ring-offset-w":[{"ring-offset":[m,P]}],"ring-offset-color":[{"ring-offset":d()}],"inset-ring-w":[{"inset-ring":v()}],"inset-ring-color":[{"inset-ring":d()}],"text-shadow":[{"text-shadow":["none",y,K,H]}],"text-shadow-color":[{"text-shadow":d()}],opacity:[{opacity:[m,n,s]}],"mix-blend":[{"mix-blend":[...fe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":fe()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[m]}],"mask-image-linear-from-pos":[{"mask-linear-from":h()}],"mask-image-linear-to-pos":[{"mask-linear-to":h()}],"mask-image-linear-from-color":[{"mask-linear-from":d()}],"mask-image-linear-to-color":[{"mask-linear-to":d()}],"mask-image-t-from-pos":[{"mask-t-from":h()}],"mask-image-t-to-pos":[{"mask-t-to":h()}],"mask-image-t-from-color":[{"mask-t-from":d()}],"mask-image-t-to-color":[{"mask-t-to":d()}],"mask-image-r-from-pos":[{"mask-r-from":h()}],"mask-image-r-to-pos":[{"mask-r-to":h()}],"mask-image-r-from-color":[{"mask-r-from":d()}],"mask-image-r-to-color":[{"mask-r-to":d()}],"mask-image-b-from-pos":[{"mask-b-from":h()}],"mask-image-b-to-pos":[{"mask-b-to":h()}],"mask-image-b-from-color":[{"mask-b-from":d()}],"mask-image-b-to-color":[{"mask-b-to":d()}],"mask-image-l-from-pos":[{"mask-l-from":h()}],"mask-image-l-to-pos":[{"mask-l-to":h()}],"mask-image-l-from-color":[{"mask-l-from":d()}],"mask-image-l-to-color":[{"mask-l-to":d()}],"mask-image-x-from-pos":[{"mask-x-from":h()}],"mask-image-x-to-pos":[{"mask-x-to":h()}],"mask-image-x-from-color":[{"mask-x-from":d()}],"mask-image-x-to-color":[{"mask-x-to":d()}],"mask-image-y-from-pos":[{"mask-y-from":h()}],"mask-image-y-to-pos":[{"mask-y-to":h()}],"mask-image-y-from-color":[{"mask-y-from":d()}],"mask-image-y-to-color":[{"mask-y-to":d()}],"mask-image-radial":[{"mask-radial":[n,s]}],"mask-image-radial-from-pos":[{"mask-radial-from":h()}],"mask-image-radial-to-pos":[{"mask-radial-to":h()}],"mask-image-radial-from-color":[{"mask-radial-from":d()}],"mask-image-radial-to-color":[{"mask-radial-to":d()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":j()}],"mask-image-conic-pos":[{"mask-conic":[m]}],"mask-image-conic-from-pos":[{"mask-conic-from":h()}],"mask-image-conic-to-pos":[{"mask-conic-to":h()}],"mask-image-conic-from-color":[{"mask-conic-from":d()}],"mask-image-conic-to-color":[{"mask-conic-to":d()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:me()}],"mask-repeat":[{mask:ue()}],"mask-size":[{mask:ge()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",n,s]}],filter:[{filter:["","none",n,s]}],blur:[{blur:be()}],brightness:[{brightness:[m,n,s]}],contrast:[{contrast:[m,n,s]}],"drop-shadow":[{"drop-shadow":["","none",A,K,H]}],"drop-shadow-color":[{"drop-shadow":d()}],grayscale:[{grayscale:["",m,n,s]}],"hue-rotate":[{"hue-rotate":[m,n,s]}],invert:[{invert:["",m,n,s]}],saturate:[{saturate:[m,n,s]}],sepia:[{sepia:["",m,n,s]}],"backdrop-filter":[{"backdrop-filter":["","none",n,s]}],"backdrop-blur":[{"backdrop-blur":be()}],"backdrop-brightness":[{"backdrop-brightness":[m,n,s]}],"backdrop-contrast":[{"backdrop-contrast":[m,n,s]}],"backdrop-grayscale":[{"backdrop-grayscale":["",m,n,s]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m,n,s]}],"backdrop-invert":[{"backdrop-invert":["",m,n,s]}],"backdrop-opacity":[{"backdrop-opacity":[m,n,s]}],"backdrop-saturate":[{"backdrop-saturate":[m,n,s]}],"backdrop-sepia":[{"backdrop-sepia":["",m,n,s]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":p()}],"border-spacing-x":[{"border-spacing-x":p()}],"border-spacing-y":[{"border-spacing-y":p()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",n,s]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[m,"initial",n,s]}],ease:[{ease:["linear","initial",M,n,s]}],delay:[{delay:[m,n,s]}],animate:[{animate:["none",D,n,s]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[z,n,s]}],"perspective-origin":[{"perspective-origin":G()}],rotate:[{rotate:Y()}],"rotate-x":[{"rotate-x":Y()}],"rotate-y":[{"rotate-y":Y()}],"rotate-z":[{"rotate-z":Y()}],scale:[{scale:X()}],"scale-x":[{"scale-x":X()}],"scale-y":[{"scale-y":X()}],"scale-z":[{"scale-z":X()}],"scale-3d":["scale-3d"],skew:[{skew:re()}],"skew-x":[{"skew-x":re()}],"skew-y":[{"skew-y":re()}],transform:[{transform:[n,s,"","none","gpu","cpu"]}],"transform-origin":[{origin:G()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Z()}],"translate-x":[{"translate-x":Z()}],"translate-y":[{"translate-y":Z()}],"translate-z":[{"translate-z":Z()}],"translate-none":["translate-none"],accent:[{accent:d()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:d()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",n,s]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":p()}],"scroll-mx":[{"scroll-mx":p()}],"scroll-my":[{"scroll-my":p()}],"scroll-ms":[{"scroll-ms":p()}],"scroll-me":[{"scroll-me":p()}],"scroll-mt":[{"scroll-mt":p()}],"scroll-mr":[{"scroll-mr":p()}],"scroll-mb":[{"scroll-mb":p()}],"scroll-ml":[{"scroll-ml":p()}],"scroll-p":[{"scroll-p":p()}],"scroll-px":[{"scroll-px":p()}],"scroll-py":[{"scroll-py":p()}],"scroll-ps":[{"scroll-ps":p()}],"scroll-pe":[{"scroll-pe":p()}],"scroll-pt":[{"scroll-pt":p()}],"scroll-pr":[{"scroll-pr":p()}],"scroll-pb":[{"scroll-pb":p()}],"scroll-pl":[{"scroll-pl":p()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",n,s]}],fill:[{fill:["none",...d()]}],"stroke-w":[{stroke:[m,$,P,ne]}],stroke:[{stroke:["none",...d()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},jt=gt(Pt);function We(...e){return jt(Re(e))}function Gt(e){throw new Error(`Unexpected value: ${e}`)}function Lt(e,r){if(!e)throw new Error(r)}const Vt=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ft=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(r,o,t)=>t?t.toUpperCase():o.toLowerCase()),ve=e=>{const r=Ft(e);return r.charAt(0).toUpperCase()+r.slice(1)},_e=(...e)=>e.filter((r,o,t)=>!!r&&r.trim()!==""&&t.indexOf(r)===o).join(" ").trim(),Wt=e=>{for(const r in e)if(r.startsWith("aria-")||r==="role"||r==="title")return!0};var _t={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Ut=C.forwardRef(({color:e="currentColor",size:r=24,strokeWidth:o=2,absoluteStrokeWidth:t,className:a="",children:l,iconNode:i,...u},c)=>C.createElement("svg",{ref:c,..._t,width:r,height:r,stroke:e,strokeWidth:t?Number(o)*24/Number(r):o,className:_e("lucide",a),...!l&&!Wt(u)&&{"aria-hidden":"true"},...u},[...i.map(([g,f])=>C.createElement(g,f)),...Array.isArray(l)?l:[l]]));const Ue=(e,r)=>{const o=C.forwardRef(({className:t,...a},l)=>C.createElement(Ut,{ref:l,iconNode:r,className:_e(`lucide-${Vt(ve(e))}`,`lucide-${e}`,t),...a}));return o.displayName=ve(e),o};const Bt=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Be=Ue("circle-alert",Bt),$t=({code:e})=>{const r=De.useAssistantState(({message:x})=>x),o=C.useRef(null),t=C.useRef(null),[a,l]=C.useState(null),i=r.status?.type==="complete",u=Ae(),c=ze(),g=C.useMemo(()=>{const x=e.trim();if(!x)return null;try{return JSON.parse(x)}catch{return null}},[e]),f=i&&g!==null;return C.useEffect(()=>!o.current||!f?void 0:(l(null),(async()=>{try{t.current&&(t.current.finalize(),t.current=null);const y=oe.parse(g),A=new oe.View(y,{container:o.current??void 0,renderer:"svg",hover:!0,logLevel:oe.Warn});t.current=A,await A.runAsync()}catch(y){console.error("Failed to render chart:",y),l(y instanceof Error?y.message:"Failed to render chart")}})(),()=>{t.current&&(t.current.finalize(),t.current=null)}),[f,g]),B.jsxs("div",{className:We("relative flex min-h-[400px] w-fit max-w-full min-w-[400px] items-center justify-center border p-6 after:hidden",u("lg"),c("p-lg")),children:[!f&&!a&&B.jsx("div",{className:"shimmer text-muted-foreground bg-background/80 absolute inset-0 z-10 flex items-center justify-center",children:"Rendering chart..."}),a&&B.jsxs("div",{className:"bg-background absolute inset-0 z-10 flex items-center justify-center gap-2 text-rose-500",children:[B.jsx(Be,{name:"alert-circle",className:"h-4 w-4"}),a]}),B.jsx("div",{ref:o,className:f?"block":"hidden"})]})},$e={language:"vega",prompt:`When a user requests a chart or visualization, respond with a valid Vega specification (https://vega.github.io/vega/) in a code block with language 'vega'.
|
|
2
2
|
|
|
3
3
|
CRITICAL JSON REQUIREMENTS:
|
|
4
4
|
- The code block MUST contain ONLY valid, parseable JSON
|
|
@@ -13,4 +13,4 @@ CONTENT GUIDELINES:
|
|
|
13
13
|
- Do not describe visual properties or technical implementation details
|
|
14
14
|
- Do not mention "Vega" or other technical terms - this is user-facing
|
|
15
15
|
|
|
16
|
-
The Vega spec will be parsed with JSON.parse() - if it fails, the chart will error. Ensure strict JSON validity.`,Component:$t,Header:void 0},
|
|
16
|
+
The Vega spec will be parsed with JSON.parse() - if it fails, the chart will error. Ensure strict JSON validity.`,Component:$t,Header:void 0},Dt=[$e];exports.CircleAlert=Be;exports.ElementsContext=Ce;exports.assert=Lt;exports.assertNever=Gt;exports.chart=$e;exports.clsx=Re;exports.cn=We;exports.createLucideIcon=Ue;exports.recommended=Dt;exports.useDensity=ze;exports.useElements=ie;exports.useRadius=Ae;
|
package/dist/lib/tools.d.ts
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import { JSONSchema7 } from 'ai';
|
|
2
2
|
import { AssistantToolProps, Tool } from '@assistant-ui/react';
|
|
3
3
|
import { FC } from 'react';
|
|
4
|
+
/**
|
|
5
|
+
* Converts from assistant-ui tool format to the AI SDK tool shape
|
|
6
|
+
*/
|
|
4
7
|
export declare const toAISDKTools: (tools: Record<string, Tool>) => {
|
|
5
8
|
[k: string]: {
|
|
6
9
|
parameters: JSONSchema7;
|
|
7
10
|
description?: string | undefined;
|
|
8
11
|
};
|
|
9
12
|
};
|
|
13
|
+
/**
|
|
14
|
+
* Returns only frontend tools that are enabled
|
|
15
|
+
*/
|
|
10
16
|
export declare const getEnabledTools: (tools: Record<string, Tool>) => {
|
|
11
17
|
[k: string]: Tool;
|
|
12
18
|
};
|
package/dist/lib/utils.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { ClassValue } from 'clsx';
|
|
2
2
|
export declare function cn(...inputs: ClassValue[]): string;
|
|
3
3
|
export declare function assertNever(value: unknown): never;
|
|
4
|
-
export declare function assert(condition:
|
|
4
|
+
export declare function assert(condition: unknown, message: string): asserts condition;
|
package/dist/plugins.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-CqzaiyM-.cjs");exports.chart=e.chart;exports.recommended=e.recommended;
|
package/dist/plugins.js
CHANGED
package/dist/server.cjs
CHANGED
|
@@ -1,29 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./index-BqoFmyxX.cjs"),cr=e=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,{...n.description?{description:n.description}:void 0,inputSchema:t.jsonSchema(n.parameters)}]));var ur=({prefix:e,size:r=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const s=()=>{const a=n.length,i=new Array(r);for(let c=0;c<r;c++)i[c]=n[Math.random()*a|0];return i.join("")};if(e==null)return s;if(n.includes(o))throw new t.InvalidArgumentError({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${s()}`};ur();function rt(e=globalThis){var r,n,o;return e.window?"runtime/browser":(r=e.navigator)!=null&&r.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(o=(n=e.process)==null?void 0:n.versions)!=null&&o.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function dr(e){if(e==null)return{};const r={};if(e instanceof Headers)e.forEach((n,o)=>{r[o.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,o]of e)o!=null&&(r[n.toLowerCase()]=o)}return r}function nt(e,...r){const n=new Headers(dr(e)),o=n.get("user-agent")||"";return n.set("user-agent",[o,...r].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var pr=Symbol.for("vercel.ai.validator");function hr(e){return{...e,type:"dynamic"}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var mr=Symbol.for("vercel.ai.schema");function gr(e,{validate:r}={}){return{[mr]:!0,_type:void 0,[pr]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:r}}let Ae;Ae=globalThis.crypto;async function fr(e){return(await Ae).getRandomValues(new Uint8Array(e))}async function _r(e){const r="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const o=await fr(e);for(let s=0;s<e;s++){const a=o[s]%r.length;n+=r[a]}return n}async function vr(e){return await _r(e)}async function yr(e){const r=await(await Ae).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function br(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const r=await vr(e),n=await yr(r);return{code_verifier:r,code_challenge:n}}var wr="AI_MCPClientError",ot=`vercel.ai.error.${wr}`,kr=Symbol.for(ot),Be,Je,R=class extends(Je=t.AISDKError,Be=kr,Je){constructor({name:e="MCPClientError",message:r,cause:n,data:o,code:s}){super({name:e,message:r,cause:n}),this[Be]=!0,this.data=o,this.code=s}static isInstance(e){return t.AISDKError.hasMarker(e,ot)}},ee="2025-06-18",Sr=[ee,"2025-03-26","2024-11-05"],Tr=t.looseObject({name:t.string(),version:t.string()}),be=t.looseObject({_meta:t.optional(t.object({}).loose())}),J=be,st=t.object({method:t.string(),params:t.optional(be)}),at=t.object({applyDefaults:t.optional(t.boolean())}).loose(),Rr=t.looseObject({experimental:t.optional(t.object({}).loose()),logging:t.optional(t.object({}).loose()),prompts:t.optional(t.looseObject({listChanged:t.optional(t.boolean())})),resources:t.optional(t.looseObject({subscribe:t.optional(t.boolean()),listChanged:t.optional(t.boolean())})),tools:t.optional(t.looseObject({listChanged:t.optional(t.boolean())})),elicitation:t.optional(at)});t.object({elicitation:t.optional(at)}).loose();var Er=J.extend({protocolVersion:t.string(),capabilities:Rr,serverInfo:Tr,instructions:t.optional(t.string())}),Ue=J.extend({nextCursor:t.optional(t.string())}),Cr=t.object({name:t.string(),description:t.optional(t.string()),inputSchema:t.object({type:t.literal("object"),properties:t.optional(t.object({}).loose())}).loose()}).loose(),Ir=Ue.extend({tools:t.array(Cr)}),it=t.object({type:t.literal("text"),text:t.string()}).loose(),lt=t.object({type:t.literal("image"),data:t.base64(),mimeType:t.string()}).loose(),xr=t.object({uri:t.string(),name:t.string(),title:t.optional(t.string()),description:t.optional(t.string()),mimeType:t.optional(t.string()),size:t.optional(t.number())}).loose(),Or=Ue.extend({resources:t.array(xr)}),ct=t.object({uri:t.string(),name:t.optional(t.string()),title:t.optional(t.string()),mimeType:t.optional(t.string())}).loose(),ut=ct.extend({text:t.string()}),dt=ct.extend({blob:t.base64()}),pt=t.object({type:t.literal("resource"),resource:t.union([ut,dt])}).loose(),jr=J.extend({content:t.array(t.union([it,lt,pt])),isError:t.boolean().default(!1).optional()}).or(J.extend({toolResult:t.unknown()})),Pr=t.object({uriTemplate:t.string(),name:t.string(),title:t.optional(t.string()),description:t.optional(t.string()),mimeType:t.optional(t.string())}).loose(),Ar=J.extend({resourceTemplates:t.array(Pr)}),Ur=J.extend({contents:t.array(t.union([ut,dt]))}),$r=t.object({name:t.string(),description:t.optional(t.string()),required:t.optional(t.boolean())}).loose(),Mr=t.object({name:t.string(),title:t.optional(t.string()),description:t.optional(t.string()),arguments:t.optional(t.array($r))}).loose(),Nr=Ue.extend({prompts:t.array(Mr)}),Dr=t.object({role:t.union([t.literal("user"),t.literal("assistant")]),content:t.union([it,lt,pt])}).loose(),Hr=J.extend({description:t.optional(t.string()),messages:t.array(Dr)}),Lr=be.extend({message:t.string(),requestedSchema:t.unknown()}),ze=st.extend({method:t.literal("elicitation/create"),params:Lr}),qr=J.extend({action:t.union([t.literal("accept"),t.literal("decline"),t.literal("cancel")]),content:t.optional(t.record(t.string(),t.unknown()))}),we="2.0",Vr=t.object({jsonrpc:t.literal(we),id:t.union([t.string(),t.number().int()])}).merge(st).strict(),Br=t.object({jsonrpc:t.literal(we),id:t.union([t.string(),t.number().int()]),result:J}).strict(),Jr=t.object({jsonrpc:t.literal(we),id:t.union([t.string(),t.number().int()]),error:t.object({code:t.number().int(),message:t.string(),data:t.optional(t.unknown())})}).strict(),zr=t.object({jsonrpc:t.literal(we)}).merge(t.object({method:t.string(),params:t.optional(be)})).strict(),re=t.union([Vr,zr,Br,Jr]),ht=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",mt=t.object({access_token:t.string(),id_token:t.string().optional(),token_type:t.string(),expires_in:t.number().optional(),scope:t.string().optional(),refresh_token:t.string().optional()}).strip(),N=t.string().url().superRefine((e,r)=>{if(!URL.canParse(e))return r.addIssue({code:t.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),t.NEVER}).refine(e=>{const r=new URL(e);return r.protocol!=="javascript:"&&r.protocol!=="data:"&&r.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Gr=t.object({resource:t.string().url(),authorization_servers:t.array(N).optional(),jwks_uri:t.string().url().optional(),scopes_supported:t.array(t.string()).optional(),bearer_methods_supported:t.array(t.string()).optional(),resource_signing_alg_values_supported:t.array(t.string()).optional(),resource_name:t.string().optional(),resource_documentation:t.string().optional(),resource_policy_uri:t.string().url().optional(),resource_tos_uri:t.string().url().optional(),tls_client_certificate_bound_access_tokens:t.boolean().optional(),authorization_details_types_supported:t.array(t.string()).optional(),dpop_signing_alg_values_supported:t.array(t.string()).optional(),dpop_bound_access_tokens_required:t.boolean().optional()}).passthrough(),gt=t.object({issuer:t.string(),authorization_endpoint:N,token_endpoint:N,registration_endpoint:N.optional(),scopes_supported:t.array(t.string()).optional(),response_types_supported:t.array(t.string()),grant_types_supported:t.array(t.string()).optional(),code_challenge_methods_supported:t.array(t.string()),token_endpoint_auth_methods_supported:t.array(t.string()).optional(),token_endpoint_auth_signing_alg_values_supported:t.array(t.string()).optional()}).passthrough(),Wr=t.object({issuer:t.string(),authorization_endpoint:N,token_endpoint:N,userinfo_endpoint:N.optional(),jwks_uri:N,registration_endpoint:N.optional(),scopes_supported:t.array(t.string()).optional(),response_types_supported:t.array(t.string()),grant_types_supported:t.array(t.string()).optional(),subject_types_supported:t.array(t.string()),id_token_signing_alg_values_supported:t.array(t.string()),claims_supported:t.array(t.string()).optional(),token_endpoint_auth_methods_supported:t.array(t.string()).optional()}).passthrough(),Fr=Wr.merge(gt.pick({code_challenge_methods_supported:!0})),Kr=t.object({client_id:t.string(),client_secret:t.string().optional(),client_id_issued_at:t.number().optional(),client_secret_expires_at:t.number().optional()}).strip(),Zr=t.object({redirect_uris:t.array(N),token_endpoint_auth_method:t.string().optional(),grant_types:t.array(t.string()).optional(),response_types:t.array(t.string()).optional(),client_name:t.string().optional(),client_uri:N.optional(),logo_uri:N.optional(),scope:t.string().optional(),contacts:t.array(t.string()).optional(),tos_uri:N.optional(),policy_uri:t.string().optional(),jwks_uri:N.optional(),jwks:t.any().optional(),software_id:t.string().optional(),software_version:t.string().optional(),software_statement:t.string().optional()}).strip(),Xr=t.object({error:t.string(),error_description:t.string().optional(),error_uri:t.string().optional()}),Yr=Zr.merge(Kr),Qr="AI_MCPClientOAuthError",ft=`vercel.ai.error.${Qr}`,en=Symbol.for(ft),Ge,We,ie=class extends(We=t.AISDKError,Ge=en,We){constructor({name:e="MCPClientOAuthError",message:r,cause:n}){super({name:e,message:r,cause:n}),this[Ge]=!0}static isInstance(e){return t.AISDKError.hasMarker(e,ft)}},Q=class extends ie{};Q.errorCode="server_error";var de=class extends ie{};de.errorCode="invalid_client";var pe=class extends ie{};pe.errorCode="invalid_grant";var he=class extends ie{};he.errorCode="unauthorized_client";var tn={[Q.errorCode]:Q,[de.errorCode]:de,[pe.errorCode]:pe,[he.errorCode]:he};function rn(e){const r=typeof e=="string"?new URL(e):new URL(e.href);return r.hash="",r}function nn({requestedResource:e,configuredResource:r}){const n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof r=="string"?new URL(r):new URL(r.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;const s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return s.startsWith(a)}var me=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function ge(e){var r;const n=(r=e.headers.get("www-authenticate"))!=null?r:e.headers.get("WWW-Authenticate");if(!n)return;const[o,s]=n.split(" ");if(o.toLowerCase()!=="bearer"||!s)return;const a=/resource_metadata="([^"]*)"/,i=n.match(a);if(i)try{return new URL(i[1])}catch{return}}function on(e,r="",n={}){return r.endsWith("/")&&(r=r.slice(0,-1)),n.prependPathname?`${r}/.well-known/${e}`:`/.well-known/${e}${r}`}async function $e(e,r,n=fetch){try{return await n(e,{headers:r})}catch(o){if(o instanceof TypeError)return r?$e(e,void 0,n):void 0;throw o}}async function Fe(e,r,n=fetch){return await $e(e,{"MCP-Protocol-Version":r},n)}function sn(e,r){return!e||e.status>=400&&e.status<500&&r!=="/"}async function an(e,r,n,o){var s,a;const i=new URL(e),c=(s=o?.protocolVersion)!=null?s:ee;let l;if(o?.metadataUrl)l=new URL(o.metadataUrl);else{const p=on(r,i.pathname);l=new URL(p,(a=o?.metadataServerUrl)!=null?a:i),l.search=i.search}let u=await Fe(l,c,n);if(!o?.metadataUrl&&sn(u,i.pathname)){const p=new URL(`/.well-known/${r}`,i);u=await Fe(p,c,n)}return u}async function ln(e,r,n=fetch){const o=await an(e,"oauth-protected-resource",n,{protocolVersion:r?.protocolVersion,metadataUrl:r?.resourceMetadataUrl});if(!o||o.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Gr.parse(await o.json())}function cn(e){const r=typeof e=="string"?new URL(e):e,n=r.pathname!=="/",o=[];if(!n)return o.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",r.origin),type:"oidc"}),o;let s=r.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,r.origin),type:"oauth"}),o.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${s}`,r.origin),type:"oidc"}),o.push({url:new URL(`${s}/.well-known/openid-configuration`,r.origin),type:"oidc"}),o}async function un(e,{fetchFn:r=fetch,protocolVersion:n=ee}={}){var o;const s={"MCP-Protocol-Version":n},a=cn(e);for(const{url:i,type:c}of a){const l=await $e(i,s,r);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}if(c==="oauth")return gt.parse(await l.json());{const u=Fr.parse(await l.json());if(!((o=u.code_challenge_methods_supported)!=null&&o.includes("S256")))throw new Error(`Incompatible OIDC provider at ${i}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function dn(e,{metadata:r,clientInformation:n,redirectUrl:o,scope:s,state:a,resource:i}){const c="code",l="S256";let u;if(r){if(u=new URL(r.authorization_endpoint),!r.response_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support response type ${c}`);if(!r.code_challenge_methods_supported||!r.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else u=new URL("/authorize",e);const p=await br(),g=p.code_verifier,m=p.code_challenge;return u.searchParams.set("response_type",c),u.searchParams.set("client_id",n.client_id),u.searchParams.set("code_challenge",m),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(o)),a&&u.searchParams.set("state",a),s&&u.searchParams.set("scope",s),s?.includes("offline_access")&&u.searchParams.append("prompt","consent"),i&&u.searchParams.set("resource",i.href),{authorizationUrl:u,codeVerifier:g}}function _t(e,r){const n=e.client_secret!==void 0;return r.length===0?n?"client_secret_post":"none":n&&r.includes("client_secret_basic")?"client_secret_basic":n&&r.includes("client_secret_post")?"client_secret_post":r.includes("none")?"none":n?"client_secret_post":"none"}function vt(e,r,n,o){const{client_id:s,client_secret:a}=r;switch(e){case"client_secret_basic":pn(s,a,n);return;case"client_secret_post":hn(s,a,o);return;case"none":mn(s,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function pn(e,r,n){if(!r)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${r}`);n.set("Authorization",`Basic ${o}`)}function hn(e,r,n){n.set("client_id",e),r&&n.set("client_secret",r)}function mn(e,r){r.set("client_id",e)}async function Me(e){const r=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const o=Xr.parse(JSON.parse(n)),{error:s,error_description:a,error_uri:i}=o,c=tn[s]||Q;return new c({message:a||"",cause:i})}catch(o){const s=`${r?`HTTP ${r}: `:""}Invalid OAuth error response: ${o}. Raw body: ${n}`;return new Q({message:s})}}async function gn(e,{metadata:r,clientInformation:n,authorizationCode:o,codeVerifier:s,redirectUri:a,resource:i,addClientAuthentication:c,fetchFn:l}){var u;const p="authorization_code",g=r?.token_endpoint?new URL(r.token_endpoint):new URL("/token",e);if(r?.grant_types_supported&&!r.grant_types_supported.includes(p))throw new Error(`Incompatible auth server: does not support grant type ${p}`);const m=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),_=new URLSearchParams({grant_type:p,code:o,code_verifier:s,redirect_uri:String(a)});if(c)c(m,_,e,r);else{const d=(u=r?.token_endpoint_auth_methods_supported)!=null?u:[],v=_t(n,d);vt(v,n,m,_)}i&&_.set("resource",i.href);const h=await(l??fetch)(g,{method:"POST",headers:m,body:_});if(!h.ok)throw await Me(h);return mt.parse(await h.json())}async function fn(e,{metadata:r,clientInformation:n,refreshToken:o,resource:s,addClientAuthentication:a,fetchFn:i}){var c;const l="refresh_token";let u;if(r){if(u=new URL(r.token_endpoint),r.grant_types_supported&&!r.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",e);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),g=new URLSearchParams({grant_type:l,refresh_token:o});if(a)a(p,g,e,r);else{const _=(c=r?.token_endpoint_auth_methods_supported)!=null?c:[],h=_t(n,_);vt(h,n,p,g)}s&&g.set("resource",s.href);const m=await(i??fetch)(u,{method:"POST",headers:p,body:g});if(!m.ok)throw await Me(m);return mt.parse({refresh_token:o,...await m.json()})}async function _n(e,{metadata:r,clientMetadata:n,fetchFn:o}){let s;if(r){if(!r.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(r.registration_endpoint)}else s=new URL("/register",e);const a=await(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok)throw await Me(a);return Yr.parse(await a.json())}async function fe(e,r){var n,o;try{return await Te(e,r)}catch(s){if(s instanceof de||s instanceof he)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"all")),await Te(e,r);if(s instanceof pe)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"tokens")),await Te(e,r);throw s}}async function vn(e,r,n){const o=rn(e);if(r.validateResourceURL)return await r.validateResourceURL(o,n?.resource);if(n){if(!nn({requestedResource:o,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${o} (or origin)`);return new URL(n.resource)}}async function Te(e,{serverUrl:r,authorizationCode:n,scope:o,resourceMetadataUrl:s,fetchFn:a}){let i,c;try{i=await ln(r,{resourceMetadataUrl:s},a),i.authorization_servers&&i.authorization_servers.length>0&&(c=i.authorization_servers[0])}catch{}c||(c=r);const l=await vn(r,e,i),u=await un(c,{fetchFn:a});let p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const d=await _n(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(d),p=d}if(n!==void 0){const d=await e.codeVerifier(),v=await gn(c,{metadata:u,clientInformation:p,authorizationCode:n,codeVerifier:d,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(v),"AUTHORIZED"}const g=await e.tokens();if(g?.refresh_token)try{const d=await fn(c,{metadata:u,clientInformation:p,refreshToken:g.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(d),"AUTHORIZED"}catch(d){if(!(!(d instanceof ie)||d instanceof Q))throw d}const m=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:h}=await dn(c,{metadata:u,clientInformation:p,state:m,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(_),"REDIRECT"}var yn=class{constructor({url:e,headers:r,authProvider:n}){this.connected=!1,this.url=new URL(e),this.headers=r,this.authProvider=n}async commonHeaders(e){const r={...this.headers,...e,"mcp-protocol-version":ee};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return nt(r,`ai-sdk/${ht}`,rt())}async start(){return new Promise((e,r)=>{if(this.connected)return e();this.abortController=new AbortController;const n=async(o=!1)=>{var s,a,i,c,l;try{const u=await this.commonHeaders({Accept:"text/event-stream"}),p=await fetch(this.url.href,{headers:u,signal:(s=this.abortController)==null?void 0:s.signal});if(p.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=ge(p);try{if(await fe(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new me;return(a=this.onerror)==null||a.call(this,d),r(d)}}catch(h){return(i=this.onerror)==null||i.call(this,h),r(h)}return n(!0)}if(!p.ok||!p.body){let h=`MCP SSE Transport Error: ${p.status} ${p.statusText}`;p.status===405&&(h+=". This server does not support SSE transport. Try using `http` transport instead");const d=new R({message:h});return(c=this.onerror)==null||c.call(this,d),r(d)}const m=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).getReader(),_=async()=>{var h,d,v;try{for(;;){const{done:y,value:k}=await m.read();if(y){if(this.connected)throw this.connected=!1,new R({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:b,data:w}=k;if(b==="endpoint"){if(this.endpoint=new URL(w,this.url),this.endpoint.origin!==this.url.origin)throw new R({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(b==="message")try{const O=re.parse(JSON.parse(w));(h=this.onmessage)==null||h.call(this,O)}catch(O){const I=new R({message:"MCP SSE Transport Error: Failed to parse message",cause:O});(d=this.onerror)==null||d.call(this,I)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(v=this.onerror)==null||v.call(this,y),r(y)}};this.sseConnection={close:()=>m.cancel()},_()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(l=this.onerror)==null||l.call(this,u),r(u)}};n()})}async close(){var e,r,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(r=this.abortController)==null||r.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new R({message:"MCP SSE Transport Error: Not connected"});const r=this.endpoint,n=async(o=!1)=>{var s,a,i,c,l;try{const p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(s=this.abortController)==null?void 0:s.signal},g=await fetch(r,p);if(g.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=ge(g);try{if(await fe(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new me;(a=this.onerror)==null||a.call(this,_);return}}catch(m){(i=this.onerror)==null||i.call(this,m);return}return n(!0)}if(!g.ok){const m=await g.text().catch(()=>null),_=new R({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${g.status}): ${m}`});(c=this.onerror)==null||c.call(this,_);return}}catch(u){(l=this.onerror)==null||l.call(this,u);return}};await n()}},bn=class{constructor({url:e,headers:r,authProvider:n}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=r,this.authProvider=n}async commonHeaders(e){const r={...this.headers,...e,"mcp-protocol-version":ee};if(this.sessionId&&(r["mcp-session-id"]=this.sessionId),this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return nt(r,`ai-sdk/${ht}`,rt())}async start(){if(this.abortController)throw new R({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,r,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const o=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:o,signal:this.abortController.signal}).catch(()=>{})}}catch{}(r=this.abortController)==null||r.abort(),(n=this.onclose)==null||n.call(this)}async send(e){const r=async(n=!1)=>{var o,s,a,i,c,l,u;try{const g={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},m=await fetch(this.url,g),_=m.headers.get("mcp-session-id");if(_&&(this.sessionId=_),m.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ge(m);try{if(await fe(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new me}catch(v){throw(s=this.onerror)==null||s.call(this,v),v}return r(!0)}if(m.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!m.ok){const v=await m.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${m.status}): ${v}`;m.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const k=new R({message:y});throw(a=this.onerror)==null||a.call(this,k),k}const h=m.headers.get("content-type")||"";if(h.includes("application/json")){const v=await m.json(),y=Array.isArray(v)?v.map(k=>re.parse(k)):[re.parse(v)];for(const k of y)(i=this.onmessage)==null||i.call(this,k);return}if(h.includes("text/event-stream")){if(!m.body){const b=new R({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(c=this.onerror)==null||c.call(this,b),b}const y=m.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).getReader();(async()=>{var b,w,O;try{for(;;){const{done:I,value:C}=await y.read();if(I)return;const{event:T,data:H}=C;if(T==="message")try{const D=re.parse(JSON.parse(H));(b=this.onmessage)==null||b.call(this,D)}catch(D){const L=new R({message:"MCP HTTP Transport Error: Failed to parse message",cause:D});(w=this.onerror)==null||w.call(this,L)}}}catch(I){if(I instanceof Error&&I.name==="AbortError")return;(O=this.onerror)==null||O.call(this,I)}})();return}const d=new R({message:`MCP HTTP Transport Error: Unexpected content type: ${h}`});throw(l=this.onerror)==null||l.call(this,d),d}catch(p){throw(u=this.onerror)==null||u.call(this,p),p}};await r()}getNextReconnectionDelay(e){const{initialReconnectionDelay:r,reconnectionDelayGrowFactor:n,maxReconnectionDelay:o}=this.reconnectionOptions;return Math.min(r*Math.pow(n,e),o)}scheduleInboundSseReconnection(){var e;const{maxRetries:r}=this.reconnectionOptions;if(r>0&&this.inboundReconnectAttempts>=r){(e=this.onerror)==null||e.call(this,new R({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${r}) exceeded.`}));return}const n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var o;(o=this.abortController)!=null&&o.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,r){var n,o,s,a,i,c;try{const l=await this.commonHeaders({Accept:"text/event-stream"});r&&(l["last-event-id"]=r);const u=await fetch(this.url.href,{method:"GET",headers:l,signal:(n=this.abortController)==null?void 0:n.signal}),p=u.headers.get("mcp-session-id");if(p&&(this.sessionId=p),u.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=ge(u);try{if(await fe(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new me;(o=this.onerror)==null||o.call(this,d);return}}catch(h){(s=this.onerror)==null||s.call(this,h);return}return this.openInboundSse(!0,r)}if(u.status===405)return;if(!u.ok||!u.body){const h=new R({message:`MCP HTTP Transport Error: GET SSE failed: ${u.status} ${u.statusText}`});(a=this.onerror)==null||a.call(this,h);return}const m=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).getReader(),_=async()=>{var h,d,v,y;try{for(;;){const{done:k,value:b}=await m.read();if(k)return;const{event:w,data:O,id:I}=b;if(I&&(this.lastInboundEventId=I),w==="message")try{const C=re.parse(JSON.parse(O));(h=this.onmessage)==null||h.call(this,C)}catch(C){const T=new R({message:"MCP HTTP Transport Error: Failed to parse message",cause:C});(d=this.onerror)==null||d.call(this,T)}}}catch(k){if(k instanceof Error&&k.name==="AbortError")return;(v=this.onerror)==null||v.call(this,k),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>m.cancel()},this.inboundReconnectAttempts=0,_()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(i=this.onerror)==null||i.call(this,l),(c=this.abortController)!=null&&c.signal.aborted||this.scheduleInboundSseReconnection()}}};function wn(e){switch(e.type){case"sse":return new yn(e);case"http":return new bn(e);default:throw new R({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function kn(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var Sn="1.0.0";async function Tn(e){const r=new Rn(e);return await r.init(),r}var Rn=class{constructor({transport:e,name:r="ai-sdk-mcp-client",version:n=Sn,onUncaughtError:o,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=o,this.clientCapabilities=s??{},kn(e)?this.transport=e:this.transport=wn(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=a=>this.onError(a),this.transport.onmessage=a=>{if("method"in a){"id"in a?this.onRequestMessage(a):this.onError(new R({message:"Unsupported message type"}));return}this.onResponse(a)},this.clientInfo={name:r,version:n}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:ee,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Er});if(e===void 0)throw new R({message:"Server sent invalid initialize result"});if(!Sr.includes(e.protocolVersion))throw new R({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new R({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new R({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new R({message:"Server does not support prompts"});break;default:throw new R({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:r,options:n}){return new Promise((o,s)=>{if(this.isClosed)return s(new R({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const a=n?.signal;a?.throwIfAborted();const i=this.requestMessageId++,c={...e,jsonrpc:"2.0",id:i},l=()=>{this.responseHandlers.delete(i)};this.responseHandlers.set(i,u=>{if(a?.aborted)return s(new R({message:"Request was aborted",cause:a.reason}));if(u instanceof Error)return s(u);try{const p=r.parse(u.result);o(p)}catch(p){const g=new R({message:"Failed to parse server response",cause:p});s(g)}}),this.transport.send(c).catch(u=>{l(),s(u)})})}async listTools({params:e,options:r}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:Ir,options:r})}catch(n){throw n}}async callTool({name:e,args:r,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:r}},resultSchema:jr,options:{signal:n?.abortSignal}})}catch(o){throw o}}async listResourcesInternal({params:e,options:r}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:Or,options:r})}catch(n){throw n}}async readResourceInternal({uri:e,options:r}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:Ur,options:r})}catch(n){throw n}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:Ar,options:e})}catch(r){throw r}}async listPromptsInternal({params:e,options:r}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:Nr,options:r})}catch(n){throw n}}async getPromptInternal({name:e,args:r,options:n}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:r}},resultSchema:Hr,options:n})}catch(o){throw o}}async notification(e){const r={...e,jsonrpc:"2.0"};await this.transport.send(r)}async tools({schemas:e="automatic"}={}){var r;const n={};try{const o=await this.listTools();for(const{name:s,description:a,inputSchema:i}of o.tools){if(e!=="automatic"&&!(s in e))continue;const c=this,l=async(p,g)=>{var m;return(m=g?.abortSignal)==null||m.throwIfAborted(),c.callTool({name:s,args:p,options:g})},u=e==="automatic"?hr({description:a,inputSchema:gr({...i,properties:(r=i.properties)!=null?r:{},additionalProperties:!1}),execute:l}):{description:a,inputSchema:e[s].inputSchema,execute:l};n[s]=u}return n}catch(o){throw o}}listResources({params:e,options:r}={}){return this.listResourcesInternal({params:e,options:r})}readResource({uri:e,options:r}){return this.readResourceInternal({uri:e,options:r})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}listPrompts({params:e,options:r}={}){return this.listPromptsInternal({params:e,options:r})}getPrompt({name:e,arguments:r,options:n}){return this.getPromptInternal({name:e,args:r,options:n})}onElicitationRequest(e,r){if(e!==ze)throw new R({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=r}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const r=ze.safeParse({method:e.method,params:e.params});if(!r.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${r.error.message}`,data:r.error.issues}});return}try{const n=await this.elicitationRequestHandler(r.data),o=qr.parse(n);await this.transport.send({jsonrpc:"2.0",id:e.id,result:o})}catch(n){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:n instanceof Error?n.message:"Failed to handle elicitation request"}}),this.onError(n)}}catch(r){this.onError(r)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new R({message:"Connection closed"});for(const r of this.responseHandlers.values())r(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const r=Number(e.id),n=this.responseHandlers.get(r);if(n===void 0)throw new R({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(r),n("result"in e?e:new R({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},En=Object.defineProperty,Cn=Object.defineProperties,In=Object.getOwnPropertyDescriptors,Ke=Object.getOwnPropertySymbols,xn=Object.prototype.hasOwnProperty,On=Object.prototype.propertyIsEnumerable,Ze=(e,r,n)=>r in e?En(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n,E=(e,r)=>{for(var n in r||(r={}))xn.call(r,n)&&Ze(e,n,r[n]);if(Ke)for(var n of Ke(r))On.call(r,n)&&Ze(e,n,r[n]);return e},_e=(e,r)=>Cn(e,In(r)),yt="vercel.ai.error",jn=Symbol.for(yt),bt,Pn=class wt extends Error{constructor({name:r,message:n,cause:o}){super(n),this[bt]=!0,this.name=r,this.cause=o}static isInstance(r){return wt.hasMarker(r,yt)}static hasMarker(r,n){const o=Symbol.for(n);return r!=null&&typeof r=="object"&&o in r&&typeof r[o]=="boolean"&&r[o]===!0}};bt=jn;var U=Pn,kt="AI_APICallError",St=`vercel.ai.error.${kt}`,An=Symbol.for(St),Tt,V=class extends U{constructor({message:e,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:a,cause:i,isRetryable:c=o!=null&&(o===408||o===409||o===429||o>=500),data:l}){super({name:kt,message:e,cause:i}),this[Tt]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=c,this.data=l}static isInstance(e){return U.hasMarker(e,St)}};Tt=An;var Rt="AI_EmptyResponseBodyError",Et=`vercel.ai.error.${Rt}`,Un=Symbol.for(Et),Ct,$n=class extends U{constructor({message:e="Empty response body"}={}){super({name:Rt,message:e}),this[Ct]=!0}static isInstance(e){return U.hasMarker(e,Et)}};Ct=Un;function It(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var xt="AI_InvalidArgumentError",Ot=`vercel.ai.error.${xt}`,Mn=Symbol.for(Ot),jt,Pt=class extends U{constructor({message:e,cause:r,argument:n}){super({name:xt,message:e,cause:r}),this[jt]=!0,this.argument=n}static isInstance(e){return U.hasMarker(e,Ot)}};jt=Mn;var At="AI_InvalidPromptError",Ut=`vercel.ai.error.${At}`,Nn=Symbol.for(Ut),$t,Dn=class extends U{constructor({prompt:e,message:r,cause:n}){super({name:At,message:`Invalid prompt: ${r}`,cause:n}),this[$t]=!0,this.prompt=e}static isInstance(e){return U.hasMarker(e,Ut)}};$t=Nn;var Mt="AI_InvalidResponseDataError",Nt=`vercel.ai.error.${Mt}`,Hn=Symbol.for(Nt),Dt,te=class extends U{constructor({data:e,message:r=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Mt,message:r}),this[Dt]=!0,this.data=e}static isInstance(e){return U.hasMarker(e,Nt)}};Dt=Hn;var Ht="AI_JSONParseError",Lt=`vercel.ai.error.${Ht}`,Ln=Symbol.for(Lt),qt,ve=class extends U{constructor({text:e,cause:r}){super({name:Ht,message:`JSON parsing failed: Text: ${e}.
|
|
2
|
-
Error message: ${It(r)}`,cause:r}),this[qt]=!0,this.text=e}static isInstance(e){return U.hasMarker(e,Lt)}};qt=Ln;var Vt="AI_LoadAPIKeyError",Bt=`vercel.ai.error.${Vt}`,qn=Symbol.for(Bt),Jt,ce=class extends U{constructor({message:e}){super({name:Vt,message:e}),this[Jt]=!0}static isInstance(e){return U.hasMarker(e,Bt)}};Jt=qn;var zt="AI_NoContentGeneratedError",Gt=`vercel.ai.error.${zt}`,Vn=Symbol.for(Gt),Wt,Ft=class extends U{constructor({message:e="No content generated."}={}){super({name:zt,message:e}),this[Wt]=!0}static isInstance(e){return U.hasMarker(e,Gt)}};Wt=Vn;var Kt="AI_TypeValidationError",Zt=`vercel.ai.error.${Kt}`,Bn=Symbol.for(Zt),Xt,Jn=class Ie extends U{constructor({value:r,cause:n}){super({name:Kt,message:`Type validation failed: Value: ${JSON.stringify(r)}.
|
|
3
|
-
Error message: ${It(n)}`,cause:n}),this[Xt]=!0,this.value=r}static isInstance(r){return U.hasMarker(r,Zt)}static wrap({value:r,cause:n}){return Ie.isInstance(n)&&n.value===r?n:new Ie({value:r,cause:n})}};Xt=Bn;var ne=Jn,Yt="AI_UnsupportedFunctionalityError",Qt=`vercel.ai.error.${Yt}`,zn=Symbol.for(Qt),er,W=class extends U{constructor({functionality:e,message:r=`'${e}' functionality not supported.`}){super({name:Yt,message:r}),this[er]=!0,this.functionality=e}static isInstance(e){return U.hasMarker(e,Qt)}};er=zn;var Xe=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function Re(e){}function Gn(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:r=Re,onError:n=Re,onRetry:o=Re,onComment:s}=e;let a="",i=!0,c,l="",u="";function p(d){const v=i?d.replace(/^\xEF\xBB\xBF/,""):d,[y,k]=Wn(`${a}${v}`);for(const b of y)g(b);a=k,i=!1}function g(d){if(d===""){_();return}if(d.startsWith(":")){s&&s(d.slice(d.startsWith(": ")?2:1));return}const v=d.indexOf(":");if(v!==-1){const y=d.slice(0,v),k=d[v+1]===" "?2:1,b=d.slice(v+k);m(y,b,d);return}m(d,"",d)}function m(d,v,y){switch(d){case"event":u=v;break;case"data":l=`${l}${v}
|
|
4
|
-
`;break;case"id":c=v.includes("\0")?void 0:v;break;case"retry":/^\d+$/.test(v)?o(parseInt(v,10)):n(new Xe(`Invalid \`retry\` value: "${v}"`,{type:"invalid-retry",value:v,line:y}));break;default:n(new Xe(`Unknown field "${d.length>20?`${d.slice(0,20)}…`:d}"`,{type:"unknown-field",field:d,value:v,line:y}));break}}function _(){l.length>0&&r({id:c,event:u||void 0,data:l.endsWith(`
|
|
5
|
-
`)?l.slice(0,-1):l}),c=void 0,l="",u=""}function h(d={}){a&&d.consume&&g(a),i=!0,c=void 0,l="",u="",a=""}return{feed:p,reset:h}}function Wn(e){const r=[];let n="",o=0;for(;o<e.length;){const s=e.indexOf("\r",o),a=e.indexOf(`
|
|
6
|
-
`,o);let i=-1;if(s!==-1&&a!==-1?i=Math.min(s,a):s!==-1?i=s:a!==-1&&(i=a),i===-1){n=e.slice(o);break}else{const c=e.slice(o,i);r.push(c),o=i+1,e[o-1]==="\r"&&e[o]===`
|
|
7
|
-
`&&o++}}return[r,n]}var Fn=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(s){o=Gn({onEvent:a=>{s.enqueue(a)},onError(a){e==="terminate"?s.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function oe(...e){return e.reduce((r,n)=>E(E({},r),n??{}),{})}function ke(e){return Object.fromEntries([...e.headers])}var Kn=({prefix:e,size:r=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const s=()=>{const a=n.length,i=new Array(r);for(let c=0;c<r;c++)i[c]=n[Math.random()*a|0];return i.join("")};if(e==null)return s;if(n.includes(o))throw new Pt({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${s()}`},q=Kn();function xe(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Zn=["fetch failed","failed to fetch"];function Xn({error:e,url:r,requestBodyValues:n}){if(xe(e))return e;if(e instanceof TypeError&&Zn.includes(e.message.toLowerCase())){const o=e.cause;if(o!=null)return new V({message:`Cannot connect to API: ${o.message}`,cause:o,url:r,requestBodyValues:n,isRetryable:!0})}return e}function Yn(e){return Object.fromEntries(Object.entries(e).filter(([r,n])=>n!=null))}function Qn({apiKey:e,environmentVariableName:r,apiKeyParameterName:n="apiKey",description:o}){if(typeof e=="string")return e;if(e!=null)throw new ce({message:`${o} API key must be a string.`});if(typeof process>"u")throw new ce({message:`${o} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[r],e==null)throw new ce({message:`${o} API key is missing. Pass it using the '${n}' parameter or the ${r} environment variable.`});if(typeof e!="string")throw new ce({message:`${o} API key must be a string. The value of the ${r} environment variable is not a string.`});return e}var eo=/"__proto__"\s*:/,to=/"constructor"\s*:/;function ro(e){const r=JSON.parse(e);return r===null||typeof r!="object"||eo.test(e)===!1&&to.test(e)===!1?r:no(r)}function no(e){let r=[e];for(;r.length;){const n=r;r=[];for(const o of n){if(Object.prototype.hasOwnProperty.call(o,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(o,"constructor")&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in o){const a=o[s];a&&typeof a=="object"&&r.push(a)}}}return e}function Ne(e){const{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return ro(e)}finally{Error.stackTraceLimit=r}}var Oe=Symbol.for("vercel.ai.validator");function oo(e){return{[Oe]:!0,validate:e}}function so(e){return typeof e=="object"&&e!==null&&Oe in e&&e[Oe]===!0&&"validate"in e}function ao(e){return so(e)?e:io(e)}function io(e){return oo(async r=>{const n=await e["~standard"].validate(r);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new ne({value:r,cause:n.issues})}})}async function lo({value:e,schema:r}){const n=await tr({value:e,schema:r});if(!n.success)throw ne.wrap({value:e,cause:n.error});return n.value}async function tr({value:e,schema:r}){const n=ao(r);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:ne.wrap({value:e,cause:o.error}),rawValue:e}}catch(o){return{success:!1,error:ne.wrap({value:e,cause:o}),rawValue:e}}}async function co({text:e,schema:r}){try{const n=Ne(e);return r==null?n:lo({value:n,schema:r})}catch(n){throw ve.isInstance(n)||ne.isInstance(n)?n:new ve({text:e,cause:n})}}async function rr({text:e,schema:r}){try{const n=Ne(e);return r==null?{success:!0,value:n,rawValue:n}:await tr({value:n,schema:r})}catch(n){return{success:!1,error:ve.isInstance(n)?n:new ve({text:e,cause:n}),rawValue:void 0}}}function Ee(e){try{return Ne(e),!0}catch{return!1}}function uo({stream:e,schema:r}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Fn).pipeThrough(new TransformStream({async transform({data:n},o){n!=="[DONE]"&&o.enqueue(await rr({text:n,schema:r}))}}))}var po=()=>globalThis.fetch,se=async({url:e,headers:r,body:n,failedResponseHandler:o,successfulResponseHandler:s,abortSignal:a,fetch:i})=>ho({url:e,headers:E({"Content-Type":"application/json"},r),body:{content:JSON.stringify(n),values:n},failedResponseHandler:o,successfulResponseHandler:s,abortSignal:a,fetch:i}),ho=async({url:e,headers:r={},body:n,successfulResponseHandler:o,failedResponseHandler:s,abortSignal:a,fetch:i=po()})=>{try{const c=await i(e,{method:"POST",headers:Yn(r),body:n.content,signal:a}),l=ke(c);if(!c.ok){let u;try{u=await s({response:c,url:e,requestBodyValues:n.values})}catch(p){throw xe(p)||V.isInstance(p)?p:new V({message:"Failed to process error response",cause:p,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw u.value}try{return await o({response:c,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(xe(u)||V.isInstance(u))?u:new V({message:"Failed to process successful response",cause:u,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(c){throw Xn({error:c,url:e,requestBodyValues:n.values})}},mo=({errorSchema:e,errorToMessage:r,isRetryable:n})=>async({response:o,url:s,requestBodyValues:a})=>{const i=await o.text(),c=ke(o);if(i.trim()==="")return{responseHeaders:c,value:new V({message:o.statusText,url:s,requestBodyValues:a,statusCode:o.status,responseHeaders:c,responseBody:i,isRetryable:n?.(o)})};try{const l=await co({text:i,schema:e});return{responseHeaders:c,value:new V({message:r(l),url:s,requestBodyValues:a,statusCode:o.status,responseHeaders:c,responseBody:i,data:l,isRetryable:n?.(o,l)})}}catch{return{responseHeaders:c,value:new V({message:o.statusText,url:s,requestBodyValues:a,statusCode:o.status,responseHeaders:c,responseBody:i,isRetryable:n?.(o)})}}},nr=e=>async({response:r})=>{const n=ke(r);if(r.body==null)throw new $n({});return{responseHeaders:n,value:uo({stream:r.body,schema:e})}},De=e=>async({response:r,url:n,requestBodyValues:o})=>{const s=await r.text(),a=await rr({text:s,schema:e}),i=ke(r);if(!a.success)throw new V({message:"Invalid JSON response",cause:a.error,statusCode:r.status,responseHeaders:i,responseBody:s,url:n,requestBodyValues:o});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}},{btoa:go}=globalThis;function fo(e){let r="";for(let n=0;n<e.length;n++)r+=String.fromCodePoint(e[n]);return go(r)}function _o(e){return e?.replace(/\/$/,"")}function Ce(e){return e!=null}var or=(e=>(e.Unknown="unknown",e.OpenAIResponsesV1="openai-responses-v1",e.XAIResponsesV1="xai-responses-v1",e.AnthropicClaudeV1="anthropic-claude-v1",e.GoogleGeminiV1="google-gemini-v1",e))(or||{}),He=t.object({id:t.string().nullish(),format:t._enum$1(or).nullish(),index:t.number().optional()}).loose(),vo=t.object({type:t.literal("reasoning.summary"),summary:t.string()}).extend(He.shape),yo=t.object({type:t.literal("reasoning.encrypted"),data:t.string()}).extend(He.shape),bo=t.object({type:t.literal("reasoning.text"),text:t.string().nullish(),signature:t.string().nullish()}).extend(He.shape),Le=t.union([vo,yo,bo]),ue=t.union([Le,t.unknown().transform(()=>null)]),qe=t.array(ue).transform(e=>e.filter(r=>!!r));t.union([t.object({delta:t.object({reasoning_details:t.array(ue)})}).transform(e=>e.delta.reasoning_details.filter(Ce)),t.object({message:t.object({reasoning_details:t.array(ue)})}).transform(e=>e.message.reasoning_details.filter(Ce)),t.object({text:t.string(),reasoning_details:t.array(ue)}).transform(e=>e.reasoning_details.filter(Ce))]);var Se=t.object({error:t.object({code:t.union([t.string(),t.number()]).nullable().optional().default(null),message:t.string(),type:t.string().nullable().optional().default(null),param:t.any().nullable().optional().default(null)}).passthrough()}).passthrough(),ae=mo({errorSchema:Se,errorToMessage:e=>e.error.message}),sr=t.object({type:t.literal("file"),file:t.object({hash:t.string(),name:t.string(),content:t.array(t.object({type:t.string(),text:t.string().optional()}).catchall(t.any())).optional()}).catchall(t.any())}).catchall(t.any()),wo=t.object({provider:t.string(),reasoning_details:t.array(Le).optional(),annotations:t.array(sr).optional(),usage:t.object({promptTokens:t.number(),promptTokensDetails:t.object({cachedTokens:t.number()}).catchall(t.any()).optional(),completionTokens:t.number(),completionTokensDetails:t.object({reasoningTokens:t.number()}).catchall(t.any()).optional(),totalTokens:t.number(),cost:t.number().optional(),costDetails:t.object({upstreamInferenceCost:t.number()}).catchall(t.any()).optional()}).catchall(t.any())}).catchall(t.any()),Ye=t.object({openrouter:t.object({reasoning_details:t.array(Le).optional(),annotations:t.array(sr).optional()}).optional()}).optional();function ye(e){switch(e){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 ko=["wav","mp3","aiff","aac","ogg","flac","m4a","pcm16","pcm24"];function Ve({url:e,protocols:r}){try{const n=new URL(e);return r.has(n.protocol)}catch{return!1}}function je({part:e,defaultMediaType:r}){var n,o;if(e.data instanceof Uint8Array){const a=fo(e.data);return`data:${(n=e.mediaType)!=null?n:r};base64,${a}`}const s=e.data.toString();return Ve({url:s,protocols:new Set(["http:","https:"])})||s.startsWith("data:")?s:`data:${(o=e.mediaType)!=null?o:r};base64,${s}`}function Qe(e,r){var n;const o=e.match(/^data:([^;]+)/);return o&&(n=o[1])!=null?n:r}function Pe(e){const r=e.match(/^data:[^;]*;base64,(.+)$/);return r?r[1]:e}var So={mpeg:"mp3",mp3:"mp3","x-wav":"wav",wave:"wav",wav:"wav",ogg:"ogg",vorbis:"ogg",aac:"aac","x-aac":"aac",m4a:"m4a","x-m4a":"m4a",mp4:"m4a",aiff:"aiff","x-aiff":"aiff",flac:"flac","x-flac":"flac",pcm16:"pcm16",pcm24:"pcm24"};function To(e){const r=je({part:e,defaultMediaType:"audio/mpeg"});if(Ve({url:r,protocols:new Set(["http:","https:"])}))throw new Error(`Audio files cannot be provided as URLs.
|
|
8
|
-
|
|
9
|
-
OpenRouter requires audio to be base64-encoded. Please:
|
|
10
|
-
1. Download the audio file locally
|
|
11
|
-
2. Read it as a Buffer or Uint8Array
|
|
12
|
-
3. Pass it as the data parameter
|
|
13
|
-
|
|
14
|
-
The AI SDK will automatically handle base64 encoding.
|
|
15
|
-
|
|
16
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);const n=Pe(r),o=e.mediaType||"audio/mpeg",s=o.replace("audio/",""),a=So[s];if(a===void 0){const i=ko.join(", ");throw new Error(`Unsupported audio format: "${o}"
|
|
17
|
-
|
|
18
|
-
OpenRouter supports the following audio formats: ${i}
|
|
19
|
-
|
|
20
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`)}return{data:n,format:a}}function G(e){var r,n,o;const s=e?.anthropic,a=e?.openrouter;return(o=(n=(r=a?.cacheControl)!=null?r:a?.cache_control)!=null?n:s?.cacheControl)!=null?o:s?.cache_control}function Ro(e){var r,n,o,s,a,i,c,l,u,p;const g=[];for(const{role:m,content:_,providerOptions:h}of e)switch(m){case"system":{g.push({role:"system",content:_,cache_control:G(h)});break}case"user":{if(_.length===1&&((r=_[0])==null?void 0:r.type)==="text"){const y=(n=G(h))!=null?n:G(_[0].providerOptions),k=y?[{type:"text",text:_[0].text,cache_control:y}]:_[0].text;g.push({role:"user",content:k});break}const d=G(h),v=_.map(y=>{var k,b,w,O,I,C,T;const H=(k=G(y.providerOptions))!=null?k:d;switch(y.type){case"text":return{type:"text",text:y.text,cache_control:H};case"file":{if((b=y.mediaType)!=null&&b.startsWith("image/"))return{type:"image_url",image_url:{url:je({part:y,defaultMediaType:"image/jpeg"})},cache_control:H};if((w=y.mediaType)!=null&&w.startsWith("audio/"))return{type:"input_audio",input_audio:To(y),cache_control:H};const D=String((T=(C=(I=(O=y.providerOptions)==null?void 0:O.openrouter)==null?void 0:I.filename)!=null?C:y.filename)!=null?T:""),L=je({part:y,defaultMediaType:"application/pdf"});return Ve({url:L,protocols:new Set(["http:","https:"])})?{type:"file",file:{filename:D,file_data:L}}:{type:"file",file:{filename:D,file_data:L},cache_control:H}}default:return{type:"text",text:"",cache_control:H}}});g.push({role:"user",content:v});break}case"assistant":{let d="",v="";const y=[],k=[];for(const C of _)switch(C.type){case"text":{d+=C.text;break}case"tool-call":{const T=(o=C.providerOptions)==null?void 0:o.openrouter;T?.reasoning_details&&Array.isArray(T.reasoning_details)&&k.push(...T.reasoning_details),y.push({id:C.toolCallId,type:"function",function:{name:C.toolName,arguments:JSON.stringify(C.input)}});break}case"reasoning":{v+=C.text;const T=Ye.safeParse(C.providerOptions);T.success&&((a=(s=T.data)==null?void 0:s.openrouter)!=null&&a.reasoning_details)&&k.push(...T.data.openrouter.reasoning_details);break}}const b=Ye.safeParse(h),w=b.success?(c=(i=b.data)==null?void 0:i.openrouter)==null?void 0:c.reasoning_details:void 0,O=b.success?(u=(l=b.data)==null?void 0:l.openrouter)==null?void 0:u.annotations:void 0,I=w&&Array.isArray(w)&&w.length>0?w:k.length>0?k:void 0;g.push({role:"assistant",content:d,tool_calls:y.length>0?y:void 0,reasoning:v||void 0,reasoning_details:I,annotations:O,cache_control:G(h)});break}case"tool":{for(const d of _){const v=Eo(d);g.push({role:"tool",tool_call_id:d.toolCallId,content:v,cache_control:(p=G(h))!=null?p:G(d.providerOptions)})}break}}return g}function Eo(e){return e.output.type==="text"?e.output.value:JSON.stringify(e.output.value)}t.union([t.literal("auto"),t.literal("none"),t.literal("required"),t.object({type:t.literal("function"),function:t.object({name:t.string()})})]);function Co(e){switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:e.toolName}};default:throw new Pt({argument:"toolChoice",message:`Invalid tool choice type: ${JSON.stringify(e)}`})}}var Io=t.object({type:t.literal("image_url"),image_url:t.object({url:t.string()}).passthrough()}).passthrough(),xo=t.union([Io,t.unknown().transform(()=>null)]),ar=t.array(xo).transform(e=>e.filter(r=>!!r)),ir=t.object({id:t.string().optional(),model:t.string().optional(),provider:t.string().optional(),usage:t.object({prompt_tokens:t.number(),prompt_tokens_details:t.object({cached_tokens:t.number()}).passthrough().nullish(),completion_tokens:t.number(),completion_tokens_details:t.object({reasoning_tokens:t.number()}).passthrough().nullish(),total_tokens:t.number(),cost:t.number().optional(),cost_details:t.object({upstream_inference_cost:t.number().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),Oo=t.union([ir.extend({choices:t.array(t.object({message:t.object({role:t.literal("assistant"),content:t.string().nullable().optional(),reasoning:t.string().nullable().optional(),reasoning_details:qe.nullish(),images:ar.nullish(),tool_calls:t.array(t.object({id:t.string().optional().nullable(),type:t.literal("function"),function:t.object({name:t.string(),arguments:t.string()}).passthrough()}).passthrough()).optional(),annotations:t.array(t.union([t.object({type:t.literal("url_citation"),url_citation:t.object({end_index:t.number(),start_index:t.number(),title:t.string(),url:t.string(),content:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file_annotation"),file_annotation:t.object({file_id:t.string(),quote:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file"),file:t.object({hash:t.string(),name:t.string(),content:t.array(t.object({type:t.string(),text:t.string().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough(),index:t.number().nullish(),logprobs:t.object({content:t.array(t.object({token:t.string(),logprob:t.number(),top_logprobs:t.array(t.object({token:t.string(),logprob:t.number()}).passthrough())}).passthrough()).nullable()}).passthrough().nullable().optional(),finish_reason:t.string().optional().nullable()}).passthrough())}),Se.extend({user_id:t.string().optional()})]),jo=t.union([ir.extend({choices:t.array(t.object({delta:t.object({role:t._enum$1(["assistant"]).optional(),content:t.string().nullish(),reasoning:t.string().nullish().optional(),reasoning_details:qe.nullish(),images:ar.nullish(),tool_calls:t.array(t.object({index:t.number().nullish(),id:t.string().nullish(),type:t.literal("function").optional(),function:t.object({name:t.string().nullish(),arguments:t.string().nullish()}).passthrough()}).passthrough()).nullish(),annotations:t.array(t.union([t.object({type:t.literal("url_citation"),url_citation:t.object({end_index:t.number(),start_index:t.number(),title:t.string(),url:t.string(),content:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file_annotation"),file_annotation:t.object({file_id:t.string(),quote:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file"),file:t.object({hash:t.string(),name:t.string(),content:t.array(t.object({type:t.string(),text:t.string().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough().nullish(),logprobs:t.object({content:t.array(t.object({token:t.string(),logprob:t.number(),top_logprobs:t.array(t.object({token:t.string(),logprob:t.number()}).passthrough())}).passthrough()).nullable()}).passthrough().nullish(),finish_reason:t.string().nullable().optional(),index:t.number().nullish()}).passthrough())}),Se]),Po=class{constructor(e,r,n){this.specificationVersion="v2",this.provider="openrouter",this.defaultObjectGenerationMode="tool",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.modelId=e,this.settings=r,this.config=n}getArgs({prompt:e,maxOutputTokens:r,temperature:n,topP:o,frequencyPenalty:s,presencePenalty:a,seed:i,stopSequences:c,responseFormat:l,topK:u,tools:p,toolChoice:g}){var m;const _=E(E({model:this.modelId,models:this.settings.models,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:o,frequency_penalty:s,presence_penalty:a,seed:i,stop:c,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:E({schema:l.schema,strict:!0,name:(m=l.name)!=null?m:"response"},l.description&&{description:l.description})}:{type:"json_object"}:void 0,top_k:u,messages:Ro(e),include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning,usage:this.settings.usage,plugins:this.settings.plugins,web_search_options:this.settings.web_search_options,provider:this.settings.provider,debug:this.settings.debug},this.config.extraBody),this.settings.extraBody);if(p&&p.length>0){const h=p.filter(d=>d.type==="function").map(d=>({type:"function",function:{name:d.name,description:d.description,parameters:d.inputSchema}}));return _e(E({},_),{tools:h,tool_choice:g?Co(g):void 0})}return _}async doGenerate(e){var r,n,o,s,a,i,c,l,u,p,g,m,_,h,d,v,y,k,b,w,O,I,C;const H=(e.providerOptions||{}).openrouter||{},D=E(E({},this.getArgs(e)),H),{value:L,responseHeaders:Z}=await se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:oe(this.config.headers(),e.headers),body:D,failedResponseHandler:ae,successfulResponseHandler:De(Oo),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in L){const f=L.error;throw new V({message:f.message,url:this.config.url({path:"/chat/completions",modelId:this.modelId}),requestBodyValues:D,statusCode:200,responseHeaders:Z,data:f})}const P=L,A=P.choices[0];if(!A)throw new Ft({message:"No choice in response"});const F=P.usage?{inputTokens:(r=P.usage.prompt_tokens)!=null?r:0,outputTokens:(n=P.usage.completion_tokens)!=null?n:0,totalTokens:((o=P.usage.prompt_tokens)!=null?o:0)+((s=P.usage.completion_tokens)!=null?s:0),reasoningTokens:(i=(a=P.usage.completion_tokens_details)==null?void 0:a.reasoning_tokens)!=null?i:0,cachedInputTokens:(l=(c=P.usage.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?l:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},K=(u=A.message.reasoning_details)!=null?u:[],le=K.length>0?K.map(f=>{switch(f.type){case"reasoning.text":{if(f.text)return{type:"reasoning",text:f.text,providerMetadata:{openrouter:{reasoning_details:[f]}}};break}case"reasoning.summary":{if(f.summary)return{type:"reasoning",text:f.summary,providerMetadata:{openrouter:{reasoning_details:[f]}}};break}case"reasoning.encrypted":{if(f.data)return{type:"reasoning",text:"[REDACTED]",providerMetadata:{openrouter:{reasoning_details:[f]}}};break}}return null}).filter(f=>f!==null):A.message.reasoning?[{type:"reasoning",text:A.message.reasoning}]:[],B=[];if(B.push(...le),A.message.content&&B.push({type:"text",text:A.message.content}),A.message.tool_calls)for(const f of A.message.tool_calls)B.push({type:"tool-call",toolCallId:(p=f.id)!=null?p:q(),toolName:f.function.name,input:f.function.arguments,providerMetadata:{openrouter:{reasoning_details:K}}});if(A.message.images)for(const f of A.message.images)B.push({type:"file",mediaType:Qe(f.image_url.url,"image/jpeg"),data:Pe(f.image_url.url)});if(A.message.annotations)for(const f of A.message.annotations)f.type==="url_citation"&&B.push({type:"source",sourceType:"url",id:f.url_citation.url,url:f.url_citation.url,title:f.url_citation.title,providerMetadata:{openrouter:{content:f.url_citation.content||""}}});const X=(g=A.message.annotations)==null?void 0:g.filter(f=>f.type==="file"),x=A.message.tool_calls&&A.message.tool_calls.length>0,z=K.some(f=>f.type==="reasoning.encrypted"&&f.data),Y=x&&z&&A.finish_reason==="stop"?"tool-calls":ye(A.finish_reason);return{content:B,finishReason:Y,usage:F,warnings:[],providerMetadata:{openrouter:wo.parse({provider:(m=P.provider)!=null?m:"",reasoning_details:(_=A.message.reasoning_details)!=null?_:[],annotations:X&&X.length>0?X:void 0,usage:E(E(E({promptTokens:(h=F.inputTokens)!=null?h:0,completionTokens:(d=F.outputTokens)!=null?d:0,totalTokens:(v=F.totalTokens)!=null?v:0,cost:(y=P.usage)==null?void 0:y.cost},((b=(k=P.usage)==null?void 0:k.prompt_tokens_details)==null?void 0:b.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:P.usage.prompt_tokens_details.cached_tokens}}:{}),((O=(w=P.usage)==null?void 0:w.completion_tokens_details)==null?void 0:O.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:P.usage.completion_tokens_details.reasoning_tokens}}:{}),((C=(I=P.usage)==null?void 0:I.cost_details)==null?void 0:C.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:P.usage.cost_details.upstream_inference_cost}}:{})})},request:{body:D},response:{id:P.id,modelId:P.model,headers:Z}}}async doStream(e){var r;const o=(e.providerOptions||{}).openrouter||{},s=E(E({},this.getArgs(e)),o),{value:a,responseHeaders:i}=await se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:oe(this.config.headers(),e.headers),body:_e(E({},s),{stream:!0,stream_options:this.config.compatibility==="strict"?E({include_usage:!0},(r=this.settings.usage)!=null&&r.include?{include_usage:!0}:{}):void 0}),failedResponseHandler:ae,successfulResponseHandler:nr(jo),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=[];let l="other";const u={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},p={},g=[],m=[];let _=!1,h=!1,d,v,y,k;return{stream:a.pipeThrough(new TransformStream({transform(b,w){var O,I,C,T,H,D,L,Z,P,A,F,K,le,B,X;if(!b.success){l="error",w.enqueue({type:"error",error:b.error});return}const x=b.value;if("error"in x){l="error",w.enqueue({type:"error",error:x.error});return}if(x.provider&&(k=x.provider),x.id&&(y=x.id,w.enqueue({type:"response-metadata",id:x.id})),x.model&&w.enqueue({type:"response-metadata",modelId:x.model}),x.usage!=null){if(u.inputTokens=x.usage.prompt_tokens,u.outputTokens=x.usage.completion_tokens,u.totalTokens=x.usage.prompt_tokens+x.usage.completion_tokens,p.promptTokens=x.usage.prompt_tokens,x.usage.prompt_tokens_details){const S=(O=x.usage.prompt_tokens_details.cached_tokens)!=null?O:0;u.cachedInputTokens=S,p.promptTokensDetails={cachedTokens:S}}if(p.completionTokens=x.usage.completion_tokens,x.usage.completion_tokens_details){const S=(I=x.usage.completion_tokens_details.reasoning_tokens)!=null?I:0;u.reasoningTokens=S,p.completionTokensDetails={reasoningTokens:S}}p.cost=x.usage.cost,p.totalTokens=x.usage.total_tokens;const f=(C=x.usage.cost_details)==null?void 0:C.upstream_inference_cost;f!=null&&(p.costDetails={upstreamInferenceCost:f})}const z=x.choices[0];if(z?.finish_reason!=null&&(l=ye(z.finish_reason)),z?.delta==null)return;const $=z.delta,Y=(f,S)=>{h||(v=y||q(),w.enqueue({providerMetadata:S,type:"reasoning-start",id:v}),h=!0),w.enqueue({providerMetadata:S,type:"reasoning-delta",delta:f,id:v||q()})};if($.reasoning_details&&$.reasoning_details.length>0){for(const S of $.reasoning_details)if(S.type==="reasoning.text"){const j=g[g.length-1];j?.type==="reasoning.text"?(j.text=(j.text||"")+(S.text||""),j.signature=j.signature||S.signature,j.format=j.format||S.format):g.push(E({},S))}else g.push(S);const f={openrouter:{reasoning_details:$.reasoning_details}};for(const S of $.reasoning_details)switch(S.type){case"reasoning.text":{S.text&&Y(S.text,f);break}case"reasoning.encrypted":{S.data&&Y("[REDACTED]",f);break}case"reasoning.summary":{S.summary&&Y(S.summary,f);break}}}else $.reasoning&&Y($.reasoning);if($.content&&(h&&!_&&(w.enqueue({type:"reasoning-end",id:v||q()}),h=!1),_||(d=y||q(),w.enqueue({type:"text-start",id:d}),_=!0),w.enqueue({type:"text-delta",delta:$.content,id:d||q()})),$.annotations){for(const f of $.annotations)if(f.type==="url_citation")w.enqueue({type:"source",sourceType:"url",id:f.url_citation.url,url:f.url_citation.url,title:f.url_citation.title,providerMetadata:{openrouter:{content:f.url_citation.content||""}}});else if(f.type==="file"){const S=f.file;S&&typeof S=="object"&&"hash"in S&&"name"in S&&m.push(f)}}if($.tool_calls!=null)for(const f of $.tool_calls){const S=(T=f.index)!=null?T:c.length-1;if(c[S]==null){if(f.type!=="function")throw new te({data:f,message:"Expected 'function' type."});if(f.id==null)throw new te({data:f,message:"Expected 'id' to be a string."});if(((H=f.function)==null?void 0:H.name)==null)throw new te({data:f,message:"Expected 'function.name' to be a string."});c[S]={id:f.id,type:"function",function:{name:f.function.name,arguments:(D=f.function.arguments)!=null?D:""},inputStarted:!1,sent:!1};const M=c[S];if(M==null)throw new te({data:{index:S,toolCallsLength:c.length},message:`Tool call at index ${S} is missing after creation.`});((L=M.function)==null?void 0:L.name)!=null&&((Z=M.function)==null?void 0:Z.arguments)!=null&&Ee(M.function.arguments)&&(M.inputStarted=!0,w.enqueue({type:"tool-input-start",id:M.id,toolName:M.function.name}),w.enqueue({type:"tool-input-delta",id:M.id,delta:M.function.arguments}),w.enqueue({type:"tool-input-end",id:M.id}),w.enqueue({type:"tool-call",toolCallId:M.id,toolName:M.function.name,input:M.function.arguments,providerMetadata:{openrouter:{reasoning_details:g}}}),M.sent=!0);continue}const j=c[S];if(j==null)throw new te({data:{index:S,toolCallsLength:c.length,toolCallDelta:f},message:`Tool call at index ${S} is missing during merge.`});j.inputStarted||(j.inputStarted=!0,w.enqueue({type:"tool-input-start",id:j.id,toolName:j.function.name})),((P=f.function)==null?void 0:P.arguments)!=null&&(j.function.arguments+=(F=(A=f.function)==null?void 0:A.arguments)!=null?F:""),w.enqueue({type:"tool-input-delta",id:j.id,delta:(K=f.function.arguments)!=null?K:""}),((le=j.function)==null?void 0:le.name)!=null&&((B=j.function)==null?void 0:B.arguments)!=null&&Ee(j.function.arguments)&&(w.enqueue({type:"tool-call",toolCallId:(X=j.id)!=null?X:q(),toolName:j.function.name,input:j.function.arguments,providerMetadata:{openrouter:{reasoning_details:g}}}),j.sent=!0)}if($.images!=null)for(const f of $.images)w.enqueue({type:"file",mediaType:Qe(f.image_url.url,"image/jpeg"),data:Pe(f.image_url.url)})},flush(b){var w;const O=c.length>0,I=g.some(T=>T.type==="reasoning.encrypted"&&T.data);if(O&&I&&l==="stop"&&(l="tool-calls"),l==="tool-calls")for(const T of c)T&&!T.sent&&(b.enqueue({type:"tool-call",toolCallId:(w=T.id)!=null?w:q(),toolName:T.function.name,input:Ee(T.function.arguments)?T.function.arguments:"{}",providerMetadata:{openrouter:{reasoning_details:g}}}),T.sent=!0);h&&b.enqueue({type:"reasoning-end",id:v||q()}),_&&b.enqueue({type:"text-end",id:d||q()});const C={usage:p};k!==void 0&&(C.provider=k),g.length>0&&(C.reasoning_details=g),m.length>0&&(C.annotations=m),b.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:{openrouter:C}})}})),warnings:[],request:{body:s},response:{headers:i}}}};function Ao({prompt:e,inputFormat:r,user:n="user",assistant:o="assistant"}){if(e.length===1&&e[0]&&e[0].role==="user"&&e[0].content.length===1&&e[0].content[0]&&e[0].content[0].type==="text")return{prompt:e[0].content[0].text};let s="";e[0]&&e[0].role==="system"&&(s+=`${e[0].content}
|
|
21
|
-
|
|
22
|
-
`,e=e.slice(1));for(const{role:a,content:i}of e)switch(a){case"system":throw new Dn({message:`Unexpected system message in prompt: ${i}`,prompt:e});case"user":{const c=i.map(l=>{switch(l.type){case"text":return l.text;case"file":throw new W({functionality:"file attachments"});default:return""}}).join("");s+=`${n}:
|
|
23
|
-
${c}
|
|
24
|
-
|
|
25
|
-
`;break}case"assistant":{const c=i.map(l=>{switch(l.type){case"text":return l.text;case"tool-call":throw new W({functionality:"tool-call messages"});case"tool-result":throw new W({functionality:"tool-result messages"});case"reasoning":throw new W({functionality:"reasoning messages"});case"file":throw new W({functionality:"file attachments"});default:return""}}).join("");s+=`${o}:
|
|
26
|
-
${c}
|
|
27
|
-
|
|
28
|
-
`;break}case"tool":throw new W({functionality:"tool messages"})}return s+=`${o}:
|
|
29
|
-
`,{prompt:s}}var et=t.union([t.object({id:t.string().optional(),model:t.string().optional(),choices:t.array(t.object({text:t.string(),reasoning:t.string().nullish().optional(),reasoning_details:qe.nullish(),finish_reason:t.string().nullish(),index:t.number().nullish(),logprobs:t.object({tokens:t.array(t.string()),token_logprobs:t.array(t.number()),top_logprobs:t.array(t.record(t.string(),t.number())).nullable()}).passthrough().nullable().optional()}).passthrough()),usage:t.object({prompt_tokens:t.number(),prompt_tokens_details:t.object({cached_tokens:t.number()}).passthrough().nullish(),completion_tokens:t.number(),completion_tokens_details:t.object({reasoning_tokens:t.number()}).passthrough().nullish(),total_tokens:t.number(),cost:t.number().optional(),cost_details:t.object({upstream_inference_cost:t.number().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),Se]),Uo=class{constructor(e,r,n){this.specificationVersion="v2",this.provider="openrouter",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=e,this.settings=r,this.config=n}getArgs({prompt:e,maxOutputTokens:r,temperature:n,topP:o,frequencyPenalty:s,presencePenalty:a,seed:i,responseFormat:c,topK:l,stopSequences:u,tools:p,toolChoice:g}){const{prompt:m}=Ao({prompt:e,inputFormat:"prompt"});if(p?.length)throw new W({functionality:"tools"});if(g)throw new W({functionality:"toolChoice"});return E(E({model:this.modelId,models:this.settings.models,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:r,temperature:n,top_p:o,frequency_penalty:s,presence_penalty:a,seed:i,stop:u,response_format:c,top_k:l,prompt:m,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate(e){var r,n,o,s,a,i,c,l,u,p,g,m,_,h,d;const y=(e.providerOptions||{}).openrouter||{},k=E(E({},this.getArgs(e)),y),{value:b,responseHeaders:w}=await se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:oe(this.config.headers(),e.headers),body:k,failedResponseHandler:ae,successfulResponseHandler:De(et),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in b){const I=b.error;throw new V({message:I.message,url:this.config.url({path:"/completions",modelId:this.modelId}),requestBodyValues:k,statusCode:200,responseHeaders:w,data:I})}const O=b.choices[0];if(!O)throw new Ft({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(r=O.text)!=null?r:""}],finishReason:ye(O.finish_reason),usage:{inputTokens:(o=(n=b.usage)==null?void 0:n.prompt_tokens)!=null?o:0,outputTokens:(a=(s=b.usage)==null?void 0:s.completion_tokens)!=null?a:0,totalTokens:((c=(i=b.usage)==null?void 0:i.prompt_tokens)!=null?c:0)+((u=(l=b.usage)==null?void 0:l.completion_tokens)!=null?u:0),reasoningTokens:(m=(g=(p=b.usage)==null?void 0:p.completion_tokens_details)==null?void 0:g.reasoning_tokens)!=null?m:0,cachedInputTokens:(d=(h=(_=b.usage)==null?void 0:_.prompt_tokens_details)==null?void 0:h.cached_tokens)!=null?d:0},warnings:[],response:{headers:w}}}async doStream(e){const n=(e.providerOptions||{}).openrouter||{},o=E(E({},this.getArgs(e)),n),{value:s,responseHeaders:a}=await se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:oe(this.config.headers(),e.headers),body:_e(E({},o),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:ae,successfulResponseHandler:nr(et),abortSignal:e.abortSignal,fetch:this.config.fetch});let i="other";const c={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},l={};return{stream:s.pipeThrough(new TransformStream({transform(u,p){var g,m,_;if(!u.success){i="error",p.enqueue({type:"error",error:u.error});return}const h=u.value;if("error"in h){i="error",p.enqueue({type:"error",error:h.error});return}if(h.usage!=null){if(c.inputTokens=h.usage.prompt_tokens,c.outputTokens=h.usage.completion_tokens,c.totalTokens=h.usage.prompt_tokens+h.usage.completion_tokens,l.promptTokens=h.usage.prompt_tokens,h.usage.prompt_tokens_details){const y=(g=h.usage.prompt_tokens_details.cached_tokens)!=null?g:0;c.cachedInputTokens=y,l.promptTokensDetails={cachedTokens:y}}if(l.completionTokens=h.usage.completion_tokens,h.usage.completion_tokens_details){const y=(m=h.usage.completion_tokens_details.reasoning_tokens)!=null?m:0;c.reasoningTokens=y,l.completionTokensDetails={reasoningTokens:y}}l.cost=h.usage.cost,l.totalTokens=h.usage.total_tokens;const v=(_=h.usage.cost_details)==null?void 0:_.upstream_inference_cost;v!=null&&(l.costDetails={upstreamInferenceCost:v})}const d=h.choices[0];d?.finish_reason!=null&&(i=ye(d.finish_reason)),d?.text!=null&&p.enqueue({type:"text-delta",delta:d.text,id:q()})},flush(u){u.enqueue({type:"finish",finishReason:i,usage:c,providerMetadata:{openrouter:{usage:l}}})}})),response:{headers:a}}}},$o=t.object({prompt_tokens:t.number(),total_tokens:t.number(),cost:t.number().optional()}),Mo=t.object({object:t.literal("embedding"),embedding:t.array(t.number()),index:t.number().optional()}),No=t.object({id:t.string().optional(),object:t.literal("list"),data:t.array(Mo),model:t.string(),usage:$o.optional()}),Do=class{constructor(e,r,n){this.specificationVersion="v2",this.provider="openrouter",this.maxEmbeddingsPerCall=void 0,this.supportsParallelCalls=!0,this.modelId=e,this.settings=r,this.config=n}async doEmbed(e){var r;const{values:n,abortSignal:o,headers:s}=e,a=E(E({model:this.modelId,input:n,user:this.settings.user,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody),{value:i,responseHeaders:c}=await se({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:oe(this.config.headers(),s),body:a,failedResponseHandler:ae,successfulResponseHandler:De(No),abortSignal:o,fetch:this.config.fetch});return{embeddings:i.data.map(l=>l.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,providerMetadata:(r=i.usage)!=null&&r.cost?{openrouter:{usage:{cost:i.usage.cost}}}:void 0,response:{headers:c,body:i}}}};function Ho(e){return Object.fromEntries(Object.entries(e).filter(([,r])=>r!==null))}function Lo(e,...r){const n=Ho(e??{}),s=[n["user-agent"]||"",...r].filter(Boolean).join(" ");return _e(E({},n),{"user-agent":s})}var qo="1.5.4";function lr(e={}){var r,n,o;const s=(n=_o((r=e.baseURL)!=null?r:e.baseUrl))!=null?n:"https://openrouter.ai/api/v1",a=(o=e.compatibility)!=null?o:"compatible",i=()=>Lo(E(E({Authorization:`Bearer ${Qn({apiKey:e.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},e.headers),e.api_keys&&Object.keys(e.api_keys).length>0&&{"X-Provider-API-Keys":JSON.stringify(e.api_keys)}),`ai-sdk/openrouter/${qo}`),c=(m,_={})=>new Po(m,_,{provider:"openrouter.chat",url:({path:h})=>`${s}${h}`,headers:i,compatibility:a,fetch:e.fetch,extraBody:e.extraBody}),l=(m,_={})=>new Uo(m,_,{provider:"openrouter.completion",url:({path:h})=>`${s}${h}`,headers:i,compatibility:a,fetch:e.fetch,extraBody:e.extraBody}),u=(m,_={})=>new Do(m,_,{provider:"openrouter.embedding",url:({path:h})=>`${s}${h}`,headers:i,fetch:e.fetch,extraBody:e.extraBody}),p=(m,_)=>{if(new.target)throw new Error("The OpenRouter model function cannot be called with the new keyword.");return m==="openai/gpt-3.5-turbo-instruct"?l(m,_):c(m,_)},g=(m,_)=>p(m,_);return g.languageModel=p,g.chat=c,g.completion=l,g.textEmbeddingModel=u,g.embedding=u,g}lr({compatibility:"strict"});const Vo="https://app.getgram.ai",Bo=()=>({chat:zo}),Jo=t.object({mcp:t.union([t.string()]),environment:t.record(t.string(),t.unknown()).optional(),projectSlug:t.string(),model:t._enum$1(t.MODELS)}),zo=async(e,r)=>{if(e.method==="POST")try{const n=[];for await(const _ of e)n.push(_);const o=Buffer.concat(n).toString(),{messages:s,config:a,system:i,tools:c}=JSON.parse(o),l=Jo.parse(a),p=await(await Tn({transport:{type:"http",url:l.mcp,headers:{...Go(l.environment??{}),Authorization:`Bearer ${process.env.GRAM_API_KEY??""}`}}})).tools(),g=lr({baseURL:Vo,apiKey:"must be set",headers:{"Gram-Project":l.projectSlug,"Gram-Key":process.env.GRAM_API_KEY??""}}),m=t.streamText({system:i,model:g.chat(l.model),messages:t.convertToModelMessages(s),tools:{...p,...cr(c)},stopWhen:t.stepCountIs(10)});r.setHeader("Content-Type","text/event-stream"),r.setHeader("Cache-Control","no-cache"),r.setHeader("Connection","keep-alive"),r.setHeader("Transfer-Encoding","chunked"),r.statusCode=200,m.pipeUIMessageStreamToResponse(r,{sendReasoning:!0,sendSources:!0})}catch(n){r.statusCode=500,r.end(JSON.stringify({error:n instanceof Error?n.message:"Unknown error"}))}},tt="MCP-";function Go(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((r,[n,o])=>{const s=n.replace(/_/g,"-"),a=s.startsWith(tt)?s:`${tt}${s}`;return r[a]=o,r},{})}exports.createElementsServerHandlers=Bo;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s="https://app.getgram.ai",i=()=>({session:o}),o=async(a,t,n)=>{a.method==="POST"&&fetch(s+"/rpc/chatSessions.create",{method:"POST",body:JSON.stringify({embed_origin:n?.embedOrigin,user_identifier:n?.userIdentifier,expires_after:n?.expiresAfter}),headers:{"Content-Type":"application/json","Gram-Project":"default","Gram-Key":process.env.GRAM_API_KEY??""}}).then(async e=>{const r=await e.text();t.writeHead(e.status,{"Content-Type":"application/json"}),t.end(r)}).catch(e=>{console.error("Failed to create chat session:",e),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Failed to create chat session: "+e.message}))})};exports.createElementsServerHandlers=i;
|
package/dist/server.d.ts
CHANGED
|
@@ -1,7 +1,35 @@
|
|
|
1
1
|
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
-
type
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
type ServerHandler<T> = (req: IncomingMessage, res: ServerResponse, options?: T) => Promise<void>;
|
|
3
|
+
interface ServerHandlers {
|
|
4
|
+
/**
|
|
5
|
+
* Handler to create a new chat session token.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { createElementsServerHandlers } from '@gram-ai/elements/server'
|
|
10
|
+
* import express from 'express'
|
|
11
|
+
* const app = express()
|
|
12
|
+
* const handlers = createElementsServerHandlers()
|
|
13
|
+
* app.post('/chat/session', handlers.session)
|
|
14
|
+
* app.listen(3000)
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
session: ServerHandler<SessionHandlerOptions>;
|
|
18
|
+
}
|
|
6
19
|
export declare const createElementsServerHandlers: () => ServerHandlers;
|
|
20
|
+
interface SessionHandlerOptions {
|
|
21
|
+
/**
|
|
22
|
+
* The origin from which the token will be used
|
|
23
|
+
*/
|
|
24
|
+
embedOrigin: string;
|
|
25
|
+
/**
|
|
26
|
+
* Free-form user identifier
|
|
27
|
+
*/
|
|
28
|
+
userIdentifier: string;
|
|
29
|
+
/**
|
|
30
|
+
* Token expiration in seconds (max / default 3600)
|
|
31
|
+
* @default 3600
|
|
32
|
+
*/
|
|
33
|
+
expiresAfter?: number;
|
|
34
|
+
}
|
|
7
35
|
export {};
|