@saar-ai/web-widget 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +209 -0
  2. package/dist/bot-avatar.d.ts +41 -0
  3. package/dist/bot-avatar.d.ts.map +1 -0
  4. package/dist/bot-face.d.ts +39 -0
  5. package/dist/bot-face.d.ts.map +1 -0
  6. package/dist/bot-state.d.ts +39 -0
  7. package/dist/bot-state.d.ts.map +1 -0
  8. package/dist/chunks/chat-ZLxYRTml.js +173 -0
  9. package/dist/chunks/esm-DSxqq2-d.js +3299 -0
  10. package/dist/chunks/host-widget-iy3qC-1p.js +7677 -0
  11. package/dist/chunks/livekit-client.esm-OPuvn_z-.js +26600 -0
  12. package/dist/chunks/schemas-Bl_6mxe4.js +4123 -0
  13. package/dist/chunks/telemetry-Bw-3F_Zk.js +290 -0
  14. package/dist/cn.d.ts +14 -0
  15. package/dist/cn.d.ts.map +1 -0
  16. package/dist/concierge-launcher.d.ts +50 -0
  17. package/dist/concierge-launcher.d.ts.map +1 -0
  18. package/dist/concierge-shell.d.ts +194 -0
  19. package/dist/concierge-shell.d.ts.map +1 -0
  20. package/dist/error-boundary.d.ts +34 -0
  21. package/dist/error-boundary.d.ts.map +1 -0
  22. package/dist/format-money.d.ts +20 -0
  23. package/dist/format-money.d.ts.map +1 -0
  24. package/dist/generated/widget-css.d.ts +2 -0
  25. package/dist/generated/widget-css.d.ts.map +1 -0
  26. package/dist/host-widget.d.ts +165 -0
  27. package/dist/host-widget.d.ts.map +1 -0
  28. package/dist/index.d.ts +28 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +583 -0
  31. package/dist/messages.d.ts +116 -0
  32. package/dist/messages.d.ts.map +1 -0
  33. package/dist/morphing-loader.d.ts +16 -0
  34. package/dist/morphing-loader.d.ts.map +1 -0
  35. package/dist/mount.d.ts +45 -0
  36. package/dist/mount.d.ts.map +1 -0
  37. package/dist/next/index.d.ts +3 -0
  38. package/dist/next/index.d.ts.map +1 -0
  39. package/dist/next/index.js +86 -0
  40. package/dist/next/use-next-bridge.d.ts +113 -0
  41. package/dist/next/use-next-bridge.d.ts.map +1 -0
  42. package/dist/position.d.ts +65 -0
  43. package/dist/position.d.ts.map +1 -0
  44. package/dist/session-log.d.ts +84 -0
  45. package/dist/session-log.d.ts.map +1 -0
  46. package/dist/session-panel.d.ts +15 -0
  47. package/dist/session-panel.d.ts.map +1 -0
  48. package/dist/sse-parser.d.ts +38 -0
  49. package/dist/sse-parser.d.ts.map +1 -0
  50. package/dist/styles.d.ts +19 -0
  51. package/dist/styles.d.ts.map +1 -0
  52. package/dist/text-direction.d.ts +49 -0
  53. package/dist/text-direction.d.ts.map +1 -0
  54. package/dist/use-chat-session.d.ts +344 -0
  55. package/dist/use-chat-session.d.ts.map +1 -0
  56. package/dist/use-voice-session.d.ts +273 -0
  57. package/dist/use-voice-session.d.ts.map +1 -0
  58. package/dist/voice-session-state.d.ts +44 -0
  59. package/dist/voice-session-state.d.ts.map +1 -0
  60. package/dist/voice-widget.d.ts +167 -0
  61. package/dist/voice-widget.d.ts.map +1 -0
  62. package/dist/widget-cards.d.ts +69 -0
  63. package/dist/widget-cards.d.ts.map +1 -0
  64. package/dist/widget-cart-summary.d.ts +66 -0
  65. package/dist/widget-cart-summary.d.ts.map +1 -0
  66. package/dist/widget-markdown.d.ts +33 -0
  67. package/dist/widget-markdown.d.ts.map +1 -0
  68. package/dist/widget.css +2 -0
  69. package/package.json +88 -0
  70. package/src/styles/concierge.css +351 -0
  71. package/src/styles/tokens.css +67 -0
  72. package/src/styles/widget-entry.css +13 -0
