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