@widgetic/embed-sdk 0.0.0-stage → 2.0.7

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 (89) hide show
  1. package/README.md +567 -2
  2. package/dist/browser/chunks/ABTestManager.js +1 -0
  3. package/dist/browser/chunks/advanced.js +1 -0
  4. package/dist/browser/chunks/api.js +1 -0
  5. package/dist/browser/chunks/core.js +1 -0
  6. package/dist/browser/chunks/display.js +1 -0
  7. package/dist/browser/chunks/media.js +1 -0
  8. package/dist/browser/chunks/messaging.js +1 -0
  9. package/dist/browser/chunks/performance.js +1 -0
  10. package/dist/browser/chunks/renderers.js +1 -0
  11. package/dist/browser/chunks/scanner.js +1 -0
  12. package/dist/browser/chunks/security.js +1 -0
  13. package/dist/browser/chunks/vendor.js +1 -0
  14. package/dist/browser/embed-bootstrap.js +1 -0
  15. package/dist/browser/embed-sdk.js +1 -0
  16. package/dist/esm/chunks/ABTestManager.js +1 -0
  17. package/dist/esm/chunks/advanced.js +1 -0
  18. package/dist/esm/chunks/api.js +1 -0
  19. package/dist/esm/chunks/core.js +1 -0
  20. package/dist/esm/chunks/display.js +1 -0
  21. package/dist/esm/chunks/media.js +1 -0
  22. package/dist/esm/chunks/messaging.js +1 -0
  23. package/dist/esm/chunks/performance.js +1 -0
  24. package/dist/esm/chunks/renderers.js +1 -0
  25. package/dist/esm/chunks/scanner.js +1 -0
  26. package/dist/esm/chunks/security.js +1 -0
  27. package/dist/esm/chunks/vendor.js +1 -0
  28. package/dist/esm/embed-bootstrap.js +1 -0
  29. package/dist/esm/embed-sdk.js +1 -0
  30. package/dist/esm/types/abTesting/ABTestElement.d.ts +120 -0
  31. package/dist/esm/types/abTesting/ABTestManager.d.ts +177 -0
  32. package/dist/esm/types/api/batch-client.d.ts +163 -0
  33. package/dist/esm/types/api/layers.d.ts +119 -0
  34. package/dist/esm/types/core/advanced-security-manager.d.ts +330 -0
  35. package/dist/esm/types/core/analytics-tracker.d.ts +224 -0
  36. package/dist/esm/types/core/auth-detector.d.ts +65 -0
  37. package/dist/esm/types/core/auth-manager.d.ts +90 -0
  38. package/dist/esm/types/core/autoscale-manager.d.ts +91 -0
  39. package/dist/esm/types/core/breakpoints.d.ts +48 -0
  40. package/dist/esm/types/core/config.d.ts +152 -0
  41. package/dist/esm/types/core/constants.d.ts +75 -0
  42. package/dist/esm/types/core/content-position-manager.d.ts +228 -0
  43. package/dist/esm/types/core/custom-element.d.ts +152 -0
  44. package/dist/esm/types/core/display-manager.d.ts +109 -0
  45. package/dist/esm/types/core/editor-overlay.d.ts +113 -0
  46. package/dist/esm/types/core/embed-sdk.d.ts +310 -0
  47. package/dist/esm/types/core/exit-intent-trigger.d.ts +114 -0
  48. package/dist/esm/types/core/lazy-loader.d.ts +111 -0
  49. package/dist/esm/types/core/media-manager.d.ts +364 -0
  50. package/dist/esm/types/core/messaging.d.ts +251 -0
  51. package/dist/esm/types/core/overlay-manager.d.ts +119 -0
  52. package/dist/esm/types/core/performance-monitor.d.ts +152 -0
  53. package/dist/esm/types/core/privacy-compliance.d.ts +236 -0
  54. package/dist/esm/types/core/realtime-manager.d.ts +279 -0
  55. package/dist/esm/types/core/resize-handler.d.ts +81 -0
  56. package/dist/esm/types/core/resource-optimizer.d.ts +133 -0
  57. package/dist/esm/types/core/responsive-manager.d.ts +49 -0
  58. package/dist/esm/types/core/scroll-trigger.d.ts +105 -0
  59. package/dist/esm/types/core/security-manager.d.ts +150 -0
  60. package/dist/esm/types/core/text-field-manager.d.ts +204 -0
  61. package/dist/esm/types/core/token-provider.d.ts +75 -0
  62. package/dist/esm/types/core/trigger-defaults.d.ts +36 -0
  63. package/dist/esm/types/core/trigger-manager.d.ts +248 -0
  64. package/dist/esm/types/core/types.d.ts +473 -0
  65. package/dist/esm/types/core/ui-sdk-loader.d.ts +90 -0
  66. package/dist/esm/types/core/widget-manager.d.ts +285 -0
  67. package/dist/esm/types/core/widget-metadata.d.ts +107 -0
  68. package/dist/esm/types/embed-sdk.d.ts +31 -0
  69. package/dist/esm/types/loaders/module-loader.d.ts +147 -0
  70. package/dist/esm/types/renderers/custom-element-renderer.d.ts +78 -0
  71. package/dist/esm/types/renderers/iframe-renderer.d.ts +185 -0
  72. package/dist/esm/types/renderers/widget-renderer.d.ts +173 -0
  73. package/dist/esm/types/sdk/embed-bootstrap.d.ts +84 -0
  74. package/dist/esm/types/sdk/embed-sdk.d.ts +31 -0
  75. package/dist/esm/types/translations/TranslationElement.d.ts +93 -0
  76. package/dist/esm/types/utils/browser.d.ts +29 -0
  77. package/dist/esm/types/utils/caseConversion.d.ts +2 -0
  78. package/dist/esm/types/utils/css-debug.d.ts +105 -0
  79. package/dist/esm/types/utils/device-detector.d.ts +100 -0
  80. package/dist/esm/types/utils/event-emitter.d.ts +14 -0
  81. package/dist/esm/types/utils/hydrate-published-host.d.ts +17 -0
  82. package/dist/esm/types/utils/logger.d.ts +31 -0
  83. package/dist/esm/types/utils/parser.d.ts +39 -0
  84. package/dist/esm/types/utils/portal.d.ts +74 -0
  85. package/dist/esm/types/utils/public-embed-lookup.d.ts +68 -0
  86. package/dist/esm/types/utils/published-host-display.d.ts +61 -0
  87. package/dist/umd/embed-bootstrap.js +1 -0
  88. package/dist/umd/embed-sdk.js +1 -0
  89. package/package.json +154 -4
