@blotoutio/edgetag-sdk-browser 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +269 -204
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -190,6 +190,43 @@
190
190
  return '';
191
191
  }
192
192
  };
193
+ const getReferrer = () => {
194
+ let referrer = '';
195
+ try {
196
+ const referrerUrl = new URL(document.referrer);
197
+ if (referrerUrl.host !== window.location.host) {
198
+ referrer = referrerUrl.href;
199
+ }
200
+ return referrer;
201
+ }
202
+ catch (error) {
203
+ return referrer;
204
+ }
205
+ };
206
+ const getPageUrl = () => {
207
+ try {
208
+ return window.location.href;
209
+ }
210
+ catch (_a) {
211
+ return '';
212
+ }
213
+ };
214
+ const getSearch = () => {
215
+ try {
216
+ return window.location.search;
217
+ }
218
+ catch (_a) {
219
+ return '';
220
+ }
221
+ };
222
+ const getPageTitle = () => {
223
+ try {
224
+ return document.title;
225
+ }
226
+ catch (_a) {
227
+ return '';
228
+ }
229
+ };
193
230
  const isProviderIncluded = (providers, providerValue) => {
194
231
  return (providerValue || (providers['all'] === true && providerValue === undefined));
195
232
  };
@@ -262,29 +299,6 @@
262
299
  const keyPrefix = `_worker`;
263
300
 
264
301
  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 '';
283
- }
284
- catch (_a) {
285
- return '';
286
- }
287
- };
288
302
  const saveDataPerKey = (persistType, provider, value, key) => {
289
303
  const storage = getData$1(persistType);
290
304
  if (!storage['data']) {
@@ -388,164 +402,6 @@
388
402
  }
389
403
  };
390
404
 
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;
400
- };
401
-
402
- const getHeaders = () => ({
403
- 'Content-type': 'application/json; charset=utf-8',
404
- Accept: 'application/json; charset=utf-8',
405
- EdgeTagUserId: handleGetUserId(),
406
- });
407
- const beacon = (url, payload) => {
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
- return Promise.reject(new Error('Beacon not supported.'));
417
- }
418
- };
419
- const fallbackAjax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
420
- const https = yield import('https');
421
- const options = {
422
- method,
423
- headers: getHeaders(),
424
- };
425
- return new Promise((resolve, reject) => {
426
- const req = https.request(url, options, (res) => {
427
- res.on('data', (data) => {
428
- try {
429
- data = JSON.parse(data);
430
- }
431
- catch (_a) {
432
- // do nothing
433
- }
434
- resolve({
435
- body: data,
436
- status: res.statusCode || 500,
437
- });
438
- });
439
- });
440
- req.on('error', (e) => {
441
- reject(new Error(e.message));
442
- });
443
- if (payload && method !== 'GET') {
444
- req.write(JSON.stringify(payload));
445
- }
446
- req.end();
447
- });
448
- });
449
- const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
450
- if (typeof fetch === 'undefined') {
451
- return yield fallbackAjax(method, url, payload)
452
- .then((data) => {
453
- if (data.status < 200 || data.status >= 300) {
454
- return Promise.reject(new Error(`Request failed with code ${data.status} occurred: ${JSON.stringify(data.body)}`));
455
- }
456
- return Promise.resolve(data.body);
457
- })
458
- .catch((error) => {
459
- return Promise.reject(new Error(error));
460
- });
461
- }
462
- return yield fetch(url, {
463
- method,
464
- headers: getHeaders(),
465
- body: JSON.stringify(payload),
466
- credentials: 'include',
467
- })
468
- .then((response) => response.json().then((data) => ({ status: response.status, body: data })))
469
- .then((data) => {
470
- if (data.status < 200 || data.status >= 300) {
471
- return Promise.reject(new Error(`Request failed with code ${data.status}: ${JSON.stringify(data.body)}`));
472
- }
473
- return Promise.resolve(data.body);
474
- })
475
- .catch((error) => {
476
- return Promise.reject(new Error(error));
477
- });
478
- });
479
- const getStandardPayload = (payload) => {
480
- let pageUrl;
481
- try {
482
- pageUrl = window.location.href;
483
- }
484
- catch (_a) {
485
- pageUrl = '';
486
- }
487
- const data = Object.assign({ pageUrl, userAgent: getUserAgent() }, (payload || {}));
488
- let storage = {};
489
- const session = getData$1('session');
490
- if (session) {
491
- storage = Object.assign(Object.assign({}, storage), session);
492
- }
493
- const local = getData$1('local');
494
- if (local) {
495
- storage = Object.assign(Object.assign({}, storage), local);
496
- }
497
- data.storage = storage;
498
- return data;
499
- };
500
- function postRequest(url, data, options) {
501
- return __awaiter(this, void 0, void 0, function* () {
502
- if (!url) {
503
- return Promise.reject(new Error('URL is empty.'));
504
- }
505
- const payload = getStandardPayload(data);
506
- if (options && options.method === 'beacon') {
507
- return Promise.resolve(beacon(url, payload));
508
- }
509
- return yield ajax('POST', url, payload);
510
- });
511
- }
512
- function getRequest(url, options) {
513
- return __awaiter(this, void 0, void 0, function* () {
514
- if (!url) {
515
- return Promise.reject(new Error('URL is empty.'));
516
- }
517
- if (options && options.method === 'beacon') {
518
- return {
519
- result: Promise.resolve(beacon(url)),
520
- };
521
- }
522
- return yield ajax('GET', url);
523
- });
524
- }
525
-
526
- let memoryConsent;
527
- const saveConsent = (consent) => {
528
- setConsent(consent);
529
- savePerKey('local', tagStorage, consent, consentKey);
530
- };
531
- const handleConsent = (consent) => {
532
- const payload = {
533
- consentString: consent,
534
- };
535
- saveConsent(consent);
536
- postRequest(getConsentURL(), payload).catch(error);
537
- };
538
- const setConsent = (newConsent) => {
539
- memoryConsent = newConsent;
540
- };
541
- const getConsent = () => {
542
- const storageConsent = getDataPerKey('local', tagStorage, consentKey);
543
- if (storageConsent) {
544
- return storageConsent;
545
- }
546
- return memoryConsent;
547
- };
548
-
549
405
  // Unique ID creation requires a high quality random # generator. In the browser we therefore
