@amedia/user 0.13.35 → 0.13.37

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 (179) hide show
  1. package/dist/user.cjs +1 -1
  2. package/dist/user.cjs.map +3 -3
  3. package/dist/user.d.ts +15 -1
  4. package/dist/user.js +1 -1
  5. package/dist/user.js.map +3 -3
  6. package/package.json +5 -2
  7. package/.codeclimate.yml +0 -8
  8. package/.eslintignore +0 -2
  9. package/.eslintrc +0 -11
  10. package/.prettierrc.json +0 -1
  11. package/@types/amedia-frontend-rpc.d.ts +0 -11
  12. package/@types/browserid.d.ts +0 -4
  13. package/build.js +0 -28
  14. package/checkVersion.cjs +0 -12
  15. package/cloudbuild.json +0 -29
  16. package/cop.json +0 -8
  17. package/dist/actions/authentication.d.ts +0 -4
  18. package/dist/actions/authentication.spec.d.ts +0 -1
  19. package/dist/actions/authorization.d.ts +0 -14
  20. package/dist/actions/authorization.spec.d.ts +0 -4
  21. package/dist/actions/preferences.d.ts +0 -9
  22. package/dist/actions/preferences.spec.d.ts +0 -1
  23. package/dist/actions/storage.d.ts +0 -7
  24. package/dist/actions/userData.d.ts +0 -2
  25. package/dist/actions/userData.spec.d.ts +0 -1
  26. package/dist/autologin/index.d.ts +0 -7
  27. package/dist/autologin/index.spec.d.ts +0 -1
  28. package/dist/autologin/thirdPartyCookie.d.ts +0 -3
  29. package/dist/autologin/thirdPartyCookie.spec.d.ts +0 -1
  30. package/dist/cache/engines/global.d.ts +0 -24
  31. package/dist/cache/engines/global.spec.d.ts +0 -1
  32. package/dist/cache/index.d.ts +0 -11
  33. package/dist/cache/index.spec.d.ts +0 -1
  34. package/dist/cache/types.d.ts +0 -11
  35. package/dist/clients/europa.d.ts +0 -24
  36. package/dist/clients/europa.spec.d.ts +0 -1
  37. package/dist/clients/jupiter.d.ts +0 -30
  38. package/dist/clients/jupiter.spec.d.ts +0 -1
  39. package/dist/clients/mercury.d.ts +0 -3
  40. package/dist/clients/mercury.spec.d.ts +0 -1
  41. package/dist/clients/mercuryLog.d.ts +0 -8
  42. package/dist/clients/mercuryLog.spec.d.ts +0 -1
  43. package/dist/clients/nebula.d.ts +0 -2
  44. package/dist/clients/nebula.spec.d.ts +0 -1
  45. package/dist/clients/pluto.d.ts +0 -4
  46. package/dist/clients/pluto.spec.d.ts +0 -1
  47. package/dist/eventHandlers/activation.d.ts +0 -15
  48. package/dist/eventHandlers/authentication.d.ts +0 -17
  49. package/dist/eventHandlers/eventMap.d.ts +0 -29
  50. package/dist/eventHandlers/state.d.ts +0 -1
  51. package/dist/eventHandlers/state.spec.d.ts +0 -1
  52. package/dist/eventHandlers/storage.d.ts +0 -1
  53. package/dist/eventHandlers/storage.spec.d.ts +0 -1
  54. package/dist/eventHandlers/userAttributes.d.ts +0 -1
  55. package/dist/eventHandlers/userAttributes.spec.d.ts +0 -1
  56. package/dist/exceptions/PaywallError.d.ts +0 -8
  57. package/dist/index-authentcation.spec.d.ts +0 -1
  58. package/dist/index-storage.spec.d.ts +0 -1
  59. package/dist/index-subscription.spec.d.ts +0 -1
  60. package/dist/index.d.ts +0 -20
  61. package/dist/janitor/index.d.ts +0 -10
  62. package/dist/janitor/index.spec.d.ts +0 -1
  63. package/dist/janitor/jobs/accessCookieRefresher.d.ts +0 -1
  64. package/dist/janitor/jobs/accessCookieRefresher.spec.d.ts +0 -1
  65. package/dist/janitor/jobs/daxsubCookie.d.ts +0 -3
  66. package/dist/janitor/jobs/daxsubCookie.spec.d.ts +0 -1
  67. package/dist/janitor/jobs/removeUserStorage.d.ts +0 -1
  68. package/dist/janitor/jobs/removeUserStorage.spec.d.ts +0 -1
  69. package/dist/lib/PaywallUnlockRequest.d.ts +0 -17
  70. package/dist/lib/PaywallUnlockRequest.spec.d.ts +0 -1
  71. package/dist/lib/UserDataRequest.d.ts +0 -22
  72. package/dist/lib/UserDataRequest.spec.d.ts +0 -1
  73. package/dist/lib/cookie.d.ts +0 -9
  74. package/dist/lib/rpc.d.ts +0 -6
  75. package/dist/store/index.d.ts +0 -23
  76. package/dist/store/index.spec.d.ts +0 -1
  77. package/dist/types.d.ts +0 -22
  78. package/dist/utils/customEventWrapper.d.ts +0 -19
  79. package/dist/utils/debouncer.d.ts +0 -26
  80. package/dist/utils/debouncer.spec.d.ts +0 -1
  81. package/dist/utils/deepEquals.d.ts +0 -1
  82. package/dist/utils/expectBootLogs.d.ts +0 -2
  83. package/dist/utils/getOrUpdate.d.ts +0 -6
  84. package/dist/utils/getOrUpdate.spec.d.ts +0 -1
  85. package/dist/utils/localhostCheck.d.ts +0 -1
  86. package/dist/utils/location.d.ts +0 -3
  87. package/dist/utils/log.d.ts +0 -9
  88. package/dist/utils/log.spec.d.ts +0 -1
  89. package/dist/utils/loginState.d.ts +0 -2
  90. package/dist/utils/networkError.d.ts +0 -1
  91. package/dist/utils/queue.d.ts +0 -12
  92. package/dist/utils/type.d.ts +0 -6
  93. package/dist/utils/url.d.ts +0 -6
  94. package/dist/utils/url.spec.d.ts +0 -1
  95. package/eik.json +0 -10
  96. package/global.d.ts +0 -1
  97. package/jest.config.js +0 -7
  98. package/setupJest.js +0 -1
  99. package/src/actions/authentication.spec.ts +0 -51
  100. package/src/actions/authentication.ts +0 -43
  101. package/src/actions/authorization.spec.ts +0 -369
  102. package/src/actions/authorization.ts +0 -117
  103. package/src/actions/preferences.spec.ts +0 -41
  104. package/src/actions/preferences.ts +0 -41
  105. package/src/actions/storage.ts +0 -22
  106. package/src/actions/userData.spec.ts +0 -133
  107. package/src/actions/userData.ts +0 -68
  108. package/src/autologin/index.spec.ts +0 -239
  109. package/src/autologin/index.ts +0 -92
  110. package/src/autologin/thirdPartyCookie.spec.ts +0 -95
  111. package/src/autologin/thirdPartyCookie.ts +0 -55
  112. package/src/cache/engines/global.spec.ts +0 -62
  113. package/src/cache/engines/global.ts +0 -48
  114. package/src/cache/index.spec.ts +0 -130
  115. package/src/cache/index.ts +0 -48
  116. package/src/cache/types.ts +0 -12
  117. package/src/clients/europa.spec.ts +0 -209
  118. package/src/clients/europa.ts +0 -183
  119. package/src/clients/jupiter.spec.ts +0 -179
  120. package/src/clients/jupiter.ts +0 -119
  121. package/src/clients/mercury.spec.ts +0 -59
  122. package/src/clients/mercury.ts +0 -48
  123. package/src/clients/mercuryLog.spec.ts +0 -20
  124. package/src/clients/mercuryLog.ts +0 -67
  125. package/src/clients/nebula.spec.ts +0 -70
  126. package/src/clients/nebula.ts +0 -83
  127. package/src/clients/pluto.spec.ts +0 -165
  128. package/src/clients/pluto.ts +0 -118
  129. package/src/eventHandlers/activation.ts +0 -35
  130. package/src/eventHandlers/authentication.ts +0 -34
  131. package/src/eventHandlers/eventMap.ts +0 -34
  132. package/src/eventHandlers/state.spec.ts +0 -48
  133. package/src/eventHandlers/state.ts +0 -23
  134. package/src/eventHandlers/storage.spec.ts +0 -114
  135. package/src/eventHandlers/storage.ts +0 -45
  136. package/src/eventHandlers/userAttributes.spec.ts +0 -93
  137. package/src/eventHandlers/userAttributes.ts +0 -31
  138. package/src/exceptions/PaywallError.ts +0 -16
  139. package/src/index-authentcation.spec.ts +0 -26
  140. package/src/index-storage.spec.ts +0 -144
  141. package/src/index-subscription.spec.ts +0 -213
  142. package/src/index.ts +0 -59
  143. package/src/janitor/index.spec.ts +0 -18
  144. package/src/janitor/index.ts +0 -59
  145. package/src/janitor/jobs/accessCookieRefresher.spec.ts +0 -213
  146. package/src/janitor/jobs/accessCookieRefresher.ts +0 -98
  147. package/src/janitor/jobs/daxsubCookie.spec.ts +0 -109
  148. package/src/janitor/jobs/daxsubCookie.ts +0 -38
  149. package/src/janitor/jobs/removeUserStorage.spec.ts +0 -34
  150. package/src/janitor/jobs/removeUserStorage.ts +0 -12
  151. package/src/lib/PaywallUnlockRequest.spec.ts +0 -363
  152. package/src/lib/PaywallUnlockRequest.ts +0 -143
  153. package/src/lib/UserDataRequest.spec.ts +0 -77
  154. package/src/lib/UserDataRequest.ts +0 -213
  155. package/src/lib/cookie.ts +0 -121
  156. package/src/lib/rpc.ts +0 -19
  157. package/src/store/index.spec.ts +0 -49
  158. package/src/store/index.ts +0 -64
  159. package/src/types.ts +0 -22
  160. package/src/utils/customEventWrapper.ts +0 -58
  161. package/src/utils/debouncer.spec.ts +0 -252
  162. package/src/utils/debouncer.ts +0 -123
  163. package/src/utils/deepEquals.ts +0 -42
  164. package/src/utils/expectBootLogs.ts +0 -9
  165. package/src/utils/getOrUpdate.spec.ts +0 -166
  166. package/src/utils/getOrUpdate.ts +0 -66
  167. package/src/utils/localhostCheck.ts +0 -9
  168. package/src/utils/location.ts +0 -31
  169. package/src/utils/log.spec.ts +0 -148
  170. package/src/utils/log.ts +0 -124
  171. package/src/utils/loginState.ts +0 -24
  172. package/src/utils/networkError.ts +0 -11
  173. package/src/utils/queue.ts +0 -32
  174. package/src/utils/type.ts +0 -19
  175. package/src/utils/url.spec.ts +0 -33
  176. package/src/utils/url.ts +0 -35
  177. package/testSetup.js +0 -19
  178. package/tsconfig.eslint.json +0 -24
  179. package/tsconfig.json +0 -18
