@blotoutio/edgetag-sdk-js 0.5.1 → 0.6.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.
package/index..cjs ADDED
@@ -0,0 +1,580 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var uuid = require('uuid');
6
+
7
+ /******************************************************************************
8
+ Copyright (c) Microsoft Corporation.
9
+
10
+ Permission to use, copy, modify, and/or distribute this software for any
11
+ purpose with or without fee is hereby granted.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
+ PERFORMANCE OF THIS SOFTWARE.
20
+ ***************************************************************************** */
21
+
22
+ function __awaiter(thisArg, _arguments, P, generator) {
23
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
24
+ return new (P || (P = Promise))(function (resolve, reject) {
25
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
26
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
27
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
28
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
29
+ });
30
+ }
31
+
32
+ const tagStorage = 'edgeTag';
33
+ const consentKey = 'consent';
34
+ const providersKey = 'providers';
35
+ const keyPrefix = `_worker`;
36
+
37
+ const initKey = `${keyPrefix}Store`;
38
+ const getCookieValue = (key) => {
39
+ if (!document || !document.cookie) {
40
+ return '';
41
+ }
42
+ const name = `${key}=`;
43
+ const decodedCookie = decodeURIComponent(document.cookie);
44
+ const ca = decodedCookie.split(';');
45
+ for (let i = 0; i < ca.length; i++) {
46
+ let c = ca[i];
47
+ while (c.charAt(0) === ' ') {
48
+ c = c.substring(1);
49
+ }
50
+ if (c.indexOf(name) === 0) {
51
+ return c.substring(name.length, c.length);
52
+ }
53
+ }
54
+ return '';
55
+ };
56
+ const saveDataPerKey = (persistType, provider, value, key) => {
57
+ const storage = getData$1(persistType);
58
+ if (!storage['data']) {
59
+ storage['data'] = {};
60
+ }
61
+ if (!storage['data'][provider]) {
62
+ storage['data'][provider] = {};
63
+ }
64
+ storage['data'][provider][key] = value;
65
+ saveData(persistType, storage);
66
+ };
67
+ const savePerKey = (persistType, provider, value, key) => {
68
+ const storage = getData$1(persistType);
69
+ if (!storage[provider]) {
70
+ storage[provider] = {};
71
+ }
72
+ storage[provider][key] = value;
73
+ saveData(persistType, storage);
74
+ };
75
+ const getDataPerKey = (persistType, provider, key) => {
76
+ const storage = getData$1(persistType);
77
+ if (!storage[provider]) {
78
+ return undefined;
79
+ }
80
+ return storage[provider][key];
81
+ };
82
+ const saveData = (persistType, value, key = initKey) => {
83
+ if (persistType === 'session') {
84
+ saveSession(value, key);
85
+ return;
86
+ }
87
+ saveLocal(value, key);
88
+ };
89
+ const getData$1 = (persistType, key = initKey) => {
90
+ if (persistType === 'session') {
91
+ return getSession(key);
92
+ }
93
+ return getLocal(key);
94
+ };
95
+ const saveKV = (data) => {
96
+ let currentSession = getData$1('session');
97
+ if (!currentSession) {
98
+ currentSession = {};
99
+ }
100
+ if (!currentSession['kv']) {
101
+ currentSession['kv'] = {};
102
+ }
103
+ currentSession['kv'] = Object.assign(Object.assign({}, currentSession['kv']), data);
104
+ saveData('session', currentSession);
105
+ };
106
+ const saveLocal = (value, key) => {
107
+ localStorage.setItem(key, JSON.stringify(value));
108
+ };
109
+ const getLocal = (key) => {
110
+ const data = localStorage.getItem(key);
111
+ if (!data) {
112
+ return {};
113
+ }
114
+ return JSON.parse(data) || {};
115
+ };
116
+ const saveSession = (value, key) => {
117
+ sessionStorage.setItem(key, JSON.stringify(value));
118
+ };
119
+ const getSession = (key) => {
120
+ const data = sessionStorage.getItem(key);
121
+ if (!data) {
122
+ return {};
123
+ }
124
+ return JSON.parse(data) || {};
125
+ };
126
+
127
+ let endpointUrl = '';
128
+ const generateUrl = (path) => {
129
+ const endpoint = getUrl();
130
+ if (!endpoint) {
131
+ console.log('URL is not valid');
132
+ return '';
133
+ }
134
+ return `${endpoint}${path}`;
135
+ };
136
+ const getUrl = () => {
137
+ return endpointUrl;
138
+ };
139
+ const setUrl = (url) => {
140
+ if (url == null) {
141
+ return;
142
+ }
143
+ endpointUrl = url;
144
+ };
145
+ const getTagURL = () => {
146
+ return generateUrl('/tag');
147
+ };
148
+ const getInitURL = () => {
149
+ return generateUrl('/init');
150
+ };
151
+ const getConsentURL = () => {
152
+ return generateUrl('/consent');
153
+ };
154
+ const getUserURL = () => {
155
+ return generateUrl('/user');
156
+ };
157
+ const getDataURL = () => {
158
+ return generateUrl(`/data`);
159
+ };
160
+ const getGetDataURL = (keys) => {
161
+ return generateUrl(`/data?keys=${encodeURIComponent(keys.join(','))}`);
162
+ };
163
+ const getKeysURL = () => {
164
+ return generateUrl(`/keys`);
165
+ };
166
+
167
+ let consentDisabled = false;
168
+ let providers = [];
169
+ const setPreferences = (preferences) => {
170
+ if (!preferences) {
171
+ return false;
172
+ }
173
+ if (!preferences.edgeURL) {
174
+ console.error('Please provide URL for EdgeTag');
175
+ return false;
176
+ }
177
+ consentDisabled = !!preferences.disableConsentCheck;
178
+ providers = preferences.providers || [];
179
+ if (window && window.edgetagPackages) {
180
+ providers = [...window.edgetagPackages, ...providers];
181
+ }
182
+ setUrl(preferences.edgeURL);
183
+ return true;
184
+ };
185
+ const isConsentDisabled = () => consentDisabled;
186
+ const getProvidersPackage = () => providers;
187
+
188
+ const getUserAgent = () => {
189
+ const nav = navigator;
190
+ let ua = nav.userAgent;
191
+ ua += nav.brave ? `${ua} Brave` : '';
192
+ return ua;
193
+ };
194
+ const allowTag = (providers) => {
195
+ const consent = getDataPerKey('local', tagStorage, consentKey);
196
+ if (isConsentDisabled()) {
197
+ return true;
198
+ }
199
+ if (!consent) {
200
+ return false;
201
+ }
202
+ if (consent['all']) {
203
+ return true;
204
+ }
205
+ if (!providers) {
206
+ return (Object.values(consent).find((isAllowed) => isAllowed) || false);
207
+ }
208
+ const allProviders = (getDataPerKey('local', tagStorage, providersKey) ||
209
+ []);
210
+ for (const provider of allProviders) {
211
+ const tagProviderSetting = providers[provider];
212
+ if (tagProviderSetting ||
213
+ (providers['all'] === true && tagProviderSetting === undefined) ||
214
+ (providers['all'] === false && tagProviderSetting === true)) {
215
+ if (consent[provider]) {
216
+ return true;
217
+ }
218
+ }
219
+ }
220
+ return false;
221
+ };
222
+ const allowProvider = (providers, providerId) => {
223
+ const consent = getDataPerKey('local', tagStorage, consentKey);
224
+ if (isConsentDisabled()) {
225
+ return true;
226
+ }
227
+ if (!consent) {
228
+ return false;
229
+ }
230
+ if (consent['all']) {
231
+ return true;
232
+ }
233
+ if (!providers) {
234
+ return consent[providerId];
235
+ }
236
+ const tagProvider = providers[providerId];
237
+ if (tagProvider ||
238
+ (providers['all'] === true && tagProvider === undefined) ||
239
+ (providers['all'] === false && tagProvider === true)) {
240
+ if (consent[providerId]) {
241
+ return true;
242
+ }
243
+ }
244
+ return false;
245
+ };
246
+
247
+ const beacon = (url, payload) => {
248
+ let blob;
249
+ if (payload) {
250
+ blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
251
+ }
252
+ return navigator.sendBeacon(url, blob);
253
+ };
254
+ const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
255
+ return yield fetch(url, {
256
+ method,
257
+ headers: {
258
+ 'Content-type': 'application/json; charset=utf-8',
259
+ Accept: 'application/json; charset=utf-8',
260
+ },
261
+ body: JSON.stringify(payload),
262
+ credentials: 'include',
263
+ })
264
+ .then((response) => response.json().then((data) => ({ status: response.status, body: data })))
265
+ .then((data) => {
266
+ if (data.status < 200 || data.status >= 300) {
267
+ // Q: do we need to retry?
268
+ return Promise.reject(new Error(JSON.stringify(data.body)));
269
+ }
270
+ return Promise.resolve(data.body);
271
+ })
272
+ .catch((error) => {
273
+ // Q: do we need to retry?
274
+ return Promise.reject(new Error(error));
275
+ });
276
+ });
277
+ const getStandardPayload = (payload) => {
278
+ const data = Object.assign({ pageUrl: window.location.href, userAgent: getUserAgent() }, (payload || {}));
279
+ let storage = {};
280
+ const session = getData$1('session');
281
+ if (session) {
282
+ storage = Object.assign(Object.assign({}, storage), session);
283
+ }
284
+ const local = getData$1('local');
285
+ if (local) {
286
+ storage = Object.assign(Object.assign({}, storage), local);
287
+ }
288
+ data.storage = storage;
289
+ return data;
290
+ };
291
+ function postRequest(url, data, options) {
292
+ return __awaiter(this, void 0, void 0, function* () {
293
+ if (!url) {
294
+ return Promise.reject(new Error('URL is empty'));
295
+ }
296
+ const payload = getStandardPayload(data);
297
+ if (options && options.method === 'beacon') {
298
+ return Promise.resolve(beacon(url, payload));
299
+ }
300
+ return yield ajax('POST', url, payload);
301
+ });
302
+ }
303
+ function getRequest(url, options) {
304
+ return __awaiter(this, void 0, void 0, function* () {
305
+ if (!url) {
306
+ return Promise.reject(new Error('URL is empty'));
307
+ }
308
+ if (options && options.method === 'beacon') {
309
+ return {
310
+ result: Promise.resolve(beacon(url)),
311
+ };
312
+ }
313
+ return yield ajax('GET', url);
314
+ });
315
+ }
316
+
317
+ const info = (data) => {
318
+ };
319
+
320
+ const saveConsent = (consent) => {
321
+ savePerKey('local', tagStorage, consent, consentKey);
322
+ };
323
+ const handleConsent = (consent) => {
324
+ const payload = {
325
+ consentString: consent,
326
+ };
327
+ saveConsent(consent);
328
+ postRequest(getConsentURL(), payload).catch(info);
329
+ };
330
+
331
+ const generateEventId = (name) => {
332
+ let time = Date.now().toString();
333
+ if (typeof performance !== 'undefined' &&
334
+ typeof performance.now === 'function') {
335
+ const perf = performance.now();
336
+ if (perf) {
337
+ time = perf.toFixed(4);
338
+ }
339
+ }
340
+ return `${btoa(name)}-${uuid.v4()}-${time}`;
341
+ };
342
+
343
+ const handleGetUserId = () => {
344
+ return getCookieValue('tag_user_id');
345
+ };
346
+
347
+ const manifestVariables = {};
348
+ const addProviderVariable = (name, variables) => {
349
+ manifestVariables[name] = variables;
350
+ };
351
+ const getProviderVariables = (name) => manifestVariables[name] || {};
352
+
353
+ const sendTag = ({ eventName, eventId, data, providerData, providers, options, }) => {
354
+ const payload = {
355
+ eventName,
356
+ eventId,
357
+ timestamp: Date.now(),
358
+ data,
359
+ providerData,
360
+ };
361
+ if (providers) {
362
+ payload.providers = providers;
363
+ }
364
+ postRequest(getTagURL(), payload, options).catch(info);
365
+ };
366
+ const handleTag = (eventName, data = {}, providers, options) => {
367
+ if (!allowTag(providers)) {
368
+ console.log('No consent');
369
+ return;
370
+ }
371
+ let eventId = data['eventId'];
372
+ if (!eventId) {
373
+ eventId = generateEventId(eventName);
374
+ }
375
+ const providerPackages = getProvidersPackage();
376
+ const userId = handleGetUserId();
377
+ const providerData = {};
378
+ if (providerPackages) {
379
+ providerPackages.forEach((pkg) => {
380
+ if (!allowProvider(providers, pkg.name)) {
381
+ return;
382
+ }
383
+ if (pkg && pkg.tag) {
384
+ const result = pkg.tag({
385
+ userId,
386
+ eventName,
387
+ eventId,
388
+ data,
389
+ sendTag,
390
+ manifestVariables: getProviderVariables(pkg.name),
391
+ });
392
+ if (result) {
393
+ providerData[pkg.name] = result;
394
+ }
395
+ }
396
+ });
397
+ }
398
+ sendTag({
399
+ eventName,
400
+ eventId,
401
+ data,
402
+ providerData,
403
+ providers,
404
+ options,
405
+ });
406
+ };
407
+
408
+ const handleCaptureQuery = (provider, key, persistType) => {
409
+ if (!window) {
410
+ return;
411
+ }
412
+ const params = new URLSearchParams(window.location.search);
413
+ if (!params || !params.get(key)) {
414
+ return;
415
+ }
416
+ saveDataPerKey(persistType, provider, params.get(key), key);
417
+ };
418
+ const handleCaptureStorage = (provider, key, persistType, location) => {
419
+ let data;
420
+ switch (location) {
421
+ case 'cookie': {
422
+ data = getCookieValue(key);
423
+ break;
424
+ }
425
+ case 'local': {
426
+ data = sessionStorage && sessionStorage.getItem(key);
427
+ break;
428
+ }
429
+ case 'session': {
430
+ data = localStorage && localStorage.getItem(key);
431
+ break;
432
+ }
433
+ }
434
+ if (!data) {
435
+ return;
436
+ }
437
+ saveDataPerKey(persistType, provider, data, key);
438
+ };
439
+ const handleCapture = (provider, params) => {
440
+ params.forEach((param) => {
441
+ switch (param.type) {
442
+ case 'query': {
443
+ handleCaptureQuery(provider, param.key, param.persist);
444
+ break;
445
+ }
446
+ case 'storage': {
447
+ handleCaptureStorage(provider, param.key, param.persist, param.location);
448
+ break;
449
+ }
450
+ }
451
+ });
452
+ };
453
+
454
+ const handleManifest = (manifest) => {
455
+ const providers = [];
456
+ const providerPackages = getProvidersPackage();
457
+ const userId = handleGetUserId();
458
+ manifest.forEach((provider) => {
459
+ providers.push(provider.package);
460
+ addProviderVariable(provider.package, provider.variables);
461
+ if (provider.rules) {
462
+ Object.entries(provider.rules).forEach(([name, recipe]) => {
463
+ switch (name) {
464
+ case 'capture': {
465
+ handleCapture(provider.package, recipe);
466
+ return;
467
+ }
468
+ }
469
+ });
470
+ }
471
+ if (providerPackages) {
472
+ const pkg = providerPackages.find((pkg) => pkg.name === provider.package);
473
+ if (pkg && pkg.init) {
474
+ pkg.init({ userId, manifest: provider, sendTag });
475
+ }
476
+ }
477
+ });
478
+ savePerKey('local', tagStorage, providers, providersKey);
479
+ };
480
+
481
+ const handleInit = (preferences) => {
482
+ const success = setPreferences(preferences);
483
+ if (!success) {
484
+ return;
485
+ }
486
+ const url = new URL(getInitURL());
487
+ if (preferences.disableConsentCheck) {
488
+ url.searchParams.set('consentDisabled', 'true');
489
+ saveConsent({ all: true });
490
+ }
491
+ if (preferences.userId) {
492
+ url.searchParams.set('userId', preferences.userId);
493
+ }
494
+ getRequest(url.href)
495
+ .then((result) => {
496
+ if (!result) {
497
+ console.log('init failed');
498
+ return;
499
+ }
500
+ handleManifest(result.result);
501
+ })
502
+ .catch(info);
503
+ };
504
+
505
+ const handleUser = (key, value, options) => {
506
+ if (!key || !value) {
507
+ console.error('Key or Value is missing in user API.');
508
+ return;
509
+ }
510
+ saveKV({
511
+ [key]: value,
512
+ });
513
+ postRequest(getUserURL(), {
514
+ key,
515
+ value,
516
+ }, options).catch(info);
517
+ };
518
+
519
+ const handleData = (data, options) => {
520
+ if (!data || Object.keys(data).length === 0) {
521
+ console.error('Provide data for data API.');
522
+ return;
523
+ }
524
+ saveKV(data);
525
+ postRequest(getDataURL(), { data }, options).catch(info);
526
+ };
527
+
528
+ const handleGetData = (keys, callback) => {
529
+ if (!keys || keys.length === 0) {
530
+ console.error('Provide keys for get data API.');
531
+ return;
532
+ }
533
+ getRequest(getGetDataURL(keys))
534
+ .then((result) => {
535
+ callback((result === null || result === void 0 ? void 0 : result.result) || {});
536
+ })
537
+ .catch(info);
538
+ };
539
+
540
+ const handleKeys = (callback) => {
541
+ getRequest(getKeysURL())
542
+ .then((result) => {
543
+ callback((result === null || result === void 0 ? void 0 : result.result) || []);
544
+ })
545
+ .catch(info);
546
+ };
547
+
548
+ const init = (preferences) => {
549
+ handleInit(preferences);
550
+ };
551
+ const tag = (name, data, providers, options) => {
552
+ handleTag(name, data, providers, options);
553
+ };
554
+ const consent = (consent) => {
555
+ handleConsent(consent);
556
+ };
557
+ const user = (key, value, options) => {
558
+ handleUser(key, value, options);
559
+ };
560
+ const data = (data, options) => {
561
+ handleData(data, options);
562
+ };
563
+ const getData = (keys, callback) => {
564
+ handleGetData(keys, callback);
565
+ };
566
+ const keys = (callback) => {
567
+ handleKeys(callback);
568
+ };
569
+ const getUserId = () => {
570
+ return handleGetUserId();
571
+ };
572
+
573
+ exports.consent = consent;
574
+ exports.data = data;
575
+ exports.getData = getData;
576
+ exports.getUserId = getUserId;
577
+ exports.init = init;
578
+ exports.keys = keys;
579
+ exports.tag = tag;
580
+ exports.user = user;