550
406
  // require the crypto API and do not support built-in fallback to lower quality random number
551
407
  // generators (like Math.random()).
@@ -1044,6 +900,181 @@
1044
900
  return `${encodeString(name)}-${v4()}-${time}`;
1045
901
  };
1046
902
 
903
+ const getCookieValue = (key) => {
904
+ try {
905
+ if (!document || !document.cookie) {
906
+ return '';
907
+ }
908
+ const name = `${key}=`;
909
+ const decodedCookie = decodeURIComponent(document.cookie);
910
+ const ca = decodedCookie.split(';');
911
+ for (let i = 0; i < ca.length; i++) {
912
+ let c = ca[i];
913
+ while (c.charAt(0) === ' ') {
914
+ c = c.substring(1);
915
+ }
916
+ if (c.indexOf(name) === 0) {
917
+ return c.substring(name.length, c.length);
918
+ }
919
+ }
920
+ return '';
921
+ }
922
+ catch (_a) {
923
+ return '';
924
+ }
925
+ };
926
+
927
+ let initUserId = '';
928
+ const handleGetUserId = () => {
929
+ if (initUserId) {
930
+ return initUserId;
931
+ }
932
+ return getCookieValue('tag_user_id');
933
+ };
934
+ const setUserId = (userId) => {
935
+ initUserId = userId;
936
+ };
937
+
938
+ const getHeaders = () => ({
939
+ 'Content-type': 'application/json; charset=utf-8',
940
+ Accept: 'application/json; charset=utf-8',
941
+ EdgeTagUserId: handleGetUserId(),
942
+ });
943
+ const beacon = (url, payload) => {
944
+ try {
945
+ let blob;
946
+ if (payload) {
947
+ blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
948
+ }
949
+ return navigator.sendBeacon(url, blob);
950
+ }
951
+ catch (e) {
952
+ return Promise.reject(new Error('Beacon not supported.'));
953
+ }
954
+ };
955
+ const fallbackAjax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
956
+ const https = yield import('https');
957
+ const options = {
958
+ method,
959
+ headers: getHeaders(),
960
+ };
961
+ return new Promise((resolve, reject) => {
962
+ const req = https.request(url, options, (res) => {
963
+ res.on('data', (data) => {
964
+ try {
965
+ data = JSON.parse(data);
966
+ }
967
+ catch (_a) {
968
+ // do nothing
969
+ }
970
+ resolve({
971
+ body: data,
972
+ status: res.statusCode || 500,
973
+ });
974
+ });
975
+ });
976
+ req.on('error', (e) => {
977
+ reject(new Error(e.message));
978
+ });
979
+ if (payload && method !== 'GET') {
980
+ req.write(JSON.stringify(payload));
981
+ }
982
+ req.end();
983
+ });
984
+ });
985
+ const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
986
+ if (typeof fetch === 'undefined') {
987
+ return yield fallbackAjax(method, url, payload)
988
+ .then((data) => {
989
+ if (data.status < 200 || data.status >= 300) {
990
+ return Promise.reject(new Error(`Request failed with code ${data.status} occurred: ${JSON.stringify(data.body)}`));
991
+ }
992
+ return Promise.resolve(data.body);
993
+ })
994
+ .catch((error) => {
995
+ return Promise.reject(new Error(error));
996
+ });
997
+ }
998
+ return yield fetch(url, {
999
+ method,
1000
+ headers: getHeaders(),
1001
+ body: JSON.stringify(payload),
1002
+ credentials: 'include',
1003
+ })
1004
+ .then((response) => response.json().then((data) => ({ status: response.status, body: data })))
1005
+ .then((data) => {
1006
+ if (data.status < 200 || data.status >= 300) {
1007
+ return Promise.reject(new Error(`Request failed with code ${data.status}: ${JSON.stringify(data.body)}`));
1008
+ }
1009
+ return Promise.resolve(data.body);
1010
+ })
1011
+ .catch((error) => {
1012
+ return Promise.reject(new Error(error));
1013
+ });
1014
+ });
1015
+ const getStandardPayload = (payload) => {
1016
+ const data = Object.assign({ pageUrl: getPageUrl(), pageTitle: getPageTitle(), userAgent: getUserAgent(), referrer: getReferrer(), search: getSearch() }, (payload || {}));
1017
+ let storage = {};
1018
+ const session = getData$1('session');
1019
+ if (session) {
1020
+ storage = Object.assign(Object.assign({}, storage), session);
1021
+ }
1022
+ const local = getData$1('local');
1023
+ if (local) {
1024
+ storage = Object.assign(Object.assign({}, storage), local);
1025
+ }
1026
+ data.storage = storage;
1027
+ return data;
1028
+ };
1029
+ function postRequest(url, data, options) {
1030
+ return __awaiter(this, void 0, void 0, function* () {
1031
+ if (!url) {
1032
+ return Promise.reject(new Error('URL is empty.'));
1033
+ }
1034
+ const payload = getStandardPayload(data);
1035
+ if (options && options.method === 'beacon') {
1036
+ return Promise.resolve(beacon(url, payload));
1037
+ }
1038
+ return yield ajax('POST', url, payload);
1039
+ });
1040
+ }
1041
+ function getRequest(url, options) {
1042
+ return __awaiter(this, void 0, void 0, function* () {
1043
+ if (!url) {
1044
+ return Promise.reject(new Error('URL is empty.'));
1045
+ }
1046
+ if (options && options.method === 'beacon') {
1047
+ return {
1048
+ result: Promise.resolve(beacon(url)),
1049
+ };
1050
+ }
1051
+ return yield ajax('GET', url);
1052
+ });
1053
+ }
1054
+
1055
+ let memoryConsent;
1056
+ const saveConsent = (consent) => {
1057
+ setConsent(consent);
1058
+ savePerKey('local', tagStorage, consent, consentKey);
1059
+ };
1060
+ const handleConsent = (consent) => {
1061
+ const payload = {
1062
+ consentString: consent,
1063
+ };
1064
+ saveConsent(consent);
1065
+ postRequest(getConsentURL(), payload).catch(error);
1066
+ };
1067
+ const setConsent = (newConsent) => {
1068
+ memoryConsent = newConsent;
1069
+ };
1070
+ const getConsent = () => {
1071
+ const storageConsent = getDataPerKey('local', tagStorage, consentKey);
1072
+ if (storageConsent) {
1073
+ return storageConsent;
1074
+ }
1075
+ return memoryConsent;
1076
+ };
1077
+
1047
1078
  const manifestVariables = {};
