@amedia/user 0.14.18 → 0.14.20

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 (85) hide show
  1. package/package.json +2 -3
  2. package/src/actions/authentication.spec.ts +0 -51
  3. package/src/actions/authentication.ts +0 -49
  4. package/src/actions/authorization.spec.ts +0 -377
  5. package/src/actions/authorization.ts +0 -120
  6. package/src/actions/preferences.spec.ts +0 -41
  7. package/src/actions/preferences.ts +0 -41
  8. package/src/actions/storage.ts +0 -22
  9. package/src/actions/userData.spec.ts +0 -133
  10. package/src/actions/userData.ts +0 -68
  11. package/src/autologin/index.spec.ts +0 -264
  12. package/src/autologin/index.ts +0 -113
  13. package/src/autologin/thirdPartyCookie.spec.ts +0 -95
  14. package/src/autologin/thirdPartyCookie.ts +0 -55
  15. package/src/cache/engines/global.spec.ts +0 -62
  16. package/src/cache/engines/global.ts +0 -49
  17. package/src/cache/index.spec.ts +0 -132
  18. package/src/cache/index.ts +0 -48
  19. package/src/cache/types.ts +0 -12
  20. package/src/clients/europa.spec.ts +0 -209
  21. package/src/clients/europa.ts +0 -183
  22. package/src/clients/jupiter.spec.ts +0 -178
  23. package/src/clients/jupiter.ts +0 -119
  24. package/src/clients/mercury.spec.ts +0 -126
  25. package/src/clients/mercury.ts +0 -105
  26. package/src/clients/mercuryLog.spec.ts +0 -20
  27. package/src/clients/mercuryLog.ts +0 -67
  28. package/src/clients/nebula.spec.ts +0 -70
  29. package/src/clients/nebula.ts +0 -83
  30. package/src/clients/pluto.spec.ts +0 -262
  31. package/src/clients/pluto.ts +0 -126
  32. package/src/eventHandlers/activation.ts +0 -40
  33. package/src/eventHandlers/authentication.ts +0 -34
  34. package/src/eventHandlers/eventMap.ts +0 -40
  35. package/src/eventHandlers/navigation.spec.ts +0 -189
  36. package/src/eventHandlers/navigation.ts +0 -58
  37. package/src/eventHandlers/state.spec.ts +0 -48
  38. package/src/eventHandlers/state.ts +0 -23
  39. package/src/eventHandlers/storage.spec.ts +0 -114
  40. package/src/eventHandlers/storage.ts +0 -45
  41. package/src/eventHandlers/userAttributes.spec.ts +0 -93
  42. package/src/eventHandlers/userAttributes.ts +0 -31
  43. package/src/exceptions/FetchTimeoutError.ts +0 -8
  44. package/src/exceptions/PaywallError.ts +0 -16
  45. package/src/index-authentcation.spec.ts +0 -26
  46. package/src/index-storage.spec.ts +0 -144
  47. package/src/index-subscription.spec.ts +0 -213
  48. package/src/index.ts +0 -46
  49. package/src/janitor/index.spec.ts +0 -18
  50. package/src/janitor/index.ts +0 -60
  51. package/src/janitor/jobs/accessCookieRefresher.spec.ts +0 -213
  52. package/src/janitor/jobs/accessCookieRefresher.ts +0 -96
  53. package/src/janitor/jobs/daxsubCookie.spec.ts +0 -109
  54. package/src/janitor/jobs/daxsubCookie.ts +0 -38
  55. package/src/janitor/jobs/removeUserStorage.spec.ts +0 -34
  56. package/src/janitor/jobs/removeUserStorage.ts +0 -12
  57. package/src/lib/PaywallUnlockRequest.spec.ts +0 -446
  58. package/src/lib/PaywallUnlockRequest.ts +0 -161
  59. package/src/lib/UserDataRequest.spec.ts +0 -231
  60. package/src/lib/UserDataRequest.ts +0 -267
  61. package/src/lib/cookie.ts +0 -121
  62. package/src/lib/rpc.ts +0 -19
  63. package/src/store/index.spec.ts +0 -49
  64. package/src/store/index.ts +0 -66
  65. package/src/types.ts +0 -22
  66. package/src/utils/customEventWrapper.spec.ts +0 -237
  67. package/src/utils/customEventWrapper.ts +0 -77
  68. package/src/utils/debouncer.spec.ts +0 -252
  69. package/src/utils/debouncer.ts +0 -123
  70. package/src/utils/deepEquals.ts +0 -42
  71. package/src/utils/expectBootLogs.ts +0 -9
  72. package/src/utils/getGlobalThis.ts +0 -17
  73. package/src/utils/getOrUpdate.spec.ts +0 -166
  74. package/src/utils/getOrUpdate.ts +0 -66
  75. package/src/utils/localhostCheck.ts +0 -10
  76. package/src/utils/location.spec.ts +0 -61
  77. package/src/utils/location.ts +0 -16
  78. package/src/utils/log.spec.ts +0 -177
  79. package/src/utils/log.ts +0 -112
  80. package/src/utils/loginState.ts +0 -24
  81. package/src/utils/networkError.ts +0 -11
  82. package/src/utils/queue.ts +0 -32
  83. package/src/utils/type.ts +0 -19
  84. package/src/utils/url.spec.ts +0 -33
  85. package/src/utils/url.ts +0 -37
