{"version":3,"file":"postgres.cjs","names":["ms: number","pool: pg.Pool","err: Error","client: pg.PoolClient","databaseUrl: string","runsOnServer"],"sources":["../src/postgres.ts"],"sourcesContent":["import { runsOnServer } from \"@settlemint/sdk-utils/runtime\";\nimport pg from \"pg\";\n\n/**\n * Type definition extending the pg.Pool interface to include custom permanent-failure event\n */\ndeclare module \"pg\" {\n  interface Pool {\n    on(event: \"permanent-failure\", listener: (err: Error) => void): this;\n    emit(event: \"permanent-failure\", err: Error): boolean;\n  }\n}\n\n/**\n * Utility function to pause execution for a specified duration\n *\n * @param ms - The number of milliseconds to sleep\n * @returns A promise that resolves after the specified duration\n */\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Configures error handling and recovery mechanisms for a PostgreSQL connection pool\n *\n * @param pool - The PostgreSQL connection pool to configure\n */\nfunction setupErrorHandling(pool: pg.Pool) {\n  let retryCount = 0;\n  let isRetrying = false;\n  const clientErrorHandlers = new WeakSet<pg.PoolClient>();\n\n  const handlePoolError = async (err: Error) => {\n    console.error(\"[Drizzle] Pool error occurred:\", err);\n\n    // Prevent concurrent retry attempts\n    if (isRetrying) {\n      console.log(\"[Drizzle] Recovery already in progress, skipping\");\n      return;\n    }\n\n    if (retryCount < 3) {\n      isRetrying = true;\n      retryCount++;\n      console.log(`[Drizzle] Attempting to recover - retry ${retryCount}/3`);\n\n      try {\n        const client = await pool.connect();\n        try {\n          // Test the connection with timeout\n          await Promise.race([\n            client.query(\"SELECT 1\"),\n            new Promise((_, reject) => setTimeout(() => reject(new Error(\"Query timeout\")), 5000)),\n          ]);\n          console.log(\"[Drizzle] Successfully recovered connection\");\n          retryCount = 0;\n        } finally {\n          client.release();\n        }\n      } catch (retryError) {\n        console.error(`[Drizzle] Recovery attempt ${retryCount} failed:`, retryError);\n        await sleep(5000 * 2 ** (retryCount - 1));\n      } finally {\n        isRetrying = false;\n      }\n    } else {\n      console.error(\"[Drizzle] Max retries exceeded - pool is in an error state\");\n      pool.emit(\"permanent-failure\", err);\n    }\n  };\n\n  const handleConnect = (client: pg.PoolClient) => {\n    // Only add error handler if not already added (prevent memory leaks)\n    if (!clientErrorHandlers.has(client)) {\n      clientErrorHandlers.add(client);\n      client.on(\"error\", (err: Error) => {\n        console.error(\"[Drizzle] Database client error:\", err);\n      });\n    }\n    retryCount = 0;\n    isRetrying = false;\n  };\n\n  pool.on(\"error\", handlePoolError);\n  pool.on(\"connect\", handleConnect);\n}\n\n/**\n * Creates a PostgreSQL connection pool with error handling and retry mechanisms\n *\n * @param databaseUrl - The PostgreSQL connection URL\n * @returns A configured PostgreSQL connection pool\n * @throws Will throw an error if called from browser runtime\n * @example\n * import { createPostgresPool } from '@settlemint/sdk-hasura';\n *\n * const pool = createPostgresPool(process.env.SETTLEMINT_HASURA_DATABASE_URL);\n *\n * // The pool will automatically handle connection errors and retries\n * const client = await pool.connect();\n * try {\n *   const result = await client.query('SELECT NOW()');\n *   console.log(result.rows[0]);\n * } finally {\n *   client.release();\n * }\n */\nexport function createPostgresPool(databaseUrl: string) {\n  if (!databaseUrl?.trim()) {\n    throw new Error(\"Database URL is required\");\n  }\n\n  if (!runsOnServer) {\n    throw new Error(\"Drizzle client can only be created on the server side\");\n  }\n\n  const pool = new pg.Pool({\n    connectionString: databaseUrl,\n    max: 20,\n    idleTimeoutMillis: 30000,\n    connectionTimeoutMillis: 5000,\n  });\n\n  setupErrorHandling(pool);\n\n  return pool;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,QAAQ,CAACA,OAAe,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,GAAG;;;;;;AAO9E,SAAS,mBAAmBC,MAAe;CACzC,IAAI,aAAa;CACjB,IAAI,aAAa;CACjB,MAAM,sBAAsB,IAAI;CAEhC,MAAM,kBAAkB,OAAOC,QAAe;AAC5C,UAAQ,MAAM,kCAAkC,IAAI;AAGpD,MAAI,YAAY;AACd,WAAQ,IAAI,mDAAmD;AA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