|
| 1 | +import * as util from 'util'; |
| 2 | +import type { ActionLessMessage, ActionLessRequest, IoHelper } from './io-helper'; |
| 3 | +import type { IoMessageMaker } from './message-maker'; |
| 4 | +import { IO } from './messages'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Helper class to emit standard log messages to an IoHost |
| 8 | + * |
| 9 | + * It wraps an `IoHelper`, and adds convenience methods to emit default messages |
| 10 | + * for the various log levels. |
| 11 | + */ |
| 12 | +export class IoDefaultMessages { |
| 13 | + constructor(private readonly ioHelper: IoHelper) { |
| 14 | + } |
| 15 | + |
| 16 | + public notify(msg: ActionLessMessage<unknown>): Promise<void> { |
| 17 | + return this.ioHelper.notify(msg); |
| 18 | + } |
| 19 | + |
| 20 | + public requestResponse<T, U>(msg: ActionLessRequest<T, U>): Promise<U> { |
| 21 | + return this.ioHelper.requestResponse(msg); |
| 22 | + } |
| 23 | + |
| 24 | + public error(input: string, ...args: unknown[]) { |
| 25 | + this.emitMessage(IO.DEFAULT_TOOLKIT_ERROR, input, ...args); |
| 26 | + } |
| 27 | + |
| 28 | + public warn(input: string, ...args: unknown[]) { |
| 29 | + this.emitMessage(IO.DEFAULT_TOOLKIT_WARN, input, ...args); |
| 30 | + } |
| 31 | + |
| 32 | + public warning(input: string, ...args: unknown[]) { |
| 33 | + this.emitMessage(IO.DEFAULT_TOOLKIT_WARN, input, ...args); |
| 34 | + } |
| 35 | + |
| 36 | + public info(input: string, ...args: unknown[]) { |
| 37 | + this.emitMessage(IO.DEFAULT_TOOLKIT_INFO, input, ...args); |
| 38 | + } |
| 39 | + |
| 40 | + public debug(input: string, ...args: unknown[]) { |
| 41 | + this.emitMessage(IO.DEFAULT_TOOLKIT_DEBUG, input, ...args); |
| 42 | + } |
| 43 | + |
| 44 | + public trace(input: string, ...args: unknown[]) { |
| 45 | + this.emitMessage(IO.DEFAULT_TOOLKIT_TRACE, input, ...args); |
| 46 | + } |
| 47 | + |
| 48 | + public result(input: string, ...args: unknown[]) { |
| 49 | + const message = args.length > 0 ? util.format(input, ...args) : input; |
| 50 | + // This is just the default "info" message but with a level of "result" |
| 51 | + void this.ioHelper.notify({ |
| 52 | + time: new Date(), |
| 53 | + code: IO.DEFAULT_TOOLKIT_INFO.code, |
| 54 | + level: 'result', |
| 55 | + message, |
| 56 | + data: undefined, |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + private emitMessage(maker: IoMessageMaker<void>, input: string, ...args: unknown[]) { |
| 61 | + // Format message if args are provided |
| 62 | + const message = args.length > 0 ? util.format(input, ...args) : input; |
| 63 | + void this.ioHelper.notify(maker.msg(message)); |
| 64 | + } |
| 65 | +} |
0 commit comments