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