From 4f3481fcfc9e01eaa3eee442571961a4ee8b8467 Mon Sep 17 00:00:00 2001 From: Timur Shemsedinov Date: Wed, 12 Aug 2026 01:42:15 +0300 Subject: [PATCH] Fix code style in whole codebase --- impress.js | 23 ++++++++---- lib/api.js | 13 ++++--- lib/application.js | 46 ++++++++++++++--------- lib/auth.js | 2 +- lib/balancer.js | 8 +++- lib/bus.js | 21 +++++++---- lib/cert.js | 5 ++- lib/code.js | 9 +++-- lib/deps.js | 10 +++-- lib/place.js | 2 +- lib/planner.js | 16 +++++--- lib/procedure.js | 28 +++++++------- lib/scheduler.js | 6 ++- lib/static.js | 7 ++-- lib/worker.js | 25 +++++++------ test/api.js | 4 +- test/auth.js | 1 + test/balancer.js | 3 +- test/bus.js | 14 +++---- test/cache.js | 1 + test/cert.js | 5 ++- test/code.js | 4 +- test/deps.js | 1 + test/lib/example/start.js | 12 +++--- test/planner.js | 2 +- test/procedure.js | 4 +- test/schemas.js | 1 + test/static.js | 78 ++++++++++----------------------------- types/core.d.ts | 17 ++++++--- types/impress.d.ts | 18 ++++----- 30 files changed, 204 insertions(+), 182 deletions(-) diff --git a/impress.js b/impress.js index 7f3ec8652..45e43e12f 100644 --- a/impress.js +++ b/impress.js @@ -5,6 +5,7 @@ process.title = 'impress'; const fsp = require('node:fs').promises; const { Worker } = require('node:worker_threads'); const path = require('node:path'); + const { Config } = require('metaconfiguration'); const metavm = require('metavm'); const { Pool, isError } = require('metautil'); @@ -39,7 +40,7 @@ const exit = async (message, code) => { if (impress.finalization) return; impress.finalization = true; impress.console.info(message); - if (impress.logger && impress.logger.active) await impress.logger.close(); + if (impress.logger?.active) await impress.logger.close(); process.exit(code); }; @@ -150,7 +151,8 @@ const validateConfig = async (config) => { const checkResult = schema.check(config[section]); if (!checkResult.valid) { for (const error of checkResult.errors) { - impress.console.error(`${error} in application/config/${section}.js`); + const loc = `application/config/${section}.js`; + impress.console.error(`${error} in ${loc}`); } valid = false; } @@ -162,7 +164,8 @@ const loadApplication = async (root, dir, master) => { impress.console.info(`Start: ${dir}`); const configPath = path.join(dir, 'config'); const config = await new Config(configPath, CFG_OPTIONS).catch((error) => { - exit(`Can not read configuration: ${configPath}\n${error.stack}`, 1); + const { stack } = error; + exit(`Can not read configuration: ${configPath}\n${stack}`, 1); }); await validateConfig(config); if (master) { @@ -190,11 +193,17 @@ const loadApplication = async (root, dir, master) => { impress.applications.set(dir, app); }; +const parseApplicationsFile = async () => { + try { + const data = await fsp.readFile('.applications', 'utf8'); + return data.split(/[\r\n\s]+/).filter((s) => s.length !== 0); + } catch { + return [path.join(PATH, 'application')]; + } +}; + const loadApplications = async () => { - const applications = await fsp - .readFile('.applications', 'utf8') - .then((data) => data.split(/[\r\n\s]+/).filter((s) => s.length !== 0)) - .catch(() => [path.join(PATH, 'application')]); + const applications = await parseApplicationsFile(); let master = true; for (const dir of applications) { const location = path.isAbsolute(dir) ? dir : path.join(PATH, dir); diff --git a/lib/api.js b/lib/api.js index 5e9718b26..410198ff8 100644 --- a/lib/api.js +++ b/lib/api.js @@ -63,7 +63,8 @@ class Api extends Place { const unit = proc.exports; const relPath = filePath.substring(this.path.length + 1); const [unitDir, methodFile] = relPath.split(node.path.sep); - const unitName = unitDir.includes('.') ? unitDir : `${unitDir}.1`; + const hasVersion = unitDir.includes('.'); + const unitName = hasVersion ? unitDir : `${unitDir}.1`; if (methodFile) { const name = node.path.basename(methodFile, '.js'); return void this.changeUnit(unitName, name, proc); @@ -72,8 +73,8 @@ class Api extends Place { return void this.loadPlugin(unitName, unit); } for (const name of Object.keys(unit)) { - const proc = new Procedure(script, name, this.application); - this.changeUnit(unitName, name, proc); + const methodProc = new Procedure(script, name, this.application); + this.changeUnit(unitName, name, methodProc); } } @@ -87,9 +88,9 @@ class Api extends Place { const options = { context }; const { exports } = metarhia.metavm.createScript(name, pluginSrc, options); const plugin = exports(unit); - for (const [name, script] of Object.entries(plugin)) { - const proc = new Procedure(script, name, this.application); - this.changeUnit(unitName, name, proc); + for (const [methodName, script] of Object.entries(plugin)) { + const proc = new Procedure(script, methodName, this.application); + this.changeUnit(unitName, methodName, proc); } } diff --git a/lib/application.js b/lib/application.js index b80645f03..ee57421dd 100644 --- a/lib/application.js +++ b/lib/application.js @@ -26,6 +26,13 @@ const ERR_INIT = 'Can not initialize an Application'; const ERR_TEST = 'Application tests failed'; const TEST_DELAY = 100; +const placeFromPath = (filePath, appPath) => { + const relPath = filePath.substring(appPath.length + 1); + const sepIndex = relPath.indexOf(node.path.sep); + const place = relPath.substring(0, sepIndex); + return { relPath, place }; +}; + class Application extends EventEmitter { constructor() { super(); @@ -98,35 +105,42 @@ class Application extends EventEmitter { async start() { const { sandbox, config, cert, mode } = this; const { kind, port } = workerData; + if (sandbox.api.auth) { + const provider = sandbox.api.auth.provider || auth(config.sessions); + this.auth = provider; + sandbox.api.auth.provider = provider; + } + const { concurrency, size, timeout } = config.server.queue; + this.semaphore = new Semaphore({ concurrency, size, timeout }); if (kind === 'balancer') { const options = { ...config.server, port }; this.server = new Balancer(this, options); await this.server.listen(); } else if (kind === 'server') { const options = { ...config.server, port }; - if (config.server.protocol === 'https') { + const isHttps = config.server.protocol === 'https'; + if (isHttps) { options.SNICallback = (servername, callback) => { const domain = cert.get(servername); - if (!domain) callback(new Error(`No certificate for ${servername}`)); - else callback(null, domain.creds); + if (domain === undefined) { + const err = new Error(`No certificate for ${servername}`); + callback(err); + } else { + callback(null, domain.creds); + } }; } this.server = new Server(this, options); this.server.httpServer.on('request', (req, res) => { - if (!req.url.startsWith('/api')) this.static.serve(req.url, req, res); + const isApi = req.url.startsWith('/api'); + if (!isApi) this.static.serve(req.url, req, res); }); await this.server.listen(); } - if (sandbox.api.auth) { - const provider = sandbox.api.auth.provider || auth(config.sessions); - this.auth = provider; - sandbox.api.auth.provider = provider; - } - const { concurrency, size, timeout } = config.server.queue; - this.semaphore = new Semaphore({ concurrency, size, timeout }); this.initialization = false; sandbox.application.emit('started'); - if (mode === 'test' && threadId === 1) this.runTests(); + const shouldRunTests = mode === 'test' && threadId === 1; + if (shouldRunTests) this.runTests(); } async runTests() { @@ -201,9 +215,7 @@ class Application extends EventEmitter { this.watcher = new DirectoryWatcher({ timeout }); this.watcher.on('change', (filePath) => { - const relPath = filePath.substring(this.path.length + 1); - const sepIndex = relPath.indexOf(node.path.sep); - const place = relPath.substring(0, sepIndex); + const { relPath, place } = placeFromPath(filePath, this.path); const target = this[place]; if (!target) return; node.fs.stat(filePath, (error, stat) => { @@ -221,9 +233,7 @@ class Application extends EventEmitter { }); this.watcher.on('delete', async (filePath) => { - const relPath = filePath.substring(this.path.length + 1); - const sepIndex = relPath.indexOf(node.path.sep); - const place = relPath.substring(0, sepIndex); + const { relPath, place } = placeFromPath(filePath, this.path); const target = this[place]; if (!target) return; target.delete(filePath); diff --git a/lib/auth.js b/lib/auth.js index 60688c4ba..284775ffc 100644 --- a/lib/auth.js +++ b/lib/auth.js @@ -20,7 +20,7 @@ module.exports = ({ characters, secret, length }) => ({ }, async readSession(token) { - return sessions.get(token) || null; + return sessions.get(token) ?? null; }, async deleteSession(token) { diff --git a/lib/balancer.js b/lib/balancer.js index 7d4471c02..40760e136 100644 --- a/lib/balancer.js +++ b/lib/balancer.js @@ -1,10 +1,12 @@ 'use strict'; const http = require('node:http'); + const { parseHost, sample } = require('metautil'); const { buildHeaders } = require('metacom'); const DEFAULT_LISTEN_RETRY = 3; +const SAFE_REDIRECT_METHODS = ['GET', 'HEAD']; class Balancer { #console = null; @@ -35,7 +37,8 @@ class Balancer { const targetPath = req.url; const location = `${protocol}://${host}:${targetPort}${targetPath}`; if (res.headersSent) return; - const code = ['GET', 'HEAD'].includes(req.method) ? 302 : 307; + const isSafe = SAFE_REDIRECT_METHODS.includes(req.method); + const code = isSafe ? 302 : 307; res.writeHead(code, { ...this.#headers, Location: location }); res.end(); } @@ -57,7 +60,8 @@ class Balancer { const onError = (error) => { count--; - const fatal = error.code !== 'EADDRINUSE' || count === 0; + const addressInUse = error.code === 'EADDRINUSE'; + const fatal = !addressInUse || count === 0; if (fatal) return void reject(error); this.#console.warn(`Address in use: ${host}:${port}, retry...`); setTimeout(listen, timeouts.bind); diff --git a/lib/bus.js b/lib/bus.js index 0651b4f93..3166c5adc 100644 --- a/lib/bus.js +++ b/lib/bus.js @@ -15,19 +15,22 @@ const prepare = (unit, application) => { const { parameters, query, returns } = validation; if (parameters) { const { valid, errors } = parameters.check(args); - const problems = errors.join('; '); - if (!valid) return new Error(`Invalid parameters type: ${problems}`); + if (!valid) { + return new Error(`Invalid parameters type: ${errors.join('; ')}`); + } } if (unit.query.params) { const { valid, errors } = query.check(args); - const problems = errors.join('; '); - if (!valid) return new Error(`Invalid query type: ${problems}`); + if (!valid) { + return new Error(`Invalid query type: ${errors.join('; ')}`); + } } const service = method.parent['.service']; const verb = unit.method.get ? 'get' : 'post'; const target = [service.url, unit.method[verb]]; if (unit.method.path) { - target.push(...unit.method.path.map((arg) => args[arg])); + const pathParts = unit.method.path.map((arg) => args[arg]); + target.push(...pathParts); } let url = target.join('/'); if (unit.query) { @@ -35,7 +38,8 @@ const prepare = (unit, application) => { const { prefix = '', suffix = '' } = unit.query; for (const param of Object.keys(unit.query.params)) { if (!args[param]) continue; - params.push([`${prefix}${param}${suffix}`, args[param]]); + const key = `${prefix}${param}${suffix}`; + params.push([key, args[param]]); } const parsedParams = Object.fromEntries(params); const stringParams = new URLSearchParams(parsedParams).toString(); @@ -46,8 +50,9 @@ const prepare = (unit, application) => { const result = await metarhia.metautil.httpApiCall(url, options); if (returns) { const { valid, errors } = returns.check(result); - const problems = errors.join('; '); - if (!valid) return new Error(`Invalid result type: ${problems}`); + if (!valid) { + return new Error(`Invalid result type: ${errors.join('; ')}`); + } } return result; }; diff --git a/lib/cert.js b/lib/cert.js index 0e7163c35..8de4fa166 100644 --- a/lib/cert.js +++ b/lib/cert.js @@ -60,8 +60,9 @@ class Cert extends Static { const creds = node.tls.createSecureContext(options); const context = { ...options, creds }; for (const domain of domains) this.domains.set(domain, context); - if (!this.application.server?.httpServer.setSecureContext) continue; - this.application.server.httpServer.setSecureContext(options); + const httpServer = this.application.server?.httpServer; + if (!httpServer?.setSecureContext) continue; + httpServer.setSecureContext(options); } catch (error) { for (const domain of domains) this.domains.delete(domain); this.application.console.error(error.stack); diff --git a/lib/code.js b/lib/code.js index 3808bbae3..999297b8e 100644 --- a/lib/code.js +++ b/lib/code.js @@ -34,7 +34,8 @@ class Code extends Place { for (let depth = 0; depth <= last; depth++) { const name = names[depth]; let next = level[name]; - if (depth === last) { + const isLeaf = depth === last; + if (isLeaf) { if (unit === null) { if (name === 'stop') this.stopModule(names[0], level); delete level[name]; @@ -48,8 +49,10 @@ class Code extends Place { let { start } = unit; if (start) start = start.bind(unit); if (depth === 1 && name === 'start') start = unit; - if (start) { - if (start.constructor.name === 'AsyncFunction') { + const shouldRegister = start && (isLeaf || name === 'start'); + if (shouldRegister) { + const isAsync = start.constructor.name === 'AsyncFunction'; + if (isAsync) { this.application.starts.push(start); } else { const msg = `${relPath}/start expected to be async function`; diff --git a/lib/deps.js b/lib/deps.js index eafc2cd6b..218bb9a08 100644 --- a/lib/deps.js +++ b/lib/deps.js @@ -4,6 +4,7 @@ const CWD = process.cwd(); const wt = require('node:worker_threads'); const { createRequire, builtinModules } = require('node:module'); + const metautil = require('metautil'); const appRequire = createRequire(`file://${CWD}/server.js`); @@ -46,7 +47,8 @@ const validSubmodules = (key) => const loadModule = (name) => { const lib = appRequire(name); - const pkg = require(`${CWD}/node_modules/${name}/package.json`); + const pkgPath = `${CWD}/node_modules/${name}/package.json`; + const pkg = require(pkgPath); if (!pkg.exports) return lib; const subKeys = Object.keys(pkg.exports).map((key) => key.substring(2)); const subNames = subKeys.filter(validSubmodules); @@ -73,13 +75,15 @@ for (const name of dependencies) { let lib = null; try { if (internals.includes(name)) { - const realName = name.startsWith('node:') ? name : `node:${name}`; + const hasPrefix = name.startsWith('node:'); + const realName = hasPrefix ? name : `node:${name}`; lib = require(realName); } else { lib = loadModule(name); } } catch (error) { - if (npmpkg.includes(name) || !optional.includes(name)) { + const isRequired = npmpkg.includes(name) || !optional.includes(name); + if (isRequired) { notLoaded.add(`- ${name}: ${error.stack}`); } continue; diff --git a/lib/place.js b/lib/place.js index 87ad89da3..d7ba9afe8 100644 --- a/lib/place.js +++ b/lib/place.js @@ -22,7 +22,7 @@ class Place { else await this.change(filePath); } } catch (error) { - const console = this.application.console || global.console; + const console = this.application.console ?? global.console; console.error(error.stack); } } diff --git a/lib/planner.js b/lib/planner.js index 61532aeb7..c41010e57 100644 --- a/lib/planner.js +++ b/lib/planner.js @@ -81,7 +81,8 @@ class Planner { const every = metarhia.metautil.parseEvery(task.every); const next = metarhia.metautil.nextEvent(every); if (next === -1) { - this.console.error(new Error(`Can't schedule a task ${id} in the past`)); + const error = new Error(`Can't schedule a task ${id} in the past`); + this.console.error(error); return ''; } this.restore(task); @@ -131,8 +132,8 @@ class Planner { return false; } if (next === 0) return false; + const once = task.every.ms === 0; task.timer = setTimeout(() => { - const once = task.every.ms === 0; this.execute(task, once); }, next); return true; @@ -158,7 +159,9 @@ class Planner { } async execute(task, once = false) { - if (task.executing) return void this.fail(task, 'Already started task'); + if (task.executing) { + return void this.fail(task, 'Already started task'); + } task.lastStart = Date.now(); task.executing = true; try { @@ -196,8 +199,8 @@ class Planner { const app = this.applications.get(task.app); if (!app) { port2.close(); - const data = JSON.stringify(task); - const error = new Error(`No application for task: ${data}`); + const taskJson = JSON.stringify(task); + const error = new Error(`No application for task: ${taskJson}`); this.console.error(error); return void reject(error); } @@ -215,7 +218,8 @@ class Planner { fail(task, reason) { const { id, name, run, args } = task; - const target = `${name} (${id}) ${run}(${JSON.stringify(args)})`; + const argsJson = JSON.stringify(args); + const target = `${name} (${id}) ${run}(${argsJson})`; const msg = `${reason}, can't execute: ${target}`; this.console.error(msg); } diff --git a/lib/procedure.js b/lib/procedure.js index 2f1f84920..5e326e42c 100644 --- a/lib/procedure.js +++ b/lib/procedure.js @@ -20,24 +20,24 @@ class Procedure { const { Schema } = metarhia.metaschema; this.parameters = parameters ? Schema.from(parameters, namespaces) : null; this.returns = returns ? Schema.from(returns, namespaces) : null; - this.errors = errors || null; + this.errors = errors ?? null; this.semaphore = null; if (exp.queue) { const { concurrency, size, timeout } = exp.queue; const { Semaphore } = metarhia.metautil; this.semaphore = new Semaphore({ concurrency, size, timeout }); } - this.caption = exp.caption || ''; - this.description = exp.description || ''; - this.access = exp.access || ''; - this.validate = exp.validate || null; + this.caption = exp.caption ?? ''; + this.description = exp.description ?? ''; + this.access = exp.access ?? ''; + this.validate = exp.validate ?? null; const { timeouts } = application.config.server; this.timeout = (exp.timeout ?? timeouts.request) || 0; - this.serializer = exp.serialize || null; - this.protocols = exp.protocols || null; - this.deprecated = exp.deprecated || false; - this.assert = exp.assert || null; - this.examples = exp.examples || null; + this.serializer = exp.serialize ?? null; + this.protocols = exp.protocols ?? null; + this.deprecated = exp.deprecated ?? false; + this.assert = exp.assert ?? null; + this.examples = exp.examples ?? null; } async enter() { @@ -62,8 +62,8 @@ class Procedure { const exp = this.script(context); const method = typeof exp === 'object' ? exp[this.methodName] : exp; if (parameters) { - const { valid, errors } = parameters.check(args); - const problems = errors.join('; '); + const { valid, errors: issues } = parameters.check(args); + const problems = issues.join('; '); if (!valid) return new Error(`Invalid parameters type: ${problems}`); } if (validate) await validate(args); @@ -75,8 +75,8 @@ class Procedure { return result; } if (returns) { - const { valid, errors } = this.returns.check(result); - const problems = errors.join('; '); + const { valid, errors: issues } = this.returns.check(result); + const problems = issues.join('; '); if (!valid) return new Error(`Invalid result type: ${problems}`); } return result; diff --git a/lib/scheduler.js b/lib/scheduler.js index c36e84b75..4f27d35b1 100644 --- a/lib/scheduler.js +++ b/lib/scheduler.js @@ -15,11 +15,13 @@ const add = async (task) => { }; const remove = async (id) => { - wt.parentPort.postMessage({ name: 'task', action: 'remove', task: { id } }); + const task = { id }; + wt.parentPort.postMessage({ name: 'task', action: 'remove', task }); }; const stop = (name = '') => { - wt.parentPort.postMessage({ name: 'task', action: 'stop', task: { name } }); + const task = { name }; + wt.parentPort.postMessage({ name: 'task', action: 'stop', task }); }; module.exports = { add, remove, stop }; diff --git a/lib/static.js b/lib/static.js index a94a8c865..9dcaee782 100644 --- a/lib/static.js +++ b/lib/static.js @@ -10,6 +10,7 @@ const { createReadStream } = fs; const WIN = process.platform === 'win32'; const MAX_FILE_SIZE = '10 mb'; +const MAX_FIND_DEPTH = 64; const MIME_TYPES = { bin: 'application/octet-stream', @@ -129,8 +130,8 @@ class Static extends Place { async change(filePath) { if (this.maxFileSize === -1) { - const maxFileSize = this.application.config?.cache?.maxFileSize; - const size = maxFileSize || MAX_FILE_SIZE; + const configured = this.application.config?.cache?.maxFileSize; + const size = configured || MAX_FILE_SIZE; this.maxFileSize = metautil.sizeToBytes(size); } const ext = metautil.fileExt(filePath); @@ -156,7 +157,7 @@ class Static extends Place { } find(requestPath, code, isParent = false, depth = 0) { - if (depth > 64) return status(code || 404); + if (depth > MAX_FIND_DEPTH) return status(code || 404); let filePath = requestPath; const root = requestPath === '/'; if (code) { diff --git a/lib/worker.js b/lib/worker.js index cde9e3ac4..1d48972d0 100644 --- a/lib/worker.js +++ b/lib/worker.js @@ -53,34 +53,37 @@ const handlers = { process.exit(0); }, - invoke: async ({ from, to, exclusive, data }) => { + invoke: async ({ from, to, exclusive, data, port }) => { if (to) { const { id, status, error, result } = data; const handler = calls.get(id); if (!handler) return; - const callError = status === 'error' ? new Error(error.message) : null; + const isError = status === 'error'; + const callError = isError ? new Error(error.message) : null; return void handler({ error: callError, result }); } + const reply = (data) => { + if (port === undefined) { + return void parentPort.postMessage({ name: 'invoke', to: from, data }); + } + port.postMessage(data); + port.close(); + }; const { sandbox, config } = application; - const msg = { name: 'invoke', to: from }; const { timeout } = config.server.workers; - const { id, method = '', args = {} } = data; + const { method = '', args = {} } = data; const handler = metarhia.metautil.namespaceByPath(sandbox, method); if (!handler) { const error = { message: 'Handler not found' }; - const data = { id, status: 'error', error }; - return void parentPort.postMessage({ ...msg, data }); + return void reply({ error, data: null }); } try { let promise = handler(args); if (timeout) promise = metarhia.metautil.timeoutify(promise, timeout); const result = await promise; - const data = { id, status: 'done', result }; - parentPort.postMessage({ ...msg, data }); + reply({ error: null, data: result }); } catch (error) { - const errData = { message: error.message }; - const data = { id, status: 'error', error: errData }; - parentPort.postMessage({ ...msg, data }); + reply({ error, data: null }); application.console.error(error.stack); } finally { if (exclusive) parentPort.postMessage({ name: 'release' }); diff --git a/test/api.js b/test/api.js index 25e421b0c..1287d3f7c 100644 --- a/test/api.js +++ b/test/api.js @@ -3,6 +3,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); const path = require('node:path'); + const metavm = require('metavm'); const { Api } = require('../lib/api.js'); @@ -25,9 +26,10 @@ test('lib/api load - should load API correctly', async () => { assert.strictEqual(example.default, 1); const { add } = example['1']; + const methodType = add.method.constructor.name; assert.strictEqual(add.constructor.name, 'Procedure'); assert.strictEqual(typeof add.method, 'function'); - assert.strictEqual(add.method.constructor.name, 'AsyncFunction'); + assert.strictEqual(methodType, 'AsyncFunction'); const exportsKeys = ['parameters', 'method', 'returns']; assert.deepStrictEqual(Object.keys(add.exports), exportsKeys); diff --git a/test/auth.js b/test/auth.js index 32cb1aecb..d811a11c8 100644 --- a/test/auth.js +++ b/test/auth.js @@ -2,6 +2,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); + const auth = require('../lib/auth.js'); const OPTIONS = { characters: 'ABCabc123', secret: 'test-secret', length: 32 }; diff --git a/test/balancer.js b/test/balancer.js index d95bc5f8e..602772b46 100644 --- a/test/balancer.js +++ b/test/balancer.js @@ -4,11 +4,10 @@ const { test } = require('node:test'); const assert = require('node:assert'); const http = require('node:http'); -// buildHeaders was removed from metacom; stub it so Balancer can be constructed const metacom = require('metacom'); if (typeof metacom.buildHeaders !== 'function') { metacom.buildHeaders = (cors = {}) => ({ - 'Access-Control-Allow-Origin': cors.origin || '*', + 'Access-Control-Allow-Origin': cors.origin ?? '*', 'Access-Control-Allow-Headers': 'Content-Type', }); } diff --git a/test/bus.js b/test/bus.js index 26427868e..0c86fcd63 100644 --- a/test/bus.js +++ b/test/bus.js @@ -3,6 +3,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); const path = require('node:path'); + const { Code } = require('../lib/code.js'); const root = process.cwd(); @@ -25,15 +26,14 @@ test('lib/bus - should load bus correctly', async () => { assert.deepStrictEqual(bus.tree, {}); await bus.load(); - assert.deepStrictEqual(Object.keys(bus.tree), [ - 'fakerapi', - 'math', - 'worldTime', - ]); + const expected = ['fakerapi', 'math', 'worldTime']; + assert.deepStrictEqual(Object.keys(bus.tree), expected); assert.strictEqual(bus.tree.math.parent, bus.tree); assert.strictEqual(typeof bus.tree.math, 'object'); assert.strictEqual(typeof bus.tree.math.eval, 'function'); - assert.strictEqual(bus.tree.math.eval.constructor.name, 'AsyncFunction'); + const evalType = bus.tree.math.eval.constructor.name; + assert.strictEqual(evalType, 'AsyncFunction'); assert.strictEqual(typeof bus.tree.math['.service'], 'function'); - assert.strictEqual(bus.tree.math['.service'].url, 'https://api.mathjs.org'); + const mathUrl = bus.tree.math['.service'].url; + assert.strictEqual(mathUrl, 'https://api.mathjs.org'); }); diff --git a/test/cache.js b/test/cache.js index 9358ff846..28052bab3 100644 --- a/test/cache.js +++ b/test/cache.js @@ -3,6 +3,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); const path = require('node:path'); + const { Place } = require('../lib/place.js'); const root = process.cwd(); diff --git a/test/cert.js b/test/cert.js index 42e10fb1c..b2d7d15df 100644 --- a/test/cert.js +++ b/test/cert.js @@ -5,6 +5,7 @@ const assert = require('node:assert'); const fs = require('node:fs'); const path = require('node:path'); const cp = require('node:child_process'); + const { Cert } = require('../lib/cert.js'); const WIN = process.platform === 'win32'; @@ -33,7 +34,9 @@ test('lib/cert - should load certificates correctly', async () => { assert.strictEqual(cert.files.size, 3); assert.strictEqual(cert.domains.size, 5); - fs.copyFileSync(`${certPath}self.pem`, `${certPath}key.pem`); + const selfPem = path.join(certPath, 'self.pem'); + const keyPem = path.join(certPath, 'key.pem'); + fs.copyFileSync(selfPem, keyPem); cert = new Cert('cert', application, { ext: ['pem'] }); await cert.load(); assert.strictEqual(cert.files.size, 3); diff --git a/test/code.js b/test/code.js index 9dc4e4ac4..c31cb7fa0 100644 --- a/test/code.js +++ b/test/code.js @@ -3,6 +3,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); const path = require('node:path'); + const { Code } = require('../lib/code.js'); const root = process.cwd(); @@ -25,7 +26,8 @@ test('lib/code - should load code correctly', async () => { assert.deepStrictEqual(code.tree, {}); await code.load(); - assert.deepStrictEqual(Object.keys(code.tree), ['example', 'utils']); + const expected = ['example', 'utils']; + assert.deepStrictEqual(Object.keys(code.tree), expected); assert.strictEqual(code.tree.example.parent, code.tree); assert.strictEqual(typeof code.tree.example.add, 'object'); assert.strictEqual(typeof code.tree.example.doSomething, 'function'); diff --git a/test/deps.js b/test/deps.js index 6cc6777ec..7f23bd703 100644 --- a/test/deps.js +++ b/test/deps.js @@ -2,6 +2,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); + const deps = require('../lib/deps.js'); const { node, npm, metarhia } = deps; diff --git a/test/lib/example/start.js b/test/lib/example/start.js index 3ba9e1669..7e53e52cd 100644 --- a/test/lib/example/start.js +++ b/test/lib/example/start.js @@ -1,8 +1,8 @@ async () => { - if (application.worker.id === 'W1') { - console.debug('Start example plugin'); - this.parent.cache.set({ key: 'keyName', val: 'value' }); - const res = lib.example.cache.get({ key: 'keyName' }); - console.debug({ res, cache: this.parent.cache.values }); - } + const isPrimary = application.worker.id === 'W1'; + if (!isPrimary) return; + console.debug('Start example plugin'); + this.parent.cache.set({ key: 'keyName', val: 'value' }); + const res = lib.example.cache.get({ key: 'keyName' }); + console.debug({ res, cache: this.parent.cache.values }); }; diff --git a/test/planner.js b/test/planner.js index 705202443..69551c33f 100644 --- a/test/planner.js +++ b/test/planner.js @@ -5,6 +5,7 @@ const assert = require('node:assert'); const os = require('node:os'); const path = require('node:path'); const fsp = require('node:fs').promises; + const { Planner } = require('../lib/planner.js'); const mockConsole = { @@ -129,7 +130,6 @@ test('lib/planner - should restore tasks from persisted files', async () => { run: 'lib.job', }); assert.ok(id.length > 0); - // Clear timers without deleting files so planner2 can restore them for (const task of planner1.tasks.values()) { if (task.timer) { clearTimeout(task.timer); diff --git a/test/procedure.js b/test/procedure.js index cf5856070..00d50205b 100644 --- a/test/procedure.js +++ b/test/procedure.js @@ -2,6 +2,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); + const metautil = require('metautil'); const { Procedure } = require('../lib/procedure.js'); @@ -177,7 +178,8 @@ test('lib/procedure - should handle queue correctly', async () => { try { result = await proc.invoke({}, args); } catch { - throw new Error('Procedure.invoke failed. Check your script.method'); + const msg = 'Procedure.invoke failed. Check your script.method'; + throw new Error(msg); } proc.leave(); return result; diff --git a/test/schemas.js b/test/schemas.js index 9c322d76f..f982257d6 100644 --- a/test/schemas.js +++ b/test/schemas.js @@ -2,6 +2,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); + const { loadSchema } = require('metaschema'); const { createContext } = require('metavm'); const { Config } = require('metaconfiguration'); diff --git a/test/static.js b/test/static.js index 0d9458bfa..7d25bc065 100644 --- a/test/static.js +++ b/test/static.js @@ -4,6 +4,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); const zlib = require('node:zlib'); const path = require('node:path'); + const { Static } = require('../lib/static.js'); const root = process.cwd(); @@ -16,80 +17,51 @@ const application = { }, }; -test('lib/static load - should load static files correctly', async () => { - const cache = new Static('lib', application); +const assertEmptyCache = (cache) => { assert.strictEqual(cache.files instanceof Map, true); assert.strictEqual(cache.files.size, 0); assert.strictEqual(cache.ext, undefined); assert.strictEqual(cache.maxFileSize, -1); assert.strictEqual(cache.get('/example/add.js'), undefined); +}; +const assertLoadedFile = async (cache, expectedLength) => { await cache.load(); assert.strictEqual(cache.files.size, 13); const file = cache.get('/example/add.js'); assert.strictEqual(file.data instanceof Buffer, true); - assert.strictEqual(file.data.length, 158); + assert.strictEqual(file.data.length, expectedLength); assert.strictEqual(cache.get('/example/unknown.js'), undefined); assert.strictEqual(cache.ext, undefined); assert.strictEqual(cache.maxFileSize, 10000000); +}; + +test('lib/static load - should load static files correctly', async () => { + const cache = new Static('lib', application); + assertEmptyCache(cache); + await assertLoadedFile(cache, 158); }); test('lib/static load - should compress correctly by gzip', async () => { const cache = new Static('lib', application, { compressType: 'gzip' }); - assert.strictEqual(cache.files instanceof Map, true); - assert.strictEqual(cache.files.size, 0); - assert.strictEqual(cache.ext, undefined); - assert.strictEqual(cache.maxFileSize, -1); - assert.strictEqual(cache.get('/example/add.js'), undefined); - - await cache.load(); - assert.strictEqual(cache.files.size, 13); - const file = cache.get('/example/add.js'); - assert.strictEqual(file.data instanceof Buffer, true); - assert.strictEqual(file.data.length, 116); - assert.strictEqual(cache.get('/example/unknown.js'), undefined); - assert.strictEqual(cache.ext, undefined); - assert.strictEqual(cache.maxFileSize, 10000000); + assertEmptyCache(cache); + await assertLoadedFile(cache, 116); }); test('lib/static load - should compress correctly by deflate', async () => { const cache = new Static('lib', application, { compressType: 'deflate', }); - assert.strictEqual(cache.files instanceof Map, true); - assert.strictEqual(cache.files.size, 0); - assert.strictEqual(cache.ext, undefined); - assert.strictEqual(cache.maxFileSize, -1); - assert.strictEqual(cache.get('/example/add.js'), undefined); - - await cache.load(); - assert.strictEqual(cache.files.size, 13); - const file = cache.get('/example/add.js'); - assert.strictEqual(file.data instanceof Buffer, true); - assert.strictEqual(file.data.length, 104); - assert.strictEqual(cache.get('/example/unknown.js'), undefined); - assert.strictEqual(cache.ext, undefined); - assert.strictEqual(cache.maxFileSize, 10000000); + assertEmptyCache(cache); + await assertLoadedFile(cache, 104); }); test('lib/static load - should compress correctly by brotli', async () => { const cache = new Static('lib', application, { compressType: 'br', }); - assert.strictEqual(cache.files instanceof Map, true); - assert.strictEqual(cache.files.size, 0); - assert.strictEqual(cache.ext, undefined); - assert.strictEqual(cache.maxFileSize, -1); - assert.strictEqual(cache.get('/example/add.js'), undefined); - - await cache.load(); - assert.strictEqual(cache.files.size, 13); - const file = cache.get('/example/add.js'); - assert.strictEqual(file.data instanceof Buffer, true); - assert.strictEqual(file.data.length, 100); - assert.strictEqual(cache.get('/example/unknown.js'), undefined); - assert.strictEqual(cache.ext, undefined); - assert.strictEqual(cache.maxFileSize, 10000000); + assertEmptyCache(cache); + await assertLoadedFile(cache, 100); }); if (zlib.zstdCompress) { @@ -97,20 +69,8 @@ if (zlib.zstdCompress) { const cache = new Static('lib', application, { compressType: 'zstd', }); - assert.strictEqual(cache.files instanceof Map, true); - assert.strictEqual(cache.files.size, 0); - assert.strictEqual(cache.ext, undefined); - assert.strictEqual(cache.maxFileSize, -1); - assert.strictEqual(cache.get('/example/add.js'), undefined); - - await cache.load(); - assert.strictEqual(cache.files.size, 13); - const file = cache.get('/example/add.js'); - assert.strictEqual(file.data instanceof Buffer, true); - assert.strictEqual(file.data.length, 109); - assert.strictEqual(cache.get('/example/unknown.js'), undefined); - assert.strictEqual(cache.ext, undefined); - assert.strictEqual(cache.maxFileSize, 10000000); + assertEmptyCache(cache); + await assertLoadedFile(cache, 109); }); } diff --git a/types/core.d.ts b/types/core.d.ts index 0cc8ea4f4..aff2d6194 100644 --- a/types/core.d.ts +++ b/types/core.d.ts @@ -1,5 +1,4 @@ import { EventEmitter } from 'node:events'; -import { IncomingMessage, ServerResponse } from 'node:http'; export * from './procedure'; @@ -22,16 +21,22 @@ export interface InvokeTarget { exclusive?: boolean; } +export interface StaticFile { + data: Buffer | null; + stat: object | null; +} + +export interface StaticFindResult extends StaticFile { + code: number; +} + export interface Static { name: string; path: string; - files: Map; + files: Map; get(name: string): unknown; compress(filePath: string): Promise; - find( - path: string, - code?: number, - ): { data: Buffer | null; stat: object | null; code: number }; + find(path: string, code?: number): StaticFindResult; serve(url: string, transport: object): Promise; load(targetPath?: string): Promise; delete(filePath: string): void; diff --git a/types/impress.d.ts b/types/impress.d.ts index 06fbe75cd..fdc52ed8b 100644 --- a/types/impress.d.ts +++ b/types/impress.d.ts @@ -1,12 +1,3 @@ -import { - LogConfig, - ScaleConfig, - ServerConfig, - SessionsConfig, - CacheConfig, -} from './config'; -import { Application, Context, Client } from './core'; - import * as _util from 'node:util'; import * as _buffer from 'node:buffer'; import * as _cp from 'node:child_process'; @@ -37,8 +28,15 @@ import * as _https from 'node:https'; import * as _http2 from 'node:http2'; import * as _dgram from 'node:dgram'; +import { + LogConfig, + ScaleConfig, + ServerConfig, + SessionsConfig, + CacheConfig, +} from './config'; +import { Application, Context } from './core'; import * as _ws from 'ws'; - import * as _config from 'metaconfiguration'; import * as _metautil from 'metautil'; import * as _metavm from 'metavm';