claudius-chat-widget 1.6.0 → 1.9.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 (39) hide show
  1. package/dist/claudius.cjs +2 -2
  2. package/dist/claudius.iife.js +11 -11
  3. package/dist/claudius.js +871 -608
  4. package/dist/index.d.cts +676 -0
  5. package/dist/index.d.ts +676 -12
  6. package/package.json +20 -7
  7. package/dist/api/client.d.ts +0 -24
  8. package/dist/api/errors.d.ts +0 -9
  9. package/dist/api/index.d.ts +0 -4
  10. package/dist/api/types.d.ts +0 -22
  11. package/dist/components/ChatInput.d.ts +0 -9
  12. package/dist/components/ChatMessage.d.ts +0 -10
  13. package/dist/components/ChatSources.d.ts +0 -7
  14. package/dist/components/ChatToggleButton.d.ts +0 -10
  15. package/dist/components/ChatWidget.d.ts +0 -29
  16. package/dist/components/ChatWindow.d.ts +0 -21
  17. package/dist/components/GreetingBubble.d.ts +0 -10
  18. package/dist/components/SourceIcon.d.ts +0 -7
  19. package/dist/embed.d.ts +0 -38
  20. package/dist/hooks/useChat.d.ts +0 -20
  21. package/dist/hooks/useFocusTrap.d.ts +0 -2
  22. package/dist/hooks/useMediaQuery.d.ts +0 -1
  23. package/dist/hooks/useSwipeToDismiss.d.ts +0 -4
  24. package/dist/hooks/useTriggers.d.ts +0 -32
  25. package/dist/i18n.d.ts +0 -21
  26. package/dist/locales/de.d.ts +0 -2
  27. package/dist/locales/en.d.ts +0 -2
  28. package/dist/locales/es.d.ts +0 -2
  29. package/dist/locales/fr.d.ts +0 -2
  30. package/dist/locales/index.d.ts +0 -9
  31. package/dist/main.d.ts +0 -1
  32. package/dist/test-utils/MockChatApiClient.d.ts +0 -64
  33. package/dist/theme/index.d.ts +0 -4
  34. package/dist/theme/resolve.d.ts +0 -19
  35. package/dist/theme/themes.d.ts +0 -8
  36. package/dist/theme/types.d.ts +0 -34
  37. package/dist/theme/useTheme.d.ts +0 -14
  38. package/dist/utils/sanitize.d.ts +0 -36
  39. package/dist/utils/stripAnnouncementFormatting.d.ts +0 -1