1048
1079
  const addProviderVariable = (name, variables) => {
1049
1080
  manifestVariables[name] = variables;
@@ -1137,12 +1168,25 @@
1137
1168
  });
1138
1169
  };
1139
1170
 
1140
- const handleData = (data, options) => {
1171
+ const handleData = (data, providers, options) => {
1141
1172
  if (!data || Object.keys(data).length === 0) {
1142
1173
  error('Provide data for data API.');
1143
1174
  return;
1144
1175
  }
1145
1176
  saveKV(data);
1177
+ const providerPackages = getProvidersPackage();
1178
+ const userId = handleGetUserId();
1179
+ if (providerPackages) {
1180
+ Object.values(providerPackages).forEach((pkg) => {
1181
+ if (!pkg || !pkg.user || !allowProviderWithConsent(providers, pkg.name)) {
1182
+ return;
1183
+ }
1184
+ pkg.user({
1185
+ userId,
1186
+ data,
1187
+ });
1188
+ });
1189
+ }
1146
1190
  postRequest(getDataURL(), { data }, options).catch(error);
1147
1191
  };
1148
1192
 
@@ -1228,6 +1272,18 @@
1228
1272
  });
1229
1273
  };
1230
1274
 
1275
+ const handleGetData = (keys, callback) => {
1276
+ if (!keys || keys.length === 0) {
1277
+ error('Provide keys for get data API.');
1278
+ return;
1279
+ }
1280
+ getRequest(getGetDataURL(keys))
1281
+ .then((result) => {
1282
+ callback((result === null || result === void 0 ? void 0 : result.result) || {});
1283
+ })
1284
+ .catch(error);
1285
+ };
1286
+
1231
1287
  const handleManifest = (manifest) => {
1232
1288
  const providerPackages = getProvidersPackage();
1233
1289
  const userId = handleGetUserId();
@@ -1247,7 +1303,15 @@
1247
1303
  if (providerPackages) {
1248
1304
  const pkg = providerPackages[provider.package];
1249
1305
  if (pkg && pkg.init && allowProvider(pkg.name)) {
1250
- pkg.init({ userId, manifest: provider, sendTag });
1306
+ const initData = {
1307
+ userId,
1308
+ manifest: provider,
1309
+ sendTag,
1310
+ sendEdgeData: handleData,
1311
+ getEdgeData: handleGetData,
1312
+ keyName: `${keyPrefix}Store`,
1313
+ };
1314
+ pkg.init(initData);
1251
1315
  }
1252
1316
  }
1253
1317
  });
