@blyp/core 0.1.2 → 0.1.22

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.
Files changed (230) hide show
  1. package/README.md +273 -14
  2. package/STABILITY.md +56 -0
  3. package/dist/ai/anthropic/index.d.ts +3 -0
  4. package/dist/ai/anthropic/normalize.d.ts +9 -0
  5. package/dist/ai/anthropic/stream.d.ts +3 -0
  6. package/dist/ai/anthropic/wrap.d.ts +13 -0
  7. package/dist/ai/anthropic.js +701 -0
  8. package/dist/ai/anthropic.mjs +701 -0
  9. package/dist/ai/fetch.js +701 -0
  10. package/dist/ai/fetch.mjs +701 -0
  11. package/dist/ai/openai/index.d.ts +3 -0
  12. package/dist/ai/openai/normalize.d.ts +10 -0
  13. package/dist/ai/openai/stream.d.ts +3 -0
  14. package/dist/ai/openai/wrap.d.ts +24 -0
  15. package/dist/ai/openai.js +701 -0
  16. package/dist/ai/openai.mjs +701 -0
  17. package/dist/ai/shared/fetch.d.ts +5 -0
  18. package/dist/ai/shared/index.d.ts +2 -0
  19. package/dist/ai/shared/normalize.d.ts +17 -0
  20. package/dist/ai/shared/redaction.d.ts +6 -0
  21. package/dist/ai/shared/stream.d.ts +7 -0
  22. package/dist/ai/shared/trace.d.ts +116 -0
  23. package/dist/ai/shared/types.d.ts +161 -0
  24. package/dist/ai/shared.js +701 -0
  25. package/dist/ai/shared.mjs +701 -0
  26. package/dist/ai/vercel/index.d.ts +3 -0
  27. package/dist/ai/vercel/middleware.d.ts +3 -0
  28. package/dist/ai/vercel/model.d.ts +3 -0
  29. package/dist/ai/vercel.js +701 -0
  30. package/dist/ai/vercel.mjs +701 -0
  31. package/dist/astro.js +701 -0
  32. package/dist/astro.mjs +701 -0
  33. package/dist/client.js +1 -1132
  34. package/dist/client.mjs +1 -1125
  35. package/dist/connectors/betterstack.js +9 -1508
  36. package/dist/connectors/betterstack.mjs +9 -1483
  37. package/dist/connectors/databuddy/index.d.ts +7 -0
  38. package/dist/connectors/databuddy/sender.d.ts +5 -0
  39. package/dist/connectors/databuddy.js +9 -0
  40. package/dist/connectors/databuddy.mjs +9 -0
  41. package/dist/connectors/delivery/backoff.d.ts +2 -0
  42. package/dist/connectors/delivery/manager.d.ts +44 -0
  43. package/dist/connectors/delivery/queue-path.d.ts +1 -0
  44. package/dist/connectors/delivery/sqlite-adapter-bun.d.ts +1 -0
  45. package/dist/connectors/delivery/sqlite-adapter-node.d.ts +1 -0
  46. package/dist/connectors/delivery/sqlite-client.d.ts +37 -0
  47. package/dist/connectors/delivery/sqlite-worker.d.ts +1 -0
  48. package/dist/connectors/delivery/studio-queue.d.ts +12 -0
  49. package/dist/connectors/delivery/types.d.ts +98 -0
  50. package/dist/connectors/otlp/index.d.ts +1 -0
  51. package/dist/connectors/otlp.js +9 -1347
  52. package/dist/connectors/otlp.mjs +9 -1344
  53. package/dist/connectors/posthog/properties.d.ts +4 -0
  54. package/dist/connectors/posthog/sender.d.ts +0 -1
  55. package/dist/connectors/posthog.js +10 -1503
  56. package/dist/connectors/posthog.mjs +10 -1498
  57. package/dist/connectors/sentry.js +9 -1356
  58. package/dist/connectors/sentry.mjs +9 -1333
  59. package/dist/core/config.d.ts +7 -2
  60. package/dist/core/log-record.d.ts +5 -4
  61. package/dist/core/logger.d.ts +5 -0
  62. package/dist/core/optional-module.d.ts +1 -0
  63. package/dist/core/pino-pretty-loader.d.ts +4 -0
  64. package/dist/database.js +1 -24
  65. package/dist/database.mjs +1 -21
  66. package/dist/elysia.js +621 -4100
  67. package/dist/elysia.mjs +622 -4073
  68. package/dist/expo.js +1 -719
  69. package/dist/expo.mjs +1 -717
  70. package/dist/express.js +616 -4085
  71. package/dist/express.mjs +616 -4056
  72. package/dist/fastify.js +618 -4104
  73. package/dist/fastify.mjs +618 -4075
  74. package/dist/frameworks/astro/index.d.ts +2 -0
  75. package/dist/frameworks/astro/logger.d.ts +3 -0
  76. package/dist/frameworks/elysia/index.d.ts +1 -1
  77. package/dist/frameworks/elysia/logger.d.ts +2 -35
  78. package/dist/frameworks/nestjs/helpers.d.ts +2 -0
  79. package/dist/frameworks/nitro/index.d.ts +2 -0
  80. package/dist/frameworks/nitro/logger.d.ts +6 -0
  81. package/dist/frameworks/nuxt/index.d.ts +2 -0
  82. package/dist/frameworks/nuxt/logger.d.ts +3 -0
  83. package/dist/frameworks/react-router/index.d.ts +2 -0
  84. package/dist/frameworks/react-router/logger.d.ts +3 -0
  85. package/dist/frameworks/shared/h3.d.ts +19 -0
  86. package/dist/frameworks/shared/http.d.ts +3 -2
  87. package/dist/frameworks/shared/index.d.ts +2 -1
  88. package/dist/frameworks/shared/logger.d.ts +2 -0
  89. package/dist/frameworks/shared/request-context.d.ts +2 -0
  90. package/dist/frameworks/shared/trace.d.ts +6 -0
  91. package/dist/hono.js +624 -4079
  92. package/dist/hono.mjs +626 -4053
  93. package/dist/index.d.ts +57 -17
  94. package/dist/index.js +616 -6494
  95. package/dist/index.mjs +619 -6410
  96. package/dist/nestjs.js +626 -4574
  97. package/dist/nestjs.mjs +622 -4542
  98. package/dist/nextjs.js +625 -4107
  99. package/dist/nextjs.mjs +627 -4081
  100. package/dist/nitro.js +701 -0
  101. package/dist/nitro.mjs +701 -0
  102. package/dist/nuxt.js +701 -0
  103. package/dist/nuxt.mjs +701 -0
  104. package/dist/react-router.js +701 -0
  105. package/dist/react-router.mjs +701 -0
  106. package/dist/shared/redaction.d.ts +17 -0
  107. package/dist/standalone.js +606 -3258
  108. package/dist/standalone.mjs +611 -3234
  109. package/dist/sveltekit.js +625 -4106
  110. package/dist/sveltekit.mjs +626 -4079
  111. package/dist/tanstack-start.js +624 -4105
  112. package/dist/tanstack-start.mjs +626 -4079
  113. package/dist/types/connectors/databuddy.d.ts +52 -0
  114. package/dist/types/core/config.d.ts +89 -0
  115. package/dist/types/core/logger.d.ts +5 -0
  116. package/dist/types/core/structured-log.d.ts +2 -0
  117. package/dist/types/database.d.ts +1 -0
  118. package/dist/types/frameworks/astro.d.ts +33 -0
  119. package/dist/types/frameworks/client.d.ts +2 -0
  120. package/dist/types/frameworks/elysia.d.ts +2 -0
  121. package/dist/types/frameworks/express.d.ts +1 -0
  122. package/dist/types/frameworks/fastify.d.ts +1 -0
  123. package/dist/types/frameworks/hono.d.ts +1 -0
  124. package/dist/types/frameworks/http.d.ts +1 -0
  125. package/dist/types/frameworks/nestjs.d.ts +2 -0
  126. package/dist/types/frameworks/nextjs.d.ts +1 -0
  127. package/dist/types/frameworks/nitro.d.ts +63 -0
  128. package/dist/types/frameworks/nuxt.d.ts +12 -0
  129. package/dist/types/frameworks/react-router.d.ts +35 -0
  130. package/dist/types/frameworks/request-context.d.ts +1 -0
  131. package/dist/types/frameworks/shared.d.ts +28 -1
  132. package/dist/types/frameworks/standalone.d.ts +3 -2
  133. package/dist/types/frameworks/sveltekit.d.ts +1 -0
  134. package/dist/types/frameworks/tanstack-start.d.ts +9 -3
  135. package/dist/types/frameworks/workers.d.ts +3 -0
  136. package/dist/types/shared/client-log.d.ts +2 -1
  137. package/dist/workers.js +2 -626
  138. package/dist/workers.mjs +2 -623
  139. package/package.json +273 -143
  140. package/dist/client.js.map +0 -1
  141. package/dist/client.mjs.map +0 -1
  142. package/dist/connectors/betterstack.js.map +0 -1
  143. package/dist/connectors/betterstack.mjs.map +0 -1
  144. package/dist/connectors/otlp.js.map +0 -1
  145. package/dist/connectors/otlp.mjs.map +0 -1
  146. package/dist/connectors/posthog.js.map +0 -1
  147. package/dist/connectors/posthog.mjs.map +0 -1
  148. package/dist/connectors/sentry.js.map +0 -1
  149. package/dist/connectors/sentry.mjs.map +0 -1
  150. package/dist/database.js.map +0 -1
  151. package/dist/database.mjs.map +0 -1
  152. package/dist/elysia.js.map +0 -1
  153. package/dist/elysia.mjs.map +0 -1
  154. package/dist/expo.js.map +0 -1
  155. package/dist/expo.mjs.map +0 -1
  156. package/dist/express.js.map +0 -1
  157. package/dist/express.mjs.map +0 -1
  158. package/dist/fastify.js.map +0 -1
  159. package/dist/fastify.mjs.map +0 -1
  160. package/dist/hono.js.map +0 -1
  161. package/dist/hono.mjs.map +0 -1
  162. package/dist/index.js.map +0 -1
  163. package/dist/index.mjs.map +0 -1
  164. package/dist/nestjs.js.map +0 -1
  165. package/dist/nestjs.mjs.map +0 -1
  166. package/dist/nextjs.js.map +0 -1
  167. package/dist/nextjs.mjs.map +0 -1
  168. package/dist/standalone.js.map +0 -1
  169. package/dist/standalone.mjs.map +0 -1
  170. package/dist/sveltekit.js.map +0 -1
  171. package/dist/sveltekit.mjs.map +0 -1
  172. package/dist/tanstack-start.js.map +0 -1
  173. package/dist/tanstack-start.mjs.map +0 -1
  174. package/dist/workers.js.map +0 -1
  175. package/dist/workers.mjs.map +0 -1
  176. package/exports/client.js +0 -3
  177. package/exports/client.mjs +0 -3
  178. package/exports/connectors/betterstack.js +0 -1
  179. package/exports/connectors/betterstack.mjs +0 -1
  180. package/exports/connectors/otlp.js +0 -1
  181. package/exports/connectors/otlp.mjs +0 -1
  182. package/exports/connectors/posthog.js +0 -1
  183. package/exports/connectors/posthog.mjs +0 -1
  184. package/exports/connectors/sentry.js +0 -1
  185. package/exports/connectors/sentry.mjs +0 -1
  186. package/exports/database.js +0 -1
  187. package/exports/database.mjs +0 -1
  188. package/exports/expo.js +0 -1
  189. package/exports/expo.mjs +0 -1
  190. package/exports/frameworks/elysia.js +0 -1
  191. package/exports/frameworks/elysia.mjs +0 -1
  192. package/exports/frameworks/express.js +0 -1
  193. package/exports/frameworks/express.mjs +0 -1
  194. package/exports/frameworks/fastify.js +0 -1
  195. package/exports/frameworks/fastify.mjs +0 -1
  196. package/exports/frameworks/hono.js +0 -1
  197. package/exports/frameworks/hono.mjs +0 -1
  198. package/exports/frameworks/nestjs.js +0 -1
  199. package/exports/frameworks/nestjs.mjs +0 -1
  200. package/exports/frameworks/nextjs.js +0 -1
  201. package/exports/frameworks/nextjs.mjs +0 -1
  202. package/exports/frameworks/standalone.js +0 -1
  203. package/exports/frameworks/standalone.mjs +0 -1
  204. package/exports/frameworks/sveltekit.js +0 -1
  205. package/exports/frameworks/sveltekit.mjs +0 -1
  206. package/exports/frameworks/tanstack-start.js +0 -1
  207. package/exports/frameworks/tanstack-start.mjs +0 -1
  208. package/exports/workers.js +0 -1
  209. package/exports/workers.mjs +0 -1
  210. package/types/client.d.ts +0 -34
  211. package/types/connectors/betterstack.d.ts +0 -1
  212. package/types/connectors/otlp.d.ts +0 -1
  213. package/types/connectors/posthog.d.ts +0 -1
  214. package/types/connectors/sentry.d.ts +0 -1
  215. package/types/database.d.ts +0 -1
  216. package/types/expo.d.ts +0 -17
  217. package/types/frameworks/client.d.ts +0 -160
  218. package/types/frameworks/elysia.d.ts +0 -1
  219. package/types/frameworks/expo.d.ts +0 -50
  220. package/types/frameworks/express.d.ts +0 -1
  221. package/types/frameworks/fastify.d.ts +0 -1
  222. package/types/frameworks/hono.d.ts +0 -1
  223. package/types/frameworks/nestjs.d.ts +0 -1
  224. package/types/frameworks/nextjs.d.ts +0 -1
  225. package/types/frameworks/standalone.d.ts +0 -1
  226. package/types/frameworks/sveltekit.d.ts +0 -1
  227. package/types/frameworks/tanstack-start.d.ts +0 -1
  228. package/types/frameworks/workers.d.ts +0 -115
  229. package/types/index.d.ts +0 -1
  230. package/types/workers.d.ts +0 -13