@@ -1,252 +0,0 @@
1
- import Debouncer from './debouncer';
2
-
3
- describe('Debouncer', () => {
4
- describe('when params is list of arrays and response is key value object', () => {
5
- let debouncer: Debouncer<string[], Record<string, string>>;
6
- const params1 = ['foo', 'bar'];
7
- const params2 = ['baz', '1337'];
8
- describe('when workload succeeds', () => {
9
- beforeEach(() => {
10
- debouncer = new Debouncer<string[], Record<string, string>>(
11
- 10,
12
- [],
13
- Debouncer.stringListParamsAccumulator,
14
- (params) =>
15
- Promise.resolve(
16
- params.reduce(
17
- (map, param): Record<string, string> => ({
18
- ...map,
19
- [param]: param.toUpperCase(),
20
- }),
21
- {} as Record<string, string>
22
- )
23
- )
24
- );
25
- });
26
- describe('when called in quick succession', () => {
27
- let result1: Record<string, string>;
28
- let result2: Record<string, string>;
29
- const expectedResult = {
30
- foo: 'FOO',
31
- bar: 'BAR',
32
- baz: 'BAZ',
33
- 1337: '1337',
34
- };
35
- beforeEach(async () => {
36
- const promise1 = debouncer.perform(params1);
37
- const promise2 = debouncer.perform(params2);
38
- result1 = await promise1;
39
- result2 = await promise2;
40
- });
41
- it('Resolution to first promise is complete set', () => {
42
- expect(result1).toEqual(expectedResult);
43
- });
44
- it('Resolution to second promise is complete set', () => {
45
- expect(result2).toEqual(expectedResult);
46
- });
47
- });
48
- describe('when waiting for first resolution before second call', () => {
49
- let result1: Record<string, string>;
50
- let result2: Record<string, string>;
51
- const expectedResult1 = {
52
- foo: 'FOO',
53
- bar: 'BAR',
54
- };
55
- const expectedResult2 = {
56
- baz: 'BAZ',
57
- 1337: '1337',
58
- };
59
- beforeEach(async () => {
60
- result1 = await debouncer.perform(params1);
61
- result2 = await debouncer.perform(params2);
62
- });
63
- it('Resolution to first promise is only result of first set', () => {
64
- expect(result1).toEqual(expectedResult1);
65
- });
66
- it('Resolution to second promise is only result of second set', () => {
67
- expect(result2).toEqual(expectedResult2);
68
- });
69
- });
70
- });
71
- describe('when workload fails', () => {
72
- beforeEach(() => {
73
- debouncer = new Debouncer<string[], Record<string, string>>(
74
- 10,
75
- [],
76
- Debouncer.stringListParamsAccumulator,
77
- (params) =>
78
- Promise.reject(new Error(`Cannot handle ${params.join(',')}`))
79
- );
80
- });
81
- describe('when called in quick succession', () => {
82
- let result1: string;
83
- let result2: string;
84
- beforeEach(async () => {
85
- const promise1 = debouncer.perform(params1);
86
- const promise2 = debouncer.perform(params2);
87
- try {
88
- await promise1;
89
- } catch (e) {
90
- result1 = e.message;
91
- }
92
- try {
93
- await promise2;
94
- } catch (e) {
95
- result2 = e.message;
96
- }
97
- });
98
- it('Resolution to first promise is error handling all params', () => {
99
- expect(result1).toEqual('Cannot handle foo,bar,baz,1337');
100
- });
101
- it('Resolution to second promise is error handling all params', async () => {
102
- expect(result2).toEqual('Cannot handle foo,bar,baz,1337');
103
- });
104
- });
105
- describe('when waiting for first resolution before second call', () => {
106
- let result1: string;
107
- let result2: string;
108
- beforeEach(async () => {
109
- try {
110
- await debouncer.perform(params1);
111
- } catch (e) {
112
- result1 = e.message;
113
- }
114
- try {
115
- await debouncer.perform(params2);
116
- } catch (e) {
117
- result2 = e.message;
118
- }
119
- });
120
- it('Resolution to first promise is error handling first set', () => {
121
- expect(result1).toEqual('Cannot handle foo,bar');
122
- });
123
- it('Resolution to second promise is error handling second set', () => {
124
- expect(result2).toEqual('Cannot handle baz,1337');
125
- });
126
- });
127
- });
128
- });
129
- describe('when params is key value object response is list of strings', () => {
130
- let debouncer: Debouncer<Record<string, string>, string[]>;
131
- const params1 = {
132
- foo: 'FOO',
133
- bar: 'BAR',
134
- };
135
- const params2 = {
136
- baz: 'BAZ',
137
- 1337: '1337',
138
- };
139
- describe('when workload succeeds', () => {
140
- beforeEach(() => {
141
- debouncer = new Debouncer<Record<string, string>, string[]>(
142
- 10,
143
- {},
144
- Debouncer.stringMapParamsAccumulator,
145
- (params) =>
146
- Promise.resolve(Object.entries(params).map(([k, v]) => `${k}=${v}`))
147
- );
148
- });
149
-
150
- describe('when called in quick succession', () => {
151
- let result1: string[];
152
- let result2: string[];
153
- const expectedResult = ['1337=1337', 'foo=FOO', 'bar=BAR', 'baz=BAZ'];
154
- beforeEach(async () => {
155
- const promise1 = debouncer.perform(params1);
156
- const promise2 = debouncer.perform(params2);
157
- result1 = await promise1;
158
- result2 = await promise2;
159
- });
160
- it('Resolution to first promise is complete set', () => {
161
- expect(result1).toEqual(expectedResult);
162
- });
163
- it('Resolution to second promise is complete set', () => {
164
- expect(result2).toEqual(expectedResult);
165
- });
166
- });
167
- describe('when waiting for first resolution before second call', () => {
168
- let result1: string[];
169
- let result2: string[];
170
- const expectedResult1 = ['foo=FOO', 'bar=BAR'];
171
- const expectedResult2 = ['1337=1337', 'baz=BAZ'];
172
- beforeEach(async () => {
173
- result1 = await debouncer.perform(params1);
174
- result2 = await debouncer.perform(params2);
175
- });
176
- it('Resolution to first promise is only result of first set', () => {
177
- expect(result1).toEqual(expectedResult1);
178
- });
179
- it('Resolution to second promise is only result of second set', () => {
180
- expect(result2).toEqual(expectedResult2);
181
- });
182
- });
183
- });
184
- describe('when workload fails', () => {
185
- beforeEach(() => {
186
- debouncer = new Debouncer<Record<string, string>, string[]>(
187
- 10,
188
- {},
189
- Debouncer.stringMapParamsAccumulator,
190
- (params) =>
191
- Promise.reject(
192
- new Error(
193
- `Cannot handle ${Object.entries(params)
194
- .map(([k, v]) => `${k}=${v}`)
195
- .join(',')}`
196
- )
197
- )
198
- );
199
- });
200
- describe('when called in quick succession', () => {
201
- let result1: string;
202
- let result2: string;
203
- beforeEach(async () => {
204
- const promise1 = debouncer.perform(params1);
205
- const promise2 = debouncer.perform(params2);
206
- try {
207
- await promise1;
208
- } catch (e) {
209
- result1 = e.message;
210
- }
211
- try {
212
- await promise2;
213
- } catch (e) {
214
- result2 = e.message;
215
- }
216
- });
217
- it('Resolution to first promise is error handling all params', () => {
218
- expect(result1).toEqual(
219
- 'Cannot handle 1337=1337,foo=FOO,bar=BAR,baz=BAZ'
220
- );
221
- });
222
- it('Resolution to second promise is error handling all params', async () => {
223
- expect(result2).toEqual(
224
- 'Cannot handle 1337=1337,foo=FOO,bar=BAR,baz=BAZ'
225
- );
226
- });
227
- });
228
- describe('when waiting for first resolution before second call', () => {
229
- let result1: string;
230
- let result2: string;
231
- beforeEach(async () => {
232
- try {
233
- await debouncer.perform(params1);
234
- } catch (e) {
235
- result1 = e.message;
236
- }
237
- try {
238
- await debouncer.perform(params2);
239
- } catch (e) {
240
- result2 = e.message;
241
- }
242
- });
243
- it('Resolution to first promise is error handling first set', () => {
244
- expect(result1).toEqual('Cannot handle foo=FOO,bar=BAR');
245
- });
246
- it('Resolution to second promise is error handling second set', () => {
247
- expect(result2).toEqual('Cannot handle 1337=1337,baz=BAZ');
248
- });
249
- });
250
- });
251
- });
252
- });
@@ -1,123 +0,0 @@
1
- import deepmerge from 'ts-deepmerge';
2
-
3
- /** Naive implementation of deep copy needed for copying parameters when
4
- * merging multiple calls to perform.
5
- *
6
- * @param obj object to copy deeply
7
- */
8
- function deepCopy<T>(obj: T): T {
9
- if (typeof obj === 'string' || obj instanceof String) {
10
- return `${obj}` as unknown as T;
11
- }
12
- if (obj instanceof Array) {
13
- return [...obj].map(deepCopy) as unknown as T;
14
- }
15
- return Object.entries(obj).reduce(
16
- (copy, [k, v]) => ({
17
- ...copy,
18
- [k]: deepCopy(v),
19
- }),
20
- {}
21
- ) as T;
22
- }
23
-
24
- /**
25
- * The Debouncer can be used when we want a clean way to say 'I want to fetch this and that, and once it's done,
26
- * resolve my promise', but instead of the fetch being performed right away, we want to wait for more users to
27
- * request other stuff. This will keep us from performing lots of individual fetches to the backend.
28
- *
29
- * Our main use case is a standard publication front page where one component on the page requests the euucp namespace
30
- * from Europa, and then another component requests the privacy_preferences namespace. Instead of the Europa client
31
- * calling two fetches to the server, one for euucp and another for privacy_preferences, we want the Debouncer to
32
- * aggregate these calls into one call to the backend, that requests both euucp AND privacy_preferences, so the response
33
- * to both components will be both namespaces (which the Europa client can filter before it actually reaches the
34
- * component).
35
- */
36
- class Debouncer<ParamsType, ResultType> {
37
- private timer: ReturnType<typeof setTimeout> | undefined;
38
-
39
- private params: ParamsType;
40
-
41
- private queue: {
42
- resolve: (arg0: any) => void;
43
- reject: (reason?: any) => void;
44
- }[] = [];
45
-
46
- constructor(
47
- // The number of milliseconds to wait for new calls to perform before actually performing workload
48
- private timeoutMs: number,
49
-
50
- // Default parameters if none provided, normally an empty object or list
51
- private defaultParams: ParamsType,
52
-
53
- // Function that can accumulate parameters from successive calls to perform, see examples below
54
- private paramAccumulator: (
55
- previousParams: ParamsType,
56
- newParams: ParamsType
57
- ) => ParamsType,
58
-
59
- // The workload we want to perform on accumulated parameters once timeout has been reached
60
- private workload: (params: ParamsType) => Promise<ResultType>
61
- ) {
62
- this.params = deepCopy(defaultParams);
63
- }
64
-
65
- // Caller indicates that it wants to perform workload on a set of parameters. We will wait this.timeoutMs milliseconds
66
- // and see if we get more calls to perform workload, if we do, we accumulate parameters and wait this.timeoutMs
67
- // more milliseconds until we finally perform workload and resolve promises.
68
- perform(newParams: ParamsType): Promise<ResultType> {
69
- return new Promise((resolve, reject) => {
70
- if (this.timer) {
71
- clearTimeout(this.timer);
72
- }
73
- this.params = this.paramAccumulator(this.params, newParams);
74
- this.queue.push({ resolve, reject });
75
- this.timer = setTimeout(async () => {
76
- // Copy current state to use for performing workload and resolving promises after workload completes
77
- const params = deepCopy(this.params);
78
- const promisesToKeep = [...this.queue];
79
-
80
- // Setup new clean state for future calls to perform
81
- this.params = this.defaultParams;
82
- this.queue = [];
83
-
84
- // Perform workload and resolve promises for all callers with result
85
- this.workload(params)
86
- .then((result) => {
87
- promisesToKeep.forEach((promise) => {
88
- promise.resolve(result);
89
- });
90
- })
91
- .catch((e) => {
92
- // If workload fails, we need to reject all promises so callers won't be left hanging
93
- promisesToKeep.forEach((promise) => {
94
- promise.reject(e);
95
- });
96
- });
97
- }, this.timeoutMs);
98
- });
99
- }
100
-
101
- // Accumulate parameters as lists of strings
102
- static stringListParamsAccumulator(
103
- accumulatedParams: string[],
104
- newParams: string[]
105
- ) {
106
- newParams.forEach((param) => {
107
- if (!accumulatedParams.includes(param)) {
108
- accumulatedParams.push(param);
109
- }
110
- });
111
- return accumulatedParams;
112
- }
113
-
114
- // Accumulate parameters as map with string keys
115
- static stringMapParamsAccumulator(
116
- previousParams: Record<string, any>,
117
- newParams: Record<string, any>
118
- ) {
119
- return deepmerge(previousParams, newParams);
120
- }
121
- }
122
-
123
- export default Debouncer;
@@ -1,42 +0,0 @@
1
- /**
2
- * @see https://dev.to/sanderdebr/deep-equality-checking-of-objects-in-vanilla-javascript-5592
3
- */
4
- import { isFunction, isRecord } from './type';
5
-
6
- export const deepEquals = (a: unknown, b: unknown): boolean => {
7
- if (a === b) {
8
- return true;
9
- }
10
-
11
- if (!isRecord(a) || !isRecord(b) || a === null || b === null) {
12
- return false;
13
- }
14
-
15
- const keysA = Object.keys(a);
16
- const keysB = Object.keys(b);
17
-
18
- if (keysA.length !== keysB.length) {
19
- return false;
20
- }
21
-
22
- // eslint-disable-next-line no-restricted-syntax
23
- for (const key of keysA) {
24
- if (!keysB.includes(key)) {
25
- return false;
26
- }
27
-
28
- const currentA = a[key];
29
- const currentB = b[key];
30
- if (isFunction(currentA) || isFunction(currentB)) {
31
- return isFunction(currentA) && isFunction(currentB)
32
- ? currentA.toString() !== currentB.toString()
33
- : false;
34
- }
35
-
36
- if (!deepEquals(currentA, currentB)) {
37
- return false;
38
- }
39
- }
40
-
41
- return true;
42
- };
@@ -1,9 +0,0 @@
1
- import log from './log';
2
-
3
- jest.spyOn(log, 'warn').mockImplementation();
4
-
5
- export default () => {
6
- expect(log.warn).toHaveBeenCalledWith(
7
- '@amedia/user started on localhost. In this scenario we have no way to resolve any login-, access- or userdata. Expect errors or redirects if you try.'
8
- );
9
- };
@@ -1,166 +0,0 @@
1
- import { Partial, String } from 'runtypes';
2
- import cache from '../cache';
3
- import getOrUpdate from './getOrUpdate';
4
- import queue from './queue';
5
- import spyOn = jest.spyOn;
6
-
7
- const schema = Partial({ field: String, extraField: String });
8
-
9
- beforeEach(async () => {
10
- await cache.clear();
11
- });
12
- describe('getOrUpdate', () => {
13
- it('should fetch if no cache is available', () => {
14
- const fetcher = jest.fn().mockResolvedValue({
15
- ttl: 0,
16
- data: { field: 'fetchedValue' },
17
- });
18
- expect(getOrUpdate('client', schema, fetcher))
19
- .resolves.toEqual({
20
- field: 'fetchedValue',
21
- })
22
- .then(expect(fetcher).toHaveBeenCalled);
23
- });
24
-
25
- it('should add to cache after fetching', async () => {
26
- const cacheSpy = spyOn(cache, 'set');
27
- await getOrUpdate(
28
- 'client',
29
- schema,
30
- jest.fn().mockResolvedValue({
31
- ttl: 10,
32
- data: { field: 'value' },
33
- })
34
- );
35
- expect(cacheSpy).toHaveBeenCalledWith('client', { field: 'value' }, 10);
36
- });
37
-
38
- it('should use cache if available instead of fetching', () => {
39
- spyOn(cache, 'get').mockResolvedValue({
40
- field: 'cachedValue',
41
- });
42
- const fetcher = jest.fn().mockResolvedValue({
43
- ttl: 0,
44
- data: { field: 'fetchedValue' },
45
- });
46
- expect(getOrUpdate('client', schema, fetcher))
47
- .resolves.toEqual({ field: 'cachedValue' })
48
- .then(expect(fetcher).not.toHaveBeenCalled);
49
- });
50
-
51
- it('should allow cache qualifier to override valid result', () => {
52
- spyOn(cache, 'get').mockResolvedValue({
53
- field: 'cachedValue',
54
- });
55
- const fetcher = jest.fn().mockResolvedValue({
56
- ttl: 0,
57
- data: { field: 'fetchedValue' },
58
- });
59
- const qualifier = jest.fn().mockReturnValue(false);
60
- expect(getOrUpdate('client', schema, fetcher, qualifier))
61
- .resolves.toEqual({ field: 'fetchedValue' })
62
- .then(expect(fetcher).toHaveBeenCalled)
63
- .then(() =>
64
- expect(qualifier).toHaveBeenCalledWith({ field: 'cachedValue' })
65
- );
66
- });
67
-
68
- it('should append to existing cache if any', async () => {
69
- spyOn(cache, 'get').mockResolvedValue({
70
- field: 'cachedValue',
71
- });
72
- const cacheSetSpy = spyOn(cache, 'set');
73
- await getOrUpdate(
74
- 'client',
75
- schema,
76
- () => Promise.resolve({ ttl: 0, data: { extraField: 'extraValue' } }),
77
- () => false
78
- );
79
- expect(cacheSetSpy).toHaveBeenCalledWith(
80
- 'client',
81
- { field: 'cachedValue', extraField: 'extraValue' },
82
- 0
83
- );
84
- });
85
-
86
- it('should resolve queue on cached data', (done) => {
87
- let resolvePromise: Function;
88
- const promise = new Promise((resolve) => {
89
- resolvePromise = resolve;
90
- });
91
- spyOn(cache, 'get').mockReturnValue(promise);
92
-
93
- expect(
94
- Promise.all([
95
- getOrUpdate('client', schema, jest.fn()),
96
- getOrUpdate('client', schema, jest.fn()),
97
- getOrUpdate('client', schema, jest.fn()),
98
- ])
99
- )
100
- .resolves.toEqual([
101
- { field: 'value' },
102
- { field: 'value' },
103
- { field: 'value' },
104
- ])
105
- .then(done);
106
-
107
- expect(queue.peekQueueSize('client')).toEqual(3);
108
-
109
- // @ts-ignore It has been assigned. Promise
110
- resolvePromise({ field: 'value' });
111
- });
112
-
113
- it('should resolve queue on fetched data', (done) => {
114
- let resolvePromise: Function;
115
- const promise = new Promise((resolve) => {
116
- resolvePromise = resolve;
117
- });
118
-
119
- spyOn(cache, 'get').mockResolvedValue(null);
120
-
121
- expect(
122
- Promise.all([
123
- getOrUpdate('client', schema, jest.fn().mockReturnValue(promise)),
124
- getOrUpdate('client', schema, jest.fn()),
125
- getOrUpdate('client', schema, jest.fn()),
126
- ])
127
- )
128
- .resolves.toEqual([
129
- { field: 'value' },
130
- { field: 'value' },
131
- { field: 'value' },
132
- ])
133
- .then(() => expect(queue.peekQueueSize('client')).toEqual(0))
134
- .then(done);
135
-
136
- expect(queue.peekQueueSize('client')).toEqual(3);
137
-
138
- // @ts-ignore It has been assigned. Promise
139
- resolvePromise({ ttl: 0, data: { field: 'value' } });
140
- });
141
-
142
- it('should reject queue if fetching fails', (done) => {
143
- let rejectPromise: Function;
144
- const promise = new Promise((resolve, reject) => {
145
- rejectPromise = reject;
146
- });
147
-
148
- spyOn(cache, 'get').mockResolvedValue(null);
149
-
150
- const a = jest.fn().mockReturnValue(promise);
151
- const b = jest.fn();
152
- const c = jest.fn();
153
-
154
- expect(getOrUpdate('client', schema, a)).rejects.toEqual(undefined);
155
- expect(getOrUpdate('client', schema, b)).rejects.toEqual(undefined);
156
- expect(getOrUpdate('client', schema, c))
157
- .rejects.toEqual(undefined)
158
- .then(() => expect(queue.peekQueueSize('client')).toEqual(0))
159
- .then(done);
160
-
161
- expect(queue.peekQueueSize('client')).toEqual(3);
162
-
163
- // @ts-ignore It has been assigned. Promise
164
- rejectPromise();
165
- });
166
- });
@@ -1,66 +0,0 @@
1
- import { Runtype, Static } from 'runtypes';
2
- import queue from './queue';
3
- import cache from '../cache';
4
-
5
- export type DataFetcherWithCacheTTL<T extends Runtype> = Promise<{
6
- ttl: number;
7
- data: Static<T>;
8
- }>;
9
-
10
- const mergeCache = <T>(oldCache: T, newCache: T): T => {
11
- // Since we cannot know how to deal with duplicates when newCache is array
12
- // always return newCache
13
- if (!oldCache || Array.isArray(newCache)) {
14
- return newCache;
15
- }
16
-
17
- // TODO: Possible bug? :)
18
- if (!newCache) {
19
- return oldCache;
20
- }
21
-
22
- if (typeof oldCache === 'object' && typeof newCache === 'object') {
23
- return { ...oldCache, ...newCache };
24
- }
25
-
26
- // Cannot merge (eg type is string etc)
27
- return newCache;
28
- };
29
-
30
- export default function getOrUpdate<T extends Runtype>(
31
- key: string,
32
- schema: T,
33
- fetch: () => DataFetcherWithCacheTTL<T>,
34
- cacheQualifier?: (cacheData: Static<T>) => boolean
35
- ): Promise<Static<T>> {
36
- return new Promise((resolve, reject) => {
37
- queue.add(key, { resolve, reject });
38
- if (queue.peekQueueSize(key) > 1) {
39
- return;
40
- }
41
-
42
- cache.get(key, schema).then((cacheResponse) => {
43
- if (cacheResponse && (!cacheQualifier || cacheQualifier(cacheResponse))) {
44
- queue.getAll(key).forEach((promise) => {
45
- promise.resolve(cacheResponse);
46
- });
47
- return;
48
- }
49
- fetch()
50
- .then((res) => {
51
- const newCache = cacheResponse
52
- ? mergeCache(cacheResponse, res.data)
53
- : res.data;
54
- cache.set(key, newCache, res.ttl);
55
- queue.getAll(key).forEach((promise) => {
56
- promise.resolve(res.data);
57
- });
58
- })
59
- .catch(() => {
60
- queue.getAll(key).forEach((promise) => {
61
- promise.reject();
62
- });
63
- });
64
- });
65
- });
66
- }
@@ -1,9 +0,0 @@
1
- import log from './log';
2
-
3
- export const isRunningOnLocalhost = (): boolean => {
4
- if (globalThis.location.hostname === 'localhost') {
5
- log.error('@amedia/user cannot work on localhost.');
6
- return true;
7
- }
8
- return false;
9
- };
@@ -1,31 +0,0 @@
1
- import log from './log';
2
-
3
- export const reload = () => {
4
- if (typeof window === 'undefined') {
5
- log.error(
6
- 'location.reload used in a context without window. Be careful not to use paywall logic etc. in workers and other settings.'
7
- );
8
- return;
9
- }
10
- window.location.reload();
11
- };
12
-
13
- export const replace = (requestedUrl: string) => {
14
- if (typeof window === 'undefined') {
15
- log.error(
16
- 'location.replace used in a context without window. Be careful not to use paywall logic etc. in workers and other settings.'
17
- );
18
- return;
19
- }
20
- window.location.replace(requestedUrl);
21
- };
22
-
23
- export const navigateTo = (url: string) => {
24
- if (typeof window === 'undefined') {
25
- log.error(
26
- 'location.navigateTo used in a context without window. Be careful not to use interactive UX code in workers and other settings.'
27
- );
28
- return;
29
- }
30
- window.location.href = url;
31
- };