@@ -1283,7 +1347,7 @@
1283
1347
  .catch(error);
1284
1348
  };
1285
1349
 
1286
- const handleUser = (key, value, options) => {
1350
+ const handleUser = (key, value, providers, options) => {
1287
1351
  if (!key || !value) {
1288
1352
  error('Key or Value is missing in user API.');
1289
1353
  return;
@@ -1291,24 +1355,25 @@
1291
1355
  saveKV({
1292
1356
  [key]: value,
1293
1357
  });
1358
+ const providerPackages = getProvidersPackage();
1359
+ const userId = handleGetUserId();
1360
+ if (providerPackages) {
1361
+ Object.values(providerPackages).forEach((pkg) => {
1362
+ if (!pkg || !pkg.user || !allowProviderWithConsent(providers, pkg.name)) {
1363
+ return;
1364
+ }
1365
+ pkg.user({
1366
+ userId,
1367
+ data: { [key]: value },
1368
+ });
1369
+ });
1370
+ }
1294
1371
  postRequest(getUserURL(), {
1295
1372
  key,
1296
1373
  value,
1297
1374
  }, options).catch(error);
1298
1375
  };
1299
1376
 
1300
- const handleGetData = (keys, callback) => {
1301
- if (!keys || keys.length === 0) {
1302
- error('Provide keys for get data API.');
1303
- return;
1304
- }
1305
- getRequest(getGetDataURL(keys))
1306
- .then((result) => {
1307
- callback((result === null || result === void 0 ? void 0 : result.result) || {});
1308
- })
1309
- .catch(error);
1310
- };
1311
-
1312
1377
  const handleKeys = (callback) => {
1313
1378
  getRequest(getKeysURL())
1314
1379
  .then((result) => {
@@ -1326,11 +1391,11 @@
1326
1391
  const consent = (consent) => {
1327
1392
  handleConsent(consent);
1328
1393
  };
1329
- const user = (key, value, options) => {
1330
- handleUser(key, value, options);
1394
+ const user = (key, value, providers, options) => {
1395
+ handleUser(key, value, providers, options);
1331
1396
  };
1332
- const data = (data, options) => {
1333
- handleData(data, options);
1397
+ const data = (data, providers, options) => {
1398
+ handleData(data, providers, options);
1334
1399
  };
1335
1400
  const getData = (keys, callback) => {
1336
1401
  handleGetData(keys, callback);
@@ -1357,12 +1422,12 @@
1357
1422
  consent(consentString);
1358
1423
  }
1359
1424
 
1360
- user(key, value, options) {
1361
- user(key, value, options);
1425
+ user(key, value, providers, options) {
1426
+ user(key, value, providers, options);
1362
1427
  }
1363
1428
 
1364
- data(data$1, options) {
1365
- data(data$1, options);
1429
+ data(data$1, providers, options) {
1430
+ data(data$1, providers, options);
1366
1431
  }
1367
1432
 
1368
1433
  getData(keys, callback) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotoutio/edgetag-sdk-browser",
3
- "version": "0.7.2",
3
+ "version": "0.8.0",
4
4
  "description": "Browser SDK for EdgeTag",
5
5
  "author": "Blotout",
6
6
  "license": "MIT",