@saasquatch/squatch-js 2.7.0-3 → 2.7.0-4

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 (48) hide show
  1. package/dist/squatch.cjs.js +2119 -7
  2. package/dist/squatch.cjs.js.map +1 -1
  3. package/dist/squatch.esm.js +2161 -0
  4. package/dist/squatch.esm.js.map +1 -0
  5. package/dist/squatch.js +2125 -9
  6. package/dist/squatch.js.map +1 -1
  7. package/dist/squatch.min.js +6 -0
  8. package/package.json +8 -8
  9. package/vite.config.ts +10 -3
  10. package/coverage/clover.xml +0 -917
  11. package/coverage/coverage-final.json +0 -21
  12. package/coverage/lcov-report/base.css +0 -224
  13. package/coverage/lcov-report/block-navigation.js +0 -87
  14. package/coverage/lcov-report/favicon.png +0 -0
  15. package/coverage/lcov-report/prettify.css +0 -1
  16. package/coverage/lcov-report/prettify.js +0 -2
  17. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  18. package/coverage/lcov-report/sorter.js +0 -196
  19. package/coverage/lcov.info +0 -1669
  20. package/dist/squatch.es.js +0 -1623
  21. package/dist/squatch.es.js.map +0 -1
  22. package/dist copy/api/AnalyticsApi.d.ts +0 -32
  23. package/dist copy/api/EventsApi.d.ts +0 -52
  24. package/dist copy/api/WidgetApi.d.ts +0 -64
  25. package/dist copy/api/graphql.d.ts +0 -1
  26. package/dist copy/async.d.ts +0 -20
  27. package/dist copy/docs.d.ts +0 -1
  28. package/dist copy/globals.d.ts +0 -4
  29. package/dist copy/squatch.cjs.js +0 -48
  30. package/dist copy/squatch.d.ts +0 -122
  31. package/dist copy/squatch.es.js +0 -1622
  32. package/dist copy/squatch.esm.js +0 -2317
  33. package/dist copy/squatch.esm.js.map +0 -1
  34. package/dist copy/squatch.js +0 -2337
  35. package/dist copy/squatch.js.map +0 -1
  36. package/dist copy/types.d.ts +0 -109
  37. package/dist copy/utils/cookieUtils.d.ts +0 -3
  38. package/dist copy/utils/decodeUserJwt.d.ts +0 -2
  39. package/dist copy/utils/domready.d.ts +0 -6
  40. package/dist copy/utils/io.d.ts +0 -5
  41. package/dist copy/utils/utmUtils.d.ts +0 -14
  42. package/dist copy/utils/validate.d.ts +0 -12
  43. package/dist copy/widgets/EmbedWidget.d.ts +0 -25
  44. package/dist copy/widgets/PopupWidget.d.ts +0 -30
  45. package/dist copy/widgets/Widget.d.ts +0 -57
  46. package/dist copy/widgets/Widgets.d.ts +0 -112
  47. package/dist copy/widgets/declarative/DeclarativeWidget.d.ts +0 -100
  48. package/dist copy/widgets/declarative/DeclarativeWidgets.d.ts +0 -35