package/README.md ADDED
@@ -0,0 +1,209 @@
1
+ # @saar-ai/web-widget
2
+
3
+ The concierge widget's full React UI: the chrome (`ConciergeShell`,
4
+ `ConciergeLauncher`, `BotFace`, `MorphingLoader`) AND the end-user
5
+ conversation (`VoiceWidget`, `useChatSession`, `useVoiceSession`, product
6
+ cards, the cart summary, Markdown rendering) — de-Nexted so the package
7
+ builds and ships without Next.js, `next-intl`, or `next/link`. React and
8
+ `react-dom` are peer dependencies only; `next` is an OPTIONAL peer, needed
9
+ only by the `@saar-ai/web-widget/next` subpath (Phase 5, below) — see
10
+ [`AGENTS.md`](./AGENTS.md) for the full contract, the CSS wiring an app
11
+ needs, and why this exists as its own package.
12
+
13
+ Also exports `mountConciergeWidget(host, props)` — attaches a shadow root to
14
+ `host` and renders the widget inside it, for a merchant page with no build
15
+ step of its own — and the plain `ConciergeWidget` component for a Next.js host.
16
+
17
+ See [`docs/WIDGET_EMBED_PLAN.md`](../../docs/WIDGET_EMBED_PLAN.md) (§4 Phase 3) for the design this package implements.
18
+
19
+ ## Usage
20
+
21
+ ```tsx
22
+ 'use client';
23
+ import { useState } from 'react';
24
+ import { ConciergeShell, type ConciergePosition } from '@saar-ai/web-widget';
25
+ import '@saar-ai/web-widget/styles/concierge.css';
26
+
27
+ const LABELS = {
28
+ open: 'Open the assistant',
29
+ close: 'Close',
30
+ dialog: 'Assistant conversation',
31
+ composerPlaceholder: 'Ask about pricing or products…',
32
+ send: 'Send',
33
+ };
34
+
35
+ export function Widget() {
36
+ const [open, setOpen] = useState(false);
37
+ const [draft, setDraft] = useState('');
38
+ const [position, setPosition] = useState<ConciergePosition>('bottom-center');
39
+
40
+ return (
41
+ <ConciergeShell
42
+ open={open}
43
+ onOpenChange={setOpen}
44
+ state="idle"
45
+ labels={LABELS}
46
+ draft={draft}
47
+ onDraftChange={setDraft}
48
+ onSubmit={() => setDraft('')}
49
+ position={position}
50
+ onPositionChange={setPosition}
51
+ >
52
+ <p>the conversation</p>
53
+ </ConciergeShell>
54
+ );
55
+ }
56
+ ```
57
+
58
+ The app supplies the conversation (`children`), the strings (`labels` — this
59
+ package has no locale of its own), and, for a live call, the voice leg
60
+ (`voice`). Everything else — the modal dialog semantics, the focus trap, the
61
+ drag-to-reposition launcher, the mascot and its animations — is this
62
+ package's job.
63
+
64
+ ## Moved from `@wesence/ui`
65
+
66
+ These components used to live in `@wesence/ui`'s `components/concierge/`. They
67
+ moved here (not forked) because `@wesence/ui` is `template`-classified and a
68
+ `publishable` package — this one — cannot depend on a template package; see
69
+ [`AGENTS.md`](./AGENTS.md#what-it-does) for the full reasoning and what was
70
+ copied rather than imported.
71
+
72
+ ## Using the conversation UI
73
+
74
+ ```tsx
75
+ 'use client';
76
+ import { VoiceWidget, useChatSession, type WidgetTurn } from '@saar-ai/web-widget';
77
+ import '@saar-ai/web-widget/styles/concierge.css';
78
+
79
+ export function MyWidget() {
80
+ const session = useChatSession({ embedKey: 'wgt_...', apiBase: '/api/widget' });
81
+ return (
82
+ <VoiceWidget
83
+ state="idle"
84
+ mode="text"
85
+ turns={session.turns as readonly WidgetTurn[]}
86
+ onSendText={session.send}
87
+ onToggleMic={() => undefined}
88
+ micOpen={false}
89
+ open
90
+ onOpenChange={() => undefined}
91
+ escalated={session.status === 'escalated'}
92
+ />
93
+ );
94
+ }
95
+ ```
96
+
97
+ `messages` (a `WidgetMessages` object — defaults to `defaultWidgetMessages`,
98
+ the package's brand-neutral fallback) is how a host with its own translation
99
+ catalogue supplies strings; the package no longer calls `next-intl` itself.
100
+ `apiBase` defaults to `''` (same-origin) — a merchant page hits its own
101
+ origin, apps/web overrides it to its `/api/widget` proxy.
102
+
103
+ ## Shadow-DOM mount (the CDN embed's entry point)
104
+
105
+ ```ts
106
+ import { mountConciergeWidget } from '@saar-ai/web-widget';
107
+
108
+ mountConciergeWidget(document.getElementById('saar-widget-host')!, {
109
+ embedKey: 'wgt_...',
110
+ apiBase: 'https://api.example.com/widget',
111
+ });
112
+ ```
113
+
114
+ Attaches `attachShadow({ mode: 'open' })` to the host element, resets it with
115
+ `all: initial` plus the widget's own type scale, adopts the compiled
116
+ `WIDGET_CSS` (via `adoptedStyleSheets`, falling back to a `<style>` element),
117
+ and renders the widget — wrapped in `WidgetErrorBoundary`, so a render error
118
+ here unmounts silently rather than breaking the host page — inside.
119
+
120
+ ## Using it from a Next.js host (Phase 5)
121
+
122
+ ```tsx
123
+ 'use client';
124
+ import { ConciergeWidget, useNextBridge } from '@saar-ai/web-widget/next';
125
+
126
+ export function Concierge() {
127
+ const bridge = useNextBridge(); // wraps useRouter().push + usePathname()
128
+ return <ConciergeWidget embedKey="wgt_..." bridge={bridge} />;
129
+ }
130
+ ```
131
+
132
+ `@saar-ai/web-widget/next` is a SEPARATE export subpath, not part of the
133
+ root import above — `next` is an optional peer dependency, and only this
134
+ subpath ever resolves it, so a merchant page (the CDN embed) or a bare-React
135
+ host never needs Next.js installed at all just to depend on this package.
136
+
137
+ `useNextBridge(options?)` builds a `HostBridge`: `navigate` is a soft
138
+ `router.push` (never a full page load), `onPageChange` fires on a pathname
139
+ change, and `currentPage()` classifies the page via
140
+ `@saar-ai/widget-bridge`'s detection ladder (JSON-LD → microdata →
141
+ OpenGraph → URL/DOM heuristics → `'other'`) rather than a guess. A host with
142
+ its own cart wiring can pass `{ addToCart, applyFilter, readCart }` through;
143
+ left out, the widget uses its own documented degraded paths (e.g.
144
+ `addToCart` absent ⇒ navigate to the product page instead).
145
+
146
+ See [`AGENTS.md`](./AGENTS.md#the-nextjs-host-entry-phase-5) for the full
147
+ contract and why the split matters, and
148
+ [`docs/WIDGET_EMBED_PLAN.md`](../../docs/WIDGET_EMBED_PLAN.md) §4 Phase 5.
149
+
150
+ ## The CDN embed build (Phase 4)
151
+
152
+ `pnpm --filter @saar-ai/web-widget build:cdn` produces the staged,
153
+ merchant-facing artefacts a `<script>` tag actually loads:
154
+
155
+ ```html
156
+ <script src="https://widget.saar.live/v1/widget.js" data-embed-key="wgt_..." async></script>
157
+ ```
158
+
159
+ That tag stays the same forever — the load is staged behind it into a ≤3 KB
160
+ boot script, a ≤20 KB idle-loaded core (collector, consent, the plain-DOM
161
+ launcher pill), and a ≤95 KB UI chunk fetched only on the first interaction,
162
+ so React and the conversation UI never reach a shopper who never opens the
163
+ widget. See [`AGENTS.md`](./AGENTS.md#the-cdn-build-phase-4) for the full
164
+ artefact layout, cache-header contract, and measured sizes — this output is
165
+ deployed to S3/CloudFront, never published to npm (`dist/cdn` is excluded
166
+ from the package's `files`).
167
+
168
+ ## Publishing
169
+
170
+ This package publishes **publicly to the npmjs registry** as
171
+ `@saar-ai/web-widget`, `publishConfig: { "access": "public", "registry":
172
+ "https://registry.npmjs.org/" }` — the ONE package in this workspace that
173
+ does not publish to AWS CodeArtifact. docs/WIDGET_EMBED_PLAN.md §5.1 called
174
+ for exactly this: a merchant installing this package cannot authenticate to
175
+ this org's restricted CodeArtifact registry, so it needs a different scope
176
+ (`@saar-ai`, not `@wesence`) and a different registry from every other
177
+ `@wesence/*` package. See
178
+ [`docs/RELEASING.md`](../../docs/RELEASING.md#how-web-widget-releases-differently)
179
+ for how the release pipeline routes this one package differently, and
180
+ [`AGENTS.md`](./AGENTS.md#publishing) for the full mechanics.
181
+
182
+ **`dependencies` is genuinely empty.** Every workspace (`@wesence/branding`,
183
+ `@wesence/shared-types`, `@wesence/voice-protocol`, `@saar-ai/widget-bridge`)
184
+ and third-party (`clsx`, `lucide-react`, `tailwind-merge`, `livekit-client`,
185
+ `socket.io-client`) runtime dependency is bundled into `dist/` at build time
186
+ by `vite.npm.config.ts` — a real bundler pass, not `tsc`'s pass-through
187
+ specifiers — so a public `npm install @saar-ai/web-widget` never tries to
188
+ resolve a restricted `@wesence/*` package. `react`/`react-dom` are the only
189
+ required peers; `next` is an optional peer, resolved only by the `./next`
190
+ subpath. `src/__tests__/dist-npm-bundle.test.ts` proves both claims against
191
+ the real built `dist/` output: no `@wesence/` import specifier survives into
192
+ the shipped JS, and `package.json.dependencies` is `{}`.
193
+
194
+ `tools/check-publishable.mjs` still hard-fails a `"publishable"` package
195
+ whose `publishConfig.access !== "restricted"` for every OTHER package — this
196
+ one has a narrow, reasoned allow-entry in `tools/check-config.json`
197
+ (`"publishable-public-access"`), keyed to this package's path and requiring
198
+ `publishConfig.access` to be exactly `"public"`. See that guard's own
199
+ comment and [`AGENTS.md`](./AGENTS.md#publishing) for the reasoning.
200
+
201
+ ## Status
202
+
203
+ Phase 4 of the widget embed plan: the CDN build has landed alongside Phase
204
+ 3's React UI. The rest of `apps/web/src/components/widget/*` (the
205
+ translation catalogue, the transport, the `next/link` navigation intent,
206
+ `socket.io-client`'s lazy import) moved here in Phase 3 step 2. Phase 5's
207
+ distribution mechanics — the `@saar-ai/web-widget/next` subpath,
208
+ `useNextBridge`, and the public npm rename above — have all landed. See
209
+ "Publishing" above for the rename's mechanics.
@@ -0,0 +1,41 @@
1
+ import { type BotState } from './bot-state.js';
2
+ import { type WidgetMessages } from './messages.js';
3
+ /**
4
+ * The agent avatar: two counter-rotating gradient blobs behind a pulsing core,
5
+ * wrapped in a halo and a ring whose colour and tempo carry the agent's state.
6
+ *
7
+ * ## It is an image, not a control
8
+ *
9
+ * `role="img"` with a stateful accessible name. The product name in it is a
10
+ * PROP, never a compiled-in constant: this package ships to merchants on
11
+ * public npm, and importing `@wesence/branding` here would bundle this
12
+ * deployment's own brand defaults into every consumer's tarball — eagerly,
13
+ * for a value only the host knows. The host passes its own name; absent one,
14
+ * the label degrades to the brand-neutral fallback in `messages.ts`.
15
+ * The avatar is never clickable — the mic button below it is the control. A
16
+ * decorative element that also happens to be the affordance is the classic way
17
+ * a widget becomes unusable by keyboard, and splitting them keeps the focus
18
+ * order honest.
19
+ *
20
+ * ## State is announced, not only animated
21
+ *
22
+ * Every state difference is expressed three ways: colour, tempo, and the
23
+ * accessible name. Animation alone excludes anyone with reduced-motion enabled
24
+ * (where `globals.css` stops the animation entirely) and anyone who cannot
25
+ * distinguish the ramp. `aria-live="polite"` on the name means a screen-reader
26
+ * user hears the turn change rather than sitting in silence wondering whether
27
+ * the agent is still listening.
28
+ */
29
+ export declare function BotAvatar({ state, size, messages, productName, }: {
30
+ state: BotState;
31
+ size?: number;
32
+ /** Defaults to the package's brand-neutral fallback — see `messages.ts`. */
33
+ messages?: WidgetMessages;
34
+ /**
35
+ * Product name interpolated into the accessible label. Empty (the default)
36
+ * leaves the `{product}` placeholder to resolve against the message
37
+ * catalogue's own neutral phrasing rather than naming anyone.
38
+ */
39
+ productName?: string;
40
+ }): import("react").JSX.Element;
41
+ //# sourceMappingURL=bot-avatar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bot-avatar.d.ts","sourceRoot":"","sources":["../src/bot-avatar.tsx"],"names":[],"mappings":"AAEA,OAAO,EAA2B,KAAK,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AACxE,OAAO,EAAwC,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAE1F;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,SAAS,CAAC,EACxB,KAAK,EACL,IAAU,EACV,QAAgC,EAChC,WAAgB,GACjB,EAAE;IACD,KAAK,EAAE,QAAQ,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,4EAA4E;IAC5E,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,+BAuFA"}
@@ -0,0 +1,39 @@
1
+ import type { BotState } from './bot-state.js';
2
+ export type { BotState };
3
+ /**
4
+ * The concierge's face, in two sizes: the small floating trigger and the large
5
+ * animated orb inside the panel.
6
+ *
7
+ * ## It names no product
8
+ *
9
+ * This is a design-system component an adopter inherits, so the accessible name
10
+ * arrives as `label` or not at all — a hardcoded product name would ship one
11
+ * brand inside another company's product (`tools/check-branding.mjs`, which is
12
+ * what caught it when this file moved out of `apps/marketing`).
13
+ *
14
+ * Omitting `label` makes the face DECORATIVE, and that is the right default
15
+ * inside `ConciergeShell`: the trigger button already has its own accessible
16
+ * name and the panel already announces the state in a live region, so a name
17
+ * here would be the same information a third time.
18
+ *
19
+ * Ported verbatim from the marketing design source — presentation only, no
20
+ * state of its own. Every animation is decorative and is stopped wholesale
21
+ * under `prefers-reduced-motion` (see globals.css), which is safe precisely
22
+ * because nothing here carries information the motion is the only carrier of;
23
+ * the state is also announced in text by the widget's live region.
24
+ *
25
+ * `BotState` itself is `bot-state.ts`'s canonical union (moved here from
26
+ * `apps/web/src/components/widget/bot-state.ts`, docs/WIDGET_EMBED_PLAN.md §4
27
+ * Phase 3) — re-exported rather than redeclared, so `VoiceWidget`'s `state`
28
+ * prop and `ConciergeShell`'s `state` prop are the exact same type, not two
29
+ * structurally-identical unions that happen to agree.
30
+ */
31
+ type Size = 'sm' | 'lg';
32
+ export declare function BotFace({ state, size, messageArrived, label, }: {
33
+ state?: BotState;
34
+ size?: Size;
35
+ messageArrived?: boolean;
36
+ /** Accessible name. Omitted ⇒ decorative; see this module's doc comment. */
37
+ label?: string;
38
+ }): import("react").JSX.Element;
39
+ //# sourceMappingURL=bot-face.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bot-face.d.ts","sourceRoot":"","sources":["../src/bot-face.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C,YAAY,EAAE,QAAQ,EAAE,CAAC;AAEzB;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,KAAK,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;AAExB,wBAAgB,OAAO,CAAC,EACtB,KAAc,EACd,IAAW,EACX,cAAsB,EACtB,KAAK,GACN,EAAE;IACD,KAAK,CAAC,EAAE,QAAQ,CAAC;IACjB,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,4EAA4E;IAC5E,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,+BAKA"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The voice widget's visible state.
3
+ *
4
+ * Kept as data, separate from the component, for one reason: the state is the
5
+ * only thing telling a caller whether the agent is hearing them or answering
6
+ * them, and that has to be assertable without rendering an SVG. Animation class
7
+ * names and the accessible-name key are derived here and tested directly.
8
+ */
9
+ export declare const BOT_STATES: readonly ['idle', 'listening', 'thinking', 'speaking'];
10
+ export type BotState = (typeof BOT_STATES)[number];
11
+ export interface BotVisuals {
12
+ /** Soft outer glow. */
13
+ readonly halo: string;
14
+ /** Tight ring pulse just inside the halo. */
15
+ readonly ring: string;
16
+ /** The two counter-rotating gradient blobs. */
17
+ readonly blobA: string;
18
+ readonly blobB: string;
19
+ /** The bright centre. */
20
+ readonly core: string;
21
+ }
22
+ /**
23
+ * @param state the widget's current state
24
+ * @returns animation utilities for each layer of the avatar
25
+ */
26
+ export declare function visualsFor(state: BotState): BotVisuals;
27
+ /**
28
+ * Message key for the avatar's accessible name.
29
+ *
30
+ * The avatar is `role="img"`, so this string IS the state for a screen-reader
31
+ * user. It is a translation key rather than a literal because the widget faces
32
+ * end users in every locale the product serves, not console operators.
33
+ *
34
+ * @param state the widget's current state
35
+ */
36
+ export declare function labelKeyFor(state: BotState): `state_${BotState}`;
37
+ /** Whether a value is a state this widget knows how to render. */
38
+ export declare function isBotState(value: unknown): value is BotState;
39
+ //# sourceMappingURL=bot-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bot-state.d.ts","sourceRoot":"","sources":["../src/bot-state.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU,YAAI,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,CAAU,CAAC;AAEjF,MAAM,MAAM,QAAQ,GAAG,CAAC,OAAO,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC;AAEnD,MAAM,WAAW,UAAU;IACzB,uBAAuB;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,6CAA6C;IAC7C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,+CAA+C;IAC/C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,yBAAyB;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAyCD;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,QAAQ,GAAG,UAAU,CAEtD;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,QAAQ,GAAG,SAAS,QAAQ,EAAE,CAEhE;AAED,kEAAkE;AAClE,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAE5D"}
@@ -0,0 +1,173 @@
1
+ import { a as httpUrl, c as number, i as discriminatedUnion, l as object, n as array, o as literal, r as boolean, u as string } from "./schemas-Bl_6mxe4.js";
2
+ //#region ../widget-protocol/dist/chat.js
3
+ /**
4
+ * The webchat SSE wire contract, and the sidecar `widgetEvent` a tool result
5
+ * may carry to short-circuit into one of those events.
6
+ *
7
+ * ## Why this lives in `@saar-ai/widget-protocol`, zod, not a plain interface
8
+ *
9
+ * Two independent runtimes read this shape: `apps/api`'s
10
+ * `widget-chat.controller.ts` WRITES it onto an SSE response, and
11
+ * `@saar-ai/web-widget`'s voice leg (`use-voice-session.ts`, via the
12
+ * `widget.event` sidecar on the telemetry channel — see `./telemetry.ts`)
13
+ * PARSES `WidgetToolEventSchema` off it. A hand-maintained interface on each
14
+ * side drifts silently — the failure mode is a widget that renders
15
+ * `undefined` for a field the server renamed. Zod schemas, exported from one
16
+ * package both sides can import, make the shape a single source of truth and
17
+ * let each side `.parse()`/`.safeParse()` at its own boundary instead of
18
+ * trusting an unchecked cast.
19
+ *
20
+ * Moved here from the framework-inherited `@wesence/shared-types` — this
21
+ * package's own `AGENTS.md` explains why a widget-only contract does not
22
+ * belong inside a package a framework regeneration can silently clobber, and
23
+ * why it must not be reachable from `@saar-ai/web-widget`'s published bundle
24
+ * via a `@wesence/*` import path at all (docs/PACKAGE_DISTRIBUTION.md).
25
+ *
26
+ * ## The six event types, and why cards/checkout are separate events from text
27
+ *
28
+ * A reply may interleave prose with product/price/checkout data. Prices,
29
+ * stock, and product attributes are NEVER stated as text by the model (see
30
+ * `widget-chat.service.ts`'s system-prompt guardrail) — they arrive only as
31
+ * `cards`, sourced from a tool result, so the widget can render them as
32
+ * structured UI (an image, a price, an availability badge) rather than text
33
+ * the model could hallucinate. The real checkout URL is likewise never typed
34
+ * by the model — it arrives only as `checkout`.
35
+ *
36
+ * - `text-delta` — one chunk of the assistant's streamed reply.
37
+ * - `cards` — one or more product/curation cards to render.
38
+ * - `escalated` — the conversation just moved to a human/queue; the AI
39
+ * will not reply further on this turn. The widget should show a "connecting
40
+ * you with a person" state and start polling `/widget/messages`.
41
+ * - `checkout` — a real Shopify cart permalink to hand the shopper off
42
+ * to; the widget renders a "Go to checkout" control around `url`.
43
+ * - `done` — the turn is over. Carries the turn id so the widget can
44
+ * correlate a later `/widget/messages` page against what it already
45
+ * rendered inline.
46
+ * - `error` — the turn failed. `message` is safe to show the visitor
47
+ * (never a raw exception/stack).
48
+ *
49
+ * ## `widgetEvent` — the tool-result sidecar
50
+ *
51
+ * A tool (e.g. a product-search tool) may attach `widgetEvent` to its output
52
+ * to ask the chat loop to forward one of these events verbatim, alongside the
53
+ * tool's own return value the model sees. Only `cards`, `escalated`, and
54
+ * `checkout` are valid sidecar events — `text-delta`/`done`/`error` are
55
+ * lifecycle events the runtime itself owns and a tool must never emit.
56
+ */
57
+ /** Bound for a display string a card renders. Never free-form model prose. */
58
+ var CARD_TEXT_MAX = 500;
59
+ /** Bound for an id-shaped field (product/variant/curation ids). */
60
+ var ID_MAX = 200;
61
+ /**
62
+ * One product/curation card. `priceMinor` is the ISO 4217 minor-unit integer
63
+ * (cents, paise, …) — never a float — and `currency` is the ISO 4217 code, so
64
+ * the widget formats price itself rather than trusting a pre-formatted
65
+ * string the model could get wrong.
66
+ */
67
+ var WidgetChatCardSchema = object({
68
+ productId: string().min(1).max(ID_MAX),
69
+ /** The INTERNAL catalog UUID (`curation_items.variant_id`) — never a platform id. See `platformVariantId` for what a storefront `addToCart` bridge actually needs. */
70
+ variantId: string().min(1).max(ID_MAX).optional(),
71
+ /**
72
+ * The PLATFORM-NATIVE variant id (e.g. Shopify's numeric `/cart/add.js`
73
+ * id) — extracted server-side from the variant's provider GID via
74
+ * `apps/api/src/catalog/checkout-permalink.ts`'s
75
+ * `parseShopifyVariantNumericId`, the SAME parser the checkout permalink
76
+ * uses, never a string-slice of `variantId`. `@saar-ai/web-widget`'s
77
+ * `resolveAddToCartHandler` calls a storefront bridge's `addToCart` with
78
+ * THIS field, never `variantId` (adversarial-review finding #2 — the
79
+ * internal UUID is meaningless to `ShopifyBridge`'s `POST /cart/add.js`).
80
+ * Absent whenever the underlying variant's external id isn't a
81
+ * recognised platform GID (§5.3's "degrade, never fabricate" — never
82
+ * guessed) — the widget then offers no add-to-cart action for the card
83
+ * and falls back to a PDP navigation instead.
84
+ */
85
+ platformVariantId: string().min(1).max(ID_MAX).optional(),
86
+ title: string().min(1).max(CARD_TEXT_MAX),
87
+ /** http(s) only — `z.httpUrl()` refuses `javascript:`/`data:`/etc, the same scheme allowlist `conversations/attribution.ts` enforces for stored URLs. */
88
+ imageUrl: httpUrl().optional(),
89
+ /**
90
+ * The product's storefront handle, so the widget's card can link to its PDP.
91
+ *
92
+ * A SLUG, never a URL or a path: the widget's host builds the href from it
93
+ * (`widget-launcher.tsx`'s `productHref`), so anything path-like here would
94
+ * let a catalogue row steer where a card points. The character class below
95
+ * is what a Shopify handle actually is, and it cannot express a scheme, a
96
+ * host, a `..` segment or a leading slash.
97
+ */
98
+ handle: string().min(1).max(ID_MAX).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/i).optional(),
99
+ /** ISO 4217 minor units — an integer, never a float. */
100
+ priceMinor: number().int().min(0),
101
+ /** ISO 4217 currency code, e.g. "USD". */
102
+ currency: string().length(3),
103
+ available: boolean(),
104
+ /** Short, optional "why this" — e.g. "matches your search". Never a price/stock claim. */
105
+ reason: string().max(CARD_TEXT_MAX).optional()
106
+ });
107
+ var WidgetChatTextDeltaEventSchema = object({
108
+ type: literal("text-delta"),
109
+ delta: string()
110
+ });
111
+ var WidgetChatCardsEventSchema = object({
112
+ type: literal("cards"),
113
+ /** Correlates this render back to whichever tool call produced it, when the tool supplies one. */
114
+ curationId: string().min(1).max(ID_MAX).optional(),
115
+ items: array(WidgetChatCardSchema).min(1).max(20)
116
+ });
117
+ var WidgetChatEscalatedEventSchema = object({ type: literal("escalated") });
118
+ /**
119
+ * A real Shopify checkout handoff — `checkout_handoff` (the concierge tool)
120
+ * emits this as a `widgetEvent` sidecar so the widget can render a "Go to
121
+ * checkout" control instead of the model reciting a raw URL. `url` is a
122
+ * SERVER-BUILT Shopify cart permalink (`apps/api/src/catalog/checkout-permalink.ts`)
123
+ * — never a client- or model-supplied value; it carries no internal
124
+ * identifier, only Shopify variant ids/quantities and an opaque attribution
125
+ * token (see that module's doc comment).
126
+ */
127
+ var WidgetChatCheckoutEventSchema = object({
128
+ type: literal("checkout"),
129
+ handoffId: string().min(1).max(ID_MAX),
130
+ url: httpUrl(),
131
+ itemCount: number().int().positive()
132
+ });
133
+ var WidgetChatDoneEventSchema = object({
134
+ type: literal("done"),
135
+ turnId: string().min(1)
136
+ });
137
+ var WidgetChatErrorEventSchema = object({
138
+ type: literal("error"),
139
+ /** Safe to show the visitor as-is — never a raw exception message or stack. */
140
+ message: string().min(1).max(CARD_TEXT_MAX)
141
+ });
142
+ /** The full SSE event union — every `event:`/`data:` pair `/widget/chat` may write. */
143
+ var WidgetChatSseEventSchema = discriminatedUnion("type", [
144
+ WidgetChatTextDeltaEventSchema,
145
+ WidgetChatCardsEventSchema,
146
+ WidgetChatEscalatedEventSchema,
147
+ WidgetChatCheckoutEventSchema,
148
+ WidgetChatDoneEventSchema,
149
+ WidgetChatErrorEventSchema
150
+ ]);
151
+ /**
152
+ * What a tool result may carry, under an `output.widgetEvent` key, to ask the
153
+ * chat loop to forward one of these as its own SSE event. Deliberately a
154
+ * NARROWER union than {@link WidgetChatSseEventSchema} — `text-delta`,
155
+ * `done`, and `error` are lifecycle events the runtime alone controls; a tool
156
+ * asserting one of those could inject a fake "done" mid-stream or spoof a
157
+ * fake error to the visitor.
158
+ */
159
+ var WidgetToolEventSchema = discriminatedUnion("type", [
160
+ WidgetChatCardsEventSchema,
161
+ WidgetChatEscalatedEventSchema,
162
+ WidgetChatCheckoutEventSchema
163
+ ]);
164
+ /** Parse a tool's raw output for an optional, well-shaped `widgetEvent`. Never throws. */
165
+ function extractWidgetToolEvent(output) {
166
+ if (typeof output !== "object" || output === null) return null;
167
+ const candidate = output["widgetEvent"];
168
+ if (candidate === void 0) return null;
169
+ const parsed = WidgetToolEventSchema.safeParse(candidate);
170
+ return parsed.success ? parsed.data : null;
171
+ }
172
+ //#endregion
173
+ export { WidgetChatCardSchema, WidgetChatCardsEventSchema, WidgetChatCheckoutEventSchema, WidgetChatDoneEventSchema, WidgetChatErrorEventSchema, WidgetChatEscalatedEventSchema, WidgetChatSseEventSchema, WidgetChatTextDeltaEventSchema, WidgetToolEventSchema, extractWidgetToolEvent };