@blotoutio/edgetag-sdk-js 0.6.9 → 0.7.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 (4) hide show
  1. package/README.md +1 -1
  2. package/index.cjs +325 -182
  3. package/index.esm.js +307 -182
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
1
  # EdgeTag SDK Core
2
2
 
3
- More info on https://app.edgetag.io/integration/js
3
+ More info on https://app.edgetag.io/docs/js
package/index.cjs CHANGED
@@ -4,6 +4,24 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var uuid = require('uuid');
6
6
 
7
+ function _interopNamespace(e) {
8
+ if (e && e.__esModule) return e;
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n["default"] = e;
22
+ return Object.freeze(n);
23
+ }
24
+
7
25
  var api = /*#__PURE__*/Object.freeze({
8
26
  __proto__: null,
9
27
  get init () { return init; },
@@ -41,132 +59,6 @@ function __awaiter(thisArg, _arguments, P, generator) {
41
59
  });
42
60
  }
43
61
 
44
- const tagStorage = 'edgeTag';
45
- const consentKey = 'consent';
46
- const keyPrefix = `_worker`;
47
-
48
- const initKey = `${keyPrefix}Store`;
49
- const getCookieValue = (key) => {
50
- if (!document || !document.cookie) {
51
- return '';
52
- }
53
- const name = `${key}=`;
54
- const decodedCookie = decodeURIComponent(document.cookie);
55
- const ca = decodedCookie.split(';');
56
- for (let i = 0; i < ca.length; i++) {
57
- let c = ca[i];
58
- while (c.charAt(0) === ' ') {
59
- c = c.substring(1);
60
- }
61
- if (c.indexOf(name) === 0) {
62
- return c.substring(name.length, c.length);
63
- }
64
- }
65
- return '';
66
- };
67
- const saveDataPerKey = (persistType, provider, value, key) => {
68
- const storage = getData$1(persistType);
69
- if (!storage['data']) {
70
- storage['data'] = {};
71
- }
72
- if (!storage['data'][provider]) {
73
- storage['data'][provider] = {};
74
- }
75
- storage['data'][provider][key] = value;
76
- saveData(persistType, storage);
77
- };
78
- const savePerKey = (persistType, provider, value, key) => {
79
- const storage = getData$1(persistType);
80
- if (!storage[provider]) {
81
- storage[provider] = {};
82
- }
83
- storage[provider][key] = value;
84
- saveData(persistType, storage);
85
- };
86
- const getDataPerKey = (persistType, provider, key) => {
87
- const storage = getData$1(persistType);
88
- if (!storage[provider]) {
89
- return undefined;
90
- }
91
- return storage[provider][key];
92
- };
93
- const saveData = (persistType, value, key = initKey) => {
94
- if (persistType === 'session') {
95
- saveSession(value, key);
96
- return;
97
- }
98
- saveLocal(value, key);
99
- };
100
- const getData$1 = (persistType, key = initKey) => {
101
- if (persistType === 'session') {
102
- return getSession(key);
103
- }
104
- return getLocal(key);
105
- };
106
- const saveKV = (data) => {
107
- let currentSession = getData$1('session');
108
- if (!currentSession) {
109
- currentSession = {};
110
- }
111
- if (!currentSession['kv']) {
112
- currentSession['kv'] = {};
113
- }
114
- currentSession['kv'] = Object.assign(Object.assign({}, currentSession['kv']), data);
115
- saveData('session', currentSession);
116
- };
117
- const saveLocal = (value, key) => {
118
- try {
119
- if (!localStorage) {
120
- return;
121
- }
122
- localStorage.setItem(key, JSON.stringify(value));
123
- }
124
- catch (_a) {
125
- console.log('Local storage not supported');
126
- }
127
- };
128
- const getLocal = (key) => {
129
- try {
130
- if (!localStorage) {
131
- return {};
132
- }
133
- const data = localStorage.getItem(key);
134
- if (!data) {
135
- return {};
136
- }
137
- return JSON.parse(data) || {};
138
- }
139
- catch (_a) {
140
- return {};
141
- }
142
- };
143
- const saveSession = (value, key) => {
144
- try {
145
- if (!sessionStorage) {
146
- return;
147
- }
148
- sessionStorage.setItem(key, JSON.stringify(value));
149
- }
150
- catch (_a) {
151
- console.log('Session storage not supported');
152
- }
153
- };
154
- const getSession = (key) => {
155
- try {
156
- if (!sessionStorage) {
157
- return {};
158
- }
159
- const data = sessionStorage.getItem(key);
160
- if (!data) {
161
- return {};
162
- }
163
- return JSON.parse(data) || {};
164
- }
165
- catch (_a) {
166
- return {};
167
- }
168
- };
169
-
170
62
  let endpointUrl = '';
171
63
  const generateUrl = (path) => {
172
64
  const endpoint = getUrl();
@@ -227,13 +119,18 @@ const setPreferences = (preferences) => {
227
119
  }
228
120
  providersPackages[provider.name] = provider;
229
121
  });
