@rubytech/create-realagent 1.0.440 → 1.0.442

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,5 +0,0 @@
1
- import{C as e,D as t,S as n,T as r,_ as i,a,b as o,d as s,f as c,g as l,h as u,i as d,k as f,m as p,n as m,p as h,r as g,s as _,t as v,u as y,v as b,x,y as S}from"./ChatInput-D1ZgZMZz.js";var C=r(),w=f(t(),1),T=`image/jpeg,image/png,image/gif,image/webp,application/pdf,text/plain,text/markdown,text/csv`,E=new Set(T.split(`,`)),D=20*1024*1024,O=typeof window<`u`&&/^(localhost|127\.0\.0\.1|[a-z0-9-]+\.local)(:|$)/.test(window.location.hostname);function k(){let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function A(){let e=window.location.pathname.match(/^\/([a-z][a-z0-9-]{2,49})$/);return e?e[1]:void 0}function j(e){return[{key:`length`,label:`At least 8 characters`,met:e.length>=8},{key:`number`,label:`Contains a number`,met:/\d/.test(e)},{key:`special`,label:`Contains a special character`,met:/[^A-Za-z0-9]/.test(e)},{key:`whitespace`,label:`No leading or trailing spaces`,met:e.length>0&&e===e.trim()}]}function M(e,t){if(t===`phone`)return e.length>4?e.slice(0,e.length-4).replace(/\d/g,`•`)+` `+e.slice(-4):e;let n=e.indexOf(`@`);return n<=2?e:e.slice(0,2)+`•••`+e.slice(n)}function N(e){let[t,n]=(0,w.useState)(null),[r,i]=(0,w.useState)(null),[a,o]=(0,w.useState)(`loading`),[s,c]=(0,w.useState)(``),[l,u]=(0,w.useState)(null),d=(0,w.useMemo)(()=>A(),[]),f=(0,w.useRef)(d||``),p=(0,w.useRef)(null),m=(0,w.useRef)(null),h=(0,w.useRef)(!1),g=(0,w.useRef)(null),[_,v]=(0,w.useState)(`sign-in`),[y,b]=(0,w.useState)(null),x=(0,w.useRef)(null),S=(0,w.useRef)(null);(0,w.useEffect)(()=>{try{let e=sessionStorage.getItem(`maxy_session`);e&&(S.current=e)}catch{}},[]);let C=(0,w.useCallback)(t=>{p.current=t,n(t);try{sessionStorage.setItem(`maxy_session`,t)}catch{}o(`chat`),e(t)},[e]),T=(0,w.useCallback)(()=>{p.current=null;try{sessionStorage.removeItem(`maxy_session`)}catch{}n(null),o(`auth-required`),v(`sign-in`)},[]),E=(0,w.useCallback)(async e=>{try{let t=f.current,n=await fetch(`/api/access/verify-token`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({token:e,agentSlug:t})}),r=await n.json();n.ok?(x.current=r.session_key,b(r.grant),v(`set-password`),window.history.replaceState({},``,window.location.pathname)):v(`link-expired`)}catch{v(`sign-in`)}},[]);return{sessionId:t,sessionKeyRef:p,sessionError:r,pageState:a,setPageState:o,agentDisplayName:s,agentSlug:d,branding:l,resolvedSlugRef:f,ensureSession:(0,w.useCallback)(async()=>{if(p.current)return p.current;if(m.current)return m.current;let e=(async()=>{try{let e=S.current,t=await fetch(`/api/session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({session_id:k(),...d?{agent:d}:{},...e?{session_key:e}:{}})});if(!t.ok){let e=await t.json().catch(()=>({error:``}));return O&&console.error(`[session] POST /api/session failed: ${t.status} ${t.statusText}`,e),t.status===404?i(e.error||`Agent not found`):t.status===503&&i(e.error||`Service unavailable`),null}let r=await t.json();if(r.auth_required){r.agent_id&&(f.current=r.agent_id),c(r.displayName||``),r.branding&&u(r.branding),o(`auth-required`);let e=new URLSearchParams(window.location.search).get(`token`);return e?E(e):v(`sign-in`),null}p.current=r.session_key,n(r.session_key),r.branding&&u(r.branding),o(`chat`),r.resumed&&r.messages&&(h.current=!0,g.current=r.messages);try{sessionStorage.setItem(`maxy_session`,r.session_key)}catch{}return r.session_key}catch(e){return O&&console.error(`[session] fetch /api/session threw:`,e),i(`Unable to connect. Please check your connection and try again.`),null}finally{m.current=null}})();return m.current=e,e},[d,E]),enterChat:C,enterGate:T,resumedRef:h,resumeMessagesRef:g,gateState:_,setGateState:v,grantInfo:y,setGrantInfo:b,gateSessionKeyRef:x}}function P({sessionKeyRef:e,ensureSession:t,sessionError:n,pageState:r,inputRef:i}){let[a,o]=(0,w.useState)([]),[s,c]=(0,w.useState)(!1),u=(0,w.useRef)(!1),d=e=>{u.current=e,c(e)},f=(0,w.useCallback)(async a=>{if(!u.current){d(!0),o([{role:`maxy`,content:``,timestamp:Date.now()}]);try{let n=await fetch(`/api/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({greeting:!0,session_key:a})});if(n.status===401){e.current=null;try{sessionStorage.removeItem(`maxy_session`)}catch{}O&&console.warn(`[greeting] stale session, retrying with fresh session`);let r=await t();if(!r)return;n=await fetch(`/api/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({greeting:!0,session_key:r})})}if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error||`Something went wrong`)}let r=``,i=``,s=()=>{i&&(r+=i,i=``,o(e=>{let t=[...e];return t[0]={...t[0],content:r},t}))},c=setInterval(s,60);try{for await(let e of l(n)){if(e.error)throw Object.assign(Error(e.error),{fromSSE:!0});e.text&&(i+=e.text),e.type===`component`&&(s(),o(t=>{let n=[...t],r={...n[0]},i=[...r.components||[]];return i.push({name:e.name,data:e.data,submitted:!1}),n[0]={...r,components:i},n}))}}finally{clearInterval(c),s()}}catch(e){if(O&&console.error(`[chat] greeting failed:`,e),r===`auth-required`)return;let t=e instanceof Error?e.message:String(e);o([{role:`maxy`,content:e instanceof Error&&e.fromSSE?t:n??`I'm having trouble connecting right now. Try refreshing the page.`,timestamp:Date.now()}])}finally{d(!1),r===`chat`&&i.current?.focus()}}},[e,t,n,r,i]),p=(0,w.useCallback)(async(a,s)=>{let c=s?.hidden??!1,f=s?.files??[];if(!a&&f.length===0||u.current)return;d(!0);let p=f.map(e=>({filename:e.name,mimeType:e.type})),m={role:`visitor`,content:a,attachments:p.length>0?p:void 0,timestamp:Date.now(),hidden:c},h;o(e=>{let t=[...e,m,{role:`maxy`,content:``,timestamp:Date.now()}];return h=t.length-1,t});try{let n=await t();if(!n)throw Error(`session`);let r=e=>{if(f.length>0){let t=new FormData;t.append(`message`,a),t.append(`session_key`,e);for(let e of f)t.append(`attachments`,e);return{body:t,headers:{}}}return{body:JSON.stringify({message:a,session_key:e}),headers:{"Content-Type":`application/json`}}},{body:i,headers:s}=r(n),c=await fetch(`/api/chat`,{method:`POST`,headers:s,body:i});if(c.status===401){e.current=null;try{sessionStorage.removeItem(`maxy_session`)}catch{}O&&console.warn(`[session-expired] stale key cleared, retrying with fresh session`);let n=await t();if(!n)throw Error(`session`);({body:i,headers:s}=r(n)),c=await fetch(`/api/chat`,{method:`POST`,headers:s,body:i})}if(!c.ok){let e=await c.json().catch(()=>({}));throw Error(e.error||`Something went wrong`)}let u=``,d=``,p=()=>{d&&(u+=d,d=``,o(e=>{let t=[...e];return t[h]={...t[h],content:u},t}))},m=setInterval(p,60);try{for await(let e of l(c)){if(e.error)throw Object.assign(Error(e.error),{fromSSE:!0});e.text&&(d+=e.text),e.type===`component`&&(p(),o(t=>{let n=[...t],r={...n[h]},i=[...r.components||[]];return i.push({name:e.name,data:e.data,submitted:!1}),n[h]={...r,components:i},n}))}}finally{clearInterval(m),p()}}catch(e){if(O&&console.error(`[chat] sendMessage failed:`,e),r===`auth-required`)return;let t=e instanceof Error?e.message:String(e),i=e instanceof Error&&e.fromSSE;o(e=>{let r=[...e];return r[h]={...r[h],content:i?t:t===`session`?n??`I'm having trouble connecting right now. Try refreshing the page.`:`Sorry, I hit a snag. Try again in a moment.`},r})}finally{d(!1),r===`chat`&&i.current?.focus()}},[e,t,n,r,i]);return{messages:a,setMessages:o,isStreaming:s,sendMessage:p,sendGreeting:f,handleComponentSubmit:(0,w.useCallback)((e,t,n)=>{o(n=>{let r=[...n],i={...r[e]},a=[...i.components||[]];return a[t]={...a[t],submitted:!0},r[e]={...i,components:a},r}),p(n,{hidden:!0})},[p])}}var F=c();function I({value:e,onChange:t,onComplete:n,disabled:r}){let i=(0,w.useRef)([]);function a(n,r){r.key===`Backspace`?(r.preventDefault(),e[n]?t(e.slice(0,n)+e.slice(n+1)):n>0&&(t(e.slice(0,n-1)+e.slice(n)),i.current[n-1]?.focus())):r.key===`ArrowLeft`&&n>0?i.current[n-1]?.focus():r.key===`ArrowRight`&&n<5&&i.current[n+1]?.focus()}function o(r,a){let o=a.nativeEvent.data;if(!o||!/^\d$/.test(o))return;let s=e.split(``);for(s[r]=o;s.length<r;)s.push(``);let c=s.join(``).replace(/\D/g,``).slice(0,6);t(c),c.length===6?n(c):r<5&&i.current[r+1]?.focus()}function s(e){e.preventDefault();let r=e.clipboardData.getData(`text`).replace(/\D/g,``).slice(0,6);r&&(t(r),r.length===6?n(r):i.current[r.length]?.focus())}return(0,F.jsx)(`div`,{className:`gate-otp-field`,children:Array.from({length:6}).map((t,n)=>(0,F.jsx)(`input`,{ref:e=>{i.current[n]=e},type:`text`,inputMode:`numeric`,className:`pin-box${e[n]?` pin-box-filled`:``}`,value:e[n]||``,onKeyDown:e=>a(n,e),onInput:e=>o(n,e),onPaste:s,onFocus:e=>e.target.select(),autoFocus:n===0,autoComplete:`off`,maxLength:1,disabled:r,"aria-label":`Code digit ${n+1}`},n))})}function L({gateState:e,setGateState:t,grantInfo:n,setGrantInfo:r,gateSessionKeyRef:i,resolvedSlugRef:a,onAuthenticated:o}){let[c,l]=(0,w.useState)(``),[u,d]=(0,w.useState)(``),[f,p]=(0,w.useState)(``),[m,h]=(0,w.useState)(!1),[g,_]=(0,w.useState)(``),[v,b]=(0,w.useState)(``),[x,S]=(0,w.useState)(!1),[C,T]=(0,w.useState)(null),[E,D]=(0,w.useState)(null),[O,k]=(0,w.useState)(!1);async function A(e){if(e.preventDefault(),!O){T(null),k(!0);try{let e=a.current,n=await fetch(`/api/access/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({contact:c,password:u,agentSlug:e})}),i=await n.json();n.ok?o(i.session_key):n.status===401?i.error?.includes(`setup not complete`)||i.error?.includes(`invitation link`)?(t(`private-agent`),T(null)):T(i.error||`Invalid credentials`):n.status===403?(t(`access-expired`),i.expiresAt&&r(e=>e?{...e,expiresAt:i.expiresAt}:{displayName:null,contactValue:c,contactMethod:`email`,expiresAt:i.expiresAt,status:`expired`})):n.status===429?T(i.error||`Too many attempts. Please try again later.`):T(i.error||`Something went wrong`)}catch{T(`Unable to connect. Please try again.`)}finally{k(!1)}}}async function N(e){if(!O){T(null),k(!0);try{let n=a.current,o=await fetch(`/api/access/verify-otp`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({phone:v,code:e,agentSlug:n})}),s=await o.json();o.ok?(i.current=s.session_key,r(s.grant),t(`set-password`)):o.status===429?t(`otp-failed`):(T(s.error||`Invalid code`),_(``))}catch{T(`Unable to connect. Please try again.`)}finally{k(!1)}}}async function P(e){if(e.preventDefault(),!O){if(T(null),u!==f){T(`Passwords do not match`);return}if(!j(u).every(e=>e.met)){T(`Password does not meet requirements`);return}k(!0);try{let e=i.current;if(!e){T(`Session expired. Please use your invitation link again.`);return}let t=await fetch(`/api/access/create-credentials`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({session_key:e,password:u})}),n=await t.json();t.ok?o(n.session_key):t.status===400&&n.requirements?T(n.requirements.filter(e=>!e.met).map(e=>e.label).join(`, `)):T(n.error||`Something went wrong`)}catch{T(`Unable to connect. Please try again.`)}finally{k(!1)}}}async function L(e){if(e.preventDefault(),!(O||!c)){T(null),k(!0);try{let e=a.current,t=await fetch(`/api/access/forgot-password`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({contact:c,agentSlug:e})});t.status===429?T((await t.json()).error||`Too many attempts. Please try again later.`):(D(`If an account exists, a reset link has been sent.`),setTimeout(()=>{S(!1),D(null)},4e3))}catch{T(`Unable to connect. Please try again.`)}finally{k(!1)}}}switch(e){case`set-password`:{let e=j(u),t=e.every(e=>e.met),r=u===f,i=t&&r&&f.length>0;return(0,F.jsx)(`div`,{className:`gate-wrap`,children:(0,F.jsxs)(`div`,{className:`gate-card`,children:[n?.expiresAt&&(0,F.jsxs)(`div`,{className:`gate-expiry-badge`,children:[`Access until `,new Date(n.expiresAt).toLocaleDateString(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`})]}),(0,F.jsxs)(`h2`,{className:`gate-title`,children:[`Welcome, `,n?.displayName||`there`]}),(0,F.jsx)(`p`,{className:`gate-subtitle`,children:`Create a password to access this agent in the future.`}),(0,F.jsxs)(`form`,{className:`gate-form`,onSubmit:P,children:[(0,F.jsxs)(`div`,{className:`gate-field`,children:[(0,F.jsx)(`label`,{htmlFor:`gate-display-name`,children:`Display name`}),(0,F.jsx)(`input`,{id:`gate-display-name`,type:`text`,value:n?.displayName||``,disabled:!0})]}),(0,F.jsxs)(`div`,{className:`gate-field gate-pw-row`,children:[(0,F.jsx)(`label`,{htmlFor:`gate-pw`,children:`Password`}),(0,F.jsx)(`div`,{className:`gate-pw-toggle`,children:(0,F.jsx)(s,{checked:m,onChange:h,label:`Show`})}),(0,F.jsx)(`input`,{id:`gate-pw`,type:m?`text`:`password`,value:u,onChange:e=>d(e.target.value),placeholder:`Your password`,autoFocus:!0,autoComplete:`new-password`}),u.length>0&&(0,F.jsx)(`div`,{className:`gate-strength`,children:e.map(e=>(0,F.jsxs)(`span`,{className:`gate-strength-item${e.met?` met`:``}`,children:[e.met?`✓`:`○`,` `,e.label]},e.key))})]}),(0,F.jsxs)(`div`,{className:`gate-field`,children:[(0,F.jsx)(`label`,{htmlFor:`gate-pw-confirm`,children:`Confirm password`}),(0,F.jsx)(`input`,{id:`gate-pw-confirm`,type:m?`text`:`password`,value:f,onChange:e=>p(e.target.value),placeholder:`Confirm your password`,autoComplete:`new-password`}),f.length>0&&!r&&(0,F.jsx)(`div`,{className:`gate-error`,children:`Passwords do not match`})]}),C&&(0,F.jsx)(`div`,{className:`gate-error`,children:C}),(0,F.jsx)(`div`,{className:`gate-submit`,children:(0,F.jsx)(y,{variant:`primary`,type:`submit`,fullWidth:!0,disabled:!i||O,loading:O,children:`Create account & enter chat`})})]})]})})}case`enter-otp`:return(0,F.jsx)(`div`,{className:`gate-wrap`,children:(0,F.jsxs)(`div`,{className:`gate-card`,children:[(0,F.jsx)(`h2`,{className:`gate-title`,children:`Enter your code`}),(0,F.jsxs)(`p`,{className:`gate-subtitle`,children:[`Enter the 6-digit code sent to `,M(v,`phone`)]}),(0,F.jsx)(I,{value:g,onChange:_,onComplete:N,disabled:O}),C&&(0,F.jsx)(`div`,{className:`gate-error`,children:C}),O&&(0,F.jsxs)(`div`,{className:`gate-loading`,children:[(0,F.jsx)(`span`,{className:`spinner`}),`Verifying...`]}),(0,F.jsx)(`div`,{className:`gate-resend`,children:(0,F.jsx)(`button`,{type:`button`,className:`gate-link`,onClick:()=>{t(`sign-in`),_(``),T(null)},children:`Use a different number`})})]})});case`sign-in`:case`private-agent`:return(0,F.jsx)(`div`,{className:`gate-wrap`,children:(0,F.jsxs)(`div`,{className:`gate-card`,children:[(0,F.jsx)(`h2`,{className:`gate-title`,children:e===`private-agent`?`Private Agent`:`Welcome back`}),(0,F.jsx)(`p`,{className:`gate-subtitle`,children:e===`private-agent`?`This agent is invitation-only. If you have an account, sign in below.`:`Sign in to continue your conversation.`}),x?(0,F.jsxs)(`form`,{className:`gate-form`,onSubmit:L,children:[(0,F.jsxs)(`div`,{className:`gate-field`,children:[(0,F.jsx)(`label`,{htmlFor:`gate-forgot-contact`,children:`Email or phone`}),(0,F.jsx)(`input`,{id:`gate-forgot-contact`,type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`you@example.com`,autoFocus:!0,autoComplete:`email`})]}),C&&(0,F.jsx)(`div`,{className:`gate-error`,children:C}),E&&(0,F.jsx)(`div`,{className:`gate-success`,children:E}),(0,F.jsx)(`div`,{className:`gate-submit`,children:(0,F.jsx)(y,{variant:`primary`,type:`submit`,fullWidth:!0,disabled:!c.trim()||O,loading:O,children:`Send reset link`})}),(0,F.jsx)(`div`,{className:`gate-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`gate-link`,onClick:()=>{S(!1),T(null),D(null)},children:`Back to sign in`})})]}):(0,F.jsxs)(`form`,{className:`gate-form`,onSubmit:A,children:[(0,F.jsxs)(`div`,{className:`gate-field`,children:[(0,F.jsx)(`label`,{htmlFor:`gate-contact`,children:`Email or phone`}),(0,F.jsx)(`input`,{id:`gate-contact`,type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`you@example.com`,autoFocus:!0,autoComplete:`email`})]}),(0,F.jsxs)(`div`,{className:`gate-field gate-pw-row`,children:[(0,F.jsx)(`label`,{htmlFor:`gate-login-pw`,children:`Password`}),(0,F.jsx)(`div`,{className:`gate-pw-toggle`,children:(0,F.jsx)(s,{checked:m,onChange:h,label:`Show`})}),(0,F.jsx)(`input`,{id:`gate-login-pw`,type:m?`text`:`password`,value:u,onChange:e=>d(e.target.value),placeholder:`Your password`,autoComplete:`current-password`})]}),C&&(0,F.jsx)(`div`,{className:`gate-error`,children:C}),(0,F.jsx)(`div`,{className:`gate-submit`,children:(0,F.jsx)(y,{variant:`primary`,type:`submit`,fullWidth:!0,disabled:!c.trim()||!u||O,loading:O,children:`Sign in`})}),(0,F.jsx)(`div`,{className:`gate-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`gate-link`,onClick:()=>{S(!0),T(null)},children:`Forgot password?`})})]}),e===`private-agent`&&(0,F.jsx)(`p`,{className:`gate-hint`,children:`No account? You need an invitation from the agent owner.`})]})});case`access-expired`:return(0,F.jsx)(`div`,{className:`gate-wrap`,children:(0,F.jsxs)(`div`,{className:`gate-card`,children:[(0,F.jsx)(`div`,{className:`gate-icon`,children:`⏰`}),(0,F.jsx)(`h2`,{className:`gate-title`,children:`Access expired`}),(0,F.jsxs)(`p`,{className:`gate-subtitle`,children:[n?.expiresAt?`Your access expired on ${new Date(n.expiresAt).toLocaleDateString(`en-GB`,{day:`numeric`,month:`long`,year:`numeric`})}.`:`Your access to this agent has expired.`,` `,`Contact the agent owner to renew.`]}),(0,F.jsx)(`div`,{className:`gate-actions`,children:(0,F.jsx)(y,{variant:`secondary`,onClick:()=>{t(`sign-in`),T(null),d(``)},children:`Sign in with a different account`})})]})});case`link-expired`:return(0,F.jsx)(`div`,{className:`gate-wrap`,children:(0,F.jsxs)(`div`,{className:`gate-card`,children:[(0,F.jsx)(`div`,{className:`gate-icon`,children:`⚠️`}),(0,F.jsx)(`h2`,{className:`gate-title`,children:`Link expired`}),(0,F.jsx)(`p`,{className:`gate-subtitle`,children:`This invitation link has expired or has already been used. If you already set your password, sign in below. Otherwise, ask the agent owner to send a new invitation.`}),(0,F.jsx)(`div`,{className:`gate-actions`,children:(0,F.jsx)(y,{variant:`primary`,onClick:()=>{t(`sign-in`),T(null)},children:`Go to sign in`})})]})});case`otp-failed`:return(0,F.jsx)(`div`,{className:`gate-wrap`,children:(0,F.jsxs)(`div`,{className:`gate-card`,children:[(0,F.jsx)(`div`,{className:`gate-icon`,children:`⛔`}),(0,F.jsx)(`h2`,{className:`gate-title`,children:`Too many attempts`}),(0,F.jsx)(`p`,{className:`gate-subtitle`,children:`You've entered the wrong code too many times. Ask the agent owner to send a new code.`}),(0,F.jsx)(`div`,{className:`gate-actions`,children:(0,F.jsx)(y,{variant:`secondary`,onClick:()=>{t(`sign-in`),T(null),_(``)},children:`Back to sign in`})})]})})}}var R={"single-select":a,"multi-select":d};function z({name:e,data:t,onSubmit:n,submitted:r}){let i=R[e];return i?(0,F.jsx)(i,{data:t,onSubmit:n,submitted:r}):null}function B({messages:t,isStreaming:n,sessionError:r,selectionMode:i,selectedItems:a,longPressProps:c,toggleSelectItem:l,onComponentSubmit:u,remainingSuggestions:d,onSuggestionClick:f,isAtBottom:p,setIsAtBottom:m}){let[h,v]=(0,w.useState)(new Set),[b,S]=(0,w.useState)(new Set),C=(0,w.useRef)(null),T=(0,w.useRef)(null),E=(0,w.useRef)(null),D=(0,w.useRef)(!1),O=(0,w.useRef)(new Map);(0,w.useEffect)(()=>{if(!p){D.current=n;return}if(D.current&&!n&&E.current&&T.current){let e=E.current;if(e.offsetHeight>T.current.clientHeight){e.scrollIntoView({behavior:`smooth`,block:`start`}),D.current=n;return}}C.current?.scrollIntoView({behavior:`smooth`}),D.current=n},[t,p,n]),(0,w.useEffect)(()=>{let e=T.current;if(!e)return;let t=()=>{m(e.scrollHeight-e.scrollTop-e.clientHeight<80)};return e.addEventListener(`scroll`,t,{passive:!0}),t(),()=>e.removeEventListener(`scroll`,t)},[m]),(0,w.useEffect)(()=>{function e(){S(e=>{let t=new Set;return O.current.forEach((n,r)=>{n.isConnected&&(h.has(r)?e.has(r)&&t.add(r):n.scrollHeight>n.clientHeight+2&&t.add(r))}),e.size===t.size&&[...e].every(e=>t.has(e))?e:t})}e();let t=new ResizeObserver(e);return O.current.forEach(e=>t.observe(e)),()=>t.disconnect()},[t.length,h]);let k=t.reduce((e,t,n)=>t.role===`maxy`&&!t.hidden?n:e,-1);return(0,F.jsxs)(`div`,{className:`chat-messages-wrap`,children:[i&&(0,F.jsx)(`div`,{className:`selection-overlay-band`}),(0,F.jsxs)(`div`,{className:`chat-messages`,ref:T,children:[r&&t.length===0&&(0,F.jsx)(`div`,{className:`session-error`,children:(0,F.jsx)(`p`,{children:r})}),t.map((r,d)=>{if(r.hidden)return null;let f=n&&d===t.length-1,p=`${r.timestamp}_${r.role}`,m=a.has(p);return(0,F.jsxs)(`div`,{ref:d===k?E:void 0,className:`message ${r.role}${m?` selected`:``}`,...f?{}:c(p),children:[i&&!f&&(0,F.jsx)(`div`,{className:`message-select-check`,children:(0,F.jsx)(s,{checked:m,onChange:()=>l(p)})}),(0,F.jsxs)(`div`,{className:`bubble`,children:[r.role===`visitor`&&r.content?(()=>{let t=h.has(d),n=b.has(d);return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{ref:e=>{e?O.current.set(d,e):O.current.delete(d)},className:t?`bubble-content`:`bubble-content clamped${n?` overflowing`:``}`,children:r.content}),n&&(0,F.jsx)(`div`,{className:`bubble-expand`,children:(0,F.jsx)(y,{variant:`icon`,className:t?`expanded`:``,onClick:()=>v(e=>{let t=new Set(e);return t.has(d)?t.delete(d):t.add(d),t}),"aria-label":t?`Collapse message`:`Expand message`,children:(0,F.jsx)(e,{size:14})})})]})})():r.content?(0,F.jsx)(_,{content:r.content,timestamp:g(r.timestamp)}):(0,F.jsxs)(`span`,{className:`typing-indicator`,children:[(0,F.jsx)(`span`,{className:`typing-dot`}),(0,F.jsx)(`span`,{className:`typing-dot`}),(0,F.jsx)(`span`,{className:`typing-dot`})]}),r.attachments&&r.attachments.length>0&&(0,F.jsx)(`div`,{className:`message-attachments`,children:r.attachments.map((e,t)=>(0,F.jsxs)(`span`,{className:`message-attachment-chip no-action`,children:[e.mimeType===`application/pdf`?(0,F.jsx)(o,{size:12}):e.mimeType.startsWith(`text/`)?(0,F.jsx)(x,{size:12}):null,(0,F.jsx)(`span`,{children:e.filename})]},t))}),r.role===`visitor`&&(0,F.jsx)(`span`,{className:`message-timestamp`,children:g(r.timestamp)})]}),r.role===`maxy`&&r.components&&r.components.length>0&&(0,F.jsx)(`div`,{className:`public-components`,children:r.components.map((e,t)=>(0,F.jsx)(`div`,{className:`public-component-enter`,children:(0,F.jsx)(z,{name:e.name,data:e.data,onSubmit:e=>u(d,t,e),submitted:e.submitted})},t))})]},d)}),!n&&d.length>0&&(0,F.jsx)(`div`,{className:`chat-suggestions`,children:d.map(e=>(0,F.jsx)(y,{variant:`suggestion`,onClick:()=>f(e),children:e},e))}),(0,F.jsx)(`div`,{ref:C})]}),!p&&(0,F.jsx)(`button`,{className:`scroll-to-bottom`,onClick:()=>C.current?.scrollIntoView({behavior:`smooth`}),"aria-label":`Scroll to bottom`})]})}function V({selectedItems:e,messages:t,copySelected:r,exitSelection:a,showCopyToast:o}){let[s,c]=(0,w.useState)(!1),l=(0,w.useRef)(null),u=(0,w.useRef)(!1);function d(e){let n=e.lastIndexOf(`_`),r=e.slice(0,n),i=e.slice(n+1),a=parseInt(r,10);return t.find(e=>e.timestamp===a&&e.role===i)?.content??``}function f(e,t){return parseInt(e.slice(0,e.lastIndexOf(`_`)),10)-parseInt(t.slice(0,t.lastIndexOf(`_`)),10)}function p(){let e=[...t].sort((e,t)=>e.timestamp-t.timestamp),n=[];for(let t of e){if(t.hidden||!t.content)continue;let e=t.role===`visitor`?`Visitor`:`Maxy`;n.push(`${e}:\n${t.content}`)}return n.join(`
2
-
3
- ---
4
-
5
- `)}w.useEffect(()=>{if(!s)return;let e=e=>{e.target.closest(`.selection-copy-wrap`)||c(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[s]);function m(){l.current!==null&&(clearTimeout(l.current),l.current=null)}return(0,F.jsx)(`div`,{className:`chat-input-area`,children:(0,F.jsxs)(`div`,{className:`selection-bar`,children:[(0,F.jsxs)(`span`,{className:`selection-count`,children:[e.size,` Selected`]}),(0,F.jsxs)(`div`,{className:`selection-copy-wrap`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`selection-copy`,onPointerDown:()=>{if(s){c(!1);return}u.current=!1,l.current=setTimeout(()=>{u.current=!0,c(!0),l.current=null},500)},onPointerUp:m,onPointerLeave:m,onPointerCancel:m,onClick:async()=>{u.current||await r(d,f)},children:[(0,F.jsx)(n,{size:18}),(0,F.jsx)(`span`,{children:`Copy`})]}),s&&(0,F.jsx)(`div`,{className:`copy-menu`,children:(0,F.jsx)(`button`,{type:`button`,className:`copy-menu-item`,onClick:async()=>{let e=p();e&&o(await i(e)),a()},children:`Copy all`})})]}),(0,F.jsx)(`button`,{type:`button`,className:`selection-cancel`,onClick:a,children:`Cancel`})]})})}function H({input:e,setInput:t,isStreaming:n,pendingFiles:r,setPendingFiles:i,attachError:a,setAttachError:s,isDragOver:c,setIsDragOver:l,inputRef:u,onSubmit:d}){let f=(0,w.useRef)(null);function p(e){s(null);let t=e.find(e=>!E.has(e.type));if(t){s(`Unsupported file type: "${t.type}". Supported: images, PDF, plain text, markdown, CSV.`);return}let n=e.find(e=>e.size>D);if(n){s(`"${n.name}" exceeds the 20 MB limit.`);return}i(t=>[...t,...e].slice(0,5))}function h(e){e.preventDefault(),l(!0)}function g(){l(!1)}function _(e){e.preventDefault(),l(!1),p([...e.dataTransfer.files])}return(0,F.jsxs)(`div`,{className:`chat-input-area`,children:[(0,F.jsx)(`input`,{ref:f,type:`file`,multiple:!0,accept:T,style:{display:`none`},onChange:e=>{e.target.files&&p([...e.target.files]),e.target.value=``}}),r.length>0&&(0,F.jsx)(`div`,{className:`attachment-strip`,children:r.map((e,t)=>(0,F.jsxs)(`div`,{className:`attachment-chip`,children:[e.type.startsWith(`image/`)?(0,F.jsx)(`img`,{src:URL.createObjectURL(e),alt:e.name,className:`attachment-chip-thumb`}):e.type===`application/pdf`?(0,F.jsx)(o,{size:14}):(0,F.jsx)(x,{size:14}),(0,F.jsx)(`span`,{className:`attachment-chip-name`,children:e.name}),(0,F.jsx)(`button`,{type:`button`,className:`attachment-chip-remove`,onClick:()=>i(e=>e.filter((e,n)=>n!==t)),"aria-label":`Remove ${e.name}`,children:`×`})]},t))}),a&&(0,F.jsx)(`p`,{className:`attach-error`,children:a}),(0,F.jsx)(m,{inputRef:u}),(0,F.jsxs)(`form`,{className:`chat-form${c?` drag-over`:``}`,onSubmit:d,onDragOver:h,onDragLeave:g,onDrop:_,onPaste:e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e of t){if(e.kind!==`file`)continue;let t=e.getAsFile();if(!t)continue;let r=t.type.split(`/`)[1]?.replace(`jpeg`,`jpg`)||`png`;n.push(new File([t],`pasted-image-${Date.now()}.${r}`,{type:t.type}))}n.length>0&&p(n)},children:[(0,F.jsx)(y,{variant:`icon`,type:`button`,onClick:()=>f.current?.click(),disabled:n,"aria-label":`Attach file`,children:(0,F.jsx)(S,{size:14})}),(0,F.jsx)(v,{ref:u,value:e,onChange:t,placeholder:`Type a message...`}),(0,F.jsx)(y,{variant:`send`,type:`submit`,disabled:n||!e.trim()&&r.length===0,"aria-label":`Send message`,children:(0,F.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,F.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`}),(0,F.jsx)(`polyline`,{points:`12 5 19 12 12 19`})]})})]})]})}var U=[];function W(){let[e,t]=(0,w.useState)(``),[n,r]=(0,w.useState)([]),[i,a]=(0,w.useState)(!1),[o,s]=(0,w.useState)(null),[c,l]=(0,w.useState)(U),[d,f]=(0,w.useState)(!0),m=(0,w.useRef)(null),{selectionMode:g,selectedItems:_,copyToast:v,longPressProps:y,exitSelection:x,toggleSelectItem:S,copySelected:C,showCopyToast:T}=b(),E=(0,w.useRef)(()=>{}),D=N((0,w.useCallback)(e=>{E.current(e)},[])),{sessionId:O,sessionKeyRef:k,sessionError:A,pageState:j,agentDisplayName:M,branding:I,ensureSession:R,resumedRef:z,resumeMessagesRef:W}=D,{messages:G,setMessages:K,isStreaming:q,sendMessage:J,sendGreeting:Y,handleComponentSubmit:X}=P({sessionKeyRef:k,ensureSession:R,sessionError:A,pageState:j,inputRef:m});(0,w.useEffect)(()=>{E.current=Y},[Y]),(0,w.useEffect)(()=>{let e=!1;return(async()=>{let t=await R();if(!e&&t){if(z.current&&W.current&&W.current.length>0){K(W.current.map(e=>({role:e.role,content:e.content,timestamp:e.timestamp}))),W.current=null;return}Y(t)}})(),()=>{e=!0}},[]),(0,w.useEffect)(()=>{j===`chat`&&m.current?.focus()},[j]),(0,w.useEffect)(()=>{if(!I)return;let e=document.documentElement;if(I.primaryColor&&(e.style.setProperty(`--sage`,I.primaryColor),e.style.setProperty(`--sage-hover`,I.primaryColor),e.style.setProperty(`--sage-subtle`,I.primaryColor+`14`),e.style.setProperty(`--sage-glow`,I.primaryColor+`26`)),I.accentColor&&e.style.setProperty(`--visitor-bubble`,I.accentColor),I.backgroundColor&&e.style.setProperty(`--bg`,I.backgroundColor),document.title=I.name,I.primaryColor){let e=document.querySelector(`meta[name="theme-color"]`);e||(e=document.createElement(`meta`),e.name=`theme-color`,document.head.appendChild(e)),e.content=I.primaryColor}if(I.faviconUrl){let e=document.querySelector(`link[rel="icon"]`);e||(e=document.createElement(`link`),e.rel=`icon`,document.head.appendChild(e)),e.href=I.faviconUrl}},[I]),(0,w.useEffect)(()=>{function e(e){e.key===`Escape`&&g&&x()}return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[g,x]);function Z(e){if(!e&&n.length===0||q)return;K(e=>e.map(e=>e.components?.some(e=>!e.submitted)?{...e,components:e.components.map(e=>e.submitted?e:{...e,submitted:!0})}:e)),l(t=>t.filter(t=>t!==e)),f(!0);let i=[...n];t(``),r([]),s(null),J(e,{files:i})}function Q(t){t.preventDefault(),Z(e.trim()),m.current?.resetHeight()}return(0,F.jsxs)(`div`,{className:`chat-page`,children:[(0,F.jsxs)(`header`,{className:`chat-header`,children:[(0,F.jsx)(`img`,{src:I?.logoUrl||u,alt:I?.name||h.productName,className:`chat-logo`,onError:e=>{e.target.src=u}}),(0,F.jsx)(`h1`,{className:`chat-tagline`,children:M||I?.name||h.productName}),(0,F.jsx)(`p`,{className:`chat-intro`,children:I?.tagline||``})]}),j===`loading`&&(0,F.jsx)(`div`,{className:`gate-wrap`,children:(0,F.jsx)(`div`,{className:`gate-loading`,children:(0,F.jsx)(`span`,{className:`spinner`})})}),j===`auth-required`&&(0,F.jsx)(L,{gateState:D.gateState,setGateState:D.setGateState,grantInfo:D.grantInfo,setGrantInfo:D.setGrantInfo,gateSessionKeyRef:D.gateSessionKeyRef,resolvedSlugRef:D.resolvedSlugRef,onAuthenticated:D.enterChat}),j===`chat`&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(B,{messages:G,isStreaming:q,sessionError:A,selectionMode:g,selectedItems:_,longPressProps:y,toggleSelectItem:S,onComponentSubmit:X,remainingSuggestions:c,onSuggestionClick:Z,isAtBottom:d,setIsAtBottom:f}),g?(0,F.jsx)(V,{selectedItems:_,messages:G,copySelected:C,exitSelection:x,showCopyToast:T}):(0,F.jsx)(H,{input:e,setInput:t,isStreaming:q,pendingFiles:n,setPendingFiles:r,attachError:o,setAttachError:s,isDragOver:i,setIsDragOver:a,inputRef:m,onSubmit:Q})]}),v&&(0,F.jsx)(`span`,{className:`copy-toast${v===`failed`?` copy-toast-failed`:``}`,children:v===`copied`?`Copied`:`Copy failed`}),(0,F.jsxs)(`footer`,{className:`chat-footer`,children:[(0,F.jsxs)(`a`,{href:p,children:[h.domain,` `,`↗`]}),O&&(0,F.jsxs)(`span`,{style:{opacity:.35,fontSize:`10px`,fontFamily:`monospace`,marginLeft:`1rem`},children:[`Session · `,O.slice(0,8)]})]})]})}(0,C.createRoot)(document.getElementById(`root`)).render((0,F.jsx)(W,{}));