@blotoutio/edgetag-sdk-js 0.7.0 → 0.7.2

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 +172 -64
  3. package/index.esm.js +154 -64
  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,11 +59,32 @@ function __awaiter(thisArg, _arguments, P, generator) {
41
59
  });
42
60
  }
43
61
 
62
+ const getMessage = (error) => {
63
+ if (error instanceof Error) {
64
+ return error.message;
65
+ }
66
+ if (typeof error === 'string') {
67
+ return error;
68
+ }
69
+ try {
70
+ return JSON.stringify(error);
71
+ }
72
+ catch (_a) {
73
+ return error;
74
+ }
75
+ };
76
+ const log = (data) => {
77
+ console.log('[EdgeTag]', getMessage(data));
78
+ };
79
+ const error = (data) => {
80
+ console.error('[EdgeTag]', getMessage(data));
81
+ };
82
+
44
83
  let endpointUrl = '';
45
84
  const generateUrl = (path) => {
46
85
  const endpoint = getUrl();
47
86
  if (!endpoint) {
48
- console.log('URL is not valid');
87
+ log('URL is not valid');
49
88
  return '';
50
89
  }
51
90
  return `${endpoint}${path}`;
@@ -91,7 +130,7 @@ const setPreferences = (preferences) => {
91
130
  return false;
92
131
  }
93
132
  if (!preferences.edgeURL) {
94
- console.error('Please provide URL for EdgeTag');
133
+ error('Please provide URL for EdgeTag');
95
134
  return false;
96
135
  }
97
136
  consentDisabled = !!preferences.disableConsentCheck;
@@ -128,6 +167,39 @@ const setAllowedProviders = (providers) => {
128
167
  allowedProvider = providers;
129
168
  };
130
169
 
170
+ const checkConsent = (providers) => {
171
+ if (isConsentDisabled()) {
172
+ return true;
173
+ }
174
+ const consent = getConsent();
175
+ if (!consent) {
176
+ return false;
177
+ }
178
+ const consentLength = Object.keys(consent).length;
179
+ if (!consentLength || (consentLength === 1 && consent['all'] === false)) {
180
+ return false;
181
+ }
182
+ const providersLength = Object.keys(providers || {}).length;
183
+ if (!providers ||
184
+ providersLength === 0 ||
185
+ (providersLength === 1 && providers['all'])) {
186
+ return (Object.values(consent).find((isAllowed) => isAllowed) || false);
187
+ }
188
+ for (const [key, value] of Object.entries(providers)) {
189
+ if (value === false || consent[key] === false) {
190
+ continue;
191
+ }
192
+ // we have consent
193
+ if (consent[key] ||
194
+ (consent['all'] === true && consent[key] === undefined)) {
195
+ // we have provider
196
+ if (value || (providers['all'] && providers[key] === undefined)) {
197
+ return true;
198
+ }
199
+ }
200
+ }
201
+ return false;
202
+ };
131
203
  const getUserAgent = () => {
132
204
  try {
133
205
  const nav = navigator;
@@ -143,23 +215,20 @@ const isProviderIncluded = (providers, providerValue) => {
143
215
  return (providerValue || (providers['all'] === true && providerValue === undefined));
144
216
  };
145
217
  const allowTag = (providers) => {
146
- const consent = getConsent();
147
- if (isConsentDisabled()) {
148
- return true;
149
- }
150
- if (!consent) {
218
+ if (!checkConsent(providers)) {
151
219
  return false;
152
220
  }
153
- if (consent['all']) {
221
+ const providersLength = Object.values(providers || {}).length;
222
+ if (!providers || providersLength === 0) {
154
223
  return true;
155
224
  }
156
- if (!providers) {
157
- return (Object.values(consent).find((isAllowed) => isAllowed) || false);
158
- }
159
225
  const allProviders = getAllowedProviders();
226
+ const allProvidersLength = Object.keys(allProviders || {}).length;
227
+ if (allProvidersLength === 0) {
228
+ return true;
229
+ }
160
230
  for (const provider of allProviders) {
161
- if (isProviderIncluded(providers, !!providers[provider]) &&
162
- consent[provider]) {
231
+ if (isProviderIncluded(providers, providers[provider])) {
163
232
  return true;
164
233
  }
165
234
  }
@@ -198,25 +267,15 @@ const allowProviderWithConsent = (providers, providerId) => {
198
267
  if (!allowProvider(providerId)) {
199
268
  return false;
200
269
  }
270
+ if (!checkConsent(providers)) {
271
+ return false;
272
+ }
201
273
  if (providers && Object.keys(providers).length) {
202
- const tagProvider = providers[providerId];
203
- if (!(tagProvider ||
204
- (providers['all'] === true && tagProvider === undefined) ||
205
- (providers['all'] === false && tagProvider === true))) {
274
+ if (!isProviderIncluded(providers, providers[providerId])) {
206
275
  return false;
207
276
  }
208
277
  }
209
- const consent = getConsent();
210
- if (isConsentDisabled()) {
211
- return true;
212
- }
213
- if (!consent) {
214
- return false;
215
- }
216
- if (consent['all']) {
217
- return true;
218
- }
219
- return consent[providerId];
278
+ return true;
220
279
  };
221
280
 
222
281
  const tagStorage = 'edgeTag';
@@ -305,7 +364,7 @@ const saveLocal = (value, key) => {
305
364
  localStorage.setItem(key, JSON.stringify(value));
306
365
  }
307
366
  catch (_a) {
308
- console.log('Local storage not supported');
367
+ log('Local storage not supported.');
309
368
  }
310
369
  };
311
370
  const getLocal = (key) => {
@@ -331,7 +390,7 @@ const saveSession = (value, key) => {
331
390
  sessionStorage.setItem(key, JSON.stringify(value));
332
391
  }
333
392
  catch (_a) {
334
- console.log('Session storage not supported');
393
+ log('Session storage not supported.');
335
394
  }
336
395
  };
337
396
  const getSession = (key) => {
@@ -361,34 +420,80 @@ const setUserId = (userId) => {
361
420
  initUserId = userId;
362
421
  };
363
422
 
423
+ const getHeaders = () => ({
424
+ 'Content-type': 'application/json; charset=utf-8',
425
+ Accept: 'application/json; charset=utf-8',
426
+ EdgeTagUserId: handleGetUserId(),
427
+ });
364
428
  const beacon = (url, payload) => {
365
- let blob;
366
- if (payload) {
367
- blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
429
+ try {
430
+ let blob;
431
+ if (payload) {
432
+ blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
433
+ }
434
+ return navigator.sendBeacon(url, blob);
435
+ }
436
+ catch (e) {
437
+ return Promise.reject(new Error('Beacon not supported.'));
368
438
  }
369
- return navigator.sendBeacon(url, blob);
370
439
  };
440
+ const fallbackAjax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
441
+ const https = yield Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('https')); });
442
+ const options = {
443
+ method,
444
+ headers: getHeaders(),
445
+ };
446
+ return new Promise((resolve, reject) => {
447
+ const req = https.request(url, options, (res) => {
448
+ res.on('data', (data) => {
449
+ try {
450
+ data = JSON.parse(data);
451
+ }
452
+ catch (_a) {
453
+ // do nothing
454
+ }
455
+ resolve({
456
+ body: data,
457
+ status: res.statusCode || 500,
458
+ });
459
+ });
460
+ });
461
+ req.on('error', (e) => {
462
+ reject(new Error(e.message));
463
+ });
464
+ if (payload && method !== 'GET') {
465
+ req.write(JSON.stringify(payload));
466
+ }
467
+ req.end();
468
+ });
469
+ });
371
470
  const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
471
+ if (typeof fetch === 'undefined') {
472
+ return yield fallbackAjax(method, url, payload)
473
+ .then((data) => {
474
+ if (data.status < 200 || data.status >= 300) {
475
+ return Promise.reject(new Error(`Request failed with code ${data.status} occurred: ${JSON.stringify(data.body)}`));
476
+ }
477
+ return Promise.resolve(data.body);
478
+ })
479
+ .catch((error) => {
480
+ return Promise.reject(new Error(error));
481
+ });
482
+ }
372
483
  return yield fetch(url, {
373
484
  method,
374
- headers: {
375
- 'Content-type': 'application/json; charset=utf-8',
376
- Accept: 'application/json; charset=utf-8',
377
- EdgeTagUserId: handleGetUserId(),
378
- },
485
+ headers: getHeaders(),
379
486
  body: JSON.stringify(payload),
380
487
  credentials: 'include',
381
488
  })
382
489
  .then((response) => response.json().then((data) => ({ status: response.status, body: data })))
383
490
  .then((data) => {
384
491
  if (data.status < 200 || data.status >= 300) {
385
- // Q: do we need to retry?
386
- return Promise.reject(new Error(JSON.stringify(data.body)));
492
+ return Promise.reject(new Error(`Request failed with code ${data.status}: ${JSON.stringify(data.body)}`));
387
493
  }
388
494
  return Promise.resolve(data.body);
389
495
  })
390
496
  .catch((error) => {
391
- // Q: do we need to retry?
392
497
  return Promise.reject(new Error(error));
393
498
  });
394
499
  });
@@ -416,7 +521,7 @@ const getStandardPayload = (payload) => {
416
521
  function postRequest(url, data, options) {
417
522
  return __awaiter(this, void 0, void 0, function* () {
418
523
  if (!url) {
419
- return Promise.reject(new Error('URL is empty'));
524
+ return Promise.reject(new Error('URL is empty.'));
420
525
  }
421
526
  const payload = getStandardPayload(data);
422
527
  if (options && options.method === 'beacon') {
@@ -428,7 +533,7 @@ function postRequest(url, data, options) {
428
533
  function getRequest(url, options) {
429
534
  return __awaiter(this, void 0, void 0, function* () {
430
535
  if (!url) {
431
- return Promise.reject(new Error('URL is empty'));
536
+ return Promise.reject(new Error('URL is empty.'));
432
537
  }
433
538
  if (options && options.method === 'beacon') {
434
539
  return {
@@ -439,9 +544,6 @@ function getRequest(url, options) {
439
544
  });
440
545
  }
441
546
 
442
- const info = (data) => {
443
- };
444
-
445
547
  let memoryConsent;
446
548
  const saveConsent = (consent) => {
447
549
  setConsent(consent);
@@ -452,7 +554,7 @@ const handleConsent = (consent) => {
452
554
  consentString: consent,
453
555
  };
454
556
  saveConsent(consent);
455
- postRequest(getConsentURL(), payload).catch(info);
557
+ postRequest(getConsentURL(), payload).catch(error);
456
558
  };
457
559
  const setConsent = (newConsent) => {
458
560
  memoryConsent = newConsent;
@@ -465,6 +567,12 @@ const getConsent = () => {
465
567
  return memoryConsent;
466
568
  };
467
569
 
570
+ const encodeString = (name) => {
571
+ if (typeof btoa === 'undefined') {
572
+ return Buffer.from(name).toString('base64');
573
+ }
574
+ return btoa(name);
575
+ };
468
576
  const generateEventId = (name) => {
469
577
  let time = Date.now().toString();
470
578
  if (typeof performance !== 'undefined' &&
@@ -474,7 +582,7 @@ const generateEventId = (name) => {
474
582
  time = perf.toFixed(4);
475
583
  }
476
584
  }
477
- return `${btoa(name)}-${uuid.v4()}-${time}`;
585
+ return `${encodeString(name)}-${uuid.v4()}-${time}`;
478
586
  };
479
587
 
480
588
  const manifestVariables = {};
@@ -498,13 +606,13 @@ const processStubs = () => {
498
606
  stubs = [];
499
607
  }
500
608
  catch (e) {
501
- console.error(e);
609
+ error(e);
502
610
  }
503
611
  };
504
612
 
505
613
  const sendTag = ({ eventName, eventId, data, providerData, providers, options, }) => {
506
614
  if (!allowProviders(providers)) {
507
- console.log('Provider is not allowed.');
615
+ log('Provider is not allowed.');
508
616
  return;
509
617
  }
510
618
  const payload = {
@@ -517,7 +625,7 @@ const sendTag = ({ eventName, eventId, data, providerData, providers, options, }
517
625
  if (providers) {
518
626
  payload.providers = providers;
519
627
  }
520
- postRequest(getTagURL(), payload, options).catch(info);
628
+ postRequest(getTagURL(), payload, options).catch(error);
521
629
  };
522
630
  const handleTag = (eventName, data = {}, providers, options) => {
523
631
  if (!isInitialized()) {
@@ -528,11 +636,11 @@ const handleTag = (eventName, data = {}, providers, options) => {
528
636
  return;
529
637
  }
530
638
  if (!allowProviders(providers)) {
531
- console.log('Provider is not allowed.');
639
+ log('Provider is not allowed.');
532
640
  return;
533
641
  }
534
642
  if (!allowTag(providers)) {
535
- console.log('No consent');
643
+ log('Consent is missing.');
536
644
  return;
537
645
  }
538
646
  let eventId = data['eventId'];
@@ -572,11 +680,11 @@ const handleTag = (eventName, data = {}, providers, options) => {
572
680
 
573
681
  const handleData = (data, options) => {
574
682
  if (!data || Object.keys(data).length === 0) {
575
- console.error('Provide data for data API.');
683
+ error('Provide data for data API.');
576
684
  return;
577
685
  }
578
686
  saveKV(data);
579
- postRequest(getDataURL(), { data }, options).catch(info);
687
+ postRequest(getDataURL(), { data }, options).catch(error);
580
688
  };
581
689
 
582
690
  const saveDataToEdge = (key, value, provider) => {
@@ -588,7 +696,7 @@ const saveDataToEdge = (key, value, provider) => {
588
696
  value = JSON.stringify(value);
589
697
  }
590
698
  catch (_a) {
591
- console.log('Error stringify value');
699
+ log('Error stringify value.');
592
700
  return;
593
701
  }
594
702
  }
@@ -708,17 +816,17 @@ const handleInit = (preferences) => {
708
816
  getRequest(url.href)
709
817
  .then((result) => {
710
818
  if (!result) {
711
- console.log('init failed');
819
+ log('Initialization failed');
712
820
  return;
713
821
  }
714
822
  handleManifest(result.result);
715
823
  })
716
- .catch(info);
824
+ .catch(error);
717
825
  };
718
826
 
719
827
  const handleUser = (key, value, options) => {
720
828
  if (!key || !value) {
721
- console.error('Key or Value is missing in user API.');
829
+ error('Key or Value is missing in user API.');
722
830
  return;
723
831
  }
724
832
  saveKV({
@@ -727,19 +835,19 @@ const handleUser = (key, value, options) => {
727
835
  postRequest(getUserURL(), {
728
836
  key,
729
837
  value,
730
- }, options).catch(info);
838
+ }, options).catch(error);
731
839
  };
732
840
 
733
841
  const handleGetData = (keys, callback) => {
734
842
  if (!keys || keys.length === 0) {
735
- console.error('Provide keys for get data API.');
843
+ error('Provide keys for get data API.');
736
844
  return;
737
845
  }
738
846
  getRequest(getGetDataURL(keys))
739
847
  .then((result) => {
740
848
  callback((result === null || result === void 0 ? void 0 : result.result) || {});
741
849
  })
742
- .catch(info);
850
+ .catch(error);
743
851
  };
744
852
 
745
853
  const handleKeys = (callback) => {
@@ -747,7 +855,7 @@ const handleKeys = (callback) => {
747
855
  .then((result) => {
748
856
  callback((result === null || result === void 0 ? void 0 : result.result) || []);
749
857
  })
750
- .catch(info);
858
+ .catch(error);
751
859
  };
752
860
 
753
861
  const init = (preferences) => {
package/index.esm.js CHANGED
@@ -37,11 +37,32 @@ function __awaiter(thisArg, _arguments, P, generator) {
37
37
  });
38
38
  }
39
39
 
40
+ const getMessage = (error) => {
41
+ if (error instanceof Error) {
42
+ return error.message;
43
+ }
44
+ if (typeof error === 'string') {
45
+ return error;
46
+ }
47
+ try {
48
+ return JSON.stringify(error);
49
+ }
50
+ catch (_a) {
51
+ return error;
52
+ }
53
+ };
54
+ const log = (data) => {
55
+ console.log('[EdgeTag]', getMessage(data));
56
+ };
57
+ const error = (data) => {
58
+ console.error('[EdgeTag]', getMessage(data));
59
+ };
60
+
40
61
  let endpointUrl = '';
41
62
  const generateUrl = (path) => {
42
63
  const endpoint = getUrl();
43
64
  if (!endpoint) {
44
- console.log('URL is not valid');
65
+ log('URL is not valid');
45
66
  return '';
46
67
  }
47
68
  return `${endpoint}${path}`;
@@ -87,7 +108,7 @@ const setPreferences = (preferences) => {
87
108
  return false;
88
109
  }
89
110
  if (!preferences.edgeURL) {
90
- console.error('Please provide URL for EdgeTag');
111
+ error('Please provide URL for EdgeTag');
91
112
  return false;
92
113
  }
93
114
  consentDisabled = !!preferences.disableConsentCheck;
@@ -124,6 +145,39 @@ const setAllowedProviders = (providers) => {
124
145
  allowedProvider = providers;
125
146
  };
126
147
 
148
+ const checkConsent = (providers) => {
149
+ if (isConsentDisabled()) {
150
+ return true;
151
+ }
152
+ const consent = getConsent();
153
+ if (!consent) {
154
+ return false;
155
+ }
156
+ const consentLength = Object.keys(consent).length;
157
+ if (!consentLength || (consentLength === 1 && consent['all'] === false)) {
158
+ return false;
159
+ }
160
+ const providersLength = Object.keys(providers || {}).length;
161
+ if (!providers ||
162
+ providersLength === 0 ||
163
+ (providersLength === 1 && providers['all'])) {
164
+ return (Object.values(consent).find((isAllowed) => isAllowed) || false);
165
+ }
166
+ for (const [key, value] of Object.entries(providers)) {
167
+ if (value === false || consent[key] === false) {
168
+ continue;
169
+ }
170
+ // we have consent
171
+ if (consent[key] ||
172
+ (consent['all'] === true && consent[key] === undefined)) {
173
+ // we have provider
174
+ if (value || (providers['all'] && providers[key] === undefined)) {
175
+ return true;
176
+ }
177
+ }
178
+ }
179
+ return false;
180
+ };
127
181
  const getUserAgent = () => {
128
182
  try {
129
183
  const nav = navigator;
@@ -139,23 +193,20 @@ const isProviderIncluded = (providers, providerValue) => {
139
193
  return (providerValue || (providers['all'] === true && providerValue === undefined));
140
194
  };
141
195
  const allowTag = (providers) => {
142
- const consent = getConsent();
143
- if (isConsentDisabled()) {
144
- return true;
145
- }
146
- if (!consent) {
196
+ if (!checkConsent(providers)) {
147
197
  return false;
148
198
  }
149
- if (consent['all']) {
199
+ const providersLength = Object.values(providers || {}).length;
200
+ if (!providers || providersLength === 0) {
150
201
  return true;
151
202
  }
152
- if (!providers) {
153
- return (Object.values(consent).find((isAllowed) => isAllowed) || false);
154
- }
155
203
  const allProviders = getAllowedProviders();
204
+ const allProvidersLength = Object.keys(allProviders || {}).length;
205
+ if (allProvidersLength === 0) {
206
+ return true;
207
+ }
156
208
  for (const provider of allProviders) {
157
- if (isProviderIncluded(providers, !!providers[provider]) &&
158
- consent[provider]) {
209
+ if (isProviderIncluded(providers, providers[provider])) {
159
210
  return true;
160
211
  }
161
212
  }
@@ -194,25 +245,15 @@ const allowProviderWithConsent = (providers, providerId) => {
194
245
  if (!allowProvider(providerId)) {
195
246
  return false;
196
247
  }
248
+ if (!checkConsent(providers)) {
249
+ return false;
250
+ }
197
251
  if (providers && Object.keys(providers).length) {
198
- const tagProvider = providers[providerId];
199
- if (!(tagProvider ||
200
- (providers['all'] === true && tagProvider === undefined) ||
201
- (providers['all'] === false && tagProvider === true))) {
252
+ if (!isProviderIncluded(providers, providers[providerId])) {
202
253
  return false;
203
254
  }
204
255
  }
205
- const consent = getConsent();
206
- if (isConsentDisabled()) {
207
- return true;
208
- }
209
- if (!consent) {
210
- return false;
211
- }
212
- if (consent['all']) {
213
- return true;
214
- }
215
- return consent[providerId];
256
+ return true;
216
257
  };
217
258
 
218
259
  const tagStorage = 'edgeTag';
@@ -301,7 +342,7 @@ const saveLocal = (value, key) => {
301
342
  localStorage.setItem(key, JSON.stringify(value));
302
343
  }
303
344
  catch (_a) {
304
- console.log('Local storage not supported');
345
+ log('Local storage not supported.');
305
346
  }
306
347
  };
307
348
  const getLocal = (key) => {
@@ -327,7 +368,7 @@ const saveSession = (value, key) => {
327
368
  sessionStorage.setItem(key, JSON.stringify(value));
328
369
  }
329
370
  catch (_a) {
330
- console.log('Session storage not supported');
371
+ log('Session storage not supported.');
331
372
  }
332
373
  };
333
374
  const getSession = (key) => {
@@ -357,34 +398,80 @@ const setUserId = (userId) => {
357
398
  initUserId = userId;
358
399
  };
359
400
 
401
+ const getHeaders = () => ({
402
+ 'Content-type': 'application/json; charset=utf-8',
403
+ Accept: 'application/json; charset=utf-8',
404
+ EdgeTagUserId: handleGetUserId(),
405
+ });
360
406
  const beacon = (url, payload) => {
361
- let blob;
362
- if (payload) {
363
- blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
407
+ try {
408
+ let blob;
409
+ if (payload) {
410
+ blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
411
+ }
412
+ return navigator.sendBeacon(url, blob);
413
+ }
414
+ catch (e) {
415
+ return Promise.reject(new Error('Beacon not supported.'));
364
416
  }
365
- return navigator.sendBeacon(url, blob);
366
417
  };
418
+ const fallbackAjax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
419
+ const https = yield import('https');
420
+ const options = {
421
+ method,
422
+ headers: getHeaders(),
423
+ };
424
+ return new Promise((resolve, reject) => {
425
+ const req = https.request(url, options, (res) => {
426
+ res.on('data', (data) => {
427
+ try {
428
+ data = JSON.parse(data);
429
+ }
430
+ catch (_a) {
431
+ // do nothing
432
+ }
433
+ resolve({
434
+ body: data,
435
+ status: res.statusCode || 500,
436
+ });
437
+ });
438
+ });
439
+ req.on('error', (e) => {
440
+ reject(new Error(e.message));
441
+ });
442
+ if (payload && method !== 'GET') {
443
+ req.write(JSON.stringify(payload));
444
+ }
445
+ req.end();
446
+ });
447
+ });
367
448
  const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
449
+ if (typeof fetch === 'undefined') {
450
+ return yield fallbackAjax(method, url, payload)
451
+ .then((data) => {
452
+ if (data.status < 200 || data.status >= 300) {
453
+ return Promise.reject(new Error(`Request failed with code ${data.status} occurred: ${JSON.stringify(data.body)}`));
454
+ }
455
+ return Promise.resolve(data.body);
456
+ })
457
+ .catch((error) => {
458
+ return Promise.reject(new Error(error));
459
+ });
460
+ }
368
461
  return yield fetch(url, {
369
462
  method,
370
- headers: {
371
- 'Content-type': 'application/json; charset=utf-8',
372
- Accept: 'application/json; charset=utf-8',
373
- EdgeTagUserId: handleGetUserId(),
374
- },
463
+ headers: getHeaders(),
375
464
  body: JSON.stringify(payload),
376
465
  credentials: 'include',
377
466
  })
378
467
  .then((response) => response.json().then((data) => ({ status: response.status, body: data })))
379
468
  .then((data) => {
380
469
  if (data.status < 200 || data.status >= 300) {
381
- // Q: do we need to retry?
382
- return Promise.reject(new Error(JSON.stringify(data.body)));
470
+ return Promise.reject(new Error(`Request failed with code ${data.status}: ${JSON.stringify(data.body)}`));
383
471
  }
384
472
  return Promise.resolve(data.body);
385
473
  })
386
474
  .catch((error) => {
387
- // Q: do we need to retry?
388
475
  return Promise.reject(new Error(error));
389
476
  });
390
477
  });
@@ -412,7 +499,7 @@ const getStandardPayload = (payload) => {
412
499
  function postRequest(url, data, options) {
413
500
  return __awaiter(this, void 0, void 0, function* () {
414
501
  if (!url) {
415
- return Promise.reject(new Error('URL is empty'));
502
+ return Promise.reject(new Error('URL is empty.'));
416
503
  }
417
504
  const payload = getStandardPayload(data);
418
505
  if (options && options.method === 'beacon') {
@@ -424,7 +511,7 @@ function postRequest(url, data, options) {
424
511
  function getRequest(url, options) {
425
512
  return __awaiter(this, void 0, void 0, function* () {
426
513
  if (!url) {
427
- return Promise.reject(new Error('URL is empty'));
514
+ return Promise.reject(new Error('URL is empty.'));
428
515
  }
429
516
  if (options && options.method === 'beacon') {
430
517
  return {
@@ -435,9 +522,6 @@ function getRequest(url, options) {
435
522
  });
436
523
  }
437
524
 
438
- const info = (data) => {
439
- };
440
-
441
525
  let memoryConsent;
442
526
  const saveConsent = (consent) => {
443
527
  setConsent(consent);
@@ -448,7 +532,7 @@ const handleConsent = (consent) => {
448
532
  consentString: consent,
449
533
  };
450
534
  saveConsent(consent);
451
- postRequest(getConsentURL(), payload).catch(info);
535
+ postRequest(getConsentURL(), payload).catch(error);
452
536
  };
453
537
  const setConsent = (newConsent) => {
454
538
  memoryConsent = newConsent;
@@ -461,6 +545,12 @@ const getConsent = () => {
461
545
  return memoryConsent;
462
546
  };
463
547
 
548
+ const encodeString = (name) => {
549
+ if (typeof btoa === 'undefined') {
550
+ return Buffer.from(name).toString('base64');
551
+ }
552
+ return btoa(name);
553
+ };
464
554
  const generateEventId = (name) => {
465
555
  let time = Date.now().toString();
466
556
  if (typeof performance !== 'undefined' &&
@@ -470,7 +560,7 @@ const generateEventId = (name) => {
470
560
  time = perf.toFixed(4);
471
561
  }
472
562
  }
473
- return `${btoa(name)}-${v4()}-${time}`;
563
+ return `${encodeString(name)}-${v4()}-${time}`;
474
564
  };
475
565
 
476
566
  const manifestVariables = {};
@@ -494,13 +584,13 @@ const processStubs = () => {
494
584
  stubs = [];
495
585
  }
496
586
  catch (e) {
497
- console.error(e);
587
+ error(e);
498
588
  }
499
589
  };
500
590
 
501
591
  const sendTag = ({ eventName, eventId, data, providerData, providers, options, }) => {
502
592
  if (!allowProviders(providers)) {
503
- console.log('Provider is not allowed.');
593
+ log('Provider is not allowed.');
504
594
  return;
505
595
  }
506
596
  const payload = {
@@ -513,7 +603,7 @@ const sendTag = ({ eventName, eventId, data, providerData, providers, options, }
513
603
  if (providers) {
514
604
  payload.providers = providers;
515
605
  }
516
- postRequest(getTagURL(), payload, options).catch(info);
606
+ postRequest(getTagURL(), payload, options).catch(error);
517
607
  };
518
608
  const handleTag = (eventName, data = {}, providers, options) => {
519
609
  if (!isInitialized()) {
@@ -524,11 +614,11 @@ const handleTag = (eventName, data = {}, providers, options) => {
524
614
  return;
525
615
  }
526
616
  if (!allowProviders(providers)) {
527
- console.log('Provider is not allowed.');
617
+ log('Provider is not allowed.');
528
618
  return;
529
619
  }
530
620
  if (!allowTag(providers)) {
531
- console.log('No consent');
621
+ log('Consent is missing.');
532
622
  return;
533
623
  }
534
624
  let eventId = data['eventId'];
@@ -568,11 +658,11 @@ const handleTag = (eventName, data = {}, providers, options) => {
568
658
 
569
659
  const handleData = (data, options) => {
570
660
  if (!data || Object.keys(data).length === 0) {
571
- console.error('Provide data for data API.');
661
+ error('Provide data for data API.');
572
662
  return;
573
663
  }
574
664
  saveKV(data);
575
- postRequest(getDataURL(), { data }, options).catch(info);
665
+ postRequest(getDataURL(), { data }, options).catch(error);
576
666
  };
577
667
 
578
668
  const saveDataToEdge = (key, value, provider) => {
@@ -584,7 +674,7 @@ const saveDataToEdge = (key, value, provider) => {
584
674
  value = JSON.stringify(value);
585
675
  }
586
676
  catch (_a) {
587
- console.log('Error stringify value');
677
+ log('Error stringify value.');
588
678
  return;
589
679
  }
590
680
  }
@@ -704,17 +794,17 @@ const handleInit = (preferences) => {
704
794
  getRequest(url.href)
705
795
  .then((result) => {
706
796
  if (!result) {
707
- console.log('init failed');
797
+ log('Initialization failed');
708
798
  return;
709
799
  }
710
800
  handleManifest(result.result);
711
801
  })
712
- .catch(info);
802
+ .catch(error);
713
803
  };
714
804
 
715
805
  const handleUser = (key, value, options) => {
716
806
  if (!key || !value) {
717
- console.error('Key or Value is missing in user API.');
807
+ error('Key or Value is missing in user API.');
718
808
  return;
719
809
  }
720
810
  saveKV({
@@ -723,19 +813,19 @@ const handleUser = (key, value, options) => {
723
813
  postRequest(getUserURL(), {
724
814
  key,
725
815
  value,
726
- }, options).catch(info);
816
+ }, options).catch(error);
727
817
  };
728
818
 
729
819
  const handleGetData = (keys, callback) => {
730
820
  if (!keys || keys.length === 0) {
731
- console.error('Provide keys for get data API.');
821
+ error('Provide keys for get data API.');
732
822
  return;
733
823
  }
734
824
  getRequest(getGetDataURL(keys))
735
825
  .then((result) => {
736
826
  callback((result === null || result === void 0 ? void 0 : result.result) || {});
737
827
  })
738
- .catch(info);
828
+ .catch(error);
739
829
  };
740
830
 
741
831
  const handleKeys = (callback) => {
@@ -743,7 +833,7 @@ const handleKeys = (callback) => {
743
833
  .then((result) => {
744
834
  callback((result === null || result === void 0 ? void 0 : result.result) || []);
745
835
  })
746
- .catch(info);
836
+ .catch(error);
747
837
  };
748
838
 
749
839
  const init = (preferences) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotoutio/edgetag-sdk-js",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "JS SDK for EdgeTag",
5
5
  "author": "Blotout",
6
6
  "license": "MIT",