@omni-commerce/sdk 0.7.0 → 0.8.1

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,4 +1,4 @@
1
- "use strict";var OmniCommerceChat=(()=>{var y=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var S=(n,e)=>{for(var t in e)y(n,t,{get:e[t],enumerable:!0})},P=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of I(e))!A.call(n,o)&&o!==t&&y(n,o,{get:()=>e[o],enumerable:!(r=k(e,o))||r.enumerable});return n};var $=n=>P(y({},"__esModule",{value:!0}),n);var W={};S(W,{createOmniChatEmbed:()=>x,createOmniChatWidget:()=>C,getOmniChatEmbedCode:()=>O,getOmniChatEmbedUrl:()=>m,getOmniChatReactCode:()=>E});var L={chat:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z",close:"m6 6 12 12M6 18 18 6",collapse:"m6 9 6 6 6-6"};function f(n,e){let t=n.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let r=n.createElementNS("http://www.w3.org/2000/svg","path");return r.setAttribute("d",L[e]),t.append(r),t}var w=`
1
+ "use strict";var OmniCommerceChat=(()=>{var v=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var M=(r,e)=>{for(var t in e)v(r,t,{get:e[t],enumerable:!0})},N=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of F(e))!j.call(r,i)&&i!==t&&v(r,i,{get:()=>e[i],enumerable:!(o=U(e,i))||o.enumerable});return r};var B=r=>N(v({},"__esModule",{value:!0}),r);var J={};M(J,{createOmniChatEmbed:()=>I,createOmniChatWidget:()=>$,getOmniChatEmbedCode:()=>T,getOmniChatEmbedUrl:()=>f,getOmniChatReactCode:()=>W});function S(r,e){let t=JSON.stringify(r);if(typeof t!="string"||new TextEncoder().encode(t).length>e||/data:[^"\s]{0,100};base64,/i.test(t))throw new Error("Application data must be bounded JSON without base64 payloads.");return JSON.parse(t)}function P(r){let e=new Map;return async t=>{if(!(typeof t.requestId!="string"||t.requestId.length>200))try{if(t.type==="omni-chat:application-request"){let o=r.options.application;r.reply({type:"omni-chat:application-response",requestId:t.requestId,application:o?S({name:o.name,description:o.description,context:await o.getContext()??null,tools:Object.entries(r.options.frontendTools??{}).map(([i,l])=>({name:i,description:l.description,parameters:l.parameters}))},65536):void 0})}else if(t.type==="omni-chat:tool-request"){let o=t.toolName,i=t.toolCallId;if(typeof o!="string"||!/^app_[a-z][a-z0-9_]{0,59}$/.test(o)||typeof i!="string"||!i||i.length>200)throw new Error("Invalid application tool request.");let l=Object.hasOwn(r.options.frontendTools??{},o)?r.options.frontendTools?.[o]:void 0;if(!r.options.application||!l)throw new Error("This application action is unavailable.");let n=t.args;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid application action arguments.");let h=JSON.stringify({name:o,args:n}),c=e.get(i);if(c&&c.signature!==h)throw new Error("This tool call ID was already used.");let a=c?.result??Promise.resolve().then(()=>l.execute(n,{toolCallId:i,abortSignal:r.signal}));if(!c){if(e.size>=200)throw new Error("Start a new application chat.");e.set(i,{signature:h,result:a})}r.reply({type:"omni-chat:tool-response",requestId:t.requestId,toolCallId:i,result:S(await a??null,12e3)})}}catch(o){r.reply({type:t.type==="omni-chat:application-request"?"omni-chat:application-response":"omni-chat:tool-response",requestId:t.requestId,toolCallId:t.toolCallId,error:o instanceof Error?o.message:"The application action failed."})}}}var H={chat:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z",close:"m6 6 12 12M6 18 18 6",collapse:"m6 9 6 6 6-6"};function C(r,e){let t=r.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let o=r.createElementNS("http://www.w3.org/2000/svg","path");return o.setAttribute("d",H[e]),t.append(o),t}var q=`
2
2
  :host { all: initial; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color-scheme: light; }
3
3
  *, *::before, *::after { box-sizing: border-box; }
4
4
  button { font: inherit; cursor: pointer; -webkit-tap-highlight-color: transparent; }
@@ -49,16 +49,16 @@
49
49
  @keyframes omni-chat-enter { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }
50
50
  @media (max-width: 480px) { :host([data-presentation="floating"]) .panel { width: calc(100vw - 40px); border-radius: 18px; } }
51
51
  @media (prefers-reduced-motion: reduce) { .panel, :host([data-presentation="sidebar"]) .panel { animation: none; } .launcher { transition: none; } }
52
- `;var U=0;function C(n,e){m(e);let t=n.ownerDocument,r=t.createElement("div");r.setAttribute("data-omni-chat-widget",""),r.setAttribute("data-position",e.position??"right"),r.setAttribute("data-presentation",e.presentation??"floating");let o=r.attachShadow({mode:"open"}),c=t.createElement("style");c.textContent=w;let i=t.createElement("button"),s=t.createElement("section"),l=t.createElement("button"),p=t.createElement("div"),h,u=!1;Object.assign(r.style,{position:"fixed",bottom:"20px",[e.position??"right"]:"20px",zIndex:"2147483000"}),r.style.setProperty("--omni-launcher-bg",e.launcherBackground??"#2563eb"),r.style.setProperty("--omni-launcher-fg",e.launcherForeground??"#ffffff"),r.style.setProperty("--omni-panel-bg",e.panelBackground??"#ffffff"),r.style.setProperty("--omni-panel-fg",e.panelForeground??"#171717"),i.type=l.type="button",i.className="launcher";let d=t.createElement("span");d.className="label",d.textContent=e.launcherLabel??"Chat with us",i.append(f(t,"chat"),d),i.setAttribute("aria-expanded","false"),i.setAttribute("aria-label",d.textContent),s.hidden=!0,s.className="panel",s.setAttribute("role","region"),s.setAttribute("aria-label",e.title??"Assistant chat"),s.id=`omni-chat-widget-${++U}`,i.setAttribute("aria-controls",s.id),p.className="frame",l.className="close",l.setAttribute("aria-label","Close chat"),l.title="Close chat",l.append(f(t,"close"));let a=()=>{u||(s.hidden=!0,i.hidden=!1,i.setAttribute("aria-expanded","false"),i.setAttribute("aria-label",d.textContent),i.querySelector("svg")?.replaceWith(f(t,"chat")),i.focus())},b=()=>{u||(h??(h=x(p,{...e,onRequestClose:a})),h.iframe.style.minHeight="0",s.hidden=!1,i.hidden=e.presentation==="sidebar",i.setAttribute("aria-expanded","true"),i.setAttribute("aria-label","Close chat"),i.querySelector("svg")?.replaceWith(f(t,"collapse")),h.focus())};return i.addEventListener("click",()=>s.hidden?b():a()),l.addEventListener("click",a),o.addEventListener("keydown",v=>{v.key==="Escape"&&!s.hidden&&a()}),s.append(l,p),o.append(c,s,i),n.append(r),{open:b,close:a,destroy(){u=!0,h?.destroy(),r.remove()}}}var g=n=>JSON.stringify(n,null,2).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`);function O(n,e="widget"){let t=new URL(m(n)).origin,r={...n,baseUrl:t},o=`omni-chat-${n.deploymentId}`,c=e==="widget"?`OmniCommerceChat.createOmniChatWidget(document.body, ${g(r)});`:`OmniCommerceChat.createOmniChatEmbed(document.getElementById(${g(o)}), ${g(r)});`;return`${e==="inline"?`<div id="${o}" style="height:600px"></div>
52
+ `;async function L(r,e,t,o){let i=await r.fetch(`${e}/api/embed/${t}`,{credentials:"include",cache:"no-store",signal:o}),l=await i.json();if(!i.ok)throw new Error(l.error??"Could not load the chat design.");let n=l.design,h=/^#[0-9a-f]{6}$/i;if(!n||typeof n.title!="string"||!n.title.trim()||n.title.length>80||typeof n.launcherLabel!="string"||!n.launcherLabel.trim()||n.launcherLabel.length>60||!["left","right"].includes(n.position)||!["floating","sidebar"].includes(n.presentation)||!n.theme||![n.theme.primary,n.theme.primaryForeground,n.theme.background,n.theme.foreground].every(c=>typeof c=="string"&&h.test(c)))throw new Error("Invalid chat design response.");return{deploymentId:t,title:n.title,launcherLabel:n.launcherLabel,position:n.position,presentation:n.presentation,launcherBackground:n.theme.primary,launcherForeground:n.theme.primaryForeground,panelBackground:n.theme.background,panelForeground:n.theme.foreground}}var z=0;function $(r,e){let t=new URL(f(e)).origin,o=r.ownerDocument,i=o.defaultView;if(!i)throw new Error("A browser document is required to mount chat.");let l=new AbortController,n=o.createElement("div");n.setAttribute("data-omni-chat-widget","");let h=n.attachShadow({mode:"open"}),c=o.createElement("style");c.textContent=q;let a=o.createElement("button"),p=o.createElement("section"),u=o.createElement("button"),b=o.createElement("div"),d,s=!1,x=!1,E=!1,m=e;Object.assign(n.style,{position:"fixed",bottom:"20px",zIndex:"2147483000"}),a.type=u.type="button",a.className="launcher";let g=o.createElement("span");g.className="label",g.textContent=e.launcherLabel??"Chat with us",a.append(C(o,"chat"),g),a.setAttribute("aria-expanded","false"),a.setAttribute("aria-label",g.textContent),p.hidden=!0,p.className="panel",p.setAttribute("role","region"),p.setAttribute("aria-label",e.title??"Assistant chat"),p.id=`omni-chat-widget-${++z}`,a.setAttribute("aria-controls",p.id),b.className="frame",u.className="close",u.setAttribute("aria-label","Close chat"),u.title="Close chat",u.append(C(o,"close"));let O=()=>{s||(E=!1,p.hidden=!0,a.hidden=!1,a.setAttribute("aria-expanded","false"),a.setAttribute("aria-label",g.textContent),a.querySelector("svg")?.replaceWith(C(o,"chat")),a.focus())},k=()=>{if(!s){if(!x){E=!0;return}d??(d=I(b,{...m,onRequestClose:O})),d.iframe.style.minHeight="0",p.hidden=!1,a.hidden=m.presentation==="sidebar",a.setAttribute("aria-expanded","true"),a.setAttribute("aria-label","Close chat"),a.querySelector("svg")?.replaceWith(C(o,"collapse")),d.focus()}};a.addEventListener("click",()=>p.hidden?k():O()),u.addEventListener("click",O),h.addEventListener("keydown",y=>{y.key==="Escape"&&!p.hidden&&O()}),p.append(u,b),h.append(c,p,a);let A=L(i,t,e.deploymentId,l.signal).then(y=>{s||(m=Object.assign(y,Object.fromEntries(Object.entries(e).filter(([,R])=>R!==void 0))),n.dataset.position=m.position??"right",n.dataset.presentation=m.presentation??"floating",n.style.removeProperty("left"),n.style.removeProperty("right"),n.style.setProperty(m.position??"right","20px"),n.style.setProperty("--omni-launcher-bg",m.launcherBackground),n.style.setProperty("--omni-launcher-fg",m.launcherForeground),n.style.setProperty("--omni-panel-bg",m.panelBackground),n.style.setProperty("--omni-panel-fg",m.panelForeground),g.textContent=m.launcherLabel,a.setAttribute("aria-label",g.textContent),p.setAttribute("aria-label",m.title),x=!0,r.append(n),E&&k())});return A.catch(y=>{s||e.onError?.(y instanceof Error?y:new Error("Could not load chat."))}),{ready:A,open:k,close:O,destroy(){s=!0,l.abort(),d?.destroy(),n.remove()}}}var w=r=>JSON.stringify(r,null,2).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`);function T(r,e="widget"){let t=new URL(f(r)).origin,o={...r,baseUrl:t},i=`omni-chat-${r.deploymentId}`,l=e==="widget"?`OmniCommerceChat.createOmniChatWidget(document.body, ${w(o)});`:`OmniCommerceChat.createOmniChatEmbed(document.getElementById(${w(i)}), ${w(o)});`;return`${e==="inline"?`<div id="${i}" style="height:600px"></div>
53
53
  `:""}<script src="${t}/sdk/embed.global.js"><\/script>
54
54
  <script>
55
- ${c.replace(/\n/g,`
55
+ ${l.replace(/\n/g,`
56
56
  `)}
57
- <\/script>`}function E(n){let e=new URL(m(n)).origin;return`import { OmniProvider, OmniChat } from "@omni-commerce/sdk/react";
57
+ <\/script>`}function W(r){let e=new URL(f(r)).origin;return`import { OmniProvider, OmniChat } from "@omni-commerce/sdk/react";
58
58
 
59
- <OmniProvider deploymentId={${g(n.deploymentId)}}
60
- baseUrl={${g(e)}}${n.title?`
61
- title={${g(n.title)}}`:""}>
59
+ <OmniProvider deploymentId={${w(r.deploymentId)}}
60
+ baseUrl={${w(e)}}${r.title?`
61
+ title={${w(r.title)}}`:""}>
62
62
  <OmniChat style={{ height: 600 }} />
63
- </OmniProvider>`}function m(n,e){if(!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(n.deploymentId))throw new Error("A valid chat deployment ID is required.");let t=new URL(n.baseUrl??"https://omnicommerce.sg");if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1"].includes(t.hostname))||t.username||t.password||t.pathname!=="/"||t.search||t.hash)throw new Error("Chat baseUrl must be an HTTPS origin, or HTTP localhost.");let r=new URL(`/embed/${n.deploymentId}`,t.origin);return e&&r.searchParams.set("parentOrigin",new URL(e).origin),r.toString()}function x(n,e){let t=n.ownerDocument,r=t.defaultView;if(!r)throw new Error("A browser document is required to mount chat.");let o=t.createElement("iframe");o.src=m(e,r.location.origin),o.title=e.title??"OmniCommerce assistant",o.referrerPolicy="strict-origin-when-cross-origin",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),Object.assign(o.style,{width:"100%",height:"100%",minHeight:"320px",border:"0",display:"block"});let c=new URL(o.src).origin,i=!1,s,l,p=new AbortController,h=async()=>{if(e.getSession)return e.getSession();let d=await r.fetch(`${c}/api/embed/${e.deploymentId}/session`,{method:"POST",credentials:"include",signal:p.signal,headers:{"Content-Type":"application/json",...l?{Authorization:`Bearer ${l}`}:{}},body:"{}"}),a=await d.json();if(!d.ok)throw(d.status===401||d.status===403)&&(l=void 0),new Error(a.error??"Could not open the chat session.");return a},u=d=>{if(!(i||d.source!==o.contentWindow||d.origin!==c||d.data?.deploymentId!==e.deploymentId)){if(d.data.type==="omni-chat:close-request"){e.onRequestClose?.();return}d.data.type==="omni-chat:session-request"&&(s??(s=h()),s.then(a=>{if(!i){if(typeof a?.token!="string"||!a.token||a.token.length>4096||typeof a.threadId!="string"||!a.threadId||!Number.isFinite(a.expiresIn)||a.expiresIn<=0)throw new Error("Invalid chat session response.");l=a.token,o.contentWindow?.postMessage({type:"omni-chat:session",deploymentId:e.deploymentId,session:a},c)}}).catch(a=>{if(i)return;let b=a instanceof Error?a:new Error("Could not open chat.");e.onError?.(b),o.contentWindow?.postMessage({type:"omni-chat:session-error",deploymentId:e.deploymentId,error:b.message},c)}).finally(()=>{s=void 0}))}};return r.addEventListener("message",u),n.append(o),{iframe:o,focus(){i||(o.focus(),o.contentWindow?.postMessage({type:"omni-chat:focus-composer",deploymentId:e.deploymentId},c))},destroy(){i||(i=!0,p.abort(),l=void 0,r.removeEventListener("message",u),o.remove())}}}return $(W);})();
63
+ </OmniProvider>`}function f(r,e){if(!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(r.deploymentId))throw new Error("A valid chat deployment ID is required.");let t=new URL(r.baseUrl??"https://omnicommerce.sg");if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1"].includes(t.hostname))||t.username||t.password||t.pathname!=="/"||t.search||t.hash)throw new Error("Chat baseUrl must be an HTTPS origin, or HTTP localhost.");let o=new URL(`/embed/${r.deploymentId}`,t.origin);return e&&o.searchParams.set("parentOrigin",new URL(e).origin),o.toString()}function I(r,e){let t=r.ownerDocument,o=t.defaultView;if(!o)throw new Error("A browser document is required to mount chat.");let i=t.createElement("iframe");i.src=f(e,o.location.origin),i.title=e.title??"OmniCommerce assistant",i.referrerPolicy="strict-origin-when-cross-origin",i.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),Object.assign(i.style,{width:"100%",height:"100%",minHeight:"320px",border:"0",display:"block"});let l=new URL(i.src).origin,n=!1,h,c,a=new AbortController,p=async()=>{if(e.getSession)return e.getSession();let d=await o.fetch(`${l}/api/embed/${e.deploymentId}/session`,{method:"POST",credentials:"include",signal:a.signal,headers:{"Content-Type":"application/json",...c?{Authorization:`Bearer ${c}`}:{}},body:"{}"}),s=await d.json();if(!d.ok)throw(d.status===401||d.status===403)&&(c=void 0),new Error(s.error??"Could not open the chat session.");return s},u=P({options:e,signal:a.signal,reply:d=>{n||i.contentWindow?.postMessage({...d,deploymentId:e.deploymentId},l)}}),b=d=>{if(!(n||d.source!==i.contentWindow||d.origin!==l||d.data?.deploymentId!==e.deploymentId)){if(d.data.type==="omni-chat:application-request"||d.data.type==="omni-chat:tool-request"){u(d.data);return}if(d.data.type==="omni-chat:close-request"){e.onRequestClose?.();return}d.data.type==="omni-chat:session-request"&&(h??(h=p()),h.then(s=>{if(!n){if(typeof s?.token!="string"||!s.token||s.token.length>4096||typeof s.threadId!="string"||!s.threadId||!Number.isFinite(s.expiresIn)||s.expiresIn<=0)throw new Error("Invalid chat session response.");c=s.token,i.contentWindow?.postMessage({type:"omni-chat:session",deploymentId:e.deploymentId,session:s,...e.application?{applicationEnabled:!0}:{}},l)}}).catch(s=>{if(n)return;let x=s instanceof Error?s:new Error("Could not open chat.");e.onError?.(x),i.contentWindow?.postMessage({type:"omni-chat:session-error",deploymentId:e.deploymentId,error:x.message,...e.application?{applicationEnabled:!0}:{}},l)}).finally(()=>{h=void 0}))}};return o.addEventListener("message",b),r.append(i),{iframe:i,focus(){n||(i.focus(),i.contentWindow?.postMessage({type:"omni-chat:focus-composer",deploymentId:e.deploymentId},l))},destroy(){n||(n=!0,a.abort(),c=void 0,o.removeEventListener("message",b),i.remove())}}}return B(J);})();
64
64
  //# sourceMappingURL=embed.global.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/embed.ts","../src/widget-chrome.ts","../src/widget.ts","../src/embed-code.ts"],"sourcesContent":["/** A hosted chat session. Keep its short-lived token in memory, never in iframe URLs. */\nexport { createOmniChatWidget, type OmniChatWidgetOptions } from \"./widget\";\nexport { getOmniChatEmbedCode, getOmniChatReactCode } from \"./embed-code\";\nexport interface OmniChatSession {\n token: string;\n threadId: string;\n expiresIn: number;\n}\nexport interface OmniChatEmbedOptions {\n deploymentId: string;\n baseUrl?: string;\n /** Optional authenticated session mint on the host application's server. */\n getSession?: () => Promise<OmniChatSession>;\n title?: string;\n onError?: (error: Error) => void;\n /** Floating widgets use this to close on Escape from the hosted chat. */\n onRequestClose?: () => void;\n}\nexport interface OmniChatEmbed {\n iframe: HTMLIFrameElement;\n /** Focus the hosted composer, including when reopening a retained chat. */\n focus(): void;\n destroy(): void;\n}\n\nexport function getOmniChatEmbedUrl(\n options: Pick<OmniChatEmbedOptions, \"baseUrl\" | \"deploymentId\">,\n parentOrigin?: string,\n): string {\n if (\n !/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/i.test(\n options.deploymentId,\n )\n )\n throw new Error(\"A valid chat deployment ID is required.\");\n const base = new URL(options.baseUrl ?? \"https://omnicommerce.sg\");\n if (\n (base.protocol !== \"https:\" &&\n !(\n base.protocol === \"http:\" &&\n [\"localhost\", \"127.0.0.1\"].includes(base.hostname)\n )) ||\n base.username ||\n base.password ||\n base.pathname !== \"/\" ||\n base.search ||\n base.hash\n )\n throw new Error(\"Chat baseUrl must be an HTTPS origin, or HTTP localhost.\");\n const url = new URL(`/embed/${options.deploymentId}`, base.origin);\n if (parentOrigin)\n url.searchParams.set(\"parentOrigin\", new URL(parentOrigin).origin);\n return url.toString();\n}\n\n/** Browser-only mounting; importing this entry point is safe during SSR. */\nexport function createOmniChatEmbed(\n container: HTMLElement,\n options: OmniChatEmbedOptions,\n): OmniChatEmbed {\n const document = container.ownerDocument;\n const host = document.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const iframe = document.createElement(\"iframe\");\n iframe.src = getOmniChatEmbedUrl(options, host.location.origin);\n iframe.title = options.title ?? \"OmniCommerce assistant\";\n iframe.referrerPolicy = \"strict-origin-when-cross-origin\";\n iframe.setAttribute(\n \"sandbox\",\n \"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\",\n );\n Object.assign(iframe.style, {\n width: \"100%\",\n height: \"100%\",\n minHeight: \"320px\",\n border: \"0\",\n display: \"block\",\n });\n const chatOrigin = new URL(iframe.src).origin;\n let destroyed = false;\n let pending: Promise<OmniChatSession> | undefined;\n let previousToken: string | undefined;\n const controller = new AbortController();\n\n const mint = async (): Promise<OmniChatSession> => {\n if (options.getSession) return options.getSession();\n const response = await host.fetch(\n `${chatOrigin}/api/embed/${options.deploymentId}/session`,\n {\n method: \"POST\",\n credentials: \"include\",\n signal: controller.signal,\n headers: {\n \"Content-Type\": \"application/json\",\n ...(previousToken\n ? { Authorization: `Bearer ${previousToken}` }\n : {}),\n },\n body: \"{}\",\n },\n );\n const result = (await response.json()) as OmniChatSession & {\n error?: string;\n };\n if (!response.ok) {\n // A rejected renewal must not keep Retry bound to an obsolete session.\n // The next mint still performs the deployment's full access checks.\n if (response.status === 401 || response.status === 403)\n previousToken = undefined;\n throw new Error(result.error ?? \"Could not open the chat session.\");\n }\n return result;\n };\n const receive = (event: MessageEvent) => {\n if (\n destroyed ||\n event.source !== iframe.contentWindow ||\n event.origin !== chatOrigin ||\n event.data?.deploymentId !== options.deploymentId\n )\n return;\n if (event.data.type === \"omni-chat:close-request\") {\n options.onRequestClose?.();\n return;\n }\n if (event.data.type !== \"omni-chat:session-request\") return;\n pending ??= mint();\n void pending\n .then((session) => {\n if (destroyed) return;\n if (\n typeof session?.token !== \"string\" ||\n !session.token ||\n session.token.length > 4096 ||\n typeof session.threadId !== \"string\" ||\n !session.threadId ||\n !Number.isFinite(session.expiresIn) ||\n session.expiresIn <= 0\n )\n throw new Error(\"Invalid chat session response.\");\n previousToken = session.token;\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:session\",\n deploymentId: options.deploymentId,\n session,\n },\n chatOrigin,\n );\n })\n .catch((error: unknown) => {\n if (destroyed) return;\n const failure =\n error instanceof Error ? error : new Error(\"Could not open chat.\");\n options.onError?.(failure);\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:session-error\",\n deploymentId: options.deploymentId,\n error: failure.message,\n },\n chatOrigin,\n );\n })\n .finally(() => {\n pending = undefined;\n });\n };\n host.addEventListener(\"message\", receive);\n container.append(iframe);\n return {\n iframe,\n focus() {\n if (destroyed) return;\n iframe.focus();\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:focus-composer\",\n deploymentId: options.deploymentId,\n },\n chatOrigin,\n );\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n controller.abort();\n previousToken = undefined;\n host.removeEventListener(\"message\", receive);\n iframe.remove();\n },\n };\n}\n","const iconPaths = {\n chat: \"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z\",\n close: \"m6 6 12 12M6 18 18 6\",\n collapse: \"m6 9 6 6 6-6\",\n};\n\nexport function widgetIcon(document: Document, name: keyof typeof iconPaths) {\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"viewBox\", \"0 0 24 24\");\n svg.setAttribute(\"fill\", \"none\");\n svg.setAttribute(\"stroke\", \"currentColor\");\n svg.setAttribute(\"stroke-width\", \"1.8\");\n svg.setAttribute(\"stroke-linecap\", \"round\");\n svg.setAttribute(\"stroke-linejoin\", \"round\");\n svg.setAttribute(\"aria-hidden\", \"true\");\n const path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n path.setAttribute(\"d\", iconPaths[name]);\n svg.append(path);\n return svg;\n}\n\n/** Shadow DOM keeps a store's button, font and section CSS out of the widget. */\nexport const widgetStyles = `\n :host { all: initial; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; color-scheme: light; }\n *, *::before, *::after { box-sizing: border-box; }\n button { font: inherit; cursor: pointer; -webkit-tap-highlight-color: transparent; }\n button:focus-visible { outline: 3px solid var(--omni-launcher-bg); outline-offset: 4px; }\n svg { display: block; width: 22px; height: 22px; flex: none; }\n .launcher {\n display: flex; align-items: center; justify-content: center; gap: 10px;\n height: 52px; padding: 0 20px; border: 1px solid rgba(255,255,255,.14);\n border-radius: 999px; background: var(--omni-launcher-bg); color: var(--omni-launcher-fg);\n font-size: 14px; font-weight: 600; line-height: 1; letter-spacing: -.01em;\n box-shadow: 0 6px 24px rgba(0,0,0,.16), 0 2px 6px rgba(0,0,0,.08);\n transition: transform 160ms ease, box-shadow 160ms ease;\n margin-left: auto;\n }\n .launcher:hover { transform: translateY(-2px); box-shadow: 0 10px 28px rgba(0,0,0,.2); }\n .launcher[hidden] { display: none; }\n .launcher[aria-expanded=\"true\"] { width: 52px; padding: 0; }\n .launcher[aria-expanded=\"true\"] .label { display: none; }\n .panel {\n position: absolute; bottom: 66px; right: 0; width: min(392px, calc(100vw - 40px));\n overflow: hidden; border: 1px solid rgba(0,0,0,.08); border-radius: 20px;\n background: var(--omni-panel-bg); box-shadow: 0 24px 80px rgba(0,0,0,.18), 0 4px 16px rgba(0,0,0,.06);\n animation: omni-chat-enter 180ms ease-out;\n }\n .panel[hidden] { display: none; }\n .frame { height: min(780px, calc(100dvh - 112px)); min-height: 240px; }\n .close {\n position: absolute; z-index: 1; top: 18px; right: 14px;\n display: flex; align-items: center; justify-content: center; width: 34px; height: 34px;\n border: 1px solid color-mix(in srgb, var(--omni-panel-fg) 10%, transparent); border-radius: 50%;\n background: var(--omni-panel-bg); color: var(--omni-panel-fg); transition: background 160ms ease;\n }\n .close svg { width: 17px; height: 17px; }\n .close:hover { background: color-mix(in srgb, var(--omni-panel-fg) 6%, var(--omni-panel-bg)); }\n :host([data-position=\"left\"]) .panel { right: auto; left: 0; }\n :host([data-position=\"left\"]) .launcher { margin-left: 0; }\n :host([data-presentation=\"sidebar\"]) .panel {\n position: fixed; top: 0; bottom: 0; right: 0; left: auto;\n width: min(440px, 100vw); border-radius: 0; border-top: 0; border-bottom: 0;\n animation: omni-sidebar-enter 180ms ease-out;\n }\n :host([data-presentation=\"sidebar\"]) .frame { height: 100dvh; min-height: 0; }\n :host([data-presentation=\"sidebar\"][data-position=\"left\"]) .panel {\n right: auto; left: 0; animation-name: omni-sidebar-enter-left;\n }\n @keyframes omni-sidebar-enter { from { opacity: 0; transform: translateX(100%); } to { opacity: 1; transform: none; } }\n @keyframes omni-sidebar-enter-left { from { opacity: 0; transform: translateX(-100%); } to { opacity: 1; transform: none; } }\n @keyframes omni-chat-enter { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }\n @media (max-width: 480px) { :host([data-presentation=\"floating\"]) .panel { width: calc(100vw - 40px); border-radius: 18px; } }\n @media (prefers-reduced-motion: reduce) { .panel, :host([data-presentation=\"sidebar\"]) .panel { animation: none; } .launcher { transition: none; } }\n`;\n","import {\n createOmniChatEmbed,\n getOmniChatEmbedUrl,\n type OmniChatEmbedOptions,\n type OmniChatEmbed,\n} from \"./embed\";\nimport { widgetIcon, widgetStyles } from \"./widget-chrome\";\n\nexport type OmniChatWidgetOptions = OmniChatEmbedOptions & {\n /** Floating window by default; sidebar fills the viewport height. */\n presentation?: \"floating\" | \"sidebar\";\n launcherLabel?: string;\n position?: \"left\" | \"right\";\n launcherBackground?: string;\n launcherForeground?: string;\n panelBackground?: string;\n panelForeground?: string;\n};\nlet widgetSequence = 0;\n/** A website launcher using the same hosted assistant as OmniChat. */\nexport function createOmniChatWidget(\n container: HTMLElement,\n options: OmniChatWidgetOptions,\n) {\n getOmniChatEmbedUrl(options);\n const document = container.ownerDocument;\n const root = document.createElement(\"div\");\n root.setAttribute(\"data-omni-chat-widget\", \"\");\n root.setAttribute(\"data-position\", options.position ?? \"right\");\n root.setAttribute(\"data-presentation\", options.presentation ?? \"floating\");\n const shadow = root.attachShadow({ mode: \"open\" });\n const style = document.createElement(\"style\");\n style.textContent = widgetStyles;\n const launcher = document.createElement(\"button\");\n const panel = document.createElement(\"section\");\n const close = document.createElement(\"button\");\n const frame = document.createElement(\"div\");\n let embed: OmniChatEmbed | undefined;\n let destroyed = false;\n Object.assign(root.style, {\n position: \"fixed\",\n bottom: \"20px\",\n [options.position ?? \"right\"]: \"20px\",\n zIndex: \"2147483000\",\n });\n root.style.setProperty(\n \"--omni-launcher-bg\",\n options.launcherBackground ?? \"#2563eb\",\n );\n root.style.setProperty(\n \"--omni-launcher-fg\",\n options.launcherForeground ?? \"#ffffff\",\n );\n root.style.setProperty(\n \"--omni-panel-bg\",\n options.panelBackground ?? \"#ffffff\",\n );\n root.style.setProperty(\n \"--omni-panel-fg\",\n options.panelForeground ?? \"#171717\",\n );\n launcher.type = close.type = \"button\";\n launcher.className = \"launcher\";\n const label = document.createElement(\"span\");\n label.className = \"label\";\n label.textContent = options.launcherLabel ?? \"Chat with us\";\n launcher.append(widgetIcon(document, \"chat\"), label);\n launcher.setAttribute(\"aria-expanded\", \"false\");\n launcher.setAttribute(\"aria-label\", label.textContent);\n panel.hidden = true;\n panel.className = \"panel\";\n panel.setAttribute(\"role\", \"region\");\n panel.setAttribute(\"aria-label\", options.title ?? \"Assistant chat\");\n panel.id = `omni-chat-widget-${++widgetSequence}`;\n launcher.setAttribute(\"aria-controls\", panel.id);\n frame.className = \"frame\";\n close.className = \"close\";\n close.setAttribute(\"aria-label\", \"Close chat\");\n close.title = \"Close chat\";\n close.append(widgetIcon(document, \"close\"));\n const closeChat = () => {\n if (destroyed) return;\n panel.hidden = true;\n launcher.hidden = false;\n launcher.setAttribute(\"aria-expanded\", \"false\");\n launcher.setAttribute(\"aria-label\", label.textContent!);\n launcher.querySelector(\"svg\")?.replaceWith(widgetIcon(document, \"chat\"));\n launcher.focus();\n };\n const openChat = () => {\n if (destroyed) return;\n embed ??= createOmniChatEmbed(frame, {\n ...options,\n onRequestClose: closeChat,\n });\n embed.iframe.style.minHeight = \"0\";\n panel.hidden = false;\n launcher.hidden = options.presentation === \"sidebar\";\n launcher.setAttribute(\"aria-expanded\", \"true\");\n launcher.setAttribute(\"aria-label\", \"Close chat\");\n launcher\n .querySelector(\"svg\")\n ?.replaceWith(widgetIcon(document, \"collapse\"));\n embed.focus();\n };\n launcher.addEventListener(\"click\", () =>\n panel.hidden ? openChat() : closeChat(),\n );\n close.addEventListener(\"click\", closeChat);\n shadow.addEventListener(\"keydown\", (event) => {\n if ((event as KeyboardEvent).key === \"Escape\" && !panel.hidden) closeChat();\n });\n panel.append(close, frame);\n shadow.append(style, panel, launcher);\n container.append(root);\n return {\n open: openChat,\n close: closeChat,\n destroy() {\n destroyed = true;\n embed?.destroy();\n root.remove();\n },\n };\n}\n","import { getOmniChatEmbedUrl, type OmniChatEmbedOptions } from \"./embed\";\nimport type { OmniChatWidgetOptions } from \"./widget\";\n\ntype EmbedCodeOptions = Pick<\n OmniChatEmbedOptions,\n \"baseUrl\" | \"deploymentId\" | \"title\"\n> &\n Pick<\n OmniChatWidgetOptions,\n | \"presentation\"\n | \"launcherLabel\"\n | \"position\"\n | \"launcherBackground\"\n | \"launcherForeground\"\n | \"panelBackground\"\n | \"panelForeground\"\n >;\nconst scriptJson = (value: unknown) =>\n JSON.stringify(value, null, 2).replace(\n /[<>&\\u2028\\u2029]/g,\n (character) =>\n `\\\\u${character.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n\n/** Copyable integrations contain only public deployment configuration. */\nexport function getOmniChatEmbedCode(\n options: EmbedCodeOptions,\n mode: \"widget\" | \"inline\" = \"widget\",\n) {\n const baseUrl = new URL(getOmniChatEmbedUrl(options)).origin;\n const config = { ...options, baseUrl };\n const id = `omni-chat-${options.deploymentId}`;\n const mount =\n mode === \"widget\"\n ? `OmniCommerceChat.createOmniChatWidget(document.body, ${scriptJson(config)});`\n : `OmniCommerceChat.createOmniChatEmbed(document.getElementById(${scriptJson(id)}), ${scriptJson(config)});`;\n return `${mode === \"inline\" ? `<div id=\"${id}\" style=\"height:600px\"></div>\\n` : \"\"}<script src=\"${baseUrl}/sdk/embed.global.js\"></script>\\n<script>\\n ${mount.replace(/\\n/g, \"\\n \")}\\n</script>`;\n}\nexport function getOmniChatReactCode(options: EmbedCodeOptions) {\n const baseUrl = new URL(getOmniChatEmbedUrl(options)).origin;\n return `import { OmniProvider, OmniChat } from \"@omni-commerce/sdk/react\";\\n\\n<OmniProvider deploymentId={${scriptJson(options.deploymentId)}}\\n baseUrl={${scriptJson(baseUrl)}}${options.title ? `\\n title={${scriptJson(options.title)}}` : \"\"}>\\n <OmniChat style={{ height: 600 }} />\\n</OmniProvider>`;\n}\n"],"mappings":"ocAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,yBAAAE,EAAA,yBAAAC,EAAA,yBAAAC,EAAA,wBAAAC,EAAA,yBAAAC,ICAA,IAAMC,EAAY,CAChB,KAAM,2LACN,MAAO,uBACP,SAAU,cACZ,EAEO,SAASC,EAAWC,EAAoBC,EAA8B,CAC3E,IAAMC,EAAMF,EAAS,gBAAgB,6BAA8B,KAAK,EACxEE,EAAI,aAAa,UAAW,WAAW,EACvCA,EAAI,aAAa,OAAQ,MAAM,EAC/BA,EAAI,aAAa,SAAU,cAAc,EACzCA,EAAI,aAAa,eAAgB,KAAK,EACtCA,EAAI,aAAa,iBAAkB,OAAO,EAC1CA,EAAI,aAAa,kBAAmB,OAAO,EAC3CA,EAAI,aAAa,cAAe,MAAM,EACtC,IAAMC,EAAOH,EAAS,gBAAgB,6BAA8B,MAAM,EAC1E,O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GACL,EACA,OAAAJ,EAAK,iBAAiB,UAAWU,CAAO,EACxCZ,EAAU,OAAOG,CAAM,EAChB,CACL,OAAAA,EACA,OAAQ,CACFE,IACJF,EAAO,MAAM,EACbA,EAAO,eAAe,YACpB,CACE,KAAM,2BACN,aAAcR,EAAQ,YACxB,EACAS,CACF,EACF,EACA,SAAU,CACJC,IACJA,EAAY,GACZG,EAAW,MAAM,EACjBD,EAAgB,OAChBL,EAAK,oBAAoB,UAAWU,CAAO,EAC3CT,EAAO,OAAO,EAChB,CACF,CACF","names":["embed_exports","__export","createOmniChatEmbed","createOmniChatWidget","getOmniChatEmbedCode","getOmniChatEmbedUrl","getOmniChatReactCode","iconPaths","widgetIcon","document","name","svg","path","widgetStyles","widgetSequence","createOmniChatWidget","container","options","getOmniChatEmbedUrl","document","root","shadow","style","widgetStyles","launcher","panel","close","frame","embed","destroyed","label","widgetIcon","closeChat","openChat","createOmniChatEmbed","event","scriptJson","value","character","getOmniChatEmbedCode","options","mode","baseUrl","getOmniChatEmbedUrl","config","id","mount","getOmniChatReactCode","getOmniChatEmbedUrl","options","parentOrigin","base","url","createOmniChatEmbed","container","document","host","iframe","chatOrigin","destroyed","pending","previousToken","controller","mint","response","result","receive","event","session","error","failure"]}
1
+ {"version":3,"sources":["../src/embed.ts","../src/application.ts","../src/widget-chrome.ts","../src/widget-config.ts","../src/widget.ts","../src/embed-code.ts"],"sourcesContent":["import {\n createApplicationMessageHandler,\n type OmniApplicationOptions,\n} from \"./application\";\nexport type {\n OmniFrontendTool,\n OmniChatApplication,\n OmniApplicationOptions,\n} from \"./application\";\n/** A hosted chat session. Keep its short-lived token in memory, never in iframe URLs. */\nexport { createOmniChatWidget, type OmniChatWidgetOptions } from \"./widget\";\nexport { getOmniChatEmbedCode, getOmniChatReactCode } from \"./embed-code\";\nexport interface OmniChatSession {\n token: string;\n threadId: string;\n expiresIn: number;\n}\nexport interface OmniChatEmbedOptions extends OmniApplicationOptions {\n deploymentId: string;\n baseUrl?: string;\n /** Optional authenticated session mint on the host application's server. */\n getSession?: () => Promise<OmniChatSession>;\n title?: string;\n onError?: (error: Error) => void;\n /** Floating widgets use this to close on Escape from the hosted chat. */\n onRequestClose?: () => void;\n}\nexport interface OmniChatEmbed {\n iframe: HTMLIFrameElement;\n /** Focus the hosted composer, including when reopening a retained chat. */\n focus(): void;\n destroy(): void;\n}\n\nexport function getOmniChatEmbedUrl(\n options: Pick<OmniChatEmbedOptions, \"baseUrl\" | \"deploymentId\">,\n parentOrigin?: string,\n): string {\n if (\n !/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/i.test(\n options.deploymentId,\n )\n )\n throw new Error(\"A valid chat deployment ID is required.\");\n const base = new URL(options.baseUrl ?? \"https://omnicommerce.sg\");\n if (\n (base.protocol !== \"https:\" &&\n !(\n base.protocol === \"http:\" &&\n [\"localhost\", \"127.0.0.1\"].includes(base.hostname)\n )) ||\n base.username ||\n base.password ||\n base.pathname !== \"/\" ||\n base.search ||\n base.hash\n )\n throw new Error(\"Chat baseUrl must be an HTTPS origin, or HTTP localhost.\");\n const url = new URL(`/embed/${options.deploymentId}`, base.origin);\n if (parentOrigin)\n url.searchParams.set(\"parentOrigin\", new URL(parentOrigin).origin);\n return url.toString();\n}\n\n/** Browser-only mounting; importing this entry point is safe during SSR. */\nexport function createOmniChatEmbed(\n container: HTMLElement,\n options: OmniChatEmbedOptions,\n): OmniChatEmbed {\n const document = container.ownerDocument;\n const host = document.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const iframe = document.createElement(\"iframe\");\n iframe.src = getOmniChatEmbedUrl(options, host.location.origin);\n iframe.title = options.title ?? \"OmniCommerce assistant\";\n iframe.referrerPolicy = \"strict-origin-when-cross-origin\";\n iframe.setAttribute(\n \"sandbox\",\n \"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\",\n );\n Object.assign(iframe.style, {\n width: \"100%\",\n height: \"100%\",\n minHeight: \"320px\",\n border: \"0\",\n display: \"block\",\n });\n const chatOrigin = new URL(iframe.src).origin;\n let destroyed = false;\n let pending: Promise<OmniChatSession> | undefined;\n let previousToken: string | undefined;\n const controller = new AbortController();\n\n const mint = async (): Promise<OmniChatSession> => {\n if (options.getSession) return options.getSession();\n const response = await host.fetch(\n `${chatOrigin}/api/embed/${options.deploymentId}/session`,\n {\n method: \"POST\",\n credentials: \"include\",\n signal: controller.signal,\n headers: {\n \"Content-Type\": \"application/json\",\n ...(previousToken\n ? { Authorization: `Bearer ${previousToken}` }\n : {}),\n },\n body: \"{}\",\n },\n );\n const result = (await response.json()) as OmniChatSession & {\n error?: string;\n };\n if (!response.ok) {\n // A rejected renewal must not keep Retry bound to an obsolete session.\n // The next mint still performs the deployment's full access checks.\n if (response.status === 401 || response.status === 403)\n previousToken = undefined;\n throw new Error(result.error ?? \"Could not open the chat session.\");\n }\n return result;\n };\n const applicationMessage = createApplicationMessageHandler({\n options,\n signal: controller.signal,\n reply: (message) => {\n if (!destroyed)\n iframe.contentWindow?.postMessage(\n { ...message, deploymentId: options.deploymentId },\n chatOrigin,\n );\n },\n });\n const receive = (event: MessageEvent) => {\n if (\n destroyed ||\n event.source !== iframe.contentWindow ||\n event.origin !== chatOrigin ||\n event.data?.deploymentId !== options.deploymentId\n )\n return;\n if (\n event.data.type === \"omni-chat:application-request\" ||\n event.data.type === \"omni-chat:tool-request\"\n ) {\n void applicationMessage(event.data);\n return;\n }\n if (event.data.type === \"omni-chat:close-request\") {\n options.onRequestClose?.();\n return;\n }\n if (event.data.type !== \"omni-chat:session-request\") return;\n pending ??= mint();\n void pending\n .then((session) => {\n if (destroyed) return;\n if (\n typeof session?.token !== \"string\" ||\n !session.token ||\n session.token.length > 4096 ||\n typeof session.threadId !== \"string\" ||\n !session.threadId ||\n !Number.isFinite(session.expiresIn) ||\n session.expiresIn <= 0\n )\n throw new Error(\"Invalid chat session response.\");\n previousToken = session.token;\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:session\",\n deploymentId: options.deploymentId,\n session,\n ...(options.application ? { applicationEnabled: true } : {}),\n },\n chatOrigin,\n );\n })\n .catch((error: unknown) => {\n if (destroyed) return;\n const failure =\n error instanceof Error ? error : new Error(\"Could not open chat.\");\n options.onError?.(failure);\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:session-error\",\n deploymentId: options.deploymentId,\n error: failure.message,\n ...(options.application ? { applicationEnabled: true } : {}),\n },\n chatOrigin,\n );\n })\n .finally(() => {\n pending = undefined;\n });\n };\n host.addEventListener(\"message\", receive);\n container.append(iframe);\n return {\n iframe,\n focus() {\n if (destroyed) return;\n iframe.focus();\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:focus-composer\",\n deploymentId: options.deploymentId,\n },\n chatOrigin,\n );\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n controller.abort();\n previousToken = undefined;\n host.removeEventListener(\"message\", receive);\n iframe.remove();\n },\n };\n}\n","/** Host-defined actions execute inside the application, never on the assistant server. */\nexport interface OmniFrontendTool {\n description: string;\n parameters: Record<string, unknown>;\n execute: (\n args: Record<string, unknown>,\n context: { toolCallId: string; abortSignal: AbortSignal },\n ) => unknown | Promise<unknown>;\n}\nexport interface OmniChatApplication {\n name: string;\n description: string;\n /** Return a small, explicitly selected snapshot. Do not include secrets. */\n getContext: () => unknown | Promise<unknown>;\n}\nexport interface OmniApplicationOptions {\n application?: OmniChatApplication;\n /** Names must start with app_; use array arguments for actions with multiple targets. */\n frontendTools?: Record<string, OmniFrontendTool>;\n}\n\nfunction boundedJson(value: unknown, maximum: number): unknown {\n const encoded = JSON.stringify(value);\n if (\n typeof encoded !== \"string\" ||\n new TextEncoder().encode(encoded).length > maximum ||\n /data:[^\"\\s]{0,100};base64,/i.test(encoded)\n )\n throw new Error(\n \"Application data must be bounded JSON without base64 payloads.\",\n );\n return JSON.parse(encoded);\n}\n\nexport function createApplicationMessageHandler(input: {\n options: OmniApplicationOptions;\n signal: AbortSignal;\n reply: (message: Record<string, unknown>) => void;\n}) {\n // A repeated parked call reuses its result instead of applying an action twice.\n const calls = new Map<\n string,\n { signature: string; result: Promise<unknown> }\n >();\n return async (message: Record<string, unknown>) => {\n if (typeof message.requestId !== \"string\" || message.requestId.length > 200)\n return;\n try {\n if (message.type === \"omni-chat:application-request\") {\n const application = input.options.application;\n input.reply({\n type: \"omni-chat:application-response\",\n requestId: message.requestId,\n application: application\n ? boundedJson(\n {\n name: application.name,\n description: application.description,\n context: (await application.getContext()) ?? null,\n tools: Object.entries(input.options.frontendTools ?? {}).map(\n ([name, definition]) => ({\n name,\n description: definition.description,\n parameters: definition.parameters,\n }),\n ),\n },\n 65536,\n )\n : undefined,\n });\n } else if (message.type === \"omni-chat:tool-request\") {\n const name = message.toolName;\n const toolCallId = message.toolCallId;\n if (\n typeof name !== \"string\" ||\n !/^app_[a-z][a-z0-9_]{0,59}$/.test(name) ||\n typeof toolCallId !== \"string\" ||\n !toolCallId ||\n toolCallId.length > 200\n )\n throw new Error(\"Invalid application tool request.\");\n const definition = Object.hasOwn(\n input.options.frontendTools ?? {},\n name,\n )\n ? input.options.frontendTools?.[name]\n : undefined;\n if (!input.options.application || !definition)\n throw new Error(\"This application action is unavailable.\");\n const args = message.args;\n if (!args || typeof args !== \"object\" || Array.isArray(args))\n throw new Error(\"Invalid application action arguments.\");\n const signature = JSON.stringify({ name, args });\n const prior = calls.get(toolCallId);\n if (prior && prior.signature !== signature)\n throw new Error(\"This tool call ID was already used.\");\n const result =\n prior?.result ??\n Promise.resolve().then(() =>\n definition.execute(args as Record<string, unknown>, {\n toolCallId,\n abortSignal: input.signal,\n }),\n );\n if (!prior) {\n if (calls.size >= 200)\n throw new Error(\"Start a new application chat.\");\n calls.set(toolCallId, { signature, result });\n }\n input.reply({\n type: \"omni-chat:tool-response\",\n requestId: message.requestId,\n toolCallId,\n result: boundedJson((await result) ?? null, 12000),\n });\n }\n } catch (error) {\n input.reply({\n type:\n message.type === \"omni-chat:application-request\"\n ? \"omni-chat:application-response\"\n : \"omni-chat:tool-response\",\n requestId: message.requestId,\n toolCallId: message.toolCallId,\n error:\n error instanceof Error\n ? error.message\n : \"The application action failed.\",\n });\n }\n };\n}\n","const iconPaths = {\n chat: \"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z\",\n close: \"m6 6 12 12M6 18 18 6\",\n collapse: \"m6 9 6 6 6-6\",\n};\n\nexport function widgetIcon(document: Document, name: keyof typeof iconPaths) {\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"viewBox\", \"0 0 24 24\");\n svg.setAttribute(\"fill\", \"none\");\n svg.setAttribute(\"stroke\", \"currentColor\");\n svg.setAttribute(\"stroke-width\", \"1.8\");\n svg.setAttribute(\"stroke-linecap\", \"round\");\n svg.setAttribute(\"stroke-linejoin\", \"round\");\n svg.setAttribute(\"aria-hidden\", \"true\");\n const path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n path.setAttribute(\"d\", iconPaths[name]);\n svg.append(path);\n return svg;\n}\n\n/** Shadow DOM keeps a store's button, font and section CSS out of the widget. */\nexport const widgetStyles = `\n :host { all: initial; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; color-scheme: light; }\n *, *::before, *::after { box-sizing: border-box; }\n button { font: inherit; cursor: pointer; -webkit-tap-highlight-color: transparent; }\n button:focus-visible { outline: 3px solid var(--omni-launcher-bg); outline-offset: 4px; }\n svg { display: block; width: 22px; height: 22px; flex: none; }\n .launcher {\n display: flex; align-items: center; justify-content: center; gap: 10px;\n height: 52px; padding: 0 20px; border: 1px solid rgba(255,255,255,.14);\n border-radius: 999px; background: var(--omni-launcher-bg); color: var(--omni-launcher-fg);\n font-size: 14px; font-weight: 600; line-height: 1; letter-spacing: -.01em;\n box-shadow: 0 6px 24px rgba(0,0,0,.16), 0 2px 6px rgba(0,0,0,.08);\n transition: transform 160ms ease, box-shadow 160ms ease;\n margin-left: auto;\n }\n .launcher:hover { transform: translateY(-2px); box-shadow: 0 10px 28px rgba(0,0,0,.2); }\n .launcher[hidden] { display: none; }\n .launcher[aria-expanded=\"true\"] { width: 52px; padding: 0; }\n .launcher[aria-expanded=\"true\"] .label { display: none; }\n .panel {\n position: absolute; bottom: 66px; right: 0; width: min(392px, calc(100vw - 40px));\n overflow: hidden; border: 1px solid rgba(0,0,0,.08); border-radius: 20px;\n background: var(--omni-panel-bg); box-shadow: 0 24px 80px rgba(0,0,0,.18), 0 4px 16px rgba(0,0,0,.06);\n animation: omni-chat-enter 180ms ease-out;\n }\n .panel[hidden] { display: none; }\n .frame { height: min(780px, calc(100dvh - 112px)); min-height: 240px; }\n .close {\n position: absolute; z-index: 1; top: 18px; right: 14px;\n display: flex; align-items: center; justify-content: center; width: 34px; height: 34px;\n border: 1px solid color-mix(in srgb, var(--omni-panel-fg) 10%, transparent); border-radius: 50%;\n background: var(--omni-panel-bg); color: var(--omni-panel-fg); transition: background 160ms ease;\n }\n .close svg { width: 17px; height: 17px; }\n .close:hover { background: color-mix(in srgb, var(--omni-panel-fg) 6%, var(--omni-panel-bg)); }\n :host([data-position=\"left\"]) .panel { right: auto; left: 0; }\n :host([data-position=\"left\"]) .launcher { margin-left: 0; }\n :host([data-presentation=\"sidebar\"]) .panel {\n position: fixed; top: 0; bottom: 0; right: 0; left: auto;\n width: min(440px, 100vw); border-radius: 0; border-top: 0; border-bottom: 0;\n animation: omni-sidebar-enter 180ms ease-out;\n }\n :host([data-presentation=\"sidebar\"]) .frame { height: 100dvh; min-height: 0; }\n :host([data-presentation=\"sidebar\"][data-position=\"left\"]) .panel {\n right: auto; left: 0; animation-name: omni-sidebar-enter-left;\n }\n @keyframes omni-sidebar-enter { from { opacity: 0; transform: translateX(100%); } to { opacity: 1; transform: none; } }\n @keyframes omni-sidebar-enter-left { from { opacity: 0; transform: translateX(-100%); } to { opacity: 1; transform: none; } }\n @keyframes omni-chat-enter { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }\n @media (max-width: 480px) { :host([data-presentation=\"floating\"]) .panel { width: calc(100vw - 40px); border-radius: 18px; } }\n @media (prefers-reduced-motion: reduce) { .panel, :host([data-presentation=\"sidebar\"]) .panel { animation: none; } .launcher { transition: none; } }\n`;\n","import type { OmniChatWidgetOptions } from \"./widget\";\n\n/** Only public appearance is loaded here; agent settings remain on the server. */\nexport async function loadWidgetConfiguration(\n host: Window,\n origin: string,\n deploymentId: string,\n signal: AbortSignal,\n): Promise<OmniChatWidgetOptions> {\n const response = await host.fetch(`${origin}/api/embed/${deploymentId}`, {\n credentials: \"include\",\n cache: \"no-store\",\n signal,\n });\n const result = await response.json();\n if (!response.ok)\n throw new Error(result.error ?? \"Could not load the chat design.\");\n const design = result.design;\n const color = /^#[0-9a-f]{6}$/i;\n if (\n !design ||\n typeof design.title !== \"string\" ||\n !design.title.trim() ||\n design.title.length > 80 ||\n typeof design.launcherLabel !== \"string\" ||\n !design.launcherLabel.trim() ||\n design.launcherLabel.length > 60 ||\n ![\"left\", \"right\"].includes(design.position) ||\n ![\"floating\", \"sidebar\"].includes(design.presentation) ||\n !design.theme ||\n ![\n design.theme.primary,\n design.theme.primaryForeground,\n design.theme.background,\n design.theme.foreground,\n ].every((value) => typeof value === \"string\" && color.test(value))\n )\n throw new Error(\"Invalid chat design response.\");\n return {\n deploymentId,\n title: design.title,\n launcherLabel: design.launcherLabel,\n position: design.position,\n presentation: design.presentation,\n launcherBackground: design.theme.primary,\n launcherForeground: design.theme.primaryForeground,\n panelBackground: design.theme.background,\n panelForeground: design.theme.foreground,\n };\n}\n","import {\n createOmniChatEmbed,\n getOmniChatEmbedUrl,\n type OmniChatEmbedOptions,\n type OmniChatEmbed,\n} from \"./embed\";\nimport { widgetIcon, widgetStyles } from \"./widget-chrome\";\nimport { loadWidgetConfiguration } from \"./widget-config\";\n\nexport type OmniChatWidgetOptions = OmniChatEmbedOptions & {\n /** Floating window by default; sidebar fills the viewport height. */\n presentation?: \"floating\" | \"sidebar\";\n launcherLabel?: string;\n position?: \"left\" | \"right\";\n launcherBackground?: string;\n launcherForeground?: string;\n panelBackground?: string;\n panelForeground?: string;\n};\nlet widgetSequence = 0;\n/** Loads saved appearance by deployment ID. Explicit options override saved appearance. */\nexport function createOmniChatWidget(\n container: HTMLElement,\n options: OmniChatWidgetOptions,\n) {\n const origin = new URL(getOmniChatEmbedUrl(options)).origin;\n const document = container.ownerDocument;\n const host = document.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const controller = new AbortController();\n const root = document.createElement(\"div\");\n root.setAttribute(\"data-omni-chat-widget\", \"\");\n const shadow = root.attachShadow({ mode: \"open\" });\n const style = document.createElement(\"style\");\n style.textContent = widgetStyles;\n const launcher = document.createElement(\"button\");\n const panel = document.createElement(\"section\");\n const close = document.createElement(\"button\");\n const frame = document.createElement(\"div\");\n let embed: OmniChatEmbed | undefined;\n let destroyed = false;\n let loaded = false;\n let openRequested = false;\n let appearance = options;\n Object.assign(root.style, {\n position: \"fixed\",\n bottom: \"20px\",\n zIndex: \"2147483000\",\n });\n launcher.type = close.type = \"button\";\n launcher.className = \"launcher\";\n const label = document.createElement(\"span\");\n label.className = \"label\";\n label.textContent = options.launcherLabel ?? \"Chat with us\";\n launcher.append(widgetIcon(document, \"chat\"), label);\n launcher.setAttribute(\"aria-expanded\", \"false\");\n launcher.setAttribute(\"aria-label\", label.textContent);\n panel.hidden = true;\n panel.className = \"panel\";\n panel.setAttribute(\"role\", \"region\");\n panel.setAttribute(\"aria-label\", options.title ?? \"Assistant chat\");\n panel.id = `omni-chat-widget-${++widgetSequence}`;\n launcher.setAttribute(\"aria-controls\", panel.id);\n frame.className = \"frame\";\n close.className = \"close\";\n close.setAttribute(\"aria-label\", \"Close chat\");\n close.title = \"Close chat\";\n close.append(widgetIcon(document, \"close\"));\n const closeChat = () => {\n if (destroyed) return;\n openRequested = false;\n panel.hidden = true;\n launcher.hidden = false;\n launcher.setAttribute(\"aria-expanded\", \"false\");\n launcher.setAttribute(\"aria-label\", label.textContent!);\n launcher.querySelector(\"svg\")?.replaceWith(widgetIcon(document, \"chat\"));\n launcher.focus();\n };\n const openChat = () => {\n if (destroyed) return;\n if (!loaded) {\n openRequested = true;\n return;\n }\n embed ??= createOmniChatEmbed(frame, {\n ...appearance,\n onRequestClose: closeChat,\n });\n embed.iframe.style.minHeight = \"0\";\n panel.hidden = false;\n launcher.hidden = appearance.presentation === \"sidebar\";\n launcher.setAttribute(\"aria-expanded\", \"true\");\n launcher.setAttribute(\"aria-label\", \"Close chat\");\n launcher\n .querySelector(\"svg\")\n ?.replaceWith(widgetIcon(document, \"collapse\"));\n embed.focus();\n };\n launcher.addEventListener(\"click\", () =>\n panel.hidden ? openChat() : closeChat(),\n );\n close.addEventListener(\"click\", closeChat);\n shadow.addEventListener(\"keydown\", (event) => {\n if ((event as KeyboardEvent).key === \"Escape\" && !panel.hidden) closeChat();\n });\n panel.append(close, frame);\n shadow.append(style, panel, launcher);\n const ready = loadWidgetConfiguration(\n host,\n origin,\n options.deploymentId,\n controller.signal,\n ).then((configuration) => {\n if (destroyed) return;\n appearance = Object.assign(\n configuration,\n Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined),\n ),\n );\n root.dataset.position = appearance.position ?? \"right\";\n root.dataset.presentation = appearance.presentation ?? \"floating\";\n root.style.removeProperty(\"left\");\n root.style.removeProperty(\"right\");\n root.style.setProperty(appearance.position ?? \"right\", \"20px\");\n root.style.setProperty(\n \"--omni-launcher-bg\",\n appearance.launcherBackground!,\n );\n root.style.setProperty(\n \"--omni-launcher-fg\",\n appearance.launcherForeground!,\n );\n root.style.setProperty(\"--omni-panel-bg\", appearance.panelBackground!);\n root.style.setProperty(\"--omni-panel-fg\", appearance.panelForeground!);\n label.textContent = appearance.launcherLabel!;\n launcher.setAttribute(\"aria-label\", label.textContent);\n panel.setAttribute(\"aria-label\", appearance.title!);\n loaded = true;\n container.append(root);\n if (openRequested) openChat();\n });\n void ready.catch((error: unknown) => {\n if (!destroyed)\n options.onError?.(\n error instanceof Error ? error : new Error(\"Could not load chat.\"),\n );\n });\n return {\n /** Resolves once saved appearance is loaded and the launcher is mounted. */\n ready,\n open: openChat,\n close: closeChat,\n destroy() {\n destroyed = true;\n controller.abort();\n embed?.destroy();\n root.remove();\n },\n };\n}\n","import { getOmniChatEmbedUrl, type OmniChatEmbedOptions } from \"./embed\";\nimport type { OmniChatWidgetOptions } from \"./widget\";\n\ntype EmbedCodeOptions = Pick<\n OmniChatEmbedOptions,\n \"baseUrl\" | \"deploymentId\" | \"title\"\n> &\n Pick<\n OmniChatWidgetOptions,\n | \"presentation\"\n | \"launcherLabel\"\n | \"position\"\n | \"launcherBackground\"\n | \"launcherForeground\"\n | \"panelBackground\"\n | \"panelForeground\"\n >;\nconst scriptJson = (value: unknown) =>\n JSON.stringify(value, null, 2).replace(\n /[<>&\\u2028\\u2029]/g,\n (character) =>\n `\\\\u${character.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n\n/** Copyable integrations contain only public deployment configuration. */\nexport function getOmniChatEmbedCode(\n options: EmbedCodeOptions,\n mode: \"widget\" | \"inline\" = \"widget\",\n) {\n const baseUrl = new URL(getOmniChatEmbedUrl(options)).origin;\n const config = { ...options, baseUrl };\n const id = `omni-chat-${options.deploymentId}`;\n const mount =\n mode === \"widget\"\n ? `OmniCommerceChat.createOmniChatWidget(document.body, ${scriptJson(config)});`\n : `OmniCommerceChat.createOmniChatEmbed(document.getElementById(${scriptJson(id)}), ${scriptJson(config)});`;\n return `${mode === \"inline\" ? `<div id=\"${id}\" style=\"height:600px\"></div>\\n` : \"\"}<script src=\"${baseUrl}/sdk/embed.global.js\"></script>\\n<script>\\n ${mount.replace(/\\n/g, \"\\n \")}\\n</script>`;\n}\nexport function getOmniChatReactCode(options: EmbedCodeOptions) {\n const baseUrl = new URL(getOmniChatEmbedUrl(options)).origin;\n return `import { OmniProvider, OmniChat } from \"@omni-commerce/sdk/react\";\\n\\n<OmniProvider deploymentId={${scriptJson(options.deploymentId)}}\\n baseUrl={${scriptJson(baseUrl)}}${options.title ? `\\n title={${scriptJson(options.title)}}` : \"\"}>\\n <OmniChat style={{ height: 600 }} />\\n</OmniProvider>`;\n}\n"],"mappings":"ocAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,yBAAAE,EAAA,yBAAAC,EAAA,yBAAAC,EAAA,wBAAAC,EAAA,yBAAAC,ICqBA,SAASC,EAAYC,EAAgBC,EAA0B,CAC7D,IAAMC,EAAU,KAAK,UAAUF,CAAK,EACpC,GACE,OAAOE,GAAY,UACnB,IAAI,YAAY,EAAE,OAAOA,CAAO,EAAE,OAASD,GAC3C,8BAA8B,KAAKC,CAAO,EAE1C,MAAM,IAAI,MACR,gEACF,EACF,OAAO,KAAK,MAAMA,CAAO,CAC3B,CAEO,SAASC,EAAgCC,EAI7C,CAED,IAAMC,EAAQ,IAAI,IAIlB,MAAO,OAAOC,GAAqC,CACjD,GAAI,SAAOA,EAAQ,WAAc,UAAYA,EAAQ,UAAU,OAAS,KAExE,GAAI,CACF,GAAIA,EAAQ,OAAS,gCAAiC,CACpD,IAAMC,EAAcH,EAAM,QAAQ,YAClCA,EAAM,MAAM,CACV,KAAM,iCACN,UAAWE,EAAQ,UACnB,YAAaC,EACTR,EACE,CACE,KAAMQ,EAAY,KAClB,YAAaA,EAAY,YACzB,QAAU,MAAMA,EAAY,WAAW,GAAM,KAC7C,MAAO,OAAO,QAAQH,EAAM,QAAQ,eAAiB,CAAC,CAAC,EAAE,IACvD,CAAC,CAACI,EAAMC,CAAU,KAAO,CACvB,KAAAD,EACA,YAAaC,EAAW,YACxB,WAAYA,EAAW,UACzB,EACF,CACF,EACA,KACF,EACA,MACN,CAAC,CACH,SAAWH,EAAQ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sBAAsB,EACnEvB,EAAQ,UAAUwB,CAAO,EACzBhB,EAAO,eAAe,YACpB,CACE,KAAM,0BACN,aAAcR,EAAQ,aACtB,MAAOwB,EAAQ,QACf,GAAIxB,EAAQ,YAAc,CAAE,mBAAoB,EAAK,EAAI,CAAC,CAC5D,EACAS,CACF,CACF,CAAC,EACA,QAAQ,IAAM,CACbE,EAAU,MACZ,CAAC,GACL,EACA,OAAAJ,EAAK,iBAAiB,UAAWa,CAAO,EACxCf,EAAU,OAAOG,CAAM,EAChB,CACL,OAAAA,EACA,OAAQ,CACFE,IACJF,EAAO,MAAM,EACbA,EAAO,eAAe,YACpB,CACE,KAAM,2BACN,aAAcR,EAAQ,YACxB,EACAS,CACF,EACF,EACA,SAAU,CACJC,IACJA,EAAY,GACZG,EAAW,MAAM,EACjBD,EAAgB,OAChBL,EAAK,oBAAoB,UAAWa,CAAO,EAC3CZ,EAAO,OAAO,EAChB,CACF,CACF","names":["embed_exports","__export","createOmniChatEmbed","createOmniChatWidget","getOmniChatEmbedCode","getOmniChatEmbedUrl","getOmniChatReactCode","boundedJson","value","maximum","encoded","createApplicationMessageHandler","input","calls","message","application","name","definition","toolCallId","args","signature","prior","result","error","iconPaths","widgetIcon","document","name","svg","path","widgetStyles","loadWidgetConfiguration","host","origin","deploymentId","signal","response","result","design","color","value","widgetSequence","createOmniChatWidget","container","options","origin","getOmniChatEmbedUrl","document","host","controller","root","shadow","style","widgetStyles","launcher","panel","close","frame","embed","destroyed","loaded","openRequested","appearance","label","widgetIcon","closeChat","openChat","createOmniChatEmbed","event","ready","loadWidgetConfiguration","configuration","value","error","scriptJson","value","character","getOmniChatEmbedCode","options","mode","baseUrl","getOmniChatEmbedUrl","config","id","mount","getOmniChatReactCode","getOmniChatEmbedUrl","options","parentOrigin","base","url","createOmniChatEmbed","container","document","host","iframe","chatOrigin","destroyed","pending","previousToken","controller","mint","response","result","applicationMessage","createApplicationMessageHandler","message","receive","event","session","error","failure"]}
package/dist/embed.js CHANGED
@@ -1,3 +1,86 @@
1
+ // src/application.ts
2
+ function boundedJson(value, maximum) {
3
+ const encoded = JSON.stringify(value);
4
+ if (typeof encoded !== "string" || new TextEncoder().encode(encoded).length > maximum || /data:[^"\s]{0,100};base64,/i.test(encoded))
5
+ throw new Error(
6
+ "Application data must be bounded JSON without base64 payloads."
7
+ );
8
+ return JSON.parse(encoded);
9
+ }
10
+ function createApplicationMessageHandler(input) {
11
+ const calls = /* @__PURE__ */ new Map();
12
+ return async (message) => {
13
+ if (typeof message.requestId !== "string" || message.requestId.length > 200)
14
+ return;
15
+ try {
16
+ if (message.type === "omni-chat:application-request") {
17
+ const application = input.options.application;
18
+ input.reply({
19
+ type: "omni-chat:application-response",
20
+ requestId: message.requestId,
21
+ application: application ? boundedJson(
22
+ {
23
+ name: application.name,
24
+ description: application.description,
25
+ context: await application.getContext() ?? null,
26
+ tools: Object.entries(input.options.frontendTools ?? {}).map(
27
+ ([name, definition]) => ({
28
+ name,
29
+ description: definition.description,
30
+ parameters: definition.parameters
31
+ })
32
+ )
33
+ },
34
+ 65536
35
+ ) : void 0
36
+ });
37
+ } else if (message.type === "omni-chat:tool-request") {
38
+ const name = message.toolName;
39
+ const toolCallId = message.toolCallId;
40
+ if (typeof name !== "string" || !/^app_[a-z][a-z0-9_]{0,59}$/.test(name) || typeof toolCallId !== "string" || !toolCallId || toolCallId.length > 200)
41
+ throw new Error("Invalid application tool request.");
42
+ const definition = Object.hasOwn(
43
+ input.options.frontendTools ?? {},
44
+ name
45
+ ) ? input.options.frontendTools?.[name] : void 0;
46
+ if (!input.options.application || !definition)
47
+ throw new Error("This application action is unavailable.");
48
+ const args = message.args;
49
+ if (!args || typeof args !== "object" || Array.isArray(args))
50
+ throw new Error("Invalid application action arguments.");
51
+ const signature = JSON.stringify({ name, args });
52
+ const prior = calls.get(toolCallId);
53
+ if (prior && prior.signature !== signature)
54
+ throw new Error("This tool call ID was already used.");
55
+ const result = prior?.result ?? Promise.resolve().then(
56
+ () => definition.execute(args, {
57
+ toolCallId,
58
+ abortSignal: input.signal
59
+ })
60
+ );
61
+ if (!prior) {
62
+ if (calls.size >= 200)
63
+ throw new Error("Start a new application chat.");
64
+ calls.set(toolCallId, { signature, result });
65
+ }
66
+ input.reply({
67
+ type: "omni-chat:tool-response",
68
+ requestId: message.requestId,
69
+ toolCallId,
70
+ result: boundedJson(await result ?? null, 12e3)
71
+ });
72
+ }
73
+ } catch (error) {
74
+ input.reply({
75
+ type: message.type === "omni-chat:application-request" ? "omni-chat:application-response" : "omni-chat:tool-response",
76
+ requestId: message.requestId,
77
+ toolCallId: message.toolCallId,
78
+ error: error instanceof Error ? error.message : "The application action failed."
79
+ });
80
+ }
81
+ };
82
+ }
83
+
1
84
  // src/widget-chrome.ts
2
85
  var iconPaths = {
3
86
  chat: "M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z",
@@ -71,15 +154,48 @@ var widgetStyles = `
71
154
  @media (prefers-reduced-motion: reduce) { .panel, :host([data-presentation="sidebar"]) .panel { animation: none; } .launcher { transition: none; } }
72
155
  `;
73
156
 
157
+ // src/widget-config.ts
158
+ async function loadWidgetConfiguration(host, origin, deploymentId, signal) {
159
+ const response = await host.fetch(`${origin}/api/embed/${deploymentId}`, {
160
+ credentials: "include",
161
+ cache: "no-store",
162
+ signal
163
+ });
164
+ const result = await response.json();
165
+ if (!response.ok)
166
+ throw new Error(result.error ?? "Could not load the chat design.");
167
+ const design = result.design;
168
+ const color = /^#[0-9a-f]{6}$/i;
169
+ if (!design || typeof design.title !== "string" || !design.title.trim() || design.title.length > 80 || typeof design.launcherLabel !== "string" || !design.launcherLabel.trim() || design.launcherLabel.length > 60 || !["left", "right"].includes(design.position) || !["floating", "sidebar"].includes(design.presentation) || !design.theme || ![
170
+ design.theme.primary,
171
+ design.theme.primaryForeground,
172
+ design.theme.background,
173
+ design.theme.foreground
174
+ ].every((value) => typeof value === "string" && color.test(value)))
175
+ throw new Error("Invalid chat design response.");
176
+ return {
177
+ deploymentId,
178
+ title: design.title,
179
+ launcherLabel: design.launcherLabel,
180
+ position: design.position,
181
+ presentation: design.presentation,
182
+ launcherBackground: design.theme.primary,
183
+ launcherForeground: design.theme.primaryForeground,
184
+ panelBackground: design.theme.background,
185
+ panelForeground: design.theme.foreground
186
+ };
187
+ }
188
+
74
189
  // src/widget.ts
75
190
  var widgetSequence = 0;
76
191
  function createOmniChatWidget(container, options) {
77
- getOmniChatEmbedUrl(options);
192
+ const origin = new URL(getOmniChatEmbedUrl(options)).origin;
78
193
  const document = container.ownerDocument;
194
+ const host = document.defaultView;
195
+ if (!host) throw new Error("A browser document is required to mount chat.");
196
+ const controller = new AbortController();
79
197
  const root = document.createElement("div");
80
198
  root.setAttribute("data-omni-chat-widget", "");
81
- root.setAttribute("data-position", options.position ?? "right");
82
- root.setAttribute("data-presentation", options.presentation ?? "floating");
83
199
  const shadow = root.attachShadow({ mode: "open" });
84
200
  const style = document.createElement("style");
85
201
  style.textContent = widgetStyles;
@@ -89,28 +205,14 @@ function createOmniChatWidget(container, options) {
89
205
  const frame = document.createElement("div");
90
206
  let embed;
91
207
  let destroyed = false;
208
+ let loaded = false;
209
+ let openRequested = false;
210
+ let appearance = options;
92
211
  Object.assign(root.style, {
93
212
  position: "fixed",
94
213
  bottom: "20px",
95
- [options.position ?? "right"]: "20px",
96
214
  zIndex: "2147483000"
97
215
  });
98
- root.style.setProperty(
99
- "--omni-launcher-bg",
100
- options.launcherBackground ?? "#2563eb"
101
- );
102
- root.style.setProperty(
103
- "--omni-launcher-fg",
104
- options.launcherForeground ?? "#ffffff"
105
- );
106
- root.style.setProperty(
107
- "--omni-panel-bg",
108
- options.panelBackground ?? "#ffffff"
109
- );
110
- root.style.setProperty(
111
- "--omni-panel-fg",
112
- options.panelForeground ?? "#171717"
113
- );
114
216
  launcher.type = close.type = "button";
115
217
  launcher.className = "launcher";
116
218
  const label = document.createElement("span");
@@ -132,6 +234,7 @@ function createOmniChatWidget(container, options) {
132
234
  close.append(widgetIcon(document, "close"));
133
235
  const closeChat = () => {
134
236
  if (destroyed) return;
237
+ openRequested = false;
135
238
  panel.hidden = true;
136
239
  launcher.hidden = false;
137
240
  launcher.setAttribute("aria-expanded", "false");
@@ -141,13 +244,17 @@ function createOmniChatWidget(container, options) {
141
244
  };
142
245
  const openChat = () => {
143
246
  if (destroyed) return;
247
+ if (!loaded) {
248
+ openRequested = true;
249
+ return;
250
+ }
144
251
  embed ?? (embed = createOmniChatEmbed(frame, {
145
- ...options,
252
+ ...appearance,
146
253
  onRequestClose: closeChat
147
254
  }));
148
255
  embed.iframe.style.minHeight = "0";
149
256
  panel.hidden = false;
150
- launcher.hidden = options.presentation === "sidebar";
257
+ launcher.hidden = appearance.presentation === "sidebar";
151
258
  launcher.setAttribute("aria-expanded", "true");
152
259
  launcher.setAttribute("aria-label", "Close chat");
153
260
  launcher.querySelector("svg")?.replaceWith(widgetIcon(document, "collapse"));
@@ -163,12 +270,55 @@ function createOmniChatWidget(container, options) {
163
270
  });
164
271
  panel.append(close, frame);
165
272
  shadow.append(style, panel, launcher);
166
- container.append(root);
273
+ const ready = loadWidgetConfiguration(
274
+ host,
275
+ origin,
276
+ options.deploymentId,
277
+ controller.signal
278
+ ).then((configuration) => {
279
+ if (destroyed) return;
280
+ appearance = Object.assign(
281
+ configuration,
282
+ Object.fromEntries(
283
+ Object.entries(options).filter(([, value]) => value !== void 0)
284
+ )
285
+ );
286
+ root.dataset.position = appearance.position ?? "right";
287
+ root.dataset.presentation = appearance.presentation ?? "floating";
288
+ root.style.removeProperty("left");
289
+ root.style.removeProperty("right");
290
+ root.style.setProperty(appearance.position ?? "right", "20px");
291
+ root.style.setProperty(
292
+ "--omni-launcher-bg",
293
+ appearance.launcherBackground
294
+ );
295
+ root.style.setProperty(
296
+ "--omni-launcher-fg",
297
+ appearance.launcherForeground
298
+ );
299
+ root.style.setProperty("--omni-panel-bg", appearance.panelBackground);
300
+ root.style.setProperty("--omni-panel-fg", appearance.panelForeground);
301
+ label.textContent = appearance.launcherLabel;
302
+ launcher.setAttribute("aria-label", label.textContent);
303
+ panel.setAttribute("aria-label", appearance.title);
304
+ loaded = true;
305
+ container.append(root);
306
+ if (openRequested) openChat();
307
+ });
308
+ void ready.catch((error) => {
309
+ if (!destroyed)
310
+ options.onError?.(
311
+ error instanceof Error ? error : new Error("Could not load chat.")
312
+ );
313
+ });
167
314
  return {
315
+ /** Resolves once saved appearance is loaded and the launcher is mounted. */
316
+ ready,
168
317
  open: openChat,
169
318
  close: closeChat,
170
319
  destroy() {
171
320
  destroyed = true;
321
+ controller.abort();
172
322
  embed?.destroy();
173
323
  root.remove();
174
324
  }
@@ -263,9 +413,24 @@ function createOmniChatEmbed(container, options) {
263
413
  }
264
414
  return result;
265
415
  };
416
+ const applicationMessage = createApplicationMessageHandler({
417
+ options,
418
+ signal: controller.signal,
419
+ reply: (message) => {
420
+ if (!destroyed)
421
+ iframe.contentWindow?.postMessage(
422
+ { ...message, deploymentId: options.deploymentId },
423
+ chatOrigin
424
+ );
425
+ }
426
+ });
266
427
  const receive = (event) => {
267
428
  if (destroyed || event.source !== iframe.contentWindow || event.origin !== chatOrigin || event.data?.deploymentId !== options.deploymentId)
268
429
  return;
430
+ if (event.data.type === "omni-chat:application-request" || event.data.type === "omni-chat:tool-request") {
431
+ void applicationMessage(event.data);
432
+ return;
433
+ }
269
434
  if (event.data.type === "omni-chat:close-request") {
270
435
  options.onRequestClose?.();
271
436
  return;
@@ -281,7 +446,8 @@ function createOmniChatEmbed(container, options) {
281
446
  {
282
447
  type: "omni-chat:session",
283
448
  deploymentId: options.deploymentId,
284
- session
449
+ session,
450
+ ...options.application ? { applicationEnabled: true } : {}
285
451
  },
286
452
  chatOrigin
287
453
  );
@@ -293,7 +459,8 @@ function createOmniChatEmbed(container, options) {
293
459
  {
294
460
  type: "omni-chat:session-error",
295
461
  deploymentId: options.deploymentId,
296
- error: failure.message
462
+ error: failure.message,
463
+ ...options.application ? { applicationEnabled: true } : {}
297
464
  },
298
465
  chatOrigin
299
466
  );