@inkeep/cxkit-primitives 0.5.75 → 0.5.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});async function b(r){const{type:t,messageId:n,reasons:s=[],apiKey:a,apiUrl:i,userProperties:c}=r,d=`${i}/feedback`,o={type:t,messageId:n,createdAt:new Date().toISOString(),userProperties:c};t==="negative"&&(o.reasons=s);const e=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(o)});if(!e.ok){const u=await e.text();throw new Error(`Failed to send feedback: ${u}`)}return e.json()}exports.submitFeedback=b;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});async function b(r){const{type:t,messageId:n,reasons:s=[],apiKey:a,apiUrl:i,userProperties:c,properties:d}=r,p=`${i}/feedback`,o={type:t,messageId:n,createdAt:new Date().toISOString(),userProperties:c,properties:d};t==="negative"&&(o.reasons=s);const e=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(o)});if(!e.ok){const u=await e.text();throw new Error(`Failed to send feedback: ${u}`)}return e.json()}exports.submitFeedback=b;
@@ -1,13 +1,14 @@
1
1
  "use client";
2
- async function f(n) {
3
- const { type: t, messageId: r, reasons: s = [], apiKey: a, apiUrl: i, userProperties: c } = n, d = `${i}/feedback`, o = {
2
+ async function u(r) {
3
+ const { type: t, messageId: n, reasons: s = [], apiKey: a, apiUrl: i, userProperties: c, properties: d } = r, p = `${i}/feedback`, o = {
4
4
  type: t,
5
- messageId: r,
5
+ messageId: n,
6
6
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
7
- userProperties: c
7
+ userProperties: c,
8
+ properties: d
8
9
  };
9
10
  t === "negative" && (o.reasons = s);
10
- const e = await fetch(d, {
11
+ const e = await fetch(p, {
11
12
  method: "POST",
12
13
  headers: {
13
14
  "Content-Type": "application/json",
@@ -16,11 +17,11 @@ async function f(n) {
16
17
  body: JSON.stringify(o)
17
18
  });
18
19
  if (!e.ok) {
19
- const p = await e.text();
20
- throw new Error(`Failed to send feedback: ${p}`);
20
+ const f = await e.text();
21
+ throw new Error(`Failed to send feedback: ${f}`);
21
22
  }
22
23
  return e.json();
23
24
  }
24
25
  export {
25
- f as submitFeedback
26
+ u as submitFeedback
26
27
  };
@@ -1,4 +1,4 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ae=require("openai"),t=require("react"),Re=require("../../providers/config-provider.cjs"),Le=require("../../providers/conversation-provider.cjs"),xe=require("../../providers/chat-events-provider.cjs"),D=require("../../utils/get-message-metadata.cjs"),Be=require("../../utils/misc.cjs"),ae=require("../../utils/reset-query-params.cjs"),De=require("../../providers/chat-form-provider.cjs"),Oe=require("../../providers/widget-provider.cjs"),Fe=require("../../hooks/use-media-query.cjs"),Te=require("./use-captcha.cjs"),Ke=require("../modal/modal-provider.cjs"),l=require("../../utils/generate-uid.cjs"),Qe=require("../../utils/tools/links-tool.cjs"),We=require("../../atoms/api/analytics/conversation.cjs"),Je=()=>{const{chatId:f,setConversation:re,conversation:$,resetConversation:ie}=Le.useInkeepConversation(),{baseSettings:b,aiChatSettings:O}=Re.useInkeepConfig(),{aiApiBaseUrl:F,shouldBypassCaptcha:T,filters:K}=b,Q=Ke.useModal(),{getSolution:ce,prefetchSolution:q,invalidateSolution:W}=Te.useCaptcha({fetchUrl:`${F}/v1/challenge`,shouldBypassCaptcha:T,shouldMakeInitialRequest:Q?Q.isOpen:!0}),ue=new Ae({baseURL:`${F}/v1`,apiKey:b.apiKey??"",dangerouslyAllowBrowser:!0}),{onInputMessageChange:le,getTools:ge,prompts:de,model:me,filters:J,onToolCall:fe}=O,[p,N]=t.useState(""),z=t.useRef(null);t.useEffect(()=>{le?.(p)},[p]);const[g,u]=t.useState([]),[H,h]=t.useState(!1),[pe,v]=t.useState(!1),[he,j]=t.useState(null),[A,G]=t.useState(null),[y,S]=t.useState([]),ve=e=>{S(s=>[...s,e])},[ye,V]=t.useState({}),r=t.useRef([]),M=t.useRef(null),{logEvent:P}=xe.useChatEvents(),X=de?.map((e,s)=>({id:`system-${Date.now().toString()}-${l.generateUid(4)}-${s}`,role:"system",content:e})),[Se,Me]=t.useState(!!f);t.useEffect(()=>{if(f){const{apiKey:e,analyticsApiBaseUrl:s}=b;We.getConversation(f,e,s).then(o=>{if(o){P({eventName:"shared_chat_loaded",properties:{conversation:o}}),Me(!1),re({...o,id:""});const a=o.messages.map(c=>({id:Date.now().toString()+l.generateUid(4)+c.id,content:Be.parseIfJson(c.content),role:c.role,links:c.links}));u(a),r.current=a}})}},[f]);const we=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${b.organizationDisplayName??"Administrator"}`;default:return`Hmm..
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ae=require("openai"),t=require("react"),Re=require("../../providers/config-provider.cjs"),Le=require("../../providers/conversation-provider.cjs"),xe=require("../../providers/chat-events-provider.cjs"),F=require("../../utils/get-message-metadata.cjs"),ae=require("../../utils/reset-query-params.cjs"),Be=require("../../providers/chat-form-provider.cjs"),Oe=require("../../providers/widget-provider.cjs"),De=require("../../hooks/use-media-query.cjs"),Fe=require("./use-captcha.cjs"),Te=require("../modal/modal-provider.cjs"),d=require("../../utils/generate-uid.cjs"),Ke=require("../../utils/tools/links-tool.cjs"),Qe=require("../../atoms/api/analytics/conversation.cjs"),We=require("../../utils/misc.cjs"),Je=()=>{const{chatId:v,setConversation:re,conversation:A,resetConversation:ie}=Le.useInkeepConversation(),{baseSettings:q,aiChatSettings:T}=Re.useInkeepConfig(),{aiApiBaseUrl:K,shouldBypassCaptcha:Q,filters:W}=q,J=Te.useModal(),{getSolution:ce,prefetchSolution:_,invalidateSolution:z}=Fe.useCaptcha({fetchUrl:`${K}/v1/challenge`,shouldBypassCaptcha:Q,shouldMakeInitialRequest:J?J.isOpen:!0}),le=new Ae({baseURL:`${K}/v1`,apiKey:q.apiKey??"",dangerouslyAllowBrowser:!0}),{onInputMessageChange:ue,getTools:de,prompts:ge,model:me,filters:H,onToolCall:pe}=T,[y,R]=t.useState(""),j=t.useRef(null);t.useEffect(()=>{ue?.(y)},[y]);const[g,l]=t.useState([]),[G,S]=t.useState(!1),[fe,M]=t.useState(!1),[he,V]=t.useState(null),[L,X]=t.useState(null),[C,w]=t.useState([]),ve=e=>{w(s=>[...s,e])},[ye,Y]=t.useState({}),o=t.useRef([]),I=t.useRef(null),{logEvent:P}=xe.useChatEvents(),Z=ge?.map((e,s)=>({id:`system-${Date.now().toString()}-${d.generateUid(4)}-${s}`,role:"system",content:e})),[Se,Me]=t.useState(!!v);t.useEffect(()=>{if(v){const{apiKey:e,analyticsApiBaseUrl:s}=q;Qe.getConversation(v,e,s).then(a=>{if(a){P({eventName:"shared_chat_loaded",properties:{conversation:a}}),Me(!1),re({...a});const r=a.messages.map(m=>({...m,content:We.parseIfJson(m.content)}));l(r),o.current=r}})}},[v]);const Ce=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${q.organizationDisplayName??"Administrator"}`;default:return`Hmm..
2
2
 
3
- It seems I might be having some issues right now. Please clear the chat and try again.`}},Y=e=>{j(e),u(s=>{const o=[...s],a=o[o.length-1];return a&&(a.content=we(e)),o}),h(!1),v(!1),W(),q()},R=!p.trim()&&!y.length||H,Ce=e=>{e.key==="Enter"&&!e.shiftKey&&!R&&!e.nativeEvent.isComposing&&(e.preventDefault(),L())},Ie=e=>{const s=e.target.value;N(s)},L=async(e=p)=>{if(R&&(!e||e.trim().length===0))return;h(!0);const s=A?g.length===2:g.length===0,o=D.getMessageMetadata(A,y,s);let a;const c=D.serializeAttachments(y);y.length&&c?a=[{type:"text",text:c}]:a=e;const ee={id:`${Date.now().toString()}-${l.generateUid(4)}-1`,role:"user",content:a,metadata:o},E=[...g.length?[]:X,ee];f&&ae.resetQueryParams(),u(w=>[...w,...E]),r.current=[...r.current,...E],S([]),N(""),P({eventName:"user_message_submitted",properties:{}},r.current);const te=[Qe.provideLinksTool,...ge?.({conversation:$})||[]];try{const w={model:me,messages:r.current,stream:!0,tools:te,tool_choice:"auto"},se=await ce(),ne=se?btoa(JSON.stringify(se)):null,oe=K||J?JSON.stringify({...K,...J}):void 0,U={};!T&&ne&&(U["X-INKEEP-CHALLENGE-SOLUTION"]=ne),oe&&(U["inkeep-filters"]=oe);const d=ue.beta.chat.completions.stream(w,Object.keys(U).length>0?{headers:U}:void 0),n={id:`${Date.now().toString()}-${l.generateUid(4)}-2`,role:"assistant",content:"",links:[],tool_calls:[]};u(C=>[...C,n]),d.on("content",(C,I)=>{v(!0),n.content=I,u(_=>{const i=[..._],x=i.findIndex(k=>k.id===n.id);return x===-1?[...i,n]:(i[x]={...n},i)})}),d.on("tool_calls.function.arguments.done",async C=>{const{name:I,arguments:_}=C,i=te?.find(m=>m.function.name===I);if(!i)return;const k=("parse"in i.function?i.function.parse:JSON.parse)(_),Ue=i.function.function?.(k,d),_e=i.renderMessageButtons?.({args:k,execution:Ue})??[];I==="provideLinks"?n.links=k.links??[]:V(m=>({...m,[n.id]:[...m[n.id]??[],..._e]})),n.tool_calls?.push({id:"call_"+l.generateUid(24),type:"function",function:{name:I,arguments:_}}),u(m=>{const B=[...m],$e=B.findIndex(Ne=>Ne.id===n.id);return B[$e]={...n},B}),fe?.(C,{conversation:{...$,messages:[...r.current,n]}})}),d.on("error",Y),d.finalChatCompletion().then(()=>{r.current=[...r.current,n],M.current=null,h(!1),v(!1),q(),P({eventName:"assistant_message_received",properties:{}},r.current)}),M.current=d.controller}catch(w){Y(w),h(!1),v(!1)}},ke=()=>{M.current&&(M.current.abort(),M.current=null),h(!1),v(!1),q()},Z=()=>{j(null),u([]),r.current=[],ie(),V({}),S([]),ae.resetQueryParams(),G(null),W(),q(),P({eventName:"chat_clear_button_clicked",properties:{conversation:$}})},be=e=>{G(e);const{initialReplyMessage:s,displayName:o}=e,a={id:g.length.toString()+l.generateUid(4),role:"user",content:o},c={id:(g.length+1).toString()+l.generateUid(4),role:"assistant",content:s,links:[]},E=[{id:`system-${Date.now().toString()}-${l.generateUid(4)}-${e.id}`,role:"system",content:`Company has asked user to follow this guided workflow:
4
- ${D.serializeWorkflow(e)}`},...X,a,c];u(E),S([])},{openForm:qe}=De.useChatForm(),Pe=Oe.useWidget();t.useImperativeHandle(O.chatFunctionsRef,()=>({submitMessage:L,updateInputMessage(e){N(e)},clearChat:Z,openForm:e=>{Pe?.setView("chat"),qe(e)},focusInput:()=>{z.current?.focus()}}));const Ee=Fe.useMediaQuery("(max-width: 768px)");return{messages:g,input:p,isLoading:H,isStreaming:pe,isLoadingConversation:Se,error:he,isSubmitDisabled:R,handleInputChange:Ie,handleInputKeyDown:Ce,handleSubmit:L,stop:ke,clear:Z,handleWorkflow:be,selectedWorkflow:A,messageAttachments:y,setMessageAttachments:S,addAttachment:ve,messageButtons:ye,isEmpty:g.length===0,inputRef:z,isMobile:Ee}};exports.useInkeepChat=Je;
3
+ It seems I might be having some issues right now. Please clear the chat and try again.`}},ee=e=>{V(e),l(s=>{const a=[...s],r=a[a.length-1];return r&&(r.content=Ce(e)),a}),S(!1),M(!1),z(),_()},x=!y.trim()&&!C.length||G,we=e=>{e.key==="Enter"&&!e.shiftKey&&!x&&!e.nativeEvent.isComposing&&(e.preventDefault(),B())},Ie=e=>{const s=e.target.value;R(s)},B=async(e=y)=>{if(x&&(!e||e.trim().length===0))return;S(!0);const s=L?g.length===2:g.length===0,a=F.getMessageMetadata(L,C,s);let r;const m=F.serializeAttachments(C);C.length&&m?r=[{type:"text",text:m}]:r=e;const se={id:`${Date.now().toString()}-${d.generateUid(4)}-1`,role:"user",content:r,metadata:a},p=[...g.length?[]:Z,se];if(v){ae.resetQueryParams();const u=o.current.map((i,E)=>({id:`${i.id}-${d.generateUid(6)}-${E}`,role:i.role,...i.role==="assistant"?{links:i.links??[]}:{},content:i.content,metadata:i.metadata,tool_calls:i.tool_calls}));l([...u,...p]),o.current=[...u,...p]}else l(u=>[...u,...p]),o.current=[...o.current,...p];w([]),R(""),P({eventName:"user_message_submitted",properties:{}},o.current);const ne=[Ke.provideLinksTool,...de?.({conversation:A})||[]];try{const u={model:me,messages:o.current,stream:!0,tools:ne,tool_choice:"auto"},i=await ce(),E=i?btoa(JSON.stringify(i)):null,oe=W||H?JSON.stringify({...W,...H}):void 0,U={};!Q&&E&&(U["X-INKEEP-CHALLENGE-SOLUTION"]=E),oe&&(U["inkeep-filters"]=oe);const f=le.beta.chat.completions.stream(u,Object.keys(U).length>0?{headers:U}:void 0),n={id:`${Date.now().toString()}-${d.generateUid(4)}-2`,role:"assistant",content:"",links:[],tool_calls:[]};l(k=>[...k,n]),f.on("content",(k,b)=>{M(!0),n.content=b,l(N=>{const c=[...N],O=c.findIndex($=>$.id===n.id);return O===-1?[...c,n]:(c[O]={...n},c)})}),f.on("tool_calls.function.arguments.done",async k=>{const{name:b,arguments:N}=k,c=ne?.find(h=>h.function.name===b);if(!c)return;const $=("parse"in c.function?c.function.parse:JSON.parse)(N),Pe=c.function.function?.($,f),Ee=c.renderMessageButtons?.({args:$,execution:Pe})??[];b==="provideLinks"?n.links=$.links??[]:Y(h=>({...h,[n.id]:[...h[n.id]??[],...Ee]})),n.tool_calls?.push({id:"call_"+d.generateUid(24),type:"function",function:{name:b,arguments:N}}),l(h=>{const D=[...h],Ue=D.findIndex(Ne=>Ne.id===n.id);return D[Ue]={...n},D}),pe?.(k,{conversation:{...A,messages:[...o.current,n]}})}),f.on("error",ee),f.finalChatCompletion().then(()=>{o.current=[...o.current,n],I.current=null,S(!1),M(!1),_(),P({eventName:"assistant_message_received",properties:{}},o.current)}),I.current=f.controller}catch(u){ee(u),S(!1),M(!1)}},ke=()=>{I.current&&(I.current.abort(),I.current=null),S(!1),M(!1),_()},te=()=>{V(null),l([]),o.current=[],ie(),Y({}),w([]),ae.resetQueryParams(),X(null),z(),_(),P({eventName:"chat_clear_button_clicked",properties:{conversation:A}})},be=e=>{X(e);const{initialReplyMessage:s,displayName:a}=e,r={id:g.length.toString()+d.generateUid(4),role:"user",content:a},m={id:(g.length+1).toString()+d.generateUid(4),role:"assistant",content:s,links:[]},p=[{id:`system-${Date.now().toString()}-${d.generateUid(4)}-${e.id}`,role:"system",content:`Company has asked user to follow this guided workflow:
4
+ ${F.serializeWorkflow(e)}`},...Z,r,m];l(p),w([])},{openForm:$e}=Be.useChatForm(),qe=Oe.useWidget();t.useImperativeHandle(T.chatFunctionsRef,()=>({submitMessage:B,updateInputMessage(e){R(e)},clearChat:te,openForm:e=>{qe?.setView("chat"),$e(e)},focusInput:()=>{j.current?.focus()}}));const _e=De.useMediaQuery("(max-width: 768px)");return{messages:g,input:y,isLoading:G,isStreaming:fe,isLoadingConversation:Se,error:he,isSubmitDisabled:x,handleInputChange:Ie,handleInputKeyDown:we,handleSubmit:B,stop:ke,clear:te,handleWorkflow:be,selectedWorkflow:L,messageAttachments:C,setMessageAttachments:w,addAttachment:ve,messageButtons:ye,isEmpty:g.length===0,inputRef:j,isMobile:_e}};exports.useInkeepChat=Je;
@@ -1,236 +1,247 @@
1
1
  "use client";
2
2
  import De from "openai";
3
- import { useState as c, useRef as U, useEffect as ae, useImperativeHandle as Oe } from "react";
3
+ import { useState as l, useRef as K, useEffect as ae, useImperativeHandle as Oe } from "react";
4
4
  import { useInkeepConfig as Re } from "../../providers/config-provider.js";
5
5
  import { useInkeepConversation as Pe } from "../../providers/conversation-provider.js";
6
6
  import { useChatEvents as Ue } from "../../providers/chat-events-provider.js";
7
7
  import { getMessageMetadata as Fe, serializeAttachments as Ke, serializeWorkflow as Te } from "../../utils/get-message-metadata.js";
8
- import { parseIfJson as We } from "../../utils/misc.js";
9
8
  import { resetQueryParams as re } from "../../utils/reset-query-params.js";
10
- import { useChatForm as Je } from "../../providers/chat-form-provider.js";
11
- import { useWidget as ze } from "../../providers/widget-provider.js";
12
- import { useMediaQuery as He } from "../../hooks/use-media-query.js";
13
- import { useCaptcha as Qe } from "./use-captcha.js";
14
- import { useModal as je } from "../modal/modal-provider.js";
15
- import { generateUid as u } from "../../utils/generate-uid.js";
16
- import { provideLinksTool as qe } from "../../utils/tools/links-tool.js";
17
- import { getConversation as Ge } from "../../atoms/api/analytics/conversation.js";
9
+ import { useChatForm as We } from "../../providers/chat-form-provider.js";
10
+ import { useWidget as Je } from "../../providers/widget-provider.js";
11
+ import { useMediaQuery as ze } from "../../hooks/use-media-query.js";
12
+ import { useCaptcha as He } from "./use-captcha.js";
13
+ import { useModal as Qe } from "../modal/modal-provider.js";
14
+ import { generateUid as m } from "../../utils/generate-uid.js";
15
+ import { provideLinksTool as je } from "../../utils/tools/links-tool.js";
16
+ import { getConversation as qe } from "../../atoms/api/analytics/conversation.js";
17
+ import { parseIfJson as Ge } from "../../utils/misc.js";
18
18
  const gt = () => {
19
- const { chatId: d, setConversation: ie, conversation: x, resetConversation: ce } = Pe(), { baseSettings: b, aiChatSettings: F } = Re(), { aiApiBaseUrl: K, shouldBypassCaptcha: T, filters: W } = b, J = je(), { getSolution: le, prefetchSolution: _, invalidateSolution: z } = Qe({
20
- fetchUrl: `${K}/v1/challenge`,
21
- shouldBypassCaptcha: T,
22
- shouldMakeInitialRequest: J ? J.isOpen : !0
19
+ const { chatId: y, setConversation: ie, conversation: B, resetConversation: ce } = Pe(), { baseSettings: $, aiChatSettings: T } = Re(), { aiApiBaseUrl: W, shouldBypassCaptcha: J, filters: z } = $, H = Qe(), { getSolution: le, prefetchSolution: E, invalidateSolution: Q } = He({
20
+ fetchUrl: `${W}/v1/challenge`,
21
+ shouldBypassCaptcha: J,
22
+ shouldMakeInitialRequest: H ? H.isOpen : !0
23
23
  }), ue = new De({
24
- baseURL: `${K}/v1`,
25
- apiKey: b.apiKey ?? "",
24
+ baseURL: `${W}/v1`,
25
+ apiKey: $.apiKey ?? "",
26
26
  dangerouslyAllowBrowser: !0
27
27
  }), {
28
28
  onInputMessageChange: me,
29
29
  getTools: ge,
30
30
  prompts: pe,
31
31
  model: de,
32
- filters: H,
32
+ filters: j,
33
33
  onToolCall: fe
34
- } = F, [f, L] = c(""), Q = U(null);
34
+ } = T, [v, D] = l(""), q = K(null);
35
35
  ae(() => {
36
- me?.(f);
37
- }, [f]);
38
- const [m, l] = c([]), [j, h] = c(!1), [he, y] = c(!1), [ye, q] = c(null), [B, G] = c(null), [v, w] = c([]), ve = (e) => {
39
- w((t) => [...t, e]);
40
- }, [we, V] = c({}), a = U([]), C = U(null), { logEvent: $ } = Ue(), X = pe?.map((e, t) => ({
41
- id: `system-${Date.now().toString()}-${u(4)}-${t}`,
36
+ me?.(v);
37
+ }, [v]);
38
+ const [g, c] = l([]), [G, M] = l(!1), [he, w] = l(!1), [ye, V] = l(null), [O, X] = l(null), [C, I] = l([]), ve = (e) => {
39
+ I((t) => [...t, e]);
40
+ }, [Me, Y] = l({}), n = K([]), S = K(null), { logEvent: N } = Ue(), Z = pe?.map((e, t) => ({
41
+ id: `system-${Date.now().toString()}-${m(4)}-${t}`,
42
42
  role: "system",
43
43
  content: e
44
- })), [Ce, Ie] = c(!!d);
44
+ })), [we, Ce] = l(!!y);
45
45
  ae(() => {
46
- if (d) {
47
- const { apiKey: e, analyticsApiBaseUrl: t } = b;
48
- Ge(d, e, t).then((n) => {
49
- if (n) {
50
- $({
46
+ if (y) {
47
+ const { apiKey: e, analyticsApiBaseUrl: t } = $;
48
+ qe(y, e, t).then((o) => {
49
+ if (o) {
50
+ N({
51
51
  eventName: "shared_chat_loaded",
52
52
  properties: {
53
- conversation: n
53
+ conversation: o
54
54
  }
55
- }), Ie(!1), ie({ ...n, id: "" });
56
- const o = n.messages.map((i) => ({
57
- id: Date.now().toString() + u(4) + i.id,
58
- content: We(i.content),
59
- role: i.role,
60
- links: i.links
55
+ }), Ce(!1), ie({ ...o });
56
+ const a = o.messages.map((p) => ({
57
+ ...p,
58
+ content: Ge(p.content)
61
59
  }));
62
- l(o), a.current = o;
60
+ c(a), n.current = a;
63
61
  }
64
62
  });
65
63
  }
66
- }, [d]);
67
- const Me = (e) => {
64
+ }, [y]);
65
+ const Ie = (e) => {
68
66
  switch (e.code) {
69
67
  case 400:
70
68
  return e.message;
71
69
  case 403:
72
- return `There seems to be a configuration error. Please contact ${b.organizationDisplayName ?? "Administrator"}`;
70
+ return `There seems to be a configuration error. Please contact ${$.organizationDisplayName ?? "Administrator"}`;
73
71
  default:
74
72
  return `Hmm..
75
73
 
76
74
  It seems I might be having some issues right now. Please clear the chat and try again.`;
77
75
  }
78
- }, Y = (e) => {
79
- q(e), l((t) => {
80
- const n = [...t], o = n[n.length - 1];
81
- return o && (o.content = Me(e)), n;
82
- }), h(!1), y(!1), z(), _();
83
- }, D = !f.trim() && !v.length || j, Se = (e) => {
84
- e.key === "Enter" && !e.shiftKey && !D && !e.nativeEvent.isComposing && (e.preventDefault(), O());
76
+ }, ee = (e) => {
77
+ V(e), c((t) => {
78
+ const o = [...t], a = o[o.length - 1];
79
+ return a && (a.content = Ie(e)), o;
80
+ }), M(!1), w(!1), Q(), E();
81
+ }, R = !v.trim() && !C.length || G, Se = (e) => {
82
+ e.key === "Enter" && !e.shiftKey && !R && !e.nativeEvent.isComposing && (e.preventDefault(), P());
85
83
  }, ke = (e) => {
86
84
  const t = e.target.value;
87
- L(t);
88
- }, O = async (e = f) => {
89
- if (D && (!e || e.trim().length === 0)) return;
90
- h(!0);
91
- const t = B ? m.length === 2 : m.length === 0, n = Fe(B, v, t);
92
- let o;
93
- const i = Ke(v);
94
- v.length && i ? o = [{ type: "text", text: i }] : o = e;
95
- const ee = {
96
- id: `${Date.now().toString()}-${u(4)}-1`,
85
+ D(t);
86
+ }, P = async (e = v) => {
87
+ if (R && (!e || e.trim().length === 0)) return;
88
+ M(!0);
89
+ const t = O ? g.length === 2 : g.length === 0, o = Fe(O, C, t);
90
+ let a;
91
+ const p = Ke(C);
92
+ C.length && p ? a = [{ type: "text", text: p }] : a = e;
93
+ const se = {
94
+ id: `${Date.now().toString()}-${m(4)}-1`,
97
95
  role: "user",
98
- content: o,
99
- metadata: n
100
- }, E = [...m.length ? [] : X, ee];
101
- d && re(), l((I) => [...I, ...E]), a.current = [...a.current, ...E], w([]), L(""), $(
96
+ content: a,
97
+ metadata: o
98
+ }, d = [...g.length ? [] : Z, se];
99
+ if (y) {
100
+ re();
101
+ const u = n.current.map((r, A) => ({
102
+ id: `${r.id}-${m(6)}-${A}`,
103
+ role: r.role,
104
+ ...r.role === "assistant" ? { links: r.links ?? [] } : {},
105
+ content: r.content,
106
+ metadata: r.metadata,
107
+ tool_calls: r.tool_calls
108
+ }));
109
+ c([...u, ...d]), n.current = [...u, ...d];
110
+ } else
111
+ c((u) => [...u, ...d]), n.current = [...n.current, ...d];
112
+ I([]), D(""), N(
102
113
  {
103
114
  eventName: "user_message_submitted",
104
115
  properties: {}
105
116
  },
106
- a.current
117
+ n.current
107
118
  );
108
- const te = [qe, ...ge?.({ conversation: x }) || []];
119
+ const ne = [je, ...ge?.({ conversation: B }) || []];
109
120
  try {
110
- const I = {
121
+ const u = {
111
122
  model: de,
112
- messages: a.current,
123
+ messages: n.current,
113
124
  stream: !0,
114
- tools: te,
125
+ tools: ne,
115
126
  tool_choice: "auto"
116
- }, se = await le(), ne = se ? btoa(JSON.stringify(se)) : null, oe = W || H ? JSON.stringify({
117
- ...W,
118
- ...H
119
- }) : void 0, N = {};
120
- !T && ne && (N["X-INKEEP-CHALLENGE-SOLUTION"] = ne), oe && (N["inkeep-filters"] = oe);
121
- const g = ue.beta.chat.completions.stream(
122
- I,
123
- Object.keys(N).length > 0 ? { headers: N } : void 0
127
+ }, r = await le(), A = r ? btoa(JSON.stringify(r)) : null, oe = z || j ? JSON.stringify({
128
+ ...z,
129
+ ...j
130
+ }) : void 0, x = {};
131
+ !J && A && (x["X-INKEEP-CHALLENGE-SOLUTION"] = A), oe && (x["inkeep-filters"] = oe);
132
+ const f = ue.beta.chat.completions.stream(
133
+ u,
134
+ Object.keys(x).length > 0 ? { headers: x } : void 0
124
135
  ), s = {
125
- id: `${Date.now().toString()}-${u(4)}-2`,
136
+ id: `${Date.now().toString()}-${m(4)}-2`,
126
137
  role: "assistant",
127
138
  content: "",
128
139
  links: [],
129
140
  tool_calls: []
130
141
  };
131
- l((M) => [...M, s]), g.on("content", (M, S) => {
132
- y(!0), s.content = S, l((A) => {
133
- const r = [...A], R = r.findIndex((k) => k.id === s.id);
134
- return R === -1 ? [...r, s] : (r[R] = { ...s }, r);
142
+ c((k) => [...k, s]), f.on("content", (k, b) => {
143
+ w(!0), s.content = b, c((L) => {
144
+ const i = [...L], U = i.findIndex((_) => _.id === s.id);
145
+ return U === -1 ? [...i, s] : (i[U] = { ...s }, i);
135
146
  });
136
- }), g.on("tool_calls.function.arguments.done", async (M) => {
137
- const { name: S, arguments: A } = M, r = te?.find((p) => p.function.name === S);
138
- if (!r) return;
139
- const k = ("parse" in r.function ? r.function.parse : JSON.parse)(A), Ae = r.function.function?.(k, g), xe = r.renderMessageButtons?.({ args: k, execution: Ae }) ?? [];
140
- S === "provideLinks" ? s.links = k.links ?? [] : V((p) => ({
141
- ...p,
142
- [s.id]: [...p[s.id] ?? [], ...xe]
147
+ }), f.on("tool_calls.function.arguments.done", async (k) => {
148
+ const { name: b, arguments: L } = k, i = ne?.find((h) => h.function.name === b);
149
+ if (!i) return;
150
+ const _ = ("parse" in i.function ? i.function.parse : JSON.parse)(L), Ae = i.function.function?.(_, f), xe = i.renderMessageButtons?.({ args: _, execution: Ae }) ?? [];
151
+ b === "provideLinks" ? s.links = _.links ?? [] : Y((h) => ({
152
+ ...h,
153
+ [s.id]: [...h[s.id] ?? [], ...xe]
143
154
  })), s.tool_calls?.push({
144
- id: "call_" + u(24),
155
+ id: "call_" + m(24),
145
156
  type: "function",
146
157
  function: {
147
- name: S,
148
- arguments: A
158
+ name: b,
159
+ arguments: L
149
160
  }
150
- }), l((p) => {
151
- const P = [...p], Le = P.findIndex((Be) => Be.id === s.id);
152
- return P[Le] = { ...s }, P;
153
- }), fe?.(M, {
161
+ }), c((h) => {
162
+ const F = [...h], Le = F.findIndex((Be) => Be.id === s.id);
163
+ return F[Le] = { ...s }, F;
164
+ }), fe?.(k, {
154
165
  conversation: {
155
- ...x,
156
- messages: [...a.current, s]
166
+ ...B,
167
+ messages: [...n.current, s]
157
168
  }
158
169
  });
159
- }), g.on("error", Y), g.finalChatCompletion().then(() => {
160
- a.current = [...a.current, s], C.current = null, h(!1), y(!1), _(), $(
170
+ }), f.on("error", ee), f.finalChatCompletion().then(() => {
171
+ n.current = [...n.current, s], S.current = null, M(!1), w(!1), E(), N(
161
172
  {
162
173
  eventName: "assistant_message_received",
163
174
  properties: {}
164
175
  },
165
- a.current
176
+ n.current
166
177
  );
167
- }), C.current = g.controller;
168
- } catch (I) {
169
- Y(I), h(!1), y(!1);
178
+ }), S.current = f.controller;
179
+ } catch (u) {
180
+ ee(u), M(!1), w(!1);
170
181
  }
171
182
  }, be = () => {
172
- C.current && (C.current.abort(), C.current = null), h(!1), y(!1), _();
173
- }, Z = () => {
174
- q(null), l([]), a.current = [], ce(), V({}), w([]), re(), G(null), z(), _(), $({
183
+ S.current && (S.current.abort(), S.current = null), M(!1), w(!1), E();
184
+ }, te = () => {
185
+ V(null), c([]), n.current = [], ce(), Y({}), I([]), re(), X(null), Q(), E(), N({
175
186
  eventName: "chat_clear_button_clicked",
176
187
  properties: {
177
- conversation: x
188
+ conversation: B
178
189
  }
179
190
  });
180
191
  }, _e = (e) => {
181
- G(e);
182
- const { initialReplyMessage: t, displayName: n } = e, o = {
183
- id: m.length.toString() + u(4),
192
+ X(e);
193
+ const { initialReplyMessage: t, displayName: o } = e, a = {
194
+ id: g.length.toString() + m(4),
184
195
  role: "user",
185
- content: n
186
- }, i = {
187
- id: (m.length + 1).toString() + u(4),
196
+ content: o
197
+ }, p = {
198
+ id: (g.length + 1).toString() + m(4),
188
199
  role: "assistant",
189
200
  content: t,
190
201
  links: []
191
- }, E = [{
192
- id: `system-${Date.now().toString()}-${u(4)}-${e.id}`,
202
+ }, d = [{
203
+ id: `system-${Date.now().toString()}-${m(4)}-${e.id}`,
193
204
  role: "system",
194
205
  content: `Company has asked user to follow this guided workflow:
195
206
  ${Te(e)}`
196
- }, ...X, o, i];
197
- l(E), w([]);
198
- }, { openForm: $e } = Je(), Ee = ze();
199
- Oe(F.chatFunctionsRef, () => ({
200
- submitMessage: O,
207
+ }, ...Z, a, p];
208
+ c(d), I([]);
209
+ }, { openForm: $e } = We(), Ee = Je();
210
+ Oe(T.chatFunctionsRef, () => ({
211
+ submitMessage: P,
201
212
  updateInputMessage(e) {
202
- L(e);
213
+ D(e);
203
214
  },
204
- clearChat: Z,
215
+ clearChat: te,
205
216
  openForm: (e) => {
206
217
  Ee?.setView("chat"), $e(e);
207
218
  },
208
219
  focusInput: () => {
209
- Q.current?.focus();
220
+ q.current?.focus();
210
221
  }
211
222
  }));
212
- const Ne = He("(max-width: 768px)");
223
+ const Ne = ze("(max-width: 768px)");
213
224
  return {
214
- messages: m,
215
- input: f,
216
- isLoading: j,
225
+ messages: g,
226
+ input: v,
227
+ isLoading: G,
217
228
  isStreaming: he,
218
- isLoadingConversation: Ce,
229
+ isLoadingConversation: we,
219
230
  error: ye,
220
- isSubmitDisabled: D,
231
+ isSubmitDisabled: R,
221
232
  handleInputChange: ke,
222
233
  handleInputKeyDown: Se,
223
- handleSubmit: O,
234
+ handleSubmit: P,
224
235
  stop: be,
225
- clear: Z,
236
+ clear: te,
226
237
  handleWorkflow: _e,
227
- selectedWorkflow: B,
228
- messageAttachments: v,
229
- setMessageAttachments: w,
238
+ selectedWorkflow: O,
239
+ messageAttachments: C,
240
+ setMessageAttachments: I,
230
241
  addAttachment: ve,
231
- messageButtons: we,
232
- isEmpty: m.length === 0,
233
- inputRef: Q,
242
+ messageButtons: Me,
243
+ isEmpty: g.length === 0,
244
+ inputRef: q,
234
245
  isMobile: Ne
235
246
  };
236
247
  };
package/dist/index.d.cts CHANGED
@@ -2780,6 +2780,7 @@ export declare interface InkeepConversationContextValue {
2780
2780
  setConversation: React.Dispatch<React.SetStateAction<ConversationResponse>>;
2781
2781
  chatId: string | undefined;
2782
2782
  resetConversation: () => void;
2783
+ setExternalChatId: React.Dispatch<React.SetStateAction<string | undefined>>;
2783
2784
  }
2784
2785
 
2785
2786
  export declare const InkeepConversationProvider: React.FC<{
package/dist/index.d.ts CHANGED
@@ -2780,6 +2780,7 @@ export declare interface InkeepConversationContextValue {
2780
2780
  setConversation: React.Dispatch<React.SetStateAction<ConversationResponse>>;
2781
2781
  chatId: string | undefined;
2782
2782
  resetConversation: () => void;
2783
+ setExternalChatId: React.Dispatch<React.SetStateAction<string | undefined>>;
2783
2784
  }
2784
2785
 
2785
2786
  export declare const InkeepConversationProvider: React.FC<{
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react/jsx-runtime"),t=require("react"),B=require("../atoms/api/analytics/events.cjs"),f=require("./config-provider.cjs"),b=require("./user-provider.cjs"),p=t.createContext(void 0),x=({children:e})=>{const{baseSettings:n,componentType:r}=f.useInkeepConfig(),{apiKey:i,analyticsApiBaseUrl:c,tags:a,privacyPreferences:E,env:m}=n,{userProperties:v}=b.useUser(),u=t.useMemo(()=>({widgetLibraryVersion:"0.5.75",componentType:r,tags:a}),[r,a]),d=!E.optOutAllAnalytics&&m!=="development",g={logEvent:t.useCallback(async s=>{const o={...u,...s.properties},l={eventName:s.eventName,properties:o,userProperties:v},P=["modal_opened","modal_closed"].includes(s.eventName);if(d&&!P){if("conversation"in o&&!o.conversation?.id)return;B.logEvent(l,i,c)}n.onEvent?.(l)},[d,n,i,c,v,u])};return y.jsx(p.Provider,{value:g,children:e})},q=()=>{const e=t.useContext(p);if(!e)throw new Error("useBaseEvents must be used within a BaseEventsProvider");return e};exports.BaseEventsProvider=x;exports.useBaseEvents=q;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("react/jsx-runtime"),t=require("react"),f=require("../atoms/api/analytics/events.cjs"),b=require("./config-provider.cjs"),x=require("./user-provider.cjs"),E=t.createContext(void 0),q=({children:e})=>{const{baseSettings:s,componentType:r}=b.useInkeepConfig(),{apiKey:i,analyticsApiBaseUrl:c,tags:a,privacyPreferences:m,env:g,analyticsProperties:v}=s,{userProperties:u}=x.useUser(),l=t.useMemo(()=>({widgetLibraryVersion:"0.5.77",componentType:r,tags:a}),[r,a]),d=!m.optOutAllAnalytics&&g!=="development",P={logEvent:t.useCallback(async n=>{const o={...l,...n.properties,...v},p={eventName:n.eventName,properties:o,userProperties:u},y=["modal_opened","modal_closed"].includes(n.eventName);if(d&&!y){if("conversation"in o&&!o.conversation?.id)return;f.logEvent(p,i,c)}s.onEvent?.(p)},[d,s,i,c,u,l,v])};return B.jsx(E.Provider,{value:P,children:e})},C=()=>{const e=t.useContext(E);if(!e)throw new Error("useBaseEvents must be used within a BaseEventsProvider");return e};exports.BaseEventsProvider=q;exports.useBaseEvents=C;
@@ -1,43 +1,52 @@
1
1
  "use client";
2
- import { jsx as g } from "react/jsx-runtime";
3
- import { useMemo as y, useCallback as x, createContext as B, useContext as P } from "react";
4
- import { logEvent as C } from "../atoms/api/analytics/events.js";
5
- import { useInkeepConfig as b } from "./config-provider.js";
6
- import { useUser as w } from "./user-provider.js";
7
- const l = B(void 0), _ = ({ children: e }) => {
8
- const { baseSettings: t, componentType: s } = b(), { apiKey: r, analyticsApiBaseUrl: i, tags: a, privacyPreferences: u, env: d } = t, { userProperties: c } = w(), v = y(
2
+ import { jsx as y } from "react/jsx-runtime";
3
+ import { useMemo as P, useCallback as x, createContext as B, useContext as C } from "react";
4
+ import { logEvent as b } from "../atoms/api/analytics/events.js";
5
+ import { useInkeepConfig as w } from "./config-provider.js";
6
+ import { useUser as A } from "./user-provider.js";
7
+ const u = B(void 0), $ = ({ children: e }) => {
8
+ const { baseSettings: t, componentType: s } = w(), { apiKey: r, analyticsApiBaseUrl: i, tags: a, privacyPreferences: d, env: E, analyticsProperties: c } = t, { userProperties: v } = A(), p = P(
9
9
  () => ({
10
- widgetLibraryVersion: "0.5.75",
10
+ widgetLibraryVersion: "0.5.77",
11
11
  componentType: s,
12
12
  tags: a
13
13
  }),
14
14
  [s, a]
15
- ), m = !u.optOutAllAnalytics && d !== "development", E = { logEvent: x(
15
+ ), m = !d.optOutAllAnalytics && E !== "development", f = { logEvent: x(
16
16
  async (o) => {
17
17
  const n = {
18
- ...v,
19
- ...o.properties
20
- }, p = {
18
+ ...p,
19
+ ...o.properties,
20
+ ...c
21
+ }, l = {
21
22
  eventName: o.eventName,
22
23
  properties: n,
23
- userProperties: c
24
- }, f = ["modal_opened", "modal_closed"].includes(o.eventName);
25
- if (m && !f) {
24
+ userProperties: v
25
+ }, g = ["modal_opened", "modal_closed"].includes(o.eventName);
26
+ if (m && !g) {
26
27
  if ("conversation" in n && !n.conversation?.id) return;
27
- C(p, r, i);
28
+ b(l, r, i);
28
29
  }
29
- t.onEvent?.(p);
30
+ t.onEvent?.(l);
30
31
  },
31
- [m, t, r, i, c, v]
32
+ [
33
+ m,
34
+ t,
35
+ r,
36
+ i,
37
+ v,
38
+ p,
39
+ c
40
+ ]
32
41
  ) };
33
- return /* @__PURE__ */ g(l.Provider, { value: E, children: e });
34
- }, $ = () => {
35
- const e = P(l);
42
+ return /* @__PURE__ */ y(u.Provider, { value: f, children: e });
43
+ }, j = () => {
44
+ const e = C(u);
36
45
  if (!e)
37
46
  throw new Error("useBaseEvents must be used within a BaseEventsProvider");
38
47
  return e;
39
48
  };
40
49
  export {
41
- _ as BaseEventsProvider,
42
- $ as useBaseEvents
50
+ $ as BaseEventsProvider,
51
+ j as useBaseEvents
43
52
  };
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("react/jsx-runtime"),e=require("react"),y=require("../atoms/api/analytics/conversation.cjs"),x=require("./config-provider.cjs"),w=require("./conversation-provider.cjs"),j=require("./user-provider.cjs"),k=require("./base-events-provider.cjs"),U=require("../utils/generate-uid.cjs"),g=e.createContext(void 0),A=({children:s})=>{const{baseSettings:f}=x.useInkeepConfig(),{apiKey:l,analyticsApiBaseUrl:C,tags:d,privacyPreferences:{optOutAllAnalytics:i},env:a}=f,{userProperties:E}=j.useUser(),{logEvent:p}=k.useBaseEvents(),{conversation:c,setConversation:P}=w.useInkeepConversation(),v=e.useRef(c);e.useEffect(()=>{v.current=c},[c]);const u=e.useCallback(async t=>{const n=v.current,o=!i&&a!=="development";let r=Object.assign({},n,{messages:t});if(o){const h=await y.logConversation(n.id,{messages:t,tags:d,userProperties:E},l,C);h&&(r=h)}else r.id="conv_"+U.generateUid(16);return r},[C,l,d,E,i,a]),b={logEvent:e.useCallback(async(t,n)=>{let o=v.current;n&&(o=await u(n),P(o));const r={...t,properties:{conversation:o,...t.properties}};p(r)},[p,u,i,a]),logConversation:u};return q.jsx(g.Provider,{value:b,children:s})},O=()=>{const s=e.useContext(g);if(!s)throw new Error("useChatEvents must be used within a ChatEventsProvider");return s};exports.ChatEventsProvider=A;exports.useChatEvents=O;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("react/jsx-runtime"),e=require("react"),j=require("../atoms/api/analytics/conversation.cjs"),k=require("./config-provider.cjs"),R=require("./conversation-provider.cjs"),U=require("./user-provider.cjs"),A=require("./base-events-provider.cjs"),O=require("../utils/generate-uid.cjs"),b=e.createContext(void 0),S=({children:o})=>{const{baseSettings:q}=k.useInkeepConfig(),{apiKey:p,analyticsApiBaseUrl:E,tags:h,privacyPreferences:{optOutAllAnalytics:c},env:a,analyticsProperties:u}=q,{userProperties:f}=U.useUser(),{logEvent:g}=A.useBaseEvents(),{conversation:v,setConversation:x,chatId:l,setExternalChatId:P}=R.useInkeepConversation(),i=e.useRef(v),d=e.useRef(l);e.useEffect(()=>{i.current=v},[v]),e.useEffect(()=>{d.current=l},[l]);const C=e.useCallback(async r=>{const t=i.current;d.current&&(t.id="",P(void 0),d.current=void 0);const n=!c&&a!=="development";let s=Object.assign({},t,{messages:r});if(n){const y=await j.logConversation(t.id,{messages:r,tags:h,userProperties:f,properties:u},p,E);y&&(s=y)}else s.id="conv_"+O.generateUid(16);return s},[E,p,h,f,c,a,u,P]),w={logEvent:e.useCallback(async(r,t)=>{let n=i.current;t&&(n=await C(t),x(n),i.current=n);const s={...r,properties:{conversation:n,...r.properties}};g(s)},[g,C,c,a,u]),logConversation:C};return I.jsx(b.Provider,{value:w,children:o})},m=()=>{const o=e.useContext(b);if(!o)throw new Error("useChatEvents must be used within a ChatEventsProvider");return o};exports.ChatEventsProvider=S;exports.useChatEvents=m;
@@ -1,70 +1,85 @@
1
1
  "use client";
2
- import { jsx as y } from "react/jsx-runtime";
3
- import { useRef as w, useEffect as P, useCallback as d, createContext as b, useContext as k } from "react";
4
- import { logConversation as A } from "../atoms/api/analytics/conversation.js";
5
- import { useInkeepConfig as U } from "./config-provider.js";
6
- import { useInkeepConversation as j } from "./conversation-provider.js";
7
- import { useUser as B } from "./user-provider.js";
8
- import { useBaseEvents as I } from "./base-events-provider.js";
9
- import { generateUid as O } from "../utils/generate-uid.js";
10
- const E = b(void 0), F = ({ children: r }) => {
11
- const { baseSettings: h } = U(), {
12
- apiKey: u,
13
- analyticsApiBaseUrl: p,
14
- tags: l,
15
- privacyPreferences: { optOutAllAnalytics: s },
16
- env: i
17
- } = h, { userProperties: C } = B(), { logEvent: f } = I(), { conversation: a, setConversation: g } = j(), c = w(a);
18
- P(() => {
19
- c.current = a;
20
- }, [a]);
21
- const v = d(
22
- async (t) => {
23
- const e = c.current, n = !s && i !== "development";
24
- let o = Object.assign({}, e, { messages: t });
25
- if (n) {
26
- const m = await A(
27
- e.id,
2
+ import { jsx as A } from "react/jsx-runtime";
3
+ import { useRef as x, useEffect as y, useCallback as P, createContext as U, useContext as j } from "react";
4
+ import { logConversation as B } from "../atoms/api/analytics/conversation.js";
5
+ import { useInkeepConfig as O } from "./config-provider.js";
6
+ import { useInkeepConversation as K } from "./conversation-provider.js";
7
+ import { useUser as L } from "./user-provider.js";
8
+ import { useBaseEvents as R } from "./base-events-provider.js";
9
+ import { generateUid as S } from "../utils/generate-uid.js";
10
+ const w = U(void 0), M = ({ children: r }) => {
11
+ const { baseSettings: I } = O(), {
12
+ apiKey: C,
13
+ analyticsApiBaseUrl: d,
14
+ tags: f,
15
+ privacyPreferences: { optOutAllAnalytics: i },
16
+ env: a,
17
+ analyticsProperties: c
18
+ } = I, { userProperties: m } = L(), { logEvent: h } = R(), { conversation: v, setConversation: b, chatId: u, setExternalChatId: E } = K(), s = x(v), p = x(u);
19
+ y(() => {
20
+ s.current = v;
21
+ }, [v]), y(() => {
22
+ p.current = u;
23
+ }, [u]);
24
+ const l = P(
25
+ async (n) => {
26
+ const t = s.current;
27
+ p.current && (t.id = "", E(void 0), p.current = void 0);
28
+ const e = !i && a !== "development";
29
+ let o = Object.assign({}, t, { messages: n });
30
+ if (e) {
31
+ const g = await B(
32
+ t.id,
28
33
  {
29
- messages: t,
30
- tags: l,
31
- userProperties: C
34
+ messages: n,
35
+ tags: f,
36
+ userProperties: m,
37
+ properties: c
32
38
  },
33
- u,
34
- p
39
+ C,
40
+ d
35
41
  );
36
- m && (o = m);
42
+ g && (o = g);
37
43
  } else
38
- o.id = "conv_" + O(16);
44
+ o.id = "conv_" + S(16);
39
45
  return o;
40
46
  },
41
- [p, u, l, C, s, i]
42
- ), x = {
43
- logEvent: d(
44
- async (t, e) => {
45
- let n = c.current;
46
- e && (n = await v(e), g(n));
47
+ [
48
+ d,
49
+ C,
50
+ f,
51
+ m,
52
+ i,
53
+ a,
54
+ c,
55
+ E
56
+ ]
57
+ ), k = {
58
+ logEvent: P(
59
+ async (n, t) => {
60
+ let e = s.current;
61
+ t && (e = await l(t), b(e), s.current = e);
47
62
  const o = {
48
- ...t,
63
+ ...n,
49
64
  properties: {
50
- conversation: n,
51
- ...t.properties
65
+ conversation: e,
66
+ ...n.properties
52
67
  }
53
68
  };
54
- f(o);
69
+ h(o);
55
70
  },
56
- [f, v, s, i]
71
+ [h, l, i, a, c]
57
72
  ),
58
- logConversation: v
73
+ logConversation: l
59
74
  };
60
- return /* @__PURE__ */ y(E.Provider, { value: x, children: r });
61
- }, G = () => {
62
- const r = k(E);
75
+ return /* @__PURE__ */ A(w.Provider, { value: k, children: r });
76
+ }, N = () => {
77
+ const r = j(w);
63
78
  if (!r)
64
79
  throw new Error("useChatEvents must be used within a ChatEventsProvider");
65
80
  return r;
66
81
  };
67
82
  export {
68
- F as ChatEventsProvider,
69
- G as useChatEvents
83
+ M as ChatEventsProvider,
84
+ N as useChatEvents
70
85
  };
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react/jsx-runtime"),o=require("react"),h=require("./config-provider.cjs"),C="conversationId",l=o.createContext(null),S=({children:n})=>{const i=w(),{aiChatSettings:c}=h.useInkeepConfig(),t=c.chatId||i,s={id:"",messages:[]},[r,a]=o.useState(s),e=()=>{a(s)},u=o.useMemo(()=>({conversation:r,setConversation:a,chatId:t,resetConversation:e}),[r,t]);return p.jsx(l.Provider,{value:u,children:n})},f=()=>{const n=o.useContext(l);if(!n)throw new Error("useInkeepConversation must be used within an InkeepConversationProvider");return n};function w(){const[n,i]=o.useState(void 0),{aiChatSettings:c}=h.useInkeepConfig(),{shareChatUrlBasePath:t}=c;return o.useEffect(()=>{if(!t||typeof window>"u")return;const s=e=>e.endsWith("/")?e.slice(0,-1):e,r=()=>{const{origin:e,pathname:u,search:m}=window.location,d=new URL(t),I=s(u),P=s(d.pathname);if(e===d.origin&&I===P){const v=new URLSearchParams(m).get(C);v&&i(v)}};r();const a=()=>r();return window.addEventListener("popstate",a),()=>{window.removeEventListener("popstate",a)}},[t]),n}exports.InkeepConversationProvider=S;exports.SHARE_QUERY_PARAM=C;exports.useInkeepConversation=f;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react/jsx-runtime"),t=require("react"),C=require("./config-provider.cjs"),l="conversationId",I=t.createContext(null),f=({children:o})=>{const d=w(),{aiChatSettings:u}=C.useInkeepConfig(),n=u.chatId||d,[r,s]=t.useState(n);t.useEffect(()=>{s(n)},[n]);const a={id:"",messages:[]},[e,i]=t.useState(a),h=()=>{i(a),s(void 0)},c=t.useMemo(()=>({conversation:e,setConversation:i,chatId:r,resetConversation:h,setExternalChatId:s}),[e,r]);return p.jsx(I.Provider,{value:c,children:o})},S=()=>{const o=t.useContext(I);if(!o)throw new Error("useInkeepConversation must be used within an InkeepConversationProvider");return o};function w(){const[o,d]=t.useState(void 0),{aiChatSettings:u}=C.useInkeepConfig(),{shareChatUrlBasePath:n}=u;return t.useEffect(()=>{if(!n||typeof window>"u")return;const r=e=>e.endsWith("/")?e.slice(0,-1):e,s=()=>{const{origin:e,pathname:i,search:h}=window.location,c=new URL(n),m=r(i),P=r(c.pathname);if(e===c.origin&&m===P){const v=new URLSearchParams(h).get(l);v&&d(v)}};s();const a=()=>s();return window.addEventListener("popstate",a),()=>{window.removeEventListener("popstate",a)}},[n]),o}exports.InkeepConversationProvider=f;exports.SHARE_QUERY_PARAM=l;exports.useInkeepConversation=S;
@@ -1,49 +1,54 @@
1
1
  "use client";
2
- import { jsx as I } from "react/jsx-runtime";
3
- import { useState as u, useMemo as f, createContext as w, useContext as P, useEffect as S } from "react";
4
- import { useInkeepConfig as m } from "./config-provider.js";
5
- const g = "conversationId", v = w(null), z = ({ children: t }) => {
6
- const a = x(), { aiChatSettings: i } = m(), n = i.chatId || a, o = {
2
+ import { jsx as f } from "react/jsx-runtime";
3
+ import { useState as u, useEffect as m, useMemo as w, createContext as P, useContext as S } from "react";
4
+ import { useInkeepConfig as v } from "./config-provider.js";
5
+ const x = "conversationId", l = P(null), z = ({ children: n }) => {
6
+ const c = g(), { aiChatSettings: d } = v(), t = d.chatId || c, [s, o] = u(t);
7
+ m(() => {
8
+ o(t);
9
+ }, [t]);
10
+ const r = {
7
11
  id: "",
8
12
  messages: []
9
- }, [s, r] = u(o), e = () => {
10
- r(o);
11
- }, c = f(
13
+ }, [e, a] = u(r), h = () => {
14
+ a(r), o(void 0);
15
+ }, i = w(
12
16
  () => ({
13
- conversation: s,
14
- setConversation: r,
15
- chatId: n,
16
- resetConversation: e
17
+ conversation: e,
18
+ setConversation: a,
19
+ chatId: s,
20
+ resetConversation: h,
21
+ setExternalChatId: o
17
22
  }),
18
- [s, n]
23
+ [e, s]
19
24
  );
20
- return /* @__PURE__ */ I(v.Provider, { value: c, children: t });
25
+ return /* @__PURE__ */ f(l.Provider, { value: i, children: n });
21
26
  }, L = () => {
22
- const t = P(v);
23
- if (!t)
27
+ const n = S(l);
28
+ if (!n)
24
29
  throw new Error("useInkeepConversation must be used within an InkeepConversationProvider");
25
- return t;
30
+ return n;
26
31
  };
27
- function x() {
28
- const [t, a] = u(void 0), { aiChatSettings: i } = m(), { shareChatUrlBasePath: n } = i;
29
- return S(() => {
30
- if (!n || typeof window > "u") return;
31
- const o = (e) => e.endsWith("/") ? e.slice(0, -1) : e, s = () => {
32
- const { origin: e, pathname: c, search: C } = window.location, d = new URL(n), l = o(c), p = o(d.pathname);
33
- if (e === d.origin && l === p) {
34
- const h = new URLSearchParams(C).get(g);
35
- h && a(h);
32
+ function g() {
33
+ const [n, c] = u(void 0), { aiChatSettings: d } = v(), { shareChatUrlBasePath: t } = d;
34
+ return m(() => {
35
+ if (!t || typeof window > "u") return;
36
+ const s = (e) => e.endsWith("/") ? e.slice(0, -1) : e, o = () => {
37
+ const { origin: e, pathname: a, search: h } = window.location, i = new URL(t), I = s(a), p = s(i.pathname);
38
+ if (e === i.origin && I === p) {
39
+ const C = new URLSearchParams(h).get(x);
40
+ C && c(C);
36
41
  }
37
42
  };
38
- s();
39
- const r = () => s();
43
+ o();
44
+ const r = () => o();
40
45
  return window.addEventListener("popstate", r), () => {
41
46
  window.removeEventListener("popstate", r);
42
47
  };
43
- }, [n]), t;
48
+ }, [t]), n;
44
49
  }
45
50
  export {
46
51
  z as InkeepConversationProvider,
47
- g as SHARE_QUERY_PARAM,
52
+ x as SHARE_QUERY_PARAM,
48
53
  L as useInkeepConversation
49
54
  };
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("react/jsx-runtime"),n=require("react"),_=require("../atoms/api/analytics/feedback.cjs"),M=require("../components/embedded-chat/chat-provider.cjs"),l=require("../utils/misc.cjs"),S=require("./config-provider.cjs"),E=require("./conversation-provider.cjs"),j=require("./chat-events-provider.cjs"),I=require("./user-provider.cjs"),f=n.createContext(void 0);function R(){const{baseSettings:e}=S.useInkeepConfig(),{apiKey:s,analyticsApiBaseUrl:o}=e,[b,g]=n.useState(null),[F,p]=n.useState({}),{conversation:k}=E.useInkeepConversation(),{messages:c,selectedWorkflow:C}=M.useChat(),{userProperties:P}=I.useUser(),{logEvent:m}=j.useChatEvents(),r=n.useCallback(async(t,i,a=[])=>{const u=await _.submitFeedback({type:i,messageId:t,reasons:a,apiKey:s,apiUrl:o,userProperties:P});u&&p(d=>({...d,[t]:{type:u.type,reasons:u.reasons}}));const v=c.findIndex(d=>d.id===t),y=c[v],w={conversationId:k.id,question:l.getMessageContent(c[v-1]),answer:l.getMessageContent(y),messageId:t,reasons:a,workflowId:C?.id};m({eventName:i==="positive"?"assistant_positive_feedback_submitted":"assistant_negative_feedback_submitted",properties:w})},[c,k]),h=n.useCallback(async t=>{r(t,"positive")},[r]),q=n.useCallback(async(t,i)=>{const a=$(i);r(t,"negative",a)},[r]);return{feedback:F,currentFeedback:b,setCurrentFeedback:g,submitPositiveFeedback:h,submitNegativeFeedback:q}}const U=({children:e})=>{const s=R();return x.jsx(f.Provider,{value:s,children:e})},N=()=>{const e=n.useContext(f);if(!e)throw new Error("useFeedback must be used within a FeedbackProvider");return e};function $(e){const s=[];for(const o in e)e[o]==="on"&&s.push({label:o,details:e[`${o}:description`]||""});return s.length>0?s:[]}exports.FeedbackProvider=U;exports.useMessageFeedback=N;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("react/jsx-runtime"),n=require("react"),M=require("../atoms/api/analytics/feedback.cjs"),S=require("../components/embedded-chat/chat-provider.cjs"),l=require("../utils/misc.cjs"),E=require("./config-provider.cjs"),j=require("./conversation-provider.cjs"),I=require("./chat-events-provider.cjs"),R=require("./user-provider.cjs"),f=n.createContext(void 0);function U(){const{baseSettings:e}=E.useInkeepConfig(),{apiKey:s,analyticsApiBaseUrl:o,analyticsProperties:b}=e,[g,p]=n.useState(null),[F,P]=n.useState({}),{conversation:k}=j.useInkeepConversation(),{messages:r,selectedWorkflow:C}=S.useChat(),{userProperties:m}=R.useUser(),{logEvent:h}=I.useChatEvents(),c=n.useCallback(async(t,i,a=[])=>{const u=await M.submitFeedback({type:i,messageId:t,reasons:a,apiKey:s,apiUrl:o,userProperties:m,properties:b});u&&P(d=>({...d,[t]:{type:u.type,reasons:u.reasons}}));const v=r.findIndex(d=>d.id===t),w=r[v],x={conversationId:k.id,question:l.getMessageContent(r[v-1]),answer:l.getMessageContent(w),messageId:t,reasons:a,workflowId:C?.id};h({eventName:i==="positive"?"assistant_positive_feedback_submitted":"assistant_negative_feedback_submitted",properties:x})},[r,k]),q=n.useCallback(async t=>{c(t,"positive")},[c]),y=n.useCallback(async(t,i)=>{const a=A(i);c(t,"negative",a)},[c]);return{feedback:F,currentFeedback:g,setCurrentFeedback:p,submitPositiveFeedback:q,submitNegativeFeedback:y}}const N=({children:e})=>{const s=U();return _.jsx(f.Provider,{value:s,children:e})},$=()=>{const e=n.useContext(f);if(!e)throw new Error("useFeedback must be used within a FeedbackProvider");return e};function A(e){const s=[];for(const o in e)e[o]==="on"&&s.push({label:o,details:e[`${o}:description`]||""});return s.length>0?s:[]}exports.FeedbackProvider=N;exports.useMessageFeedback=$;
@@ -1,40 +1,41 @@
1
1
  "use client";
2
- import { jsx as E } from "react/jsx-runtime";
3
- import { createContext as I, useContext as U, useState as p, useCallback as u } from "react";
4
- import { submitFeedback as M } from "../atoms/api/analytics/feedback.js";
5
- import { useChat as N } from "../components/embedded-chat/chat-provider.js";
2
+ import { jsx as I } from "react/jsx-runtime";
3
+ import { createContext as U, useContext as M, useState as k, useCallback as u } from "react";
4
+ import { submitFeedback as N } from "../atoms/api/analytics/feedback.js";
5
+ import { useChat as S } from "../components/embedded-chat/chat-provider.js";
6
6
  import { getMessageContent as f } from "../utils/misc.js";
7
- import { useInkeepConfig as S } from "./config-provider.js";
8
- import { useInkeepConversation as j } from "./conversation-provider.js";
9
- import { useChatEvents as q } from "./chat-events-provider.js";
10
- import { useUser as A } from "./user-provider.js";
11
- const v = I(void 0);
12
- function B() {
13
- const { baseSettings: e } = S(), { apiKey: s, analyticsApiBaseUrl: o } = e, [b, l] = p(null), [F, g] = p({}), { conversation: m } = j(), { messages: n, selectedWorkflow: C } = N(), { userProperties: h } = A(), { logEvent: w } = q(), r = u(
7
+ import { useInkeepConfig as j } from "./config-provider.js";
8
+ import { useInkeepConversation as q } from "./conversation-provider.js";
9
+ import { useChatEvents as A } from "./chat-events-provider.js";
10
+ import { useUser as B } from "./user-provider.js";
11
+ const v = U(void 0);
12
+ function K() {
13
+ const { baseSettings: e } = j(), { apiKey: s, analyticsApiBaseUrl: o, analyticsProperties: b } = e, [l, F] = k(null), [g, C] = k({}), { conversation: m } = q(), { messages: n, selectedWorkflow: h } = S(), { userProperties: w } = B(), { logEvent: y } = A(), r = u(
14
14
  async (t, i, c = []) => {
15
- const a = await M({
15
+ const a = await N({
16
16
  type: i,
17
17
  messageId: t,
18
18
  reasons: c,
19
19
  apiKey: s,
20
20
  apiUrl: o,
21
- userProperties: h
21
+ userProperties: w,
22
+ properties: b
22
23
  });
23
- a && g((d) => ({
24
+ a && C((d) => ({
24
25
  ...d,
25
26
  [t]: { type: a.type, reasons: a.reasons }
26
27
  }));
27
- const k = n.findIndex((d) => d.id === t), P = n[k], _ = {
28
+ const p = n.findIndex((d) => d.id === t), _ = n[p], E = {
28
29
  conversationId: m.id,
29
- question: f(n[k - 1]),
30
- answer: f(P),
30
+ question: f(n[p - 1]),
31
+ answer: f(_),
31
32
  messageId: t,
32
33
  reasons: c,
33
- workflowId: C?.id
34
+ workflowId: h?.id
34
35
  };
35
- w({
36
+ y({
36
37
  eventName: i === "positive" ? "assistant_positive_feedback_submitted" : "assistant_negative_feedback_submitted",
37
- properties: _
38
+ properties: E
38
39
  });
39
40
  },
40
41
  [n, m]
@@ -43,31 +44,31 @@ function B() {
43
44
  r(t, "positive");
44
45
  },
45
46
  [r]
46
- ), y = u(
47
+ ), P = u(
47
48
  async (t, i) => {
48
- const c = K(i);
49
+ const c = R(i);
49
50
  r(t, "negative", c);
50
51
  },
51
52
  [r]
52
53
  );
53
54
  return {
54
- feedback: F,
55
- currentFeedback: b,
56
- setCurrentFeedback: l,
55
+ feedback: g,
56
+ currentFeedback: l,
57
+ setCurrentFeedback: F,
57
58
  submitPositiveFeedback: x,
58
- submitNegativeFeedback: y
59
+ submitNegativeFeedback: P
59
60
  };
60
61
  }
61
- const O = ({ children: e }) => {
62
- const s = B();
63
- return /* @__PURE__ */ E(v.Provider, { value: s, children: e });
64
- }, Q = () => {
65
- const e = U(v);
62
+ const Q = ({ children: e }) => {
63
+ const s = K();
64
+ return /* @__PURE__ */ I(v.Provider, { value: s, children: e });
65
+ }, T = () => {
66
+ const e = M(v);
66
67
  if (!e)
67
68
  throw new Error("useFeedback must be used within a FeedbackProvider");
68
69
  return e;
69
70
  };
70
- function K(e) {
71
+ function R(e) {
71
72
  const s = [];
72
73
  for (const o in e)
73
74
  e[o] === "on" && s.push({
@@ -77,6 +78,6 @@ function K(e) {
77
78
  return s.length > 0 ? s : [];
78
79
  }
79
80
  export {
80
- O as FeedbackProvider,
81
- Q as useMessageFeedback
81
+ Q as FeedbackProvider,
82
+ T as useMessageFeedback
82
83
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/cxkit-primitives",
3
- "version": "0.5.75",
3
+ "version": "0.5.77",
4
4
  "description": "",
5
5
  "license": "Inkeep, Inc. Customer License (IICL) v1.1",
6
6
  "homepage": "",
@@ -60,9 +60,9 @@
60
60
  "remark-gfm": "^4.0.1",
61
61
  "unist-util-visit": "^5.0.0",
62
62
  "use-sync-external-store": "^1.4.0",
63
- "@inkeep/cxkit-color-mode": "0.5.75",
64
- "@inkeep/cxkit-theme": "0.5.75",
65
- "@inkeep/cxkit-types": "0.5.75"
63
+ "@inkeep/cxkit-color-mode": "0.5.77",
64
+ "@inkeep/cxkit-theme": "0.5.77",
65
+ "@inkeep/cxkit-types": "0.5.77"
66
66
  },
67
67
  "devDependencies": {
68
68
  "@biomejs/biome": "1.9.4",