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