@blotoutio/edgetag-sdk-js 0.2.0 → 0.4.3

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