package/README.md CHANGED
@@ -1,3 +1,568 @@
1
- # Temporary Holding Version
1
+ # Widgetic Embed SDK v1.0
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/@widgetic/embed-sdk.svg)](https://www.npmjs.com/package/@widgetic/embed-sdk)
4
+ [![Build Status](https://img.shields.io/github/workflow/status/widgetic/embed-sdk/CI)](https://github.com/widgetic/embed-sdk/actions)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](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{a as t,d as i}from"./core.js";import{W as n}from"./api.js";import{WidgeticMessenger as s}from"./messaging.js";import{Configuration as r,ABTestingApi as o,CompositionsApi as a}from"@widgetic/api-sdk";import{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};
@@ -0,0 +1 @@
1
+ import{_ as t}from"./vendor.js";import{l as e,c as i,n as o}from"./core.js";import{Configuration as n,AuthenticationApi as s,CompositionsApi as r}from"@widgetic/api-sdk";import{getMessenger as a}from"./messaging.js";const d=t=>null!==t&&"object"==typeof t&&!Array.isArray(t)&&"[object Object]"===Object.prototype.toString.call(t);function c(t){if(Array.isArray(t))return t.map(c);if(!d(t))return t;const e={};for(const[i,o]of Object.entries(t)){e[i.replace(/[_-](\w)/g,((t,e)=>e?e.toUpperCase():""))]=Array.isArray(o)?o.map(c):d(o)?c(o):o}return e}function l(t){if(Array.isArray(t))return t.map(l);if(!d(t))return t;const e={};for(const[i,o]of Object.entries(t)){e[i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()]=Array.isArray(o)?o.map(l):d(o)?l(o):o}return e}class h{constructor(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache=new Map;const t=o(),e=new n({basePath:t.basePath,apiKey:t.apiKey,credentials:"include"});this.authApi=new s(e),this.compositionsApi=new r(e)}checkAuthentication(){return t(this,void 0,void 0,(function*(){try{if(this.sessionCache&&Date.now()<this.sessionCacheExpiry)return{isAuthenticated:!0,session:this.sessionCache,user:this.sessionCache.user,canEdit:!0};const t=c(yield this.authApi.getSession());return t&&t.accessToken&&t.user?(this.sessionCache=t,this.sessionCacheExpiry=Date.now()+3e5,e.info("User authenticated for editing",{userId:t.user.id,email:t.user.email}),{isAuthenticated:!0,session:t,user:t.user,canEdit:!0}):{isAuthenticated:!1,canEdit:!1}}catch(t){return e.debug("Authentication check failed",{error:t}),t instanceof Response&&t.status,{isAuthenticated:!1,canEdit:!1}}}))}checkCompositionOwnership(i){return t(this,void 0,void 0,(function*(){var t;try{const o=this.ownershipCache.get(i);if(o)return o;const n=yield this.checkAuthentication();if(!n.isAuthenticated||!(null===(t=n.session)||void 0===t?void 0:t.user)){const t={isOwner:!1,canEdit:!1,error:"User not authenticated"};return this.ownershipCache.set(i,t),t}const s=c(yield this.compositionsApi.getCompositionById({id:i}));if(!s){const t={isOwner:!1,canEdit:!1,error:"Composition not found"};return this.ownershipCache.set(i,t),t}const r=s.creatorId===n.session.user.id,a={isOwner:r,canEdit:r,composition:s,error:r?void 0:"User does not own this composition"};return this.ownershipCache.set(i,a),setTimeout((()=>{this.ownershipCache.delete(i)}),12e4),e.debug("Composition ownership checked",{compositionId:i,isOwner:r,userId:n.session.user.id,compositionCreatorId:s.creatorId}),a}catch(t){e.warn("Failed to check composition ownership",{compositionId:i,error:t});const o={isOwner:!1,canEdit:!1,error:t instanceof Error?t.message:"Unknown error"};return this.ownershipCache.set(i,o),o}}))}canEditComposition(e){return t(this,void 0,void 0,(function*(){return(yield this.checkCompositionOwnership(e)).canEdit}))}getCurrentUser(){return t(this,void 0,void 0,(function*(){return(yield this.checkAuthentication()).user||null}))}clearCache(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache.clear(),e.debug("Authentication cache cleared")}checkMultipleCompositions(e){return t(this,void 0,void 0,(function*(){const i=new Map;return(yield this.checkAuthentication()).isAuthenticated?(yield Promise.all(e.map((e=>t(this,void 0,void 0,(function*(){const t=yield this.checkCompositionOwnership(e);i.set(e,t)}))))),i):(e.forEach((t=>{i.set(t,{isOwner:!1,canEdit:!1,error:"User not authenticated"})})),i)}))}isEditingEnabled(){return i.ENABLE_EDITING}}let u=null;function p(){return u||(u=new h),u}class g{constructor(t={}){this.host=null,this.container=null,this.content=null,this.destroyed=!1,this.options=Object.assign({target:"widgetic-portal",className:"",style:"",clickThrough:!1,zIndex:99999999},t),this.createPortal()}createPortal(){this.host=this.findOrCreateHost(),this.container=document.createElement("div"),this.container.className=(this.options.className?this.options.className+" ":"")+"widgetic-portal-contents",this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough?"none":"auto"};\n ${this.options.style}\n `,this.options.clickThrough?this.container.style.pointerEvents="none":this.container.style.pointerEvents="auto",this.host.appendChild(this.container),e.debug("Portal created",{target:this.options.target,host:this.host,container:this.container})}findOrCreateHost(){let t=null;if(this.options.target instanceof HTMLElement)return this.options.target;if("string"==typeof this.options.target){const e=`.${this.options.target}`;t=document.querySelector(e)}return t||(t=document.createElement("div"),t.classList.add("string"==typeof this.options.target?this.options.target:"widgetic-portal"),document.body.appendChild(t),e.debug("Portal host created",{target:this.options.target,host:t})),t}mount(t){this.destroyed?e.warn("Cannot mount content to destroyed portal"):this.container?(this.content&&this.unmount(),t.style.pointerEvents="auto",this.content=t,this.container.appendChild(t),e.debug("Content mounted to portal",{content:t})):e.error("Portal container not available")}unmount(){this.content&&this.container&&this.container.contains(this.content)&&(this.container.removeChild(this.content),this.content=null,e.debug("Content unmounted from portal"))}destroy(){if(!this.destroyed){if(this.unmount(),this.container&&this.host&&this.host.contains(this.container)&&this.host.removeChild(this.container),this.host&&0===this.host.childNodes.length&&this.host.parentNode){const t="string"==typeof this.options.target?this.options.target:"widgetic-portal";this.host.classList.contains(t)&&this.host.parentNode.removeChild(this.host)}this.destroyed=!0,this.host=null,this.container=null,this.content=null,e.debug("Portal destroyed")}}getContainer(){return this.container}isDestroyed(){return this.destroyed}updateOptions(t){this.destroyed?e.warn("Cannot update options on destroyed portal"):(this.options=Object.assign(Object.assign({},this.options),t),this.container&&(void 0!==t.className&&(this.container.className=(t.className?t.className+" ":"")+"widgetic-portal-contents"),void 0!==t.style&&(this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough,"none"};\n ${this.options.style}\n `),void 0!==t.clickThrough&&(this.container.style.pointerEvents=(t.clickThrough,"none"))),e.debug("Portal options updated",{options:this.options}))}}function m(t){return new g(t)}class y{constructor(t={}){this.config=t,this.loadPromise=null,this.sdkInstance=null,this.isLoading=!1,this.loadTimeout=3e4,this.config=Object.assign({basePath:t.basePath||this.getUISdkBaseUrl(),version:t.version||"latest",debug:t.debug||!1},t)}getUISdkBaseUrl(){return"development"===i.NODE_ENV?i.CLIENT_URL:`${i.PRODUCTION_URL}/ui-sdk`}loadUISdk(){return t(this,void 0,void 0,(function*(){if(this.sdkInstance)return this.sdkInstance;if(this.loadPromise)return this.loadPromise;this.isLoading=!0,this.loadPromise=this.performLoad();try{return this.sdkInstance=yield this.loadPromise,e.info("UI SDK loaded successfully",{basePath:this.config.basePath,version:this.config.version}),this.sdkInstance}catch(t){throw e.error("Failed to load UI SDK",{error:t,config:this.config}),this.loadPromise=null,t}finally{this.isLoading=!1}}))}performLoad(){return t(this,void 0,void 0,(function*(){return new Promise(((t,i)=>{const o=setTimeout((()=>{i(new Error("UI SDK load timeout"))}),this.loadTimeout);try{if(window.WidgeticUI)return clearTimeout(o),void t(window.WidgeticUI);const n=document.createElement("script");n.src=`${this.config.basePath}/widgetic-ui.js`,n.async=!0,n.crossOrigin="anonymous",n.onload=()=>{clearTimeout(o),window.WidgeticUI?(e.debug("UI SDK script loaded from external source"),t(window.WidgeticUI)):i(new Error("UI SDK script loaded but WidgeticUI not available"))},n.onerror=()=>{clearTimeout(o),i(new Error("Failed to load UI SDK script"))},document.head.appendChild(n),e.debug("Loading UI SDK",{src:n.src})}catch(t){clearTimeout(o),i(t)}}))}))}isLoaded(){return null!==this.sdkInstance}isLoadingState(){return this.isLoading}getInstance(){return this.sdkInstance}initializeUISdk(i){return t(this,void 0,void 0,(function*(){const t=yield this.loadUISdk();return yield t.init(Object.assign(Object.assign({},this.config),i)),e.info("UI SDK initialized",{config:Object.assign(Object.assign({},this.config),i)}),t}))}cleanup(){return t(this,void 0,void 0,(function*(){if(this.sdkInstance){try{yield this.sdkInstance.destroy()}catch(t){e.warn("Error during UI SDK cleanup",{error:t})}this.sdkInstance=null}this.loadPromise=null,this.isLoading=!1,window.WidgeticUI&&delete window.WidgeticUI,e.debug("UI SDK cleanup complete")}))}preload(){return t(this,void 0,void 0,(function*(){try{yield this.loadUISdk(),e.debug("UI SDK preloaded successfully")}catch(t){e.warn("UI SDK preload failed",{error:t})}}))}}let v=null;function f(t){return v||(v=new y(t)),v}class w{constructor(t={}){this.options=t,this.sessions=new Map,this.defaultOptions={showEditButton:!0,editButtonText:"✏️ Edit",editButtonPosition:"top-right",enableClickToEdit:!0,autoDetectAuth:!0},this.options=Object.assign(Object.assign({},this.defaultOptions),t)}addOverlay(i,o){return t(this,void 0,void 0,(function*(){try{if(!this.options.autoDetectAuth)return void(yield this.createOverlay(i,o,!0));const t=p(),n=yield t.checkCompositionOwnership(o);n.canEdit?(yield this.createOverlay(i,o,!0),e.debug("Editor overlay added for owned composition",{compositionId:o})):e.debug("Editor overlay not added - user cannot edit",{compositionId:o,reason:n.error})}catch(t){e.warn("Failed to add editor overlay",{compositionId:o,error:t})}}))}createOverlay(i,o,n){return t(this,void 0,void 0,(function*(){if(this.sessions.has(o))return;const t=document.createElement("div");if(t.className="widgetic-editor-overlay",t.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 10000;\n pointer-events: none;\n ${this.getOverlayStyles()}\n `,this.options.showEditButton&&n){const e=this.createEditButton(o);t.appendChild(e)}this.options.enableClickToEdit&&n&&this.addClickToEdit(t,o);const s=i.parentElement;if(s){"static"===window.getComputedStyle(s).position&&(s.style.position="relative"),s.appendChild(t)}else i.style.position="relative",i.appendChild(t);const r={compositionId:o,isOpen:!1,overlay:t};this.sessions.set(o,r),e.debug("Editor overlay created",{compositionId:o})}))}createEditButton(e){const i=document.createElement("button");return i.className="widgetic-edit-button",i.textContent=this.options.editButtonText||"✏️ Edit",i.style.cssText=`\n position: absolute;\n ${this.getButtonPositionStyles()}\n background: #007bff;\n color: white;\n border: none;\n border-radius: 4px;\n padding: 8px 12px;\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n pointer-events: auto;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n transition: all 0.2s ease;\n z-index: 10001;\n ${this.getCustomButtonStyles()}\n `,i.addEventListener("mouseenter",(()=>{i.style.background="#0056b3",i.style.transform="scale(1.05)"})),i.addEventListener("mouseleave",(()=>{i.style.background="#007bff",i.style.transform="scale(1)"})),i.addEventListener("click",(i=>t(this,void 0,void 0,(function*(){i.preventDefault(),i.stopPropagation(),yield this.openEditor(e)})))),i}getButtonPositionStyles(){const t="10px";switch(this.options.editButtonPosition||"top-right"){case"top-left":return`top: ${t}; left: ${t};`;case"top-right":default:return`top: ${t}; right: ${t};`;case"bottom-left":return`bottom: ${t}; left: ${t};`;case"bottom-right":return`bottom: ${t}; right: ${t};`}}getCustomButtonStyles(){return this.options.editButtonStyle?Object.entries(this.options.editButtonStyle).map((([t,e])=>`${this.camelToKebab(t)}: ${e};`)).join(" "):""}getOverlayStyles(){return this.options.overlayStyle?Object.entries(this.options.overlayStyle).map((([t,e])=>`${this.camelToKebab(t)}: ${e};`)).join(" "):""}camelToKebab(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}addClickToEdit(e,i){e.style.cursor="pointer",e.style.pointerEvents="auto",e.addEventListener("click",(o=>t(this,void 0,void 0,(function*(){o.target===e&&(o.preventDefault(),o.stopPropagation(),yield this.openEditor(i))})))),e.addEventListener("mouseenter",(()=>{e.style.backgroundColor="rgba(0, 123, 255, 0.1)",e.style.border="2px dashed #007bff"})),e.addEventListener("mouseleave",(()=>{e.style.backgroundColor="transparent",e.style.border="none"}))}createEditorContainer(){const t=new g({target:"widgetic-editor-portal",className:"widgetic-editor-modal",zIndex:1e5,clickThrough:!1});const e=document.createElement("div");e.className="widgetic-editor-modal-backdrop",e.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n align-items: center;\n justify-content: center;\n ";const i=document.createElement("div");return i.className="widgetic-editor-content",i.style.cssText="\n width: 90vw;\n height: 90vh;\n max-width: 1200px;\n max-height: 800px;\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n ",e.appendChild(i),t.mount(e),{container:e,portal:t}}openEditor(i){return t(this,void 0,void 0,(function*(){try{const t=this.sessions.get(i);if(!t)return void e.warn("No editor session found",{compositionId:i});if(t.isOpen)return void e.debug("Editor already open",{compositionId:i});e.info("Opening composition editor",{compositionId:i});const o=f(),n=yield o.initializeUISdk(),{container:s,portal:r}=this.createEditorContainer(),d=yield n.mountCompositionEditor(s.querySelector(".widgetic-editor-content"),i,{onSave:t=>this.handleEditorSave(i,t),onClose:()=>this.closeEditor(i),onPreview:t=>this.handleEditorPreview(i,t)}),c=a().createWidgetController(i);if(t.isOpen=!0,t.editorContainer=s,t.editorInstance=d,t.widgetController=c,t.portal=r,t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="none")}e.info("Composition editor opened successfully",{compositionId:i})}catch(t){e.error("Failed to open editor",{compositionId:i,error:t}),this.showError("Failed to open editor. Please try again.",i)}}))}handleEditorSave(i,o){return t(this,void 0,void 0,(function*(){try{e.info("Saving composition changes",{compositionId:i,data:o});const t=this.sessions.get(i);(null==t?void 0:t.widgetController)&&(yield t.widgetController.updateConfig(o),yield t.widgetController.refresh()),yield this.closeEditor(i),e.info("Composition saved successfully",{compositionId:i})}catch(t){e.error("Failed to save composition",{compositionId:i,error:t}),this.showError("Failed to save changes. Please try again.",i)}}))}handleEditorPreview(i,o){return t(this,void 0,void 0,(function*(){try{const t=this.sessions.get(i);(null==t?void 0:t.widgetController)&&(yield t.widgetController.callFunction("preview",o))}catch(t){e.warn("Preview update failed",{compositionId:i,error:t})}}))}closeEditor(i){return t(this,void 0,void 0,(function*(){const t=this.sessions.get(i);if(t&&t.isOpen)try{if(t.editorInstance&&t.editorContainer){const e=f().getInstance();e&&(yield e.unmountCompositionEditor(t.editorContainer))}if(t.portal&&t.portal.destroy(),t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="block")}t.isOpen=!1,t.editorContainer=void 0,t.editorInstance=void 0,t.portal=void 0,e.info("Editor closed",{compositionId:i})}catch(t){e.error("Error closing editor",{compositionId:i,error:t})}}))}showError(t,e){const i=document.createElement("div");i.style.cssText="\n position: fixed;\n top: 20px;\n right: 20px;\n background: #dc3545;\n color: white;\n padding: 12px 16px;\n border-radius: 4px;\n z-index: 100001;\n font-size: 14px;\n max-width: 300px;\n ",i.textContent=t,document.body.appendChild(i),setTimeout((()=>{i.parentNode&&i.parentNode.removeChild(i)}),5e3)}removeOverlay(t){const i=this.sessions.get(t);i&&(i.isOpen&&this.closeEditor(t),i.overlay&&i.overlay.parentNode&&i.overlay.parentNode.removeChild(i.overlay),i.portal&&i.portal.destroy(),this.sessions.delete(t),e.debug("Editor overlay removed",{compositionId:t}))}isEditorOpen(t){var e;return(null===(e=this.sessions.get(t))||void 0===e?void 0:e.isOpen)||!1}getActiveSessions(){return Array.from(this.sessions.keys())}cleanup(){for(const t of this.sessions.keys())this.removeOverlay(t);e.debug("Editor overlay cleanup complete")}}let b=null;function E(t){return b||(b=new w(t)),b}var C=Object.freeze({__proto__:null,EditorOverlay:w,getEditorOverlay:E,resetEditorOverlay:function(){b&&(b.cleanup(),b=null)}});export{E as a,f as b,m as c,c as d,C as e,p as g,l as t};