chattr
Version:
A chatgpt chatbot component library for nextjs.
3 lines (2 loc) • 33.7 kB
JavaScript
;var t=require("react");function e({key:e,content:r,chattrBotName:a="Chattrbot"}){return t.createElement("div",{key:e,className:"mb-3 flex justify-start"},t.createElement("div",{className:"rounded-chattrRoundedLarge bg-chattrPrimary px-3 py-2 dark:bg-chattrPrimaryDark"},t.createElement("p",{className:"max-w-[160px] break-words text-sm font-light text-chattrTextDark"},r)),t.createElement("p",{className:"flex items-center pl-2 text-sm font-semibold tracking-normal text-chattrText dark:text-chattrTextDark"},a))}function r(){return t.createElement("svg",{stroke:"currentColor",fill:"currentColor",strokeWidth:"0",version:"1.1",viewBox:"0 0 21 21",height:"1em",width:"1em",xmlns:"http://www.w3.org/2000/svg"},t.createElement("path",{d:"M9.207 8.5l6.646 6.646-0.707 0.707-6.646-6.646-6.646 6.646-0.707-0.707 6.646-6.646-6.647-6.646 0.707-0.707 6.647 6.646 6.646-6.646 0.707 0.707-6.646 6.646z"}))}function a({children:e}){return t.createElement("div",{className:"rounded-chattrRoundedLarge border-chattrGray bg-chattrWhite dark:border-chattrText dark:bg-chattrPitchBlack fixed bottom-4 right-4 z-20 flex h-96 max-h-96 w-72 flex-col justify-between border shadow"},e)}function n(){const[e,r]=t.useState(!1);return{isOpen:e,toggle:t.useCallback((()=>{r((t=>!t))}),[])}}function s(e){const r=t.useRef(null);return t.useEffect((()=>{r.current&&(r.current.scrollTop=r.current.scrollHeight)}),[e]),r}function i({key:e,content:r,userName:a="You"}){return t.createElement("div",{key:e,className:"mb-3 flex justify-end"},t.createElement("p",{className:"flex items-center pr-2 text-sm font-semibold tracking-wide text-chattrText dark:text-chattrTextDark"},a),t.createElement("div",{className:"rounded-chattrRoundedLarge bg-chattrBackgroundMuted px-3 py-2 dark:bg-chattrGrayDark"},t.createElement("p",{className:"max-w-[160px] break-words text-sm font-light text-chattrText dark:text-chattrTextDark"},r)))}var o=t.memo((function({message:{content:r,role:a,key:n},userName:s,chattrBotName:o}){return"user"===a?t.createElement(i,{key:n,content:r,userName:s}):t.createElement(e,{key:n,content:r,chattrBotName:o})}));function c({chattrBotName:e="Chattrbot"}){return t.createElement("div",{className:"mb-3 flex justify-start"},t.createElement("div",{className:"rounded-chattrRoundedMedium bg-chattrPrimary px-0.5 py-1.5 dark:bg-chattrPrimaryDark"},t.createElement("div",{className:"flex items-center justify-center px-3 py-2"},t.createElement("div",{className:"chattrDotDefault animate-chattrLoader"}),t.createElement("div",{className:"chattrDotDefault animation-delay-200 animate-chattrLoader"}),t.createElement("div",{className:"chattrDotDefault animation-delay-400 animate-chattrLoader"}))),t.createElement("p",{className:"flex items-center pl-2 text-sm font-semibold tracking-wide text-zinc-900 dark:text-zinc-100"},e))}var l=t.memo((function({messages:e,userName:r,chattrBotName:a,loading:n}){const i=s(e);return t.createElement("div",{ref:i,className:"max-h-[275px] flex-auto overflow-y-scroll px-3"},t.createElement("div",{className:"mb-3"}),e.map(((e,n)=>t.createElement(o,{key:`${e.role}_message_${n}`,message:e,userName:r,chattrBotName:a}))),n&&t.createElement(c,{chattrBotName:a}))}));function d({setMessage:e,sendMessage:r,message:a,loading:n}){return t.createElement("form",{onSubmit:t=>r(t),className:"dark:bg-chattrPitchBlack rounded-b-chattrRoundedLarge border-chattrGray bg-chattrWhite dark:border-chattrTextDark/10 z-40 flex h-16 items-center justify-between border-t px-2 py-2.5"},t.createElement("input",{className:"rounded-chattrRoundedMedium border-chattrGray bg-chattrWhite text-chattrText placeholder:text-chattrSecondary/70 focus:border-chattrPrimary dark:border-chattrTextDark/10 dark:bg-chattrBlack dark:text-chattrTextDark dark:placeholder:text-chattrTextDark/50 dark:focus:border-chattrPrimaryDark h-10 min-w-0 flex-auto appearance-none border px-3 py-2 font-light focus:outline-none sm:text-sm",type:"text",required:!0,placeholder:"Ask a question...",autoComplete:"off",autoCorrect:"off",value:a,onChange:({target:{value:t}})=>e(t)}),t.createElement("button",{type:"submit",disabled:n,className:"rounded-chattrRoundedMedium bg-chattrPrimary text-chattrWhite hover:bg-chattrPrimaryDark disabled:bg-chattrPrimary/70 dark:bg-chattrPrimaryDark dark:hover:bg-chattrPrimaryDark/90 ml-2 h-10 flex-none items-center justify-center gap-2 px-3 py-2 text-sm font-semibold outline-offset-2 disabled:cursor-not-allowed"},"Send"))}var u=t.memo((function({toggle:e,chattrBotName:a="Chattrbot"}){return t.createElement("div",{className:"dark:bg-chattrPitchBlack rounded-t-chattrRoundedLarge border-chattrGray bg-chattrWhite dark:border-chattrTextDark/10 z-40 flex h-14 w-full items-center justify-between border-b px-3 py-2"},t.createElement("div",{className:"ml-1 flex flex-[0.5] justify-start"},t.createElement("h3",{className:"text-chattrText dark:text-chattrTextDark text-sm font-semibold tracking-wide"},a)),t.createElement("div",{className:"mr-1 flex flex-[0.5] justify-end"},t.createElement("a",{onClick:e,className:"text-chattrText dark:text-chattrTextDark cursor-pointer hover:opacity-80 hover:dark:opacity-80"},t.createElement(r,null))))}));function h(){return t.createElement("svg",{className:"h-7 w-7 stroke-chattrWhite text-chattrBlack dark:text-chattrPrimary",stroke:"currentColor",fill:"currentColor",strokeWidth:"0",viewBox:"0 0 16 16",height:"1em",width:"1em",xmlns:"http://www.w3.org/2000/svg"},t.createElement("path",{d:"M5 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm4 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 1a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"}),t.createElement("path",{d:"m2.165 15.803.02-.004c1.83-.363 2.948-.842 3.468-1.105A9.06 9.06 0 0 0 8 15c4.418 0 8-3.134 8-7s-3.582-7-8-7-8 3.134-8 7c0 1.76.743 3.37 1.97 4.6a10.437 10.437 0 0 1-.524 2.318l-.003.011a10.722 10.722 0 0 1-.244.637c-.079.186.074.394.273.362a21.673 21.673 0 0 0 .693-.125zm.8-3.108a1 1 0 0 0-.287-.801C1.618 10.83 1 9.468 1 8c0-3.192 3.004-6 7-6s7 2.808 7 6c0 3.193-3.004 6-7 6a8.06 8.06 0 0 1-2.088-.272 1 1 0 0 0-.711.074c-.387.196-1.24.57-2.634.893a10.97 10.97 0 0 0 .398-2z"}))}function m({toggle:e}){return t.createElement("div",{className:"border-chattrGray dark:border-chattrTextDark/10 fixed bottom-4 right-4 z-20 flex items-center justify-center rounded-full border md:flex-1"},t.createElement("button",{onClick:e,className:"bg-chattrWhite dark:bg-chattrBlack group rounded-full p-3 shadow",type:"button",role:"button","aria-label":"Toggle Chattrbot"},t.createElement(h,null)))}var f=Object.freeze({__proto__:null,ChattrAssistantMessage:e,ChattrCloseIcon:r,ChattrContainer:a,ChattrFeed:l,ChattrForm:d,ChattrHeader:u,ChattrMessages:o,ChattrUserMessage:i,Chattrbot:function(){const{isOpen:e,toggle:r}=n(),s="Bob",[i,o]=t.useState(!1),[c,h]=t.useState(""),[f,p]=t.useState([{content:`Hey! Thanks for visiting. I'm ${s}, you can ask me anything!`,role:"assistant"}]);return e?t.createElement(a,null,t.createElement(u,{toggle:r,chattrBotName:s}),t.createElement(l,{messages:f,userName:"Visitor",chattrBotName:s,loading:i}),t.createElement(d,{message:c,setMessage:h,sendMessage:async function(t){t.preventDefault(),h(""),o(!0),p((t=>[...t,{content:c,role:"user"}]));const e=await fetch("/api/chat-gpt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:c,chattrBotName:s,chattrBotHistory:f})});let r=await e.json();r.ok&&(r.content.text?(o(!1),p((t=>[...t,{content:r.content.text,role:"assistant"}]))):(o(!1),p((t=>[...t,{content:r.error,role:"assistant"}]))))},loading:i})):t.createElement(m,{toggle:r})}});function p({key:e,content:r}){return t.createElement("div",{key:e,className:"flex justify-end"},t.createElement("div",{className:"rounded-chattrRoundedLarge bg-chattrBackgroundMuted px-3 py-2 shadow dark:bg-chattrGrayDark"},t.createElement("p",{className:"max-w-[160px] break-words text-sm font-light text-chattrText dark:text-chattrTextDark"},r)))}function g({key:e,data:r}){return r?t.createElement("div",{key:e,className:"flex justify-end"},t.createElement("div",{className:"rounded-chattrRoundedLarge bg-chattrBackgroundMuted dark:bg-chattrGrayDark px-3 py-2 shadow"},t.createElement("p",{className:"text-chattrText dark:text-chattrTextDark break-words text-sm font-light"},"Here's what i generated with your description, ",r.description,":"),t.createElement("div",{className:"rounded-chattrRoundedLarge mb-2 mt-3 overflow-hidden"},t.createElement("img",{alt:`Chattr | ${r.description}`,className:"aspect-square w-full object-cover",src:r.url,height:500,width:500})))):t.createElement(p,{key:e,content:"It looks like something went wrong while creating the image :( Try again later!"})}function y({key:e,data:r}){return r?t.createElement("div",{key:e,className:"flex justify-end"},t.createElement("div",{className:"rounded-chattrRoundedLarge bg-chattrBackgroundMuted px-3 py-2 shadow dark:bg-chattrGrayDark"},t.createElement("p",{className:"break-words text-sm font-light text-chattrText dark:text-chattrTextDark"},"Here's a video that I generated with your description,"," ",r.description,":"),t.createElement("div",{className:"mb-2 mt-3 overflow-hidden rounded-chattrRoundedLarge"},t.createElement("video",{className:"aspect-square w-full object-cover",height:320,width:576,src:r.url,loop:!0,autoPlay:!0})))):t.createElement(p,{key:e,content:"It looks like something went wrong while creating the video :( Try again later!"})}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function x(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var w={exports:{}},b=x(w.exports=function(){var t=1e3,e=6e4,r=36e5,a="millisecond",n="second",s="minute",i="hour",o="day",c="week",l="month",d="quarter",u="year",h="date",m="Invalid Date",f=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,p=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(t){var e=["th","st","nd","rd"],r=t%100;return"["+t+(e[(r-20)%10]||e[r]||e[0])+"]"}},y=function(t,e,r){var a=String(t);return!a||a.length>=e?t:""+Array(e+1-a.length).join(r)+t},x={s:y,z:function(t){var e=-t.utcOffset(),r=Math.abs(e),a=Math.floor(r/60),n=r%60;return(e<=0?"+":"-")+y(a,2,"0")+":"+y(n,2,"0")},m:function t(e,r){if(e.date()<r.date())return-t(r,e);var a=12*(r.year()-e.year())+(r.month()-e.month()),n=e.clone().add(a,l),s=r-n<0,i=e.clone().add(a+(s?-1:1),l);return+(-(a+(r-n)/(s?n-i:i-n))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:l,y:u,w:c,d:o,D:h,h:i,m:s,s:n,ms:a,Q:d}[t]||String(t||"").toLowerCase().replace(/s$/,"")},u:function(t){return void 0===t}},w="en",b={};b[w]=g;var v="$isDayjsObject",k=function(t){return t instanceof D||!(!t||!t[v])},E=function t(e,r,a){var n;if(!e)return w;if("string"==typeof e){var s=e.toLowerCase();b[s]&&(n=s),r&&(b[s]=r,n=s);var i=e.split("-");if(!n&&i.length>1)return t(i[0])}else{var o=e.name;b[o]=e,n=o}return!a&&n&&(w=n),n||!a&&w},$=function(t,e){if(k(t))return t.clone();var r="object"==typeof e?e:{};return r.date=t,r.args=arguments,new D(r)},N=x;N.l=E,N.i=k,N.w=function(t,e){return $(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var D=function(){function g(t){this.$L=E(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[v]=!0}var y=g.prototype;return y.parse=function(t){this.$d=function(t){var e=t.date,r=t.utc;if(null===e)return new Date(NaN);if(N.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var a=e.match(f);if(a){var n=a[2]-1||0,s=(a[7]||"0").substring(0,3);return r?new Date(Date.UTC(a[1],n,a[3]||1,a[4]||0,a[5]||0,a[6]||0,s)):new Date(a[1],n,a[3]||1,a[4]||0,a[5]||0,a[6]||0,s)}}return new Date(e)}(t),this.init()},y.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},y.$utils=function(){return N},y.isValid=function(){return!(this.$d.toString()===m)},y.isSame=function(t,e){var r=$(t);return this.startOf(e)<=r&&r<=this.endOf(e)},y.isAfter=function(t,e){return $(t)<this.startOf(e)},y.isBefore=function(t,e){return this.endOf(e)<$(t)},y.$g=function(t,e,r){return N.u(t)?this[e]:this.set(r,t)},y.unix=function(){return Math.floor(this.valueOf()/1e3)},y.valueOf=function(){return this.$d.getTime()},y.startOf=function(t,e){var r=this,a=!!N.u(e)||e,d=N.p(t),m=function(t,e){var n=N.w(r.$u?Date.UTC(r.$y,e,t):new Date(r.$y,e,t),r);return a?n:n.endOf(o)},f=function(t,e){return N.w(r.toDate()[t].apply(r.toDate("s"),(a?[0,0,0,0]:[23,59,59,999]).slice(e)),r)},p=this.$W,g=this.$M,y=this.$D,x="set"+(this.$u?"UTC":"");switch(d){case u:return a?m(1,0):m(31,11);case l:return a?m(1,g):m(0,g+1);case c:var w=this.$locale().weekStart||0,b=(p<w?p+7:p)-w;return m(a?y-b:y+(6-b),g);case o:case h:return f(x+"Hours",0);case i:return f(x+"Minutes",1);case s:return f(x+"Seconds",2);case n:return f(x+"Milliseconds",3);default:return this.clone()}},y.endOf=function(t){return this.startOf(t,!1)},y.$set=function(t,e){var r,c=N.p(t),d="set"+(this.$u?"UTC":""),m=(r={},r[o]=d+"Date",r[h]=d+"Date",r[l]=d+"Month",r[u]=d+"FullYear",r[i]=d+"Hours",r[s]=d+"Minutes",r[n]=d+"Seconds",r[a]=d+"Milliseconds",r)[c],f=c===o?this.$D+(e-this.$W):e;if(c===l||c===u){var p=this.clone().set(h,1);p.$d[m](f),p.init(),this.$d=p.set(h,Math.min(this.$D,p.daysInMonth())).$d}else m&&this.$d[m](f);return this.init(),this},y.set=function(t,e){return this.clone().$set(t,e)},y.get=function(t){return this[N.p(t)]()},y.add=function(a,d){var h,m=this;a=Number(a);var f=N.p(d),p=function(t){var e=$(m);return N.w(e.date(e.date()+Math.round(t*a)),m)};if(f===l)return this.set(l,this.$M+a);if(f===u)return this.set(u,this.$y+a);if(f===o)return p(1);if(f===c)return p(7);var g=(h={},h[s]=e,h[i]=r,h[n]=t,h)[f]||1,y=this.$d.getTime()+a*g;return N.w(y,this)},y.subtract=function(t,e){return this.add(-1*t,e)},y.format=function(t){var e=this,r=this.$locale();if(!this.isValid())return r.invalidDate||m;var a=t||"YYYY-MM-DDTHH:mm:ssZ",n=N.z(this),s=this.$H,i=this.$m,o=this.$M,c=r.weekdays,l=r.months,d=r.meridiem,u=function(t,r,n,s){return t&&(t[r]||t(e,a))||n[r].slice(0,s)},h=function(t){return N.s(s%12||12,t,"0")},f=d||function(t,e,r){var a=t<12?"AM":"PM";return r?a.toLowerCase():a};return a.replace(p,(function(t,a){return a||function(t){switch(t){case"YY":return String(e.$y).slice(-2);case"YYYY":return N.s(e.$y,4,"0");case"M":return o+1;case"MM":return N.s(o+1,2,"0");case"MMM":return u(r.monthsShort,o,l,3);case"MMMM":return u(l,o);case"D":return e.$D;case"DD":return N.s(e.$D,2,"0");case"d":return String(e.$W);case"dd":return u(r.weekdaysMin,e.$W,c,2);case"ddd":return u(r.weekdaysShort,e.$W,c,3);case"dddd":return c[e.$W];case"H":return String(s);case"HH":return N.s(s,2,"0");case"h":return h(1);case"hh":return h(2);case"a":return f(s,i,!0);case"A":return f(s,i,!1);case"m":return String(i);case"mm":return N.s(i,2,"0");case"s":return String(e.$s);case"ss":return N.s(e.$s,2,"0");case"SSS":return N.s(e.$ms,3,"0");case"Z":return n}return null}(t)||n.replace(":","")}))},y.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},y.diff=function(a,h,m){var f,p=this,g=N.p(h),y=$(a),x=(y.utcOffset()-this.utcOffset())*e,w=this-y,b=function(){return N.m(p,y)};switch(g){case u:f=b()/12;break;case l:f=b();break;case d:f=b()/3;break;case c:f=(w-x)/6048e5;break;case o:f=(w-x)/864e5;break;case i:f=w/r;break;case s:f=w/e;break;case n:f=w/t;break;default:f=w}return m?f:N.a(f)},y.daysInMonth=function(){return this.endOf(l).$D},y.$locale=function(){return b[this.$L]},y.locale=function(t,e){if(!t)return this.$L;var r=this.clone(),a=E(t,e,!0);return a&&(r.$L=a),r},y.clone=function(){return N.w(this.$d,this)},y.toDate=function(){return new Date(this.valueOf())},y.toJSON=function(){return this.isValid()?this.toISOString():null},y.toISOString=function(){return this.$d.toISOString()},y.toString=function(){return this.$d.toUTCString()},g}(),T=D.prototype;return $.prototype=T,[["$ms",a],["$s",n],["$m",s],["$H",i],["$W",o],["$M",l],["$y",u],["$D",h]].forEach((function(t){T[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),$.extend=function(t,e){return t.$i||(t(e,D,$),t.$i=!0),$},$.locale=E,$.isDayjs=k,$.unix=function(t){return $(1e3*t)},$.en=b[w],$.Ls=b,$.p={},$}());function v({key:e,data:r}){const a=Date.now(),n=b(a).format("dddd, MMMM DD, YYYY");return r?t.createElement("div",{key:e,className:"flex justify-end"},t.createElement("div",{className:"w-full rounded-chattrRoundedLarge bg-chattrBackgroundMuted px-3 py-2 shadow dark:bg-chattrGrayDark"},t.createElement("p",{className:"break-words text-sm font-light text-chattrText dark:text-chattrTextDark"},"Here's the most recent weather data I found for ",r.location,":"),t.createElement("div",{className:"mb-2 mt-3 flex w-full flex-col rounded-chattrRoundedLarge bg-chattrPrimary p-4 dark:bg-chattrPrimaryDark"},t.createElement("div",{className:"text-center"},t.createElement("p",{className:"text-xl font-bold text-chattrWhite"},r.location,", ",r.state),t.createElement("p",{className:"text-sm font-light text-chattrBackgroundMuted"},n)),t.createElement("div",{className:"flex items-center justify-center py-3"},t.createElement("img",{alt:"Weather Icon",className:"h-16 w-16",src:r.url,height:100,width:100})),t.createElement("div",{className:"flex flex-col items-center justify-center"},t.createElement("p",{className:"text-4xl font-bold text-chattrWhite"},r.temperature),t.createElement("p",{className:"mt-2 text-sm font-light text-chattrGray"},r.celcius)),t.createElement("div",{className:"mt-6 flex flex-row justify-between"},t.createElement("div",{className:"flex flex-col items-center"},t.createElement("p",{className:"text-sm font-semibold text-chattrWhite"},"Wind"),t.createElement("p",{className:"text-sm font-light text-chattrGray"},r.wind)),t.createElement("div",{className:"flex flex-col items-center"},t.createElement("p",{className:"text-sm font-semibold text-chattrWhite"},"Humidity"),t.createElement("p",{className:"text-sm font-light text-chattrGray"},r.humidity)),t.createElement("div",{className:"flex flex-col items-center"},t.createElement("p",{className:"text-sm font-semibold text-chattrWhite"},"Clouds"),t.createElement("p",{className:"text-sm font-light text-chattrGray"},r.clouds)))))):t.createElement(p,{key:e,content:"It looks like something went wrong while fetching the weather :( Try again later!"})}function k(){return t.createElement("svg",{stroke:"currentColor",fill:"currentColor",strokeWidth:"0",version:"1.1",viewBox:"0 0 21 21",height:"1em",width:"1em",xmlns:"http://www.w3.org/2000/svg"},t.createElement("path",{d:"M9.207 8.5l6.646 6.646-0.707 0.707-6.646-6.646-6.646 6.646-0.707-0.707 6.646-6.646-6.647-6.646 0.707-0.707 6.647 6.646 6.646-6.646 0.707 0.707-6.646 6.646z"}))}function E({children:e}){return t.createElement("div",{className:"border-chattrGray dark:border-chattrGrayDark dark:bg-chattrBlack rounded-chattrRoundedMedium bg-chattrWhite dark:text-chattrTextDark fixed bottom-4 right-4 z-20 h-96 max-h-96 w-[315px] border"},e)}function $({key:e,content:r}){return t.createElement("div",{key:e,className:"flex justify-start"},t.createElement("div",{className:"rounded-chattrRoundedLarge bg-chattrPrimary px-3 py-2 shadow dark:bg-chattrPrimaryDark"},t.createElement("p",{className:"max-w-[160px] break-words text-sm font-light text-chattrTextDark"},r)))}var N=t.memo((function({message:{content:e,role:r,key:a,ui:n,data:s}}){return t.createElement("div",{className:"px-4 py-2"},"assistant"===r&&"default"===n?t.createElement(p,{key:a,content:e}):"assistant"===r&&"weather"===n?t.createElement(v,{key:a,data:s}):"assistant"===r&&"image"===n?t.createElement(g,{key:a,data:s}):"assistant"===r&&"video"===n?t.createElement(y,{key:a,data:s}):t.createElement($,{key:a,content:e}))}));function D(){return t.createElement("div",{className:"px-3 py-2"},t.createElement("div",{className:"mb-3 flex justify-end"},t.createElement("div",{className:"rounded-chattrRoundedLarge bg-chattrBackgroundMuted dark:bg-chattrGrayDark inline-flex px-0.5 py-1.5 shadow"},t.createElement("div",{className:"flex items-center justify-center px-3 py-2"},t.createElement("div",{className:"chattrDotMinimalist animate-chattrLoader"}),t.createElement("div",{className:"chattrDotMinimalist animation-delay-200 animate-chattrLoader"}),t.createElement("div",{className:"chattrDotMinimalist animation-delay-400 animate-chattrLoader"})))))}var T=t.memo((function({messages:e,loading:r}){const a=s(e);return t.createElement("div",{ref:a,className:"max-h-[245px] min-h-[245px] flex-auto overflow-y-scroll"},e.map(((e,r)=>t.createElement(N,{key:`${e.role}_message_${r}`,message:e}))),r&&t.createElement(D,null))}));function M({setMessage:e,sendMessage:r,message:a,loading:n}){return t.createElement("div",{className:"absolute bottom-0 flex h-16 w-full items-center p-4"},t.createElement("form",{onSubmit:t=>r(t),className:"flex w-full items-center justify-between space-x-2"},t.createElement("input",{className:"rounded-chattrRoundedSmall border-chattrGray text-chattrText focus:border-chattrPrimary focus-visible:ring-chattrPrimary dark:border-chattrGrayDark dark:text-chattrTextDark flex h-9 w-full flex-auto border bg-transparent px-2 py-1 text-sm font-light shadow-sm transition-colors placeholder:bg-transparent focus-visible:outline-none focus-visible:ring-1 disabled:cursor-not-allowed disabled:opacity-50",type:"text",required:!0,autoComplete:"off",autoCorrect:"off",placeholder:"Ask a question...",value:a,onChange:({target:{value:t}})=>e(t)}),t.createElement("button",{className:"rounded-chattrRoundedSmall bg-chattrBackgroundMuted text-chattrText focus-visible:ring-chattrPrimary dark:bg-chattrGrayDark dark:text-chattrTextDark inline-flex h-9 w-9 items-center justify-center whitespace-nowrap text-sm font-medium shadow transition-colors hover:opacity-80 focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:opacity-50",type:"submit",disabled:n},t.createElement("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4"},t.createElement("path",{d:"M1.20308 1.04312C1.00481 0.954998 0.772341 1.0048 0.627577 1.16641C0.482813 1.32802 0.458794 1.56455 0.568117 1.75196L3.92115 7.50002L0.568117 13.2481C0.458794 13.4355 0.482813 13.672 0.627577 13.8336C0.772341 13.9952 1.00481 14.045 1.20308 13.9569L14.7031 7.95693C14.8836 7.87668 15 7.69762 15 7.50002C15 7.30243 14.8836 7.12337 14.7031 7.04312L1.20308 1.04312ZM4.84553 7.10002L2.21234 2.586L13.2689 7.50002L2.21234 12.414L4.84552 7.90002H9C9.22092 7.90002 9.4 7.72094 9.4 7.50002C9.4 7.27911 9.22092 7.10002 9 7.10002H4.84553Z",fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd"})),t.createElement("span",{className:"sr-only"},"Send"))))}function C({chattrBotName:e,role:r,toggle:a}){return t.createElement("div",{className:"flex flex-row items-center space-y-1.5 p-4"},t.createElement("div",{className:"flex items-center space-x-4"},t.createElement("span",{className:"relative flex h-10 w-10 flex-none items-center justify-center rounded-full border border-chattrGray dark:border dark:border-chattrGrayDark"},t.createElement("img",{alt:"Chatbot Image",width:28,height:28,className:"h-9 w-9 rounded-full",src:"/bot.webp"})),t.createElement("div",null,t.createElement("p",{className:"text-sm font-medium leading-none text-chattrText dark:text-chattrTextDark"},e),t.createElement("p",{className:"text-sm font-light text-chattrSecondary dark:text-chattrSecondaryDark"},r))),t.createElement("button",{onClick:a,className:"ml-auto inline-flex h-5 w-5 items-start justify-end text-sm font-medium hover:opacity-60"},t.createElement(k,null)))}var j=Object.freeze({__proto__:null,ChattrAssistantImage:g,ChattrAssistantMessage:p,ChattrAssistantVideo:y,ChattrAssistantWeather:v,ChattrCloseIcon:k,ChattrContainer:E,ChattrFeed:T,ChattrForm:M,ChattrHeader:C,ChattrLoader:D,ChattrMessages:N,ChattrUserMessage:$,Chattrbot:function(){const{isOpen:e,toggle:r}=n(),a="Chattrbot",[s,i]=t.useState(!1),[o,c]=t.useState(""),[l,d]=t.useState([{ui:"default",content:`Hey! Thanks for visiting. I'm ${a}, you can ask me anything!`,role:"assistant"}]);return e?t.createElement(E,null,t.createElement(C,{chattrBotName:a,role:"Assistant",toggle:r}),t.createElement(T,{messages:l,loading:s}),t.createElement(M,{message:o,setMessage:c,sendMessage:async function(t){t.preventDefault(),c(""),i(!0),d((t=>[...t,{ui:"default",content:o,role:"user"}]));const e=await fetch("/api/function-calling",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:o,chattrBotName:a,chattrBotHistory:l})});let r=await e.json();r.ok?r.content.text?(i(!1),d((t=>[...t,{ui:"default",content:r.content.text,role:"assistant"}]))):r.content.function_response&&(i(!1),d((t=>[...t,{ui:r.ui,data:r.content.function_response,role:"assistant"}]))):(i(!1),d((t=>[...t,{ui:"default",content:r.error,role:"assistant"}])))},loading:s})):t.createElement(m,{toggle:r})}});var S=class extends Error{constructor(t,e,r){super(t),this.name="ApiError",this.request=e,this.response=r}};var _=class t{constructor(t,e,r=null){this.owner=t,this.name=e,this.version=r}static parse(e){const r=e.match(/^(?<owner>[^/]+)\/(?<name>[^/:]+)(:(?<version>.+))?$/);if(!r)throw new Error(`Invalid reference to model version: ${e}. Expected format: owner/name or owner/name:version`);const{owner:a,name:n,version:s}=r.groups;return new t(a,n,s)}};const O=S;var L={withAutomaticRetries:async function(t,e={}){const r=e.shouldRetry||(()=>!1),a=e.maxRetries||5,n=e.interval||500,s=e.jitter||100,i=t=>new Promise((e=>setTimeout(e,t)));let o=0;do{let c=n*2**o+Math.random()*s;try{const e=await t();if(e.ok||!r(e))return e}catch(t){if(t instanceof O){const e=t.response.headers.get("Retry-After");if(e)if(Number.isInteger(e))c=1e3*e;else{const t=new Date(e);Number.isNaN(t.getTime())||(c=t.getTime()-(new Date).getTime())}}}Number.isInteger(a)&&a>0&&(Number.isInteger(c)&&c>0&&await i(n*2**(e.maxRetries-a)),o+=1)}while(o<a);return t()}};var P={get:async function(t){return(await this.request(`/collections/${t}`,{method:"GET"})).json()},list:async function(){return(await this.request("/collections",{method:"GET"})).json()}};var R={predictions:{create:async function(t,e,r){const{stream:a,...n}=r;if(n.webhook)try{new URL(n.webhook)}catch(t){throw new Error("Invalid webhook URL")}return(await this.request(`/deployments/${t}/${e}/predictions`,{method:"POST",data:{...n,stream:a}})).json()}}};var B={list:async function(){return(await this.request("/hardware",{method:"GET"})).json()}};var G={get:async function(t,e){return(await this.request(`/models/${t}/${e}`,{method:"GET"})).json()},list:async function(){return(await this.request("/models",{method:"GET"})).json()},create:async function(t,e,r){const a={owner:t,name:e,...r};return(await this.request("/models",{method:"POST",data:a})).json()},versions:{list:async function(t,e){return(await this.request(`/models/${t}/${e}/versions`,{method:"GET"})).json()},get:async function(t,e,r){return(await this.request(`/models/${t}/${e}/versions/${r}`,{method:"GET"})).json()}},predictions:{create:async function(t,e,r){const{stream:a,...n}=r;return(await this.request(`/models/${t}/${e}/predictions`,{method:"POST",data:{...n,stream:a}})).json()}}};var A={create:async function(t){const{stream:e,...r}=t;if(r.webhook)try{new URL(r.webhook)}catch(t){throw new Error("Invalid webhook URL")}return(await this.request("/predictions",{method:"POST",data:{...r,stream:e}})).json()},get:async function(t){return(await this.request(`/predictions/${t}`,{method:"GET"})).json()},cancel:async function(t){return(await this.request(`/predictions/${t}/cancel`,{method:"POST"})).json()},list:async function(){return(await this.request("/predictions",{method:"GET"})).json()}};var I={create:async function(t,e,r,a){const{...n}=a;if(n.webhook)try{new URL(n.webhook)}catch(t){throw new Error("Invalid webhook URL")}return(await this.request(`/models/${t}/${e}/versions/${r}/trainings`,{method:"POST",data:n})).json()},get:async function(t){return(await this.request(`/trainings/${t}`,{method:"GET"})).json()},cancel:async function(t){return(await this.request(`/trainings/${t}/cancel`,{method:"POST"})).json()},list:async function(){return(await this.request("/trainings",{method:"GET"})).json()}},q={name:"replicate",version:"0.24.0",description:"JavaScript client for Replicate",repository:"github:replicate/replicate-javascript",homepage:"https://github.com/replicate/replicate-javascript#readme",bugs:"https://github.com/replicate/replicate-javascript/issues",license:"Apache-2.0",main:"index.js",engines:{node:">=18.0.0",npm:">=7.19.0",git:">=2.11.0",yarn:">=1.7.0"},scripts:{check:"tsc",format:"biome format . --write",lint:"biome lint .",test:"jest"},devDependencies:{"@biomejs/biome":"^1.4.1","@types/jest":"^29.5.3","@typescript-eslint/eslint-plugin":"^5.56.0","cross-fetch":"^3.1.5",jest:"^29.6.2",nock:"^13.3.0","ts-jest":"^29.1.0",typescript:"^5.0.2"}};const W=S,H=_,{withAutomaticRetries:z}=L,U=P,Y=R,F=B,J=G,V=A,Z=I,K=q;var Q=class{constructor(t={}){this.auth=t.auth||process.env.REPLICATE_API_TOKEN,this.userAgent=t.userAgent||`replicate-javascript/${K.version}`,this.baseUrl=t.baseUrl||"https://api.replicate.com/v1",this.fetch=t.fetch||globalThis.fetch,this.collections={list:U.list.bind(this),get:U.get.bind(this)},this.deployments={predictions:{create:Y.predictions.create.bind(this)}},this.hardware={list:F.list.bind(this)},this.models={get:J.get.bind(this),list:J.list.bind(this),create:J.create.bind(this),versions:{list:J.versions.list.bind(this),get:J.versions.get.bind(this)},predictions:{create:J.predictions.create.bind(this)}},this.predictions={create:V.create.bind(this),get:V.get.bind(this),cancel:V.cancel.bind(this),list:V.list.bind(this)},this.trainings={create:Z.create.bind(this),get:Z.get.bind(this),cancel:Z.cancel.bind(this),list:Z.list.bind(this)}}async run(t,e,r){const{wait:a,...n}=e,s=H.parse(t);let i;i=s.version?await this.predictions.create({...n,version:s.version}):await this.models.predictions.create(s.owner,s.name,n),r&&r(i);const{signal:o}=e;if(i=await this.wait(i,a||{},(async t=>(r&&r(t),!(!o||!o.aborted)&&(await this.predictions.cancel(t.id),!0)))),r&&r(i),"failed"===i.status)throw new Error(`Prediction failed: ${i.error}`);return i.output}async request(t,e){const{auth:r,baseUrl:a,userAgent:n}=this;let s;s=t instanceof URL?t:new URL(t.startsWith("/")?t.slice(1):t,a.endsWith("/")?a:`${a}/`);const{method:i="GET",params:o={},data:c}=e;for(const[t,e]of Object.entries(o))s.searchParams.append(t,e);const l=new Headers;if(r&&l.append("Authorization",`Token ${r}`),l.append("Content-Type","application/json"),l.append("User-Agent",n),e.headers)for(const[t,r]of e.headers.entries())l.append(t,r);const d={method:i,headers:l,body:c?JSON.stringify(c):void 0},u="GET"===i?t=>429===t.status||t.status>=500:t=>429===t.status,h=this.fetch,m=await z((async()=>h(s,d)),{shouldRetry:u});if(!m.ok){const t=new Request(s,d),e=await m.text();throw new W(`Request to ${s} failed with status ${m.status} ${m.statusText}: ${e}.`,t,m)}return m}async*paginate(t){const e=await t();if(yield e.results,e.next){const t=()=>this.request(e.next,{method:"GET"}).then((t=>t.json()));yield*this.paginate(t)}}async wait(t,e,r){const{id:a}=t;if(!a)throw new Error("Invalid prediction");if("succeeded"===t.status||"failed"===t.status||"canceled"===t.status)return t;const n=t=>new Promise((e=>setTimeout(e,t))),s=e&&e.interval||500;let i=await this.predictions.get(a);for(;"succeeded"!==i.status&&"failed"!==i.status&&"canceled"!==i.status&&(!r||!0!==await r(i));)await n(s),i=await this.predictions.get(t.id);if("failed"===i.status)throw new Error(`Prediction failed: ${i.error}`);return i}},X=x(Q);exports.ChattrOpenButton=m,exports.ChattrOpenIcon=h,exports.Default=f,exports.Minimalist=j,exports.create_image=async function(t){try{const e={model:"dall-e-3",prompt:t,n:1,size:"1024x1024",response_format:"url",quality:"hd"},r=await fetch("https://api.openai.com/v1/images/generations",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${process.env.OPENAI_API_KEY}`},method:"POST",body:JSON.stringify(e)});if(!r.ok)throw new Error("Image data not available");return{description:t,url:`${(await r.json()).data[0].url}`}}catch(t){throw console.log(t),t}},exports.create_video=async function(t){try{const e=new X({auth:process.env.REPLICATE_API_TOKEN}),r=await e.run("anotherjesse/zeroscope-v2-xl:1f0dd155aeff719af56f4a2e516c7f7d4c91a38c7b8e9e81808e7c71bde9b868",{input:{fps:24,fast:!0,width:576,height:320,prompt:t,num_frames:24,guidance_scale:17.5,num_inference_steps:50}});if(!r)throw new Error("Video data not available");return{description:t,url:r}}catch(t){throw console.log(t),t}},exports.get_current_weather=async function(t,e){try{const r=await fetch(`http://api.openweathermap.org/data/2.5/weather?zip=${t}&appid=${process.env.WEATHER_APP_ID}&units=imperial`);if(!r.ok)throw new Error("Weather data not available");const a=await r.json(),n=5*(a.main.temp-32)/9;return{temperature:`${a.main.temp}°F`,celcius:Math.round(100*n)/100+"°C",location:`${a.name}`,url:`https://openweathermap.org/img/wn/${a.weather[0].icon}@2x.png`,description:`${a.weather[0].description}`,humidity:`${a.main.humidity}%`,wind:`${a.wind.speed}m/h`,clouds:`${a.clouds.all}%`,state:e}}catch(t){throw console.log(t),t}},exports.useChattr=n,exports.useScroll=s;
//# sourceMappingURL=index.js.map