package/dist/express.mjs CHANGED
@@ -1,4141 +1,701 @@
1
- import { z } from 'zod';
2
- import fs, { existsSync, readFileSync, writeFileSync, appendFileSync } from 'fs';
3
- import { createJiti } from 'jiti';
4
- import path, { resolve, dirname } from 'path';
5
- import { SeverityNumber } from '@opentelemetry/api-logs';
6
- import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
7
- import { resourceFromAttributes } from '@opentelemetry/resources';
8
- import { LoggerProvider, BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';
9
- import { PostHog } from 'posthog-node';
10
- import { gzipSync } from 'fflate';
11
- import pino from 'pino';
12
- import { AsyncLocalStorage } from 'async_hooks';
13
- import { randomUUID } from 'crypto';
14
- import * as Sentry from '@sentry/node';
15
- import { Logtail } from '@logtail/node';
1
+ import {z as z$1}from'zod';import S,{existsSync,readFileSync,writeFileSync,appendFileSync}from'fs';import {createJiti}from'jiti';import q,{resolve,dirname}from'path';import nn from'os';import {gzipSync}from'fflate';import rr from'pino';import {createRequire}from'module';import {AsyncLocalStorage}from'async_hooks';import {randomUUID}from'crypto';import {Worker}from'worker_threads';var _r=Object.defineProperty;var Pr=(e,t,r)=>t in e?_r(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var d=(e,t,r)=>Pr(e,typeof t!="symbol"?t+"":t,r);function re(e){return `${{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[33m",PATCH:"\x1B[34m",DELETE:"\x1B[31m"}[e.toUpperCase()]||""}${e}\x1B[0m`}function ne(e){let t="\x1B[0m";return e>=500?`\x1B[31m${e}${t}`:e>=400?`\x1B[33m${e}${t}`:e>=300?`\x1B[36m${e}${t}`:e>=200?`\x1B[32m${e}${t}`:`\x1B[37m${e}${t}`}function dt(e){return {GET:"\u2192",POST:"\u2191",PUT:"\u21D1",PATCH:"\u2197",DELETE:"\u2715"}[e.toUpperCase()]||"\u2022"}function oe(e){let t="\x1B[0m";return e<100?`\x1B[32m${e}ms${t}`:e<300?`\x1B[33m${e}ms${t}`:e<1e3?`\x1B[31m${e}ms${t}`:`\x1B[41m\x1B[37m${e}ms${t}`}function ie(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let r=e;return r.cause!==void 0&&(t.cause=T(r.cause)),t}function T(e,t=new WeakSet){if(e instanceof Error)return ie(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(r=>T(r,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let r={};for(let[n,o]of Object.entries(e))r[n]=T(o,t);return t.delete(e),r}return e}function ve(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=T(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var pt="[REDACTED]",Ar=["password","passwd","pwd","secret","token","api_key","apikey","api_secret","authorization","auth","x-api-key","private_key","privatekey","access_token","refresh_token","client_secret","session","cookie","set-cookie","ssn","credit_card","card_number","cvv","cvc","otp","pin"],Br=["authorization","cookie","set-cookie","x-api-key","x-auth-token"],Ir=[{type:"bearer",pattern:/\bBearer\s+(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Za-z0-9._~+/-]{20,})\b/g},{type:"jwt",pattern:/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"api_key",pattern:/\b(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,})\b/g}],Or=/\b(?:\d[ -]*?){16}\b/g;function gt(e){let t=new Set,r=[];for(let n of e)typeof n!="string"||n.length===0||t.has(n)||(t.add(n),r.push(n));return r}function Nr(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Mr(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Fr(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function zr(e){return new Set([...Br,...e.keys.map(t=>t.toLowerCase())])}function jr(e){return e.split(".").filter(Boolean)}function xe(e,t,r=0,n=0){if(r===e.length)return n===t.length;let o=e[r];if(o==="**"){if(r===e.length-1)return true;for(let i=n;i<=t.length;i+=1)if(xe(e,t,r+1,i))return true;return false}return n>=t.length||o!=="*"&&o!==t[n]?false:xe(e,t,r+1,n+1)}function Ur(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(r=>xe(jr(r),e))}function $r(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let r=0,n=false;for(let o=t.length-1;o>=0;o-=1){let i=Number(t[o]);n&&(i*=2,i>9&&(i-=9)),r+=i,n=!n;}return r%10===0}function se(e,t,r){if(r||t.disablePatternScanning)return e;let n=e;for(let{type:o,pattern:i}of Ir)n=n.replace(i,`[REDACTED:${o}]`);n=n.replace(Or,o=>$r(o)?"[REDACTED:card]":o);for(let o of t.patterns)n=n.replace(Nr(o),"[REDACTED:pattern]");return n}function ae(e,t,r,n){if(typeof e=="string")return se(e,t,!!n.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((i,a)=>ae(i,t,r,{path:[...n.path,String(a)],skipPatternScanning:n.skipPatternScanning}));if(!Mr(e))return e;let o={};for(let[i,a]of Object.entries(e)){let s=[...n.path,i];if(r.has(i.toLowerCase())||Ur(s,t)){if(a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){o[i]=pt;continue}o[i]=ae(a,t,r,{path:s,skipPatternScanning:n.skipPatternScanning});continue}o[i]=ae(a,t,r,{path:s,skipPatternScanning:n.skipPatternScanning});}return o}function x(e,t){return {keys:gt([...Ar,...e?.keys??[],...t?.keys??[]]),paths:gt([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(r=>r instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function C(e,t,r={path:[]}){let n=T(e);return ae(n,t,Fr(t),r)}function I(e,t){return typeof e=="string"?se(e,t,false):ve(C(e,t))}function qr(e){if(!e)return {};if(e instanceof Headers){let t={};return e.forEach((r,n)=>{t[n]=r;}),t}if(typeof e.entries=="function"){let t={};for(let[r,n]of e.entries())t[r]=n;return t}return typeof e.get=="function"?{}:{...e}}function ft(e,t){let r=qr(e),n=zr(t),o={};for(let[i,a]of Object.entries(r)){if(n.has(i.toLowerCase())){o[i]=pt;continue}if(Array.isArray(a)){o[i]=a.map(s=>se(s,t,false));continue}o[i]=typeof a=="string"?se(a,t,false):a;}return o}function b(e,t){if(!e)return;if(e instanceof Headers||typeof e.get=="function")return e.get(t)??e.get(t.toLowerCase())??void 0;let r=e,n=r[t]??r[t.toLowerCase()];return Array.isArray(n)?n[0]:n}function Hr(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>t.match(/for="?(\[[^\]]+\]|[^;,\s"]+)/i)?.[1]?.replace(/^"|"$/g,"")??"").map(t=>t.replace(/^\[|\]$/g,"")).filter(Boolean):[]}function Wr(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Qr(e){if(e.startsWith("[")){let t=e.indexOf("]");return t>=0?e.slice(1,t):e}return e.replace(/:\d+$/,"")}function Jr(e){return /edg\//i.test(e)?"Edge":/opr\//i.test(e)||/opera/i.test(e)?"Opera":/chrome\//i.test(e)&&!/edg\//i.test(e)?"Chrome":/firefox\//i.test(e)?"Firefox":/safari\//i.test(e)&&!/chrome\//i.test(e)?"Safari":/curl\//i.test(e)?"curl":/postmanruntime/i.test(e)?"Postman":"Unknown"}function Gr(e){return /windows/i.test(e)?"Windows":/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/mac os x|macintosh/i.test(e)?"macOS":/linux/i.test(e)?"Linux":"Unknown"}function Kr(e){return e?/bot|crawler|spider|curl|wget|postmanruntime/i.test(e)?"bot":/ipad|tablet/i.test(e)?"tablet":/mobi|iphone|android/i.test(e)?"mobile":"desktop":"unknown"}function D(e,t="/"){if(!e)return t;if(e.startsWith("http://")||e.startsWith("https://"))try{return new URL(e).pathname||t}catch{return t}if(e.startsWith("/")){let r=e.indexOf("?");return r>=0?e.slice(0,r):e}try{return new URL(e,"http://localhost").pathname||t}catch{return t}}function ce(e,t,r){return {method:e,url:t,headers:r}}function Te(e,t,r=x()){let n=t??D(e.url),o=(()=>{try{return new URL(e.url)}catch{try{return new URL(n,"http://localhost")}catch{return null}}})(),i=b(e.headers,"x-forwarded-host")??b(e.headers,"host")??o?.host??void 0,a=i?Qr(i):o?.hostname,s=i?.match(/:(\d+)$/)?.[1]??(o?.port||void 0),l=Wr(b(e.headers,"x-forwarded-for")),u=Hr(b(e.headers,"forwarded")),c=[b(e.headers,"cf-connecting-ip"),b(e.headers,"true-client-ip"),b(e.headers,"fly-client-ip"),b(e.headers,"x-real-ip"),b(e.headers,"x-client-ip"),l[0],u[0]].filter(w=>!!w),p=b(e.headers,"user-agent"),m=b(e.headers,"sec-ch-ua-platform")?.replace(/^"|"$/g,"")??void 0,R=Kr(p??"");return {hostname:a,ip:c[0],forwardedFor:[...l,...u].filter((w,f,g)=>g.indexOf(w)===f),protocol:b(e.headers,"x-forwarded-proto")??(o?.protocol?o.protocol.replace(/:$/,""):void 0),port:s,userAgent:p,origin:b(e.headers,"origin"),referer:b(e.headers,"referer"),acceptLanguage:b(e.headers,"accept-language"),headers:ft(e.headers,r),client:{ip:c[0],hostname:a,browser:p?Jr(p):void 0,os:p?Gr(p):void 0,deviceType:R,platform:m,isMobile:R==="mobile"}}}function ue(e,t,r,n,o,i={},a=x()){return {type:t,method:e.method,url:r,statusCode:n,responseTime:o,...Te(e,r,a),...i}}function le(e,t,r,n){let o=re(e),i=ne(t),a=oe(n),s=dt(e);return `${o} ${s} ${i} ${r} ${a}`}function Ee(e,t){if(e==null)return t===void 0?void 0:{statusCode:t,message:`HTTP ${t}`};if(e instanceof Error){let r=e;return {status:r.status,statusCode:r.statusCode??t,code:r.code,message:e.message,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:r.details,cause:r.cause}}if(typeof e=="object"){let r=e;return {status:typeof r.status=="number"?r.status:void 0,statusCode:typeof r.statusCode=="number"?r.statusCode:t,code:typeof r.code=="string"||typeof r.code=="number"?r.code:void 0,message:typeof r.message=="string"?r.message:`HTTP ${t??500}`,stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:r.details!==null&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:void 0,cause:r.cause}}return {statusCode:t,message:typeof e=="string"?e:`HTTP ${t??500}`}}function De(e){return e>=400}var Xr=z$1.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"}),G=z$1.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),_e=z$1.string().trim().min(1);function Pe(e){return Xr.safeParse(e).success}function z(e){return G.safeParse(e).success}function O(e){return _e.safeParse(e).success}var N="/inngest";var Vr=["debug","info","warning","error","critical","success","table"],Yr=z$1.union([z$1.literal("betterstack"),z$1.literal("databuddy"),z$1.literal("posthog"),z$1.literal("sentry"),z$1.undefined(),z$1.object({type:z$1.literal("otlp"),name:_e})]);function Zr(e){return typeof e=="string"&&Vr.includes(e)}function en(e){return Yr.safeParse(e).success}function tn(e){try{return e()}catch{return}}function rn(){return Math.random().toString(36).slice(2,10)}function de(){let e=tn(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${rn()}`}function mt(e){if(!z(e)||e.type!=="client_log"||e.source!=="client"||!Zr(e.level)||typeof e.id!="string"||typeof e.message!="string"||typeof e.clientTimestamp!="string")return false;let t=G.safeParse(e.page),r=G.safeParse(e.browser),n=G.safeParse(e.session);return !t.success||!r.success||!n.success||!en(e.connector)?false:typeof n.data.pageId=="string"&&typeof n.data.sessionId=="string"}function Ae(e){return e?e.startsWith("/")?e:`/${e}`:N}function yt(){return q.join(nn.homedir(),".blyp","queue.db")}function an(e,t=new Set){return (r,n,o)=>{if(t.has(r)||typeof console>"u")return;let i=console[e];if(typeof i=="function"){if(t.add(r),o===void 0){i.call(console,n);return}i.call(console,n,o);}}}function _(e){return an("warn",e)}var ln="@blyp/core",dn=".gitignore",wt=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],gn="blyp.config.json",pn="https://us.i.posthog.com",fn="blyp-app",mn=fn,yn=new Set,P=_(yn),Rt={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},Lt={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:Rt},Be={enabled:true,path:N},St=x(),j={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},v={enabled:false,memoryBufferSize:500,durableQueuePath:yt(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:j},vt={maxRetries:1,backoffMs:100},hn={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:vt},ht={pretty:true,level:"info",destination:"file",file:Lt,clientLogging:Be,redact:St,connectors:{delivery:v}},K=null;function bn(e){let t=e;for(;;){let r=resolve(t,"package.json");if(existsSync(r))try{let o=JSON.parse(readFileSync(r,"utf-8"));if(O(o.name))return o.name}catch{}let n=dirname(t);if(n===t)return;t=n;}}function Oe(e=process.cwd()){return bn(e)??mn}function Cn(){return {pretty:true,level:"info",destination:"file",file:{enabled:true,format:"ndjson",rotation:{enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true}},clientLogging:{enabled:true,path:N},redact:St,connectors:{delivery:v}}}function wn(e){let t=resolve(e,"package.json");if(!existsSync(t))return true;try{return JSON.parse(readFileSync(t,"utf-8")).name!==ln}catch{return true}}function Rn(e){if(wt.some(r=>existsSync(resolve(e,r))))return;let t=resolve(e,gn);if(!existsSync(t))try{writeFileSync(t,`${JSON.stringify(Cn(),null,2)}
2
+ `);}catch(r){console.error("[Blyp] Warning: Failed to create blyp.config.json:",r);}}function Ln(e){let t=resolve(e,dn);if(!existsSync(t)){try{writeFileSync(t,`logs
3
+ .blyp
4
+ `);}catch(r){console.error("[Blyp] Warning: Failed to create .gitignore:",r);}return}try{let r=readFileSync(t,"utf-8"),n=["logs",".blyp"].filter(i=>{let a=i.replace(".","\\.");return !new RegExp(`^(?:/?${a}/?)\\s*$`,"m").test(r)});if(n.length===0)return;let o=r.endsWith(`
5
+ `)?"":`
6
+ `;appendFileSync(t,`${o}${n.join(`
7
+ `)}
8
+ `);}catch(r){console.error("[Blyp] Warning: Failed to update .gitignore:",r);}}function Sn(){let e=process.cwd();wn(e)&&(Rn(e),Ln(e));}function vn(){let e=process.cwd(),t=wt.map(n=>resolve(e,n)).filter(n=>existsSync(n));if(t.length===0)return null;if(t.length>1){let n=t[0];P(`config-multiple:${n}`,`[Blyp] Warning: Multiple config files found. Using ${n} and ignoring ${t.slice(1).join(", ")}.`);}let r=t[0];return {path:r,type:r.endsWith(".json")?"json":"jiti"}}function xt(e,t){let r=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !r||typeof r!="object"||Array.isArray(r)?(P(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):r}function xn(e){try{let t=readFileSync(e,"utf-8");return xt(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function Tn(e){try{let t=createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return xt(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function En(e){return e.type==="json"?xn(e.path):Tn(e.path)}function bt(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function Dn(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function kn(e,t){return {...vt,...e,...t}}function _n(e,t){return {...hn,...e,...t,retry:kn(e?.retry,t?.retry)}}function Pn(e){let t=e.model??"blypLog",n=e.client?.[t];return !!n&&typeof n.create=="function"}function An(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function Bn(e,t){if(!e)return;let r=e.adapter,n=false;t==="json"?P("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?P(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):r?bt(r)?(n=Pn({...r,model:r.model??"blypLog"}),n||P("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${r.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):Dn(r)&&(n=An(r),n||P("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):P("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let o=bt(r)?{...r,model:r.model??"blypLog"}:r;return {dialect:e.dialect,adapter:o,delivery:_n(void 0,e.delivery),ready:n,status:n?"enabled":"missing"}}function In(e,t){return {...Rt,...e,...t}}function On(e,t){return {...Lt,...e,...t,rotation:In(e?.rotation,t?.rotation)}}function Nn(e,t){return {...Be,...e,...t,path:t?.path??e?.path??Be.path}}function Mn(e,t){return x(e,t)}function Fn(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??j.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??j.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??j.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??j.multiplier),jitter:t?.jitter??e?.jitter??j.jitter}}function zn(e,t){let r=t?.durableQueuePath??e?.durableQueuePath??v.durableQueuePath;return {enabled:t?.enabled??e?.enabled??v.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??v.memoryBufferSize)),durableQueuePath:O(r)?r:v.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??v.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??v.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??v.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??v.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??v.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??v.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??v.overflowStrategy,retry:Fn(e?.retry,t?.retry),durableReady:false}}function jn(e,t,r){if(!(!e&&!t))return Bn({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},r)}function Un(e,t){let r=t?.enabled??e?.enabled??false,n=t?.projectKey??e?.projectKey,o=e?.enabled===true?e?.errorTracking:void 0,i=t?.errorTracking?.mode??o?.mode??"auto",a=t?.errorTracking?.enabled??o?.enabled??r,s=r&&a&&typeof n=="string"&&n.trim().length>0;return {enabled:r,mode:t?.mode??e?.mode??"auto",projectKey:n,host:t?.host??e?.host??pn,serviceName:t?.serviceName??e?.serviceName??Oe(),errorTracking:{enabled:a,mode:i,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??o?.enableExceptionAutocapture??i==="auto",ready:s,status:s?"enabled":"missing"}}}function $n(e,t){let r=t?.enabled??e?.enabled??false,n=t?.apiKey??e?.apiKey,o=t?.websiteId??e?.websiteId,i=r&&O(n)&&O(o);return {enabled:r,mode:t?.mode??e?.mode??"auto",apiKey:n,websiteId:o,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:i,status:i?"enabled":"missing"}}function qn(e,t){let r=t?.sourceToken??e?.sourceToken,n=t?.ingestingHost??e?.ingestingHost,o=t?.enabled??e?.enabled??false,i=e?.enabled===true?e?.errorTracking:void 0,a=Hn(o,i,t?.errorTracking),s=o&&O(r)&&Pe(n);return {enabled:o,mode:t?.mode??e?.mode??"auto",sourceToken:r,ingestingHost:n,serviceName:t?.serviceName??e?.serviceName??Oe(),errorTracking:a,ready:s,status:s?"enabled":"missing"}}function Hn(e,t,r){let n=r?.dsn??t?.dsn,o=r?.enabled??t?.enabled??e,i=o&&O(n);return {enabled:o,dsn:n,tracesSampleRate:r?.tracesSampleRate??t?.tracesSampleRate??1,environment:r?.environment??t?.environment,release:r?.release??t?.release,ready:i,status:i?"enabled":"missing"}}function Wn(e,t){let r=t?.dsn??e?.dsn,n=t?.enabled??e?.enabled??false,o=n&&typeof r=="string"&&r.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",dsn:r,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:o,status:o?"enabled":"missing"}}function Qn(e,t){let r=t?.endpoint??e?.endpoint,n=t?.enabled??e?.enabled??false,o={...{},...t?.headers??{}},i=n&&Pe(r);return {name:t?.name??e?.name??"",enabled:n,mode:t?.mode??e?.mode??"auto",endpoint:r,headers:o,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??Oe(),ready:i,status:i?"enabled":"missing"}}function Jn(e,t){let r=t??e??[],n=new Map;for(let o of r)!o||typeof o.name!="string"||o.name.length===0||(n.has(o.name)&&P(`otlp-duplicate:${o.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${o.name}" found. Using the last definition.`),n.set(o.name,Qn(void 0,o)));return Array.from(n.values())}function Gn(e,t){return {betterstack:qn(e?.betterstack,t?.betterstack),databuddy:$n(e?.databuddy,t?.databuddy),posthog:Un(e?.posthog,t?.posthog),sentry:Wn(e?.sentry,t?.sentry),otlp:Jn(e?.otlp,t?.otlp),delivery:zn(e?.delivery,t?.delivery)}}function Ie(e,t={},r={}){return {...e,...t,destination:t.destination??e.destination??"file",file:On(e.file,t.file),database:jn(e.database,t.database,r.configFileType),clientLogging:Nn(e.clientLogging,t.clientLogging),redact:Mn(e.redact,t.redact),connectors:Gn(e.connectors,t.connectors)}}function Kn(){if(K!==null)return K;Sn();let e=vn();if(e){let t=En(e);K=Ie(ht,t,{configFileType:e.type});}else K=Ie(ht);return K}function X(e={}){return Ie(Kn(),e)}function Xn(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function Vn(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function Ne(e,t){if(!t||t.length===0)return false;let r=Xn(e);return t.some(n=>{let o=Vn(n);if(o===r||o==="/**"||o==="**")return true;if(o==="/*")return r.split("/").filter(a=>a.length>0).length===1;if(o.endsWith("/*")&&!o.includes("**")){let i=o.slice(0,-1);return r.startsWith(i)?r.slice(i.length).split("/").filter(l=>l.length>0).length===1:false}if(o.includes("**")){if(o==="/**")return true;if(o.startsWith("/")&&o.endsWith("**")){let l=o.slice(0,-2);return l.endsWith("/")&&l.length>1&&(l=l.slice(0,-1)),l===r?true:r.startsWith(l+"/")}let i=o.indexOf("**"),a=o.substring(0,i),s=o.substring(i+2);return a.endsWith("/")&&a.length>1&&(a=a.slice(0,-1)),a===""&&s===""?true:a!==""&&s===""?r.startsWith(a+"/"):a===""&&s!==""?r.endsWith(s)||r.includes(s+"/"):a!==""&&s!==""?r.startsWith(a)&&(r.endsWith(s)||r.includes(s+"/")):false}if(o.includes("*")){let i=o.lastIndexOf("."),a=o.lastIndexOf("*");if(i>a&&a>0&&o[a-1]==="/"){let c=o.slice(a),p=r.slice(r.lastIndexOf("/")+1),m=p.lastIndexOf(".");if(m>0)return p.slice(m)===c}let s=o.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*");return new RegExp("^"+s+"$").test(r)}return false})}function Zn(e){return Buffer.from(gzipSync(e))}function eo(e,t){console.warn(`[Blyp] Warning: ${e}`,t);}function pe(e){S.mkdirSync(e,{recursive:true});}function to(e){try{return S.statSync(e).size}catch{return 0}}function ro(e){let t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),i=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0");return `${t}${r}${n}T${o}${i}${a}Z`}function no(e,t){let r=`${e}${t}`,n=1;for(;S.existsSync(r);)r=`${e}-${n}${t}`,n+=1;return r}function oo(e,t,r,n){let o=`${t}.`;try{let i=S.readdirSync(e).filter(s=>s.startsWith(o)&&(s.endsWith(".ndjson")||s.endsWith(".ndjson.gz"))).map(s=>q.join(e,s)).sort((s,l)=>S.statSync(s).mtimeMs-S.statSync(l).mtimeMs),a=Math.max(i.length-r,0);for(let s=0;s<a;s+=1)S.rmSync(i[s]);}catch(i){n(`Failed to prune archives for ${t}`,i);}}function io(){let e=new WeakSet;return (t,r)=>{if(typeof r=="function")return `[Function: ${r.name||"anonymous"}]`;if(r===void 0)return "[undefined]";if(typeof r=="symbol")return r.toString();if(r!==null&&typeof r=="object"){if(e.has(r))return "[Circular]";e.add(r);}return r}}function Fe(e){return JSON.stringify(e,io())}function ao(e){let t=e.file,r=t?.dir||e.logDir||q.join(process.cwd(),"logs"),n=t?.archiveDir||q.join(r,"archive"),o=t?.rotation;return {enabled:t?.enabled??true,dir:r,archiveDir:n,rotationEnabled:o?.enabled??true,maxSizeBytes:o?.maxSizeBytes??10*1024*1024,maxArchives:o?.maxArchives??5,compress:o?.compress??true}}var Me=class{constructor(t,r={}){d(this,"config");d(this,"gzip");d(this,"warn");d(this,"combined");d(this,"error");this.config=ao(t),this.gzip=r.gzip??Zn,this.warn=r.warn??eo,this.combined={activePath:q.join(this.config.dir,"log.ndjson"),archivePrefix:"log",bytes:0,queue:[],processing:false},this.error={activePath:q.join(this.config.dir,"log.error.ndjson"),archivePrefix:"log.error",bytes:0,queue:[],processing:false},this.config.enabled&&(pe(this.config.dir),pe(this.config.archiveDir),this.seedStream(this.combined),this.seedStream(this.error));}write(t){if(!this.config.enabled)return;let r=`${Fe(t)}
9
+ `;this.enqueue(this.combined,r),(t.level==="error"||t.level==="critical")&&this.enqueue(this.error,r);}enqueue(t,r){t.queue.push(r),this.processQueue(t);}processQueue(t){if(!t.processing){t.processing=true;try{for(;t.queue.length>0;){let r=t.queue.shift();if(r!==void 0)try{this.append(t,r);}catch(n){this.warn(`Failed writing log line for ${t.archivePrefix}`,n);}}}finally{t.processing=false;}}}seedStream(t){t.bytes=to(t.activePath),this.config.rotationEnabled&&t.bytes>this.config.maxSizeBytes&&t.bytes>0&&(this.rotate(t),S.closeSync(S.openSync(t.activePath,"a")),t.bytes=0);}append(t,r){pe(this.config.dir);let n=Buffer.byteLength(r,"utf8");this.config.rotationEnabled&&t.bytes>0&&t.bytes+n>this.config.maxSizeBytes&&this.rotate(t),S.appendFileSync(t.activePath,r,"utf8"),t.bytes+=n;}rotate(t){if(pe(this.config.archiveDir),!S.existsSync(t.activePath)||t.bytes===0){t.bytes=0;return}let r=ro(new Date),n=q.join(this.config.archiveDir,`${t.archivePrefix}.${r}`),o=no(n,".ndjson");if(S.renameSync(t.activePath,o),this.config.compress)try{let i=`${o}.gz`,a=this.gzip(S.readFileSync(o));S.writeFileSync(i,a),S.rmSync(o);}catch(i){this.warn(`Failed to gzip archive ${o}`,i);}t.bytes=0,oo(this.config.archiveDir,t.archivePrefix,this.config.maxArchives,this.warn);}};function Tt(e){return new Me(e)}function ze(e){return z(e.data)?e.data:e}function A(e,t){if(t in e){let o=e[t];if(typeof o=="string"||typeof o=="number")return o}let n=ze(e)[t];if(typeof n=="string"||typeof n=="number")return n}function je(e,t){let r=ze(e),o=(z(r.page)?r.page:void 0)?.[t];return typeof o=="string"?o:void 0}function Ue(e,t){let r=ze(e),o=(z(r.session)?r.session:void 0)?.[t];return typeof o=="string"?o:void 0}function fe(e){return A(e,"type")}function so(e,t){let r=fe(e),n=typeof e.caller=="string"?e.caller:void 0,o=A(e,"groupId"),i=A(e,"traceId"),a=A(e,"method"),s=A(e,"path"),l=A(e,"status"),u=A(e,"duration"),c=je(e,"pathname"),p=je(e,"url"),m=Ue(e,"sessionId"),R=Ue(e,"pageId"),w={"blyp.level":e.level,"blyp.source":t,"blyp.payload":Fe(e)},f=[["blyp.type",r],["blyp.caller",n],["blyp.group_id",o],["blyp.trace_id",i],["http.method",a],["url.path",s],["client.page_path",c],["client.page_url",p],["client.session_id",m],["client.page_id",R]],g=[["http.status_code",l],["blyp.duration_ms",u]];for(let[y,L]of f)L&&(w[y]=L);for(let[y,L]of g)L!==void 0&&(w[y]=L);return w}function $e(e,t,r={}){return {...so(e,t),...r}}var uo=createJiti(typeof __filename=="string"?__filename:import.meta.url,{interopDefault:false,moduleCache:true,fsCache:false}),Et=new Map;function lo(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function H(e,t,r=`@blyp/core/${e}`){let n=`@blyp/core/${e}`,o=`${n}::${r}`,i=Et.get(o);if(i)return i;try{let a=uo(r);return Et.set(o,a),a}catch(a){if(!lo(a))throw a;let s=t.map(u=>`"${u}"`).join(", "),l=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${n}". Install ${s} to use this API. Example: bun add ${l}. You can also import directly from "${n}".`,{cause:a instanceof Error?a:void 0})}}var po=createRequire(typeof __filename=="string"?__filename:import.meta.url),qe=null;function fo(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function mo(e){if(typeof e=="function")return e;if(!e||typeof e!="object")return null;let t="default"in e?e.default:void 0;return typeof t=="function"?t:null}function Dt(){if(qe)return qe;let e;try{e=po("pino-pretty");}catch(r){throw fo(r)?new Error('[Blyp] Failed to initialize the pretty logger transport because pretty: true requires "pino-pretty" to be installed.',{cause:r instanceof Error?r:void 0}):new Error('[Blyp] Failed to initialize the pretty logger transport with "pino-pretty".',{cause:r instanceof Error?r:void 0})}let t=mo(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return qe=t,t}var kt=new AsyncLocalStorage;function ho(){return {requestScopedLoggerActive:true,structuredCollectorActive:false,structuredLogEmitted:false,mixedLoggerWarningShown:false}}function He(){let e=ho();return kt.enterWith(e),e}function M(){return kt.getStore()}function We(e){let t=M();t&&(t.activeLogger=e);}function V(e){let t=M();t&&(t.traceId=e);}function B(){return M()?.traceId}function Qe(){let e=M();e&&(e.structuredCollectorActive=true);}function Je(){let e=M();e&&(e.structuredLogEmitted=true);}function me(){let e=M();return !e||!e.requestScopedLoggerActive||!e.structuredCollectorActive?false:(e.mixedLoggerWarningShown||(e.mixedLoggerWarningShown=true,console.warn("[Blyp] Warning: Mixed logger usage detected for this request. The root logger call was ignored because a request-scoped structured logger is active.")),true)}var _t={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function ye(e){return e.replace(/\\/g,"/")}function bo(e){let t=ye(e);return t.startsWith("node:")||t.includes("/node_modules/pino")||t.includes("/node_modules/pino-pretty")||t.includes("/node_modules/@blyp/core/")||t.includes("/blyp/src/core/")||t.includes("/blyp/src/frameworks/")||t.includes("/blyp/src/posthog/")||t.includes("/blyp/dist/")}function Co(e){let t=ye(e),r=ye(process.cwd());return t.startsWith(`${r}/`)?t.slice(r.length+1):t}function Pt(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
10
+ `),r=null;for(let n=2;n<t.length;n+=1){let o=t[n];if(!o)continue;let i=o.match(/\((.*):(\d+):\d+\)/)||o.match(/at\s+(.*):(\d+):(\d+)/);if(!i)continue;let a=i[1]||"",s=parseInt(i[2]||"0",10)||null;if(a&&!a.includes("node_modules")&&!bo(a)){let l=Co(a);if(!ye(l).startsWith("dist/"))return {file:l,line:s};r??(r={file:l,line:s});}}if(r)return r}catch{return {file:null,line:null}}return {file:null,line:null}}var At=I;function Bt(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function It(e,t,r,n,o=x()){let{file:i,line:a}=Pt(),s=At(t,o),l={timestamp:new Date().toISOString(),level:_t[e],message:Bt(s)},u=B();return t instanceof Error&&(l.error=C(ie(t),o)),i&&(l.caller=a!==null?`${i}:${a}`:i),r.length===1?l.data=C(r[0],o):r.length>1&&(l.data=C(r,o)),Object.keys(n).length>0&&(l.bindings=C(n,o)),u&&(l.traceId=u),l}function Ot(e,t,r,n,o=x()){let{file:i,line:a}=Pt(),s=C(r,o),l=B(),u={message:Bt(At(t,o)),...s};return i&&(u.caller=a!==null?`${i}:${a}`:i),Object.keys(n).length>0&&(u.bindings=C(n,o)),l&&u.traceId===void 0&&(u.traceId=l),u.level=typeof s.level=="string"&&s.level.length>0?s.level:_t[e],u.timestamp=typeof s.timestamp=="string"&&s.timestamp.length>0?s.timestamp:new Date().toISOString(),u}function Nt(e){switch(e){case "debug":return "debug";case "warning":return "warning";case "warn":return "warn";case "error":return "error";case "success":return "success";case "critical":return "critical";case "table":return "table";default:return "info"}}var Ge=class{constructor(t){this.logger=t;d(this,"isAsync",false);d(this,"isReady",true);}write(t){this.logger.write(t);}async flush(){}async shutdown(){}};function Mt(e){return new Ge(Tt(e))}function Ft(e){let t=e.db;if(typeof t?.insert!="function"||e.table===void 0)throw new Error("[Blyp] Drizzle database adapter is missing a db.insert function or table reference.");return {async insert(r){r.length!==0&&await t.insert(e.table).values(r);}}}function wo(e){let t=String(e??"");return t.includes("createMany")||t.includes("Unknown argument")||t.includes("not supported")||t.includes("is not a function")}function zt(e){let t=e.client,r=e.model??"blypLog",n=t[r];if(!n||typeof n.create!="function")throw new Error(`[Blyp] Prisma database adapter is missing the "${r}" delegate or its create method.`);let o=n,i=typeof o.createMany=="function";async function a(s){if(typeof t.$transaction=="function"){await t.$transaction(s.map(l=>o.create({data:l})));return}for(let l of s)await o.create({data:l});}return {async insert(s){if(s.length!==0){if(s.length===1){await o.create({data:s[0]});return}if(!i||typeof o.createMany!="function"){await a(s);return}try{await o.createMany({data:s});}catch(l){if(!wo(l))throw l;i=false,await a(s);}}}}}function jt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function W(e){return typeof e=="string"&&e.length>0?e:null}function Lo(e){if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function Ut(e){let t=T(e);return {id:randomUUID(),timestamp:Lo(e.timestamp),level:e.level,message:e.message,caller:W(e.caller),type:W(e.type),traceId:W(e.traceId),groupId:W(e.groupId),method:W(e.method),path:W(e.path),status:jt(e.status),duration:jt(e.duration),hasError:t.error!=null,data:t.data??null,bindings:t.bindings??null,error:t.error??null,events:t.events??null,record:t,createdAt:new Date}}function So(e){return !!e&&e.type==="prisma"}function vo(e){return !!e&&e.type==="drizzle"}function $t(e){if(So(e.adapter))return zt(e.adapter);if(vo(e.adapter))return Ft(e.adapter);throw new Error("[Blyp] Unsupported database adapter configuration.")}function xo(e){return new Promise(t=>{setTimeout(t,e);})}var he=class{constructor(t){this.config=t;d(this,"isAsync",true);d(this,"isReady",true);d(this,"warnOnce",_(new Set));d(this,"queue",[]);d(this,"writer");d(this,"timer",null);d(this,"processing",false);d(this,"closed",false);d(this,"terminalError",null);d(this,"activeDispatch",null);this.writer=$t(t);}write(t){this.closed||(this.enqueue(Ut(t)),this.scheduleDispatch());}async flush(){this.timer&&(clearTimeout(this.timer),this.timer=null);let t=(async()=>{if(await this.drain(),this.terminalError)throw this.terminalError})(),r=null;try{await Promise.race([t,new Promise((n,o)=>{r=setTimeout(()=>{this.warnOnce("database-flush-timeout",`[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`),o(new Error("[Blyp] Timed out flushing database logs."));},this.config.delivery.flushTimeoutMs);})]);}finally{r&&clearTimeout(r);}}async shutdown(){this.closed=true,await this.flush();}enqueue(t){this.queue.push(t);let r=this.queue.length-this.config.delivery.maxQueueSize;if(!(r<=0)){if(this.warnOnce("database-overflow",`[Blyp] Warning: Database log queue exceeded ${this.config.delivery.maxQueueSize} entries. Applying ${this.config.delivery.overflowStrategy} overflow handling.`),this.config.delivery.overflowStrategy==="drop-new"){this.queue.splice(this.config.delivery.maxQueueSize);return}this.queue.splice(0,r);}}scheduleDispatch(){if(!this.processing){if(this.config.delivery.strategy==="immediate"){this.drain();return}if(this.queue.length>=this.config.delivery.batchSize){this.drain();return}this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.drain();},this.config.delivery.flushIntervalMs));}}async drain(){if(this.processing){this.activeDispatch&&await this.activeDispatch;return}this.processing=true,this.activeDispatch=this.processQueue();try{await this.activeDispatch;}finally{this.processing=false,this.activeDispatch=null;}}async processQueue(){for(;this.queue.length>0;){let t=this.config.delivery.strategy==="batch"?Math.max(1,this.config.delivery.batchSize):1,r=this.queue.splice(0,t);try{await this.insertWithRetry(r);}catch(n){let o=n instanceof Error?n:new Error(String(n??"Unknown database logging failure"));throw this.terminalError=o,this.warnOnce("database-insert-failure",`[Blyp] Warning: Failed to persist logs to the ${this.config.dialect??"database"} database.`,o),o}}}async insertWithRetry(t){let r=Math.max(1,this.config.delivery.retry.maxRetries+1),n=0;for(;n<r;){n+=1;try{await this.writer.insert(t);return}catch(o){if(n>=r)throw o;await xo(this.config.delivery.retry.backoffMs);}}}};var Ke=class{constructor(){d(this,"isAsync",false);d(this,"isReady",false);}write(t){}async flush(){}async shutdown(){}},To=_(new Set);function qt(e){if(e.destination!=="database")return Mt(e);let t=e.database;return t?.ready?new he(t):(To("database-sink-disabled","[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."),new Ke)}function Ht(e,t){let r=Math.max(1,Math.floor(e)),n=Math.pow(t.multiplier,r-1),o=Math.min(Math.max(0,Math.floor(t.initialBackoffMs*n)),Math.max(0,t.maxBackoffMs));return t.jitter?Math.floor(Math.random()*(o+1)):o}var Wt="bun:sqlite";var Qt="node:sqlite";function Jt(){return `
11
+ const { parentPort } = require('node:worker_threads');
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
16
14
 
17
- var __defProp = Object.defineProperty;
18
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
19
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
20
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
21
- }) : x)(function(x) {
22
- if (typeof require !== "undefined") return require.apply(this, arguments);
23
- throw Error('Dynamic require of "' + x + '" is not supported');
24
- });
25
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
26
-
27
- // src/core/colors.ts
28
- function getMethodColor(method) {
29
- const colors = {
30
- GET: "\x1B[32m",
31
- POST: "\x1B[36m",
32
- PUT: "\x1B[33m",
33
- PATCH: "\x1B[34m",
34
- DELETE: "\x1B[31m"
35
- };
36
- const reset = "\x1B[0m";
37
- return `${colors[method.toUpperCase()] || ""}${method}${reset}`;
38
- }
39
- function getStatusColor(statusCode) {
40
- const reset = "\x1B[0m";
41
- if (statusCode >= 500) return `\x1B[31m${statusCode}${reset}`;
42
- if (statusCode >= 400) return `\x1B[33m${statusCode}${reset}`;
43
- if (statusCode >= 300) return `\x1B[36m${statusCode}${reset}`;
44
- if (statusCode >= 200) return `\x1B[32m${statusCode}${reset}`;
45
- return `\x1B[37m${statusCode}${reset}`;
46
- }
47
- function getArrowForMethod(method) {
48
- const arrows = {
49
- GET: "\u2192",
50
- POST: "\u2191",
51
- PUT: "\u21D1",
52
- PATCH: "\u2197",
53
- DELETE: "\u2715"
54
- };
55
- return arrows[method.toUpperCase()] || "\u2022";
56
- }
57
- function getResponseTimeColor(ms) {
58
- const reset = "\x1B[0m";
59
- if (ms < 100) return `\x1B[32m${ms}ms${reset}`;
60
- if (ms < 300) return `\x1B[33m${ms}ms${reset}`;
61
- if (ms < 1e3) return `\x1B[31m${ms}ms${reset}`;
62
- return `\x1B[41m\x1B[37m${ms}ms${reset}`;
63
- }
64
-
65
- // src/frameworks/shared/http.ts
66
- function getHeaderValue(headers, name) {
67
- if (!headers) {
68
- return void 0;
69
- }
70
- if (headers instanceof Headers) {
71
- return headers.get(name) ?? headers.get(name.toLowerCase()) ?? void 0;
72
- }
73
- if (typeof headers.get === "function") {
74
- const direct2 = headers.get(name);
75
- return direct2 ?? headers.get(name.toLowerCase()) ?? void 0;
76
- }
77
- const record = headers;
78
- const direct = record[name] ?? record[name.toLowerCase()];
79
- if (Array.isArray(direct)) {
80
- return direct[0];
81
- }
82
- return direct;
83
- }
84
- function parseForwardedHeader(value) {
85
- if (!value) {
86
- return [];
87
- }
88
- return value.split(",").map((entry) => entry.trim()).filter(Boolean).map((entry) => {
89
- const match = entry.match(/for="?(\[[^\]]+\]|[^;,\s"]+)/i);
90
- return match?.[1]?.replace(/^"|"$/g, "") ?? "";
91
- }).map((entry) => entry.replace(/^\[|\]$/g, "")).filter(Boolean);
92
- }
93
- function parseForwardedFor(value) {
94
- if (!value) {
95
- return [];
96
- }
97
- return value.split(",").map((entry) => entry.trim()).filter(Boolean);
98
- }
99
- function stripPort(host) {
100
- if (host.startsWith("[")) {
101
- const endIndex = host.indexOf("]");
102
- return endIndex >= 0 ? host.slice(1, endIndex) : host;
103
- }
104
- return host.replace(/:\d+$/, "");
105
- }
106
- function detectBrowser(userAgent) {
107
- if (/edg\//i.test(userAgent)) return "Edge";
108
- if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) return "Opera";
109
- if (/chrome\//i.test(userAgent) && !/edg\//i.test(userAgent)) return "Chrome";
110
- if (/firefox\//i.test(userAgent)) return "Firefox";
111
- if (/safari\//i.test(userAgent) && !/chrome\//i.test(userAgent)) return "Safari";
112
- if (/curl\//i.test(userAgent)) return "curl";
113
- if (/postmanruntime/i.test(userAgent)) return "Postman";
114
- return "Unknown";
115
- }
116
- function detectOperatingSystem(userAgent) {
117
- if (/windows/i.test(userAgent)) return "Windows";
118
- if (/android/i.test(userAgent)) return "Android";
119
- if (/iphone|ipad|ipod/i.test(userAgent)) return "iOS";
120
- if (/mac os x|macintosh/i.test(userAgent)) return "macOS";
121
- if (/linux/i.test(userAgent)) return "Linux";
122
- return "Unknown";
123
- }
124
- function detectDeviceType(userAgent) {
125
- if (!userAgent) return "unknown";
126
- if (/bot|crawler|spider|curl|wget|postmanruntime/i.test(userAgent)) return "bot";
127
- if (/ipad|tablet/i.test(userAgent)) return "tablet";
128
- if (/mobi|iphone|android/i.test(userAgent)) return "mobile";
129
- return "desktop";
130
- }
131
- function extractPathname(requestUrl, fallbackPath = "/") {
132
- if (!requestUrl) {
133
- return fallbackPath;
134
- }
135
- if (requestUrl.startsWith("http://") || requestUrl.startsWith("https://")) {
136
- try {
137
- return new URL(requestUrl).pathname || fallbackPath;
138
- } catch {
139
- return fallbackPath;
140
- }
141
- }
142
- if (requestUrl.startsWith("/")) {
143
- const queryIndex = requestUrl.indexOf("?");
144
- return queryIndex >= 0 ? requestUrl.slice(0, queryIndex) : requestUrl;
145
- }
146
- try {
147
- return new URL(requestUrl, "http://localhost").pathname || fallbackPath;
148
- } catch {
149
- return fallbackPath;
150
- }
151
- }
152
- function createRequestLike(method, url, headers) {
153
- return { method, url, headers };
154
- }
155
- function buildClientDetails(request, fallbackPath) {
156
- const pathname = fallbackPath ?? extractPathname(request.url);
157
- const urlObject = (() => {
158
- try {
159
- return new URL(request.url);
160
- } catch {
161
- try {
162
- return new URL(pathname, "http://localhost");
163
- } catch {
164
- return null;
165
- }
166
- }
167
- })();
168
- const hostHeader = getHeaderValue(request.headers, "x-forwarded-host") ?? getHeaderValue(request.headers, "host") ?? urlObject?.host ?? void 0;
169
- const hostname = hostHeader ? stripPort(hostHeader) : urlObject?.hostname;
170
- const port = hostHeader?.match(/:(\d+)$/)?.[1] ?? (urlObject?.port || void 0);
171
- const xForwardedFor = parseForwardedFor(getHeaderValue(request.headers, "x-forwarded-for"));
172
- const forwardedFor = parseForwardedHeader(getHeaderValue(request.headers, "forwarded"));
173
- const ipCandidates = [
174
- getHeaderValue(request.headers, "cf-connecting-ip"),
175
- getHeaderValue(request.headers, "true-client-ip"),
176
- getHeaderValue(request.headers, "fly-client-ip"),
177
- getHeaderValue(request.headers, "x-real-ip"),
178
- getHeaderValue(request.headers, "x-client-ip"),
179
- xForwardedFor[0],
180
- forwardedFor[0]
181
- ].filter((value) => Boolean(value));
182
- const userAgent = getHeaderValue(request.headers, "user-agent");
183
- const platform = getHeaderValue(request.headers, "sec-ch-ua-platform")?.replace(/^"|"$/g, "") ?? void 0;
184
- const deviceType = detectDeviceType(userAgent ?? "");
185
- return {
186
- hostname,
187
- ip: ipCandidates[0],
188
- forwardedFor: [...xForwardedFor, ...forwardedFor].filter((value, index, values) => {
189
- return values.indexOf(value) === index;
190
- }),
191
- protocol: getHeaderValue(request.headers, "x-forwarded-proto") ?? (urlObject?.protocol ? urlObject.protocol.replace(/:$/, "") : void 0),
192
- port,
193
- userAgent,
194
- origin: getHeaderValue(request.headers, "origin"),
195
- referer: getHeaderValue(request.headers, "referer"),
196
- acceptLanguage: getHeaderValue(request.headers, "accept-language"),
197
- client: {
198
- ip: ipCandidates[0],
199
- hostname,
200
- browser: userAgent ? detectBrowser(userAgent) : void 0,
201
- os: userAgent ? detectOperatingSystem(userAgent) : void 0,
202
- deviceType,
203
- platform,
204
- isMobile: deviceType === "mobile"
205
- }
206
- };
207
- }
208
- function buildRequestLogData(request, type, path3, statusCode, responseTime, extra = {}) {
209
- return {
210
- type,
211
- method: request.method,
212
- url: path3,
213
- statusCode,
214
- responseTime,
215
- ...buildClientDetails(request, path3),
216
- ...extra
217
- };
218
- }
219
- function buildInfoLogMessage(method, statusCode, url, responseTime) {
220
- const methodColor = getMethodColor(method);
221
- const statusColor = getStatusColor(statusCode);
222
- const timeColor = getResponseTimeColor(responseTime);
223
- const arrow = getArrowForMethod(method);
224
- return `${methodColor} ${arrow} ${statusColor} ${url} ${timeColor}`;
225
- }
226
- function toErrorLike(error, fallbackStatusCode) {
227
- if (error === void 0 || error === null) {
228
- return fallbackStatusCode === void 0 ? void 0 : { statusCode: fallbackStatusCode, message: `HTTP ${fallbackStatusCode}` };
229
- }
230
- if (error instanceof Error) {
231
- const errorWithStatus = error;
232
- return {
233
- status: errorWithStatus.status,
234
- statusCode: errorWithStatus.statusCode ?? fallbackStatusCode,
235
- code: errorWithStatus.code,
236
- message: error.message,
237
- stack: error.stack,
238
- why: errorWithStatus.why,
239
- fix: errorWithStatus.fix,
240
- link: errorWithStatus.link,
241
- details: errorWithStatus.details,
242
- cause: errorWithStatus.cause
243
- };
244
- }
245
- if (typeof error === "object") {
246
- const record = error;
247
- return {
248
- status: typeof record.status === "number" ? record.status : void 0,
249
- statusCode: typeof record.statusCode === "number" ? record.statusCode : fallbackStatusCode,
250
- code: typeof record.code === "string" || typeof record.code === "number" ? record.code : void 0,
251
- message: typeof record.message === "string" ? record.message : `HTTP ${fallbackStatusCode ?? 500}`,
252
- stack: typeof record.stack === "string" ? record.stack : void 0,
253
- why: typeof record.why === "string" ? record.why : void 0,
254
- fix: typeof record.fix === "string" ? record.fix : void 0,
255
- link: typeof record.link === "string" ? record.link : void 0,
256
- details: record.details !== null && typeof record.details === "object" && !Array.isArray(record.details) ? record.details : void 0,
257
- cause: record.cause
258
- };
259
- }
260
- return {
261
- statusCode: fallbackStatusCode,
262
- message: typeof error === "string" ? error : `HTTP ${fallbackStatusCode ?? 500}`
263
- };
264
- }
265
- function isErrorStatus(statusCode) {
266
- return statusCode >= 400;
267
- }
268
-
269
- // src/shared/log-value.ts
270
- function normalizeError(error) {
271
- const normalized = {
272
- name: error.name,
273
- message: error.message
274
- };
275
- if (error.stack) {
276
- normalized.stack = error.stack;
277
- }
278
- const errorWithCause = error;
279
- if (errorWithCause.cause !== void 0) {
280
- normalized.cause = normalizeLogValue(errorWithCause.cause);
281
- }
282
- return normalized;
283
- }
284
- function normalizeLogValue(value, seen = /* @__PURE__ */ new WeakSet()) {
285
- if (value instanceof Error) {
286
- return normalizeError(value);
287
- }
288
- if (typeof value === "function") {
289
- return `[Function: ${value.name || "anonymous"}]`;
290
- }
291
- if (typeof value === "symbol") {
292
- return value.toString();
293
- }
294
- if (value === void 0 || value === null) {
295
- return value;
296
- }
297
- if (Array.isArray(value)) {
298
- return value.map((entry) => normalizeLogValue(entry, seen));
299
- }
300
- if (typeof value === "object") {
301
- if (seen.has(value)) {
302
- return "[Circular]";
303
- }
304
- seen.add(value);
305
- const normalized = {};
306
- for (const [key, entry] of Object.entries(value)) {
307
- normalized[key] = normalizeLogValue(entry, seen);
308
- }
309
- seen.delete(value);
310
- return normalized;
311
- }
312
- return value;
313
- }
314
- function serializeLogMessage(message) {
315
- if (typeof message === "string") {
316
- return message;
317
- }
318
- if (message instanceof Error) {
319
- return message.message || message.name;
320
- }
321
- const normalized = normalizeLogValue(message);
322
- if (typeof normalized === "string") {
323
- return normalized;
324
- }
325
- try {
326
- const serialized = JSON.stringify(normalized, null, 2);
327
- return serialized ?? String(normalized);
328
- } catch {
329
- return String(normalized);
330
- }
331
- }
332
- var absoluteHttpUrlSchema = z.string().url().refine((value) => {
333
- try {
334
- const url = new URL(value);
335
- return url.protocol === "http:" || url.protocol === "https:";
336
- } catch {
337
- return false;
338
- }
339
- }, {
340
- message: "Expected an absolute http(s) URL"
341
- });
342
- var plainObjectSchema = z.custom(
343
- (value) => {
344
- return value !== null && typeof value === "object" && !Array.isArray(value);
345
- },
346
- {
347
- message: "Expected a plain object"
348
- }
349
- );
350
- var nonEmptyStringSchema = z.string().trim().min(1);
351
- function isAbsoluteHttpUrl(value) {
352
- return absoluteHttpUrlSchema.safeParse(value).success;
353
- }
354
- function isPlainObject(value) {
355
- return plainObjectSchema.safeParse(value).success;
356
- }
357
- function hasNonEmptyString(value) {
358
- return nonEmptyStringSchema.safeParse(value).success;
359
- }
360
-
361
- // src/shared/client-log.ts
362
- var DEFAULT_CLIENT_LOG_ENDPOINT = "/inngest";
363
- var CLIENT_LOG_LEVELS = [
364
- "debug",
365
- "info",
366
- "warning",
367
- "error",
368
- "critical",
369
- "success",
370
- "table"
371
- ];
372
- var clientConnectorRequestSchema = z.union([
373
- z.literal("betterstack"),
374
- z.literal("posthog"),
375
- z.literal("sentry"),
376
- z.undefined(),
377
- z.object({
378
- type: z.literal("otlp"),
379
- name: nonEmptyStringSchema
380
- })
381
- ]);
382
- function isClientLogLevel(value) {
383
- return typeof value === "string" && CLIENT_LOG_LEVELS.includes(value);
384
- }
385
- function isClientConnectorRequest(value) {
386
- return clientConnectorRequestSchema.safeParse(value).success;
387
- }
388
- function isClientLogEvent(payload) {
389
- if (!isPlainObject(payload)) {
390
- return false;
391
- }
392
- if (payload.type !== "client_log" || payload.source !== "client" || !isClientLogLevel(payload.level) || typeof payload.id !== "string" || typeof payload.message !== "string" || typeof payload.clientTimestamp !== "string") {
393
- return false;
394
- }
395
- const pageResult = plainObjectSchema.safeParse(payload.page);
396
- const browserResult = plainObjectSchema.safeParse(payload.browser);
397
- const sessionResult = plainObjectSchema.safeParse(payload.session);
398
- if (!pageResult.success || !browserResult.success || !sessionResult.success) {
399
- return false;
400
- }
401
- if (!isClientConnectorRequest(payload.connector)) {
402
- return false;
403
- }
404
- return typeof sessionResult.data.pageId === "string" && typeof sessionResult.data.sessionId === "string";
405
- }
406
- function normalizeEndpointPath(path3) {
407
- if (!path3) {
408
- return DEFAULT_CLIENT_LOG_ENDPOINT;
409
- }
410
- return path3.startsWith("/") ? path3 : `/${path3}`;
411
- }
412
-
413
- // src/shared/once.ts
414
- function createConsoleOnceLogger(method, warnedKeys6 = /* @__PURE__ */ new Set()) {
415
- return (key, message, error) => {
416
- if (warnedKeys6.has(key) || typeof console === "undefined") {
417
- return;
418
- }
419
- const writer = console[method];
420
- if (typeof writer !== "function") {
421
- return;
422
- }
423
- warnedKeys6.add(key);
424
- if (error === void 0) {
425
- writer.call(console, message);
426
- return;
427
- }
428
- writer.call(console, message, error);
429
- };
430
- }
431
- function createWarnOnceLogger(warnedKeys6) {
432
- return createConsoleOnceLogger("warn", warnedKeys6);
433
- }
434
- function createErrorOnceLogger(warnedKeys6) {
435
- return createConsoleOnceLogger("error", warnedKeys6);
436
- }
437
-
438
- // src/core/config.ts
439
- var PACKAGE_NAME = "@blyp/core";
440
- var GITIGNORE_FILE_NAME = ".gitignore";
441
- var CONFIG_FILE_NAMES = [
442
- "blyp.config.ts",
443
- "blyp.config.mts",
444
- "blyp.config.cts",
445
- "blyp.config.js",
446
- "blyp.config.mjs",
447
- "blyp.config.cjs",
448
- "blyp.config.json"
449
- ];
450
- var CONFIG_FILE_NAME = "blyp.config.json";
451
- var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
452
- var DEFAULT_CONNECTOR_SERVICE_NAME = "blyp-app";
453
- var DEFAULT_POSTHOG_SERVICE_NAME = DEFAULT_CONNECTOR_SERVICE_NAME;
454
- var warnedKeys = /* @__PURE__ */ new Set();
455
- var warnOnce = createWarnOnceLogger(warnedKeys);
456
- var DEFAULT_ROTATION_CONFIG = {
457
- enabled: true,
458
- maxSizeBytes: 10 * 1024 * 1024,
459
- maxArchives: 5,
460
- compress: true
461
- };
462
- var DEFAULT_FILE_CONFIG = {
463
- enabled: true,
464
- dir: "",
465
- archiveDir: "",
466
- format: "ndjson",
467
- rotation: DEFAULT_ROTATION_CONFIG
468
- };
469
- var DEFAULT_CLIENT_LOGGING_CONFIG = {
470
- enabled: true,
471
- path: DEFAULT_CLIENT_LOG_ENDPOINT
472
- };
473
- var DEFAULT_DATABASE_RETRY_CONFIG = {
474
- maxRetries: 1,
475
- backoffMs: 100
476
- };
477
- var DEFAULT_DATABASE_DELIVERY_CONFIG = {
478
- strategy: "immediate",
479
- batchSize: 1,
480
- flushIntervalMs: 250,
481
- maxQueueSize: 1e3,
482
- overflowStrategy: "drop-oldest",
483
- flushTimeoutMs: 5e3,
484
- retry: DEFAULT_DATABASE_RETRY_CONFIG
485
- };
486
- var DEFAULT_CONFIG = {
487
- pretty: true,
488
- level: "info",
489
- destination: "file",
490
- file: DEFAULT_FILE_CONFIG,
491
- clientLogging: DEFAULT_CLIENT_LOGGING_CONFIG,
492
- connectors: {}
493
- };
494
- var cachedConfig = null;
495
- function findNearestPackageName(startDir) {
496
- let currentDir = startDir;
497
- while (true) {
498
- const packageJsonPath = resolve(currentDir, "package.json");
499
- if (existsSync(packageJsonPath)) {
500
- try {
501
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
502
- if (hasNonEmptyString(packageJson.name)) {
503
- return packageJson.name;
504
- }
505
- } catch {
506
- }
507
- }
508
- const parentDir = dirname(currentDir);
509
- if (parentDir === currentDir) {
510
- return void 0;
511
- }
512
- currentDir = parentDir;
513
- }
514
- }
515
- function resolveDefaultConnectorServiceName(cwd = process.cwd()) {
516
- return findNearestPackageName(cwd) ?? DEFAULT_POSTHOG_SERVICE_NAME;
517
- }
518
- function getBootstrapConfig() {
519
- return {
520
- pretty: true,
521
- level: "info",
522
- destination: "file",
523
- file: {
524
- enabled: true,
525
- format: "ndjson",
526
- rotation: {
527
- enabled: true,
528
- maxSizeBytes: 10 * 1024 * 1024,
529
- maxArchives: 5,
530
- compress: true
531
- }
532
- },
533
- clientLogging: {
534
- enabled: true,
535
- path: DEFAULT_CLIENT_LOG_ENDPOINT
536
- },
537
- connectors: {}
538
- };
539
- }
540
- function shouldBootstrapProjectFiles(cwd) {
541
- const packageJsonPath = resolve(cwd, "package.json");
542
- if (!existsSync(packageJsonPath)) {
543
- return true;
544
- }
545
- try {
546
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
547
- return packageJson.name !== PACKAGE_NAME;
548
- } catch {
549
- return true;
550
- }
551
- }
552
- function ensureConfigFile(cwd) {
553
- if (CONFIG_FILE_NAMES.some((fileName) => existsSync(resolve(cwd, fileName)))) {
554
- return;
555
- }
556
- const configPath = resolve(cwd, CONFIG_FILE_NAME);
557
- if (existsSync(configPath)) {
558
- return;
559
- }
560
- try {
561
- writeFileSync(configPath, `${JSON.stringify(getBootstrapConfig(), null, 2)}
562
- `);
563
- } catch (error) {
564
- console.error("[Blyp] Warning: Failed to create blyp.config.json:", error);
565
- }
566
- }
567
- function ensureLogsIgnored(cwd) {
568
- const gitignorePath = resolve(cwd, GITIGNORE_FILE_NAME);
569
- if (!existsSync(gitignorePath)) {
570
- try {
571
- writeFileSync(gitignorePath, "logs\n");
572
- } catch (error) {
573
- console.error("[Blyp] Warning: Failed to create .gitignore:", error);
574
- }
575
- return;
576
- }
577
- try {
578
- const currentContent = readFileSync(gitignorePath, "utf-8");
579
- if (/^(?:\/?logs\/?)\s*$/m.test(currentContent)) {
580
- return;
581
- }
582
- const separator = currentContent.endsWith("\n") ? "" : "\n";
583
- appendFileSync(gitignorePath, `${separator}logs
584
- `);
585
- } catch (error) {
586
- console.error("[Blyp] Warning: Failed to update .gitignore:", error);
587
- }
588
- }
589
- function bootstrapProjectFiles() {
590
- const cwd = process.cwd();
591
- if (!shouldBootstrapProjectFiles(cwd)) {
592
- return;
593
- }
594
- ensureConfigFile(cwd);
595
- ensureLogsIgnored(cwd);
596
- }
597
- function findConfigFile() {
598
- const cwd = process.cwd();
599
- const matches = CONFIG_FILE_NAMES.map((fileName) => resolve(cwd, fileName)).filter((filePath) => existsSync(filePath));
600
- if (matches.length === 0) {
601
- return null;
602
- }
603
- if (matches.length > 1) {
604
- const preferred = matches[0];
605
- warnOnce(
606
- `config-multiple:${preferred}`,
607
- `[Blyp] Warning: Multiple config files found. Using ${preferred} and ignoring ${matches.slice(1).join(", ")}.`
608
- );
609
- }
610
- const selectedPath = matches[0];
611
- return {
612
- path: selectedPath,
613
- type: selectedPath.endsWith(".json") ? "json" : "jiti"
614
- };
615
- }
616
- function normalizeLoadedConfig(value, configPath) {
617
- const normalized = value && typeof value === "object" && "default" in value && value.default !== void 0 ? value.default : value;
618
- if (!normalized || typeof normalized !== "object" || Array.isArray(normalized)) {
619
- warnOnce(
620
- `config-invalid:${configPath}`,
621
- `[Blyp] Warning: Config file ${configPath} did not export an object. Falling back to defaults.`
622
- );
623
- return {};
624
- }
625
- return normalized;
626
- }
627
- function parseJsonConfigFile(configPath) {
628
- try {
629
- const content = readFileSync(configPath, "utf-8");
630
- return normalizeLoadedConfig(JSON.parse(content), configPath);
631
- } catch (error) {
632
- console.error("[Blyp] Warning: Failed to parse blyp.config.json:", error);
633
- return {};
634
- }
635
- }
636
- function parseExecutableConfigFile(configPath) {
637
- try {
638
- const jiti = createJiti(process.cwd(), {
639
- interopDefault: true,
640
- moduleCache: false,
641
- fsCache: false
642
- });
643
- return normalizeLoadedConfig(jiti(configPath), configPath);
644
- } catch (error) {
645
- console.error(`[Blyp] Warning: Failed to load ${configPath}:`, error);
646
- return {};
647
- }
648
- }
649
- function parseConfigFile(config) {
650
- return config.type === "json" ? parseJsonConfigFile(config.path) : parseExecutableConfigFile(config.path);
651
- }
652
- function isPrismaAdapter(value) {
653
- return !!value && typeof value === "object" && value.type === "prisma";
654
- }
655
- function isDrizzleAdapter(value) {
656
- return !!value && typeof value === "object" && value.type === "drizzle";
657
- }
658
- function mergeDatabaseRetryConfig(base, override) {
659
- return {
660
- ...DEFAULT_DATABASE_RETRY_CONFIG,
661
- ...base,
662
- ...override
663
- };
664
- }
665
- function mergeDatabaseDeliveryConfig(base, override) {
666
- return {
667
- ...DEFAULT_DATABASE_DELIVERY_CONFIG,
668
- ...base,
669
- ...override,
670
- retry: mergeDatabaseRetryConfig(base?.retry, override?.retry)
671
- };
672
- }
673
- function hasPrismaDelegate(adapter) {
674
- const model = adapter.model ?? "blypLog";
675
- const client = adapter.client;
676
- const delegate = client?.[model];
677
- return !!delegate && typeof delegate.create === "function";
678
- }
679
- function hasDrizzleAdapterShape(adapter) {
680
- const db = adapter.db;
681
- return !!db && typeof db.insert === "function" && adapter.table !== void 0;
682
- }
683
- function resolveDatabaseLoggerConfig(config, sourceType) {
684
- if (!config) {
685
- return void 0;
686
- }
687
- const adapter = config.adapter;
688
- let ready = false;
689
- if (sourceType === "json") {
690
- warnOnce(
691
- "database-json-config",
692
- "[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."
693
- );
694
- } else if (config.dialect !== "postgres" && config.dialect !== "mysql") {
695
- warnOnce(
696
- `database-dialect:${String(config.dialect)}`,
697
- `[Blyp] Warning: Unsupported database dialect "${String(config.dialect)}". Database logging is disabled.`
698
- );
699
- } else if (!adapter) {
700
- warnOnce(
701
- "database-adapter-missing",
702
- "[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled."
703
- );
704
- } else if (isPrismaAdapter(adapter)) {
705
- ready = hasPrismaDelegate({
706
- ...adapter,
707
- model: adapter.model ?? "blypLog"
708
- });
709
- if (!ready) {
710
- warnOnce(
711
- "database-prisma-missing",
712
- `[Blyp] Warning: Prisma database adapter is missing the "${adapter.model ?? "blypLog"}" delegate or its create method. Database logging is disabled.`
713
- );
714
- }
715
- } else if (isDrizzleAdapter(adapter)) {
716
- ready = hasDrizzleAdapterShape(adapter);
717
- if (!ready) {
718
- warnOnce(
719
- "database-drizzle-missing",
720
- "[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled."
721
- );
722
- }
723
- }
724
- const normalizedAdapter = isPrismaAdapter(adapter) ? {
725
- ...adapter,
726
- model: adapter.model ?? "blypLog"
727
- } : adapter;
728
- return {
729
- dialect: config.dialect,
730
- adapter: normalizedAdapter,
731
- delivery: mergeDatabaseDeliveryConfig(void 0, config.delivery),
732
- ready,
733
- status: ready ? "enabled" : "missing"
734
- };
735
- }
736
- function mergeRotationConfig(base, override) {
737
- return {
738
- ...DEFAULT_ROTATION_CONFIG,
739
- ...base,
740
- ...override
741
- };
742
- }
743
- function mergeFileConfig(base, override) {
744
- return {
745
- ...DEFAULT_FILE_CONFIG,
746
- ...base,
747
- ...override,
748
- rotation: mergeRotationConfig(base?.rotation, override?.rotation)
749
- };
750
- }
751
- function mergeClientLoggingConfig(base, override) {
752
- return {
753
- ...DEFAULT_CLIENT_LOGGING_CONFIG,
754
- ...base,
755
- ...override,
756
- path: override?.path ?? base?.path ?? DEFAULT_CLIENT_LOGGING_CONFIG.path
757
- };
758
- }
759
- function mergeDatabaseLoggerConfig(base, override, sourceType) {
760
- if (!base && !override) {
761
- return void 0;
762
- }
763
- return resolveDatabaseLoggerConfig(
764
- {
765
- dialect: override?.dialect ?? base?.dialect,
766
- adapter: override?.adapter ?? base?.adapter,
767
- delivery: {
768
- ...base?.delivery ?? {},
769
- ...override?.delivery ?? {},
770
- retry: {
771
- ...base?.delivery?.retry ?? {},
772
- ...override?.delivery?.retry ?? {}
773
- }
774
- }
775
- },
776
- sourceType
777
- );
778
- }
779
- function mergePostHogConnectorConfig(base, override) {
780
- const enabled = override?.enabled ?? base?.enabled ?? false;
781
- const projectKey = override?.projectKey ?? base?.projectKey;
782
- const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
783
- const errorTrackingMode = override?.errorTracking?.mode ?? baseErrorTracking?.mode ?? "auto";
784
- const errorTrackingEnabled = override?.errorTracking?.enabled ?? baseErrorTracking?.enabled ?? enabled;
785
- const errorTrackingReady = enabled && errorTrackingEnabled && typeof projectKey === "string" && projectKey.trim().length > 0;
786
- return {
787
- enabled,
788
- mode: override?.mode ?? base?.mode ?? "auto",
789
- projectKey,
790
- host: override?.host ?? base?.host ?? DEFAULT_POSTHOG_HOST,
791
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
792
- errorTracking: {
793
- enabled: errorTrackingEnabled,
794
- mode: errorTrackingMode,
795
- enableExceptionAutocapture: override?.errorTracking?.enableExceptionAutocapture ?? baseErrorTracking?.enableExceptionAutocapture ?? errorTrackingMode === "auto",
796
- ready: errorTrackingReady,
797
- status: errorTrackingReady ? "enabled" : "missing"
798
- }
799
- };
800
- }
801
- function mergeBetterStackConnectorConfig(base, override) {
802
- const sourceToken = override?.sourceToken ?? base?.sourceToken;
803
- const ingestingHost = override?.ingestingHost ?? base?.ingestingHost;
804
- const enabled = override?.enabled ?? base?.enabled ?? false;
805
- const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
806
- const errorTracking = mergeBetterStackErrorTrackingConfig(
807
- enabled,
808
- baseErrorTracking,
809
- override?.errorTracking
810
- );
811
- const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
812
- return {
813
- enabled,
814
- mode: override?.mode ?? base?.mode ?? "auto",
815
- sourceToken,
816
- ingestingHost,
817
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
818
- errorTracking,
819
- ready,
820
- status: ready ? "enabled" : "missing"
821
- };
822
- }
823
- function mergeBetterStackErrorTrackingConfig(connectorEnabled, base, override) {
824
- const dsn = override?.dsn ?? base?.dsn;
825
- const enabled = override?.enabled ?? base?.enabled ?? connectorEnabled;
826
- const ready = enabled && hasNonEmptyString(dsn);
827
- return {
828
- enabled,
829
- dsn,
830
- tracesSampleRate: override?.tracesSampleRate ?? base?.tracesSampleRate ?? 1,
831
- environment: override?.environment ?? base?.environment,
832
- release: override?.release ?? base?.release,
833
- ready,
834
- status: ready ? "enabled" : "missing"
835
- };
836
- }
837
- function mergeSentryConnectorConfig(base, override) {
838
- const dsn = override?.dsn ?? base?.dsn;
839
- const enabled = override?.enabled ?? base?.enabled ?? false;
840
- const ready = enabled && typeof dsn === "string" && dsn.trim().length > 0;
841
- return {
842
- enabled,
843
- mode: override?.mode ?? base?.mode ?? "auto",
844
- dsn,
845
- environment: override?.environment ?? base?.environment,
846
- release: override?.release ?? base?.release,
847
- ready,
848
- status: ready ? "enabled" : "missing"
849
- };
850
- }
851
- function mergeOTLPConnectorConfig(base, override) {
852
- const endpoint = override?.endpoint ?? base?.endpoint;
853
- const enabled = override?.enabled ?? base?.enabled ?? false;
854
- const resolvedHeaders = {
855
- ...{},
856
- ...override?.headers ?? {}
857
- };
858
- const ready = enabled && isAbsoluteHttpUrl(endpoint);
859
- return {
860
- name: override?.name ?? base?.name ?? "",
861
- enabled,
862
- mode: override?.mode ?? base?.mode ?? "auto",
863
- endpoint,
864
- headers: resolvedHeaders,
865
- auth: override?.auth ?? base?.auth,
866
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
867
- ready,
868
- status: ready ? "enabled" : "missing"
869
- };
870
- }
871
- function mergeOTLPConnectorsConfig(base, override) {
872
- const source = override ?? base ?? [];
873
- const deduped = /* @__PURE__ */ new Map();
874
- for (const connector of source) {
875
- if (!connector || typeof connector.name !== "string" || connector.name.length === 0) {
876
- continue;
877
- }
878
- if (deduped.has(connector.name)) {
879
- warnOnce(
880
- `otlp-duplicate:${connector.name}`,
881
- `[Blyp] Warning: Duplicate OTLP connector name "${connector.name}" found. Using the last definition.`
882
- );
883
- }
884
- deduped.set(connector.name, mergeOTLPConnectorConfig(void 0, connector));
885
- }
886
- return Array.from(deduped.values());
887
- }
888
- function mergeConnectorsConfig(base, override) {
889
- return {
890
- betterstack: mergeBetterStackConnectorConfig(base?.betterstack, override?.betterstack),
891
- posthog: mergePostHogConnectorConfig(base?.posthog, override?.posthog),
892
- sentry: mergeSentryConnectorConfig(base?.sentry, override?.sentry),
893
- otlp: mergeOTLPConnectorsConfig(base?.otlp, override?.otlp)
894
- };
895
- }
896
- function mergeBlypConfig(base, override = {}, options = {}) {
897
- return {
898
- ...base,
899
- ...override,
900
- destination: override.destination ?? base.destination ?? "file",
901
- file: mergeFileConfig(base.file, override.file),
902
- database: mergeDatabaseLoggerConfig(base.database, override.database, options.configFileType),
903
- clientLogging: mergeClientLoggingConfig(base.clientLogging, override.clientLogging),
904
- connectors: mergeConnectorsConfig(base.connectors, override.connectors)
905
- };
906
- }
907
- function loadConfig() {
908
- if (cachedConfig !== null) {
909
- return cachedConfig;
910
- }
911
- bootstrapProjectFiles();
912
- const configFile = findConfigFile();
913
- if (configFile) {
914
- const userConfig = parseConfigFile(configFile);
915
- cachedConfig = mergeBlypConfig(DEFAULT_CONFIG, userConfig, {
916
- configFileType: configFile.type
917
- });
918
- } else {
919
- cachedConfig = mergeBlypConfig(DEFAULT_CONFIG);
920
- }
921
- return cachedConfig;
922
- }
923
- function resolveConfig(overrides = {}) {
924
- return mergeBlypConfig(loadConfig(), overrides);
925
- }
926
-
927
- // src/core/helpers.ts
928
- function normalizePath(path3) {
929
- const queryIndex = path3.indexOf("?");
930
- let withoutQuery = queryIndex >= 0 ? path3.substring(0, queryIndex) : path3;
931
- if (withoutQuery.endsWith("/") && withoutQuery.length > 1) {
932
- withoutQuery = withoutQuery.slice(0, -1);
933
- }
934
- if (!withoutQuery.startsWith("/")) {
935
- withoutQuery = "/" + withoutQuery;
936
- }
937
- return withoutQuery;
938
- }
939
- function normalizePattern(pattern) {
940
- const queryIndex = pattern.indexOf("?");
941
- let withoutQuery = queryIndex >= 0 ? pattern.substring(0, queryIndex) : pattern;
942
- if (withoutQuery.endsWith("/") && withoutQuery.length > 1) {
943
- withoutQuery = withoutQuery.slice(0, -1);
944
- }
945
- if (!withoutQuery.startsWith("/")) {
946
- withoutQuery = "/" + withoutQuery;
947
- }
948
- return withoutQuery;
949
- }
950
- function shouldIgnorePath(path3, ignorePaths) {
951
- if (!ignorePaths || ignorePaths.length === 0) {
952
- return false;
953
- }
954
- const normalizedPath = normalizePath(path3);
955
- return ignorePaths.some((ignoredPattern) => {
956
- const normalizedPattern = normalizePattern(ignoredPattern);
957
- if (normalizedPattern === normalizedPath) {
958
- return true;
959
- }
960
- if (normalizedPattern === "/**" || normalizedPattern === "**") {
961
- return true;
962
- }
963
- if (normalizedPattern === "/*") {
964
- const segments = normalizedPath.split("/").filter((s) => s.length > 0);
965
- return segments.length === 1;
966
- }
967
- if (normalizedPattern.endsWith("/*") && !normalizedPattern.includes("**")) {
968
- const prefix = normalizedPattern.slice(0, -1);
969
- if (normalizedPath.startsWith(prefix)) {
970
- const rest = normalizedPath.slice(prefix.length);
971
- const restSegments = rest.split("/").filter((s) => s.length > 0);
972
- return restSegments.length === 1;
973
- }
974
- return false;
975
- }
976
- if (normalizedPattern.includes("**")) {
977
- if (normalizedPattern === "/**") {
978
- return true;
979
- }
980
- if (normalizedPattern.startsWith("/") && normalizedPattern.endsWith("**")) {
981
- let prefix2 = normalizedPattern.slice(0, -2);
982
- if (prefix2.endsWith("/") && prefix2.length > 1) {
983
- prefix2 = prefix2.slice(0, -1);
984
- }
985
- if (prefix2 === normalizedPath) {
986
- return true;
987
- }
988
- return normalizedPath.startsWith(prefix2 + "/");
989
- }
990
- const starIndex = normalizedPattern.indexOf("**");
991
- let prefix = normalizedPattern.substring(0, starIndex);
992
- const suffix = normalizedPattern.substring(starIndex + 2);
993
- if (prefix.endsWith("/") && prefix.length > 1) {
994
- prefix = prefix.slice(0, -1);
995
- }
996
- if (prefix === "" && suffix === "") {
997
- return true;
998
- }
999
- if (prefix !== "" && suffix === "") {
1000
- return normalizedPath.startsWith(prefix + "/");
1001
- }
1002
- if (prefix === "" && suffix !== "") {
1003
- return normalizedPath.endsWith(suffix) || normalizedPath.includes(suffix + "/");
1004
- }
1005
- if (prefix !== "" && suffix !== "") {
1006
- return normalizedPath.startsWith(prefix) && (normalizedPath.endsWith(suffix) || normalizedPath.includes(suffix + "/"));
1007
- }
1008
- return false;
1009
- }
1010
- if (normalizedPattern.includes("*")) {
1011
- const lastDotIndex = normalizedPattern.lastIndexOf(".");
1012
- const lastStarIndex = normalizedPattern.lastIndexOf("*");
1013
- if (lastDotIndex > lastStarIndex && lastStarIndex > 0) {
1014
- const charBeforeStar = normalizedPattern[lastStarIndex - 1];
1015
- if (charBeforeStar === "/") {
1016
- const extPattern = normalizedPattern.slice(lastStarIndex);
1017
- const filePart = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1);
1018
- const extIndex = filePart.lastIndexOf(".");
1019
- if (extIndex > 0) {
1020
- const actualExt = filePart.slice(extIndex);
1021
- return actualExt === extPattern;
1022
- }
1023
- }
1024
- }
1025
- const regexPattern = normalizedPattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*");
1026
- const regex = new RegExp("^" + regexPattern + "$");
1027
- return regex.test(normalizedPath);
1028
- }
1029
- return false;
1030
- });
1031
- }
1032
- function gzipBuffer(buf) {
1033
- return Buffer.from(gzipSync(buf));
1034
- }
1035
- function warnWithConsole(message, error) {
1036
- console.warn(`[Blyp] Warning: ${message}`, error);
1037
- }
1038
- function ensureDirectory(dirPath) {
1039
- fs.mkdirSync(dirPath, { recursive: true });
1040
- }
1041
- function getFileSize(filePath) {
1042
- try {
1043
- return fs.statSync(filePath).size;
1044
- } catch {
1045
- return 0;
1046
- }
1047
- }
1048
- function formatArchiveTimestamp(timestamp) {
1049
- const year = timestamp.getUTCFullYear();
1050
- const month = String(timestamp.getUTCMonth() + 1).padStart(2, "0");
1051
- const day = String(timestamp.getUTCDate()).padStart(2, "0");
1052
- const hours = String(timestamp.getUTCHours()).padStart(2, "0");
1053
- const minutes = String(timestamp.getUTCMinutes()).padStart(2, "0");
1054
- const seconds = String(timestamp.getUTCSeconds()).padStart(2, "0");
1055
- return `${year}${month}${day}T${hours}${minutes}${seconds}Z`;
1056
- }
1057
- function getUniqueArchivePath(basePath, extension) {
1058
- let candidate = `${basePath}${extension}`;
1059
- let suffix = 1;
1060
- while (fs.existsSync(candidate)) {
1061
- candidate = `${basePath}-${suffix}${extension}`;
1062
- suffix += 1;
1063
- }
1064
- return candidate;
1065
- }
1066
- function pruneArchives(archiveDir, archivePrefix, maxArchives, warn) {
1067
- const prefix = `${archivePrefix}.`;
1068
- try {
1069
- const archivePaths = fs.readdirSync(archiveDir).filter(
1070
- (name) => name.startsWith(prefix) && (name.endsWith(".ndjson") || name.endsWith(".ndjson.gz"))
1071
- ).map((name) => path.join(archiveDir, name)).sort((left, right) => {
1072
- return fs.statSync(left).mtimeMs - fs.statSync(right).mtimeMs;
1073
- });
1074
- const deleteCount = Math.max(archivePaths.length - maxArchives, 0);
1075
- for (let index = 0; index < deleteCount; index += 1) {
1076
- fs.rmSync(archivePaths[index]);
1077
- }
1078
- } catch (error) {
1079
- warn(`Failed to prune archives for ${archivePrefix}`, error);
1080
- }
1081
- }
1082
- function createSafeReplacer() {
1083
- const seen = /* @__PURE__ */ new WeakSet();
1084
- return (_key, value) => {
1085
- if (typeof value === "function") {
1086
- return `[Function: ${value.name || "anonymous"}]`;
1087
- }
1088
- if (value === void 0) {
1089
- return "[undefined]";
1090
- }
1091
- if (typeof value === "symbol") {
1092
- return value.toString();
1093
- }
1094
- if (value !== null && typeof value === "object") {
1095
- if (seen.has(value)) {
1096
- return "[Circular]";
1097
- }
1098
- seen.add(value);
1099
- }
1100
- return value;
1101
- };
1102
- }
1103
- function serializeLogRecord(record) {
1104
- return JSON.stringify(record, createSafeReplacer());
1105
- }
1106
- function resolveFileLoggerConfig(config) {
1107
- const fileConfig = config.file;
1108
- const dir = fileConfig?.dir || config.logDir || path.join(process.cwd(), "logs");
1109
- const archiveDir = fileConfig?.archiveDir || path.join(dir, "archive");
1110
- const rotation = fileConfig?.rotation;
1111
- return {
1112
- enabled: fileConfig?.enabled ?? true,
1113
- dir,
1114
- archiveDir,
1115
- rotationEnabled: rotation?.enabled ?? true,
1116
- maxSizeBytes: rotation?.maxSizeBytes ?? 10 * 1024 * 1024,
1117
- maxArchives: rotation?.maxArchives ?? 5,
1118
- compress: rotation?.compress ?? true
1119
- };
1120
- }
1121
- var RotatingFileLogger = class {
1122
- constructor(config, dependencies = {}) {
1123
- __publicField(this, "config");
1124
- __publicField(this, "gzip");
1125
- __publicField(this, "warn");
1126
- __publicField(this, "combined");
1127
- __publicField(this, "error");
1128
- this.config = resolveFileLoggerConfig(config);
1129
- this.gzip = dependencies.gzip ?? gzipBuffer;
1130
- this.warn = dependencies.warn ?? warnWithConsole;
1131
- this.combined = {
1132
- activePath: path.join(this.config.dir, "log.ndjson"),
1133
- archivePrefix: "log",
1134
- bytes: 0,
1135
- queue: [],
1136
- processing: false
1137
- };
1138
- this.error = {
1139
- activePath: path.join(this.config.dir, "log.error.ndjson"),
1140
- archivePrefix: "log.error",
1141
- bytes: 0,
1142
- queue: [],
1143
- processing: false
1144
- };
1145
- if (!this.config.enabled) {
1146
- return;
1147
- }
1148
- ensureDirectory(this.config.dir);
1149
- ensureDirectory(this.config.archiveDir);
1150
- this.seedStream(this.combined);
1151
- this.seedStream(this.error);
1152
- }
1153
- write(record) {
1154
- if (!this.config.enabled) {
1155
- return;
1156
- }
1157
- const line = `${serializeLogRecord(record)}
1158
- `;
1159
- this.enqueue(this.combined, line);
1160
- if (record.level === "error" || record.level === "critical") {
1161
- this.enqueue(this.error, line);
1162
- }
1163
- }
1164
- enqueue(stream, line) {
1165
- stream.queue.push(line);
1166
- this.processQueue(stream);
1167
- }
1168
- processQueue(stream) {
1169
- if (stream.processing) {
1170
- return;
1171
- }
1172
- stream.processing = true;
1173
- try {
1174
- while (stream.queue.length > 0) {
1175
- const queuedLine = stream.queue.shift();
1176
- if (queuedLine === void 0) {
1177
- continue;
1178
- }
1179
- try {
1180
- this.append(stream, queuedLine);
1181
- } catch (error) {
1182
- this.warn(`Failed writing log line for ${stream.archivePrefix}`, error);
1183
- }
1184
- }
1185
- } finally {
1186
- stream.processing = false;
1187
- }
1188
- }
1189
- seedStream(stream) {
1190
- stream.bytes = getFileSize(stream.activePath);
1191
- if (this.config.rotationEnabled && stream.bytes > this.config.maxSizeBytes && stream.bytes > 0) {
1192
- this.rotate(stream);
1193
- fs.closeSync(fs.openSync(stream.activePath, "a"));
1194
- stream.bytes = 0;
1195
- }
1196
- }
1197
- append(stream, line) {
1198
- ensureDirectory(this.config.dir);
1199
- const lineBytes = Buffer.byteLength(line, "utf8");
1200
- if (this.config.rotationEnabled && stream.bytes > 0 && stream.bytes + lineBytes > this.config.maxSizeBytes) {
1201
- this.rotate(stream);
1202
- }
1203
- fs.appendFileSync(stream.activePath, line, "utf8");
1204
- stream.bytes += lineBytes;
1205
- }
1206
- rotate(stream) {
1207
- ensureDirectory(this.config.archiveDir);
1208
- if (!fs.existsSync(stream.activePath) || stream.bytes === 0) {
1209
- stream.bytes = 0;
1210
- return;
1211
- }
1212
- const archiveTimestamp = formatArchiveTimestamp(/* @__PURE__ */ new Date());
1213
- const archiveBasePath = path.join(
1214
- this.config.archiveDir,
1215
- `${stream.archivePrefix}.${archiveTimestamp}`
1216
- );
1217
- const archivePath = getUniqueArchivePath(archiveBasePath, ".ndjson");
1218
- fs.renameSync(stream.activePath, archivePath);
1219
- if (this.config.compress) {
1220
- try {
1221
- const compressedPath = `${archivePath}.gz`;
1222
- const gzipped = this.gzip(fs.readFileSync(archivePath));
1223
- fs.writeFileSync(compressedPath, gzipped);
1224
- fs.rmSync(archivePath);
1225
- } catch (error) {
1226
- this.warn(`Failed to gzip archive ${archivePath}`, error);
1227
- }
1228
- }
1229
- stream.bytes = 0;
1230
- pruneArchives(this.config.archiveDir, stream.archivePrefix, this.config.maxArchives, this.warn);
1231
- }
1232
- };
1233
- function createFileLogger(config) {
1234
- return new RotatingFileLogger(config);
1235
- }
1236
-
1237
- // src/connectors/shared.ts
1238
- function isBlypConfig(config) {
1239
- return isPlainObject(config) && ("connectors" in config || "pretty" in config || "level" in config);
1240
- }
1241
- function getPrimaryPayload(record) {
1242
- return isPlainObject(record.data) ? record.data : record;
1243
- }
1244
- function getField(record, key) {
1245
- if (key in record) {
1246
- const direct = record[key];
1247
- if (typeof direct === "string" || typeof direct === "number") {
1248
- return direct;
1249
- }
1250
- }
1251
- const payload = getPrimaryPayload(record);
1252
- const nested = payload[key];
1253
- if (typeof nested === "string" || typeof nested === "number") {
1254
- return nested;
1255
- }
1256
- return void 0;
1257
- }
1258
- function getClientPageField(record, key) {
1259
- const payload = getPrimaryPayload(record);
1260
- const page = isPlainObject(payload.page) ? payload.page : void 0;
1261
- const value = page?.[key];
1262
- return typeof value === "string" ? value : void 0;
1263
- }
1264
- function getClientSessionField(record, key) {
1265
- const payload = getPrimaryPayload(record);
1266
- const session = isPlainObject(payload.session) ? payload.session : void 0;
1267
- const value = session?.[key];
1268
- return typeof value === "string" ? value : void 0;
1269
- }
1270
- function getRecordType(record) {
1271
- return getField(record, "type");
1272
- }
1273
-
1274
- // src/connectors/posthog/sender.ts
1275
- var PREVIOUSLY_CAPTURED_ERROR_KEY = "__posthog_previously_captured_error";
1276
- var warnedKeys2 = /* @__PURE__ */ new Set();
1277
- var testHooks = {};
1278
- var warnOnce2 = createErrorOnceLogger(warnedKeys2);
1279
- function normalizeHost(host) {
1280
- const trimmed = (host || "https://us.i.posthog.com").trim();
1281
- return trimmed.replace(/\/+$/, "");
1282
- }
1283
- function buildRecordAttributes(record, source) {
1284
- const recordType = getRecordType(record);
1285
- const caller = typeof record.caller === "string" ? record.caller : void 0;
1286
- const groupId = getField(record, "groupId");
1287
- const method = getField(record, "method");
1288
- const path3 = getField(record, "path");
1289
- const status = getField(record, "status");
1290
- const duration = getField(record, "duration");
1291
- const pagePath = getClientPageField(record, "pathname");
1292
- const pageUrl = getClientPageField(record, "url");
1293
- const sessionId = getClientSessionField(record, "sessionId");
1294
- const pageId = getClientSessionField(record, "pageId");
1295
- const attributes = {
1296
- "blyp.level": record.level,
1297
- "blyp.source": source,
1298
- "blyp.payload": serializeLogRecord(record)
1299
- };
1300
- const ifTruthy = [
1301
- ["blyp.type", recordType],
1302
- ["blyp.caller", caller],
1303
- ["blyp.group_id", groupId],
1304
- ["http.method", method],
1305
- ["url.path", path3],
1306
- ["client.page_path", pagePath],
1307
- ["client.page_url", pageUrl],
1308
- ["client.session_id", sessionId],
1309
- ["client.page_id", pageId]
1310
- ];
1311
- const ifDefined = [
1312
- ["http.status_code", status],
1313
- ["blyp.duration_ms", duration]
1314
- ];
1315
- for (const [k, v] of ifTruthy) if (v) attributes[k] = v;
1316
- for (const [k, v] of ifDefined) if (v !== void 0) attributes[k] = v;
1317
- return attributes;
1318
- }
1319
- function normalizeExceptionProperties(value) {
1320
- if (!isPlainObject(value)) {
1321
- return {};
1322
- }
1323
- return normalizeLogValue(value);
1324
- }
1325
- function assignExceptionField(target, key, value) {
1326
- if (value === void 0) {
1327
- return;
1328
- }
1329
- try {
1330
- target[key] = value;
1331
- } catch {
1332
- }
1333
- }
1334
- function createSyntheticError(message, source) {
1335
- const error = new Error(message);
1336
- const name = hasNonEmptyString(source.name) ? source.name : "Error";
1337
- error.name = name;
1338
- if (hasNonEmptyString(source.stack)) {
1339
- error.stack = source.stack;
1340
- }
1341
- assignExceptionField(error, "cause", source.cause);
1342
- assignExceptionField(error, "status", source.status);
1343
- assignExceptionField(error, "statusCode", source.statusCode);
1344
- assignExceptionField(error, "code", source.code);
1345
- assignExceptionField(error, "why", source.why);
1346
- assignExceptionField(error, "fix", source.fix);
1347
- assignExceptionField(error, "link", source.link);
1348
- assignExceptionField(error, "details", source.details);
1349
- return error;
1350
- }
1351
- function normalizeExceptionInput(input, fallbackMessage = "Unknown error") {
1352
- if (input instanceof Error) {
1353
- return {
1354
- error: input,
1355
- properties: normalizeExceptionProperties(input)
1356
- };
1357
- }
1358
- if (isPlainObject(input)) {
1359
- const message = hasNonEmptyString(input.message) ? input.message : hasNonEmptyString(input.error) ? input.error : fallbackMessage;
1360
- return {
1361
- error: createSyntheticError(message, input),
1362
- properties: normalizeExceptionProperties(input)
1363
- };
1364
- }
1365
- if (typeof input === "string") {
1366
- return {
1367
- error: new Error(input),
1368
- properties: {
1369
- message: input
1370
- }
1371
- };
1372
- }
1373
- return {
1374
- error: new Error(fallbackMessage),
1375
- properties: {
1376
- value: normalizeLogValue(input)
1377
- }
1378
- };
1379
- }
1380
- function createExceptionPropertiesFromRecord(record, source) {
1381
- return buildRecordAttributes(record, source);
1382
- }
1383
- function isPreviouslyCapturedPostHogError(value) {
1384
- return isPlainObject(value) && value[PREVIOUSLY_CAPTURED_ERROR_KEY] === true;
1385
- }
1386
- function markPostHogCapturedError(value) {
1387
- if (!isPlainObject(value) || isPreviouslyCapturedPostHogError(value)) {
1388
- return;
1389
- }
1390
- try {
1391
- Object.defineProperty(value, PREVIOUSLY_CAPTURED_ERROR_KEY, {
1392
- value: true,
1393
- enumerable: false,
1394
- configurable: true,
1395
- writable: true
1396
- });
1397
- } catch {
1398
- try {
1399
- value[PREVIOUSLY_CAPTURED_ERROR_KEY] = true;
1400
- } catch {
1401
- }
1402
- }
1403
- }
1404
- function isClientLogRecord(record) {
1405
- return getRecordType(record) === "client_log";
1406
- }
1407
- function normalizePostHogRecord(record, connector, source = "server") {
1408
- const severity = resolveSeverity(record.level);
1409
- const body = typeof record.message === "string" ? record.message : String(record.message);
1410
- return {
1411
- body,
1412
- severityText: severity.text,
1413
- severityNumber: severity.number,
1414
- attributes: buildRecordAttributes(record, source),
1415
- resourceAttributes: {
1416
- "service.name": connector.serviceName
1417
- }
1418
- };
1419
- }
1420
- function resolveSeverity(level) {
1421
- switch (level) {
1422
- case "debug":
1423
- return { text: "debug", number: SeverityNumber.DEBUG };
1424
- case "warning":
1425
- case "warn":
1426
- return { text: "warn", number: SeverityNumber.WARN };
1427
- case "error":
1428
- return { text: "error", number: SeverityNumber.ERROR };
1429
- case "critical":
1430
- return { text: "fatal", number: SeverityNumber.FATAL };
1431
- case "success":
1432
- case "table":
1433
- case "info":
1434
- default:
1435
- return { text: "info", number: SeverityNumber.INFO };
1436
- }
1437
- }
1438
- function registerShutdownHooks(key, shutdown) {
1439
- const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
1440
- for (const event of handlers) {
1441
- process.once(event, () => {
1442
- void shutdown().catch((error) => {
1443
- warnOnce2(
1444
- `${key}:shutdown`,
1445
- "[Blyp] Failed to flush PostHog telemetry during shutdown.",
1446
- error
1447
- );
1448
- });
1449
- });
1450
- }
1451
- }
1452
- function createDefaultTransport(connector) {
1453
- const exporter = new OTLPLogExporter({
1454
- url: `${normalizeHost(connector.host)}/i/v1/logs`,
1455
- headers: {
1456
- Authorization: `Bearer ${connector.projectKey}`
1457
- }
1458
- });
1459
- const provider = new LoggerProvider({
1460
- resource: resourceFromAttributes({
1461
- "service.name": connector.serviceName
1462
- }),
1463
- processors: [new BatchLogRecordProcessor(exporter)]
1464
- });
1465
- const logger2 = provider.getLogger("blyp-posthog");
1466
- return {
1467
- emit(payload) {
1468
- logger2.emit({
1469
- body: payload.body,
1470
- severityText: payload.severityText,
1471
- severityNumber: payload.severityNumber,
1472
- attributes: payload.attributes
1473
- });
1474
- },
1475
- flush() {
1476
- return provider.forceFlush();
1477
- },
1478
- shutdown() {
1479
- return provider.shutdown();
1480
- }
1481
- };
1482
- }
1483
- function createDefaultExceptionClient(connector) {
1484
- const client = new PostHog(connector.projectKey ?? "", {
1485
- host: connector.host,
1486
- enableExceptionAutocapture: connector.errorTracking.enableExceptionAutocapture
1487
- });
1488
- return {
1489
- captureException(error, distinctId, additionalProperties) {
1490
- return client.captureExceptionImmediate(error, distinctId, additionalProperties);
1491
- },
1492
- shutdown() {
1493
- return client._shutdown();
1494
- }
1495
- };
1496
- }
1497
- function resolveConnectorConfig(config) {
1498
- const connector = isBlypConfig(config) ? config.connectors?.posthog : config;
1499
- const enabled = connector?.enabled ?? false;
1500
- const projectKey = connector?.projectKey;
1501
- const errorTrackingEnabled = connector?.errorTracking?.enabled ?? enabled;
1502
- const errorTrackingMode = connector?.errorTracking?.mode ?? "auto";
1503
- const errorTrackingReady = enabled && errorTrackingEnabled && hasNonEmptyString(projectKey);
1504
- return {
1505
- enabled,
1506
- mode: connector?.mode ?? "auto",
1507
- projectKey,
1508
- host: normalizeHost(connector?.host),
1509
- serviceName: connector?.serviceName ?? "blyp-app",
1510
- errorTracking: {
1511
- enabled: errorTrackingEnabled,
1512
- mode: errorTrackingMode,
1513
- enableExceptionAutocapture: connector?.errorTracking?.enableExceptionAutocapture ?? errorTrackingMode === "auto",
1514
- ready: errorTrackingReady,
1515
- status: errorTrackingReady ? "enabled" : "missing"
1516
- }
1517
- };
1518
- }
1519
- function createPostHogSender(config) {
1520
- const connector = resolveConnectorConfig(config);
1521
- const key = `${connector.serviceName}:${connector.host}:${connector.mode}`;
1522
- const ready = connector.enabled === true && hasNonEmptyString(connector.projectKey);
1523
- const transport = ready ? testHooks.createTransport?.(connector) ?? createDefaultTransport(connector) : void 0;
1524
- const exceptionClient = connector.errorTracking.ready ? testHooks.createExceptionClient?.(connector) ?? createDefaultExceptionClient(connector) : void 0;
1525
- const shutdown = async () => {
1526
- if (transport?.shutdown) {
1527
- await transport.shutdown();
1528
- } else if (transport?.flush) {
1529
- await transport.flush();
1530
- }
1531
- if (exceptionClient?.shutdown) {
1532
- await exceptionClient.shutdown();
1533
- }
1534
- };
1535
- if (transport || exceptionClient) {
1536
- registerShutdownHooks(key, shutdown);
1537
- }
1538
- const emitUnavailableWarning = () => {
1539
- warnOnce2(
1540
- `posthog-unavailable:${key}`,
1541
- "[Blyp] PostHog connector is not configured. Skipping PostHog delivery."
1542
- );
1543
- };
1544
- const emitExceptionUnavailableWarning = () => {
1545
- warnOnce2(
1546
- `posthog-exception-unavailable:${key}`,
1547
- "[Blyp] PostHog error tracking is not configured. Skipping PostHog exception capture."
1548
- );
1549
- };
1550
- return {
1551
- enabled: connector.enabled,
1552
- ready,
1553
- mode: connector.mode,
1554
- serviceName: connector.serviceName,
1555
- host: connector.host,
1556
- status: ready ? "enabled" : "missing",
1557
- errorTracking: {
1558
- enabled: connector.errorTracking.enabled,
1559
- ready: connector.errorTracking.ready,
1560
- mode: connector.errorTracking.mode,
1561
- status: connector.errorTracking.status,
1562
- enableExceptionAutocapture: connector.errorTracking.enableExceptionAutocapture
1563
- },
1564
- shouldAutoForwardServerLogs() {
1565
- return ready && connector.mode === "auto";
1566
- },
1567
- shouldAutoCaptureExceptions() {
1568
- return connector.errorTracking.ready && connector.errorTracking.mode === "auto";
1569
- },
1570
- send(record, options = {}) {
1571
- const source = options.source ?? "server";
1572
- if (!ready || !transport) {
1573
- if (options.warnIfUnavailable) {
1574
- emitUnavailableWarning();
1575
- }
1576
- return;
1577
- }
1578
- const normalized = normalizePostHogRecord(record, connector, source);
1579
- try {
1580
- const result = transport.emit(normalized);
1581
- if (result && typeof result.catch === "function") {
1582
- void result.catch((error) => {
1583
- warnOnce2(
1584
- `posthog-emit:${key}`,
1585
- "[Blyp] Failed to deliver log to PostHog.",
1586
- error
1587
- );
1588
- });
1589
- }
1590
- } catch (error) {
1591
- warnOnce2(
1592
- `posthog-emit:${key}`,
1593
- "[Blyp] Failed to deliver log to PostHog.",
1594
- error
1595
- );
1596
- }
1597
- },
1598
- captureException(error, options = {}) {
1599
- if (!connector.errorTracking.ready || !exceptionClient) {
1600
- if (options.warnIfUnavailable) {
1601
- emitExceptionUnavailableWarning();
1602
- }
1603
- return;
1604
- }
1605
- if (isPreviouslyCapturedPostHogError(error)) {
1606
- return;
1607
- }
1608
- const normalized = normalizeExceptionInput(
1609
- error,
1610
- options.source === "client" ? "Client error" : "Server error"
1611
- );
1612
- const properties = {
1613
- ...normalized.properties,
1614
- ...options.properties ?? {},
1615
- "blyp.source": options.source ?? "server"
1616
- };
1617
- try {
1618
- const result = exceptionClient.captureException(
1619
- normalized.error,
1620
- options.distinctId,
1621
- properties
1622
- );
1623
- markPostHogCapturedError(error);
1624
- markPostHogCapturedError(normalized.error);
1625
- if (result && typeof result.catch === "function") {
1626
- void result.catch((captureError) => {
1627
- warnOnce2(
1628
- `posthog-capture:${key}`,
1629
- "[Blyp] Failed to capture exception in PostHog.",
1630
- captureError
1631
- );
1632
- });
1633
- }
1634
- } catch (captureError) {
1635
- warnOnce2(
1636
- `posthog-capture:${key}`,
1637
- "[Blyp] Failed to capture exception in PostHog.",
1638
- captureError
1639
- );
1640
- }
1641
- },
1642
- async flush() {
1643
- try {
1644
- if (transport?.flush) {
1645
- await transport.flush();
1646
- }
1647
- } catch (error) {
1648
- warnOnce2(
1649
- `posthog-flush:${key}`,
1650
- "[Blyp] Failed to flush PostHog telemetry.",
1651
- error
1652
- );
1653
- }
1654
- }
1655
- };
1656
- }
1657
- function buildPostHogExceptionProperties(record, source, properties = {}) {
1658
- return {
1659
- ...createExceptionPropertiesFromRecord(record, source),
1660
- ...properties
1661
- };
1662
- }
1663
- var requestContextStorage = new AsyncLocalStorage();
1664
- function createStore() {
1665
- return {
1666
- requestScopedLoggerActive: true,
1667
- structuredCollectorActive: false,
1668
- structuredLogEmitted: false,
1669
- mixedLoggerWarningShown: false
1670
- };
1671
- }
1672
- function enterRequestContext() {
1673
- const store = createStore();
1674
- requestContextStorage.enterWith(store);
1675
- return store;
1676
- }
1677
- function getRequestContextStore() {
1678
- return requestContextStorage.getStore();
1679
- }
1680
- function setActiveRequestLogger(logger2) {
1681
- const store = getRequestContextStore();
1682
- if (store) {
1683
- store.activeLogger = logger2;
1684
- }
1685
- }
1686
- function markStructuredCollectorActive() {
1687
- const store = getRequestContextStore();
1688
- if (store) {
1689
- store.structuredCollectorActive = true;
1690
- }
1691
- }
1692
- function markStructuredLogEmitted() {
1693
- const store = getRequestContextStore();
1694
- if (store) {
1695
- store.structuredLogEmitted = true;
1696
- }
1697
- }
1698
- function shouldDropRootLogWrite() {
1699
- const store = getRequestContextStore();
1700
- if (!store || !store.requestScopedLoggerActive || !store.structuredCollectorActive) {
1701
- return false;
1702
- }
1703
- if (!store.mixedLoggerWarningShown) {
1704
- store.mixedLoggerWarningShown = true;
1705
- console.warn(
1706
- "[Blyp] Warning: Mixed logger usage detected for this request. The root logger call was ignored because a request-scoped structured logger is active."
1707
- );
1708
- }
1709
- return true;
1710
- }
1711
-
1712
- // src/core/log-record.ts
1713
- var RECORD_LEVELS = {
1714
- success: "success",
1715
- critical: "critical",
1716
- warning: "warning",
1717
- info: "info",
1718
- debug: "debug",
1719
- error: "error",
1720
- warn: "warning",
1721
- table: "table"
1722
- };
1723
- function normalizePath2(filePath) {
1724
- return filePath.replace(/\\/g, "/");
1725
- }
1726
- function isInternalLoggerFrame(filePath) {
1727
- const normalizedPath = normalizePath2(filePath);
1728
- return normalizedPath.startsWith("node:") || normalizedPath.includes("/node_modules/pino") || normalizedPath.includes("/node_modules/pino-pretty") || normalizedPath.includes("/node_modules/@blyp/core/") || normalizedPath.includes("/blyp/src/core/") || normalizedPath.includes("/blyp/src/frameworks/") || normalizedPath.includes("/blyp/src/posthog/") || normalizedPath.includes("/blyp/dist/");
1729
- }
1730
- function formatCallerPath(filePath) {
1731
- const normalizedPath = normalizePath2(filePath);
1732
- const normalizedCwd = normalizePath2(process.cwd());
1733
- return normalizedPath.startsWith(`${normalizedCwd}/`) ? normalizedPath.slice(normalizedCwd.length + 1) : normalizedPath;
1734
- }
1735
- function getCallerLocation() {
1736
- try {
1737
- const stack = new Error().stack;
1738
- if (!stack) {
1739
- return { file: null, line: null };
1740
- }
1741
- const lines = stack.split("\n");
1742
- let fallback = null;
1743
- for (let index = 2; index < lines.length; index += 1) {
1744
- const line = lines[index];
1745
- if (!line) {
1746
- continue;
1747
- }
1748
- const match = line.match(/\((.*):(\d+):\d+\)/) || line.match(/at\s+(.*):(\d+):(\d+)/);
1749
- if (!match) {
1750
- continue;
1751
- }
1752
- const fileName = match[1] || "";
1753
- const lineNumber = parseInt(match[2] || "0", 10) || null;
1754
- if (fileName && !fileName.includes("node_modules") && !isInternalLoggerFrame(fileName)) {
1755
- const formattedPath = formatCallerPath(fileName);
1756
- const normalizedFormattedPath = normalizePath2(formattedPath);
1757
- if (!normalizedFormattedPath.startsWith("dist/")) {
1758
- return { file: formattedPath, line: lineNumber };
1759
- }
1760
- fallback ?? (fallback = { file: formattedPath, line: lineNumber });
1761
- }
1762
- }
1763
- if (fallback) {
1764
- return fallback;
1765
- }
1766
- } catch {
1767
- return { file: null, line: null };
1768
- }
1769
- return { file: null, line: null };
1770
- }
1771
- var serializeMessage = serializeLogMessage;
1772
- function stripAnsi(value) {
1773
- return value.replace(/\u001b\[[0-9;]*m/g, "");
1774
- }
1775
- function buildRecord(level, message, args, bindings) {
1776
- const { file, line } = getCallerLocation();
1777
- const serializedMessage = serializeMessage(message);
1778
- const record = {
1779
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1780
- level: RECORD_LEVELS[level],
1781
- message: stripAnsi(serializedMessage)
1782
- };
1783
- if (message instanceof Error) {
1784
- record.error = normalizeError(message);
1785
- }
1786
- if (file) {
1787
- record.caller = line !== null ? `${file}:${line}` : file;
1788
- }
1789
- if (args.length === 1) {
1790
- record.data = normalizeLogValue(args[0]);
1791
- } else if (args.length > 1) {
1792
- record.data = normalizeLogValue(args);
1793
- }
1794
- if (Object.keys(bindings).length > 0) {
1795
- record.bindings = normalizeLogValue(bindings);
1796
- }
1797
- return record;
1798
- }
1799
- function buildStructuredRecord(level, message, payload, bindings) {
1800
- const { file, line } = getCallerLocation();
1801
- const normalizedPayload = normalizeLogValue(payload);
1802
- const record = {
1803
- message: stripAnsi(message),
1804
- ...normalizedPayload
1805
- };
1806
- if (file) {
1807
- record.caller = line !== null ? `${file}:${line}` : file;
1808
- }
1809
- if (Object.keys(bindings).length > 0) {
1810
- record.bindings = normalizeLogValue(bindings);
1811
- }
1812
- record.level = typeof normalizedPayload.level === "string" && normalizedPayload.level.length > 0 ? normalizedPayload.level : RECORD_LEVELS[level];
1813
- record.timestamp = typeof normalizedPayload.timestamp === "string" && normalizedPayload.timestamp.length > 0 ? normalizedPayload.timestamp : (/* @__PURE__ */ new Date()).toISOString();
1814
- return record;
1815
- }
1816
- function resolveStructuredWriteLevel(level) {
1817
- switch (level) {
1818
- case "debug":
1819
- return "debug";
1820
- case "warning":
1821
- return "warning";
1822
- case "warn":
1823
- return "warn";
1824
- case "error":
1825
- return "error";
1826
- case "success":
1827
- return "success";
1828
- case "critical":
1829
- return "critical";
1830
- case "table":
1831
- return "table";
1832
- case "info":
1833
- default:
1834
- return "info";
1835
- }
1836
- }
1837
-
1838
- // src/core/sinks/file-primary-sink.ts
1839
- var FilePrimarySink = class {
1840
- constructor(logger2) {
1841
- this.logger = logger2;
1842
- __publicField(this, "isAsync", false);
1843
- __publicField(this, "isReady", true);
1844
- }
1845
- write(record) {
1846
- this.logger.write(record);
1847
- }
1848
- async flush() {
1849
- }
1850
- async shutdown() {
1851
- }
1852
- };
1853
- function createFilePrimarySink(config) {
1854
- return new FilePrimarySink(createFileLogger(config));
1855
- }
1856
-
1857
- // src/database/adapters/drizzle.ts
1858
- function createDrizzleRowWriter(adapter) {
1859
- const db = adapter.db;
1860
- if (typeof db?.insert !== "function" || adapter.table === void 0) {
1861
- throw new Error(
1862
- "[Blyp] Drizzle database adapter is missing a db.insert function or table reference."
1863
- );
1864
- }
1865
- return {
1866
- async insert(rows) {
1867
- if (rows.length === 0) {
1868
- return;
1869
- }
1870
- await db.insert(adapter.table).values(rows);
1871
- }
1872
- };
1873
- }
1874
-
1875
- // src/database/adapters/prisma.ts
1876
- function shouldFallbackFromCreateMany(error) {
1877
- const message = String(error ?? "");
1878
- return message.includes("createMany") || message.includes("Unknown argument") || message.includes("not supported") || message.includes("is not a function");
1879
- }
1880
- function createPrismaRowWriter(adapter) {
1881
- const client = adapter.client;
1882
- const model = adapter.model ?? "blypLog";
1883
- const delegateCandidate = client[model];
1884
- if (!delegateCandidate || typeof delegateCandidate.create !== "function") {
1885
- throw new Error(
1886
- `[Blyp] Prisma database adapter is missing the "${model}" delegate or its create method.`
1887
- );
1888
- }
1889
- const delegate = delegateCandidate;
1890
- let useCreateMany = typeof delegate.createMany === "function";
1891
- async function fallbackInsert(rows) {
1892
- if (typeof client.$transaction === "function") {
1893
- await client.$transaction(
1894
- rows.map((row) => delegate.create({ data: row }))
1895
- );
1896
- return;
1897
- }
1898
- for (const row of rows) {
1899
- await delegate.create({ data: row });
1900
- }
1901
- }
1902
- return {
1903
- async insert(rows) {
1904
- if (rows.length === 0) {
1905
- return;
1906
- }
1907
- if (rows.length === 1) {
1908
- await delegate.create({ data: rows[0] });
1909
- return;
1910
- }
1911
- if (!useCreateMany || typeof delegate.createMany !== "function") {
1912
- await fallbackInsert(rows);
1913
- return;
1914
- }
1915
- try {
1916
- await delegate.createMany({ data: rows });
1917
- } catch (error) {
1918
- if (!shouldFallbackFromCreateMany(error)) {
1919
- throw error;
1920
- }
1921
- useCreateMany = false;
1922
- await fallbackInsert(rows);
1923
- }
1924
- }
1925
- };
1926
- }
1927
-
1928
- // src/database/helpers.ts
1929
- function normalizeNullableNumber(value) {
1930
- return typeof value === "number" && Number.isFinite(value) ? value : null;
1931
- }
1932
- function normalizeNullableString(value) {
1933
- return typeof value === "string" && value.length > 0 ? value : null;
1934
- }
1935
- function parseTimestamp(value) {
1936
- if (typeof value === "string") {
1937
- const timestamp = new Date(value);
1938
- if (!Number.isNaN(timestamp.getTime())) {
1939
- return timestamp;
1940
- }
1941
- }
1942
- return /* @__PURE__ */ new Date();
1943
- }
1944
- function toDatabaseLogRow(record) {
1945
- const normalizedRecord = normalizeLogValue(record);
1946
- return {
1947
- id: randomUUID(),
1948
- timestamp: parseTimestamp(record.timestamp),
1949
- level: record.level,
1950
- message: record.message,
1951
- caller: normalizeNullableString(record.caller),
1952
- type: normalizeNullableString(record.type),
1953
- groupId: normalizeNullableString(record.groupId),
1954
- method: normalizeNullableString(record.method),
1955
- path: normalizeNullableString(record.path),
1956
- status: normalizeNullableNumber(record.status),
1957
- duration: normalizeNullableNumber(record.duration),
1958
- hasError: normalizedRecord.error != null,
1959
- data: normalizedRecord.data ?? null,
1960
- bindings: normalizedRecord.bindings ?? null,
1961
- error: normalizedRecord.error ?? null,
1962
- events: normalizedRecord.events ?? null,
1963
- record: normalizedRecord,
1964
- createdAt: /* @__PURE__ */ new Date()
1965
- };
1966
- }
1967
- function isPrismaAdapter2(adapter) {
1968
- return !!adapter && adapter.type === "prisma";
1969
- }
1970
- function isDrizzleAdapter2(adapter) {
1971
- return !!adapter && adapter.type === "drizzle";
1972
- }
1973
- function createDatabaseRowWriter(config) {
1974
- if (isPrismaAdapter2(config.adapter)) {
1975
- return createPrismaRowWriter(config.adapter);
1976
- }
1977
- if (isDrizzleAdapter2(config.adapter)) {
1978
- return createDrizzleRowWriter(config.adapter);
1979
- }
1980
- throw new Error("[Blyp] Unsupported database adapter configuration.");
1981
- }
15
+ const NODE_SQLITE_MODULE = ${JSON.stringify(Qt)};
16
+ const BUN_SQLITE_MODULE = ${JSON.stringify(Wt)};
17
+ const CLAIM_LEASE_MS = 30000;
1982
18
 
1983
- // src/core/sinks/database-primary-sink.ts
1984
- function delay(ms) {
1985
- return new Promise((resolve2) => {
1986
- setTimeout(resolve2, ms);
1987
- });
1988
- }
1989
- var DatabasePrimarySink = class {
1990
- constructor(config) {
1991
- this.config = config;
1992
- __publicField(this, "isAsync", true);
1993
- __publicField(this, "isReady", true);
1994
- __publicField(this, "warnOnce", createWarnOnceLogger(/* @__PURE__ */ new Set()));
1995
- __publicField(this, "queue", []);
1996
- __publicField(this, "writer");
1997
- __publicField(this, "timer", null);
1998
- __publicField(this, "processing", false);
1999
- __publicField(this, "closed", false);
2000
- __publicField(this, "terminalError", null);
2001
- __publicField(this, "activeDispatch", null);
2002
- this.writer = createDatabaseRowWriter(config);
2003
- }
2004
- write(record) {
2005
- if (this.closed) {
2006
- return;
2007
- }
2008
- this.enqueue(toDatabaseLogRow(record));
2009
- this.scheduleDispatch();
2010
- }
2011
- async flush() {
2012
- if (this.timer) {
2013
- clearTimeout(this.timer);
2014
- this.timer = null;
2015
- }
2016
- const flushPromise = (async () => {
2017
- await this.drain();
2018
- if (this.terminalError) {
2019
- throw this.terminalError;
2020
- }
2021
- })();
2022
- let timeoutHandle = null;
2023
- try {
2024
- await Promise.race([
2025
- flushPromise,
2026
- new Promise((_, reject) => {
2027
- timeoutHandle = setTimeout(() => {
2028
- this.warnOnce(
2029
- "database-flush-timeout",
2030
- `[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`
2031
- );
2032
- reject(new Error("[Blyp] Timed out flushing database logs."));
2033
- }, this.config.delivery.flushTimeoutMs);
2034
- })
2035
- ]);
2036
- } finally {
2037
- if (timeoutHandle) {
2038
- clearTimeout(timeoutHandle);
2039
- }
2040
- }
2041
- }
2042
- async shutdown() {
2043
- this.closed = true;
2044
- await this.flush();
2045
- }
2046
- enqueue(row) {
2047
- this.queue.push(row);
2048
- const overflow = this.queue.length - this.config.delivery.maxQueueSize;
2049
- if (overflow <= 0) {
2050
- return;
2051
- }
2052
- this.warnOnce(
2053
- "database-overflow",
2054
- `[Blyp] Warning: Database log queue exceeded ${this.config.delivery.maxQueueSize} entries. Applying ${this.config.delivery.overflowStrategy} overflow handling.`
2055
- );
2056
- if (this.config.delivery.overflowStrategy === "drop-new") {
2057
- this.queue.splice(this.config.delivery.maxQueueSize);
2058
- return;
2059
- }
2060
- this.queue.splice(0, overflow);
2061
- }
2062
- scheduleDispatch() {
2063
- if (this.processing) {
2064
- return;
2065
- }
2066
- if (this.config.delivery.strategy === "immediate") {
2067
- void this.drain();
2068
- return;
2069
- }
2070
- if (this.queue.length >= this.config.delivery.batchSize) {
2071
- void this.drain();
2072
- return;
2073
- }
2074
- if (this.timer) {
2075
- return;
2076
- }
2077
- this.timer = setTimeout(() => {
2078
- this.timer = null;
2079
- void this.drain();
2080
- }, this.config.delivery.flushIntervalMs);
2081
- }
2082
- async drain() {
2083
- if (this.processing) {
2084
- if (this.activeDispatch) {
2085
- await this.activeDispatch;
2086
- }
2087
- return;
2088
- }
2089
- this.processing = true;
2090
- this.activeDispatch = this.processQueue();
2091
- try {
2092
- await this.activeDispatch;
2093
- } finally {
2094
- this.processing = false;
2095
- this.activeDispatch = null;
2096
- }
2097
- }
2098
- async processQueue() {
2099
- while (this.queue.length > 0) {
2100
- const batchSize = this.config.delivery.strategy === "batch" ? Math.max(1, this.config.delivery.batchSize) : 1;
2101
- const batch = this.queue.splice(0, batchSize);
2102
- try {
2103
- await this.insertWithRetry(batch);
2104
- } catch (error) {
2105
- const failure = error instanceof Error ? error : new Error(String(error ?? "Unknown database logging failure"));
2106
- this.terminalError = failure;
2107
- this.warnOnce(
2108
- "database-insert-failure",
2109
- `[Blyp] Warning: Failed to persist logs to the ${this.config.dialect ?? "database"} database.`,
2110
- failure
2111
- );
2112
- throw failure;
2113
- }
2114
- }
2115
- }
2116
- async insertWithRetry(batch) {
2117
- const maxAttempts = Math.max(1, this.config.delivery.retry.maxRetries + 1);
2118
- let attempt = 0;
2119
- while (attempt < maxAttempts) {
2120
- attempt += 1;
2121
- try {
2122
- await this.writer.insert(batch);
2123
- return;
2124
- } catch (error) {
2125
- if (attempt >= maxAttempts) {
2126
- throw error;
2127
- }
2128
- await delay(this.config.delivery.retry.backoffMs);
2129
- }
2130
- }
2131
- }
2132
- };
19
+ let db;
20
+ let runtime = 'unsupported';
2133
21
 
2134
- // src/core/primary-sink.ts
2135
- var NoopPrimarySink = class {
2136
- constructor() {
2137
- __publicField(this, "isAsync", false);
2138
- __publicField(this, "isReady", false);
2139
- }
2140
- write(_record) {
2141
- }
2142
- async flush() {
2143
- }
2144
- async shutdown() {
2145
- }
2146
- };
2147
- var warnOnce3 = createWarnOnceLogger(/* @__PURE__ */ new Set());
2148
- function createPrimarySink(config) {
2149
- if (config.destination !== "database") {
2150
- return createFilePrimarySink(config);
2151
- }
2152
- const databaseConfig = config.database;
2153
- if (!databaseConfig?.ready) {
2154
- warnOnce3(
2155
- "database-sink-disabled",
2156
- "[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."
2157
- );
2158
- return new NoopPrimarySink();
2159
- }
2160
- return new DatabasePrimarySink(databaseConfig);
2161
- }
2162
- var PREVIOUSLY_CAPTURED_ERROR_KEY2 = "__betterstack_previously_captured_error";
2163
- var warnedKeys3 = /* @__PURE__ */ new Set();
2164
- var testHooks2 = {};
2165
- var warnOnce4 = createErrorOnceLogger(warnedKeys3);
2166
- function getSentryModule() {
2167
- return testHooks2.module ?? Sentry;
2168
- }
2169
- function resolveConnectorConfig2(config) {
2170
- const connector = isBlypConfig(config) ? config.connectors?.betterstack : config;
2171
- const enabled = connector?.enabled ?? false;
2172
- const sourceToken = connector?.sourceToken;
2173
- const ingestingHost = connector?.ingestingHost;
2174
- const errorTrackingEnabled = connector?.errorTracking?.enabled ?? enabled;
2175
- const errorTrackingDsn = connector?.errorTracking?.dsn;
2176
- const errorTrackingReady = enabled && errorTrackingEnabled && hasNonEmptyString(errorTrackingDsn);
2177
- const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
2178
- return {
2179
- enabled,
2180
- mode: connector?.mode ?? "auto",
2181
- sourceToken,
2182
- ingestingHost,
2183
- serviceName: connector?.serviceName ?? "blyp-app",
2184
- errorTracking: {
2185
- enabled: errorTrackingEnabled,
2186
- dsn: errorTrackingDsn,
2187
- tracesSampleRate: connector?.errorTracking?.tracesSampleRate ?? 1,
2188
- environment: connector?.errorTracking?.environment,
2189
- release: connector?.errorTracking?.release,
2190
- ready: errorTrackingReady,
2191
- status: errorTrackingReady ? "enabled" : "missing"
2192
- },
2193
- ready,
2194
- status: ready ? "enabled" : "missing"
2195
- };
2196
- }
2197
- function resolveBetterStackLevel(level) {
2198
- switch (level) {
2199
- case "debug":
2200
- return "debug";
2201
- case "warning":
2202
- case "warn":
2203
- return "warn";
2204
- case "error":
2205
- return "error";
2206
- case "critical":
2207
- return "fatal";
2208
- case "success":
2209
- case "table":
2210
- case "info":
2211
- default:
2212
- return "info";
2213
- }
2214
- }
2215
- function parseCaller(caller) {
2216
- if (typeof caller !== "string" || caller.trim().length === 0) {
2217
- return {};
2218
- }
2219
- const match = caller.match(/^(.*):(\d+)$/);
2220
- if (!match) {
2221
- return {};
2222
- }
2223
- const file = match[1]?.trim();
2224
- const line = Number.parseInt(match[2] ?? "", 10);
2225
- return {
2226
- ...file ? { file } : {},
2227
- ...Number.isFinite(line) ? { line } : {}
2228
- };
2229
- }
2230
- function buildContext(record, connector, source) {
2231
- const recordType = getRecordType(record);
2232
- const groupId = getField(record, "groupId");
2233
- const method = getField(record, "method");
2234
- const path3 = getField(record, "path");
2235
- const status = getField(record, "status");
2236
- const duration = getField(record, "duration");
2237
- const pagePath = getClientPageField(record, "pathname");
2238
- const pageUrl = getClientPageField(record, "url");
2239
- const sessionId = getClientSessionField(record, "sessionId");
2240
- const pageId = getClientSessionField(record, "pageId");
2241
- const runtime2 = parseCaller(record.caller);
2242
- return {
2243
- service: connector.serviceName,
2244
- context: {
2245
- blyp: {
2246
- level: record.level,
2247
- source,
2248
- ...recordType ? { type: recordType } : {},
2249
- ...groupId ? { group_id: groupId } : {},
2250
- ...record.caller ? { caller: record.caller } : {},
2251
- ...duration !== void 0 ? { duration_ms: duration } : {},
2252
- ...record.bindings ? { bindings: record.bindings } : {},
2253
- payload: serializeLogRecord(record)
2254
- },
2255
- ...method || path3 || status !== void 0 ? {
2256
- http: {
2257
- ...method ? { method } : {},
2258
- ...path3 ? { path: path3 } : {},
2259
- ...status !== void 0 ? { status_code: status } : {}
2260
- }
2261
- } : {},
2262
- ...pagePath || pageUrl || sessionId || pageId ? {
2263
- client: {
2264
- ...pagePath ? { page_path: pagePath } : {},
2265
- ...pageUrl ? { page_url: pageUrl } : {},
2266
- ...sessionId ? { session_id: sessionId } : {},
2267
- ...pageId ? { page_id: pageId } : {}
2268
- }
2269
- } : {},
2270
- ...Object.keys(runtime2).length > 0 ? { runtime: runtime2 } : {},
2271
- ...record.data !== void 0 ? { data: record.data } : {},
2272
- ...record.error !== void 0 ? { error: record.error } : {}
2273
- }
2274
- };
2275
- }
2276
- function toExceptionCandidate(value) {
2277
- if (!isPlainObject(value)) {
2278
- return void 0;
2279
- }
2280
- const message = typeof value.message === "string" ? value.message : void 0;
2281
- const name = typeof value.name === "string" ? value.name : void 0;
2282
- const stack = typeof value.stack === "string" ? value.stack : void 0;
2283
- if (!message && !name && !stack) {
2284
- return void 0;
2285
- }
2286
- const error = new Error(message ?? name ?? "Unknown error");
2287
- error.name = name ?? "Error";
2288
- if (stack) {
2289
- error.stack = stack;
2290
- }
2291
- for (const [key, entry] of Object.entries(value)) {
2292
- if (key === "message" || key === "name" || key === "stack") {
2293
- continue;
2294
- }
2295
- error[key] = entry;
2296
- }
2297
- return error;
2298
- }
2299
- function normalizeScopeLevel(level) {
2300
- switch (level) {
2301
- case "debug":
2302
- return "debug";
2303
- case "warning":
2304
- case "warn":
2305
- return "warning";
2306
- case "critical":
2307
- return "fatal";
2308
- case "error":
2309
- return "error";
2310
- case "success":
2311
- case "table":
2312
- case "info":
2313
- default:
2314
- return "info";
2315
- }
2316
- }
2317
- function normalizeExceptionInput2(input) {
2318
- if (input instanceof Error) {
2319
- return input;
2320
- }
2321
- const direct = toExceptionCandidate(input);
2322
- if (direct) {
2323
- return direct;
2324
- }
2325
- if (typeof input === "string") {
2326
- return new Error(input);
2327
- }
2328
- return new Error("Unknown Better Stack exception");
2329
- }
2330
- function isPreviouslyCapturedError(value) {
2331
- return isPlainObject(value) && value[PREVIOUSLY_CAPTURED_ERROR_KEY2] === true;
2332
- }
2333
- function markCapturedError(value) {
2334
- if (!isPlainObject(value) || isPreviouslyCapturedError(value)) {
2335
- return;
2336
- }
22
+ async function loadDatabase() {
2337
23
  try {
2338
- Object.defineProperty(value, PREVIOUSLY_CAPTURED_ERROR_KEY2, {
2339
- value: true,
2340
- enumerable: false,
2341
- configurable: true,
2342
- writable: true
2343
- });
2344
- } catch {
2345
- try {
2346
- value[PREVIOUSLY_CAPTURED_ERROR_KEY2] = true;
2347
- } catch {
2348
- }
2349
- }
2350
- }
2351
- function createDefaultClient(connector) {
2352
- return new Logtail(connector.sourceToken ?? "", {
2353
- endpoint: connector.ingestingHost,
2354
- captureStackContext: false
2355
- });
2356
- }
2357
- function getClientOptions(client) {
2358
- return client?.getOptions?.() ?? {};
2359
- }
2360
- function registerShutdownHooks2(key, flush) {
2361
- const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
2362
- for (const event of handlers) {
2363
- process.once(event, () => {
2364
- void flush().catch((error) => {
2365
- warnOnce4(
2366
- `${key}:shutdown`,
2367
- "[Blyp] Failed to flush Better Stack logs during shutdown.",
2368
- error
2369
- );
2370
- });
2371
- });
2372
- }
2373
- }
2374
- function createBetterStackSender(config) {
2375
- const connector = resolveConnectorConfig2(config);
2376
- const key = `${connector.serviceName}:${connector.ingestingHost ?? "missing"}:${connector.mode}`;
2377
- const sentryModule = getSentryModule();
2378
- const client = connector.ready ? testHooks2.createClient?.(connector) ?? createDefaultClient(connector) : void 0;
2379
- let sentryClient = connector.errorTracking.enabled ? sentryModule?.getClient?.() : void 0;
2380
- if (sentryClient) {
2381
- const options = getClientOptions(sentryClient);
2382
- if (hasNonEmptyString(connector.errorTracking.dsn) && connector.errorTracking.dsn !== options.dsn || hasNonEmptyString(connector.errorTracking.environment) && connector.errorTracking.environment !== options.environment || hasNonEmptyString(connector.errorTracking.release) && connector.errorTracking.release !== options.release) {
2383
- warnOnce4(
2384
- `betterstack-error-mismatch:${key}`,
2385
- "[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client for Better Stack error tracking."
2386
- );
2387
- }
2388
- }
2389
- if (!sentryClient && connector.errorTracking.enabled && hasNonEmptyString(connector.errorTracking.dsn) && sentryModule) {
2390
- try {
2391
- sentryModule.init({
2392
- dsn: connector.errorTracking.dsn,
2393
- tracesSampleRate: connector.errorTracking.tracesSampleRate,
2394
- environment: connector.errorTracking.environment,
2395
- release: connector.errorTracking.release
2396
- });
2397
- sentryClient = sentryModule.getClient();
2398
- } catch (error) {
2399
- warnOnce4(
2400
- `betterstack-error-init:${key}`,
2401
- "[Blyp] Failed to initialize Better Stack error tracking.",
2402
- error
2403
- );
2404
- }
2405
- }
2406
- const errorTrackingReady = connector.errorTracking.enabled && sentryClient !== void 0;
2407
- if (client || errorTrackingReady) {
2408
- registerShutdownHooks2(key, async () => {
2409
- if (client) {
2410
- await client.flush();
2411
- }
2412
- if (errorTrackingReady) {
2413
- await sentryModule.flush(2e3);
2414
- }
2415
- });
2416
- }
2417
- const emitUnavailableWarning = () => {
2418
- warnOnce4(
2419
- `betterstack-unavailable:${key}`,
2420
- "[Blyp] Better Stack connector is not configured or not ready. Skipping Better Stack delivery."
2421
- );
2422
- };
2423
- const emitExceptionUnavailableWarning = () => {
2424
- warnOnce4(
2425
- `betterstack-exception-unavailable:${key}`,
2426
- "[Blyp] Better Stack error tracking is not configured. Skipping Better Stack exception capture."
2427
- );
2428
- };
2429
- return {
2430
- enabled: connector.enabled,
2431
- ready: connector.ready,
2432
- mode: connector.mode,
2433
- serviceName: connector.serviceName,
2434
- ingestingHost: connector.ingestingHost,
2435
- status: connector.status,
2436
- errorTracking: {
2437
- enabled: connector.errorTracking.enabled,
2438
- ready: errorTrackingReady,
2439
- status: errorTrackingReady ? "enabled" : "missing",
2440
- dsn: connector.errorTracking.dsn,
2441
- tracesSampleRate: connector.errorTracking.tracesSampleRate,
2442
- environment: connector.errorTracking.environment,
2443
- release: connector.errorTracking.release
2444
- },
2445
- shouldAutoForwardServerLogs() {
2446
- return connector.ready && connector.mode === "auto";
2447
- },
2448
- shouldAutoCaptureExceptions() {
2449
- return errorTrackingReady;
2450
- },
2451
- send(record, options = {}) {
2452
- if (!connector.ready || !client) {
2453
- if (options.warnIfUnavailable) {
2454
- emitUnavailableWarning();
2455
- }
2456
- return;
2457
- }
2458
- const source = options.source ?? "server";
2459
- void client.log(
2460
- record.message,
2461
- resolveBetterStackLevel(record.level),
2462
- buildContext(record, connector, source)
2463
- ).catch((error) => {
2464
- warnOnce4(
2465
- `betterstack-send:${key}`,
2466
- "[Blyp] Failed to deliver log to Better Stack.",
2467
- error
2468
- );
2469
- });
2470
- },
2471
- captureException(error, options = {}) {
2472
- if (!errorTrackingReady || !sentryModule) {
2473
- if (options.warnIfUnavailable) {
2474
- emitExceptionUnavailableWarning();
2475
- }
2476
- return;
2477
- }
2478
- if (isPreviouslyCapturedError(error)) {
2479
- return;
2480
- }
2481
- try {
2482
- const exception = normalizeExceptionInput2(error);
2483
- sentryModule.withScope((scope) => {
2484
- scope.setLevel(
2485
- normalizeScopeLevel(
2486
- options.source === "client" ? "error" : "error"
2487
- )
2488
- );
2489
- scope.setContext("blyp", {
2490
- source: options.source ?? "server",
2491
- ...options.context ? { context: options.context } : {}
2492
- });
2493
- sentryModule.captureException(exception);
2494
- });
2495
- markCapturedError(error);
2496
- markCapturedError(exception);
2497
- } catch (captureError) {
2498
- warnOnce4(
2499
- `betterstack-manual-capture:${key}`,
2500
- "[Blyp] Failed to capture exception in Better Stack error tracking.",
2501
- captureError
2502
- );
2503
- }
2504
- },
2505
- async flush() {
2506
- if (!client) {
2507
- if (!errorTrackingReady || !sentryModule) {
2508
- return;
2509
- }
2510
- }
2511
- try {
2512
- if (client) {
2513
- await client.flush();
2514
- }
2515
- if (errorTrackingReady && sentryModule) {
2516
- await sentryModule.flush(2e3);
2517
- }
2518
- } catch (error) {
2519
- warnOnce4(
2520
- `betterstack-flush:${key}`,
2521
- "[Blyp] Failed to flush Better Stack logs.",
2522
- error
2523
- );
2524
- }
2525
- }
2526
- };
2527
- }
2528
- var warnedKeys4 = /* @__PURE__ */ new Set();
2529
- var testHooks3 = {};
2530
- var warnOnce5 = createErrorOnceLogger(warnedKeys4);
2531
- function getSentryModule2() {
2532
- return testHooks3.module ?? Sentry;
2533
- }
2534
- function resolveConnectorConfig3(config) {
2535
- const connector = isBlypConfig(config) ? config.connectors?.sentry : config;
2536
- const enabled = connector?.enabled ?? false;
2537
- const dsn = connector?.dsn;
2538
- const ready = enabled && hasNonEmptyString(dsn);
2539
- return {
2540
- enabled,
2541
- mode: connector?.mode ?? "auto",
2542
- dsn,
2543
- environment: connector?.environment,
2544
- release: connector?.release,
2545
- ready,
2546
- status: ready ? "enabled" : "missing"
2547
- };
2548
- }
2549
- function normalizeAttributes(record, source) {
2550
- const attributes = {
2551
- "blyp.level": record.level,
2552
- "blyp.source": source,
2553
- "blyp.payload": serializeLogRecord(record)
2554
- };
2555
- const recordType = getRecordType(record);
2556
- const caller = typeof record.caller === "string" ? record.caller : void 0;
2557
- const groupId = getField(record, "groupId");
2558
- const method = getField(record, "method");
2559
- const path3 = getField(record, "path");
2560
- const status = getField(record, "status");
2561
- const duration = getField(record, "duration");
2562
- const pagePath = getClientPageField(record, "pathname");
2563
- const pageUrl = getClientPageField(record, "url");
2564
- const sessionId = getClientSessionField(record, "sessionId");
2565
- const pageId = getClientSessionField(record, "pageId");
2566
- const ifTruthy = [
2567
- ["blyp.type", recordType],
2568
- ["blyp.caller", caller],
2569
- ["blyp.group_id", groupId],
2570
- ["http.method", method],
2571
- ["url.path", path3],
2572
- ["client.page_path", pagePath],
2573
- ["client.page_url", pageUrl],
2574
- ["client.session_id", sessionId],
2575
- ["client.page_id", pageId]
2576
- ];
2577
- const ifDefined = [
2578
- ["http.status_code", status],
2579
- ["blyp.duration_ms", duration]
2580
- ];
2581
- for (const [k, v] of ifTruthy) if (v) attributes[k] = v;
2582
- for (const [k, v] of ifDefined) if (v !== void 0) attributes[k] = v;
2583
- return attributes;
2584
- }
2585
- function resolveLogMethod(module, level) {
2586
- switch (level) {
2587
- case "debug":
2588
- return module.logger.debug;
2589
- case "warning":
2590
- case "warn":
2591
- return module.logger.warn;
2592
- case "error":
2593
- return module.logger.error;
2594
- case "critical":
2595
- return module.logger.fatal;
2596
- case "success":
2597
- case "table":
2598
- case "info":
2599
- default:
2600
- return module.logger.info;
2601
- }
2602
- }
2603
- function normalizeScopeLevel2(level) {
2604
- switch (level) {
2605
- case "debug":
2606
- return "debug";
2607
- case "warning":
2608
- case "warn":
2609
- return "warning";
2610
- case "critical":
2611
- return "fatal";
2612
- case "error":
2613
- return "error";
2614
- case "success":
2615
- case "table":
2616
- case "info":
2617
- default:
2618
- return "info";
2619
- }
2620
- }
2621
- function toExceptionCandidate2(value) {
2622
- if (!isPlainObject(value)) {
2623
- return void 0;
2624
- }
2625
- const message = typeof value.message === "string" ? value.message : void 0;
2626
- const name = typeof value.name === "string" ? value.name : void 0;
2627
- const stack = typeof value.stack === "string" ? value.stack : void 0;
2628
- if (!message && !name && !stack) {
2629
- return void 0;
2630
- }
2631
- const error = new Error(message ?? name ?? "Unknown error");
2632
- error.name = name ?? "Error";
2633
- if (stack) {
2634
- error.stack = stack;
2635
- }
2636
- for (const [key, entry] of Object.entries(value)) {
2637
- if (key === "message" || key === "name" || key === "stack") {
2638
- continue;
2639
- }
2640
- error[key] = entry;
2641
- }
2642
- return error;
2643
- }
2644
- function extractExceptionCandidate(record) {
2645
- if (record.level !== "error" && record.level !== "critical") {
2646
- return void 0;
2647
- }
2648
- const direct = toExceptionCandidate2(record.error);
2649
- if (direct) {
2650
- return direct;
2651
- }
2652
- if (isPlainObject(record.data)) {
2653
- const directData = toExceptionCandidate2(record.data);
2654
- if (directData) {
2655
- return directData;
2656
- }
2657
- const nested = toExceptionCandidate2(record.data.error);
2658
- if (nested) {
2659
- return nested;
2660
- }
2661
- }
2662
- const payload = getPrimaryPayload(record);
2663
- if (isPlainObject(payload)) {
2664
- const nested = toExceptionCandidate2(payload.error);
2665
- if (nested) {
2666
- return nested;
2667
- }
2668
- }
2669
- return void 0;
2670
- }
2671
- function getClientOptions2(client) {
2672
- return client?.getOptions?.() ?? {};
2673
- }
2674
- function hasConfigMismatch(connector, client) {
2675
- const options = getClientOptions2(client);
2676
- return hasNonEmptyString(connector.dsn) && connector.dsn !== options.dsn || hasNonEmptyString(connector.environment) && connector.environment !== options.environment || hasNonEmptyString(connector.release) && connector.release !== options.release;
2677
- }
2678
- function createSentrySender(config) {
2679
- const connector = resolveConnectorConfig3(config);
2680
- const key = `${connector.mode}:${connector.dsn ?? "missing"}`;
2681
- const module = getSentryModule2();
2682
- let client = connector.enabled ? module.getClient() : void 0;
2683
- if (!client && connector.enabled && hasNonEmptyString(connector.dsn)) {
2684
- try {
2685
- module.init({
2686
- dsn: connector.dsn,
2687
- environment: connector.environment,
2688
- release: connector.release,
2689
- enableLogs: true
2690
- });
2691
- client = module.getClient();
2692
- } catch (error) {
2693
- warnOnce5(
2694
- `sentry-init:${key}`,
2695
- "[Blyp] Failed to initialize Sentry. Skipping Sentry delivery.",
2696
- error
2697
- );
2698
- }
2699
- }
2700
- if (client && hasConfigMismatch(connector, client)) {
2701
- warnOnce5(
2702
- `sentry-mismatch:${key}`,
2703
- "[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client."
2704
- );
2705
- }
2706
- const ready = connector.enabled && client !== void 0;
2707
- const emitUnavailableWarning = () => {
2708
- warnOnce5(
2709
- `sentry-unavailable:${key}`,
2710
- "[Blyp] Sentry connector is not configured. Skipping Sentry delivery."
2711
- );
2712
- };
2713
- return {
2714
- enabled: connector.enabled,
2715
- ready,
2716
- mode: connector.mode,
2717
- status: ready ? "enabled" : "missing",
2718
- shouldAutoForwardServerLogs() {
2719
- return ready && connector.mode === "auto";
2720
- },
2721
- send(record, options = {}) {
2722
- if (!ready) {
2723
- if (options.warnIfUnavailable) {
2724
- emitUnavailableWarning();
2725
- }
2726
- return;
2727
- }
2728
- const source = options.source ?? "server";
2729
- const attributes = normalizeAttributes(record, source);
2730
- const logMethod = resolveLogMethod(module, record.level);
2731
- try {
2732
- logMethod(record.message, attributes);
2733
- } catch (error) {
2734
- warnOnce5(
2735
- `sentry-log:${key}`,
2736
- "[Blyp] Failed to deliver log to Sentry.",
2737
- error
2738
- );
2739
- }
2740
- const exception = extractExceptionCandidate(record);
2741
- if (!exception) {
2742
- return;
2743
- }
2744
- try {
2745
- module.withScope((scope) => {
2746
- scope.setLevel(normalizeScopeLevel2(record.level));
2747
- scope.setContext("blyp", attributes);
2748
- scope.setExtra("blyp.payload", serializeLogRecord(record));
2749
- module.captureException(exception);
2750
- });
2751
- } catch (error) {
2752
- warnOnce5(
2753
- `sentry-exception:${key}`,
2754
- "[Blyp] Failed to capture exception in Sentry.",
2755
- error
2756
- );
2757
- }
2758
- },
2759
- async flush() {
2760
- try {
2761
- await module.flush(2e3);
2762
- } catch (error) {
2763
- warnOnce5(
2764
- `sentry-flush:${key}`,
2765
- "[Blyp] Failed to flush Sentry logs.",
2766
- error
2767
- );
2768
- }
2769
- }
2770
- };
2771
- }
2772
- var warnedKeys5 = /* @__PURE__ */ new Set();
2773
- var testHooks4 = {};
2774
- var warnOnce6 = createErrorOnceLogger(warnedKeys5);
2775
- function normalizeOTLPRecord(record, connector, source = "server") {
2776
- const severity = resolveSeverity2(record.level);
2777
- const body = typeof record.message === "string" ? record.message : String(record.message);
2778
- const recordType = getRecordType(record);
2779
- const caller = typeof record.caller === "string" ? record.caller : void 0;
2780
- const groupId = getField(record, "groupId");
2781
- const method = getField(record, "method");
2782
- const path3 = getField(record, "path");
2783
- const status = getField(record, "status");
2784
- const duration = getField(record, "duration");
2785
- const pagePath = getClientPageField(record, "pathname");
2786
- const pageUrl = getClientPageField(record, "url");
2787
- const sessionId = getClientSessionField(record, "sessionId");
2788
- const pageId = getClientSessionField(record, "pageId");
2789
- const attributes = {
2790
- "blyp.level": record.level,
2791
- "blyp.source": source,
2792
- "blyp.payload": serializeLogRecord(record)
2793
- };
2794
- const ifTruthy = [
2795
- ["blyp.type", recordType],
2796
- ["blyp.caller", caller],
2797
- ["blyp.group_id", groupId],
2798
- ["http.method", method],
2799
- ["url.path", path3],
2800
- ["client.page_path", pagePath],
2801
- ["client.page_url", pageUrl],
2802
- ["client.session_id", sessionId],
2803
- ["client.page_id", pageId]
2804
- ];
2805
- const ifDefined = [
2806
- ["http.status_code", status],
2807
- ["blyp.duration_ms", duration]
2808
- ];
2809
- for (const [k, v] of ifTruthy) if (v) attributes[k] = v;
2810
- for (const [k, v] of ifDefined) if (v !== void 0) attributes[k] = v;
2811
- return {
2812
- body,
2813
- severityText: severity.text,
2814
- severityNumber: severity.number,
2815
- attributes,
2816
- resourceAttributes: {
2817
- "service.name": connector.serviceName
2818
- }
2819
- };
2820
- }
2821
- function resolveSeverity2(level) {
2822
- switch (level) {
2823
- case "debug":
2824
- return { text: "debug", number: SeverityNumber.DEBUG };
2825
- case "warning":
2826
- case "warn":
2827
- return { text: "warn", number: SeverityNumber.WARN };
2828
- case "error":
2829
- return { text: "error", number: SeverityNumber.ERROR };
2830
- case "critical":
2831
- return { text: "fatal", number: SeverityNumber.FATAL };
2832
- case "success":
2833
- case "table":
2834
- case "info":
2835
- default:
2836
- return { text: "info", number: SeverityNumber.INFO };
2837
- }
2838
- }
2839
- function registerShutdownHooks3(key, shutdown) {
2840
- const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
2841
- for (const event of handlers) {
2842
- process.once(event, async () => {
2843
- try {
2844
- await shutdown();
2845
- } catch (error) {
2846
- warnOnce6(
2847
- `${key}:shutdown`,
2848
- "[Blyp] Failed to flush OTLP logs during shutdown.",
2849
- error
2850
- );
2851
- }
2852
- if (event !== "beforeExit") {
2853
- process.exit(0);
2854
- }
2855
- });
2856
- }
2857
- }
2858
- function resolveTransportHeaders(connector) {
2859
- const headers = {
2860
- ...connector.headers ?? {}
2861
- };
2862
- if (headers.Authorization === void 0 && connector.auth) {
2863
- headers.Authorization = connector.auth;
2864
- }
2865
- return headers;
2866
- }
2867
- function createDefaultTransport2(connector) {
2868
- const exporter = new OTLPLogExporter({
2869
- url: connector.endpoint,
2870
- headers: resolveTransportHeaders(connector)
2871
- });
2872
- const provider = new LoggerProvider({
2873
- resource: resourceFromAttributes({
2874
- "service.name": connector.serviceName
2875
- }),
2876
- processors: [new BatchLogRecordProcessor(exporter)]
2877
- });
2878
- const logger2 = provider.getLogger(`blyp-otlp:${connector.name}`);
2879
- return {
2880
- emit(payload) {
2881
- logger2.emit({
2882
- body: payload.body,
2883
- severityText: payload.severityText,
2884
- severityNumber: payload.severityNumber,
2885
- attributes: payload.attributes
2886
- });
2887
- },
2888
- flush() {
2889
- return provider.forceFlush();
2890
- },
2891
- shutdown() {
2892
- return provider.shutdown();
2893
- }
2894
- };
2895
- }
2896
- function resolveConnectors(config) {
2897
- const connectors = isBlypConfig(config) ? config.connectors?.otlp ?? [] : config;
2898
- return connectors.map((connector) => {
2899
- const headers = {
2900
- ...connector.headers ?? {}
2901
- };
2902
- const enabled = connector.enabled ?? false;
2903
- const endpoint = connector.endpoint;
2904
- const explicitReady = "ready" in connector && typeof connector.ready === "boolean" ? connector.ready : void 0;
2905
- const ready = (explicitReady ?? (enabled && isAbsoluteHttpUrl(endpoint))) && isAbsoluteHttpUrl(endpoint);
24
+ const mod = await import(BUN_SQLITE_MODULE);
25
+ const Database = mod.default;
26
+ runtime = 'bun';
2906
27
  return {
2907
- name: connector.name,
2908
- enabled,
2909
- mode: connector.mode ?? "auto",
2910
- endpoint,
2911
- headers,
2912
- auth: connector.auth,
2913
- serviceName: connector.serviceName ?? "blyp-app",
2914
- ready,
2915
- status: ready ? "enabled" : "missing"
28
+ create(filePath) {
29
+ return new Database(filePath);
30
+ },
31
+ exec(instance, sql) {
32
+ instance.exec(sql);
33
+ },
34
+ prepare(instance, sql) {
35
+ return instance.prepare(sql);
36
+ },
37
+ close(instance) {
38
+ instance.close();
39
+ },
40
+ run(statement, params) {
41
+ statement.run(...params);
42
+ },
43
+ all(statement, params) {
44
+ return statement.all(...params);
45
+ },
2916
46
  };
2917
- });
2918
- }
2919
- function createUnavailableSender(name, connector) {
2920
- const senderName = name || connector?.name || "otlp";
2921
- const key = `${senderName}:${connector?.serviceName ?? "blyp-app"}:${connector?.endpoint ?? "missing"}`;
2922
- const emitUnavailableWarning = () => {
2923
- warnOnce6(
2924
- `otlp-unavailable:${key}`,
2925
- `[Blyp] OTLP target "${senderName}" is not configured or not ready. Skipping OTLP delivery.`
2926
- );
2927
- };
2928
- return {
2929
- name: senderName,
2930
- enabled: connector?.enabled ?? false,
2931
- ready: false,
2932
- mode: connector?.mode ?? "auto",
2933
- serviceName: connector?.serviceName ?? "blyp-app",
2934
- endpoint: connector?.endpoint,
2935
- status: "missing",
2936
- send(_record, options = {}) {
2937
- if (options.warnIfUnavailable) {
2938
- emitUnavailableWarning();
2939
- }
2940
- },
2941
- async flush() {
2942
- }
2943
- };
2944
- }
2945
- function createSender(connector) {
2946
- if (!connector.ready || !connector.endpoint) {
2947
- return createUnavailableSender(connector.name, connector);
2948
- }
2949
- const key = `${connector.name}:${connector.serviceName}:${connector.endpoint}:${connector.mode}`;
2950
- const transportConnector = {
2951
- ...connector,
2952
- headers: resolveTransportHeaders(connector)
2953
- };
2954
- const transport = testHooks4.createTransport?.(transportConnector) ?? createDefaultTransport2(transportConnector);
2955
- return {
2956
- name: connector.name,
2957
- enabled: connector.enabled,
2958
- ready: connector.ready,
2959
- mode: connector.mode,
2960
- serviceName: connector.serviceName,
2961
- endpoint: connector.endpoint,
2962
- status: connector.status,
2963
- send(record, options = {}) {
2964
- const source = options.source ?? "server";
2965
- const normalized = normalizeOTLPRecord(record, connector, source);
2966
- try {
2967
- const result = transport.emit(normalized);
2968
- if (result && typeof result.catch === "function") {
2969
- void result.catch((error) => {
2970
- warnOnce6(
2971
- `otlp-emit:${key}`,
2972
- `[Blyp] Failed to deliver log to OTLP target "${connector.name}".`,
2973
- error
2974
- );
2975
- });
2976
- }
2977
- } catch (error) {
2978
- warnOnce6(
2979
- `otlp-emit:${key}`,
2980
- `[Blyp] Failed to deliver log to OTLP target "${connector.name}".`,
2981
- error
2982
- );
2983
- }
2984
- },
2985
- async flush() {
2986
- try {
2987
- if (transport.flush) {
2988
- await transport.flush();
2989
- }
2990
- } catch (error) {
2991
- warnOnce6(
2992
- `otlp-flush:${key}`,
2993
- `[Blyp] Failed to flush OTLP logs for target "${connector.name}".`,
2994
- error
2995
- );
2996
- }
2997
- }
2998
- };
2999
- }
3000
- function createOTLPRegistry(config) {
3001
- const senders = /* @__PURE__ */ new Map();
3002
- for (const connector of resolveConnectors(config)) {
3003
- senders.set(connector.name, createSender(connector));
3004
- }
3005
- const registry = {
3006
- get(name) {
3007
- return senders.get(name) ?? createUnavailableSender(name);
3008
- },
3009
- getAutoForwardTargets() {
3010
- return Array.from(senders.values()).filter((sender) => sender.ready && sender.mode === "auto");
3011
- },
3012
- send(name, record, options = {}) {
3013
- const sender = senders.get(name) ?? createUnavailableSender(name);
3014
- sender.send(record, options);
3015
- },
3016
- async flush() {
3017
- await Promise.all(Array.from(senders.values()).map((sender) => sender.flush()));
3018
- }
3019
- };
3020
- registerShutdownHooks3("otlp-registry", () => registry.flush());
3021
- return registry;
3022
- }
3023
- var _RuntimeDetector = class _RuntimeDetector {
3024
- constructor() {
3025
- __publicField(this, "_type", null);
3026
- }
3027
- static getInstance() {
3028
- if (!_RuntimeDetector.instance) {
3029
- _RuntimeDetector.instance = new _RuntimeDetector();
3030
- }
3031
- return _RuntimeDetector.instance;
3032
- }
3033
- get type() {
3034
- if (this._type === null) {
3035
- this._type = this.detectRuntime();
3036
- }
3037
- return this._type;
3038
- }
3039
- get isBun() {
3040
- return this.type === "bun";
3041
- }
3042
- get isNode() {
3043
- return this.type === "node";
3044
- }
3045
- detectRuntime() {
3046
- if (typeof Bun !== "undefined" && typeof Bun.file === "function") {
3047
- return "bun";
3048
- }
3049
- return "node";
3050
- }
3051
- };
3052
- __publicField(_RuntimeDetector, "instance");
3053
- var RuntimeDetector = _RuntimeDetector;
3054
- var BunAdapter = class {
3055
- constructor() {
3056
- __publicField(this, "type", "bun");
3057
- __publicField(this, "isBun", true);
3058
- __publicField(this, "isNode", false);
3059
- __publicField(this, "file", {
3060
- existsSync: (filePath) => {
3061
- try {
3062
- const file = Bun.file(filePath);
3063
- return file.size > 0 || file.name !== "";
3064
- } catch {
3065
- return false;
3066
- }
47
+ } catch {}
48
+
49
+ try {
50
+ const mod = await import(NODE_SQLITE_MODULE);
51
+ runtime = 'node';
52
+ return {
53
+ create(filePath) {
54
+ return new mod.DatabaseSync(filePath);
3067
55
  },
3068
- mkdirSync: (filePath, options) => {
3069
- try {
3070
- fs.mkdirSync(filePath, options);
3071
- } catch {
3072
- }
56
+ exec(instance, sql) {
57
+ instance.exec(sql);
3073
58
  },
3074
- writeFileSync: (filePath, data) => {
3075
- Bun.write(filePath, data);
3076
- }
3077
- });
3078
- __publicField(this, "path", {
3079
- join: (...paths) => {
3080
- return path.join(...paths);
3081
- }
3082
- });
3083
- __publicField(this, "env", {
3084
- get: (key) => Bun.env[key]
3085
- });
3086
- __publicField(this, "cwd", () => {
3087
- return process.cwd();
3088
- });
3089
- }
3090
- };
3091
- var NodeAdapter = class {
3092
- constructor() {
3093
- __publicField(this, "type", "node");
3094
- __publicField(this, "isBun", false);
3095
- __publicField(this, "isNode", true);
3096
- __publicField(this, "file", {
3097
- existsSync: (filePath) => fs.existsSync(filePath),
3098
- mkdirSync: (filePath, options) => {
3099
- fs.mkdirSync(filePath, options);
59
+ prepare(instance, sql) {
60
+ return instance.prepare(sql);
3100
61
  },
3101
- writeFileSync: (filePath, data) => {
3102
- fs.writeFileSync(filePath, data);
3103
- }
3104
- });
3105
- __publicField(this, "path", {
3106
- join: (...paths) => path.join(...paths)
3107
- });
3108
- __publicField(this, "env", {
3109
- get: (key) => process.env[key]
3110
- });
3111
- __publicField(this, "cwd", () => process.cwd());
3112
- }
3113
- };
3114
- function createRuntimeAdapter() {
3115
- const detector = RuntimeDetector.getInstance();
3116
- if (detector.isBun) {
3117
- return new BunAdapter();
3118
- }
3119
- return new NodeAdapter();
3120
- }
3121
- var runtime = createRuntimeAdapter();
62
+ close(instance) {
63
+ instance.close();
64
+ },
65
+ run(statement, params) {
66
+ statement.run(...params);
67
+ },
68
+ all(statement, params) {
69
+ return statement.all(...params);
70
+ },
71
+ };
72
+ } catch {}
3122
73
 
3123
- // src/core/structured-log.ts
3124
- function serializeMessage2(message) {
3125
- if (typeof message === "string") {
3126
- return message;
3127
- }
3128
- if (message !== null && typeof message === "object") {
3129
- try {
3130
- return JSON.stringify(
3131
- message,
3132
- (_key, value) => {
3133
- if (typeof value === "function") {
3134
- return `[Function: ${value.name || "anonymous"}]`;
3135
- }
3136
- if (value === void 0) {
3137
- return "[undefined]";
3138
- }
3139
- if (typeof value === "symbol") {
3140
- return value.toString();
3141
- }
3142
- return value;
3143
- },
3144
- 2
3145
- );
3146
- } catch {
3147
- return "[Object]";
3148
- }
3149
- }
3150
- return String(message);
74
+ throw new Error('No built-in SQLite runtime is available in this worker.');
3151
75
  }
3152
- function normalizeEventData(message, args) {
3153
- if (typeof message === "string") {
3154
- if (args.length === 0) {
3155
- return void 0;
3156
- }
3157
- return args.length === 1 ? args[0] : args;
76
+
77
+ let adapter;
78
+
79
+ function ensureReady() {
80
+ if (!db || !adapter) {
81
+ throw new Error('SQLite durable queue is not initialized.');
3158
82
  }
3159
- const values = [message, ...args];
3160
- return values.length === 1 ? values[0] : values;
3161
83
  }
3162
- function normalizeDetails(value) {
3163
- if (!value || typeof value !== "object" || Array.isArray(value)) {
3164
- return void 0;
3165
- }
3166
- return value;
84
+
85
+ function normalizeConnectorTarget(value) {
86
+ return typeof value === 'string' && value.length > 0 ? value : null;
3167
87
  }
3168
- function normalizeError2(error, fallbackStatus) {
3169
- if (error === void 0 || error === null) {
3170
- return fallbackStatus === void 0 || fallbackStatus < 400 ? void 0 : {
3171
- message: `HTTP ${fallbackStatus}`,
3172
- code: fallbackStatus,
3173
- type: "HttpError"
3174
- };
3175
- }
3176
- if (error instanceof Error) {
3177
- const errorLike = error;
3178
- return {
3179
- message: error.message,
3180
- code: errorLike.code,
3181
- type: errorLike.type ?? error.name ?? error.constructor?.name,
3182
- stack: error.stack,
3183
- why: errorLike.why,
3184
- fix: errorLike.fix,
3185
- link: errorLike.link,
3186
- details: normalizeDetails(errorLike.details),
3187
- cause: errorLike.cause
3188
- };
3189
- }
3190
- if (typeof error === "object") {
3191
- const record = error;
3192
- const statusCode = typeof record.statusCode === "number" ? record.statusCode : typeof record.status === "number" ? record.status : fallbackStatus;
3193
- return {
3194
- message: typeof record.message === "string" ? record.message : `HTTP ${statusCode ?? 500}`,
3195
- code: typeof record.code === "string" || typeof record.code === "number" ? record.code : statusCode,
3196
- type: typeof record.type === "string" ? record.type : typeof record.name === "string" ? record.name : "Error",
3197
- stack: typeof record.stack === "string" ? record.stack : void 0,
3198
- why: typeof record.why === "string" ? record.why : void 0,
3199
- fix: typeof record.fix === "string" ? record.fix : void 0,
3200
- link: typeof record.link === "string" ? record.link : void 0,
3201
- details: normalizeDetails(record.details),
3202
- cause: record.cause
3203
- };
3204
- }
3205
- return {
3206
- message: String(error),
3207
- code: fallbackStatus,
3208
- type: typeof error
3209
- };
88
+
89
+ function createConnectorCondition() {
90
+ return '(connector_type = ? AND ((connector_target IS NULL AND ? IS NULL) OR connector_target = ?))';
3210
91
  }
3211
- function resolveEmitStatus(options) {
3212
- if (options.response && typeof options.response.status === "number") {
3213
- return options.response.status;
3214
- }
3215
- if (typeof options.status === "number") {
3216
- return options.status;
3217
- }
3218
- if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.statusCode === "number") {
3219
- return options.error.statusCode;
3220
- }
3221
- if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.status === "number") {
3222
- return options.error.status;
92
+
93
+ function updateConnectorDeliveryStatus(item, success) {
94
+ const connectorTarget = normalizeConnectorTarget(item.connectorTarget);
95
+ const select = adapter.prepare(
96
+ db,
97
+ 'SELECT rowid FROM connector_delivery_status WHERE ' + createConnectorCondition() + ' LIMIT 1'
98
+ );
99
+ const existing = adapter.all(select, [item.connectorType, connectorTarget, connectorTarget])[0];
100
+
101
+ if (existing) {
102
+ const update = adapter.prepare(
103
+ db,
104
+ success
105
+ ? 'UPDATE connector_delivery_status SET last_success_at = ?, last_error = NULL, updated_at = ? WHERE rowid = ?'
106
+ : 'UPDATE connector_delivery_status SET last_failure_at = ?, last_error = ?, updated_at = ? WHERE rowid = ?'
107
+ );
108
+
109
+ adapter.run(
110
+ update,
111
+ success
112
+ ? [item.timestamp, item.timestamp, existing.rowid]
113
+ : [item.timestamp, item.lastError ?? null, item.timestamp, existing.rowid]
114
+ );
115
+ return;
3223
116
  }
3224
- return options.error ? 500 : void 0;
117
+
118
+ const insert = adapter.prepare(
119
+ db,
120
+ 'INSERT INTO connector_delivery_status (connector_type, connector_target, last_success_at, last_failure_at, last_error, updated_at) VALUES (?, ?, ?, ?, ?, ?)'
121
+ );
122
+
123
+ adapter.run(insert, [
124
+ item.connectorType,
125
+ connectorTarget,
126
+ success ? item.timestamp : null,
127
+ success ? null : item.timestamp,
128
+ success ? null : item.lastError ?? null,
129
+ item.timestamp,
130
+ ]);
3225
131
  }
3226
- function createStructuredLog(groupId, options) {
3227
- const startedAt = performance.now();
3228
- const fields = { ...options.initialFields ?? {} };
3229
- const events = [];
3230
- let emittedPayload;
3231
- options.onCreate?.();
3232
- const appendEvent = (level, message, args) => {
3233
- events.push({
3234
- level,
3235
- message: serializeMessage2(message),
3236
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3237
- ...normalizeEventData(message, args) === void 0 ? {} : { data: normalizeEventData(message, args) }
3238
- });
3239
- return structuredLog;
3240
- };
3241
- const structuredLog = {
3242
- set(extraFields) {
3243
- Object.assign(fields, extraFields);
3244
- return structuredLog;
3245
- },
3246
- debug(message, ...args) {
3247
- return appendEvent("debug", message, args);
3248
- },
3249
- info(message, ...args) {
3250
- return appendEvent("info", message, args);
3251
- },
3252
- warn(message, ...args) {
3253
- return appendEvent("warn", message, args);
3254
- },
3255
- warning(message, ...args) {
3256
- return appendEvent("warning", message, args);
3257
- },
3258
- error(message, ...args) {
3259
- return appendEvent("error", message, args);
3260
- },
3261
- success(message, ...args) {
3262
- return appendEvent("success", message, args);
3263
- },
3264
- critical(message, ...args) {
3265
- return appendEvent("critical", message, args);
3266
- },
3267
- table(message, data) {
3268
- return appendEvent("table", message, data === void 0 ? [] : [data]);
3269
- },
3270
- emit(emitOptions = {}) {
3271
- if (emittedPayload) {
3272
- return emittedPayload;
3273
- }
3274
- const defaultFields = options.resolveDefaultFields?.() ?? {};
3275
- const status = resolveEmitStatus(emitOptions);
3276
- const error = normalizeError2(emitOptions.error, status);
3277
- const level = emitOptions.level ?? (error ? "error" : "info");
3278
- const payload = {
3279
- ...defaultFields,
3280
- ...fields,
3281
- groupId,
3282
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3283
- level,
3284
- duration: Math.round(performance.now() - startedAt),
3285
- ...typeof status === "number" ? { status } : {},
3286
- ...events.length > 0 ? { events: [...events] } : {},
3287
- ...error ? { error } : {}
3288
- };
3289
- options.write(payload, emitOptions.message ?? "structured_log");
3290
- emittedPayload = payload;
3291
- options.onEmit?.(payload);
3292
- return payload;
3293
- }
3294
- };
3295
- return structuredLog;
132
+
133
+ function initializeSchema() {
134
+ ensureReady();
135
+ adapter.exec(db, [
136
+ 'PRAGMA journal_mode = WAL;',
137
+ 'PRAGMA busy_timeout = 5000;',
138
+ 'CREATE TABLE IF NOT EXISTS connector_queue_meta (schema_version INTEGER NOT NULL);',
139
+ 'DELETE FROM connector_queue_meta;',
140
+ 'INSERT INTO connector_queue_meta (schema_version) VALUES (2);',
141
+ 'CREATE TABLE IF NOT EXISTS connector_jobs (',
142
+ ' id TEXT PRIMARY KEY,',
143
+ ' connector_type TEXT NOT NULL,',
144
+ ' connector_target TEXT NULL,',
145
+ ' operation TEXT NOT NULL,',
146
+ ' payload_json TEXT NOT NULL,',
147
+ ' attempt_count INTEGER NOT NULL,',
148
+ ' max_attempts INTEGER NOT NULL,',
149
+ ' next_attempt_at INTEGER NOT NULL,',
150
+ ' state TEXT NOT NULL,',
151
+ ' last_error TEXT NULL,',
152
+ ' created_at INTEGER NOT NULL,',
153
+ ' updated_at INTEGER NOT NULL,',
154
+ ' claimed_at INTEGER NULL',
155
+ ');',
156
+ 'CREATE TABLE IF NOT EXISTS connector_dead_letters (',
157
+ ' id TEXT PRIMARY KEY,',
158
+ ' connector_type TEXT NOT NULL,',
159
+ ' connector_target TEXT NULL,',
160
+ ' operation TEXT NOT NULL,',
161
+ ' payload_json TEXT NOT NULL,',
162
+ ' attempt_count INTEGER NOT NULL,',
163
+ ' max_attempts INTEGER NOT NULL,',
164
+ ' last_error TEXT NULL,',
165
+ ' first_enqueued_at INTEGER NOT NULL,',
166
+ ' dead_lettered_at INTEGER NOT NULL,',
167
+ ' last_attempt_at INTEGER NOT NULL',
168
+ ');',
169
+ 'CREATE TABLE IF NOT EXISTS connector_delivery_status (',
170
+ ' connector_type TEXT NOT NULL,',
171
+ ' connector_target TEXT NULL,',
172
+ ' last_success_at INTEGER NULL,',
173
+ ' last_failure_at INTEGER NULL,',
174
+ ' last_error TEXT NULL,',
175
+ ' updated_at INTEGER NOT NULL',
176
+ ');',
177
+ 'CREATE INDEX IF NOT EXISTS idx_connector_jobs_state_due ON connector_jobs(state, next_attempt_at);',
178
+ 'CREATE INDEX IF NOT EXISTS idx_connector_jobs_connector_state_due ON connector_jobs(connector_type, connector_target, state, next_attempt_at);',
179
+ 'CREATE INDEX IF NOT EXISTS idx_connector_dead_letters_connector_dead_lettered ON connector_dead_letters(connector_type, connector_target, dead_lettered_at);',
180
+ 'CREATE INDEX IF NOT EXISTS idx_connector_delivery_status_connector ON connector_delivery_status(connector_type, connector_target);'
181
+ ].join('\\n'));
3296
182
  }
3297
183
 
3298
- // src/core/logger.ts
3299
- var LOGGER_FACTORY = /* @__PURE__ */ Symbol("blyp.logger.factory");
3300
- var CUSTOM_LEVELS = {
3301
- success: 25,
3302
- info: 30,
3303
- debug: 35,
3304
- table: 37,
3305
- warning: 40,
3306
- error: 50,
3307
- critical: 60
3308
- };
3309
- var CONSOLE_LEVELS = {
3310
- success: "success",
3311
- critical: "critical",
3312
- warning: "warning",
3313
- info: "info",
3314
- debug: "debug",
3315
- error: "error",
3316
- warn: "warn",
3317
- table: "debug"
3318
- };
3319
- var MAGENTA = "\x1B[35m";
3320
- var RESET = "\x1B[0m";
3321
- function summarizeClientConsoleData(data) {
3322
- if (!data || typeof data !== "object" || Array.isArray(data)) {
3323
- return null;
3324
- }
3325
- const record = data;
3326
- const summary = {};
3327
- if (record.data !== void 0) {
3328
- summary.data = record.data;
3329
- }
3330
- const pathname = typeof record.page?.pathname === "string" ? record.page.pathname : void 0;
3331
- const url = typeof record.page?.url === "string" ? record.page.url : void 0;
3332
- if (pathname || url) {
3333
- summary.page = pathname ?? url;
3334
- }
3335
- if (record.metadata !== void 0) {
3336
- summary.metadata = record.metadata;
3337
- }
3338
- return Object.keys(summary).length > 0 ? summary : null;
184
+ function reclaimExpired(now) {
185
+ ensureReady();
186
+ const statement = adapter.prepare(
187
+ db,
188
+ 'UPDATE connector_jobs SET state = ?, claimed_at = NULL, updated_at = ? WHERE state = ? AND claimed_at IS NOT NULL AND claimed_at <= ?'
189
+ );
190
+ adapter.run(statement, ['pending', now, 'claimed', now - CLAIM_LEASE_MS]);
3339
191
  }
3340
- function getConsoleDataPayload(data) {
3341
- if (!data || typeof data !== "object" || Array.isArray(data)) {
3342
- return { hidden: false, value: data };
3343
- }
3344
- const record = data;
3345
- if (record.type === "http_request" || record.type === "http_error") {
3346
- return { hidden: true };
3347
- }
3348
- if (record.type === "client_log") {
3349
- const summary = summarizeClientConsoleData(data);
3350
- if (!summary) {
3351
- return { hidden: true };
3352
- }
3353
- return {
3354
- hidden: false,
3355
- value: summary
3356
- };
192
+
193
+ function insertJobs(jobs) {
194
+ ensureReady();
195
+ if (!Array.isArray(jobs) || jobs.length === 0) {
196
+ return;
3357
197
  }
3358
- return { hidden: false, value: data };
3359
- }
3360
- function createPinoLogger(config) {
3361
- if (config.pretty) {
3362
- const pinoPretty = __require("pino-pretty");
3363
- const pretty = pinoPretty.default({
3364
- colorize: true,
3365
- translateTime: "SYS:HH:MM:ss",
3366
- ignore: "pid,hostname,caller",
3367
- customColors: {
3368
- success: "green",
3369
- critical: "red bold",
3370
- info: "blue",
3371
- warning: "yellow",
3372
- error: "red",
3373
- debug: "cyan",
3374
- table: "cyan"
3375
- },
3376
- messageFormat: (log, messageKey) => {
3377
- const message = String(log[messageKey] ?? "");
3378
- const caller = typeof log.caller === "string" ? log.caller.trim() : "";
3379
- if (!caller) {
3380
- return message;
3381
- }
3382
- return `${message} ${MAGENTA}${caller}${RESET}`;
3383
- }
3384
- });
3385
- return pino(
3386
- {
3387
- level: config.level,
3388
- customLevels: CUSTOM_LEVELS
3389
- },
3390
- pretty
198
+
199
+ adapter.exec(db, 'BEGIN');
200
+ try {
201
+ const statement = adapter.prepare(
202
+ db,
203
+ 'INSERT OR REPLACE INTO connector_jobs (id, connector_type, connector_target, operation, payload_json, attempt_count, max_attempts, next_attempt_at, state, last_error, created_at, updated_at, claimed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
3391
204
  );
205
+
206
+ for (const job of jobs) {
207
+ adapter.run(statement, [
208
+ job.id,
209
+ job.connectorType,
210
+ normalizeConnectorTarget(job.connectorTarget),
211
+ job.operation,
212
+ job.payloadJson,
213
+ job.attemptCount,
214
+ job.maxAttempts,
215
+ job.nextAttemptAt,
216
+ job.state,
217
+ job.lastError ?? null,
218
+ job.createdAt,
219
+ job.updatedAt,
220
+ job.claimedAt ?? null,
221
+ ]);
222
+ }
223
+
224
+ adapter.exec(db, 'COMMIT');
225
+ } catch (error) {
226
+ adapter.exec(db, 'ROLLBACK');
227
+ throw error;
3392
228
  }
3393
- return pino({
3394
- level: config.level,
3395
- customLevels: CUSTOM_LEVELS
3396
- });
3397
229
  }
3398
- function getLoggerFactory(logger2) {
3399
- const factory = logger2[LOGGER_FACTORY];
3400
- if (!factory) {
3401
- throw new Error("Unsupported Blyp logger instance");
230
+
231
+ function claimDue(limit, now) {
232
+ ensureReady();
233
+ reclaimExpired(now);
234
+
235
+ const select = adapter.prepare(
236
+ db,
237
+ 'SELECT * FROM connector_jobs WHERE state = ? AND next_attempt_at <= ? ORDER BY next_attempt_at ASC LIMIT ?'
238
+ );
239
+ const rows = adapter.all(select, ['pending', now, limit]);
240
+
241
+ if (!Array.isArray(rows) || rows.length === 0) {
242
+ return [];
3402
243
  }
3403
- return factory;
3404
- }
3405
- function getPostHogSender(logger2) {
3406
- return getLoggerFactory(logger2).posthog;
3407
- }
3408
- function getBetterStackSender(logger2) {
3409
- return getLoggerFactory(logger2).betterstack;
3410
- }
3411
- function tryGetPostHogSender(logger2) {
244
+
245
+ adapter.exec(db, 'BEGIN');
3412
246
  try {
3413
- return getPostHogSender(logger2);
3414
- } catch {
3415
- return null;
247
+ const update = adapter.prepare(
248
+ db,
249
+ 'UPDATE connector_jobs SET state = ?, claimed_at = ?, updated_at = ? WHERE id = ?'
250
+ );
251
+ for (const row of rows) {
252
+ adapter.run(update, ['claimed', now, now, row.id]);
253
+ row.state = 'claimed';
254
+ row.claimed_at = now;
255
+ row.updated_at = now;
256
+ }
257
+ adapter.exec(db, 'COMMIT');
258
+ } catch (error) {
259
+ adapter.exec(db, 'ROLLBACK');
260
+ throw error;
3416
261
  }
262
+
263
+ return rows.map((row) => ({
264
+ id: row.id,
265
+ connectorType: row.connector_type,
266
+ connectorTarget: row.connector_target ?? undefined,
267
+ operation: row.operation,
268
+ payloadJson: row.payload_json,
269
+ attemptCount: row.attempt_count,
270
+ maxAttempts: row.max_attempts,
271
+ nextAttemptAt: row.next_attempt_at,
272
+ state: row.state,
273
+ lastError: row.last_error ?? undefined,
274
+ createdAt: row.created_at,
275
+ updatedAt: row.updated_at,
276
+ claimedAt: row.claimed_at ?? undefined,
277
+ }));
3417
278
  }
3418
- function tryGetBetterStackSender(logger2) {
279
+
280
+ function ack(ids) {
281
+ ensureReady();
282
+ if (!Array.isArray(ids) || ids.length === 0) {
283
+ return;
284
+ }
285
+
286
+ adapter.exec(db, 'BEGIN');
3419
287
  try {
3420
- return getBetterStackSender(logger2);
3421
- } catch {
3422
- return null;
288
+ const statement = adapter.prepare(db, 'DELETE FROM connector_jobs WHERE id = ?');
289
+ for (const id of ids) {
290
+ adapter.run(statement, [id]);
291
+ }
292
+ adapter.exec(db, 'COMMIT');
293
+ } catch (error) {
294
+ adapter.exec(db, 'ROLLBACK');
295
+ throw error;
3423
296
  }
3424
297
  }
3425
- function getSentrySender(logger2) {
3426
- return getLoggerFactory(logger2).sentry;
3427
- }
3428
- function getOtlpRegistry(logger2) {
3429
- return getLoggerFactory(logger2).otlp;
3430
- }
3431
- function attachLoggerInternals(target, source) {
3432
- const factory = getLoggerFactory(source);
3433
- Object.defineProperty(target, LOGGER_FACTORY, {
3434
- value: factory,
3435
- enumerable: false,
3436
- configurable: false,
3437
- writable: false
3438
- });
3439
- return target;
3440
- }
3441
- function createLoggerWithSource(logger2, source) {
3442
- const factory = getLoggerFactory(logger2);
3443
- return factory.create(source, factory.bindings);
3444
- }
3445
- function createStructuredLogForLogger(logger2, groupId, options = {}) {
3446
- const factory = getLoggerFactory(logger2);
3447
- return createStructuredLog(groupId, {
3448
- initialFields: options.initialFields,
3449
- resolveDefaultFields: () => ({
3450
- ...factory.bindings,
3451
- ...options.resolveDefaultFields?.() ?? {}
3452
- }),
3453
- write: (payload, message) => {
3454
- factory.writeStructured(payload, message, "structured-flush");
3455
- },
3456
- onCreate: options.onCreate,
3457
- onEmit: options.onEmit
3458
- });
3459
- }
3460
- function maybeSendToPostHog(posthog, record) {
3461
- if (isClientLogRecord(record)) {
298
+
299
+ function reschedule(items, now) {
300
+ ensureReady();
301
+ if (!Array.isArray(items) || items.length === 0) {
3462
302
  return;
3463
303
  }
3464
- if (!posthog.shouldAutoForwardServerLogs()) {
3465
- if (posthog.enabled && !posthog.ready) {
3466
- posthog.send(record, { source: "server", warnIfUnavailable: true });
304
+
305
+ adapter.exec(db, 'BEGIN');
306
+ try {
307
+ const statement = adapter.prepare(
308
+ db,
309
+ 'UPDATE connector_jobs SET state = ?, attempt_count = ?, next_attempt_at = ?, last_error = ?, claimed_at = NULL, updated_at = ? WHERE id = ?'
310
+ );
311
+ for (const item of items) {
312
+ adapter.run(statement, [
313
+ 'pending',
314
+ item.attemptCount,
315
+ item.nextAttemptAt,
316
+ item.lastError ?? null,
317
+ now,
318
+ item.id,
319
+ ]);
3467
320
  }
3468
- return;
321
+ adapter.exec(db, 'COMMIT');
322
+ } catch (error) {
323
+ adapter.exec(db, 'ROLLBACK');
324
+ throw error;
3469
325
  }
3470
- posthog.send(record, { source: "server", warnIfUnavailable: true });
3471
326
  }
3472
- function maybeSendToBetterStack(betterstack, record) {
3473
- if (isClientLogRecord(record)) {
327
+
328
+ function deadLetter(items) {
329
+ ensureReady();
330
+ if (!Array.isArray(items) || items.length === 0) {
3474
331
  return;
3475
332
  }
3476
- if (!betterstack.shouldAutoForwardServerLogs()) {
3477
- if (betterstack.enabled && !betterstack.ready) {
3478
- betterstack.send(record, { source: "server", warnIfUnavailable: true });
333
+
334
+ adapter.exec(db, 'BEGIN');
335
+ try {
336
+ const insert = adapter.prepare(
337
+ db,
338
+ 'INSERT OR REPLACE INTO connector_dead_letters (id, connector_type, connector_target, operation, payload_json, attempt_count, max_attempts, last_error, first_enqueued_at, dead_lettered_at, last_attempt_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
339
+ );
340
+ const remove = adapter.prepare(db, 'DELETE FROM connector_jobs WHERE id = ?');
341
+
342
+ for (const item of items) {
343
+ adapter.run(insert, [
344
+ item.id,
345
+ item.connectorType,
346
+ normalizeConnectorTarget(item.connectorTarget),
347
+ item.operation,
348
+ item.payloadJson,
349
+ item.attemptCount,
350
+ item.maxAttempts,
351
+ item.lastError ?? null,
352
+ item.firstEnqueuedAt,
353
+ item.deadLetteredAt,
354
+ item.lastAttemptAt,
355
+ ]);
356
+ adapter.run(remove, [item.id]);
3479
357
  }
3480
- return;
358
+
359
+ adapter.exec(db, 'COMMIT');
360
+ } catch (error) {
361
+ adapter.exec(db, 'ROLLBACK');
362
+ throw error;
3481
363
  }
3482
- betterstack.send(record, { source: "server", warnIfUnavailable: true });
3483
364
  }
3484
- function maybeSendToSentry(sentry, record) {
3485
- if (isClientLogRecord(record)) {
365
+
366
+ function markSuccess(items) {
367
+ ensureReady();
368
+ if (!Array.isArray(items) || items.length === 0) {
3486
369
  return;
3487
370
  }
3488
- if (!sentry.shouldAutoForwardServerLogs()) {
3489
- if (sentry.enabled && !sentry.ready) {
3490
- sentry.send(record, { source: "server", warnIfUnavailable: true });
371
+
372
+ adapter.exec(db, 'BEGIN');
373
+ try {
374
+ for (const item of items) {
375
+ updateConnectorDeliveryStatus(item, true);
3491
376
  }
3492
- return;
377
+ adapter.exec(db, 'COMMIT');
378
+ } catch (error) {
379
+ adapter.exec(db, 'ROLLBACK');
380
+ throw error;
3493
381
  }
3494
- sentry.send(record, { source: "server", warnIfUnavailable: true });
3495
382
  }
3496
- function maybeSendToOTLP(otlp, record) {
3497
- if (isClientLogRecord(record)) {
383
+
384
+ function markFailure(items) {
385
+ ensureReady();
386
+ if (!Array.isArray(items) || items.length === 0) {
3498
387
  return;
3499
388
  }
3500
- for (const sender of otlp.getAutoForwardTargets()) {
3501
- sender.send(record, { source: "server", warnIfUnavailable: true });
389
+
390
+ adapter.exec(db, 'BEGIN');
391
+ try {
392
+ for (const item of items) {
393
+ updateConnectorDeliveryStatus(item, false);
394
+ }
395
+ adapter.exec(db, 'COMMIT');
396
+ } catch (error) {
397
+ adapter.exec(db, 'ROLLBACK');
398
+ throw error;
3502
399
  }
3503
400
  }
3504
- function createLoggerInstance(rootRawLogger, sink, betterstack, posthog, sentry, otlp, bindings = {}, source = "root") {
3505
- const rawLogger = Object.keys(bindings).length > 0 ? rootRawLogger.child(bindings) : rootRawLogger;
3506
- const writeRecord = (level, message, args, writeSource = source) => {
3507
- if (writeSource === "root" && shouldDropRootLogWrite()) {
3508
- return;
3509
- }
3510
- const record = buildRecord(level, message, args, bindings);
3511
- const consoleMessage = serializeMessage(message);
3512
- const payload = {
3513
- caller: record.caller
401
+
402
+ function getStatusSummary() {
403
+ ensureReady();
404
+ const rows = [];
405
+ const byKey = new Map();
406
+
407
+ const statusRows = adapter.all(
408
+ adapter.prepare(
409
+ db,
410
+ 'SELECT connector_type, connector_target, last_success_at, last_failure_at, last_error, updated_at FROM connector_delivery_status'
411
+ ),
412
+ []
413
+ );
414
+
415
+ for (const row of statusRows) {
416
+ const key = row.connector_type + ':' + (row.connector_target ?? '');
417
+ const item = {
418
+ connectorType: row.connector_type,
419
+ connectorTarget: row.connector_target ?? undefined,
420
+ pendingCount: 0,
421
+ deadLetterCount: 0,
422
+ lastSuccessAt: row.last_success_at ?? undefined,
423
+ lastFailureAt: row.last_failure_at ?? undefined,
424
+ lastError: row.last_error ?? undefined,
425
+ updatedAt: row.updated_at ?? undefined,
3514
426
  };
3515
- const consoleData = getConsoleDataPayload(record.data);
3516
- if (!consoleData.hidden && consoleData.value !== void 0) {
3517
- payload.data = consoleData.value;
3518
- }
3519
- const consoleMethod = CONSOLE_LEVELS[level];
3520
- const boundLogger = rawLogger;
3521
- const logMethod = boundLogger[consoleMethod] ?? boundLogger.info ?? ((_payload, _message) => {
3522
- });
3523
- logMethod.call(
3524
- rawLogger,
3525
- payload,
3526
- consoleMessage
3527
- );
3528
- sink.write(record);
3529
- maybeSendToBetterStack(betterstack, record);
3530
- maybeSendToPostHog(posthog, record);
3531
- maybeSendToSentry(sentry, record);
3532
- maybeSendToOTLP(otlp, record);
3533
- };
3534
- const writeStructuredRecord = (payload, message, writeSource = "structured-flush") => {
3535
- const level = resolveStructuredWriteLevel(payload.level);
3536
- const record = buildStructuredRecord(level, message, payload, bindings);
3537
- const consoleMethod = CONSOLE_LEVELS[level];
3538
- const boundLogger = rawLogger;
3539
- const logMethod = boundLogger[consoleMethod] ?? boundLogger.info ?? ((_payload, _message) => {
3540
- });
3541
- logMethod.call(
3542
- rawLogger,
3543
- {
3544
- caller: record.caller,
3545
- ...payload
3546
- },
3547
- message
3548
- );
3549
- if (writeSource !== "root" || !shouldDropRootLogWrite()) {
3550
- sink.write(record);
3551
- }
3552
- maybeSendToBetterStack(betterstack, record);
3553
- maybeSendToPostHog(posthog, record);
3554
- maybeSendToSentry(sentry, record);
3555
- maybeSendToOTLP(otlp, record);
3556
- };
3557
- const logger2 = {
3558
- success: (message, ...args) => {
3559
- writeRecord("success", message, args);
3560
- },
3561
- critical: (message, ...args) => {
3562
- writeRecord("critical", message, args);
3563
- },
3564
- warning: (message, ...args) => {
3565
- writeRecord("warning", message, args);
3566
- },
3567
- info: (message, ...args) => {
3568
- writeRecord("info", message, args);
3569
- },
3570
- debug: (message, ...args) => {
3571
- writeRecord("debug", message, args);
3572
- },
3573
- error: (message, ...args) => {
3574
- writeRecord("error", message, args);
3575
- },
3576
- warn: (message, ...args) => {
3577
- writeRecord("warn", message, args);
3578
- },
3579
- table: (message, data) => {
3580
- if (data && typeof data === "object" && runtime.env.get("NODE_ENV") !== "production") {
3581
- console.log("TABLE:", message);
3582
- console.table(data);
3583
- }
3584
- writeRecord("table", message, data === void 0 ? [] : [data]);
3585
- },
3586
- flush: () => sink.flush(),
3587
- shutdown: () => sink.shutdown(),
3588
- createStructuredLog: (groupId, initial) => {
3589
- return createStructuredLogForLogger(logger2, groupId, {
3590
- initialFields: initial
3591
- });
3592
- },
3593
- child: (childBindings) => {
3594
- const mergedBindings = { ...bindings, ...childBindings };
3595
- return createLoggerInstance(
3596
- rootRawLogger,
3597
- sink,
3598
- betterstack,
3599
- posthog,
3600
- sentry,
3601
- otlp,
3602
- mergedBindings,
3603
- source
3604
- );
3605
- },
3606
- [LOGGER_FACTORY]: {
3607
- bindings,
3608
- betterstack,
3609
- posthog,
3610
- sentry,
3611
- otlp,
3612
- sink,
3613
- create: (nextSource, nextBindings = bindings) => {
3614
- return createLoggerInstance(
3615
- rootRawLogger,
3616
- sink,
3617
- betterstack,
3618
- posthog,
3619
- sentry,
3620
- otlp,
3621
- nextBindings,
3622
- nextSource
3623
- );
3624
- },
3625
- writeStructured: (payload, message, nextSource = "structured-flush") => {
3626
- writeStructuredRecord(payload, message, nextSource);
3627
- }
3628
- }
3629
- };
3630
- return logger2;
3631
- }
3632
- var loggerInstance = null;
3633
- function createBaseLogger(config) {
3634
- if (config === void 0 && loggerInstance) {
3635
- return loggerInstance;
427
+ byKey.set(key, item);
428
+ rows.push(item);
3636
429
  }
3637
- const resolvedConfig = resolveConfig(config);
3638
- const rawLogger = createPinoLogger(resolvedConfig);
3639
- const sink = createPrimarySink(resolvedConfig);
3640
- const betterstack = createBetterStackSender(resolvedConfig);
3641
- const posthog = createPostHogSender(resolvedConfig);
3642
- const sentry = createSentrySender(resolvedConfig);
3643
- const otlp = createOTLPRegistry(resolvedConfig);
3644
- const instance = createLoggerInstance(
3645
- rawLogger,
3646
- sink,
3647
- betterstack,
3648
- posthog,
3649
- sentry,
3650
- otlp
430
+
431
+ const pendingRows = adapter.all(
432
+ adapter.prepare(
433
+ db,
434
+ 'SELECT connector_type, connector_target, COUNT(*) AS count FROM connector_jobs WHERE state = ? GROUP BY connector_type, connector_target'
435
+ ),
436
+ ['pending']
3651
437
  );
3652
- if (config === void 0) {
3653
- loggerInstance = instance;
438
+
439
+ for (const row of pendingRows) {
440
+ const key = row.connector_type + ':' + (row.connector_target ?? '');
441
+ const item = byKey.get(key) ?? {
442
+ connectorType: row.connector_type,
443
+ connectorTarget: row.connector_target ?? undefined,
444
+ pendingCount: 0,
445
+ deadLetterCount: 0,
446
+ };
447
+ item.pendingCount = Number(row.count ?? 0);
448
+ if (!byKey.has(key)) {
449
+ byKey.set(key, item);
450
+ rows.push(item);
451
+ }
3654
452
  }
3655
- return instance;
3656
- }
3657
- createBaseLogger();
3658
453
 
3659
- // src/frameworks/shared/logger.ts
3660
- function buildVerboseLogMessage(method, statusCode, url, responseTime) {
3661
- const methodColor = getMethodColor(method);
3662
- const statusColor = getStatusColor(statusCode);
3663
- const timeColor = getResponseTimeColor(responseTime);
3664
- return `${methodColor} ${url} ${statusColor} ${timeColor}`;
3665
- }
3666
- function resolveClientLoggingConfig(clientLogging, defaultClientLogging) {
3667
- const defaultPath = normalizeEndpointPath(
3668
- defaultClientLogging?.path ?? DEFAULT_CLIENT_LOG_ENDPOINT
454
+ const deadLetterRows = adapter.all(
455
+ adapter.prepare(
456
+ db,
457
+ 'SELECT connector_type, connector_target, COUNT(*) AS count FROM connector_dead_letters GROUP BY connector_type, connector_target'
458
+ ),
459
+ []
3669
460
  );
3670
- const defaultConfig = defaultClientLogging?.enabled === false ? null : { path: defaultPath };
3671
- if (clientLogging === false) {
3672
- return null;
3673
- }
3674
- if (clientLogging === void 0) {
3675
- return defaultConfig;
3676
- }
3677
- if (clientLogging === true) {
3678
- return {
3679
- path: defaultPath
461
+
462
+ for (const row of deadLetterRows) {
463
+ const key = row.connector_type + ':' + (row.connector_target ?? '');
464
+ const item = byKey.get(key) ?? {
465
+ connectorType: row.connector_type,
466
+ connectorTarget: row.connector_target ?? undefined,
467
+ pendingCount: 0,
468
+ deadLetterCount: 0,
3680
469
  };
470
+ item.deadLetterCount = Number(row.count ?? 0);
471
+ if (!byKey.has(key)) {
472
+ byKey.set(key, item);
473
+ rows.push(item);
474
+ }
3681
475
  }
3682
- return {
3683
- ...defaultConfig,
3684
- ...clientLogging,
3685
- path: normalizeEndpointPath(clientLogging.path ?? defaultPath)
3686
- };
3687
- }
3688
- function resolveServerLogger(config = {}, loggerOverride) {
3689
- const resolvedConfig = resolveConfig({
3690
- ...config.level !== void 0 ? { level: config.level } : {},
3691
- ...config.pretty !== void 0 ? { pretty: config.pretty } : {},
3692
- ...config.destination !== void 0 ? { destination: config.destination } : {},
3693
- ...config.logDir !== void 0 ? { logDir: config.logDir } : {},
3694
- ...config.file !== void 0 ? { file: config.file } : {},
3695
- ...config.database !== void 0 ? { database: config.database } : {},
3696
- ...config.connectors !== void 0 ? { connectors: config.connectors } : {}
3697
- });
3698
- const {
3699
- level = resolvedConfig.level,
3700
- pretty = resolvedConfig.pretty,
3701
- destination = resolvedConfig.destination,
3702
- logDir = resolvedConfig.logDir,
3703
- file = resolvedConfig.file,
3704
- database = resolvedConfig.database,
3705
- autoLogging = true,
3706
- customProps,
3707
- logErrors = true,
3708
- ignorePaths,
3709
- clientLogging,
3710
- connectors
3711
- } = config;
3712
- const logger2 = createBaseLogger({
3713
- level,
3714
- pretty,
3715
- destination,
3716
- logDir,
3717
- file,
3718
- database,
3719
- connectors
476
+
477
+ return rows.sort((left, right) => {
478
+ const leftKey = left.connectorType + ':' + (left.connectorTarget ?? '');
479
+ const rightKey = right.connectorType + ':' + (right.connectorTarget ?? '');
480
+ return leftKey.localeCompare(rightKey);
3720
481
  });
3721
- const resolvedClientLogging = resolveClientLoggingConfig(
3722
- clientLogging,
3723
- resolvedConfig.clientLogging
3724
- );
3725
- const ingestionPath = resolvedClientLogging?.path ?? DEFAULT_CLIENT_LOG_ENDPOINT;
3726
- const resolvedIgnorePaths = resolvedClientLogging ? Array.from(/* @__PURE__ */ new Set([...ignorePaths ?? [], ingestionPath])) : ignorePaths;
3727
- return {
3728
- logger: logger2,
3729
- betterstack: getBetterStackSender(logger2),
3730
- posthog: getPostHogSender(logger2),
3731
- sentry: getSentrySender(logger2),
3732
- otlp: getOtlpRegistry(logger2),
3733
- resolvedConfig,
3734
- level,
3735
- pretty,
3736
- logDir,
3737
- file,
3738
- autoLogging,
3739
- customProps,
3740
- logErrors,
3741
- resolvedIgnorePaths,
3742
- resolvedClientLogging,
3743
- ingestionPath
3744
- };
3745
- }
3746
- function shouldSkipAutoLogging(config, ctx, path3) {
3747
- if (config.autoLogging === false) {
3748
- return true;
3749
- }
3750
- if (typeof config.autoLogging === "object" && config.autoLogging.ignore?.(ctx)) {
3751
- return true;
3752
- }
3753
- return shouldIgnorePath(path3, config.resolvedIgnorePaths);
3754
482
  }
3755
- function shouldSkipErrorLogging(config, path3) {
3756
- if (!config.logErrors) {
3757
- return true;
483
+
484
+ function listDeadLetters(limit, offset, connectorType, connectorTarget) {
485
+ ensureReady();
486
+ const clauses = [];
487
+ const params = [];
488
+
489
+ if (typeof connectorType === 'string' && connectorType.length > 0) {
490
+ clauses.push('connector_type = ?');
491
+ params.push(connectorType);
3758
492
  }
3759
- return shouldIgnorePath(path3, config.resolvedIgnorePaths);
3760
- }
3761
- function resolveAdditionalProps(config, ctx) {
3762
- return config.customProps ? config.customProps(ctx) : {};
3763
- }
3764
- function emitHttpRequestLog(logger2, level, request, path3, statusCode, responseTime, additionalProps = {}) {
3765
- const requestLogData = buildRequestLogData(
3766
- request,
3767
- "http_request",
3768
- path3,
3769
- statusCode,
3770
- responseTime,
3771
- additionalProps
3772
- );
3773
- if (level === "info") {
3774
- logger2.info(
3775
- buildInfoLogMessage(request.method, statusCode, path3, responseTime),
3776
- requestLogData
3777
- );
3778
- } else {
3779
- logger2.info(
3780
- buildVerboseLogMessage(request.method, statusCode, path3, responseTime),
3781
- requestLogData
3782
- );
3783
- if (Object.keys(additionalProps).length > 0) {
3784
- logger2.debug("Request context", additionalProps);
493
+
494
+ if (connectorTarget !== undefined) {
495
+ if (connectorTarget === null || connectorTarget === '') {
496
+ clauses.push('connector_target IS NULL');
497
+ } else {
498
+ clauses.push('connector_target = ?');
499
+ params.push(connectorTarget);
3785
500
  }
3786
501
  }
3787
- return requestLogData;
3788
- }
3789
- function emitHttpErrorLog(logger2, level, request, path3, statusCode, responseTime, error, additionalProps = {}, captureContext = {}) {
3790
- const errorLogData = buildRequestLogData(
3791
- request,
3792
- "http_error",
3793
- path3,
3794
- statusCode,
3795
- responseTime,
3796
- {
3797
- error: error?.message ?? `HTTP ${statusCode}`,
3798
- stack: error?.stack,
3799
- code: error?.code,
3800
- why: error?.why,
3801
- fix: error?.fix,
3802
- link: error?.link,
3803
- details: error?.details,
3804
- ...additionalProps
3805
- }
502
+
503
+ const whereSql = clauses.length > 0 ? ' WHERE ' + clauses.join(' AND ') : '';
504
+ const countRow = adapter.all(
505
+ adapter.prepare(db, 'SELECT COUNT(*) AS count FROM connector_dead_letters' + whereSql),
506
+ params
507
+ )[0];
508
+ const rows = adapter.all(
509
+ adapter.prepare(
510
+ db,
511
+ 'SELECT * FROM connector_dead_letters' + whereSql + ' ORDER BY dead_lettered_at DESC LIMIT ? OFFSET ?'
512
+ ),
513
+ [...params, limit, offset]
3806
514
  );
3807
- const message = level === "info" ? buildInfoLogMessage(request.method, statusCode, path3, responseTime) : buildVerboseLogMessage(request.method, statusCode, path3, responseTime);
3808
- logger2.error(message, errorLogData);
3809
- const posthog = tryGetPostHogSender(logger2);
3810
- if (posthog?.shouldAutoCaptureExceptions()) {
3811
- posthog.captureException(captureContext.error ?? error ?? message, {
3812
- source: "server",
3813
- warnIfUnavailable: true,
3814
- distinctId: captureContext.distinctId ?? getHeaderValue(request.headers, "x-posthog-distinct-id"),
3815
- properties: buildPostHogExceptionProperties(
3816
- {
3817
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3818
- level: "error",
3819
- message,
3820
- data: errorLogData
3821
- },
3822
- "server",
3823
- {
3824
- $request_method: request.method,
3825
- $request_path: path3,
3826
- $current_url: request.url,
3827
- $response_status_code: statusCode,
3828
- ...getHeaderValue(request.headers, "user-agent") ? { $user_agent: getHeaderValue(request.headers, "user-agent") } : {},
3829
- ...errorLogData.ip ? { $ip: errorLogData.ip } : {}
3830
- }
3831
- )
3832
- });
515
+
516
+ return {
517
+ items: rows.map((row) => ({
518
+ id: row.id,
519
+ connectorType: row.connector_type,
520
+ connectorTarget: row.connector_target ?? undefined,
521
+ operation: row.operation,
522
+ payloadJson: row.payload_json,
523
+ attemptCount: row.attempt_count,
524
+ maxAttempts: row.max_attempts,
525
+ lastError: row.last_error ?? undefined,
526
+ firstEnqueuedAt: row.first_enqueued_at,
527
+ deadLetteredAt: row.dead_lettered_at,
528
+ lastAttemptAt: row.last_attempt_at,
529
+ })),
530
+ total: Number(countRow?.count ?? 0),
531
+ };
532
+ }
533
+
534
+ function retryDeadLetters(ids, now) {
535
+ ensureReady();
536
+ if (!Array.isArray(ids) || ids.length === 0) {
537
+ return 0;
3833
538
  }
3834
- const betterstack = tryGetBetterStackSender(logger2);
3835
- if (betterstack?.shouldAutoCaptureExceptions()) {
3836
- betterstack.captureException(captureContext.error ?? error ?? message, {
3837
- source: "server",
3838
- warnIfUnavailable: true,
3839
- context: {
3840
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3841
- level: "error",
3842
- message,
3843
- status: statusCode,
3844
- path: path3,
3845
- data: errorLogData
539
+
540
+ adapter.exec(db, 'BEGIN');
541
+ try {
542
+ const select = adapter.prepare(db, 'SELECT * FROM connector_dead_letters WHERE id = ?');
543
+ const insert = adapter.prepare(
544
+ db,
545
+ 'INSERT OR REPLACE INTO connector_jobs (id, connector_type, connector_target, operation, payload_json, attempt_count, max_attempts, next_attempt_at, state, last_error, created_at, updated_at, claimed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
546
+ );
547
+ const remove = adapter.prepare(db, 'DELETE FROM connector_dead_letters WHERE id = ?');
548
+ let count = 0;
549
+
550
+ for (const id of ids) {
551
+ const row = adapter.all(select, [id])[0];
552
+ if (!row) {
553
+ continue;
3846
554
  }
3847
- });
3848
- }
3849
- return errorLogData;
3850
- }
3851
- async function parseClientLogPayload(request, body) {
3852
- if (body !== void 0) {
3853
- if (typeof body === "string") {
3854
- return JSON.parse(body);
555
+
556
+ adapter.run(insert, [
557
+ row.id,
558
+ row.connector_type,
559
+ row.connector_target ?? null,
560
+ row.operation,
561
+ row.payload_json,
562
+ 0,
563
+ row.max_attempts,
564
+ now,
565
+ 'pending',
566
+ null,
567
+ row.first_enqueued_at,
568
+ now,
569
+ null,
570
+ ]);
571
+ adapter.run(remove, [id]);
572
+ count += 1;
3855
573
  }
3856
- return body;
3857
- }
3858
- if (typeof request.json === "function") {
3859
- return await request.json();
3860
- }
3861
- throw new Error("Unable to parse client log payload");
3862
- }
3863
- function getClientLogMethod(logger2, level) {
3864
- switch (level) {
3865
- case "debug":
3866
- return logger2.debug;
3867
- case "info":
3868
- return logger2.info;
3869
- case "warning":
3870
- return logger2.warning;
3871
- case "error":
3872
- return logger2.error;
3873
- case "critical":
3874
- return logger2.critical;
3875
- case "success":
3876
- return logger2.success;
574
+
575
+ adapter.exec(db, 'COMMIT');
576
+ return count;
577
+ } catch (error) {
578
+ adapter.exec(db, 'ROLLBACK');
579
+ throw error;
3877
580
  }
3878
581
  }
3879
- async function handleClientLogIngestion(options) {
3880
- const { config, ctx, request, body, deliveryPath } = options;
3881
- if (!config.resolvedClientLogging) {
3882
- return { status: 404 };
582
+
583
+ function clearDeadLetters(ids) {
584
+ ensureReady();
585
+ if (!Array.isArray(ids) || ids.length === 0) {
586
+ return 0;
3883
587
  }
3884
- let payload;
588
+
589
+ adapter.exec(db, 'BEGIN');
3885
590
  try {
3886
- payload = await parseClientLogPayload(request, body);
3887
- } catch {
3888
- return { status: 400 };
3889
- }
3890
- if (!isClientLogEvent(payload)) {
3891
- return { status: 400 };
3892
- }
3893
- const isAllowed = config.resolvedClientLogging.validate ? await config.resolvedClientLogging.validate(ctx, payload) : true;
3894
- if (!isAllowed) {
3895
- return { status: 403 };
3896
- }
3897
- const serverContext = config.resolvedClientLogging.enrich ? await config.resolvedClientLogging.enrich(ctx, payload) : void 0;
3898
- const structuredPayload = {
3899
- ...payload,
3900
- receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
3901
- delivery: buildClientDetails(request, deliveryPath ?? extractPathname(request.url))
3902
- };
3903
- if (serverContext !== void 0) {
3904
- structuredPayload.serverContext = serverContext;
3905
- }
3906
- if (payload.level === "table") {
3907
- config.logger.table(`[client] ${payload.message}`, structuredPayload);
3908
- } else {
3909
- const logMethod = getClientLogMethod(config.logger, payload.level);
3910
- logMethod(`[client] ${payload.message}`, structuredPayload);
3911
- }
3912
- const headers = {};
3913
- if (payload.connector === "betterstack") {
3914
- headers["x-blyp-betterstack-status"] = config.betterstack.ready ? "enabled" : "missing";
3915
- if (config.betterstack.ready) {
3916
- const forwardedRecord = {
3917
- timestamp: structuredPayload.receivedAt,
3918
- level: payload.level,
3919
- message: `[client] ${payload.message}`,
3920
- data: structuredPayload
3921
- };
3922
- config.betterstack.send(forwardedRecord, {
3923
- source: "client"
3924
- });
3925
- if ((payload.level === "error" || payload.level === "critical") && config.betterstack.shouldAutoCaptureExceptions()) {
3926
- const clientErrorCandidate = payload.data && typeof payload.data === "object" && !Array.isArray(payload.data) && typeof payload.data.message === "string" ? payload.data : payload.message;
3927
- config.betterstack.captureException(clientErrorCandidate, {
3928
- source: "client",
3929
- warnIfUnavailable: true,
3930
- context: {
3931
- sessionId: payload.session.sessionId,
3932
- pageUrl: payload.page.url,
3933
- pagePath: payload.page.pathname,
3934
- metadata: payload.metadata,
3935
- payload: structuredPayload
3936
- }
3937
- });
3938
- }
3939
- }
3940
- } else if (payload.connector === "posthog") {
3941
- headers["x-blyp-posthog-status"] = config.posthog.ready ? "enabled" : "missing";
3942
- if (config.posthog.ready) {
3943
- const forwardedRecord = {
3944
- timestamp: structuredPayload.receivedAt,
3945
- level: payload.level,
3946
- message: `[client] ${payload.message}`,
3947
- data: structuredPayload
3948
- };
3949
- config.posthog.send(forwardedRecord, {
3950
- source: "client"
3951
- });
3952
- if ((payload.level === "error" || payload.level === "critical") && config.posthog.shouldAutoCaptureExceptions()) {
3953
- const metadata = structuredPayload.metadata;
3954
- const posthogDistinctId = metadata && typeof metadata === "object" && !Array.isArray(metadata) && typeof metadata.posthogDistinctId === "string" && metadata.posthogDistinctId ? String(metadata.posthogDistinctId) : void 0;
3955
- const clientErrorCandidate = payload.data && typeof payload.data === "object" && !Array.isArray(payload.data) && typeof payload.data.message === "string" ? payload.data : payload.message;
3956
- config.posthog.captureException(clientErrorCandidate, {
3957
- source: "client",
3958
- warnIfUnavailable: true,
3959
- distinctId: posthogDistinctId,
3960
- properties: buildPostHogExceptionProperties(forwardedRecord, "client", {
3961
- $session_id: payload.session.sessionId,
3962
- $current_url: payload.page.url,
3963
- $request_path: payload.page.pathname,
3964
- "client.runtime": payload.device?.runtime,
3965
- "client.metadata": payload.metadata
3966
- })
3967
- });
591
+ const select = adapter.prepare(db, 'SELECT id FROM connector_dead_letters WHERE id = ?');
592
+ const remove = adapter.prepare(db, 'DELETE FROM connector_dead_letters WHERE id = ?');
593
+ let count = 0;
594
+ for (const id of ids) {
595
+ const row = adapter.all(select, [id])[0];
596
+ if (!row) {
597
+ continue;
3968
598
  }
599
+ adapter.run(remove, [id]);
600
+ count += 1;
3969
601
  }
3970
- } else if (payload.connector === "sentry") {
3971
- headers["x-blyp-sentry-status"] = config.sentry.ready ? "enabled" : "missing";
3972
- if (config.sentry.ready) {
3973
- config.sentry.send({
3974
- timestamp: structuredPayload.receivedAt,
3975
- level: payload.level,
3976
- message: `[client] ${payload.message}`,
3977
- data: structuredPayload
3978
- }, {
3979
- source: "client"
3980
- });
3981
- }
3982
- } else if (payload.connector?.type === "otlp") {
3983
- const sender = config.otlp.get(payload.connector.name);
3984
- headers["x-blyp-otlp-status"] = sender.ready ? "enabled" : "missing";
3985
- if (sender.ready) {
3986
- sender.send({
3987
- timestamp: structuredPayload.receivedAt,
3988
- level: payload.level,
3989
- message: `[client] ${payload.message}`,
3990
- data: structuredPayload
3991
- }, {
3992
- source: "client"
3993
- });
3994
- }
3995
- }
3996
- return Object.keys(headers).length > 0 ? { status: 204, headers } : { status: 204 };
3997
- }
3998
- async function readNodeRequestBody(stream) {
3999
- const chunks = [];
4000
- for await (const chunk of stream) {
4001
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
4002
- }
4003
- return Buffer.concat(chunks).toString("utf8");
4004
- }
4005
- function buildAbsoluteUrl(path3, headers) {
4006
- if (path3.startsWith("http://") || path3.startsWith("https://")) {
4007
- return path3;
602
+ adapter.exec(db, 'COMMIT');
603
+ return count;
604
+ } catch (error) {
605
+ adapter.exec(db, 'ROLLBACK');
606
+ throw error;
4008
607
  }
4009
- const protocol = getHeaderValue(headers, "x-forwarded-proto") ?? "http";
4010
- const host = getHeaderValue(headers, "host") ?? "localhost";
4011
- return `${protocol}://${host}${path3.startsWith("/") ? path3 : `/${path3}`}`;
4012
608
  }
4013
609
 
4014
- // src/frameworks/shared/request-logger.ts
4015
- function createRequestScopedLogger(logger2, options = {}) {
4016
- const scopedLogger = createLoggerWithSource(logger2, "request-scoped");
4017
- const requestScopedLogger = attachLoggerInternals({
4018
- ...scopedLogger,
4019
- createStructuredLog: (groupId, initial) => {
4020
- return createStructuredLogForLogger(requestScopedLogger, groupId, {
4021
- initialFields: initial,
4022
- resolveDefaultFields: options.resolveStructuredFields,
4023
- onCreate: () => {
4024
- markStructuredCollectorActive();
4025
- },
4026
- onEmit: () => {
4027
- markStructuredLogEmitted();
4028
- options.onStructuredEmit?.();
4029
- }
4030
- });
4031
- },
4032
- child(bindings) {
4033
- return createRequestScopedLogger(scopedLogger.child(bindings), options);
4034
- }
4035
- }, scopedLogger);
4036
- setActiveRequestLogger(requestScopedLogger);
4037
- return requestScopedLogger;
610
+ function count() {
611
+ ensureReady();
612
+ const statement = adapter.prepare(db, 'SELECT COUNT(*) as count FROM connector_jobs');
613
+ const rows = adapter.all(statement, []);
614
+ return Number(rows[0]?.count ?? 0);
4038
615
  }
4039
616
 
4040
- // src/frameworks/express/logger.ts
4041
- function buildExpressContext(req, res, error) {
4042
- return { req, res, error };
4043
- }
4044
- function createExpressLogger(config = {}) {
4045
- const shared = resolveServerLogger(config);
4046
- return (req, res, next) => {
4047
- enterRequestContext();
4048
- let structuredLogEmitted = false;
4049
- req.blypLog = createRequestScopedLogger(shared.logger, {
4050
- resolveStructuredFields: () => ({
4051
- method: req.method,
4052
- path: extractPathname(req.originalUrl || req.url || "/"),
4053
- ...resolveAdditionalProps(shared, buildExpressContext(req, res, res.locals.blypError))
4054
- }),
4055
- onStructuredEmit: () => {
4056
- structuredLogEmitted = true;
4057
- }
4058
- });
4059
- res.locals.blypStartTime = performance.now();
4060
- res.on("finish", () => {
4061
- const path4 = extractPathname(req.originalUrl || req.url || "/");
4062
- const request = createRequestLike(
4063
- req.method,
4064
- buildAbsoluteUrl(req.originalUrl || req.url || "/", req.headers),
4065
- req.headers
4066
- );
4067
- const responseTime = Math.round(
4068
- performance.now() - (res.locals.blypStartTime ?? performance.now())
4069
- );
4070
- const context = buildExpressContext(req, res, res.locals.blypError);
4071
- if (structuredLogEmitted) {
617
+ parentPort.on('message', async (message) => {
618
+ const { id, type, payload } = message;
619
+ try {
620
+ switch (type) {
621
+ case 'init': {
622
+ adapter = await loadDatabase();
623
+ const filePath = payload.path;
624
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
625
+ db = adapter.create(filePath);
626
+ initializeSchema();
627
+ reclaimExpired(Date.now());
628
+ parentPort.postMessage({ id, ok: true, result: { runtime } });
4072
629
  return;
4073
630
  }
4074
- if (res.locals.blypError || isErrorStatus(res.statusCode)) {
4075
- if (!shouldSkipErrorLogging(shared, path4)) {
4076
- emitHttpErrorLog(
4077
- shared.logger,
4078
- shared.level,
4079
- request,
4080
- path4,
4081
- res.statusCode,
4082
- responseTime,
4083
- toErrorLike(res.locals.blypError, res.statusCode),
4084
- resolveAdditionalProps(shared, context),
4085
- {
4086
- error: res.locals.blypError
4087
- }
4088
- );
4089
- }
631
+ case 'insert':
632
+ insertJobs(payload.jobs);
633
+ parentPort.postMessage({ id, ok: true, result: true });
4090
634
  return;
4091
- }
4092
- if (!shouldSkipAutoLogging(shared, context, path4)) {
4093
- emitHttpRequestLog(
4094
- shared.logger,
4095
- shared.level,
4096
- request,
4097
- path4,
4098
- res.statusCode,
4099
- responseTime,
4100
- resolveAdditionalProps(shared, context)
4101
- );
4102
- }
4103
- });
4104
- const path3 = extractPathname(req.originalUrl || req.url || "/");
4105
- if (shared.resolvedClientLogging && req.method.toUpperCase() === "POST" && path3 === shared.ingestionPath) {
4106
- void (async () => {
4107
- const body = req.body === void 0 ? await readNodeRequestBody(req) : req.body;
4108
- const result = await handleClientLogIngestion({
4109
- config: shared,
4110
- ctx: buildExpressContext(req, res),
4111
- request: createRequestLike(
4112
- req.method,
4113
- buildAbsoluteUrl(req.originalUrl || req.url || "/", req.headers),
4114
- req.headers
635
+ case 'claimDue':
636
+ parentPort.postMessage({ id, ok: true, result: claimDue(payload.limit, payload.now) });
637
+ return;
638
+ case 'ack':
639
+ ack(payload.ids);
640
+ parentPort.postMessage({ id, ok: true, result: true });
641
+ return;
642
+ case 'reschedule':
643
+ reschedule(payload.items, payload.now);
644
+ parentPort.postMessage({ id, ok: true, result: true });
645
+ return;
646
+ case 'deadLetter':
647
+ deadLetter(payload.items);
648
+ parentPort.postMessage({ id, ok: true, result: true });
649
+ return;
650
+ case 'markSuccess':
651
+ markSuccess(payload.items);
652
+ parentPort.postMessage({ id, ok: true, result: true });
653
+ return;
654
+ case 'markFailure':
655
+ markFailure(payload.items);
656
+ parentPort.postMessage({ id, ok: true, result: true });
657
+ return;
658
+ case 'getStatusSummary':
659
+ parentPort.postMessage({ id, ok: true, result: getStatusSummary() });
660
+ return;
661
+ case 'listDeadLetters':
662
+ parentPort.postMessage({
663
+ id,
664
+ ok: true,
665
+ result: listDeadLetters(
666
+ payload.limit,
667
+ payload.offset,
668
+ payload.connectorType,
669
+ payload.connectorTarget
4115
670
  ),
4116
- body,
4117
- deliveryPath: shared.ingestionPath
4118
671
  });
4119
- if (result.headers) {
4120
- for (const [key, value] of Object.entries(result.headers)) {
4121
- res.setHeader(key, value);
4122
- }
672
+ return;
673
+ case 'retryDeadLetters':
674
+ parentPort.postMessage({ id, ok: true, result: retryDeadLetters(payload.ids, payload.now) });
675
+ return;
676
+ case 'clearDeadLetters':
677
+ parentPort.postMessage({ id, ok: true, result: clearDeadLetters(payload.ids) });
678
+ return;
679
+ case 'count':
680
+ parentPort.postMessage({ id, ok: true, result: count() });
681
+ return;
682
+ case 'shutdown':
683
+ if (db && adapter) {
684
+ adapter.close(db);
685
+ db = undefined;
4123
686
  }
4124
- res.status(result.status).end();
4125
- })().catch(next);
4126
- return;
687
+ parentPort.postMessage({ id, ok: true, result: true });
688
+ return;
689
+ default:
690
+ throw new Error('Unknown SQLite worker command: ' + type);
4127
691
  }
4128
- next();
4129
- };
4130
- }
4131
- function createExpressErrorLogger(_config = {}) {
4132
- return (error, _req, res, next) => {
4133
- res.locals.blypError = error;
4134
- next(error);
4135
- };
4136
- }
4137
- var createLogger = createExpressLogger;
4138
-
4139
- export { createExpressErrorLogger, createExpressLogger, createLogger };
4140
- //# sourceMappingURL=express.mjs.map
4141
- //# sourceMappingURL=express.mjs.map
692
+ } catch (error) {
693
+ parentPort.postMessage({
694
+ id,
695
+ ok: false,
696
+ error: error instanceof Error ? error.message : String(error),
697
+ });
698
+ }
699
+ });
700
+ `}var be=class{constructor(t){this.path=t;d(this,"worker");d(this,"pending",new Map);d(this,"nextId",1);this.worker=new Worker(Jt(),{eval:true}),this.worker.on("message",r=>{let n=this.pending.get(r.id);if(n){if(this.pending.delete(r.id),r.ok){n.resolve(r.result);return}n.reject(new Error(r.error??"SQLite worker request failed."));}}),this.worker.on("error",r=>{for(let n of this.pending.values())n.reject(r instanceof Error?r:new Error(String(r)));this.pending.clear();});}request(t,r={}){let n=this.nextId++;return new Promise((o,i)=>{this.pending.set(n,{resolve:o,reject:i}),this.worker.postMessage({id:n,type:t,payload:r});})}async init(){await this.request("init",{path:this.path});}async insert(t){await this.request("insert",{jobs:t});}async claimDue(t,r){return this.request("claimDue",{limit:t,now:r})}async ack(t){await this.request("ack",{ids:t});}async reschedule(t,r){await this.request("reschedule",{items:t,now:r});}async deadLetter(t){await this.request("deadLetter",{items:t});}async markSuccess(t){await this.request("markSuccess",{items:t});}async markFailure(t){await this.request("markFailure",{items:t});}async getStatusSummary(){return this.request("getStatusSummary")}async listDeadLetters(t){return this.request("listDeadLetters",t)}async retryDeadLetters(t,r){return this.request("retryDeadLetters",{ids:t,now:r})}async clearDeadLetters(t){return this.request("clearDeadLetters",{ids:t})}async count(){return this.request("count")}async shutdown(){try{await this.request("shutdown");}finally{await this.worker.terminate();}}};var Gt=Symbol("blyp.connector.batch-dispatch"),Y=Symbol("blyp.connector.delivery-binder");function Z(e){return new Promise(t=>{setTimeout(t,e);})}function Do(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function Kt(e){return JSON.stringify(e)}function ko(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function Xt(e){let t=new Map;for(let r of e){let n=`${r.connectorType}:${r.connectorTarget??""}`;t.has(n)||t.set(n,{connectorType:r.connectorType,connectorTarget:r.connectorTarget});}return [...t.values()]}var Ce=class{constructor(t){this.config=t;d(this,"warnOnce",_(new Set));d(this,"memoryQueue",[]);d(this,"durableStaging",[]);d(this,"dispatchers",new Map);d(this,"activeDispatches",0);d(this,"flushPromise",null);d(this,"durableFlushPromise",null);d(this,"pollTimer",null);d(this,"durablePollRunning",false);d(this,"closed",false);d(this,"durableClient",null);d(this,"durableReady",false);d(this,"durableInitPromise",null);t.enabled&&(this.durableInitPromise=this.initializeDurableQueue());}bindTarget(t){typeof t[Y]=="function"&&t[Y](this);let r=t[Gt];r&&this.dispatchers.set(r.dispatchKey,r);}unbindTarget(t){typeof t[Y]=="function"&&t[Y](null);}enqueue(t,r,n,o){this.closed||!Do(r)||(this.dispatchers.set(n.dispatchKey,n),this.memoryQueue.push({id:de(),connectorType:t,connectorTarget:o,source:"server",record:r,attemptCount:0,maxAttempts:this.config.retry.maxAttempts,nextAttemptAt:Date.now(),createdAt:Date.now(),dispatchKey:n.dispatchKey,dispatcher:n}),this.enforceMemoryCapacity(),this.scheduleDispatch());}async flush(){await this.durableInitPromise?.catch(()=>{}),await this.processUntilIdle(),await this.flushDurableStaging(),await this.drainDurableQueueForFlush(),await this.flushDurableStaging(),await this.processUntilIdle();}async shutdown(){if(this.closed=true,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),await this.durableInitPromise?.catch(()=>{}),this.durableReady){let t=this.memoryQueue.splice(0,this.memoryQueue.length);for(let r of t)this.stageDurableJob(r,r.attemptCount,Math.max(r.nextAttemptAt,Date.now()));await this.flushDurableStaging();}await this.processUntilIdle(),this.durableClient&&(await this.durableClient.shutdown().catch(()=>{}),this.durableClient=null);}async getDurableCountForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?0:this.durableClient.count()}async getStatusSummaryForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:this.durableClient.getStatusSummary()}async listDeadLettersForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:(await this.durableClient.listDeadLetters({limit:1e3,offset:0})).items}async initializeDurableQueue(){try{let t=new be(this.config.durableQueuePath);await t.init(),this.durableClient=t,this.durableReady=!0,this.scheduleDurablePoll();}catch(t){this.durableReady=false,this.durableClient=null,this.warnOnce("connector-durable-disabled",`[Blyp] Warning: Failed to initialize the connector SQLite queue at ${this.config.durableQueuePath}. Falling back to in-memory retries.`,t);}}scheduleDispatch(){this.flushPromise||(this.flushPromise=(async()=>{try{await this.pumpMemoryQueue();}finally{this.flushPromise=null,!this.closed&&this.hasReadyMemoryJobs()&&this.scheduleDispatch();}})());}async pumpMemoryQueue(){for(;!this.closed;){for(;this.activeDispatches<this.config.dispatchConcurrency;){let t=this.takeNextMemoryBatch();if(t.length===0)break;this.activeDispatches+=1,this.dispatchMemoryBatch(t).finally(()=>{this.activeDispatches-=1,this.closed||this.scheduleDispatch();});}if(this.activeDispatches===0||!this.hasReadyMemoryJobs())break;await Z(10);}}takeNextMemoryBatch(){let t=Date.now(),r=this.memoryQueue.findIndex(i=>i.nextAttemptAt<=t);if(r===-1)return [];let n=this.memoryQueue[r],o=[n];this.memoryQueue.splice(r,1);for(let i=this.memoryQueue.length-1;i>=0;i-=1){let a=this.memoryQueue[i];a.dispatchKey===n.dispatchKey&&a.connectorTarget===n.connectorTarget&&a.nextAttemptAt<=t&&o.length<this.config.memoryBatchSize&&(o.push(a),this.memoryQueue.splice(i,1));}return o}async dispatchMemoryBatch(t){let r=t[0].dispatcher,n=Date.now(),o=await r.dispatch(t.map(i=>i.record),{source:"server",target:t[0].connectorTarget}).catch(i=>({ok:false,retryable:true,error:i instanceof Error?i.message:String(i)}));if(o.ok){await this.recordSuccessfulDispatch(t,n);return}await this.handleRetryableFailure(t,o,false,n);}async handleRetryableFailure(t,r,n,o){n||await this.durableInitPromise?.catch(()=>{});let i=[],a=[];await this.recordFailedDispatch(t,r,o);for(let s of t){let l=s.attemptCount+1;if(!r.retryable||l>=s.maxAttempts){a.push({id:s.id,connectorType:s.connectorType,connectorTarget:s.connectorTarget,operation:"send",payloadJson:Kt({jobId:s.id,connectorType:s.connectorType,connectorTarget:s.connectorTarget,source:s.source,record:s.record,createdAt:s.createdAt}),attemptCount:l,maxAttempts:s.maxAttempts,lastError:r.error,firstEnqueuedAt:s.createdAt,deadLetteredAt:o,lastAttemptAt:o}),this.warnOnce(`connector-drop:${s.connectorType}:${s.connectorTarget??"default"}:${s.id}`,n&&this.durableReady?`[Blyp] Warning: Dead-lettered ${s.connectorType} connector job after ${l} failed attempt(s). ${r.error??"Connector delivery failed."}`:`[Blyp] Warning: Dropped ${s.connectorType} connector job after ${l} failed attempt(s). ${r.error??"Connector delivery failed."}`);continue}let u=o+Ht(l,this.config.retry);if(n){i.push({id:s.id,attemptCount:l,nextAttemptAt:u,lastError:r.error});continue}if(this.durableReady&&this.config.durableSpillStrategy==="after-first-failure"){this.stageDurableJob(s,l,u,r.error);continue}this.memoryQueue.push({...s,attemptCount:l,nextAttemptAt:u});}a.length>0&&await this.durableClient?.deadLetter(a).catch(s=>{this.warnOnce("connector-dead-letter-failure","[Blyp] Warning: Failed to persist dead-lettered connector queue jobs.",s);}),i.length>0&&await this.durableClient?.reschedule(i,o).catch(s=>{this.warnOnce("connector-reschedule-failure","[Blyp] Warning: Failed to reschedule durable connector queue jobs.",s);});}async recordSuccessfulDispatch(t,r){if(!this.durableReady||!this.durableClient||t.length===0)return;let n=Xt(t).map(o=>({connectorType:o.connectorType,connectorTarget:o.connectorTarget,timestamp:r}));await this.durableClient.markSuccess(n).catch(o=>{this.warnOnce("connector-status-success-failure","[Blyp] Warning: Failed to record connector delivery success state.",o);});}async recordFailedDispatch(t,r,n){if(!this.durableReady||!this.durableClient||t.length===0)return;let o=Xt(t).map(i=>({connectorType:i.connectorType,connectorTarget:i.connectorTarget,timestamp:n,lastError:r.error}));await this.durableClient.markFailure(o).catch(i=>{this.warnOnce("connector-status-failure-failure","[Blyp] Warning: Failed to record connector delivery failure state.",i);});}stageDurableJob(t,r,n,o){let i=Kt({jobId:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,source:t.source,record:t.record,createdAt:t.createdAt});this.durableStaging.push({id:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,operation:"send",payloadJson:i,attemptCount:r,maxAttempts:t.maxAttempts,nextAttemptAt:n,state:"pending",lastError:o,createdAt:t.createdAt,updatedAt:Date.now()}),this.flushDurableStaging();}async flushDurableStaging(){if(!(!this.durableReady||!this.durableClient||this.durableStaging.length===0)){if(this.durableFlushPromise){await this.durableFlushPromise;return}this.durableFlushPromise=(async()=>{for(;this.durableStaging.length>0;){let t=this.durableStaging.splice(0,this.config.sqliteWriteBatchSize);try{await this.durableClient.insert(t);}catch(r){this.warnOnce("connector-durable-insert-failure","[Blyp] Warning: Failed to persist connector jobs into the durable SQLite queue.",r),this.durableStaging.unshift(...t);break}}})();try{await this.durableFlushPromise;}finally{this.durableFlushPromise=null;}}}async processDurableQueueOnce(){if(!(!this.durableReady||!this.durableClient||this.durablePollRunning)){this.durablePollRunning=true;try{for(;!this.closed;){let t=await this.durableClient.claimDue(this.config.sqliteReadBatchSize,Date.now());if(t.length===0)break;let r=new Map,n=[];for(let o of t){let i=ko(o.payloadJson);if(!i){n.push(o.id);continue}let a=o.connectorType==="otlp"?`otlp:${o.connectorTarget??""}`:o.connectorType,s=this.dispatchers.get(a);if(!s){n.push(o.id);continue}let l={id:o.id,connectorType:o.connectorType,connectorTarget:o.connectorTarget,source:i.source,record:i.record,attemptCount:o.attemptCount,maxAttempts:o.maxAttempts,nextAttemptAt:o.nextAttemptAt,createdAt:o.createdAt,dispatchKey:a,dispatcher:s},u=r.get(a)??[];u.push(l),r.set(a,u);}n.length>0&&await this.durableClient.ack(n);for(let o of r.values()){let a=await o[0].dispatcher.dispatch(o.map(s=>s.record),{source:"server",target:o[0].connectorTarget}).catch(s=>({ok:!1,retryable:!0,error:s instanceof Error?s.message:String(s)}));if(a.ok){await this.recordSuccessfulDispatch(o,Date.now()),await this.durableClient.ack(o.map(s=>s.id));continue}await this.handleRetryableFailure(o,a,!0,Date.now());}}}finally{this.durablePollRunning=false;}}}async drainDurableQueueForFlush(){if(!(!this.durableReady||!this.durableClient)){this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null);try{for(;!this.closed;){for(;this.durablePollRunning;)await Z(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await Z(10);}}finally{this.closed||this.scheduleDurablePoll();}}}scheduleDurablePoll(){this.closed||!this.durableReady||this.pollTimer||(this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.flushDurableStaging(),await this.processDurableQueueOnce(),this.scheduleDurablePoll();},this.config.pollIntervalMs));}enforceMemoryCapacity(){for(;this.memoryQueue.length>this.config.memoryBufferSize;){let t=this.config.overflowStrategy==="drop-new"?this.memoryQueue.length-1:0,[r]=this.memoryQueue.splice(t,1);if(!r)break;if(this.durableReady){this.stageDurableJob(r,r.attemptCount,Math.max(Date.now(),r.nextAttemptAt),"spilled from in-memory buffer");continue}this.warnOnce(`connector-overflow:${r.connectorType}:${r.connectorTarget??"default"}:${t}`,`[Blyp] Warning: Connector queue overflow reached ${this.config.memoryBufferSize}. Dropping queued ${r.connectorType} job.`);}}hasReadyMemoryJobs(){let t=Date.now();return this.memoryQueue.some(r=>r.nextAttemptAt<=t)}async processUntilIdle(){for(;this.activeDispatches>0||this.memoryQueue.length>0||this.durableStaging.length>0||this.flushPromise!==null||this.durableFlushPromise!==null;){if(this.scheduleDispatch(),await this.flushPromise?.catch(()=>{}),await this.flushDurableStaging(),this.memoryQueue.some(t=>t.nextAttemptAt>Date.now())||await this.processDurableQueueOnce(),this.activeDispatches===0&&this.memoryQueue.length>0&&!this.hasReadyMemoryJobs()){let t=Math.min(...this.memoryQueue.map(r=>r.nextAttemptAt));await Z(Math.max(t-Date.now(),0));}else await Z(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var F=class F{constructor(){d(this,"_type",null);}static getInstance(){return F.instance||(F.instance=new F),F.instance}get type(){return this._type===null&&(this._type=this.detectRuntime()),this._type}get isBun(){return this.type==="bun"}get isNode(){return this.type==="node"}detectRuntime(){return typeof Bun<"u"&&typeof Bun.file=="function"?"bun":"node"}};d(F,"instance");var Xe=F,Ve=class{constructor(){d(this,"type","bun");d(this,"isBun",true);d(this,"isNode",false);d(this,"file",{existsSync:t=>{try{let r=Bun.file(t);return r.size>0||r.name!==""}catch{return false}},mkdirSync:(t,r)=>{try{S.mkdirSync(t,r);}catch{}},writeFileSync:(t,r)=>{Bun.write(t,r);}});d(this,"path",{join:(...t)=>q.join(...t)});d(this,"env",{get:t=>Bun.env[t]});d(this,"cwd",()=>process.cwd());}},Ye=class{constructor(){d(this,"type","node");d(this,"isBun",false);d(this,"isNode",true);d(this,"file",{existsSync:t=>S.existsSync(t),mkdirSync:(t,r)=>{S.mkdirSync(t,r);},writeFileSync:(t,r)=>{S.writeFileSync(t,r);}});d(this,"path",{join:(...t)=>q.join(...t)});d(this,"env",{get:t=>process.env[t]});d(this,"cwd",()=>process.cwd());}};function _o(){return Xe.getInstance().isBun?new Ve:new Ye}var Yt=_o();function Zt(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let r=[e,...t];return r.length===1?r[0]:r}function er(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Po(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let r=e;return {message:e.message,code:r.code,type:r.type??e.name??e.constructor?.name,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:er(r.details),cause:r.cause}}if(typeof e=="object"){let r=e,n=typeof r.statusCode=="number"?r.statusCode:typeof r.status=="number"?r.status:t;return {message:typeof r.message=="string"?r.message:`HTTP ${n??500}`,code:typeof r.code=="string"||typeof r.code=="number"?r.code:n,type:typeof r.type=="string"?r.type:typeof r.name=="string"?r.name:"Error",stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:er(r.details),cause:r.cause}}return {message:String(e),code:t,type:typeof e}}function Ao(e){return e.response&&typeof e.response.status=="number"?e.response.status:typeof e.status=="number"?e.status:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.statusCode=="number"?e.error.statusCode:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.status=="number"?e.error.status:e.error?500:void 0}function tr(e,t){let r=t.redact??x(),n=performance.now(),o=C(t.initialFields??{},r),i=[],a;t.onCreate?.();let s=(u,c,p)=>(i.push({level:u,message:I(c,r),timestamp:new Date().toISOString(),...Zt(c,p)===void 0?{}:{data:C(Zt(c,p),r)}}),l),l={set(u){return Object.assign(o,C(u,r)),l},debug(u,...c){return s("debug",u,c)},info(u,...c){return s("info",u,c)},warn(u,...c){return s("warn",u,c)},warning(u,...c){return s("warning",u,c)},error(u,...c){return s("error",u,c)},success(u,...c){return s("success",u,c)},critical(u,...c){return s("critical",u,c)},table(u,c){return s("table",u,c===void 0?[]:[c])},emit(u={}){if(a)return a;let c=C(t.resolveDefaultFields?.()??{},r),p=Ao(u),m=C(Po(u.error,p),r),R=u.level??(m?"error":"info"),w=C({...c,...o,groupId:e,timestamp:new Date().toISOString(),level:R,duration:Math.round(performance.now()-n),...typeof p=="number"?{status:p}:{},...i.length>0?{events:[...i]}:{},...m?{error:m}:{}},r);return t.write(w,I(u.message??"structured_log",r)),a=w,t.onEmit?.(w),w}};return l}var tt=Symbol("blyp.logger.factory"),nr={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},or={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},Bo="\x1B[35m",Io="\x1B[0m";function ee(e){return fe(e)==="client_log"}function Oo(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",ingestingHost:void 0,status:"missing",errorTracking:{enabled:false,ready:false,status:"missing",dsn:void 0,tracesSampleRate:1,environment:void 0,release:void 0},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function No(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Mo(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",host:"https://us.i.posthog.com",status:"missing",errorTracking:{enabled:false,ready:false,mode:"auto",status:"missing",enableExceptionAutocapture:false},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Fo(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function zo(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function jo(){return {get:e=>zo(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function Uo(e){return e.connectors?.betterstack?.enabled?H("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):Oo()}function $o(e){return e.connectors?.databuddy?.enabled?H("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):No()}function qo(e){return e.connectors?.posthog?.enabled?H("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):Mo()}function Ho(e){return e.connectors?.sentry?.enabled?H("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):Fo()}function Wo(e){return e.connectors?.otlp?.some(t=>t.enabled)?H("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):jo()}function Qo(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};t.data!==void 0&&(r.data=t.data);let n=typeof t.page?.pathname=="string"?t.page.pathname:void 0,o=typeof t.page?.url=="string"?t.page.url:void 0;return (n||o)&&(r.page=n??o),t.metadata!==void 0&&(r.metadata=t.metadata),Object.keys(r).length>0?r:null}function Jo(e){if(!e||typeof e!="object"||Array.isArray(e))return {hidden:false,value:e};let t=e;if(t.type==="http_request"||t.type==="http_error")return {hidden:true};if(t.type==="client_log"){let r=Qo(e);return r?{hidden:false,value:r}:{hidden:true}}return {hidden:false,value:e}}function Go(e){if(e.pretty){let r=Dt()({colorize:true,translateTime:"SYS:HH:MM:ss",ignore:"pid,hostname,caller",customColors:{success:"green",critical:"red bold",info:"blue",warning:"yellow",error:"red",debug:"cyan",table:"cyan"},messageFormat:(n,o)=>{let i=String(n[o]??""),a=typeof n.caller=="string"?n.caller.trim():"";return a?`${i} ${Bo}${a}${Io}`:i}});return rr({level:e.level,customLevels:nr},r)}return rr({level:e.level,customLevels:nr})}function E(e){let t=e[tt];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function rt(e){return E(e).posthog}function nt(e){return E(e).betterstack}function ot(e){return E(e).databuddy}function lr(e){try{return rt(e)}catch{return null}}function dr(e){try{return nt(e)}catch{return null}}function gr(e){try{return ot(e)}catch{return null}}function pr(e){return E(e).sentry}function fr(e){return E(e).otlp}function Re(e){try{return E(e).redact}catch{return X().redact}}function mr(e,t){let r=E(t);return Object.defineProperty(e,tt,{value:r,enumerable:false,configurable:false,writable:false}),e}function yr(e,t){let r=E(e);return r.create(t,r.bindings)}function it(e,t,r={}){let n=E(e);return tr(t,{initialFields:r.initialFields,resolveDefaultFields:()=>({...n.bindings,...r.resolveDefaultFields?.()??{}}),write:(o,i)=>{n.writeStructured(o,i,"structured-flush");},onCreate:r.onCreate,onEmit:r.onEmit,redact:r.redact??n.redact})}function ir(e,t){if(!ee(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function ar(e,t){if(!ee(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function sr(e,t){if(!ee(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function cr(e,t){if(!ee(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function ur(e,t){if(!ee(t))for(let r of e.getAutoForwardTargets())r.send(t,{source:"server",warnIfUnavailable:true});}function et(e,t,r,n,o,i,a,s,l,u={},c="root"){let p=Object.keys(u).length>0?e.child(u):e,m=(f,g,y,L=c)=>{if(L==="root"&&me())return;let h=It(f,g,y,u,l),Q=h.message,J={caller:h.caller},te=Jo(h.data);!te.hidden&&te.value!==void 0&&(J.data=te.value);let lt=or[f],Se=p;(Se[lt]??Se.info??((ni,oi)=>{})).call(p,J,Q),t.write(h),ar(n,h),sr(o,h),ir(i,h),cr(a,h),ur(s,h);},R=(f,g,y="structured-flush")=>{let L=Nt(f.level),h=Ot(L,g,f,u,l),Q=or[L],J=p;(J[Q]??J.info??((lt,Se)=>{})).call(p,{caller:h.caller,...h},h.message),(y!=="root"||!me())&&t.write(h),ar(n,h),sr(o,h),ir(i,h),cr(a,h),ur(s,h);},w={success:(f,...g)=>{m("success",f,g);},critical:(f,...g)=>{m("critical",f,g);},warning:(f,...g)=>{m("warning",f,g);},info:(f,...g)=>{m("info",f,g);},debug:(f,...g)=>{m("debug",f,g);},error:(f,...g)=>{m("error",f,g);},warn:(f,...g)=>{m("warn",f,g);},table:(f,g)=>{g&&typeof g=="object"&&Yt.env.get("NODE_ENV")!=="production"&&(console.log("TABLE:",f),console.table(C(g,l))),m("table",f,g===void 0?[]:[g]);},flush:async()=>{await t.flush(),r&&await r.flush(),await Promise.allSettled([n.flush(),o.flush(),i.flush(),a.flush(),s.flush()]);},shutdown:async()=>{await t.shutdown(),r&&await r.shutdown(),await Promise.allSettled([n.flush(),o.flush(),i.flush(),a.flush(),s.flush()]);},createStructuredLog:(f,g)=>it(w,f,{initialFields:g}),child:f=>{let g={...u,...f};return et(e,t,r,n,o,i,a,s,l,g,c)},[tt]:{bindings:u,betterstack:n,databuddy:o,posthog:i,sentry:a,otlp:s,redact:l,sink:t,create:(f,g=u)=>et(e,t,r,n,o,i,a,s,l,g,f),writeStructured:(f,g,y="structured-flush")=>{R(f,g,y);}}};return w}var Ze=null;function at(e){if(e===void 0&&Ze)return Ze;let t=X(e),r=Go(t),n=qt(t),o=Uo(t),i=$o(t),a=qo(t),s=Ho(t),l=Wo(t),u=t.connectors.delivery.enabled?new Ce(t.connectors.delivery):null;if(u){u.bindTarget(o),u.bindTarget(i),u.bindTarget(a),u.bindTarget(s);for(let p of l.getAutoForwardTargets())u.bindTarget(p);}let c=et(r,n,u,o,i,a,s,l,t.redact);return e===void 0&&(Ze=c),c}at();function hr(e,t,r,n){let o=re(e),i=ne(t),a=oe(n);return `${o} ${r} ${i} ${a}`}function Ko(e,t){let r=Ae(t?.path??N),n=t?.enabled===false?null:{path:r};return e===false?null:e===void 0?n:e===true?{path:r}:{...n,...e,path:Ae(e.path??r)}}function br(e={},t){let r=X({...e.level!==void 0?{level:e.level}:{},...e.pretty!==void 0?{pretty:e.pretty}:{},...e.destination!==void 0?{destination:e.destination}:{},...e.logDir!==void 0?{logDir:e.logDir}:{},...e.file!==void 0?{file:e.file}:{},...e.database!==void 0?{database:e.database}:{},...e.redact!==void 0?{redact:e.redact}:{},...e.connectors!==void 0?{connectors:e.connectors}:{}}),{level:n=r.level,pretty:o=r.pretty,destination:i=r.destination,logDir:a=r.logDir,file:s=r.file,database:l=r.database,autoLogging:u=true,customProps:c,logErrors:p=true,includePaths:m,ignorePaths:R,clientLogging:w,connectors:f}=e,g=at({level:n,pretty:o,destination:i,logDir:a,file:s,database:l,connectors:f}),y=Ko(w,r.clientLogging),L=y?.path??N,h=m,Q=y?Array.from(new Set([...R??[],L])):R;return {logger:g,betterstack:nt(g),databuddy:ot(g),posthog:rt(g),sentry:pr(g),otlp:fr(g),resolvedConfig:r,level:n,pretty:o,logDir:a,file:s,autoLogging:u,customProps:c,logErrors:p,resolvedIncludePaths:h,resolvedIgnorePaths:Q,resolvedClientLogging:y,ingestionPath:L}}function Xo(e,t){return !t||t.length===0?true:Ne(e,t)}function Cr(e,t,r){return Xo(e,t)?Ne(e,r):true}function wr(e,t,r){return e.autoLogging===false||typeof e.autoLogging=="object"&&e.autoLogging.ignore?.(t)?true:Cr(r,e.resolvedIncludePaths,e.resolvedIgnorePaths)}function Rr(e,t){return e.logErrors?Cr(t,e.resolvedIncludePaths,e.resolvedIgnorePaths):true}function Le(e,t){return e.customProps?e.customProps(t):{}}function Lr(e,t,r,n,o,i,a={}){let s=ue(r,"http_request",n,o,i,a,Re(e));return t==="info"?e.info(le(r.method,o,n,i),s):(e.info(hr(r.method,o,n,i),s),Object.keys(a).length>0&&e.debug("Request context",a)),s}function Sr(e,t,r,n,o,i,a,s={},l={}){let u=ue(r,"http_error",n,o,i,{error:a?.message??`HTTP ${o}`,stack:a?.stack,code:a?.code,why:a?.why,fix:a?.fix,link:a?.link,details:a?.details,...s},Re(e)),c=t==="info"?le(r.method,o,n,i):hr(r.method,o,n,i);e.error(c,u);let p=lr(e);p?.shouldAutoCaptureExceptions()&&p.captureException(l.error??a??c,{source:"server",warnIfUnavailable:true,distinctId:l.distinctId??b(r.headers,"x-posthog-distinct-id"),properties:$e({timestamp:new Date().toISOString(),level:"error",message:c,data:u},"server",{$request_method:r.method,$request_path:n,$current_url:r.url,$response_status_code:o,...b(r.headers,"user-agent")?{$user_agent:b(r.headers,"user-agent")}:{},...u.ip?{$ip:u.ip}:{}})});let m=dr(e);m?.shouldAutoCaptureExceptions()&&m.captureException(l.error??a??c,{source:"server",warnIfUnavailable:true,context:{timestamp:new Date().toISOString(),level:"error",message:c,status:o,path:n,data:u}});let R=gr(e);return R?.shouldAutoCaptureExceptions()&&R.captureException(l.error??a??c,{source:"server",warnIfUnavailable:true,properties:{method:r.method,path:n,status_code:o,...r.url?{current_url:r.url}:{},...b(r.headers,"user-agent")?{user_agent:b(r.headers,"user-agent")}:{},...u.ip?{ip:u.ip}:{},payload:u}}),u}async function Vo(e,t){if(t!==void 0)return typeof t=="string"?JSON.parse(t):t;if(typeof e.json=="function")return await e.json();throw new Error("Unable to parse client log payload")}function Yo(e,t){switch(t){case "debug":return e.debug;case "info":return e.info;case "warning":return e.warning;case "error":return e.error;case "critical":return e.critical;case "success":return e.success}}async function vr(e){let{config:t,ctx:r,request:n,body:o,deliveryPath:i}=e;if(!t.resolvedClientLogging)return {status:404};let a;try{a=await Vo(n,o);}catch{return {status:400}}if(!mt(a))return {status:400};if(!(t.resolvedClientLogging.validate?await t.resolvedClientLogging.validate(r,a):true))return {status:403};let l=t.resolvedClientLogging.enrich?await t.resolvedClientLogging.enrich(r,a):void 0,u=Re(t.logger),c=C(a,u),p=C({...c,receivedAt:new Date().toISOString(),delivery:Te(n,i??D(n.url),u)},u);l!==void 0&&(p.serverContext=C(l,u));let m=I(`[client] ${c.message}`,u),R=B(),w=typeof c.traceId=="string"&&c.traceId.length>0?c.traceId:R;try{w&&V(w),c.level==="table"?t.logger.table(m,p):Yo(t.logger,c.level)(m,p);}finally{V(R);}let f={};if(c.connector==="betterstack"){if(f["x-blyp-betterstack-status"]=t.betterstack.ready?"enabled":"missing",t.betterstack.ready){let g={timestamp:p.receivedAt,level:c.level,message:m,data:p};if(t.betterstack.send(g,{source:"client"}),(c.level==="error"||c.level==="critical")&&t.betterstack.shouldAutoCaptureExceptions()){let y=c.data&&typeof c.data=="object"&&!Array.isArray(c.data)&&typeof c.data.message=="string"?c.data:c.message;t.betterstack.captureException(y,{source:"client",warnIfUnavailable:true,context:{sessionId:c.session.sessionId,pageUrl:c.page.url,pagePath:c.page.pathname,metadata:c.metadata,payload:p}});}}}else if(c.connector==="databuddy"){if(f["x-blyp-databuddy-status"]=t.databuddy.ready?"enabled":"missing",t.databuddy.ready){let g={timestamp:p.receivedAt,level:c.level,message:m,data:p};if(t.databuddy.send(g,{source:"client"}),(c.level==="error"||c.level==="critical")&&t.databuddy.shouldAutoCaptureExceptions()){let y=c.data&&typeof c.data=="object"&&!Array.isArray(c.data)&&typeof c.data.message=="string"?c.data:c.message;t.databuddy.captureException(y,{source:"client",warnIfUnavailable:true,sessionId:c.session.sessionId,properties:{page_url:c.page.url,page_path:c.page.pathname,client_runtime:c.device?.runtime,metadata:c.metadata,payload:p}});}}}else if(c.connector==="posthog"){if(f["x-blyp-posthog-status"]=t.posthog.ready?"enabled":"missing",t.posthog.ready){let g={timestamp:p.receivedAt,level:c.level,message:m,data:p};if(t.posthog.send(g,{source:"client"}),(c.level==="error"||c.level==="critical")&&t.posthog.shouldAutoCaptureExceptions()){let y=p.metadata,L=y&&typeof y=="object"&&!Array.isArray(y)&&typeof y.posthogDistinctId=="string"&&y.posthogDistinctId?String(y.posthogDistinctId):void 0,h=c.data&&typeof c.data=="object"&&!Array.isArray(c.data)&&typeof c.data.message=="string"?c.data:c.message;t.posthog.captureException(h,{source:"client",warnIfUnavailable:true,distinctId:L,properties:$e(g,"client",{$session_id:c.session.sessionId,$current_url:c.page.url,$request_path:c.page.pathname,"client.runtime":c.device?.runtime,"client.metadata":c.metadata})});}}}else if(c.connector==="sentry")f["x-blyp-sentry-status"]=t.sentry.ready?"enabled":"missing",t.sentry.ready&&t.sentry.send({timestamp:p.receivedAt,level:c.level,message:m,data:p},{source:"client"});else if(c.connector?.type==="otlp"){let g=t.otlp.get(c.connector.name);f["x-blyp-otlp-status"]=g.ready?"enabled":"missing",g.ready&&g.send({timestamp:p.receivedAt,level:c.level,message:m,data:p},{source:"client"});}return Object.keys(f).length>0?{status:204,headers:f}:{status:204}}async function xr(e){let t=[];for await(let r of e)t.push(Buffer.isBuffer(r)?r:Buffer.from(r));return Buffer.concat(t).toString("utf8")}function st(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return e;let r=b(t,"x-forwarded-proto")??"http",n=b(t,"host")??"localhost";return `${r}://${n}${e.startsWith("/")?e:`/${e}`}`}function ct(e,t={}){let r=yr(e,"request-scoped"),n=mr({...r,createStructuredLog:(o,i)=>it(n,o,{initialFields:i,resolveDefaultFields:()=>{let a=B();return {...t.resolveStructuredFields?.()??{},...a?{traceId:a}:{}}},onCreate:()=>{Qe();},onEmit:()=>{Je(),t.onStructuredEmit?.();}}),child(o){return ct(r.child(o),t)}},r);return We(n),n}var Tr="x-blyp-trace-id",Zo="trace_";function Er(){return `${Zo}${de().replace(/[^a-z0-9]/gi,"").toLowerCase().slice(0,12)}`}function Dr(e){V(e);}function ut(e,t,r){return {req:e,res:t,error:r}}function kr(e={}){let t=br(e);return (r,n,o)=>{He();let i=Er();Dr(i);let a=false;r.blypTraceId=i,n.setHeader(Tr,i),r.blypLog=ct(t.logger,{resolveStructuredFields:()=>({method:r.method,path:D(r.originalUrl||r.url||"/"),...Le(t,ut(r,n,n.locals.blypError))}),onStructuredEmit:()=>{a=true;}}),n.locals.blypStartTime=performance.now(),n.on("finish",()=>{let l=D(r.originalUrl||r.url||"/"),u=ce(r.method,st(r.originalUrl||r.url||"/",r.headers),r.headers),c=Math.round(performance.now()-(n.locals.blypStartTime??performance.now())),p=ut(r,n,n.locals.blypError);if(!a){if(n.locals.blypError||De(n.statusCode)){Rr(t,l)||Sr(t.logger,t.level,u,l,n.statusCode,c,Ee(n.locals.blypError,n.statusCode),Le(t,p),{error:n.locals.blypError});return}wr(t,p,l)||Lr(t.logger,t.level,u,l,n.statusCode,c,Le(t,p));}});let s=D(r.originalUrl||r.url||"/");if(t.resolvedClientLogging&&r.method.toUpperCase()==="POST"&&s===t.ingestionPath){(async()=>{let l=r.body===void 0?await xr(r):r.body,u=await vr({config:t,ctx:ut(r,n),request:ce(r.method,st(r.originalUrl||r.url||"/",r.headers),r.headers),body:l,deliveryPath:t.ingestionPath});if(u.headers)for(let[c,p]of Object.entries(u.headers))n.setHeader(c,p);n.status(u.status).end();})().catch(o);return}o();}}function ei(e={}){return (t,r,n,o)=>{n.locals.blypError=t,o(t);}}var ti=kr;
701
+ export{ei as createExpressErrorLogger,kr as createExpressLogger,ti as createLogger};