@widgetic/embed-sdk 2.0.11 → 2.0.13
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/LICENSE +122 -0
- package/README.md +3 -1
- package/dist/browser/chunks/ABTestManager.js +1 -1
- package/dist/browser/chunks/advanced.js +1 -1
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/display.js +1 -1
- package/dist/browser/chunks/media.js +1 -1
- package/dist/browser/chunks/messaging.js +1 -1
- package/dist/browser/chunks/renderers.js +1 -1
- package/dist/browser/chunks/scanner.js +1 -1
- package/dist/browser/chunks/security.js +1 -1
- package/dist/browser/embed-bootstrap.js +1 -1
- package/dist/browser/embed-sdk.js +1 -1
- package/dist/esm/chunks/ABTestManager.js +1 -1
- package/dist/esm/chunks/advanced.js +1 -1
- package/dist/esm/chunks/api.js +1 -1
- package/dist/esm/chunks/display.js +1 -1
- package/dist/esm/chunks/media.js +1 -1
- package/dist/esm/chunks/messaging.js +1 -1
- package/dist/esm/chunks/renderers.js +1 -1
- package/dist/esm/chunks/scanner.js +1 -1
- package/dist/esm/chunks/security.js +1 -1
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/esm/types/core/content-position-manager.d.ts +4 -0
- package/dist/esm/types/core/media-manager.d.ts +18 -1
- package/dist/esm/types/core/realtime-manager.d.ts +9 -2
- package/dist/esm/types/utils/chrome-labels.d.ts +26 -0
- package/dist/esm/types/utils/declarative-embed-parser.d.ts +84 -0
- package/dist/esm/types/utils/hydrate-published-host.d.ts +17 -2
- package/dist/esm/types/utils/mount-direct-widget.d.ts +34 -0
- package/dist/esm/types/utils/public-embed-lookup.d.ts +17 -0
- package/dist/esm/types/utils/published-host-bridge.d.ts +24 -0
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +2 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Widgetic Integration License
|
|
2
|
+
Version 1.0
|
|
3
|
+
|
|
4
|
+
Copyright (c) Widgetic. All rights reserved.
|
|
5
|
+
|
|
6
|
+
This license covers the software package that it came with, in source and
|
|
7
|
+
compiled form, together with its documentation (the "Software"). By
|
|
8
|
+
installing, copying or using the Software you accept this license. If you do
|
|
9
|
+
not accept it, do not install or use the Software.
|
|
10
|
+
|
|
11
|
+
In this license, "Widgetic" is the company that publishes the Software, "you"
|
|
12
|
+
is the person or organization that uses it, and "Your Application" is an
|
|
13
|
+
application, website, product or service that you build or operate, for
|
|
14
|
+
yourself or for a client. "Widgetic Services" are the services that Widgetic
|
|
15
|
+
operates: the Widgetic API, widgets, compositions, embeds, editors, file
|
|
16
|
+
browser, chat and AI creator, and the other services that can be reached from
|
|
17
|
+
widgetic.com or its API hosts.
|
|
18
|
+
|
|
19
|
+
1. What you may do
|
|
20
|
+
|
|
21
|
+
Widgetic grants you a worldwide, non-exclusive, non-transferable and
|
|
22
|
+
non-sublicensable license to use the Software, unmodified, for one purpose: to
|
|
23
|
+
integrate the Widgetic Services into Your Application. Within that purpose you
|
|
24
|
+
may:
|
|
25
|
+
|
|
26
|
+
(a) install the Software and run it in Your Application, in development,
|
|
27
|
+
testing and production;
|
|
28
|
+
|
|
29
|
+
(b) use it to call the Widgetic API, to show Widgetic widgets and
|
|
30
|
+
compositions, and to open Widgetic's editors, file browser, chat and AI
|
|
31
|
+
creator inside Your Application;
|
|
32
|
+
|
|
33
|
+
(c) bundle, minify and tree-shake the Software with the build tools of Your
|
|
34
|
+
Application, deliver the result to the people who use Your Application as a
|
|
35
|
+
part of it, and let them run it there;
|
|
36
|
+
|
|
37
|
+
(d) keep the copies of the Software that (a), (b) and (c) need, including
|
|
38
|
+
copies in your version control, your build systems and your backups.
|
|
39
|
+
|
|
40
|
+
2. What you may not do
|
|
41
|
+
|
|
42
|
+
You may not, and may not allow anyone else to:
|
|
43
|
+
|
|
44
|
+
(a) use the Software for any purpose other than the one in section 1;
|
|
45
|
+
|
|
46
|
+
(b) use the Software to build, run or improve a service that offers what the
|
|
47
|
+
Widgetic Services offer, or to connect Your Application to anything other than
|
|
48
|
+
the Widgetic Services (a proxy of yours that forwards calls to the Widgetic
|
|
49
|
+
Services is fine);
|
|
50
|
+
|
|
51
|
+
(c) copy, modify, translate, adapt or make derivative works of the Software,
|
|
52
|
+
except as section 1(c) allows;
|
|
53
|
+
|
|
54
|
+
(d) publish, sell, rent, lease, sublicense or distribute the Software on its
|
|
55
|
+
own, or inside a library, SDK, template or product that others could use for
|
|
56
|
+
anything other than integrating the Widgetic Services, including by
|
|
57
|
+
publishing it, or a copy of it, to a package registry or a public CDN;
|
|
58
|
+
|
|
59
|
+
(e) reverse engineer, decompile or disassemble the Software, or try to get at
|
|
60
|
+
its source code, except as far as the law lets you despite this restriction;
|
|
61
|
+
|
|
62
|
+
(f) remove or change a copyright, license or attribution notice in the
|
|
63
|
+
Software;
|
|
64
|
+
|
|
65
|
+
(g) bypass, disable or interfere with the authentication, rate limits, quotas,
|
|
66
|
+
credits, plan limits or other protections of the Widgetic Services, or help
|
|
67
|
+
anyone else to;
|
|
68
|
+
|
|
69
|
+
(h) use the name, logo or trademarks of Widgetic, except to say truthfully
|
|
70
|
+
that Your Application integrates Widgetic.
|
|
71
|
+
|
|
72
|
+
3. The Widgetic Services are separate
|
|
73
|
+
|
|
74
|
+
This license is for the Software only. It does not give you the right to use
|
|
75
|
+
the Widgetic Services. That right comes from your account or agreement with
|
|
76
|
+
Widgetic and from Widgetic's Terms of Service (https://widgetic.com/terms),
|
|
77
|
+
which this license does not change.
|
|
78
|
+
|
|
79
|
+
4. Ownership
|
|
80
|
+
|
|
81
|
+
The Software is licensed to you, not sold. Widgetic and its licensors keep all
|
|
82
|
+
rights in it. Any right that this license does not give you in plain words is
|
|
83
|
+
reserved to Widgetic.
|
|
84
|
+
|
|
85
|
+
5. Third-party software
|
|
86
|
+
|
|
87
|
+
The Software may include or depend on software from others. That software is
|
|
88
|
+
under its own license, which applies to it instead of this one, and nothing in
|
|
89
|
+
this license limits your rights under it.
|
|
90
|
+
|
|
91
|
+
6. How long it lasts
|
|
92
|
+
|
|
93
|
+
This license lasts while you follow it and while you are entitled to use the
|
|
94
|
+
Widgetic Services. It ends on its own if you break it or that entitlement
|
|
95
|
+
ends. When it ends, you stop using the Software and delete your copies of it,
|
|
96
|
+
except copies that the law requires you to keep. Sections 4, 8 and 9 still
|
|
97
|
+
apply after it has ended.
|
|
98
|
+
|
|
99
|
+
7. Versions
|
|
100
|
+
|
|
101
|
+
This license applies to the version of the Software that it came with and to
|
|
102
|
+
later versions that carry it. A version that Widgetic published under another
|
|
103
|
+
license stays under that license, for the copies of it that you already have.
|
|
104
|
+
|
|
105
|
+
8. No warranty
|
|
106
|
+
|
|
107
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
108
|
+
IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
|
109
|
+
PURPOSE AND NON-INFRINGEMENT.
|
|
110
|
+
|
|
111
|
+
9. Limit of liability
|
|
112
|
+
|
|
113
|
+
TO THE EXTENT THE LAW ALLOWS, WIDGETIC IS NOT LIABLE FOR ANY INDIRECT,
|
|
114
|
+
INCIDENTAL, SPECIAL, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR FOR LOST PROFITS,
|
|
115
|
+
REVENUE, DATA OR GOODWILL, THAT ARISE FROM THE SOFTWARE OR FROM THIS LICENSE,
|
|
116
|
+
EVEN IF IT HAS BEEN TOLD THAT THEY ARE POSSIBLE. NOTHING IN THIS LICENSE
|
|
117
|
+
LIMITS A LIABILITY THAT THE LAW DOES NOT ALLOW TO BE LIMITED.
|
|
118
|
+
|
|
119
|
+
10. Questions
|
|
120
|
+
|
|
121
|
+
If you need to do something that this license does not allow, ask first:
|
|
122
|
+
support@widgetic.com.
|
package/README.md
CHANGED
|
@@ -92,6 +92,8 @@ Optional attributes on `<widgetic>` are sent to the published frame as a `widget
|
|
|
92
92
|
|
|
93
93
|
A widget keeps the language and the colours its author gave it, whatever page it sits in, so there is no attribute that changes either. Your own language and colours belong to Widgetic's editors (`@widgetic/ui-sdk`): each module takes `locale`, `messages` and `theme`. Versions 2.0.8 and 2.0.9 of this package also passed `lang`, `dir`, `mode` and `colors` on to the frame; they no longer do, and a tag that still carries them is drawn as any other.
|
|
94
94
|
|
|
95
|
+
The few words the script draws itself on your page, the accessible names of its close buttons and of the frame, follow the page's own `lang` (`<body lang>` first, then `<html lang>`). Twelve languages are built in, the same twelve that `@widgetic/ui-sdk` ships packs for (French, German, Spanish, Brazilian Portuguese, Dutch, Danish, Swedish, simplified Chinese, Arabic, Hebrew, Persian, Urdu); any other language, and a page that does not say its own, gets English. They are provisional until a native speaker has read them.
|
|
96
|
+
|
|
95
97
|
The element fires DOM events (bubbling, composed) that match the frame protocol: `widgetic:ready`, `widgetic:error`, `widgetic:submitted`, `widgetic:resize`, `widgetic:data`, `widgetic:interaction`, `widgetic:form-submit`. Lookup failures use `widgetic:error` with `detail.code` in lower case (`not_found`, `domain_not_allowed`, `device_restricted`, …).
|
|
96
98
|
|
|
97
99
|
Markers the script writes: `data-widgetic-mounting`, `data-widgetic-mounted`, `data-device-restricted`, `data-widgetic-refused="CODE"`, `data-widgetic-context-invalid`. See `docs/host-contract.md` for the full contract.
|
|
@@ -165,7 +167,7 @@ npm run publish:cdn -- --purge --allow-dirty --env-file .env
|
|
|
165
167
|
|
|
166
168
|
## License
|
|
167
169
|
|
|
168
|
-
|
|
170
|
+
This package is licensed under the Widgetic Integration License (see the `LICENSE` file in the package): you may use it to integrate Widgetic into your own application, and for nothing else. It is not open source. For any other use, write to support@widgetic.com.
|
|
169
171
|
|
|
170
172
|
## Support
|
|
171
173
|
|
|
@@ -1 +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};
|
|
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"./scanner.js";import"./media.js";import"./display.js";import"./security.js";import"./performance.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};
|