@saasquatch/squatch-js 2.8.2-9 → 2.8.3-0

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