@pickaxeproject/react 5.6.1-beta.6 → 5.6.1-beta.8

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.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const e=e=>{try{const t=document.cookie.split("; ");for(const o of t){const[t,r]=o.split("=");if(t===e)return r}return null}catch(e){return console.error("[pxe] failed to get cookie",e),null}};exports.deleteAuthToken=e=>{try{if("undefined"==typeof window)return;localStorage.removeItem(e)}catch(e){console.error("[pxe] failed to delete auth token",e)}},exports.deleteCookie=e=>{document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},exports.extractUrlsFromText=e=>{const t=e.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(t))},exports.formatBytes=(e,t=2)=>{if(!+e)return"0 Bytes";const o=t<0?0:t,r=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,r)).toFixed(o))} ${["Bytes","KB","MB","PB","EB"][r]}`},exports.generateId=(e,t="",o="")=>{let r="";for(let t=0;t<e;t++){r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return t+r+o},exports.getAuthToken=t=>{try{if("undefined"==typeof window)return null;let o=null;return o=new URLSearchParams(window.location.search).get("pxtoken"),o||(o=localStorage.getItem(`PXE-token-${t}`)),o||(o=e(`PXE-token-${t}`)),o||(o=e(`__Secure-PS-${t}.session-token`)),o?decodeURIComponent(o):null}catch(e){return null}},exports.getCookie=e,exports.isInIframe=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(e){return!0}},exports.mergeRefs=function(...e){return t=>{for(const o of e)o&&("function"==typeof o?o(t):o.current=t)}},exports.randomStr=(e,t=!1)=>{let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";t&&(o=o.replace(/[0-9]/g,""));let r="";for(let t=0;t<e;t++)r+=o.charAt(Math.floor(Math.random()*o.length));return r},exports.safeJSONParse=e=>{try{return JSON.parse(e)}catch(e){return null}},exports.setAuthToken=(e,t)=>{try{if("undefined"==typeof window)return;localStorage.setItem(e,t)}catch(e){console.error("[pxe] failed to set auth token",e)}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tldts");const t="PXE-uid",r=(e,t=!1)=>{let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";t&&(r=r.replace(/[0-9]/g,""));let o="";for(let t=0;t<e;t++)o+=r.charAt(Math.floor(Math.random()*r.length));return o},o=e=>{try{const t=document.cookie.split("; ");for(const r of t){const[t,o]=r.split("=");if(t===e)return o}return null}catch(e){return console.error("[pxe] failed to get cookie",e),null}};exports.COOKIE_USER_ID=t,exports.deleteAuthToken=e=>{try{if("undefined"==typeof window)return;localStorage.removeItem(e)}catch(e){console.error("[pxe] failed to delete auth token",e)}},exports.deleteCookie=e=>{document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},exports.extractUrlsFromText=e=>{const t=e.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(t))},exports.formatBytes=(e,t=2)=>{if(!+e)return"0 Bytes";const r=t<0?0:t,o=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,o)).toFixed(r))} ${["Bytes","KB","MB","PB","EB"][o]}`},exports.generateId=(e,t="",r="")=>{let o="";for(let t=0;t<e;t++){o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return t+o+r},exports.getAuthToken=e=>{try{if("undefined"==typeof window)return null;let t=null;return t=new URLSearchParams(window.location.search).get("pxtoken"),t||(t=localStorage.getItem(`PXE-token-${e}`)),t||(t=o(`PXE-token-${e}`)),t||(t=o(`__Secure-PS-${e}.session-token`)),t?decodeURIComponent(t):null}catch(e){return null}},exports.getCookie=o,exports.initializeEmbedUserId=()=>{try{const n=o(t);if(!n){const o=r(28),n=new Date;n.setFullYear(n.getFullYear()+1);let s=window.location.hostname;const l=e.parse(s).domain;if(l)s=`.${l}`;else{const e=s.split(":")[0],t=e.split(".");s=e,t.length>=2&&(s=`.${t.slice(-2).join(".")}`)}return document.cookie=`${t}=${o};Path=/; Domain=${s}; Expires=${n.toUTCString()}`,o}return n}catch(e){return console.error("[pxe-embed] failed to initialized embed user id",e),r(28)}},exports.isInIframe=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(e){return!0}},exports.mergeRefs=function(...e){return t=>{for(const r of e)r&&("function"==typeof r?r(t):r.current=t)}},exports.randomStr=r,exports.safeJSONParse=e=>{try{return JSON.parse(e)}catch(e){return null}},exports.setAuthToken=(e,t)=>{try{if("undefined"==typeof window)return;localStorage.setItem(e,t)}catch(e){console.error("[pxe] failed to set auth token",e)}};
@@ -0,0 +1 @@
1
+ "use strict";function e(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}})),r.default=e,Object.freeze(r)}Object.defineProperty(exports,"__esModule",{value:!0});var r,t=e(require("react"));function n(){return n=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},n.apply(null,arguments)}var a=e=>t.createElement("svg",n({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 18 18"},e),r||(r=t.createElement("path",{fill:"currentColor",d:"m11.06 6.02.92.92L2.92 16H2v-.92zM14.66 0c-.25 0-.51.1-.7.29l-1.83 1.83 3.75 3.75 1.83-1.83a.996.996 0 0 0 0-1.41L15.37.29c-.2-.2-.45-.29-.71-.29m-3.6 3.19L0 14.25V18h3.75L14.81 6.94z"})));exports.default=a;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react");require("../../../node_modules/.pnpm/regenerator-runtime@0.14.1/node_modules/regenerator-runtime/runtime.js");var n=require("react-speech-recognition"),i=require("../../../hooks/pickaxe/usePickaxeContext.js"),r=require("../../../hooks/pickaxe/useResponseContext.js"),o=require("../../../hooks/studio/useStyleInput.js"),a=require("../../../hooks/studio/useStyleFontSize.js"),l=require("../../../hooks/pickaxe/useConversation.js"),c=require("../../../hooks/pickaxe/useDimensionContext.js"),u=require("../Addons/Auth/hooks/useAuthContext.js"),d=require("../Addons/Document/hooks/useDocument.js"),f=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),m=require("../../../hooks/core/useHover.js"),h=require("../../../hooks/core/useMediaQuery.js"),g=require("../../../common/documents.js"),v=require("eventsource-parser"),y=require("../../Icons/attach-vertical.svg.js"),b=require("../../Icons/arrow-right.svg.js"),x=require("../../Icons/microphone.svg.js"),j=require("../../Icons/stop.svg.js"),w=require("../Addons/Document/List.js"),O=require("../../Core/Textarea.js"),S=require("../../Core/ErrorAlert.js"),k=require("../../../common/error.js"),C=require("../../../common/cn.js");function I(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var N=I(n);const _=s.forwardRef((({resubmitPrompt:I,onFocus:_,onBlur:E,onInputHeightChange:A,initSmitheryAuthData:q},R)=>{var T,P,D;const{origin:L,pickaxeId:H,sessionId:M,sender:F,senderType:$,portalId:W,deploymentId:B,deploymentType:J,pickaxe:U,styles:V,colors:K,locale:X,forceMobile:z,isNewChat:G,isRtl:Q,isEmailLogin:Y,isShowFeedbackMessage:Z,setIsNewChat:ee,setIsShowIceBreaker:te,onGenerateComplete:se}=i.usePickaxeContext(),{token:ne,isLoggedOut:ie,isSent:re}=u.useAuthContext(),{messages:oe,isGenerating:ae,setMessages:le,setStatus:ce,setLimitData:ue,setError:de}=r.useResponseContext(),{documents:fe,isUploading:pe,documentError:me,onFileUpload:he,setDocuments:ge,setDocumentError:ve}=d.useDocument(),{scrollStartSession:ye,scrollEndSession:be,scrollToBottom:xe}=f.useScroll({auto:!0}),{artifacts:je,currentPopupType:we,setArtifacts:Oe,setCurrentArtifact:Se}=p.useArtifactContext(),{height:ke}=c.useDimensionContext(),Ce=l.useConversation(),[Ie,Ne]=s.useState(""),[_e,Ee]=s.useState(!1),[Ae,qe]=s.useState(!1),Re=s.useRef(null),Te=s.useRef(""),Pe=s.useRef(null),De=s.useRef(null),Le=s.useRef(null),He=s.useRef(null),Me=s.useRef(null),Fe=Math.max(.4*ke,100),{transcript:$e,listening:We,resetTranscript:Be,browserSupportsSpeechRecognition:Je}=n.useSpeechRecognition(),[Ue]=h.useMediaQuery("(max-width: 480px)"),Ve=m.useHover(),{isHover:Ke}=Ve,Xe=e.__rest(Ve,["isHover"]),ze=m.useHover(),{isHover:Ge}=ze,Qe=e.__rest(ze,["isHover"]),Ye=m.useHover(),{isHover:Ze}=Ye,et=e.__rest(Ye,["isHover"]),tt=a.useStyleFontSize(),st=o.useStyleInput(),nt="undefined"!=typeof window?window.location.hostname:"",it="undefined"!=typeof window?window.location.href:"",rt="undefined"!=typeof window&&window.self!==window.top,ot=nt.includes("pickaxe.co")&&!it.includes("https://studio.pickaxe.co/_embed")&&!rt,at=null===(T=null==U?void 0:U.documentuploadtype)||void 0===T?void 0:T.startsWith("enduserupload"),lt=Je&&(null==U?void 0:U.enablevoicetotext),ct="chat-input"===J&&G&&!re,ut="chat-input"===J&&Y&&ie&&re,dt=null!==(P=null==U?void 0:U.placeholdertext)&&void 0!==P?P:Q?"بماذا تريد أن تتحدث؟":"What do you want to talk about?",ft=_e||Ae,pt=s.useMemo((()=>{var e,t,s;return!!G&&(!!U&&(!Ce.isLoading&&(!((null!==(t=null===(e=Ce.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=U.icebreakers)||void 0===s?void 0:s.length)&&(!Z&&!ct)))))}),[U,G,Z,ct,Ce.data,Ce.isLoading]),mt=s.useMemo((()=>{if(ae||pe)return!1;const e=fe.length>0&&fe.every((e=>"finished"===e.status));return!(!Ie.trim()&&!e)&&fe.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[ae,pe,Ie,fe]);s.useImperativeHandle(R,(()=>({onSubmit:ht}))),s.useEffect((()=>{te(pt)}),[pt]),s.useEffect((()=>{var e;if(I){const t=Array.from(oe),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;ht(s,!0)}}),[I]),s.useEffect((()=>{if(!He.current||!A)return;const e=new ResizeObserver((e=>{for(const t of e)A(t.contentRect.height)}));return e.observe(He.current),()=>{e.disconnect()}}),[A]),s.useEffect((()=>{if(!We)return;const e=Te.current?`${Te.current} `:"";Ne(`${e}${$e}`)}),[$e,We]),s.useEffect((()=>{if(!De.current)return;(()=>{if(!De.current)return;let e=De.current.scrollHeight>52;Ie.includes("\n")||fe.length?e=!0:Ie.trim()||(e=!1),Ee(e)})()}),[Ie,fe]),s.useEffect((()=>{const e=De.current,t=Le.current;if(!e||!t||_e||Ie.includes("\n"))return void qe(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,i=document.createElement("span");Object.assign(i.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),i.textContent=Ie||dt,document.body.appendChild(i);const r=i.offsetWidth;i.remove();const o=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-o-a-t.offsetWidth;qe(r>l)}),[Ie,_e,dt]);const ht=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i;try{if(ae||pe)return;const r=fe.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),o=r.map((e=>e.documentId)).filter(Boolean),a=r.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=o.length>0,c=null!=t?t:Ie;if(!c&&!l)return;de(""),ve(""),ue(null),Ne(""),ee(!1),ce("fetching"),ye(),xe();const u=null!==(n=null===(e=null==U?void 0:U.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&o.length>0,d=[...s?Array.from(oe.slice(0,oe.length-1)):Array.from(oe),...s?[]:[{id:oe.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:u?o:[]}],{id:oe.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];le(d),xe(),u&&ge([]);const f=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign(Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:L,pickaxeId:H,sessionId:M,senderType:$,value:c},u&&{documentIds:o}),F&&{sender:F}),ne&&{studioSessionToken:ne}),W&&{portalId:W}),B&&{deploymentId:B}),a.length>0&&{uploadedModelImages:a}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),ot&&{credentials:"include"})),p=yield f.json();if(!p.success){const e=new Error(p.error||"Failed to start generation");throw p.limitData&&(e.limitData=p.limitData),e}const m=p.submissionId;ce("streaming"),Me.current=new AbortController;const h=d.length-1,g=[];let y=[...null!=je?je:[]],b=0,x=!1,j="";for(;!x;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${m}?index=${b}`,{signal:null===(i=Me.current)||void 0===i?void 0:i.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();Pe.current=t;const s=new TextDecoder,n=v.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&b++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data).error||"Something went wrong.";return de(t),void(x=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&q){const e=n.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw x=!0,q({smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw x=!0,q({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)j="",g.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)j+=n.delta,g[g.length-1].content=j;else if("text-end"===n.type)j="";else if("reasoning-start"===n.type)j="",g.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)j+=n.delta,g[g.length-1].content=j;else if("reasoning-end"===n.type)j="";else if(n.type.startsWith("data-")){const e=n;g.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}le([...d.slice(0,h),Object.assign(Object.assign({},d[d.length-1]),{id:oe.length+1,role:"assistant",parts:g})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);y=y.filter((e=>!(e.id===t.id&&e.version===t.version))),y.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Oe([...y]),we.startsWith("inline")||Se({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);y=y.filter((e=>!(e.id===t.id&&e.version===t.version))),y.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Oe(y),we.startsWith("inline")||Se({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);y=y.filter((e=>!(e.id===t.id&&e.version===t.version))),y.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Oe(y),we.startsWith("inline")||Se({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");y=y.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Oe(y)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Oe(y.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);de(t.error||"Something went wrong, please try again.")}else"stop"===e.event&&(x=!0)}else x=!0}});for(;;){const{value:e,done:i}=yield t.read();if(i)break;n.feed(s.decode(e))}x||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(x=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==se||se(M)}catch(e){if(e.limitData)ue(e.limitData),de("");else{let t=k.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t="Oops! We're experiencing high traffic at the moment. Please try again later."),de(t)}}finally{xe(),ce("idle"),be(),Pe.current=null}}));return ut?null:t.jsx("div",Object.assign({className:C.default("flex w-full flex-shrink-0 flex-col items-center",!ct&&"px-4 pb-8"),dir:Q?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:He,className:C.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===V.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},st),{maxHeight:`${Fe}px`,overflowY:"auto"})},{children:[We&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(D=K.accent)&&void 0!==D?D:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:K.text+"90"}},{children:"Listening..."}))]})),!ae&&fe.length>0&&t.jsx(w.default,{className:"p-4 pb-0",isDisabled:ae}),t.jsx(O.default,Object.assign({ref:De,className:C.default(tt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Ie.trim()&&!Ie.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Q?"text-right":"text-left",ft&&"mb-12",We&&"text-transparent"),value:Ie,placeholder:dt,onChange:e=>{if(Ne(e),A){const t=(e.match(/\n/g)||[]).length+1;if(!e)return void A(0);if(t>=11)return;let s=0;t>1&&(s=50),A(24*(t-1)+s)}},onKeyDown:e=>{z||Ue||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),pe||ae||ht()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);e.length>0&&(t.preventDefault(),ee(!1),yield he(e))}))},_&&{onFocus:_},E&&{onBlur:E},{dir:Q?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:Le,className:C.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",ft?"mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!ft&&st.backgroundColor&&{backgroundColor:st.backgroundColor}),{borderTopRightRadius:V.cornerRadius+"px",borderBottomRightRadius:V.cornerRadius+"px"})},{children:ae?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{Me.current&&(Me.current.abort(),Me.current=null),Pe.current&&(Pe.current.cancel(),Pe.current=null),ce("idle")},style:{backgroundColor:K.accent,color:K.accentText}},{children:t.jsx(j.default,{className:"h-4 w-4 shrink-0"})})):We?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:N.default.stopListening,style:{backgroundColor:K.accent,color:K.accentText}},{children:t.jsx(j.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[at&&t.jsxs("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Ge?K.accent+"10":void 0,color:Ge?K.accent:K.accent+"80"},disabled:pe||ae,onClick:()=>{var e;return null===(e=Re.current)||void 0===e?void 0:e.click()}},Qe,{children:[t.jsx("input",{id:"file-upload",ref:Re,type:"file",accept:[...g.allowedFileMimeTypes,...g.allowedImageMimeTypes,...g.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){ee(!1),yield he(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(y.default,{className:"h-6 w-6 shrink-0"})]})),lt&&t.jsx("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:We?K.accent:Ze?K.accent+"10":void 0,color:We?K.accentText:Ze?K.accent:K.accent+"80"},disabled:pe||ae,onClick:()=>{We?N.default.stopListening():(Te.current=Ie,Be(),N.default.startListening({continuous:!0,interimResults:!0,language:X||"en-US"}))}},et,{children:t.jsx(x.default,{className:"h-5 w-5 shrink-0"})})),t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Ke||mt?K.accent:K.accent+"10",color:Ke||mt?K.accentText:K.accent+"80"},disabled:!mt,onClick:()=>ht()},Xe,{children:t.jsx(b.default,{className:C.default("h-6 w-6 shrink-0",Q&&"scale-x-[-1] transform")})}))]})}))]})),me&&t.jsx(S.default,{error:me,className:"mt-3"})]}))}))}));_.displayName="Input",exports.default=_;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react");require("../../../node_modules/.pnpm/regenerator-runtime@0.14.1/node_modules/regenerator-runtime/runtime.js");var n=require("react-speech-recognition"),i=require("../../../hooks/pickaxe/usePickaxeContext.js"),r=require("../../../hooks/pickaxe/useResponseContext.js"),o=require("../../../hooks/studio/useStyleInput.js"),a=require("../../../hooks/studio/useStyleFontSize.js"),l=require("../../../hooks/pickaxe/useConversation.js"),c=require("../../../hooks/pickaxe/useDimensionContext.js"),u=require("../Addons/Auth/hooks/useAuthContext.js"),d=require("../Addons/Document/hooks/useDocument.js"),f=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),m=require("../../../hooks/core/useHover.js"),h=require("../../../hooks/core/useMediaQuery.js"),g=require("../../../common/documents.js"),v=require("eventsource-parser"),b=require("../../Icons/attach-vertical.svg.js"),y=require("../../Icons/arrow-right.svg.js"),x=require("../../Icons/microphone.svg.js"),j=require("../../Icons/stop.svg.js"),w=require("../Addons/Document/List.js"),O=require("../../Core/Textarea.js"),S=require("../../Core/ErrorAlert.js"),k=require("../../../common/error.js"),I=require("../../../common/cn.js"),C=require("../../../common/utils.js");function N(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var _=N(n);const E=s.forwardRef((({resubmitPrompt:N,onFocus:E,onBlur:A,onInputHeightChange:q,initSmitheryAuthData:R},T)=>{var P,D,L;const{origin:H,pickaxeId:M,sessionId:F,sender:$,senderType:W,portalId:B,deploymentId:U,deploymentType:J,pickaxe:V,styles:z,colors:K,locale:X,forceMobile:G,isNewChat:Q,isRtl:Y,isEmailLogin:Z,isShowFeedbackMessage:ee,setIsNewChat:te,setIsShowIceBreaker:se,onGenerateComplete:ne}=i.usePickaxeContext(),{token:ie,isLoggedOut:re,isSent:oe}=u.useAuthContext(),{messages:ae,isGenerating:le,setMessages:ce,setStatus:ue,setLimitData:de,setError:fe}=r.useResponseContext(),{documents:pe,isUploading:me,documentError:he,onFileUpload:ge,setDocuments:ve,setDocumentError:be}=d.useDocument(),{scrollStartSession:ye,scrollEndSession:xe,scrollToBottom:je}=f.useScroll({auto:!0}),{artifacts:we,currentPopupType:Oe,setArtifacts:Se,setCurrentArtifact:ke}=p.useArtifactContext(),{height:Ie}=c.useDimensionContext(),Ce=l.useConversation(),[Ne,_e]=s.useState(""),[Ee,Ae]=s.useState(!1),[qe,Re]=s.useState(!1),Te=s.useRef(null),Pe=s.useRef(""),De=s.useRef(null),Le=s.useRef(null),He=s.useRef(null),Me=s.useRef(null),Fe=s.useRef(null),$e=Math.max(.4*Ie,100),{transcript:We,listening:Be,resetTranscript:Ue,browserSupportsSpeechRecognition:Je}=n.useSpeechRecognition(),[Ve]=h.useMediaQuery("(max-width: 480px)"),ze=m.useHover(),{isHover:Ke}=ze,Xe=e.__rest(ze,["isHover"]),Ge=m.useHover(),{isHover:Qe}=Ge,Ye=e.__rest(Ge,["isHover"]),Ze=m.useHover(),{isHover:et}=Ze,tt=e.__rest(Ze,["isHover"]),st=a.useStyleFontSize(),nt=o.useStyleInput(),it="undefined"!=typeof window?window.location.hostname:"",rt="undefined"!=typeof window?window.location.href:"",ot="undefined"!=typeof window&&window.self!==window.top,at=it.includes("pickaxe.co")&&!rt.includes("https://studio.pickaxe.co/_embed")&&!ot,lt=null===(P=null==V?void 0:V.documentuploadtype)||void 0===P?void 0:P.startsWith("enduserupload"),ct=Je&&(null==V?void 0:V.enablevoicetotext),ut="chat-input"===J&&Q&&!oe,dt="chat-input"===J&&Z&&re&&oe,ft=null!==(D=null==V?void 0:V.placeholdertext)&&void 0!==D?D:Y?"بماذا تريد أن تتحدث؟":"What do you want to talk about?",pt=Ee||qe,mt=s.useMemo((()=>{var e,t,s;return!!Q&&(!!V&&(!Ce.isLoading&&(!((null!==(t=null===(e=Ce.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=V.icebreakers)||void 0===s?void 0:s.length)&&(!ee&&!ut)))))}),[V,Q,ee,ut,Ce.data,Ce.isLoading]),ht=s.useMemo((()=>{if(le||me)return!1;const e=pe.length>0&&pe.every((e=>"finished"===e.status));return!(!Ne.trim()&&!e)&&pe.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[le,me,Ne,pe]);s.useImperativeHandle(T,(()=>({onSubmit:gt}))),s.useEffect((()=>{se(mt)}),[mt]),s.useEffect((()=>{var e;if(N){const t=Array.from(ae),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;gt(s,!0)}}),[N]),s.useEffect((()=>{if(!Me.current||!q)return;const e=new ResizeObserver((e=>{for(const t of e)q(t.contentRect.height)}));return e.observe(Me.current),()=>{e.disconnect()}}),[q]),s.useEffect((()=>{if(!Be)return;const e=Pe.current?`${Pe.current} `:"";_e(`${e}${We}`)}),[We,Be]),s.useEffect((()=>{if(!Le.current)return;(()=>{if(!Le.current)return;let e=Le.current.scrollHeight>52;Ne.includes("\n")||pe.length?e=!0:Ne.trim()||(e=!1),Ae(e)})()}),[Ne,pe]),s.useEffect((()=>{const e=Le.current,t=He.current;if(!e||!t||Ee||Ne.includes("\n"))return void Re(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,i=document.createElement("span");Object.assign(i.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),i.textContent=Ne||ft,document.body.appendChild(i);const r=i.offsetWidth;i.remove();const o=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-o-a-t.offsetWidth;Re(r>l)}),[Ne,Ee,ft]);const gt=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i;try{if(le||me)return;const r=pe.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),o=r.map((e=>e.documentId)).filter(Boolean),a=r.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=o.length>0,c=null!=t?t:Ne;if(!c&&!l)return;fe(""),be(""),de(null),_e(""),te(!1),ue("fetching"),ye(),je();const u=null!==(n=null===(e=null==V?void 0:V.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&o.length>0,d=[...s?Array.from(ae.slice(0,ae.length-1)):Array.from(ae),...s?[]:[{id:ae.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:u?o:[]}],{id:ae.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];ce(d),je(),u&&ve([]);const f=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign(Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:H,pickaxeId:M,sessionId:F,senderType:W,value:c},u&&{documentIds:o}),$&&{sender:$}),ie&&{studioSessionToken:ie}),!ie&&!$&&{sender:C.initializeEmbedUserId()}),B&&{portalId:B}),U&&{deploymentId:U}),a.length>0&&{uploadedModelImages:a}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),at&&{credentials:"include"})),p=yield f.json();if(!p.success){const e=new Error(p.error||"Failed to start generation");throw p.limitData&&(e.limitData=p.limitData),e}const m=p.submissionId;ue("streaming"),Fe.current=new AbortController;const h=d.length-1,g=[];let b=[...null!=we?we:[]],y=0,x=!1,j="";for(;!x;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${m}?index=${y}`,{signal:null===(i=Fe.current)||void 0===i?void 0:i.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();De.current=t;const s=new TextDecoder,n=v.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&y++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data).error||"Something went wrong.";return fe(t),void(x=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&R){const e=n.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw x=!0,R({smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw x=!0,R({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)j="",g.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)j+=n.delta,g[g.length-1].content=j;else if("text-end"===n.type)j="";else if("reasoning-start"===n.type)j="",g.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)j+=n.delta,g[g.length-1].content=j;else if("reasoning-end"===n.type)j="";else if(n.type.startsWith("data-")){const e=n;g.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}ce([...d.slice(0,h),Object.assign(Object.assign({},d[d.length-1]),{id:ae.length+1,role:"assistant",parts:g})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Se([...b]),Oe.startsWith("inline")||ke({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Se(b),Oe.startsWith("inline")||ke({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Se(b),Oe.startsWith("inline")||ke({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");b=b.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Se(b)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Se(b.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);fe(t.error||"Something went wrong, please try again.")}else"stop"===e.event&&(x=!0)}else x=!0}});for(;;){const{value:e,done:i}=yield t.read();if(i)break;n.feed(s.decode(e))}x||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(x=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==ne||ne(F)}catch(e){if(e.limitData)de(e.limitData),fe("");else{let t=k.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t="Oops! We're experiencing high traffic at the moment. Please try again later."),fe(t)}}finally{je(),ue("idle"),xe(),De.current=null}}));return dt?null:t.jsx("div",Object.assign({className:I.default("flex w-full flex-shrink-0 flex-col items-center",!ut&&"px-4 pb-8"),dir:Y?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:Me,className:I.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===z.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},nt),{maxHeight:`${$e}px`,overflowY:"auto"})},{children:[Be&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(L=K.accent)&&void 0!==L?L:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:K.text+"90"}},{children:"Listening..."}))]})),!le&&pe.length>0&&t.jsx(w.default,{className:"p-4 pb-0",isDisabled:le}),t.jsx(O.default,Object.assign({ref:Le,className:I.default(st.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Ne.trim()&&!Ne.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Y?"text-right":"text-left",pt&&"mb-12",Be&&"text-transparent"),value:Ne,placeholder:ft,onChange:e=>{if(_e(e),q){const t=(e.match(/\n/g)||[]).length+1;if(!e)return void q(0);if(t>=11)return;let s=0;t>1&&(s=50),q(24*(t-1)+s)}},onKeyDown:e=>{G||Ve||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),me||le||gt()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);e.length>0&&(t.preventDefault(),te(!1),yield ge(e))}))},E&&{onFocus:E},A&&{onBlur:A},{dir:Y?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:He,className:I.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",pt?"mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!pt&&nt.backgroundColor&&{backgroundColor:nt.backgroundColor}),{borderTopRightRadius:z.cornerRadius+"px",borderBottomRightRadius:z.cornerRadius+"px"})},{children:le?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{Fe.current&&(Fe.current.abort(),Fe.current=null),De.current&&(De.current.cancel(),De.current=null),ue("idle")},style:{backgroundColor:K.accent,color:K.accentText}},{children:t.jsx(j.default,{className:"h-4 w-4 shrink-0"})})):Be?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:_.default.stopListening,style:{backgroundColor:K.accent,color:K.accentText}},{children:t.jsx(j.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[lt&&t.jsxs("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Qe?K.accent+"10":void 0,color:Qe?K.accent:K.accent+"80"},disabled:me||le,onClick:()=>{var e;return null===(e=Te.current)||void 0===e?void 0:e.click()}},Ye,{children:[t.jsx("input",{id:"file-upload",ref:Te,type:"file",accept:[...g.allowedFileMimeTypes,...g.allowedImageMimeTypes,...g.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){te(!1),yield ge(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(b.default,{className:"h-6 w-6 shrink-0"})]})),ct&&t.jsx("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:Be?K.accent:et?K.accent+"10":void 0,color:Be?K.accentText:et?K.accent:K.accent+"80"},disabled:me||le,onClick:()=>{Be?_.default.stopListening():(Pe.current=Ne,Ue(),_.default.startListening({continuous:!0,interimResults:!0,language:X||"en-US"}))}},tt,{children:t.jsx(x.default,{className:"h-5 w-5 shrink-0"})})),t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Ke||ht?K.accent:K.accent+"10",color:Ke||ht?K.accentText:K.accent+"80"},disabled:!ht,onClick:()=>gt()},Xe,{children:t.jsx(y.default,{className:I.default("h-6 w-6 shrink-0",Y&&"scale-x-[-1] transform")})}))]})}))]})),he&&t.jsx(S.default,{error:he,className:"mt-3"})]}))}))}));E.displayName="Input",exports.default=E;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),r=require("../../../hooks/pickaxe/usePickaxeContext.js"),n=require("../Addons/Auth/hooks/useAuthContext.js"),i=require("../../../hooks/pickaxe/useDimensionContext.js"),o=require("../Addons/Document/hooks/useDocument.js"),a=require("../../../hooks/studio/useStyleFontSize.js"),u=require("./History/index.js"),c=require("./Input.js"),l=require("../../Icons/attach-vertical.svg.js"),d=require("../../../common/cn.js");exports.default=()=>{const{deploymentType:f,isNewChat:h,setIsNewChat:m}=r.usePickaxeContext(),{isSent:p}=n.useAuthContext(),{width:x,height:j,setDimension:g}=i.useDimensionContext(),{setDocuments:b,onFileUpload:v}=o.useDocument(),D=a.useStyleFontSize(),[y,S]=s.useState(0),[k,w]=s.useState(!1),[q,A]=s.useState(!1),C=s.useRef(null),F=s.useRef(null),P=s.useRef(0),[I,N]=s.useState(null),[O,_]=s.useState(!1),R="chat-input"===f&&h&&!p;s.useEffect((()=>()=>{b([])}),[]),s.useEffect((()=>{if(!C.current)return;const e=new ResizeObserver((e=>{for(const t of e){const{width:e,height:s}=t.contentRect;g(parseInt(e.toFixed(0)),parseInt(s.toFixed(0)))}}));return e.observe(C.current),()=>{e.disconnect()}}),[C.current]);return t.jsxs("div",Object.assign({ref:C,className:"relative flex h-full w-full flex-col items-center",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),P.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&A(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),P.current-=1,0===P.current&&A(!1)},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e.__awaiter(void 0,void 0,void 0,(function*(){t.preventDefault(),t.stopPropagation(),A(!1),P.current=0;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(m(!1),yield v(e))}))},{children:[q&&t.jsxs("div",Object.assign({className:"absolute inset-0 z-50 flex flex-col items-center justify-center rounded-lg bg-white/80 backdrop-blur-sm transition-all duration-300"},{children:[t.jsx("div",Object.assign({className:"flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-lg animate-bounce text-black"},{children:t.jsx(l.default,{className:"h-10 w-10"})})),t.jsx("h3",Object.assign({className:d.default(D.h3,"mt-6 font-semibold text-c-primary text-black")},{children:"Drop files to upload"})),t.jsx("p",Object.assign({className:d.default(D.b2,"mt-2 opacity-60 text-black")},{children:"Add anything to the conversation"}))]})),R?t.jsx(c.default,{}):t.jsxs(t.Fragment,{children:[t.jsx(u.default,{additionalScrollHeight:y,isForceHideInfo:j<=545||x<=350||k,isInputFocused:k,onSubmit:t=>e.__awaiter(void 0,void 0,void 0,(function*(){F.current&&F.current.onSubmit(t)})),smitheryAuthData:I,resubmitPrompt:()=>{N(null),_(!0)}}),t.jsx(c.default,{ref:F,onFocus:()=>w(!0),onBlur:()=>w(!1),onInputHeightChange:S,initSmitheryAuthData:e=>N(e),resubmitPrompt:O})]})]}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../hooks/pickaxe/usePickaxeContext.js"),r=require("../Addons/Auth/hooks/useAuthContext.js"),o=require("../../../hooks/pickaxe/useDimensionContext.js"),i=require("../Addons/Document/hooks/useDocument.js"),a=require("../../../hooks/studio/useStyleFontSize.js"),l=require("./History/index.js"),c=require("./Input.js"),u=require("../../Icons/attach-vertical.svg.js"),d=require("../../../common/cn.js"),m=require("../../../common/api/pickaxe.js"),x=require("lucide-react"),f=require("uuid"),h=require("../../Icons/trash-2.svg.js"),p=require("../../Icons/pencil.svg.js"),b=require("../../../hooks/pickaxe/useResponseContext.js");const j=({children:e,className:s})=>t.jsx("div",Object.assign({className:d.default("flex items-center gap-2 transition-all duration-200 select-none","rounded-[40px] h-[72px] border border-white/70 px-6 py-3 bg-white/10 backdrop-blur-md",s)},{children:e})),v=({text:e,icon:s,className:n,onClick:r})=>t.jsx("div",Object.assign({onClick:r,className:d.default("relative flex items-center justify-center px-3 h-full shrink-0 transition-all duration-200 rounded-[40px] border border-white/70 bg-[#FFFFFF1A]",n)},{children:t.jsxs("div",Object.assign({className:"flex items-center gap-2 z-20"},{children:[s&&t.jsx("img",{src:s,alt:"",className:"h-5 w-5 rounded-full object-cover"}),t.jsx("p",Object.assign({className:"text-sm font-medium truncate max-w-[150px] text-foreground"},{children:e}))]}))})),g=({text:n,className:r,onRename:o,onDelete:i})=>{const[a,l]=s.useState(!1),[c,u]=s.useState(!1),[m,f]=s.useState(n),[b,j]=s.useState(!1),v=s.useRef(null),g=s.useRef(null);s.useEffect((()=>{c||f(n)}),[n,c]),s.useEffect((()=>{const e=e=>{g.current&&!g.current.contains(e.target)&&l(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)}),[]);const w=()=>e.__awaiter(void 0,void 0,void 0,(function*(){m.trim()&&(j(!0),yield o(m),j(!1),u(!1))})),y=()=>{f(n),u(!1)};return t.jsxs("div",Object.assign({ref:g,className:"relative z-40 h-full"},{children:[t.jsx("div",Object.assign({className:d.default("relative flex items-center justify-center px-3 h-full shrink-0 rounded-[40px] overflow-visible transition-all duration-200 cursor-pointer group border border-white/70 bg-[#FFFFFF1A]",r),onClick:e=>{e.stopPropagation(),c||a?a&&l(!1):l(!0)}},{children:c?t.jsxs("div",Object.assign({className:"flex items-center gap-2 z-20 min-w-[140px]",onClick:e=>e.stopPropagation()},{children:[t.jsx("input",{autoFocus:!0,type:"text",value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&w(),"Escape"===e.key&&y()},className:"bg-transparent border-b border-black/30 text-sm font-medium focus:outline-none w-full min-w-[80px] text-foreground"}),t.jsx("button",Object.assign({onClick:w,disabled:b,className:"p-1 rounded hover:bg-black/10 text-green-600"},{children:t.jsx(x.Check,{className:"h-4 w-4"})})),t.jsx("button",Object.assign({onClick:y,disabled:b,className:"p-1 rounded hover:bg-black/10 text-red-600"},{children:t.jsx(x.X,{className:"h-4 w-4"})}))]})):t.jsxs("div",Object.assign({className:"flex items-center gap-2 z-20 max-w-[200px]"},{children:[t.jsx("p",Object.assign({className:"text-sm font-medium truncate text-foreground"},{children:n})),t.jsx(x.MoreHorizontal,{className:d.default("h-4 w-4 opacity-50 group-hover:opacity-100 transition-opacity")})]}))})),a&&t.jsxs("div",Object.assign({className:"absolute top-full right-0 mt-2 w-48 shadow-xl z-50 rounded-[16px] border border-white/70 bg-neutral-400 backdrop-blur-md overflow-hidden animate-in fade-in zoom-in-95 duration-100",ref:v},{children:[t.jsxs("button",Object.assign({onClick:e=>{e.stopPropagation(),l(!1),u(!0)},className:"w-full text-left px-4 py-3 flex items-center gap-3 transition-colors border-b border-white/10 hover:bg-white/10"},{children:[t.jsx(p.default,{className:"h-4 w-4"}),t.jsx("span",Object.assign({className:"font-medium text-sm"},{children:"Rename chat"}))]})),t.jsxs("button",Object.assign({onClick:e=>{e.stopPropagation(),l(!1),i()},className:"w-full text-left px-4 py-3 flex items-center gap-3 transition-colors hover:bg-white/10"},{children:[t.jsx(h.default,{className:"h-4 w-4"}),t.jsx("span",Object.assign({className:"font-medium text-sm"},{children:"Delete chat"}))]}))]}))]}))};exports.default=()=>{const{deploymentType:x,isNewChat:h,setIsNewChat:p,sessionId:w,setSessionId:y,pickaxeId:k,sender:N,colors:O,styles:C,pickaxe:F,isEmbed:D}=n.usePickaxeContext(),{isSent:_}=r.useAuthContext(),{width:I,height:S,setDimension:q}=o.useDimensionContext(),{setDocuments:E,onFileUpload:P}=i.useDocument(),{isGenerating:z}=b.useResponseContext(),A=a.useStyleFontSize(),[R,T]=s.useState(0),[H,L]=s.useState(!1),[M,B]=s.useState(!1),G=s.useRef(null),K=s.useRef(null),U=s.useRef(0),[X,J]=s.useState(null),[Q,V]=s.useState(!1),W="chat-input"===x&&h&&!_;s.useEffect((()=>()=>{E([])}),[]);const Y=s.useCallback((()=>{if(!k||!N)return;const t=(s=0)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e;try{const t=yield m.default.post("/get_pickaxe_conversation",{sessionId:w,userId:N});if(t.data&&t.data.success){const e=t.data.title;if(e&&"Conversation Title"!==e)return void $(e)}else console.error("Failed to load conversation:",null===(e=t.data)||void 0===e?void 0:e.error)}catch(e){console.error("Error fetching conversation:",e)}s<20&&setTimeout((()=>t(s+1)),3e3)}));t()}),[k,N,w]);s.useEffect((()=>{z||h||!w||Y()}),[z,h,w,Y]),s.useEffect((()=>{if(!G.current)return;const e=new ResizeObserver((e=>{for(const t of e){const{width:e,height:s}=t.contentRect;q(parseInt(e.toFixed(0)),parseInt(s.toFixed(0)))}}));return e.observe(G.current),()=>{e.disconnect()}}),[G.current]);const[Z,$]=s.useState("New Chat"),ee=(null==F?void 0:F.formtitle)||"Pickaxe",te=(null==F?void 0:F.coverphoto)||void 0,se=!W&&!D;return t.jsxs("div",Object.assign({ref:G,className:"relative flex h-full w-full flex-col items-center overflow-hidden",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),U.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&B(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),U.current-=1,0===U.current&&B(!1)},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e.__awaiter(void 0,void 0,void 0,(function*(){t.preventDefault(),t.stopPropagation(),B(!1),U.current=0;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(p(!1),yield P(e))}))},{children:[M&&t.jsxs("div",Object.assign({className:"absolute inset-0 z-50 flex flex-col items-center justify-center rounded-lg bg-white/80 backdrop-blur-sm transition-all duration-300"},{children:[t.jsx("div",Object.assign({className:"flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-lg animate-bounce text-black"},{children:t.jsx(u.default,{className:"h-10 w-10"})})),t.jsx("h3",Object.assign({className:d.default(A.h3,"mt-6 font-semibold text-c-primary text-black")},{children:"Drop files to upload"})),t.jsx("p",Object.assign({className:d.default(A.b2,"mt-2 opacity-60 text-black")},{children:"Add anything to the conversation"}))]})),W?t.jsx(c.default,{}):t.jsxs(t.Fragment,{children:[t.jsxs("div",Object.assign({className:d.default("flex flex-col w-full items-center h-full relative z-0",se?"pt-6":"")},{children:[se&&t.jsx("div",Object.assign({className:"w-full max-w-3xl px-4 md:px-0 flex justify-start z-30 mb-4 animate-in fade-in slide-in-from-top-4 duration-500"},{children:t.jsxs(j,Object.assign({colors:O,styles:C},{children:[t.jsx(v,{text:ee,icon:te,colors:O,styles:C}),h||"New Chat"===Z?t.jsx(v,{text:Z,colors:O,styles:C}):t.jsx(g,{text:Z,sessionId:w,colors:O,styles:C,onRename:t=>e.__awaiter(void 0,void 0,void 0,(function*(){if(w)try{yield m.default.post("/edit_conversation_name",{sessionId:w,name:t,userId:N}),$(t)}catch(e){console.error("Error renaming chat:",e),alert("Failed to rename chat.")}})),onDelete:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(w&&window.confirm("Are you sure you want to delete this conversation?"))try{yield m.default.post("/delete_pickaxe_conversation",{sessionId:w,userId:N}),p(!0),y(f.v4()),$("New Chat")}catch(e){console.error("Error deleting chat:",e),alert("Failed to delete chat.")}}))})]}))})),t.jsx(l.default,{additionalScrollHeight:R,isForceHideInfo:S<=545||I<=350||H,isInputFocused:H,onSubmit:t=>e.__awaiter(void 0,void 0,void 0,(function*(){K.current&&K.current.onSubmit(t)})),smitheryAuthData:X,resubmitPrompt:()=>{J(null),V(!0)}})]})),t.jsx(c.default,{ref:K,onFocus:()=>L(!0),onBlur:()=>L(!1),onInputHeightChange:T,initSmitheryAuthData:e=>J(e),resubmitPrompt:Q})]})]}))};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../Addons/Auth/hooks/useAuthContext.js"),o=require("../../../../hooks/pickaxe/useResponseContext.js"),r=require("../../Addons/Document/hooks/useDocument.js"),a=require("../../Addons/Scroll/hooks/useScroll.js"),l=require("../../Addons/Artifact/hooks/useArtifactContext.js"),d=require("../../../../common/utils.js"),c=require("@nem035/gpt-3-encoder"),u=require("eventsource-parser"),p=require("../../common/PickaxeBranding.js"),m=require("../../common/PickaxeButton.js"),g=require("../../../../common/error.js");exports.default=({questions:f,resetQuestions:h})=>{var v;const{origin:b,pickaxeId:x,sender:y,senderType:j,portalId:O,deploymentId:w,pickaxe:C,misc:S,translations:k,isRtl:I,setSessionId:_,setIsNewChat:P,onGenerateComplete:A}=n.usePickaxeContext(),{token:N}=i.useAuthContext(),{isGenerating:q,setResponse:E,setMessages:T,setStatus:D,setLimitData:U,setError:L,setIsSwitchedToChat:R}=o.useResponseContext(),{documents:J,websiteLink:B,isUploading:K,onWebsiteUpload:W,setDocuments:X,setDocumentError:V}=r.useDocument(),{scrollStartSession:M,scrollEndSession:$,scrollToTarget:F}=a.useScroll({auto:!(null==C?void 0:C.enablechatresponses)}),{artifacts:G,currentPopupType:Q,setArtifacts:Y,setCurrentArtifact:z}=l.useArtifactContext(),[H,Z]=s.useState(!1),ee=s.useRef(null),te=s.useMemo((()=>f.some((e=>("Short Answer"===e.type||"Long Answer"===e.type||"long"===e.type||"short"===e.type||"Checkbox"===e.type||"Knowledge Upload"===e.type||e.id.includes("documentupload"))&&e.input.length>0))),[f]);return t.jsxs("div",Object.assign({className:"mt-4 flex flex-wrap justify-between gap-4 items-center",dir:I?"rtl":"ltr"},{children:[t.jsxs("div",Object.assign({className:"flex items-center flex-grow flex-wrap gap-2"},{children:[t.jsx(m.default,Object.assign({className:"px-5 min-h-[42px]",isDisabled:K||q||H,onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,t,s;try{if(q||K||H)return;L(""),V(""),U(null),E(null);const n=["Multiple Choice","Checkbox"];for(const e of f){if(c.encode(e.input).length>e.maxLength&&!n.includes(e.type))throw new Error("One or more of your responses is too long!");if(e.isRequired&&!e.input.trim()&&"userinput:documentupload"!==e.id)throw new Error("You must fill out all required fields.")}const i=J.filter((e=>"finished"===e.status)),o=J.map((e=>e.name)),r=null!==(t=null===(e=null==C?void 0:C.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==t&&t,a=f.some((e=>"userinput:documentupload"===e.id&&e.isRequired)),l=d.extractUrlsFromText(B).filter((e=>!o.includes(e)));if(l.length){const e=l[l.length-1];Z(!0);const t=yield W(e);t&&(i.push(t),yield new Promise((e=>setTimeout(e,5e3)))),Z(!1)}else if(a&&r&&!i.length)return void V("Please paste a valid website/video link or drag a file to add to the knowledge base.");const p=i.map((e=>e.documentId||"")).filter(Boolean),m=r&&p.length>0,g={};f.forEach((e=>{g[e.id]="Knowledge Upload"===e.type||e.id.includes("documentupload")?i.map((e=>e.name)).join(",")||"":e.input})),D("fetching"),M(),F();const h=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}),body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:b,pickaxeId:x,senderType:j,valueObj:g},m&&{documentIds:p}),y&&{sender:y}),N&&{studioSessionToken:N}),O&&{portalId:O}),w&&{deploymentId:w}))}),v=yield h.json();if(!v.success){const e=new Error(v.error||"Failed to start generation");throw v.limitData&&(e.limitData=v.limitData),e}const S=v.submissionId,k=v.sessionId,I={sessionId:k,documentIds:m?p:[],question:{inputs:f.map((e=>({id:e.id,question:e.main,answer:e.input}))),responseParts:[]},messageCount:0,sentAt:new Date};E(I),(null==C?void 0:C.enablechatresponses)&&(_(k),P(!1),R(!0),T([{id:0,role:"assistant",parts:[],documentIds:[]}])),m&&X([]),D("streaming"),ee.current=new AbortController;const $=[];let te=[...null!=G?G:[]],se=0,ne=!1,ie="";for(;!ne;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${S}?index=${se}`,{signal:null===(s=ee.current)||void 0===s?void 0:s.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader(),n=new TextDecoder,i=u.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&se++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data).error||"Something went wrong.";return L(t),void(ne=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("text-start"===n.type)ie="",$.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)ie+=n.delta,$[$.length-1].content=ie;else if("text-end"===n.type)ie="";else if("reasoning-start"===n.type)ie="",$.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)ie+=n.delta,$[$.length-1].content=ie;else if("reasoning-end"===n.type)ie="";else if(n.type.startsWith("data-")){const e=n;$.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}const i=Object.assign(Object.assign({},I),{question:Object.assign(Object.assign({},I.question),{responseParts:[...$]})});E(i),(null==C?void 0:C.enablechatresponses)&&T([{id:0,role:"assistant",parts:[...$],documentIds:[]}])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);te=te.filter((e=>!(e.id===t.id&&e.version===t.version))),te.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Y([...te]),Q.startsWith("inline")||z({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);te=te.filter((e=>!(e.id===t.id&&e.version===t.version))),te.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Y([...te]),Q.startsWith("inline")||z({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);te=te.filter((e=>!(e.id===t.id&&e.version===t.version))),te.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Y([...te]),Q.startsWith("inline")||z({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");te=te.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Y([...te])}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Y(te.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}}else ne=!0}});for(;;){const{value:e,done:s}=yield t.read();if(s)break;i.feed(n.decode(e))}ne||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("AbortError"===e.name)return void(ne=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==A||A(k)}catch(e){let t=g.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t="Oops! We're experiencing high traffic at the moment. Please try again later."),L(t),F()}finally{D("idle"),Z(!1),$()}}))},{children:H?(null==k?void 0:k.processing)||"Processing...":K?(null==k?void 0:k.uploading)||"Uploading...":q?(null==k?void 0:k.loading)||"Loading...":null!==(v=null==C?void 0:C.submittext)&&void 0!==v?v:"Submit"})),te&&t.jsx(m.default,Object.assign({variant:"transparent-text",className:"min-h-[42px] px-5",isDisabled:K||q||H,onClick:h},{children:(null==k?void 0:k["clear-form"])||"Clear form"}))]})),!S.isWhiteLabel&&t.jsx(p.default,{containerClassName:"justify-end"})]}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../Addons/Auth/hooks/useAuthContext.js"),o=require("../../../../hooks/pickaxe/useResponseContext.js"),r=require("../../Addons/Document/hooks/useDocument.js"),a=require("../../Addons/Scroll/hooks/useScroll.js"),l=require("../../Addons/Artifact/hooks/useArtifactContext.js"),d=require("../../../../common/utils.js"),c=require("@nem035/gpt-3-encoder"),u=require("eventsource-parser"),p=require("../../common/PickaxeBranding.js"),m=require("../../common/PickaxeButton.js"),g=require("../../../../common/error.js");exports.default=({questions:f,resetQuestions:h})=>{var v;const{origin:b,pickaxeId:x,sender:j,senderType:y,portalId:O,deploymentId:w,pickaxe:C,misc:S,translations:k,isRtl:I,setSessionId:_,setIsNewChat:P,onGenerateComplete:A}=n.usePickaxeContext(),{token:N}=i.useAuthContext(),{isGenerating:q,setResponse:E,setMessages:T,setStatus:U,setLimitData:D,setError:L,setIsSwitchedToChat:R}=o.useResponseContext(),{documents:J,websiteLink:B,isUploading:K,onWebsiteUpload:W,setDocuments:X,setDocumentError:V}=r.useDocument(),{scrollStartSession:M,scrollEndSession:$,scrollToTarget:F}=a.useScroll({auto:!(null==C?void 0:C.enablechatresponses)}),{artifacts:G,currentPopupType:z,setArtifacts:Q,setCurrentArtifact:Y}=l.useArtifactContext(),[H,Z]=s.useState(!1),ee=s.useRef(null),te=s.useMemo((()=>f.some((e=>("Short Answer"===e.type||"Long Answer"===e.type||"long"===e.type||"short"===e.type||"Checkbox"===e.type||"Knowledge Upload"===e.type||e.id.includes("documentupload"))&&e.input.length>0))),[f]);return t.jsxs("div",Object.assign({className:"mt-4 flex flex-wrap justify-between gap-4 items-center",dir:I?"rtl":"ltr"},{children:[t.jsxs("div",Object.assign({className:"flex items-center flex-grow flex-wrap gap-2"},{children:[t.jsx(m.default,Object.assign({className:"px-5 min-h-[42px]",isDisabled:K||q||H,onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,t,s;try{if(q||K||H)return;L(""),V(""),D(null),E(null);const n=["Multiple Choice","Checkbox"];for(const e of f){if(c.encode(e.input).length>e.maxLength&&!n.includes(e.type))throw new Error("One or more of your responses is too long!");if(e.isRequired&&!e.input.trim()&&"userinput:documentupload"!==e.id)throw new Error("You must fill out all required fields.")}const i=J.filter((e=>"finished"===e.status)),o=J.map((e=>e.name)),r=null!==(t=null===(e=null==C?void 0:C.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==t&&t,a=f.some((e=>"userinput:documentupload"===e.id&&e.isRequired)),l=d.extractUrlsFromText(B).filter((e=>!o.includes(e)));if(l.length){const e=l[l.length-1];Z(!0);const t=yield W(e);t&&(i.push(t),yield new Promise((e=>setTimeout(e,5e3)))),Z(!1)}else if(a&&r&&!i.length)return void V("Please paste a valid website/video link or drag a file to add to the knowledge base.");const p=i.map((e=>e.documentId||"")).filter(Boolean),m=r&&p.length>0,g={};f.forEach((e=>{g[e.id]="Knowledge Upload"===e.type||e.id.includes("documentupload")?i.map((e=>e.name)).join(",")||"":e.input})),U("fetching"),M(),F();const h=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}),body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:b,pickaxeId:x,senderType:y,valueObj:g},m&&{documentIds:p}),j&&{sender:j}),N&&{studioSessionToken:N}),!N&&!j&&{sender:d.initializeEmbedUserId()}),O&&{portalId:O}),w&&{deploymentId:w}))}),v=yield h.json();if(!v.success){const e=new Error(v.error||"Failed to start generation");throw v.limitData&&(e.limitData=v.limitData),e}const S=v.submissionId,k=v.sessionId,I={sessionId:k,documentIds:m?p:[],question:{inputs:f.map((e=>({id:e.id,question:e.main,answer:e.input}))),responseParts:[]},messageCount:0,sentAt:new Date};E(I),(null==C?void 0:C.enablechatresponses)&&(_(k),P(!1),R(!0),T([{id:0,role:"assistant",parts:[],documentIds:[]}])),m&&X([]),U("streaming"),ee.current=new AbortController;const $=[];let te=[...null!=G?G:[]],se=0,ne=!1,ie="";for(;!ne;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${S}?index=${se}`,{signal:null===(s=ee.current)||void 0===s?void 0:s.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader(),n=new TextDecoder,i=u.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&se++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data).error||"Something went wrong.";return L(t),void(ne=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("text-start"===n.type)ie="",$.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)ie+=n.delta,$[$.length-1].content=ie;else if("text-end"===n.type)ie="";else if("reasoning-start"===n.type)ie="",$.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)ie+=n.delta,$[$.length-1].content=ie;else if("reasoning-end"===n.type)ie="";else if(n.type.startsWith("data-")){const e=n;$.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}const i=Object.assign(Object.assign({},I),{question:Object.assign(Object.assign({},I.question),{responseParts:[...$]})});E(i),(null==C?void 0:C.enablechatresponses)&&T([{id:0,role:"assistant",parts:[...$],documentIds:[]}])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);te=te.filter((e=>!(e.id===t.id&&e.version===t.version))),te.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Q([...te]),z.startsWith("inline")||Y({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);te=te.filter((e=>!(e.id===t.id&&e.version===t.version))),te.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Q([...te]),z.startsWith("inline")||Y({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);te=te.filter((e=>!(e.id===t.id&&e.version===t.version))),te.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Q([...te]),z.startsWith("inline")||Y({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");te=te.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Q([...te])}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Q(te.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}}else ne=!0}});for(;;){const{value:e,done:s}=yield t.read();if(s)break;i.feed(n.decode(e))}ne||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("AbortError"===e.name)return void(ne=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==A||A(k)}catch(e){let t=g.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t="Oops! We're experiencing high traffic at the moment. Please try again later."),L(t),F()}finally{U("idle"),Z(!1),$()}}))},{children:H?(null==k?void 0:k.processing)||"Processing...":K?(null==k?void 0:k.uploading)||"Uploading...":q?(null==k?void 0:k.loading)||"Loading...":null!==(v=null==C?void 0:C.submittext)&&void 0!==v?v:"Submit"})),te&&t.jsx(m.default,Object.assign({variant:"transparent-text",className:"min-h-[42px] px-5",isDisabled:K||q||H,onClick:h},{children:(null==k?void 0:k["clear-form"])||"Clear form"}))]})),!S.isWhiteLabel&&t.jsx(p.default,{containerClassName:"justify-end"})]}))};
@@ -1,10 +1,12 @@
1
1
  import type { Ref } from "react";
2
+ export declare const COOKIE_USER_ID = "PXE-uid";
2
3
  export declare const generateId: (length: number, prefix?: string, suffix?: string) => string;
3
4
  export declare const randomStr: (len: number, charOnly?: boolean) => string;
4
5
  export declare const extractUrlsFromText: (text: string) => string[];
5
6
  export declare const formatBytes: (bytes: number, decimals?: number) => string;
6
7
  export declare const getCookie: (name: string) => string | null;
7
8
  export declare const deleteCookie: (name: string) => void;
9
+ export declare const initializeEmbedUserId: () => string;
8
10
  export declare const getAuthToken: (studioId: string) => string | null;
9
11
  export declare const setAuthToken: (name: string, token: string) => void;
10
12
  export declare const deleteAuthToken: (name: string) => void;
@@ -1 +1 @@
1
- const t=(t,e="",o="")=>{let r="";for(let e=0;e<t;e++){r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return e+r+o},e=(t,e=!1)=>{let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";e&&(o=o.replace(/[0-9]/g,""));let r="";for(let e=0;e<t;e++)r+=o.charAt(Math.floor(Math.random()*o.length));return r},o=t=>{const e=t.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(e))},r=(t,e=2)=>{if(!+t)return"0 Bytes";const o=e<0?0:e,r=Math.floor(Math.log(t)/Math.log(1024));return`${parseFloat((t/Math.pow(1024,r)).toFixed(o))} ${["Bytes","KB","MB","PB","EB"][r]}`},n=t=>{try{const e=document.cookie.split("; ");for(const o of e){const[e,r]=o.split("=");if(e===t)return r}return null}catch(t){return console.error("[pxe] failed to get cookie",t),null}},l=t=>{document.cookie=t+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},c=t=>{try{if("undefined"==typeof window)return null;let e=null;return e=new URLSearchParams(window.location.search).get("pxtoken"),e||(e=localStorage.getItem(`PXE-token-${t}`)),e||(e=n(`PXE-token-${t}`)),e||(e=n(`__Secure-PS-${t}.session-token`)),e?decodeURIComponent(e):null}catch(t){return null}},a=(t,e)=>{try{if("undefined"==typeof window)return;localStorage.setItem(t,e)}catch(t){console.error("[pxe] failed to set auth token",t)}},u=t=>{try{if("undefined"==typeof window)return;localStorage.removeItem(t)}catch(t){console.error("[pxe] failed to delete auth token",t)}};function f(...t){return e=>{for(const o of t)o&&("function"==typeof o?o(e):o.current=e)}}const i=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(t){return!0}},s=t=>{try{return JSON.parse(t)}catch(t){return null}};export{u as deleteAuthToken,l as deleteCookie,o as extractUrlsFromText,r as formatBytes,t as generateId,c as getAuthToken,n as getCookie,i as isInIframe,f as mergeRefs,e as randomStr,s as safeJSONParse,a as setAuthToken};
1
+ import{parse as t}from"tldts";const e="PXE-uid",o=(t,e="",o="")=>{let r="";for(let e=0;e<t;e++){r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return e+r+o},r=(t,e=!1)=>{let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";e&&(o=o.replace(/[0-9]/g,""));let r="";for(let e=0;e<t;e++)r+=o.charAt(Math.floor(Math.random()*o.length));return r},n=t=>{const e=t.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(e))},l=(t,e=2)=>{if(!+t)return"0 Bytes";const o=e<0?0:e,r=Math.floor(Math.log(t)/Math.log(1024));return`${parseFloat((t/Math.pow(1024,r)).toFixed(o))} ${["Bytes","KB","MB","PB","EB"][r]}`},c=t=>{try{const e=document.cookie.split("; ");for(const o of e){const[e,r]=o.split("=");if(e===t)return r}return null}catch(t){return console.error("[pxe] failed to get cookie",t),null}},a=t=>{document.cookie=t+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},i=()=>{try{const o=c(e);if(!o){const o=r(28),n=new Date;n.setFullYear(n.getFullYear()+1);let l=window.location.hostname;const c=t(l).domain;if(c)l=`.${c}`;else{const t=l.split(":")[0],e=t.split(".");l=t,e.length>=2&&(l=`.${e.slice(-2).join(".")}`)}return document.cookie=`${e}=${o};Path=/; Domain=${l}; Expires=${n.toUTCString()}`,o}return o}catch(t){return console.error("[pxe-embed] failed to initialized embed user id",t),r(28)}},u=t=>{try{if("undefined"==typeof window)return null;let e=null;return e=new URLSearchParams(window.location.search).get("pxtoken"),e||(e=localStorage.getItem(`PXE-token-${t}`)),e||(e=c(`PXE-token-${t}`)),e||(e=c(`__Secure-PS-${t}.session-token`)),e?decodeURIComponent(e):null}catch(t){return null}},s=(t,e)=>{try{if("undefined"==typeof window)return;localStorage.setItem(t,e)}catch(t){console.error("[pxe] failed to set auth token",t)}},d=t=>{try{if("undefined"==typeof window)return;localStorage.removeItem(t)}catch(t){console.error("[pxe] failed to delete auth token",t)}};function f(...t){return e=>{for(const o of t)o&&("function"==typeof o?o(e):o.current=e)}}const h=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(t){return!0}},p=t=>{try{return JSON.parse(t)}catch(t){return null}};export{e as COOKIE_USER_ID,d as deleteAuthToken,a as deleteCookie,n as extractUrlsFromText,l as formatBytes,o as generateId,u as getAuthToken,c as getCookie,i as initializeEmbedUserId,h as isInIframe,f as mergeRefs,r as randomStr,p as safeJSONParse,s as setAuthToken};
@@ -0,0 +1 @@
1
+ import*as r from"react";var e;function t(){return t=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},t.apply(null,arguments)}var n=n=>r.createElement("svg",t({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 18 18"},n),e||(e=r.createElement("path",{fill:"currentColor",d:"m11.06 6.02.92.92L2.92 16H2v-.92zM14.66 0c-.25 0-.51.1-.7.29l-1.83 1.83 3.75 3.75 1.83-1.83a.996.996 0 0 0 0-1.41L15.37.29c-.2-.2-.45-.29-.71-.29m-3.6 3.19L0 14.25V18h3.75L14.81 6.94z"})));export{n as default};
@@ -1 +1 @@
1
- import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as n,jsxs as s,Fragment as o}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useMemo as l,useImperativeHandle as c,useEffect as d}from"react";import"../../../node_modules/.pnpm/regenerator-runtime@0.14.1/node_modules/regenerator-runtime/runtime.js";import u,{useSpeechRecognition as m}from"react-speech-recognition";import{usePickaxeContext as p}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as f}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as h}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as g}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as v}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as b}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as y}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as x}from"../Addons/Document/hooks/useDocument.js";import{useScroll as j}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as w}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as O}from"../../../hooks/core/useHover.js";import{useMediaQuery as k}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as S,allowedImageMimeTypes as N,additionalAllowedFileExtensions as I}from"../../../common/documents.js";import{createParser as C}from"eventsource-parser";import E from"../../Icons/attach-vertical.svg.js";import _ from"../../Icons/arrow-right.svg.js";import A from"../../Icons/microphone.svg.js";import T from"../../Icons/stop.svg.js";import D from"../Addons/Document/List.js";import P from"../../Core/Textarea.js";import R from"../../Core/ErrorAlert.js";import L from"../../../common/error.js";import $ from"../../../common/cn.js";const W=i((({resubmitPrompt:i,onFocus:W,onBlur:B,onInputHeightChange:H,initSmitheryAuthData:F},J)=>{var U,M,V;const{origin:K,pickaxeId:X,sessionId:z,sender:q,senderType:G,portalId:Q,deploymentId:Y,deploymentType:Z,pickaxe:ee,styles:te,colors:ne,locale:se,forceMobile:oe,isNewChat:ie,isRtl:re,isEmailLogin:ae,isShowFeedbackMessage:le,setIsNewChat:ce,setIsShowIceBreaker:de,onGenerateComplete:ue}=p(),{token:me,isLoggedOut:pe,isSent:fe}=y(),{messages:he,isGenerating:ge,setMessages:ve,setStatus:be,setLimitData:ye,setError:xe}=f(),{documents:je,isUploading:we,documentError:Oe,onFileUpload:ke,setDocuments:Se,setDocumentError:Ne}=x(),{scrollStartSession:Ie,scrollEndSession:Ce,scrollToBottom:Ee}=j({auto:!0}),{artifacts:_e,currentPopupType:Ae,setArtifacts:Te,setCurrentArtifact:De}=w(),{height:Pe}=b(),Re=v(),[Le,$e]=r(""),[We,Be]=r(!1),[He,Fe]=r(!1),Je=a(null),Ue=a(""),Me=a(null),Ve=a(null),Ke=a(null),Xe=a(null),ze=a(null),qe=Math.max(.4*Pe,100),{transcript:Ge,listening:Qe,resetTranscript:Ye,browserSupportsSpeechRecognition:Ze}=m(),[et]=k("(max-width: 480px)"),tt=O(),{isHover:nt}=tt,st=e(tt,["isHover"]),ot=O(),{isHover:it}=ot,rt=e(ot,["isHover"]),at=O(),{isHover:lt}=at,ct=e(at,["isHover"]),dt=g(),ut=h(),mt="undefined"!=typeof window?window.location.hostname:"",pt="undefined"!=typeof window?window.location.href:"",ft="undefined"!=typeof window&&window.self!==window.top,ht=mt.includes("pickaxe.co")&&!pt.includes("https://studio.pickaxe.co/_embed")&&!ft,gt=null===(U=null==ee?void 0:ee.documentuploadtype)||void 0===U?void 0:U.startsWith("enduserupload"),vt=Ze&&(null==ee?void 0:ee.enablevoicetotext),bt="chat-input"===Z&&ie&&!fe,yt="chat-input"===Z&&ae&&pe&&fe,xt=null!==(M=null==ee?void 0:ee.placeholdertext)&&void 0!==M?M:re?"بماذا تريد أن تتحدث؟":"What do you want to talk about?",jt=We||He,wt=l((()=>{var e,t,n;return!!ie&&(!!ee&&(!Re.isLoading&&(!((null!==(t=null===(e=Re.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=ee.icebreakers)||void 0===n?void 0:n.length)&&(!le&&!bt)))))}),[ee,ie,le,bt,Re.data,Re.isLoading]),Ot=l((()=>{if(ge||we)return!1;const e=je.length>0&&je.every((e=>"finished"===e.status));return!(!Le.trim()&&!e)&&je.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[ge,we,Le,je]);c(J,(()=>({onSubmit:kt}))),d((()=>{de(wt)}),[wt]),d((()=>{var e;if(i){const t=Array.from(he),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;kt(n,!0)}}),[i]),d((()=>{if(!Xe.current||!H)return;const e=new ResizeObserver((e=>{for(const t of e)H(t.contentRect.height)}));return e.observe(Xe.current),()=>{e.disconnect()}}),[H]),d((()=>{if(!Qe)return;const e=Ue.current?`${Ue.current} `:"";$e(`${e}${Ge}`)}),[Ge,Qe]),d((()=>{if(!Ve.current)return;(()=>{if(!Ve.current)return;let e=Ve.current.scrollHeight>52;Le.includes("\n")||je.length?e=!0:Le.trim()||(e=!1),Be(e)})()}),[Le,je]),d((()=>{const e=Ve.current,t=Ke.current;if(!e||!t||We||Le.includes("\n"))return void Fe(!1);const n=window.getComputedStyle(e),s=`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${n.fontSize} / ${n.lineHeight} ${n.fontFamily}`,o=document.createElement("span");Object.assign(o.style,{font:s,letterSpacing:n.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),o.textContent=Le||xt,document.body.appendChild(o);const i=o.offsetWidth;o.remove();const r=parseFloat(n.paddingLeft)||0,a=parseFloat(n.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;Fe(i>l)}),[Le,We,xt]);const kt=(e,n=!1)=>t(void 0,void 0,void 0,(function*(){var t,s,o;try{if(ge||we)return;const i=je.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),r=i.map((e=>e.documentId)).filter(Boolean),a=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=r.length>0,c=null!=e?e:Le;if(!c&&!l)return;xe(""),Ne(""),ye(null),$e(""),ce(!1),be("fetching"),Ie(),Ee();const d=null!==(s=null===(t=null==ee?void 0:ee.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==s&&s&&r.length>0,u=[...n?Array.from(he.slice(0,he.length-1)):Array.from(he),...n?[]:[{id:he.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?r:[]}],{id:he.length+(n?0:2),role:"assistant",parts:[],documentIds:[]}];ve(u),Ee(),d&&Se([]);const m=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign(Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:K,pickaxeId:X,sessionId:z,senderType:G,value:c},d&&{documentIds:r}),q&&{sender:q}),me&&{studioSessionToken:me}),Q&&{portalId:Q}),Y&&{deploymentId:Y}),a.length>0&&{uploadedModelImages:a}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),ht&&{credentials:"include"})),p=yield m.json();if(!p.success){const e=new Error(p.error||"Failed to start generation");throw p.limitData&&(e.limitData=p.limitData),e}const f=p.submissionId;be("streaming"),ze.current=new AbortController;const h=u.length-1,g=[];let v=[...null!=_e?_e:[]],b=0,y=!1,x="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${f}?index=${b}`,{signal:null===(o=ze.current)||void 0===o?void 0:o.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();Me.current=t;const n=new TextDecoder,s=C({onEvent:e=>{var t,n;if(e.event&&"ping"!==e.event&&b++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data).error||"Something went wrong.";return xe(t),void(y=!0)}if("delta"===e.event){const s=JSON.parse(e.data);if("data-error"===s.type&&F){const e=s.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&s&&s[1])throw y=!0,F({smitheryId:t[1],serverId:n[1],name:s[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,F({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===s.type)x="",g.push({type:"text",content:"",isVisible:null===(t=s.isVisible)||void 0===t||t});else if("text-delta"===s.type)x+=s.delta,g[g.length-1].content=x;else if("text-end"===s.type)x="";else if("reasoning-start"===s.type)x="",g.push({type:"reasoning",content:"",isVisible:null===(n=s.isVisible)||void 0===n||n});else if("reasoning-delta"===s.type)x+=s.delta,g[g.length-1].content=x;else if("reasoning-end"===s.type)x="";else if(s.type.startsWith("data-")){const e=s;g.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}ve([...u.slice(0,h),Object.assign(Object.assign({},u[u.length-1]),{id:he.length+1,role:"assistant",parts:g})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Te([...v]),Ae.startsWith("inline")||De({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Te(v),Ae.startsWith("inline")||De({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Te(v),Ae.startsWith("inline")||De({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");v=v.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),Te(v)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Te(v.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);xe(t.error||"Something went wrong, please try again.")}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:o}=yield t.read();if(o)break;s.feed(n.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==ue||ue(z)}catch(e){if(e.limitData)ye(e.limitData),xe("");else{let t=L(e)||"";t&&!t.includes("Unexpected token 'A',")||(t="Oops! We're experiencing high traffic at the moment. Please try again later."),xe(t)}}finally{Ee(),be("idle"),Ce(),Me.current=null}}));return yt?null:n("div",Object.assign({className:$("flex w-full flex-shrink-0 flex-col items-center",!bt&&"px-4 pb-8"),dir:re?"rtl":"ltr"},{children:s("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[s("div",Object.assign({ref:Xe,className:$("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===te.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},ut),{maxHeight:`${qe}px`,overflowY:"auto"})},{children:[Qe&&s("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(V=ne.accent)&&void 0!==V?V:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:ne.text+"90"}},{children:"Listening..."}))]})),!ge&&je.length>0&&n(D,{className:"p-4 pb-0",isDisabled:ge}),n(P,Object.assign({ref:Ve,className:$(dt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Le.trim()&&!Le.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",re?"text-right":"text-left",jt&&"mb-12",Qe&&"text-transparent"),value:Le,placeholder:xt,onChange:e=>{if($e(e),H){const t=(e.match(/\n/g)||[]).length+1;if(!e)return void H(0);if(t>=11)return;let n=0;t>1&&(n=50),H(24*(t-1)+n)}},onKeyDown:e=>{oe||et||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),we||ge||kt()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);t.length>0&&(e.preventDefault(),ce(!1),yield ke(t))}))},W&&{onFocus:W},B&&{onBlur:B},{dir:re?"rtl":"ltr"})),n("div",Object.assign({ref:Ke,className:$("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",jt?"mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!jt&&ut.backgroundColor&&{backgroundColor:ut.backgroundColor}),{borderTopRightRadius:te.cornerRadius+"px",borderBottomRightRadius:te.cornerRadius+"px"})},{children:ge?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{ze.current&&(ze.current.abort(),ze.current=null),Me.current&&(Me.current.cancel(),Me.current=null),be("idle")},style:{backgroundColor:ne.accent,color:ne.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):Qe?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:u.stopListening,style:{backgroundColor:ne.accent,color:ne.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):s(o,{children:[gt&&s("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:it?ne.accent+"10":void 0,color:it?ne.accent:ne.accent+"80"},disabled:we||ge,onClick:()=>{var e;return null===(e=Je.current)||void 0===e?void 0:e.click()}},rt,{children:[n("input",{id:"file-upload",ref:Je,type:"file",accept:[...S,...N,...I].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){ce(!1),yield ke(Array.from(e.target.files||[])),e.target.value=""}))}),n(E,{className:"h-6 w-6 shrink-0"})]})),vt&&n("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:Qe?ne.accent:lt?ne.accent+"10":void 0,color:Qe?ne.accentText:lt?ne.accent:ne.accent+"80"},disabled:we||ge,onClick:()=>{Qe?u.stopListening():(Ue.current=Le,Ye(),u.startListening({continuous:!0,interimResults:!0,language:se||"en-US"}))}},ct,{children:n(A,{className:"h-5 w-5 shrink-0"})})),n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:nt||Ot?ne.accent:ne.accent+"10",color:nt||Ot?ne.accentText:ne.accent+"80"},disabled:!Ot,onClick:()=>kt()},st,{children:n(_,{className:$("h-6 w-6 shrink-0",re&&"scale-x-[-1] transform")})}))]})}))]})),Oe&&n(R,{error:Oe,className:"mt-3"})]}))}))}));W.displayName="Input";export{W as default};
1
+ import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as n,jsxs as s,Fragment as o}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useMemo as l,useImperativeHandle as c,useEffect as d}from"react";import"../../../node_modules/.pnpm/regenerator-runtime@0.14.1/node_modules/regenerator-runtime/runtime.js";import u,{useSpeechRecognition as m}from"react-speech-recognition";import{usePickaxeContext as p}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as f}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as h}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as g}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as v}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as b}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as y}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as j}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as w}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as O}from"../../../hooks/core/useHover.js";import{useMediaQuery as k}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as S,allowedImageMimeTypes as N,additionalAllowedFileExtensions as I}from"../../../common/documents.js";import{createParser as C}from"eventsource-parser";import E from"../../Icons/attach-vertical.svg.js";import _ from"../../Icons/arrow-right.svg.js";import A from"../../Icons/microphone.svg.js";import T from"../../Icons/stop.svg.js";import D from"../Addons/Document/List.js";import P from"../../Core/Textarea.js";import R from"../../Core/ErrorAlert.js";import L from"../../../common/error.js";import $ from"../../../common/cn.js";import{initializeEmbedUserId as W}from"../../../common/utils.js";const B=i((({resubmitPrompt:i,onFocus:B,onBlur:H,onInputHeightChange:F,initSmitheryAuthData:J},U)=>{var M,V,K;const{origin:X,pickaxeId:z,sessionId:q,sender:G,senderType:Q,portalId:Y,deploymentId:Z,deploymentType:ee,pickaxe:te,styles:ne,colors:se,locale:oe,forceMobile:ie,isNewChat:re,isRtl:ae,isEmailLogin:le,isShowFeedbackMessage:ce,setIsNewChat:de,setIsShowIceBreaker:ue,onGenerateComplete:me}=p(),{token:pe,isLoggedOut:fe,isSent:he}=y(),{messages:ge,isGenerating:ve,setMessages:be,setStatus:ye,setLimitData:je,setError:xe}=f(),{documents:we,isUploading:Oe,documentError:ke,onFileUpload:Se,setDocuments:Ne,setDocumentError:Ie}=j(),{scrollStartSession:Ce,scrollEndSession:Ee,scrollToBottom:_e}=x({auto:!0}),{artifacts:Ae,currentPopupType:Te,setArtifacts:De,setCurrentArtifact:Pe}=w(),{height:Re}=b(),Le=v(),[$e,We]=r(""),[Be,He]=r(!1),[Fe,Je]=r(!1),Ue=a(null),Me=a(""),Ve=a(null),Ke=a(null),Xe=a(null),ze=a(null),qe=a(null),Ge=Math.max(.4*Re,100),{transcript:Qe,listening:Ye,resetTranscript:Ze,browserSupportsSpeechRecognition:et}=m(),[tt]=k("(max-width: 480px)"),nt=O(),{isHover:st}=nt,ot=e(nt,["isHover"]),it=O(),{isHover:rt}=it,at=e(it,["isHover"]),lt=O(),{isHover:ct}=lt,dt=e(lt,["isHover"]),ut=g(),mt=h(),pt="undefined"!=typeof window?window.location.hostname:"",ft="undefined"!=typeof window?window.location.href:"",ht="undefined"!=typeof window&&window.self!==window.top,gt=pt.includes("pickaxe.co")&&!ft.includes("https://studio.pickaxe.co/_embed")&&!ht,vt=null===(M=null==te?void 0:te.documentuploadtype)||void 0===M?void 0:M.startsWith("enduserupload"),bt=et&&(null==te?void 0:te.enablevoicetotext),yt="chat-input"===ee&&re&&!he,jt="chat-input"===ee&&le&&fe&&he,xt=null!==(V=null==te?void 0:te.placeholdertext)&&void 0!==V?V:ae?"بماذا تريد أن تتحدث؟":"What do you want to talk about?",wt=Be||Fe,Ot=l((()=>{var e,t,n;return!!re&&(!!te&&(!Le.isLoading&&(!((null!==(t=null===(e=Le.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=te.icebreakers)||void 0===n?void 0:n.length)&&(!ce&&!yt)))))}),[te,re,ce,yt,Le.data,Le.isLoading]),kt=l((()=>{if(ve||Oe)return!1;const e=we.length>0&&we.every((e=>"finished"===e.status));return!(!$e.trim()&&!e)&&we.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[ve,Oe,$e,we]);c(U,(()=>({onSubmit:St}))),d((()=>{ue(Ot)}),[Ot]),d((()=>{var e;if(i){const t=Array.from(ge),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;St(n,!0)}}),[i]),d((()=>{if(!ze.current||!F)return;const e=new ResizeObserver((e=>{for(const t of e)F(t.contentRect.height)}));return e.observe(ze.current),()=>{e.disconnect()}}),[F]),d((()=>{if(!Ye)return;const e=Me.current?`${Me.current} `:"";We(`${e}${Qe}`)}),[Qe,Ye]),d((()=>{if(!Ke.current)return;(()=>{if(!Ke.current)return;let e=Ke.current.scrollHeight>52;$e.includes("\n")||we.length?e=!0:$e.trim()||(e=!1),He(e)})()}),[$e,we]),d((()=>{const e=Ke.current,t=Xe.current;if(!e||!t||Be||$e.includes("\n"))return void Je(!1);const n=window.getComputedStyle(e),s=`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${n.fontSize} / ${n.lineHeight} ${n.fontFamily}`,o=document.createElement("span");Object.assign(o.style,{font:s,letterSpacing:n.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),o.textContent=$e||xt,document.body.appendChild(o);const i=o.offsetWidth;o.remove();const r=parseFloat(n.paddingLeft)||0,a=parseFloat(n.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;Je(i>l)}),[$e,Be,xt]);const St=(e,n=!1)=>t(void 0,void 0,void 0,(function*(){var t,s,o;try{if(ve||Oe)return;const i=we.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),r=i.map((e=>e.documentId)).filter(Boolean),a=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=r.length>0,c=null!=e?e:$e;if(!c&&!l)return;xe(""),Ie(""),je(null),We(""),de(!1),ye("fetching"),Ce(),_e();const d=null!==(s=null===(t=null==te?void 0:te.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==s&&s&&r.length>0,u=[...n?Array.from(ge.slice(0,ge.length-1)):Array.from(ge),...n?[]:[{id:ge.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?r:[]}],{id:ge.length+(n?0:2),role:"assistant",parts:[],documentIds:[]}];be(u),_e(),d&&Ne([]);const m=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign(Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:X,pickaxeId:z,sessionId:q,senderType:Q,value:c},d&&{documentIds:r}),G&&{sender:G}),pe&&{studioSessionToken:pe}),!pe&&!G&&{sender:W()}),Y&&{portalId:Y}),Z&&{deploymentId:Z}),a.length>0&&{uploadedModelImages:a}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),gt&&{credentials:"include"})),p=yield m.json();if(!p.success){const e=new Error(p.error||"Failed to start generation");throw p.limitData&&(e.limitData=p.limitData),e}const f=p.submissionId;ye("streaming"),qe.current=new AbortController;const h=u.length-1,g=[];let v=[...null!=Ae?Ae:[]],b=0,y=!1,j="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${f}?index=${b}`,{signal:null===(o=qe.current)||void 0===o?void 0:o.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();Ve.current=t;const n=new TextDecoder,s=C({onEvent:e=>{var t,n;if(e.event&&"ping"!==e.event&&b++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data).error||"Something went wrong.";return xe(t),void(y=!0)}if("delta"===e.event){const s=JSON.parse(e.data);if("data-error"===s.type&&J){const e=s.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&s&&s[1])throw y=!0,J({smitheryId:t[1],serverId:n[1],name:s[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,J({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===s.type)j="",g.push({type:"text",content:"",isVisible:null===(t=s.isVisible)||void 0===t||t});else if("text-delta"===s.type)j+=s.delta,g[g.length-1].content=j;else if("text-end"===s.type)j="";else if("reasoning-start"===s.type)j="",g.push({type:"reasoning",content:"",isVisible:null===(n=s.isVisible)||void 0===n||n});else if("reasoning-delta"===s.type)j+=s.delta,g[g.length-1].content=j;else if("reasoning-end"===s.type)j="";else if(s.type.startsWith("data-")){const e=s;g.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}be([...u.slice(0,h),Object.assign(Object.assign({},u[u.length-1]),{id:ge.length+1,role:"assistant",parts:g})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),De([...v]),Te.startsWith("inline")||Pe({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),De(v),Te.startsWith("inline")||Pe({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),De(v),Te.startsWith("inline")||Pe({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");v=v.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),De(v)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);De(v.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);xe(t.error||"Something went wrong, please try again.")}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:o}=yield t.read();if(o)break;s.feed(n.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==me||me(q)}catch(e){if(e.limitData)je(e.limitData),xe("");else{let t=L(e)||"";t&&!t.includes("Unexpected token 'A',")||(t="Oops! We're experiencing high traffic at the moment. Please try again later."),xe(t)}}finally{_e(),ye("idle"),Ee(),Ve.current=null}}));return jt?null:n("div",Object.assign({className:$("flex w-full flex-shrink-0 flex-col items-center",!yt&&"px-4 pb-8"),dir:ae?"rtl":"ltr"},{children:s("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[s("div",Object.assign({ref:ze,className:$("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===ne.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},mt),{maxHeight:`${Ge}px`,overflowY:"auto"})},{children:[Ye&&s("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(K=se.accent)&&void 0!==K?K:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:se.text+"90"}},{children:"Listening..."}))]})),!ve&&we.length>0&&n(D,{className:"p-4 pb-0",isDisabled:ve}),n(P,Object.assign({ref:Ke,className:$(ut.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!$e.trim()&&!$e.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ae?"text-right":"text-left",wt&&"mb-12",Ye&&"text-transparent"),value:$e,placeholder:xt,onChange:e=>{if(We(e),F){const t=(e.match(/\n/g)||[]).length+1;if(!e)return void F(0);if(t>=11)return;let n=0;t>1&&(n=50),F(24*(t-1)+n)}},onKeyDown:e=>{ie||tt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Oe||ve||St()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);t.length>0&&(e.preventDefault(),de(!1),yield Se(t))}))},B&&{onFocus:B},H&&{onBlur:H},{dir:ae?"rtl":"ltr"})),n("div",Object.assign({ref:Xe,className:$("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",wt?"mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!wt&&mt.backgroundColor&&{backgroundColor:mt.backgroundColor}),{borderTopRightRadius:ne.cornerRadius+"px",borderBottomRightRadius:ne.cornerRadius+"px"})},{children:ve?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{qe.current&&(qe.current.abort(),qe.current=null),Ve.current&&(Ve.current.cancel(),Ve.current=null),ye("idle")},style:{backgroundColor:se.accent,color:se.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):Ye?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:u.stopListening,style:{backgroundColor:se.accent,color:se.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):s(o,{children:[vt&&s("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:rt?se.accent+"10":void 0,color:rt?se.accent:se.accent+"80"},disabled:Oe||ve,onClick:()=>{var e;return null===(e=Ue.current)||void 0===e?void 0:e.click()}},at,{children:[n("input",{id:"file-upload",ref:Ue,type:"file",accept:[...S,...N,...I].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){de(!1),yield Se(Array.from(e.target.files||[])),e.target.value=""}))}),n(E,{className:"h-6 w-6 shrink-0"})]})),bt&&n("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:Ye?se.accent:ct?se.accent+"10":void 0,color:Ye?se.accentText:ct?se.accent:se.accent+"80"},disabled:Oe||ve,onClick:()=>{Ye?u.stopListening():(Me.current=$e,Ze(),u.startListening({continuous:!0,interimResults:!0,language:oe||"en-US"}))}},dt,{children:n(A,{className:"h-5 w-5 shrink-0"})})),n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:st||kt?se.accent:se.accent+"10",color:st||kt?se.accentText:se.accent+"80"},disabled:!kt,onClick:()=>St()},ot,{children:n(_,{className:$("h-6 w-6 shrink-0",ae&&"scale-x-[-1] transform")})}))]})}))]})),ke&&n(R,{error:ke,className:"mt-3"})]}))}))}));B.displayName="Input";export{B as default};
@@ -1 +1 @@
1
- import{__awaiter as t}from"../../../_virtual/_tslib.js";import{jsxs as e,jsx as o,Fragment as r}from"react/jsx-runtime";import{useState as n,useRef as i,useEffect as s}from"react";import{usePickaxeContext as a}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as c}from"../Addons/Auth/hooks/useAuthContext.js";import{useDimensionContext as l}from"../../../hooks/pickaxe/useDimensionContext.js";import{useDocument as u}from"../Addons/Document/hooks/useDocument.js";import{useStyleFontSize as m}from"../../../hooks/studio/useStyleFontSize.js";import d from"./History/index.js";import p from"./Input.js";import f from"../../Icons/attach-vertical.svg.js";import h from"../../../common/cn.js";const g=()=>{const{deploymentType:g,isNewChat:b,setIsNewChat:v}=a(),{isSent:x}=c(),{width:j,height:D,setDimension:y}=l(),{setDocuments:k,onFileUpload:w}=u(),A=m(),[I,N]=n(0),[F,O]=n(!1),[P,S]=n(!1),C=i(null),H=i(null),T=i(0),[z,R]=n(null),[_,B]=n(!1),E="chat-input"===g&&b&&!x;s((()=>()=>{k([])}),[]),s((()=>{if(!C.current)return;const t=new ResizeObserver((t=>{for(const e of t){const{width:t,height:o}=e.contentRect;y(parseInt(t.toFixed(0)),parseInt(o.toFixed(0)))}}));return t.observe(C.current),()=>{t.disconnect()}}),[C.current]);return e("div",Object.assign({ref:C,className:"relative flex h-full w-full flex-col items-center",onDragEnter:t=>{t.preventDefault(),t.stopPropagation(),T.current+=1,t.dataTransfer.items&&t.dataTransfer.items.length>0&&S(!0)},onDragLeave:t=>{t.preventDefault(),t.stopPropagation(),T.current-=1,0===T.current&&S(!1)},onDragOver:t=>{t.preventDefault(),t.stopPropagation()},onDrop:e=>t(void 0,void 0,void 0,(function*(){e.preventDefault(),e.stopPropagation(),S(!1),T.current=0;const t=Array.from(e.dataTransfer.files||[]);t.length>0&&(v(!1),yield w(t))}))},{children:[P&&e("div",Object.assign({className:"absolute inset-0 z-50 flex flex-col items-center justify-center rounded-lg bg-white/80 backdrop-blur-sm transition-all duration-300"},{children:[o("div",Object.assign({className:"flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-lg animate-bounce text-black"},{children:o(f,{className:"h-10 w-10"})})),o("h3",Object.assign({className:h(A.h3,"mt-6 font-semibold text-c-primary text-black")},{children:"Drop files to upload"})),o("p",Object.assign({className:h(A.b2,"mt-2 opacity-60 text-black")},{children:"Add anything to the conversation"}))]})),E?o(p,{}):e(r,{children:[o(d,{additionalScrollHeight:I,isForceHideInfo:D<=545||j<=350||F,isInputFocused:F,onSubmit:e=>t(void 0,void 0,void 0,(function*(){H.current&&H.current.onSubmit(e)})),smitheryAuthData:z,resubmitPrompt:()=>{R(null),B(!0)}}),o(p,{ref:H,onFocus:()=>O(!0),onBlur:()=>O(!1),onInputHeightChange:N,initSmitheryAuthData:t=>R(t),resubmitPrompt:_})]})]}))};export{g as default};
1
+ import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsxs as t,jsx as o,Fragment as n}from"react/jsx-runtime";import{useState as s,useRef as r,useEffect as i,useCallback as a}from"react";import{usePickaxeContext as c}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as l}from"../Addons/Auth/hooks/useAuthContext.js";import{useDimensionContext as d}from"../../../hooks/pickaxe/useDimensionContext.js";import{useDocument as m}from"../Addons/Document/hooks/useDocument.js";import{useStyleFontSize as u}from"../../../hooks/studio/useStyleFontSize.js";import p from"./History/index.js";import h from"./Input.js";import f from"../../Icons/attach-vertical.svg.js";import b from"../../../common/cn.js";import g from"../../../common/api/pickaxe.js";import{Check as v,X as x,MoreHorizontal as w}from"lucide-react";import{v4 as j}from"uuid";import y from"../../Icons/trash-2.svg.js";import N from"../../Icons/pencil.svg.js";import{useResponseContext as k}from"../../../hooks/pickaxe/useResponseContext.js";const O=({children:e,className:t})=>o("div",Object.assign({className:b("flex items-center gap-2 transition-all duration-200 select-none","rounded-[40px] h-[72px] border border-white/70 px-6 py-3 bg-white/10 backdrop-blur-md",t)},{children:e})),F=({text:e,icon:n,className:s,onClick:r})=>o("div",Object.assign({onClick:r,className:b("relative flex items-center justify-center px-3 h-full shrink-0 transition-all duration-200 rounded-[40px] border border-white/70 bg-[#FFFFFF1A]",s)},{children:t("div",Object.assign({className:"flex items-center gap-2 z-20"},{children:[n&&o("img",{src:n,alt:"",className:"h-5 w-5 rounded-full object-cover"}),o("p",Object.assign({className:"text-sm font-medium truncate max-w-[150px] text-foreground"},{children:e}))]}))})),C=({text:n,className:a,onRename:c,onDelete:l})=>{const[d,m]=s(!1),[u,p]=s(!1),[h,f]=s(n),[g,j]=s(!1),k=r(null),O=r(null);i((()=>{u||f(n)}),[n,u]),i((()=>{const e=e=>{O.current&&!O.current.contains(e.target)&&m(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)}),[]);const F=()=>e(void 0,void 0,void 0,(function*(){h.trim()&&(j(!0),yield c(h),j(!1),p(!1))})),C=()=>{f(n),p(!1)};return t("div",Object.assign({ref:O,className:"relative z-40 h-full"},{children:[o("div",Object.assign({className:b("relative flex items-center justify-center px-3 h-full shrink-0 rounded-[40px] overflow-visible transition-all duration-200 cursor-pointer group border border-white/70 bg-[#FFFFFF1A]",a),onClick:e=>{e.stopPropagation(),u||d?d&&m(!1):m(!0)}},{children:t("div",u?Object.assign({className:"flex items-center gap-2 z-20 min-w-[140px]",onClick:e=>e.stopPropagation()},{children:[o("input",{autoFocus:!0,type:"text",value:h,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&F(),"Escape"===e.key&&C()},className:"bg-transparent border-b border-black/30 text-sm font-medium focus:outline-none w-full min-w-[80px] text-foreground"}),o("button",Object.assign({onClick:F,disabled:g,className:"p-1 rounded hover:bg-black/10 text-green-600"},{children:o(v,{className:"h-4 w-4"})})),o("button",Object.assign({onClick:C,disabled:g,className:"p-1 rounded hover:bg-black/10 text-red-600"},{children:o(x,{className:"h-4 w-4"})}))]}):Object.assign({className:"flex items-center gap-2 z-20 max-w-[200px]"},{children:[o("p",Object.assign({className:"text-sm font-medium truncate text-foreground"},{children:n})),o(w,{className:b("h-4 w-4 opacity-50 group-hover:opacity-100 transition-opacity")})]}))})),d&&t("div",Object.assign({className:"absolute top-full right-0 mt-2 w-48 shadow-xl z-50 rounded-[16px] border border-white/70 bg-neutral-400 backdrop-blur-md overflow-hidden animate-in fade-in zoom-in-95 duration-100",ref:k},{children:[t("button",Object.assign({onClick:e=>{e.stopPropagation(),m(!1),p(!0)},className:"w-full text-left px-4 py-3 flex items-center gap-3 transition-colors border-b border-white/10 hover:bg-white/10"},{children:[o(N,{className:"h-4 w-4"}),o("span",Object.assign({className:"font-medium text-sm"},{children:"Rename chat"}))]})),t("button",Object.assign({onClick:e=>{e.stopPropagation(),m(!1),l()},className:"w-full text-left px-4 py-3 flex items-center gap-3 transition-colors hover:bg-white/10"},{children:[o(y,{className:"h-4 w-4"}),o("span",Object.assign({className:"font-medium text-sm"},{children:"Delete chat"}))]}))]}))]}))},D=()=>{const{deploymentType:v,isNewChat:x,setIsNewChat:w,sessionId:y,setSessionId:N,pickaxeId:D,sender:I,colors:P,styles:z,pickaxe:A,isEmbed:E}=c(),{isSent:S}=l(),{width:_,height:R,setDimension:T}=d(),{setDocuments:H,onFileUpload:L}=m(),{isGenerating:B}=k(),G=u(),[K,U]=s(0),[q,J]=s(!1),[M,Q]=s(!1),V=r(null),W=r(null),X=r(0),[Y,Z]=s(null),[$,ee]=s(!1),te="chat-input"===v&&x&&!S;i((()=>()=>{H([])}),[]);const oe=a((()=>{if(!D||!I)return;const t=(o=0)=>e(void 0,void 0,void 0,(function*(){var e;try{const t=yield g.post("/get_pickaxe_conversation",{sessionId:y,userId:I});if(t.data&&t.data.success){const e=t.data.title;if(e&&"Conversation Title"!==e)return void se(e)}else console.error("Failed to load conversation:",null===(e=t.data)||void 0===e?void 0:e.error)}catch(e){console.error("Error fetching conversation:",e)}o<20&&setTimeout((()=>t(o+1)),3e3)}));t()}),[D,I,y]);i((()=>{B||x||!y||oe()}),[B,x,y,oe]),i((()=>{if(!V.current)return;const e=new ResizeObserver((e=>{for(const t of e){const{width:e,height:o}=t.contentRect;T(parseInt(e.toFixed(0)),parseInt(o.toFixed(0)))}}));return e.observe(V.current),()=>{e.disconnect()}}),[V.current]);const[ne,se]=s("New Chat"),re=(null==A?void 0:A.formtitle)||"Pickaxe",ie=(null==A?void 0:A.coverphoto)||void 0,ae=!te&&!E;return t("div",Object.assign({ref:V,className:"relative flex h-full w-full flex-col items-center overflow-hidden",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),X.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&Q(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),X.current-=1,0===X.current&&Q(!1)},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e(void 0,void 0,void 0,(function*(){t.preventDefault(),t.stopPropagation(),Q(!1),X.current=0;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(w(!1),yield L(e))}))},{children:[M&&t("div",Object.assign({className:"absolute inset-0 z-50 flex flex-col items-center justify-center rounded-lg bg-white/80 backdrop-blur-sm transition-all duration-300"},{children:[o("div",Object.assign({className:"flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-lg animate-bounce text-black"},{children:o(f,{className:"h-10 w-10"})})),o("h3",Object.assign({className:b(G.h3,"mt-6 font-semibold text-c-primary text-black")},{children:"Drop files to upload"})),o("p",Object.assign({className:b(G.b2,"mt-2 opacity-60 text-black")},{children:"Add anything to the conversation"}))]})),te?o(h,{}):t(n,{children:[t("div",Object.assign({className:b("flex flex-col w-full items-center h-full relative z-0",ae?"pt-6":"")},{children:[ae&&o("div",Object.assign({className:"w-full max-w-3xl px-4 md:px-0 flex justify-start z-30 mb-4 animate-in fade-in slide-in-from-top-4 duration-500"},{children:t(O,Object.assign({colors:P,styles:z},{children:[o(F,{text:re,icon:ie,colors:P,styles:z}),x||"New Chat"===ne?o(F,{text:ne,colors:P,styles:z}):o(C,{text:ne,sessionId:y,colors:P,styles:z,onRename:t=>e(void 0,void 0,void 0,(function*(){if(y)try{yield g.post("/edit_conversation_name",{sessionId:y,name:t,userId:I}),se(t)}catch(e){console.error("Error renaming chat:",e),alert("Failed to rename chat.")}})),onDelete:()=>e(void 0,void 0,void 0,(function*(){if(y&&window.confirm("Are you sure you want to delete this conversation?"))try{yield g.post("/delete_pickaxe_conversation",{sessionId:y,userId:I}),w(!0),N(j()),se("New Chat")}catch(e){console.error("Error deleting chat:",e),alert("Failed to delete chat.")}}))})]}))})),o(p,{additionalScrollHeight:K,isForceHideInfo:R<=545||_<=350||q,isInputFocused:q,onSubmit:t=>e(void 0,void 0,void 0,(function*(){W.current&&W.current.onSubmit(t)})),smitheryAuthData:Y,resubmitPrompt:()=>{Z(null),ee(!0)}})]})),o(h,{ref:W,onFocus:()=>J(!0),onBlur:()=>J(!1),onInputHeightChange:U,initSmitheryAuthData:e=>Z(e),resubmitPrompt:$})]})]}))};export{D as default};
@@ -1 +1 @@
1
- import{__awaiter as e}from"../../../../_virtual/_tslib.js";import{jsxs as t,jsx as s}from"react/jsx-runtime";import{useState as n,useRef as i,useMemo as o}from"react";import{usePickaxeContext as r}from"../../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as a}from"../../Addons/Auth/hooks/useAuthContext.js";import{useResponseContext as l}from"../../../../hooks/pickaxe/useResponseContext.js";import{useDocument as d}from"../../Addons/Document/hooks/useDocument.js";import{useScroll as c}from"../../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as p}from"../../Addons/Artifact/hooks/useArtifactContext.js";import{extractUrlsFromText as u}from"../../../../common/utils.js";import{encode as m}from"@nem035/gpt-3-encoder";import{createParser as f}from"eventsource-parser";import g from"../../common/PickaxeBranding.js";import h from"../../common/PickaxeButton.js";import v from"../../../../common/error.js";const b=({questions:b,resetQuestions:y})=>{var j;const{origin:O,pickaxeId:x,sender:w,senderType:k,portalId:C,deploymentId:I,pickaxe:S,misc:N,translations:P,isRtl:_,setSessionId:A,setIsNewChat:E,onGenerateComplete:T}=r(),{token:D}=a(),{isGenerating:L,setResponse:U,setMessages:J,setStatus:q,setLimitData:B,setError:K,setIsSwitchedToChat:R}=l(),{documents:W,websiteLink:X,isUploading:V,onWebsiteUpload:$,setDocuments:G,setDocumentError:M}=d(),{scrollStartSession:F,scrollEndSession:Q,scrollToTarget:Y}=c({auto:!(null==S?void 0:S.enablechatresponses)}),{artifacts:z,currentPopupType:H,setArtifacts:Z,setCurrentArtifact:ee}=p(),[te,se]=n(!1),ne=i(null),ie=o((()=>b.some((e=>("Short Answer"===e.type||"Long Answer"===e.type||"long"===e.type||"short"===e.type||"Checkbox"===e.type||"Knowledge Upload"===e.type||e.id.includes("documentupload"))&&e.input.length>0))),[b]);return t("div",Object.assign({className:"mt-4 flex flex-wrap justify-between gap-4 items-center",dir:_?"rtl":"ltr"},{children:[t("div",Object.assign({className:"flex items-center flex-grow flex-wrap gap-2"},{children:[s(h,Object.assign({className:"px-5 min-h-[42px]",isDisabled:V||L||te,onClick:()=>e(void 0,void 0,void 0,(function*(){var e,t,s;try{if(L||V||te)return;K(""),M(""),B(null),U(null);const n=["Multiple Choice","Checkbox"];for(const e of b){if(m(e.input).length>e.maxLength&&!n.includes(e.type))throw new Error("One or more of your responses is too long!");if(e.isRequired&&!e.input.trim()&&"userinput:documentupload"!==e.id)throw new Error("You must fill out all required fields.")}const i=W.filter((e=>"finished"===e.status)),o=W.map((e=>e.name)),r=null!==(t=null===(e=null==S?void 0:S.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==t&&t,a=b.some((e=>"userinput:documentupload"===e.id&&e.isRequired)),l=u(X).filter((e=>!o.includes(e)));if(l.length){const e=l[l.length-1];se(!0);const t=yield $(e);t&&(i.push(t),yield new Promise((e=>setTimeout(e,5e3)))),se(!1)}else if(a&&r&&!i.length)return void M("Please paste a valid website/video link or drag a file to add to the knowledge base.");const d=i.map((e=>e.documentId||"")).filter(Boolean),c=r&&d.length>0,p={};b.forEach((e=>{p[e.id]="Knowledge Upload"===e.type||e.id.includes("documentupload")?i.map((e=>e.name)).join(",")||"":e.input})),q("fetching"),F(),Y();const g=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}),body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:O,pickaxeId:x,senderType:k,valueObj:p},c&&{documentIds:d}),w&&{sender:w}),D&&{studioSessionToken:D}),C&&{portalId:C}),I&&{deploymentId:I}))}),h=yield g.json();if(!h.success){const e=new Error(h.error||"Failed to start generation");throw h.limitData&&(e.limitData=h.limitData),e}const v=h.submissionId,y=h.sessionId,j={sessionId:y,documentIds:c?d:[],question:{inputs:b.map((e=>({id:e.id,question:e.main,answer:e.input}))),responseParts:[]},messageCount:0,sentAt:new Date};U(j),(null==S?void 0:S.enablechatresponses)&&(A(y),E(!1),R(!0),J([{id:0,role:"assistant",parts:[],documentIds:[]}])),c&&G([]),q("streaming"),ne.current=new AbortController;const N=[];let P=[...null!=z?z:[]],_=0,Q=!1,ie="";for(;!Q;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${v}?index=${_}`,{signal:null===(s=ne.current)||void 0===s?void 0:s.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader(),n=new TextDecoder,i=f({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&_++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data).error||"Something went wrong.";return K(t),void(Q=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("text-start"===n.type)ie="",N.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)ie+=n.delta,N[N.length-1].content=ie;else if("text-end"===n.type)ie="";else if("reasoning-start"===n.type)ie="",N.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)ie+=n.delta,N[N.length-1].content=ie;else if("reasoning-end"===n.type)ie="";else if(n.type.startsWith("data-")){const e=n;N.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}const i=Object.assign(Object.assign({},j),{question:Object.assign(Object.assign({},j.question),{responseParts:[...N]})});U(i),(null==S?void 0:S.enablechatresponses)&&J([{id:0,role:"assistant",parts:[...N],documentIds:[]}])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);P=P.filter((e=>!(e.id===t.id&&e.version===t.version))),P.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Z([...P]),H.startsWith("inline")||ee({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);P=P.filter((e=>!(e.id===t.id&&e.version===t.version))),P.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Z([...P]),H.startsWith("inline")||ee({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);P=P.filter((e=>!(e.id===t.id&&e.version===t.version))),P.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Z([...P]),H.startsWith("inline")||ee({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");P=P.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Z([...P])}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Z(P.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}}else Q=!0}});for(;;){const{value:e,done:s}=yield t.read();if(s)break;i.feed(n.decode(e))}Q||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("AbortError"===e.name)return void(Q=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==T||T(y)}catch(e){let t=v(e)||"";t&&!t.includes("Unexpected token 'A',")||(t="Oops! We're experiencing high traffic at the moment. Please try again later."),K(t),Y()}finally{q("idle"),se(!1),Q()}}))},{children:te?(null==P?void 0:P.processing)||"Processing...":V?(null==P?void 0:P.uploading)||"Uploading...":L?(null==P?void 0:P.loading)||"Loading...":null!==(j=null==S?void 0:S.submittext)&&void 0!==j?j:"Submit"})),ie&&s(h,Object.assign({variant:"transparent-text",className:"min-h-[42px] px-5",isDisabled:V||L||te,onClick:y},{children:(null==P?void 0:P["clear-form"])||"Clear form"}))]})),!N.isWhiteLabel&&s(g,{containerClassName:"justify-end"})]}))};export{b as default};
1
+ import{__awaiter as e}from"../../../../_virtual/_tslib.js";import{jsxs as t,jsx as s}from"react/jsx-runtime";import{useState as n,useRef as i,useMemo as o}from"react";import{usePickaxeContext as r}from"../../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as a}from"../../Addons/Auth/hooks/useAuthContext.js";import{useResponseContext as l}from"../../../../hooks/pickaxe/useResponseContext.js";import{useDocument as d}from"../../Addons/Document/hooks/useDocument.js";import{useScroll as c}from"../../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as p}from"../../Addons/Artifact/hooks/useArtifactContext.js";import{extractUrlsFromText as u,initializeEmbedUserId as m}from"../../../../common/utils.js";import{encode as f}from"@nem035/gpt-3-encoder";import{createParser as g}from"eventsource-parser";import h from"../../common/PickaxeBranding.js";import v from"../../common/PickaxeButton.js";import b from"../../../../common/error.js";const y=({questions:y,resetQuestions:j})=>{var O;const{origin:x,pickaxeId:w,sender:k,senderType:C,portalId:I,deploymentId:S,pickaxe:N,misc:P,translations:_,isRtl:A,setSessionId:E,setIsNewChat:T,onGenerateComplete:D}=r(),{token:L}=a(),{isGenerating:U,setResponse:J,setMessages:q,setStatus:B,setLimitData:K,setError:R,setIsSwitchedToChat:W}=l(),{documents:X,websiteLink:V,isUploading:$,onWebsiteUpload:G,setDocuments:M,setDocumentError:F}=d(),{scrollStartSession:Q,scrollEndSession:Y,scrollToTarget:z}=c({auto:!(null==N?void 0:N.enablechatresponses)}),{artifacts:H,currentPopupType:Z,setArtifacts:ee,setCurrentArtifact:te}=p(),[se,ne]=n(!1),ie=i(null),oe=o((()=>y.some((e=>("Short Answer"===e.type||"Long Answer"===e.type||"long"===e.type||"short"===e.type||"Checkbox"===e.type||"Knowledge Upload"===e.type||e.id.includes("documentupload"))&&e.input.length>0))),[y]);return t("div",Object.assign({className:"mt-4 flex flex-wrap justify-between gap-4 items-center",dir:A?"rtl":"ltr"},{children:[t("div",Object.assign({className:"flex items-center flex-grow flex-wrap gap-2"},{children:[s(v,Object.assign({className:"px-5 min-h-[42px]",isDisabled:$||U||se,onClick:()=>e(void 0,void 0,void 0,(function*(){var e,t,s;try{if(U||$||se)return;R(""),F(""),K(null),J(null);const n=["Multiple Choice","Checkbox"];for(const e of y){if(f(e.input).length>e.maxLength&&!n.includes(e.type))throw new Error("One or more of your responses is too long!");if(e.isRequired&&!e.input.trim()&&"userinput:documentupload"!==e.id)throw new Error("You must fill out all required fields.")}const i=X.filter((e=>"finished"===e.status)),o=X.map((e=>e.name)),r=null!==(t=null===(e=null==N?void 0:N.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==t&&t,a=y.some((e=>"userinput:documentupload"===e.id&&e.isRequired)),l=u(V).filter((e=>!o.includes(e)));if(l.length){const e=l[l.length-1];ne(!0);const t=yield G(e);t&&(i.push(t),yield new Promise((e=>setTimeout(e,5e3)))),ne(!1)}else if(a&&r&&!i.length)return void F("Please paste a valid website/video link or drag a file to add to the knowledge base.");const d=i.map((e=>e.documentId||"")).filter(Boolean),c=r&&d.length>0,p={};y.forEach((e=>{p[e.id]="Knowledge Upload"===e.type||e.id.includes("documentupload")?i.map((e=>e.name)).join(",")||"":e.input})),B("fetching"),Q(),z();const h=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}),body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:x,pickaxeId:w,senderType:C,valueObj:p},c&&{documentIds:d}),k&&{sender:k}),L&&{studioSessionToken:L}),!L&&!k&&{sender:m()}),I&&{portalId:I}),S&&{deploymentId:S}))}),v=yield h.json();if(!v.success){const e=new Error(v.error||"Failed to start generation");throw v.limitData&&(e.limitData=v.limitData),e}const b=v.submissionId,j=v.sessionId,O={sessionId:j,documentIds:c?d:[],question:{inputs:y.map((e=>({id:e.id,question:e.main,answer:e.input}))),responseParts:[]},messageCount:0,sentAt:new Date};J(O),(null==N?void 0:N.enablechatresponses)&&(E(j),T(!1),W(!0),q([{id:0,role:"assistant",parts:[],documentIds:[]}])),c&&M([]),B("streaming"),ie.current=new AbortController;const P=[];let _=[...null!=H?H:[]],A=0,Y=!1,oe="";for(;!Y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${b}?index=${A}`,{signal:null===(s=ie.current)||void 0===s?void 0:s.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader(),n=new TextDecoder,i=g({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&A++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data).error||"Something went wrong.";return R(t),void(Y=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("text-start"===n.type)oe="",P.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)oe+=n.delta,P[P.length-1].content=oe;else if("text-end"===n.type)oe="";else if("reasoning-start"===n.type)oe="",P.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)oe+=n.delta,P[P.length-1].content=oe;else if("reasoning-end"===n.type)oe="";else if(n.type.startsWith("data-")){const e=n;P.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}const i=Object.assign(Object.assign({},O),{question:Object.assign(Object.assign({},O.question),{responseParts:[...P]})});J(i),(null==N?void 0:N.enablechatresponses)&&q([{id:0,role:"assistant",parts:[...P],documentIds:[]}])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),ee([..._]),Z.startsWith("inline")||te({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),ee([..._]),Z.startsWith("inline")||te({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),ee([..._]),Z.startsWith("inline")||te({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");_=_.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),ee([..._])}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);ee(_.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}}else Y=!0}});for(;;){const{value:e,done:s}=yield t.read();if(s)break;i.feed(n.decode(e))}Y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("AbortError"===e.name)return void(Y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==D||D(j)}catch(e){let t=b(e)||"";t&&!t.includes("Unexpected token 'A',")||(t="Oops! We're experiencing high traffic at the moment. Please try again later."),R(t),z()}finally{B("idle"),ne(!1),Y()}}))},{children:se?(null==_?void 0:_.processing)||"Processing...":$?(null==_?void 0:_.uploading)||"Uploading...":U?(null==_?void 0:_.loading)||"Loading...":null!==(O=null==N?void 0:N.submittext)&&void 0!==O?O:"Submit"})),oe&&s(v,Object.assign({variant:"transparent-text",className:"min-h-[42px] px-5",isDisabled:$||U||se,onClick:j},{children:(null==_?void 0:_["clear-form"])||"Clear form"}))]})),!P.isWhiteLabel&&s(h,{containerClassName:"justify-end"})]}))};export{y as default};
@@ -1,10 +1,12 @@
1
1
  import type { Ref } from "react";
2
+ export declare const COOKIE_USER_ID = "PXE-uid";
2
3
  export declare const generateId: (length: number, prefix?: string, suffix?: string) => string;
3
4
  export declare const randomStr: (len: number, charOnly?: boolean) => string;
4
5
  export declare const extractUrlsFromText: (text: string) => string[];
5
6
  export declare const formatBytes: (bytes: number, decimals?: number) => string;
6
7
  export declare const getCookie: (name: string) => string | null;
7
8
  export declare const deleteCookie: (name: string) => void;
9
+ export declare const initializeEmbedUserId: () => string;
8
10
  export declare const getAuthToken: (studioId: string) => string | null;
9
11
  export declare const setAuthToken: (name: string, token: string) => void;
10
12
  export declare const deleteAuthToken: (name: string) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pickaxeproject/react",
3
- "version": "5.6.1-beta.6",
3
+ "version": "5.6.1-beta.8",
4
4
  "description": "Client utility library for Pickaxe",
5
5
  "repository": {
6
6
  "type": "git",