@telia-ace/widget-services 1.0.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.
@@ -0,0 +1,36 @@
1
+ import { Container } from '@webprovisions/platform';
2
+ import { Duration, StorageCategory, StorageMedium, Store, StoredValue } from './types';
3
+ export declare const createEmptyStore: () => Store;
4
+ export declare const isExpired: (isoDateString: string) => boolean;
5
+ export declare const getValue: <Type>(store: Store, key: string) => Type | undefined;
6
+ export declare const createValue: (value: any, category: StorageCategory, duration: Duration | string) => StoredValue;
7
+ export declare const processStore: (store: Store, policy?: StorageCategory[] | undefined) => Store;
8
+ /**
9
+ * @param category Storage Category.
10
+ * @param policy Current Storage Policy.
11
+ * @returns true if not allowed, false if allowed.
12
+ */
13
+ export declare const isNotAllowedAsync: (container: Container, category?: StorageCategory | undefined) => Promise<boolean>;
14
+ /**
15
+ * @param category Storage Category.
16
+ * @param policy Current Storage Policy.
17
+ * @returns true if not allowed, false if allowed.
18
+ */
19
+ export declare const isNotAllowed: (policy?: StorageCategory[], category?: StorageCategory | undefined) => boolean;
20
+ /**
21
+ * Processes storage and removes items if they are expired or if
22
+ * the storage policy is defined and the category of the stored
23
+ * value is not allowed.
24
+ * @param container Widget Container
25
+ */
26
+ export declare const processStorage: (container: Container) => void;
27
+ /**
28
+ * Creates an expiration date string with the passed options.
29
+ * @param options Duration options.
30
+ * @returns ISO formatted date string.
31
+ */
32
+ export declare const createExpirationDate: (options?: Duration) => string;
33
+ export declare const getCookieStoreAsync: (container: Container) => Promise<Store>;
34
+ export declare const setCookieStoreAsync: (container: Container, store: Store) => Promise<any>;
35
+ export declare const getApplicationStoreAsync: (container: Container, type: StorageMedium.Local | StorageMedium.Session) => Promise<Store>;
36
+ export declare const setApplicationStoreAsync: (container: Container, type: StorageMedium.Local | StorageMedium.Session, store: Store) => Promise<void>;
@@ -0,0 +1,224 @@
1
+ var __read = (this && this.__read) || function (o, n) {
2
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
3
+ if (!m) return o;
4
+ var i = m.call(o), r, ar = [], e;
5
+ try {
6
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
7
+ }
8
+ catch (error) { e = { error: error }; }
9
+ finally {
10
+ try {
11
+ if (r && !r.done && (m = i["return"])) m.call(i);
12
+ }
13
+ finally { if (e) throw e.error; }
14
+ }
15
+ return ar;
16
+ };
17
+ import { deepClone, hash, lock, mergeDeep } from '@telia-ace/widget-utilities';
18
+ import { readStorage } from './storage';
19
+ import { StorageCategory, StorageMedium, } from './types';
20
+ var hasEntries = function (object) {
21
+ return !!Object.entries(object).filter(function (_a) {
22
+ var _b = __read(_a, 2), _ = _b[0], value = _b[1];
23
+ return typeof value !== 'undefined';
24
+ }).length;
25
+ };
26
+ var cleanUndefined = function (object) {
27
+ return Object.entries(object)
28
+ .filter(function (_a) {
29
+ var _b = __read(_a, 2), _ = _b[0], value = _b[1];
30
+ return typeof value !== 'undefined';
31
+ })
32
+ .forEach(function (_a) {
33
+ var _b = __read(_a, 2), key = _b[0], value = _b[1].value;
34
+ if (typeof value === 'undefined') {
35
+ delete object[key];
36
+ }
37
+ });
38
+ };
39
+ var mergeAndClean = function (target, source) {
40
+ var merged = mergeDeep(target, source);
41
+ cleanUndefined(merged.tenant);
42
+ cleanUndefined(merged.implementation);
43
+ cleanUndefined(merged.widget);
44
+ return merged;
45
+ };
46
+ var getLongestExpirationDate = function (store) {
47
+ var expirationDates = Object.entries(store).reduce(function (acc, storeEntry) {
48
+ var _a = __read(storeEntry, 2), _ = _a[0], container = _a[1];
49
+ Object.entries(container).forEach(function (containerEntry) {
50
+ var _a = __read(containerEntry, 2), _ = _a[0], expiration = _a[1].expiration;
51
+ acc.push(expiration);
52
+ });
53
+ return acc;
54
+ }, []);
55
+ return (expirationDates
56
+ .slice()
57
+ .sort(function (a, b) { return new Date(b).valueOf() - new Date(a).valueOf(); })
58
+ .shift() || createExpirationDate());
59
+ };
60
+ var createStorageKeys = function (container) {
61
+ var _a = container.get('$widget'), widgetName = _a.name, _b = _a.implementation, implementationName = _b.name, tenantName = _b.tenant;
62
+ return [
63
+ "humany_".concat(tenantName),
64
+ "humany_".concat(hash(tenantName + implementationName)),
65
+ "humany_".concat(hash(tenantName + implementationName + widgetName)),
66
+ ];
67
+ };
68
+ var getCookie = function (cookieName) {
69
+ var regExp = new RegExp("(?:^|;)\\s?".concat(cookieName, "=(.*?)(?:;|$)"), 'i');
70
+ var cookie = document.cookie.match(regExp);
71
+ var value = cookie && cookie[1] && JSON.parse(cookie[1]);
72
+ return value || undefined;
73
+ };
74
+ var setCookie = function (cookieName, value, expires) {
75
+ var cookie = "".concat(cookieName, "=").concat(JSON.stringify(value).trim(), ";");
76
+ var expiration = "expires=".concat(new Date(expires).toUTCString(), ";");
77
+ var path = 'path=/';
78
+ return (document.cookie = "".concat(cookie, " ").concat(expiration, " ").concat(path));
79
+ };
80
+ var getCookieStore = function (container) {
81
+ var _a = __read(createStorageKeys(container), 3), tenantKey = _a[0], implementationKey = _a[1], widgetKey = _a[2];
82
+ var tenant = getCookie(tenantKey) || {};
83
+ var implementation = getCookie(implementationKey) || {};
84
+ var widget = getCookie(widgetKey) || {};
85
+ return {
86
+ tenant: tenant,
87
+ implementation: implementation,
88
+ widget: widget,
89
+ };
90
+ };
91
+ var setCookieStore = function (container, store) {
92
+ var current = getCookieStore(container);
93
+ var merged = mergeAndClean(current, store);
94
+ var _a = __read(createStorageKeys(container), 3), tenantKey = _a[0], implementationKey = _a[1], widgetKey = _a[2];
95
+ var tenant = merged.tenant, implementation = merged.implementation, widget = merged.widget;
96
+ var expirationDate = getLongestExpirationDate(store);
97
+ var deleteDate = createExpirationDate({ days: -1 });
98
+ setCookie(tenantKey, tenant, hasEntries(tenant) ? expirationDate : deleteDate);
99
+ setCookie(implementationKey, implementation, hasEntries(implementation) ? expirationDate : deleteDate);
100
+ setCookie(widgetKey, widget, hasEntries(widget) ? expirationDate : deleteDate);
101
+ };
102
+ var getApplicationStore = function (container, storage) {
103
+ var _a = __read(createStorageKeys(container), 3), tenantKey = _a[0], implementationKey = _a[1], widgetKey = _a[2];
104
+ var tenant = storage.getItem(tenantKey) || '{}';
105
+ var implementation = storage.getItem(implementationKey) || '{}';
106
+ var widget = storage.getItem(widgetKey) || '{}';
107
+ return {
108
+ tenant: JSON.parse(tenant),
109
+ implementation: JSON.parse(implementation),
110
+ widget: JSON.parse(widget),
111
+ };
112
+ };
113
+ var setApplicationStore = function (container, applicationStorage, store) {
114
+ var current = getApplicationStore(container, applicationStorage);
115
+ var merged = mergeAndClean(current, store);
116
+ var _a = __read(createStorageKeys(container), 3), tenantKey = _a[0], implementationKey = _a[1], widgetKey = _a[2];
117
+ var tenant = merged.tenant, implementation = merged.implementation, widget = merged.widget;
118
+ hasEntries(tenant)
119
+ ? applicationStorage.setItem(tenantKey, JSON.stringify(tenant))
120
+ : applicationStorage.removeItem(tenantKey);
121
+ hasEntries(implementation)
122
+ ? applicationStorage.setItem(implementationKey, JSON.stringify(implementation))
123
+ : applicationStorage.removeItem(implementationKey);
124
+ hasEntries(widget)
125
+ ? applicationStorage.setItem(widgetKey, JSON.stringify(widget))
126
+ : applicationStorage.removeItem(widgetKey);
127
+ };
128
+ export var createEmptyStore = function () { return ({ tenant: {}, implementation: {}, widget: {} }); };
129
+ export var isExpired = function (isoDateString) {
130
+ return !!isoDateString && new Date() > new Date(isoDateString);
131
+ };
132
+ export var getValue = function (store, key) {
133
+ var storedValue = store.widget[key] || store.implementation[key] || store.tenant[key];
134
+ return storedValue === null || storedValue === void 0 ? void 0 : storedValue.value;
135
+ };
136
+ export var createValue = function (value, category, duration) {
137
+ return {
138
+ value: value,
139
+ category: category,
140
+ expiration: typeof duration === 'object' ? createExpirationDate(duration) : duration,
141
+ };
142
+ };
143
+ export var processStore = function (store, policy) {
144
+ var clone = deepClone(store);
145
+ Object.entries(clone).forEach(function (_a) {
146
+ var _b = __read(_a, 2), _ = _b[0], storageContainer = _b[1];
147
+ Object.entries(storageContainer).forEach(function (_a) {
148
+ var _b = __read(_a, 2), key = _b[0], storedValue = _b[1];
149
+ var expiration = storedValue.expiration, category = storedValue.category;
150
+ if (isExpired(expiration) || isNotAllowed(policy, category))
151
+ storageContainer[key] = createValue(undefined, category, expiration);
152
+ });
153
+ });
154
+ return clone;
155
+ };
156
+ /**
157
+ * @param category Storage Category.
158
+ * @param policy Current Storage Policy.
159
+ * @returns true if not allowed, false if allowed.
160
+ */
161
+ export var isNotAllowedAsync = function (container, category) {
162
+ return readStorage(container, 'storagePolicy', StorageMedium.Cookie).then(function (policy) {
163
+ if (policy === void 0) { policy = [StorageCategory.Necessary]; }
164
+ return !!category && policy.indexOf(category) === -1;
165
+ });
166
+ };
167
+ /**
168
+ * @param category Storage Category.
169
+ * @param policy Current Storage Policy.
170
+ * @returns true if not allowed, false if allowed.
171
+ */
172
+ export var isNotAllowed = function (policy, category) {
173
+ if (policy === void 0) { policy = [StorageCategory.Necessary]; }
174
+ return !!category && policy.indexOf(category) === -1;
175
+ };
176
+ /**
177
+ * Processes storage and removes items if they are expired or if
178
+ * the storage policy is defined and the category of the stored
179
+ * value is not allowed.
180
+ * @param container Widget Container
181
+ */
182
+ export var processStorage = function (container) {
183
+ var cookieStore = getCookieStore(container);
184
+ var localStore = getApplicationStore(container, window.localStorage);
185
+ var sessionStore = getApplicationStore(container, sessionStorage);
186
+ var policy = getValue(cookieStore, 'storagePolicy');
187
+ var _a = __read([
188
+ cookieStore,
189
+ localStore,
190
+ sessionStore,
191
+ ].map(function (store) { return processStore(store, policy); }), 3), processedCookieStore = _a[0], processedLocalStore = _a[1], processedSessionStore = _a[2];
192
+ setCookieStore(container, processedCookieStore);
193
+ setApplicationStore(container, window.localStorage, processedLocalStore);
194
+ setApplicationStore(container, window.sessionStorage, processedSessionStore);
195
+ };
196
+ /**
197
+ * Creates an expiration date string with the passed options.
198
+ * @param options Duration options.
199
+ * @returns ISO formatted date string.
200
+ */
201
+ export var createExpirationDate = function (options) {
202
+ if (options === void 0) { options = { days: 30 }; }
203
+ var _a = options.days, days = _a === void 0 ? 0 : _a, _b = options.hours, hours = _b === void 0 ? 0 : _b, _c = options.minutes, minutes = _c === void 0 ? 0 : _c, _d = options.seconds, seconds = _d === void 0 ? 0 : _d;
204
+ var date = new Date();
205
+ date.setTime(date.getTime() + hours * 60 * 60 * 1000);
206
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
207
+ date.setTime(date.getTime() + minutes * 60 * 1000);
208
+ date.setTime(date.getTime() + seconds * 1000);
209
+ return date.toISOString();
210
+ };
211
+ export var getCookieStoreAsync = function (container) {
212
+ return lock(document)(function () { return getCookieStore(container); });
213
+ };
214
+ export var setCookieStoreAsync = function (container, store) {
215
+ return lock(document)(function () { return setCookieStore(container, store); });
216
+ };
217
+ export var getApplicationStoreAsync = function (container, type) {
218
+ var storage = type === StorageMedium.Local ? window.localStorage : window.sessionStorage;
219
+ return lock(storage)(function () { return getApplicationStore(container, storage); });
220
+ };
221
+ export var setApplicationStoreAsync = function (container, type, store) {
222
+ var storage = type === StorageMedium.Local ? window.localStorage : window.sessionStorage;
223
+ return lock(storage)(function () { return setApplicationStore(container, storage, store); });
224
+ };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@telia-ace/widget-services",
3
+ "version": "1.0.0",
4
+ "description": "Services for ACE Widgets.",
5
+ "license": "SEE LICENSE IN LICENSE.txt",
6
+ "author": "Telia Company AB",
7
+ "keywords": [
8
+ "telia"
9
+ ],
10
+ "main": "lib/index.js",
11
+ "module": "lib-esm/index.js",
12
+ "files": [
13
+ "LICENSE.txt",
14
+ "README.md",
15
+ "lib/",
16
+ "lib-esm/"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "scripts": {
22
+ "clean": "cleandir lib && cleandir lib-esm",
23
+ "compile": "tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json"
24
+ },
25
+ "sideEffects": false,
26
+ "typings": "lib/index.d.ts",
27
+ "dependencies": {
28
+ "@telia-ace/widget-utilities": "^1.0.1"
29
+ },
30
+ "devDependencies": {
31
+ "@webprovisions/platform": "^1.1.2"
32
+ },
33
+ "gitHead": "a45fde2bae0981a2a791a2362f2ecaf53430570b"
34
+ }