Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switched to ESM #554

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintrc.js → .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ module.exports = {
'**/docs/*'
],
rules: {
'@typescript-eslint/no-misused-promises': 'off'
'@typescript-eslint/no-misused-promises': 'off',
"@typescript-eslint/unbound-method": "off"
},
parserOptions: {
project: './tsconfig.json'
Expand Down
18 changes: 12 additions & 6 deletions core/app.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import minimist from 'minimist'
import { lt } from 'semver'
import { version } from '../package.json'
import logger, { eventbusTransport } from './logging'
import { runServer } from './web/server'
import moduleService from './modules/ModuleService'
import lpteService from './eventbus/LPTEService'
import logger, { eventbusTransport } from './logging/logger.js'
import { runServer } from './web/server.js'
import moduleService from './modules/ModuleService.js'
import lpteService from './eventbus/LPTEService.js'
import axios from 'axios'
import { readJSON } from 'fs-extra/esm'
import { fileURLToPath } from 'url'
import { join } from 'path'
// eslint-disable-next-line @typescript-eslint/naming-convention
const __dirname = fileURLToPath(new URL('.', import.meta.url))

const argv = minimist(process.argv.slice(2))

Expand All @@ -22,6 +26,8 @@ log.info('| |__| (_) | |___ | | (_) | (_) | | <| | |_ ')
log.info('|_____\\___/|_____| |_|\\___/ \\___/|_|_|\\_\\_|\\__|')
log.info('')

const { version } = await readJSON(join(__dirname, '..', 'package.json'))

const checkVersion = async (): Promise<any> => {
const res = await axios.get('https://prod-toolkit-latest.himyu.workers.dev/', {
headers: { 'Accept-Encoding': 'gzip,deflate,compress' }
Expand All @@ -31,7 +37,7 @@ const checkVersion = async (): Promise<any> => {
return log.warn('The current version could not be checked')
}

if (lt(version, res.data.tag_name)) {
if (lt(version as string, res.data.tag_name)) {
log.info('='.repeat(50))
log.info(`There is a new version available: ${res.data.tag_name as string}`)
log.info('='.repeat(50))
Expand Down
2 changes: 1 addition & 1 deletion core/eventbus/LPTE.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type ModuleType from '../modules/ModuleType'
import type ModuleType from '../modules/ModuleType.js'

export enum EventType {
BROADCAST = 'BROADCAST',
Expand Down
13 changes: 6 additions & 7 deletions core/eventbus/LPTEService.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { type LPTE, type LPTEvent, EventType, Registration } from './LPTE'
import logger from '../logging'
import { type Plugin } from '../modules/Module'
import ModuleType from '../modules/ModuleType'
import { wsClients } from '../web/server'
import { type LPTE, type LPTEvent, EventType, Registration } from './LPTE.js'
import logger from '../logging/index.js'
import { type Plugin } from '../modules/Module.js'
import ModuleType from '../modules/ModuleType.js'
import { wsClients } from '../web/server.js'
import uniqid from 'uniqid'

const log = logger('lpte-svc')

export const isValidEvent = (event: LPTEvent): boolean => {
if (
event.meta === undefined ||
event.meta.namespace === undefined ||
event.meta?.namespace === undefined ||
event.meta.type === undefined
) {
return false
Expand Down
2 changes: 1 addition & 1 deletion core/logging/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import logger, { eventbusTransport } from './logger'
import logger, { eventbusTransport } from './logger.js'

export default logger
export { eventbusTransport }
6 changes: 3 additions & 3 deletions core/logging/logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import winston, { type Logger } from 'winston'
import Transport from 'winston-transport'

import { type LPTE } from '../eventbus/LPTE'
import { type LPTE } from '../eventbus/LPTE.js'

const customFormat = winston.format.printf(
({ level, message, label, timestamp }) =>
Expand All @@ -12,13 +12,13 @@ const customFormat = winston.format.printf(
export class EventbusTransport extends Transport {
lpte?: LPTE

constructor(opts: any = {}) {
constructor (opts: any = {}) {
super(opts)

this.log = this.log.bind(this)
}

log(info: any, callback: () => void): void {
log (info: any, callback: () => void): void {
if ((info.level.includes('error') as boolean) && this.lpte != null) {
this.lpte.emit({
meta: {
Expand Down
25 changes: 13 additions & 12 deletions core/modules/Module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { join } from 'path'
import { Logger } from 'winston'
import ModuleType from './ModuleType'
import lpteService from '../eventbus/LPTEService'
import logger from '../logging'
import { LPTE } from '../eventbus/LPTE'
import ModuleType from './ModuleType.js'
import lpteService from '../eventbus/LPTEService.js'
import logger from '../logging/index.js'
import { LPTE } from '../eventbus/LPTE.js'
import { MultiBar } from 'cli-progress'
import progress from '../logging/progress'
import progress from '../logging/progress.js'
import { gt } from 'semver'
import { pathToFileURL } from 'url'

export interface PackageJson {
name: string
Expand Down Expand Up @@ -112,15 +113,15 @@ export enum PluginStatus {

export class PluginContext {
log: Logger
require: (file: string) => any
require: (file: string) => Promise<any>
LPTE: LPTE
plugin: Plugin
progress: MultiBar

constructor(plugin: Plugin) {
this.log = logger(plugin.getModule().getName())
this.require = (file: string) =>
require(join(plugin.getModule().getFolder(), file))
this.require = async (file: string) =>
await import(join(plugin.getModule().getFolder(), file))
this.LPTE = lpteService.forPlugin(plugin)
this.plugin = plugin
this.progress = progress(plugin.module.getName())
Expand Down Expand Up @@ -160,7 +161,7 @@ export class Plugin {
}
}

initialize(): void {
async initialize(): Promise<void> {
// Craft context
this.context = new PluginContext(this)

Expand All @@ -179,16 +180,16 @@ export class Plugin {

let main
try {
// eslint-disable-next-line
main = require(join(this.getModule().getFolder(), mainFile))
const mainURL = pathToFileURL(join(this.getModule().getFolder(), mainFile))
main = await import(mainURL.href)
} catch (e) {
handleError(e)
return
}

// Execute main (and wrap it in a try / catch, so there cannot be an exception bubbling up)
try {
const response: void | Promise<void> | undefined = main(this.context)
const response: void | Promise<void> | undefined = main.default(this.context)

if (response !== undefined && typeof response.catch === 'function') {
response.catch((e: any) => handleError(e))
Expand Down
21 changes: 12 additions & 9 deletions core/modules/ModuleService.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { Stats } from 'fs'
import { readdir, stat } from 'fs/promises'
import { join } from 'path'
import LPTEService from '../eventbus/LPTEService.js'
import logging from '../logging/index.js'
import Module, { Plugin, PluginStatus, Asset, PackageJson } from './Module.js'
import ModuleType from './ModuleType.js'
import { EventType } from '../eventbus/LPTE.js'
import { download, getAll } from '../../scripts/install.js'
import { fileURLToPath } from 'url';
import { readJSON } from 'fs-extra/esm'

import LPTEService from '../eventbus/LPTEService'
import logging from '../logging'
import Module, { Plugin, PluginStatus, Asset, PackageJson } from './Module'
import ModuleType from './ModuleType'
import { EventType } from '../eventbus/LPTE'
import { download, getAll } from '../../scripts/install'
const __dirname = fileURLToPath(new URL('.', import.meta.url));

const readdirPromise = readdir
const statPromise = stat
Expand Down Expand Up @@ -165,8 +168,8 @@ export class ModuleService {
)

// Launch plugins
this.activePlugins.forEach((plugin) => {
plugin.initialize()
this.activePlugins.forEach(async (plugin) => {
await plugin.initialize()
})
}

Expand Down Expand Up @@ -232,7 +235,7 @@ export class ModuleService {
}

// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJson = require(packageJsonPath) as PackageJson
const packageJson = await readJSON(packageJsonPath) as PackageJson

const index = this.assets.findIndex((a) => a.name === packageJson.name)
let asset
Expand Down
18 changes: 11 additions & 7 deletions core/web/auth.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import LPTEService from '../eventbus/LPTEService'
import LPTEService from '../eventbus/LPTEService.js'
import { type IncomingMessage } from 'http'
import type WebSocket from 'ws'
import uuidAPIKey from 'uuid-apikey'
import logging from '../logging'
import logging from '../logging/index.js'
import { type OutgoingHttpHeaders } from 'http2'
import { type Express, type NextFunction, type Request, type Response } from 'express'
import jwt from 'jsonwebtoken'
import ModuleType from '../modules/ModuleType'
import ModuleType from '../modules/ModuleType.js'

const log = logging('auth')

Expand All @@ -16,7 +16,8 @@ let config: any

export async function runAuth (
server: Express,
wss: WebSocket.Server
wss: WebSocket.Server,
swss?: WebSocket.Server
): Promise<void> {
const configReq = await LPTEService.request({
meta: {
Expand Down Expand Up @@ -51,6 +52,9 @@ export async function runAuth (
log.info('=========================')

wss.options.verifyClient = verifyWSClient

if (swss !== undefined) swss.options.verifyClient = verifyWSClient

server.all('*', verifyEPClient)

server.get('/login', (_req, res) => {
Expand Down Expand Up @@ -86,7 +90,7 @@ async function getKeys (): Promise<void> {
}

LPTEService.on('auth', 'add-key', (e) => {
const { apiKey } = uuidAPIKey.create()
const { apiKey } = uuidAPIKey.default.create()

LPTEService.emit({
meta: {
Expand All @@ -96,15 +100,15 @@ LPTEService.on('auth', 'add-key', (e) => {
},
collection: 'key',
data: {
apiKey: 'RCVPT-' + apiKey,
apiKey: `RCVPT-${apiKey}`,
description: e.description,
expiring: (e.neverExpires as boolean)
? -1
: new Date(e.expiring).getTime()
}
})

allowedKeys.add('RCVPT-' + apiKey)
allowedKeys.add(`RCVPT-${apiKey}`)

LPTEService.emit({
meta: {
Expand Down
2 changes: 1 addition & 1 deletion core/web/controller/api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Router } from 'express'

import lpte from '../../eventbus/LPTEService'
import lpte from '../../eventbus/LPTEService.js'

const router = Router()

Expand Down
2 changes: 1 addition & 1 deletion core/web/controller/events.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Router } from 'express'

import lpteService from '../../eventbus/LPTEService'
import lpteService from '../../eventbus/LPTEService.js'

export default (globalContext: any): Router => {
const router = Router()
Expand Down
8 changes: 7 additions & 1 deletion core/web/controller/home.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { Router } from 'express'
import { version } from '../../../package.json'
import { readJSON } from 'fs-extra/esm'
import { fileURLToPath } from 'url'
import { join } from 'path'
// eslint-disable-next-line @typescript-eslint/naming-convention
const __dirname = fileURLToPath(new URL('.', import.meta.url))

const { version } = await readJSON(join(__dirname, '../../../package.json'))

export default (globalContext: any): Router => {
const router = Router()
Expand Down
16 changes: 8 additions & 8 deletions core/web/controller/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { type Router } from 'express'

import modules from './modules'
import home from './home'
import plugins from './plugins'
import events from './events'
import api from './api'
import pages from './pages'
import serve from './serve'
import keys from './keys'
import modules from './modules.js'
import home from './home.js'
import plugins from './plugins.js'
import events from './events.js'
import api from './api.js'
import pages from './pages.js'
import serve from './serve.js'
import keys from './keys.js'

export default (
globalContext: any
Expand Down
2 changes: 1 addition & 1 deletion core/web/controller/keys.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Router } from 'express'

import lpteService from '../../eventbus/LPTEService'
import lpteService from '../../eventbus/LPTEService.js'

export default (globalContext: any): Router => {
const router = Router()
Expand Down
2 changes: 1 addition & 1 deletion core/web/controller/modules.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Router } from 'express'

import moduleService from '../../modules/ModuleService'
import moduleService from '../../modules/ModuleService.js'

export default (globalContext: any): Router => {
const router = Router()
Expand Down
10 changes: 5 additions & 5 deletions core/web/controller/pages.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Router } from 'express'
import { join, relative, isAbsolute } from 'path'
import send from 'send'
import svc from '../../modules/ModuleService'
import svc from '../../modules/ModuleService.js'
import { readFile } from 'fs/promises'
import { pathExists } from 'fs-extra'
import { type GlobalContext } from '../globalContext'
import escape from 'validator/lib/escape'
import { pathExists } from 'fs-extra/esm'
import { type GlobalContext } from '../globalContext.js'
import validator from 'validator'

export default (globalContext: GlobalContext): Router => {
const router = Router()
Expand All @@ -19,7 +19,7 @@ export default (globalContext: GlobalContext): Router => {
if (page === undefined) {
return res
.status(404)
.send(`No page found with name ${escape(anyParams?.page)}`)
.send(`No page found with name ${validator.default.escape(anyParams?.page)}`)
}

const relativePath = anyParams?.[0] !== '' ? anyParams?.[0] : '/'
Expand Down
2 changes: 1 addition & 1 deletion core/web/controller/plugins.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Router } from 'express'

import moduleService from '../../modules/ModuleService'
import moduleService from '../../modules/ModuleService.js'

export default (globalContext: any): Router => {
const router = Router()
Expand Down
Loading