@@ -1,231 +0,0 @@
1
- import store from '../store';
2
- import UserDataRequest from './UserDataRequest';
3
- import { listenForUserAttributeRequests } from '../eventHandlers/userAttributes';
4
- import { listenForStateRequests } from '../eventHandlers/state';
5
- import { listenForStorageRequests } from '../eventHandlers/storage';
6
- import * as europa from '../clients/europa';
7
- import * as localhostCheck from '../utils/localhostCheck';
8
- import FetchTimeoutError from '../exceptions/FetchTimeoutError';
9
-
10
- beforeEach(() => {
11
- store.clear();
12
-
13
- listenForUserAttributeRequests();
14
- listenForStateRequests();
15
- listenForStorageRequests();
16
- });
17
-
18
- describe('UserDataRequest', () => {
19
- describe('When running on localhost', () => {
20
- beforeEach(() => {
21
- jest.spyOn(localhostCheck, 'isRunningOnLocalhost').mockReturnValue(true);
22
- });
23
-
24
- it('should fail with expected error', async () => {
25
- try {
26
- await new UserDataRequest().withAttributes(['name']).fetch();
27
- } catch (e) {
28
- expect(e).toEqual(new Error('@amedia/user cannot run on localhost'));
29
- }
30
- });
31
- });
32
-
33
- describe('when fetching', () => {
34
- describe('and is logged in', () => {
35
- beforeEach(() => {
36
- store.set('state', { isLoggedIn: true });
37
- store.set('userAttributes', {
38
- uuid: 'uuid',
39
- name: 'Donald Duck',
40
- });
41
- });
42
-
43
- describe('and already have all requested attributes', () => {
44
- let response: any;
45
- beforeEach(async () => {
46
- response = await new UserDataRequest()
47
- .withAttributes(['name'])
48
- .fetch();
49
- });
50
-
51
- it('should have resolved to include name', () => {
52
- expect(response.attributes).toEqual({ name: 'Donald Duck' });
53
- });
54
-
55
- it('should be logged in', () => {
56
- expect(response.state).toEqual({ isLoggedIn: true });
57
- });
58
- });
59
- });
60
-
61
- describe('and not logged in', () => {
62
- beforeEach(() => {
63
- store.set('state', { isLoggedIn: false });
64
- });
65
-
66
- describe('when getting storage', () => {
67
- beforeEach(async () => {
68
- spyOn(europa, 'getNamespaces');
69
- await new UserDataRequest().withStorage(['euucp']).fetch();
70
- });
71
-
72
- it('should not request data', () => {
73
- expect(europa.getNamespaces).not.toHaveBeenCalled();
74
- });
75
- });
76
- });
77
-
78
- describe('and not receiving data', () => {
79
- let fetchPromise: Promise<Record<string, unknown>>;
80
- let onFakeData: (data: any) => void;
81
- beforeEach(() => {
82
- jest.useFakeTimers();
83
- spyOn(UserDataRequest.prototype, 'subscribe').and.callFake((onData) => {
84
- onFakeData = onData;
85
- });
86
- fetchPromise = new UserDataRequest()
87
- .withAttributes(['name', 'trackingKey'])
88
- .withStorage(['privacy_preferences'])
89
- .fetch();
90
- });
91
-
92
- afterEach(() => {
93
- jest.useRealTimers();
94
- });
95
-
96
- describe('at all', () => {
97
- beforeEach(() => {
98
- jest.advanceTimersByTime(UserDataRequest.FETCH_TIMEOUT);
99
- });
100
-
101
- it('should reject after timeout', () =>
102
- expect(fetchPromise).rejects.toEqual(
103
- new FetchTimeoutError(
104
- '@amedia/user timed out while waiting for {"attributes":["name","trackingKey"],"namespaces":["privacy_preferences"]}',
105
- {}
106
- )
107
- ));
108
-
109
- it('should include partially fetched data in error', () =>
110
- fetchPromise.catch((error: FetchTimeoutError) => {
111
- expect(error.partialData).toEqual({});
112
- }));
113
- });
114
-
115
- describe('with name received', () => {
116
- beforeEach(() => {
117
- jest.advanceTimersByTime(UserDataRequest.FETCH_TIMEOUT - 1);
118
- onFakeData({
119
- state: { isLoggedIn: true },
120
- attributes: { name: 'Donald Duck' },
121
- });
122
- jest.advanceTimersByTime(UserDataRequest.FETCH_TIMEOUT);
123
- });
124
-
125
- it('should not include name', () =>
126
- expect(fetchPromise).rejects.toEqual(
127
- new Error(
128
- '@amedia/user timed out while waiting for {"attributes":["trackingKey"],"namespaces":["privacy_preferences"]}'
129
- )
130
- ));
131
-
132
- it('should include partially fetched data in error', () =>
133
- fetchPromise.catch((error: FetchTimeoutError) => {
134
- expect(error.partialData).toEqual({
135
- attributes: {
136
- name: 'Donald Duck',
137
- },
138
- state: {
139
- isLoggedIn: true,
140
- },
141
- });
142
- }));
143
- });
144
-
145
- describe('with all attributes fulfilled', () => {
146
- beforeEach(() => {
147
- jest.advanceTimersByTime(UserDataRequest.FETCH_TIMEOUT - 1);
148
- onFakeData({
149
- state: { isLoggedIn: true },
150
- attributes: { name: 'Donald Duck', trackingKey: '123' },
151
- });
152
- jest.advanceTimersByTime(UserDataRequest.FETCH_TIMEOUT);
153
- });
154
-
155
- it('should only wait for storage', () =>
156
- expect(fetchPromise).rejects.toEqual(
157
- new Error(
158
- '@amedia/user timed out while waiting for {"attributes":[],"namespaces":["privacy_preferences"]}'
159
- )
160
- ));
161
-
162
- it('should include partially fetched data in error', () =>
163
- fetchPromise.catch((error: FetchTimeoutError) => {
164
- expect(error.partialData).toEqual({
165
- attributes: {
166
- name: 'Donald Duck',
167
- trackingKey: '123',
168
- },
169
- state: {
170
- isLoggedIn: true,
171
- },
172
- });
173
- }));
174
- });
175
-
176
- describe('with storage fulfilled', () => {
177
- beforeEach(() => {
178
- jest.advanceTimersByTime(UserDataRequest.FETCH_TIMEOUT - 1);
179
- onFakeData({
180
- state: { isLoggedIn: true },
181
- storage: { privacy_preferences: { allow_research_usage: 'true' } },
182
- });
183
- jest.advanceTimersByTime(UserDataRequest.FETCH_TIMEOUT);
184
- });
185
-
186
- it('should only wait for storage', () =>
187
- expect(fetchPromise).rejects.toEqual(
188
- new Error(
189
- '@amedia/user timed out while waiting for {"attributes":["name","trackingKey"],"namespaces":[]}'
190
- )
191
- ));
192
-
193
- it('should include partially fetched data in error', () =>
194
- fetchPromise.catch((error: FetchTimeoutError) => {
195
- expect(error.partialData).toEqual({
196
- storage: {
197
- privacy_preferences: {
198
- allow_research_usage: 'true',
199
- },
200
- },
201
- state: {
202
- isLoggedIn: true,
203
- },
204
- });
205
- }));
206
- });
207
- });
208
-
209
- describe('with custom timeout', () => {
210
- let fetchPromise: Promise<Record<string, unknown>>;
211
- beforeEach(() => {
212
- jest.useFakeTimers();
213
- spyOn(UserDataRequest.prototype, 'subscribe').and.stub();
214
- fetchPromise = new UserDataRequest().fetch({ timeout: 10 });
215
- jest.advanceTimersByTime(10);
216
- });
217
-
218
- afterEach(() => {
219
- jest.useRealTimers();
220
- });
221
-
222
- it('should reject after overridden timeout', () =>
223
- expect(fetchPromise).rejects.toEqual(
224
- new FetchTimeoutError(
225
- '@amedia/user timed out while waiting for {}',
226
- {}
227
- )
228
- ));
229
- });
230
- });
231
- });
@@ -1,267 +0,0 @@
1
- /* eslint-disable @typescript-eslint/dot-notation */
2
- import { State, UserAttributes } from '../types';
3
- import { dispatch, listenForAllEvents } from '../utils/customEventWrapper';
4
- import { AmediaUserEvents } from '../eventHandlers/eventMap';
5
- import { deepEquals } from '../utils/deepEquals';
6
- import { isRunningOnLocalhost } from '../utils/localhostCheck';
7
- import FetchTimeoutError from '../exceptions/FetchTimeoutError';
8
-
9
- type Millis = number;
10
-
11
- function isMissingData(requestedKeys?: any[], data?: Object) {
12
- if (requestedKeys && requestedKeys.length > 0) {
13
- if (data && Object.keys(data).length > 0) {
14
- return (
15
- requestedKeys.filter((a) => !Object.keys(data).includes(a)).length > 0
16
- );
17
- }
18
- return true;
19
- }
20
- return false;
21
- }
22
-
23
- const findMissingKeys = (a: any[] | undefined, b: object | undefined) =>
24
- a?.filter((e) => !Object.keys(b || []).includes(e));
25
-
26
- class UserDataRequest<
27
- UA extends UserAttributes,
28
- S extends { [index: string]: unknown },
29
- Attributes extends Array<keyof UA>,
30
- Namespaces extends Array<string>,
31
- SubscribeResponse extends Record<string, object> = { state: State }
32
- > {
33
- static FETCH_TIMEOUT: Millis = 10000;
34
-
35
- // Node and web cannot agree on a type and a union type was not accepted.
36
- private fetchTimeoutId: any;
37
-
38
- private lastReceivedData?: SubscribeResponse;
39
-
40
- constructor(
41
- private attributes?: Attributes,
42
- private namespaces?: Namespaces
43
- ) {}
44
-
45
- withAttributes<NewAttributes extends Array<keyof UA>>(
46
- attributes: NewAttributes
47
- ) {
48
- return new UserDataRequest<
49
- UA,
50
- S,
51
- Array<Attributes[number] & NewAttributes[number]>,
52
- Namespaces,
53
- SubscribeResponse & {
54
- attributes: Pick<UA, Attributes[number] & NewAttributes[number]>;
55
- }
56
- >(
57
- [...((this.attributes || ([] as unknown)) as Attributes), ...attributes],
58
- this.namespaces
59
- );
60
- }
61
-
62
- withStorage<NewNamespaces extends Array<string>>(namespaces: NewNamespaces) {
63
- return new UserDataRequest<
64
- UA,
65
- S,
66
- Attributes,
67
- Array<Namespaces[number] & NewNamespaces[number]>,
68
- SubscribeResponse & {
69
- storage: Pick<S, Namespaces[number] & NewNamespaces[number]>;
70
- }
71
- >(this.attributes, [
72
- ...((this.namespaces || ([] as unknown)) as Namespaces),
73
- ...namespaces,
74
- ]);
75
- }
76
-
77
- subscribe(onData: (data: SubscribeResponse) => void): void {
78
- let previousData = this.setupLocalCache();
79
- if (isRunningOnLocalhost()) {
80
- onData(previousData);
81
- return;
82
- }
83
- listenForAllEvents(AmediaUserEvents.ON_STATE_UPDATED, (evt) => {
84
- const state = evt.detail;
85
- if (
86
- // eslint-disable-next-line @typescript-eslint/dot-notation
87
- Object.keys(previousData['state']).length > 0 &&
88
- // eslint-disable-next-line @typescript-eslint/dot-notation
89
- deepEquals(previousData['state'], state)
90
- ) {
91
- return;
92
- }
93
-
94
- previousData = { ...previousData, state };
95
- onData(previousData);
96
- });
97
- dispatch(new CustomEvent(AmediaUserEvents.REQUEST_STATE));
98
-
99
- if (Array.isArray(this.attributes) && this.attributes.length > 0) {
100
- listenForAllEvents(AmediaUserEvents.ON_ATTRIBUTES_UPDATED, (evt) => {
101
- const responseAttributes = this.processUserAttributesEvent(evt);
102
-
103
- if (
104
- // eslint-disable-next-line @typescript-eslint/dot-notation
105
- Object.keys(previousData['attributes']).length > 0 &&
106
- // eslint-disable-next-line @typescript-eslint/dot-notation
107
- deepEquals(previousData['attributes'], responseAttributes)
108
- ) {
109
- return;
110
- }
111
-
112
- previousData = { ...previousData, attributes: responseAttributes };
113
- onData(previousData);
114
- });
115
- dispatch(
116
- new CustomEvent(AmediaUserEvents.REQUEST_USER_ATTRIBUTES, {
117
- detail: [...this.attributes, 'uuid'],
118
- })
119
- );
120
- }
121
-
122
- if (Array.isArray(this.namespaces) && this.namespaces.length > 0) {
123
- listenForAllEvents(AmediaUserEvents.ON_STORAGE_UPDATED, (evt) => {
124
- const responseStorage = this.processStorageEvent(evt);
125
-
126
- // eslint-disable-next-line @typescript-eslint/dot-notation
127
- if (deepEquals(previousData['storage'], responseStorage)) {
128
- return;
129
- }
130
-
131
- previousData = { ...previousData, storage: responseStorage };
132
- onData(previousData);
133
- });
134
- dispatch(
135
- new CustomEvent(AmediaUserEvents.REQUEST_STORAGE_NAMESPACES, {
136
- detail: this.namespaces,
137
- })
138
- );
139
- }
140
- }
141
-
142
- fetch(options?: { timeout?: Millis }): Promise<SubscribeResponse> {
143
- return new Promise<SubscribeResponse>((resolve, reject) => {
144
- if (isRunningOnLocalhost()) {
145
- reject(new Error('@amedia/user cannot run on localhost'));
146
- }
147
-
148
- // Set a limit for how long we will accept waiting for data
149
- this.startFetchTimeout(reject, options?.timeout);
150
-
151
- this.subscribe((data: any) => {
152
- // In case of slow network conditions we increase waiting time when some data is received
153
- this.clearFetchTimeout();
154
- this.startFetchTimeout(reject, options?.timeout);
155
- this.lastReceivedData = data;
156
-
157
- // @ts-ignore
158
- if (typeof data.state.isLoggedIn === 'undefined') {
159
- return;
160
- }
161
-
162
- // @ts-ignore
163
- if (data.state.isLoggedIn === false) {
164
- if (
165
- this.attributes?.includes('extraData') &&
166
- !Object.keys(data.attributes).includes('extraData')
167
- ) {
168
- return; // ExtraData is valid even for logged out users
169
- }
170
- resolve(data);
171
- return;
172
- }
173
-
174
- if (
175
- isMissingData(this.attributes, data.attributes) ||
176
- isMissingData(this.namespaces, data.storage)
177
- ) {
178
- return;
179
- }
180
-
181
- resolve(data);
182
- });
183
- }).then((data) => {
184
- this.clearFetchTimeout();
185
- return data;
186
- });
187
- }
188
-
189
- private clearFetchTimeout() {
190
- if (this.fetchTimeoutId) {
191
- clearTimeout(this.fetchTimeoutId);
192
- }
193
- }
194
-
195
- private startFetchTimeout(
196
- promiseRejectCallback: (error: Error) => void,
197
- timeout?: number
198
- ) {
199
- this.fetchTimeoutId = setTimeout(() => {
200
- promiseRejectCallback(
201
- new FetchTimeoutError(
202
- `@amedia/user timed out while waiting for ${JSON.stringify({
203
- attributes: findMissingKeys(
204
- this.attributes,
205
- this.lastReceivedData?.attributes
206
- ),
207
- namespaces: findMissingKeys(
208
- this.namespaces,
209
- this.lastReceivedData?.storage
210
- ),
211
- })}`,
212
- this.lastReceivedData || {}
213
- )
214
- );
215
- }, timeout || UserDataRequest.FETCH_TIMEOUT);
216
- }
217
-
218
- private processUserAttributesEvent(evt: CustomEvent<UserAttributes>) {
219
- const userAttributes = evt.detail as UA;
220
-
221
- // Reduce responseAttributes to match requested attributes
222
- // @ts-ignore Cannot be undefined. Guarded above
223
- const responseAttributes = this.attributes.reduce((map, attribute) => {
224
- if (userAttributes[attribute] !== undefined) {
225
- // @ts-ignore
226
- // eslint-disable-next-line no-param-reassign
227
- map[attribute] = userAttributes[attribute];
228
- }
229
- return map;
230
- }, {} as UA);
231
- return responseAttributes;
232
- }
233
-
234
- private processStorageEvent(evt: CustomEvent<{ [index: string]: unknown }>) {
235
- const storage = evt.detail as S;
236
-
237
- // Reduce responseAttributes to match requested attributes
238
- return (
239
- this.namespaces &&
240
- this.namespaces.reduce((map, namespace) => {
241
- if (storage[namespace] !== undefined) {
242
- // @ts-ignore
243
- // eslint-disable-next-line no-param-reassign
244
- map[namespace] = storage[namespace];
245
- }
246
- return map;
247
- }, {} as S)
248
- );
249
- }
250
-
251
- private setupLocalCache() {
252
- // @ts-ignore
253
- let previousData: SubscribeResponse = {
254
- state: {},
255
- };
256
- if (this.attributes && this.attributes.length > 0) {
257
- previousData = { ...previousData, attributes: {} };
258
- }
259
-
260
- if (this.namespaces && this.namespaces.length > 0) {
261
- previousData = { ...previousData, storage: {} };
262
- }
263
- return previousData;
264
- }
265
- }
266
-
267
- export default UserDataRequest;
package/src/lib/cookie.ts DELETED
@@ -1,121 +0,0 @@
1
- const getCookieValue = (
2
- nameEQ: string,
3
- c: string
4
- ): undefined | null | string | { [index: string]: unknown } => {
5
- const value = c.substring(nameEQ.length, c.length);
6
-
7
- if (value.substring(0, 1) === '{') {
8
- return JSON.parse(value);
9
- }
10
-
11
- if (value.substring(0, 3) === '%7B') {
12
- return JSON.parse(decodeURIComponent(value));
13
- }
14
-
15
- if (value === 'undefined') {
16
- return undefined;
17
- }
18
-
19
- if (value === '' || value === 'null') {
20
- return null;
21
- }
22
-
23
- return value;
24
- };
25
-
26
- export const getCookie = (name: string) => {
27
- const nameEQ = `${name}=`;
28
- const ca = document.cookie.split(';');
29
-
30
- for (let i = ca.length - 1; i >= 0; i -= 1) {
31
- const c = ca[i].trim();
32
- if (c.indexOf(nameEQ) === 0) {
33
- return getCookieValue(nameEQ, c);
34
- }
35
- }
36
- return null;
37
- };
38
-
39
- const setValidTime = (date: Date, validTimeDateOrDays?: Date | number) => {
40
- if (!validTimeDateOrDays) {
41
- return '';
42
- }
43
-
44
- if (validTimeDateOrDays instanceof Date) {
45
- return `; expires=${validTimeDateOrDays.toUTCString()}`;
46
- }
47
- /* Assume validTime is given in days */
48
- date.setTime(date.getTime() + validTimeDateOrDays * 24 * 60 * 60 * 1000);
49
- return `; expires=${date.toUTCString()}`;
50
- };
51
-
52
- const setValue = (value: unknown): string => {
53
- if (!value || value === '') {
54
- return '';
55
- }
56
- if (value instanceof Object) {
57
- return encodeURIComponent(JSON.stringify(value));
58
- }
59
-
60
- if (typeof value === 'number') {
61
- return value.toString(10);
62
- }
63
- return <string>value;
64
- };
65
-
66
- export function setCookie(
67
- name: string,
68
- value?: unknown,
69
- validTimeInDateOrDays: Date | number = Date.now(),
70
- path = '/',
71
- secure: boolean = false
72
- ) {
73
- const date = new Date();
74
-
75
- let cookiestring = `${name}=`;
76
-
77
- /* If value is empty or not set, handle as a cookie delete */
78
- if (!value || value === '') {
79
- // eslint-disable-next-line no-param-reassign
80
- validTimeInDateOrDays = -1;
81
- }
82
-
83
- cookiestring += setValue(value);
84
- cookiestring += setValidTime(date, validTimeInDateOrDays);
85
- cookiestring += `; path=${path}`;
86
-
87
- if (secure) {
88
- cookiestring += '; secure';
89
- }
90
-
91
- document.cookie = cookiestring;
92
-
93
- if (
94
- validTimeInDateOrDays &&
95
- validTimeInDateOrDays !== -1 &&
96
- getCookie(name) === null
97
- ) {
98
- /**
99
- * IE has a mode where user can choose to only accept session cookies, if we were unable to set it with
100
- * expires, we need to try setting it without expires to trigger setting it as session cookie for these users.
101
- */
102
- document.cookie = cookiestring.replace(/; expires=[^;]*/, '');
103
- }
104
- return cookiestring;
105
- }
106
-
107
- export function removeCookie(name: string): void {
108
- setCookie(name);
109
- }
110
-
111
- /**
112
- * This function should only be used in tests, as it will remove all cookies a user has on the domain.
113
- */
114
- export function removeAllCookies() {
115
- const cookies = document.cookie.split(';');
116
-
117
- cookies.forEach((cookieToDelete) => {
118
- const eqPos = cookieToDelete.indexOf('=');
119
- removeCookie(eqPos > -1 ? cookieToDelete.substr(0, eqPos) : cookieToDelete);
120
- });
121
- }
package/src/lib/rpc.ts DELETED
@@ -1,19 +0,0 @@
1
- import { RPCclient } from '@amedia/frontend-rpc';
2
-
3
- interface LocalRPCclient extends RPCclient {
4
- userAuthenticated: (isLoggedIn: boolean) => void;
5
- }
6
-
7
- let rpcSessionClient: LocalRPCclient;
8
- export const getRPCClient = (): LocalRPCclient => {
9
- if (rpcSessionClient) {
10
- return rpcSessionClient;
11
- }
12
- rpcSessionClient = new RPCclient({
13
- version: '1.0.0',
14
- component: `userdata-session`,
15
- methods: ['userAuthenticated'],
16
- }) as LocalRPCclient;
17
-
18
- return rpcSessionClient;
19
- };
@@ -1,49 +0,0 @@
1
- import store from '.';
2
-
3
- beforeEach(() => {
4
- store.clear();
5
- });
6
-
7
- describe('Store', () => {
8
- it('should set in store', () => {
9
- store.merge('userAttributes', { access: ['newspaper'] });
10
- expect(store.get('userAttributes')).toEqual({ access: ['newspaper'] });
11
- });
12
-
13
- it('should append in store', () => {
14
- store.merge('userAttributes', { access: ['newspaper'] });
15
- store.merge('userAttributes', { name: 'foo' });
16
- expect(store.get('userAttributes')).toEqual({
17
- name: 'foo',
18
- access: ['newspaper'],
19
- });
20
- });
21
-
22
- it('should replace in store', () => {
23
- store.merge('userAttributes', { access: ['newspaper'] });
24
- store.set('userAttributes', {});
25
- expect(store.get('userAttributes')).toEqual({});
26
- });
27
-
28
- it('should emit on change', () => {
29
- const listenerSpy = jest.fn();
30
- store.on('userAttributes', listenerSpy);
31
- expect(listenerSpy).not.toHaveBeenCalled();
32
- store.merge('userAttributes', { name: 'Donald' });
33
- expect(listenerSpy).toHaveBeenCalledWith({ name: 'Donald' });
34
- });
35
-
36
- it('should emit to multiple relevant', () => {
37
- const listenerSpy1 = jest.fn();
38
- const listenerSpy2 = jest.fn();
39
- const listenerSpy3 = jest.fn();
40
- store.on('userAttributes', listenerSpy1);
41
- store.on('userAttributes', listenerSpy2);
42
- store.on('state', listenerSpy3);
43
-
44
- store.merge('userAttributes', { name: 'Donald' });
45
- expect(listenerSpy1).toHaveBeenCalledWith({ name: 'Donald' });
46
- expect(listenerSpy2).toHaveBeenCalledWith({ name: 'Donald' });
47
- expect(listenerSpy3).not.toHaveBeenCalled();
48
- });
49
- });