@webority/chat-core 0.133.0 → 0.134.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/audioType.js +1 -0
- package/dist/client.js +2 -2
- package/dist/conversationList.js +1 -1
- package/dist/dictation.js +1 -1
- package/dist/explain.js +1 -1
- package/dist/format.js +1 -1
- package/dist/index.js +1 -1
- package/dist/labels.js +1 -1
- package/dist/look.js +1 -1
- package/dist/session.js +2 -2
- package/dist/starters.js +1 -1
- package/dist/types/audioType.d.ts +1 -0
- package/dist/types/client.d.ts +2 -2
- package/dist/types/contract.d.ts +1 -1
- package/dist/types/dictation.d.ts +2 -2
- package/dist/types/explain.d.ts +1 -1
- package/dist/types/fixtureClient.d.ts +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/labels.d.ts +7 -1
- package/dist/types/session.d.ts +9 -4
- package/dist/types/speech.d.ts +2 -0
- package/package.json +3 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){let t=new Uint8Array(e),n=(e,n)=>String.fromCharCode(...t.slice(e,n));return n(0,4)===`OggS`?`audio/ogg`:t[0]===26&&t[1]===69&&t[2]===223&&t[3]===163?`audio/webm`:n(4,8)===`ftyp`?`audio/mp4`:n(0,4)===`RIFF`?`audio/wav`:n(0,3)===`ID3`||t[0]===255&&(t[1]&224)==224?`audio/mpeg`:`application/octet-stream`}export{e as sniffAudioType};
|
package/dist/client.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import"./contract.js";import{DEFAULT_CHAT_LABELS as e}from"./labels.js";import{createStreamReader as t}from"./stream.js";var n=class extends Error{code;status;
|
|
2
|
-
`);t=i.pop()??``;for(let t of i){let r=t.endsWith(`\r`)?t.slice(0,-1):t;if(!r.startsWith(`id:`))continue;let i=r.slice(3).replace(/^ /,``);if(!/^\d+$/.test(i))continue;let a=Number(i);(n===null||a>n)&&(n=a,e?.(a))}}},g=(r,{base:i})=>{if(typeof i!=`string`||i.trim()===``)throw TypeError(`createChatClient needs a base path, e.g. { base: "/api/assistant" }.`);let a=i.replace(/\/+$/,``),u={"Chat-Contract":`4`},g=e=>`${a}/conversations/${encodeURIComponent(e)}`,_=e=>`${a}/attachments/${encodeURIComponent(e)}`,v=e=>`${a}/actions/${encodeURIComponent(e)}`,y=/* @__PURE__ */ new Map,b=async t=>{let i=t===void 0?``:`?screen=${encodeURIComponent(t)}`;try{let t=await s(()=>r.get(`${a}/profile${i}`,{headers:u}));if(typeof t?.contractVersion!=`number`||t.contractVersion<4)throw new n(`assistant_outdated`,e.assistantOutdated);return t}catch(t){throw t instanceof n&&t.status===404?new n(`assistant_outdated`,e.assistantOutdated,404):t}},x=e=>{let t=e??``,n=y.get(t);return n||(n=b(e).catch(e=>{throw y.delete(t),e}),y.set(t,n)),n},S=async(i,a,s)=>{let l=t(s.onEvent),u=0,d=e=>{typeof e!=`string`||e.length<=u||(l.push(e.slice(u)),u=e.length)},f;try{f=await r.post(i,a,{responseType:`text`,headers:s.headers,signal:s.signal,onDownloadProgress:e=>d(c(e))})}catch(e){throw o(e,s.signal)}d(f.data),l.end();let p=l.failure;if(p)throw new n(p.code||`unknown`,p.message||e.errorGeneric);let m=l.last;if(!m)throw new n(`invalid-response`,e.errorGeneric,f.status);return m};return{getProfile:x,send:(e,t={})=>{let n=p({conversationId:e.conversationId,text:e.text,quickReplyId:e.quickReplyId,attachmentIds:e.attachmentIds&&e.attachmentIds.length>0?e.attachmentIds:void 0,replacesMessageId:e.replacesMessageId,pageContext:e.pageContext,captchaToken:e.captchaToken});return S(`${a}/messages`,n,{signal:t.signal,onEvent:t.onEvent,headers:{...u,Accept:`text/event-stream`,"Idempotency-Key":f()}})},answerInput:(e,t,n={})=>{let r=p({values:t.values,captchaToken:t.captchaToken,attribution:t.attribution});return S(`${a}/inputs/${encodeURIComponent(e)}`,r,{signal:n.signal,onEvent:n.onEvent,headers:{...u,Accept:`text/event-stream`,"Idempotency-Key":f()}})},confirmAction:e=>s(()=>r.post(`${v(e)}/confirm`,{},{headers:u})),rejectAction:(e,t)=>s(()=>r.post(`${v(e)}/reject`,t===void 0?{}:{reason:t},{headers:u})),listConversations:(e={})=>{let t=[];e.page!==void 0&&t.push(`page=${encodeURIComponent(String(e.page))}`),e.pageSize!==void 0&&t.push(`pageSize=${encodeURIComponent(String(e.pageSize))}`);let n=t.join(`&`),i=n?`${a}/conversations?${n}`:`${a}/conversations`;return s(()=>r.get(i,{headers:u}))},getConversation:(e,t)=>{let n=t===void 0?g(e):`${g(e)}?afterSequence=${t}`;return s(()=>r.get(n,{headers:u}))},renameConversation:async(e,t)=>{await s(()=>r.put(`${g(e)}/title`,{title:t},{headers:u}))},deleteConversation:async e=>{await s(()=>r.delete(g(e),{headers:u}))},rateMessage:async(e,t)=>{let n=typeof t.note==`string`?t.note.trim():``;await s(()=>r.put(`${a}/messages/${encodeURIComponent(e)}/rating`,{rating:t.rating,note:n||null},{headers:u}))},uploadAttachment:(e,t={})=>{let n=l();return d(n,e),s(()=>r.post(`${a}/attachments`,n,{headers:{...u,"Content-Type":`multipart/form-data`},timeout:3e5,signal:t.signal,onUploadProgress:({loaded:e,total:n})=>{t.onProgress&&n&&t.onProgress((e??0)/n)}}))},deleteAttachment:async e=>{await s(()=>r.delete(_(e),{headers:u}))},getAttachment:e=>s(()=>r.get(_(e),{headers:u,responseType:`arraybuffer`})),sendOtp:async(e,t)=>{await s(()=>r.post(`${a}/inputs/${encodeURIComponent(e)}/otp`,t,{headers:u}))},requestHandoff:(e,t={})=>{let n=typeof e.reason==`string`&&e.reason.trim()!==``?e.reason:void 0;return S(`${a}/handoff`,p({conversationId:e.conversationId,reason:n}),{signal:t.signal,onEvent:t.onEvent,headers:{...u,Accept:`text/event-stream`,"Idempotency-Key":f()}})},watchConversation:async(i,a)=>{let s=new m.AbortController,l=()=>s.abort();a.signal?.aborted&&s.abort(),a.signal?.addEventListener(`abort`,l);let d=!1,f=null,p=()=>{f!==null&&m.clearTimeout(f),f=m.setTimeout(()=>{d=!0,s.abort()},a.stallTimeoutMs??9e4)},_=h(a.onCursor),v=t(a.onEvent),y=0,b=e=>{if(typeof e!=`string`||e.length<=y)return;let t=e.slice(y);y=e.length,_(t),v.push(t)},x={...u,Accept:`text/event-stream`};typeof a.afterSequence==`number`&&Number.isFinite(a.afterSequence)&&(x[`Last-Event-ID`]=String(a.afterSequence)),p();try{b((await r.get(`${g(i)}/events`,{headers:x,responseType:`text`,timeout:0,signal:s.signal,onDownloadProgress:e=>{let t=c(e);t!==void 0&&(p(),b(t))}})).data),_(`
|
|
1
|
+
import"./contract.js";import{DEFAULT_CHAT_LABELS as e}from"./labels.js";import{createStreamReader as t}from"./stream.js";var n=class extends Error{code;status;resetsDateTimeUtc;errors;constructor(e,t,n,r=null,i=null){super(t),this.name=`ChatApiError`,this.code=e,this.status=n,this.resetsDateTimeUtc=r,this.errors=i}},r=e=>{if(typeof e==`string`)try{return JSON.parse(e)}catch{return null}return e??null},i=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return null;let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&typeof r[0]==`string`&&(t[n]=r[0]);return Object.keys(t).length>0?t:null},a=(e,t)=>!!t?.aborted||e?.code===`ERR_CANCELED`||e?.name===`CanceledError`||e?.name===`AbortError`,o=(t,o)=>{if(t instanceof n)return t;let s=t;if(a(s,o))return new n(`aborted`,`The request was cancelled.`);let c=s?.response;if(!c)return new n(`network`,e.errorGeneric);let l=r(c.data),u=typeof l?.code==`string`&&l.code?l.code:`unknown`,d=typeof l?.detail==`string`&&l.detail?l.detail:e.errorGeneric,f=typeof l?.resetsDateTimeUtc==`string`?l.resetsDateTimeUtc:null;return new n(u,d,typeof c.status==`number`?c.status:void 0,f,i(l?.errors))},s=async e=>{try{return(await e()).data}catch(e){throw o(e)}},c=e=>{let t=e?.event?.target;if(t&&typeof t.responseText==`string`&&!(typeof t.status==`number`&&(t.status<200||t.status>=300)))return t.responseText},l=()=>{let e=globalThis.FormData;if(!e)throw Error(`FormData is not available.`);return new e},u=e=>typeof e.uri==`string`,d=(e,t)=>{if(u(t)){e.append(`file`,t);return}let n=t.name;if(typeof n!=`string`||n===``)throw Error(`The file needs a name.`);e.append(`file`,t,n)},f=()=>{let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`},p=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t},m=globalThis,h=e=>{let t=``,n=null;return r=>{let i=(t+r).split(`
|
|
2
|
+
`);t=i.pop()??``;for(let t of i){let r=t.endsWith(`\r`)?t.slice(0,-1):t;if(!r.startsWith(`id:`))continue;let i=r.slice(3).replace(/^ /,``);if(!/^\d+$/.test(i))continue;let a=Number(i);(n===null||a>n)&&(n=a,e?.(a))}}},g=(r,{base:i})=>{if(typeof i!=`string`||i.trim()===``)throw TypeError(`createChatClient needs a base path, e.g. { base: "/api/assistant" }.`);let a=i.replace(/\/+$/,``),u={"Chat-Contract":`4`},g=e=>`${a}/conversations/${encodeURIComponent(e)}`,_=e=>`${a}/attachments/${encodeURIComponent(e)}`,v=e=>`${a}/actions/${encodeURIComponent(e)}`,y=/* @__PURE__ */ new Map,b=async t=>{let i=t===void 0?``:`?screen=${encodeURIComponent(t)}`;try{let t=await s(()=>r.get(`${a}/profile${i}`,{headers:u}));if(typeof t?.contractVersion!=`number`||t.contractVersion<4)throw new n(`assistant_outdated`,e.assistantOutdated);return t}catch(t){throw t instanceof n&&t.status===404?new n(`assistant_outdated`,e.assistantOutdated,404):t}},x=e=>{let t=e??``,n=y.get(t);return n||(n=b(e).catch(e=>{throw y.delete(t),e}),y.set(t,n)),n},S=async(i,a,s)=>{let l=t(s.onEvent),u=0,d=e=>{typeof e!=`string`||e.length<=u||(l.push(e.slice(u)),u=e.length)},f;try{f=await r.post(i,a,{responseType:`text`,headers:s.headers,signal:s.signal,onDownloadProgress:e=>d(c(e))})}catch(e){throw o(e,s.signal)}d(f.data),l.end();let p=l.failure;if(p)throw new n(p.code||`unknown`,p.message||e.errorGeneric);let m=l.last;if(!m)throw new n(`invalid-response`,e.errorGeneric,f.status);return m};return{getProfile:x,send:(e,t={})=>{let n=p({conversationId:e.conversationId,text:e.text,quickReplyId:e.quickReplyId,attachmentIds:e.attachmentIds&&e.attachmentIds.length>0?e.attachmentIds:void 0,replacesMessageId:e.replacesMessageId,pageContext:e.pageContext,captchaToken:e.captchaToken});return S(`${a}/messages`,n,{signal:t.signal,onEvent:t.onEvent,headers:{...u,Accept:`text/event-stream`,"Idempotency-Key":f()}})},answerInput:(e,t,n={})=>{let r=p({values:t.values,captchaToken:t.captchaToken,codes:t.codes,attribution:t.attribution});return S(`${a}/inputs/${encodeURIComponent(e)}`,r,{signal:n.signal,onEvent:n.onEvent,headers:{...u,Accept:`text/event-stream`,"Idempotency-Key":f()}})},confirmAction:e=>s(()=>r.post(`${v(e)}/confirm`,{},{headers:u})),rejectAction:(e,t)=>s(()=>r.post(`${v(e)}/reject`,t===void 0?{}:{reason:t},{headers:u})),listConversations:(e={})=>{let t=[];e.page!==void 0&&t.push(`page=${encodeURIComponent(String(e.page))}`),e.pageSize!==void 0&&t.push(`pageSize=${encodeURIComponent(String(e.pageSize))}`);let n=t.join(`&`),i=n?`${a}/conversations?${n}`:`${a}/conversations`;return s(()=>r.get(i,{headers:u}))},getConversation:(e,t)=>{let n=t===void 0?g(e):`${g(e)}?afterSequence=${t}`;return s(()=>r.get(n,{headers:u}))},renameConversation:async(e,t)=>{await s(()=>r.put(`${g(e)}/title`,{title:t},{headers:u}))},deleteConversation:async e=>{await s(()=>r.delete(g(e),{headers:u}))},rateMessage:async(e,t)=>{let n=typeof t.note==`string`?t.note.trim():``;await s(()=>r.put(`${a}/messages/${encodeURIComponent(e)}/rating`,{rating:t.rating,note:n||null},{headers:u}))},uploadAttachment:(e,t={})=>{let n=l();return d(n,e),s(()=>r.post(`${a}/attachments`,n,{headers:{...u,"Content-Type":`multipart/form-data`},timeout:3e5,signal:t.signal,onUploadProgress:({loaded:e,total:n})=>{t.onProgress&&n&&t.onProgress((e??0)/n)}}))},deleteAttachment:async e=>{await s(()=>r.delete(_(e),{headers:u}))},getAttachment:e=>s(()=>r.get(_(e),{headers:u,responseType:`arraybuffer`})),sendOtp:async(e,t)=>{await s(()=>r.post(`${a}/inputs/${encodeURIComponent(e)}/otp`,t,{headers:u}))},requestHandoff:(e,t={})=>{let n=typeof e.reason==`string`&&e.reason.trim()!==``?e.reason:void 0;return S(`${a}/handoff`,p({conversationId:e.conversationId,reason:n}),{signal:t.signal,onEvent:t.onEvent,headers:{...u,Accept:`text/event-stream`,"Idempotency-Key":f()}})},watchConversation:async(i,a)=>{let s=new m.AbortController,l=()=>s.abort();a.signal?.aborted&&s.abort(),a.signal?.addEventListener(`abort`,l);let d=!1,f=null,p=()=>{f!==null&&m.clearTimeout(f),f=m.setTimeout(()=>{d=!0,s.abort()},a.stallTimeoutMs??9e4)},_=h(a.onCursor),v=t(a.onEvent),y=0,b=e=>{if(typeof e!=`string`||e.length<=y)return;let t=e.slice(y);y=e.length,_(t),v.push(t)},x={...u,Accept:`text/event-stream`};typeof a.afterSequence==`number`&&Number.isFinite(a.afterSequence)&&(x[`Last-Event-ID`]=String(a.afterSequence)),p();try{b((await r.get(`${g(i)}/events`,{headers:x,responseType:`text`,timeout:0,signal:s.signal,onDownloadProgress:e=>{let t=c(e);t!==void 0&&(p(),b(t))}})).data),_(`
|
|
3
3
|
`),v.end();let t=v.failure;if(t)throw new n(t.code||`unknown`,t.message||e.errorGeneric)}catch(t){if(a.signal?.aborted)return;throw d?new n(`stalled`,e.errorGeneric):o(t,s.signal)}finally{f!==null&&m.clearTimeout(f),a.signal?.removeEventListener(`abort`,l)}},sendTyping:async e=>{await s(()=>r.post(`${g(e)}/typing`,void 0,{headers:u}))},listOpenTickets:async()=>{let t=await s(()=>r.get(`${a}/tickets/open`,{headers:u}));if(!Array.isArray(t))throw new n(`invalid-response`,e.errorGeneric);return t},getSpeechToken:()=>s(()=>r.post(`${a}/speech/token`,void 0,{headers:u}))}};export{n as ChatApiError,g as createChatClient,f as newIdempotencyKey};
|
package/dist/conversationList.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ChatApiError as e}from"./client.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";var n=20,r=n=>n instanceof e?{code:n.code,message:n.message||t.loadFailed,
|
|
1
|
+
import{ChatApiError as e}from"./client.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";var n=20,r=n=>n instanceof e?{code:n.code,message:n.message||t.loadFailed,resetsDateTimeUtc:n.resetsDateTimeUtc}:{code:`unknown`,message:t.loadFailed,resetsDateTimeUtc:null},i=e=>{let t=e.client,i=e.pageSize??n,a=/* @__PURE__ */ new Set,o={items:[],totalCount:null,loading:!1,error:null,hasMore:!1},s=0,c=!1,l=e=>{if(!c){o={...o,...e};for(let e of a)e()}};return{getState:()=>o,subscribe:e=>(a.add(e),()=>{a.delete(e)}),load:async()=>{s+=1;let e=s;l({loading:!0,error:null});try{let n=await t.listConversations({page:1,pageSize:i});if(c||e!==s)return;l({items:n.items,totalCount:n.totalCount,hasMore:n.page<n.totalPages,loading:!1})}catch(t){if(c||e!==s)return;l({loading:!1,error:r(t)})}},loadMore:async()=>{if(o.loading||!o.hasMore)return;let e=s,n=Math.floor(o.items.length/i)+1;l({loading:!0,error:null});try{let r=await t.listConversations({page:n,pageSize:i});if(c||e!==s)return;let a=new Set(o.items.map(e=>e.publicId)),u=r.items.filter(e=>!a.has(e.publicId));l({items:[...o.items,...u],totalCount:r.totalCount,hasMore:r.page<r.totalPages,loading:!1})}catch(t){if(c||e!==s)return;l({loading:!1,error:r(t)})}},rename:async(e,n)=>{let r=n.trim();if(await t.renameConversation(e,r),c)return;let i=r.replace(/\s+/g,` `);l({items:o.items.map(t=>t.publicId===e?{...t,title:i}:t)})},remove:async e=>{await t.deleteConversation(e),c||l({items:o.items.filter(t=>t.publicId!==e),totalCount:o.totalCount===null?null:o.totalCount-1})},dispose:()=>{c=!0,a.clear()}}};export{i as createConversationList};
|
package/dist/dictation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ChatSpeechError as e}from"./speech.js";var t=2e3,n=1e4,r=globalThis,i=e=>Object.freeze({status:e}),a={Idle:i(`Idle`),Listening:i(`Listening`),Blocked:i(`Blocked`),NotHeard:i(`NotHeard`),Failed:i(`Failed`)};function o(t){let{adapter:n}=t,i=t.silenceMs??2e3,o=t.noSpeechMs??1e4,s=/* @__PURE__ */ new Set,c=a.Idle,l=!1,u=0,d=!1,f=null,p=null,m=null,h=e=>{if(c.status!==e){c=a[e];for(let e of[...s])e()}},g=()=>{p!==null&&r.clearTimeout(p),m!==null&&r.clearTimeout(m),p=null,m=null},_=()=>{u+=1,g();let e=f;return f=null,e},v=e=>e===u,y=()=>{p!==null&&r.clearTimeout(p),p=r.setTimeout(()=>{p=null,S()},i)},b=()=>{m!==null&&r.clearTimeout(m),m=r.setTimeout(()=>{m=null,_()?.abort(),h(`NotHeard`)},o)},x=()=>{if(l||c.status===`Listening`)return;_()?.abort();let i=u;d=!1;let a=new r.AbortController;f=a,h(`Listening`),new Promise(e=>e(n.startDictation({language:t.language,signal:a.signal,onLevel:e=>{v(i)&&t.onLevel?.(e)},onStarted:()=>{v(i)&&!d&&n.streamsText&&b()},onText:(e,a)=>{v(i)&&(d=!0,m!==null&&(r.clearTimeout(m),m=null),n.streamsText&&y(),t.onText(e,a))}}))).then(()=>{if(!v(i))return;let e=d;_(),h(e?`Idle`:`NotHeard`)},t=>{v(i)&&(_(),h(t instanceof e&&t.code===`Blocked
|
|
1
|
+
import{ChatSpeechError as e}from"./speech.js";var t=2e3,n=1e4,r=globalThis,i=e=>Object.freeze({status:e}),a={Idle:i(`Idle`),Listening:i(`Listening`),Blocked:i(`Blocked`),NotHeard:i(`NotHeard`),Failed:i(`Failed`),NoMicrophone:i(`NoMicrophone`),Unavailable:i(`Unavailable`)};function o(t){let{adapter:n}=t,i=t.silenceMs??2e3,o=t.noSpeechMs??1e4,s=/* @__PURE__ */ new Set,c=a.Idle,l=!1,u=0,d=!1,f=null,p=null,m=null,h=e=>{if(c.status!==e){c=a[e];for(let e of[...s])e()}},g=()=>{p!==null&&r.clearTimeout(p),m!==null&&r.clearTimeout(m),p=null,m=null},_=()=>{u+=1,g();let e=f;return f=null,e},v=e=>e===u,y=()=>{p!==null&&r.clearTimeout(p),p=r.setTimeout(()=>{p=null,S()},i)},b=()=>{m!==null&&r.clearTimeout(m),m=r.setTimeout(()=>{m=null,_()?.abort(),h(`NotHeard`)},o)},x=()=>{if(l||c.status===`Listening`)return;_()?.abort();let i=u;d=!1;let a=new r.AbortController;f=a,h(`Listening`),new Promise(e=>e(n.startDictation({language:t.language,signal:a.signal,onLevel:e=>{v(i)&&t.onLevel?.(e)},onStarted:()=>{v(i)&&!d&&n.streamsText&&b()},onText:(e,a)=>{v(i)&&(d=!0,m!==null&&(r.clearTimeout(m),m=null),n.streamsText&&y(),t.onText(e,a))}}))).then(()=>{if(!v(i))return;let e=d;_(),h(e?`Idle`:`NotHeard`)},t=>{v(i)&&(_(),h(t instanceof e&&(t.code===`Blocked`||t.code===`NoMicrophone`||t.code===`Unavailable`)?t.code:`Failed`))})},S=()=>{l||(_()?.abort(),h(`Idle`))};return{getState:()=>c,subscribe(e){return l?()=>void 0:(s.add(e),()=>{s.delete(e)})},start:()=>{l||x()},stop:S,toggle(){l||(c.status===`Listening`?S():x())},dispose(){l||(_()?.abort(),h(`Idle`),l=!0,s.clear())}}}export{n as DICTATION_NO_SPEECH_MS,t as DICTATION_SILENCE_MS,o as createDictation};
|
package/dist/explain.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=globalThis,t=(e,t)=>typeof e==`number`&&Number.isFinite(e)&&e>=0?e:t,n=e=>typeof e==`object`&&e?e:{},r=e=>{let t=n(e),r=n(n(t.response).data);return{capacity:t.code===`assistant_at_capacity`||r.code===`assistant_at_capacity`,
|
|
1
|
+
var e=globalThis,t=(e,t)=>typeof e==`number`&&Number.isFinite(e)&&e>=0?e:t,n=e=>typeof e==`object`&&e?e:{},r=e=>{let t=n(e),r=n(n(t.response).data);return{capacity:t.code===`assistant_at_capacity`||r.code===`assistant_at_capacity`,resetsDateTimeUtc:typeof t.resetsDateTimeUtc==`string`?t.resetsDateTimeUtc:typeof r.resetsDateTimeUtc==`string`?r.resetsDateTimeUtc:null}};function i(n){let i=t(n.thinkingAfterMs,300),a=t(n.thinkingMinMs,500),o=t(n.slowAfterMs,8e3),s=t(n.timeoutMs,45e3),c=n.isEmpty??(e=>e==null),l=/* @__PURE__ */ new Set,u=e.navigator?.onLine===!1,d={state:u?`offline`:`idle`,answer:null,pillVisible:!1,resetsDateTimeUtc:null,offline:u},f=0,p=!1,m=null,h=null,g=null,_=null,v=null,y=0,b=e=>{if(Object.keys(e).some(t=>e[t]!==d[t])){d={...d,...e};for(let e of l)e()}},x=t=>(t!==null&&e.clearTimeout(t),null),S=()=>{f+=1,m?.abort(),m=null,h=x(h),g=x(g),_=x(_),v=x(v)},C=t=>{let n=f;if(m=null,g=x(g),_=x(_),d.pillVisible){let r=a-(Date.now()-y);if(r>0){v=e.setTimeout(()=>{v=null,n===f&&b({...t,pillVisible:!1})},r);return}}else h=x(h);b({...t,pillVisible:!1})},w=()=>{if(p||u)return;S();let t=f,a=new e.AbortController;m=a,b({state:`thinking`,answer:null,pillVisible:!1,resetsDateTimeUtc:null}),h=e.setTimeout(()=>{h=null,y=Date.now(),b({pillVisible:!0})},i),g=e.setTimeout(()=>{g=null,t===f&&d.state===`thinking`&&b({state:`slow`})},o),_=e.setTimeout(()=>{_=null,t===f&&(f+=1,a.abort(),C({state:`error`,answer:null,resetsDateTimeUtc:null}))},s),new Promise(e=>e(n.request(a.signal))).then(e=>{t===f&&C(c(e)?{state:`empty`,answer:null,resetsDateTimeUtc:null}:{state:`answered`,answer:e,resetsDateTimeUtc:null})},e=>{if(t!==f)return;let n=r(e);C(n.capacity?{state:`capacity`,answer:null,resetsDateTimeUtc:n.resetsDateTimeUtc}:{state:`error`,answer:null,resetsDateTimeUtc:null})})},T=()=>{p||(S(),b({state:u?`offline`:`idle`,answer:null,pillVisible:!1,resetsDateTimeUtc:null}))},E=()=>{u=!0,b(d.state===`idle`||d.state===`offline`?{offline:!0,state:`offline`}:{offline:!0})},D=()=>{u=!1,b(d.state===`offline`?{offline:!1,state:`idle`}:{offline:!1})};return typeof e.addEventListener==`function`&&(e.addEventListener(`offline`,E),e.addEventListener(`online`,D)),{getSnapshot:()=>d,subscribe:e=>p?()=>void 0:(l.add(e),()=>{l.delete(e)}),ask:w,reset:T,dispose:()=>{p||(T(),p=!0,typeof e.removeEventListener==`function`&&(e.removeEventListener(`offline`,E),e.removeEventListener(`online`,D)),l.clear())}}}export{i as createExplain};
|
package/dist/format.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
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(`
|
|
2
2
|
|
|
3
|
-
`).trim(),s=new Intl.DateTimeFormat(`en-
|
|
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};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ChatApiError as
|
|
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};
|
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:`
|
|
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};
|
package/dist/look.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e={launcher:{style:`Round`,entrance:`SlideUp`,idle:`
|
|
1
|
+
var e={launcher:{style:`Round`,entrance:`SlideUp`,idle:`None`,labelReveal:`Bubble`,compact:!1},panel:{motion:`Spring`,widthPx:420,maxHeightPx:650,bottomGapPx:80},phone:{maxWidthPx:768,mode:`FullScreen`,sheetHeightDvh:85,sheetMaxHeightPx:640},input:{ring:!0,sendReveal:`OnText`},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`};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}}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{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,
|
|
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(`
|
|
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,be=null,x=null,S=/* @__PURE__ */ new Map,xe=/* @__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,Se=!0,Ce=!1,we=/* @__PURE__ */ new Set,N=/* @__PURE__ */ new Map,P=Promise.resolve(),F=0,Te=()=>p.pathname?.()??l.location?.pathname??`/`,Ee=()=>p.reducedMotion?.()===!0||_.profile?.experience.motion===!1,I=()=>_.streaming||_.thinking,De=e=>{if(!e.profile)return{...e,greeting:null,starters:[]};let t=Te(),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}},L=()=>{O!==null&&(l.clearTimeout(O),O=null)},R=()=>{A!==null&&(l.clearTimeout(A),A=null)},Oe=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()},ke=e=>{for(let t of Oe(e))D.add(t.actionId)},Ae=()=>{for(let e of Oe(_.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}))},je=(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}))},Me=()=>!Ce&&Se&&_.features.HumanHandoff&&_.conversationId!==null&&(_.conversationState===`WaitingForAgent`||_.conversationState===`WithAgent`),V=()=>{if(!Me()){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=>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&&H({live:e})},onError:e=>q(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=fe(t.messages,t.conversationState)),_=De(t);for(let e of g)e();e.messages!==void 0&&Ae(),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},Ne=(e,t,n)=>{let r=`${e}#${t}`,i=S.get(r);S.set(r,{messageId:e,index:t,text:(i?.text??``)+n}),b||=_e(()=>{b=null,W()})},K=()=>{W(),v+=1,y?.abort(),y=null},q=e=>{if(p.onError)p.onError(e);else throw e},J=()=>{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(q)}w.clear(),C.clear()},Pe=e=>{let t=C.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},Fe=async(e,t)=>{let n=new l.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(q)},Ie=e=>{let t={...u(p.pageContext?.()),path:Te(),behaviour:p.behaviour?.()??null};return e&&(t.attribution=p.attribution?.()??null),t},Le=async()=>{let e=_.profile?.captcha;return!e||!p.getCaptchaToken||e.mode===`Off`&&!e.siteKey?null:p.getCaptchaToken(e.action)},Re=(e,t,n)=>{let r=oe(_.messages,f(e,!1));H(n?{messages:r,messagesLeftToday:t??_.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},ze=e=>{let n=_.profile?.experience.pacing;return!n||xe.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:a(t(e.parts),n,Ee())},Be=(e,t,n,r,i)=>{F+=1,H({pending:{typing:!0,authorKind:e.author.kind}}),P=P.then(()=>new Promise(e=>l.setTimeout(e,n))).then(()=>{--F,r()&&Re(e,t,i),F===0&&H({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=()=>{L(),_.agentTyping!==null&&H({agentTyping:null})},Ue=e=>{L(),O=l.setTimeout(()=>{O=null,H({agentTyping:null})},te),H({agentTyping:{displayName:e}})},Z=(e,t,n)=>{if(!n())return;let r=t===`turn`;if(e.name===`partDelta`)xe.add(e.data.messageId),Ne(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`&&He(),X(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(!X(t))break;H({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;H({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[...S.keys()])S.get(e)?.messageId===t&&S.delete(e);H({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&&H({steps:[..._.steps,t]});break}case`messageCompleted`:{let{message:t,messagesLeftToday:i}=e.data;t.author.kind===`Agent`&&He();let a=ze(t);a>0||F>0?Be(t,i,a,n,r):Re(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`&&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));H({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&&(w.clear(),C.clear()),H({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(W(),!a())return;let t=d(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 Q();let c=_.conversationId;s&&c!==null&&c!==be&&(be=c,p.onEvent?.(`chatStarted`,{conversationId:c}))},We=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)}))}),Ge=async()=>{try{H({openTickets:await o.listOpenTickets()})}catch{}},Ke=async()=>{let e;try{e=await o.getProfile(p.screen)}catch(e){H({profileError:d(e)});return}let t=s(e,p.narrow);if(H({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});H({lastConversation:e.items[0]??null})}catch{}p.conversationId&&await ot(p.conversationId)},qe=()=>(x||=Ke(),x),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`||I()||await $({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,attachments:[]},_.messages,!1)},Xe=async(t,n)=>{if(_.streaming)return{ok:!1,errors:{},message:m.errorGeneric};let r=v,i=new l.AbortController,a=()=>r===v&&!i.signal.aborted;y=i,je(t,n),H({streaming:!0,thinking:!0});try{let e=await Le();await o.answerInput(t,{values:n,captchaToken:e,attribution:p.attribution?.()??null},{signal:i.signal,onEvent:e=>Z(e,`turn`,a)})}catch(t){if(W(),H({thinking:!1,streaming:!1}),i.signal.aborted)return{ok:!1,errors:{},message:m.errorGeneric};if(t instanceof e&&t.code===`validation_failed`)return{ok:!1,errors:t.errors??{},message:t.message};if(t instanceof e&&t.code===`input_request_closed`)return await Q(),{ok:!1,errors:{},message:t.message};let n=d(t);return H({turnError:n}),{ok:!1,errors:{},message:n.message}}finally{y===i&&(y=null)}return await P,a()&&(W(),H({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})},Qe=async(e,t)=>{We(await o.rejectAction(e,t))},$e=()=>{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})},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(I())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(),H({editing:{messageId:e,text:ce(t.parts)},attachments:[]}))},rt=()=>{_.editing&&(J(),H({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}))}H({attachments:[..._.attachments,...i]}),await Promise.all(a.map(({key:e,file:t})=>Fe(e,t)))},at=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 ot(e){K();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=>f(e,!0));z(),ke(r),H({messages:r,conversationId:n.publicId,title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){if(t!==v)return;H({loadError:d(e)})}finally{t===v&&H({loading:!1})}}let st=async()=>{let e=_.lastConversation;e&&await ot(e.publicId)},ct=()=>{J(),K(),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&&Ge()},lt=(e,t,n)=>{H({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`),H(i),t||p.onEvent?.(`chatOpened`,{layout:p.layout??null,trigger:n})},ft=e=>{_.open&&(h?.set(`wchat:dismissed`,`1`),H({open:!1}),p.onEvent?.(`chatClosed`,{layout:p.layout??null,reason:e}))},pt=e=>{h?.set(`wchat:muted`,e?`1`:`0`),H({muted:e}),p.onEvent?.(`chatSoundToggled`,{muted:e})},mt=async e=>{I()||(p.onEvent?.(`chatLeadSkipped`,{requestId:e}),await $({wireText:null,displayText:m.skip,quickReplyId:`lead.skip`,replacesMessageId:null,attachments:[]},_.messages,!1))},ht=async()=>{I()||(p.onEvent?.(`chatLeadCancelled`,{}),await $({wireText:null,displayText:m.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,attachments:[]},_.messages,!1))},gt=async(e,t)=>{I()||_.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,H({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 H({messages:_.messages.filter(e=>!e.streaming),handoffPending:!1}),e}finally{j===i&&(j=null)}H({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();k!==null&&t-k<ne||(k=t,o.sendTyping(e).catch(()=>void 0))},yt=e=>{Se=e,V()},bt=()=>{_.live===`Lost`&&Me()&&(B(null),V())},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=()=>{R(),_.handoffPause&&H({handoffPause:!1})};return{client:o,getState:()=>_,subscribe:e=>(g.add(e),x||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||(H({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&&H({draft:null})},loadAttachmentUrl:t=>{let n=N.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 we.add(a),a})();return N.set(t,r),r.catch(()=>{N.get(t)===r&&N.delete(t)}),r},reset:()=>{J(),G(),K(),x=null,P=Promise.resolve(),F=0,xe.clear(),be=null,z(),L(),R(),H(ge(h))},dispose:()=>{g.clear(),Ce=!0,v+=1;let e=y;y=null,e?.abort(),j?.abort(),j=null,R(),L(),B(null),J(),G();for(let e of we)l.URL?.revokeObjectURL?.(e);we.clear(),N.clear(),H({attachments:[],editing:null,agentTyping:null})}}},_e=(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},chooseQuickReply(t){e.chooseQuickReply(t)},skipInput(t){e.skipField(t)},cancelLead(){e.cancelLead()},answerInput:(t,n)=>e.answerInput(t,n),uploadInputFile:async(t,n)=>(await e.client.uploadAttachment(t,n?{onProgress:n}:{})).publicId,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,_e as createTurnApi};
|
|
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};
|
package/dist/starters.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=e=>e.replace(/[-_]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/\s+/g,` `).trim(),t=(e,t)=>e===`/`||t===e||t.startsWith(`${e}/`),n=(n,r)=>{let i=n.starters,a=null;for(let e of n.pageRules)t(e.pathPrefix,r.pathname)&&(a===null||e.pathPrefix.length>a.pathPrefix.length)&&(a=e);a?.starters&&(i=a.starters),r.returning&&n.returningStarters&&(i=n.returningStarters);let o=r.behaviour;if(r.behaviourStarters&&o&&n.rules){let e=n.rules.find(e=>(e.minTimeOnSiteSeconds===null||o.timeOnSiteSeconds>=e.minTimeOnSiteSeconds)&&(e.minScrollPercent===null||o.scrollPercent>=e.minScrollPercent)&&(e.minPagesViewed===null||o.pagesViewed>=e.minPagesViewed)&&(e.minServicesViewed===null||o.viewedServices.length>=e.minServicesViewed));e&&(i=[...e.starters,...i.slice(0,e.keepPageStarters)])}let s=n.behaviour?.recentServiceStarter,c=o?.viewedServices[o.viewedServices.length-1];if(o&&s&&c!==void 0){let t=e(c),n=t.toLowerCase(),r=i.some(e=>e.label.toLowerCase().includes(n));if(t!==``&&!r){let e=s.replace(/\{service\}/g,t);i=[{id:`recent-service`,label:e,message:e,icon:null,variant:null},...i]}}let l=n.behaviour?.maxStarters;return l===void 0?[...i]:i.slice(0,l)};export{e as humanizeService,n as selectStarters};
|
|
1
|
+
var e=e=>e.replace(/[-_]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/\s+/g,` `).trim(),t=(e,t)=>e===`/`||t===e||t.startsWith(`${e}/`),n=(n,r)=>{let i=n.starters,a=null;for(let e of n.pageRules)t(e.pathPrefix,r.pathname)&&(a===null||e.pathPrefix.length>a.pathPrefix.length)&&(a=e);a?.starters&&(i=a.starters),r.returning&&n.returningStarters&&(i=n.returningStarters);let o=r.behaviour;if(r.behaviourStarters&&o&&n.rules){let e=n.rules.find(e=>(e.minTimeOnSiteSeconds===null||o.timeOnSiteSeconds>=e.minTimeOnSiteSeconds)&&(e.minScrollPercent===null||o.scrollPercent>=e.minScrollPercent)&&(e.minPagesViewed===null||o.pagesViewed>=e.minPagesViewed)&&(e.minServicesViewed===null||o.viewedServices.length>=e.minServicesViewed));e&&(i=[...e.starters,...i.slice(0,e.keepPageStarters)])}let s=n.behaviour?.recentServiceStarter,c=o?.viewedServices[o.viewedServices.length-1];if(r.behaviourStarters&&o&&s&&c!==void 0){let t=e(c),n=t.toLowerCase(),r=i.some(e=>e.label.toLowerCase().includes(n));if(t!==``&&!r){let e=s.replace(/\{service\}/g,t);i=[{id:`recent-service`,label:e,message:e,icon:null,variant:null},...i]}}let l=n.behaviour?.maxStarters;return l===void 0?[...i]:i.slice(0,l)};export{e as humanizeService,n as selectStarters};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function sniffAudioType(buffer: ArrayBuffer): string;
|
package/dist/types/client.d.ts
CHANGED
|
@@ -2,9 +2,9 @@ import { type ChatClient, type ChatHttpClient } from "./contract";
|
|
|
2
2
|
export declare class ChatApiError extends Error {
|
|
3
3
|
readonly code: string;
|
|
4
4
|
readonly status: number | undefined;
|
|
5
|
-
readonly
|
|
5
|
+
readonly resetsDateTimeUtc: string | null;
|
|
6
6
|
readonly errors: Record<string, string> | null;
|
|
7
|
-
constructor(code: string, message: string, status?: number,
|
|
7
|
+
constructor(code: string, message: string, status?: number, resetsDateTimeUtc?: string | null, errors?: Record<string, string> | null);
|
|
8
8
|
}
|
|
9
9
|
export declare const newIdempotencyKey: () => string;
|
|
10
10
|
export declare const createChatClient: (http: ChatHttpClient, { base }: {
|
package/dist/types/contract.d.ts
CHANGED
|
@@ -3,8 +3,8 @@ import { type ChatSpeechAdapter } from "./speech";
|
|
|
3
3
|
export declare const DICTATION_SILENCE_MS = 2000;
|
|
4
4
|
/** How long recognition may run before any words arrive before it gives up. */
|
|
5
5
|
export declare const DICTATION_NO_SPEECH_MS = 10000;
|
|
6
|
-
/** Idle when not dictating; Listening while recording; Blocked, NotHeard and Failed stay until the next start or stop. */
|
|
7
|
-
export type ChatDictationStatus = "Idle" | "Listening" | "Blocked" | "NotHeard" | "Failed";
|
|
6
|
+
/** Idle when not dictating; Listening while recording; Blocked, NoMicrophone, Unavailable, NotHeard and Failed stay until the next start or stop. */
|
|
7
|
+
export type ChatDictationStatus = "Idle" | "Listening" | "Blocked" | "NotHeard" | "Failed" | "NoMicrophone" | "Unavailable";
|
|
8
8
|
/** The dictation state a screen renders. The same object is returned until the status changes. */
|
|
9
9
|
export interface ChatDictationState {
|
|
10
10
|
readonly status: ChatDictationStatus;
|
package/dist/types/explain.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export interface ChatExplainSnapshot<TAnswer = unknown> {
|
|
|
6
6
|
/** True from 300 ms after the request began, and for at least 500 ms. */
|
|
7
7
|
pillVisible: boolean;
|
|
8
8
|
/** Set only in "capacity". */
|
|
9
|
-
|
|
9
|
+
resetsDateTimeUtc: string | null;
|
|
10
10
|
offline: boolean;
|
|
11
11
|
}
|
|
12
12
|
export interface ChatExplain<TAnswer = unknown> {
|
package/dist/types/index.d.ts
CHANGED
package/dist/types/labels.d.ts
CHANGED
|
@@ -50,6 +50,8 @@ export interface ChatLabels {
|
|
|
50
50
|
captchaNote: string;
|
|
51
51
|
captchaPrivacy: string;
|
|
52
52
|
captchaTerms: string;
|
|
53
|
+
captchaUnavailable: string;
|
|
54
|
+
newMessages: string;
|
|
53
55
|
disclaimer: string;
|
|
54
56
|
copy: string;
|
|
55
57
|
copied: string;
|
|
@@ -61,6 +63,7 @@ export interface ChatLabels {
|
|
|
61
63
|
edit: string;
|
|
62
64
|
rateUp: string;
|
|
63
65
|
rateDown: string;
|
|
66
|
+
rating: string;
|
|
64
67
|
rated: string;
|
|
65
68
|
ratingFailed: string;
|
|
66
69
|
sources: string;
|
|
@@ -74,6 +77,10 @@ export interface ChatLabels {
|
|
|
74
77
|
inputSkipped: string;
|
|
75
78
|
inputOptional: string;
|
|
76
79
|
inputChooseFile: string;
|
|
80
|
+
inputSendCode: string;
|
|
81
|
+
inputEnterCode: string;
|
|
82
|
+
inputCodeSent: string;
|
|
83
|
+
inputCodeFailed: string;
|
|
77
84
|
inputRemoveFile: (fileName: string) => string;
|
|
78
85
|
actionConfirm: string;
|
|
79
86
|
actionDismiss: string;
|
|
@@ -129,7 +136,6 @@ export interface ChatLabels {
|
|
|
129
136
|
statusWaitingForAgent: string;
|
|
130
137
|
statusWithAgent: (name: string) => string;
|
|
131
138
|
openTickets: string;
|
|
132
|
-
openTicketRow: string;
|
|
133
139
|
ticketAria: (number: string) => string;
|
|
134
140
|
ticketView: string;
|
|
135
141
|
ticketStatus: (status: string) => string;
|
package/dist/types/session.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type { ChatAttribution, ChatAuthor, ChatAuthorKind, ChatBehaviour, ChatClient, ChatConversationState, ChatConversationSummary, ChatFeature, ChatOpenTicket, ChatPart, ChatParticipant, ChatProfileView, ChatQuickReply, ChatRating, ChatStarter, ChatUploadFile } from "./contract";
|
|
1
|
+
import type { ChatAttribution, ChatAuthor, ChatAuthorKind, ChatBehaviour, ChatClient, ChatConversationState, ChatConversationSummary, ChatFeature, ChatOpenTicket, ChatOtpRequest, ChatPart, ChatParticipant, ChatProfileView, ChatQuickReply, ChatRating, ChatStarter, ChatUploadFile } from "./contract";
|
|
2
2
|
import { type ChatLabels } from "./labels";
|
|
3
3
|
export type FrameScheduler = (callback: () => void) => () => void;
|
|
4
4
|
export type ChatLiveStatus = "Off" | "Connecting" | "Live" | "Lost";
|
|
5
5
|
export interface ChatTurnError {
|
|
6
6
|
code: string;
|
|
7
7
|
message: string;
|
|
8
|
-
|
|
8
|
+
resetsDateTimeUtc: string | null;
|
|
9
9
|
}
|
|
10
10
|
export interface ComposerAttachment {
|
|
11
11
|
key: string;
|
|
@@ -104,7 +104,7 @@ export interface ChatSession {
|
|
|
104
104
|
load(): Promise<void>;
|
|
105
105
|
submit(text: string): Promise<void>;
|
|
106
106
|
chooseQuickReply(reply: ChatQuickReply): Promise<void>;
|
|
107
|
-
answerInput(requestId: string, values: Record<string, string>): Promise<ChatInputOutcome>;
|
|
107
|
+
answerInput(requestId: string, values: Record<string, string>, codes?: Record<string, string> | null): Promise<ChatInputOutcome>;
|
|
108
108
|
confirmAction(actionId: string): Promise<void>;
|
|
109
109
|
rejectAction(actionId: string, reason?: string): Promise<void>;
|
|
110
110
|
stop(): void;
|
|
@@ -144,13 +144,17 @@ export interface ChatTurnApi {
|
|
|
144
144
|
readonly isLast: boolean;
|
|
145
145
|
readonly busy: boolean;
|
|
146
146
|
readonly handoffPause: boolean;
|
|
147
|
+
/** True when a later hand-off message exists, so this message's stored Waiting or Requested card is hidden. */
|
|
148
|
+
readonly handoffSettled: boolean;
|
|
147
149
|
readonly handoffHosts?: readonly string[];
|
|
148
150
|
chooseQuickReply(reply: ChatQuickReply): void;
|
|
149
151
|
skipInput(requestId: string): void;
|
|
150
152
|
cancelLead(): void;
|
|
151
|
-
answerInput(requestId: string, values: Record<string, string>): Promise<ChatInputOutcome>;
|
|
153
|
+
answerInput(requestId: string, values: Record<string, string>, codes?: Record<string, string> | null): Promise<ChatInputOutcome>;
|
|
152
154
|
/** Uploads the file a File question asks for; resolves to the attachment public id that answerInput takes as the field value. */
|
|
153
155
|
uploadInputFile(file: ChatUploadFile, onProgress?: (fraction: number) => void): Promise<string>;
|
|
156
|
+
/** Sends the one-time code for a Verify field to the address or number the field's request names. */
|
|
157
|
+
sendOtp(requestId: string, request: ChatOtpRequest): Promise<void>;
|
|
154
158
|
confirmAction(actionId: string): Promise<void>;
|
|
155
159
|
rejectAction(actionId: string, reason?: string): Promise<void>;
|
|
156
160
|
requestHandoff(reason?: string): Promise<void>;
|
|
@@ -187,4 +191,5 @@ export interface ChatTurnApiContext {
|
|
|
187
191
|
onNavigate?: ChatTurnApi["onNavigate"];
|
|
188
192
|
}
|
|
189
193
|
export declare const createChatSession: (client: ChatClient, options: ChatSessionOptions) => ChatSession;
|
|
194
|
+
export declare const handoffSettledIds: (messages: readonly ChatLiveMessage[]) => ReadonlySet<string>;
|
|
190
195
|
export declare const createTurnApi: (session: ChatSession, context: ChatTurnApiContext) => ChatTurnApi;
|
package/dist/types/speech.d.ts
CHANGED
|
@@ -24,6 +24,8 @@ export interface ChatSpeechAdapter {
|
|
|
24
24
|
onStarted?: () => void;
|
|
25
25
|
onLevel?: (level: number) => void;
|
|
26
26
|
signal?: ChatAbortSignal;
|
|
27
|
+
/** Asked once the clip is recorded: true means the clip is deleted and not transcribed. */
|
|
28
|
+
shouldDiscard?: () => boolean;
|
|
27
29
|
}): Promise<void>;
|
|
28
30
|
/** Resolves when the audio ends or the signal aborts. A new call cancels the one in progress. */
|
|
29
31
|
speak(text: string, options: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/chat-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.134.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,10 +26,10 @@
|
|
|
26
26
|
},
|
|
27
27
|
"sideEffects": false,
|
|
28
28
|
"peerDependencies": {
|
|
29
|
-
"@webority/markdown-core": "^0.130.
|
|
29
|
+
"@webority/markdown-core": "^0.130.3"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@webority/markdown-core": "0.130.
|
|
32
|
+
"@webority/markdown-core": "0.130.3",
|
|
33
33
|
"typescript": "^7.0.2",
|
|
34
34
|
"vite": "^8.0.12",
|
|
35
35
|
"vitest": "5.0.1"
|