@smooai/chat-widget 0.4.0 → 0.5.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.
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Tiny, dependency-free deferred loader for `@smooai/chat-widget`.
3
+ *
4
+ * The recommended embed: a host includes this *small* script eagerly, and it
5
+ * defers injecting the real (heavier) `chat-widget.global.js` module until the
6
+ * page is past its critical render — so the widget never competes with the host
7
+ * page's LCP/TBT. It triggers the real load on the **first** of:
8
+ *
9
+ * - `window` `load` → `requestIdleCallback` (idle time), or
10
+ * - user intent (`pointerdown` / `keydown` / `scroll`), or
11
+ * - an 8s fallback.
12
+ *
13
+ * After the module loads (which registers `<smooth-agent-chat>` and exposes
14
+ * `window.SmoothAgentChat`), it mounts the widget with the host's config.
15
+ *
16
+ * Deliberately imports nothing from the widget itself — this file must stay a
17
+ * few hundred bytes so including it eagerly is free.
18
+ *
19
+ * ## Config
20
+ * Set a global before/with the loader (any `ChatWidgetConfig`, plus an optional
21
+ * `src` pointing at the module bundle):
22
+ *
23
+ * ```html
24
+ * <script>window.SmoothAgentChatConfig = { endpoint: 'wss://…/ws', agentId: '…' };</script>
25
+ * <script src="https://cdn/…/chat-widget-loader.global.js" async></script>
26
+ * ```
27
+ *
28
+ * Or, for the simplest installs, `data-*` attributes on the loader's own tag
29
+ * (`data-endpoint`, `data-agent-id`, `data-primary`, `data-mode`, `data-src`).
30
+ * If no config is found, the module is still loaded (registering the element) so
31
+ * a `<smooth-agent-chat …>` placed directly in markup upgrades itself.
32
+ */
33
+
34
+ /** Must match `ELEMENT_TAG` in `element.ts`; inlined to avoid importing it. */
35
+ const ELEMENT_TAG = 'smooth-agent-chat';
36
+ /** Default module filename, resolved as a sibling of the loader script. */
37
+ const DEFAULT_MODULE = 'chat-widget.global.js';
38
+
39
+ type MountFn = (config: Record<string, unknown>, target?: HTMLElement) => unknown;
40
+
41
+ interface LoaderWindow extends Window {
42
+ SmoothAgentChat?: { mount: MountFn };
43
+ SmoothAgentChatConfig?: Record<string, unknown> & { src?: string };
44
+ }
45
+
46
+ /**
47
+ * Resolve the module URL: explicit `src` (config or `data-src`) wins, else a
48
+ * sibling of the loader script, else the bare default filename.
49
+ */
50
+ function resolveModuleSrc(win: LoaderWindow, script: HTMLScriptElement | null): string {
51
+ const fromConfig = win.SmoothAgentChatConfig?.src;
52
+ if (fromConfig) return fromConfig;
53
+ const fromAttr = script?.getAttribute('data-src');
54
+ if (fromAttr) return fromAttr;
55
+ const selfSrc = script?.src;
56
+ if (selfSrc) return selfSrc.replace(/[^/]*$/, DEFAULT_MODULE);
57
+ return DEFAULT_MODULE;
58
+ }
59
+
60
+ /**
61
+ * The widget mount config: the `SmoothAgentChatConfig` global (minus the
62
+ * loader-only `src`), or `data-*` attributes. `undefined` ⇒ no programmatic
63
+ * mount (a markup element will upgrade itself once the module registers it).
64
+ */
65
+ function resolveMountConfig(win: LoaderWindow, script: HTMLScriptElement | null): Record<string, unknown> | undefined {
66
+ if (win.SmoothAgentChatConfig) {
67
+ const { src: _src, ...config } = win.SmoothAgentChatConfig;
68
+ // Only `src` (no real fields) ⇒ no programmatic mount; a markup element
69
+ // upgrades itself once the module registers it.
70
+ return Object.keys(config).length > 0 ? config : undefined;
71
+ }
72
+ if (!script) return undefined;
73
+ const endpoint = script.getAttribute('data-endpoint');
74
+ const agentId = script.getAttribute('data-agent-id');
75
+ if (!endpoint && !agentId) return undefined;
76
+ const config: Record<string, unknown> = {};
77
+ if (endpoint) config.endpoint = endpoint;
78
+ if (agentId) config.agentId = agentId;
79
+ const primary = script.getAttribute('data-primary');
80
+ if (primary) config.theme = { primary };
81
+ const mode = script.getAttribute('data-mode');
82
+ if (mode) config.mode = mode;
83
+ return config;
84
+ }
85
+
86
+ /**
87
+ * Install the deferred loader. Idempotent per call; the IIFE entry
88
+ * (`loader.ts`) invokes it once on script execution.
89
+ */
90
+ export function initChatWidgetLoader(): void {
91
+ const win = window as LoaderWindow;
92
+ const script = (document.currentScript as HTMLScriptElement | null) ?? null;
93
+ const moduleSrc = resolveModuleSrc(win, script);
94
+
95
+ let loaded = false;
96
+ let idleId: number | undefined;
97
+ let fallbackId: number | undefined;
98
+
99
+ function mountWhenReady(): void {
100
+ const config = resolveMountConfig(win, script);
101
+ if (!config) return; // markup element upgrades itself; nothing to mount
102
+ const apply = () => {
103
+ try {
104
+ win.SmoothAgentChat?.mount(config);
105
+ } catch (error) {
106
+ console.error('[chat-widget loader] mount failed', error);
107
+ }
108
+ };
109
+ if (win.SmoothAgentChat) {
110
+ apply();
111
+ } else if (window.customElements?.whenDefined) {
112
+ window.customElements.whenDefined(ELEMENT_TAG).then(apply, apply);
113
+ } else {
114
+ apply();
115
+ }
116
+ }
117
+
118
+ function teardown(): void {
119
+ if (idleId !== undefined) {
120
+ // The id is either an idle handle or (fallback path) a timeout id;
121
+ // both cancels are no-ops on the wrong kind, so calling both is safe.
122
+ window.cancelIdleCallback?.(idleId);
123
+ window.clearTimeout(idleId);
124
+ }
125
+ if (fallbackId !== undefined) window.clearTimeout(fallbackId);
126
+ window.removeEventListener('pointerdown', load);
127
+ window.removeEventListener('keydown', load);
128
+ window.removeEventListener('scroll', load);
129
+ }
130
+
131
+ function load(): void {
132
+ if (loaded) return;
133
+ loaded = true;
134
+ teardown();
135
+ const tag = document.createElement('script');
136
+ tag.src = moduleSrc;
137
+ tag.onload = mountWhenReady;
138
+ tag.onerror = () => console.error('[chat-widget loader] failed to load', moduleSrc);
139
+ document.head.appendChild(tag);
140
+ }
141
+
142
+ function schedule(): void {
143
+ if (window.requestIdleCallback) {
144
+ idleId = window.requestIdleCallback(() => load(), { timeout: 5000 });
145
+ } else {
146
+ idleId = window.setTimeout(load, 2500) as unknown as number;
147
+ }
148
+ fallbackId = window.setTimeout(load, 8000) as unknown as number;
149
+ }
150
+
151
+ // User intent loads immediately (they're about to want the widget).
152
+ window.addEventListener('pointerdown', load, { once: true, passive: true });
153
+ window.addEventListener('keydown', load, { once: true });
154
+ window.addEventListener('scroll', load, { once: true, passive: true });
155
+
156
+ if (document.readyState === 'complete') {
157
+ schedule();
158
+ } else {
159
+ window.addEventListener('load', schedule, { once: true });
160
+ }
161
+ }
package/src/loader.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Standalone IIFE entry for the **deferred loader** — built to
3
+ * `dist/chat-widget-loader.global.js`.
4
+ *
5
+ * This is the recommended embed: include it eagerly (it's tiny) and it lazily
6
+ * injects the real `chat-widget.global.js` module only once the host page is
7
+ * past its critical render (idle / user intent / 8s fallback), so the widget
8
+ * never competes with the host's LCP/TBT. See {@link initChatWidgetLoader}.
9
+ *
10
+ * ```html
11
+ * <script>window.SmoothAgentChatConfig = { endpoint: 'wss://…/ws', agentId: '…' };</script>
12
+ * <script src="https://cdn/…/chat-widget-loader.global.js" async></script>
13
+ * ```
14
+ */
15
+ import { initChatWidgetLoader } from './loader-core.js';
16
+
17
+ initChatWidgetLoader();