@amedia/user 0.13.39 → 0.13.40
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/dist/user.cjs +1 -1
- package/dist/user.cjs.map +3 -3
- package/dist/user.d.ts +5 -5
- package/dist/user.js +1 -1
- package/dist/user.js.map +3 -3
- package/package.json +5 -3
- package/src/actions/authentication.spec.ts +51 -0
- package/src/actions/authentication.ts +43 -0
- package/src/actions/authorization.spec.ts +369 -0
- package/src/actions/authorization.ts +117 -0
- package/src/actions/preferences.spec.ts +41 -0
- package/src/actions/preferences.ts +41 -0
- package/src/actions/storage.ts +22 -0
- package/src/actions/userData.spec.ts +133 -0
- package/src/actions/userData.ts +68 -0
- package/src/autologin/index.spec.ts +239 -0
- package/src/autologin/index.ts +92 -0
- package/src/autologin/thirdPartyCookie.spec.ts +95 -0
- package/src/autologin/thirdPartyCookie.ts +55 -0
- package/src/cache/engines/global.spec.ts +62 -0
- package/src/cache/engines/global.ts +49 -0
- package/src/cache/index.spec.ts +130 -0
- package/src/cache/index.ts +48 -0
- package/src/cache/types.ts +12 -0
- package/src/clients/europa.spec.ts +209 -0
- package/src/clients/europa.ts +183 -0
- package/src/clients/jupiter.spec.ts +179 -0
- package/src/clients/jupiter.ts +119 -0
- package/src/clients/mercury.spec.ts +59 -0
- package/src/clients/mercury.ts +48 -0
- package/src/clients/mercuryLog.spec.ts +20 -0
- package/src/clients/mercuryLog.ts +67 -0
- package/src/clients/nebula.spec.ts +70 -0
- package/src/clients/nebula.ts +83 -0
- package/src/clients/pluto.spec.ts +165 -0
- package/src/clients/pluto.ts +118 -0
- package/src/eventHandlers/activation.ts +36 -0
- package/src/eventHandlers/authentication.ts +34 -0
- package/src/eventHandlers/eventMap.ts +34 -0
- package/src/eventHandlers/state.spec.ts +48 -0
- package/src/eventHandlers/state.ts +23 -0
- package/src/eventHandlers/storage.spec.ts +114 -0
- package/src/eventHandlers/storage.ts +45 -0
- package/src/eventHandlers/userAttributes.spec.ts +93 -0
- package/src/eventHandlers/userAttributes.ts +31 -0
- package/src/exceptions/FetchTimeoutError.ts +8 -0
- package/src/exceptions/PaywallError.ts +16 -0
- package/src/index-authentcation.spec.ts +26 -0
- package/src/index-storage.spec.ts +144 -0
- package/src/index-subscription.spec.ts +213 -0
- package/src/index.ts +40 -0
- package/src/janitor/index.spec.ts +18 -0
- package/src/janitor/index.ts +59 -0
- package/src/janitor/jobs/accessCookieRefresher.spec.ts +213 -0
- package/src/janitor/jobs/accessCookieRefresher.ts +98 -0
- package/src/janitor/jobs/daxsubCookie.spec.ts +109 -0
- package/src/janitor/jobs/daxsubCookie.ts +38 -0
- package/src/janitor/jobs/removeUserStorage.spec.ts +34 -0
- package/src/janitor/jobs/removeUserStorage.ts +12 -0
- package/src/lib/PaywallUnlockRequest.spec.ts +363 -0
- package/src/lib/PaywallUnlockRequest.ts +143 -0
- package/src/lib/UserDataRequest.spec.ts +231 -0
- package/src/lib/UserDataRequest.ts +267 -0
- package/src/lib/cookie.ts +121 -0
- package/src/lib/rpc.ts +19 -0
- package/src/store/index.spec.ts +49 -0
- package/src/store/index.ts +64 -0
- package/src/types.ts +22 -0
- package/src/utils/customEventWrapper.ts +58 -0
- package/src/utils/debouncer.spec.ts +252 -0
- package/src/utils/debouncer.ts +123 -0
- package/src/utils/deepEquals.ts +42 -0
- package/src/utils/expectBootLogs.ts +9 -0
- package/src/utils/getGlobalThis.ts +17 -0
- package/src/utils/getOrUpdate.spec.ts +166 -0
- package/src/utils/getOrUpdate.ts +66 -0
- package/src/utils/localhostCheck.ts +10 -0
- package/src/utils/location.ts +31 -0
- package/src/utils/log.spec.ts +148 -0
- package/src/utils/log.ts +124 -0
- package/src/utils/loginState.ts +24 -0
- package/src/utils/networkError.ts +11 -0
- package/src/utils/queue.ts +32 -0
- package/src/utils/type.ts +19 -0
- package/src/utils/url.spec.ts +33 -0
- package/src/utils/url.ts +37 -0
|
@@ -0,0 +1,166 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import log from './log';
|
|
2
|
+
import getGlobalThis from './getGlobalThis';
|
|
3
|
+
|
|
4
|
+
export const isRunningOnLocalhost = (): boolean => {
|
|
5
|
+
if (getGlobalThis().location.hostname === 'localhost') {
|
|
6
|
+
log.error('@amedia/user cannot work on localhost.');
|
|
7
|
+
return true;
|
|
8
|
+
}
|
|
9
|
+
return false;
|
|
10
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import log, { Logger, setLogger } from './log';
|
|
2
|
+
|
|
3
|
+
describe('Log', () => {
|
|
4
|
+
let logger: Logger;
|
|
5
|
+
beforeEach(() => {
|
|
6
|
+
logger = {
|
|
7
|
+
debug: jest.fn(),
|
|
8
|
+
info: jest.fn(),
|
|
9
|
+
warn: jest.fn(),
|
|
10
|
+
error: jest.fn(),
|
|
11
|
+
};
|
|
12
|
+
setLogger(logger);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
function itShouldLogMessage(message: string, level: keyof Logger = 'error') {
|
|
16
|
+
it('should log message', () => {
|
|
17
|
+
expect(logger[level]).toHaveBeenCalledWith(message, expect.anything());
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function itShouldLogContext(context: Object, level: keyof Logger = 'error') {
|
|
22
|
+
it('should log context', () => {
|
|
23
|
+
expect(logger[level]).toHaveBeenCalledWith(expect.anything(), {
|
|
24
|
+
...context,
|
|
25
|
+
origin: '@amedia/user',
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function expectRewrittenError(message: string) {
|
|
31
|
+
const matcher = new RegExp(`Error: ${message}\n(^\\s+at .+$\\n){3,}`, 'm');
|
|
32
|
+
return {
|
|
33
|
+
message,
|
|
34
|
+
stack: expect.stringMatching(matcher),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
describe('with stringed message', () => {
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
log.error('Epic fail');
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
itShouldLogMessage('Epic fail');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe('with all error levels', () => {
|
|
47
|
+
beforeEach(() => {
|
|
48
|
+
log.debug('debug');
|
|
49
|
+
log.info('info');
|
|
50
|
+
log.warn('warn');
|
|
51
|
+
log.error('error');
|
|
52
|
+
});
|
|
53
|
+
itShouldLogMessage('debug', 'debug');
|
|
54
|
+
itShouldLogMessage('info', 'info');
|
|
55
|
+
itShouldLogMessage('warn', 'warn');
|
|
56
|
+
itShouldLogMessage('error', 'error');
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe('with stringed message and context', () => {
|
|
60
|
+
beforeEach(() => {
|
|
61
|
+
log.error('Epic fail', {
|
|
62
|
+
my: 'context',
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
itShouldLogMessage('Epic fail');
|
|
66
|
+
itShouldLogContext({
|
|
67
|
+
my: 'context',
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe('with stringed message and complex context', () => {
|
|
72
|
+
beforeEach(() => {
|
|
73
|
+
log.error('Epic fail', {
|
|
74
|
+
my: 'context',
|
|
75
|
+
more: {
|
|
76
|
+
nested: 'context',
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
itShouldLogMessage('Epic fail');
|
|
81
|
+
itShouldLogContext({
|
|
82
|
+
my: 'context',
|
|
83
|
+
more: {
|
|
84
|
+
nested: 'context',
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe('with Error as message', () => {
|
|
90
|
+
beforeEach(() => {
|
|
91
|
+
log.error(new Error('Epic fail'));
|
|
92
|
+
});
|
|
93
|
+
itShouldLogMessage('Epic fail');
|
|
94
|
+
itShouldLogContext({
|
|
95
|
+
error: expectRewrittenError('Epic fail'),
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
describe('with Error as message and context', () => {
|
|
100
|
+
beforeEach(() => {
|
|
101
|
+
log.error(new Error('Epic fail'), {
|
|
102
|
+
my: 'context',
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
itShouldLogMessage('Epic fail');
|
|
106
|
+
itShouldLogContext({
|
|
107
|
+
my: 'context',
|
|
108
|
+
error: expectRewrittenError('Epic fail'),
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
describe('with message as string and Errors in context', () => {
|
|
113
|
+
beforeEach(() => {
|
|
114
|
+
log.error('Epic fail', {
|
|
115
|
+
failError: new Error('Much fail'),
|
|
116
|
+
boomError: new Error('Very boom'),
|
|
117
|
+
my: 'context',
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
itShouldLogMessage('Epic fail');
|
|
121
|
+
itShouldLogContext({
|
|
122
|
+
my: 'context',
|
|
123
|
+
failError: expectRewrittenError('Much fail'),
|
|
124
|
+
boomError: expectRewrittenError('Very boom'),
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
describe('with Error directly as context', () => {
|
|
129
|
+
beforeEach(() => {
|
|
130
|
+
log.error('Epic fail', new Error('Downhill from here'));
|
|
131
|
+
});
|
|
132
|
+
itShouldLogMessage('Epic fail');
|
|
133
|
+
itShouldLogContext({
|
|
134
|
+
error: expectRewrittenError('Downhill from here'),
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
describe('with Error both at message and context', () => {
|
|
139
|
+
beforeEach(() => {
|
|
140
|
+
log.error(new Error('Epic fail'), new Error('Downhill from here'));
|
|
141
|
+
});
|
|
142
|
+
itShouldLogMessage('Epic fail');
|
|
143
|
+
itShouldLogContext({
|
|
144
|
+
error: expectRewrittenError('Epic fail'),
|
|
145
|
+
contextError: expectRewrittenError('Downhill from here'),
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
});
|
package/src/utils/log.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import mercury from '../clients/mercuryLog';
|
|
2
|
+
|
|
3
|
+
export type Logger = {
|
|
4
|
+
debug: (message: string | Error, context?: any) => void;
|
|
5
|
+
info: (message: string | Error, context?: any) => void;
|
|
6
|
+
warn: (message: string | Error, context?: any) => void;
|
|
7
|
+
error: (message: string | Error, context?: any) => void;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
let logger: Logger;
|
|
11
|
+
|
|
12
|
+
export const setLogger = (engine: Logger) => {
|
|
13
|
+
logger = engine;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const getLogger = () => logger || mercury;
|
|
17
|
+
|
|
18
|
+
const rewriteErrorObject = (
|
|
19
|
+
error: Error
|
|
20
|
+
): { [key: string]: unknown } & { message: string } => {
|
|
21
|
+
const rewrittenError: any = {
|
|
22
|
+
message: error.message,
|
|
23
|
+
};
|
|
24
|
+
Object.getOwnPropertyNames(error).forEach((key) => {
|
|
25
|
+
// @ts-ignore
|
|
26
|
+
rewrittenError[key] = error[key];
|
|
27
|
+
});
|
|
28
|
+
return rewrittenError;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const rewriteResponseObject = async (
|
|
32
|
+
response: Response
|
|
33
|
+
): Promise<
|
|
34
|
+
{ [key: string]: unknown } & {
|
|
35
|
+
url: string;
|
|
36
|
+
status: number;
|
|
37
|
+
statusText: string;
|
|
38
|
+
body: string;
|
|
39
|
+
}
|
|
40
|
+
> => {
|
|
41
|
+
const responseText = !response.bodyUsed
|
|
42
|
+
? await response.text()
|
|
43
|
+
: 'Response body not available for logging';
|
|
44
|
+
const rewrittenResponseObject: any = {
|
|
45
|
+
url: response.url,
|
|
46
|
+
status: response.status,
|
|
47
|
+
statusText: response.statusText,
|
|
48
|
+
body: responseText,
|
|
49
|
+
};
|
|
50
|
+
Object.getOwnPropertyNames(response).forEach((key) => {
|
|
51
|
+
// @ts-ignore
|
|
52
|
+
rewrittenResponseObject[key] = response[key];
|
|
53
|
+
});
|
|
54
|
+
return rewrittenResponseObject;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
function isError(param: any): param is Error {
|
|
58
|
+
return param && param instanceof Error;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isResponse(param: any): param is Response {
|
|
62
|
+
return param && param instanceof Response;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const processIncomingLogData = async (
|
|
66
|
+
message: string | Error,
|
|
67
|
+
context: any = {}
|
|
68
|
+
): Promise<{ message: string; context: any }> => {
|
|
69
|
+
let internalMessage = message;
|
|
70
|
+
let internalContext = context || {};
|
|
71
|
+
if (internalMessage instanceof Error) {
|
|
72
|
+
const rewrittenErrorObject = rewriteErrorObject(internalMessage);
|
|
73
|
+
internalMessage = rewrittenErrorObject.message;
|
|
74
|
+
internalContext = { ...internalContext, error: rewrittenErrorObject };
|
|
75
|
+
}
|
|
76
|
+
internalContext = { ...internalContext, origin: '@amedia/user' };
|
|
77
|
+
if (context instanceof Error) {
|
|
78
|
+
const parsedContextError = rewriteErrorObject(context);
|
|
79
|
+
internalContext = {
|
|
80
|
+
...internalContext,
|
|
81
|
+
...{
|
|
82
|
+
[Object.keys(internalContext).includes('error')
|
|
83
|
+
? 'contextError'
|
|
84
|
+
: 'error']: parsedContextError,
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
} else if (internalContext instanceof Response) {
|
|
88
|
+
const rewritten = await rewriteResponseObject(internalContext);
|
|
89
|
+
internalContext = { ...internalContext, response: rewritten };
|
|
90
|
+
} else {
|
|
91
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
92
|
+
for (const key of Object.keys(internalContext)) {
|
|
93
|
+
const currentInternalContext = internalContext[key];
|
|
94
|
+
if (isError(currentInternalContext)) {
|
|
95
|
+
internalContext[key] = rewriteErrorObject(currentInternalContext);
|
|
96
|
+
} else if (isResponse(currentInternalContext)) {
|
|
97
|
+
// eslint-disable-next-line no-await-in-loop
|
|
98
|
+
const rewritten = await rewriteResponseObject(currentInternalContext);
|
|
99
|
+
internalContext[key] = rewritten;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
message: internalMessage,
|
|
105
|
+
context: internalContext,
|
|
106
|
+
};
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const processAndLog = (
|
|
110
|
+
level: keyof Logger,
|
|
111
|
+
message: string | Error,
|
|
112
|
+
context?: any
|
|
113
|
+
) => {
|
|
114
|
+
processIncomingLogData(message, context).then(({ message: m, context: c }) =>
|
|
115
|
+
getLogger()[level](m, c)
|
|
116
|
+
);
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export default <Logger>{
|
|
120
|
+
debug: (message, context) => processAndLog('debug', message, context),
|
|
121
|
+
info: (message, context) => processAndLog('info', message, context),
|
|
122
|
+
warn: (message, context) => processAndLog('warn', message, context),
|
|
123
|
+
error: (message, context) => processAndLog('error', message, context),
|
|
124
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import store from '../store';
|
|
2
|
+
|
|
3
|
+
export const whenLoginStateResolved = (): Promise<boolean> =>
|
|
4
|
+
new Promise((resolve) => {
|
|
5
|
+
const currentLoggedInState = store.get('state')?.isLoggedIn;
|
|
6
|
+
if (currentLoggedInState === false || currentLoggedInState === true) {
|
|
7
|
+
resolve(currentLoggedInState);
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
store.on('state', ({ isLoggedIn }) => {
|
|
11
|
+
if (isLoggedIn === false || isLoggedIn === true) {
|
|
12
|
+
resolve(isLoggedIn);
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export const whenIsLoggedIn = (): Promise<void> =>
|
|
18
|
+
new Promise((resolve) =>
|
|
19
|
+
whenLoginStateResolved().then((isLoggedIn) => {
|
|
20
|
+
if (isLoggedIn) {
|
|
21
|
+
resolve();
|
|
22
|
+
}
|
|
23
|
+
})
|
|
24
|
+
);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const ABORTED_WORDS = [
|
|
2
|
+
'avbrutt',
|
|
3
|
+
'kansellert',
|
|
4
|
+
'cancelled',
|
|
5
|
+
'aborted',
|
|
6
|
+
'failed to fetch',
|
|
7
|
+
'abgebrochen',
|
|
8
|
+
'the operation was aborted.',
|
|
9
|
+
];
|
|
10
|
+
export const isAbortedNetworkError = (message: string) =>
|
|
11
|
+
ABORTED_WORDS.includes(message.toLowerCase().trim());
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const queue: {
|
|
2
|
+
[key: string]: {
|
|
3
|
+
resolve: (arg0?: any) => void;
|
|
4
|
+
reject: (reason?: any) => void;
|
|
5
|
+
}[];
|
|
6
|
+
} = {};
|
|
7
|
+
|
|
8
|
+
const add = (
|
|
9
|
+
key: string,
|
|
10
|
+
promiseCallbacks: {
|
|
11
|
+
resolve: (arg0?: any) => void;
|
|
12
|
+
reject: (reason?: any) => void;
|
|
13
|
+
}
|
|
14
|
+
): void => {
|
|
15
|
+
if (!queue[key]) {
|
|
16
|
+
queue[key] = [];
|
|
17
|
+
}
|
|
18
|
+
queue[key].push(promiseCallbacks);
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const getAll = (key: string) => {
|
|
22
|
+
const keyQueue = queue[key];
|
|
23
|
+
if (!keyQueue) {
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
delete queue[key];
|
|
27
|
+
return keyQueue;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const peekQueueSize = (key: string): number => queue[key]?.length || 0;
|
|
31
|
+
|
|
32
|
+
export default { add, getAll, peekQueueSize };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export const isFunction = (argument: unknown): argument is Function =>
|
|
2
|
+
!!argument && typeof argument === 'function';
|
|
3
|
+
|
|
4
|
+
export const isRecord = (
|
|
5
|
+
argument: unknown
|
|
6
|
+
): argument is Record<string, unknown> =>
|
|
7
|
+
!!argument && typeof argument === 'object';
|
|
8
|
+
|
|
9
|
+
export const isError = (argument: unknown): argument is Error =>
|
|
10
|
+
!!argument && argument instanceof Error;
|
|
11
|
+
|
|
12
|
+
export const isString = (argument: unknown): argument is string =>
|
|
13
|
+
!!argument && typeof argument === 'string';
|
|
14
|
+
|
|
15
|
+
export const isNumber = (argument: unknown): argument is number =>
|
|
16
|
+
!!argument && typeof argument === 'number';
|
|
17
|
+
|
|
18
|
+
export const isBoolean = (argument: unknown): argument is boolean =>
|
|
19
|
+
!!argument && typeof argument === 'boolean';
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getCurrentEnvironment,
|
|
3
|
+
getCurrentPublicationDomain,
|
|
4
|
+
setCurrentHostname,
|
|
5
|
+
} from './url';
|
|
6
|
+
|
|
7
|
+
describe('URL utils', () => {
|
|
8
|
+
it('should get proper publication domain', () => {
|
|
9
|
+
const domains = [
|
|
10
|
+
'www.telen.no.localhost.api.no',
|
|
11
|
+
'www.telen.no.snap5.api.no',
|
|
12
|
+
'www.telen.no',
|
|
13
|
+
];
|
|
14
|
+
expect.assertions(domains.length);
|
|
15
|
+
domains.forEach((domain) => {
|
|
16
|
+
setCurrentHostname(domain);
|
|
17
|
+
expect(getCurrentPublicationDomain()).toEqual('www.telen.no');
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('should get current environment', () => {
|
|
22
|
+
const domains = {
|
|
23
|
+
'www.telen.no.localhost.api.no': 'localhost',
|
|
24
|
+
'www.telen.no.snap5.api.no': 'snap5',
|
|
25
|
+
'www.telen.no': null,
|
|
26
|
+
};
|
|
27
|
+
expect.assertions(Object.keys(domains).length);
|
|
28
|
+
Object.entries(domains).forEach(([domain, expectedEnvironment]) => {
|
|
29
|
+
setCurrentHostname(domain);
|
|
30
|
+
expect(getCurrentEnvironment()).toEqual(expectedEnvironment);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
});
|