@@ -0,0 +1,676 @@
1
+ import { JSX as JSX_2 } from 'react/jsx-runtime';
2
+
3
+ /** Options for {@link pluginAnalytics}. */
4
+ export declare interface AnalyticsPluginOptions {
5
+ /**
6
+ * Sink called once per chat lifecycle event. Wire it to your analytics
7
+ * provider (Google Analytics, PostHog, Segment, a custom endpoint, ...).
8
+ */
9
+ onEvent: (event: ClaudiusAnalyticsEvent) => void;
10
+ /**
11
+ * Include message text in `message_sent` / `message_received` events. Set to
12
+ * `false` to record only the character count and avoid logging user content.
13
+ * @defaultValue `true`
14
+ */
15
+ includeContent?: boolean;
16
+ }
17
+
18
+ /**
19
+ * Context for {@link ClaudiusPlugin.onBeforeSend}. Adds the ability to
20
+ * short-circuit the request before it reaches the network.
21
+ */
22
+ export declare interface BeforeSendContext extends PluginContext {
23
+ /**
24
+ * Skip the network request and render this assistant reply instead. The
25
+ * (possibly modified) user message is still shown. Stops the hook chain —
26
+ * later plugins' `onBeforeSend` hooks do not run.
27
+ */
28
+ respondWith(reply: string | PluginReply): void;
29
+ /**
30
+ * Cancel the send entirely: no request is made and nothing is rendered (the
31
+ * user message is dropped). Stops the hook chain. Use for client-only
32
+ * commands the chat should swallow.
33
+ */
34
+ abort(reason?: string): void;
35
+ }
36
+
37
+ /** Names of the built-in themes shipped in {@link builtinThemes}. */
38
+ export declare type BuiltinThemeName = "default" | "minimal" | "playful" | "corporate";
39
+
40
+ /**
41
+ * Built-in themes. `default` is intentionally empty: the baked-in token
42
+ * defaults (see tailwind.config.ts fallbacks and the dark block in
43
+ * styles.css) ARE the default theme.
44
+ */
45
+ export declare const builtinThemes: Record<BuiltinThemeName, ClaudiusTheme>;
46
+
47
+ /** Options for {@link pluginCannedResponses}. */
48
+ export declare interface CannedResponsesOptions {
49
+ /** Rules evaluated in order; the first match wins. */
50
+ rules: CannedRule[];
51
+ /**
52
+ * Make `string` matchers case-sensitive.
53
+ * @defaultValue `false`
54
+ */
55
+ caseSensitive?: boolean;
56
+ }
57
+
58
+ /** A single intent-matching rule for {@link pluginCannedResponses}. */
59
+ export declare interface CannedRule {
60
+ /**
61
+ * How to match the user's message:
62
+ * - `string` — case-insensitive substring match (see
63
+ * {@link CannedResponsesOptions.caseSensitive}).
64
+ * - `RegExp` — tested against the message content.
65
+ * - function — receives the content and returns whether it matches.
66
+ */
67
+ match: string | RegExp | ((content: string) => boolean);
68
+ /** The reply rendered when the rule matches. */
69
+ reply: string | PluginReply;
70
+ }
71
+
72
+ /**
73
+ * Typed client for the Claudius Worker chat API. Handles debouncing,
74
+ * per-attempt timeouts, and automatic retries with backoff for transient
75
+ * failures (HTTP 429/503, network errors, timeouts).
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * const client = new ChatApiClient("https://api.example.com");
80
+ * const { reply } = await client.sendMessage([
81
+ * { id: "1", role: "user", content: "Hello" },
82
+ * ]);
83
+ * ```
84
+ */
85
+ export declare class ChatApiClient {
86
+ private readonly baseUrl;
87
+ private readonly maxRetries;
88
+ private readonly debounceMs;
89
+ private readonly timeoutMs;
90
+ private lastSendTime;
91
+ /**
92
+ * Create a chat client for the given Worker base URL.
93
+ *
94
+ * @param baseUrl - Base URL of the Worker. Requests post to `${baseUrl}/api/chat`.
95
+ * @param options - Optional retry, debounce, and timeout settings.
96
+ */
97
+ constructor(baseUrl: string, options?: ChatApiClientOptions);
98
+ /**
99
+ * Send the conversation to the chat endpoint and return the assistant's
100
+ * reply, retrying transient failures with backoff up to
101
+ * {@link ChatApiClientOptions.maxRetries} times.
102
+ *
103
+ * @param messages - The full conversation so far, oldest message first.
104
+ * @returns The assistant's reply and any cited sources.
105
+ * @throws {@link DebounceError} when called within the debounce window.
106
+ * @throws {@link ChatApiError} when the request fails after all retries.
107
+ */
108
+ sendMessage(messages: ChatMessage[]): Promise<ChatResponse>;
109
+ private fetchWithTimeout;
110
+ private isRetryable;
111
+ private getRetryDelay;
112
+ private delay;
113
+ }
114
+
115
+ /**
116
+ * Options for {@link ChatApiClient}.
117
+ */
118
+ export declare interface ChatApiClientOptions {
119
+ /**
120
+ * Maximum retries after the first attempt, for retryable failures (HTTP
121
+ * 429/503, network errors, timeouts).
122
+ * @defaultValue `2`
123
+ */
124
+ maxRetries?: number;
125
+ /**
126
+ * Minimum gap between sends, in milliseconds. A send inside this window
127
+ * rejects with {@link DebounceError}. Set to 0 to disable.
128
+ * @defaultValue `300`
129
+ */
130
+ debounceMs?: number;
131
+ /**
132
+ * Per-attempt request timeout in milliseconds. Aborts the in-flight fetch
133
+ * via `AbortController` and surfaces a retryable {@link ChatApiError} with
134
+ * code `"TIMEOUT"`. Set to 0 to disable.
135
+ * @defaultValue `30000`
136
+ */
137
+ timeoutMs?: number;
138
+ }
139
+
140
+ /**
141
+ * Error thrown by {@link ChatApiClient} when a chat request ultimately fails:
142
+ * either after exhausting retries, or immediately for a non-retryable status.
143
+ */
144
+ export declare class ChatApiError extends Error {
145
+ /** HTTP status code, or `0` for network and timeout failures. */
146
+ readonly status: number;
147
+ /** Machine-readable error code, when available (e.g. `"TIMEOUT"`). */
148
+ readonly code?: string | undefined;
149
+ /** Seconds to wait before retrying, parsed from the `Retry-After` header. */
150
+ readonly retryAfter?: number | undefined;
151
+ /**
152
+ * Create a {@link ChatApiError}.
153
+ *
154
+ * @param message - Human-readable error message.
155
+ * @param status - HTTP status code, or `0` for network and timeout failures.
156
+ * @param code - Optional machine-readable error code (e.g. `"TIMEOUT"`, `"NETWORK_ERROR"`).
157
+ * @param retryAfter - Seconds to wait before retrying, from the `Retry-After` header.
158
+ */
159
+ constructor(message: string,
160
+ /** HTTP status code, or `0` for network and timeout failures. */
161
+ status: number,
162
+ /** Machine-readable error code, when available (e.g. `"TIMEOUT"`). */
163
+ code?: string | undefined,
164
+ /** Seconds to wait before retrying, parsed from the `Retry-After` header. */
165
+ retryAfter?: number | undefined);
166
+ }
167
+
168
+ /**
169
+ * Error response body returned by the Worker when a chat request fails.
170
+ */
171
+ export declare interface ChatErrorResponse {
172
+ /** Human-readable error message. */
173
+ error: string;
174
+ /** Optional machine-readable error code (e.g. `"RATE_LIMITED"`). */
175
+ code?: string;
176
+ }
177
+
178
+ /**
179
+ * A single chat message exchanged between the user and the assistant.
180
+ */
181
+ export declare interface ChatMessage {
182
+ /** Stable unique identifier, used as the React list key. */
183
+ id: string;
184
+ /** Who authored the message. */
185
+ role: "user" | "assistant";
186
+ /** Plain-text message body. */
187
+ content: string;
188
+ /** Sources cited by the assistant for this message, when any. */
189
+ sources?: Source[];
190
+ }
191
+
192
+ /**
193
+ * Request payload sent to the Worker `POST /api/chat` endpoint.
194
+ */
195
+ export declare interface ChatRequest {
196
+ /** The full conversation so far, oldest message first. */
197
+ messages: ChatMessage[];
198
+ }
199
+
200
+ /**
201
+ * Successful response body from `POST /api/chat`.
202
+ */
203
+ export declare interface ChatResponse {
204
+ /** The assistant's reply text. */
205
+ reply: string;
206
+ /** Sources the assistant cited, when any. */
207
+ sources?: Source[];
208
+ }
209
+
210
+ /**
211
+ * Root Claudius chat widget: a floating toggle button that opens a chat window
212
+ * backed by the Worker chat API. Render a single instance on the page.
213
+ *
214
+ * @param props - See {@link ChatWidgetProps}.
215
+ * @example
216
+ * ```tsx
217
+ * <ChatWidget apiUrl="https://api.example.com" title="Support" />
218
+ * ```
219
+ */
220
+ export declare function ChatWidget({ apiUrl, title, subtitle, welcomeMessage, placeholder, persistMessages, storageKeyPrefix, requestTimeoutMs, theme, accentColor, position, locale, translations: translationOverrides, triggers, plugins, }: ChatWidgetProps): JSX_2.Element;
221
+
222
+ /**
223
+ * Props for the {@link ChatWidget} component.
224
+ */
225
+ export declare interface ChatWidgetProps {
226
+ /** Absolute URL of the Worker chat endpoint (e.g. `https://api.example.com`). */
227
+ apiUrl: string;
228
+ /** Header title. Falls back to the active locale's default title. */
229
+ title?: string;
230
+ /** Header subtitle shown beneath the title. */
231
+ subtitle?: string;
232
+ /** First assistant message shown when the chat opens. */
233
+ welcomeMessage?: string;
234
+ /** Placeholder text for the message input. */
235
+ placeholder?: string;
236
+ /**
237
+ * Persist the conversation to storage so it survives reloads.
238
+ * @defaultValue `false`
239
+ */
240
+ persistMessages?: boolean;
241
+ /** Prefix for the storage key used when {@link ChatWidgetProps.persistMessages} is enabled. */
242
+ storageKeyPrefix?: string;
243
+ /** Abort a chat request after this many milliseconds. */
244
+ requestTimeoutMs?: number;
245
+ /**
246
+ * Color-scheme mode ("light" | "dark" | "auto"), a built-in theme name
247
+ * ("default" | "minimal" | "playful" | "corporate"), an inline
248
+ * ClaudiusTheme object, or a URL to a theme JSON file.
249
+ * @defaultValue `"light"`
250
+ */
251
+ theme?: ClaudiusThemeInput;
252
+ /** Accent color override; wins over the theme's accent in both light and dark. */
253
+ accentColor?: string;
254
+ /**
255
+ * Corner of the viewport the widget docks to.
256
+ * @defaultValue `"bottom-right"`
257
+ */
258
+ position?: WidgetPosition;
259
+ /** BCP-47 locale used to select built-in translations. */
260
+ locale?: LocaleCode;
261
+ /** Partial overrides merged over the resolved locale translations. */
262
+ translations?: Partial<ClaudiusTranslations>;
263
+ /** Proactive open/greeting rules evaluated against the current page. */
264
+ triggers?: Trigger[];
265
+ /**
266
+ * Middleware run around each message: `onBeforeSend`, `onAfterReceive`, and
267
+ * `onError`. Hooks run in array order and may modify, replace, or
268
+ * short-circuit messages. See {@link ClaudiusPlugin}.
269
+ */
270
+ plugins?: ClaudiusPlugin[];
271
+ }
272
+
273
+ /** An analytics event emitted by {@link pluginAnalytics}. */
274
+ export declare type ClaudiusAnalyticsEvent = {
275
+ /** Event discriminant. */
276
+ type: "message_sent";
277
+ /** Always `"user"`. */
278
+ role: "user";
279
+ /** Message text, or `""` when `includeContent` is `false`. */
280
+ content: string;
281
+ /** Length of the message in characters. */
282
+ chars: number;
283
+ } | {
284
+ /** Event discriminant. */
285
+ type: "message_received";
286
+ /** Always `"assistant"`. */
287
+ role: "assistant";
288
+ /** Reply text, or `""` when `includeContent` is `false`. */
289
+ content: string;
290
+ /** Length of the reply in characters. */
291
+ chars: number;
292
+ } | {
293
+ /** Event discriminant. */
294
+ type: "chat_error";
295
+ /** The error message. */
296
+ message: string;
297
+ /** Machine-readable error code, when available (e.g. `"TIMEOUT"`). */
298
+ code?: string;
299
+ };
300
+
301
+ /**
302
+ * A client-side middleware that runs around the chat message lifecycle. Pass
303
+ * an array of plugins to {@link ChatWidget} via the `plugins` prop; hooks run
304
+ * in array order.
305
+ *
306
+ * Hooks may be async, and may modify, replace, or short-circuit messages. A
307
+ * hook that throws is caught and logged — a misbehaving plugin will not break
308
+ * the chat — so security-sensitive transforms (e.g. PII redaction) should be
309
+ * written defensively.
310
+ *
311
+ * @example
312
+ * ```ts
313
+ * const logger: ClaudiusPlugin = {
314
+ * name: "logger",
315
+ * onBeforeSend: (message) => { console.log("sending", message.content); },
316
+ * onAfterReceive: (message) => { console.log("received", message.content); },
317
+ * };
318
+ * ```
319
+ */
320
+ export declare interface ClaudiusPlugin {
321
+ /** Stable identifier, used in log messages. */
322
+ name: string;
323
+ /**
324
+ * Runs before the user message is sent. Return a {@link ChatMessage} to
325
+ * replace it (the returned message is both displayed and sent), return
326
+ * nothing to leave it unchanged, or call {@link BeforeSendContext.respondWith}
327
+ * / {@link BeforeSendContext.abort} to short-circuit.
328
+ */
329
+ onBeforeSend?(message: ChatMessage, ctx: BeforeSendContext): MaybePromise<ChatMessage | void>;
330
+ /**
331
+ * Runs after the assistant reply is received, before it is rendered. Return
332
+ * a {@link ChatMessage} to replace it, or nothing to leave it unchanged.
333
+ */
334
+ onAfterReceive?(message: ChatMessage, ctx: PluginContext): MaybePromise<ChatMessage | void>;
335
+ /**
336
+ * Runs when a send fails. Observe the error, or call
337
+ * {@link ErrorContext.respondWith} to render a fallback reply instead of the
338
+ * error UI.
339
+ */
340
+ onError?(error: Error, ctx: ErrorContext): MaybePromise<void>;
341
+ }
342
+
343
+ /**
344
+ * A Claudius design-token theme. Every value is a CSS string applied via
345
+ * --cl-* custom properties. `colors` apply to both light and dark modes
346
+ * unless `colorsDark` overrides a token for dark mode specifically.
347
+ *
348
+ * JSON theme files validate against
349
+ * https://claudius-docs.pages.dev/schema/theme.v1.json
350
+ */
351
+ export declare interface ClaudiusTheme {
352
+ /** Optional JSON Schema URL, for editor validation and autocomplete. */
353
+ $schema?: string;
354
+ /** Human-readable theme name. */
355
+ name?: string;
356
+ /** Initial color scheme this theme is designed for. Defaults to "light". */
357
+ colorScheme?: "light" | "dark" | "auto";
358
+ /** Color token overrides applied in both light and dark mode. */
359
+ colors?: Partial<Record<ThemeColorToken, string>>;
360
+ /** Color token overrides applied only in dark mode, layered over {@link ClaudiusTheme.colors}. */
361
+ colorsDark?: Partial<Record<ThemeColorToken, string>>;
362
+ /** Border-radius token overrides. */
363
+ radii?: Partial<Record<ThemeRadiusToken, string>>;
364
+ /** Box-shadow token overrides. */
365
+ shadows?: Partial<Record<ThemeShadowToken, string>>;
366
+ /** Font-family token overrides. */
367
+ fonts?: Partial<Record<ThemeFontToken, string>>;
368
+ }
369
+
370
+ /**
371
+ * Everything the `theme` option accepts: the original color-scheme modes, a
372
+ * built-in theme name, an inline theme object, or a URL to a theme JSON file.
373
+ * `(string & {})` keeps literal autocomplete while allowing URLs.
374
+ */
375
+ export declare type ClaudiusThemeInput = "light" | "dark" | "auto" | BuiltinThemeName | ClaudiusTheme | (string & {});
376
+
377
+ /**
378
+ * Every user-facing string the widget renders. Pass a {@link ClaudiusTranslations}
379
+ * (or a partial override) to localize the UI. English is the source of truth;
380
+ * see {@link defaultTranslations}.
381
+ */
382
+ export declare interface ClaudiusTranslations {
383
+ /** Chat window header title. */
384
+ title: string;
385
+ /** Chat window header subtitle. */
386
+ subtitle: string;
387
+ /** First assistant message shown when the chat opens. */
388
+ welcomeMessage: string;
389
+ /** Accessible label for the close button. */
390
+ closeChat: string;
391
+ /** Accessible label for the message list region. */
392
+ chatMessages: string;
393
+ /** Accessible label for the typing indicator. */
394
+ typingIndicator: string;
395
+ /** Placeholder text for the message input. */
396
+ placeholder: string;
397
+ /** Accessible label for the send button. */
398
+ sendMessage: string;
399
+ /** Accessible label for the message input field. */
400
+ typeYourMessage: string;
401
+ /** Accessible label for the button that opens the chat. */
402
+ openChat: string;
403
+ /** Accessible label for dismissing the greeting bubble. */
404
+ dismissGreeting: string;
405
+ /** Generic fallback error message. */
406
+ errorGeneric: string;
407
+ /** Error shown when the network request fails. */
408
+ errorConnection: string;
409
+ /** Error shown when a request times out. */
410
+ errorTimeout: string;
411
+ /** Error shown when rate-limited (per-minute limit). */
412
+ errorRateLimitMinute: string;
413
+ /** Error shown when rate-limited (per-hour limit). */
414
+ errorRateLimitHour: string;
415
+ /** Label for the retry action on a failed message. */
416
+ errorRetry: string;
417
+ }
418
+
419
+ /**
420
+ * Build a complete {@link ClaudiusTranslations} from the English defaults,
421
+ * applying the given overrides.
422
+ *
423
+ * @param overrides - Strings to override on top of {@link defaultTranslations}.
424
+ * @returns A complete translations object.
425
+ */
426
+ export declare function createTranslations(overrides?: Partial<ClaudiusTranslations>): ClaudiusTranslations;
427
+
428
+ /**
429
+ * Error thrown by {@link ChatApiClient.sendMessage} when a send is rejected
430
+ * for arriving within the configured debounce window.
431
+ */
432
+ export declare class DebounceError extends Error {
433
+ /** Creates a `DebounceError` with a fixed message. */
434
+ constructor();
435
+ }
436
+
437
+ /**
438
+ * Default PII patterns: email addresses, North-American-style phone numbers,
439
+ * US Social Security numbers, and 13–16 digit card-like sequences. These are
440
+ * intentionally conservative starting points — tune {@link RedactPiiOptions.patterns}
441
+ * for your data.
442
+ */
443
+ export declare const DEFAULT_PII_PATTERNS: readonly RegExp[];
444
+
445
+ /** The default (English) translations, used when no locale or override applies. */
446
+ export declare const defaultTranslations: ClaudiusTranslations;
447
+
448
+ /**
449
+ * Detect the best {@link LocaleCode} for the current environment: the document
450
+ * `lang` attribute first, then the browser language, falling back to `"en"`.
451
+ *
452
+ * @returns The detected locale code.
453
+ */
454
+ export declare function detectLocale(): LocaleCode;
455
+
456
+ /**
457
+ * Context for {@link ClaudiusPlugin.onError}. Adds the ability to recover from
458
+ * a failed send by rendering a reply in place of the error UI.
459
+ */
460
+ export declare interface ErrorContext extends PluginContext {
461
+ /**
462
+ * Recover from the failure by rendering this assistant reply instead of the
463
+ * error state. Stops the hook chain — later plugins' `onError` hooks do not
464
+ * run.
465
+ */
466
+ respondWith(reply: string | PluginReply): void;
467
+ }
468
+
469
+ /** BCP-47 primary language subtags the widget ships built-in translations for. */
470
+ export declare type LocaleCode = "en" | "es" | "fr" | "de";
471
+
472
+ /** Built-in translations keyed by {@link LocaleCode}. */
473
+ export declare const locales: Record<LocaleCode, ClaudiusTranslations>;
474
+
475
+ /** A value that may be returned synchronously or as a promise. */
476
+ export declare type MaybePromise<T> = T | Promise<T>;
477
+
478
+ /**
479
+ * Reference plugin that emits a structured analytics event for every message
480
+ * sent, every reply received, and every error. It never modifies messages.
481
+ *
482
+ * @example
483
+ * ```ts
484
+ * <ChatWidget
485
+ * apiUrl={url}
486
+ * plugins={[pluginAnalytics({ onEvent: (e) => gtag("event", e.type, e) })]}
487
+ * />
488
+ * ```
489
+ */
490
+ export declare function pluginAnalytics(options: AnalyticsPluginOptions): ClaudiusPlugin;
491
+
492
+ /**
493
+ * Reference plugin that answers matching messages locally, without calling the
494
+ * API. The first rule whose matcher fires short-circuits the send via
495
+ * `ctx.respondWith`, so the network is never hit for that turn.
496
+ *
497
+ * @example
498
+ * ```ts
499
+ * <ChatWidget
500
+ * apiUrl={url}
501
+ * plugins={[pluginCannedResponses({
502
+ * rules: [
503
+ * { match: "hours", reply: "We're open 9-5, Mon-Fri." },
504
+ * { match: /pricing|cost/i, reply: "See https://example.com/pricing." },
505
+ * ],
506
+ * })]}
507
+ * />
508
+ * ```
509
+ */
510
+ export declare function pluginCannedResponses(options: CannedResponsesOptions): ClaudiusPlugin;
511
+
512
+ /**
513
+ * Read-only context shared by every plugin hook.
514
+ *
515
+ * `messages` is a snapshot of the conversation at the moment the hook runs:
516
+ * in {@link ClaudiusPlugin.onBeforeSend} it excludes the in-flight user
517
+ * message; in {@link ClaudiusPlugin.onAfterReceive} and
518
+ * {@link ClaudiusPlugin.onError} it includes it.
519
+ */
520
+ export declare interface PluginContext {
521
+ /** Conversation snapshot, oldest message first. Treat as immutable. */
522
+ readonly messages: readonly ChatMessage[];
523
+ /** The Worker chat endpoint URL the widget posts to. */
524
+ readonly apiUrl: string;
525
+ }
526
+
527
+ /**
528
+ * Reference plugin that strips PII from the user's message before it leaves the
529
+ * browser. The redacted text is what gets displayed and sent, so the user sees
530
+ * that redaction happened. Optionally redacts assistant replies too.
531
+ *
532
+ * @example
533
+ * ```ts
534
+ * <ChatWidget apiUrl={url} plugins={[pluginRedactPII()]} />
535
+ * ```
536
+ */
537
+ export declare function pluginRedactPII(options?: RedactPiiOptions): ClaudiusPlugin;
538
+
539
+ /**
540
+ * A synthesized assistant reply, produced by a plugin instead of (or in
541
+ * recovery from) a network round-trip. Passed to
542
+ * {@link BeforeSendContext.respondWith} and {@link ErrorContext.respondWith}.
543
+ */
544
+ export declare interface PluginReply {
545
+ /** The assistant reply text to render. */
546
+ content: string;
547
+ /** Optional sources to attach to the synthesized reply. */
548
+ sources?: Source[];
549
+ }
550
+
551
+ /** Options for {@link pluginRedactPII}. */
552
+ export declare interface RedactPiiOptions {
553
+ /**
554
+ * Patterns to redact. Each must carry the global (`g`) flag.
555
+ * @defaultValue {@link DEFAULT_PII_PATTERNS}
556
+ */
557
+ patterns?: readonly RegExp[];
558
+ /**
559
+ * Text substituted for each match.
560
+ * @defaultValue `"[redacted]"`
561
+ */
562
+ replacement?: string;
563
+ /**
564
+ * Also redact the assistant's replies, not just outgoing user messages.
565
+ * @defaultValue `false`
566
+ */
567
+ redactReplies?: boolean;
568
+ }
569
+
570
+ /** Replace every match of every pattern in `text` with `replacement`. */
571
+ export declare function redactText(text: string, patterns: readonly RegExp[], replacement: string): string;
572
+
573
+ /**
574
+ * Resolve the final translations for a locale, applying any per-string
575
+ * overrides on top of the chosen locale's defaults.
576
+ *
577
+ * @param options - Locale and override settings.
578
+ * @returns A complete translations object.
579
+ */
580
+ export declare function resolveTranslations(options?: ResolveTranslationsOptions): ClaudiusTranslations;
581
+
582
+ /** Options for {@link resolveTranslations}. */
583
+ export declare interface ResolveTranslationsOptions {
584
+ /** Locale to use. Defaults to the result of {@link detectLocale}. */
585
+ locale?: LocaleCode;
586
+ /** Per-string overrides layered over the chosen locale's translations. */
587
+ translations?: Partial<ClaudiusTranslations>;
588
+ }
589
+
590
+ /**
591
+ * A cited source the assistant referenced when answering. Rendered as a link
592
+ * in the chat and grouped in the sources sidebar.
593
+ */
594
+ export declare interface Source {
595
+ /** Absolute URL of the source. */
596
+ url: string;
597
+ /** Human-readable link title shown to the user. */
598
+ title: string;
599
+ /** Origin category, used to group and label the source. */
600
+ type: "blog" | "page" | "external";
601
+ }
602
+
603
+ declare const THEME_COLOR_TOKENS: readonly ["accent", "accentText", "accentSoft", "accentTextMuted", "surface", "surfaceMuted", "text", "textMuted", "border", "userBubble", "userBubbleText", "assistantBubble", "assistantBubbleText", "field", "error", "errorSurface", "errorText", "link", "scrim"];
604
+
605
+ declare const THEME_FONT_TOKENS: readonly ["heading", "body"];
606
+
607
+ declare const THEME_RADIUS_TOKENS: readonly ["sm", "md", "lg", "full", "tail"];
608
+
609
+ declare const THEME_SHADOW_TOKENS: readonly ["elevated", "floating", "floatingHover"];
610
+
611
+ /** Names of the color tokens a theme can override (e.g. `accent`, `surface`, `text`). */
612
+ export declare type ThemeColorToken = (typeof THEME_COLOR_TOKENS)[number];
613
+
614
+ /** Names of the font-family tokens a theme can override. */
615
+ export declare type ThemeFontToken = (typeof THEME_FONT_TOKENS)[number];
616
+
617
+ /** Names of the border-radius tokens a theme can override. */
618
+ export declare type ThemeRadiusToken = (typeof THEME_RADIUS_TOKENS)[number];
619
+
620
+ /** Names of the box-shadow tokens a theme can override. */
621
+ export declare type ThemeShadowToken = (typeof THEME_SHADOW_TOKENS)[number];
622
+
623
+ /**
624
+ * A proactive engagement rule. Each variant fires at most once per page on a
625
+ * different signal: elapsed time, scroll depth, exit intent, or URL match.
626
+ */
627
+ export declare type Trigger = {
628
+ /** Fire after a fixed dwell time. */
629
+ on: "time";
630
+ /** Seconds to wait before firing. */
631
+ seconds: number;
632
+ /** Only fire when the current URL matches this pattern. */
633
+ matchUrl?: UrlPattern;
634
+ /** Action to run when the trigger fires. */
635
+ action: TriggerAction;
636
+ } | {
637
+ /** Fire once the user scrolls past a depth threshold. */
638
+ on: "scroll";
639
+ /** Scroll depth (0-100) that fires the trigger. */
640
+ percent: number;
641
+ /** Only fire when the current URL matches this pattern. */
642
+ matchUrl?: UrlPattern;
643
+ /** Action to run when the trigger fires. */
644
+ action: TriggerAction;
645
+ } | {
646
+ /** Fire when the pointer leaves the top of the viewport (exit intent). */
647
+ on: "exit-intent";
648
+ /** Only fire when the current URL matches this pattern. */
649
+ matchUrl?: UrlPattern;
650
+ /** Action to run when the trigger fires. */
651
+ action: TriggerAction;
652
+ } | {
653
+ /** Fire immediately when the current URL matches. */
654
+ on: "url";
655
+ /** URL pattern that must match for the trigger to fire. */
656
+ pattern: UrlPattern;
657
+ /** Action to run when the trigger fires. */
658
+ action: TriggerAction;
659
+ };
660
+
661
+ /**
662
+ * What a {@link Trigger} does when it fires: open the chat, or show a greeting
663
+ * bubble with the given message.
664
+ */
665
+ export declare type TriggerAction = "open" | {
666
+ /** Greeting bubble message to display. */
667
+ greeting: string;
668
+ };
669
+
670
+ /** A URL match: a case-insensitive substring, or a regular expression. */
671
+ export declare type UrlPattern = string | RegExp;
672
+
673
+ /** Corner of the viewport the widget docks to. */
674
+ export declare type WidgetPosition = "bottom-right" | "bottom-left" | "top-right" | "top-left";
675
+
676
+ export { }