@webority/chat-core 0.135.1 → 0.137.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/format.js CHANGED
@@ -1,3 +1,3 @@
1
- import{formatFigure as e}from"./figures.js";import{markdownToPlainText as t}from"@webority/markdown-core";var n=[`KB`,`MB`,`GB`],r=e=>{if(e<1024)return`${e} B`;let t=e/1024,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t.toFixed(1)} ${n[r]}`},i=new Intl.DateTimeFormat(`en-GB`,{timeZone:`Asia/Kolkata`,day:`2-digit`,month:`short`,year:`numeric`}),a=e=>i.format(new Date(e)).replace(/ /g,`-`),o=e=>e.flatMap(e=>e.kind===`Text`?[t(e.text)]:e.kind===`Notice`?[e.text]:[]).filter(e=>e!==``).join(`
1
+ import{formatFigure as e}from"./figures.js";import{markdownToPlainText as t}from"@webority/markdown-core";var n=[`KB`,`MB`,`GB`],r=e=>{if(e<1024)return`${e} B`;let t=e/1024,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t.toFixed(1)} ${n[r]}`},i=new Intl.DateTimeFormat(`en-GB`,{timeZone:`Asia/Kolkata`,day:`2-digit`,month:`short`,year:`numeric`}),a=e=>i.format(new Date(e)).replace(/ /g,`-`),o=864e5,s=(e,t,n=/* @__PURE__ */ new Date)=>{let r=a(e);return r===a(n.toISOString())?t.today:r===a((/* @__PURE__ */ new Date(n.getTime()-o)).toISOString())?t.yesterday:r},c=e=>e.flatMap(e=>e.kind===`Text`?[t(e.text)]:e.kind===`Notice`?[e.text]:[]).filter(e=>e!==``).join(`
2
2
 
