{"version":3,"file":"knex-log.mjs","sources":["../../src/utils/knex-log.ts"],"sourcesContent":["import type { Knex } from 'knex';\n\nimport { createThrottle } from './throttle';\n\n/** knex 3.3 logs this, with a stack, on every failed connection acquire. */\nexport const KNEX_ACQUIRE_ERROR_PREFIX = 'Acquire connection error:';\n\nconst KNEX_WARNING_INTERVAL_MS = 30_000;\n\ninterface WarnLogger {\n  warn(message: string): void;\n}\n\nexport interface KnexWarnOptions {\n  intervalMs?: number;\n  now?: () => number;\n}\n\n/**\n * During pool exhaustion knex warns once per waiting query. Keep the first acquire warning and at\n * most one per interval after it; pass every other knex warning through.\n */\nexport const createKnexWarn = (\n  logger: WarnLogger,\n  { intervalMs = KNEX_WARNING_INTERVAL_MS, now }: KnexWarnOptions = {}\n) => {\n  const acquireErrors = createThrottle({ intervalMs, now });\n\n  return (message: unknown) => {\n    try {\n      const text = typeof message === 'string' ? message : String(message);\n\n      if (!text.startsWith(KNEX_ACQUIRE_ERROR_PREFIX)) {\n        logger.warn(`[database] knex: ${text}`);\n        return;\n      }\n\n      const { emit, suppressed } = acquireErrors.take();\n      if (!emit) {\n        return;\n      }\n\n      const held =\n        suppressed > 0\n          ? `\\n  - acquire connection errors not logged since the previous one: ${suppressed}`\n          : '';\n      logger.warn(`[database] knex: ${text}${held}`);\n    } catch {\n      // knex calls this from inside a catch block, right before it throws the error the caller\n      // needs to see. A failing logger (custom logger, broken transport) must not replace that error.\n    }\n  };\n};\n\n/** Route knex's warnings through the Strapi logger unless the project configured its own. */\nexport const withStrapiKnexLog = (\n  config: Knex.Config,\n  logger: WarnLogger,\n  options?: KnexWarnOptions\n): Knex.Config => {\n  const projectLog = config.log ?? {};\n\n  if (typeof projectLog.warn === 'function') {\n    return config;\n  }\n\n  return { ...config, log: { ...projectLog, warn: createKnexWarn(logger, options) } };\n};\n"],"names":["KNEX_ACQUIRE_ERROR_PREFIX","KNEX_WARNING_INTERVAL_MS","createKnexWarn","logger","intervalMs","now","acquireErrors","createThrottle","message","text","String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