@saasquatch/squatch-js 2.6.3-3 → 2.7.0-1

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