3
- `).trim(),s=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],c=`-`,l=new Intl.DateTimeFormat(`en-IN`,{timeZone:`Asia/Kolkata`,day:`2-digit`,month:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}),u=e=>{let t=Date.parse(e);if(Number.isNaN(t))return c;let n=l.formatToParts(t),r=e=>n.find(t=>t.type===e)?.value??``;return`${r(`day`)}-${s[Number(r(`month`))-1]}-${r(`year`)}, ${r(`hour`)}:${r(`minute`)} ${r(`dayPeriod`).toUpperCase()}`},d=new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:0}),f=new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:3}),p=new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:2}),m=new Intl.NumberFormat(`en-IN`,{minimumFractionDigits:2,maximumFractionDigits:2}),h=/^\d{4}-\d{2}-\d{2}$/,g=e=>h.test(e)?Date.parse(`${e}T00:00:00+05:30`):Date.parse(e),_=e=>e.map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``),v=(e,t)=>{if(t===null)return m.format(e/100);try{let n=new Intl.NumberFormat(`en-IN`,{style:`currency`,currency:t}),r=n.resolvedOptions().maximumFractionDigits;if(r===void 0)throw Error(`No fraction digits resolved for currency ${t}.`);return n.format(e/10**r)}catch(n){if(!(n instanceof RangeError))throw n;return`${m.format(e/100)} ${t.toUpperCase()}`}},y=(t,n,r)=>{if(t==null||t===``)return c;if(n===`Text`)return String(t);if(n===`Date`){let e=g(String(t));return Number.isNaN(e)?c:i.format(e).replace(/ /g,`-`)}if(n===`DateTimeUtc`)return u(String(t));let a=Number(t);return Number.isFinite(a)?n===`Integer`?d.format(a):n===`Decimal`?a!==0&&Math.abs(a)<.001?_(e(a)):f.format(a):n===`Percent`?`${p.format(a)}%`:v(a,r):String(t)};export{a as formatChatDate,u as formatChatDateTime,y as formatChatValue,r as formatFileSize,o as messagePlainText};
3
+ `).trim(),l=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],u=`-`,d=new Intl.DateTimeFormat(`en-IN`,{timeZone:`Asia/Kolkata`,day:`2-digit`,month:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}),f=e=>{let t=Date.parse(e);if(Number.isNaN(t))return u;let n=d.formatToParts(t),r=e=>n.find(t=>t.type===e)?.value??``;return`${r(`day`)}-${l[Number(r(`month`))-1]}-${r(`year`)}, ${r(`hour`)}:${r(`minute`)} ${r(`dayPeriod`).toUpperCase()}`},p=new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:0}),m=new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:3}),h=new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:2}),g=new Intl.NumberFormat(`en-IN`,{minimumFractionDigits:2,maximumFractionDigits:2}),_=/^\d{4}-\d{2}-\d{2}$/,v=e=>_.test(e)?Date.parse(`${e}T00:00:00+05:30`):Date.parse(e),y=e=>e.map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``),b=(e,t)=>{if(t===null)return g.format(e/100);try{let n=new Intl.NumberFormat(`en-IN`,{style:`currency`,currency:t}),r=n.resolvedOptions().maximumFractionDigits;if(r===void 0)throw Error(`No fraction digits resolved for currency ${t}.`);return n.format(e/10**r)}catch(n){if(!(n instanceof RangeError))throw n;return`${g.format(e/100)} ${t.toUpperCase()}`}},x=(t,n,r)=>{if(t==null||t===``)return u;if(n===`Text`)return String(t);if(n===`Date`){let e=v(String(t));return Number.isNaN(e)?u:i.format(e).replace(/ /g,`-`)}if(n===`DateTimeUtc`)return f(String(t));let a=Number(t);return Number.isFinite(a)?n===`Integer`?p.format(a):n===`Decimal`?a!==0&&Math.abs(a)<.001?y(e(a)):m.format(a):n===`Percent`?`${h.format(a)}%`:b(a,r):String(t)};export{a as formatChatDate,f as formatChatDateTime,s as formatChatDay,x as formatChatValue,r as formatFileSize,c as messagePlainText};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{sniffAudioType as e}from"./audioType.js";import{ChatApiError as t,createChatClient as n,newIdempotencyKey as r}from"./client.js";import{CHAT_CONTRACT_VERSION as i,CHAT_HANDOFF_REQUEST_ID as a}from"./contract.js";import{createConversationList as o}from"./conversationList.js";import{DICTATION_NO_SPEECH_MS as s,DICTATION_SILENCE_MS as c,createDictation as l}from"./dictation.js";import{createExplain as u}from"./explain.js";import{formatFigure as d,toFigureRuns as f,toFigureText as p}from"./figures.js";import{createFixtureClient as m}from"./fixtureClient.js";import{formatChatDate as h,formatChatDateTime as g,formatChatValue as _,formatFileSize as v,messagePlainText as y}from"./format.js";import{isHandoffTarget as b}from"./handoff.js";import{DEFAULT_CHAT_LABELS as x,mergeLabels as S}from"./labels.js";import{defaultChatLook as C,mergeLook as w}from"./look.js";import{pacingDelayMs as T}from"./pacing.js";import{CHAT_FEATURES as E,LOADER_STYLES as D,emptyFeatures as O,loaderView as k,resolveFeatures as A,resolveNudge as j,resolveStart as M,showsCaptchaNote as N}from"./profile.js";import{createChatSession as P,createTurnApi as F,handoffSettledIds as I}from"./session.js";import{CHAT_SPEECH_TOKEN_MARGIN_MS as L,ChatSpeechError as R,createSpeechTokenSource as z}from"./speech.js";import{humanizeService as B,selectStarters as V}from"./starters.js";import{createSseParser as H,createStreamReader as U}from"./stream.js";import{buildTranscript as W,transcriptToText as G}from"./transcript.js";import{formatClipTime as K,voiceClipBars as q}from"./voiceClip.js";export{i as CHAT_CONTRACT_VERSION,E as CHAT_FEATURES,a as CHAT_HANDOFF_REQUEST_ID,L as CHAT_SPEECH_TOKEN_MARGIN_MS,t as ChatApiError,R as ChatSpeechError,x as DEFAULT_CHAT_LABELS,s as DICTATION_NO_SPEECH_MS,c as DICTATION_SILENCE_MS,D as LOADER_STYLES,W as buildTranscript,n as createChatClient,P as createChatSession,o as createConversationList,l as createDictation,u as createExplain,m as createFixtureClient,z as createSpeechTokenSource,H as createSseParser,U as createStreamReader,F as createTurnApi,C as defaultChatLook,O as emptyFeatures,h as formatChatDate,g as formatChatDateTime,_ as formatChatValue,K as formatClipTime,d as formatFigure,v as formatFileSize,I as handoffSettledIds,B as humanizeService,b as isHandoffTarget,k as loaderView,S as mergeLabels,w as mergeLook,y as messagePlainText,r as newIdempotencyKey,T as pacingDelayMs,A as resolveFeatures,j as resolveNudge,M as resolveStart,V as selectStarters,N as showsCaptchaNote,e as sniffAudioType,f as toFigureRuns,p as toFigureText,G as transcriptToText,q as voiceClipBars};
1
+ import{sniffAudioType as e}from"./audioType.js";import{ChatApiError as t,createChatClient as n,newIdempotencyKey as r}from"./client.js";import{CHAT_CONTRACT_VERSION as i,CHAT_HANDOFF_REQUEST_ID as a}from"./contract.js";import{createConversationList as o}from"./conversationList.js";import{DICTATION_NO_SPEECH_MS as s,DICTATION_SILENCE_MS as c,createDictation as l}from"./dictation.js";import{createExplain as u}from"./explain.js";import{formatFigure as d,toFigureRuns as f,toFigureText as p}from"./figures.js";import{createFixtureClient as m}from"./fixtureClient.js";import{formatChatDate as h,formatChatDateTime as g,formatChatDay as _,formatChatValue as v,formatFileSize as y,messagePlainText as b}from"./format.js";import{isHandoffTarget as x}from"./handoff.js";import{DEFAULT_CHAT_LABELS as S,mergeLabels as C}from"./labels.js";import{defaultChatLook as w,mergeLook as T}from"./look.js";import{pacingDelayMs as E}from"./pacing.js";import{CHAT_FEATURES as D,LOADER_STYLES as O,emptyFeatures as k,loaderView as A,resolveFeatures as j,resolveNudge as M,resolveStart as N,showsCaptchaNote as P}from"./profile.js";import{createChatSession as F,createTurnApi as I,handoffSettledIds as L}from"./session.js";import{CHAT_SPEECH_TOKEN_MARGIN_MS as R,ChatSpeechError as z,createSpeechTokenSource as B}from"./speech.js";import{humanizeService as V,selectStarters as H}from"./starters.js";import{createSseParser as U,createStreamReader as W}from"./stream.js";import{buildTranscript as G,transcriptToText as K}from"./transcript.js";import{formatClipTime as q,voiceClipBars as J}from"./voiceClip.js";export{i as CHAT_CONTRACT_VERSION,D as CHAT_FEATURES,a as CHAT_HANDOFF_REQUEST_ID,R as CHAT_SPEECH_TOKEN_MARGIN_MS,t as ChatApiError,z as ChatSpeechError,S as DEFAULT_CHAT_LABELS,s as DICTATION_NO_SPEECH_MS,c as DICTATION_SILENCE_MS,O as LOADER_STYLES,G as buildTranscript,n as createChatClient,F as createChatSession,o as createConversationList,l as createDictation,u as createExplain,m as createFixtureClient,B as createSpeechTokenSource,U as createSseParser,W as createStreamReader,I as createTurnApi,w as defaultChatLook,k as emptyFeatures,h as formatChatDate,g as formatChatDateTime,_ as formatChatDay,v as formatChatValue,q as formatClipTime,d as formatFigure,y as formatFileSize,L as handoffSettledIds,V as humanizeService,x as isHandoffTarget,A as loaderView,C as mergeLabels,T as mergeLook,b as messagePlainText,r as newIdempotencyKey,E as pacingDelayMs,j as resolveFeatures,M as resolveNudge,N as resolveStart,H as selectStarters,P as showsCaptchaNote,e as sniffAudioType,f as toFigureRuns,p as toFigureText,K as transcriptToText,J as voiceClipBars};
package/dist/labels.js CHANGED
@@ -1 +1 @@
1
- var e={Open:`Open`,InProgress:`In progress`,WaitingOnCustomer:`Waiting on you`,Resolved:`Resolved`,Closed:`Closed`,Cancelled:`Cancelled`},t={Positive:`Good`,Caution:`Watch`,Negative:`Poor`,Neutral:``},n=Object.freeze({launcher:`Open chat`,launcherClose:`Close chat`,panelTitle:`Assistant`,headerStatus:`Usually replies instantly`,newChat:`New chat`,close:`Close`,history:`Past chats`,historyEmptyTitle:`No past chats`,historyEmptyText:`Your conversations show here.`,untitled:`Untitled chat`,rename:`Rename chat`,renameSave:`Save`,conversationTitle:`Chat name`,renameFailed:`We could not rename this chat. Please try again.`,deleteChat:`Delete chat`,deleteConfirmTitle:`Delete this chat?`,deleteConfirmMessage:`The conversation is removed for good.`,deleteConfirm:`Delete`,deleteFailed:`We could not delete this chat. Please try again.`,cancel:`Cancel`,loadMore:`Show more`,loadFailed:`We could not load your chats. Please try again.`,backToChat:`Back to the chat`,thread:`Conversation`,you:`You`,assistant:`Assistant`,agent:`Team`,thinking:`Working on it`,loadingConversation:`Loading the conversation`,emptyTitle:`How can I help?`,starters:`Suggested questions`,resumeLast:`Continue your last chat`,nudgeDismiss:`Dismiss suggestion`,composer:`Your message`,placeholder:`Ask anything`,send:`Send`,stop:`Stop`,composerHint:`Press Enter to send, Shift and Enter for a new line.`,counter:(e,t)=>`${e.toLocaleString(`en-GB`)} of ${t.toLocaleString(`en-GB`)}`,allowance:e=>e===0?`You have no messages left today.`:e===1?`You have 1 message left today.`:`You have ${e} messages left today.`,attach:`Attach a file`,attachHint:`Pictures or PDFs.`,removeAttachment:e=>`Remove ${e}`,attachmentUploading:`Uploading`,attachmentFailed:`That file did not upload. Please try again.`,attachmentLimit:e=>`You can attach up to ${e} files.`,editing:`Editing your message`,footerPrivacy:`Privacy`,captchaNote:`Protected by reCAPTCHA.`,captchaPrivacy:`Privacy`,captchaTerms:`Terms`,captchaUnavailable:`We could not check this message. Please try again in a moment.`,newMessages:`New messages`,disclaimer:`The assistant can make mistakes, so check important details.`,copy:`Copy`,copied:`Copied`,share:`Share`,print:`Print`,retry:`Try again`,stopped:`Stopped.`,regenerate:`New answer`,edit:`Edit`,rateUp:`Helpful`,rateDown:`Not helpful`,rating:`Rate this answer`,rated:`Thanks for the feedback.`,ratingFailed:`Your rating did not save. Please try again.`,sources:`Sources`,openSource:e=>`Open ${e}`,quickReplies:`Suggested replies`,inputSubmitting:`Sending`,inputRequired:`This field is required.`,inputConsentRequired:`Please accept to continue.`,inputAnswered:`Details sent.`,inputExpired:`This form has expired.`,inputSkipped:`Skipped.`,inputOptional:`Optional`,inputChooseFile:`Choose a file`,inputSendCode:`Send code`,inputEnterCode:`Enter the code`,inputCodeSent:`We sent a code. Enter it below.`,inputCodeFailed:`The code could not be sent. Try again.`,inputRemoveFile:e=>`Remove ${e}`,actionConfirm:`Confirm`,actionDismiss:`Not now`,actionWorking:`Working on it`,actionConfirmed:`Confirmed.`,actionRejected:`Not sent.`,actionExpired:`This request expired and was not sent.`,actionDone:`Done.`,actionFailed:`We could not do this. Please try again.`,actionRepeat:e=>`Already done on ${e}. Nothing was sent again.`,fileOpen:e=>`Open ${e}`,needsNewerApp:`This message needs a newer version of the app.`,errorGeneric:`Something went wrong. Please try again.`,assistantOutdated:`The assistant needs an update before it can answer. Please try again later.`,typeAnswer:`or type your answer below`,skip:`Skip`,editSomething:`Edit something`,muteSounds:`Mute sounds`,unmuteSounds:`Unmute sounds`,preparingAnswer:e=>`${e} is preparing an answer`,explainTrigger:`Why?`,explainTriggerLabel:e=>`Why? Explain ${e}`,explainAskMore:`Ask more`,explainSlow:`Still working on this.`,explainOffline:`You are offline. Explanations need a connection.`,explainError:`This could not be explained just now. Try again.`,explainRetry:`Try again`,explainEmpty:`This could not be explained in words.`,explainCapacity:e=>`The limit for explanations has been reached. They come back at ${e}.`,explainCapacityNoDate:`You have reached today's limit. Try again later.`,explainNotCounted:`Explanations do not use your daily messages. A question you type does.`,openFullScreen:`Open full screen`,openSidePanel:`Open as side panel`,earlierChat:`Earlier chat`,justNow:`Just now`,dailyLimitRefresh:e=>`They refresh on ${e}.`,talkToPerson:`Talk to a person`,handoffRequested:`Connecting you to our team.`,handoffWaiting:`Waiting for the next available person.`,handoffQueued:e=>`You are number ${e} in line.`,handoffQueuedText:`We will bring you in as soon as someone is free.`,handoffJoined:e=>`${e} joined the chat.`,handoffJoinedText:e=>`The conversation so far has been shared with ${e}, so you will not need to repeat anything.`,handoffLeft:e=>`${e} left the chat.`,handoffLeftText:`Another member of the team may join, or you can start a new chat.`,handoffEnded:`This chat with our team has ended.`,handoffEndedText:`Thank you for talking to us. Start a new chat if you need anything else.`,handoffAgentFallback:`A member of our team`,handoffMoment:`One moment`,liveLost:`We lost the connection to support.`,agentTyping:e=>`${e} is typing`,agentSays:e=>`${e} says`,statusWaitingForAgent:`Waiting for a person`,statusWithAgent:e=>`${e} from our team`,openTickets:`Your open tickets`,ticketAria:e=>`Ticket ${e}`,ticketView:`View ticket`,ticketStatus:t=>e[t]??``,table:`Table`,tableShowAll:e=>`Show all ${e} rows`,tableEmpty:`No rows to show.`,chart:`Chart`,chartEmpty:`No data to show.`,chartShowTable:`Show as table`,chartShowChart:`Show as chart`,chartLoadFailed:`This chart could not be drawn.`,chartLow:e=>`Low ${e}`,chartHigh:e=>`High ${e}`,figures:`Key figures`,figureStatus:e=>t[e]??``,recordOpen:`Open`,recordOpenFor:e=>`Open ${e}`,imageLoading:`Loading image`,imageFailed:`This image could not be loaded.`,imageViewer:`Image viewer`,imageOpen:e=>`View image: ${e}`,dictate:`Dictate`,dictateStop:`Stop dictating`,dictateListening:`Listening`,dictateTranscribing:`Turning your voice into text`,dictationBlocked:`The microphone is blocked. Allow it in your settings to dictate.`,dictationNoMicrophone:`No microphone was found. Connect one and try again.`,dictationNotHeard:`Nothing was heard. Check your microphone and try again.`,dictationFailed:`Dictation stopped working. Try again.`,dictationUnavailable:`Dictation is not available here.`,dictateOpenSettings:`Open Settings`,readAloud:`Read aloud`,readAloudStop:`Stop reading`,readAloudFailed:`This could not be read aloud.`,voiceClip:`Voice message`,voiceClipPlay:`Play voice message`,voiceClipPause:`Pause voice message`,voiceClipFailed:`This voice message could not be played.`,voiceClipShowTranscript:`Show transcript`,voiceClipHideTranscript:`Hide transcript`,voiceClipTime:(e,t)=>`${e} of ${t}`,shareConversation:`Share this conversation`,printConversation:`Print this conversation`,shareFailed:`Could not share. Try again.`,printFailed:`Could not open the print view. Try again.`,printedOn:e=>`Printed on ${e}`}),r=e=>e?{...n,...e}:n;export{n as DEFAULT_CHAT_LABELS,r as mergeLabels};
1
+ var e={Open:`Open`,InProgress:`In progress`,WaitingOnCustomer:`Waiting on you`,Resolved:`Resolved`,Closed:`Closed`,Cancelled:`Cancelled`},t={Positive:`Good`,Caution:`Watch`,Negative:`Poor`,Neutral:``},n=Object.freeze({launcher:`Open chat`,launcherClose:`Close chat`,panelTitle:`Assistant`,headerStatus:`Usually replies instantly`,newChat:`New chat`,close:`Close`,history:`Past chats`,historyEmptyTitle:`No past chats`,historyEmptyText:`Your conversations show here.`,untitled:`Untitled chat`,rename:`Rename chat`,renameSave:`Save`,conversationTitle:`Chat name`,renameFailed:`We could not rename this chat. Please try again.`,deleteChat:`Delete chat`,deleteConfirmTitle:`Delete this chat?`,deleteConfirmMessage:`The conversation is removed for good.`,deleteConfirm:`Delete`,deleteFailed:`We could not delete this chat. Please try again.`,cancel:`Cancel`,loadMore:`Show more`,loadFailed:`We could not load your chats. Please try again.`,backToChat:`Back to the chat`,thread:`Conversation`,you:`You`,assistant:`Assistant`,agent:`Team`,thinking:`Working on it`,loadingConversation:`Loading the conversation`,emptyTitle:`How can I help?`,starters:`Suggested questions`,resumeLast:`Continue your last chat`,nudgeDismiss:`Dismiss suggestion`,composer:`Your message`,placeholder:`Ask anything`,send:`Send`,stop:`Stop`,composerHint:`Press Enter to send, Shift and Enter for a new line.`,counter:(e,t)=>`${e.toLocaleString(`en-GB`)} of ${t.toLocaleString(`en-GB`)}`,allowance:e=>e===0?`You have no messages left today.`:e===1?`You have 1 message left today.`:`You have ${e} messages left today.`,attach:`Attach a file`,attachHint:`Pictures or PDFs.`,removeAttachment:e=>`Remove ${e}`,attachmentUploading:`Uploading`,attachmentFailed:`That file did not upload. Please try again.`,attachmentLimit:e=>`You can attach up to ${e} files.`,editing:`Editing your message`,footerPrivacy:`Privacy`,captchaNote:`Protected by reCAPTCHA.`,captchaPrivacy:`Privacy`,captchaTerms:`Terms`,captchaUnavailable:`We could not check this message. Please try again in a moment.`,newMessages:`New messages`,disclaimer:`The assistant can make mistakes, so check important details.`,copy:`Copy`,copied:`Copied`,share:`Share`,print:`Print`,retry:`Try again`,stopped:`Stopped.`,regenerate:`New answer`,edit:`Edit`,rateUp:`Helpful`,rateDown:`Not helpful`,rating:`Rate this answer`,rated:`Thanks for the feedback.`,ratingFailed:`Your rating did not save. Please try again.`,sources:`Sources`,openSource:e=>`Open ${e}`,quickReplies:`Suggested replies`,inputSubmitting:`Sending`,inputRequired:`This field is required.`,inputConsentRequired:`Please accept to continue.`,inputAnswered:`Details sent.`,inputExpired:`This form has expired.`,inputSkipped:`Skipped.`,inputOptional:`Optional`,inputChooseFile:`Choose a file`,inputSendCode:`Send code`,inputEnterCode:`Enter the code`,inputCodeSent:`We sent a code. Enter it below.`,inputCodeFailed:`The code could not be sent. Try again.`,inputRemoveFile:e=>`Remove ${e}`,actionConfirm:`Confirm`,actionDismiss:`Not now`,actionWorking:`Working on it`,actionConfirmed:`Confirmed.`,actionRejected:`Not sent.`,actionExpired:`This request expired and was not sent.`,actionDone:`Done.`,actionFailed:`We could not do this. Please try again.`,actionRepeat:e=>`Already done on ${e}. Nothing was sent again.`,fileOpen:e=>`Open ${e}`,needsNewerApp:`This message needs a newer version of the app.`,errorGeneric:`Something went wrong. Please try again.`,assistantOutdated:`The assistant needs an update before it can answer. Please try again later.`,typeAnswer:`or type your answer below`,skip:`Skip`,editSomething:`Edit something`,muteSounds:`Mute sounds`,unmuteSounds:`Unmute sounds`,preparingAnswer:e=>`${e} is preparing an answer`,explainTrigger:`Why?`,explainTriggerLabel:e=>`Why? Explain ${e}`,explainAskMore:`Ask more`,explainSlow:`Still working on this.`,explainOffline:`You are offline. Explanations need a connection.`,explainError:`This could not be explained just now. Try again.`,explainRetry:`Try again`,explainEmpty:`This could not be explained in words.`,explainCapacity:e=>`The limit for explanations has been reached. They come back at ${e}.`,explainCapacityNoDate:`You have reached today's limit. Try again later.`,explainNotCounted:`Explanations do not use your daily messages. A question you type does.`,openFullScreen:`Open full screen`,openSidePanel:`Open as side panel`,earlierChat:`Earlier chat`,justNow:`Just now`,today:`Today`,yesterday:`Yesterday`,dailyLimitRefresh:e=>`They refresh on ${e}.`,talkToPerson:`Talk to a person`,handoffRequested:`Connecting you to our team.`,handoffWaiting:`Waiting for the next available person.`,handoffQueued:e=>`You are number ${e} in line.`,handoffQueuedText:`We will bring you in as soon as someone is free.`,handoffJoined:e=>`${e} joined the chat.`,handoffJoinedText:e=>`The conversation so far has been shared with ${e}, so you will not need to repeat anything.`,handoffLeft:e=>`${e} left the chat.`,handoffLeftText:`Another member of the team may join, or you can start a new chat.`,handoffEnded:`This chat with our team has ended.`,handoffEndedText:`Thank you for talking to us. Start a new chat if you need anything else.`,handoffAgentFallback:`A member of our team`,handoffMoment:`One moment`,liveLost:`We lost the connection to support.`,agentTyping:e=>`${e} is typing`,agentSays:e=>`${e} says`,statusWaitingForAgent:`Waiting for a person`,statusWithAgent:e=>`${e} from our team`,openTickets:`Your open tickets`,ticketAria:e=>`Ticket ${e}`,ticketView:`View ticket`,ticketStatus:t=>e[t]??``,table:`Table`,tableShowAll:e=>`Show all ${e} rows`,tableEmpty:`No rows to show.`,chart:`Chart`,chartEmpty:`No data to show.`,chartShowTable:`Show as table`,chartShowChart:`Show as chart`,chartLoadFailed:`This chart could not be drawn.`,chartLow:e=>`Low ${e}`,chartHigh:e=>`High ${e}`,figures:`Key figures`,figureStatus:e=>t[e]??``,recordOpen:`Open`,recordOpenFor:e=>`Open ${e}`,imageLoading:`Loading image`,imageFailed:`This image could not be loaded.`,imageViewer:`Image viewer`,imageOpen:e=>`View image: ${e}`,dictate:`Dictate`,dictateStop:`Stop dictating`,dictateListening:`Listening`,dictateTranscribing:`Turning your voice into text`,dictationBlocked:`The microphone is blocked. Allow it in your settings to dictate.`,dictationNoMicrophone:`No microphone was found. Connect one and try again.`,dictationNotHeard:`Nothing was heard. Check your microphone and try again.`,dictationFailed:`Dictation stopped working. Try again.`,dictationUnavailable:`Dictation is not available here.`,dictateOpenSettings:`Open Settings`,readAloud:`Read aloud`,readAloudStop:`Stop reading`,readAloudFailed:`This could not be read aloud.`,voiceClip:`Voice message`,voiceClipPlay:`Play voice message`,voiceClipPause:`Pause voice message`,voiceClipFailed:`This voice message could not be played.`,voiceClipShowTranscript:`Show transcript`,voiceClipHideTranscript:`Hide transcript`,voiceClipTime:(e,t)=>`${e} of ${t}`,shareConversation:`Share this conversation`,printConversation:`Print this conversation`,shareFailed:`Could not share. Try again.`,printFailed:`Could not open the print view. Try again.`,printedOn:e=>`Printed on ${e}`}),r=e=>e?{...n,...e}:n;export{n as DEFAULT_CHAT_LABELS,r as mergeLabels};
package/dist/look.js CHANGED
@@ -1 +1 @@
1
- var e={launcher:{style:`Round`,entrance:`Rise`,idle:`None`,labelReveal:`Bubble`,compact:!1,mark:`Icon`},panel:{motion:`Spring`,widthPx:420,maxHeightPx:650,bottomGapPx:80,height:`Fixed`,replyAvatars:!0,greetingLoaderMs:0},phone:{maxWidthPx:768,mode:`FullScreen`,sheetHeightDvh:85,sheetMaxHeightPx:640},input:{ring:!0,sendReveal:`OnText`,sendIcon:`arrow-up`},avoid:{liftSelectors:[`footer`,`.form-actions-sticky`,`.wui-tabbar`],menuSelectors:[`.offcanvas.show`,`wui-drawer[open]`,`[data-menu-open]`],darkSelectors:[`[data-theme='dark']`,`[data-bs-theme='dark']`],autoOpenOptOutSelector:`[data-chat-no-autoopen]`,autoOpenBusySelectors:[`[data-chat-busy]`]},motion:`On`,avatar:null};function t(t){let n=t??{};return{launcher:{...e.launcher,...n.launcher},panel:{...e.panel,...n.panel},phone:{...e.phone,...n.phone},input:{...e.input,...n.input},avoid:{...e.avoid,...n.avoid},motion:n.motion??e.motion,avatar:n.avatar??e.avatar}}export{e as defaultChatLook,t as mergeLook};
1
+ var e={launcher:{style:`Round`,entrance:`Rise`,idle:`None`,labelReveal:`Bubble`,compact:!1,mark:`Icon`},panel:{motion:`Spring`,widthPx:420,maxHeightPx:650,bottomGapPx:80,height:`Fixed`,replyAvatars:!0,greetingLoaderMs:0},phone:{maxWidthPx:768,mode:`FullScreen`,sheetHeightDvh:85,sheetMaxHeightPx:640},input:{ring:!0,sendReveal:`OnText`,sendIcon:`arrow-up`},avoid:{liftSelectors:[`footer`,`.form-actions-sticky`,`.wui-tabbar`],menuSelectors:[`.offcanvas.show`,`wui-drawer[open]`,`[data-menu-open]`],darkSelectors:[`[data-theme='dark']`,`[data-bs-theme='dark']`],autoOpenOptOutSelector:`[data-chat-no-autoopen]`,autoOpenBusySelectors:[`[data-chat-busy]`]},motion:`On`,avatar:null,expressive:!1};function t(t){let n=t??{};return{launcher:{...e.launcher,...n.launcher},panel:{...e.panel,...n.panel},phone:{...e.phone,...n.phone},input:{...e.input,...n.input},avoid:{...e.avoid,...n.avoid},motion:n.motion??e.motion,avatar:n.avatar??e.avatar,expressive:n.expressive??e.expressive}}export{e as defaultChatLook,t as mergeLook};
package/dist/session.js CHANGED
@@ -1,3 +1,3 @@
1
- import{ChatApiError as e}from"./client.js";import"./contract.js";import{messagePlainText as t}from"./format.js";import{DEFAULT_CHAT_LABELS as n,mergeLabels as r}from"./labels.js";import{startLiveConnection as i}from"./live.js";import{pacingDelayMs as a}from"./pacing.js";import{emptyFeatures as o,resolveFeatures as s,resolveStart as ee}from"./profile.js";import{selectStarters as c}from"./starters.js";var l=globalThis,te=5e3,ne=3e3,re=300,ie=1200,ae=e=>{if(l.requestAnimationFrame&&l.cancelAnimationFrame){let t=l.requestAnimationFrame(()=>e());return()=>l.cancelAnimationFrame?.(t)}let t=l.setTimeout(e,16);return()=>l.clearTimeout(t)},u=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:{},d=e=>{let t=u(e);return{code:typeof t.code==`string`&&t.code?t.code:`unknown`,message:typeof t.message==`string`&&t.message?t.message:n.errorGeneric,resetsDateTimeUtc:typeof t.resetsDateTimeUtc==`string`?t.resetsDateTimeUtc:null}},f=(e,t)=>({id:e.publicId,author:e.author,createdDateTimeUtc:e.createdDateTimeUtc,parts:e.parts,sequence:e.sequence,rating:e.rating,ratingNote:e.ratingNote,streaming:!1,stored:!0,restored:t}),oe=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);return n<0?[...e,t]:e.map((e,r)=>r===n?t:e)},se=(e,t)=>{for(let n=e.length-1;n>=0;--n)if(t(e[n]))return n;return-1},ce=e=>e.flatMap(e=>e.kind===`Text`?[e.text]:[]).join(`
1
+ import{ChatApiError as e}from"./client.js";import"./contract.js";import{messagePlainText as t}from"./format.js";import{DEFAULT_CHAT_LABELS as n,mergeLabels as r}from"./labels.js";import{startLiveConnection as i}from"./live.js";import{pacingDelayMs as a}from"./pacing.js";import{emptyFeatures as o,resolveFeatures as s,resolveStart as c}from"./profile.js";import{selectStarters as l}from"./starters.js";var u=globalThis,ee=5e3,te=3e3,ne=300,re=1200,ie=e=>{if(u.requestAnimationFrame&&u.cancelAnimationFrame){let t=u.requestAnimationFrame(()=>e());return()=>u.cancelAnimationFrame?.(t)}let t=u.setTimeout(e,16);return()=>u.clearTimeout(t)},d=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:{},f=e=>{let t=d(e);return{code:typeof t.code==`string`&&t.code?t.code:`unknown`,message:typeof t.message==`string`&&t.message?t.message:n.errorGeneric,resetsDateTimeUtc:typeof t.resetsDateTimeUtc==`string`?t.resetsDateTimeUtc:null}},ae=(e,t)=>({id:e.publicId,author:e.author,createdDateTimeUtc:e.createdDateTimeUtc,parts:e.parts,sequence:e.sequence,rating:e.rating,ratingNote:e.ratingNote,streaming:!1,stored:!0,restored:t}),oe=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);return n<0?[...e,t]:e.map((e,r)=>r===n?t:e)},se=(e,t)=>{for(let n=e.length-1;n>=0;--n)if(t(e[n]))return n;return-1},ce=e=>e.flatMap(e=>e.kind===`Text`?[e.text]:[]).join(`
2
2
 
3
- `),p=e=>e.flatMap(e=>e.kind===`File`?[{publicId:e.attachmentId,fileName:e.fileName,contentType:e.contentType,length:e.length}]:[]),le=e=>{let t=u(e);return{fileName:typeof t.name==`string`?t.name:``,contentType:typeof t.type==`string`?t.type:``,length:typeof t.size==`number`?t.size:null}},ue=(e,t)=>e.length===t.length&&e.every((e,n)=>e.id===t[n].id&&e.label===t[n].label&&e.message===t[n].message),de=e=>{for(let t of e){if(!t.startsWith(`Enquiry type:`))continue;let e=t.slice(13).trim();return e===``?null:e}return null},fe=(e,t)=>{if(t!==`WithAgent`)return null;for(let t=e.length-1;t>=0;--t){let n=e[t];for(let e=n.parts.length-1;e>=0;--e){let t=n.parts[e];if(t.kind===`Handoff`){if(t.state===`Left`||t.state===`Ended`)return null;if(t.state===`Joined`&&t.agent)return t.agent}}if(n.author.kind===`Agent`)return{displayName:n.author.displayName??``,avatarUrl:n.author.avatarUrl}}return null},pe=(e,t)=>{(e.cursor===null||t>e.cursor)&&(e.cursor=t)},me=(e,t)=>{let n=[];e!==``&&n.push({kind:`Text`,text:e});for(let e of t)n.push({kind:`File`,attachmentId:e.publicId,fileName:e.fileName,contentType:e.contentType,length:e.length});return n},he=e=>{let t=ce(e.parts);return{wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:null,attachments:p(e.parts)}},ge=e=>({profile:null,profileError:null,features:o(),conversationId:null,conversationState:`Open`,title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,open:!1,muted:e?.get(`wchat:muted`)===`1`,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:`Off`,handoffPending:!1,handoffPause:!1,openTickets:[],draft:null}),m=(o,p)=>{let m=r(p.labels),_e=p.schedule??ae,h=p.prefs,g=/* @__PURE__ */ new Set,_=ge(h),v=0,y=null,b=null,ve=0,ye=0,x=null,S=null,C=/* @__PURE__ */ new Map,be=/* @__PURE__ */ new Set,w=/* @__PURE__ */ new Map,T=/* @__PURE__ */ new Set,E=/* @__PURE__ */ new Map,D={name:null,email:null,phone:null},O=/* @__PURE__ */ new Set,k=null,xe=null,A=null,j=null,M=null,Se=!0,Ce=!1,N=/* @__PURE__ */ new Set,P=/* @__PURE__ */ new Map,F=Promise.resolve(),I=0,we=()=>p.pathname?.()??l.location?.pathname??`/`,Te=()=>p.reducedMotion?.()===!0||_.profile?.experience.motion===!1,L=()=>_.streaming||_.thinking,Ee=e=>{if(!e.profile)return{...e,greeting:null,starters:[]};let t=we(),n=e.lastConversation!==null,r=ee(e.profile,{pathname:t,returning:n}).greeting,i=c(e.profile.start,{pathname:t,returning:n,behaviour:p.behaviour?.()??null,behaviourStarters:e.features.BehaviourStarters});return{...e,greeting:r,starters:ue(e.starters,i)?e.starters:i}},R=()=>{k!==null&&(l.clearTimeout(k),k=null)},z=()=>{A!==null&&(l.clearTimeout(A),A=null)},De=e=>e.flatMap(e=>e.parts.flatMap(e=>e.kind===`Action`&&e.actionKind===`ChatLeadCapture`&&e.state===`Done`?[{actionId:e.actionId,leadType:de(e.lines)}]:[])),B=()=>{D.name=null,D.email=null,D.phone=null,O.clear()},Oe=e=>{for(let t of De(e))O.add(t.actionId)},ke=()=>{for(let e of De(_.messages))O.has(e.actionId)||(O.add(e.actionId),p.onEvent?.(`leadSubmitted`,{conversationId:_.conversationId,fields:{name:D.name,email:D.email,phone:D.phone},leadType:e.leadType}))},Ae=(e,t)=>{let n=_.messages.flatMap(e=>e.parts).find(t=>t.kind===`InputRequest`&&t.requestId===e);if(n)for(let e of n.fields){let n=t[e.key];typeof n==`string`&&n.trim()!==``&&(e.type===`Email`?D.email=n.trim():e.type===`Phone`?D.phone=n.trim():(e.type===`Name`||e.key.toLowerCase()===`name`)&&(D.name=n.trim()))}},V=e=>{let t=M;t!==null&&(M=null,t.handle?.stop(),e!==null&&U({live:e}))},je=()=>!Ce&&Se&&_.features.HumanHandoff&&_.conversationId!==null&&(_.conversationState===`WaitingForAgent`||_.conversationState===`WithAgent`),H=()=>{if(!je()){M!==null&&V(`Off`);return}let e=_.conversationId;if(e===null||M!==null&&M.conversationId===e)return;V(null);let t={conversationId:e,cursor:null,handle:null};M=t;let n=i({watch:(n,r,i)=>o.watchConversation(e,{afterSequence:n,signal:r,onCursor:e=>pe(t,e),onEvent:e=>{i(),M===t&&(e.name===`messageCompleted`&&pe(t,e.data.message.sequence),Z(e,`live`,()=>M===t))}}),beforeReconnect:()=>Q(),getCursor:()=>{let e=t.cursor;for(let t of _.messages)t.sequence!==null&&(e===null||t.sequence>e)&&(e=t.sequence);return e},onStatus:e=>{M===t&&_.live!==e&&U({live:e})},onError:e=>q(e)});t.handle=n,M!==t&&n.stop()},U=e=>{let t={..._,...e};_.conversationState===`WithAgent`&&t.conversationState!==`WithAgent`&&t.agentTyping!==null&&(R(),t.agentTyping=null),(e.messages!==void 0||e.conversationState!==void 0)&&(t.agent=fe(t.messages,t.conversationState)),_=Ee(t);for(let e of g)e();e.messages!==void 0&&ke(),H()},W=(e,t)=>U({attachments:_.attachments.map(n=>n.key===e?{...n,...t}:n)}),G=()=>{if(C.size===0)return;let e=[...C.values()];C.clear(),U({messages:_.messages.map(t=>{let n=e.filter(e=>e.messageId===t.id);if(n.length===0)return t;let r=t.parts.map((e,t)=>{let r=n.filter(e=>e.index===t).map(e=>e.text).join(``);return e.kind===`Text`&&r!==``?{...e,text:e.text+r}:e});return{...t,parts:r}})})},K=()=>{C.clear(),b?.(),b=null},Me=(e,t,n)=>{let r=`${e}#${t}`,i=C.get(r);C.set(r,{messageId:e,index:t,text:(i?.text??``)+n}),b||=_e(()=>{b=null,G()})},Ne=()=>{G(),v+=1,y?.abort(),y=null},q=e=>{if(p.onError)p.onError(e);else throw e},J=()=>{for(let e of E.values())e.abort();E.clear();for(let e of T){let t=w.get(e);t&&o.deleteAttachment(t.publicId).catch(q)}T.clear(),w.clear()},Pe=e=>{let t=w.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},Fe=async(e,t)=>{let n=new l.AbortController;E.set(e,n);let r;try{r=await o.uploadAttachment(t,{signal:n.signal,onProgress:t=>{E.get(e)===n&&W(e,{progress:t})}})}catch{E.get(e)===n&&(E.delete(e),W(e,{status:`Failed`,progress:null,error:m.attachmentFailed}));return}E.get(e)===n?(E.delete(e),w.set(e,r),T.add(e),W(e,{status:`Ready`,progress:null})):o.deleteAttachment(r.publicId).catch(q)},Ie=e=>{let t={...u(p.pageContext?.()),path:we(),behaviour:p.behaviour?.()??null};return e&&(t.attribution=p.attribution?.()??null),t},Le=async()=>{let t=_.profile?.captcha;if(!t||!p.getCaptchaToken||t.mode===`Off`&&!t.siteKey)return null;let n=null;try{n=await p.getCaptchaToken(t.action)}catch{}if(!n)throw new e(`captcha_unavailable`,m.captchaUnavailable);return n},Re=(e,t,n)=>{let r=oe(_.messages,f(e,!1));U(n?{messages:r,messagesLeftToday:t??_.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},ze=e=>{let n=_.profile?.experience.pacing;return!n||be.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:a(t(e.parts),n,Te())},Be=(e,t,n,r,i)=>{I+=1,U({pending:{typing:!0,authorKind:e.author.kind}}),F=F.then(()=>new Promise(e=>l.setTimeout(e,n))).then(()=>{--I,r()&&Re(e,t,i),I===0&&U({pending:null})})},Ve=(e,t,n)=>{let r=[...e];return r[t]=n,r},Y=(e,t)=>_.messages.map(n=>n.id===e?t(n):n),X=e=>_.messages.some(t=>t.id===e),He=()=>{R(),_.agentTyping!==null&&U({agentTyping:null})},Ue=e=>{R(),k=l.setTimeout(()=>{k=null,U({agentTyping:null})},te),U({agentTyping:{displayName:e}})},Z=(e,t,n)=>{if(!n())return;let r=t===`turn`;if(e.name===`partDelta`)be.add(e.data.messageId),Me(e.data.messageId,e.data.index,e.data.text);else switch(G(),e.name){case`messageStarted`:{let t=e.data.message;if(t.author.kind===`Agent`&&He(),X(t.publicId))break;U({messages:[..._.messages,{id:t.publicId,author:t.author,createdDateTimeUtc:t.createdDateTimeUtc,parts:[...t.parts],sequence:t.sequence,rating:t.rating,ratingNote:t.ratingNote,streaming:!0,stored:!1,restored:!1}]});break}case`partStarted`:{let{messageId:t,index:n,part:i}=e.data;if(!X(t))break;U({messages:Y(t,e=>({...e,parts:Ve(e.parts,n,i)})),...r?{thinking:!1}:{}});break}case`partCompleted`:{let{messageId:t,index:n,part:r}=e.data;if(!X(t))break;U({messages:Y(t,e=>({...e,parts:Ve(e.parts,n,r)}))});break}case`messageReset`:{let{messageId:t}=e.data;if(!X(t))break;for(let e of[...C.keys()])C.get(e)?.messageId===t&&C.delete(e);U({messages:Y(t,e=>({...e,parts:[]})),...r?{thinking:!0,steps:[]}:{}});break}case`step`:{if(!r)break;let t=e.data.label;_.steps[_.steps.length-1]!==t&&U({steps:[..._.steps,t]});break}case`messageCompleted`:{let{message:t,messagesLeftToday:i}=e.data;t.author.kind===`Agent`&&He();let a=ze(t);a>0||I>0?Be(t,i,a,n,r):Re(t,i,r);break}case`conversationUpdated`:{let t=e.data;U({conversationId:t.conversationId,conversationState:t.state,title:t.title,continuesConversationId:t.continuesConversationId});break}case`typing`:e.data.authorKind===`Agent`&&Ue(e.data.displayName)}},Q=async()=>{let e=_.conversationId;if(e===null)return;let t=v;try{let n=await o.getConversation(e);if(t!==v)return;let r=new Set(_.messages.filter(e=>e.restored).map(e=>e.id));U({messages:n.messages.map(e=>f(e,r.has(e.publicId))),title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){q(e)}},$=async(e,t,n)=>{let r=v,i=new l.AbortController,a=()=>r===v&&!i.signal.aborted;y=i;let s=_.conversationId===null;ve+=1;let ee={id:`local-${ve}`,author:{kind:`Visitor`,displayName:null,avatarUrl:null},createdDateTimeUtc:(/* @__PURE__ */ new Date()).toISOString(),parts:me(e.displayText,e.attachments),sequence:null,rating:null,ratingNote:null,streaming:!1,stored:!1,restored:!1};n&&(T.clear(),w.clear()),U({messages:[...t,ee],thinking:!0,streaming:!0,steps:[],turnError:null,stopped:!1,...n?{editing:null,attachments:[]}:{}});try{let t=await Le();await o.send({conversationId:_.conversationId,text:e.wireText,quickReplyId:e.quickReplyId,attachmentIds:e.attachments.map(e=>e.publicId),replacesMessageId:e.replacesMessageId,pageContext:Ie(s),captchaToken:t},{signal:i.signal,onEvent:e=>Z(e,`turn`,a)})}catch(e){if(G(),!a())return;let t=d(e);U({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,turnError:t,...t.code===`daily_limit`?{messagesLeftToday:0}:{},...t.code===`conversation_not_found`?{conversationId:null}:{}});return}finally{y===i&&(y=null)}if(await F,!a())return;G(),U({thinking:!1,streaming:!1}),await Q();let c=_.conversationId;s&&c!==null&&c!==x&&(x=c,p.onEvent?.(`chatStarted`,{conversationId:c}))},We=e=>U({messages:_.messages.map(t=>({...t,parts:t.parts.map(t=>t.kind===`Action`&&t.actionId===e.actionId?{...t,state:e.state,decidedDateTimeUtc:e.decidedDateTimeUtc,note:e.note}:t)}))}),Ge=async()=>{try{U({openTickets:await o.listOpenTickets()})}catch{}},Ke=async()=>{let e;try{e=await o.getProfile(p.screen)}catch(e){U({profileError:d(e)});return}let t=s(e,p.narrow);if(U({profile:e,profileError:null,features:t,messagesLeftToday:e.messagesLeftToday}),t.OpenTickets&&Ge(),t.ResumeLast&&t.History)try{let e=await o.listConversations({page:1,pageSize:1});U({lastConversation:e.items[0]??null})}catch{}p.conversationId&&await ot(p.conversationId)},qe=()=>(S||=Ke(),S),Je=async e=>{let t=typeof e==`string`?e.trim():``,n=_.attachments.filter(e=>e.status===`Ready`);if(t===``&&n.length===0||_.streaming||_.attachments.some(e=>e.status===`Uploading`))return;let r=_.messages,i=null;if(_.editing){let e=_.messages.findIndex(e=>e.id===_.editing?.messageId),t=_.messages[e];if(!t?.stored)return;i=t.id,r=_.messages.slice(0,e)}let a=n.map(e=>Pe(e.key));await $({wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:i,attachments:a},r,!0)},Ye=async e=>{e.action!==`Send`||L()||(e.id===`handoff.request`&&_.features.HumanHandoff&&_.conversationId!==null&&!_.handoffPending?await _t():await $({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,attachments:[]},_.messages,!1))},Xe=async(t,n,r=null)=>{if(_.streaming)return{ok:!1,errors:{},message:m.errorGeneric};let i=v,a=new l.AbortController,s=()=>i===v&&!a.signal.aborted;y=a,Ae(t,n),U({streaming:!0,thinking:!0});try{let e=await Le();await o.answerInput(t,{values:n,codes:r,captchaToken:e,attribution:p.attribution?.()??null},{signal:a.signal,onEvent:e=>Z(e,`turn`,s)})}catch(t){return G(),U({thinking:!1,streaming:!1}),a.signal.aborted?{ok:!1,errors:{},message:m.errorGeneric}:t instanceof e&&t.code===`validation_failed`?{ok:!1,errors:t.errors??{},message:t.message}:t instanceof e&&t.code===`input_request_closed`?(await Q(),{ok:!1,errors:{},message:t.message}):{ok:!1,errors:{},message:d(t).message}}finally{y===a&&(y=null)}return await F,s()&&(G(),U({thinking:!1,streaming:!1}),p.onEvent?.(`inputSubmitted`,{requestId:t}),await Q()),{ok:!0}},Ze=async e=>{let t=await o.confirmAction(e);We(t),p.onEvent?.(`chatActionConfirmed`,{actionId:t.actionId,kind:t.actionKind}),await Q()},Qe=async(e,t)=>{We(await o.rejectAction(e,t)),await Q()},$e=()=>{if(!_.streaming)return;K();let e=y;y=null,e?.abort(),U({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,stopped:!0,steps:[],pending:null})},et=async()=>{if(_.streaming||_.turnError===null&&!_.stopped)return;let e=se(_.messages,e=>e.author.kind===`Visitor`);e<0||await $(he(_.messages[e]),_.messages.slice(0,e),!1)},tt=async()=>{if(L())return;let e=se(_.messages,e=>e.author.kind===`Visitor`&&e.stored);if(e<0)return;let t=_.messages[e];await $({...he(t),replacesMessageId:t.id},_.messages.slice(0,e),!1)},nt=e=>{let t=_.messages.find(t=>t.id===e);t?.stored&&t.author.kind===`Visitor`&&(J(),U({editing:{messageId:e,text:ce(t.parts)},attachments:[]}))},rt=()=>{_.editing&&(J(),U({editing:null,attachments:[]}))},it=async e=>{let t=_.profile;if(!t||!_.features.Attachments)return;let n=t.limits,r=n.maxAttachments-_.attachments.filter(e=>e.status!==`Failed`).length,i=[],a=[];for(let t of e){let e=le(t);ye+=1;let o=`file-${ye}`,s={key:o,fileName:e.fileName,contentType:e.contentType,length:e.length??0};r<=0?i.push({...s,status:`Failed`,progress:null,error:m.attachmentLimit(n.maxAttachments)}):e.length!==null&&e.length>n.maxFileBytes||!n.contentTypes.includes(e.contentType)?i.push({...s,status:`Failed`,progress:null,error:m.attachmentFailed}):(--r,i.push({...s,status:`Uploading`,progress:0,error:null}),a.push({key:o,file:t}))}U({attachments:[..._.attachments,...i]}),await Promise.all(a.map(({key:e,file:t})=>Fe(e,t)))},at=async e=>{let t=E.get(e);t&&(E.delete(e),t.abort());let n=T.has(e)?w.get(e):void 0;n&&await o.deleteAttachment(n.publicId),T.delete(e),w.delete(e),U({attachments:_.attachments.filter(t=>t.key!==e)})};async function ot(e){Ne();let t=v;U({messages:[],conversationId:null,loadError:null,loading:!0,editing:null,thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1});try{let n=await o.getConversation(e);if(t!==v)return;let r=n.messages.map(e=>f(e,!0));B(),Oe(r),U({messages:r,conversationId:n.publicId,title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){if(t!==v)return;U({loadError:d(e)})}finally{t===v&&U({loading:!1})}}let st=async()=>{let e=_.lastConversation;e&&await ot(e.publicId)},ct=()=>{J(),Ne(),K(),B(),U({messages:[],conversationId:null,title:null,conversationState:`Open`,continuesConversationId:null,loadError:null,loading:!1,editing:null,attachments:[],thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1,pending:null}),_.features.OpenTickets&&Ge()},lt=(e,t,n)=>{U({messages:Y(e,e=>({...e,rating:t,ratingNote:n}))})},ut=async(e,t,n)=>{let r=_.messages.find(t=>t.id===e);if(!r?.stored)throw Error(`Only a stored reply can be rated.`);let i={rating:r.rating,ratingNote:r.ratingNote},a=typeof n==`string`&&n.trim()?n.trim():null;lt(e,t,a);try{await o.rateMessage(e,{rating:t,note:a})}catch(t){throw lt(e,i.rating,i.ratingNote),t}p.onEvent?.(`rated`,{messageId:e,rating:t})},dt=e=>{let t=_.open,n=e?.trigger??`manual`,r=e?.draft,i={open:!0};typeof r==`string`&&r.trim()!==``&&(i.draft=r),!t&&n===`auto`&&h?.set(`wchat:auto-opened`,`1`),U(i),t||p.onEvent?.(`chatOpened`,{layout:p.layout??null,trigger:n})},ft=e=>{_.open&&(h?.set(`wchat:dismissed`,`1`),U({open:!1}),p.onEvent?.(`chatClosed`,{layout:p.layout??null,reason:e}))},pt=e=>{h?.set(`wchat:muted`,e?`1`:`0`),U({muted:e}),p.onEvent?.(`chatSoundToggled`,{muted:e})},mt=async e=>{L()||(p.onEvent?.(`chatLeadSkipped`,{requestId:e}),await $({wireText:null,displayText:m.skip,quickReplyId:`lead.skip`,replacesMessageId:null,attachments:[]},_.messages,!1))},ht=async()=>{L()||(p.onEvent?.(`chatLeadCancelled`,{}),await $({wireText:null,displayText:m.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,attachments:[]},_.messages,!1))},gt=async(e,t)=>{L()||_.messages.some(t=>t.parts.some(t=>t.kind===`Action`&&t.actionId===e))&&await $({wireText:null,displayText:m.editSomething,quickReplyId:`lead.edit:${t}`,replacesMessageId:null,attachments:[]},_.messages,!1)},_t=async t=>{if(!_.features.HumanHandoff)throw new e(`chat_feature_off`,n.errorGeneric,403);let r=_.conversationId;if(r===null)throw new e(`conversation_required`,n.errorGeneric);if(_.streaming||_.handoffPending)throw new e(`busy`,n.errorGeneric);let i=new l.AbortController;j=i,U({handoffPending:!0}),p.onEvent?.(`chatHandoffRequested`,{conversationId:r});try{await o.requestHandoff({conversationId:r,reason:t??null},{signal:i.signal,onEvent:e=>Z(e,`handoff`,()=>!i.signal.aborted)})}catch(e){throw U({messages:_.messages.filter(e=>!e.streaming),handoffPending:!1}),e}finally{j===i&&(j=null)}U({handoffPending:!1}),await Q(),p.onEvent?.(`chatHandoff`,{destination:`person`})},vt=()=>{let e=_.conversationId;if(!_.features.HumanHandoff||e===null||_.conversationState!==`WithAgent`)return;let t=Date.now();xe!==null&&t-xe<ne||(xe=t,o.sendTyping(e).catch(()=>void 0))},yt=e=>{Se=e,H()},bt=()=>{_.live===`Lost`&&je()&&(V(null),H())},xt=e=>{if(p.reducedMotion?.()===!0)return re;let t=e.navigateAfterMs;if(typeof t==`number`&&Number.isFinite(t)&&t>=0)return t;let n=_.profile?.experience.pacing.handoffPauseMs;return typeof n==`number`&&Number.isFinite(n)?n:ie},St=()=>{z(),_.handoffPause&&U({handoffPause:!1})};return{client:o,getState:()=>_,subscribe:e=>(g.add(e),S||qe(),()=>{g.delete(e)}),load:qe,submit:Je,chooseQuickReply:Ye,answerInput:Xe,confirmAction:Ze,rejectAction:Qe,stop:$e,retry:et,regenerate:tt,startEdit:nt,cancelEdit:rt,attach:it,removeAttachment:at,openConversation:ot,resumeLast:st,newConversation:ct,rate:ut,open:dt,close:ft,setMuted:pt,skipField:mt,cancelLead:ht,editLeadField:gt,requestHandoff:_t,notifyTyping:vt,setLiveActive:yt,resumeLive:bt,beginHandoff:(e,t)=>{_.handoffPause||(U({handoffPause:!0}),p.onEvent?.(`chatHandoff`,{destination:e.id}),A=l.setTimeout(()=>{A=null;try{t()}catch(e){St(),q(e)}},xt(e)))},endHandoffPause:St,consumeDraft:()=>{_.draft!==null&&U({draft:null})},loadAttachmentUrl:t=>{let n=P.get(t);if(n)return n;let r=(async()=>{let n=l.Blob,r=l.URL;if(!n||typeof r?.createObjectURL!=`function`)throw new e(`unsupported`,m.errorGeneric);let i=await o.getAttachment(t);if(Ce)throw new e(`aborted`,m.errorGeneric);let a=r.createObjectURL(new n([i]));return N.add(a),a})();return P.set(t,r),r.catch(()=>{P.get(t)===r&&P.delete(t)}),r},reset:()=>{J(),K(),Ne(),S=null,F=Promise.resolve(),I=0,be.clear(),x=null,B(),R(),z(),U(ge(h))},dispose:()=>{g.clear(),Ce=!0,v+=1;let e=y;y=null,e?.abort(),j?.abort(),j=null,z(),R(),V(null),J(),K();for(let e of N)l.URL?.revokeObjectURL?.(e);N.clear(),P.clear(),U({attachments:[],editing:null,agentTyping:null})}}},_e=e=>{let t=-1;for(let n=e.length-1;n>=0;--n)if(e[n].parts.some(e=>e.kind===`Handoff`)){t=n;break}let n=/* @__PURE__ */ new Set;for(let r=0;r<t;r+=1)n.add(e[r].id);return n},h=(e,t)=>({get features(){return e.getState().features},labels:t.labels,get isLast(){let n=e.getState().messages;return n[n.length-1]?.id===t.messageId},get busy(){let t=e.getState();return t.streaming||t.thinking},get handoffPause(){return e.getState().handoffPause},get handoffSettled(){return _e(e.getState().messages).has(t.messageId)},chooseQuickReply(t){e.chooseQuickReply(t)},skipInput(t){e.skipField(t)},cancelLead(){e.cancelLead()},answerInput:(t,n,r)=>e.answerInput(t,n,r),uploadInputFile:async(t,n)=>(await e.client.uploadAttachment(t,n?{onProgress:n}:{})).publicId,sendOtp:(t,n)=>e.client.sendOtp(t,n),confirmAction:t=>e.confirmAction(t),rejectAction:(t,n)=>e.rejectAction(t,n),requestHandoff:t=>e.requestHandoff(t),beginHandoff:(t,n)=>e.beginHandoff(t,n),readAttachment:t=>e.client.getAttachment(t),loadAttachmentUrl:t=>e.loadAttachmentUrl(t),...t.openAttachment?{openAttachment:t.openAttachment}:{},...t.openRecord?{openRecord:t.openRecord}:{},...t.openTicket?{openTicket:t.openTicket}:{},...t.attachmentUrl?{attachmentUrl:t.attachmentUrl}:{},...t.handoffHosts?{handoffHosts:t.handoffHosts}:{},...t.openCitation?{openCitation:t.openCitation}:{},...t.isCitation?{isCitation:t.isCitation}:{},...t.openTarget?{openTarget:t.openTarget}:{},...t.onNavigate?{onNavigate:t.onNavigate}:{}});export{m as createChatSession,h as createTurnApi,_e as handoffSettledIds};
3
+ `),p=e=>e.flatMap(e=>e.kind===`File`?[{publicId:e.attachmentId,fileName:e.fileName,contentType:e.contentType,length:e.length}]:[]),le=e=>{let t=d(e);return{fileName:typeof t.name==`string`?t.name:``,contentType:typeof t.type==`string`?t.type:``,length:typeof t.size==`number`?t.size:null}},ue=(e,t)=>e.length===t.length&&e.every((e,n)=>e.id===t[n].id&&e.label===t[n].label&&e.message===t[n].message),de=e=>{for(let t of e){if(!t.startsWith(`Enquiry type:`))continue;let e=t.slice(13).trim();return e===``?null:e}return null},fe=e=>e.some(e=>e.kind===`Handoff`)?null:e.find(e=>e.kind===`InputRequest`)?.requestId??null,pe=(e,t)=>e.some(e=>e.parts.some(e=>e.kind===`InputRequest`&&e.requestId===t&&(e.state===`Skipped`||e.state===`Expired`))),me=(e,t)=>{if(t!==`WithAgent`)return null;for(let t=e.length-1;t>=0;--t){let n=e[t];for(let e=n.parts.length-1;e>=0;--e){let t=n.parts[e];if(t.kind===`Handoff`){if(t.state===`Left`||t.state===`Ended`)return null;if(t.state===`Joined`&&t.agent)return t.agent}}if(n.author.kind===`Agent`)return{displayName:n.author.displayName??``,avatarUrl:n.author.avatarUrl}}return null},he=(e,t)=>{(e.cursor===null||t>e.cursor)&&(e.cursor=t)},ge=(e,t)=>{let n=[];e!==``&&n.push({kind:`Text`,text:e});for(let e of t)n.push({kind:`File`,attachmentId:e.publicId,fileName:e.fileName,contentType:e.contentType,length:e.length});return n},_e=e=>{let t=ce(e.parts);return{wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:null,attachments:p(e.parts)}},ve=e=>({profile:null,profileError:null,features:o(),conversationId:null,conversationState:`Open`,title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,open:!1,muted:e?.get(`wchat:muted`)===`1`,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:`Off`,handoffPending:!1,handoffContactRequestId:null,handoffPause:!1,openTickets:[],draft:null}),m=(o,p)=>{let m=r(p.labels),ye=p.schedule??ie,h=p.prefs,g=/* @__PURE__ */ new Set,_=ve(h),v=0,y=null,b=null,be=0,xe=0,Se=null,x=null,S=/* @__PURE__ */ new Map,Ce=/* @__PURE__ */ new Set,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Set,T=/* @__PURE__ */ new Map,E={name:null,email:null,phone:null},D=/* @__PURE__ */ new Set,O=null,k=null,A=null,j=null,M=null,we=!0,Te=!1,Ee=/* @__PURE__ */ new Set,N=/* @__PURE__ */ new Map,P=Promise.resolve(),F=0,De=()=>p.pathname?.()??u.location?.pathname??`/`,Oe=()=>p.reducedMotion?.()===!0||_.profile?.experience.motion===!1,I=()=>_.streaming||_.thinking,ke=e=>{if(!e.profile)return{...e,greeting:null,starters:[]};let t=De(),n=e.lastConversation!==null,r=c(e.profile,{pathname:t,returning:n}).greeting,i=l(e.profile.start,{pathname:t,returning:n,behaviour:p.behaviour?.()??null,behaviourStarters:e.features.BehaviourStarters});return{...e,greeting:r,starters:ue(e.starters,i)?e.starters:i}},L=()=>{O!==null&&(u.clearTimeout(O),O=null)},R=()=>{A!==null&&(u.clearTimeout(A),A=null)},Ae=e=>e.flatMap(e=>e.parts.flatMap(e=>e.kind===`Action`&&e.actionKind===`ChatLeadCapture`&&e.state===`Done`?[{actionId:e.actionId,leadType:de(e.lines)}]:[])),z=()=>{E.name=null,E.email=null,E.phone=null,D.clear()},je=e=>{for(let t of Ae(e))D.add(t.actionId)},Me=()=>{for(let e of Ae(_.messages))D.has(e.actionId)||(D.add(e.actionId),p.onEvent?.(`leadSubmitted`,{conversationId:_.conversationId,fields:{name:E.name,email:E.email,phone:E.phone},leadType:e.leadType}))},Ne=(e,t)=>{let n=_.messages.flatMap(e=>e.parts).find(t=>t.kind===`InputRequest`&&t.requestId===e);if(n)for(let e of n.fields){let n=t[e.key];typeof n==`string`&&n.trim()!==``&&(e.type===`Email`?E.email=n.trim():e.type===`Phone`?E.phone=n.trim():(e.type===`Name`||e.key.toLowerCase()===`name`)&&(E.name=n.trim()))}},B=e=>{let t=M;t!==null&&(M=null,t.handle?.stop(),e!==null&&H({live:e}))},Pe=()=>!Te&&we&&_.features.HumanHandoff&&_.conversationId!==null&&(_.conversationState===`WaitingForAgent`||_.conversationState===`WithAgent`),V=()=>{if(!Pe()){M!==null&&B(`Off`);return}let e=_.conversationId;if(e===null||M!==null&&M.conversationId===e)return;B(null);let t={conversationId:e,cursor:null,handle:null};M=t;let n=i({watch:(n,r,i)=>o.watchConversation(e,{afterSequence:n,signal:r,onCursor:e=>he(t,e),onEvent:e=>{i(),M===t&&(e.name===`messageCompleted`&&he(t,e.data.message.sequence),X(e,`live`,()=>M===t))}}),beforeReconnect:()=>Z(),getCursor:()=>{let e=t.cursor;for(let t of _.messages)t.sequence!==null&&(e===null||t.sequence>e)&&(e=t.sequence);return e},onStatus:e=>{M===t&&_.live!==e&&H({live:e})},onError:e=>K(e)});t.handle=n,M!==t&&n.stop()},H=e=>{let t={..._,...e};_.conversationState===`WithAgent`&&t.conversationState!==`WithAgent`&&t.agentTyping!==null&&(L(),t.agentTyping=null),(e.messages!==void 0||e.conversationState!==void 0)&&(t.agent=me(t.messages,t.conversationState)),e.messages!==void 0&&t.handoffContactRequestId!==null&&pe(t.messages,t.handoffContactRequestId)&&(t.handoffContactRequestId=null),_=ke(t);for(let e of g)e();e.messages!==void 0&&Me(),V()},U=(e,t)=>H({attachments:_.attachments.map(n=>n.key===e?{...n,...t}:n)}),W=()=>{if(S.size===0)return;let e=[...S.values()];S.clear(),H({messages:_.messages.map(t=>{let n=e.filter(e=>e.messageId===t.id);if(n.length===0)return t;let r=t.parts.map((e,t)=>{let r=n.filter(e=>e.index===t).map(e=>e.text).join(``);return e.kind===`Text`&&r!==``?{...e,text:e.text+r}:e});return{...t,parts:r}})})},G=()=>{S.clear(),b?.(),b=null},Fe=(e,t,n)=>{let r=`${e}#${t}`,i=S.get(r);S.set(r,{messageId:e,index:t,text:(i?.text??``)+n}),b||=ye(()=>{b=null,W()})},Ie=()=>{W(),v+=1,y?.abort(),y=null},K=e=>{if(p.onError)p.onError(e);else throw e},q=()=>{for(let e of T.values())e.abort();T.clear();for(let e of w){let t=C.get(e);t&&o.deleteAttachment(t.publicId).catch(K)}w.clear(),C.clear()},Le=e=>{let t=C.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},Re=async(e,t)=>{let n=new u.AbortController;T.set(e,n);let r;try{r=await o.uploadAttachment(t,{signal:n.signal,onProgress:t=>{T.get(e)===n&&U(e,{progress:t})}})}catch{T.get(e)===n&&(T.delete(e),U(e,{status:`Failed`,progress:null,error:m.attachmentFailed}));return}T.get(e)===n?(T.delete(e),C.set(e,r),w.add(e),U(e,{status:`Ready`,progress:null})):o.deleteAttachment(r.publicId).catch(K)},ze=e=>{let t={...d(p.pageContext?.()),path:De(),behaviour:p.behaviour?.()??null};return e&&(t.attribution=p.attribution?.()??null),t},Be=async()=>{let t=_.profile?.captcha;if(!t||!p.getCaptchaToken||t.mode===`Off`&&!t.siteKey)return null;let n=null;try{n=await p.getCaptchaToken(t.action)}catch{}if(!n)throw new e(`captcha_unavailable`,m.captchaUnavailable);return n},Ve=(e,t,n)=>{let r=oe(_.messages,ae(e,!1));H(n?{messages:r,messagesLeftToday:t??_.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},He=e=>{let n=_.profile?.experience.pacing;return!n||Ce.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:a(t(e.parts),n,Oe())},Ue=(e,t,n,r,i)=>{F+=1,H({pending:{typing:!0,authorKind:e.author.kind}}),P=P.then(()=>new Promise(e=>u.setTimeout(e,n))).then(()=>{--F,r()&&Ve(e,t,i),F===0&&H({pending:null})})},We=(e,t,n)=>{let r=[...e];return r[t]=n,r},J=(e,t)=>_.messages.map(n=>n.id===e?t(n):n),Y=e=>_.messages.some(t=>t.id===e),Ge=()=>{L(),_.agentTyping!==null&&H({agentTyping:null})},Ke=e=>{L(),O=u.setTimeout(()=>{O=null,H({agentTyping:null})},ee),H({agentTyping:{displayName:e}})},X=(e,t,n)=>{if(!n())return;let r=t===`turn`;if(e.name===`partDelta`)Ce.add(e.data.messageId),Fe(e.data.messageId,e.data.index,e.data.text);else switch(W(),e.name){case`messageStarted`:{let t=e.data.message;if(t.author.kind===`Agent`&&Ge(),Y(t.publicId))break;H({messages:[..._.messages,{id:t.publicId,author:t.author,createdDateTimeUtc:t.createdDateTimeUtc,parts:[...t.parts],sequence:t.sequence,rating:t.rating,ratingNote:t.ratingNote,streaming:!0,stored:!1,restored:!1}]});break}case`partStarted`:{let{messageId:t,index:n,part:i}=e.data;if(!Y(t))break;H({messages:J(t,e=>({...e,parts:We(e.parts,n,i)})),...r?{thinking:!1}:{}});break}case`partCompleted`:{let{messageId:t,index:n,part:r}=e.data;if(!Y(t))break;H({messages:J(t,e=>({...e,parts:We(e.parts,n,r)}))});break}case`messageReset`:{let{messageId:t}=e.data;if(!Y(t))break;for(let e of[...S.keys()])S.get(e)?.messageId===t&&S.delete(e);H({messages:J(t,e=>({...e,parts:[]})),...r?{thinking:!0,steps:[]}:{}});break}case`step`:{if(!r)break;let t=e.data.label;_.steps[_.steps.length-1]!==t&&H({steps:[..._.steps,t]});break}case`messageCompleted`:{let{message:t,messagesLeftToday:i}=e.data;t.author.kind===`Agent`&&Ge();let a=He(t);a>0||F>0?Ue(t,i,a,n,r):Ve(t,i,r);break}case`conversationUpdated`:{let t=e.data;H({conversationId:t.conversationId,conversationState:t.state,title:t.title,continuesConversationId:t.continuesConversationId});break}case`typing`:e.data.authorKind===`Agent`&&Ke(e.data.displayName)}},Z=async()=>{let e=_.conversationId;if(e===null)return;let t=v;try{let n=await o.getConversation(e);if(t!==v)return;let r=new Set(_.messages.filter(e=>e.restored).map(e=>e.id));H({messages:n.messages.map(e=>ae(e,r.has(e.publicId))),title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){K(e)}},Q=async(e,t,n)=>{let r=v,i=new u.AbortController,a=()=>r===v&&!i.signal.aborted;y=i;let s=_.conversationId===null;be+=1;let c={id:`local-${be}`,author:{kind:`Visitor`,displayName:null,avatarUrl:null},createdDateTimeUtc:(/* @__PURE__ */ new Date()).toISOString(),parts:ge(e.displayText,e.attachments),sequence:null,rating:null,ratingNote:null,streaming:!1,stored:!1,restored:!1};n&&(w.clear(),C.clear()),H({messages:[...t,c],thinking:!0,streaming:!0,steps:[],turnError:null,stopped:!1,...n?{editing:null,attachments:[]}:{}});try{let t=await Be();await o.send({conversationId:_.conversationId,text:e.wireText,quickReplyId:e.quickReplyId,attachmentIds:e.attachments.map(e=>e.publicId),replacesMessageId:e.replacesMessageId,pageContext:ze(s),captchaToken:t},{signal:i.signal,onEvent:e=>X(e,`turn`,a)})}catch(e){if(W(),!a())return;let t=f(e);H({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,turnError:t,...t.code===`daily_limit`?{messagesLeftToday:0}:{},...t.code===`conversation_not_found`?{conversationId:null}:{}});return}finally{y===i&&(y=null)}if(await P,!a())return;W(),H({thinking:!1,streaming:!1}),await Z();let l=_.conversationId;s&&l!==null&&l!==Se&&(Se=l,p.onEvent?.(`chatStarted`,{conversationId:l}))},qe=e=>H({messages:_.messages.map(t=>({...t,parts:t.parts.map(t=>t.kind===`Action`&&t.actionId===e.actionId?{...t,state:e.state,decidedDateTimeUtc:e.decidedDateTimeUtc,note:e.note}:t)}))}),Je=async()=>{try{H({openTickets:await o.listOpenTickets()})}catch{}},Ye=async()=>{let e;try{e=await o.getProfile(p.screen)}catch(e){H({profileError:f(e)});return}let t=s(e,p.narrow);if(H({profile:e,profileError:null,features:t,messagesLeftToday:e.messagesLeftToday}),t.OpenTickets&&Je(),t.ResumeLast&&t.History)try{let e=await o.listConversations({page:1,pageSize:1});H({lastConversation:e.items[0]??null})}catch{}p.conversationId&&await lt(p.conversationId)},Xe=()=>(x||=Ye(),x),Ze=async e=>{let t=typeof e==`string`?e.trim():``,n=_.attachments.filter(e=>e.status===`Ready`);if(t===``&&n.length===0||_.streaming||_.attachments.some(e=>e.status===`Uploading`))return;let r=_.messages,i=null;if(_.editing){let e=_.messages.findIndex(e=>e.id===_.editing?.messageId),t=_.messages[e];if(!t?.stored)return;i=t.id,r=_.messages.slice(0,e)}let a=n.map(e=>Le(e.key));await Q({wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:i,attachments:a},r,!0)},Qe=async e=>{e.action!==`Send`||I()||(e.id===`handoff.request`&&_.features.HumanHandoff&&_.conversationId!==null&&!_.handoffPending?await $():await Q({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,attachments:[]},_.messages,!1))},$e=async(t,n,r=null)=>{if(_.streaming)return{ok:!1,errors:{},message:m.errorGeneric};let i=v,a=new u.AbortController,s=()=>i===v&&!a.signal.aborted;y=a,Ne(t,n);let c=t===_.handoffContactRequestId;H({streaming:!0,thinking:!0});try{let e=await Be();await o.answerInput(t,{values:n,codes:r,captchaToken:e,attribution:p.attribution?.()??null},{signal:a.signal,onEvent:e=>X(e,`turn`,s)})}catch(t){return W(),H({thinking:!1,streaming:!1}),a.signal.aborted?{ok:!1,errors:{},message:m.errorGeneric}:t instanceof e&&t.code===`validation_failed`?{ok:!1,errors:t.errors??{},message:t.message}:t instanceof e&&t.code===`input_request_closed`?(await Z(),{ok:!1,errors:{},message:t.message}):{ok:!1,errors:{},message:f(t).message}}finally{y===a&&(y=null)}return await P,s()&&(W(),H({thinking:!1,streaming:!1}),p.onEvent?.(`inputSubmitted`,{requestId:t}),await Z(),c&&(H({handoffContactRequestId:null}),await $().catch(K))),{ok:!0}},et=async e=>{let t=await o.confirmAction(e);qe(t),p.onEvent?.(`chatActionConfirmed`,{actionId:t.actionId,kind:t.actionKind}),await Z()},tt=async(e,t)=>{qe(await o.rejectAction(e,t)),await Z()},nt=()=>{if(!_.streaming)return;G();let e=y;y=null,e?.abort(),H({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,stopped:!0,steps:[],pending:null})},rt=async()=>{if(_.streaming||_.turnError===null&&!_.stopped)return;let e=se(_.messages,e=>e.author.kind===`Visitor`);e<0||await Q(_e(_.messages[e]),_.messages.slice(0,e),!1)},it=async()=>{if(I())return;let e=se(_.messages,e=>e.author.kind===`Visitor`&&e.stored);if(e<0)return;let t=_.messages[e];await Q({..._e(t),replacesMessageId:t.id},_.messages.slice(0,e),!1)},at=e=>{let t=_.messages.find(t=>t.id===e);t?.stored&&t.author.kind===`Visitor`&&(q(),H({editing:{messageId:e,text:ce(t.parts)},attachments:[]}))},ot=()=>{_.editing&&(q(),H({editing:null,attachments:[]}))},st=async e=>{let t=_.profile;if(!t||!_.features.Attachments)return;let n=t.limits,r=n.maxAttachments-_.attachments.filter(e=>e.status!==`Failed`).length,i=[],a=[];for(let t of e){let e=le(t);xe+=1;let o=`file-${xe}`,s={key:o,fileName:e.fileName,contentType:e.contentType,length:e.length??0};r<=0?i.push({...s,status:`Failed`,progress:null,error:m.attachmentLimit(n.maxAttachments)}):e.length!==null&&e.length>n.maxFileBytes||!n.contentTypes.includes(e.contentType)?i.push({...s,status:`Failed`,progress:null,error:m.attachmentFailed}):(--r,i.push({...s,status:`Uploading`,progress:0,error:null}),a.push({key:o,file:t}))}H({attachments:[..._.attachments,...i]}),await Promise.all(a.map(({key:e,file:t})=>Re(e,t)))},ct=async e=>{let t=T.get(e);t&&(T.delete(e),t.abort());let n=w.has(e)?C.get(e):void 0;n&&await o.deleteAttachment(n.publicId),w.delete(e),C.delete(e),H({attachments:_.attachments.filter(t=>t.key!==e)})};async function lt(e){Ie();let t=v;H({messages:[],conversationId:null,loadError:null,loading:!0,editing:null,thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1});try{let n=await o.getConversation(e);if(t!==v)return;let r=n.messages.map(e=>ae(e,!0));z(),je(r),H({messages:r,conversationId:n.publicId,title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){if(t!==v)return;H({loadError:f(e)})}finally{t===v&&H({loading:!1})}}let ut=async()=>{let e=_.lastConversation;e&&await lt(e.publicId)},dt=()=>{q(),Ie(),G(),z(),H({messages:[],conversationId:null,title:null,conversationState:`Open`,continuesConversationId:null,loadError:null,loading:!1,editing:null,attachments:[],thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1,pending:null}),_.features.OpenTickets&&Je()},ft=(e,t,n)=>{H({messages:J(e,e=>({...e,rating:t,ratingNote:n}))})},pt=async(e,t,n)=>{let r=_.messages.find(t=>t.id===e);if(!r?.stored)throw Error(`Only a stored reply can be rated.`);let i={rating:r.rating,ratingNote:r.ratingNote},a=typeof n==`string`&&n.trim()?n.trim():null;ft(e,t,a);try{await o.rateMessage(e,{rating:t,note:a})}catch(t){throw ft(e,i.rating,i.ratingNote),t}p.onEvent?.(`rated`,{messageId:e,rating:t})},mt=e=>{let t=_.open,n=e?.trigger??`manual`,r=e?.draft,i={open:!0};typeof r==`string`&&r.trim()!==``&&(i.draft=r),!t&&n===`auto`&&h?.set(`wchat:auto-opened`,`1`),H(i),t||p.onEvent?.(`chatOpened`,{layout:p.layout??null,trigger:n})},ht=e=>{_.open&&(h?.set(`wchat:dismissed`,`1`),H({open:!1}),p.onEvent?.(`chatClosed`,{layout:p.layout??null,reason:e}))},gt=e=>{h?.set(`wchat:muted`,e?`1`:`0`),H({muted:e}),p.onEvent?.(`chatSoundToggled`,{muted:e})},_t=async e=>{I()||(e===_.handoffContactRequestId&&H({handoffContactRequestId:null}),p.onEvent?.(`chatLeadSkipped`,{requestId:e}),await Q({wireText:null,displayText:m.skip,quickReplyId:`lead.skip`,replacesMessageId:null,attachments:[]},_.messages,!1))},vt=async()=>{I()||(p.onEvent?.(`chatLeadCancelled`,{}),await Q({wireText:null,displayText:m.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,attachments:[]},_.messages,!1))},yt=async(e,t)=>{I()||_.messages.some(t=>t.parts.some(t=>t.kind===`Action`&&t.actionId===e))&&await Q({wireText:null,displayText:m.editSomething,quickReplyId:`lead.edit:${t}`,replacesMessageId:null,attachments:[]},_.messages,!1)},$=async t=>{if(!_.features.HumanHandoff)throw new e(`chat_feature_off`,n.errorGeneric,403);let r=_.conversationId;if(r===null)throw new e(`conversation_required`,n.errorGeneric);if(_.streaming||_.handoffPending)throw new e(`busy`,n.errorGeneric);let i=new u.AbortController;j=i,H({handoffPending:!0}),p.onEvent?.(`chatHandoffRequested`,{conversationId:r});let a=null;try{a=fe((await o.requestHandoff({conversationId:r,reason:t??null},{signal:i.signal,onEvent:e=>X(e,`handoff`,()=>!i.signal.aborted)})).parts)}catch(e){throw H({messages:_.messages.filter(e=>!e.streaming),handoffPending:!1}),e}finally{j===i&&(j=null)}H({handoffPending:!1,handoffContactRequestId:a}),await Z(),p.onEvent?.(`chatHandoff`,{destination:`person`})},bt=()=>{let e=_.conversationId;if(!_.features.HumanHandoff||e===null||_.conversationState!==`WithAgent`)return;let t=Date.now();k!==null&&t-k<te||(k=t,o.sendTyping(e).catch(()=>void 0))},xt=e=>{we=e,V()},St=()=>{_.live===`Lost`&&Pe()&&(B(null),V())},Ct=e=>{if(p.reducedMotion?.()===!0)return ne;let t=e.navigateAfterMs;if(typeof t==`number`&&Number.isFinite(t)&&t>=0)return t;let n=_.profile?.experience.pacing.handoffPauseMs;return typeof n==`number`&&Number.isFinite(n)?n:re},wt=()=>{R(),_.handoffPause&&H({handoffPause:!1})};return{client:o,getState:()=>_,subscribe:e=>(g.add(e),x||Xe(),()=>{g.delete(e)}),load:Xe,submit:Ze,chooseQuickReply:Qe,answerInput:$e,confirmAction:et,rejectAction:tt,stop:nt,retry:rt,regenerate:it,startEdit:at,cancelEdit:ot,attach:st,removeAttachment:ct,openConversation:lt,resumeLast:ut,newConversation:dt,rate:pt,open:mt,close:ht,setMuted:gt,skipField:_t,cancelLead:vt,editLeadField:yt,requestHandoff:$,notifyTyping:bt,setLiveActive:xt,resumeLive:St,beginHandoff:(e,t)=>{_.handoffPause||(H({handoffPause:!0}),p.onEvent?.(`chatHandoff`,{destination:e.id}),A=u.setTimeout(()=>{A=null;try{t()}catch(e){wt(),K(e)}},Ct(e)))},endHandoffPause:wt,consumeDraft:()=>{_.draft!==null&&H({draft:null})},loadAttachmentUrl:t=>{let n=N.get(t);if(n)return n;let r=(async()=>{let n=u.Blob,r=u.URL;if(!n||typeof r?.createObjectURL!=`function`)throw new e(`unsupported`,m.errorGeneric);let i=await o.getAttachment(t);if(Te)throw new e(`aborted`,m.errorGeneric);let a=r.createObjectURL(new n([i]));return Ee.add(a),a})();return N.set(t,r),r.catch(()=>{N.get(t)===r&&N.delete(t)}),r},reset:()=>{q(),G(),Ie(),x=null,P=Promise.resolve(),F=0,Ce.clear(),Se=null,z(),L(),R(),H(ve(h))},dispose:()=>{g.clear(),Te=!0,v+=1;let e=y;y=null,e?.abort(),j?.abort(),j=null,R(),L(),B(null),q(),G();for(let e of Ee)u.URL?.revokeObjectURL?.(e);Ee.clear(),N.clear(),H({attachments:[],editing:null,agentTyping:null})}}},ye=e=>{let t=-1;for(let n=e.length-1;n>=0;--n)if(e[n].parts.some(e=>e.kind===`Handoff`)){t=n;break}let n=/* @__PURE__ */ new Set;for(let r=0;r<t;r+=1)n.add(e[r].id);return n},h=(e,t)=>({get features(){return e.getState().features},labels:t.labels,get isLast(){let n=e.getState().messages;return n[n.length-1]?.id===t.messageId},get busy(){let t=e.getState();return t.streaming||t.thinking},get handoffPause(){return e.getState().handoffPause},get handoffSettled(){return ye(e.getState().messages).has(t.messageId)},chooseQuickReply(t){e.chooseQuickReply(t)},skipInput(t){e.skipField(t)},cancelLead(){e.cancelLead()},answerInput:(t,n,r)=>e.answerInput(t,n,r),uploadInputFile:async(t,n)=>(await e.client.uploadAttachment(t,n?{onProgress:n}:{})).publicId,sendOtp:(t,n)=>e.client.sendOtp(t,n),confirmAction:t=>e.confirmAction(t),rejectAction:(t,n)=>e.rejectAction(t,n),requestHandoff:t=>e.requestHandoff(t),beginHandoff:(t,n)=>e.beginHandoff(t,n),readAttachment:t=>e.client.getAttachment(t),loadAttachmentUrl:t=>e.loadAttachmentUrl(t),...t.openAttachment?{openAttachment:t.openAttachment}:{},...t.openRecord?{openRecord:t.openRecord}:{},...t.openTicket?{openTicket:t.openTicket}:{},...t.attachmentUrl?{attachmentUrl:t.attachmentUrl}:{},...t.handoffHosts?{handoffHosts:t.handoffHosts}:{},...t.openCitation?{openCitation:t.openCitation}:{},...t.isCitation?{isCitation:t.isCitation}:{},...t.openTarget?{openTarget:t.openTarget}:{},...t.onNavigate?{onNavigate:t.onNavigate}:{}});export{m as createChatSession,h as createTurnApi,ye as handoffSettledIds};
@@ -1,4 +1,4 @@
1
- import{formatFigure as e,toFigureText as t}from"./figures.js";import{formatChatDate as n,formatChatValue as r,formatFileSize as i,messagePlainText as a}from"./format.js";var o=e=>e;function s(e){return e!=null&&e.trim()!==``}function c(e){return{kind:`paragraph`,text:e}}function l(e){return e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e!==``).map(c)}function u(e){return e.url!==null&&(e.url.startsWith(`http://`)||e.url.startsWith(`https://`))?`${e.title} (${e.url})`:e.title}function d(e,t){return t===null?e:`${e??``} (${t})`.trim()}function f(e){let t=[],n=/* @__PURE__ */ new Set,i=e.map(e=>{let r=/* @__PURE__ */ new Map;for(let i of e.points)r.set(i.label,i.value),n.has(i.label)||(n.add(i.label),t.push(i.label));return r});return t.map(e=>[e,...i.map(t=>{let n=t.get(e);return n===void 0?``:r(n,`Decimal`,null)})])}function p(e){return e.map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``)}function m(t){return Math.abs(t)<.001&&t!==0?p(e(t)):r(t,`Decimal`,null)}function h(e,t){switch(e.kind){case`Text`:case`Notice`:return l(a([e]));case`Sources`:return e.sources.length===0?[]:[c(t.sources),{kind:`list`,ordered:!0,items:e.sources.map(u)}];case`QuickReplies`:case`Handoff`:return[];case`InputRequest`:return e.state!==`Answered`||!s(e.answeredSummary)?[]:[c(e.title===null?e.answeredSummary:`${e.title}: ${e.answeredSummary}`)];case`Action`:{let t=[c(e.title)];return e.lines.length>0&&t.push({kind:`list`,ordered:!1,items:[...e.lines]}),t}case`Table`:return[{kind:`table`,title:e.title,head:e.columns.map(e=>e.label),rows:e.rows.map(t=>e.columns.map((n,i)=>r(t[i],n.type,e.currency)))}];case`Chart`:return e.series.length===0?[]:[{kind:`table`,title:d(e.title,e.unit),head:[``,...e.series.map(e=>e.name)],rows:f(e.series)}];case`Figures`:return e.figures.length===0?[]:[{kind:`table`,title:null,head:[],rows:e.figures.map(e=>[e.label,m(e.value)+(s(e.unit)?` ${e.unit}`:``)])}];case`RecordCard`:{let t=[c(e.subtitle===null?e.title:`${e.title} ${e.subtitle}`)];return e.fields.length>0&&t.push({kind:`table`,title:null,head:[],rows:e.fields.map(e=>[e.label,r(e.value,e.type,null)])}),t}case`Image`:return s(e.alt)?[c(e.alt)]:[];case`File`:return[c(`${e.fileName} (${i(e.length)})`)];case`Ticket`:return[c(`${e.number} ${e.subject}`)];case`VoiceClip`:return s(e.transcript)?[c(e.transcript)]:[];default:return[]}}function g(e,t){switch(e.kind){case`paragraph`:return{kind:`paragraph`,text:t(e.text)};case`list`:return{kind:`list`,ordered:e.ordered,items:e.items.map(e=>t(e))};case`table`:return{kind:`table`,title:e.title===null?null:t(e.title),head:e.head.map(e=>t(e)),rows:e.rows.map(e=>e.map(e=>t(e)))}}}function _(e,t){switch(e.kind){case`Visitor`:case`Customer`:return t.you;case`Agent`:return s(e.displayName)?e.displayName:t.agent;case`Assistant`:case`Script`:return t.assistant;case`System`:throw Error(`A System message has no speaker: buildTranscript skips it.`)}}function v(e,r){let i=r.figureText?t:o,a=[],c=null;for(let t of e){if(t.streaming||t.author.kind===`System`)continue;let e=t.parts.flatMap(e=>h(e,r.labels)).map(e=>g(e,i));e.length!==0&&(a.push({speaker:_(t.author,r.labels),blocks:e}),c===null&&(c=n(t.createdDateTimeUtc)))}return{title:s(r.title)?r.title:r.labels.untitled,dateText:c,entries:a}}function y(e){switch(e.kind){case`paragraph`:return[e.text];case`list`:return e.items.map((t,n)=>e.ordered?`${n+1}. ${t}`:`- ${t}`);case`table`:{let t=[];e.title!==null&&t.push(e.title),e.head.length>0&&t.push(e.head.join(` | `));for(let n of e.rows)t.push(n.join(` | `));return t}}}function b(e,t){let n=[];t.heading&&n.push([e.title,...e.dateText===null?[]:[e.dateText]].join(`
1
+ import{formatFigure as e,toFigureText as t}from"./figures.js";import{formatChatDate as n,formatChatValue as r,formatFileSize as i,messagePlainText as a}from"./format.js";var o=e=>e;function s(e){return e!=null&&e.trim()!==``}function c(e){return{kind:`paragraph`,text:e}}function l(e){return e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e!==``).map(c)}function u(e){return e.url!==null&&(e.url.startsWith(`http://`)||e.url.startsWith(`https://`))?`${e.title} (${e.url})`:e.title}function d(e,t){return t===null?e:`${e??``} (${t})`.trim()}function f(e){let t=[],n=/* @__PURE__ */ new Set,i=e.map(e=>{let r=/* @__PURE__ */ new Map;for(let i of e.points)r.set(i.label,i.value),n.has(i.label)||(n.add(i.label),t.push(i.label));return r});return t.map(e=>[e,...i.map(t=>{let n=t.get(e);return n===void 0?``:r(n,`Decimal`,null)})])}function p(e){return e.map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``)}function m(t){return Math.abs(t)<.001&&t!==0?p(e(t)):r(t,`Decimal`,null)}function h(e,t){switch(e.kind){case`Text`:case`Notice`:return l(a([e]));case`Sources`:return e.sources.length===0?[]:[c(t.sources),{kind:`list`,ordered:!0,items:e.sources.map(u)}];case`QuickReplies`:case`Handoff`:return[];case`InputRequest`:return e.state!==`Answered`||!s(e.answeredSummary)?[]:[c(e.title===null?e.answeredSummary:`${e.title}: ${e.answeredSummary}`)];case`Action`:{let t=[c(e.title)];return e.lines.length>0&&t.push({kind:`list`,ordered:!1,items:[...e.lines]}),t}case`Table`:return[{kind:`table`,title:e.title,head:e.columns.map(e=>e.label),rows:e.rows.map(t=>e.columns.map((n,i)=>r(t[i],n.type,e.currency)))}];case`Chart`:return e.series.length===0?[]:[{kind:`table`,title:d(e.title,e.unit),head:[``,...e.series.map(e=>e.name)],rows:f(e.series)}];case`Figures`:return e.figures.length===0?[]:[{kind:`table`,title:null,head:[],rows:e.figures.map(e=>[e.label,m(e.value)+(s(e.unit)?` ${e.unit}`:``)])}];case`RecordCard`:{let t=[c(e.subtitle===null?e.title:`${e.title} ${e.subtitle}`)];return e.fields.length>0&&t.push({kind:`table`,title:null,head:[],rows:e.fields.map(e=>[e.label,r(e.value,e.type,null)])}),t}case`Image`:return s(e.alt)?[c(e.alt)]:[];case`File`:return[c(`${e.fileName} (${i(e.length)})`)];case`Ticket`:return[c(`${e.number} ${e.subject}`)];case`VoiceClip`:return s(e.transcript)?[c(e.transcript)]:[];default:return[]}}function g(e,t){switch(e.kind){case`paragraph`:return{kind:`paragraph`,text:t(e.text)};case`list`:return{kind:`list`,ordered:e.ordered,items:e.items.map(e=>t(e))};case`table`:return{kind:`table`,title:e.title===null?null:t(e.title),head:e.head.map(e=>t(e)),rows:e.rows.map(e=>e.map(e=>t(e)))}}}function _(e,t,n){switch(e.kind){case`Visitor`:case`Customer`:return t.you;case`Agent`:return s(e.displayName)?e.displayName:t.agent;case`Assistant`:case`Script`:return s(e.displayName)?e.displayName:s(n)?n:t.assistant;case`System`:throw Error(`A System message has no speaker: buildTranscript skips it.`)}}function v(e,r){let i=r.figureText?t:o,a=[],c=null;for(let t of e){if(t.streaming||t.author.kind===`System`)continue;let e=t.parts.flatMap(e=>h(e,r.labels)).map(e=>g(e,i));e.length!==0&&(a.push({speaker:_(t.author,r.labels,r.assistantName),blocks:e}),c===null&&(c=n(t.createdDateTimeUtc)))}return{title:s(r.title)?r.title:r.labels.untitled,dateText:c,entries:a}}function y(e){switch(e.kind){case`paragraph`:return[e.text];case`list`:return e.items.map((t,n)=>e.ordered?`${n+1}. ${t}`:`- ${t}`);case`table`:{let t=[];e.title!==null&&t.push(e.title),e.head.length>0&&t.push(e.head.join(` | `));for(let n of e.rows)t.push(n.join(` | `));return t}}}function b(e,t){let n=[];t.heading&&n.push([e.title,...e.dateText===null?[]:[e.dateText]].join(`
2
2
  `));for(let r of e.entries){let e=t.speakers?[`${r.speaker}:`]:[];for(let t of r.blocks)e.push(...y(t));n.push(e.join(`
3
3
  `))}return n.join(`
4
4
 
@@ -134,6 +134,7 @@ export interface ChatInputField {
134
134
  verify: ChatFieldVerification;
135
135
  accept: string[] | null;
136
136
  secret: boolean;
137
+ validator: string | null;
137
138
  }
138
139
  export interface ChatTableColumn {
139
140
  key: string;
@@ -354,7 +355,7 @@ export interface ChatStartSettings {
354
355
  export interface ChatAssistantCopy {
355
356
  name: string;
356
357
  tagline: string | null;
357
- intro: string;
358
+ intro: string | null;
358
359
  }
359
360
  export interface ChatFooterCopy {
360
361
  privacyText: string | null;
@@ -1,6 +1,8 @@
1
1
  import type { ChatColumnType, ChatPart } from "./contract";
2
+ import type { ChatLabels } from "./labels";
2
3
  export declare const formatFileSize: (bytes: number) => string;
3
4
  export declare const formatChatDate: (iso: string) => string;
5
+ export declare const formatChatDay: (isoUtc: string, labels: ChatLabels, now?: Date) => string;
4
6
  export declare const messagePlainText: (parts: readonly ChatPart[]) => string;
5
7
  export declare const formatChatDateTime: (iso: string) => string;
6
8
  export declare const formatChatValue: (value: string | number | null, type: ChatColumnType, currency: string | null) => string;
@@ -116,6 +116,8 @@ export interface ChatLabels {
116
116
  openSidePanel: string;
117
117
  earlierChat: string;
118
118
  justNow: string;
119
+ today: string;
120
+ yesterday: string;
119
121
  dailyLimitRefresh: (time: string) => string;
120
122
  talkToPerson: string;
121
123
  handoffRequested: string;
@@ -6,8 +6,8 @@ export type ChatPanelMotion = "Spring" | "Gentle" | "None";
6
6
  export type ChatPhoneMode = "FullScreen" | "Sheet";
7
7
  export type ChatSendReveal = "OnText" | "Always";
8
8
  export type ChatMotion = "On" | "Reduced";
9
- /** What the launcher button shows: the chat icon, or the assistant's avatar picture. */
10
- export type ChatLauncherMark = "Icon" | "Avatar";
9
+ /** What the launcher button shows: the chat icon, the assistant's avatar picture, or a living gradient orb. */
10
+ export type ChatLauncherMark = "Icon" | "Avatar" | "Orb";
11
11
  /** Fixed keeps the panel at its height; Content grows it with the conversation up to that height. */
12
12
  export type ChatPanelHeight = "Fixed" | "Content";
13
13
  export interface ChatLook {
@@ -51,6 +51,8 @@ export interface ChatLook {
51
51
  motion: ChatMotion;
52
52
  /** The assistant's avatar picture (an image URL) for the header, the replies and an Avatar launcher mark; null draws the gradient. */
53
53
  avatar: string | null;
54
+ /** Expressive motion: the ring that turns around the thinking mark through a reply and the launcher shrinking as the panel opens. Off by default; reduced motion switches it off. */
55
+ expressive: boolean;
54
56
  }
55
57
  export declare const defaultChatLook: ChatLook;
56
58
  /** A partial look, nested one level, as a surface accepts it. */
@@ -73,6 +73,7 @@ export interface ChatSessionState {
73
73
  } | null;
74
74
  live: ChatLiveStatus;
75
75
  handoffPending: boolean;
76
+ handoffContactRequestId: string | null;
76
77
  handoffPause: boolean;
77
78
  openTickets: ChatOpenTicket[];
78
79
  draft: string | null;
@@ -26,6 +26,7 @@ export interface ChatTranscriptOptions {
26
26
  labels: Pick<ChatLabels, "you" | "assistant" | "agent" | "untitled" | "sources">;
27
27
  title: string | null;
28
28
  figureText: boolean;
29
+ assistantName?: string;
29
30
  }
30
31
  export interface ChatTranscriptTextOptions {
31
32
  heading: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/chat-core",
3
- "version": "0.135.1",
3
+ "version": "0.137.0",
4
4
  "description": "The headless Webority Chat engine: the client over the chat routes, the session state machine over message parts, the stream reader, profile resolution with screen narrowing, the default English labels and a fixture client for sandboxes and tests. No DOM and no UI.",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "type": "module",
@@ -26,17 +26,17 @@
26
26
  },
27
27
  "sideEffects": false,
28
28
  "peerDependencies": {
29
- "@webority/markdown-core": "^0.131.0"
29
+ "@webority/markdown-core": "^0.134.0"
30
30
  },
31
31
  "devDependencies": {
32
- "@webority/markdown-core": "0.131.0",
32
+ "@webority/markdown-core": "0.134.0",
33
33
  "typescript": "^7.0.2",
34
34
  "vite": "^8.0.12",
35
35
  "vitest": "5.0.1"
36
36
  },
37
37
  "scripts": {
38
38
  "build": "vite build && tsc -p tsconfig.json",
39
- "test": "vitest run",
39
+ "test": "tsc -p tsconfig.test.json && vitest run",
40
40
  "test:watch": "vitest"
41
41
  }
42
42
  }