saasco-sdk 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js ADDED
@@ -0,0 +1,989 @@
1
+ import { v4 } from '@lukeed/uuid';
2
+ import { z } from 'zod';
3
+
4
+ const timezones = {
5
+ 'Asia/Barnaul': 'RU',
6
+ 'Africa/Nouakchott': 'MR',
7
+ 'Africa/Lusaka': 'ZM',
8
+ 'Asia/Pyongyang': 'KP',
9
+ 'Europe/Bratislava': 'SK',
10
+ 'America/Belize': 'BZ',
11
+ 'America/Maceio': 'BR',
12
+ 'Pacific/Chuuk': 'FM',
13
+ 'Indian/Comoro': 'KM',
14
+ 'Pacific/Palau': 'PW',
15
+ 'Asia/Jakarta': 'ID',
16
+ 'Africa/Windhoek': 'NA',
17
+ 'America/Chihuahua': 'MX',
18
+ 'America/Nome': 'US',
19
+ 'Africa/Mbabane': 'SZ',
20
+ 'Africa/Porto-Novo': 'BJ',
21
+ 'Europe/San_Marino': 'SM',
22
+ 'Pacific/Fakaofo': 'TK',
23
+ 'America/Denver': 'US',
24
+ 'Europe/Belgrade': 'RS',
25
+ 'America/Indiana/Tell_City': 'US',
26
+ 'America/Fortaleza': 'BR',
27
+ 'America/Halifax': 'CA',
28
+ 'Europe/Bucharest': 'RO',
29
+ 'America/Indiana/Petersburg': 'US',
30
+ 'Europe/Kirov': 'RU',
31
+ 'Europe/Athens': 'GR',
32
+ 'America/Argentina/Ushuaia': 'AR',
33
+ 'Europe/Monaco': 'MC',
34
+ 'Europe/Vilnius': 'LT',
35
+ 'Europe/Copenhagen': 'DK',
36
+ 'Pacific/Kanton': 'KI',
37
+ 'America/Caracas': 'VE',
38
+ 'Asia/Almaty': 'KZ',
39
+ 'Europe/Paris': 'FR',
40
+ 'Africa/Blantyre': 'MW',
41
+ 'Asia/Muscat': 'OM',
42
+ 'America/North_Dakota/Beulah': 'US',
43
+ 'America/Matamoros': 'MX',
44
+ 'Asia/Irkutsk': 'RU',
45
+ 'America/Costa_Rica': 'CR',
46
+ 'America/Araguaina': 'BR',
47
+ 'Atlantic/Canary': 'ES',
48
+ 'America/Santo_Domingo': 'DO',
49
+ 'America/Vancouver': 'CA',
50
+ 'Africa/Addis_Ababa': 'ET',
51
+ 'Africa/Accra': 'GH',
52
+ 'Pacific/Kwajalein': 'MH',
53
+ 'Asia/Baghdad': 'IQ',
54
+ 'Australia/Adelaide': 'AU',
55
+ 'Australia/Hobart': 'AU',
56
+ 'America/Guayaquil': 'EC',
57
+ 'America/Argentina/Tucuman': 'AR',
58
+ 'Australia/Lindeman': 'AU',
59
+ 'America/New_York': 'US',
60
+ 'Pacific/Fiji': 'FJ',
61
+ 'America/Antigua': 'AG',
62
+ 'Africa/Casablanca': 'MA',
63
+ 'America/Paramaribo': 'SR',
64
+ 'Africa/Cairo': 'EG',
65
+ 'America/Cayenne': 'GF',
66
+ 'America/Detroit': 'US',
67
+ 'Antarctica/Syowa': 'AQ',
68
+ 'Africa/Douala': 'CM',
69
+ 'America/Argentina/La_Rioja': 'AR',
70
+ 'Africa/Lagos': 'NG',
71
+ 'America/St_Barthelemy': 'BL',
72
+ 'Asia/Nicosia': 'CY',
73
+ 'Asia/Macau': 'MO',
74
+ 'Europe/Riga': 'LV',
75
+ 'Asia/Ashgabat': 'TM',
76
+ 'Indian/Antananarivo': 'MG',
77
+ 'America/Argentina/San_Juan': 'AR',
78
+ 'Asia/Aden': 'YE',
79
+ 'Asia/Tomsk': 'RU',
80
+ 'America/Asuncion': 'PY',
81
+ 'Pacific/Bougainville': 'PG',
82
+ 'Asia/Vientiane': 'LA',
83
+ 'America/Mazatlan': 'MX',
84
+ 'Africa/Luanda': 'AO',
85
+ 'Europe/Oslo': 'NO',
86
+ 'Africa/Kinshasa': 'CD',
87
+ 'Europe/Warsaw': 'PL',
88
+ 'America/Grand_Turk': 'TC',
89
+ 'Asia/Seoul': 'KR',
90
+ 'Africa/Tripoli': 'LY',
91
+ 'America/St_Thomas': 'VI',
92
+ 'Asia/Kathmandu': 'NP',
93
+ 'Pacific/Pitcairn': 'PN',
94
+ 'Pacific/Nauru': 'NR',
95
+ 'America/Curacao': 'CW',
96
+ 'Asia/Kabul': 'AF',
97
+ 'Pacific/Tongatapu': 'TO',
98
+ 'Europe/Simferopol': 'UA',
99
+ 'Asia/Ust-Nera': 'RU',
100
+ 'Africa/Mogadishu': 'SO',
101
+ 'Indian/Mayotte': 'YT',
102
+ 'Pacific/Niue': 'NU',
103
+ 'America/Thunder_Bay': 'CA',
104
+ 'Atlantic/Azores': 'PT',
105
+ 'Pacific/Gambier': 'PF',
106
+ 'Europe/Stockholm': 'SE',
107
+ 'Africa/Libreville': 'GA',
108
+ 'America/Punta_Arenas': 'CL',
109
+ 'America/Guatemala': 'GT',
110
+ 'America/Noronha': 'BR',
111
+ 'Europe/Helsinki': 'FI',
112
+ 'Asia/Gaza': 'PS',
113
+ 'Pacific/Kosrae': 'FM',
114
+ 'America/Aruba': 'AW',
115
+ 'America/Nassau': 'BS',
116
+ 'Asia/Choibalsan': 'MN',
117
+ 'America/Winnipeg': 'CA',
118
+ 'America/Anguilla': 'AI',
119
+ 'Asia/Thimphu': 'BT',
120
+ 'Asia/Beirut': 'LB',
121
+ 'Atlantic/Faroe': 'FO',
122
+ 'Europe/Berlin': 'DE',
123
+ 'Europe/Amsterdam': 'NL',
124
+ 'Pacific/Honolulu': 'US',
125
+ 'America/Regina': 'CA',
126
+ 'America/Scoresbysund': 'GL',
127
+ 'Europe/Vienna': 'AT',
128
+ 'Europe/Tirane': 'AL',
129
+ 'Africa/El_Aaiun': 'EH',
130
+ 'America/Creston': 'CA',
131
+ 'Asia/Qostanay': 'KZ',
132
+ 'Asia/Ho_Chi_Minh': 'VN',
133
+ 'Europe/Samara': 'RU',
134
+ 'Europe/Rome': 'IT',
135
+ 'Australia/Eucla': 'AU',
136
+ 'America/El_Salvador': 'SV',
137
+ 'America/Chicago': 'US',
138
+ 'Africa/Abidjan': 'CI',
139
+ 'Asia/Kamchatka': 'RU',
140
+ 'Pacific/Tarawa': 'KI',
141
+ 'America/Santiago': 'CL',
142
+ 'America/Bahia': 'BR',
143
+ 'Indian/Christmas': 'CX',
144
+ 'Asia/Atyrau': 'KZ',
145
+ 'Asia/Dushanbe': 'TJ',
146
+ 'Europe/Ulyanovsk': 'RU',
147
+ 'America/Yellowknife': 'CA',
148
+ 'America/Recife': 'BR',
149
+ 'Australia/Sydney': 'AU',
150
+ 'America/Fort_Nelson': 'CA',
151
+ 'Pacific/Efate': 'VU',
152
+ 'Europe/Saratov': 'RU',
153
+ 'Africa/Banjul': 'GM',
154
+ 'Asia/Omsk': 'RU',
155
+ 'Europe/Ljubljana': 'SI',
156
+ 'Europe/Budapest': 'HU',
157
+ 'Europe/Astrakhan': 'RU',
158
+ 'America/Argentina/Buenos_Aires': 'AR',
159
+ 'Pacific/Chatham': 'NZ',
160
+ 'America/Argentina/Salta': 'AR',
161
+ 'Africa/Niamey': 'NE',
162
+ 'Asia/Pontianak': 'ID',
163
+ 'Indian/Reunion': 'RE',
164
+ 'Asia/Hong_Kong': 'HK',
165
+ 'Antarctica/McMurdo': 'AQ',
166
+ 'Africa/Malabo': 'GQ',
167
+ 'America/Los_Angeles': 'US',
168
+ 'America/Argentina/Cordoba': 'AR',
169
+ 'Pacific/Pohnpei': 'FM',
170
+ 'America/Tijuana': 'MX',
171
+ 'America/Campo_Grande': 'BR',
172
+ 'America/Dawson_Creek': 'CA',
173
+ 'Asia/Novosibirsk': 'RU',
174
+ 'Pacific/Pago_Pago': 'AS',
175
+ 'Asia/Jerusalem': 'IL',
176
+ 'Europe/Sarajevo': 'BA',
177
+ 'Africa/Freetown': 'SL',
178
+ 'Asia/Yekaterinburg': 'RU',
179
+ 'America/Juneau': 'US',
180
+ 'Africa/Ouagadougou': 'BF',
181
+ 'Africa/Monrovia': 'LR',
182
+ 'Europe/Kiev': 'UA',
183
+ 'America/Argentina/San_Luis': 'AR',
184
+ 'Asia/Tokyo': 'JP',
185
+ 'Asia/Qatar': 'QA',
186
+ 'America/La_Paz': 'BO',
187
+ 'America/Bogota': 'CO',
188
+ 'America/Thule': 'GL',
189
+ 'Asia/Manila': 'PH',
190
+ 'Asia/Hovd': 'MN',
191
+ 'Asia/Tehran': 'IR',
192
+ 'Atlantic/Madeira': 'PT',
193
+ 'America/Metlakatla': 'US',
194
+ 'Europe/Vatican': 'VA',
195
+ 'Asia/Bishkek': 'KG',
196
+ 'Asia/Dili': 'TL',
197
+ 'Antarctica/Palmer': 'AQ',
198
+ 'Atlantic/Cape_Verde': 'CV',
199
+ 'Indian/Chagos': 'IO',
200
+ 'America/Kentucky/Monticello': 'US',
201
+ 'Africa/Algiers': 'DZ',
202
+ 'Africa/Maseru': 'LS',
203
+ 'Asia/Kuala_Lumpur': 'MY',
204
+ 'Africa/Khartoum': 'SD',
205
+ 'America/Argentina/Rio_Gallegos': 'AR',
206
+ 'America/Blanc-Sablon': 'CA',
207
+ 'Africa/Maputo': 'MZ',
208
+ 'America/Tortola': 'VG',
209
+ 'Atlantic/Bermuda': 'BM',
210
+ 'America/Argentina/Catamarca': 'AR',
211
+ 'America/Cayman': 'KY',
212
+ 'America/Puerto_Rico': 'PR',
213
+ 'Pacific/Majuro': 'MH',
214
+ 'Europe/Busingen': 'DE',
215
+ 'Pacific/Midway': 'UM',
216
+ 'Indian/Cocos': 'CC',
217
+ 'Asia/Singapore': 'SG',
218
+ 'America/Boise': 'US',
219
+ 'America/Nuuk': 'GL',
220
+ 'America/Goose_Bay': 'CA',
221
+ 'Australia/Broken_Hill': 'AU',
222
+ 'Africa/Dar_es_Salaam': 'TZ',
223
+ 'Africa/Asmara': 'ER',
224
+ 'Asia/Samarkand': 'UZ',
225
+ 'Asia/Tbilisi': 'GE',
226
+ 'America/Argentina/Jujuy': 'AR',
227
+ 'America/Indiana/Winamac': 'US',
228
+ 'America/Porto_Velho': 'BR',
229
+ 'Asia/Magadan': 'RU',
230
+ 'Europe/Zaporozhye': 'UA',
231
+ 'Antarctica/Casey': 'AQ',
232
+ 'Asia/Shanghai': 'CN',
233
+ 'Pacific/Norfolk': 'NF',
234
+ 'Europe/Guernsey': 'GG',
235
+ 'Australia/Brisbane': 'AU',
236
+ 'Antarctica/DumontDUrville': 'AQ',
237
+ 'America/Havana': 'CU',
238
+ 'America/Atikokan': 'CA',
239
+ 'America/Mexico_City': 'MX',
240
+ 'America/Rankin_Inlet': 'CA',
241
+ 'America/Cuiaba': 'BR',
242
+ 'America/Resolute': 'CA',
243
+ 'Africa/Ceuta': 'ES',
244
+ 'Arctic/Longyearbyen': 'SJ',
245
+ 'Pacific/Guam': 'GU',
246
+ 'Asia/Damascus': 'SY',
247
+ 'Asia/Colombo': 'LK',
248
+ 'Asia/Yerevan': 'AM',
249
+ 'America/Montserrat': 'MS',
250
+ 'America/Belem': 'BR',
251
+ 'Europe/Kaliningrad': 'RU',
252
+ 'Atlantic/South_Georgia': 'GS',
253
+ 'Asia/Tashkent': 'UZ',
254
+ 'Asia/Kolkata': 'IN',
255
+ 'America/St_Johns': 'CA',
256
+ 'Asia/Srednekolymsk': 'RU',
257
+ 'Asia/Yakutsk': 'RU',
258
+ 'Europe/Prague': 'CZ',
259
+ 'Africa/Djibouti': 'DJ',
260
+ 'Asia/Dubai': 'AE',
261
+ 'Europe/Uzhgorod': 'UA',
262
+ 'America/Edmonton': 'CA',
263
+ 'Asia/Famagusta': 'CY',
264
+ 'America/Indiana/Knox': 'US',
265
+ 'Asia/Hebron': 'PS',
266
+ 'Asia/Taipei': 'TW',
267
+ 'Europe/London': 'GB',
268
+ 'Africa/Dakar': 'SN',
269
+ 'Australia/Darwin': 'AU',
270
+ 'America/Glace_Bay': 'CA',
271
+ 'Antarctica/Vostok': 'AQ',
272
+ 'America/Indiana/Vincennes': 'US',
273
+ 'America/Nipigon': 'CA',
274
+ 'Asia/Kuwait': 'KW',
275
+ 'Pacific/Guadalcanal': 'SB',
276
+ 'America/Toronto': 'CA',
277
+ 'Africa/Gaborone': 'BW',
278
+ 'Africa/Bujumbura': 'BI',
279
+ 'Africa/Lubumbashi': 'CD',
280
+ 'America/Merida': 'MX',
281
+ 'America/Marigot': 'MF',
282
+ 'Europe/Zagreb': 'HR',
283
+ 'Pacific/Easter': 'CL',
284
+ 'America/Santarem': 'BR',
285
+ 'Pacific/Noumea': 'NC',
286
+ 'America/Sitka': 'US',
287
+ 'Atlantic/Stanley': 'FK',
288
+ 'Pacific/Funafuti': 'TV',
289
+ 'America/Iqaluit': 'CA',
290
+ 'America/Rainy_River': 'CA',
291
+ 'America/Anchorage': 'US',
292
+ 'America/Lima': 'PE',
293
+ 'Asia/Baku': 'AZ',
294
+ 'America/Indiana/Vevay': 'US',
295
+ 'Asia/Ulaanbaatar': 'MN',
296
+ 'America/Managua': 'NI',
297
+ 'Asia/Krasnoyarsk': 'RU',
298
+ 'Asia/Qyzylorda': 'KZ',
299
+ 'America/Eirunepe': 'BR',
300
+ 'Europe/Podgorica': 'ME',
301
+ 'Europe/Chisinau': 'MD',
302
+ 'Europe/Mariehamn': 'AX',
303
+ 'Europe/Volgograd': 'RU',
304
+ 'Africa/Nairobi': 'KE',
305
+ 'Europe/Isle_of_Man': 'IM',
306
+ 'America/Menominee': 'US',
307
+ 'Africa/Harare': 'ZW',
308
+ 'Asia/Anadyr': 'RU',
309
+ 'America/Moncton': 'CA',
310
+ 'Indian/Maldives': 'MV',
311
+ 'America/Whitehorse': 'CA',
312
+ 'Antarctica/Mawson': 'AQ',
313
+ 'Europe/Madrid': 'ES',
314
+ 'America/Argentina/Mendoza': 'AR',
315
+ 'America/Manaus': 'BR',
316
+ 'Africa/Bangui': 'CF',
317
+ 'Indian/Mauritius': 'MU',
318
+ 'Africa/Tunis': 'TN',
319
+ 'Australia/Lord_Howe': 'AU',
320
+ 'America/Kentucky/Louisville': 'US',
321
+ 'America/North_Dakota/Center': 'US',
322
+ 'Asia/Novokuznetsk': 'RU',
323
+ 'Asia/Makassar': 'ID',
324
+ 'America/Port_of_Spain': 'TT',
325
+ 'America/Bahia_Banderas': 'MX',
326
+ 'Pacific/Auckland': 'NZ',
327
+ 'America/Sao_Paulo': 'BR',
328
+ 'Asia/Dhaka': 'BD',
329
+ 'America/Pangnirtung': 'CA',
330
+ 'Europe/Dublin': 'IE',
331
+ 'Asia/Brunei': 'BN',
332
+ 'Africa/Brazzaville': 'CG',
333
+ 'America/Montevideo': 'UY',
334
+ 'America/Jamaica': 'JM',
335
+ 'America/Indiana/Indianapolis': 'US',
336
+ 'America/Kralendijk': 'BQ',
337
+ 'Europe/Gibraltar': 'GI',
338
+ 'Pacific/Marquesas': 'PF',
339
+ 'Pacific/Apia': 'WS',
340
+ 'Europe/Jersey': 'JE',
341
+ 'America/Phoenix': 'US',
342
+ 'Africa/Ndjamena': 'TD',
343
+ 'Asia/Karachi': 'PK',
344
+ 'Africa/Kampala': 'UG',
345
+ 'Asia/Sakhalin': 'RU',
346
+ 'America/Martinique': 'MQ',
347
+ 'Europe/Moscow': 'RU',
348
+ 'Africa/Conakry': 'GN',
349
+ 'America/Barbados': 'BB',
350
+ 'Africa/Lome': 'TG',
351
+ 'America/Ojinaga': 'MX',
352
+ 'America/Tegucigalpa': 'HN',
353
+ 'Asia/Bangkok': 'TH',
354
+ 'Africa/Johannesburg': 'ZA',
355
+ 'Europe/Vaduz': 'LI',
356
+ 'Africa/Sao_Tome': 'ST',
357
+ 'America/Cambridge_Bay': 'CA',
358
+ 'America/Lower_Princes': 'SX',
359
+ 'America/Miquelon': 'PM',
360
+ 'America/St_Kitts': 'KN',
361
+ 'Australia/Melbourne': 'AU',
362
+ 'Europe/Minsk': 'BY',
363
+ 'Asia/Vladivostok': 'RU',
364
+ 'Europe/Sofia': 'BG',
365
+ 'Antarctica/Davis': 'AQ',
366
+ 'Pacific/Galapagos': 'EC',
367
+ 'America/North_Dakota/New_Salem': 'US',
368
+ 'Asia/Amman': 'JO',
369
+ 'Pacific/Wallis': 'WF',
370
+ 'America/Hermosillo': 'MX',
371
+ 'Pacific/Kiritimati': 'KI',
372
+ 'Antarctica/Macquarie': 'AU',
373
+ 'America/Guyana': 'GY',
374
+ 'Asia/Riyadh': 'SA',
375
+ 'Pacific/Tahiti': 'PF',
376
+ 'America/St_Vincent': 'VC',
377
+ 'America/Cancun': 'MX',
378
+ 'America/Grenada': 'GD',
379
+ 'Pacific/Wake': 'UM',
380
+ 'America/Dawson': 'CA',
381
+ 'Europe/Brussels': 'BE',
382
+ 'Indian/Kerguelen': 'TF',
383
+ 'America/Yakutat': 'US',
384
+ 'Indian/Mahe': 'SC',
385
+ 'Atlantic/Reykjavik': 'IS',
386
+ 'America/Panama': 'PA',
387
+ 'America/Guadeloupe': 'GP',
388
+ 'Europe/Malta': 'MT',
389
+ 'Antarctica/Troll': 'AQ',
390
+ 'Asia/Jayapura': 'ID',
391
+ 'Asia/Bahrain': 'BH',
392
+ 'Asia/Chita': 'RU',
393
+ 'Europe/Tallinn': 'EE',
394
+ 'Asia/Khandyga': 'RU',
395
+ 'America/Rio_Branco': 'BR',
396
+ 'Atlantic/St_Helena': 'SH',
397
+ 'Africa/Juba': 'SS',
398
+ 'America/Adak': 'US',
399
+ 'Pacific/Saipan': 'MP',
400
+ 'America/St_Lucia': 'LC',
401
+ 'America/Inuvik': 'CA',
402
+ 'Europe/Luxembourg': 'LU',
403
+ 'Africa/Bissau': 'GW',
404
+ 'Asia/Oral': 'KZ',
405
+ 'America/Boa_Vista': 'BR',
406
+ 'Europe/Skopje': 'MK',
407
+ 'America/Port-au-Prince': 'HT',
408
+ 'Pacific/Port_Moresby': 'PG',
409
+ 'Europe/Andorra': 'AD',
410
+ 'America/Indiana/Marengo': 'US',
411
+ 'Africa/Kigali': 'RW',
412
+ 'Africa/Bamako': 'ML',
413
+ 'America/Dominica': 'DM',
414
+ 'Asia/Aqtobe': 'KZ',
415
+ 'Europe/Istanbul': 'TR',
416
+ 'Pacific/Rarotonga': 'CK',
417
+ 'America/Danmarkshavn': 'GL',
418
+ 'Europe/Zurich': 'CH',
419
+ 'Asia/Yangon': 'MM',
420
+ 'America/Monterrey': 'MX',
421
+ 'Europe/Lisbon': 'PT',
422
+ 'Asia/Kuching': 'MY',
423
+ 'Antarctica/Rothera': 'AQ',
424
+ 'Australia/Perth': 'AU',
425
+ 'Asia/Phnom_Penh': 'KH',
426
+ 'America/Swift_Current': 'CA',
427
+ 'Asia/Aqtau': 'KZ',
428
+ 'Asia/Urumqi': 'CN',
429
+ 'Asia/Calcutta': 'IN'
430
+ };
431
+
432
+ /* eslint-disable @typescript-eslint/no-explicit-any */
433
+ const isBrowser = typeof window !== 'undefined';
434
+ let userId = null;
435
+ const PREF = 'saasco-sdk';
436
+ const data = {};
437
+ function storeData(key, value, ttl) {
438
+ const item = {
439
+ value,
440
+ expiry: new Date().getTime() + ttl
441
+ };
442
+ if (!isBrowser) {
443
+ if (value === undefined) {
444
+ delete data[key];
445
+ return;
446
+ }
447
+ data[key] = item;
448
+ return;
449
+ }
450
+ const fullKey = `${PREF}-${key}`;
451
+ if (value === undefined) return window.localStorage.removeItem(fullKey);
452
+ localStorage.setItem(fullKey, JSON.stringify(item));
453
+ }
454
+ function retrieveData(key) {
455
+ if (!isBrowser) {
456
+ const item = data[key];
457
+ if (!item) return null;
458
+ if (Date.now() > item.expiry) {
459
+ delete data[key];
460
+ return null;
461
+ }
462
+ return item.value;
463
+ }
464
+ const fullKey = `${PREF}-${key}`;
465
+ const itemStr = localStorage.getItem(fullKey);
466
+ if (!itemStr) {
467
+ return null;
468
+ }
469
+ const item = JSON.parse(itemStr);
470
+ const now = new Date();
471
+ if (now.getTime() > item.expiry) {
472
+ localStorage.removeItem(fullKey);
473
+ return null;
474
+ }
475
+ return item.value;
476
+ }
477
+ function getSessionId() {
478
+ return retrieveData(`session-id`);
479
+ }
480
+ function setSessionId({
481
+ reset
482
+ } = {
483
+ reset: false
484
+ }) {
485
+ const sessionId = reset ? v4() : getSessionId() || v4();
486
+ storeData(`session-id`, sessionId, 1000 * 60 * 30);
487
+ }
488
+ function getAnonymousId() {
489
+ return retrieveData(`anonymous-id`);
490
+ }
491
+ function setAnonmousId({
492
+ reset
493
+ } = {
494
+ reset: false
495
+ }) {
496
+ const anonymousId = reset ? v4() : getAnonymousId() || v4();
497
+ storeData(`anonymous-id`, anonymousId, 1000 * 60 * 60 * 24 * 365);
498
+ return anonymousId;
499
+ }
500
+ class Saasco {
501
+ /**
502
+ * Creates an instance of Saasco SDK.
503
+ * @param config Configuration options.
504
+ * @param config.projectId The unique identifier for the project.
505
+ * @param config.proxy The URL of the proxy server to use, if any.
506
+ * @param config.autoPageTracking Whether to automatically track page views. Default is false.
507
+ * @param config.enabled Whether analytics is enabled. Default is true. Set to false for development and staging envioronments. Will still allow debug mode to be true, just no events will be sent
508
+ * @param config.debug Whether to log debug information. Default is false.
509
+ */
510
+ constructor(config) {
511
+ this.config = config;
512
+ this.lastPageViewHref = '';
513
+ this.isInitialized = false;
514
+ // default enabled to true
515
+ this.config.enabled = this.config.enabled === undefined ? true : this.config.enabled;
516
+ }
517
+ init() {
518
+ if (this.isInitialized) {
519
+ this.log('Saasco is already initialized. Please check your code to ensure that init() is not being called multiple times.');
520
+ return;
521
+ }
522
+ this.initiAutoPageTracking();
523
+ this.log('Saasco initialized', this.config);
524
+ this.isInitialized = true;
525
+ }
526
+ debug(value) {
527
+ this.config.debug = value;
528
+ this.log(`Debug mode ${value ? 'activated' : 'deactivated'}.`);
529
+ }
530
+ /**
531
+ * The track method lets you record the actions your users perform.
532
+ * Its good to keep a conistent naming convention for your events.
533
+ * We like the Object Action Framework from segment:
534
+ * https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/
535
+ *
536
+ * @param name The name of the event eg "Song Played"
537
+ * @param properties The properties of the event eg { genre: "Classics", song: "Never Gonna Give You Up" }
538
+ */
539
+ track(name,
540
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
541
+ properties) {
542
+ var _a;
543
+ // Prevent duplicate Page View tracking
544
+ if (name === 'Page View') {
545
+ if (!isBrowser) return;
546
+ const pageViewHref = window.location.href;
547
+ if (pageViewHref === this.lastPageViewHref) return;
548
+ this.lastPageViewHref = pageViewHref;
549
+ }
550
+ setSessionId();
551
+ setAnonmousId();
552
+ const customNavigator = isBrowser ? navigator : undefined;
553
+ const locale = isBrowser ? (customNavigator === null || customNavigator === void 0 ? void 0 : customNavigator.languages) && (customNavigator === null || customNavigator === void 0 ? void 0 : customNavigator.languages.length) ? customNavigator === null || customNavigator === void 0 ? void 0 : customNavigator.languages[0] : (customNavigator === null || customNavigator === void 0 ? void 0 : customNavigator.userLanguage) || (customNavigator === null || customNavigator === void 0 ? void 0 : customNavigator.language) || (customNavigator === null || customNavigator === void 0 ? void 0 : customNavigator.browserLanguage) || 'en' : undefined;
554
+ // https://caniuse.com/?search=Intl.DateTimeFormat().resolvedOptions().timeZone
555
+ // Only has 96.63% global support, so we need to check for undefined
556
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
557
+ const location = isBrowser ? timezones[timezone] || ((_a = locale === null || locale === void 0 ? void 0 : locale.split('-')) === null || _a === void 0 ? void 0 : _a[1]) || 'undefined' : undefined;
558
+ const userAgent = isBrowser ? window.navigator.userAgent : undefined;
559
+ const title = isBrowser ? document.title : undefined;
560
+ const pathname = isBrowser ? window.location.pathname : undefined;
561
+ const href = isBrowser ? window.location.href : undefined;
562
+ const $screenHeight = isBrowser ? screen.height : undefined;
563
+ const $screenWidth = isBrowser ? screen.width : undefined;
564
+ const $screenDPI = isBrowser ? window.devicePixelRatio : undefined;
565
+ const $referrer = isBrowser ? document.referrer : undefined;
566
+ const $utm_source = this.getSearchParam('utm_source');
567
+ const $utm_medium = this.getSearchParam('utm_medium');
568
+ const $utm_campaign = this.getSearchParam('utm_campaign');
569
+ const $utm_content = this.getSearchParam('utm_content');
570
+ const $utm_term = this.getSearchParam('utm_term');
571
+ const $gclid = this.getSearchParam('gclid');
572
+ const $fbclid = this.getSearchParam('fbclid');
573
+ const data = {
574
+ id: v4(),
575
+ timestamp: new Date().toISOString(),
576
+ action: name,
577
+ version: '1',
578
+ sessionId: getSessionId(),
579
+ anonymousId: getAnonymousId(),
580
+ projectId: this.config.projectId,
581
+ payload: JSON.stringify({
582
+ 'user-agent': userAgent,
583
+ locale,
584
+ location,
585
+ title,
586
+ pathname,
587
+ href,
588
+ $screenHeight,
589
+ $screenWidth,
590
+ $screenDPI,
591
+ $referrer,
592
+ $utm_source,
593
+ $utm_medium,
594
+ $utm_campaign,
595
+ $utm_content,
596
+ $utm_term,
597
+ $gclid,
598
+ $fbclid,
599
+ properties: properties || {}
600
+ })
601
+ };
602
+ this.doRequest('events', data);
603
+ }
604
+ /**
605
+ * The page method lets you record page views on your website
606
+ * This records the page title and path and names the event useing the reserved property "Page Viewed"
607
+ *
608
+ * Before implementing this make sure you have disabled the autoPageTracking in the config or you will get duplicate page views
609
+ */
610
+ page() {
611
+ this.track('Page View');
612
+ }
613
+ identify(distinctIdOrProperties, propertiesOrOptions, optionsOrNothing) {
614
+ const hasId = typeof distinctIdOrProperties === 'string' || typeof distinctIdOrProperties === 'number' || distinctIdOrProperties === null;
615
+ const distinctId = hasId ? distinctIdOrProperties === null || distinctIdOrProperties === void 0 ? void 0 : distinctIdOrProperties.toString() : `soft_${v4()}`;
616
+ const properties = hasId ? propertiesOrOptions : distinctIdOrProperties;
617
+ const options = hasId ? optionsOrNothing : propertiesOrOptions;
618
+ // When the user gets identified as null this will reset the users session and anonymous id
619
+ // This should only be called when distinctId is null and there is an existing userId.
620
+ // This means the user has logged out and we should reset the session and anonymous IDs
621
+ const reset = !distinctId && !!userId;
622
+ if (reset) this.log('User logged out and session reset');
623
+ setSessionId({
624
+ reset
625
+ });
626
+ const anonymousId = setAnonmousId({
627
+ reset
628
+ });
629
+ // set the distinct Id to the userId
630
+ userId = distinctId;
631
+ // No distinctId provided so we don't track the user
632
+ if (!distinctId) return;
633
+ const data = {
634
+ id: v4(),
635
+ timestamp: new Date().toISOString(),
636
+ projectId: this.config.projectId,
637
+ distinctId,
638
+ anonymousId,
639
+ version: '1',
640
+ payload: properties || {},
641
+ options: options || {}
642
+ };
643
+ this.doRequest('identify', data);
644
+ }
645
+ /**
646
+ * Handles sending data to the Saasco API
647
+ * If you have a proxy set up, it will send the data to the proxy and you can handle forawrding the data to the Saasco events API
648
+ * @param path
649
+ * @param data
650
+ */
651
+ doRequest(path, data) {
652
+ const base = this.config.proxy || 'https://www.saasco.com/api/';
653
+ const url = `${base}${path}`;
654
+ const logMessage = data.action === 'Page View' ? `Page View ${window.location.pathname}` // if its a page view, include pathname in console log
655
+ : data.action || path;
656
+ this.log(logMessage, data);
657
+ // If analytics is disabled, don't send the request
658
+ if (this.config.enabled === false) return;
659
+ fetch(url, {
660
+ method: 'POST',
661
+ headers: {
662
+ 'Content-Type': 'application/json'
663
+ },
664
+ body: JSON.stringify(data)
665
+ }).then(response => {
666
+ if (!response.ok) {
667
+ throw new Error(response.status.toString());
668
+ }
669
+ }).catch(e => {
670
+ console.error('Error with Saasco request: ' + e.message, path, data);
671
+ });
672
+ }
673
+ /**
674
+ * @param args Arguments to be logged
675
+ */
676
+ log(...args) {
677
+ if (!this.config.debug) return;
678
+ const message = '◍ Saasco Debug';
679
+ console.log(...[`\x1b[47m\x1b[30m ${message} \x1b[0m`,
680
+ // Message highlighted for easy finding
681
+ ...args]);
682
+ }
683
+ getSearchParam(param) {
684
+ if (typeof window === 'undefined') return undefined;
685
+ return new URLSearchParams(window.location.search).get(param);
686
+ }
687
+ /**
688
+ * If autoPageTracking is enabled, this will automatically track page views
689
+ * It listens to url changes to track new pages every time the url changes
690
+ * @returns
691
+ */
692
+ initiAutoPageTracking() {
693
+ // Disable auto page tracking if the config is set to false
694
+ // Will run if undefined or true
695
+ if (this.config.autoPageTracking === false) return;
696
+ // Prevent running on the server
697
+ if (!isBrowser) return console.warn('Saasco auto page tracking is only available in the browser');
698
+ // Prevent intitializing auto page tracking more than once
699
+ if (window.saascoAutoPageTrackingActive) {
700
+ this.log('Auto Page Tracking already enabled');
701
+ return;
702
+ }
703
+ window.saascoAutoPageTrackingActive = true;
704
+ this.log('Auto Page Tracking enabled');
705
+ // Track initial page load
706
+ this.page();
707
+ // Listen for hash changes
708
+ window.addEventListener('hashchange', () => this.page());
709
+ // Listen to popstate for back and forward navigation
710
+ window.addEventListener('popstate', () => this.page());
711
+ // Wrap history push state to listen for URL changes
712
+ const historyPushState = history.pushState;
713
+ history.pushState = (...args) => {
714
+ const returnValue = historyPushState.apply(history, args);
715
+ this.page();
716
+ return returnValue;
717
+ };
718
+ // Wrap history replace state to listen for URL changes
719
+ const historyReplaceState = history.replaceState;
720
+ history.replaceState = (...args) => {
721
+ const returnValue = historyReplaceState.apply(history, args);
722
+ this.page();
723
+ return returnValue;
724
+ };
725
+ }
726
+ }
727
+
728
+ function coerceReservedProperties(properties) {
729
+ const coerce = [{
730
+ key: 'age',
731
+ coerceFrom: ['age', 'age_value', 'ageValue', 'user_age', 'userAge', 'user_age_value', 'userAgeValue', 'age_of_user', 'ageOfUser', 'age_in_years', 'ageInYears', 'years_old', 'yearsOld', 'age_years', 'ageYears'],
732
+ schema: z.coerce.number().optional()
733
+ }, {
734
+ key: 'avatar',
735
+ coerceFrom: ['avatar', 'user_avatar', 'userAvatar', 'avatar_url', 'avatarUrl', 'profile_picture', 'profilePicture', 'picture', 'user_picture', 'userPicture', 'profile_pic', 'profilePic', 'pic', 'user_pic', 'userPic', 'image', 'user_image', 'userImage', 'profile_image', 'profileImage', 'profile_image_url', 'profileImageUrl', 'profile_pic_url', 'profilePicUrl', 'pic_url', 'picUrl', 'image_url', 'imageUrl', 'user_image_url', 'userImageUrl', 'user_pic_url', 'userPicUrl', 'profile_pic_url', 'profilePicUrl', 'pic_url', 'picUrl', 'image_url', 'imageUrl', 'user_image_url', 'userImageUrl', 'user_pic_url', 'userPicUrl'],
736
+ schema: z.coerce.string().url().optional()
737
+ }, {
738
+ key: 'birthday',
739
+ coerceFrom: ['birthday', 'birth_date', 'birthDate', 'date_of_birth', 'dateOfBirth', 'dob', 'Dob', 'birth_day', 'birthDay']
740
+ }, {
741
+ key: 'createdAt',
742
+ coerceFrom: ['createdAt', 'created_at', 'created', 'createdDate', 'created_date', 'dateCreated', 'date_created', 'date_created_at', 'dateCreatedAt', 'date_created_at', 'dateCreated', 'date_created'],
743
+ schema: z.coerce.date().optional()
744
+ }, {
745
+ key: 'description',
746
+ coerceFrom: ['description', 'bio', 'about', 'about_me', 'aboutMe', 'user_description', 'userDescription', 'profile_description', 'profileDescription']
747
+ }, {
748
+ key: 'email',
749
+ coerceFrom: ['email', 'user_email', 'userEmail', 'email_address', 'emailAddress', 'e_mail', 'E_Mail', 'mail', 'Mail', 'contact_email', 'contactEmail', 'primary_email', 'primaryEmail'],
750
+ schema: z.coerce.string().email().optional()
751
+ }, {
752
+ key: 'firstName',
753
+ coerceFrom: ['first_name', 'firstName', 'firstname', 'given_name', 'givenName', 'user_first_name', 'userFirstName', 'name_first', 'nameFirst', 'f_name', 'fName']
754
+ }, {
755
+ key: 'gender',
756
+ coerceFrom: ['gender', 'user_gender', 'userGender', 'sex', 'user_sex', 'userSex']
757
+ }, {
758
+ key: 'lastName',
759
+ coerceFrom: ['last_name', 'lastName', 'lastname', 'surname', 'user_last_name', 'userLastName', 'name_last', 'nameLast', 'l_name', 'lName']
760
+ }, {
761
+ key: 'name',
762
+ coerceFrom: ['name', 'full_name', 'fullName', 'user_name', 'userName', 'complete_name', 'completeName']
763
+ }, {
764
+ key: 'phone',
765
+ coerceFrom: ['phone', 'phone_number', 'phoneNumber', 'mobile', 'mobile_number', 'mobileNumber', 'contact_number', 'contactNumber', 'tel', 'telephone']
766
+ }, {
767
+ key: 'title',
768
+ coerceFrom: ['title', 'user_title', 'userTitle', 'position', 'job_title', 'jobTitle']
769
+ }, {
770
+ key: 'username',
771
+ coerceFrom: ['username', 'user_name', 'userName', 'user_login', 'userLogin', 'account_name', 'accountName', 'screen_name', 'screenName', 'handle']
772
+ }, {
773
+ key: 'website',
774
+ coerceFrom: ['website', 'web_site', 'site', 'web', 'personal_website', 'personalWebsite', 'company_website', 'companyWebsite'],
775
+ schema: z.coerce.string().url().optional()
776
+ }, {
777
+ key: 'displayName',
778
+ coerceFrom: ['display_name', 'displayName', 'user_display_name', 'userDisplayName', 'full_name', 'fullName', 'user_full_name', 'userFullName', 'complete_name', 'completeName', 'user_complete_name', 'userCompleteName', 'name', 'username'],
779
+ schema: z.coerce.string().url().optional()
780
+ }];
781
+ return coerce.reduce((acc, {
782
+ key,
783
+ coerceFrom,
784
+ schema
785
+ }) => {
786
+ const coercedValue = coerceValue(properties, coerceFrom, schema);
787
+ if (coercedValue) acc[key] = coercedValue;
788
+ if (!coercedValue && key === 'displayName' && acc['firstName']) {
789
+ const displayName = `${acc['firstName'] || ''} ${acc['lastName'] || ''}`.trim();
790
+ if (displayName) acc[key] = displayName;
791
+ }
792
+ return acc;
793
+ }, properties);
794
+ }
795
+ /**
796
+ * Coerces the first non-null value from the properties object
797
+ * @param properties
798
+ * @param keys Provided in priority order, the first to match will return
799
+ * @returns
800
+ */
801
+ function coerceValue(properties, keys, schema) {
802
+ let coercedValue = null;
803
+ for (const key of keys) {
804
+ if (properties[key] !== undefined) {
805
+ if (!schema) {
806
+ coercedValue = properties[key];
807
+ break;
808
+ } else {
809
+ const result = schema.safeParse(properties[key]);
810
+ if (result.success) {
811
+ coercedValue = properties[key];
812
+ break;
813
+ }
814
+ }
815
+ }
816
+ }
817
+ return coercedValue;
818
+ }
819
+
820
+ const tbAny = z.union([z.string(), z.number(), z.array(z.union([z.string(), z.number()]))]);
821
+ const tinyBirdBaseSchema = z.object({
822
+ meta: z.array(z.object({
823
+ name: z.string(),
824
+ type: z.string()
825
+ })),
826
+ statistics: z.object({
827
+ elapsed: z.number(),
828
+ rows_read: z.number(),
829
+ bytes_read: z.number()
830
+ }),
831
+ rows: z.number()
832
+ });
833
+ const kpisRequestSchema = z.object({
834
+ projectId: z.string(),
835
+ dateTo: z.string().optional(),
836
+ dateFrom: z.string().optional(),
837
+ referringDomain: z.string().optional(),
838
+ location: z.string().optional()
839
+ });
840
+ const kpisResponseSchema = tinyBirdBaseSchema.extend({
841
+ data: z.array(z.object({
842
+ date: z.string(),
843
+ visits: z.number(),
844
+ pageviews: z.number(),
845
+ bounceRate: z.nullable(z.number()),
846
+ avgSessionSec: z.number()
847
+ }))
848
+ });
849
+ const eventsKpisResponseSchema = tinyBirdBaseSchema.extend({
850
+ data: z.array(z.object({
851
+ unique: z.number(),
852
+ total: z.number()
853
+ }))
854
+ });
855
+ const baseTopRequestSchema = z.object({
856
+ projectId: z.string(),
857
+ dateTo: z.string().optional(),
858
+ dateFrom: z.string().optional(),
859
+ limit: z.number().optional(),
860
+ skip: z.number().optional(),
861
+ referringDomain: z.string().optional(),
862
+ location: z.string().optional()
863
+ });
864
+ const topPagesResponseSchema = tinyBirdBaseSchema.extend({
865
+ data: z.array(z.object({
866
+ pathname: z.string(),
867
+ visits: z.number(),
868
+ hits: z.number()
869
+ }))
870
+ });
871
+ const topLocationsResponseSchema = tinyBirdBaseSchema.extend({
872
+ data: z.array(z.object({
873
+ location: z.string(),
874
+ visits: z.number(),
875
+ hits: z.number(),
876
+ bounceRate: z.nullable(z.number()),
877
+ avgSessionSec: z.number()
878
+ }))
879
+ });
880
+ const topDevicesResponseSchema = tinyBirdBaseSchema.extend({
881
+ data: z.array(z.object({
882
+ device: z.string(),
883
+ visits: z.number(),
884
+ hits: z.number(),
885
+ bounceRate: z.nullable(z.number()),
886
+ avgSessionSec: z.number()
887
+ }))
888
+ });
889
+ const topBrowsersResponseSchema = tinyBirdBaseSchema.extend({
890
+ data: z.array(z.object({
891
+ browser: z.string(),
892
+ visits: z.number(),
893
+ hits: z.number(),
894
+ bounceRate: z.nullable(z.number()),
895
+ avgSessionSec: z.number()
896
+ }))
897
+ });
898
+ const topSourcesSchema = z.object({
899
+ referrer: z.string(),
900
+ visits: z.number(),
901
+ hits: z.number(),
902
+ bounceRate: z.nullable(z.number()),
903
+ avgSessionSec: z.number()
904
+ });
905
+ const topSourcesResponseSchema = tinyBirdBaseSchema.extend({
906
+ data: z.array(topSourcesSchema)
907
+ });
908
+ const topActionsResponseSchema = tinyBirdBaseSchema.extend({
909
+ data: z.array(z.object({
910
+ action: z.string(),
911
+ unique: z.number(),
912
+ total: z.number()
913
+ }))
914
+ });
915
+ const analyticsEventSchema = z.object({
916
+ id: z.string(),
917
+ timestamp: z.string(),
918
+ projectId: z.string(),
919
+ anonymousId: z.string(),
920
+ sessionId: z.string(),
921
+ version: z.string(),
922
+ action: z.string(),
923
+ payload: z.string()
924
+ });
925
+ const userEventsResponseSchema = tinyBirdBaseSchema.extend({
926
+ data: z.array(analyticsEventSchema)
927
+ });
928
+ const currentUsersRequestSchema = z.object({
929
+ projectId: z.string(),
930
+ minutes: z.number().optional(),
931
+ referringDomain: z.string().optional(),
932
+ location: z.string().optional()
933
+ });
934
+ const currentUsersResponseSchema = tinyBirdBaseSchema.extend({
935
+ data: z.array(z.object({
936
+ visits: z.number()
937
+ }))
938
+ });
939
+ const reservedPropertiesSchema = z.object({
940
+ age: z.number().nullish(),
941
+ avatar: z.string().url().nullish(),
942
+ birthday: z.string().nullish(),
943
+ createdAt: z.string().nullish(),
944
+ description: z.string().nullish(),
945
+ email: z.string().email().or(z.literal('')).nullish(),
946
+ firstName: z.string().nullish(),
947
+ gender: z.string().nullish(),
948
+ id: z.string().nullish(),
949
+ lastName: z.string().nullish(),
950
+ name: z.string().nullish(),
951
+ phone: z.string().nullish(),
952
+ title: z.string().nullish(),
953
+ username: z.string().nullish(),
954
+ website: z.string().nullish()
955
+ });
956
+ const userPropertiesSchema = reservedPropertiesSchema.and(z.record(z.union([z.string(), z.number(), z.boolean(), z.date(), z.null(), z.array(z.union([z.string(), z.number(), z.boolean(), z.date(), z.null()]))])));
957
+ const analyticsUserRawSchema = z.object({
958
+ timestamp: z.string(),
959
+ distinctId: z.string(),
960
+ projectId: z.string(),
961
+ payload: z.string()
962
+ });
963
+ const analyticsUserSchema = analyticsUserRawSchema.omit({
964
+ payload: true
965
+ }).and(z.object({
966
+ properties: userPropertiesSchema
967
+ }));
968
+ const listUsersParamsSchema = z.object({
969
+ projectId: z.string(),
970
+ limit: z.number().optional()
971
+ });
972
+ const getAnalyticsUserParamsSchema = z.object({
973
+ projectId: z.string(),
974
+ distinctId: z.string()
975
+ });
976
+ const idenfitySchema = z.object({
977
+ id: z.string(),
978
+ timestamp: z.string(),
979
+ projectId: z.string(),
980
+ distinctId: z.string(),
981
+ anonymousId: z.string(),
982
+ version: z.string(),
983
+ payload: userPropertiesSchema,
984
+ options: z.object({
985
+ active: z.boolean().optional()
986
+ }).optional()
987
+ });
988
+
989
+ export { Saasco, analyticsEventSchema, analyticsUserRawSchema, analyticsUserSchema, baseTopRequestSchema, coerceReservedProperties, currentUsersRequestSchema, currentUsersResponseSchema, eventsKpisResponseSchema, getAnalyticsUserParamsSchema, idenfitySchema, kpisRequestSchema, kpisResponseSchema, listUsersParamsSchema, reservedPropertiesSchema, tbAny, tinyBirdBaseSchema, topActionsResponseSchema, topBrowsersResponseSchema, topDevicesResponseSchema, topLocationsResponseSchema, topPagesResponseSchema, topSourcesResponseSchema, topSourcesSchema, userEventsResponseSchema, userPropertiesSchema };