@widgetic/embed-sdk 0.0.0-stage → 2.0.6
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 +567 -2
- package/dist/browser/chunks/ABTestManager.js +1 -0
- package/dist/browser/chunks/advanced.js +1 -0
- package/dist/browser/chunks/api.js +1 -0
- package/dist/browser/chunks/core.js +1 -0
- package/dist/browser/chunks/display.js +1 -0
- package/dist/browser/chunks/media.js +1 -0
- package/dist/browser/chunks/messaging.js +1 -0
- package/dist/browser/chunks/performance.js +1 -0
- package/dist/browser/chunks/renderers.js +1 -0
- package/dist/browser/chunks/scanner.js +1 -0
- package/dist/browser/chunks/security.js +1 -0
- package/dist/browser/chunks/vendor.js +1 -0
- package/dist/browser/embed-bootstrap.js +1 -0
- package/dist/browser/embed-sdk.js +1 -0
- package/dist/esm/chunks/ABTestManager.js +1 -0
- package/dist/esm/chunks/advanced.js +1 -0
- package/dist/esm/chunks/api.js +1 -0
- package/dist/esm/chunks/core.js +1 -0
- package/dist/esm/chunks/display.js +1 -0
- package/dist/esm/chunks/media.js +1 -0
- package/dist/esm/chunks/messaging.js +1 -0
- package/dist/esm/chunks/performance.js +1 -0
- package/dist/esm/chunks/renderers.js +1 -0
- package/dist/esm/chunks/scanner.js +1 -0
- package/dist/esm/chunks/security.js +1 -0
- package/dist/esm/chunks/vendor.js +1 -0
- package/dist/esm/embed-bootstrap.js +1 -0
- package/dist/esm/embed-sdk.js +1 -0
- package/dist/esm/types/abTesting/ABTestElement.d.ts +120 -0
- package/dist/esm/types/abTesting/ABTestManager.d.ts +177 -0
- package/dist/esm/types/api/batch-client.d.ts +163 -0
- package/dist/esm/types/api/layers.d.ts +119 -0
- package/dist/esm/types/core/advanced-security-manager.d.ts +330 -0
- package/dist/esm/types/core/analytics-tracker.d.ts +224 -0
- package/dist/esm/types/core/auth-detector.d.ts +65 -0
- package/dist/esm/types/core/auth-manager.d.ts +90 -0
- package/dist/esm/types/core/autoscale-manager.d.ts +91 -0
- package/dist/esm/types/core/breakpoints.d.ts +48 -0
- package/dist/esm/types/core/config.d.ts +152 -0
- package/dist/esm/types/core/constants.d.ts +75 -0
- package/dist/esm/types/core/content-position-manager.d.ts +228 -0
- package/dist/esm/types/core/custom-element.d.ts +152 -0
- package/dist/esm/types/core/display-manager.d.ts +109 -0
- package/dist/esm/types/core/editor-overlay.d.ts +113 -0
- package/dist/esm/types/core/embed-sdk.d.ts +310 -0
- package/dist/esm/types/core/exit-intent-trigger.d.ts +114 -0
- package/dist/esm/types/core/lazy-loader.d.ts +111 -0
- package/dist/esm/types/core/media-manager.d.ts +364 -0
- package/dist/esm/types/core/messaging.d.ts +251 -0
- package/dist/esm/types/core/overlay-manager.d.ts +119 -0
- package/dist/esm/types/core/performance-monitor.d.ts +152 -0
- package/dist/esm/types/core/privacy-compliance.d.ts +236 -0
- package/dist/esm/types/core/realtime-manager.d.ts +279 -0
- package/dist/esm/types/core/resize-handler.d.ts +81 -0
- package/dist/esm/types/core/resource-optimizer.d.ts +133 -0
- package/dist/esm/types/core/responsive-manager.d.ts +49 -0
- package/dist/esm/types/core/scroll-trigger.d.ts +105 -0
- package/dist/esm/types/core/security-manager.d.ts +150 -0
- package/dist/esm/types/core/text-field-manager.d.ts +204 -0
- package/dist/esm/types/core/token-provider.d.ts +75 -0
- package/dist/esm/types/core/trigger-defaults.d.ts +36 -0
- package/dist/esm/types/core/trigger-manager.d.ts +248 -0
- package/dist/esm/types/core/types.d.ts +473 -0
- package/dist/esm/types/core/ui-sdk-loader.d.ts +90 -0
- package/dist/esm/types/core/widget-manager.d.ts +285 -0
- package/dist/esm/types/core/widget-metadata.d.ts +107 -0
- package/dist/esm/types/embed-sdk.d.ts +31 -0
- package/dist/esm/types/loaders/module-loader.d.ts +147 -0
- package/dist/esm/types/renderers/custom-element-renderer.d.ts +78 -0
- package/dist/esm/types/renderers/iframe-renderer.d.ts +185 -0
- package/dist/esm/types/renderers/widget-renderer.d.ts +173 -0
- package/dist/esm/types/sdk/embed-bootstrap.d.ts +84 -0
- package/dist/esm/types/sdk/embed-sdk.d.ts +31 -0
- package/dist/esm/types/translations/TranslationElement.d.ts +93 -0
- package/dist/esm/types/utils/browser.d.ts +29 -0
- package/dist/esm/types/utils/caseConversion.d.ts +2 -0
- package/dist/esm/types/utils/css-debug.d.ts +105 -0
- package/dist/esm/types/utils/device-detector.d.ts +100 -0
- package/dist/esm/types/utils/event-emitter.d.ts +14 -0
- package/dist/esm/types/utils/hydrate-published-host.d.ts +17 -0
- package/dist/esm/types/utils/logger.d.ts +31 -0
- package/dist/esm/types/utils/parser.d.ts +39 -0
- package/dist/esm/types/utils/portal.d.ts +74 -0
- package/dist/esm/types/utils/public-embed-lookup.d.ts +68 -0
- package/dist/esm/types/utils/published-host-display.d.ts +61 -0
- package/dist/umd/embed-bootstrap.js +1 -0
- package/dist/umd/embed-sdk.js +1 -0
- package/package.json +154 -4
package/README.md
CHANGED
|
@@ -1,3 +1,568 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Widgetic Embed SDK v1.0
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@widgetic/embed-sdk)
|
|
4
|
+
[](https://github.com/widgetic/embed-sdk/actions)
|
|
5
|
+
[](https://www.typescriptlang.org/)
|
|
6
|
+
|
|
7
|
+
Framework-agnostic JavaScript SDK for embedding Widgetic widgets with support for custom elements, iframes, and batch API integration. Works with any framework or vanilla JavaScript.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
### 🚀 **Phase 1: Foundation & Core Architecture**
|
|
12
|
+
|
|
13
|
+
- **Auto-initialization** on page load with intelligent DOM scanning
|
|
14
|
+
- **Multiple render modes**: Custom Elements, iframes, with automatic fallback
|
|
15
|
+
- **Browser compatibility** detection and graceful degradation
|
|
16
|
+
- **Instance management** with singleton pattern and global coordination
|
|
17
|
+
- **Comprehensive error handling** and recovery mechanisms
|
|
18
|
+
|
|
19
|
+
### 🔥 **Phase 2: Advanced API Integration**
|
|
20
|
+
|
|
21
|
+
- **Batch API system** with intelligent request deduplication and caching
|
|
22
|
+
- **Dynamic module loading** with HTTP/3 support and version management
|
|
23
|
+
- **Performance optimization** via lazy loading and dependency resolution
|
|
24
|
+
- **TTL-based caching** for compositions and widget metadata
|
|
25
|
+
|
|
26
|
+
## Framework Compatibility
|
|
27
|
+
|
|
28
|
+
✅ **Framework-Agnostic Core**: No framework dependencies in the core SDK
|
|
29
|
+
✅ **Vanilla JavaScript**: Works directly in any HTML page
|
|
30
|
+
✅ **React**: Compatible with all React versions
|
|
31
|
+
✅ **Vue**: Compatible with Vue 2 and Vue 3
|
|
32
|
+
✅ **Angular**: Compatible with all Angular versions
|
|
33
|
+
✅ **Svelte/SvelteKit**: Compatible with Svelte 3, 4, and 5
|
|
34
|
+
✅ **Next.js**: Works with both SSR and client-side rendering
|
|
35
|
+
✅ **Other Frameworks**: Works with any framework that can render HTML
|
|
36
|
+
|
|
37
|
+
See `/demo/` directory for framework-specific integration examples.
|
|
38
|
+
|
|
39
|
+
## 🧪 Testing & Development
|
|
40
|
+
|
|
41
|
+
### External Developer Test Pages
|
|
42
|
+
|
|
43
|
+
The SDK includes comprehensive test pages that simulate real-world usage:
|
|
44
|
+
|
|
45
|
+
- **[API Key Test](examples/api-key-test.html)** - Simple test page for trying your API key with different CDN sources
|
|
46
|
+
- **[External Developer Test](examples/external-dev-test.html)** - Comprehensive test suite covering all SDK features
|
|
47
|
+
- **[UMD Build Test](examples/umd-test.html)** - Tests UMD bundle completeness and functionality
|
|
48
|
+
- **[Token Provider Examples](examples/token-provider.html)** - Demonstrates different token provider implementations
|
|
49
|
+
|
|
50
|
+
These test pages help you:
|
|
51
|
+
- Verify your API key works correctly
|
|
52
|
+
- Test different installation methods (npm, unpkg, jsDelivr)
|
|
53
|
+
- Validate token provider configurations
|
|
54
|
+
- Debug widget rendering issues
|
|
55
|
+
- Test bundle completeness for UMD builds
|
|
56
|
+
|
|
57
|
+
## 🏗️ Layered API Architecture
|
|
58
|
+
|
|
59
|
+
The Widgetic SDK provides three distinct API layers to match different use cases and complexity levels:
|
|
60
|
+
|
|
61
|
+
### 🟢 High-Level API - Declarative & Auto-magical
|
|
62
|
+
**Perfect for:** Simple integrations, HTML-first approaches, minimal JavaScript
|
|
63
|
+
**Characteristics:** Auto-initialization, convention over configuration, declarative HTML
|
|
64
|
+
|
|
65
|
+
```html
|
|
66
|
+
<!-- Just add the script and use custom elements -->
|
|
67
|
+
<script src="https://unpkg.com/@widgetic/embed-sdk/dist/umd/embed-sdk.js"></script>
|
|
68
|
+
<script>
|
|
69
|
+
widgeticEmbedSdk.setApiKey('your-api-key');
|
|
70
|
+
</script>
|
|
71
|
+
|
|
72
|
+
<widgetic-widget composition-id="your-composition-id" width="400" height="300"></widgetic-widget>
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 🔵 Mid-Level API - Programmatic with Configuration
|
|
76
|
+
**Perfect for:** Framework integrations, custom UIs, controlled rendering
|
|
77
|
+
**Characteristics:** Programmatic control, flexible configuration, managed lifecycle
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { getWidgetRenderer, setTokenProvider, EndpointTokenProvider } from '@widgetic/embed-sdk';
|
|
81
|
+
|
|
82
|
+
setTokenProvider(new EndpointTokenProvider({ tokenEndpoint: '/api/token' }));
|
|
83
|
+
|
|
84
|
+
const renderer = getWidgetRenderer();
|
|
85
|
+
const widget = await renderer.renderWidget({
|
|
86
|
+
compositionId: 'your-composition-id',
|
|
87
|
+
container: document.getElementById('widget-container'),
|
|
88
|
+
width: 400,
|
|
89
|
+
height: 300,
|
|
90
|
+
onReady: (widget) => console.log('Widget ready:', widget)
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### 🔴 Low-Level API - Full Control & Manual Management
|
|
95
|
+
**Perfect for:** Custom implementations, performance optimization, advanced use cases
|
|
96
|
+
**Characteristics:** Manual lifecycle management, direct API access, maximum flexibility
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
import { getBatchClient, getModuleLoader, getAuthManager } from '@widgetic/embed-sdk';
|
|
100
|
+
|
|
101
|
+
const authManager = getAuthManager();
|
|
102
|
+
authManager.setApiKey('your-api-key');
|
|
103
|
+
|
|
104
|
+
const batchClient = getBatchClient();
|
|
105
|
+
const compositions = await batchClient.getCompositions(['comp-1', 'comp-2']);
|
|
106
|
+
|
|
107
|
+
const moduleLoader = getModuleLoader();
|
|
108
|
+
const module = await moduleLoader.loadModule(widgetData, { version: 'latest' });
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### 📚 Layer Examples and Documentation
|
|
112
|
+
|
|
113
|
+
- **[Layered API Examples](examples/layered-api-examples.html)** - Interactive examples for all three layers
|
|
114
|
+
- **[Layer Comparison Guide](examples/layered-api-examples.html#comparison)** - When to use each layer
|
|
115
|
+
- **[Framework Integration Examples](examples/layered-api-examples.html#mid-level)** - React, Vue, Angular examples
|
|
116
|
+
|
|
117
|
+
You can also import specific layers:
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
import { HighLevelAPI, MidLevelAPI, LowLevelAPI } from '@widgetic/embed-sdk';
|
|
121
|
+
|
|
122
|
+
// Use only what you need
|
|
123
|
+
const { setApiKey, WidgeticWidget } = HighLevelAPI;
|
|
124
|
+
const { getWidgetRenderer } = MidLevelAPI;
|
|
125
|
+
const { getBatchClient } = LowLevelAPI;
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Sibling packages
|
|
129
|
+
|
|
130
|
+
In this checkout, the SDK consumes the sibling `api-sdk` package through a
|
|
131
|
+
link rather than the published registry copy.
|
|
132
|
+
|
|
133
|
+
This package consumes sibling `@widgetic/*` checkouts through a link in `node_modules` that
|
|
134
|
+
resolves the checkout itself — its built output, not its source.
|
|
135
|
+
The link is made by hand rather than through the `@widgetic/dev-tools` dev-alias setup the
|
|
136
|
+
adopting apps use, so a sibling edit stays invisible here until that package rebuilds its
|
|
137
|
+
`dist/`.
|
|
138
|
+
Setup is the install script this package ships: it reinstalls and then links the sibling, so
|
|
139
|
+
`node_modules` keeps resolving the checkout rather than the published package.
|
|
140
|
+
The dev-alias workflow these packages have not adopted, and the reasons the adopting apps use
|
|
141
|
+
it, are described in [the dev-tools README](../dev-tools/README.md).
|
|
142
|
+
|
|
143
|
+
`npm run i` is the whole setup here: it reinstalls `node_modules`, then
|
|
144
|
+
re-links the `api-sdk` checkout.
|
|
145
|
+
|
|
146
|
+
```sh
|
|
147
|
+
npm run i # install, then link the api-sdk checkout
|
|
148
|
+
npm run lapisdk # re-link only, after a fresh node_modules
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Installation
|
|
152
|
+
|
|
153
|
+
### npm/yarn
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
npm install @widgetic/embed-sdk
|
|
157
|
+
# or
|
|
158
|
+
yarn add @widgetic/embed-sdk
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### CDN
|
|
162
|
+
|
|
163
|
+
```html
|
|
164
|
+
<!-- UMD build (recommended for CDN) -->
|
|
165
|
+
<script src="https://unpkg.com/@widgetic/embed-sdk@2.0.0/dist/umd/embed-sdk.js"></script>
|
|
166
|
+
|
|
167
|
+
<!-- or via jsDelivr -->
|
|
168
|
+
<script src="https://cdn.jsdelivr.net/npm/@widgetic/embed-sdk@2.0.0/dist/umd/embed-sdk.js"></script>
|
|
169
|
+
|
|
170
|
+
<!-- Latest version (unpkg) -->
|
|
171
|
+
<script src="https://unpkg.com/@widgetic/embed-sdk/dist/umd/embed-sdk.js"></script>
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The UMD build includes all dependencies bundled, so no additional imports are needed.
|
|
175
|
+
|
|
176
|
+
## Quick Start
|
|
177
|
+
|
|
178
|
+
### HTML (Auto-initialization)
|
|
179
|
+
|
|
180
|
+
The SDK automatically initializes when the DOM is ready and scans for `<widgetic-widget>` elements:
|
|
181
|
+
|
|
182
|
+
#### UMD (Global Script)
|
|
183
|
+
|
|
184
|
+
```html
|
|
185
|
+
<!DOCTYPE html>
|
|
186
|
+
<html>
|
|
187
|
+
<head>
|
|
188
|
+
<title>Widgetic Widget</title>
|
|
189
|
+
<!-- Load SDK from CDN -->
|
|
190
|
+
<script src="https://unpkg.com/@widgetic/embed-sdk/dist/umd/embed-sdk.js"></script>
|
|
191
|
+
</head>
|
|
192
|
+
<body>
|
|
193
|
+
<!-- Widget element -->
|
|
194
|
+
<widgetic-widget
|
|
195
|
+
composition-id="your-composition-id"
|
|
196
|
+
render-mode="auto"
|
|
197
|
+
width="350"
|
|
198
|
+
height="200"
|
|
199
|
+
resize="fill-width"
|
|
200
|
+
></widgetic-widget>
|
|
201
|
+
|
|
202
|
+
<script>
|
|
203
|
+
// Configure authentication (choose one method)
|
|
204
|
+
|
|
205
|
+
// Method 1: Static API Key (development only)
|
|
206
|
+
const provider = new widgeticEmbedSdk.StaticApiKeyProvider('your-api-key');
|
|
207
|
+
widgeticEmbedSdk.setTokenProvider(provider);
|
|
208
|
+
|
|
209
|
+
// Method 2: Token from your backend (recommended)
|
|
210
|
+
const tokenProvider = new widgeticEmbedSdk.EndpointTokenProvider({
|
|
211
|
+
tokenEndpoint: '/api/widgetic/token'
|
|
212
|
+
});
|
|
213
|
+
widgeticEmbedSdk.setTokenProvider(tokenProvider);
|
|
214
|
+
|
|
215
|
+
// Method 3: AuthManager with API key (handles token lifecycle)
|
|
216
|
+
widgeticEmbedSdk.setApiKey('your-api-key');
|
|
217
|
+
|
|
218
|
+
// SDK will auto-initialize and render widgets
|
|
219
|
+
</script>
|
|
220
|
+
</body>
|
|
221
|
+
</html>
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
#### ES Modules
|
|
225
|
+
|
|
226
|
+
```html
|
|
227
|
+
<!DOCTYPE html>
|
|
228
|
+
<html>
|
|
229
|
+
<head>
|
|
230
|
+
<title>Widgetic Widget</title>
|
|
231
|
+
</head>
|
|
232
|
+
<body>
|
|
233
|
+
<!-- Widget element -->
|
|
234
|
+
<widgetic-widget
|
|
235
|
+
composition-id="62bldc5lecb2al3f458b4567"
|
|
236
|
+
render-mode="auto"
|
|
237
|
+
width="350"
|
|
238
|
+
height="50"
|
|
239
|
+
resize="fill-width"
|
|
240
|
+
autoscale="on"
|
|
241
|
+
adaptive="414"
|
|
242
|
+
>
|
|
243
|
+
</widgetic-widget>
|
|
244
|
+
|
|
245
|
+
<!-- Import SDK as ES module -->
|
|
246
|
+
<script type="module">
|
|
247
|
+
import { setTokenProvider, StaticApiKeyProvider, setApiKey } from '@widgetic/embed-sdk';
|
|
248
|
+
|
|
249
|
+
// Configure authentication (choose one method)
|
|
250
|
+
|
|
251
|
+
// Method 1: Static API Key (development only)
|
|
252
|
+
setTokenProvider(new StaticApiKeyProvider('your-api-key'));
|
|
253
|
+
|
|
254
|
+
// Method 2: AuthManager with API key (handles token lifecycle)
|
|
255
|
+
setApiKey('your-api-key');
|
|
256
|
+
|
|
257
|
+
// SDK will auto-initialize and render widgets
|
|
258
|
+
</script>
|
|
259
|
+
</body>
|
|
260
|
+
</html>
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
### JavaScript/TypeScript
|
|
265
|
+
|
|
266
|
+
```typescript
|
|
267
|
+
import { getSDK, EmbedSDK } from "@widgetic/embed-sdk";
|
|
268
|
+
|
|
269
|
+
// Get the global SDK instance
|
|
270
|
+
const sdk = getSDK();
|
|
271
|
+
|
|
272
|
+
// Or create a new instance
|
|
273
|
+
const customSDK = new EmbedSDK();
|
|
274
|
+
|
|
275
|
+
// Initialize and scan for widgets
|
|
276
|
+
await sdk.init();
|
|
277
|
+
|
|
278
|
+
// Manually refresh to detect new widgets
|
|
279
|
+
await sdk.refresh();
|
|
280
|
+
|
|
281
|
+
// Get widget instances
|
|
282
|
+
const instances = sdk.getInstances();
|
|
283
|
+
console.log(`Found ${instances.length} widgets`);
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
## Widget Attributes
|
|
287
|
+
|
|
288
|
+
| Attribute | Type | Default | Description |
|
|
289
|
+
| ---------------- | ------------------------------- | ------------ | -------------------------------------------- |
|
|
290
|
+
| `composition-id` | string | **required** | Unique identifier for the widget composition |
|
|
291
|
+
| `render-mode` | `auto\|custom-element\|iframe` | `auto` | Rendering method preference |
|
|
292
|
+
| `width` | number\|string | `350` | Widget width in pixels |
|
|
293
|
+
| `height` | number\|string | `50` | Widget height in pixels |
|
|
294
|
+
| `resize` | `fill-width\|fixed\|responsive` | `fixed` | Resize behavior |
|
|
295
|
+
| `autoscale` | `on\|off` | `off` | Enable automatic scaling |
|
|
296
|
+
| `adaptive` | number | - | Adaptive breakpoint in pixels |
|
|
297
|
+
|
|
298
|
+
## Authentication & Security
|
|
299
|
+
|
|
300
|
+
### Token Provider (Recommended)
|
|
301
|
+
|
|
302
|
+
For production applications, use a Token Provider instead of embedding API keys in client-side code:
|
|
303
|
+
|
|
304
|
+
```typescript
|
|
305
|
+
import { setTokenProvider, EndpointTokenProvider } from "@widgetic/embed-sdk";
|
|
306
|
+
|
|
307
|
+
// Recommended: Fetch tokens from your backend
|
|
308
|
+
setTokenProvider(new EndpointTokenProvider({
|
|
309
|
+
tokenEndpoint: '/api/widgetic/token',
|
|
310
|
+
headers: {
|
|
311
|
+
'Authorization': 'Bearer ' + userJwtToken
|
|
312
|
+
}
|
|
313
|
+
}));
|
|
314
|
+
|
|
315
|
+
// Custom token logic
|
|
316
|
+
setTokenProvider(new FunctionTokenProvider(async () => {
|
|
317
|
+
const response = await fetch('/api/auth/widgetic-token');
|
|
318
|
+
const data = await response.json();
|
|
319
|
+
return data.token;
|
|
320
|
+
}));
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
Your backend endpoint should return:
|
|
324
|
+
```json
|
|
325
|
+
{
|
|
326
|
+
"token": "your-widgetic-token",
|
|
327
|
+
"expires_in": 3600
|
|
328
|
+
}
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
### Short-lived Tokens with AuthManager (Recommended)
|
|
332
|
+
|
|
333
|
+
For maximum security, use the AuthManager to automatically handle short-lived token lifecycle:
|
|
334
|
+
|
|
335
|
+
```typescript
|
|
336
|
+
import { getAuthManager, setApiKey } from "@widgetic/embed-sdk";
|
|
337
|
+
|
|
338
|
+
// Configure with your API key (server-side recommended)
|
|
339
|
+
setApiKey('your-api-key');
|
|
340
|
+
|
|
341
|
+
// The AuthManager will automatically:
|
|
342
|
+
// - Exchange your API key for short-lived JWTs
|
|
343
|
+
// - Cache tokens until they expire
|
|
344
|
+
// - Refresh tokens automatically
|
|
345
|
+
// - Handle token validation
|
|
346
|
+
|
|
347
|
+
const authManager = getAuthManager();
|
|
348
|
+
// Token management is now handled automatically
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
### Backend Token Exchange Endpoint (Recommended)
|
|
352
|
+
|
|
353
|
+
Implement a secure token exchange endpoint in your backend:
|
|
354
|
+
|
|
355
|
+
```javascript
|
|
356
|
+
// Express.js example
|
|
357
|
+
app.post('/api/widgetic/token', authenticate, async (req, res) => {
|
|
358
|
+
try {
|
|
359
|
+
const response = await fetch('https://api.widgetic.com/v1/tokens', {
|
|
360
|
+
method: 'POST',
|
|
361
|
+
headers: {
|
|
362
|
+
'Authorization': `Bearer ${process.env.WIDGETIC_API_KEY}`,
|
|
363
|
+
'Content-Type': 'application/json'
|
|
364
|
+
},
|
|
365
|
+
body: JSON.stringify({
|
|
366
|
+
scope: ['widgets:read', 'compositions:read'],
|
|
367
|
+
expiresIn: 3600 // 1 hour
|
|
368
|
+
})
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
const data = await response.json();
|
|
372
|
+
res.json({ token: data.token });
|
|
373
|
+
} catch (error) {
|
|
374
|
+
res.status(500).json({ error: 'Token generation failed' });
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
### Development with API Keys
|
|
380
|
+
|
|
381
|
+
For development only, you can use static API keys:
|
|
382
|
+
|
|
383
|
+
```typescript
|
|
384
|
+
import { StaticApiKeyProvider, setTokenProvider } from "@widgetic/embed-sdk";
|
|
385
|
+
|
|
386
|
+
// ⚠️ Development only - not for production!
|
|
387
|
+
setTokenProvider(new StaticApiKeyProvider('your-api-key'));
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
### Security Best Practices
|
|
391
|
+
|
|
392
|
+
1. **Never expose API keys in client-side code** - Use token providers or AuthManager
|
|
393
|
+
2. **Use short-lived tokens** - Tokens should expire within 1-24 hours
|
|
394
|
+
3. **Implement proper scopes** - Limit token permissions to what's needed
|
|
395
|
+
4. **Validate tokens server-side** - Verify tokens in your backend before issuing them
|
|
396
|
+
5. **Use HTTPS** - Always serve your application over HTTPS in production
|
|
397
|
+
6. **Monitor token usage** - Track token generation and usage patterns
|
|
398
|
+
|
|
399
|
+
## API Reference
|
|
400
|
+
|
|
401
|
+
### Core SDK
|
|
402
|
+
|
|
403
|
+
```typescript
|
|
404
|
+
import { getSDK, EmbedSDK, config } from "@widgetic/embed-sdk";
|
|
405
|
+
|
|
406
|
+
// Global SDK instance
|
|
407
|
+
const sdk = getSDK();
|
|
408
|
+
|
|
409
|
+
// SDK configuration
|
|
410
|
+
config.apiUrl = "https://api.widgetic.com";
|
|
411
|
+
config.cdnUrl = "https://cdn.widgetic.com";
|
|
412
|
+
config.debug = true;
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
### Batch API Client
|
|
416
|
+
|
|
417
|
+
```typescript
|
|
418
|
+
import { getBatchClient } from "@widgetic/embed-sdk";
|
|
419
|
+
|
|
420
|
+
const batchClient = getBatchClient();
|
|
421
|
+
|
|
422
|
+
// Get multiple compositions efficiently
|
|
423
|
+
const compositions = await batchClient.getCompositions(["id1", "id2", "id3"]);
|
|
424
|
+
|
|
425
|
+
// Get widget metadata
|
|
426
|
+
const widgets = await batchClient.getWidgets(["widget1", "widget2"]);
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
### Module Loader
|
|
430
|
+
|
|
431
|
+
```typescript
|
|
432
|
+
import { getModuleLoader } from "@widgetic/embed-sdk";
|
|
433
|
+
|
|
434
|
+
const moduleLoader = getModuleLoader();
|
|
435
|
+
|
|
436
|
+
// Load widget module dynamically
|
|
437
|
+
const loadedModule = await moduleLoader.loadModule(widgetData, {
|
|
438
|
+
version: "latest",
|
|
439
|
+
timeout: 10000,
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
// Preload modules for performance
|
|
443
|
+
await moduleLoader.preloadModules(widgetDataList);
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
### Custom Rendering
|
|
447
|
+
|
|
448
|
+
```typescript
|
|
449
|
+
import { getWidgetRenderer } from "@widgetic/embed-sdk";
|
|
450
|
+
|
|
451
|
+
const renderer = getWidgetRenderer();
|
|
452
|
+
|
|
453
|
+
// Render single widget
|
|
454
|
+
const rendered = await renderer.renderWidget({
|
|
455
|
+
compositionId: "your-composition-id",
|
|
456
|
+
renderMode: "custom-element",
|
|
457
|
+
container: document.getElementById("widget-container"),
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
// Batch render multiple widgets
|
|
461
|
+
const results = await renderer.renderWidgets(renderOptions);
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
## Advanced Configuration
|
|
465
|
+
|
|
466
|
+
### Environment Configuration
|
|
467
|
+
|
|
468
|
+
```typescript
|
|
469
|
+
import { config } from "@widgetic/embed-sdk";
|
|
470
|
+
|
|
471
|
+
// API endpoints
|
|
472
|
+
config.apiUrl = "https://your-api.domain.com";
|
|
473
|
+
config.cdnUrl = "https://your-cdn.domain.com";
|
|
474
|
+
|
|
475
|
+
// Performance tuning
|
|
476
|
+
config.batchSize = 50;
|
|
477
|
+
config.cacheTTL = 300000; // 5 minutes
|
|
478
|
+
|
|
479
|
+
// Development
|
|
480
|
+
config.debug = true;
|
|
481
|
+
config.logLevel = "debug";
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
### Custom Error Handling
|
|
485
|
+
|
|
486
|
+
```typescript
|
|
487
|
+
import { log } from "@widgetic/embed-sdk";
|
|
488
|
+
|
|
489
|
+
// Listen for SDK events
|
|
490
|
+
document.addEventListener("widgetic:error", (event) => {
|
|
491
|
+
log.error("Widget error:", event.detail);
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
document.addEventListener("widgetic:initialized", (event) => {
|
|
495
|
+
log.info("Widget initialized:", event.detail);
|
|
496
|
+
});
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
## Browser Support
|
|
500
|
+
|
|
501
|
+
- **Modern browsers**: Chrome 60+, Firefox 60+, Safari 12+, Edge 79+
|
|
502
|
+
- **Custom Elements**: Supported natively or via polyfill
|
|
503
|
+
- **HTTP/3**: Automatically detected with graceful fallback to HTTP/2
|
|
504
|
+
- **ES Modules**: Native support with UMD fallback for older browsers
|
|
505
|
+
|
|
506
|
+
## Performance Features
|
|
507
|
+
|
|
508
|
+
- **Intelligent batching**: Groups API requests for optimal performance
|
|
509
|
+
- **Request deduplication**: Prevents redundant network calls
|
|
510
|
+
- **TTL caching**: Caches compositions and widget data
|
|
511
|
+
- **Lazy loading**: Loads widget modules on demand
|
|
512
|
+
- **HTTP/3 support**: Uses the latest protocol when available
|
|
513
|
+
- **Tree shaking**: Only includes used functionality in bundles
|
|
514
|
+
|
|
515
|
+
## TypeScript Support
|
|
516
|
+
|
|
517
|
+
Full TypeScript support with comprehensive type definitions:
|
|
518
|
+
|
|
519
|
+
```typescript
|
|
520
|
+
import type {
|
|
521
|
+
WidgetConfig,
|
|
522
|
+
WidgetInstance,
|
|
523
|
+
RenderMode,
|
|
524
|
+
CompositionData,
|
|
525
|
+
WidgetData,
|
|
526
|
+
} from "@widgetic/embed-sdk";
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
## Contributing
|
|
530
|
+
|
|
531
|
+
1. Fork the repository
|
|
532
|
+
2. Create a feature branch: `git checkout -b feature/amazing-feature`
|
|
533
|
+
3. Make your changes and add tests
|
|
534
|
+
4. Run the test suite: `npm test`
|
|
535
|
+
5. Commit your changes: `git commit -m 'Add amazing feature'`
|
|
536
|
+
6. Push to the branch: `git push origin feature/amazing-feature`
|
|
537
|
+
7. Open a Pull Request
|
|
538
|
+
|
|
539
|
+
## Development
|
|
540
|
+
|
|
541
|
+
```bash
|
|
542
|
+
# Install dependencies
|
|
543
|
+
npm install
|
|
544
|
+
|
|
545
|
+
# Start development server
|
|
546
|
+
npm run dev
|
|
547
|
+
|
|
548
|
+
# Build for production
|
|
549
|
+
npm run build
|
|
550
|
+
|
|
551
|
+
# Run tests
|
|
552
|
+
npm test
|
|
553
|
+
|
|
554
|
+
# Lint and format
|
|
555
|
+
npm run lint
|
|
556
|
+
npm run format
|
|
557
|
+
```
|
|
558
|
+
|
|
559
|
+
## License
|
|
560
|
+
|
|
561
|
+
MIT © [Widgetic](https://widgetic.com)
|
|
562
|
+
|
|
563
|
+
## Support
|
|
564
|
+
|
|
565
|
+
- 📧 Email: support@widgetic.com
|
|
566
|
+
- 💬 Discord: [Join our community](https://discord.gg/widgetic)
|
|
567
|
+
- 📖 Documentation: [docs.widgetic.com](https://docs.widgetic.com)
|
|
568
|
+
- 🐛 Issues: [GitHub Issues](https://github.com/widgetic/embed-sdk/issues)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e}from"./vendor.js";import{e as t,h as i}from"./core.js";import{W as n}from"./api.js";import{WidgeticMessenger as s}from"./messaging.js";import{C as r,h as o,a,t as d}from"./advanced.js";import"./renderers.js";import"./media.js";import"./display.js";import"./scanner.js";import"./performance.js";import"./security.js";class c{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){const i=this.listeners.get(e);return i&&(i.delete(t),0===i.size&&this.listeners.delete(e)),this}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}emit(e,...t){const i=this.listeners.get(e);return!(!i||0===i.size)&&(i.forEach((e=>{try{e(...t)}catch(e){}})),!0)}removeAllListeners(e){return e?this.listeners.delete(e):this.listeners.clear(),this}}class l extends c{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set;const e=new r({basePath:t()});this.abTestingApi=new o(e),this.compositionsApi=new a(e),this.widgetManager=n.getInstance(),this.messenger=new s,this.setupEventListeners()}static getInstance(){return l.instance||(l.instance=new l),l.instance}setupEventListeners(){this.widgetManager.addEventListener("widget_ready",(e=>{this.setupWidgetConversionTracking(e.widgetId)})),this.widgetManager.addEventListener("custom_event",(e=>{this.handleWidgetCustomEvent(e)})),this.widgetManager.addEventListener("media_play",(e=>{this.handleMediaEvent("plays",e)})),this.widgetManager.addEventListener("form_submit",(e=>{this.handleFormEvent("submissions",e)})),this.widgetManager.addEventListener("widget_click",(e=>{this.handleClickEvent(e)}))}getTestConfig(t){return e(this,void 0,void 0,(function*(){var n;try{const s=yield this.abTestingApi.getABTestConfig({id:t});if(!s)return i.warn("A/B test not found",{experimentId:t}),null;const r=(yield Promise.all((s.variants||[]).map((t=>e(this,void 0,void 0,(function*(){try{const e=t.composition_id||t.compositionId||"";return{id:t.id||"",compositionId:e,embedCode:this.generateEmbedCode(e),trafficPercentage:t.traffic_percentage||t.trafficPercentage||0}}catch(e){return i.error("Failed to fetch composition for variant",{variantId:t.id,compositionId:t.compositionId,error:e}),null}})))))).filter((e=>null!==e));if(0===r.length)return i.warn("No valid variants found for A/B test",{experimentId:t}),null;const o={experimentId:s.test_id||t,isActive:"running"===s.status,winningVariant:void 0,variants:r,successMetrics:s.success_metrics||["impressions"],primaryMetric:(null===(n=s.success_metrics)||void 0===n?void 0:n[0])||"impressions"};return i.info("A/B test config loaded",{experimentId:t,config:o}),o}catch(e){return e&&"object"==typeof e&&"status"in e&&404===e.status?(i.warn("A/B test not found",{experimentId:t}),null):(i.error("Failed to load A/B test config",{experimentId:t,error:e}),null)}}))}getVariantAssignment(t,n){return e(this,void 0,void 0,(function*(){try{const e=yield this.getTestConfig(t);if(!e)return null;if(e.winningVariant){const i=e.variants.find((t=>t.id===e.winningVariant));if(i){const e={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode};return localStorage.setItem(`ab_test_${t}`,JSON.stringify(e)),this.assignments.set(t,e),i}}const i=this.selectVariant(e.variants,n);if(!i)return null;const s={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode};return localStorage.setItem(`ab_test_${t}`,JSON.stringify(s)),this.assignments.set(t,s),yield this.setupConversionTracking(t,e,s),i}catch(e){return i.error("Failed to get variant assignment",{experimentId:t,error:e}),null}}))}setupConversionTracking(t,n,s){return e(this,void 0,void 0,(function*(){try{const e=yield this.findTrackingTargets(s.compositionId,n.successMetrics),r={experimentId:t,variantId:s.variantId,metrics:n.successMetrics,trackingTargets:e};this.conversionSetups.set(t,r),i.debug("Conversion tracking setup complete",{experimentId:t,trackingTargets:e})}catch(e){i.error("Failed to setup conversion tracking",{experimentId:t,error:e})}}))}findTrackingTargets(t,n){return e(this,void 0,void 0,(function*(){try{const e={},t={clicks:["button","a","[data-click-track]","[onclick]"],conversions:["form",'button[type="submit"]',"[data-conversion]"],plays:["video","audio","[data-play]",".play-button"],submissions:["form","[data-form]"],downloads:["a[download]","[data-download]"],signups:["form","[data-signup]",".signup-form"]};for(const i of n){const n=t[i]||[];e[i]=n}return e}catch(e){return i.error("Failed to find tracking targets",{compositionId:t,error:e}),{}}}))}selectorExistsInContent(e,t){const i=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")){const e=t.slice(1,-1);return i.includes(e)}if(t.startsWith(".")){const e=t.slice(1);return i.includes(`class="${e}"`)||i.includes(`class='${e}'`)}return i.includes(`<${t}`)}setupWidgetConversionTracking(t){return e(this,void 0,void 0,(function*(){for(const[e,n]of Array.from(this.conversionSetups.entries()))try{if(!this.widgetManager.getWidget(t))continue;const s=this.messenger.createWidgetController(t);n.metrics.includes("clicks")&&(yield this.setupClickTracking(s,e,n.variantId)),(n.metrics.includes("submissions")||n.metrics.includes("conversions"))&&(yield this.setupFormTracking(s,e,n.variantId)),n.metrics.includes("plays")&&(yield this.setupMediaTracking(s,e,n.variantId)),i.debug("Widget conversion tracking setup",{widgetId:t,experimentId:e})}catch(n){i.error("Failed to setup widget conversion tracking",{widgetId:t,experimentId:e,error:n})}}))}setupClickTracking(t,i,n){return e(this,void 0,void 0,(function*(){t.subscribe("click",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"clicks",{element:t.element,timestamp:t.timestamp})})))),yield t.callFunction("setupEventListener","click",(e=>{var t;this.trackConversion(i,n,"clicks",{target:null===(t=e.target)||void 0===t?void 0:t.tagName,timestamp:Date.now()})}))}))}setupFormTracking(t,i,n){return e(this,void 0,void 0,(function*(){t.subscribe("form-submit",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"submissions",{formData:t.formData,timestamp:t.timestamp})})))),t.subscribe("conversion",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"conversions",{conversionType:t.type,value:t.value,timestamp:t.timestamp})}))))}))}setupMediaTracking(t,i,n){return e(this,void 0,void 0,(function*(){t.subscribe("media-play",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"plays",{mediaType:t.mediaType,duration:t.duration,timestamp:t.timestamp})}))))}))}handleWidgetCustomEvent(t){return e(this,void 0,void 0,(function*(){var e;for(const[i,n]of Array.from(this.conversionSetups.entries()))if((null===(e=t.data)||void 0===e?void 0:e.experimentId)===i){const e=t.data.conversionType||"custom";yield this.trackConversion(i,n.variantId,e,t.data)}}))}handleMediaEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,n]of Array.from(this.conversionSetups.entries()))n.metrics.includes(t)&&(yield this.trackConversion(e,n.variantId,t,i.data))}))}handleFormEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,n]of Array.from(this.conversionSetups.entries()))n.metrics.includes(t)&&(yield this.trackConversion(e,n.variantId,t,i.data))}))}handleClickEvent(t){return e(this,void 0,void 0,(function*(){for(const[e,i]of Array.from(this.conversionSetups.entries()))i.metrics.includes("clicks")&&(yield this.trackConversion(e,i.variantId,"clicks",t.data))}))}trackConversion(t,n,s,r,o){return e(this,void 0,void 0,(function*(){try{const e=`${t}_${n}_${(null==o?void 0:o.userId)||(null==o?void 0:o.sessionId)||"anonymous"}`;if(this.trackedConversions.has(e))return void i.debug("Conversion already tracked for this user",{experimentId:t,variantId:n,conversionType:s});const a={experimentId:t,variantId:n,userId:null==o?void 0:o.userId,sessionId:(null==o?void 0:o.sessionId)||this.getSessionId(),conversionType:s,timestamp:(new Date).toISOString()},c={event_type:"conversion",data:d(a)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:c}),this.trackedConversions.add(e),this.emit("conversion",{experimentId:t,variantId:n,conversionType:s,data:r}),i.info("Conversion tracked",{experimentId:t,variantId:n,conversionType:s,data:r})}catch(e){i.error("Failed to track conversion",{experimentId:t,variantId:n,conversionType:s,error:e})}}))}trackImpression(t,n,s){return e(this,void 0,void 0,(function*(){try{const e={experimentId:t,variantId:n,userId:null==s?void 0:s.userId,sessionId:(null==s?void 0:s.sessionId)||this.getSessionId(),timestamp:(new Date).toISOString()},r={event_type:"impression",data:d(e)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:r}),i.debug("Impression tracked",{experimentId:t,variantId:n})}catch(e){i.error("Failed to track impression",{experimentId:t,variantId:n,error:e})}}))}validateGoalTracking(t,n){return e(this,void 0,void 0,(function*(){const e=[],s=[];try{for(const i of t){const t=yield this.validateVariantCapabilities(i,n);e.push(...t)}if(e.length>0){const t=Array.from(new Set(e.map((e=>e.metric))));s.push(`Consider adding trackable elements to your compositions for: ${t.join(", ")}`),t.includes("clicks")&&s.push("Add clickable elements like buttons, links, or interactive components"),t.includes("submissions")&&s.push("Add form elements to track form submissions"),t.includes("plays")&&s.push("Add media elements (audio/video) to track media plays"),t.includes("conversions")&&s.push("Implement custom conversion tracking using widgetic:conversion events")}const r=0===e.length;return i.info("Goal tracking validation completed",{variants:t.length,successMetrics:n,issues:e.length,isValid:r}),{isValid:r,issues:e,recommendations:s}}catch(e){return i.error("Goal tracking validation failed",{error:e}),{isValid:!1,issues:[{variant:"all",metric:"system",reason:"Validation system error"}],recommendations:["Please try again or contact support"]}}}))}validateVariantCapabilities(t,n){return e(this,void 0,void 0,(function*(){const e=[];try{const s=document.createElement("div");s.style.cssText="position: absolute; top: -9999px; left: -9999px; width: 1px; height: 1px;",document.body.appendChild(s);try{const r={compositionId:t.composition_id,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:1,height:1},o=`validation_${t.composition_id}_${Date.now()}`;if(yield this.widgetManager.registerWidget(o,r,s)){const s=this.messenger.getWidgetController(o);let r=null;if(s)try{r=yield s.callFunction("getCapabilities",[])}catch(e){i.warn("Widget does not expose getCapabilities method",{compositionId:t.composition_id})}for(const i of n){const n=this.checkMetricSupport(t,i,r);n&&e.push(n)}yield this.widgetManager.unregisterWidget(o)}else for(const i of n)e.push({variant:t.name,metric:i,reason:"Widget failed to load for validation"})}finally{document.body.removeChild(s)}}catch(s){i.error("Failed to validate variant capabilities",{variant:t.name,error:s});for(const i of n)e.push({variant:t.name,metric:i,reason:"Validation error occurred"})}return e}))}checkMetricSupport(e,t,i){var n;if(!i)return{variant:e.name,metric:t,reason:"Widget capabilities could not be determined"};switch(t){case"clicks":if(!this.hasClickableCapabilities(i))return{variant:e.name,metric:t,reason:"No clickable elements or interactive capabilities found"};break;case"submissions":if(!i.textCapabilities||!(null===(n=i.textCapabilities.fields)||void 0===n?void 0:n.length))return{variant:e.name,metric:t,reason:"No form fields or text input capabilities found"};break;case"plays":if(!i.mediaCapabilities||!i.mediaCapabilities.supportsPlay)return{variant:e.name,metric:t,reason:"No media playback capabilities found"};break;case"conversions":if("static"===i.type||!i.supportsEvents)return{variant:e.name,metric:t,reason:"Widget may not support custom conversion events"};break;default:return{variant:e.name,metric:t,reason:`Unknown success metric: ${t}`}}return null}hasClickableCapabilities(e){var t,i,n,s;if(["interactive","form","media","gallery"].includes(e.type))return!0;if(null===(t=e.mediaCapabilities)||void 0===t?void 0:t.supportsPlay)return!0;if(null===(i=e.contentCapabilities)||void 0===i?void 0:i.supportsNavigation)return!0;if(null===(s=null===(n=e.textCapabilities)||void 0===n?void 0:n.fields)||void 0===s?void 0:s.length)return!0;const r=["play","pause","next","previous","goTo","setText","submit","click","interact"];return!!e.exposedFunctions&&r.some((t=>e.exposedFunctions.includes(t)))}selectVariant(e,t){if(!e||0===e.length)return null;const i=t.userId||t.sessionId||"anonymous",n=this.createDeterministicHash(i),s=Math.abs(n)%100;let r=0;for(const t of e)if(r+=t.trafficPercentage,s<r)return t;return e[e.length-1]}createDeterministicHash(e){let t=0;for(let i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t&=t}return t}createAssignment(t,n,s){return e(this,void 0,void 0,(function*(){try{const e=this.detectDeviceType(s.userAgent),r={experimentId:t,variantId:n.variantId,userId:s.userId,sessionId:s.sessionId||this.getSessionId(),userAgent:s.userAgent||navigator.userAgent,ipAddress:s.ipAddress,deviceType:e},o=d(r);yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:o}),i.debug("Assignment created in backend",{experimentId:t,variantId:n.variantId})}catch(e){i.error("Failed to create assignment in backend",{experimentId:t,error:e})}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){let e=localStorage.getItem("widgetic_session_id");return e||(e="session_"+Math.random().toString(36).substr(2,9)+"_"+Date.now(),localStorage.setItem("widgetic_session_id",e)),e}detectDeviceType(e){if(!e)return"desktop";const t=e.toLowerCase();return/tablet|ipad|playbook|silk/.test(t)?"tablet":/mobile|iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(t)?"mobile":"desktop"}}l.instance=null;export{l as ABTestManager};
|