@servicetitan/log-service 40.2.2 → 40.4.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.
@@ -1,29 +0,0 @@
1
- import { useDependencies } from '@servicetitan/react-ioc';
2
- import { render } from '@testing-library/react';
3
- import { FC } from 'react';
4
- import { LOG_CONFIG_TOKEN, LogConfig } from '../log-config';
5
- import { LogConfigProvider } from '../log-config-provider';
6
-
7
- describe(`[log-service] ${LogConfigProvider.name}`, () => {
8
- const logConfig: LogConfig = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
9
- let providedLogConfig: LogConfig;
10
-
11
- const Wrapper: FC = () => {
12
- const [logConfig] = useDependencies(LOG_CONFIG_TOKEN);
13
- providedLogConfig = logConfig;
14
- return null;
15
- };
16
-
17
- const subject = () =>
18
- render(
19
- <LogConfigProvider value={logConfig}>
20
- <Wrapper />
21
- </LogConfigProvider>
22
- );
23
-
24
- test('provides LOG_CONFIG_TOKEN', () => {
25
- subject();
26
-
27
- expect(providedLogConfig).toBe(logConfig);
28
- });
29
- });
@@ -1,145 +0,0 @@
1
- import axios from 'axios';
2
- import { ConnectionService } from '../connection-service';
3
- import { Log, LogConfig, LogEntryType, LogInfo, LogWarning } from '../log';
4
- import { LogSender } from '../log-sender';
5
- import { lastId, LogStorage } from '../log-storage';
6
-
7
- jest.mock('axios', () => ({ post: jest.fn() }));
8
-
9
- class MockLog {
10
- constructor(private readonly logStorage: LogStorage) {}
11
-
12
- info(entry: LogInfo) {
13
- this.logStorage.store({
14
- type: LogEntryType.Info,
15
- ...entry,
16
- category: null,
17
- code: null,
18
- data: {},
19
- error: null,
20
- message: null,
21
- });
22
- }
23
-
24
- warning(_entry: LogWarning) {}
25
- }
26
-
27
- const SECOND = 1000;
28
- const MINUTE = 60 * SECOND;
29
-
30
- describe(`[log-service] ${LogSender.name}`, () => {
31
- const connectionService = new ConnectionService();
32
- const logConfig: LogConfig = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
33
- let logStorage: LogStorage;
34
- let log: Pick<Log, 'info' | 'warning'>;
35
-
36
- beforeAll(() => {
37
- process.env.NODE_ENV ??= 'test'; // workaround issue with Jest not setting NODE_ENV=test
38
- jest.spyOn(window, 'setInterval').mockImplementation(jest.fn());
39
- jest.spyOn(axios, 'post').mockImplementation(jest.fn());
40
- });
41
-
42
- beforeEach(() => {
43
- jest.clearAllMocks();
44
-
45
- logStorage = new LogStorage(logConfig);
46
- log = new MockLog(logStorage);
47
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
48
- const logSender = new LogSender(connectionService, logStorage, logConfig, log as Log);
49
- });
50
-
51
- afterEach(() => logStorage.deleteToId(lastId(logStorage.items)));
52
-
53
- const subject = async () => {
54
- getHandler().fn();
55
- await Promise.resolve(); // resolve pending promises
56
- };
57
-
58
- function getHandler() {
59
- const [fn, interval] = jest.mocked(window.setInterval).mock.calls[0];
60
- return { fn, interval };
61
- }
62
-
63
- function initLog(count: number) {
64
- Array.from({ length: count }).map((_, index) => log.info({ message: `Message ${index}` }));
65
- return logStorage.items;
66
- }
67
-
68
- test('schedules handler to run once per minute', async () => {
69
- await subject();
70
-
71
- expect(getHandler().interval).toBe(MINUTE);
72
- });
73
-
74
- describe('when there are items waiting to be sent', () => {
75
- beforeEach(() => initLog(3));
76
-
77
- test('handler posts then purges log', async () => {
78
- const { items } = logStorage;
79
-
80
- await subject();
81
-
82
- expect(axios.post).toHaveBeenCalledWith(logConfig.endpoint, items);
83
- expect(logStorage.items).toEqual([]);
84
- });
85
-
86
- describe('when post fails', () => {
87
- beforeEach(() => jest.mocked(axios.post).mockRejectedValue(new Error('Oops!')));
88
-
89
- test('reschedules handler to run in exponentially increasing intervals until it succeeds', async () => {
90
- for (let n = 0; n <= 10; n++) {
91
- // eslint-disable-next-line no-await-in-loop
92
- await subject();
93
- }
94
-
95
- for (let n = 0; n < 10; n++) {
96
- expect(window.setInterval).toHaveBeenCalledWith(
97
- expect.any(Function),
98
- 2 ** n * SECOND
99
- );
100
- }
101
-
102
- jest.mocked(axios.post).mockReset();
103
- await subject();
104
-
105
- expect(logStorage.items).toEqual([]);
106
- expect(window.setInterval).toHaveBeenCalledWith(expect.any(Function), MINUTE);
107
- });
108
- });
109
-
110
- describe('when handler runs while posting', () => {
111
- beforeEach(() =>
112
- jest.spyOn(axios, 'post').mockImplementation(() => {
113
- getHandler().fn();
114
- return Promise.resolve({});
115
- })
116
- );
117
-
118
- test('skips redundant post', async () => {
119
- await subject();
120
-
121
- expect(axios.post).toHaveBeenCalledTimes(1);
122
- });
123
- });
124
-
125
- describe('when offline', () => {
126
- beforeEach(() => connectionService.setOnline(false));
127
- afterEach(() => connectionService.setOnline(true));
128
-
129
- test('does not post', async () => {
130
- await subject();
131
-
132
- expect(axios.post).not.toHaveBeenCalled();
133
- });
134
- });
135
- });
136
-
137
- test('automatically posts when log >= 128 items', async () => {
138
- await subject();
139
- expect(axios.post).not.toHaveBeenCalled();
140
-
141
- const items = initLog(128);
142
-
143
- expect(axios.post).toHaveBeenCalledWith(logConfig.endpoint, items);
144
- });
145
- });
@@ -1,76 +0,0 @@
1
- import {
2
- Provider,
3
- ProviderProps,
4
- useDependencies,
5
- useOptionalDependencies,
6
- } from '@servicetitan/react-ioc';
7
- import { render } from '@testing-library/react';
8
- import { FC } from 'react';
9
- import { LOG_CONFIG_TOKEN, LOG_PARENT_TOKEN, Log, LogConfig } from '../log';
10
- import { defaultLogConfig } from '../log-config';
11
- import { LogService, LogServiceProps } from '../log-service';
12
- import { LogStorage } from '../log-storage';
13
-
14
- describe(`[log-service] ${LogService.name}`, () => {
15
- let props: LogServiceProps;
16
- let providedLog: Log;
17
- let providedLogConfig: LogConfig;
18
- let providedParent: Log | undefined;
19
- let singletons: ProviderProps['singletons'];
20
-
21
- const Component: FC = () => {
22
- [providedLog, providedLogConfig] = useDependencies(Log, LOG_CONFIG_TOKEN);
23
- [providedParent] = useOptionalDependencies(LOG_PARENT_TOKEN);
24
- return null;
25
- };
26
-
27
- const subject = () => {
28
- return render(
29
- <Provider singletons={singletons}>
30
- <LogService {...props}>
31
- <Component />
32
- </LogService>
33
- </Provider>
34
- );
35
- };
36
-
37
- test('provides Log instance', () => {
38
- subject();
39
-
40
- expect(providedLog).toBeInstanceOf(Log);
41
- });
42
-
43
- test('defaults to endpoint "/Log/Send" and storageKey "LogStorage"', () => {
44
- subject();
45
-
46
- expect(providedLogConfig).toEqual({ endpoint: '/Log/Send', storageKey: 'LogStorage' });
47
- });
48
-
49
- describe.each(['endpoint', 'storageKey'] as (keyof LogConfig)[])(
50
- 'when "%s" is specified',
51
- prop => {
52
- beforeEach(() => (props = { [prop]: 'Foo' }));
53
-
54
- test(`uses the specified ${prop}`, () => {
55
- subject();
56
-
57
- expect(providedLogConfig[prop]).toEqual(props[prop]);
58
- });
59
- }
60
- );
61
-
62
- describe('with a parent log', () => {
63
- const parent: Log = new Log(new LogStorage(defaultLogConfig));
64
-
65
- beforeEach(() => {
66
- singletons = [{ provide: Log, useValue: parent }];
67
- props = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
68
- });
69
-
70
- test('provides parent Log', () => {
71
- subject();
72
-
73
- expect(providedParent).toBe(parent);
74
- });
75
- });
76
- });
@@ -1,194 +0,0 @@
1
- import { EntryComplete, LogEntryType } from '../log';
2
- import { LogConfig } from '../log-config';
3
- import { lastId, LogStorage } from '../log-storage';
4
- import { MockBroadcastChannel } from './__mocks__';
5
-
6
- describe(`${LogStorage.name}`, () => {
7
- const LOCAL_STORAGE_VERSION = '1';
8
- const logConfig: LogConfig = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
9
- let logStorage: LogStorage;
10
-
11
- beforeAll(() => {
12
- jest.spyOn(globalThis, 'BroadcastChannel').mockImplementation(
13
- (name: string) => new MockBroadcastChannel(name)
14
- );
15
- });
16
-
17
- beforeEach(() => window.localStorage.clear());
18
- afterEach(() => logStorage.dispose());
19
-
20
- const subject = (entryOrEntries: EntryComplete | EntryComplete[] = []) => {
21
- logStorage = new LogStorage(logConfig);
22
- [entryOrEntries].flat().forEach(entry => logStorage.store(entry));
23
- return logStorage;
24
- };
25
-
26
- function itLoadsNoItems() {
27
- test('loads no items', () => {
28
- expect(subject().items).toEqual([]);
29
- });
30
- }
31
-
32
- itLoadsNoItems();
33
-
34
- describe('with previously saved items', () => {
35
- const entries = createEntries(3);
36
-
37
- beforeEach(() => {
38
- const logStorage = new LogStorage(logConfig);
39
- entries.map(entry => logStorage.store(entry));
40
- logStorage.dispose();
41
- });
42
-
43
- function itLoadsSavedItems() {
44
- test('loads saved items', () => {
45
- expect(subject().items).toEqual(buildItems(entries).map(expect.objectContaining));
46
- });
47
- }
48
-
49
- itLoadsSavedItems();
50
-
51
- describe('when saved data has incompatible version', () => {
52
- const storageVersionKey = `${logConfig.storageKey}Version`;
53
-
54
- beforeEach(() => window.localStorage.setItem(storageVersionKey, '-1'));
55
-
56
- itLoadsNoItems();
57
-
58
- test('updates version', () => {
59
- subject();
60
-
61
- expect(localStorage.getItem(storageVersionKey)).toBe(LOCAL_STORAGE_VERSION);
62
- });
63
- });
64
-
65
- describe('when saved data is not valid', () => {
66
- beforeEach(() => {
67
- window.localStorage.setItem(logConfig.storageKey, '}{');
68
- });
69
-
70
- itLoadsNoItems();
71
- });
72
-
73
- describe('when saved data contains old "error" field', () => {
74
- beforeEach(() => {
75
- const itemsWithErrorField = (
76
- JSON.parse(localStorage.getItem(logConfig.storageKey)!) as LogStorage['items']
77
- ).map(({ exception, ...rest }) => ({ ...rest, error: exception }));
78
- localStorage.setItem(logConfig.storageKey, JSON.stringify(itemsWithErrorField));
79
- });
80
-
81
- itLoadsSavedItems();
82
- });
83
-
84
- describe('when multiple instances are running simultaneously', () => {
85
- let otherLogStorage: LogStorage;
86
-
87
- beforeEach(() => (otherLogStorage = new LogStorage(logConfig)));
88
- afterEach(() => otherLogStorage.dispose());
89
-
90
- test('deleteToId removes items from both instances', () => {
91
- const logStorage = subject();
92
-
93
- expect(logStorage.items.length).toEqual(entries.length);
94
- expect(otherLogStorage.items.length).toEqual(entries.length);
95
-
96
- logStorage.deleteToId(lastId(logStorage.items));
97
-
98
- expect(logStorage.items).toEqual([]);
99
- expect(otherLogStorage.items).toEqual([]);
100
- });
101
-
102
- test('deleteToId does not remove private items', () => {
103
- const logStorage = subject();
104
-
105
- const entry = createEntry({ message: 'foo' });
106
- otherLogStorage.store(entry);
107
-
108
- logStorage.deleteToId(lastId(logStorage.items));
109
-
110
- expect(logStorage.items).toEqual([]);
111
- expect(otherLogStorage.items).toEqual(
112
- buildItems([entry]).map(expect.objectContaining)
113
- );
114
- });
115
- });
116
- });
117
-
118
- test('stores items with unique ids', () => {
119
- const entries = createEntries(3);
120
-
121
- const logStorage = subject(entries);
122
-
123
- expect(logStorage.items).toEqual(buildItems(entries).map(expect.objectContaining));
124
- expect(new Set(logStorage.items.map(({ id }) => id)).size).toBe(entries.length);
125
- });
126
-
127
- test('limits storage to 1000 items', () => {
128
- const logStorage = subject(createEntries(1001));
129
-
130
- expect(logStorage.items).toHaveLength(1000);
131
- });
132
-
133
- test('stringifies entry data', () => {
134
- const entry = createEntry({ message: 'foo', data: { foo: 'bar' } });
135
-
136
- const { data } = subject(entry).items[0];
137
-
138
- expect(data).toBe(JSON.stringify(entry.data));
139
- });
140
-
141
- test('converts entry error to exception', () => {
142
- const error = new Error('Oops!');
143
-
144
- const { exception } = subject(createEntry({ error })).items[0];
145
-
146
- expect(exception).toEqual(JSON.stringify({ message: error.message, stack: error.stack }));
147
- });
148
-
149
- test('deleteToId removes entries with same or lower id', () => {
150
- const entries = createEntries(10);
151
- const logStorage = subject(entries);
152
-
153
- const index = 2;
154
- const { id } = logStorage.items[index];
155
- logStorage.deleteToId(id);
156
-
157
- expect(logStorage.items.length).toBe(entries.length - index - 1);
158
- expect(logStorage.items.every(entry => entry.id > id)).toBe(true);
159
- });
160
-
161
- test('loadBatch returns first N items', () => {
162
- const entries = createEntries(10);
163
- const logStorage = subject(entries);
164
-
165
- const count = 5;
166
- const batch = logStorage.loadBatch(count);
167
-
168
- expect(batch).toEqual(buildItems(entries.slice(0, count)).map(expect.objectContaining));
169
- });
170
- });
171
-
172
- function buildItems(entries: EntryComplete[]) {
173
- return entries.map(({ data, error, ...rest }) => ({
174
- ...rest,
175
- data: JSON.stringify(data),
176
- exception: JSON.stringify(error && { message: error.message, stack: error.stack }),
177
- }));
178
- }
179
-
180
- function createEntries(length: number) {
181
- return Array.from({ length }).map((_, index) => createEntry({ message: `Entry ${index}` }));
182
- }
183
-
184
- function createEntry(entry: Partial<EntryComplete>): EntryComplete {
185
- return {
186
- type: LogEntryType.Info,
187
- message: null,
188
- code: null,
189
- category: null,
190
- error: null,
191
- data: {},
192
- ...entry,
193
- };
194
- }
@@ -1,250 +0,0 @@
1
- import { Log, LogConfig, LogEntry, LogEntryType, LogError } from '../log';
2
- import { defaultLogConfig } from '../log-config';
3
- import { LogStorage } from '../log-storage';
4
- import { serializeWithMetadata } from '../serialize-with-metadata';
5
-
6
- const SECOND = 1000;
7
- const THROTTLE_INTERVAL = 30 * SECOND;
8
-
9
- describe(`[log-service] ${Log.name}`, () => {
10
- const logConfig: LogConfig = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
11
- const entry: LogEntry = { category: 'category', code: 'code', message: 'foo' };
12
- let parentLog: Log;
13
-
14
- beforeAll(() => jest.useFakeTimers());
15
-
16
- beforeEach(() => {
17
- jest.clearAllTimers();
18
- jest.spyOn(console, 'error').mockImplementation(jest.fn());
19
- window.localStorage.clear();
20
- });
21
-
22
- const subject = () => {
23
- const logStorage = new LogStorage(logConfig);
24
- const log = new Log(logStorage, parentLog);
25
- jest.spyOn(logStorage, 'store');
26
- return { log, logStorage };
27
- };
28
-
29
- test('logs info', () => {
30
- const { log, logStorage } = subject();
31
-
32
- log.info(entry);
33
-
34
- expect(logStorage.store).toHaveBeenCalledWith(
35
- expect.objectContaining({ ...entry, type: LogEntryType.Info })
36
- );
37
- });
38
-
39
- test('logs warnings', () => {
40
- const { log, logStorage } = subject();
41
-
42
- log.warning(entry);
43
-
44
- expect(logStorage.store).toHaveBeenCalledWith(
45
- expect.objectContaining({ ...entry, type: LogEntryType.Warning })
46
- );
47
- });
48
-
49
- describe('error', () => {
50
- const { log, logStorage } = subject();
51
- let error: Error | string;
52
- let errorEntry: LogError;
53
- let errorOptions: Parameters<typeof log.error>[1];
54
-
55
- beforeEach(() => {
56
- jest.clearAllMocks();
57
- errorOptions = undefined;
58
- });
59
-
60
- const errorSubject = () => {
61
- errorEntry = { ...entry, error, message: undefined };
62
- log.error(errorEntry, errorOptions);
63
- jest.runOnlyPendingTimers();
64
- };
65
-
66
- function itLogsError() {
67
- const expectMessage = () =>
68
- expect.stringContaining((errorEntry.error as Error)?.message ?? errorEntry.error);
69
-
70
- test('stores the error', () => {
71
- errorSubject();
72
-
73
- expect(logStorage.store).toHaveBeenCalledWith(
74
- expect.objectContaining({
75
- ...errorEntry,
76
- type: LogEntryType.Error,
77
- error: expect.objectContaining({ message: expectMessage() }),
78
- message: expectMessage(),
79
- })
80
- );
81
- });
82
-
83
- test('writes the error to the console', () => {
84
- errorSubject();
85
-
86
- // eslint-disable-next-line no-console
87
- expect(console.error).toHaveBeenCalledWith(
88
- '@log-service/error',
89
- errorEntry,
90
- expect.objectContaining({ message: expectMessage() })
91
- );
92
- });
93
- }
94
-
95
- describe('with an error object', () => {
96
- beforeEach(() => (error = new Error('Oops!')));
97
-
98
- itLogsError();
99
- });
100
-
101
- describe('with an error string', () => {
102
- beforeEach(() => (error = 'Oops!'));
103
-
104
- itLogsError();
105
- });
106
-
107
- describe('with { skipConsole: true }', () => {
108
- beforeEach(() => {
109
- error = new Error('Oops!');
110
- errorOptions = { skipConsole: true };
111
- });
112
- test('does not write error to console', () => {
113
- errorSubject();
114
- // eslint-disable-next-line no-console
115
- expect(console.error).not.toHaveBeenCalled();
116
- });
117
- });
118
- });
119
-
120
- test(`skips redundant error logged within ${THROTTLE_INTERVAL / SECOND}s`, () => {
121
- const errorEntry = { ...entry, error: new Error('Oops!') };
122
- const { log, logStorage } = subject();
123
-
124
- Array.from({ length: 5 }).forEach(() => log.error(errorEntry));
125
- jest.advanceTimersByTime(THROTTLE_INTERVAL);
126
-
127
- expect(logStorage.store).toHaveBeenCalledTimes(1);
128
- });
129
-
130
- test(`keeps redundant error logged after ${THROTTLE_INTERVAL / SECOND}s`, () => {
131
- const errorEntry = { ...entry, error: new Error('Oops!') };
132
- const { log, logStorage } = subject();
133
-
134
- Array.from({ length: 5 }).forEach(() => log.error(errorEntry));
135
- jest.advanceTimersByTime(THROTTLE_INTERVAL);
136
- Array.from({ length: 5 }).forEach(() => log.error(errorEntry));
137
- jest.runOnlyPendingTimers();
138
-
139
- expect(logStorage.store).toHaveBeenCalledTimes(2);
140
- });
141
-
142
- test('serializes non-standard errors', () => {
143
- const errorEntry = { ...entry, error: { foo: 'bar' } };
144
- const { log, logStorage } = subject();
145
-
146
- log.error(errorEntry);
147
- jest.runOnlyPendingTimers();
148
-
149
- expect(logStorage.store).toHaveBeenCalledWith(
150
- expect.objectContaining({
151
- message: errorEntry.message,
152
- error: expect.objectContaining({
153
- message: serializeWithMetadata(errorEntry.error),
154
- }),
155
- })
156
- );
157
- });
158
-
159
- test('extends log data', () => {
160
- const data = { foo: 'bar' };
161
- const { log, logStorage } = subject();
162
-
163
- log.info({ ...entry, data });
164
-
165
- expect(logStorage.store).toHaveBeenCalledWith(
166
- expect.objectContaining({
167
- data: {
168
- ...data,
169
- CreatedOn: new Date(),
170
- Online: window.navigator.onLine,
171
- Url: window.location.toString(),
172
- UserAgent: window.navigator.userAgent,
173
- Source: 'Frontend',
174
- Plugins: '',
175
- TzOffset: expect.any(Number),
176
- IsDst: expect.any(Boolean),
177
- IsDstSubject: expect.any(Boolean),
178
- },
179
- })
180
- );
181
- });
182
-
183
- describe('when browser has plugins', () => {
184
- const plugins: Partial<(typeof window.navigator.plugins)[0]>[] = [
185
- { name: 'foo', filename: 'filename', description: 'description' },
186
- { name: 'bar', filename: 'filename', description: 'description' },
187
- ];
188
-
189
- beforeEach(() => {
190
- Object.defineProperty(window.navigator, 'plugins', { value: plugins, writable: true });
191
- });
192
-
193
- test('adds plugins to log data', () => {
194
- const { log, logStorage } = subject();
195
-
196
- log.info(entry);
197
-
198
- expect(logStorage.store).toHaveBeenCalledWith(
199
- expect.objectContaining({
200
- data: expect.objectContaining({
201
- Plugins: plugins.map(p => [p.name, p.filename, p.description]).join('/'),
202
- }),
203
- })
204
- );
205
- });
206
-
207
- describe('when error occurs reading plugins', () => {
208
- beforeEach(() => Object.assign(window.navigator, { plugins: [undefined] }));
209
-
210
- test('reports "unknown"', () => {
211
- const { log, logStorage } = subject();
212
-
213
- log.info(entry);
214
-
215
- expect(logStorage.store).toHaveBeenCalledWith(
216
- expect.objectContaining({
217
- data: expect.objectContaining({ Plugins: 'unknown' }),
218
- })
219
- );
220
- });
221
- });
222
- });
223
-
224
- describe('when log has parent', () => {
225
- beforeEach(() => (parentLog = new Log(new LogStorage(defaultLogConfig))));
226
-
227
- test.each(['info', 'warning', 'error'] as (keyof Log)[])(
228
- 'forwards %s to parent log',
229
- method => {
230
- jest.spyOn(parentLog, method);
231
-
232
- const logEntry = { ...entry, error: new Error('Oops!') };
233
- subject().log[method](logEntry);
234
-
235
- expect(parentLog[method]).toHaveBeenCalledWith(logEntry);
236
- }
237
- );
238
-
239
- describe.each(['endpoint', 'storageKey'] as (keyof LogConfig)[])(
240
- 'when log uses default %s',
241
- key => {
242
- beforeEach(() => (logConfig[key] = defaultLogConfig[key]));
243
-
244
- test('throws error', () => {
245
- expect(() => subject()).toThrow(/cannot use default configuration/);
246
- });
247
- }
248
- );
249
- });
250
- });