@omni-commerce/sdk 0.8.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.
package/README.md CHANGED
@@ -127,3 +127,5 @@ yarn sdk:generate
127
127
  ```
128
128
 
129
129
  That refreshes `docs/openapi.json`, the OpenAPI TypeScript types, and `src/generated/resources.ts`.
130
+
131
+ With SDK 0.8.1, website widgets load saved Storefront appearance by deployment ID. Install the generated deployment-only snippet once; saving an agent or design change updates the next website load. Explicit appearance options override saved values. The `ready` promise resolves after configuration loads, or rejects on an error reported to `onError`.
package/dist/embed.cjs CHANGED
@@ -156,15 +156,48 @@ var widgetStyles = `
156
156
  @media (prefers-reduced-motion: reduce) { .panel, :host([data-presentation="sidebar"]) .panel { animation: none; } .launcher { transition: none; } }
157
157
  `;
158
158
 
159
+ // src/widget-config.ts
160
+ async function loadWidgetConfiguration(host, origin, deploymentId, signal) {
161
+ const response = await host.fetch(`${origin}/api/embed/${deploymentId}`, {
162
+ credentials: "include",
163
+ cache: "no-store",
164
+ signal
165
+ });
166
+ const result = await response.json();
167
+ if (!response.ok)
168
+ throw new Error(result.error ?? "Could not load the chat design.");
169
+ const design = result.design;
170
+ const color = /^#[0-9a-f]{6}$/i;
171
+ 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 || ![
172
+ design.theme.primary,
173
+ design.theme.primaryForeground,
174
+ design.theme.background,
175
+ design.theme.foreground
176
+ ].every((value) => typeof value === "string" && color.test(value)))
177
+ throw new Error("Invalid chat design response.");
178
+ return {
179
+ deploymentId,
180
+ title: design.title,
181
+ launcherLabel: design.launcherLabel,
182
+ position: design.position,
183
+ presentation: design.presentation,
184
+ launcherBackground: design.theme.primary,
185
+ launcherForeground: design.theme.primaryForeground,
186
+ panelBackground: design.theme.background,
187
+ panelForeground: design.theme.foreground
188
+ };
189
+ }
190
+
159
191
  // src/widget.ts
160
192
  var widgetSequence = 0;
161
193
  function createOmniChatWidget(container, options) {
162
- getOmniChatEmbedUrl(options);
194
+ const origin = new URL(getOmniChatEmbedUrl(options)).origin;
163
195
  const document = container.ownerDocument;
196
+ const host = document.defaultView;
197
+ if (!host) throw new Error("A browser document is required to mount chat.");
198
+ const controller = new AbortController();
164
199
  const root = document.createElement("div");
165
200
  root.setAttribute("data-omni-chat-widget", "");
166
- root.setAttribute("data-position", options.position ?? "right");
167
- root.setAttribute("data-presentation", options.presentation ?? "floating");
168
201
  const shadow = root.attachShadow({ mode: "open" });
169
202
  const style = document.createElement("style");
170
203
  style.textContent = widgetStyles;
@@ -174,28 +207,14 @@ function createOmniChatWidget(container, options) {
174
207
  const frame = document.createElement("div");
175
208
  let embed;
176
209
  let destroyed = false;
210
+ let loaded = false;
211
+ let openRequested = false;
212
+ let appearance = options;
177
213
  Object.assign(root.style, {
178
214
  position: "fixed",
179
215
  bottom: "20px",
180
- [options.position ?? "right"]: "20px",
181
216
  zIndex: "2147483000"
182
217
  });
183
- root.style.setProperty(
184
- "--omni-launcher-bg",
185
- options.launcherBackground ?? "#2563eb"
186
- );
187
- root.style.setProperty(
188
- "--omni-launcher-fg",
189
- options.launcherForeground ?? "#ffffff"
190
- );
191
- root.style.setProperty(
192
- "--omni-panel-bg",
193
- options.panelBackground ?? "#ffffff"
194
- );
195
- root.style.setProperty(
196
- "--omni-panel-fg",
197
- options.panelForeground ?? "#171717"
198
- );
199
218
  launcher.type = close.type = "button";
200
219
  launcher.className = "launcher";
201
220
  const label = document.createElement("span");
@@ -217,6 +236,7 @@ function createOmniChatWidget(container, options) {
217
236
  close.append(widgetIcon(document, "close"));
218
237
  const closeChat = () => {
219
238
  if (destroyed) return;
239
+ openRequested = false;
220
240
  panel.hidden = true;
221
241
  launcher.hidden = false;
222
242
  launcher.setAttribute("aria-expanded", "false");
@@ -226,13 +246,17 @@ function createOmniChatWidget(container, options) {
226
246
  };
227
247
  const openChat = () => {
228
248
  if (destroyed) return;
249
+ if (!loaded) {
250
+ openRequested = true;
251
+ return;
252
+ }
229
253
  embed ?? (embed = createOmniChatEmbed(frame, {
230
- ...options,
254
+ ...appearance,
231
255
  onRequestClose: closeChat
232
256
  }));
233
257
  embed.iframe.style.minHeight = "0";
234
258
  panel.hidden = false;
235
- launcher.hidden = options.presentation === "sidebar";
259
+ launcher.hidden = appearance.presentation === "sidebar";
236
260
  launcher.setAttribute("aria-expanded", "true");
237
261
  launcher.setAttribute("aria-label", "Close chat");
238
262
  launcher.querySelector("svg")?.replaceWith(widgetIcon(document, "collapse"));
@@ -248,12 +272,55 @@ function createOmniChatWidget(container, options) {
248
272
  });
249
273
  panel.append(close, frame);
250
274
  shadow.append(style, panel, launcher);
251
- container.append(root);
275
+ const ready = loadWidgetConfiguration(
276
+ host,
277
+ origin,
278
+ options.deploymentId,
279
+ controller.signal
280
+ ).then((configuration) => {
281
+ if (destroyed) return;
282
+ appearance = Object.assign(
283
+ configuration,
284
+ Object.fromEntries(
285
+ Object.entries(options).filter(([, value]) => value !== void 0)
286
+ )
287
+ );
288
+ root.dataset.position = appearance.position ?? "right";
289
+ root.dataset.presentation = appearance.presentation ?? "floating";
290
+ root.style.removeProperty("left");
291
+ root.style.removeProperty("right");
292
+ root.style.setProperty(appearance.position ?? "right", "20px");
293
+ root.style.setProperty(
294
+ "--omni-launcher-bg",
295
+ appearance.launcherBackground
296
+ );
297
+ root.style.setProperty(
298
+ "--omni-launcher-fg",
299
+ appearance.launcherForeground
300
+ );
301
+ root.style.setProperty("--omni-panel-bg", appearance.panelBackground);
302
+ root.style.setProperty("--omni-panel-fg", appearance.panelForeground);
303
+ label.textContent = appearance.launcherLabel;
304
+ launcher.setAttribute("aria-label", label.textContent);
305
+ panel.setAttribute("aria-label", appearance.title);
306
+ loaded = true;
307
+ container.append(root);
308
+ if (openRequested) openChat();
309
+ });
310
+ void ready.catch((error) => {
311
+ if (!destroyed)
312
+ options.onError?.(
313
+ error instanceof Error ? error : new Error("Could not load chat.")
314
+ );
315
+ });
252
316
  return {
317
+ /** Resolves once saved appearance is loaded and the launcher is mounted. */
318
+ ready,
253
319
  open: openChat,
254
320
  close: closeChat,
255
321
  destroy() {
256
322
  destroyed = true;
323
+ controller.abort();
257
324
  embed?.destroy();
258
325
  root.remove();
259
326
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/application.ts","../src/widget-chrome.ts","../src/widget.ts","../src/embed-code.ts","../src/embed.ts"],"names":[],"mappings":";;;AAqBA,SAAS,WAAA,CAAY,OAAgB,OAAA,EAA0B;AAC7D,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,SAAA,CAAU,KAAK,CAAA;AACpC,EAAA,IACE,OAAO,OAAA,KAAY,QAAA,IACnB,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,OAAO,CAAA,CAAE,MAAA,GAAS,OAAA,IAC3C,6BAAA,CAA8B,KAAK,OAAO,CAAA;AAE1C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AACF,EAAA,OAAO,IAAA,CAAK,MAAM,OAAO,CAAA;AAC3B;AAEO,SAAS,gCAAgC,KAAA,EAI7C;AAED,EAAA,MAAM,KAAA,uBAAY,GAAA,EAGhB;AACF,EAAA,OAAO,OAAO,OAAA,KAAqC;AACjD,IAAA,IAAI,OAAO,OAAA,CAAQ,SAAA,KAAc,QAAA,IAAY,OAAA,CAAQ,UAAU,MAAA,GAAS,GAAA;AACtE,MAAA;AACF,IAAA,IAAI;AACF,MAAA,IAAI,OAAA,CAAQ,SAAS,+BAAA,EAAiC;AACpD,QAAA,MAAM,WAAA,GAAc,MAAM,OAAA,CAAQ,WAAA;AAClC,QAAA,KAAA,CAAM,KAAA,CAAM;AAAA,UACV,IAAA,EAAM,gCAAA;AAAA,UACN,WAAW,OAAA,CAAQ,SAAA;AAAA,UACnB,aAAa,WAAA,GACT,WAAA;AAAA,YACE;AAAA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AA,SAAA,CAAU,OAAO,MAAM,CAAA;AACvB,EAAA,OAAO;AAAA,IACL,MAAA;AAAA,IACA,KAAA,GAAQ;AACN,MAAA,IAAI,SAAA,EAAW;AACf,MAAA,MAAA,CAAO,KAAA,EAAM;AACb,MAAA,MAAA,CAAO,aAAA,EAAe,WAAA;AAAA,QACpB;AAAA,UACE,IAAA,EAAM,0BAAA;AAAA,UACN,cAAc,OAAA,CAAQ;AAAA,SACxB;AAAA,QACA;AAAA,OACF;AAAA,IACF,CAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,IAAI,SAAA,EAAW;AACf,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,UAAA,CAAW,KAAA,EAAM;AACjB,MAAA,aAAA,GAAgB,MAAA;AAChB,MAAA,IAAA,CAAK,mBAAA,CAAoB,WAAW,OAAO,CAAA;AAC3C,MAAA,MAAA,CAAO,MAAA,EAAO;AAAA,IAChB;AAAA,GACF;AACF","file":"embed.cjs","sourcesContent":["/** 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 {\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","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"]}
1
+ {"version":3,"sources":["../src/application.ts","../src/widget-chrome.ts","../src/widget-config.ts","../src/widget.ts","../src/embed-code.ts","../src/embed.ts"],"names":[],"mappings":";;;AAqBA,SAAS,WAAA,CAAY,OAAgB,OAAA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;AAAA,UACtB,OAAO,OAAA,CAAQ,OAAA;AAAA,UACf,GAAI,OAAA,CAAQ,WAAA,GAAc,EAAE,kBAAA,EAAoB,IAAA,KAAS;AAAC,SAC5D;AAAA,QACA;AAAA,OACF;AAAA,IACF,CAAC,CAAA,CACA,OAAA,CAAQ,MAAM;AACb,MAAA,OAAA,GAAU,MAAA;AAAA,IACZ,CAAC,CAAA;AAAA,EACL,CAAA;AACA,EAAA,IAAA,CAAK,gBAAA,CAAiB,WAAW,OAAO,CAAA;AACxC,EAAA,SAAA,CAAU,OAAO,MAAM,CAAA;AACvB,EAAA,OAAO;AAAA,IACL,MAAA;AAAA,IACA,KAAA,GAAQ;AACN,MAAA,IAAI,SAAA,EAAW;AACf,MAAA,MAAA,CAAO,KAAA,EAAM;AACb,MAAA,MAAA,CAAO,aAAA,EAAe,WAAA;AAAA,QACpB;AAAA,UACE,IAAA,EAAM,0BAAA;AAAA,UACN,cAAc,OAAA,CAAQ;AAAA,SACxB;AAAA,QACA;AAAA,OACF;AAAA,IACF,CAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,IAAI,SAAA,EAAW;AACf,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,UAAA,CAAW,KAAA,EAAM;AACjB,MAAA,aAAA,GAAgB,MAAA;AAChB,MAAA,IAAA,CAAK,mBAAA,CAAoB,WAAW,OAAO,CAAA;AAC3C,MAAA,MAAA,CAAO,MAAA,EAAO;AAAA,IAChB;AAAA,GACF;AACF","file":"embed.cjs","sourcesContent":["/** 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","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"]}
package/dist/embed.d.cts CHANGED
@@ -29,8 +29,10 @@ type OmniChatWidgetOptions = OmniChatEmbedOptions & {
29
29
  panelBackground?: string;
30
30
  panelForeground?: string;
31
31
  };
32
- /** A website launcher using the same hosted assistant as OmniChat. */
32
+ /** Loads saved appearance by deployment ID. Explicit options override saved appearance. */
33
33
  declare function createOmniChatWidget(container: HTMLElement, options: OmniChatWidgetOptions): {
34
+ /** Resolves once saved appearance is loaded and the launcher is mounted. */
35
+ ready: Promise<void>;
34
36
  open: () => void;
35
37
  close: () => void;
36
38
  destroy(): void;
package/dist/embed.d.ts CHANGED
@@ -29,8 +29,10 @@ type OmniChatWidgetOptions = OmniChatEmbedOptions & {
29
29
  panelBackground?: string;
30
30
  panelForeground?: string;
31
31
  };
32
- /** A website launcher using the same hosted assistant as OmniChat. */
32
+ /** Loads saved appearance by deployment ID. Explicit options override saved appearance. */
33
33
  declare function createOmniChatWidget(container: HTMLElement, options: OmniChatWidgetOptions): {
34
+ /** Resolves once saved appearance is loaded and the launcher is mounted. */
35
+ ready: Promise<void>;
34
36
  open: () => void;
35
37
  close: () => void;
36
38
  destroy(): void;
@@ -1,4 +1,4 @@
1
- "use strict";var OmniCommerceChat=(()=>{var w=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var P=(n,t)=>{for(var e in t)w(n,e,{get:t[e],enumerable:!0})},T=(n,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of S(t))!q.call(n,r)&&r!==e&&w(n,r,{get:()=>t[r],enumerable:!(o=A(t,r))||o.enumerable});return n};var $=n=>T(w({},"__esModule",{value:!0}),n);var R={};P(R,{createOmniChatEmbed:()=>x,createOmniChatWidget:()=>k,getOmniChatEmbedCode:()=>v,getOmniChatEmbedUrl:()=>h,getOmniChatReactCode:()=>I});function O(n,t){let e=JSON.stringify(n);if(typeof e!="string"||new TextEncoder().encode(e).length>t||/data:[^"\s]{0,100};base64,/i.test(e))throw new Error("Application data must be bounded JSON without base64 payloads.");return JSON.parse(e)}function C(n){let t=new Map;return async e=>{if(!(typeof e.requestId!="string"||e.requestId.length>200))try{if(e.type==="omni-chat:application-request"){let o=n.options.application;n.reply({type:"omni-chat:application-response",requestId:e.requestId,application:o?O({name:o.name,description:o.description,context:await o.getContext()??null,tools:Object.entries(n.options.frontendTools??{}).map(([r,p])=>({name:r,description:p.description,parameters:p.parameters}))},65536):void 0})}else if(e.type==="omni-chat:tool-request"){let o=e.toolName,r=e.toolCallId;if(typeof o!="string"||!/^app_[a-z][a-z0-9_]{0,59}$/.test(o)||typeof r!="string"||!r||r.length>200)throw new Error("Invalid application tool request.");let p=Object.hasOwn(n.options.frontendTools??{},o)?n.options.frontendTools?.[o]:void 0;if(!n.options.application||!p)throw new Error("This application action is unavailable.");let i=e.args;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid application action arguments.");let s=JSON.stringify({name:o,args:i}),l=t.get(r);if(l&&l.signature!==s)throw new Error("This tool call ID was already used.");let c=l?.result??Promise.resolve().then(()=>p.execute(i,{toolCallId:r,abortSignal:n.signal}));if(!l){if(t.size>=200)throw new Error("Start a new application chat.");t.set(r,{signature:s,result:c})}n.reply({type:"omni-chat:tool-response",requestId:e.requestId,toolCallId:r,result:O(await c??null,12e3)})}}catch(o){n.reply({type:e.type==="omni-chat:application-request"?"omni-chat:application-response":"omni-chat:tool-response",requestId:e.requestId,toolCallId:e.toolCallId,error:o instanceof Error?o.message:"The application action failed."})}}}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 b(n,t){let e=n.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.8"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.setAttribute("aria-hidden","true");let o=n.createElementNS("http://www.w3.org/2000/svg","path");return o.setAttribute("d",L[t]),e.append(o),e}var E=`
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 k(n,t){h(t);let e=n.ownerDocument,o=e.createElement("div");o.setAttribute("data-omni-chat-widget",""),o.setAttribute("data-position",t.position??"right"),o.setAttribute("data-presentation",t.presentation??"floating");let r=o.attachShadow({mode:"open"}),p=e.createElement("style");p.textContent=E;let i=e.createElement("button"),s=e.createElement("section"),l=e.createElement("button"),c=e.createElement("div"),u,f=!1;Object.assign(o.style,{position:"fixed",bottom:"20px",[t.position??"right"]:"20px",zIndex:"2147483000"}),o.style.setProperty("--omni-launcher-bg",t.launcherBackground??"#2563eb"),o.style.setProperty("--omni-launcher-fg",t.launcherForeground??"#ffffff"),o.style.setProperty("--omni-panel-bg",t.panelBackground??"#ffffff"),o.style.setProperty("--omni-panel-fg",t.panelForeground??"#171717"),i.type=l.type="button",i.className="launcher";let m=e.createElement("span");m.className="label",m.textContent=t.launcherLabel??"Chat with us",i.append(b(e,"chat"),m),i.setAttribute("aria-expanded","false"),i.setAttribute("aria-label",m.textContent),s.hidden=!0,s.className="panel",s.setAttribute("role","region"),s.setAttribute("aria-label",t.title??"Assistant chat"),s.id=`omni-chat-widget-${++U}`,i.setAttribute("aria-controls",s.id),c.className="frame",l.className="close",l.setAttribute("aria-label","Close chat"),l.title="Close chat",l.append(b(e,"close"));let a=()=>{f||(s.hidden=!0,i.hidden=!1,i.setAttribute("aria-expanded","false"),i.setAttribute("aria-label",m.textContent),i.querySelector("svg")?.replaceWith(b(e,"chat")),i.focus())},d=()=>{f||(u??(u=x(c,{...t,onRequestClose:a})),u.iframe.style.minHeight="0",s.hidden=!1,i.hidden=t.presentation==="sidebar",i.setAttribute("aria-expanded","true"),i.setAttribute("aria-label","Close chat"),i.querySelector("svg")?.replaceWith(b(e,"collapse")),u.focus())};return i.addEventListener("click",()=>s.hidden?d():a()),l.addEventListener("click",a),r.addEventListener("keydown",y=>{y.key==="Escape"&&!s.hidden&&a()}),s.append(l,c),r.append(p,s,i),n.append(o),{open:d,close:a,destroy(){f=!0,u?.destroy(),o.remove()}}}var g=n=>JSON.stringify(n,null,2).replace(/[<>&\u2028\u2029]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`);function v(n,t="widget"){let e=new URL(h(n)).origin,o={...n,baseUrl:e},r=`omni-chat-${n.deploymentId}`,p=t==="widget"?`OmniCommerceChat.createOmniChatWidget(document.body, ${g(o)});`:`OmniCommerceChat.createOmniChatEmbed(document.getElementById(${g(r)}), ${g(o)});`;return`${t==="inline"?`<div id="${r}" style="height:600px"></div>
53
- `:""}<script src="${e}/sdk/embed.global.js"><\/script>
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
+ `:""}<script src="${t}/sdk/embed.global.js"><\/script>
54
54
  <script>
55
- ${p.replace(/\n/g,`
55
+ ${l.replace(/\n/g,`
56
56
  `)}
57
- <\/script>`}function I(n){let t=new URL(h(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(t)}}${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 h(n,t){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 e=new URL(n.baseUrl??"https://omnicommerce.sg");if(e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1"].includes(e.hostname))||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw new Error("Chat baseUrl must be an HTTPS origin, or HTTP localhost.");let o=new URL(`/embed/${n.deploymentId}`,e.origin);return t&&o.searchParams.set("parentOrigin",new URL(t).origin),o.toString()}function x(n,t){let e=n.ownerDocument,o=e.defaultView;if(!o)throw new Error("A browser document is required to mount chat.");let r=e.createElement("iframe");r.src=h(t,o.location.origin),r.title=t.title??"OmniCommerce assistant",r.referrerPolicy="strict-origin-when-cross-origin",r.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),Object.assign(r.style,{width:"100%",height:"100%",minHeight:"320px",border:"0",display:"block"});let p=new URL(r.src).origin,i=!1,s,l,c=new AbortController,u=async()=>{if(t.getSession)return t.getSession();let a=await o.fetch(`${p}/api/embed/${t.deploymentId}/session`,{method:"POST",credentials:"include",signal:c.signal,headers:{"Content-Type":"application/json",...l?{Authorization:`Bearer ${l}`}:{}},body:"{}"}),d=await a.json();if(!a.ok)throw(a.status===401||a.status===403)&&(l=void 0),new Error(d.error??"Could not open the chat session.");return d},f=C({options:t,signal:c.signal,reply:a=>{i||r.contentWindow?.postMessage({...a,deploymentId:t.deploymentId},p)}}),m=a=>{if(!(i||a.source!==r.contentWindow||a.origin!==p||a.data?.deploymentId!==t.deploymentId)){if(a.data.type==="omni-chat:application-request"||a.data.type==="omni-chat:tool-request"){f(a.data);return}if(a.data.type==="omni-chat:close-request"){t.onRequestClose?.();return}a.data.type==="omni-chat:session-request"&&(s??(s=u()),s.then(d=>{if(!i){if(typeof d?.token!="string"||!d.token||d.token.length>4096||typeof d.threadId!="string"||!d.threadId||!Number.isFinite(d.expiresIn)||d.expiresIn<=0)throw new Error("Invalid chat session response.");l=d.token,r.contentWindow?.postMessage({type:"omni-chat:session",deploymentId:t.deploymentId,session:d,...t.application?{applicationEnabled:!0}:{}},p)}}).catch(d=>{if(i)return;let y=d instanceof Error?d:new Error("Could not open chat.");t.onError?.(y),r.contentWindow?.postMessage({type:"omni-chat:session-error",deploymentId:t.deploymentId,error:y.message,...t.application?{applicationEnabled:!0}:{}},p)}).finally(()=>{s=void 0}))}};return o.addEventListener("message",m),n.append(r),{iframe:r,focus(){i||(r.focus(),r.contentWindow?.postMessage({type:"omni-chat:focus-composer",deploymentId:t.deploymentId},p))},destroy(){i||(i=!0,c.abort(),l=void 0,o.removeEventListener("message",m),r.remove())}}}return $(R);})();
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