@webority/chat-core 0.154.0 → 0.156.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/client.js +2 -2
- package/dist/decode/enums.js +1 -1
- package/dist/decode/parts.js +1 -1
- package/dist/decode/primitives.js +1 -1
- package/dist/index.js +1 -1
- package/dist/labels.js +1 -1
- package/dist/types/contract.d.ts +2 -2
- package/dist/types/decode/primitives.d.ts +2 -5
- package/dist/types/labels.d.ts +0 -1
- package/package.json +3 -3
package/dist/client.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import"./contract.js";import{decodeChatConversationSummaryPage as e,decodeChatConversationView as t}from"./decode/messages.js";import{ChatDecodeError as n,array as r,arrayBuffer as i}from"./decode/primitives.js";import{decodeChatProfileView as a}from"./decode/profile.js";import{decodeChatActionView as o,decodeChatAttachment as s,decodeChatOpenTicket as c,decodeChatSpeechToken as l}from"./decode/replies.js";import{asRecord as u,isRecord as d}from"./guards.js";import{DEFAULT_CHAT_LABELS as f}from"./labels.js";import{runtime as p}from"./runtime.js";import{createStreamReader as m}from"./stream.js";var h=class extends Error{code;status;resetsDateTimeUtc;errors;constructor(e,t){super(t.message,`cause`in t?{cause:t.cause}:void 0),this.name=`ChatApiError`,this.code=e,this.status=t.status,this.resetsDateTimeUtc=t.resetsDateTimeUtc??null,this.errors=t.errors??null}},g=e=>{if(!d(e))return null;let t={errors:e.errors};return typeof e.code==`string`&&(t.code=e.code),typeof e.detail==`string`&&(t.detail=e.detail),typeof e.resetsDateTimeUtc==`string`&&(t.resetsDateTimeUtc=e.resetsDateTimeUtc),t},_=e=>{if(typeof e==`string`)try{return g(JSON.parse(e))}catch{return null}return g(e)},v=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return null;let t={};for(let[n,r]of Object.entries(u(e)))Array.isArray(r)&&typeof r[0]==`string`&&(t[n]=r[0]);return Object.keys(t).length>0?t:null},y=(e,t)=>{let n=u(e);return!!t?.aborted||n.code===`ERR_CANCELED`||n.name===`CanceledError`||n.name===`AbortError`},b=(e,t)=>{if(e instanceof h)return e;if(y(e,t))return new h(`aborted`,{message:`The request was cancelled.`});let n=u(e).response;if(!n)return new h(`network`,{message:f.errorGeneric});let r=u(n),i=_(r.data),a=typeof i?.code==`string`&&i.code?i.code:`unknown`,o=typeof i?.detail==`string`&&i.detail?i.detail:f.errorGeneric,s=typeof i?.resetsDateTimeUtc==`string`?i.resetsDateTimeUtc:null;return new h(a,{message:o,status:typeof r.status==`number`?r.status:void 0,resetsDateTimeUtc:s,errors:v(i?.errors)})},x=e=>{try{return e()}catch(e){throw e instanceof n?new h(`invalid-response`,{message:f.errorGeneric,cause:e}):e}},S=async(e,t)=>{let n;try{n=(await e()).data}catch(e){throw b(e)}return x(()=>t(n,`response`))},C=()=>void 0,w=e=>{let t=u(u(e).event).target;if(d(t)&&typeof t.responseText==`string`&&!(typeof t.status==`number`&&(t.status<200||t.status>=300)))return t.responseText},T=()=>{let e=p.createFormData;if(!e)throw Error(`FormData is not available.`);return e()},E=e=>typeof u(e).uri==`string`,D=(e,t)=>{if(E(t)){e.append(`file`,t);return}let n=u(t).name;if(typeof n!=`string`||n===``)throw Error(`The file needs a name.`);e.append(`file`,t,n)},O=()=>{let e=p.crypto;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=e.getRandomValues(/* @__PURE__ */ new Uint8Array(16));return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}throw Error(`A chat idempotency key needs crypto.randomUUID or crypto.getRandomValues, and this runtime has neither.`)},k=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t},A=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))}}},j=(n,{base:u})=>{if(typeof u!=`string`||u.trim()===``)throw TypeError(`createChatClient needs a base path, e.g. { base: "/api/assistant" }.`);let d=u.replace(/\/+$/,``),g=
|
|
3
|
-
`),l.end();let t=l.failure;if(t)throw new h(t.code||`unknown`,{message:t.message||f.errorGeneric})}catch(e){if(t.signal?.aborted)return;let n=l.failure;throw n?new h(n.code||`unknown`,{message:n.message||f.errorGeneric,cause:e}):a?new h(`stalled`,{message:f.errorGeneric,cause:e}):b(e,r.signal)}finally{o!==null&&p.clearTimeout(o),t.signal?.removeEventListener(`abort`,i)}},sendTyping:async e=>{await S(()=>n.post(`${
|
|
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))}}},j=(n,{base:u})=>{if(typeof u!=`string`||u.trim()===``)throw TypeError(`createChatClient needs a base path, e.g. { base: "/api/assistant" }.`);let d=u.replace(/\/+$/,``),g=e=>`${d}/conversations/${encodeURIComponent(e)}`,_=e=>`${d}/attachments/${encodeURIComponent(e)}`,v=e=>`${d}/actions/${encodeURIComponent(e)}`,y=/* @__PURE__ */ new Map,x=async e=>{let t=e===void 0?``:`?screen=${encodeURIComponent(e)}`;try{let e=await S(()=>n.get(`${d}/profile${t}`),a);if(typeof e?.contractVersion!=`number`||e.contractVersion<4)throw new h(`assistant_outdated`,{message:f.assistantOutdated});return e}catch(e){throw e instanceof h&&e.status===404?new h(`assistant_outdated`,{message:f.assistantOutdated,status:404,cause:e}):e}},E=e=>{let t=e??``,n=y.get(t);return n||(n=x(e).catch(e=>{throw y.delete(t),e}),y.set(t,n)),n},j=async(e,t,r)=>{let i=m(r.onEvent),a=0,o=e=>{typeof e!=`string`||e.length<=a||(i.push(e.slice(a)),a=e.length)},s;try{s=await n.post(e,t,{responseType:`text`,headers:r.headers,...r.signal===void 0?{}:{signal:r.signal},onDownloadProgress:e=>o(w(e))})}catch(e){throw b(e,r.signal)}o(s.data),i.end();let c=i.failure;if(c)throw new h(c.code||`unknown`,{message:c.message||f.errorGeneric});let l=i.last;if(!l)throw new h(`invalid-response`,{message:f.errorGeneric,status:s.status});return l};return{getProfile:E,send:(e,t={})=>{let n=k({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 j(`${d}/messages`,n,{signal:t.signal,onEvent:t.onEvent,headers:{Accept:`text/event-stream`,"Idempotency-Key":O()}})},answerInput:(e,t,n={})=>{let r=k({values:t.values,captchaToken:t.captchaToken,codes:t.codes,attribution:t.attribution});return j(`${d}/inputs/${encodeURIComponent(e)}`,r,{signal:n.signal,onEvent:n.onEvent,headers:{Accept:`text/event-stream`,"Idempotency-Key":O()}})},confirmAction:e=>S(()=>n.post(`${v(e)}/confirm`,{}),o),rejectAction:(e,t)=>S(()=>n.post(`${v(e)}/reject`,t===void 0?{}:{reason:t}),o),listConversations:(t={})=>{let r=[];t.page!==void 0&&r.push(`page=${encodeURIComponent(String(t.page))}`),t.pageSize!==void 0&&r.push(`pageSize=${encodeURIComponent(String(t.pageSize))}`);let i=r.join(`&`),a=i?`${d}/conversations?${i}`:`${d}/conversations`;return S(()=>n.get(a),e)},getConversation:(e,r)=>{let i=r===void 0?g(e):`${g(e)}?afterSequence=${r}`;return S(()=>n.get(i),t)},renameConversation:async(e,t)=>{await S(()=>n.put(`${g(e)}/title`,{title:t}),C)},deleteConversation:async e=>{await S(()=>n.delete(g(e)),C)},rateMessage:async(e,t)=>{let r=typeof t.note==`string`?t.note.trim():``;await S(()=>n.put(`${d}/messages/${encodeURIComponent(e)}/rating`,{rating:t.rating,note:r||null}),C)},uploadAttachment:(e,t={})=>{let r=T();return D(r,e),S(()=>n.post(`${d}/attachments`,r.native,{headers:{"Content-Type":`multipart/form-data`},timeout:3e5,...t.signal===void 0?{}:{signal:t.signal},onUploadProgress:({loaded:e,total:n})=>{t.onProgress&&n&&t.onProgress((e??0)/n)}}),s)},deleteAttachment:async e=>{await S(()=>n.delete(_(e)),C)},getAttachment:e=>S(()=>n.get(_(e),{responseType:`arraybuffer`}),i),sendOtp:async(e,t)=>{await S(()=>n.post(`${d}/inputs/${encodeURIComponent(e)}/otp`,t),C)},requestHandoff:(e,t={})=>{let n=typeof e.reason==`string`&&e.reason.trim()!==``?e.reason:void 0,r=n===void 0?{conversationId:e.conversationId}:{conversationId:e.conversationId,reason:n};return j(`${d}/handoff`,r,{signal:t.signal,onEvent:t.onEvent,headers:{Accept:`text/event-stream`,"Idempotency-Key":O()}})},watchConversation:async(e,t)=>{let r=new p.AbortController,i=()=>r.abort();t.signal?.aborted&&r.abort(),t.signal?.addEventListener(`abort`,i);let a=!1,o=null,s=()=>{o!==null&&p.clearTimeout(o),o=p.setTimeout(()=>{a=!0,r.abort()},t.stallTimeoutMs??9e4)},c=A(t.onCursor),l=m(t.onEvent),u=0,d=e=>{if(typeof e!=`string`||e.length<=u)return;let t=e.slice(u);u=e.length,c(t),l.push(t),l.failure&&r.abort()},_={Accept:`text/event-stream`};typeof t.afterSequence==`number`&&Number.isFinite(t.afterSequence)&&(_[`Last-Event-ID`]=String(t.afterSequence)),s();try{d((await n.get(`${g(e)}/events`,{headers:_,responseType:`text`,timeout:0,signal:r.signal,onDownloadProgress:e=>{let t=w(e);t!==void 0&&(s(),d(t))}})).data),c(`
|
|
3
|
+
`),l.end();let t=l.failure;if(t)throw new h(t.code||`unknown`,{message:t.message||f.errorGeneric})}catch(e){if(t.signal?.aborted)return;let n=l.failure;throw n?new h(n.code||`unknown`,{message:n.message||f.errorGeneric,cause:e}):a?new h(`stalled`,{message:f.errorGeneric,cause:e}):b(e,r.signal)}finally{o!==null&&p.clearTimeout(o),t.signal?.removeEventListener(`abort`,i)}},sendTyping:async e=>{await S(()=>n.post(`${g(e)}/typing`,void 0),C)},listOpenTickets:()=>S(()=>n.get(`${d}/tickets/open`),r(c)),getSpeechToken:()=>S(()=>n.post(`${d}/speech/token`,void 0),l)}};export{h as ChatApiError,j as createChatClient,O as newIdempotencyKey};
|
package/dist/decode/enums.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{allMembers as e}from"./primitives.js";var t=e()([`Pending`,`Confirmed`,`Rejected`,`Expired`,`Done`,`Failed`,`Repeat`]),n=e()([`Visitor`,`Customer`,`Assistant`,`Agent`,`Script`,`System`]),r=e()([`Off`,`FirstMessage`,`EveryInput`]),i=e()([`Bar`,`Line`,`Donut`]),a=e()([`Text`,`Integer`,`Decimal`,`MoneyMinor`,`Percent`,`Date`,`DateTimeUtc`]),o=e()([`Open`,`WaitingForAgent`,`WithAgent`,`Closed`]),s=e()([`Email`,`Phone`,`Name`,`Company`,`Text`,`LongText`,`Choice`,`MultiChoice`,`TimeSlot`,`File`,`Consent`]),c=e()([`None`,`Otp`]),l=e()([`Neutral`,`Positive`,`Caution`,`Negative`]),u=e()([`Requested`,`Waiting`,`Joined`,`Left`,`Ended`]),d=e()([`Open`,`Answered`,`Skipped`,`Expired`]),f=e()([`
|
|
1
|
+
import{allMembers as e}from"./primitives.js";var t=e()([`Pending`,`Confirmed`,`Rejected`,`Expired`,`Done`,`Failed`,`Repeat`]),n=e()([`Visitor`,`Customer`,`Assistant`,`Agent`,`Script`,`System`]),r=e()([`Off`,`FirstMessage`,`EveryInput`]),i=e()([`Bar`,`Line`,`Donut`]),a=e()([`Text`,`Integer`,`Decimal`,`MoneyMinor`,`Percent`,`Date`,`DateTimeUtc`]),o=e()([`Open`,`WaitingForAgent`,`WithAgent`,`Closed`]),s=e()([`Email`,`Phone`,`Name`,`Company`,`Text`,`LongText`,`Choice`,`MultiChoice`,`TimeSlot`,`File`,`Consent`]),c=e()([`None`,`Otp`]),l=e()([`Neutral`,`Positive`,`Caution`,`Negative`]),u=e()([`Requested`,`Waiting`,`Joined`,`Left`,`Ended`]),d=e()([`Open`,`Answered`,`Skipped`,`Expired`]),f=e()([`ActionLimitReached`,`ConversationContinued`,`AssistantUnavailable`,`OutOfTopic`,`ConversationTooLong`,`LeadAlreadyCaptured`]),p=e()([`Text`,`Sources`,`QuickReplies`,`InputRequest`,`Action`,`Notice`,`Table`,`Chart`,`Figures`,`RecordCard`,`Image`,`File`,`Ticket`,`Handoff`,`VoiceClip`]),m=e()([`Send`,`Open`,`Navigate`]),h=e()([`Inline`,`Composer`]),g=e()([`Default`,`Primary`,`Cta`]),_=e()([`Up`,`Down`]),v=e()([`messageStarted`,`partStarted`,`partDelta`,`partCompleted`,`messageReset`,`step`,`messageCompleted`,`conversationUpdated`,`typing`,`error`]);export{t as ChatActionStateValues,n as ChatAuthorKindValues,r as ChatCaptchaModeValues,i as ChatChartTypeValues,a as ChatColumnTypeValues,o as ChatConversationStateValues,s as ChatFieldTypeValues,c as ChatFieldVerificationValues,l as ChatFigureStatusValues,u as ChatHandoffStateValues,d as ChatInputRequestStateValues,f as ChatNoticeCodeValues,p as ChatPartKindValues,m as ChatQuickReplyActionValues,h as ChatQuickReplyPlacementValues,g as ChatQuickReplyVariantValues,_ as ChatRatingValues,v as ChatStreamEventNameValues};
|
package/dist/decode/parts.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ChatActionStateValues as e,ChatChartTypeValues as t,ChatColumnTypeValues as n,ChatFieldTypeValues as r,ChatFieldVerificationValues as i,ChatFigureStatusValues as a,ChatHandoffStateValues as o,ChatInputRequestStateValues as s,ChatNoticeCodeValues as c,ChatPartKindValues as l,ChatQuickReplyActionValues as u,ChatQuickReplyPlacementValues as d,ChatQuickReplyVariantValues as f}from"./enums.js";import{ChatDecodeError as p,array as m,boolean as h,field as g,nullable as _,number as v,oneOf as y,record as b,string as x,unionByKind as S}from"./primitives.js";var C=(e,t)=>{if(e===null||typeof e==`string`||typeof e==`number`)return e;throw new p(t,`text, a number or null`)},w=(e,t)=>{let n=b(e,t);return Object.fromEntries(Object.keys(n).map(e=>[e,x(n[e],`${t}.${e}`)]))},T=(e,t)=>{let n=b(e,t);return{marker:g(n,`marker`,v,t),title:g(n,`title`,x,t),reference:g(n,`reference`,x,t),url:g(n,`url`,_(x),t)}},E=(e,t)=>{let n=b(e,t);return{id:g(n,`id`,x,t),label:g(n,`label`,x,t)}},D=(e,t)=>{let n=b(e,t);return{id:g(n,`id`,x,t),startDateTimeUtc:g(n,`startDateTimeUtc`,x,t),endDateTimeUtc:g(n,`endDateTimeUtc`,x,t)}},O=(e,t)=>{let n=b(e,t);return{id:g(n,`id`,x,t),label:g(n,`label`,x,t),action:g(n,`action`,y(u),t),target:g(n,`target`,_(x),t),navigateAfterMs:g(n,`navigateAfterMs`,_(v),t),icon:g(n,`icon`,_(x),t),variant:g(n,`variant`,_(y(f)),t)}},k=(e,t)=>{let n=b(e,t);return{key:g(n,`key`,x,t),type:g(n,`type`,y(r),t),label:g(n,`label`,x,t),placeholder:g(n,`placeholder`,_(x),t),required:g(n,`required`,h,t),maxLength:g(n,`maxLength`,_(v),t),options:g(n,`options`,_(m(E)),t),slots:g(n,`slots`,_(m(D)),t),consentText:g(n,`consentText`,_(x),t),verify:g(n,`verify`,y(i),t),accept:g(n,`accept`,_(m(x)),t),secret:g(n,`secret`,h,t),validator:g(n,`validator`,_(x),t)}},A=(e,t)=>{let r=b(e,t);return{key:g(r,`key`,x,t),label:g(r,`label`,x,t),type:g(r,`type`,y(n),t)}},j=(e,t)=>{let n=b(e,t);return{label:g(n,`label`,x,t),value:g(n,`value`,v,t)}},M=(e,t)=>{let n=b(e,t);return{name:g(n,`name`,x,t),points:g(n,`points`,m(j),t)}},N=(e,t)=>{let n=b(e,t);return{label:g(n,`label`,x,t),value:g(n,`value`,v,t),unit:g(n,`unit`,_(x),t),status:g(n,`status`,y(a),t)}},P=(e,t)=>{let r=b(e,t);return{label:g(r,`label`,x,t),value:g(r,`value`,x,t),type:g(r,`type`,y(n),t)}},F=(e,t)=>{let n=b(e,t);return{route:g(n,`route`,x,t),params:g(n,`params`,w,t)}},I=(e,t)=>{let n=b(e,t);return{displayName:g(n,`displayName`,x,t),avatarUrl:g(n,`avatarUrl`,_(x),t)}},L=S(l,{Text:(e,t)=>{let n=b(e,t);return{kind:`Text`,text:g(n,`text`,x,t)}},Sources:(e,t)=>{let n=b(e,t);return{kind:`Sources`,sources:g(n,`sources`,m(T),t)}},QuickReplies:(e,t)=>{let n=b(e,t);return{kind:`QuickReplies`,replies:g(n,`replies`,m(O),t),placement:g(n,`placement`,y(d),t)}},InputRequest:(e,t)=>{let n=b(e,t);return{kind:`InputRequest`,requestId:g(n,`requestId`,x,t),title:g(n,`title`,_(x),t),fields:g(n,`fields`,m(k),t),submitLabel:g(n,`submitLabel`,x,t),state:g(n,`state`,y(s),t),answeredSummary:g(n,`answeredSummary`,_(x),t),allowTyped:g(n,`allowTyped`,h,t),cancellable:g(n,`cancellable`,h,t)}},Action:(t,n)=>{let r=b(t,n);return{kind:`Action`,actionId:g(r,`actionId`,x,n),actionKind:g(r,`actionKind`,x,n),title:g(r,`title`,x,n),lines:g(r,`lines`,m(x),n),state:g(r,`state`,y(e),n),decidedDateTimeUtc:g(r,`decidedDateTimeUtc`,_(x),n),note:g(r,`note`,_(x),n),consentText:g(r,`consentText`,_(x),n),confirmLabel:g(r,`confirmLabel`,_(x),n),rejectLabel:g(r,`rejectLabel`,_(x),n),editFields:g(r,`editFields`,_(m(E)),n)}},Notice:(e,t)=>{let n=b(e,t);return{kind:`Notice`,code:g(n,`code`,y(c),t),text:g(n,`text`,x,t)}},Table:(e,t)=>{let n=b(e,t);return{kind:`Table`,title:g(n,`title`,_(x),t),columns:g(n,`columns`,m(A),t),rows:g(n,`rows`,m(m(C)),t),currency:g(n,`currency`,_(x),t)}},Chart:(e,n)=>{let r=b(e,n);return{kind:`Chart`,title:g(r,`title`,_(x),n),chartType:g(r,`chartType`,y(t),n),unit:g(r,`unit`,_(x),n),series:g(r,`series`,m(M),n)}},Figures:(e,t)=>{let n=b(e,t);return{kind:`Figures`,figures:g(n,`figures`,m(N),t)}},RecordCard:(e,t)=>{let n=b(e,t);return{kind:`RecordCard`,recordType:g(n,`recordType`,x,t),recordId:g(n,`recordId`,x,t),title:g(n,`title`,x,t),subtitle:g(n,`subtitle`,_(x),t),fields:g(n,`fields`,m(P),t),target:g(n,`target`,_(F),t)}},Image:(e,t)=>{let n=b(e,t);return{kind:`Image`,attachmentId:g(n,`attachmentId`,x,t),alt:g(n,`alt`,x,t),width:g(n,`width`,_(v),t),height:g(n,`height`,_(v),t)}},File:(e,t)=>{let n=b(e,t);return{kind:`File`,attachmentId:g(n,`attachmentId`,x,t),fileName:g(n,`fileName`,x,t),contentType:g(n,`contentType`,x,t),length:g(n,`length`,v,t)}},Ticket:(e,t)=>{let n=b(e,t);return{kind:`Ticket`,ticketId:g(n,`ticketId`,x,t),number:g(n,`number`,x,t),subject:g(n,`subject`,x,t),status:g(n,`status`,x,t)}},Handoff:(e,t)=>{let n=b(e,t);return{kind:`Handoff`,state:g(n,`state`,y(o),t),queuePosition:g(n,`queuePosition`,_(v),t),agent:g(n,`agent`,_(I),t)}},VoiceClip:(e,t)=>{let n=b(e,t);return{kind:`VoiceClip`,attachmentId:g(n,`attachmentId`,x,t),durationMs:g(n,`durationMs`,v,t),transcript:g(n,`transcript`,_(x),t)}}});export{j as decodeChatChartPoint,M as decodeChatChartSeries,N as decodeChatFigure,k as decodeChatInputField,E as decodeChatInputOption,L as decodeChatPart,I as decodeChatParticipant,O as decodeChatQuickReply,P as decodeChatRecordField,F as decodeChatRecordTarget,T as decodeChatSource,A as decodeChatTableColumn,D as decodeChatTimeSlot};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isRecord as e}from"../guards.js";var t=class extends Error{path;constructor(e,t){super(`Expected ${t} at ${e}.`),this.name=`ChatDecodeError`,this.path=e}},n=(n,r)=>{if(!e(n))throw new t(r,`an object`);return n},r=(e,t,n,r)=>n(e[t],`${r}.${t}`),i=(e,n)=>{if(typeof e!=`string`)throw new t(n,`a string`);return e},a=(e,n)=>{if(typeof e!=`number`||Number.isNaN(e))throw new t(n,`a number`);return e},o=(e,n)=>{if(typeof e!=`boolean`)throw new t(n,`true or false`);return e},s=(e,n)=>{if(!(e instanceof ArrayBuffer))throw new t(n,`binary data`);return e},c=e=>(t,n)=>t==null?null:e(t,n),l=e=>(n,r)=>{if(!Array.isArray(n))throw new t(r,`a list`);return n.map((t,n)=>e(t,`${r}[${n}]`))},u=()=>e=>e,d=e=>(n,r)=>{let i=e.find(e=>e===n);if(i===void 0)throw new t(r,`one of ${e.join(`, `)}`);return i},f=e=>e,p=(e,a
|
|
1
|
+
import{isRecord as e}from"../guards.js";var t=class extends Error{path;constructor(e,t){super(`Expected ${t} at ${e}.`),this.name=`ChatDecodeError`,this.path=e}},n=(n,r)=>{if(!e(n))throw new t(r,`an object`);return n},r=(e,t,n,r)=>n(e[t],`${r}.${t}`),i=(e,n)=>{if(typeof e!=`string`)throw new t(n,`a string`);return e},a=(e,n)=>{if(typeof e!=`number`||Number.isNaN(e))throw new t(n,`a number`);return e},o=(e,n)=>{if(typeof e!=`boolean`)throw new t(n,`true or false`);return e},s=(e,n)=>{if(!(e instanceof ArrayBuffer))throw new t(n,`binary data`);return e},c=e=>(t,n)=>t==null?null:e(t,n),l=e=>(n,r)=>{if(!Array.isArray(n))throw new t(r,`a list`);return n.map((t,n)=>e(t,`${r}[${n}]`))},u=()=>e=>e,d=e=>(n,r)=>{let i=e.find(e=>e===n);if(i===void 0)throw new t(r,`one of ${e.join(`, `)}`);return i},f=e=>e,p=(e,a)=>(o,s)=>{let c=r(n(o,s),`kind`,i,s);if(!(t=>e.some(e=>e===t))(c))throw new t(`${s}.kind`,`one of ${e.join(`, `)}`);return a[c](o,s)};export{t as ChatDecodeError,u as allMembers,l as array,s as arrayBuffer,o as boolean,r as field,c as nullable,a as number,d as oneOf,n as record,i as string,p as unionByKind,f as unknownValue};
|
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{ChatDecodeError as i}from"./decode/primitives.js";import{
|
|
1
|
+
import{sniffAudioType as e}from"./audioType.js";import{ChatApiError as t,createChatClient as n,newIdempotencyKey as r}from"./client.js";import{ChatDecodeError as i}from"./decode/primitives.js";import{decodeChatPart as a}from"./decode/parts.js";import{decodeChatConversationView as o,decodeChatMessageView as s}from"./decode/messages.js";import{CHAT_CONTRACT_VERSION as c,CHAT_HANDOFF_REQUEST_ID as l}from"./contract.js";import{createConversationList as u}from"./conversationList.js";import{decodeChatProfileView as d}from"./decode/profile.js";import{decodeChatStreamEvent as f}from"./decode/events.js";import{DICTATION_NO_SPEECH_MS as p,DICTATION_SILENCE_MS as m,createDictation as h}from"./dictation.js";import{createExplain as g}from"./explain.js";import{formatFigure as _,toFigureRuns as v,toFigureText as y}from"./figures.js";import{decodeChatFixture as b}from"./decode/fixture.js";import{createFixtureClient as x}from"./fixtureClient.js";import{formatChatDate as S,formatChatDateTime as C,formatChatDay as w,formatChatValue as T,formatFileSize as E,messagePlainText as D}from"./format.js";import{isHandoffTarget as O}from"./handoff.js";import{IDLE_CHAT_SESSION as k,IDLE_CHAT_STATE as A}from"./idleSession.js";import{DEFAULT_CHAT_LABELS as j,mergeLabels as M}from"./labels.js";import{isSafeLinkUrl as N}from"./links.js";import{defaultChatLook as P,mergeLook as F}from"./look.js";import{pacingDelayMs as I}from"./pacing.js";import{CHAT_FEATURES as L,LOADER_STYLES as R,emptyFeatures as z,featureRecord as B,loaderView as V,resolveFeatures as H,resolveNudge as U,resolveStart as W,showsCaptchaNote as G}from"./profile.js";import{createChatSession as K,createTurnApi as q,handoffSettledIds as J}from"./session.js";import{CHAT_SPEECH_TOKEN_MARGIN_MS as Y,ChatSpeechError as X,createSpeechTokenSource as Z}from"./speech.js";import{humanizeService as Q,selectStarters as $}from"./starters.js";import{createSseParser as ee,createStreamReader as te}from"./stream.js";import{buildTranscript as ne,transcriptToText as re}from"./transcript.js";import{formatClipTime as ie,voiceClipBars as ae}from"./voiceClip.js";export{c as CHAT_CONTRACT_VERSION,L as CHAT_FEATURES,l as CHAT_HANDOFF_REQUEST_ID,Y as CHAT_SPEECH_TOKEN_MARGIN_MS,t as ChatApiError,i as ChatDecodeError,X as ChatSpeechError,j as DEFAULT_CHAT_LABELS,p as DICTATION_NO_SPEECH_MS,m as DICTATION_SILENCE_MS,k as IDLE_CHAT_SESSION,A as IDLE_CHAT_STATE,R as LOADER_STYLES,ne as buildTranscript,n as createChatClient,K as createChatSession,u as createConversationList,h as createDictation,g as createExplain,x as createFixtureClient,Z as createSpeechTokenSource,ee as createSseParser,te as createStreamReader,q as createTurnApi,o as decodeChatConversationView,b as decodeChatFixture,s as decodeChatMessageView,a as decodeChatPart,d as decodeChatProfileView,f as decodeChatStreamEvent,P as defaultChatLook,z as emptyFeatures,B as featureRecord,S as formatChatDate,C as formatChatDateTime,w as formatChatDay,T as formatChatValue,ie as formatClipTime,_ as formatFigure,E as formatFileSize,J as handoffSettledIds,Q as humanizeService,O as isHandoffTarget,N as isSafeLinkUrl,V as loaderView,M as mergeLabels,F as mergeLook,D as messagePlainText,r as newIdempotencyKey,I as pacingDelayMs,H as resolveFeatures,U as resolveNudge,W as resolveStart,$ as selectStarters,G as showsCaptchaNote,e as sniffAudioType,v as toFigureRuns,y as toFigureText,re as transcriptToText,ae 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`,footerPrivacyFallback:`Privacy policy`,captchaNoticeBefore:`This site is protected by reCAPTCHA and the Google `,captchaPrivacyPolicy:`Privacy Policy`,captchaNoticeAnd:` and `,captchaTerms:`Terms of Service`,captchaNoticeAfter:` apply.`,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}`,
|
|
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`,footerPrivacyFallback:`Privacy policy`,captchaNoticeBefore:`This site is protected by reCAPTCHA and the Google `,captchaPrivacyPolicy:`Privacy Policy`,captchaNoticeAnd:` and `,captchaTerms:`Terms of Service`,captchaNoticeAfter:` apply.`,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}`,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/types/contract.d.ts
CHANGED
|
@@ -88,7 +88,7 @@ export type ChatFieldVerification = "None" | "Otp";
|
|
|
88
88
|
export type ChatInputRequestState = "Open" | "Answered" | "Skipped" | "Expired";
|
|
89
89
|
export type ChatActionState = "Pending" | "Confirmed" | "Rejected" | "Expired" | "Done" | "Failed" | "Repeat";
|
|
90
90
|
export type ChatHandoffState = "Requested" | "Waiting" | "Joined" | "Left" | "Ended";
|
|
91
|
-
export type ChatNoticeCode = "
|
|
91
|
+
export type ChatNoticeCode = "ActionLimitReached" | "ConversationContinued" | "AssistantUnavailable" | "OutOfTopic" | "ConversationTooLong" | "LeadAlreadyCaptured";
|
|
92
92
|
export type ChatChartType = "Bar" | "Line" | "Donut";
|
|
93
93
|
export type ChatColumnType = "Text" | "Integer" | "Decimal" | "MoneyMinor" | "Percent" | "Date" | "DateTimeUtc";
|
|
94
94
|
export type ChatFigureStatus = "Neutral" | "Positive" | "Caution" | "Negative";
|
|
@@ -480,7 +480,7 @@ export interface ChatOtpRequest {
|
|
|
480
480
|
}
|
|
481
481
|
export interface ChatHandoffRequest {
|
|
482
482
|
conversationId: string | null;
|
|
483
|
-
reason
|
|
483
|
+
reason?: string | null;
|
|
484
484
|
}
|
|
485
485
|
/** The quick reply id that asks for a person. The session raises the hand-off route for it instead of sending a message. */
|
|
486
486
|
export declare const CHAT_HANDOFF_REQUEST_ID = "handoff.request";
|
|
@@ -24,12 +24,9 @@ export declare const allMembers: <U extends string>() => <const T extends readon
|
|
|
24
24
|
export declare const oneOf: <U extends string>(values: readonly U[]) => Decoder<U>;
|
|
25
25
|
/** A plain JSON value the contract types as unknown (page context, figure data); passed through unread. */
|
|
26
26
|
export declare const unknownValue: Decoder<unknown>;
|
|
27
|
-
/**
|
|
28
|
-
* A union discriminated by `kind`. A kind the map does not know goes to `unknownKind` when one is given
|
|
29
|
-
* (a newer server's part kind renders as a Notice), and is refused otherwise.
|
|
30
|
-
*/
|
|
27
|
+
/** A union discriminated by `kind`; a kind the map does not know is refused. */
|
|
31
28
|
export declare const unionByKind: <const K extends readonly string[], U extends {
|
|
32
29
|
kind: K[number];
|
|
33
30
|
}>(kinds: K, decoders: { [Kind in K[number]]: Decoder<Extract<U, {
|
|
34
31
|
kind: Kind;
|
|
35
|
-
}>>; }
|
|
32
|
+
}>>; }) => Decoder<U>;
|
package/dist/types/labels.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/chat-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.156.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.
|
|
29
|
+
"@webority/markdown-core": "^0.178.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@webority/markdown-core": "0.
|
|
32
|
+
"@webority/markdown-core": "0.178.0",
|
|
33
33
|
"typescript": "^7.0.2",
|
|
34
34
|
"vite": "^8.1.6",
|
|
35
35
|
"vitest": "5.1.0"
|