@@ -1,4 +1,610 @@
1
- "use strict";var Ae=Object.defineProperty;var Ie=(i,n,t)=>n in i?Ae(i,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[n]=t;var p=(i,n,t)=>Ie(i,typeof n!="symbol"?n+"":n,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function _e(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var M={exports:{}},G,re;function Fe(){if(re)return G;re=1;var i=1e3,n=i*60,t=n*60,e=t*24,o=e*7,r=e*365.25;G=function(s,c){c=c||{};var l=typeof s;if(l==="string"&&s.length>0)return a(s);if(l==="number"&&isFinite(s))return c.long?u(s):d(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))};function a(s){if(s=String(s),!(s.length>100)){var c=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(c){var l=parseFloat(c[1]),m=(c[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return l*r;case"weeks":case"week":case"w":return l*o;case"days":case"day":case"d":return l*e;case"hours":case"hour":case"hrs":case"hr":case"h":return l*t;case"minutes":case"minute":case"mins":case"min":case"m":return l*n;case"seconds":case"second":case"secs":case"sec":case"s":return l*i;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return l;default:return}}}}function d(s){var c=Math.abs(s);return c>=e?Math.round(s/e)+"d":c>=t?Math.round(s/t)+"h":c>=n?Math.round(s/n)+"m":c>=i?Math.round(s/i)+"s":s+"ms"}function u(s){var c=Math.abs(s);return c>=e?h(s,c,e,"day"):c>=t?h(s,c,t,"hour"):c>=n?h(s,c,n,"minute"):c>=i?h(s,c,i,"second"):s+" ms"}function h(s,c,l,m){var f=c>=l*1.5;return Math.round(s/l)+" "+m+(f?"s":"")}return G}var V,se;function ke(){if(se)return V;se=1;function i(n){e.debug=e,e.default=e,e.coerce=h,e.disable=d,e.enable=a,e.enabled=u,e.humanize=Fe(),Object.keys(n).forEach(function(s){e[s]=n[s]}),e.instances=[],e.names=[],e.skips=[],e.formatters={};function t(s){for(var c=0,l=0;l<s.length;l++)c=(c<<5)-c+s.charCodeAt(l),c|=0;return e.colors[Math.abs(c)%e.colors.length]}e.selectColor=t;function e(s){var c;function l(){if(l.enabled){for(var m=arguments.length,f=new Array(m),b=0;b<m;b++)f[b]=arguments[b];var w=l,y=Number(new Date),Ce=y-(c||y);w.diff=Ce,w.prev=c,w.curr=y,c=y,f[0]=e.coerce(f[0]),typeof f[0]!="string"&&f.unshift("%O");var T=0;f[0]=f[0].replace(/%([a-zA-Z%])/g,function(P,be){if(P==="%%")return P;T++;var ie=e.formatters[be];if(typeof ie=="function"){var ve=f[T];P=ie.call(w,ve),f.splice(T,1),T--}return P}),e.formatArgs.call(w,f);var Ee=w.log||e.log;Ee.apply(w,f)}}return l.namespace=s,l.enabled=e.enabled(s),l.useColors=e.useColors(),l.color=t(s),l.destroy=o,l.extend=r,typeof e.init=="function"&&e.init(l),e.instances.push(l),l}function o(){var s=e.instances.indexOf(this);return s!==-1?(e.instances.splice(s,1),!0):!1}function r(s,c){return e(this.namespace+(typeof c>"u"?":":c)+s)}function a(s){e.save(s),e.names=[],e.skips=[];var c,l=(typeof s=="string"?s:"").split(/[\s,]+/),m=l.length;for(c=0;c<m;c++)l[c]&&(s=l[c].replace(/\*/g,".*?"),s[0]==="-"?e.skips.push(new RegExp("^"+s.substr(1)+"$")):e.names.push(new RegExp("^"+s+"$")));for(c=0;c<e.instances.length;c++){var f=e.instances[c];f.enabled=e.enabled(f.namespace)}}function d(){e.enable("")}function u(s){if(s[s.length-1]==="*")return!0;var c,l;for(c=0,l=e.skips.length;c<l;c++)if(e.skips[c].test(s))return!1;for(c=0,l=e.names.length;c<l;c++)if(e.names[c].test(s))return!0;return!1}function h(s){return s instanceof Error?s.stack||s.message:s}return e.enable(e.load()),e}return V=i,V}var ae;function qe(){return ae||(ae=1,function(i,n){function t(s){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?t=function(l){return typeof l}:t=function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l},t(s)}n.log=r,n.formatArgs=o,n.save=a,n.load=d,n.useColors=e,n.storage=u(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function e(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(s){if(s[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+s[0]+(this.useColors?"%c ":" ")+"+"+i.exports.humanize(this.diff),!!this.useColors){var c="color: "+this.color;s.splice(1,0,c,"color: inherit");var l=0,m=0;s[0].replace(/%[a-zA-Z%]/g,function(f){f!=="%%"&&(l++,f==="%c"&&(m=l))}),s.splice(m,0,c)}}function r(){var s;return(typeof console>"u"?"undefined":t(console))==="object"&&console.log&&(s=console).log.apply(s,arguments)}function a(s){try{s?n.storage.setItem("debug",s):n.storage.removeItem("debug")}catch{}}function d(){var s;try{s=n.storage.getItem("debug")}catch{}return!s&&typeof process<"u"&&"env"in process&&(s=process.env.DEBUG),s}function u(){try{return localStorage}catch{}}i.exports=ke()(n);var h=i.exports.formatters;h.j=function(s){try{return JSON.stringify(s)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}(M,M.exports)),M.exports}var g=qe();const xe=_e(g);/*! js-cookie v3.0.5 | MIT */function $(i){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var e in t)i[e]=t[e]}return i}var Re={read:function(i){return i[0]==='"'&&(i=i.slice(1,-1)),i.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(i){return encodeURIComponent(i).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Y(i,n){function t(o,r,a){if(!(typeof document>"u")){a=$({},n,a),typeof a.expires=="number"&&(a.expires=new Date(Date.now()+a.expires*864e5)),a.expires&&(a.expires=a.expires.toUTCString()),o=encodeURIComponent(o).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var d="";for(var u in a)a[u]&&(d+="; "+u,a[u]!==!0&&(d+="="+a[u].split(";")[0]));return document.cookie=o+"="+i.write(r,o)+d}}function e(o){if(!(typeof document>"u"||arguments.length&&!o)){for(var r=document.cookie?document.cookie.split("; "):[],a={},d=0;d<r.length;d++){var u=r[d].split("="),h=u.slice(1).join("=");try{var s=decodeURIComponent(u[0]);if(a[s]=i.read(h,s),o===s)break}catch{}}return o?a[o]:a}}return Object.create({set:t,get:e,remove:function(o,r){t(o,"",$({},r,{expires:-1}))},withAttributes:function(o){return Y(this.converter,$({},this.attributes,o))},withConverter:function(o){return Y($({},this.converter,o),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(i)}})}var L=Y(Re,{path:"/"});const I="https://app.referralsaasquatch.com",Z="https://fast.ssqt.io/npm",W="squatch",X="impact";function B(i){if(typeof i!="object")throw new Error("config must be an object");const n=window.squatchTenant,t=te(),e={tenantAlias:(i==null?void 0:i.tenantAlias)||n,domain:(i==null?void 0:i.domain)||(t==null?void 0:t.domain),npmCdn:(i==null?void 0:i.npmCdn)||(t==null?void 0:t.npmCdn),debug:(i==null?void 0:i.debug)||(t==null?void 0:t.debug)};if(typeof e.tenantAlias!="string")throw new Error("tenantAlias not provided");const o=e.tenantAlias,r=typeof e.domain=="string"&&e.domain||I,a=typeof e.debug=="boolean"&&e.debug||!1,d=typeof e.npmCdn=="string"&&e.npmCdn||Z;return{tenantAlias:o,domain:r,debug:a,npmCdn:d}}function _(i){return typeof i=="object"&&!Array.isArray(i)&&i!==null}function Ue(i){if(i&&/^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(i))return i}function he(i){if(!_(i))throw new Error("Widget properties must be an object");if(!(i!=null&&i.user))throw new Error("Required properties missing.");return i}function pe(i){if(!_(i))throw new Error("Widget properties must be an object");return i}function U(){return window.impactToken||window.squatchToken}function te(){return window.impactConfig||window.squatchConfig}g.debug("squatch-js:io");async function Se(i,n,t,e){const o=e||U(),r={Accept:"application/json","Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{},"X-SaaSquatch-Referrer":window?window.location.href:""};try{const a=await fetch(i,{method:"POST",body:JSON.stringify({query:n,variables:t}),headers:r});if(!a.ok)throw new Error(await a.text());return await a.json()}catch(a){throw a}}async function Te(i,n=""){const t={Accept:"application/json","Content-Type":"application/json"},e=n||U();e&&(t["X-SaaSquatch-User-Token"]=e);try{const o=await fetch(i,{method:"GET",credentials:"include",headers:t}),r=await o.text();if(!o.ok)throw new Error(r);return r&&JSON.parse(r)}catch(o){throw o}}async function K(i,n,t){const e={Accept:"application/json","Content-Type":"application/json"},o=t||U();o&&(e["X-SaaSquatch-User-Token"]=o);try{const r=await fetch(i,{method:"POST",body:n,headers:e}),a=await r.text();if(!r.ok)throw new Error(a);return a&&JSON.parse(a)}catch(r){throw r}}async function Pe(i,n,t){const e={Accept:"application/json","Content-Type":"application/json","X-SaaSquatch-Referrer":window?window.location.href:""},o=t||U();o&&(e["X-SaaSquatch-User-Token"]=o);try{const r=await fetch(i,{headers:e,method:"PUT",credentials:"include",body:n}),a=await r.text();if(!r.ok)throw new Error(a);return a&&JSON.parse(a)}catch(r){throw r}}const Me=`
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ var _a;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ function getDefaultExportFromCjs(x) {
8
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
9
+ }
10
+ var browser = { exports: {} };
11
+ var ms;
12
+ var hasRequiredMs;
13
+ function requireMs() {
14
+ if (hasRequiredMs) return ms;
15
+ hasRequiredMs = 1;
16
+ var s = 1e3;
17
+ var m = s * 60;
18
+ var h = m * 60;
19
+ var d = h * 24;
20
+ var w = d * 7;
21
+ var y = d * 365.25;
22
+ ms = function(val, options) {
23
+ options = options || {};
24
+ var type = typeof val;
25
+ if (type === "string" && val.length > 0) {
26
+ return parse(val);
27
+ } else if (type === "number" && isFinite(val)) {
28
+ return options.long ? fmtLong(val) : fmtShort(val);
29
+ }
30
+ throw new Error(
31
+ "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
32
+ );
33
+ };
34
+ function parse(str) {
35
+ str = String(str);
36
+ if (str.length > 100) {
37
+ return;
38
+ }
39
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
40
+ str
41
+ );
42
+ if (!match) {
43
+ return;
44
+ }
45
+ var n = parseFloat(match[1]);
46
+ var type = (match[2] || "ms").toLowerCase();
47
+ switch (type) {
48
+ case "years":
49
+ case "year":
50
+ case "yrs":
51
+ case "yr":
52
+ case "y":
53
+ return n * y;
54
+ case "weeks":
55
+ case "week":
56
+ case "w":
57
+ return n * w;
58
+ case "days":
59
+ case "day":
60
+ case "d":
61
+ return n * d;
62
+ case "hours":
63
+ case "hour":
64
+ case "hrs":
65
+ case "hr":
66
+ case "h":
67
+ return n * h;
68
+ case "minutes":
69
+ case "minute":
70
+ case "mins":
71
+ case "min":
72
+ case "m":
73
+ return n * m;
74
+ case "seconds":
75
+ case "second":
76
+ case "secs":
77
+ case "sec":
78
+ case "s":
79
+ return n * s;
80
+ case "milliseconds":
81
+ case "millisecond":
82
+ case "msecs":
83
+ case "msec":
84
+ case "ms":
85
+ return n;
86
+ default:
87
+ return void 0;
88
+ }
89
+ }
90
+ function fmtShort(ms2) {
91
+ var msAbs = Math.abs(ms2);
92
+ if (msAbs >= d) {
93
+ return Math.round(ms2 / d) + "d";
94
+ }
95
+ if (msAbs >= h) {
96
+ return Math.round(ms2 / h) + "h";
97
+ }
98
+ if (msAbs >= m) {
99
+ return Math.round(ms2 / m) + "m";
100
+ }
101
+ if (msAbs >= s) {
102
+ return Math.round(ms2 / s) + "s";
103
+ }
104
+ return ms2 + "ms";
105
+ }
106
+ function fmtLong(ms2) {
107
+ var msAbs = Math.abs(ms2);
108
+ if (msAbs >= d) {
109
+ return plural(ms2, msAbs, d, "day");
110
+ }
111
+ if (msAbs >= h) {
112
+ return plural(ms2, msAbs, h, "hour");
113
+ }
114
+ if (msAbs >= m) {
115
+ return plural(ms2, msAbs, m, "minute");
116
+ }
117
+ if (msAbs >= s) {
118
+ return plural(ms2, msAbs, s, "second");
119
+ }
120
+ return ms2 + " ms";
121
+ }
122
+ function plural(ms2, msAbs, n, name) {
123
+ var isPlural = msAbs >= n * 1.5;
124
+ return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : "");
125
+ }
126
+ return ms;
127
+ }
128
+ var common;
129
+ var hasRequiredCommon;
130
+ function requireCommon() {
131
+ if (hasRequiredCommon) return common;
132
+ hasRequiredCommon = 1;
133
+ function setup(env) {
134
+ createDebug.debug = createDebug;
135
+ createDebug.default = createDebug;
136
+ createDebug.coerce = coerce;
137
+ createDebug.disable = disable;
138
+ createDebug.enable = enable;
139
+ createDebug.enabled = enabled;
140
+ createDebug.humanize = requireMs();
141
+ Object.keys(env).forEach(function(key) {
142
+ createDebug[key] = env[key];
143
+ });
144
+ createDebug.instances = [];
145
+ createDebug.names = [];
146
+ createDebug.skips = [];
147
+ createDebug.formatters = {};
148
+ function selectColor(namespace) {
149
+ var hash = 0;
150
+ for (var i = 0; i < namespace.length; i++) {
151
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
152
+ hash |= 0;
153
+ }
154
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
155
+ }
156
+ createDebug.selectColor = selectColor;
157
+ function createDebug(namespace) {
158
+ var prevTime;
159
+ function debug2() {
160
+ if (!debug2.enabled) {
161
+ return;
162
+ }
163
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
164
+ args[_key] = arguments[_key];
165
+ }
166
+ var self = debug2;
167
+ var curr = Number(/* @__PURE__ */ new Date());
168
+ var ms2 = curr - (prevTime || curr);
169
+ self.diff = ms2;
170
+ self.prev = prevTime;
171
+ self.curr = curr;
172
+ prevTime = curr;
173
+ args[0] = createDebug.coerce(args[0]);
174
+ if (typeof args[0] !== "string") {
175
+ args.unshift("%O");
176
+ }
177
+ var index = 0;
178
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
179
+ if (match === "%%") {
180
+ return match;
181
+ }
182
+ index++;
183
+ var formatter = createDebug.formatters[format];
184
+ if (typeof formatter === "function") {
185
+ var val = args[index];
186
+ match = formatter.call(self, val);
187
+ args.splice(index, 1);
188
+ index--;
189
+ }
190
+ return match;
191
+ });
192
+ createDebug.formatArgs.call(self, args);
193
+ var logFn = self.log || createDebug.log;
194
+ logFn.apply(self, args);
195
+ }
196
+ debug2.namespace = namespace;
197
+ debug2.enabled = createDebug.enabled(namespace);
198
+ debug2.useColors = createDebug.useColors();
199
+ debug2.color = selectColor(namespace);
200
+ debug2.destroy = destroy;
201
+ debug2.extend = extend;
202
+ if (typeof createDebug.init === "function") {
203
+ createDebug.init(debug2);
204
+ }
205
+ createDebug.instances.push(debug2);
206
+ return debug2;
207
+ }
208
+ function destroy() {
209
+ var index = createDebug.instances.indexOf(this);
210
+ if (index !== -1) {
211
+ createDebug.instances.splice(index, 1);
212
+ return true;
213
+ }
214
+ return false;
215
+ }
216
+ function extend(namespace, delimiter) {
217
+ return createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
218
+ }
219
+ function enable(namespaces) {
220
+ createDebug.save(namespaces);
221
+ createDebug.names = [];
222
+ createDebug.skips = [];
223
+ var i;
224
+ var split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
225
+ var len = split.length;
226
+ for (i = 0; i < len; i++) {
227
+ if (!split[i]) {
228
+ continue;
229
+ }
230
+ namespaces = split[i].replace(/\*/g, ".*?");
231
+ if (namespaces[0] === "-") {
232
+ createDebug.skips.push(new RegExp("^" + namespaces.substr(1) + "$"));
233
+ } else {
234
+ createDebug.names.push(new RegExp("^" + namespaces + "$"));
235
+ }
236
+ }
237
+ for (i = 0; i < createDebug.instances.length; i++) {
238
+ var instance = createDebug.instances[i];
239
+ instance.enabled = createDebug.enabled(instance.namespace);
240
+ }
241
+ }
242
+ function disable() {
243
+ createDebug.enable("");
244
+ }
245
+ function enabled(name) {
246
+ if (name[name.length - 1] === "*") {
247
+ return true;
248
+ }
249
+ var i;
250
+ var len;
251
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
252
+ if (createDebug.skips[i].test(name)) {
253
+ return false;
254
+ }
255
+ }
256
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
257
+ if (createDebug.names[i].test(name)) {
258
+ return true;
259
+ }
260
+ }
261
+ return false;
262
+ }
263
+ function coerce(val) {
264
+ if (val instanceof Error) {
265
+ return val.stack || val.message;
266
+ }
267
+ return val;
268
+ }
269
+ createDebug.enable(createDebug.load());
270
+ return createDebug;
271
+ }
272
+ common = setup;
273
+ return common;
274
+ }
275
+ var hasRequiredBrowser;
276
+ function requireBrowser() {
277
+ if (hasRequiredBrowser) return browser.exports;
278
+ hasRequiredBrowser = 1;
279
+ (function(module2, exports2) {
280
+ function _typeof(obj) {
281
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
282
+ _typeof = function _typeof2(obj2) {
283
+ return typeof obj2;
284
+ };
285
+ } else {
286
+ _typeof = function _typeof2(obj2) {
287
+ return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
288
+ };
289
+ }
290
+ return _typeof(obj);
291
+ }
292
+ exports2.log = log;
293
+ exports2.formatArgs = formatArgs;
294
+ exports2.save = save;
295
+ exports2.load = load;
296
+ exports2.useColors = useColors;
297
+ exports2.storage = localstorage();
298
+ exports2.colors = ["#0000CC", "#0000FF", "#0033CC", "#0033FF", "#0066CC", "#0066FF", "#0099CC", "#0099FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#3300CC", "#3300FF", "#3333CC", "#3333FF", "#3366CC", "#3366FF", "#3399CC", "#3399FF", "#33CC00", "#33CC33", "#33CC66", "#33CC99", "#33CCCC", "#33CCFF", "#6600CC", "#6600FF", "#6633CC", "#6633FF", "#66CC00", "#66CC33", "#9900CC", "#9900FF", "#9933CC", "#9933FF", "#99CC00", "#99CC33", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF", "#CC6600", "#CC6633", "#CC9900", "#CC9933", "#CCCC00", "#CCCC33", "#FF0000", "#FF0033", "#FF0066", "#FF0099", "#FF00CC", "#FF00FF", "#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#FF6600", "#FF6633", "#FF9900", "#FF9933", "#FFCC00", "#FFCC33"];
299
+ function useColors() {
300
+ if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
301
+ return true;
302
+ }
303
+ if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
304
+ return false;
305
+ }
306
+ return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
307
+ typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
308
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
309
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
310
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
311
+ }
312
+ function formatArgs(args) {
313
+ args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
314
+ if (!this.useColors) {
315
+ return;
316
+ }
317
+ var c = "color: " + this.color;
318
+ args.splice(1, 0, c, "color: inherit");
319
+ var index = 0;
320
+ var lastC = 0;
321
+ args[0].replace(/%[a-zA-Z%]/g, function(match) {
322
+ if (match === "%%") {
323
+ return;
324
+ }
325
+ index++;
326
+ if (match === "%c") {
327
+ lastC = index;
328
+ }
329
+ });
330
+ args.splice(lastC, 0, c);
331
+ }
332
+ function log() {
333
+ var _console;
334
+ return (typeof console === "undefined" ? "undefined" : _typeof(console)) === "object" && console.log && (_console = console).log.apply(_console, arguments);
335
+ }
336
+ function save(namespaces) {
337
+ try {
338
+ if (namespaces) {
339
+ exports2.storage.setItem("debug", namespaces);
340
+ } else {
341
+ exports2.storage.removeItem("debug");
342
+ }
343
+ } catch (error) {
344
+ }
345
+ }
346
+ function load() {
347
+ var r;
348
+ try {
349
+ r = exports2.storage.getItem("debug");
350
+ } catch (error) {
351
+ }
352
+ if (!r && typeof process !== "undefined" && "env" in process) {
353
+ r = process.env.DEBUG;
354
+ }
355
+ return r;
356
+ }
357
+ function localstorage() {
358
+ try {
359
+ return localStorage;
360
+ } catch (error) {
361
+ }
362
+ }
363
+ module2.exports = requireCommon()(exports2);
364
+ var formatters = module2.exports.formatters;
365
+ formatters.j = function(v) {
366
+ try {
367
+ return JSON.stringify(v);
368
+ } catch (error) {
369
+ return "[UnexpectedJSONParseError]: " + error.message;
370
+ }
371
+ };
372
+ })(browser, browser.exports);
373
+ return browser.exports;
374
+ }
375
+ var browserExports = requireBrowser();
376
+ const debug = /* @__PURE__ */ getDefaultExportFromCjs(browserExports);
377
+ /*! js-cookie v3.0.5 | MIT */
378
+ function assign(target) {
379
+ for (var i = 1; i < arguments.length; i++) {
380
+ var source = arguments[i];
381
+ for (var key in source) {
382
+ target[key] = source[key];
383
+ }
384
+ }
385
+ return target;
386
+ }
387
+ var defaultConverter = {
388
+ read: function(value) {
389
+ if (value[0] === '"') {
390
+ value = value.slice(1, -1);
391
+ }
392
+ return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
393
+ },
394
+ write: function(value) {
395
+ return encodeURIComponent(value).replace(
396
+ /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
397
+ decodeURIComponent
398
+ );
399
+ }
400
+ };
401
+ function init$1(converter, defaultAttributes) {
402
+ function set(name, value, attributes) {
403
+ if (typeof document === "undefined") {
404
+ return;
405
+ }
406
+ attributes = assign({}, defaultAttributes, attributes);
407
+ if (typeof attributes.expires === "number") {
408
+ attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
409
+ }
410
+ if (attributes.expires) {
411
+ attributes.expires = attributes.expires.toUTCString();
412
+ }
413
+ name = encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
414
+ var stringifiedAttributes = "";
415
+ for (var attributeName in attributes) {
416
+ if (!attributes[attributeName]) {
417
+ continue;
418
+ }
419
+ stringifiedAttributes += "; " + attributeName;
420
+ if (attributes[attributeName] === true) {
421
+ continue;
422
+ }
423
+ stringifiedAttributes += "=" + attributes[attributeName].split(";")[0];
424
+ }
425
+ return document.cookie = name + "=" + converter.write(value, name) + stringifiedAttributes;
426
+ }
427
+ function get(name) {
428
+ if (typeof document === "undefined" || arguments.length && !name) {
429
+ return;
430
+ }
431
+ var cookies = document.cookie ? document.cookie.split("; ") : [];
432
+ var jar = {};
433
+ for (var i = 0; i < cookies.length; i++) {
434
+ var parts = cookies[i].split("=");
435
+ var value = parts.slice(1).join("=");
436
+ try {
437
+ var found = decodeURIComponent(parts[0]);
438
+ jar[found] = converter.read(value, found);
439
+ if (name === found) {
440
+ break;
441
+ }
442
+ } catch (e) {
443
+ }
444
+ }
445
+ return name ? jar[name] : jar;
446
+ }
447
+ return Object.create(
448
+ {
449
+ set,
450
+ get,
451
+ remove: function(name, attributes) {
452
+ set(
453
+ name,
454
+ "",
455
+ assign({}, attributes, {
456
+ expires: -1
457
+ })
458
+ );
459
+ },
460
+ withAttributes: function(attributes) {
461
+ return init$1(this.converter, assign({}, this.attributes, attributes));
462
+ },
463
+ withConverter: function(converter2) {
464
+ return init$1(assign({}, this.converter, converter2), this.attributes);
465
+ }
466
+ },
467
+ {
468
+ attributes: { value: Object.freeze(defaultAttributes) },
469
+ converter: { value: Object.freeze(converter) }
470
+ }
471
+ );
472
+ }
473
+ var api$1 = init$1(defaultConverter, { path: "/" });
474
+ const DEFAULT_DOMAIN = "https://app.referralsaasquatch.com";
475
+ const DEFAULT_NPM_CDN = "https://fast.ssqt.io/npm";
476
+ const DEFAULT_NAMESPACE = "squatch";
477
+ const IMPACT_NAMESPACE = "impact";
478
+ function validateConfig(_raw) {
479
+ if (typeof _raw !== "object") throw new Error("config must be an object");
480
+ const tenant = window.squatchTenant;
481
+ const config = getConfig();
482
+ const raw = {
483
+ tenantAlias: (_raw == null ? void 0 : _raw["tenantAlias"]) || tenant,
484
+ domain: (_raw == null ? void 0 : _raw["domain"]) || (config == null ? void 0 : config.domain),
485
+ npmCdn: (_raw == null ? void 0 : _raw["npmCdn"]) || (config == null ? void 0 : config.npmCdn),
486
+ debug: (_raw == null ? void 0 : _raw["debug"]) || (config == null ? void 0 : config.debug)
487
+ };
488
+ if (typeof raw.tenantAlias !== "string")
489
+ throw new Error("tenantAlias not provided");
490
+ const tenantAlias = raw.tenantAlias;
491
+ const domain = typeof raw.domain === "string" && raw.domain || DEFAULT_DOMAIN;
492
+ const debug2 = typeof raw.debug === "boolean" && raw.debug || false;
493
+ const npmCdn = typeof raw.npmCdn === "string" && raw.npmCdn || DEFAULT_NPM_CDN;
494
+ return {
495
+ tenantAlias,
496
+ domain,
497
+ debug: debug2,
498
+ npmCdn
499
+ };
500
+ }
501
+ function isObject$1(obj) {
502
+ return typeof obj === "object" && !Array.isArray(obj) && obj !== null;
503
+ }
504
+ function validateLocale(locale) {
505
+ if (locale && /^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(locale)) {
506
+ return locale;
507
+ }
508
+ }
509
+ function validateWidgetConfig(raw) {
510
+ if (!isObject$1(raw)) throw new Error("Widget properties must be an object");
511
+ if (!(raw == null ? void 0 : raw["user"])) throw new Error("Required properties missing.");
512
+ return raw;
513
+ }
514
+ function validatePasswordlessConfig(raw) {
515
+ if (!isObject$1(raw)) throw new Error("Widget properties must be an object");
516
+ return raw;
517
+ }
518
+ function getToken() {
519
+ return window.impactToken || window.squatchToken;
520
+ }
521
+ function getConfig() {
522
+ return window.impactConfig || window.squatchConfig;
523
+ }
524
+ browserExports.debug("squatch-js:io");
525
+ async function doQuery(url, query, variables, jwt) {
526
+ const token = jwt || getToken();
527
+ const headers = {
528
+ Accept: "application/json",
529
+ "Content-Type": "application/json",
530
+ ...token ? { Authorization: `Bearer ${token}` } : {},
531
+ "X-SaaSquatch-Referrer": window ? window.location.href : ""
532
+ };
533
+ try {
534
+ const res = await fetch(url, {
535
+ method: "POST",
536
+ body: JSON.stringify({ query, variables }),
537
+ headers
538
+ });
539
+ if (!res.ok) throw new Error(await res.text());
540
+ return await res.json();
541
+ } catch (e) {
542
+ throw e;
543
+ }
544
+ }
545
+ async function doGet(url, jwt = "") {
546
+ const headers = {
547
+ Accept: "application/json",
548
+ "Content-Type": "application/json"
549
+ };
550
+ const token = jwt || getToken();
551
+ if (token) headers["X-SaaSquatch-User-Token"] = token;
552
+ try {
553
+ const res = await fetch(url, {
554
+ method: "GET",
555
+ credentials: "include",
556
+ headers
557
+ });
558
+ const reply = await res.text();
559
+ if (!res.ok) throw new Error(reply);
560
+ return reply ? JSON.parse(reply) : reply;
561
+ } catch (e) {
562
+ throw e;
563
+ }
564
+ }
565
+ async function doPost(url, data, jwt) {
566
+ const headers = {
567
+ Accept: "application/json",
568
+ "Content-Type": "application/json"
569
+ };
570
+ const token = jwt || getToken();
571
+ if (token) headers["X-SaaSquatch-User-Token"] = token;
572
+ try {
573
+ const res = await fetch(url, {
574
+ method: "POST",
575
+ body: data,
576
+ headers
577
+ });
578
+ const reply = await res.text();
579
+ if (!res.ok) throw new Error(reply);
580
+ return reply ? JSON.parse(reply) : reply;
581
+ } catch (e) {
582
+ throw e;
583
+ }
584
+ }
585
+ async function doPut(url, data, jwt) {
586
+ const headers = {
587
+ Accept: "application/json",
588
+ "Content-Type": "application/json",
589
+ "X-SaaSquatch-Referrer": window ? window.location.href : ""
590
+ };
591
+ const token = jwt || getToken();
592
+ if (token) headers["X-SaaSquatch-User-Token"] = token;
593
+ try {
594
+ const res = await fetch(url, {
595
+ headers,
596
+ method: "PUT",
597
+ credentials: "include",
598
+ body: data
599
+ });
600
+ const reply = await res.text();
601
+ if (!res.ok) throw new Error(reply);
602
+ return reply ? JSON.parse(reply) : reply;
603
+ } catch (e) {
604
+ throw e;
605
+ }
606
+ }
607
+ const RENDER_WIDGET_QUERY = `
2
608
  query renderWidget ($user: UserIdInput, $engagementMedium: UserEngagementMedium, $widgetType: WidgetType, $locale: RSLocale) {
3
609
  renderWidget(user: $user, engagementMedium: $engagementMedium, widgetType: $widgetType, locale: $locale) {
4
610
  template
@@ -12,19 +618,331 @@
12
618
  }
13
619
  }
14
620
  }
15
- `;class z{constructor(n){p(this,"tenantAlias");p(this,"domain");p(this,"npmCdn");p(this,"referralCookie",this.squatchReferralCookie);const e=B(n);this.tenantAlias=e.tenantAlias,this.domain=e.domain,this.npmCdn=e.npmCdn}upsertUser(n){const e=he(n),{widgetType:o,engagementMedium:r="POPUP",jwt:a,locale:d,user:u}=e,h=encodeURIComponent(this.tenantAlias),s=u.accountId?encodeURIComponent(u.accountId):null,c=u.id?encodeURIComponent(u.id):null,l=$e({widgetType:o,engagementMedium:r,locale:d}),m=`/api/v1/${h}/widget/account/${s}/user/${c}/upsert${l}`,f=this.domain+m,b=(L||window.Cookies).get("_saasquatch");return b&&(u.cookies=b),Pe(f,JSON.stringify(u),a)}render(n){const e=pe(n),{widgetType:o,engagementMedium:r="POPUP",jwt:a,user:d}=e,u=encodeURIComponent(this.tenantAlias),h=d!=null&&d.accountId?encodeURIComponent(d.accountId):null,s=d!=null&&d.id?encodeURIComponent(d.id):null,c=e.locale??Ue(navigator.language.replace(/\-/g,"_")),l=`/api/v1/${u}/graphql`,m=this.domain+l;return new Promise(async(f,b)=>{var w;try{const y=await Se(m,Me,{user:s&&h?{id:s,accountId:h}:null,engagementMedium:r,widgetType:o,locale:c},a);f((w=y==null?void 0:y.data)==null?void 0:w.renderWidget)}catch(y){b(y)}})}async squatchReferralCookie(){const n=encodeURIComponent(this.tenantAlias),t=(L||window.Cookies).get("_saasquatch")||"",e=t?`?cookies=${encodeURIComponent(t)}`:"",o=`${this.domain}/a/${n}/widgets/squatchcookiejson${e}`,r=await Te(o);return Promise.resolve({...r,encodedCookie:t})}}function $e({widgetType:i,engagementMedium:n,locale:t}){const e=new URLSearchParams;return e.append("engagementMedium",n),i&&e.append("widgetType",i),t&&e.append("locale",t),`?${e.toString()}`}class fe{constructor(n){p(this,"domain");var o;const e=We(n);this.domain=(e==null?void 0:e.domain)||((o=te())==null?void 0:o.domain)||I}pushAnalyticsLoadEvent(n){if(!n.externalUserId||!n.externalAccountId)return;const t=encodeURIComponent(n.tenantAlias),e=encodeURIComponent(n.externalAccountId),o=encodeURIComponent(n.externalUserId),r=encodeURIComponent(n.engagementMedium),a=n.programId?`&programId=${encodeURIComponent(n.programId)}`:"",d=`/a/${t}/widgets/analytics/loaded?externalAccountId=${e}&externalUserId=${o}&engagementMedium=${r}${a}`,u=this.domain+d;return K(u,JSON.stringify({}))}pushAnalyticsShareClickedEvent(n){const t=encodeURIComponent(n.tenantAlias),e=encodeURIComponent(n.externalAccountId),o=encodeURIComponent(n.externalUserId),r=encodeURIComponent(n.engagementMedium),a=encodeURIComponent(n.shareMedium),d=`/a/${t}/widgets/analytics/shared?externalAccountId=${e}&externalUserId=${o}&engagementMedium=${r}&shareMedium=${a}`,u=this.domain+d;return K(u,JSON.stringify({}))}}function We(i){if(!_(i))throw new Error("'options' should be an object");return i}const C=g.debug("squatch-js:widget");class me{constructor(n){p(this,"type");p(this,"content");p(this,"analyticsApi");p(this,"widgetApi");p(this,"context");p(this,"npmCdn");p(this,"container");p(this,"loadEventListener",null);var t;C("widget initializing ..."),this.content=n.content==="error"?this._error(n.rsCode):n.content,this.type=n.type,this.widgetApi=n.api,this.npmCdn=n.npmCdn,this.analyticsApi=new fe({domain:n.domain}),this.context=n.context,this.container=((t=n.context)==null?void 0:t.container)||n.container}_findElement(){let n;if(typeof this.container=="string"?(n=document.querySelector(this.container),C("loading widget with selector",n)):this.container instanceof HTMLElement?(n=this.container,C("loading widget with container",n)):this.container?(n=null,C("container must be an HTMLElement or string",this.container)):(n=document.querySelector("#squatchembed")||document.querySelector(".squatchembed")||document.querySelector("#impactembed")||document.querySelector(".impactembed"),C("loading widget with default selector",n)),!(n instanceof HTMLElement))throw new Error(`element with selector '${this.container||"#squatchembed, .squatchembed, #impactembed, or .impactembed"}' not found.'`);return n}_createFrame(){const n=document.createElement("iframe");return n.squatchJsApi=this,n.id="squatchFrame",n.width="100%",n.src="about:blank",n.scrolling="no",n.setAttribute("style","border: 0; background-color: none; width: 1px; min-width: 100%;"),n}_findFrame(){const n=this.container?this._findElement():document.body;return(n.shadowRoot||n).querySelector("iframe#squatchFrame")}_detachLoadEventListener(n){this.loadEventListener&&(n.removeEventListener("sq:user-registration",this.loadEventListener),this.loadEventListener=null)}_attachLoadEventListener(n,t){this.loadEventListener===null&&(this.loadEventListener=e=>{this._loadEvent({...t,userId:e.detail.userId,accountId:e.detail.accountId})},n.addEventListener("sq:user-registration",this.loadEventListener))}_loadEvent(n){var e;if(!n)return;if(!_(n))throw new Error("Widget Load event identity property is not an object");let t;if("programId"in n){if(!n.tenantAlias||!n.accountId||!n.userId||!n.engagementMedium)throw new Error("Widget Load event missing required properties");t={tenantAlias:n.tenantAlias,externalAccountId:n.accountId,externalUserId:n.userId,engagementMedium:n.engagementMedium,programId:n.programId}}else{const{analytics:o,mode:r}=n;t={tenantAlias:o.attributes.tenant,externalAccountId:o.attributes.accountId,externalUserId:o.attributes.userId,engagementMedium:r.widgetMode}}(e=this.analyticsApi.pushAnalyticsLoadEvent(t))==null||e.then(o=>{C(`${t.engagementMedium} loaded event recorded.`)}).catch(o=>{C(`ERROR: pushAnalyticsLoadEvent() ${o}`)})}_shareEvent(n,t){n&&this.analyticsApi.pushAnalyticsShareClickedEvent({tenantAlias:n.analytics.attributes.tenant,externalAccountId:n.analytics.attributes.accountId,externalUserId:n.analytics.attributes.userId,engagementMedium:n.mode.widgetMode,shareMedium:t}).then(e=>{C(`${n.mode.widgetMode} share ${t} event recorded. ${e}`)}).catch(e=>{C(`ERROR: pushAnalyticsShareClickedEvent() ${e}`)})}_error(n,t="modal",e=""){return`<!DOCTYPE html>
621
+ `;
622
+ class WidgetApi {
623
+ /**
624
+ * Initialize a new {@link WidgetApi} instance.
625
+ *
626
+ * @param {ConfigOptions} config Config details
627
+ *
628
+ * @example <caption>Browser example</caption>
629
+ * var squatchApi = new squatch.WidgetApi({tenantAlias:'test_12b5bo1b25125'});
630
+ *
631
+ * @example <caption>Browserify/Webpack example</caption>
632
+ * var WidgetApi = require('@saasquatch/squatch-js').WidgetApi;
633
+ * var squatchApi = new WidgetApi({tenantAlias:'test_12b5bo1b25125'});
634
+ *
635
+ * @example <caption>Babel+Browserify/Webpack example</caption>
636
+ * import {WidgetApi} from '@saasquatch/squatch-js';
637
+ * let squatchApi = new WidgetApi({tenantAlias:'test_12b5bo1b25125'});
638
+ */
639
+ constructor(config) {
640
+ __publicField(this, "tenantAlias");
641
+ __publicField(this, "domain");
642
+ __publicField(this, "npmCdn");
643
+ __publicField(this, "referralCookie", this.squatchReferralCookie);
644
+ const raw = config;
645
+ const clean = validateConfig(raw);
646
+ this.tenantAlias = clean.tenantAlias;
647
+ this.domain = clean.domain;
648
+ this.npmCdn = clean.npmCdn;
649
+ }
650
+ /**
651
+ * Creates/upserts user, requests widget template.
652
+ *
653
+ * @param {Object} params Parameters for request
654
+ * @param {Object?} params.user The user details
655
+ * @param {string} params.user.id The user id
656
+ * @param {string} params.user.accountId The user account id
657
+ * @param {WidgetType} params.widgetType The content of the widget.
658
+ * @param {EngagementMedium?} params.engagementMedium How to display the widget.
659
+ * @param {string?} params.jwt the JSON Web Token (JWT) that is used
660
+ * to validate the data (can be disabled)
661
+ *
662
+ * @return {Promise} string if true, with the widget template, jsOptions and user details.
663
+ */
664
+ upsertUser(params) {
665
+ const raw = params;
666
+ const clean = validateWidgetConfig(raw);
667
+ const {
668
+ widgetType,
669
+ engagementMedium = "POPUP",
670
+ jwt,
671
+ locale,
672
+ user
673
+ } = clean;
674
+ const tenantAlias = encodeURIComponent(this.tenantAlias);
675
+ const accountId = user.accountId ? encodeURIComponent(user.accountId) : null;
676
+ const userId = user.id ? encodeURIComponent(user.id) : null;
677
+ const optionalParams = _buildParams({
678
+ widgetType,
679
+ engagementMedium,
680
+ locale
681
+ });
682
+ const path = `/api/v1/${tenantAlias}/widget/account/${accountId}/user/${userId}/upsert${optionalParams}`;
683
+ const url = this.domain + path;
684
+ const cookies = (api$1 || window.Cookies).get("_saasquatch");
685
+ if (cookies) user["cookies"] = cookies;
686
+ return doPut(url, JSON.stringify(user), jwt);
687
+ }
688
+ /**
689
+ * Requests widget template
690
+ *
691
+ * @param {Object} params Parameters for request
692
+ * @param {Object} params.user The user details
693
+ * @param {string} params.user.id The user id
694
+ * @param {string} params.user.accountId The user account id
695
+ * @param {WidgetType} params.widgetType The content of the widget.
696
+ * @param {EngagementMedium} params.engagementMedium How to display the widget.
697
+ * @param {string} params.jwt the JSON Web Token (JWT) that is used
698
+ * to validate the data (can be disabled)
699
+ * @return {Promise} template html if true.
700
+ */
701
+ render(params) {
702
+ const raw = params;
703
+ const clean = validatePasswordlessConfig(raw);
704
+ const { widgetType, engagementMedium = "POPUP", jwt, user } = clean;
705
+ const tenantAlias = encodeURIComponent(this.tenantAlias);
706
+ const accountId = (user == null ? void 0 : user.accountId) ? encodeURIComponent(user.accountId) : null;
707
+ const userId = (user == null ? void 0 : user.id) ? encodeURIComponent(user.id) : null;
708
+ const locale = clean.locale ?? validateLocale(navigator.language.replace(/\-/g, "_"));
709
+ const path = `/api/v1/${tenantAlias}/graphql`;
710
+ const url = this.domain + path;
711
+ return new Promise(async (resolve, reject) => {
712
+ var _a2;
713
+ try {
714
+ const res = await doQuery(
715
+ url,
716
+ RENDER_WIDGET_QUERY,
717
+ {
718
+ user: userId && accountId ? { id: userId, accountId } : null,
719
+ engagementMedium,
720
+ widgetType,
721
+ locale
722
+ },
723
+ jwt
724
+ );
725
+ resolve((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.renderWidget);
726
+ } catch (e) {
727
+ reject(e);
728
+ }
729
+ });
730
+ }
731
+ /**
732
+ * Looks up the referral code of the current user, if there is any.
733
+ *
734
+ * @return {Promise<ReferralCookie>} code referral code if true.
735
+ */
736
+ async squatchReferralCookie() {
737
+ const tenantAlias = encodeURIComponent(this.tenantAlias);
738
+ const _saasquatch = (api$1 || window.Cookies).get("_saasquatch") || "";
739
+ const cookie = _saasquatch ? `?cookies=${encodeURIComponent(_saasquatch)}` : ``;
740
+ const url = `${this.domain}/a/${tenantAlias}/widgets/squatchcookiejson${cookie}`;
741
+ const response = await doGet(url);
742
+ return Promise.resolve({
743
+ ...response,
744
+ encodedCookie: _saasquatch
745
+ });
746
+ }
747
+ }
748
+ function _buildParams({
749
+ widgetType,
750
+ engagementMedium,
751
+ locale
752
+ }) {
753
+ const queryParams = new URLSearchParams();
754
+ queryParams.append("engagementMedium", engagementMedium);
755
+ if (widgetType) queryParams.append("widgetType", widgetType);
756
+ if (locale) queryParams.append("locale", locale);
757
+ return `?${queryParams.toString()}`;
758
+ }
759
+ class AnalyticsApi {
760
+ /**
761
+ * Initialize a new {@link AnalyticsApi} instance.
762
+ *
763
+ * @param {Object} config Config details
764
+ * @param {string} [config.domain='https://app.referralsaasquatch.com'] The server domain.
765
+ *
766
+ */
767
+ constructor(config) {
768
+ __publicField(this, "domain");
769
+ var _a2;
770
+ const raw = config;
771
+ const clean = _validateAnalyticsConfig(raw);
772
+ this.domain = (clean == null ? void 0 : clean["domain"]) || ((_a2 = getConfig()) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN;
773
+ }
774
+ pushAnalyticsLoadEvent(params) {
775
+ if (!params.externalUserId || !params.externalAccountId) return;
776
+ const tenantAlias = encodeURIComponent(params.tenantAlias);
777
+ const accountId = encodeURIComponent(params.externalAccountId);
778
+ const userId = encodeURIComponent(params.externalUserId);
779
+ const engagementMedium = encodeURIComponent(params.engagementMedium);
780
+ const programId = params.programId ? `&programId=${encodeURIComponent(params.programId)}` : ``;
781
+ const path = `/a/${tenantAlias}/widgets/analytics/loaded?externalAccountId=${accountId}&externalUserId=${userId}&engagementMedium=${engagementMedium}${programId}`;
782
+ const url = this.domain + path;
783
+ return doPost(url, JSON.stringify({}));
784
+ }
785
+ pushAnalyticsShareClickedEvent(params) {
786
+ const tenantAlias = encodeURIComponent(params.tenantAlias);
787
+ const accountId = encodeURIComponent(params.externalAccountId);
788
+ const userId = encodeURIComponent(params.externalUserId);
789
+ const engagementMedium = encodeURIComponent(params.engagementMedium);
790
+ const shareMedium = encodeURIComponent(params.shareMedium);
791
+ const path = `/a/${tenantAlias}/widgets/analytics/shared?externalAccountId=${accountId}&externalUserId=${userId}&engagementMedium=${engagementMedium}&shareMedium=${shareMedium}`;
792
+ const url = this.domain + path;
793
+ return doPost(url, JSON.stringify({}));
794
+ }
795
+ }
796
+ function _validateAnalyticsConfig(raw) {
797
+ if (!isObject$1(raw)) throw new Error("'options' should be an object");
798
+ return raw;
799
+ }
800
+ const _log$8 = browserExports.debug("squatch-js:widget");
801
+ class Widget {
802
+ constructor(params) {
803
+ __publicField(this, "type");
804
+ __publicField(this, "content");
805
+ __publicField(this, "analyticsApi");
806
+ __publicField(this, "widgetApi");
807
+ __publicField(this, "context");
808
+ __publicField(this, "npmCdn");
809
+ __publicField(this, "container");
810
+ __publicField(this, "loadEventListener", null);
811
+ var _a2;
812
+ _log$8("widget initializing ...");
813
+ this.content = params.content === "error" ? this._error(params.rsCode) : params.content;
814
+ this.type = params.type;
815
+ this.widgetApi = params.api;
816
+ this.npmCdn = params.npmCdn;
817
+ this.analyticsApi = new AnalyticsApi({ domain: params.domain });
818
+ this.context = params.context;
819
+ this.container = ((_a2 = params.context) == null ? void 0 : _a2.container) || params.container;
820
+ }
821
+ _findElement() {
822
+ let element;
823
+ if (typeof this.container === "string") {
824
+ element = document.querySelector(this.container);
825
+ _log$8("loading widget with selector", element);
826
+ } else if (this.container instanceof HTMLElement) {
827
+ element = this.container;
828
+ _log$8("loading widget with container", element);
829
+ } else if (this.container) {
830
+ element = null;
831
+ _log$8("container must be an HTMLElement or string", this.container);
832
+ } else {
833
+ element = document.querySelector("#squatchembed") || document.querySelector(".squatchembed") || document.querySelector("#impactembed") || document.querySelector(".impactembed");
834
+ _log$8("loading widget with default selector", element);
835
+ }
836
+ if (!(element instanceof HTMLElement))
837
+ throw new Error(
838
+ `element with selector '${this.container || "#squatchembed, .squatchembed, #impactembed, or .impactembed"}' not found.'`
839
+ );
840
+ return element;
841
+ }
842
+ _createFrame() {
843
+ const frame = document.createElement("iframe");
844
+ frame["squatchJsApi"] = this;
845
+ frame.id = "squatchFrame";
846
+ frame.width = "100%";
847
+ frame.src = "about:blank";
848
+ frame.scrolling = "no";
849
+ frame.setAttribute(
850
+ "style",
851
+ "border: 0; background-color: none; width: 1px; min-width: 100%;"
852
+ );
853
+ return frame;
854
+ }
855
+ _findFrame() {
856
+ const element = this.container ? this._findElement() : document.body;
857
+ const parent = element.shadowRoot || element;
858
+ return parent.querySelector(
859
+ "iframe#squatchFrame"
860
+ );
861
+ }
862
+ _detachLoadEventListener(frameDoc) {
863
+ if (this.loadEventListener) {
864
+ frameDoc.removeEventListener(
865
+ "sq:user-registration",
866
+ this.loadEventListener
867
+ );
868
+ this.loadEventListener = null;
869
+ }
870
+ }
871
+ _attachLoadEventListener(frameDoc, sqh) {
872
+ if (this.loadEventListener === null) {
873
+ this.loadEventListener = (e) => {
874
+ this._loadEvent({
875
+ ...sqh,
876
+ userId: e.detail.userId,
877
+ accountId: e.detail.accountId
878
+ });
879
+ };
880
+ frameDoc.addEventListener("sq:user-registration", this.loadEventListener);
881
+ }
882
+ }
883
+ _loadEvent(sqh) {
884
+ var _a2;
885
+ if (!sqh) return;
886
+ if (!isObject$1(sqh)) {
887
+ throw new Error("Widget Load event identity property is not an object");
888
+ }
889
+ let params;
890
+ if ("programId" in sqh) {
891
+ if (!sqh.tenantAlias || !sqh.accountId || !sqh.userId || !sqh.engagementMedium)
892
+ throw new Error("Widget Load event missing required properties");
893
+ params = {
894
+ tenantAlias: sqh.tenantAlias,
895
+ externalAccountId: sqh.accountId,
896
+ externalUserId: sqh.userId,
897
+ engagementMedium: sqh.engagementMedium,
898
+ programId: sqh.programId
899
+ };
900
+ } else {
901
+ const { analytics, mode } = sqh;
902
+ params = {
903
+ tenantAlias: analytics.attributes.tenant,
904
+ externalAccountId: analytics.attributes.accountId,
905
+ externalUserId: analytics.attributes.userId,
906
+ engagementMedium: mode.widgetMode
907
+ };
908
+ }
909
+ (_a2 = this.analyticsApi.pushAnalyticsLoadEvent(params)) == null ? void 0 : _a2.then((response) => {
910
+ _log$8(`${params.engagementMedium} loaded event recorded.`);
911
+ }).catch((ex) => {
912
+ _log$8(`ERROR: pushAnalyticsLoadEvent() ${ex}`);
913
+ });
914
+ }
915
+ _shareEvent(sqh, medium) {
916
+ if (sqh) {
917
+ this.analyticsApi.pushAnalyticsShareClickedEvent({
918
+ tenantAlias: sqh.analytics.attributes.tenant,
919
+ externalAccountId: sqh.analytics.attributes.accountId,
920
+ externalUserId: sqh.analytics.attributes.userId,
921
+ engagementMedium: sqh.mode.widgetMode,
922
+ shareMedium: medium
923
+ }).then((response) => {
924
+ _log$8(
925
+ `${sqh.mode.widgetMode} share ${medium} event recorded. ${response}`
926
+ );
927
+ }).catch((ex) => {
928
+ _log$8(`ERROR: pushAnalyticsShareClickedEvent() ${ex}`);
929
+ });
930
+ }
931
+ }
932
+ _error(rs, mode = "modal", style = "") {
933
+ const errorTemplate = `<!DOCTYPE html>
16
934
  <!--[if IE 7]><html class="ie7 oldie" lang="en"><![endif]-->
17
935
  <!--[if IE 8]><html class="ie8 oldie" lang="en"><![endif]-->
18
936
  <!--[if gt IE 8]><!--><html lang="en"><!--<![endif]-->
19
937
  <head>
20
938
  <link rel="stylesheet" media="all" href="https://fast.ssqt.io/assets/css/widget/errorpage.css">
21
939
  <style>
22
- ${e}
940
+ ${style}
23
941
  </style>
24
942
  </head>
25
943
  <body>
26
944
 
27
- <div class="squatch-container ${t}" style="width:100%">
945
+ <div class="squatch-container ${mode}" style="width:100%">
28
946
  <div class="errorheader">
29
947
  <button type="button" class="close" onclick="window.frameElement.squatchJsApi.close();">&times;</button>
30
948
  <p class="errortitle">Error</p>
@@ -37,13 +955,1207 @@
37
955
  <br>
38
956
  <br>
39
957
  <div class="right-align errtxt">
40
- Error Code: ${n}
958
+ Error Code: ${rs}
41
959
  </div>
42
960
  </div>
43
961
  </div>
44
962
  </body>
45
- </html>`}async _findInnerContainer(n){const{contentWindow:t}=n;if(!t)throw new Error("Squatch.js frame inner frame is empty");const e=t.document;function o(){const a=e.getElementsByTagName("sqh-global-container"),d=e.getElementsByClassName("squatch-container");return a.length>0?a[0]:d.length>0?d[0]:null}let r=null;for(let a=0;a<5&&(r=o(),!r);a++)await Oe(100);return r||e.body}reload({email:n,firstName:t,lastName:e},o){const r=this._findFrame();if(!r)throw new Error("Could not find widget iframe");const a=r.contentWindow,d=this.context.engagementMedium||"POPUP";if(!a)throw new Error("Frame needs a content window");let u;if(this.context.type==="upsert"){if(!this.context.user)throw new Error("Can't reload without user ids");let h={email:n||null,firstName:t||null,lastName:e||null,id:this.context.user.id,accountId:this.context.user.accountId};u=this.widgetApi.upsertUser({user:h,engagementMedium:d,widgetType:this.type,jwt:o})}else if(this.context.type==="passwordless")u=this.widgetApi.render({user:void 0,engagementMedium:d,widgetType:this.type,jwt:void 0});else throw new Error("can't reload an error widget");u.then(({template:h})=>{h&&(this.content=h,this.__deprecated__register(r,{email:n,engagementMedium:d},()=>{this.load(),d==="POPUP"&&this.open()}))}).catch(({message:h})=>{C(`${h}`)})}__deprecated__register(n,t,e){const r=n.contentWindow.document,a=r.createElement("button"),d=r.getElementsByClassName("squatch-register")[0];if(d){a.className="btn btn-primary",a.id="show-stats-btn",a.textContent=this.type==="REFERRER_WIDGET"?"Show Stats":"Show Reward";const u=t.engagementMedium==="POPUP"?"margin-top: 10px; max-width: 130px; width: 100%;":"margin-top: 10px;";a.setAttribute("style",u),a.onclick=e,d.style.paddingTop="30px",d.innerHTML=`<p><strong>${t.email}</strong><br>Has been successfully registered</p>`,d.appendChild(a)}}}function Oe(i){return new Promise(n=>{setTimeout(n,i)})}/*!
963
+ </html>`;
964
+ return errorTemplate;
965
+ }
966
+ async _findInnerContainer(frame) {
967
+ const { contentWindow } = frame;
968
+ if (!contentWindow)
969
+ throw new Error("Squatch.js frame inner frame is empty");
970
+ const frameDoc = contentWindow.document;
971
+ function search() {
972
+ const containers = frameDoc.getElementsByTagName("sqh-global-container");
973
+ const legacyContainers = frameDoc.getElementsByClassName("squatch-container");
974
+ const fallback = containers.length > 0 ? containers[0] : legacyContainers.length > 0 ? legacyContainers[0] : null;
975
+ return fallback;
976
+ }
977
+ let found = null;
978
+ for (let i = 0; i < 5; i++) {
979
+ found = search();
980
+ if (found) break;
981
+ await delay(100);
982
+ }
983
+ if (!found) {
984
+ return frameDoc.body;
985
+ }
986
+ return found;
987
+ }
988
+ /**
989
+ * Reloads the current widget, makes updated request to API and renders result.
990
+ * Primarily for Classic widgets with registration
991
+ * @param param0 Form field values
992
+ * @param jwt JWT for API authentication
993
+ */
994
+ reload({ email, firstName, lastName }, jwt) {
995
+ const frame = this._findFrame();
996
+ if (!frame) throw new Error("Could not find widget iframe");
997
+ const frameWindow = frame.contentWindow;
998
+ const engagementMedium = this.context.engagementMedium || "POPUP";
999
+ if (!frameWindow) {
1000
+ throw new Error("Frame needs a content window");
1001
+ }
1002
+ let response;
1003
+ if (this.context.type === "upsert") {
1004
+ if (!this.context.user) throw new Error("Can't reload without user ids");
1005
+ let userObj = {
1006
+ email: email || null,
1007
+ firstName: firstName || null,
1008
+ lastName: lastName || null,
1009
+ id: this.context.user.id,
1010
+ accountId: this.context.user.accountId
1011
+ };
1012
+ response = this.widgetApi.upsertUser({
1013
+ user: userObj,
1014
+ engagementMedium,
1015
+ widgetType: this.type,
1016
+ jwt
1017
+ });
1018
+ } else if (this.context.type === "passwordless") {
1019
+ response = this.widgetApi.render({
1020
+ user: void 0,
1021
+ engagementMedium,
1022
+ widgetType: this.type,
1023
+ jwt: void 0
1024
+ });
1025
+ } else {
1026
+ throw new Error("can't reload an error widget");
1027
+ }
1028
+ response.then(({ template }) => {
1029
+ if (template) {
1030
+ this.content = template;
1031
+ this.__deprecated__register(
1032
+ frame,
1033
+ { email, engagementMedium },
1034
+ () => {
1035
+ this.load();
1036
+ engagementMedium === "POPUP" && this.open();
1037
+ }
1038
+ );
1039
+ }
1040
+ }).catch(({ message }) => {
1041
+ _log$8(`${message}`);
1042
+ });
1043
+ }
1044
+ __deprecated__register(frame, params, onClick) {
1045
+ const frameWindow = frame.contentWindow;
1046
+ const frameDoc = frameWindow.document;
1047
+ const showStatsBtn = frameDoc.createElement("button");
1048
+ const registerForm = frameDoc.getElementsByClassName("squatch-register")[0];
1049
+ if (registerForm) {
1050
+ showStatsBtn.className = "btn btn-primary";
1051
+ showStatsBtn.id = "show-stats-btn";
1052
+ showStatsBtn.textContent = this.type === "REFERRER_WIDGET" ? "Show Stats" : "Show Reward";
1053
+ const widgetStyle = params.engagementMedium === "POPUP" ? "margin-top: 10px; max-width: 130px; width: 100%;" : "margin-top: 10px;";
1054
+ showStatsBtn.setAttribute("style", widgetStyle);
1055
+ showStatsBtn.onclick = onClick;
1056
+ registerForm.style.paddingTop = "30px";
1057
+ registerForm.innerHTML = `<p><strong>${params.email}</strong><br>Has been successfully registered</p>`;
1058
+ registerForm.appendChild(showStatsBtn);
1059
+ }
1060
+ }
1061
+ }
1062
+ function delay(duration) {
1063
+ return new Promise((resolve) => {
1064
+ setTimeout(resolve, duration);
1065
+ });
1066
+ }
1067
+ /*!
46
1068
  * domready (c) Dustin Diaz 2014 - License MIT
47
1069
  *
48
- */function ee(i,n){let t=[],e,o=i,r=o.documentElement.doScroll,a="DOMContentLoaded",d=(r?/^loaded|^c/:/^loaded|^i|^c/).test(o.readyState);return d||o.addEventListener(a,e=()=>{for(o.removeEventListener(a,e),d=!0;e=t.shift();)e()}),d?setTimeout(n,0):t.push(n)}const A=g.debug("squatch-js:EMBEDwidget");class q extends me{constructor(t,e){super(t);p(this,"show",this.open);p(this,"hide",this.close);e&&(this.container=e)}async load(){var a,d;const t=this._createFrame(),e=this._findElement();(a=this.context)!=null&&a.container&&(e.style.visibility="hidden",e.style.height="0",e.style["overflow-y"]="hidden"),this.container?e.shadowRoot?((d=e.shadowRoot.lastChild)==null?void 0:d.nodeName)==="IFRAME"?e.shadowRoot.replaceChild(t,e.shadowRoot.lastChild):e.shadowRoot.appendChild(t):e.firstChild?e.replaceChild(t,e.firstChild):e.appendChild(t):(!e.firstChild||e.firstChild.nodeName==="#text")&&e.appendChild(t);const{contentWindow:o}=t;if(!o)throw new Error("Frame needs a content window");const r=o.document;r.open(),r.write(this.content),r.write(`<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`),r.close(),ee(r,async()=>{const u=o.squatch||o.widgetIdent;t.height=r.body.scrollHeight;const h=new o.ResizeObserver(c=>{for(const l of c){const{height:m}=l.contentRect;t.height=m}}),s=await this._findInnerContainer(t);h.observe(s),this._shouldFireLoadEvent()?(this._loadEvent(u),A("loaded")):r&&this._attachLoadEventListener(r,u)})}open(){const t=this._findFrame();if(!t)return A("no target element to open");if(!t.contentWindow)return A("Frame needs a content window");const e=this._findElement();e.style.visibility="unset",e.style.height="auto",e.style["overflow-y"]="auto",t.contentWindow.document.dispatchEvent(new CustomEvent("sq:refresh"));const o=t.contentWindow.squatch||t.contentWindow.widgetIdent;if(this.context.user)this._loadEvent(o),A("loaded");else{if(!t.contentDocument)return;this._attachLoadEventListener(t.contentDocument,o)}}close(){const t=this._findFrame();if(!t)return A("no target element to close");t.contentDocument&&this._detachLoadEventListener(t.contentDocument);const e=this._findElement();e.style.visibility="hidden",e.style.height="0",e.style["overflow-y"]="hidden",A("Embed widget closed")}_error(t,e="embed",o=""){return super._error(t,e,o)}_shouldFireLoadEvent(){const t=!this.container,e=this.container instanceof HTMLElement&&(this.container.tagName.startsWith("SQUATCH-")||this.container.tagName.startsWith("IMPACT-"));return!!this.context.user&&(t||e)}}const F=g.debug("squatch-js:POPUPwidget");let O=0;class x extends me{constructor(t,e=".squatchpop"){super(t);p(this,"trigger");p(this,"id");p(this,"show",this.open);p(this,"hide",this.close);this.trigger=e,this.container?this.id="squatchModal":(this.id=O===0?"squatchModal":`squatchModal__${O}`,O=O+1),document.head.insertAdjacentHTML("beforeend",`<style>#${this.id}::-webkit-scrollbar { display: none; }</style>`)}_initialiseCTA(){if(!this.trigger)return;let t;try{t=document.querySelector(this.trigger)||document.querySelector(".impactpop"),this.trigger&&!t&&F("No element found with trigger selector",this.trigger)}catch{F("Not a valid selector",this.trigger)}t&&(t.onclick=()=>{this.open()})}_createPopupDialog(){const t=document.createElement("dialog");t.id=this.id,t.setAttribute("style","width: 100%; max-width: 500px; border: none; padding: 0;");const e=o=>{o.stopPropagation(),o.target===t&&t.close()};return t.addEventListener("click",e),t}async load(){var u;const t=this._createFrame();this._initialiseCTA();const e=this.container?this._findElement():document.body,o=e.shadowRoot||e,r=this._createPopupDialog();r.appendChild(t),((u=o.lastChild)==null?void 0:u.nodeName)==="DIALOG"?o.replaceChild(r,o.lastChild):o.appendChild(r);const{contentWindow:a}=t;if(!a)throw new Error("Frame needs a content window");const d=a.document;d.open(),d.write(this.content),d.write(`<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`),d.close(),F("Popup template loaded into iframe"),await this._setupResizeHandler(t)}async _setupResizeHandler(t){const{contentWindow:e}=t;if(!e)throw new Error("Frame needs a content window");const o=e.document;ee(o,async()=>{o.body.style.overflowY="hidden",t.height=`${o.body.offsetHeight}px`,new e.ResizeObserver(a=>{for(const d of a){const{top:u,bottom:h}=d.contentRect,s=h+u;t.height=s+"",d.target.style=""}}).observe(await this._findInnerContainer(t))})}open(){const t=this.container?this._findElement():document.body,o=(t.shadowRoot||t).querySelector(`#${this.id}`);if(!o)throw new Error("Could not determine container div");o.showModal();const r=this._findFrame();if(!r)throw new Error("Could not find iframe");const{contentWindow:a}=r;if(!a)throw new Error("Squatch.js has an empty iframe");const d=a.document;ee(d,()=>{var h;const u=a.squatch||a.widgetIdent;(h=r.contentDocument)==null||h.dispatchEvent(new CustomEvent("sq:refresh")),this.context.user?(this._loadEvent(u),F("Popup opened")):this._attachLoadEventListener(d,u)})}close(){const t=this._findFrame();t!=null&&t.contentDocument&&this._detachLoadEventListener(t.contentDocument);const e=this.container?this._findElement():document.body,r=(e.shadowRoot||e).querySelector(`#${this.id}`);if(!r)throw new Error("Could not determine container div");r.close(),F("Popup closed")}_clickedOutside({target:t}){}_error(t,e="modal",o=""){return super._error(t,e,o||"body { margin: 0; } .modal { box-shadow: none; border: 0; }")}}const E=g.debug("squatch-js:widgets");class R{constructor(n){p(this,"api");p(this,"tenantAlias");p(this,"domain");p(this,"npmCdn");const t=B(n);this.tenantAlias=t.tenantAlias,this.domain=t.domain,this.npmCdn=t.npmCdn,this.api=new z(t)}async upsertUser(n){const e=he(n);try{const o=await this.api.upsertUser(e);return{widget:this._renderWidget(o,e,{type:"upsert",user:e.user,engagementMedium:n.engagementMedium,container:n.container,trigger:n.trigger}),user:o.user}}catch(o){throw E(o),o.apiErrorCode&&this._renderErrorWidget(o,n.engagementMedium),new Error(o)}}async render(n){const e=pe(n);try{const o=await this.api.render(e);return{widget:this._renderWidget(o,e,{type:"passwordless",engagementMedium:e.engagementMedium,container:e.container,trigger:e.trigger}),user:o.user}}catch(o){throw o.apiErrorCode&&this._renderErrorWidget(o,e.engagementMedium),new Error(o)}}async autofill(n){const t=n;if(typeof t=="function"){try{const r=await this.api.squatchReferralCookie();t(r)}catch(r){throw E("Autofill error",r),new Error(r)}return}if(typeof t!="string")throw new Error("Autofill accepts a string or function");let e=document.querySelectorAll(t),o;if(e.length>0)o=e[0];else throw E("Element id/class or function missing"),new Error("Element id/class or function missing");try{const r=await this.api.squatchReferralCookie();o.value=r.codes[0]}catch(r){throw new Error(r)}}_renderWidget(n,t,e){var u;if(E("Rendering Widget..."),!n)throw new Error("Unable to get a response");let o,r=!!t.displayOnLoad;const a=n.jsOptions||{},d={content:n.template,type:t.widgetType||((u=a.widget)==null?void 0:u.defaultWidgetType),api:this.api,domain:this.domain,npmCdn:this.npmCdn,context:e};return a.widgetUrlMappings&&a.widgetUrlMappings.forEach(h=>{var s,c;R._matchesUrl(h.url)&&(h.widgetType!=="CONVERSION_WIDGET"||(c=(s=n.user)==null?void 0:s.referredBy)!=null&&c.code?(r=h.displayOnLoad,E(`Display ${h.widgetType} on ${h.url}`)):E(`Don't display ${h.widgetType} when no referral on widget rule match ${h.url}`))}),a.fuelTankAutofillUrls&&(E("We found a fuel tank autofill!"),a.fuelTankAutofillUrls.forEach(({url:h,formSelector:s})=>{var c,l,m;if(R._matchesUrl(h)&&(E("Fuel Tank URL matches"),(l=(c=n.user)==null?void 0:c.referredBy)!=null&&l.code)){const f=document.querySelector(s);f?f.value=((m=n.user.referredBy.referredReward)==null?void 0:m.fuelTankCode)||"":E(new Error(`Element with id/class ${s} was not found.`))}})),t.engagementMedium==="EMBED"?o=this._renderEmbedWidget(d):(o=this._renderPopupWidget(d),r&&o.open()),o}_renderPopupWidget(n){const t=new x(n,n.context.trigger);return t.load(),t}_renderEmbedWidget(n){const t=new q(n,n.context.container);return t.load(),t}_renderErrorWidget(n,t="POPUP"){const{apiErrorCode:e,rsCode:o,message:r}=n;E(new Error(`${e} (${o}) ${r}`));const a={content:"error",rsCode:o,api:this.api,domain:this.domain,npmCdn:this.npmCdn,type:"ERROR_WIDGET",context:{type:"error"}};let d;t==="EMBED"?(d=new q(a),d.load()):t==="POPUP"&&(d=new x(a),d.load())}static _matchesUrl(n){return!!window.location.href.match(new RegExp(n))}}class Le{constructor(n){p(this,"tenantAlias");p(this,"domain");const e=B(n);this.tenantAlias=e.tenantAlias,this.domain=e.domain}track(n,t){const e=n,o=t,r=De(e),{jwt:a}=je(o),d=encodeURIComponent(this.tenantAlias),u=encodeURIComponent(r.userId),h=encodeURIComponent(r.accountId),s=`/api/v1/${d}/open/account/${h}/user/${u}/events`,c=this.domain+s;return K(c,JSON.stringify(r),a)}}function De(i){if(!_(i))throw new Error("tracking parameter must be an object");if(!(i!=null&&i.accountId))throw new Error("accountId field is required");if(!(i!=null&&i.events))throw new Error("events field is required");if(!(i!=null&&i.userId))throw new Error("userId field is required");const n=i;if(!Array.isArray(n.events))throw new Error("'events' should be an array");return n}function je(i){if(!_(i))throw new Error("'options' should be an object");return i}function Ne(){var o;const i=window[X]?X:W,n=((o=window["_"+i])==null?void 0:o.ready)||[],t=window.impactOnReady||window.squatchOnReady,e=[...n,t].filter(r=>!!r);setTimeout(()=>{window[W]&&(window[X]=window[W],e.forEach(r=>r()),window[W]._auto(),window["_"+i]=void 0,delete window["_"+i])},0)}const v=g.debug("squatch-js"),ce=i=>typeof i=="object"&&!Array.isArray(i),ge=(i,n)=>{const t=o=>ce(n[o])&&i.hasOwnProperty(o)&&ce(i[o]),e=Object.getOwnPropertyNames(n).map(o=>({[o]:t(o)?ge(i[o],n[o]):n[o]})).reduce((o,r)=>({...o,...r}),{});return{...i,...e}};function D(i){const n=atob(i.replace(/_/g,"/").replace(/-/g,"+")),t=new Uint8Array(n.length);for(let e=0;e<n.length;e++)t[e]=n.charCodeAt(e);return new TextDecoder("utf8").decode(t)}function de(i){const n=new TextEncoder().encode(i),t=Array.from(n,e=>String.fromCodePoint(e)).join("");return btoa(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Je(){var i,n,t="weird_get_top_level_domain=cookie",e=document.location.hostname.split(".");for(i=e.length-1;i>=0;i--)if(n=e.slice(i).join("."),document.cookie=t+";domain=."+n+";",document.cookie.indexOf(t)>-1)return document.cookie=t.split("=")[0]+"=;domain=."+n+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",n}function Be(){const i=window.location.search,t=new URLSearchParams(i).get("_saasquatch")||"";if(t){let e="",o="",r="";try{e=JSON.parse(D(t))}catch(a){v("Unable to decode params",a);return}try{o=JSON.parse(D(L.get("_saasquatch"))),v("existing cookie",o)}catch(a){v("Unable to retrieve cookie",a)}try{const a=Je();if(v("domain retrieved:",a),o){const d=ge(o,e);r=de(JSON.stringify(d)),v("cookie to store:",d)}else r=de(JSON.stringify(e)),v("cookie to store:",e);L.set("_saasquatch",r,{expires:365,secure:!1,sameSite:"Lax",domain:a,path:"/"})}catch(a){v("Unable to set cookie",a)}}}const Q=g.debug("squatch-js");function ze(i){const n=window.location.search,e=new URLSearchParams(n).get("_saasquatchExtra")||"";if(!e){Q("No _saasquatchExtra param");return}let o;try{o=JSON.parse(D(e))}catch{Q("Unable to decode _saasquatchExtra config");return}const{domain:r,tenantAlias:a,widgetConfig:d}=He(o);if(!r||!a||!d){Q("_saasquatchExtra did not have an expected structure");return}const{autoPopupWidgetType:u,...h}=d;return{widgetConfig:{widgetType:u,displayOnLoad:!0,...h},squatchConfig:{...i?{configIn:i}:{},domain:r,tenantAlias:a}}}function He(i){var r;const n=Object.keys(i||{})[0],t=Object.keys((i==null?void 0:i[n])||{})[0],e=(r=i==null?void 0:i[n])==null?void 0:r[t];return{domain:n?`https://${n}`:void 0,tenantAlias:t,widgetConfig:e}}const Ge=g.debug("squatch-js:decodeUserJwt");function Ve(i){var n;try{const t=i.split(".")[1];if(t===void 0)return null;const e=D(t);return(n=JSON.parse(e))==null?void 0:n.user}catch(t){return Ge(t),null}}const le=xe("squatch-js:DeclarativeWidget");class we extends HTMLElement{constructor(){super();p(this,"config");p(this,"token");p(this,"tenant");p(this,"widgetType");p(this,"locale");p(this,"widgetApi");p(this,"analyticsApi");p(this,"widgetInstance");p(this,"type");p(this,"container");p(this,"element");p(this,"loaded");p(this,"_setWidget",(t,e)=>{var r;const o={api:this.widgetApi,content:t,context:{type:e.type,user:e.user,container:this.container||void 0,engagementMedium:this.type},type:this.widgetType,domain:((r=this.config)==null?void 0:r.domain)||I,npmCdn:Z,container:this};if(this.type==="EMBED")return new q(o);{const a=this.firstChild?null:void 0;return new x(o,a)}});p(this,"setErrorWidget",t=>{var o;const e={api:this.widgetApi,content:"error",context:{type:"error",container:this.container||void 0},type:"ERROR_WIDGET",domain:((o=this.config)==null?void 0:o.domain)||I,npmCdn:Z,container:this};if(this.type==="EMBED")return new q(e);{const r=this.firstChild?null:void 0;return new x(e,r)}});p(this,"reload",this.renderWidget);p(this,"show",this.open);p(this,"hide",this.close);this.attachShadow({mode:"open"}).innerHTML="<style>:host { display: block; }</style><slot></slot>",this.config=te(),this.token=U(),this.tenant=window.squatchTenant,this.container=this}_setupApis(t){var e,o;if(!this.tenant)throw new Error("tenantAlias not provided");this.widgetApi=new z({tenantAlias:(t==null?void 0:t.tenantAlias)||this.tenant,domain:(t==null?void 0:t.domain)||((e=this.config)==null?void 0:e.domain)||I}),this.analyticsApi=new fe({domain:(t==null?void 0:t.domain)||((o=this.config)==null?void 0:o.domain)||I})}async renderPasswordlessVariant(){return this._setupApis(),le("Rendering as an Instant Access widget"),await this.widgetApi.render({engagementMedium:this.type,widgetType:this.widgetType,locale:this.locale}).then(t=>this._setWidget(t.template,{type:"passwordless"})).catch(this.setErrorWidget)}async renderUserUpsertVariant(){this._setupApis();const t=Ve(this.token);return t?(le("Rendering as a Verified widget"),await this.widgetApi.upsertUser({user:t,locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType,jwt:this.token}).then(o=>this._setWidget(o.template,{type:"upsert",user:t})).catch(this.setErrorWidget)):this.setErrorWidget(Error("No user object in token."))}async getWidgetInstance(){let t;if(this.widgetType=this.getAttribute("widget")||void 0,this.locale=this.getAttribute("locale")||this.locale,!this.widgetType)throw new Error("No widget has been specified");return this.token?t=await this.renderUserUpsertVariant():t=await this.renderPasswordlessVariant(),this.widgetInstance=t,this.widgetInstance&&this.dispatchEvent(new CustomEvent("sq:widget-loaded")),t}async renderWidget(){await this.getWidgetInstance(),await this.widgetInstance.load()}open(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.open()}close(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.close()}}class ne extends we{constructor(){super(),this.type="EMBED",this.loaded=!1}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(n,t,e){if(!(t===e||!this.loaded))switch(n){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){var t,e;this.loaded=!0,this.container=this.getAttribute("container"),await this.renderWidget();const n=(t=this.shadowRoot&&Array.from(this.shadowRoot.children))==null?void 0:t.find(o=>o.tagName==="SLOT");n&&((e=this.shadowRoot)==null||e.removeChild(n)),this.getAttribute("open")!==null&&this.open()}}class oe extends we{constructor(){super(),this.type="POPUP",this.loaded=!1,this.addEventListener("click",n=>{n.stopPropagation(),this.open()})}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(n,t,e){if(!(t===e||!this.loaded))switch(n){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){this.loaded=!0,this.container=this.getAttribute("container"),await this.renderWidget(),this.getAttribute("open")!==null&&this.open()}}class Xe extends ne{}class Qe extends oe{}class Ye extends ne{}class Ze extends oe{}window.customElements.get("squatch-embed")||window.customElements.define("squatch-embed",Xe);window.customElements.get("impact-embed")||window.customElements.define("impact-embed",Ye);window.customElements.get("squatch-popup")||window.customElements.define("squatch-popup",Qe);window.customElements.get("impact-popup")||window.customElements.define("impact-popup",Ze);function Ke(){console.log("Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.")}const k=g.debug("squatch-js");let j=null,N=null,J=null;function et(){return j||S({}),j}function H(){return N||S({}),N}function tt(){return J||S({}),J}function nt(i){var n;return(n=H())==null?void 0:n.render(i)}function ot(i){var t;const n=ze(i);if(n){const{squatchConfig:e,widgetConfig:o}=n;return S(e),(t=H())==null?void 0:t.render(o)}}function S(i){const t=B(i);t.tenantAlias.match("^test")||t.debug?g.debug.enable("squatch-js*"):g.debug.disable(),k("initializing ..."),j=new z(t),N=new R(t),J=new Le(t),k("Widget API instance",j),k("Widgets instance",N),k("Events API instance",J)}function it(i){i()}function rt(i){H().autofill(i)}function ye(){Be()}typeof document<"u"&&!window.SaaSquatchDoNotAutoDrop&&ye();var ue;(ue=window.squatch)!=null&&ue.init&&k("Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics.");typeof document<"u"&&Ne();exports.DeclarativeEmbedWidget=ne;exports.DeclarativePopupWidget=oe;exports.EmbedWidget=q;exports.PopupWidget=x;exports.WidgetApi=z;exports.Widgets=R;exports._auto=ot;exports.api=et;exports.autofill=rt;exports.events=tt;exports.help=Ke;exports.init=S;exports.pushCookie=ye;exports.ready=it;exports.widget=nt;exports.widgets=H;
1070
+ */
1071
+ function domready(targetDoc, fn) {
1072
+ let fns = [];
1073
+ let listener;
1074
+ let doc = targetDoc;
1075
+ let hack = doc.documentElement.doScroll;
1076
+ let domContentLoaded = "DOMContentLoaded";
1077
+ let loaded = (hack ? /^loaded|^c/ : /^loaded|^i|^c/).test(doc.readyState);
1078
+ if (!loaded)
1079
+ doc.addEventListener(
1080
+ domContentLoaded,
1081
+ listener = () => {
1082
+ doc.removeEventListener(domContentLoaded, listener);
1083
+ loaded = true;
1084
+ while (listener = fns.shift()) listener();
1085
+ }
1086
+ );
1087
+ return loaded ? setTimeout(fn, 0) : fns.push(fn);
1088
+ }
1089
+ const _log$7 = browserExports.debug("squatch-js:EMBEDwidget");
1090
+ class EmbedWidget extends Widget {
1091
+ constructor(params, container) {
1092
+ super(params);
1093
+ __publicField(this, "show", this.open);
1094
+ __publicField(this, "hide", this.close);
1095
+ if (container) this.container = container;
1096
+ }
1097
+ async load() {
1098
+ var _a2, _b;
1099
+ const frame = this._createFrame();
1100
+ const element = this._findElement();
1101
+ if ((_a2 = this.context) == null ? void 0 : _a2.container) {
1102
+ element.style.visibility = "hidden";
1103
+ element.style.height = "0";
1104
+ element.style["overflow-y"] = "hidden";
1105
+ }
1106
+ if (this.container) {
1107
+ if (element.shadowRoot) {
1108
+ if (((_b = element.shadowRoot.lastChild) == null ? void 0 : _b.nodeName) === "IFRAME") {
1109
+ element.shadowRoot.replaceChild(frame, element.shadowRoot.lastChild);
1110
+ } else {
1111
+ element.shadowRoot.appendChild(frame);
1112
+ }
1113
+ } else if (element.firstChild) {
1114
+ element.replaceChild(frame, element.firstChild);
1115
+ } else {
1116
+ element.appendChild(frame);
1117
+ }
1118
+ } else if (!element.firstChild || element.firstChild.nodeName === "#text") {
1119
+ element.appendChild(frame);
1120
+ }
1121
+ const { contentWindow } = frame;
1122
+ if (!contentWindow) {
1123
+ throw new Error("Frame needs a content window");
1124
+ }
1125
+ const frameDoc = contentWindow.document;
1126
+ frameDoc.open();
1127
+ frameDoc.write(this.content);
1128
+ frameDoc.write(
1129
+ `<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`
1130
+ );
1131
+ frameDoc.close();
1132
+ domready(frameDoc, async () => {
1133
+ const _sqh = contentWindow.squatch || contentWindow.widgetIdent;
1134
+ frame.height = frameDoc.body.scrollHeight;
1135
+ const ro = new contentWindow["ResizeObserver"]((entries) => {
1136
+ for (const entry of entries) {
1137
+ const { height } = entry.contentRect;
1138
+ frame.height = height;
1139
+ }
1140
+ });
1141
+ const container = await this._findInnerContainer(frame);
1142
+ ro.observe(container);
1143
+ if (this._shouldFireLoadEvent()) {
1144
+ this._loadEvent(_sqh);
1145
+ _log$7("loaded");
1146
+ } else if (frameDoc) {
1147
+ this._attachLoadEventListener(frameDoc, _sqh);
1148
+ }
1149
+ });
1150
+ }
1151
+ /**
1152
+ * Un-hide if element is available and refresh data
1153
+ */
1154
+ open() {
1155
+ const frame = this._findFrame();
1156
+ if (!frame) return _log$7("no target element to open");
1157
+ if (!frame.contentWindow) return _log$7("Frame needs a content window");
1158
+ const element = this._findElement();
1159
+ element.style.visibility = "unset";
1160
+ element.style.height = "auto";
1161
+ element.style["overflow-y"] = "auto";
1162
+ frame.contentWindow.document.dispatchEvent(new CustomEvent("sq:refresh"));
1163
+ const _sqh = frame.contentWindow.squatch || frame.contentWindow.widgetIdent;
1164
+ if (this.context.user) {
1165
+ this._loadEvent(_sqh);
1166
+ _log$7("loaded");
1167
+ } else {
1168
+ if (!frame.contentDocument) return;
1169
+ this._attachLoadEventListener(frame.contentDocument, _sqh);
1170
+ }
1171
+ }
1172
+ close() {
1173
+ const frame = this._findFrame();
1174
+ if (!frame) return _log$7("no target element to close");
1175
+ if (frame.contentDocument)
1176
+ this._detachLoadEventListener(frame.contentDocument);
1177
+ const element = this._findElement();
1178
+ element.style.visibility = "hidden";
1179
+ element.style.height = "0";
1180
+ element.style["overflow-y"] = "hidden";
1181
+ _log$7("Embed widget closed");
1182
+ }
1183
+ _error(rs, mode = "embed", style = "") {
1184
+ return super._error(rs, mode, style);
1185
+ }
1186
+ _shouldFireLoadEvent() {
1187
+ const noContainer = !this.container;
1188
+ const isComponent = this.container instanceof HTMLElement && (this.container.tagName.startsWith("SQUATCH-") || this.container.tagName.startsWith("IMPACT-"));
1189
+ const isVerified = !!this.context.user;
1190
+ return isVerified && (noContainer || isComponent);
1191
+ }
1192
+ }
1193
+ const _log$6 = browserExports.debug("squatch-js:POPUPwidget");
1194
+ let popupId = 0;
1195
+ class PopupWidget extends Widget {
1196
+ constructor(params, trigger = ".squatchpop") {
1197
+ super(params);
1198
+ __publicField(this, "trigger");
1199
+ __publicField(this, "id");
1200
+ __publicField(this, "show", this.open);
1201
+ __publicField(this, "hide", this.close);
1202
+ this.trigger = trigger;
1203
+ if (this.container) {
1204
+ this.id = "squatchModal";
1205
+ } else {
1206
+ this.id = popupId === 0 ? `squatchModal` : `squatchModal__${popupId}`;
1207
+ popupId = popupId + 1;
1208
+ }
1209
+ document.head.insertAdjacentHTML(
1210
+ "beforeend",
1211
+ `<style>#${this.id}::-webkit-scrollbar { display: none; }</style>`
1212
+ );
1213
+ }
1214
+ _initialiseCTA() {
1215
+ if (!this.trigger) return;
1216
+ let triggerElement;
1217
+ try {
1218
+ triggerElement = document.querySelector(this.trigger) || document.querySelector(".impactpop");
1219
+ if (this.trigger && !triggerElement)
1220
+ _log$6("No element found with trigger selector", this.trigger);
1221
+ } catch {
1222
+ _log$6("Not a valid selector", this.trigger);
1223
+ }
1224
+ if (triggerElement) {
1225
+ triggerElement.onclick = () => {
1226
+ this.open();
1227
+ };
1228
+ }
1229
+ }
1230
+ _createPopupDialog() {
1231
+ const dialog = document.createElement("dialog");
1232
+ dialog.id = this.id;
1233
+ dialog.setAttribute(
1234
+ "style",
1235
+ "width: 100%; max-width: 500px; border: none; padding: 0;"
1236
+ );
1237
+ const onClick = (e) => {
1238
+ e.stopPropagation();
1239
+ if (e.target === dialog) dialog.close();
1240
+ };
1241
+ dialog.addEventListener("click", onClick);
1242
+ return dialog;
1243
+ }
1244
+ async load() {
1245
+ var _a2;
1246
+ const frame = this._createFrame();
1247
+ this._initialiseCTA();
1248
+ const element = this.container ? this._findElement() : document.body;
1249
+ const dialogParent = element.shadowRoot || element;
1250
+ const dialog = this._createPopupDialog();
1251
+ dialog.appendChild(frame);
1252
+ if (((_a2 = dialogParent.lastChild) == null ? void 0 : _a2.nodeName) === "DIALOG") {
1253
+ dialogParent.replaceChild(dialog, dialogParent.lastChild);
1254
+ } else {
1255
+ dialogParent.appendChild(dialog);
1256
+ }
1257
+ const { contentWindow } = frame;
1258
+ if (!contentWindow) {
1259
+ throw new Error("Frame needs a content window");
1260
+ }
1261
+ const frameDoc = contentWindow.document;
1262
+ frameDoc.open();
1263
+ frameDoc.write(this.content);
1264
+ frameDoc.write(
1265
+ `<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`
1266
+ );
1267
+ frameDoc.close();
1268
+ _log$6("Popup template loaded into iframe");
1269
+ await this._setupResizeHandler(frame);
1270
+ }
1271
+ async _setupResizeHandler(frame) {
1272
+ const { contentWindow } = frame;
1273
+ if (!contentWindow) {
1274
+ throw new Error("Frame needs a content window");
1275
+ }
1276
+ const frameDoc = contentWindow.document;
1277
+ domready(frameDoc, async () => {
1278
+ frameDoc.body.style.overflowY = "hidden";
1279
+ frame.height = `${frameDoc.body.offsetHeight}px`;
1280
+ const ro = new contentWindow["ResizeObserver"]((entries) => {
1281
+ for (const entry of entries) {
1282
+ const { top, bottom } = entry.contentRect;
1283
+ const computedHeight = bottom + top;
1284
+ frame.height = computedHeight + "";
1285
+ entry.target.style = ``;
1286
+ }
1287
+ });
1288
+ ro.observe(await this._findInnerContainer(frame));
1289
+ });
1290
+ }
1291
+ open() {
1292
+ const element = this.container ? this._findElement() : document.body;
1293
+ const parent = element.shadowRoot || element;
1294
+ const dialog = parent.querySelector(`#${this.id}`);
1295
+ if (!dialog) throw new Error("Could not determine container div");
1296
+ dialog.showModal();
1297
+ const frame = this._findFrame();
1298
+ if (!frame) throw new Error("Could not find iframe");
1299
+ const { contentWindow } = frame;
1300
+ if (!contentWindow) throw new Error("Squatch.js has an empty iframe");
1301
+ const frameDoc = contentWindow.document;
1302
+ domready(frameDoc, () => {
1303
+ var _a2;
1304
+ const _sqh = contentWindow.squatch || contentWindow.widgetIdent;
1305
+ (_a2 = frame.contentDocument) == null ? void 0 : _a2.dispatchEvent(new CustomEvent("sq:refresh"));
1306
+ if (this.context.user) {
1307
+ this._loadEvent(_sqh);
1308
+ _log$6("Popup opened");
1309
+ } else {
1310
+ this._attachLoadEventListener(frameDoc, _sqh);
1311
+ }
1312
+ });
1313
+ }
1314
+ close() {
1315
+ const frame = this._findFrame();
1316
+ if (frame == null ? void 0 : frame.contentDocument)
1317
+ this._detachLoadEventListener(frame.contentDocument);
1318
+ const element = this.container ? this._findElement() : document.body;
1319
+ const parent = element.shadowRoot || element;
1320
+ const dialog = parent.querySelector(`#${this.id}`);
1321
+ if (!dialog) throw new Error("Could not determine container div");
1322
+ dialog.close();
1323
+ _log$6("Popup closed");
1324
+ }
1325
+ _clickedOutside({ target }) {
1326
+ }
1327
+ _error(rs, mode = "modal", style = "") {
1328
+ const _style = "body { margin: 0; } .modal { box-shadow: none; border: 0; }";
1329
+ return super._error(rs, mode, style || _style);
1330
+ }
1331
+ }
1332
+ const _log$5 = browserExports.debug("squatch-js:widgets");
1333
+ class Widgets {
1334
+ /**
1335
+ * Initialize a new {@link Widgets} instance.
1336
+ *
1337
+ * @param {ConfigOptions} config Config details
1338
+ *
1339
+ * @example <caption>Browser example</caption>
1340
+ * var widgets = new squatch.Widgets({tenantAlias:'test_12b5bo1b25125'});
1341
+ *
1342
+ * @example <caption>Browserify/Webpack example</caption>
1343
+ * var Widgets = require('@saasquatch/squatch-js').Widgets;
1344
+ * var widgets = new Widgets({tenantAlias:'test_12b5bo1b25125'});
1345
+ *
1346
+ * @example <caption>Babel+Browserify/Webpack example</caption>
1347
+ * import {Widgets} from '@saasquatch/squatch-js';
1348
+ * let widgets = new Widgets({tenantAlias:'test_12b5bo1b25125'});
1349
+ */
1350
+ constructor(configin) {
1351
+ /**
1352
+ * Instance of {@link WidgetApi}
1353
+ */
1354
+ __publicField(this, "api");
1355
+ /**
1356
+ * Tenant alias of SaaSquatch tenant
1357
+ */
1358
+ __publicField(this, "tenantAlias");
1359
+ /**
1360
+ * SaaSquatch domain for API requests
1361
+ * @default "https://app.referralsaasquatch.com"
1362
+ */
1363
+ __publicField(this, "domain");
1364
+ /**
1365
+ * Hosted CDN for npm packages
1366
+ * @default "https://fast.ssqt.io/npm"
1367
+ */
1368
+ __publicField(this, "npmCdn");
1369
+ const config = validateConfig(configin);
1370
+ this.tenantAlias = config.tenantAlias;
1371
+ this.domain = config.domain;
1372
+ this.npmCdn = config.npmCdn;
1373
+ this.api = new WidgetApi(config);
1374
+ }
1375
+ /**
1376
+ * This function calls the {@link WidgetApi.upsertUser} method, and it renders
1377
+ * the widget if it is successful. Otherwise it shows the "error" widget.
1378
+ *
1379
+ * @param {Object} config Config details
1380
+ * @param {Object} config.user The user details
1381
+ * @param {string} config.user.id The user id
1382
+ * @param {string} config.user.accountId The user account id
1383
+ * @param {WidgetType} config.widgetType The content of the widget
1384
+ * @param {EngagementMedium} config.engagementMedium How to display the widget
1385
+ * @param {string} config.jwt the JSON Web Token (JWT) that is used to validate the data (can be disabled)
1386
+ * @param {HTMLElement | string | undefined} config.container Element to load the widget into
1387
+ * @param {string | undefined} config.trigger Trigger element for opening the popup widget
1388
+ *
1389
+ * @return {Promise<WidgetResult>} json object if true, with a Widget and user details
1390
+ */
1391
+ async upsertUser(config) {
1392
+ const raw = config;
1393
+ const clean = validateWidgetConfig(raw);
1394
+ try {
1395
+ const response = await this.api.upsertUser(clean);
1396
+ return {
1397
+ widget: this._renderWidget(response, clean, {
1398
+ type: "upsert",
1399
+ user: clean.user,
1400
+ engagementMedium: config.engagementMedium,
1401
+ container: config.container,
1402
+ trigger: config.trigger
1403
+ }),
1404
+ user: response.user
1405
+ };
1406
+ } catch (err) {
1407
+ _log$5(err);
1408
+ if (err.apiErrorCode) {
1409
+ this._renderErrorWidget(err, config.engagementMedium);
1410
+ }
1411
+ throw new Error(err);
1412
+ }
1413
+ }
1414
+ /**
1415
+ * This function calls the {@link WidgetApi.render} method, and it renders
1416
+ * the widget if it is successful. Otherwise it shows the "error" widget.
1417
+ *
1418
+ * @param {Object} config Config details
1419
+ * @param {Object} config.user The user details
1420
+ * @param {string} config.user.id The user id
1421
+ * @param {string} config.user.accountId The user account id
1422
+ * @param {WidgetType} config.widgetType The content of the widget
1423
+ * @param {EngagementMedium} config.engagementMedium How to display the widget
1424
+ * @param {string} config.jwt the JSON Web Token (JWT) that is used
1425
+ * to validate the data (can be disabled)
1426
+ *
1427
+ * @return {Promise<WidgetResult>} json object if true, with a Widget and user details
1428
+ */
1429
+ async render(config) {
1430
+ const raw = config;
1431
+ const clean = validatePasswordlessConfig(raw);
1432
+ try {
1433
+ const response = await this.api.render(clean);
1434
+ return {
1435
+ widget: this._renderWidget(response, clean, {
1436
+ type: "passwordless",
1437
+ engagementMedium: clean.engagementMedium,
1438
+ container: clean.container,
1439
+ trigger: clean.trigger
1440
+ }),
1441
+ user: response.user
1442
+ };
1443
+ } catch (err) {
1444
+ if (err.apiErrorCode) {
1445
+ this._renderErrorWidget(err, clean.engagementMedium);
1446
+ }
1447
+ throw new Error(err);
1448
+ }
1449
+ }
1450
+ /**
1451
+ * Autofills a referral code into an element when someone has been referred.
1452
+ * Uses {@link WidgetApi.squatchReferralCookie} behind the scenes.
1453
+ *
1454
+ * @param selector Element class/id selector, or a callback function
1455
+ * @returns
1456
+ */
1457
+ async autofill(selector) {
1458
+ const input = selector;
1459
+ if (typeof input === "function") {
1460
+ try {
1461
+ const response = await this.api.squatchReferralCookie();
1462
+ input(response);
1463
+ } catch (e) {
1464
+ _log$5("Autofill error", e);
1465
+ throw new Error(e);
1466
+ }
1467
+ return;
1468
+ }
1469
+ if (typeof input !== "string")
1470
+ throw new Error("Autofill accepts a string or function");
1471
+ let elems = document.querySelectorAll(input);
1472
+ let elem;
1473
+ if (elems.length > 0) {
1474
+ elem = elems[0];
1475
+ } else {
1476
+ _log$5("Element id/class or function missing");
1477
+ throw new Error("Element id/class or function missing");
1478
+ }
1479
+ try {
1480
+ const response = await this.api.squatchReferralCookie();
1481
+ elem.value = response.codes[0];
1482
+ } catch (e) {
1483
+ throw new Error(e);
1484
+ }
1485
+ }
1486
+ /**
1487
+ * @hidden
1488
+ * @param {Object} response The json object return from the WidgetApi
1489
+ * @param {Object} config Config details
1490
+ * @param {string} config.widgetType The widget type (REFERRER_WIDGET, CONVERSION_WIDGET)
1491
+ * @param {string} config.engagementMedium (POPUP, EMBED)
1492
+ * @returns {Widget} widget (PopupWidget or EmbedWidget)
1493
+ */
1494
+ _renderWidget(response, config, context) {
1495
+ var _a2;
1496
+ _log$5("Rendering Widget...");
1497
+ if (!response) throw new Error("Unable to get a response");
1498
+ let widget2;
1499
+ let displayOnLoad = !!config.displayOnLoad;
1500
+ const opts = response.jsOptions || {};
1501
+ const params = {
1502
+ content: response.template,
1503
+ type: config.widgetType || ((_a2 = opts.widget) == null ? void 0 : _a2.defaultWidgetType),
1504
+ api: this.api,
1505
+ domain: this.domain,
1506
+ npmCdn: this.npmCdn,
1507
+ context
1508
+ };
1509
+ if (opts.widgetUrlMappings) {
1510
+ opts.widgetUrlMappings.forEach((rule) => {
1511
+ var _a3, _b;
1512
+ if (Widgets._matchesUrl(rule.url)) {
1513
+ if (rule.widgetType !== "CONVERSION_WIDGET" || ((_b = (_a3 = response.user) == null ? void 0 : _a3.referredBy) == null ? void 0 : _b.code)) {
1514
+ displayOnLoad = rule.displayOnLoad;
1515
+ _log$5(`Display ${rule.widgetType} on ${rule.url}`);
1516
+ } else {
1517
+ _log$5(
1518
+ `Don't display ${rule.widgetType} when no referral on widget rule match ${rule.url}`
1519
+ );
1520
+ }
1521
+ }
1522
+ });
1523
+ }
1524
+ if (opts.fuelTankAutofillUrls) {
1525
+ _log$5("We found a fuel tank autofill!");
1526
+ opts.fuelTankAutofillUrls.forEach(({ url, formSelector }) => {
1527
+ var _a3, _b, _c;
1528
+ if (Widgets._matchesUrl(url)) {
1529
+ _log$5("Fuel Tank URL matches");
1530
+ if ((_b = (_a3 = response.user) == null ? void 0 : _a3.referredBy) == null ? void 0 : _b.code) {
1531
+ const formAutofill = document.querySelector(formSelector);
1532
+ if (formAutofill) {
1533
+ formAutofill.value = ((_c = response.user.referredBy.referredReward) == null ? void 0 : _c.fuelTankCode) || "";
1534
+ } else {
1535
+ _log$5(
1536
+ new Error(
1537
+ `Element with id/class ${formSelector} was not found.`
1538
+ )
1539
+ );
1540
+ }
1541
+ }
1542
+ }
1543
+ });
1544
+ }
1545
+ if (config.engagementMedium === "EMBED") {
1546
+ widget2 = this._renderEmbedWidget(params);
1547
+ } else {
1548
+ widget2 = this._renderPopupWidget(params);
1549
+ if (displayOnLoad) widget2.open();
1550
+ }
1551
+ return widget2;
1552
+ }
1553
+ _renderPopupWidget(params) {
1554
+ const widget2 = new PopupWidget(params, params.context.trigger);
1555
+ widget2.load();
1556
+ return widget2;
1557
+ }
1558
+ _renderEmbedWidget(params) {
1559
+ const widget2 = new EmbedWidget(params, params.context.container);
1560
+ widget2.load();
1561
+ return widget2;
1562
+ }
1563
+ /**
1564
+ * @hidden
1565
+ * @param {Object} error The json object containing the error details
1566
+ * @param {string} em The engagementMedium
1567
+ * @returns {void}
1568
+ */
1569
+ _renderErrorWidget(props, em = "POPUP") {
1570
+ const { apiErrorCode, rsCode, message } = props;
1571
+ _log$5(new Error(`${apiErrorCode} (${rsCode}) ${message}`));
1572
+ const params = {
1573
+ content: "error",
1574
+ rsCode,
1575
+ api: this.api,
1576
+ domain: this.domain,
1577
+ npmCdn: this.npmCdn,
1578
+ type: "ERROR_WIDGET",
1579
+ context: { type: "error" }
1580
+ };
1581
+ let widget2;
1582
+ if (em === "EMBED") {
1583
+ widget2 = new EmbedWidget(params);
1584
+ widget2.load();
1585
+ } else if (em === "POPUP") {
1586
+ widget2 = new PopupWidget(params);
1587
+ widget2.load();
1588
+ }
1589
+ }
1590
+ /**
1591
+ * @hidden
1592
+ * @param {string} rule A regular expression
1593
+ * @returns {boolean} true if rule matches Url, false otherwise
1594
+ */
1595
+ static _matchesUrl(rule) {
1596
+ return window.location.href.match(new RegExp(rule)) ? true : false;
1597
+ }
1598
+ }
1599
+ class EventsApi {
1600
+ /**
1601
+ * Initialize a new {@link EventsApi} instance.
1602
+ *
1603
+ * @param {ConfigOptions} config Config details
1604
+ *
1605
+ * @example <caption>Browser example</caption>
1606
+ * var squatchApi = new squatch.EventsApi({tenantAlias:'test_12b5bo1b25125'});
1607
+ *
1608
+ * @example <caption>Browserify/Webpack example</caption>
1609
+ * var EventsApi = require('@saasquatch/squatch-js').EventsApi;
1610
+ * var squatchApi = new EventsApi({tenantAlias:'test_12b5bo1b25125'});
1611
+ *
1612
+ * @example <caption>Babel+Browserify/Webpack example</caption>
1613
+ * import {EventsApi} from '@saasquatch/squatch-js';
1614
+ * let squatchApi = new EventsApi({tenantAlias:'test_12b5bo1b25125'});
1615
+ */
1616
+ constructor(config) {
1617
+ __publicField(this, "tenantAlias");
1618
+ __publicField(this, "domain");
1619
+ const raw = config;
1620
+ const clean = validateConfig(raw);
1621
+ this.tenantAlias = clean.tenantAlias;
1622
+ this.domain = clean.domain;
1623
+ }
1624
+ /**
1625
+ * Track an event for a user
1626
+ *
1627
+ * @param params Parameters for request
1628
+ * @param options.jwt the JSON Web Token (JWT) that is used to authenticate the user
1629
+ *
1630
+ * @return An ID to confirm the event has been accepted for asynchronous processing
1631
+ */
1632
+ track(params, options) {
1633
+ const raw = params;
1634
+ const rawOpts = options;
1635
+ const body = _validateEvent(raw);
1636
+ const { jwt } = _validateTrackOptions(rawOpts);
1637
+ const ta = encodeURIComponent(this.tenantAlias);
1638
+ const userId = encodeURIComponent(body.userId);
1639
+ const accountId = encodeURIComponent(body.accountId);
1640
+ const path = `/api/v1/${ta}/open/account/${accountId}/user/${userId}/events`;
1641
+ const url = this.domain + path;
1642
+ return doPost(url, JSON.stringify(body), jwt);
1643
+ }
1644
+ }
1645
+ function _validateEvent(raw) {
1646
+ if (!isObject$1(raw)) throw new Error("tracking parameter must be an object");
1647
+ if (!(raw == null ? void 0 : raw["accountId"])) throw new Error("accountId field is required");
1648
+ if (!(raw == null ? void 0 : raw["events"])) throw new Error("events field is required");
1649
+ if (!(raw == null ? void 0 : raw["userId"])) throw new Error("userId field is required");
1650
+ const clean = raw;
1651
+ if (!Array.isArray(clean.events))
1652
+ throw new Error("'events' should be an array");
1653
+ return clean;
1654
+ }
1655
+ function _validateTrackOptions(raw) {
1656
+ if (!isObject$1(raw)) throw new Error("'options' should be an object");
1657
+ return raw;
1658
+ }
1659
+ function asyncLoad() {
1660
+ var _a2;
1661
+ const namespace = window[IMPACT_NAMESPACE] ? IMPACT_NAMESPACE : DEFAULT_NAMESPACE;
1662
+ const cached = ((_a2 = window["_" + namespace]) == null ? void 0 : _a2.ready) || [];
1663
+ const declarativeCache = window.impactOnReady || window.squatchOnReady;
1664
+ const readyFns = [...cached, declarativeCache].filter((a) => !!a);
1665
+ setTimeout(() => {
1666
+ if (!window[DEFAULT_NAMESPACE]) return;
1667
+ window[IMPACT_NAMESPACE] = window[DEFAULT_NAMESPACE];
1668
+ readyFns.forEach((cb) => cb());
1669
+ window[DEFAULT_NAMESPACE]._auto();
1670
+ window["_" + namespace] = void 0;
1671
+ delete window["_" + namespace];
1672
+ }, 0);
1673
+ }
1674
+ const _log$4 = browserExports.debug("squatch-js");
1675
+ const isObject = (item) => typeof item === "object" && !Array.isArray(item);
1676
+ const deepMerge = (target, source) => {
1677
+ const isDeep = (prop) => isObject(source[prop]) && target.hasOwnProperty(prop) && isObject(target[prop]);
1678
+ const replaced = Object.getOwnPropertyNames(source).map((prop) => ({
1679
+ [prop]: isDeep(prop) ? deepMerge(target[prop], source[prop]) : source[prop]
1680
+ })).reduce((a, b) => ({ ...a, ...b }), {});
1681
+ return {
1682
+ ...target,
1683
+ ...replaced
1684
+ };
1685
+ };
1686
+ function b64decode(input) {
1687
+ const binary = atob(input.replace(/_/g, "/").replace(/-/g, "+"));
1688
+ const bytes = new Uint8Array(binary.length);
1689
+ for (let i = 0; i < binary.length; i++) {
1690
+ bytes[i] = binary.charCodeAt(i);
1691
+ }
1692
+ return new TextDecoder("utf8").decode(bytes);
1693
+ }
1694
+ function b64encode(input) {
1695
+ const encodedInput = new TextEncoder().encode(input);
1696
+ const binary = Array.from(
1697
+ encodedInput,
1698
+ (byte) => String.fromCodePoint(byte)
1699
+ ).join("");
1700
+ return btoa(binary).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
1701
+ }
1702
+ function getTopDomain() {
1703
+ var i, h, weird_cookie = "weird_get_top_level_domain=cookie", hostname = document.location.hostname.split(".");
1704
+ for (i = hostname.length - 1; i >= 0; i--) {
1705
+ h = hostname.slice(i).join(".");
1706
+ document.cookie = weird_cookie + ";domain=." + h + ";";
1707
+ if (document.cookie.indexOf(weird_cookie) > -1) {
1708
+ document.cookie = weird_cookie.split("=")[0] + "=;domain=." + h + ";expires=Thu, 01 Jan 1970 00:00:01 GMT;";
1709
+ return h;
1710
+ }
1711
+ }
1712
+ }
1713
+ function _pushCookie() {
1714
+ const queryString = window.location.search;
1715
+ const urlParams = new URLSearchParams(queryString);
1716
+ const refParam = urlParams.get("_saasquatch") || "";
1717
+ if (refParam) {
1718
+ let paramsJSON = "", existingCookie = "", reEncodedCookie = "";
1719
+ try {
1720
+ paramsJSON = JSON.parse(b64decode(refParam));
1721
+ } catch (error) {
1722
+ _log$4("Unable to decode params", error);
1723
+ return;
1724
+ }
1725
+ try {
1726
+ existingCookie = JSON.parse(b64decode(api$1.get("_saasquatch")));
1727
+ _log$4("existing cookie", existingCookie);
1728
+ } catch (error) {
1729
+ _log$4("Unable to retrieve cookie", error);
1730
+ }
1731
+ try {
1732
+ const domain = getTopDomain();
1733
+ _log$4("domain retrieved:", domain);
1734
+ if (existingCookie) {
1735
+ const newCookie = deepMerge(existingCookie, paramsJSON);
1736
+ reEncodedCookie = b64encode(JSON.stringify(newCookie));
1737
+ _log$4("cookie to store:", newCookie);
1738
+ } else {
1739
+ reEncodedCookie = b64encode(JSON.stringify(paramsJSON));
1740
+ _log$4("cookie to store:", paramsJSON);
1741
+ }
1742
+ api$1.set("_saasquatch", reEncodedCookie, {
1743
+ expires: 365,
1744
+ secure: false,
1745
+ sameSite: "Lax",
1746
+ domain,
1747
+ path: "/"
1748
+ });
1749
+ } catch (error) {
1750
+ _log$4("Unable to set cookie", error);
1751
+ }
1752
+ }
1753
+ }
1754
+ const _log$3 = browserExports.debug("squatch-js");
1755
+ function _getAutoConfig(configIn) {
1756
+ const queryString = window.location.search;
1757
+ const urlParams = new URLSearchParams(queryString);
1758
+ const refParam = urlParams.get("_saasquatchExtra") || "";
1759
+ if (!refParam) {
1760
+ _log$3("No _saasquatchExtra param");
1761
+ return;
1762
+ }
1763
+ let raw;
1764
+ try {
1765
+ raw = JSON.parse(b64decode(refParam));
1766
+ } catch (e) {
1767
+ _log$3("Unable to decode _saasquatchExtra config");
1768
+ return;
1769
+ }
1770
+ const { domain, tenantAlias, widgetConfig } = convertExtraToConfig(raw);
1771
+ if (!domain || !tenantAlias || !widgetConfig) {
1772
+ _log$3("_saasquatchExtra did not have an expected structure");
1773
+ return void 0;
1774
+ }
1775
+ const { autoPopupWidgetType, ...rest } = widgetConfig;
1776
+ return {
1777
+ widgetConfig: {
1778
+ widgetType: autoPopupWidgetType,
1779
+ displayOnLoad: true,
1780
+ ...rest
1781
+ },
1782
+ squatchConfig: {
1783
+ ...configIn ? { configIn } : {},
1784
+ domain,
1785
+ tenantAlias
1786
+ }
1787
+ };
1788
+ }
1789
+ function convertExtraToConfig(obj) {
1790
+ var _a2;
1791
+ const _domain = Object.keys(obj || {})[0];
1792
+ const tenantAlias = Object.keys((obj == null ? void 0 : obj[_domain]) || {})[0];
1793
+ const widgetConfig = (_a2 = obj == null ? void 0 : obj[_domain]) == null ? void 0 : _a2[tenantAlias];
1794
+ const domain = _domain ? `https://${_domain}` : void 0;
1795
+ return { domain, tenantAlias, widgetConfig };
1796
+ }
1797
+ const _log$2 = browserExports.debug("squatch-js:decodeUserJwt");
1798
+ function decodeUserJwt(tokenStr) {
1799
+ var _a2;
1800
+ try {
1801
+ const base64Url = tokenStr.split(".")[1];
1802
+ if (base64Url === void 0) return null;
1803
+ const jsonStr = b64decode(base64Url);
1804
+ return (_a2 = JSON.parse(jsonStr)) == null ? void 0 : _a2.user;
1805
+ } catch (e) {
1806
+ _log$2(e);
1807
+ return null;
1808
+ }
1809
+ }
1810
+ const _log$1 = debug("squatch-js:DeclarativeWidget");
1811
+ class DeclarativeWidget extends HTMLElement {
1812
+ constructor() {
1813
+ super();
1814
+ /**
1815
+ * Configuration overrides
1816
+ * @default window.squatchConfig
1817
+ */
1818
+ __publicField(this, "config");
1819
+ /**
1820
+ * Signed JWT containing user information
1821
+ * @default window.squatchToken
1822
+ */
1823
+ __publicField(this, "token");
1824
+ /**
1825
+ * Tenant alias of SaaSquatch tenant
1826
+ * @default window.squatchTenant
1827
+ */
1828
+ __publicField(this, "tenant");
1829
+ /**
1830
+ * widgetType of widget to load
1831
+ */
1832
+ __publicField(this, "widgetType");
1833
+ /**
1834
+ * Locale to render the widget in
1835
+ */
1836
+ __publicField(this, "locale");
1837
+ /**
1838
+ * Instance of {@link WidgetApi}
1839
+ */
1840
+ __publicField(this, "widgetApi");
1841
+ /**
1842
+ * Instance of {@link AnalyticsApi}
1843
+ */
1844
+ __publicField(this, "analyticsApi");
1845
+ /**
1846
+ * Instance of {@link EmbedWidget} or {@link PopupWidget}
1847
+ */
1848
+ __publicField(this, "widgetInstance");
1849
+ /**
1850
+ * Determines whether to render the widget as an embedding widget or popup widget
1851
+ */
1852
+ __publicField(this, "type");
1853
+ /**
1854
+ * Container element to contain the widget iframe
1855
+ * @default this
1856
+ */
1857
+ __publicField(this, "container");
1858
+ __publicField(this, "element");
1859
+ /**
1860
+ * Flag for if the component has been loaded or not
1861
+ * @hidden
1862
+ */
1863
+ __publicField(this, "loaded");
1864
+ __publicField(this, "_setWidget", (template, config) => {
1865
+ var _a2;
1866
+ const params = {
1867
+ api: this.widgetApi,
1868
+ content: template,
1869
+ context: {
1870
+ type: config.type,
1871
+ user: config.user,
1872
+ container: this.container || void 0,
1873
+ engagementMedium: this.type
1874
+ },
1875
+ type: this.widgetType,
1876
+ domain: ((_a2 = this.config) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN,
1877
+ npmCdn: DEFAULT_NPM_CDN,
1878
+ container: this
1879
+ };
1880
+ if (this.type === "EMBED") {
1881
+ return new EmbedWidget(params);
1882
+ } else {
1883
+ const useFirstChildTrigger = this.firstChild ? null : void 0;
1884
+ return new PopupWidget(params, useFirstChildTrigger);
1885
+ }
1886
+ });
1887
+ /**
1888
+ * Builds a Widget instance for the default error widget
1889
+ * @returns Instance of either {@link EmbedWidget} or {@link PopupWidget} depending on `this.type`
1890
+ */
1891
+ __publicField(this, "setErrorWidget", (e) => {
1892
+ var _a2;
1893
+ const params = {
1894
+ api: this.widgetApi,
1895
+ content: "error",
1896
+ context: {
1897
+ type: "error",
1898
+ container: this.container || void 0
1899
+ },
1900
+ type: "ERROR_WIDGET",
1901
+ domain: ((_a2 = this.config) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN,
1902
+ npmCdn: DEFAULT_NPM_CDN,
1903
+ container: this
1904
+ };
1905
+ if (this.type === "EMBED") {
1906
+ return new EmbedWidget(params);
1907
+ } else {
1908
+ const useFirstChildTrigger = this.firstChild ? null : void 0;
1909
+ return new PopupWidget(params, useFirstChildTrigger);
1910
+ }
1911
+ });
1912
+ __publicField(this, "reload", this.renderWidget);
1913
+ __publicField(this, "show", this.open);
1914
+ __publicField(this, "hide", this.close);
1915
+ this.attachShadow({
1916
+ mode: "open"
1917
+ }).innerHTML = `<style>:host { display: block; }</style><slot></slot>`;
1918
+ this.config = getConfig();
1919
+ this.token = getToken();
1920
+ this.tenant = window.squatchTenant;
1921
+ this.container = this;
1922
+ }
1923
+ _setupApis(config) {
1924
+ var _a2, _b;
1925
+ if (!this.tenant) throw new Error("tenantAlias not provided");
1926
+ this.widgetApi = new WidgetApi({
1927
+ tenantAlias: (config == null ? void 0 : config.tenantAlias) || this.tenant,
1928
+ domain: (config == null ? void 0 : config.domain) || ((_a2 = this.config) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN
1929
+ });
1930
+ this.analyticsApi = new AnalyticsApi({
1931
+ domain: (config == null ? void 0 : config.domain) || ((_b = this.config) == null ? void 0 : _b.domain) || DEFAULT_DOMAIN
1932
+ });
1933
+ }
1934
+ async renderPasswordlessVariant() {
1935
+ this._setupApis();
1936
+ _log$1("Rendering as an Instant Access widget");
1937
+ return await this.widgetApi.render({
1938
+ engagementMedium: this.type,
1939
+ widgetType: this.widgetType,
1940
+ locale: this.locale
1941
+ }).then((res) => this._setWidget(res.template, { type: "passwordless" })).catch(this.setErrorWidget);
1942
+ }
1943
+ async renderUserUpsertVariant() {
1944
+ this._setupApis();
1945
+ const userObj = decodeUserJwt(this.token);
1946
+ if (!userObj) {
1947
+ return this.setErrorWidget(Error("No user object in token."));
1948
+ }
1949
+ _log$1("Rendering as a Verified widget");
1950
+ const widgetInstance = await this.widgetApi.upsertUser({
1951
+ user: userObj,
1952
+ locale: this.locale,
1953
+ engagementMedium: this.type,
1954
+ widgetType: this.widgetType,
1955
+ jwt: this.token
1956
+ }).then(
1957
+ (res) => this._setWidget(res.template, { type: "upsert", user: userObj })
1958
+ ).catch(this.setErrorWidget);
1959
+ return widgetInstance;
1960
+ }
1961
+ /**
1962
+ * Fetches widget content from SaaSquatch and builds a Widget instance to support rendering the widget in the DOM
1963
+ * @returns Instance of either {@link EmbedWidget} or {@link PopupWidget} depending on `this.type`
1964
+ * @throws Throws an Error if `widgetType` is undefined
1965
+ */
1966
+ async getWidgetInstance() {
1967
+ let widgetInstance;
1968
+ this.widgetType = this.getAttribute("widget") || void 0;
1969
+ this.locale = this.getAttribute("locale") || this.locale;
1970
+ if (!this.widgetType) throw new Error("No widget has been specified");
1971
+ if (!this.token) {
1972
+ widgetInstance = await this.renderPasswordlessVariant();
1973
+ } else {
1974
+ widgetInstance = await this.renderUserUpsertVariant();
1975
+ }
1976
+ this.widgetInstance = widgetInstance;
1977
+ if (this.widgetInstance)
1978
+ this.dispatchEvent(new CustomEvent("sq:widget-loaded"));
1979
+ return widgetInstance;
1980
+ }
1981
+ /**
1982
+ * Calls {@link getWidgetInstance} to build the Widget instance and loads the widget iframe into the DOM
1983
+ */
1984
+ async renderWidget() {
1985
+ await this.getWidgetInstance();
1986
+ await this.widgetInstance.load();
1987
+ }
1988
+ /**
1989
+ * Calls `open` method of `widgetInstance`
1990
+ * @throws Throws an Error if called before the widget has loaded
1991
+ */
1992
+ open() {
1993
+ if (!this.widgetInstance) throw new Error("Widget has not loaded yet");
1994
+ this.widgetInstance.open();
1995
+ }
1996
+ /**
1997
+ * Calls `close` method of `widgetInstance`
1998
+ * @throws Throws an Error if called before the widget has loaded
1999
+ */
2000
+ close() {
2001
+ if (!this.widgetInstance) throw new Error("Widget has not loaded yet");
2002
+ this.widgetInstance.close();
2003
+ }
2004
+ }
2005
+ class DeclarativeEmbedWidget extends DeclarativeWidget {
2006
+ constructor() {
2007
+ super();
2008
+ this.type = "EMBED";
2009
+ this.loaded = false;
2010
+ }
2011
+ static get observedAttributes() {
2012
+ return ["widget", "locale"];
2013
+ }
2014
+ attributeChangedCallback(attr, oldVal, newVal) {
2015
+ if (oldVal === newVal || !this.loaded) return;
2016
+ switch (attr) {
2017
+ case "locale":
2018
+ case "widget":
2019
+ this.connectedCallback();
2020
+ break;
2021
+ }
2022
+ }
2023
+ async connectedCallback() {
2024
+ var _a2, _b;
2025
+ this.loaded = true;
2026
+ this.container = this.getAttribute("container");
2027
+ await this.renderWidget();
2028
+ const slot = (_a2 = this.shadowRoot && Array.from(this.shadowRoot.children)) == null ? void 0 : _a2.find((c) => c.tagName === "SLOT");
2029
+ if (slot) (_b = this.shadowRoot) == null ? void 0 : _b.removeChild(slot);
2030
+ if (this.getAttribute("open") !== null) this.open();
2031
+ }
2032
+ }
2033
+ class DeclarativePopupWidget extends DeclarativeWidget {
2034
+ constructor() {
2035
+ super();
2036
+ this.type = "POPUP";
2037
+ this.loaded = false;
2038
+ this.addEventListener("click", (e) => {
2039
+ e.stopPropagation();
2040
+ this.open();
2041
+ });
2042
+ }
2043
+ static get observedAttributes() {
2044
+ return ["widget", "locale"];
2045
+ }
2046
+ attributeChangedCallback(attr, oldVal, newVal) {
2047
+ if (oldVal === newVal || !this.loaded) return;
2048
+ switch (attr) {
2049
+ case "locale":
2050
+ case "widget":
2051
+ this.connectedCallback();
2052
+ break;
2053
+ }
2054
+ }
2055
+ async connectedCallback() {
2056
+ this.loaded = true;
2057
+ this.container = this.getAttribute("container");
2058
+ await this.renderWidget();
2059
+ if (this.getAttribute("open") !== null) this.open();
2060
+ }
2061
+ }
2062
+ class SquatchEmbed extends DeclarativeEmbedWidget {
2063
+ }
2064
+ class SquatchPopup extends DeclarativePopupWidget {
2065
+ }
2066
+ class ImpactEmbed extends DeclarativeEmbedWidget {
2067
+ }
2068
+ class ImpactPopup extends DeclarativePopupWidget {
2069
+ }
2070
+ if (!window.customElements.get("squatch-embed"))
2071
+ window.customElements.define("squatch-embed", SquatchEmbed);
2072
+ if (!window.customElements.get("impact-embed"))
2073
+ window.customElements.define("impact-embed", ImpactEmbed);
2074
+ if (!window.customElements.get("squatch-popup"))
2075
+ window.customElements.define("squatch-popup", SquatchPopup);
2076
+ if (!window.customElements.get("impact-popup"))
2077
+ window.customElements.define("impact-popup", ImpactPopup);
2078
+ function help() {
2079
+ console.log(
2080
+ `Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.`
2081
+ );
2082
+ }
2083
+ const _log = browserExports.debug("squatch-js");
2084
+ let _api = null;
2085
+ let _widgets = null;
2086
+ let _events = null;
2087
+ function api() {
2088
+ if (!_api) init({});
2089
+ return _api;
2090
+ }
2091
+ function widgets() {
2092
+ if (!_widgets) init({});
2093
+ return _widgets;
2094
+ }
2095
+ function events() {
2096
+ if (!_events) init({});
2097
+ return _events;
2098
+ }
2099
+ function widget(widgetConfig) {
2100
+ var _a2;
2101
+ return (_a2 = widgets()) == null ? void 0 : _a2.render(widgetConfig);
2102
+ }
2103
+ function _auto(configIn) {
2104
+ var _a2;
2105
+ const configs = _getAutoConfig(configIn);
2106
+ if (configs) {
2107
+ const { squatchConfig, widgetConfig } = configs;
2108
+ init(squatchConfig);
2109
+ return (_a2 = widgets()) == null ? void 0 : _a2.render(widgetConfig);
2110
+ }
2111
+ }
2112
+ function init(configIn) {
2113
+ const raw = configIn;
2114
+ const config = validateConfig(raw);
2115
+ if (config.tenantAlias.match("^test") || config.debug) {
2116
+ browserExports.debug.enable("squatch-js*");
2117
+ } else {
2118
+ browserExports.debug.disable();
2119
+ }
2120
+ _log("initializing ...");
2121
+ _api = new WidgetApi(config);
2122
+ _widgets = new Widgets(config);
2123
+ _events = new EventsApi(config);
2124
+ _log("Widget API instance", _api);
2125
+ _log("Widgets instance", _widgets);
2126
+ _log("Events API instance", _events);
2127
+ }
2128
+ function ready(fn) {
2129
+ fn();
2130
+ }
2131
+ function autofill(selector) {
2132
+ widgets().autofill(selector);
2133
+ }
2134
+ function pushCookie() {
2135
+ _pushCookie();
2136
+ }
2137
+ if (typeof document !== "undefined" && !window.SaaSquatchDoNotAutoDrop) {
2138
+ pushCookie();
2139
+ }
2140
+ if ((_a = window["squatch"]) == null ? void 0 : _a.init)
2141
+ _log(
2142
+ "Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics."
2143
+ );
2144
+ if (typeof document !== "undefined") asyncLoad();
2145
+ exports.DeclarativeEmbedWidget = DeclarativeEmbedWidget;
2146
+ exports.DeclarativePopupWidget = DeclarativePopupWidget;
2147
+ exports.EmbedWidget = EmbedWidget;
2148
+ exports.PopupWidget = PopupWidget;
2149
+ exports.WidgetApi = WidgetApi;
2150
+ exports.Widgets = Widgets;
2151
+ exports._auto = _auto;
2152
+ exports.api = api;
2153
+ exports.autofill = autofill;
2154
+ exports.events = events;
2155
+ exports.help = help;
2156
+ exports.init = init;
2157
+ exports.pushCookie = pushCookie;
2158
+ exports.ready = ready;
2159
+ exports.widget = widget;
2160
+ exports.widgets = widgets;
49
2161
  //# sourceMappingURL=squatch.cjs.js.map