aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src
diff options
context:
space:
mode:
authorLibravatar Kristóf Marussy <kristof@marussy.com>2021-12-31 01:52:28 +0100
committerLibravatar Kristóf Marussy <kristof@marussy.com>2021-12-31 01:56:30 +0100
commit7108c642f4ff6dc5f0c4d30b8a8960064ff8e90f (patch)
treef8c0450a6e1b62f7e7f8470efd375b3659b91b2b /packages/main/src
parentrefactor: Install devtools extensions earlier (diff)
downloadsophie-7108c642f4ff6dc5f0c4d30b8a8960064ff8e90f.tar.gz
sophie-7108c642f4ff6dc5f0c4d30b8a8960064ff8e90f.tar.zst
sophie-7108c642f4ff6dc5f0c4d30b8a8960064ff8e90f.zip
test: Add tests for main package
- Changed jest to run from the root package and reference the packages as projects. This required moving the base jest config file away from the project root. - Module isolation seems to prevent ts-jest from loading the shared package, so we disabled it for now. - To better facilitate mocking, services should be split into interfaces and implementation - Had to downgrade to chald 4.1.2 as per https://github.com/chalk/chalk/releases/tag/v5.0.0 at least until https://github.com/microsoft/TypeScript/issues/46452 is resolved.
Diffstat (limited to 'packages/main/src')
-rw-r--r--packages/main/src/compositionRoot.ts4
-rw-r--r--packages/main/src/controllers/__tests__/config.spec.ts184
-rw-r--r--packages/main/src/controllers/__tests__/nativeTheme.spec.ts71
-rw-r--r--packages/main/src/controllers/config.ts16
-rw-r--r--packages/main/src/services/ConfigPersistenceService.ts106
-rw-r--r--packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts128
-rw-r--r--packages/main/src/utils/index.ts2
-rw-r--r--packages/main/src/utils/logging.ts16
8 files changed, 411 insertions, 116 deletions
diff --git a/packages/main/src/compositionRoot.ts b/packages/main/src/compositionRoot.ts
index eb6f50f..d420bd6 100644
--- a/packages/main/src/compositionRoot.ts
+++ b/packages/main/src/compositionRoot.ts
@@ -22,12 +22,12 @@ import { app } from 'electron';
22 22
23import { initConfig } from './controllers/config'; 23import { initConfig } from './controllers/config';
24import { initNativeTheme } from './controllers/nativeTheme'; 24import { initNativeTheme } from './controllers/nativeTheme';
25import { ConfigPersistenceService } from './services/ConfigPersistenceService'; 25import { ConfigPersistenceServiceImpl } from './services/impl/ConfigPersistenceServiceImpl';
26import { MainStore } from './stores/MainStore'; 26import { MainStore } from './stores/MainStore';
27import { Disposer } from './utils'; 27import { Disposer } from './utils';
28 28
29export async function init(store: MainStore): Promise<Disposer> { 29export async function init(store: MainStore): Promise<Disposer> {
30 const configPersistenceService = new ConfigPersistenceService(app.getPath('userData')); 30 const configPersistenceService = new ConfigPersistenceServiceImpl(app.getPath('userData'));
31 const disposeConfigController = await initConfig(store.config, configPersistenceService); 31 const disposeConfigController = await initConfig(store.config, configPersistenceService);
32 const disposeNativeThemeController = initNativeTheme(store); 32 const disposeNativeThemeController = initNativeTheme(store);
33 33
diff --git a/packages/main/src/controllers/__tests__/config.spec.ts b/packages/main/src/controllers/__tests__/config.spec.ts
new file mode 100644
index 0000000..9471ca9
--- /dev/null
+++ b/packages/main/src/controllers/__tests__/config.spec.ts
@@ -0,0 +1,184 @@
1/*
2 * Copyright (C) 2021-2022 Kristóf Marussy <kristof@marussy.com>
3 *
4 * This file is part of Sophie.
5 *
6 * Sophie is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as
8 * published by the Free Software Foundation, version 3.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: AGPL-3.0-only
19 */
20
21import { jest } from '@jest/globals';
22import { mocked } from 'jest-mock';
23import ms from 'ms';
24
25import { initConfig } from '../config';
26import type { ConfigPersistenceService } from '../../services/ConfigPersistenceService';
27import { Config, config as configModel } from '../../stores/Config';
28import { Disposer, silenceLogger } from '../../utils';
29
30let config: Config;
31let persistenceService: ConfigPersistenceService = {
32 readConfig: jest.fn(),
33 writeConfig: jest.fn(),
34 watchConfig: jest.fn(),
35};
36let lessThanThrottleMs = ms('0.1s');
37let throttleMs = ms('1s');
38
39beforeAll(() => {
40 jest.useFakeTimers();
41 silenceLogger();
42});
43
44beforeEach(() => {
45 config = configModel.create();
46});
47
48describe('when initializing', () => {
49 describe('when there is no config file', () => {
50 beforeEach(() => {
51 mocked(persistenceService.readConfig).mockResolvedValueOnce({
52 found: false,
53 });
54 });
55
56 it('should create a new config file', async () => {
57 await initConfig(config, persistenceService);
58 expect(persistenceService.writeConfig).toBeCalledTimes(1);
59 });
60
61 it('should bail if there is an an error creating the config file', async () => {
62 mocked(persistenceService.writeConfig).mockRejectedValue(new Error('boo'));
63 await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error);
64 });
65 });
66
67 describe('when there is a valid config file', () => {
68 beforeEach(() => {
69 mocked(persistenceService.readConfig).mockResolvedValueOnce({
70 found: true,
71 data: {
72 themeSource: 'dark',
73 },
74 });
75 });
76
77 it('should read the existing config file is there is one', async () => {
78 await initConfig(config, persistenceService);
79 expect(persistenceService.writeConfig).not.toBeCalled();
80 expect(config.themeSource).toBe('dark');
81 });
82
83 it('should bail if it cannot set up a watcher', async () => {
84 mocked(persistenceService.watchConfig).mockImplementationOnce(() => {
85 throw new Error('boo');
86 });
87 await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error);
88 });
89 });
90
91 it('should not apply an invalid config file', async () => {
92 mocked(persistenceService.readConfig).mockResolvedValueOnce({
93 found: true,
94 data: {
95 themeSource: -1,
96 },
97 });
98 await initConfig(config, persistenceService);
99 expect(config.themeSource).not.toBe(-1);
100 });
101
102 it('should bail if it cannot determine whether there is a config file', async () => {
103 mocked(persistenceService.readConfig).mockRejectedValue(new Error('boo'));
104 await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error);
105 });
106});
107
108describe('when it has loaded the config', () => {
109 let sutDisposer: Disposer;
110 let watcherDisposer: Disposer = jest.fn();
111 let configChangedCallback: () => Promise<void>;
112
113 beforeEach(async () => {
114 mocked(persistenceService.readConfig).mockResolvedValueOnce({
115 found: true,
116 data: {},
117 });
118 mocked(persistenceService.watchConfig).mockReturnValueOnce(watcherDisposer);
119 sutDisposer = await initConfig(config, persistenceService, throttleMs);
120 configChangedCallback = mocked(persistenceService.watchConfig).mock.calls[0][0];
121 jest.resetAllMocks();
122 });
123
124 it('should throttle saving changes to the config file', () => {
125 mocked(persistenceService.writeConfig).mockResolvedValue(undefined);
126 config.setThemeSource('dark');
127 jest.advanceTimersByTime(lessThanThrottleMs);
128 config.setThemeSource('light');
129 jest.advanceTimersByTime(throttleMs);
130 expect(persistenceService.writeConfig).toBeCalledTimes(1);
131 });
132
133 it('should handle config writing errors gracefully', () => {
134 mocked(persistenceService.writeConfig).mockRejectedValue(new Error('boo'));
135 config.setThemeSource('dark');
136 jest.advanceTimersByTime(throttleMs);
137 expect(persistenceService.writeConfig).toBeCalledTimes(1);
138 });
139
140 it('should read the config file when it has changed', async () => {
141 mocked(persistenceService.readConfig).mockResolvedValueOnce({
142 found: true,
143 data: {
144 themeSource: 'dark',
145 },
146 });
147 await configChangedCallback();
148 // Do not write back the changes we have just read.
149 expect(persistenceService.writeConfig).not.toBeCalled();
150 expect(config.themeSource).toBe('dark');
151 });
152
153 it('should not apply an invalid config file when it has changed', async () => {
154 mocked(persistenceService.readConfig).mockResolvedValueOnce({
155 found: true,
156 data: {
157 themeSource: -1,
158 },
159 });
160 await configChangedCallback();
161 expect(config.themeSource).not.toBe(-1);
162 });
163
164 it('should handle config writing errors gracefully', async () => {
165 mocked(persistenceService.readConfig).mockRejectedValue(new Error('boo'));
166 await configChangedCallback();
167 });
168
169 describe('when it was disposed', () => {
170 beforeEach(() => {
171 sutDisposer();
172 });
173
174 it('should dispose the watcher', () => {
175 expect(watcherDisposer).toBeCalled();
176 });
177
178 it('should not listen to store changes any more', () => {
179 config.setThemeSource('dark');
180 jest.advanceTimersByTime(2 * throttleMs);
181 expect(persistenceService.writeConfig).not.toBeCalled();
182 });
183 });
184});
diff --git a/packages/main/src/controllers/__tests__/nativeTheme.spec.ts b/packages/main/src/controllers/__tests__/nativeTheme.spec.ts
new file mode 100644
index 0000000..cfb557c
--- /dev/null
+++ b/packages/main/src/controllers/__tests__/nativeTheme.spec.ts
@@ -0,0 +1,71 @@
1/*
2 * Copyright (C) 2021-2022 Kristóf Marussy <kristof@marussy.com>
3 *
4 * This file is part of Sophie.
5 *
6 * Sophie is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as
8 * published by the Free Software Foundation, version 3.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: AGPL-3.0-only
19 */
20
21import { jest } from '@jest/globals';
22import { mocked } from 'jest-mock';
23
24import { createMainStore, MainStore } from '../../stores/MainStore';
25import { Disposer } from '../../utils';
26
27let shouldUseDarkColors = false;
28
29jest.unstable_mockModule('electron', () => ({
30 nativeTheme: {
31 themeSource: 'system',
32 get shouldUseDarkColors() {
33 return shouldUseDarkColors;
34 },
35 on: jest.fn(),
36 off: jest.fn(),
37 },
38}));
39
40const { nativeTheme } = await import('electron');
41const { initNativeTheme } = await import('../nativeTheme');
42
43let store: MainStore;
44let disposeSut: Disposer;
45
46beforeEach(() => {
47 store = createMainStore();
48 disposeSut = initNativeTheme(store);
49});
50
51it('should register a nativeTheme updated listener', () => {
52 expect(nativeTheme.on).toBeCalledWith('updated', expect.anything());
53});
54
55it('should synchronize themeSource changes to the nativeTheme', () => {
56 store.config.setThemeSource('dark');
57 expect(nativeTheme.themeSource).toBe('dark');
58});
59
60it('should synchronize shouldUseDarkColors changes to the store', () => {
61 const listener = mocked(nativeTheme.on).mock.calls.find(([event]) => event === 'updated')![1];
62 shouldUseDarkColors = true;
63 listener();
64 expect(store.shared.shouldUseDarkColors).toBe(true);
65});
66
67it('should remove the listener on dispose', () => {
68 const listener = mocked(nativeTheme.on).mock.calls.find(([event]) => event === 'updated')![1];
69 disposeSut();
70 expect(nativeTheme.off).toBeCalledWith('updated', listener);
71});
diff --git a/packages/main/src/controllers/config.ts b/packages/main/src/controllers/config.ts
index 600a142..d3559c8 100644
--- a/packages/main/src/controllers/config.ts
+++ b/packages/main/src/controllers/config.ts
@@ -60,12 +60,8 @@ export async function initConfig(
60 60
61 if (!await readConfig()) { 61 if (!await readConfig()) {
62 log.info('Config file was not found'); 62 log.info('Config file was not found');
63 try { 63 await writeConfig();
64 await writeConfig(); 64 log.info('Created config file');
65 log.info('Created config file');
66 } catch (err) {
67 log.error('Failed to initialize config', err);
68 }
69 } 65 }
70 66
71 const disposeOnSnapshot = onSnapshot(config, debounce((snapshot) => { 67 const disposeOnSnapshot = onSnapshot(config, debounce((snapshot) => {
@@ -73,12 +69,16 @@ export async function initConfig(
73 if (lastSnapshotOnDisk !== snapshot) { 69 if (lastSnapshotOnDisk !== snapshot) {
74 writeConfig().catch((err) => { 70 writeConfig().catch((err) => {
75 log.error('Failed to write config on config change', err); 71 log.error('Failed to write config on config change', err);
76 }) 72 });
77 } 73 }
78 }, debounceTime)); 74 }, debounceTime));
79 75
80 const disposeWatcher = persistenceService.watchConfig(async () => { 76 const disposeWatcher = persistenceService.watchConfig(async () => {
81 await readConfig(); 77 try {
78 await readConfig();
79 } catch (err) {
80 log.error('Failed to read config', err);
81 }
82 }, debounceTime); 82 }, debounceTime);
83 83
84 return () => { 84 return () => {
diff --git a/packages/main/src/services/ConfigPersistenceService.ts b/packages/main/src/services/ConfigPersistenceService.ts
index b2109f6..b3ad162 100644
--- a/packages/main/src/services/ConfigPersistenceService.ts
+++ b/packages/main/src/services/ConfigPersistenceService.ts
@@ -17,112 +17,16 @@
17 * 17 *
18 * SPDX-License-Identifier: AGPL-3.0-only 18 * SPDX-License-Identifier: AGPL-3.0-only
19 */ 19 */
20import { watch } from 'fs';
21import { readFile, stat, writeFile } from 'fs/promises';
22import JSON5 from 'json5';
23import throttle from 'lodash-es/throttle';
24import { join } from 'path';
25 20
26import type { ConfigSnapshotOut } from '../stores/Config'; 21import type { ConfigSnapshotOut } from '../stores/Config';
27import { Disposer, getLogger } from '../utils'; 22import { Disposer } from '../utils';
28
29const log = getLogger('configPersistence');
30 23
31export type ReadConfigResult = { found: true; data: unknown; } | { found: false; }; 24export type ReadConfigResult = { found: true; data: unknown; } | { found: false; };
32 25
33export class ConfigPersistenceService { 26export interface ConfigPersistenceService {
34 private readonly configFilePath: string; 27 readConfig(): Promise<ReadConfigResult>;
35
36 private writingConfig = false;
37
38 private timeLastWritten: Date | null = null;
39
40 constructor(
41 private readonly userDataDir: string,
42 private readonly configFileName: string = 'config.json5',
43 ) {
44 this.configFileName = configFileName;
45 this.configFilePath = join(this.userDataDir, this.configFileName);
46 }
47
48 async readConfig(): Promise<ReadConfigResult> {
49 let configStr;
50 try {
51 configStr = await readFile(this.configFilePath, 'utf8');
52 } catch (err) {
53 if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
54 log.debug('Config file', this.configFilePath, 'was not found');
55 return { found: false };
56 }
57 throw err;
58 }
59 log.info('Read config file', this.configFilePath);
60 return {
61 found: true,
62 data: JSON5.parse(configStr),
63 };
64 }
65
66 async writeConfig(configSnapshot: ConfigSnapshotOut): Promise<void> {
67 const configJson = JSON5.stringify(configSnapshot, {
68 space: 2,
69 });
70 this.writingConfig = true;
71 try {
72 await writeFile(this.configFilePath, configJson, 'utf8');
73 const { mtime } = await stat(this.configFilePath);
74 log.trace('Config file', this.configFilePath, 'last written at', mtime);
75 this.timeLastWritten = mtime;
76 } finally {
77 this.writingConfig = false;
78 }
79 log.info('Wrote config file', this.configFilePath);
80 }
81
82 watchConfig(callback: () => Promise<void>, throttleMs: number): Disposer {
83 log.debug('Installing watcher for', this.userDataDir);
84
85 const configChanged = throttle(async () => {
86 let mtime: Date;
87 try {
88 const stats = await stat(this.configFilePath);
89 mtime = stats.mtime;
90 log.trace('Config file last modified at', mtime);
91 } catch (err) {
92 if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
93 log.debug('Config file', this.configFilePath, 'was deleted after being changed');
94 return;
95 }
96 throw err;
97 }
98 if (!this.writingConfig
99 && (this.timeLastWritten === null || mtime > this.timeLastWritten)) {
100 log.debug(
101 'Found a config file modified at',
102 mtime,
103 'whish is newer than last written',
104 this.timeLastWritten,
105 );
106 return callback();
107 }
108 }, throttleMs);
109
110 const watcher = watch(this.userDataDir, {
111 persistent: false,
112 });
113 28
114 watcher.on('change', (eventType, filename) => { 29 writeConfig(configSnapshot: ConfigSnapshotOut): Promise<void>;
115 if (eventType === 'change'
116 && (filename === this.configFileName || filename === null)) {
117 configChanged()?.catch((err) => {
118 console.log('Unhandled error while listening for config changes', err);
119 });
120 }
121 });
122 30
123 return () => { 31 watchConfig(callback: () => Promise<void>, throttleMs: number): Disposer;
124 log.trace('Removing watcher for', this.configFilePath);
125 watcher.close();
126 };
127 }
128} 32}
diff --git a/packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts b/packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts
new file mode 100644
index 0000000..bffc38c
--- /dev/null
+++ b/packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts
@@ -0,0 +1,128 @@
1
2/*
3 * Copyright (C) 2021-2022 Kristóf Marussy <kristof@marussy.com>
4 *
5 * This file is part of Sophie.
6 *
7 * Sophie is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, version 3.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 *
19 * SPDX-License-Identifier: AGPL-3.0-only
20 */
21import { watch } from 'fs';
22import { readFile, stat, writeFile } from 'fs/promises';
23import JSON5 from 'json5';
24import throttle from 'lodash-es/throttle';
25import { join } from 'path';
26
27import type { ConfigPersistenceService, ReadConfigResult } from '../ConfigPersistenceService';
28import type { ConfigSnapshotOut } from '../../stores/Config';
29import { Disposer, getLogger } from '../../utils';
30
31const log = getLogger('configPersistence');
32
33export class ConfigPersistenceServiceImpl implements ConfigPersistenceService {
34 private readonly configFilePath: string;
35
36 private writingConfig = false;
37
38 private timeLastWritten: Date | null = null;
39
40 constructor(
41 private readonly userDataDir: string,
42 private readonly configFileName: string = 'config.json5',
43 ) {
44 this.configFileName = configFileName;
45 this.configFilePath = join(this.userDataDir, this.configFileName);
46 }
47
48 async readConfig(): Promise<ReadConfigResult> {
49 let configStr;
50 try {
51 configStr = await readFile(this.configFilePath, 'utf8');
52 } catch (err) {
53 if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
54 log.debug('Config file', this.configFilePath, 'was not found');
55 return { found: false };
56 }
57 throw err;
58 }
59 log.info('Read config file', this.configFilePath);
60 return {
61 found: true,
62 data: JSON5.parse(configStr),
63 };
64 }
65
66 async writeConfig(configSnapshot: ConfigSnapshotOut): Promise<void> {
67 const configJson = JSON5.stringify(configSnapshot, {
68 space: 2,
69 });
70 this.writingConfig = true;
71 try {
72 await writeFile(this.configFilePath, configJson, 'utf8');
73 const { mtime } = await stat(this.configFilePath);
74 log.trace('Config file', this.configFilePath, 'last written at', mtime);
75 this.timeLastWritten = mtime;
76 } finally {
77 this.writingConfig = false;
78 }
79 log.info('Wrote config file', this.configFilePath);
80 }
81
82 watchConfig(callback: () => Promise<void>, throttleMs: number): Disposer {
83 log.debug('Installing watcher for', this.userDataDir);
84
85 const configChanged = throttle(async () => {
86 let mtime: Date;
87 try {
88 const stats = await stat(this.configFilePath);
89 mtime = stats.mtime;
90 log.trace('Config file last modified at', mtime);
91 } catch (err) {
92 if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
93 log.debug('Config file', this.configFilePath, 'was deleted after being changed');
94 return;
95 }
96 throw err;
97 }
98 if (!this.writingConfig
99 && (this.timeLastWritten === null || mtime > this.timeLastWritten)) {
100 log.debug(
101 'Found a config file modified at',
102 mtime,
103 'whish is newer than last written',
104 this.timeLastWritten,
105 );
106 return callback();
107 }
108 }, throttleMs);
109
110 const watcher = watch(this.userDataDir, {
111 persistent: false,
112 });
113
114 watcher.on('change', (eventType, filename) => {
115 if (eventType === 'change'
116 && (filename === this.configFileName || filename === null)) {
117 configChanged()?.catch((err) => {
118 console.log('Unhandled error while listening for config changes', err);
119 });
120 }
121 });
122
123 return () => {
124 log.trace('Removing watcher for', this.configFilePath);
125 watcher.close();
126 };
127 }
128}
diff --git a/packages/main/src/utils/index.ts b/packages/main/src/utils/index.ts
index 9a57e02..2b85989 100644
--- a/packages/main/src/utils/index.ts
+++ b/packages/main/src/utils/index.ts
@@ -22,4 +22,4 @@ import { IDisposer } from 'mobx-state-tree';
22 22
23export type Disposer = IDisposer; 23export type Disposer = IDisposer;
24 24
25export { getLogger } from './logging'; 25export { getLogger, silenceLogger } from './logging';
diff --git a/packages/main/src/utils/logging.ts b/packages/main/src/utils/logging.ts
index 6c4cba2..ed40365 100644
--- a/packages/main/src/utils/logging.ts
+++ b/packages/main/src/utils/logging.ts
@@ -18,17 +18,17 @@
18 * SPDX-License-Identifier: AGPL-3.0-only 18 * SPDX-License-Identifier: AGPL-3.0-only
19 */ 19 */
20 20
21import chalk, { ChalkInstance } from 'chalk'; 21import chalk, { Chalk } from 'chalk';
22import loglevel, { Logger } from 'loglevel'; 22import loglevel, { Logger } from 'loglevel';
23import prefix from 'loglevel-plugin-prefix'; 23import prefix from 'loglevel-plugin-prefix';
24 24
25if (import.meta.env.DEV) { 25if (import.meta.env?.DEV) {
26 loglevel.setLevel('debug'); 26 loglevel.setLevel('debug');
27} else { 27} else {
28 loglevel.setLevel('info'); 28 loglevel.setLevel('info');
29} 29}
30 30
31const COLORS: Partial<Record<string, ChalkInstance>> = { 31const COLORS: Partial<Record<string, Chalk>> = {
32 TRACE: chalk.magenta, 32 TRACE: chalk.magenta,
33 DEBUG: chalk.cyan, 33 DEBUG: chalk.cyan,
34 INFO: chalk.blue, 34 INFO: chalk.blue,
@@ -37,7 +37,7 @@ const COLORS: Partial<Record<string, ChalkInstance>> = {
37 CRITICAL: chalk.red, 37 CRITICAL: chalk.red,
38}; 38};
39 39
40function getColor(level: string): ChalkInstance { 40function getColor(level: string): Chalk {
41 return COLORS[level] ?? chalk.gray; 41 return COLORS[level] ?? chalk.gray;
42} 42}
43 43
@@ -52,3 +52,11 @@ prefix.apply(loglevel, {
52export function getLogger(loggerName: string): Logger { 52export function getLogger(loggerName: string): Logger {
53 return loglevel.getLogger(loggerName); 53 return loglevel.getLogger(loggerName);
54} 54}
55
56export function silenceLogger(): void {
57 loglevel.disableAll();
58 const loggers = loglevel.getLoggers();
59 for (const loggerName of Object.keys(loggers)) {
60 loggers[loggerName].disableAll();
61 }
62}