feat(packages/shared): add logger factory

- @revanced/websocket-api now also utilizes the new logger from the shared package
- @revanced/websocket-api/utils/checkEnv has been renamed to its full form
  - It also no longer returns anything as it's no longer needed
This commit is contained in:
PalmDevs
2023-11-29 00:52:17 +07:00
parent f2d85c32a4
commit 17c6be7bee
20 changed files with 179 additions and 234 deletions

View File

@@ -31,7 +31,9 @@
"homepage": "https://github.com/revanced/revanced-helper#readme",
"dependencies": {
"bson": "^6.2.0",
"chalk": "^5.3.0",
"valibot": "^0.21.0",
"winston": "^3.11.0",
"zod": "^3.22.4"
}
}

View File

@@ -7,8 +7,7 @@ const HumanizedDisconnectReason = {
[DisconnectReason.InvalidPacket]: 'has sent invalid packet',
[DisconnectReason.Generic]: 'has been disconnected for unknown reasons',
[DisconnectReason.TimedOut]: 'has timed out',
[DisconnectReason.ServerError]:
'has been disconnected due to an internal server error',
[DisconnectReason.ServerError]: 'has been disconnected due to an internal server error',
[DisconnectReason.NeverConnected]: 'had never connected to the server',
} as const satisfies Record<DisconnectReason, string>

View File

@@ -15,11 +15,7 @@ import {
// merge
} from 'valibot'
import DisconnectReason from '../constants/DisconnectReason.js'
import {
ClientOperation,
Operation,
ServerOperation,
} from '../constants/Operation.js'
import { ClientOperation, Operation, ServerOperation } from '../constants/Operation.js'
/**
* Schema to validate packets
@@ -59,10 +55,7 @@ export const PacketDataSchemas = {
labels: array(
object({
name: string(),
confidence: special<number>(
input =>
typeof input === 'number' && input >= 0 && input <= 1,
),
confidence: special<number>(input => typeof input === 'number' && input >= 0 && input <= 1),
}),
),
}),

View File

@@ -1,8 +1,4 @@
import {
ClientOperation,
Operation,
ServerOperation,
} from '../constants/Operation.js'
import { ClientOperation, Operation, ServerOperation } from '../constants/Operation.js'
import { Packet } from '../schemas/Packet.js'
/**
@@ -11,10 +7,7 @@ import { Packet } from '../schemas/Packet.js'
* @param packet A packet
* @returns Whether this packet is trying to do the operation given
*/
export function packetMatchesOperation<TOp extends Operation>(
op: TOp,
packet: Packet,
): packet is Packet<TOp> {
export function packetMatchesOperation<TOp extends Operation>(op: TOp, packet: Packet): packet is Packet<TOp> {
return packet.op === op
}
@@ -23,9 +16,7 @@ export function packetMatchesOperation<TOp extends Operation>(
* @param packet A packet
* @returns Whether this packet is a client packet
*/
export function isClientPacket(
packet: Packet,
): packet is Packet<ClientOperation> {
export function isClientPacket(packet: Packet): packet is Packet<ClientOperation> {
return packet.op in ClientOperation
}
@@ -34,8 +25,6 @@ export function isClientPacket(
* @param packet A packet
* @returns Whether this packet is a server packet
*/
export function isServerPacket(
packet: Packet,
): packet is Packet<ServerOperation> {
export function isServerPacket(packet: Packet): packet is Packet<ServerOperation> {
return packet.op in ServerOperation
}

View File

@@ -1,3 +1,4 @@
export * from './guard.js'
export * from './logger.js'
export * from './serialization.js'
export * from './string.js'

View File

@@ -0,0 +1,66 @@
import { createLogger as createWinstonLogger, LoggerOptions, transports, format } from 'winston'
import { Chalk, ChalkInstance } from 'chalk'
const chalk = new Chalk()
const LevelPrefixes = {
error: `${chalk.bgRed.whiteBright(' ERR! ')} `,
warn: `${chalk.bgYellow.black(' WARN ')} `,
info: `${chalk.bgBlue.whiteBright(' INFO ')} `,
log: chalk.reset(''),
debug: chalk.gray('DEBUG: '),
silly: chalk.gray('SILLY: '),
} as Record<string, string>
const LevelColorFunctions = {
error: chalk.redBright,
warn: chalk.yellowBright,
info: chalk.cyanBright,
log: chalk.reset,
debug: chalk.gray,
silly: chalk.gray,
} as Record<string, ChalkInstance>
export function createLogger(
serviceName: string,
config: SafeOmit<
LoggerOptions,
| 'defaultMeta'
| 'exceptionHandlers'
| 'exitOnError'
| 'handleExceptions'
| 'handleRejections'
| 'levels'
| 'rejectionHandlers'
>,
) {
const logger = createWinstonLogger({
exitOnError: false,
defaultMeta: { serviceName },
handleExceptions: true,
handleRejections: true,
transports: config.transports ?? [
new transports.Console(),
new transports.File({
dirname: 'logs',
filename: `${serviceName}-${Date.now()}.log`,
format: format.combine(
format.uncolorize(),
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
format.printf(
({ level, message, timestamp }) => `[${timestamp}] ${level.toUpperCase()}: ${message}`,
),
),
}),
],
format: format.printf(({ level, message }) => LevelPrefixes[level] + LevelColorFunctions[level]!(message)),
...config,
})
logger.silly(`Logger for ${serviceName} created at ${Date.now()}`)
return logger
}
type SafeOmit<T, K extends keyof T> = Omit<T, K>
export type Logger = ReturnType<typeof createLogger>