@nmakarov/cli-toolkit 0.23.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/db.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/db/index.js","../src/errors.js"],"sourcesContent":["import knex from \"knex\";\nimport { ParamError } from \"../errors.js\";\n\nconst KNEX_DEFAULTS = {\n testConnection: true,\n pool: { min: 2, max: 10 },\n acquireConnectionTimeout: 10000,\n ssl: { rejectUnauthorized: false },\n};\n\nexport class Db {\n static async init(context, options = {}) {\n const defs = {\n dbName: \"string\",\n dbConnectionString: \"string\",\n dbProfile: \"boolean default false\",\n };\n const discovered = context?.params?.getAllForModule?.(\"db\", defs) ?? {};\n const merged = { ...discovered, ...options };\n\n let { dbName, dbConnectionString } = merged;\n const { dbProfile } = merged;\n\n if (!dbName && !dbConnectionString) {\n dbName = \"local\";\n }\n\n if (dbName && /^(postgresql|mysql):\\/\\//.test(dbName)) {\n dbConnectionString = dbName;\n dbName = undefined;\n }\n\n if (dbName && !dbConnectionString) {\n const paramName = `dbConnectionString${capitalizeFirstLetter(dbName)}`;\n dbConnectionString = await context.params.get(paramName, \"string\");\n if (!dbConnectionString) {\n throw new ParamError(\n `Db: cannot find dbConnectionString for dbName=\"${dbName}\" (looked for param \"${paramName}\")`\n );\n }\n }\n\n const config = {\n ...KNEX_DEFAULTS,\n connectionString: dbConnectionString,\n name: dbName || merged.name || \"default\",\n profile: !!dbProfile,\n logger: context.logger,\n };\n\n return dbConnect(context, config);\n }\n\n constructor(config) {\n if (!config || !config.connectionString) {\n throw new ParamError(\"Db: connectionString is required\");\n }\n\n this.knexInstance = null;\n this.isConnected = false;\n this.queriesLog = [];\n\n this.config = {\n testConnection: true,\n profile: false,\n pool: { min: 2, max: 10 },\n acquireConnectionTimeout: 10000,\n ssl: { rejectUnauthorized: false },\n logger: console,\n name: \"default\",\n ...config,\n };\n\n this.logger = this.config.logger;\n\n const instance = this;\n const callableWrapper = function () {\n throw new Error(\"This should never be called directly\");\n };\n callableWrapper._instance = instance;\n\n return new Proxy(callableWrapper, {\n apply: (target, _thisArg, argumentsList) => {\n const inst = target._instance;\n if (!inst.knexInstance) {\n throw new Error(\"Db: Not connected. Call connect() first.\");\n }\n return inst.knexInstance(...argumentsList);\n },\n get: (target, prop) => {\n if (prop === \"_instance\") {\n return target._instance;\n }\n\n const inst = target._instance;\n\n const ownMethods = [\n \"connect\",\n \"disconnect\",\n \"testConnection\",\n \"tableExists\",\n \"getQueryLog\",\n \"getKnex\",\n \"isConnectedToDb\",\n \"getErrorMessage\",\n \"detectClient\",\n \"attachProfiler\",\n ];\n\n if (prop in inst) {\n const value = inst[prop];\n if (typeof value === \"function\" && ownMethods.includes(prop)) {\n return value.bind(inst);\n }\n if (typeof value !== \"function\") {\n return value;\n }\n }\n\n if (inst.knexInstance) {\n const knexProp = inst.knexInstance[prop];\n if (typeof knexProp === \"function\") {\n return knexProp.bind(inst.knexInstance);\n }\n return knexProp;\n }\n\n if (prop in inst) {\n const method = inst[prop];\n if (typeof method === \"function\") {\n return method.bind(inst);\n }\n return method;\n }\n\n return undefined;\n },\n });\n }\n\n detectClient(connectionString) {\n if (connectionString.match(/^postgresql/)) {\n return \"pg\";\n }\n if (connectionString.match(/^mysql/)) {\n return \"mysql2\";\n }\n return null;\n }\n\n async connect() {\n if (this.isConnected && this.knexInstance) {\n this.logger.warn?.(\"[Db] Already connected\");\n return;\n }\n\n const client = this.detectClient(this.config.connectionString);\n if (!client) {\n throw new ParamError(\n \"Db: Cannot determine client type from connection string. Expected postgresql:// or mysql://\"\n );\n }\n\n try {\n const connectionConfig = {\n connectionString: this.config.connectionString,\n family: 4,\n };\n\n this.knexInstance = knex({\n client,\n connection: connectionConfig,\n pool: this.config.pool,\n acquireConnectionTimeout: this.config.acquireConnectionTimeout,\n ...(this.config.ssl && { ssl: this.config.ssl }),\n });\n\n if (this.config.profile) {\n this.attachProfiler();\n }\n\n if (this.config.testConnection) {\n await this.testConnection();\n }\n\n this.isConnected = true;\n this.logger.debug?.(\n `[Db] Connected to database \"${this.config.name || this.config.connectionString}\"`\n );\n } catch (error) {\n if (error instanceof ParamError) {\n throw error;\n }\n const errorMsg = this.getErrorMessage(error);\n throw new ParamError(`Db: Connection failed - ${errorMsg}`);\n }\n }\n\n async disconnect() {\n if (!this.knexInstance) {\n return;\n }\n\n try {\n await this.knexInstance.destroy();\n this.knexInstance = null;\n this.isConnected = false;\n this.queriesLog = [];\n this.logger.debug?.(\n `[Db] Disconnected from database \"${this.config.name || this.config.connectionString}\"`\n );\n } catch (error) {\n const errorMsg = this.getErrorMessage(error);\n this.logger.error?.(`[Db] Error disconnecting: ${errorMsg}`);\n throw error;\n }\n }\n\n getErrorMessage(error) {\n if (error instanceof AggregateError) {\n const errors = error.errors || [];\n\n if (errors.length > 0) {\n const firstError = errors[0];\n const firstErrorMsg =\n firstError instanceof Error ? firstError.message : String(firstError);\n\n const allSimilar = errors.every((e) => {\n const msg = e instanceof Error ? e.message : String(e);\n const codeMatch = msg.match(/^(\\w+)\\s/);\n const firstCodeMatch = firstErrorMsg.match(/^(\\w+)\\s/);\n return codeMatch && firstCodeMatch && codeMatch[1] === firstCodeMatch[1];\n });\n\n if (allSimilar && errors.length > 1) {\n const addresses = errors\n .map((e) => {\n const msg = e instanceof Error ? e.message : String(e);\n const addrMatch = msg.match(/([:\\d.]+:\\d+)/);\n return addrMatch ? addrMatch[1] : null;\n })\n .filter(Boolean);\n\n if (addresses.length > 0) {\n const codeMatch = firstErrorMsg.match(/^(\\w+)\\s/);\n const code = codeMatch ? codeMatch[1] : \"Connection error\";\n return `${code} (tried: ${addresses.join(\", \")})`;\n }\n }\n\n const uniqueMessages = [\n ...new Set(\n errors.map((e) => (e instanceof Error ? e.message : String(e)))\n ),\n ];\n\n if (uniqueMessages.length === 1) {\n return uniqueMessages[0];\n }\n\n return uniqueMessages.join(\"; \");\n }\n\n return error.message || \"Multiple errors occurred\";\n }\n\n if (error instanceof Error) {\n const code = error.code;\n if (code) {\n return `${code}: ${error.message || String(error)}`;\n }\n return error.message || String(error);\n }\n\n if (typeof error === \"string\") {\n return error;\n }\n\n if (error && typeof error === \"object\" && \"message\" in error) {\n const msg = String(error.message);\n const code = error.code;\n if (code) {\n return `${code}: ${msg}`;\n }\n return msg;\n }\n\n return String(error) || \"Unknown error\";\n }\n\n async testConnection() {\n if (!this.knexInstance) {\n throw new Error(\"Db: Not connected. Call connect() first.\");\n }\n\n try {\n const result = await this.knexInstance.raw(\"SELECT 2+3 AS result\");\n const isOk = result.rows?.[0]?.result === 5 || result[0]?.[0]?.result === 5;\n this.logger.debug?.(`[Db] Connection test: ${isOk ? \"OK\" : \"FAILED\"}`);\n return isOk;\n } catch (error) {\n const errorMsg = this.getErrorMessage(error);\n this.logger.error?.(`[Db] Connection test failed: ${errorMsg}`);\n throw new ParamError(`Db: Connection test failed - ${errorMsg}`);\n }\n }\n\n attachProfiler() {\n if (!this.knexInstance) {\n return;\n }\n\n this.queriesLog = [];\n this.knexInstance.queriesLog = this.queriesLog;\n\n this.knexInstance.on(\"query\", (query) => {\n query.__startTime = process.hrtime();\n });\n\n this.knexInstance.on(\"query-response\", (_response, query) => {\n const [seconds, nanoseconds] = process.hrtime(query.__startTime);\n const executionTimeMs = (seconds * 1000 + nanoseconds / 1e6).toFixed(2);\n\n const logEntry = {\n sql: query.sql,\n bindings: query.bindings || [],\n executionTimeMs,\n };\n\n this.queriesLog.push(logEntry);\n this.logger.debug?.(`[Db] Query: ${query.sql} | Duration: ${executionTimeMs}ms`);\n });\n\n this.knexInstance.on(\"query-error\", (error, query) => {\n this.logger.error?.(`[Db] Query failed: ${query.sql}`, error);\n });\n }\n\n getQueryLog() {\n return [...this.queriesLog];\n }\n\n async tableExists(tableName) {\n if (!this.knexInstance) {\n throw new Error(\"Db: Not connected. Call connect() first.\");\n }\n\n try {\n return await this.knexInstance.schema.hasTable(tableName);\n } catch (error) {\n this.logger.error?.(`[Db] Error checking table existence: ${error.message}`);\n throw error;\n }\n }\n\n getKnex() {\n if (!this.knexInstance) {\n throw new Error(\"Db: Not connected. Call connect() first.\");\n }\n return this.knexInstance;\n }\n\n isConnectedToDb() {\n return this.isConnected && this.knexInstance !== null;\n }\n}\n\nfunction capitalizeFirstLetter(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nasync function dbConnect(context, config) {\n try {\n const db = new Db(config);\n\n context.registerCleanup(async () => {\n await db.disconnect();\n context.logger.debug?.(`[Db] instance \"${config.name}\" disconnected`);\n });\n\n await db.connect();\n\n context.logger.debug?.(`[Db] instance \"${config.name}\" initialized`);\n\n return db;\n } catch (error) {\n if (error instanceof ParamError) {\n throw error;\n }\n const errorMsg = error instanceof Error ? error.message : String(error);\n throw new ParamError(`[Db] connect error: ${errorMsg}`);\n }\n}\n","/**\n * Error classes for the CLI toolkit\n */\n\nexport class FrameworkError extends Error {\n constructor(message) {\n super(message);\n this.name = \"FrameworkError\";\n }\n}\n\nexport class ParamError extends FrameworkError {\n constructor(message) {\n super(message);\n this.name = \"ParamError\";\n }\n}\n\nexport class InitError extends FrameworkError {\n constructor(message) {\n super(message);\n this.name = \"InitError\";\n }\n}\n\nexport class CriticalRequestError extends FrameworkError {\n constructor(message) {\n super(message);\n this.name = \"CriticalRequestError\";\n }\n}\n\nexport class ControlFlowError extends Error {\n constructor(message) {\n super(message);\n this.name = \"ControlFlowError\";\n }\n}\n\nexport class HttpClientError extends FrameworkError {\n constructor(message, cause) {\n super(message);this.cause = cause;;\n this.name = \"HttpClientError\";\n }\n}\n\nexport class FileDatabaseError extends FrameworkError {\n constructor(message) {\n super(message);\n this.name = \"FileDatabaseError\";\n }\n}\n\n"],"mappings":";AAAA,OAAO,UAAU;;;ACIV,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACtC,YAAY,SAAS;AACjB,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EAChB;AACJ;AAEO,IAAM,aAAN,cAAyB,eAAe;AAAA,E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AAM,0CAA0C;AAAA,IAC9D;AAEA,QAAI;AACA,aAAO,MAAM,KAAK,aAAa,OAAO,SAAS,SAAS;AAAA,IAC5D,SAAS,OAAO;AACZ,WAAK,OAAO,QAAQ,wCAAwC,MAAM,OAAO,EAAE;AAC3E,YAAM;AAAA,IACV;AAAA,EACJ;AAAA,EAEA,UAAU;AACN,QAAI,CAAC,KAAK,cAAc;AACpB,YAAM,IAAI,MAAM,0CAA0C;AAAA,IAC9D;AACA,WAAO,KAAK;AAAA,EAChB;AAAA,EAEA,kBAAkB;AACd,WAAO,KAAK,eAAe,KAAK,iBAAiB;AAAA,EACrD;AACJ;AAEA,SAAS,sBAAsB,KAAK;AAChC,SAAO,IAAI,OAAO,CAAC,EAAE,YAAY,IAAI,IAAI,MAAM,CAAC;AACpD;AAEA,eAAe,UAAU,SAAS,QAAQ;AACtC,MAAI;AACA,UAAM,KAAK,IAAI,GAAG,MAAM;AAExB,YAAQ,gBAAgB,YAAY;AAChC,YAAM,GAAG,WAAW;AACpB,cAAQ,OAAO,QAAQ,kBAAkB,OAAO,IAAI,gBAAgB;AAAA,IACxE,CAAC;AAED,UAAM,GAAG,QAAQ;AAEjB,YAAQ,OAAO,QAAQ,kBAAkB,OAAO,IAAI,eAAe;AAEnE,WAAO;AAAA,EACX,SAAS,OAAO;AACZ,QAAI,iBAAiB,YAAY;AAC7B,YAAM;AAAA,IACV;AACA,UAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACtE,UAAM,IAAI,WAAW,uBAAuB,QAAQ,EAAE;AAAA,EAC1D;AACJ;","names":[]}
1
+ {"version":3,"sources":["../src/db/index.js","../src/errors.js"],"sourcesContent":["import knex from \"knex\";\nimport { ParamError } from \"../errors.js\";\n\nconst KNEX_DEFAULTS = {\n testConnection: true,\n pool: { min: 2, max: 10 },\n acquireConnectionTimeout: 10000,\n ssl: { rejectUnauthorized: false },\n};\n\nexport class Db {\n static async init(context, options = {}) {\n const buildConfig = async () => {\n const defs = {\n dbName: \"string\",\n dbProfile: \"boolean default false\",\n };\n const discovered = context?.params?.getAllForModule?.(\"db\", defs) ?? {};\n const merged = { ...discovered, ...options };\n\n let { dbName, dbProfile } = merged;\n let dbConnectionString = options.dbConnectionString ?? options.connectionString;\n let connectionParam = dbConnectionString ? \"options\" : null;\n\n if (!dbConnectionString) {\n const src = context?.args?.getSource?.(\"dbConnectionString\");\n if (src === \"cli\" || src === \"overrides\" || src === \"config\") {\n dbConnectionString = await context.params.get(\"dbConnectionString\", \"string\");\n connectionParam = \"dbConnectionString\";\n }\n }\n\n if (!dbConnectionString && dbName && /^(postgresql|mysql):\\/\\//.test(dbName)) {\n dbConnectionString = dbName;\n dbName = undefined;\n }\n\n if (!dbConnectionString && dbName) {\n const paramName = `dbConnectionString${capitalizeFirstLetter(dbName)}`;\n dbConnectionString = await context.params.get(paramName, \"string\");\n connectionParam = paramName;\n if (!dbConnectionString) {\n throw new ParamError(\n `Db: cannot find dbConnectionString for dbName=\"${dbName}\" (looked for param \"${paramName}\")`\n );\n }\n }\n\n if (!dbConnectionString) {\n dbConnectionString = await context.params.get(\"dbConnectionString\", \"string\");\n if (dbConnectionString) {\n connectionParam = \"dbConnectionString\";\n }\n }\n\n if (!dbConnectionString) {\n if (!dbName) {\n dbName = \"local\";\n }\n const paramName = `dbConnectionString${capitalizeFirstLetter(dbName)}`;\n dbConnectionString = await context.params.get(paramName, \"string\");\n connectionParam = paramName;\n if (!dbConnectionString) {\n throw new ParamError(\n `Db: cannot find dbConnectionString for dbName=\"${dbName}\" (looked for param \"${paramName}\")`\n );\n }\n }\n\n const displayName = resolveDbDisplayName(\n dbName,\n connectionParam,\n context?.args?.env,\n merged.name\n );\n\n return {\n ...KNEX_DEFAULTS,\n connectionString: dbConnectionString,\n name: displayName,\n profile: !!dbProfile,\n logger: context.logger,\n };\n };\n\n const config = context?.params?.runWithModuleAsync\n ? await context.params.runWithModuleAsync(\"db\", buildConfig)\n : await buildConfig();\n\n return dbConnect(context, config);\n }\n\n constructor(config) {\n if (!config || !config.connectionString) {\n throw new ParamError(\"Db: connectionString is required\");\n }\n\n this.knexInstance = null;\n this.isConnected = false;\n this.queriesLog = [];\n\n this.config = {\n testConnection: true,\n profile: false,\n pool: { min: 2, max: 10 },\n acquireConnectionTimeout: 10000,\n ssl: { rejectUnauthorized: false },\n logger: console,\n ...config,\n };\n\n this.logger = this.config.logger;\n\n const instance = this;\n const callableWrapper = function () {\n throw new Error(\"This should never be called directly\");\n };\n callableWrapper._instance = instance;\n\n return new Proxy(callableWrapper, {\n apply: (target, _thisArg, argumentsList) => {\n const inst = target._instance;\n if (!inst.knexInstance) {\n throw new Error(\"Db: Not connected. Call connect() first.\");\n }\n return inst.knexInstance(...argumentsList);\n },\n get: (target, prop) => {\n if (prop === \"_instance\") {\n return target._instance;\n }\n\n const inst = target._instance;\n\n const ownMethods = [\n \"connect\",\n \"disconnect\",\n \"testConnection\",\n \"tableExists\",\n \"getQueryLog\",\n \"getKnex\",\n \"isConnectedToDb\",\n \"getErrorMessage\",\n \"detectClient\",\n \"attachProfiler\",\n ];\n\n if (prop in inst) {\n const value = inst[prop];\n if (typeof value === \"function\" && ownMethods.includes(prop)) {\n return value.bind(inst);\n }\n if (typeof value !== \"function\") {\n return value;\n }\n }\n\n if (inst.knexInstance) {\n const knexProp = inst.knexInstance[prop];\n if (typeof knexProp === \"function\") {\n return knexProp.bind(inst.knexInstance);\n }\n return knexProp;\n }\n\n if (prop in inst) {\n const method = inst[prop];\n if (typeof method === \"function\") {\n return method.bind(inst);\n }\n return method;\n }\n\n return undefined;\n },\n });\n }\n\n detectClient(connectionString) {\n if (connectionString.match(/^postgresql/)) {\n return \"pg\";\n }\n if (connectionString.match(/^mysql/)) {\n return \"mysql2\";\n }\n return null;\n }\n\n async connect() {\n if (this.isConnected && this.knexInstance) {\n this.logger.warn?.(\"[Db] Already connected\");\n return;\n }\n\n const client = this.detectClient(this.config.connectionString);\n if (!client) {\n throw new ParamError(\n \"Db: Cannot determine client type from connection string. Expected postgresql:// or mysql://\"\n );\n }\n\n try {\n const connectionConfig = {\n connectionString: this.config.connectionString,\n family: 4,\n };\n\n this.knexInstance = knex({\n client,\n connection: connectionConfig,\n pool: this.config.pool,\n acquireConnectionTimeout: this.config.acquireConnectionTimeout,\n ...(this.config.ssl && { ssl: this.config.ssl }),\n });\n\n if (this.config.profile) {\n this.attachProfiler();\n }\n\n if (this.config.testConnection) {\n await this.testConnection();\n }\n\n this.isConnected = true;\n this.logger.debug?.(formatDbConnectMessage(this.config.name, this.config.connectionString));\n } catch (error) {\n if (error instanceof ParamError) {\n throw error;\n }\n const errorMsg = this.getErrorMessage(error);\n throw new ParamError(`Db: Connection failed - ${errorMsg}`);\n }\n }\n\n async disconnect() {\n if (!this.knexInstance) {\n return;\n }\n\n try {\n await this.knexInstance.destroy();\n this.knexInstance = null;\n this.isConnected = false;\n this.queriesLog = [];\n this.logger.debug?.(formatDbDisconnectMessage(this.config.name, this.config.connectionString));\n } catch (error) {\n const errorMsg = this.getErrorMessage(error);\n this.logger.error?.(`[Db] Error disconnecting: ${errorMsg}`);\n throw error;\n }\n }\n\n getErrorMessage(error) {\n if (error instanceof AggregateError) {\n const errors = error.errors || [];\n\n if (errors.length > 0) {\n const firstError = errors[0];\n const firstErrorMsg =\n firstError instanceof Error ? firstError.message : String(firstError);\n\n const allSimilar = errors.every((e) => {\n const msg = e instanceof Error ? e.message : String(e);\n const codeMatch = msg.match(/^(\\w+)\\s/);\n const firstCodeMatch = firstErrorMsg.match(/^(\\w+)\\s/);\n return codeMatch && firstCodeMatch && codeMatch[1] === firstCodeMatch[1];\n });\n\n if (allSimilar && errors.length > 1) {\n const addresses = errors\n .map((e) => {\n const msg = e instanceof Error ? e.message : String(e);\n const addrMatch = msg.match(/([:\\d.]+:\\d+)/);\n return addrMatch ? addrMatch[1] : null;\n })\n .filter(Boolean);\n\n if (addresses.length > 0) {\n const codeMatch = firstErrorMsg.match(/^(\\w+)\\s/);\n const code = codeMatch ? codeMatch[1] : \"Connection error\";\n return `${code} (tried: ${addresses.join(\", \")})`;\n }\n }\n\n const uniqueMessages = [\n ...new Set(\n errors.map((e) => (e instanceof Error ? e.message : String(e)))\n ),\n ];\n\n if (uniqueMessages.length === 1) {\n return uniqueMessages[0];\n }\n\n return uniqueMessages.join(\"; \");\n }\n\n return error.message || \"Multiple errors occurred\";\n }\n\n if (error instanceof Error) {\n const code = error.code;\n if (code) {\n return `${code}: ${error.message || String(error)}`;\n }\n return error.message || String(error);\n }\n\n if (typeof error === \"string\") {\n return error;\n }\n\n if (error && typeof error === \"object\" && \"message\" in error) {\n const msg = String(error.message);\n const code = error.code;\n if (code) {\n return `${code}: ${msg}`;\n }\n return msg;\n }\n\n return String(error) || \"Unknown error\";\n }\n\n async testConnection() {\n if (!this.knexInstance) {\n throw new Error(\"Db: Not connected. Call connect() first.\");\n }\n\n try {\n const result = await this.knexInstance.raw(\"SELECT 2+3 AS result\");\n const isOk = result.rows?.[0]?.result === 5 || result[0]?.[0]?.result === 5;\n this.logger.debug?.(`[Db] Connection test: ${isOk ? \"OK\" : \"FAILED\"}`);\n return isOk;\n } catch (error) {\n const errorMsg = this.getErrorMessage(error);\n this.logger.error?.(`[Db] Connection test failed: ${errorMsg}`);\n throw new ParamError(`Db: Connection test failed - ${errorMsg}`);\n }\n }\n\n attachProfiler() {\n if (!this.knexInstance) {\n return;\n }\n\n this.queriesLog = [];\n this.knexInstance.queriesLog = this.queriesLog;\n\n this.knexInstance.on(\"query\", (query) => {\n query.__startTime = process.hrtime();\n });\n\n this.knexInstance.on(\"query-response\", (_response, query) => {\n const [seconds, nanoseconds] = process.hrtime(query.__startTime);\n const executionTimeMs = (seconds * 1000 + nanoseconds / 1e6).toFixed(2);\n\n const logEntry = {\n sql: query.sql,\n bindings: query.bindings || [],\n executionTimeMs,\n };\n\n this.queriesLog.push(logEntry);\n this.logger.debug?.(`[Db] Query: ${query.sql} | Duration: ${executionTimeMs}ms`);\n });\n\n this.knexInstance.on(\"query-error\", (error, query) => {\n this.logger.error?.(`[Db] Query failed: ${query.sql}`, error);\n });\n }\n\n getQueryLog() {\n return [...this.queriesLog];\n }\n\n async tableExists(tableName) {\n if (!this.knexInstance) {\n throw new Error(\"Db: Not connected. Call connect() first.\");\n }\n\n try {\n return await this.knexInstance.schema.hasTable(tableName);\n } catch (error) {\n this.logger.error?.(`[Db] Error checking table existence: ${error.message}`);\n throw error;\n }\n }\n\n getKnex() {\n if (!this.knexInstance) {\n throw new Error(\"Db: Not connected. Call connect() first.\");\n }\n return this.knexInstance;\n }\n\n isConnectedToDb() {\n return this.isConnected && this.knexInstance !== null;\n }\n}\n\nfunction capitalizeFirstLetter(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nfunction resolveDbDisplayName(dbName, connectionParam, argsEnv, mergedName) {\n if (dbName) {\n return dbName;\n }\n if (mergedName) {\n return mergedName;\n }\n if (\n connectionParam?.startsWith(\"dbConnectionString\") &&\n connectionParam.length > \"dbConnectionString\".length\n ) {\n return connectionParam.slice(\"dbConnectionString\".length).toLowerCase();\n }\n if (connectionParam === \"dbConnectionString\" && argsEnv) {\n return argsEnv;\n }\n return undefined;\n}\n\nfunction formatDbConnectMessage(name, connectionString) {\n const endpointSuffix = formatConnectionEndpointSuffix(connectionString);\n if (name) {\n return `[Db] Connected to database \"${name}\"${endpointSuffix}`;\n }\n return `[Db] Connected${endpointSuffix}`;\n}\n\nfunction formatDbDisconnectMessage(name, connectionString) {\n const endpointSuffix = formatConnectionEndpointSuffix(connectionString);\n if (name) {\n return `[Db] Disconnected from database \"${name}\"${endpointSuffix}`;\n }\n return `[Db] Disconnected${endpointSuffix}`;\n}\n\nfunction formatDbInstanceMessage(action, name) {\n if (name) {\n return `[Db] instance \"${name}\" ${action}`;\n }\n return `[Db] instance ${action}`;\n}\n\nfunction formatConnectionEndpointSuffix(connectionString) {\n const endpoint = formatConnectionEndpoint(connectionString);\n return endpoint ? ` (${endpoint})` : \"\";\n}\n\nfunction formatConnectionEndpoint(connectionString) {\n try {\n const url = new URL(connectionString);\n const host = url.hostname;\n if (!host) {\n return null;\n }\n\n let port = url.port;\n if (!port) {\n if (url.protocol === \"postgresql:\") {\n port = \"5432\";\n } else if (url.protocol === \"mysql:\") {\n port = \"3306\";\n }\n }\n\n return port ? `${host}:${port}` : host;\n } catch {\n return null;\n }\n}\n\nasync function dbConnect(context, config) {\n try {\n const db = new Db(config);\n\n context.registerCleanup(async () => {\n await db.disconnect();\n context.logger.debug?.(formatDbInstanceMessage(\"disconnected\", config.name));\n });\n\n await db.connect();\n\n context.logger.debug?.(formatDbInstanceMessage(\"initialized\", config.name));\n\n return db;\n } catch (error) {\n if (error instanceof ParamError) {\n throw error;\n }\n const errorMsg = error instanceof Error ? error.message : String(error);\n throw new ParamError(`[Db] connect error: ${errorMsg}`);\n }\n}\n","/**\n * Error classes for the CLI toolkit\n */\n\nexport class FrameworkError extends Error {\n constructor(message) {\n super(message);\n this.name = \"FrameworkError\";\n }\n}\n\nexport class ParamError extends FrameworkError {\n constructor(message) {\n super(message);\n this.name = \"ParamError\";\n }\n}\n\nexport class InitError extends FrameworkError {\n constructor(message) {\n super(message);\n this.name = \"InitError\";\n }\n}\n\nexport class CriticalRequestError extends FrameworkError {\n constructor(message) {\n super(message);\n this.name = \"CriticalRequestError\";\n }\n}\n\nexport class ControlFlowError extends Error {\n constructor(message) {\n super(message);\n this.name = \"ControlFlowError\";\n }\n}\n\nexport class HttpClientError extends FrameworkError {\n constructor(message, cause) {\n super(message);this.cause = cause;;\n this.name = \"HttpClientError\";\n }\n}\n\nexport class FileDatabaseError extends FrameworkError {\n constructor(message) {\n super(message);\n this.name = \"FileDatabaseError\";\n }\n}\n\n"],"mappings":";AAAA,OAAO,UAAU;;;ACIV,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACtC,YAAY,SAAS;AACjB,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EAChB;AACJ;AAEO,IAAM,aAAN,cAAyB,eAAe;AAAA,EAC3C,Y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;AAChC,eAAO;AAAA,MACX,WAAW,IAAI,aAAa,UAAU;AAClC,eAAO;AAAA,MACX;AAAA,IACJ;AAEA,WAAO,OAAO,GAAG,IAAI,IAAI,IAAI,KAAK;AAAA,EACtC,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAEA,eAAe,UAAU,SAAS,QAAQ;AACtC,MAAI;AACA,UAAM,KAAK,IAAI,GAAG,MAAM;AAExB,YAAQ,gBAAgB,YAAY;AAChC,YAAM,GAAG,WAAW;AACpB,cAAQ,OAAO,QAAQ,wBAAwB,gBAAgB,OAAO,IAAI,CAAC;AAAA,IAC/E,CAAC;AAED,UAAM,GAAG,QAAQ;AAEjB,YAAQ,OAAO,QAAQ,wBAAwB,eAAe,OAAO,IAAI,CAAC;AAE1E,WAAO;AAAA,EACX,SAAS,OAAO;AACZ,QAAI,iBAAiB,YAAY;AAC7B,YAAM;AAAA,IACV;AACA,UAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACtE,UAAM,IAAI,WAAW,uBAAuB,QAAQ,EAAE;AAAA,EAC1D;AACJ;","names":[]}
package/dist/index.cjs CHANGED
@@ -1810,46 +1810,83 @@ var Params = class _Params {
1810
1810
  paramGetters = [];
1811
1811
  trackedParams = [];
1812
1812
  _currentModule = "script";
1813
- /** Resolved early in constructor so cleanup does not read params lazily */
1814
- _showUsedParams = false;
1813
+ /**
1814
+ * Resolved early in constructor so cleanup does not read params lazily.
1815
+ * One of: false (off) | "end" (print at exit) | "top" (print after init,
1816
+ * via context.showUsedParamsIfNeeded()).
1817
+ */
1818
+ _showUsedParamsMode = false;
1819
+ /** Guard so the dump prints at most once (top OR end, never both). */
1820
+ _usedParamsPrinted = false;
1815
1821
  constructor(context, options = {}) {
1816
1822
  this.context = context;
1817
1823
  this.args = context.args;
1818
1824
  if (Object.keys(options).length > 0) {
1819
1825
  this.configure(options);
1820
1826
  }
1821
- this._showUsedParams = this.get("showUsedParams", "boolean default false");
1827
+ this._resolveShowUsedParams();
1822
1828
  if (context && typeof context.registerCleanup === "function") {
1823
1829
  context.registerCleanup((ctx) => {
1824
- if (!ctx.params.getShowUsedParams()) return;
1825
- const byModule = ctx.params.getFiguredByModule();
1826
- const modules = Object.keys(byModule).sort();
1827
- if (modules.length === 0) return;
1828
- const logger = ctx.logger;
1829
- logger.debug("[Params]: list of used params:");
1830
- if (typeof logger.highlight !== "function") {
1831
- for (const mod of modules) {
1832
- logger.debug(` [${mod}]`);
1833
- for (const [key, entry] of Object.entries(byModule[mod])) {
1834
- logger.debug(` ${key}: ${JSON.stringify(entry.value)} (${entry.source})`);
1835
- }
1836
- }
1837
- return;
1838
- }
1839
- for (const mod of modules) {
1840
- logger.debug(` [${mod}]`);
1841
- for (const [key, entry] of Object.entries(byModule[mod])) {
1842
- const valueStr = JSON.stringify(entry.value);
1843
- const display = entry.source === "default" ? valueStr : logger.highlight(valueStr);
1844
- logger.debug(` ${key}: ${display} (${entry.source})`);
1845
- }
1846
- }
1830
+ if (!ctx.params.getShowUsedParamsMode()) return;
1831
+ ctx.params.printUsedParams(ctx.logger);
1847
1832
  });
1848
1833
  }
1849
1834
  }
1850
- /** Whether --showUsedParams was requested (resolved in constructor). */
1835
+ /**
1836
+ * Resolve the --showUsedParams mode. The flag is intentionally dual-typed:
1837
+ * (absent) / --no-showUsedParams / =false -> false (off)
1838
+ * --showUsedParams / =true -> "end" (print at exit)
1839
+ * --showUsedParams=top -> "top" (print after init)
1840
+ * Read raw (uncoerced) from args so the string "top" isn't forced to a
1841
+ * boolean, then track it under the "script" module for the dump itself.
1842
+ */
1843
+ _resolveShowUsedParams() {
1844
+ const raw = this.args.get("showUsedParams");
1845
+ const source = this.args.getSource?.("showUsedParams") ?? "default";
1846
+ let mode = false;
1847
+ if (raw === void 0 || raw === null) {
1848
+ mode = false;
1849
+ } else if (typeof raw === "string" && raw.trim().toLowerCase() === "top") {
1850
+ mode = "top";
1851
+ } else {
1852
+ const s = typeof raw === "string" ? raw.trim().toLowerCase() : raw;
1853
+ const falsey = s === false || s === "false" || s === "0" || s === "no" || s === "off";
1854
+ mode = falsey ? false : "end";
1855
+ }
1856
+ this._showUsedParamsMode = mode;
1857
+ this.trackParam("showUsedParams", "string", mode, raw === void 0 ? "default" : source, "script");
1858
+ return mode;
1859
+ }
1860
+ /** Whether --showUsedParams was requested in any mode (truthy = on). */
1851
1861
  getShowUsedParams() {
1852
- return this._showUsedParams;
1862
+ return this._showUsedParamsMode !== false;
1863
+ }
1864
+ /** Resolved mode: false | "end" | "top". */
1865
+ getShowUsedParamsMode() {
1866
+ return this._showUsedParamsMode;
1867
+ }
1868
+ /**
1869
+ * Print the module-grouped list of figured params (the --showUsedParams
1870
+ * dump). Idempotent: only the first call prints, so callers can invoke it
1871
+ * at the top (long-running services) without double-printing at exit.
1872
+ */
1873
+ printUsedParams(logger) {
1874
+ if (this._usedParamsPrinted) return;
1875
+ const byModule = this.getFiguredByModule();
1876
+ const modules = Object.keys(byModule).sort();
1877
+ if (modules.length === 0) return;
1878
+ this._usedParamsPrinted = true;
1879
+ logger = logger ?? this.context?.logger ?? console;
1880
+ const hasHighlight = typeof logger.highlight === "function";
1881
+ logger.debug("[Params]: list of used params:");
1882
+ for (const mod of modules) {
1883
+ logger.debug(` [${mod}]`);
1884
+ for (const [key, entry] of Object.entries(byModule[mod])) {
1885
+ const valueStr = JSON.stringify(entry.value);
1886
+ const display = hasHighlight && entry.source !== "default" ? logger.highlight(valueStr) : valueStr;
1887
+ logger.debug(` ${key}: ${display} (${entry.source})`);
1888
+ }
1889
+ }
1853
1890
  }
1854
1891
  /**
1855
1892
  * Configure parameters
@@ -2117,6 +2154,18 @@ var Params = class _Params {
2117
2154
  this._currentModule = prev;
2118
2155
  }
2119
2156
  }
2157
+ /**
2158
+ * Async variant of {@link runWithModule} for modules that await params.get().
2159
+ */
2160
+ async runWithModuleAsync(moduleName, fn) {
2161
+ const prev = this._currentModule;
2162
+ this._currentModule = moduleName;
2163
+ try {
2164
+ return await fn();
2165
+ } finally {
2166
+ this._currentModule = prev;
2167
+ }
2168
+ }
2120
2169
  /**
2121
2170
  * Infer module name from call stack: first caller outside params/index gives path like .../src/<moduleName>/...
2122
2171
  */
@@ -3380,38 +3429,71 @@ var KNEX_DEFAULTS = {
3380
3429
  };
3381
3430
  var Db = class {
3382
3431
  static async init(context, options = {}) {
3383
- const defs = {
3384
- dbName: "string",
3385
- dbConnectionString: "string",
3386
- dbProfile: "boolean default false"
3387
- };
3388
- const discovered = context?.params?.getAllForModule?.("db", defs) ?? {};
3389
- const merged = { ...discovered, ...options };
3390
- let { dbName, dbConnectionString } = merged;
3391
- const { dbProfile } = merged;
3392
- if (!dbName && !dbConnectionString) {
3393
- dbName = "local";
3394
- }
3395
- if (dbName && /^(postgresql|mysql):\/\//.test(dbName)) {
3396
- dbConnectionString = dbName;
3397
- dbName = void 0;
3398
- }
3399
- if (dbName && !dbConnectionString) {
3400
- const paramName = `dbConnectionString${capitalizeFirstLetter(dbName)}`;
3401
- dbConnectionString = await context.params.get(paramName, "string");
3432
+ const buildConfig = async () => {
3433
+ const defs = {
3434
+ dbName: "string",
3435
+ dbProfile: "boolean default false"
3436
+ };
3437
+ const discovered = context?.params?.getAllForModule?.("db", defs) ?? {};
3438
+ const merged = { ...discovered, ...options };
3439
+ let { dbName, dbProfile } = merged;
3440
+ let dbConnectionString = options.dbConnectionString ?? options.connectionString;
3441
+ let connectionParam = dbConnectionString ? "options" : null;
3402
3442
  if (!dbConnectionString) {
3403
- throw new ParamError(
3404
- `Db: cannot find dbConnectionString for dbName="${dbName}" (looked for param "${paramName}")`
3405
- );
3443
+ const src = context?.args?.getSource?.("dbConnectionString");
3444
+ if (src === "cli" || src === "overrides" || src === "config") {
3445
+ dbConnectionString = await context.params.get("dbConnectionString", "string");
3446
+ connectionParam = "dbConnectionString";
3447
+ }
3406
3448
  }
3407
- }
3408
- const config2 = {
3409
- ...KNEX_DEFAULTS,
3410
- connectionString: dbConnectionString,
3411
- name: dbName || merged.name || "default",
3412
- profile: !!dbProfile,
3413
- logger: context.logger
3449
+ if (!dbConnectionString && dbName && /^(postgresql|mysql):\/\//.test(dbName)) {
3450
+ dbConnectionString = dbName;
3451
+ dbName = void 0;
3452
+ }
3453
+ if (!dbConnectionString && dbName) {
3454
+ const paramName = `dbConnectionString${capitalizeFirstLetter(dbName)}`;
3455
+ dbConnectionString = await context.params.get(paramName, "string");
3456
+ connectionParam = paramName;
3457
+ if (!dbConnectionString) {
3458
+ throw new ParamError(
3459
+ `Db: cannot find dbConnectionString for dbName="${dbName}" (looked for param "${paramName}")`
3460
+ );
3461
+ }
3462
+ }
3463
+ if (!dbConnectionString) {
3464
+ dbConnectionString = await context.params.get("dbConnectionString", "string");
3465
+ if (dbConnectionString) {
3466
+ connectionParam = "dbConnectionString";
3467
+ }
3468
+ }
3469
+ if (!dbConnectionString) {
3470
+ if (!dbName) {
3471
+ dbName = "local";
3472
+ }
3473
+ const paramName = `dbConnectionString${capitalizeFirstLetter(dbName)}`;
3474
+ dbConnectionString = await context.params.get(paramName, "string");
3475
+ connectionParam = paramName;
3476
+ if (!dbConnectionString) {
3477
+ throw new ParamError(
3478
+ `Db: cannot find dbConnectionString for dbName="${dbName}" (looked for param "${paramName}")`
3479
+ );
3480
+ }
3481
+ }
3482
+ const displayName = resolveDbDisplayName(
3483
+ dbName,
3484
+ connectionParam,
3485
+ context?.args?.env,
3486
+ merged.name
3487
+ );
3488
+ return {
3489
+ ...KNEX_DEFAULTS,
3490
+ connectionString: dbConnectionString,
3491
+ name: displayName,
3492
+ profile: !!dbProfile,
3493
+ logger: context.logger
3494
+ };
3414
3495
  };
3496
+ const config2 = context?.params?.runWithModuleAsync ? await context.params.runWithModuleAsync("db", buildConfig) : await buildConfig();
3415
3497
  return dbConnect(context, config2);
3416
3498
  }
3417
3499
  constructor(config2) {
@@ -3428,7 +3510,6 @@ var Db = class {
3428
3510
  acquireConnectionTimeout: 1e4,
3429
3511
  ssl: { rejectUnauthorized: false },
3430
3512
  logger: console,
3431
- name: "default",
3432
3513
  ...config2
3433
3514
  };
3434
3515
  this.logger = this.config.logger;
@@ -3528,9 +3609,7 @@ var Db = class {
3528
3609
  await this.testConnection();
3529
3610
  }
3530
3611
  this.isConnected = true;
3531
- this.logger.debug?.(
3532
- `[Db] Connected to database "${this.config.name || this.config.connectionString}"`
3533
- );
3612
+ this.logger.debug?.(formatDbConnectMessage(this.config.name, this.config.connectionString));
3534
3613
  } catch (error) {
3535
3614
  if (error instanceof ParamError) {
3536
3615
  throw error;
@@ -3548,9 +3627,7 @@ var Db = class {
3548
3627
  this.knexInstance = null;
3549
3628
  this.isConnected = false;
3550
3629
  this.queriesLog = [];
3551
- this.logger.debug?.(
3552
- `[Db] Disconnected from database "${this.config.name || this.config.connectionString}"`
3553
- );
3630
+ this.logger.debug?.(formatDbDisconnectMessage(this.config.name, this.config.connectionString));
3554
3631
  } catch (error) {
3555
3632
  const errorMsg = this.getErrorMessage(error);
3556
3633
  this.logger.error?.(`[Db] Error disconnecting: ${errorMsg}`);
@@ -3679,15 +3756,74 @@ var Db = class {
3679
3756
  function capitalizeFirstLetter(str) {
3680
3757
  return str.charAt(0).toUpperCase() + str.slice(1);
3681
3758
  }
3759
+ function resolveDbDisplayName(dbName, connectionParam, argsEnv, mergedName) {
3760
+ if (dbName) {
3761
+ return dbName;
3762
+ }
3763
+ if (mergedName) {
3764
+ return mergedName;
3765
+ }
3766
+ if (connectionParam?.startsWith("dbConnectionString") && connectionParam.length > "dbConnectionString".length) {
3767
+ return connectionParam.slice("dbConnectionString".length).toLowerCase();
3768
+ }
3769
+ if (connectionParam === "dbConnectionString" && argsEnv) {
3770
+ return argsEnv;
3771
+ }
3772
+ return void 0;
3773
+ }
3774
+ function formatDbConnectMessage(name, connectionString) {
3775
+ const endpointSuffix = formatConnectionEndpointSuffix(connectionString);
3776
+ if (name) {
3777
+ return `[Db] Connected to database "${name}"${endpointSuffix}`;
3778
+ }
3779
+ return `[Db] Connected${endpointSuffix}`;
3780
+ }
3781
+ function formatDbDisconnectMessage(name, connectionString) {
3782
+ const endpointSuffix = formatConnectionEndpointSuffix(connectionString);
3783
+ if (name) {
3784
+ return `[Db] Disconnected from database "${name}"${endpointSuffix}`;
3785
+ }
3786
+ return `[Db] Disconnected${endpointSuffix}`;
3787
+ }
3788
+ function formatDbInstanceMessage(action, name) {
3789
+ if (name) {
3790
+ return `[Db] instance "${name}" ${action}`;
3791
+ }
3792
+ return `[Db] instance ${action}`;
3793
+ }
3794
+ function formatConnectionEndpointSuffix(connectionString) {
3795
+ const endpoint = formatConnectionEndpoint(connectionString);
3796
+ return endpoint ? ` (${endpoint})` : "";
3797
+ }
3798
+ function formatConnectionEndpoint(connectionString) {
3799
+ try {
3800
+ const url = new URL(connectionString);
3801
+ const host = url.hostname;
3802
+ if (!host) {
3803
+ return null;
3804
+ }
3805
+ let port = url.port;
3806
+ if (!port) {
3807
+ if (url.protocol === "postgresql:") {
3808
+ port = "5432";
3809
+ } else if (url.protocol === "mysql:") {
3810
+ port = "3306";
3811
+ }
3812
+ }
3813
+ return port ? `${host}:${port}` : host;
3814
+ } catch {
3815
+ return null;
3816
+ }
3817
+ }
3682
3818
  async function dbConnect(context, config2) {
3683
3819
  try {
3684
3820
  const db = new Db(config2);
3685
3821
  context.registerCleanup(async () => {
3686
3822
  await db.disconnect();
3687
- context.logger.debug?.(`[Db] instance "${config2.name}" disconnected`);
3823
+ context.logger.debug?.(formatDbInstanceMessage("disconnected", config2.name));
3688
3824
  });
3689
3825
  await db.connect();
3690
- context.logger.debug?.(`[Db] instance "${config2.name}" initialized`);
3826
+ context.logger.debug?.(formatDbInstanceMessage("initialized", config2.name));
3691
3827
  return db;
3692
3828
  } catch (error) {
3693
3829
  if (error instanceof ParamError) {
@@ -4286,7 +4422,16 @@ function setup(opts = {}) {
4286
4422
  emitter: partialContext.emitter,
4287
4423
  isStop: partialContext.isStop,
4288
4424
  cleanupFunctions: partialContext.cleanupFunctions,
4289
- registerCleanup: partialContext.registerCleanup
4425
+ registerCleanup: partialContext.registerCleanup,
4426
+ // For long-running scripts (servers): with --showUsedParams=top, print
4427
+ // the used-params list now (after the script has initialized all its
4428
+ // own components), instead of at exit. No-op for the default mode,
4429
+ // which prints at exit via the cleanup registered by Params.
4430
+ showUsedParamsIfNeeded: () => {
4431
+ if (params.getShowUsedParamsMode?.() === "top") {
4432
+ params.printUsedParams(logger);
4433
+ }
4434
+ }
4290
4435
  };
4291
4436
  logger.debug("[setup] completed successfully");
4292
4437
  return context;