230
- if (window && Array.isArray(window.edgetagProviders)) {
231
- window.edgetagProviders.forEach((provider) => {
232
- if (!provider.name) {
233
- return;
234
- }
235
- providersPackages[provider.name] = provider;
236
- });
122
+ try {
123
+ if (window && Array.isArray(window.edgetagProviders)) {
124
+ window.edgetagProviders.forEach((provider) => {
125
+ if (!provider.name) {
126
+ return;
127
+ }
128
+ providersPackages[provider.name] = provider;
129
+ });
130
+ }
131
+ }
132
+ catch (_b) {
133
+ // do nothing
237
134
  }
238
135
  setUrl(preferences.edgeURL);
239
136
  return true;
@@ -249,44 +146,75 @@ const setAllowedProviders = (providers) => {
249
146
  allowedProvider = providers;
250
147
  };
251
148
 
252
- const getUserAgent = () => {
253
- const nav = navigator;
254
- let ua = nav.userAgent;
255
- ua += nav.brave ? `${ua} Brave` : '';
256
- return ua;
257
- };
258
- const allowTag = (providers) => {
259
- if (!allowProviders(providers)) {
260
- return false;
261
- }
262
- const consent = getDataPerKey('local', tagStorage, consentKey);
149
+ const checkConsent = (providers) => {
263
150
  if (isConsentDisabled()) {
264
151
  return true;
265
152
  }
153
+ const consent = getConsent();
266
154
  if (!consent) {
267
155
  return false;
268
156
  }
269
- if (consent['all']) {
270
- return true;
157
+ const consentLength = Object.keys(consent).length;
158
+ if (!consentLength || (consentLength === 1 && consent['all'] === false)) {
159
+ return false;
271
160
  }
272
- if (!providers) {
161
+ const providersLength = Object.keys(providers || {}).length;
162
+ if (!providers ||
163
+ providersLength === 0 ||
164
+ (providersLength === 1 && providers['all'])) {
273
165
  return (Object.values(consent).find((isAllowed) => isAllowed) || false);
274
166
  }
275
- const allProviders = getAllowedProviders();
276
- for (const provider of allProviders) {
277
- const tagProviderSetting = providers[provider];
278
- if (tagProviderSetting ||
279
- (providers['all'] === true && tagProviderSetting === undefined) ||
280
- (providers['all'] === false && tagProviderSetting === true)) {
281
- if (consent[provider]) {
167
+ for (const [key, value] of Object.entries(providers)) {
168
+ if (value === false || consent[key] === false) {
169
+ continue;
170
+ }
171
+ // we have consent
172
+ if (consent[key] ||
173
+ (consent['all'] === true && consent[key] === undefined)) {
174
+ // we have provider
175
+ if (value || (providers['all'] && providers[key] === undefined)) {
282
176
  return true;
283
177
  }
284
178
  }
285
179
  }
286
180
  return false;
287
181
  };
182
+ const getUserAgent = () => {
183
+ try {
184
+ const nav = navigator;
185
+ let ua = nav.userAgent;
186
+ ua += nav.brave ? `${ua} Brave` : '';
187
+ return ua;
188
+ }
189
+ catch (_a) {
190
+ return '';
191
+ }
192
+ };
193
+ const isProviderIncluded = (providers, providerValue) => {
194
+ return (providerValue || (providers['all'] === true && providerValue === undefined));
195
+ };
196
+ const allowTag = (providers) => {
197
+ if (!checkConsent(providers)) {
198
+ return false;
199
+ }
200
+ const providersLength = Object.values(providers || {}).length;
201
+ if (!providers || providersLength === 0) {
202
+ return true;
203
+ }
204
+ const allProviders = getAllowedProviders();
205
+ const allProvidersLength = Object.keys(allProviders || {}).length;
206
+ if (allProvidersLength === 0) {
207
+ return true;
208
+ }
209
+ for (const provider of allProviders) {
210
+ if (isProviderIncluded(providers, providers[provider])) {
211
+ return true;
212
+ }
213
+ }
214
+ return false;
215
+ };
288
216
  const allowProviders = (providers) => {
289
- if (!providers || Object.keys(providers).length === 0) {
217
+ if (!providers || Object.keys(providers).length === 0 || providers['all']) {
290
218
  return true;
291
219
  }
292
220
  const allowedProvider = getAllowedProviders();
@@ -318,41 +246,223 @@ const allowProviderWithConsent = (providers, providerId) => {
318
246
  if (!allowProvider(providerId)) {
319
247
  return false;
320
248
  }
249
+ if (!checkConsent(providers)) {
250
+ return false;
251
+ }
321
252
  if (providers && Object.keys(providers).length) {
322
- const tagProvider = providers[providerId];
323
- if (!(tagProvider ||
324
- (providers['all'] === true && tagProvider === undefined) ||
325
- (providers['all'] === false && tagProvider === true))) {
253
+ if (!isProviderIncluded(providers, providers[providerId])) {
326
254
  return false;
327
255
  }
328
256
  }
329
- const consent = getDataPerKey('local', tagStorage, consentKey);
330
- if (isConsentDisabled()) {
331
- return true;
257
+ return true;
258
+ };
259
+
260
+ const tagStorage = 'edgeTag';
261
+ const consentKey = 'consent';
262
+ const keyPrefix = `_worker`;
263
+
264
+ const initKey = `${keyPrefix}Store`;
265
+ const getCookieValue = (key) => {
266
+ try {
267
+ if (!document || !document.cookie) {
268
+ return '';
269
+ }
270
+ const name = `${key}=`;
271
+ const decodedCookie = decodeURIComponent(document.cookie);
272
+ const ca = decodedCookie.split(';');
273
+ for (let i = 0; i < ca.length; i++) {
274
+ let c = ca[i];
275
+ while (c.charAt(0) === ' ') {
276
+ c = c.substring(1);
277
+ }
278
+ if (c.indexOf(name) === 0) {
279
+ return c.substring(name.length, c.length);
280
+ }
281
+ }
282
+ return '';
332
283
  }
333
- if (!consent) {
334
- return false;
284
+ catch (_a) {
285
+ return '';
335
286
  }
336
- if (consent['all']) {
337
- return true;
287
+ };
288
+ const saveDataPerKey = (persistType, provider, value, key) => {
289
+ const storage = getData$1(persistType);
290
+ if (!storage['data']) {
291
+ storage['data'] = {};
292
+ }
293
+ if (!storage['data'][provider]) {
294
+ storage['data'][provider] = {};
338
295
  }
339
- return consent[providerId];
296
+ storage['data'][provider][key] = value;
297
+ saveData(persistType, storage);
298
+ };
299
+ const savePerKey = (persistType, provider, value, key) => {
300
+ const storage = getData$1(persistType);
301
+ if (!storage[provider]) {
302
+ storage[provider] = {};
303
+ }
304
+ storage[provider][key] = value;
305
+ saveData(persistType, storage);
306
+ };
307
+ const getDataPerKey = (persistType, provider, key) => {
308
+ const storage = getData$1(persistType);
309
+ if (!storage[provider]) {
310
+ return undefined;
311
+ }
312
+ return storage[provider][key];
313
+ };
314
+ const saveData = (persistType, value, key = initKey) => {
315
+ if (persistType === 'session') {
316
+ saveSession(value, key);
317
+ return;
318
+ }
319
+ saveLocal(value, key);
320
+ };
321
+ const getData$1 = (persistType, key = initKey) => {
322
+ if (persistType === 'session') {
323
+ return getSession(key);
324
+ }
325
+ return getLocal(key);
326
+ };
327
+ const saveKV = (data) => {
328
+ let currentSession = getData$1('session');
329
+ if (!currentSession) {
330
+ currentSession = {};
331
+ }
332
+ if (!currentSession['kv']) {
333
+ currentSession['kv'] = {};
334
+ }
335
+ currentSession['kv'] = Object.assign(Object.assign({}, currentSession['kv']), data);
336
+ saveData('session', currentSession);
337
+ };
338
+ const saveLocal = (value, key) => {
339
+ try {
340
+ if (!localStorage) {
341
+ return;
342
+ }
343
+ localStorage.setItem(key, JSON.stringify(value));
344
+ }
345
+ catch (_a) {
346
+ console.log('Local storage not supported');
347
+ }
348
+ };
349
+ const getLocal = (key) => {
350
+ try {
351
+ if (!localStorage) {
352
+ return {};
353
+ }
354
+ const data = localStorage.getItem(key);
355
+ if (!data) {
356
+ return {};
357
+ }
358
+ return JSON.parse(data) || {};
359
+ }
360
+ catch (_a) {
361
+ return {};
362
+ }
363
+ };
364
+ const saveSession = (value, key) => {
365
+ try {
366
+ if (!sessionStorage) {
367
+ return;
368
+ }
369
+ sessionStorage.setItem(key, JSON.stringify(value));
370
+ }
371
+ catch (_a) {
372
+ console.log('Session storage not supported');
373
+ }
374
+ };
375
+ const getSession = (key) => {
376
+ try {
377
+ if (!sessionStorage) {
378
+ return {};
379
+ }
380
+ const data = sessionStorage.getItem(key);
381
+ if (!data) {
382
+ return {};
383
+ }
384
+ return JSON.parse(data) || {};
385
+ }
386
+ catch (_a) {
387
+ return {};
388
+ }
389
+ };
390
+
391
+ let initUserId = '';
392
+ const handleGetUserId = () => {
393
+ if (initUserId) {
394
+ return initUserId;
395
+ }
396
+ return getCookieValue('tag_user_id');
397
+ };
398
+ const setUserId = (userId) => {
399
+ initUserId = userId;
340
400
  };
341
401
 
402
+ const getHeaders = () => ({
403
+ 'Content-type': 'application/json; charset=utf-8',
404
+ Accept: 'application/json; charset=utf-8',
405
+ EdgeTagUserId: handleGetUserId(),
406
+ });
342
407
  const beacon = (url, payload) => {
343
- let blob;
344
- if (payload) {
345
- blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
408
+ try {
409
+ let blob;
410
+ if (payload) {
411
+ blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
412
+ }
413
+ return navigator.sendBeacon(url, blob);
414
+ }
415
+ catch (e) {
416
+ console.log('Beacon not supported.');
417
+ return Promise.reject(new Error('Beacon not supported'));
346
418
  }
347
- return navigator.sendBeacon(url, blob);
348
419
  };
420
+ const fallbackAjax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
421
+ const https = yield Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('https')); });
422
+ const options = {
423
+ method,
424
+ headers: getHeaders(),
425
+ };
426
+ return new Promise((resolve, reject) => {
427
+ const req = https.request(url, options, (res) => {
428
+ res.on('data', (data) => {
429
+ try {
430
+ data = JSON.parse(data);
431
+ }
432
+ catch (_a) {
433
+ // do nothing
434
+ }
435
+ resolve({
436
+ body: data,
437
+ status: res.statusCode || 500,
438
+ });
439
+ });
440
+ });
441
+ req.on('error', (e) => {
442
+ reject(new Error(e.message));
443
+ });
444
+ if (payload && method !== 'GET') {
445
+ req.write(JSON.stringify(payload));
446
+ }
447
+ req.end();
448
+ });
449
+ });
349
450
  const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
451
+ if (typeof fetch === 'undefined') {
452
+ return yield fallbackAjax(method, url, payload)
453
+ .then((data) => {
454
+ if (data.status < 200 || data.status >= 300) {
455
+ return Promise.reject(new Error(JSON.stringify(data.body)));
456
+ }
457
+ return Promise.resolve(data.body);
458
+ })
459
+ .catch((error) => {
460
+ return Promise.reject(new Error(error));
461
+ });
462
+ }
350
463
  return yield fetch(url, {
351
464
  method,
352
- headers: {
353
- 'Content-type': 'application/json; charset=utf-8',
354
- Accept: 'application/json; charset=utf-8',
355
- },
465
+ headers: getHeaders(),
356
466
  body: JSON.stringify(payload),
357
467
  credentials: 'include',
358
468
  })
@@ -370,7 +480,14 @@ const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, functio
370
480
  });
371
481
  });
372
482
  const getStandardPayload = (payload) => {
373
- const data = Object.assign({ pageUrl: window.location.href, userAgent: getUserAgent() }, (payload || {}));
483
+ let pageUrl;
484
+ try {
485
+ pageUrl = window.location.href;
486
+ }
487
+ catch (_a) {
488
+ pageUrl = '';
489
+ }
490
+ const data = Object.assign({ pageUrl, userAgent: getUserAgent() }, (payload || {}));
374
491
  let storage = {};
375
492
  const session = getData$1('session');
376
493
  if (session) {
@@ -412,7 +529,9 @@ function getRequest(url, options) {
412
529
  const info = (data) => {
413
530
  };
414
531
 
532
+ let memoryConsent;
415
533
  const saveConsent = (consent) => {
534
+ setConsent(consent);
416
535
  savePerKey('local', tagStorage, consent, consentKey);
417
536
  };
418
537
  const handleConsent = (consent) => {
@@ -422,7 +541,23 @@ const handleConsent = (consent) => {
422
541
  saveConsent(consent);
423
542
  postRequest(getConsentURL(), payload).catch(info);
424
543
  };
544
+ const setConsent = (newConsent) => {
545
+ memoryConsent = newConsent;
546
+ };
547
+ const getConsent = () => {
548
+ const storageConsent = getDataPerKey('local', tagStorage, consentKey);
549
+ if (storageConsent) {
550
+ return storageConsent;
551
+ }
552
+ return memoryConsent;
553
+ };
425
554
 
555
+ const encodeString = (name) => {
556
+ if (typeof btoa === 'undefined') {
557
+ return Buffer.from(name).toString('base64');
558
+ }
559
+ return btoa(name);
560
+ };
426
561
  const generateEventId = (name) => {
427
562
  let time = Date.now().toString();
428
563
  if (typeof performance !== 'undefined' &&
@@ -432,11 +567,7 @@ const generateEventId = (name) => {
432
567
  time = perf.toFixed(4);
433
568
  }
434
569
  }
435
- return `${btoa(name)}-${uuid.v4()}-${time}`;
436
- };
437
-
438
- const handleGetUserId = () => {
439
- return getCookieValue('tag_user_id');
570
+ return `${encodeString(name)}-${uuid.v4()}-${time}`;
440
571
  };
441
572
 
442
573
  const manifestVariables = {};
@@ -457,6 +588,7 @@ const processStubs = () => {
457
588
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
458
589
  // @ts-ignore
459
590
  stubs.forEach((stub) => api[stub.name](...(stub.arguments || [])));
591
+ stubs = [];
460
592
  }
461
593
  catch (e) {
462
594
  console.error(e);
@@ -465,6 +597,7 @@ const processStubs = () => {
465
597
 
466
598
  const sendTag = ({ eventName, eventId, data, providerData, providers, options, }) => {
467
599
  if (!allowProviders(providers)) {
600
+ console.log('Provider is not allowed.');
468
601
  return;
469
602
  }
470
603
  const payload = {
@@ -487,6 +620,10 @@ const handleTag = (eventName, data = {}, providers, options) => {
487
620
  });
488
621
  return;
489
622
  }
623
+ if (!allowProviders(providers)) {
624
+ console.log('Provider is not allowed.');
625
+ return;
626
+ }
490
627
  if (!allowTag(providers)) {
491
628
  console.log('No consent');
492
629
  return;
@@ -551,7 +688,12 @@ const saveDataToEdge = (key, value, provider) => {
551
688
  handleData({ [`${provider}::${key}`]: value });
552
689
  };
553
690
  const handleCaptureQuery = (provider, key, persistType) => {
554
- if (!window) {
691
+ try {
692
+ if (!window) {
693
+ return;
694
+ }
695
+ }
696
+ catch (_a) {
555
697
  return;
556
698
  }
557
699
  const params = new URLSearchParams(window.location.search);
@@ -653,6 +795,7 @@ const handleInit = (preferences) => {
653
795
  saveConsent({ all: true });
654
796
  }
655
797
  if (preferences.userId) {
798
+ setUserId(preferences.userId);
656
799
  url.searchParams.set('userId', preferences.userId);
657
800
  }
658
801
  getRequest(url.href)
package/index.esm.js CHANGED
@@ -37,132 +37,6 @@ function __awaiter(thisArg, _arguments, P, generator) {
37
37
  });
38
38
  }
39
39
 
40
- const tagStorage = 'edgeTag';
41
- const consentKey = 'consent';
42
- const keyPrefix = `_worker`;
43
-
44
- const initKey = `${keyPrefix}Store`;
45
- const getCookieValue = (key) => {
46
- if (!document || !document.cookie) {
47
- return '';
48
- }
49
- const name = `${key}=`;
50
- const decodedCookie = decodeURIComponent(document.cookie);
51
- const ca = decodedCookie.split(';');
52
- for (let i = 0; i < ca.length; i++) {
53
- let c = ca[i];
54
- while (c.charAt(0) === ' ') {
55
- c = c.substring(1);
56
- }
57
- if (c.indexOf(name) === 0) {
58
- return c.substring(name.length, c.length);
59
- }
60
- }
61
- return '';
62
- };
63
- const saveDataPerKey = (persistType, provider, value, key) => {
64
- const storage = getData$1(persistType);
65
- if (!storage['data']) {
66
- storage['data'] = {};
67
- }
68
- if (!storage['data'][provider]) {
69
- storage['data'][provider] = {};
70
- }
71
- storage['data'][provider][key] = value;
72
- saveData(persistType, storage);
73
- };
74
- const savePerKey = (persistType, provider, value, key) => {
75
- const storage = getData$1(persistType);
76
- if (!storage[provider]) {
77
- storage[provider] = {};
78
- }
79
- storage[provider][key] = value;
80
- saveData(persistType, storage);
81
- };
82
- const getDataPerKey = (persistType, provider, key) => {
83
- const storage = getData$1(persistType);
84
- if (!storage[provider]) {
85
- return undefined;
86
- }
87
- return storage[provider][key];
88
- };
89
- const saveData = (persistType, value, key = initKey) => {
90
- if (persistType === 'session') {
91
- saveSession(value, key);
92
- return;
93
- }
94
- saveLocal(value, key);
95
- };
96
- const getData$1 = (persistType, key = initKey) => {
97
- if (persistType === 'session') {
98
- return getSession(key);
99
- }
100
- return getLocal(key);
101
- };
102
- const saveKV = (data) => {
103
- let currentSession = getData$1('session');
104
- if (!currentSession) {
105
- currentSession = {};
106
- }
107
- if (!currentSession['kv']) {
108
- currentSession['kv'] = {};
109
- }
110
- currentSession['kv'] = Object.assign(Object.assign({}, currentSession['kv']), data);
111
- saveData('session', currentSession);
112
- };
113
- const saveLocal = (value, key) => {
114
- try {
115
- if (!localStorage) {
116
- return;
117
- }
118
- localStorage.setItem(key, JSON.stringify(value));
119
- }
120
- catch (_a) {
121
- console.log('Local storage not supported');
122
- }
123
- };
124
- const getLocal = (key) => {
125
- try {
126
- if (!localStorage) {
127
- return {};
128
- }
129
- const data = localStorage.getItem(key);
130
- if (!data) {
131
- return {};
132
- }
133
- return JSON.parse(data) || {};
134
- }
135
- catch (_a) {
136
- return {};
137
- }
138
- };
139
- const saveSession = (value, key) => {
140
- try {
141
- if (!sessionStorage) {
142
- return;
143
- }
144
- sessionStorage.setItem(key, JSON.stringify(value));
145
- }
146
- catch (_a) {
147
- console.log('Session storage not supported');
148
- }
149
- };
150
- const getSession = (key) => {
151
- try {
152
- if (!sessionStorage) {
153
- return {};
154
- }
155
- const data = sessionStorage.getItem(key);
156
- if (!data) {
157
- return {};
158
- }
159
- return JSON.parse(data) || {};
160
- }
161
- catch (_a) {
162
- return {};
163
- }
164
- };
165
-
166
40
  let endpointUrl = '';
167
41
  const generateUrl = (path) => {
168
42
  const endpoint = getUrl();
@@ -223,13 +97,18 @@ const setPreferences = (preferences) => {
223
97
  }
224
98
  providersPackages[provider.name] = provider;
225
99
  });
226
- if (window && Array.isArray(window.edgetagProviders)) {
227
- window.edgetagProviders.forEach((provider) => {
228
- if (!provider.name) {
229
- return;
230
- }
231
- providersPackages[provider.name] = provider;
232
- });
100
+ try {
101
+ if (window && Array.isArray(window.edgetagProviders)) {
102
+ window.edgetagProviders.forEach((provider) => {
103
+ if (!provider.name) {
104
+ return;
105
+ }
106
+ providersPackages[provider.name] = provider;
107
+ });
108
+ }
109
+ }
110
+ catch (_b) {
111
+ // do nothing
233
112
  }
234
113
  setUrl(preferences.edgeURL);
235
114
  return true;
@@ -245,44 +124,75 @@ const setAllowedProviders = (providers) => {
245
124
  allowedProvider = providers;
246
125
  };
247
126
 
248
- const getUserAgent = () => {
249
- const nav = navigator;
250
- let ua = nav.userAgent;
251
- ua += nav.brave ? `${ua} Brave` : '';
252
- return ua;
253
- };
254
- const allowTag = (providers) => {
255
- if (!allowProviders(providers)) {
256
- return false;
257
- }
258
- const consent = getDataPerKey('local', tagStorage, consentKey);
127
+ const checkConsent = (providers) => {
259
128
  if (isConsentDisabled()) {
260
129
  return true;
261
130
  }
131
+ const consent = getConsent();
262
132
  if (!consent) {
263
133
  return false;
264
134
  }
265
- if (consent['all']) {
266
- return true;
135
+ const consentLength = Object.keys(consent).length;
136
+ if (!consentLength || (consentLength === 1 && consent['all'] === false)) {
137
+ return false;
267
138
  }
268
- if (!providers) {
139
+ const providersLength = Object.keys(providers || {}).length;
140
+ if (!providers ||
141
+ providersLength === 0 ||
142
+ (providersLength === 1 && providers['all'])) {
269
143
  return (Object.values(consent).find((isAllowed) => isAllowed) || false);
270
144
  }
271
- const allProviders = getAllowedProviders();
272
- for (const provider of allProviders) {
273
- const tagProviderSetting = providers[provider];
274
- if (tagProviderSetting ||
275
- (providers['all'] === true && tagProviderSetting === undefined) ||
276
- (providers['all'] === false && tagProviderSetting === true)) {
277
- if (consent[provider]) {
145
+ for (const [key, value] of Object.entries(providers)) {
146
+ if (value === false || consent[key] === false) {
147
+ continue;
148
+ }
149
+ // we have consent
150
+ if (consent[key] ||
151
+ (consent['all'] === true && consent[key] === undefined)) {
152
+ // we have provider
153
+ if (value || (providers['all'] && providers[key] === undefined)) {
278
154
  return true;
279
155
  }
280
156
  }
281
157
  }
282
158
  return false;
283
159
  };
160
+ const getUserAgent = () => {
161
+ try {
162
+ const nav = navigator;
163
+ let ua = nav.userAgent;
164
+ ua += nav.brave ? `${ua} Brave` : '';
165
+ return ua;
166
+ }
167
+ catch (_a) {
168
+ return '';
169
+ }
170
+ };
171
+ const isProviderIncluded = (providers, providerValue) => {
172
+ return (providerValue || (providers['all'] === true && providerValue === undefined));
173
+ };
174
+ const allowTag = (providers) => {
175
+ if (!checkConsent(providers)) {
176
+ return false;
177
+ }
178
+ const providersLength = Object.values(providers || {}).length;
179
+ if (!providers || providersLength === 0) {
180
+ return true;
181
+ }
182
+ const allProviders = getAllowedProviders();
183
+ const allProvidersLength = Object.keys(allProviders || {}).length;
184
+ if (allProvidersLength === 0) {
185
+ return true;
186
+ }
187
+ for (const provider of allProviders) {
188
+ if (isProviderIncluded(providers, providers[provider])) {
189
+ return true;
190
+ }
191
+ }
192
+ return false;
193
+ };
284
194
  const allowProviders = (providers) => {
285
- if (!providers || Object.keys(providers).length === 0) {
195
+ if (!providers || Object.keys(providers).length === 0 || providers['all']) {
286
196
  return true;
287
197
  }
288
198
  const allowedProvider = getAllowedProviders();
@@ -314,41 +224,223 @@ const allowProviderWithConsent = (providers, providerId) => {
314
224
  if (!allowProvider(providerId)) {
315
225
  return false;
316
226
  }
227
+ if (!checkConsent(providers)) {
228
+ return false;
229
+ }
317
230
  if (providers && Object.keys(providers).length) {
318
- const tagProvider = providers[providerId];
319
- if (!(tagProvider ||
320
- (providers['all'] === true && tagProvider === undefined) ||
321
- (providers['all'] === false && tagProvider === true))) {
231
+ if (!isProviderIncluded(providers, providers[providerId])) {
322
232
  return false;
323
233
  }
324
234
  }
325
- const consent = getDataPerKey('local', tagStorage, consentKey);
326
- if (isConsentDisabled()) {
327
- return true;
235
+ return true;
236
+ };
237
+
238
+ const tagStorage = 'edgeTag';
239
+ const consentKey = 'consent';
240
+ const keyPrefix = `_worker`;
241
+
242
+ const initKey = `${keyPrefix}Store`;
243
+ const getCookieValue = (key) => {
244
+ try {
245
+ if (!document || !document.cookie) {
246
+ return '';
247
+ }
248
+ const name = `${key}=`;
249
+ const decodedCookie = decodeURIComponent(document.cookie);
250
+ const ca = decodedCookie.split(';');
251
+ for (let i = 0; i < ca.length; i++) {
252
+ let c = ca[i];
253
+ while (c.charAt(0) === ' ') {
254
+ c = c.substring(1);
255
+ }
256
+ if (c.indexOf(name) === 0) {
257
+ return c.substring(name.length, c.length);
258
+ }
259
+ }
260
+ return '';
328
261
  }
329
- if (!consent) {
330
- return false;
262
+ catch (_a) {
263
+ return '';
331
264
  }
332
- if (consent['all']) {
333
- return true;
265
+ };
266
+ const saveDataPerKey = (persistType, provider, value, key) => {
267
+ const storage = getData$1(persistType);
268
+ if (!storage['data']) {
269
+ storage['data'] = {};
270
+ }
271
+ if (!storage['data'][provider]) {
272
+ storage['data'][provider] = {};
273
+ }
274
+ storage['data'][provider][key] = value;
275
+ saveData(persistType, storage);
276
+ };
277
+ const savePerKey = (persistType, provider, value, key) => {
278
+ const storage = getData$1(persistType);
279
+ if (!storage[provider]) {
280
+ storage[provider] = {};
281
+ }
282
+ storage[provider][key] = value;
283
+ saveData(persistType, storage);
284
+ };
285
+ const getDataPerKey = (persistType, provider, key) => {
286
+ const storage = getData$1(persistType);
287
+ if (!storage[provider]) {
288
+ return undefined;
289
+ }
290
+ return storage[provider][key];
291
+ };
292
+ const saveData = (persistType, value, key = initKey) => {
293
+ if (persistType === 'session') {
294
+ saveSession(value, key);
295
+ return;
296
+ }
297
+ saveLocal(value, key);
298
+ };
299
+ const getData$1 = (persistType, key = initKey) => {
300
+ if (persistType === 'session') {
301
+ return getSession(key);
302
+ }
303
+ return getLocal(key);
304
+ };
305
+ const saveKV = (data) => {
306
+ let currentSession = getData$1('session');
307
+ if (!currentSession) {
308
+ currentSession = {};
309
+ }
310
+ if (!currentSession['kv']) {
311
+ currentSession['kv'] = {};
312
+ }
313
+ currentSession['kv'] = Object.assign(Object.assign({}, currentSession['kv']), data);
314
+ saveData('session', currentSession);
315
+ };
316
+ const saveLocal = (value, key) => {
317
+ try {
318
+ if (!localStorage) {
319
+ return;
320
+ }
321
+ localStorage.setItem(key, JSON.stringify(value));
322
+ }
323
+ catch (_a) {
324
+ console.log('Local storage not supported');
325
+ }
326
+ };
327
+ const getLocal = (key) => {
328
+ try {
329
+ if (!localStorage) {
330
+ return {};
331
+ }
332
+ const data = localStorage.getItem(key);
333
+ if (!data) {
334
+ return {};
335
+ }
336
+ return JSON.parse(data) || {};
337
+ }
338
+ catch (_a) {
339
+ return {};
340
+ }
341
+ };
342
+ const saveSession = (value, key) => {
343
+ try {
344
+ if (!sessionStorage) {
345
+ return;
346
+ }
347
+ sessionStorage.setItem(key, JSON.stringify(value));
348
+ }
349
+ catch (_a) {
350
+ console.log('Session storage not supported');
351
+ }
352
+ };
353
+ const getSession = (key) => {
354
+ try {
355
+ if (!sessionStorage) {
356
+ return {};
357
+ }
358
+ const data = sessionStorage.getItem(key);
359
+ if (!data) {
360
+ return {};
361
+ }
362
+ return JSON.parse(data) || {};
363
+ }
364
+ catch (_a) {
365
+ return {};
334
366
  }
335
- return consent[providerId];
336
367
  };
337
368
 
369
+ let initUserId = '';
370
+ const handleGetUserId = () => {
371
+ if (initUserId) {
372
+ return initUserId;
373
+ }
374
+ return getCookieValue('tag_user_id');
375
+ };
376
+ const setUserId = (userId) => {
377
+ initUserId = userId;
378
+ };
379
+
380
+ const getHeaders = () => ({
381
+ 'Content-type': 'application/json; charset=utf-8',
382
+ Accept: 'application/json; charset=utf-8',
383
+ EdgeTagUserId: handleGetUserId(),
384
+ });
338
385
  const beacon = (url, payload) => {
339
- let blob;
340
- if (payload) {
341
- blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
386
+ try {
387
+ let blob;
388
+ if (payload) {
389
+ blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
390
+ }
391
+ return navigator.sendBeacon(url, blob);
392
+ }
393
+ catch (e) {
394
+ console.log('Beacon not supported.');
395
+ return Promise.reject(new Error('Beacon not supported'));
342
396
  }
343
- return navigator.sendBeacon(url, blob);
344
397
  };
398
+ const fallbackAjax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
399
+ const https = yield import('https');
400
+ const options = {
401
+ method,
402
+ headers: getHeaders(),
403
+ };
404
+ return new Promise((resolve, reject) => {
405
+ const req = https.request(url, options, (res) => {
406
+ res.on('data', (data) => {
407
+ try {
408
+ data = JSON.parse(data);
409
+ }
410
+ catch (_a) {
411
+ // do nothing
412
+ }
413
+ resolve({
414
+ body: data,
415
+ status: res.statusCode || 500,
416
+ });
417
+ });
418
+ });
419
+ req.on('error', (e) => {
420
+ reject(new Error(e.message));
421
+ });
422
+ if (payload && method !== 'GET') {
423
+ req.write(JSON.stringify(payload));
424
+ }
425
+ req.end();
426
+ });
427
+ });
345
428
  const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
429
+ if (typeof fetch === 'undefined') {
430
+ return yield fallbackAjax(method, url, payload)
431
+ .then((data) => {
432
+ if (data.status < 200 || data.status >= 300) {
433
+ return Promise.reject(new Error(JSON.stringify(data.body)));
434
+ }
435
+ return Promise.resolve(data.body);
436
+ })
437
+ .catch((error) => {
438
+ return Promise.reject(new Error(error));
439
+ });
440
+ }
346
441
  return yield fetch(url, {
347
442
  method,
348
- headers: {
349
- 'Content-type': 'application/json; charset=utf-8',
350
- Accept: 'application/json; charset=utf-8',
351
- },
443
+ headers: getHeaders(),
352
444
  body: JSON.stringify(payload),
353
445
  credentials: 'include',
354
446
  })
@@ -366,7 +458,14 @@ const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, functio
366
458
  });
367
459
  });
368
460
  const getStandardPayload = (payload) => {
369
- const data = Object.assign({ pageUrl: window.location.href, userAgent: getUserAgent() }, (payload || {}));
461
+ let pageUrl;
462
+ try {
463
+ pageUrl = window.location.href;
464
+ }
465
+ catch (_a) {
466
+ pageUrl = '';
467
+ }
468
+ const data = Object.assign({ pageUrl, userAgent: getUserAgent() }, (payload || {}));
370
469
  let storage = {};
371
470
  const session = getData$1('session');
372
471
  if (session) {
@@ -408,7 +507,9 @@ function getRequest(url, options) {
408
507
  const info = (data) => {
409
508
  };
410
509
 
510
+ let memoryConsent;
411
511
  const saveConsent = (consent) => {
512
+ setConsent(consent);
412
513
  savePerKey('local', tagStorage, consent, consentKey);
413
514
  };
414
515
  const handleConsent = (consent) => {
@@ -418,7 +519,23 @@ const handleConsent = (consent) => {
418
519
  saveConsent(consent);
419
520
  postRequest(getConsentURL(), payload).catch(info);
420
521
  };
522
+ const setConsent = (newConsent) => {
523
+ memoryConsent = newConsent;
524
+ };
525
+ const getConsent = () => {
526
+ const storageConsent = getDataPerKey('local', tagStorage, consentKey);
527
+ if (storageConsent) {
528
+ return storageConsent;
529
+ }
530
+ return memoryConsent;
531
+ };
421
532
 
533
+ const encodeString = (name) => {
534
+ if (typeof btoa === 'undefined') {
535
+ return Buffer.from(name).toString('base64');
536
+ }
537
+ return btoa(name);
538
+ };
422
539
  const generateEventId = (name) => {
423
540
  let time = Date.now().toString();
424
541
  if (typeof performance !== 'undefined' &&
@@ -428,11 +545,7 @@ const generateEventId = (name) => {
428
545
  time = perf.toFixed(4);
429
546
  }
430
547
  }
431
- return `${btoa(name)}-${v4()}-${time}`;
432
- };
433
-
434
- const handleGetUserId = () => {
435
- return getCookieValue('tag_user_id');
548
+ return `${encodeString(name)}-${v4()}-${time}`;
436
549
  };
437
550
 
438
551
  const manifestVariables = {};
@@ -453,6 +566,7 @@ const processStubs = () => {
453
566
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
454
567
  // @ts-ignore
455
568
  stubs.forEach((stub) => api[stub.name](...(stub.arguments || [])));
569
+ stubs = [];
456
570
  }
457
571
  catch (e) {
458
572
  console.error(e);
@@ -461,6 +575,7 @@ const processStubs = () => {
461
575
 
462
576
  const sendTag = ({ eventName, eventId, data, providerData, providers, options, }) => {
463
577
  if (!allowProviders(providers)) {
578
+ console.log('Provider is not allowed.');
464
579
  return;
465
580
  }
466
581
  const payload = {
@@ -483,6 +598,10 @@ const handleTag = (eventName, data = {}, providers, options) => {
483
598
  });
484
599
  return;
485
600
  }
601
+ if (!allowProviders(providers)) {
602
+ console.log('Provider is not allowed.');
603
+ return;
604
+ }
486
605
  if (!allowTag(providers)) {
487
606
  console.log('No consent');
488
607
  return;
@@ -547,7 +666,12 @@ const saveDataToEdge = (key, value, provider) => {
547
666
  handleData({ [`${provider}::${key}`]: value });
548
667
  };
549
668
  const handleCaptureQuery = (provider, key, persistType) => {
550
- if (!window) {
669
+ try {
670
+ if (!window) {
671
+ return;
672
+ }
673
+ }
674
+ catch (_a) {
551
675
  return;
552
676
  }
553
677
  const params = new URLSearchParams(window.location.search);
@@ -649,6 +773,7 @@ const handleInit = (preferences) => {
649
773
  saveConsent({ all: true });
650
774
  }
651
775
  if (preferences.userId) {
776
+ setUserId(preferences.userId);
652
777
  url.searchParams.set('userId', preferences.userId);
653
778
  }
654
779
  getRequest(url.href)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotoutio/edgetag-sdk-js",
3
- "version": "0.6.9",
3
+ "version": "0.7.1",
4
4
  "description": "JS SDK for EdgeTag",
5
5
  "author": "Blotout",
6
6
  "license": "MIT",