@blyp/core 0.1.2 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/README.md +273 -14
  2. package/STABILITY.md +56 -0
  3. package/dist/ai/anthropic/index.d.ts +3 -0
  4. package/dist/ai/anthropic/normalize.d.ts +9 -0
  5. package/dist/ai/anthropic/stream.d.ts +3 -0
  6. package/dist/ai/anthropic/wrap.d.ts +13 -0
  7. package/dist/ai/anthropic.js +701 -0
  8. package/dist/ai/anthropic.mjs +701 -0
  9. package/dist/ai/fetch.js +701 -0
  10. package/dist/ai/fetch.mjs +701 -0
  11. package/dist/ai/openai/index.d.ts +3 -0
  12. package/dist/ai/openai/normalize.d.ts +10 -0
  13. package/dist/ai/openai/stream.d.ts +3 -0
  14. package/dist/ai/openai/wrap.d.ts +24 -0
  15. package/dist/ai/openai.js +701 -0
  16. package/dist/ai/openai.mjs +701 -0
  17. package/dist/ai/shared/fetch.d.ts +5 -0
  18. package/dist/ai/shared/index.d.ts +2 -0
  19. package/dist/ai/shared/normalize.d.ts +17 -0
  20. package/dist/ai/shared/redaction.d.ts +6 -0
  21. package/dist/ai/shared/stream.d.ts +7 -0
  22. package/dist/ai/shared/trace.d.ts +116 -0
  23. package/dist/ai/shared/types.d.ts +161 -0
  24. package/dist/ai/shared.js +701 -0
  25. package/dist/ai/shared.mjs +701 -0
  26. package/dist/ai/vercel/index.d.ts +3 -0
  27. package/dist/ai/vercel/middleware.d.ts +3 -0
  28. package/dist/ai/vercel/model.d.ts +3 -0
  29. package/dist/ai/vercel.js +701 -0
  30. package/dist/ai/vercel.mjs +701 -0
  31. package/dist/astro.js +701 -0
  32. package/dist/astro.mjs +701 -0
  33. package/dist/client.js +1 -1132
  34. package/dist/client.mjs +1 -1125
  35. package/dist/connectors/betterstack.js +9 -1508
  36. package/dist/connectors/betterstack.mjs +9 -1483
  37. package/dist/connectors/databuddy/index.d.ts +7 -0
  38. package/dist/connectors/databuddy/sender.d.ts +5 -0
  39. package/dist/connectors/databuddy.js +9 -0
  40. package/dist/connectors/databuddy.mjs +9 -0
  41. package/dist/connectors/delivery/backoff.d.ts +2 -0
  42. package/dist/connectors/delivery/manager.d.ts +44 -0
  43. package/dist/connectors/delivery/queue-path.d.ts +1 -0
  44. package/dist/connectors/delivery/sqlite-adapter-bun.d.ts +1 -0
  45. package/dist/connectors/delivery/sqlite-adapter-node.d.ts +1 -0
  46. package/dist/connectors/delivery/sqlite-client.d.ts +37 -0
  47. package/dist/connectors/delivery/sqlite-worker.d.ts +1 -0
  48. package/dist/connectors/delivery/studio-queue.d.ts +12 -0
  49. package/dist/connectors/delivery/types.d.ts +98 -0
  50. package/dist/connectors/otlp/index.d.ts +1 -0
  51. package/dist/connectors/otlp.js +9 -1347
  52. package/dist/connectors/otlp.mjs +9 -1344
  53. package/dist/connectors/posthog/properties.d.ts +4 -0
  54. package/dist/connectors/posthog/sender.d.ts +0 -1
  55. package/dist/connectors/posthog.js +10 -1503
  56. package/dist/connectors/posthog.mjs +10 -1498
  57. package/dist/connectors/sentry.js +9 -1356
  58. package/dist/connectors/sentry.mjs +9 -1333
  59. package/dist/core/config.d.ts +7 -2
  60. package/dist/core/log-record.d.ts +5 -4
  61. package/dist/core/logger.d.ts +5 -0
  62. package/dist/core/optional-module.d.ts +1 -0
  63. package/dist/core/pino-pretty-loader.d.ts +4 -0
  64. package/dist/database.js +1 -24
  65. package/dist/database.mjs +1 -21
  66. package/dist/elysia.js +621 -4100
  67. package/dist/elysia.mjs +622 -4073
  68. package/dist/expo.js +1 -719
  69. package/dist/expo.mjs +1 -717
  70. package/dist/express.js +616 -4085
  71. package/dist/express.mjs +616 -4056
  72. package/dist/fastify.js +618 -4104
  73. package/dist/fastify.mjs +618 -4075
  74. package/dist/frameworks/astro/index.d.ts +2 -0
  75. package/dist/frameworks/astro/logger.d.ts +3 -0
  76. package/dist/frameworks/elysia/index.d.ts +1 -1
  77. package/dist/frameworks/elysia/logger.d.ts +2 -35
  78. package/dist/frameworks/nestjs/helpers.d.ts +2 -0
  79. package/dist/frameworks/nitro/index.d.ts +2 -0
  80. package/dist/frameworks/nitro/logger.d.ts +6 -0
  81. package/dist/frameworks/nuxt/index.d.ts +2 -0
  82. package/dist/frameworks/nuxt/logger.d.ts +3 -0
  83. package/dist/frameworks/react-router/index.d.ts +2 -0
  84. package/dist/frameworks/react-router/logger.d.ts +3 -0
  85. package/dist/frameworks/shared/h3.d.ts +19 -0
  86. package/dist/frameworks/shared/http.d.ts +3 -2
  87. package/dist/frameworks/shared/index.d.ts +2 -1
  88. package/dist/frameworks/shared/logger.d.ts +2 -0
  89. package/dist/frameworks/shared/request-context.d.ts +2 -0
  90. package/dist/frameworks/shared/trace.d.ts +6 -0
  91. package/dist/hono.js +624 -4079
  92. package/dist/hono.mjs +626 -4053
  93. package/dist/index.d.ts +57 -17
  94. package/dist/index.js +616 -6494
  95. package/dist/index.mjs +619 -6410
  96. package/dist/nestjs.js +626 -4574
  97. package/dist/nestjs.mjs +622 -4542
  98. package/dist/nextjs.js +625 -4107
  99. package/dist/nextjs.mjs +627 -4081
  100. package/dist/nitro.js +701 -0
  101. package/dist/nitro.mjs +701 -0
  102. package/dist/nuxt.js +701 -0
  103. package/dist/nuxt.mjs +701 -0
  104. package/dist/react-router.js +701 -0
  105. package/dist/react-router.mjs +701 -0
  106. package/dist/shared/redaction.d.ts +17 -0
  107. package/dist/standalone.js +606 -3258
  108. package/dist/standalone.mjs +611 -3234
  109. package/dist/sveltekit.js +625 -4106
  110. package/dist/sveltekit.mjs +626 -4079
  111. package/dist/tanstack-start.js +624 -4105
  112. package/dist/tanstack-start.mjs +626 -4079
  113. package/dist/types/connectors/databuddy.d.ts +52 -0
  114. package/dist/types/core/config.d.ts +89 -0
  115. package/dist/types/core/logger.d.ts +5 -0
  116. package/dist/types/core/structured-log.d.ts +2 -0
  117. package/dist/types/database.d.ts +1 -0
  118. package/dist/types/frameworks/astro.d.ts +33 -0
  119. package/dist/types/frameworks/client.d.ts +2 -0
  120. package/dist/types/frameworks/elysia.d.ts +2 -0
  121. package/dist/types/frameworks/express.d.ts +1 -0
  122. package/dist/types/frameworks/fastify.d.ts +1 -0
  123. package/dist/types/frameworks/hono.d.ts +1 -0
  124. package/dist/types/frameworks/http.d.ts +1 -0
  125. package/dist/types/frameworks/nestjs.d.ts +2 -0
  126. package/dist/types/frameworks/nextjs.d.ts +1 -0
  127. package/dist/types/frameworks/nitro.d.ts +63 -0
  128. package/dist/types/frameworks/nuxt.d.ts +12 -0
  129. package/dist/types/frameworks/react-router.d.ts +35 -0
  130. package/dist/types/frameworks/request-context.d.ts +1 -0
  131. package/dist/types/frameworks/shared.d.ts +28 -1
  132. package/dist/types/frameworks/standalone.d.ts +3 -2
  133. package/dist/types/frameworks/sveltekit.d.ts +1 -0
  134. package/dist/types/frameworks/tanstack-start.d.ts +9 -3
  135. package/dist/types/frameworks/workers.d.ts +3 -0
  136. package/dist/types/shared/client-log.d.ts +2 -1
  137. package/dist/workers.js +2 -626
  138. package/dist/workers.mjs +2 -623
  139. package/package.json +273 -143
  140. package/dist/client.js.map +0 -1
  141. package/dist/client.mjs.map +0 -1
  142. package/dist/connectors/betterstack.js.map +0 -1
  143. package/dist/connectors/betterstack.mjs.map +0 -1
  144. package/dist/connectors/otlp.js.map +0 -1
  145. package/dist/connectors/otlp.mjs.map +0 -1
  146. package/dist/connectors/posthog.js.map +0 -1
  147. package/dist/connectors/posthog.mjs.map +0 -1
  148. package/dist/connectors/sentry.js.map +0 -1
  149. package/dist/connectors/sentry.mjs.map +0 -1
  150. package/dist/database.js.map +0 -1
  151. package/dist/database.mjs.map +0 -1
  152. package/dist/elysia.js.map +0 -1
  153. package/dist/elysia.mjs.map +0 -1
  154. package/dist/expo.js.map +0 -1
  155. package/dist/expo.mjs.map +0 -1
  156. package/dist/express.js.map +0 -1
  157. package/dist/express.mjs.map +0 -1
  158. package/dist/fastify.js.map +0 -1
  159. package/dist/fastify.mjs.map +0 -1
  160. package/dist/hono.js.map +0 -1
  161. package/dist/hono.mjs.map +0 -1
  162. package/dist/index.js.map +0 -1
  163. package/dist/index.mjs.map +0 -1
  164. package/dist/nestjs.js.map +0 -1
  165. package/dist/nestjs.mjs.map +0 -1
  166. package/dist/nextjs.js.map +0 -1
  167. package/dist/nextjs.mjs.map +0 -1
  168. package/dist/standalone.js.map +0 -1
  169. package/dist/standalone.mjs.map +0 -1
  170. package/dist/sveltekit.js.map +0 -1
  171. package/dist/sveltekit.mjs.map +0 -1
  172. package/dist/tanstack-start.js.map +0 -1
  173. package/dist/tanstack-start.mjs.map +0 -1
  174. package/dist/workers.js.map +0 -1
  175. package/dist/workers.mjs.map +0 -1
  176. package/exports/client.js +0 -3
  177. package/exports/client.mjs +0 -3
  178. package/exports/connectors/betterstack.js +0 -1
  179. package/exports/connectors/betterstack.mjs +0 -1
  180. package/exports/connectors/otlp.js +0 -1
  181. package/exports/connectors/otlp.mjs +0 -1
  182. package/exports/connectors/posthog.js +0 -1
  183. package/exports/connectors/posthog.mjs +0 -1
  184. package/exports/connectors/sentry.js +0 -1
  185. package/exports/connectors/sentry.mjs +0 -1
  186. package/exports/database.js +0 -1
  187. package/exports/database.mjs +0 -1
  188. package/exports/expo.js +0 -1
  189. package/exports/expo.mjs +0 -1
  190. package/exports/frameworks/elysia.js +0 -1
  191. package/exports/frameworks/elysia.mjs +0 -1
  192. package/exports/frameworks/express.js +0 -1
  193. package/exports/frameworks/express.mjs +0 -1
  194. package/exports/frameworks/fastify.js +0 -1
  195. package/exports/frameworks/fastify.mjs +0 -1
  196. package/exports/frameworks/hono.js +0 -1
  197. package/exports/frameworks/hono.mjs +0 -1
  198. package/exports/frameworks/nestjs.js +0 -1
  199. package/exports/frameworks/nestjs.mjs +0 -1
  200. package/exports/frameworks/nextjs.js +0 -1
  201. package/exports/frameworks/nextjs.mjs +0 -1
  202. package/exports/frameworks/standalone.js +0 -1
  203. package/exports/frameworks/standalone.mjs +0 -1
  204. package/exports/frameworks/sveltekit.js +0 -1
  205. package/exports/frameworks/sveltekit.mjs +0 -1
  206. package/exports/frameworks/tanstack-start.js +0 -1
  207. package/exports/frameworks/tanstack-start.mjs +0 -1
  208. package/exports/workers.js +0 -1
  209. package/exports/workers.mjs +0 -1
  210. package/types/client.d.ts +0 -34
  211. package/types/connectors/betterstack.d.ts +0 -1
  212. package/types/connectors/otlp.d.ts +0 -1
  213. package/types/connectors/posthog.d.ts +0 -1
  214. package/types/connectors/sentry.d.ts +0 -1
  215. package/types/database.d.ts +0 -1
  216. package/types/expo.d.ts +0 -17
  217. package/types/frameworks/client.d.ts +0 -160
  218. package/types/frameworks/elysia.d.ts +0 -1
  219. package/types/frameworks/expo.d.ts +0 -50
  220. package/types/frameworks/express.d.ts +0 -1
  221. package/types/frameworks/fastify.d.ts +0 -1
  222. package/types/frameworks/hono.d.ts +0 -1
  223. package/types/frameworks/nestjs.d.ts +0 -1
  224. package/types/frameworks/nextjs.d.ts +0 -1
  225. package/types/frameworks/standalone.d.ts +0 -1
  226. package/types/frameworks/sveltekit.d.ts +0 -1
  227. package/types/frameworks/tanstack-start.d.ts +0 -1
  228. package/types/frameworks/workers.d.ts +0 -115
  229. package/types/index.d.ts +0 -1
  230. package/types/workers.d.ts +0 -13
package/dist/nuxt.mjs ADDED
@@ -0,0 +1,701 @@
1
+ import {AsyncLocalStorage}from'async_hooks';import {z as z$1}from'zod';import S,{existsSync,readFileSync,writeFileSync,appendFileSync}from'fs';import {createJiti}from'jiti';import U,{resolve,dirname}from'path';import yn from'os';import {gzipSync}from'fflate';import gr from'pino';import {createRequire}from'module';import {randomUUID}from'crypto';import {Worker}from'worker_threads';var qr=Object.defineProperty;var jr=(e,t,r)=>t in e?qr(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var d=(e,t,r)=>jr(e,typeof t!="symbol"?t+"":t,r);var wt=new AsyncLocalStorage;function $r(){return {requestScopedLoggerActive:true,structuredCollectorActive:false,structuredLogEmitted:false,mixedLoggerWarningShown:false}}function ne(){let e=$r();return wt.enterWith(e),e}function B(){return wt.getStore()}function De(e){let t=B();t&&(t.activeLogger=e);}function J(e){let t=B();t&&(t.traceId=e);}function E(){return B()?.traceId}function _e(){let e=B();e&&(e.structuredCollectorActive=true);}function Pe(){let e=B();e&&(e.structuredLogEmitted=true);}function oe(){let e=B();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 ie(e){return `${{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[33m",PATCH:"\x1B[34m",DELETE:"\x1B[31m"}[e.toUpperCase()]||""}${e}\x1B[0m`}function ae(e){let t="\x1B[0m";return e>=500?`\x1B[31m${e}${t}`:e>=400?`\x1B[33m${e}${t}`:e>=300?`\x1B[36m${e}${t}`:e>=200?`\x1B[32m${e}${t}`:`\x1B[37m${e}${t}`}function Rt(e){return {GET:"\u2192",POST:"\u2191",PUT:"\u21D1",PATCH:"\u2197",DELETE:"\u2715"}[e.toUpperCase()]||"\u2022"}function se(e){let t="\x1B[0m";return e<100?`\x1B[32m${e}ms${t}`:e<300?`\x1B[33m${e}ms${t}`:e<1e3?`\x1B[31m${e}ms${t}`:`\x1B[41m\x1B[37m${e}ms${t}`}function ce(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let r=e;return r.cause!==void 0&&(t.cause=T(r.cause)),t}function T(e,t=new WeakSet){if(e instanceof Error)return ce(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(r=>T(r,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let r={};for(let[o,n]of Object.entries(e))r[o]=T(n,t);return t.delete(e),r}return e}function Ae(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=T(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var vt="[REDACTED]",Hr=["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"],Wr=["authorization","cookie","set-cookie","x-api-key","x-auth-token"],Qr=[{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}],Jr=/\b(?:\d[ -]*?){16}\b/g;function St(e){let t=new Set,r=[];for(let o of e)typeof o!="string"||o.length===0||t.has(o)||(t.add(o),r.push(o));return r}function Gr(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Kr(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Xr(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Vr(e){return new Set([...Wr,...e.keys.map(t=>t.toLowerCase())])}function Yr(e){return e.split(".").filter(Boolean)}function Be(e,t,r=0,o=0){if(r===e.length)return o===t.length;let n=e[r];if(n==="**"){if(r===e.length-1)return true;for(let a=o;a<=t.length;a+=1)if(Be(e,t,r+1,a))return true;return false}return o>=t.length||n!=="*"&&n!==t[o]?false:Be(e,t,r+1,o+1)}function Zr(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(r=>Be(Yr(r),e))}function en(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let r=0,o=false;for(let n=t.length-1;n>=0;n-=1){let a=Number(t[n]);o&&(a*=2,a>9&&(a-=9)),r+=a,o=!o;}return r%10===0}function le(e,t,r){if(r||t.disablePatternScanning)return e;let o=e;for(let{type:n,pattern:a}of Qr)o=o.replace(a,`[REDACTED:${n}]`);o=o.replace(Jr,n=>en(n)?"[REDACTED:card]":n);for(let n of t.patterns)o=o.replace(Gr(n),"[REDACTED:pattern]");return o}function ue(e,t,r,o){if(typeof e=="string")return le(e,t,!!o.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((a,i)=>ue(a,t,r,{path:[...o.path,String(i)],skipPatternScanning:o.skipPatternScanning}));if(!Kr(e))return e;let n={};for(let[a,i]of Object.entries(e)){let s=[...o.path,a];if(r.has(a.toLowerCase())||Zr(s,t)){if(i==null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"){n[a]=vt;continue}n[a]=ue(i,t,r,{path:s,skipPatternScanning:o.skipPatternScanning});continue}n[a]=ue(i,t,r,{path:s,skipPatternScanning:o.skipPatternScanning});}return n}function x(e,t){return {keys:St([...Hr,...e?.keys??[],...t?.keys??[]]),paths:St([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(r=>r instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function C(e,t,r={path:[]}){let o=T(e);return ue(o,t,Xr(t),r)}function N(e,t){return typeof e=="string"?le(e,t,false):Ae(C(e,t))}function tn(e){if(!e)return {};if(e instanceof Headers){let t={};return e.forEach((r,o)=>{t[o]=r;}),t}if(typeof e.entries=="function"){let t={};for(let[r,o]of e.entries())t[r]=o;return t}return typeof e.get=="function"?{}:{...e}}function xt(e,t){let r=tn(e),o=Vr(t),n={};for(let[a,i]of Object.entries(r)){if(o.has(a.toLowerCase())){n[a]=vt;continue}if(Array.isArray(i)){n[a]=i.map(s=>le(s,t,false));continue}n[a]=typeof i=="string"?le(i,t,false):i;}return n}function b(e,t){if(!e)return;if(e instanceof Headers||typeof e.get=="function")return e.get(t)??e.get(t.toLowerCase())??void 0;let r=e,o=r[t]??r[t.toLowerCase()];return Array.isArray(o)?o[0]:o}function rn(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>t.match(/for="?(\[[^\]]+\]|[^;,\s"]+)/i)?.[1]?.replace(/^"|"$/g,"")??"").map(t=>t.replace(/^\[|\]$/g,"")).filter(Boolean):[]}function nn(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function on(e){if(e.startsWith("[")){let t=e.indexOf("]");return t>=0?e.slice(1,t):e}return e.replace(/:\d+$/,"")}function an(e){return /edg\//i.test(e)?"Edge":/opr\//i.test(e)||/opera/i.test(e)?"Opera":/chrome\//i.test(e)&&!/edg\//i.test(e)?"Chrome":/firefox\//i.test(e)?"Firefox":/safari\//i.test(e)&&!/chrome\//i.test(e)?"Safari":/curl\//i.test(e)?"curl":/postmanruntime/i.test(e)?"Postman":"Unknown"}function sn(e){return /windows/i.test(e)?"Windows":/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/mac os x|macintosh/i.test(e)?"macOS":/linux/i.test(e)?"Linux":"Unknown"}function cn(e){return e?/bot|crawler|spider|curl|wget|postmanruntime/i.test(e)?"bot":/ipad|tablet/i.test(e)?"tablet":/mobi|iphone|android/i.test(e)?"mobile":"desktop":"unknown"}function de(e,t="/"){if(!e)return t;if(e.startsWith("http://")||e.startsWith("https://"))try{return new URL(e).pathname||t}catch{return t}if(e.startsWith("/")){let r=e.indexOf("?");return r>=0?e.slice(0,r):e}try{return new URL(e,"http://localhost").pathname||t}catch{return t}}function Ne(e,t,r){return {method:e,url:t,headers:r}}function Ie(e,t,r=x()){let o=t??de(e.url),n=(()=>{try{return new URL(e.url)}catch{try{return new URL(o,"http://localhost")}catch{return null}}})(),a=b(e.headers,"x-forwarded-host")??b(e.headers,"host")??n?.host??void 0,i=a?on(a):n?.hostname,s=a?.match(/:(\d+)$/)?.[1]??(n?.port||void 0),l=nn(b(e.headers,"x-forwarded-for")),u=rn(b(e.headers,"forwarded")),c=[b(e.headers,"cf-connecting-ip"),b(e.headers,"true-client-ip"),b(e.headers,"fly-client-ip"),b(e.headers,"x-real-ip"),b(e.headers,"x-client-ip"),l[0],u[0]].filter(L=>!!L),p=b(e.headers,"user-agent"),m=b(e.headers,"sec-ch-ua-platform")?.replace(/^"|"$/g,"")??void 0,w=cn(p??"");return {hostname:i,ip:c[0],forwardedFor:[...l,...u].filter((L,f,g)=>g.indexOf(L)===f),protocol:b(e.headers,"x-forwarded-proto")??(n?.protocol?n.protocol.replace(/:$/,""):void 0),port:s,userAgent:p,origin:b(e.headers,"origin"),referer:b(e.headers,"referer"),acceptLanguage:b(e.headers,"accept-language"),headers:xt(e.headers,r),client:{ip:c[0],hostname:i,browser:p?an(p):void 0,os:p?sn(p):void 0,deviceType:w,platform:m,isMobile:w==="mobile"}}}function ge(e,t,r,o,n,a={},i=x()){return {type:t,method:e.method,url:r,statusCode:o,responseTime:n,...Ie(e,r,i),...a}}function pe(e,t,r,o){let n=ie(e),a=ae(t),i=se(o),s=Rt(e);return `${n} ${s} ${a} ${r} ${i}`}function fe(e,t){if(e==null)return t===void 0?void 0:{statusCode:t,message:`HTTP ${t}`};if(e instanceof Error){let r=e;return {status:r.status,statusCode:r.statusCode??t,code:r.code,message:e.message,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:r.details,cause:r.cause}}if(typeof e=="object"){let r=e;return {status:typeof r.status=="number"?r.status:void 0,statusCode:typeof r.statusCode=="number"?r.statusCode:t,code:typeof r.code=="string"||typeof r.code=="number"?r.code:void 0,message:typeof r.message=="string"?r.message:`HTTP ${t??500}`,stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:r.details!==null&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:void 0,cause:r.cause}}return {statusCode:t,message:typeof e=="string"?e:`HTTP ${t??500}`}}function Oe(e){return e>=400}var un=z$1.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"}),G=z$1.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),Fe=z$1.string().trim().min(1);function ze(e){return un.safeParse(e).success}function F(e){return G.safeParse(e).success}function I(e){return Fe.safeParse(e).success}var O="/inngest";var ln=["debug","info","warning","error","critical","success","table"],dn=z$1.union([z$1.literal("betterstack"),z$1.literal("databuddy"),z$1.literal("posthog"),z$1.literal("sentry"),z$1.undefined(),z$1.object({type:z$1.literal("otlp"),name:Fe})]);function gn(e){return typeof e=="string"&&ln.includes(e)}function pn(e){return dn.safeParse(e).success}function fn(e){try{return e()}catch{return}}function mn(){return Math.random().toString(36).slice(2,10)}function me(){let e=fn(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${mn()}`}function Tt(e){if(!F(e)||e.type!=="client_log"||e.source!=="client"||!gn(e.level)||typeof e.id!="string"||typeof e.message!="string"||typeof e.clientTimestamp!="string")return false;let t=G.safeParse(e.page),r=G.safeParse(e.browser),o=G.safeParse(e.session);return !t.success||!r.success||!o.success||!pn(e.connector)?false:typeof o.data.pageId=="string"&&typeof o.data.sessionId=="string"}function qe(e){return e?e.startsWith("/")?e:`/${e}`:O}function kt(){return U.join(yn.homedir(),".blyp","queue.db")}function bn(e,t=new Set){return (r,o,n)=>{if(t.has(r)||typeof console>"u")return;let a=console[e];if(typeof a=="function"){if(t.add(r),n===void 0){a.call(console,o);return}a.call(console,o,n);}}}function _(e){return bn("warn",e)}var Rn="@blyp/core",Sn=".gitignore",Pt=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],vn="blyp.config.json",xn="https://us.i.posthog.com",Tn="blyp-app",kn=Tn,En=new Set,P=_(En),At={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},Bt={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:At},je={enabled:true,path:O},Nt=x(),z={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},v={enabled:false,memoryBufferSize:500,durableQueuePath:kt(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:z},It={maxRetries:1,backoffMs:100},Dn={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:It},Et={pretty:true,level:"info",destination:"file",file:Bt,clientLogging:je,redact:Nt,connectors:{delivery:v}},K=null;function _n(e){let t=e;for(;;){let r=resolve(t,"package.json");if(existsSync(r))try{let n=JSON.parse(readFileSync(r,"utf-8"));if(I(n.name))return n.name}catch{}let o=dirname(t);if(o===t)return;t=o;}}function $e(e=process.cwd()){return _n(e)??kn}function Pn(){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:O},redact:Nt,connectors:{delivery:v}}}function An(e){let t=resolve(e,"package.json");if(!existsSync(t))return true;try{return JSON.parse(readFileSync(t,"utf-8")).name!==Rn}catch{return true}}function Bn(e){if(Pt.some(r=>existsSync(resolve(e,r))))return;let t=resolve(e,vn);if(!existsSync(t))try{writeFileSync(t,`${JSON.stringify(Pn(),null,2)}
2
+ `);}catch(r){console.error("[Blyp] Warning: Failed to create blyp.config.json:",r);}}function Nn(e){let t=resolve(e,Sn);if(!existsSync(t)){try{writeFileSync(t,`logs
3
+ .blyp
4
+ `);}catch(r){console.error("[Blyp] Warning: Failed to create .gitignore:",r);}return}try{let r=readFileSync(t,"utf-8"),o=["logs",".blyp"].filter(a=>{let i=a.replace(".","\\.");return !new RegExp(`^(?:/?${i}/?)\\s*$`,"m").test(r)});if(o.length===0)return;let n=r.endsWith(`
5
+ `)?"":`
6
+ `;appendFileSync(t,`${n}${o.join(`
7
+ `)}
8
+ `);}catch(r){console.error("[Blyp] Warning: Failed to update .gitignore:",r);}}function In(){let e=process.cwd();An(e)&&(Bn(e),Nn(e));}function On(){let e=process.cwd(),t=Pt.map(o=>resolve(e,o)).filter(o=>existsSync(o));if(t.length===0)return null;if(t.length>1){let o=t[0];P(`config-multiple:${o}`,`[Blyp] Warning: Multiple config files found. Using ${o} and ignoring ${t.slice(1).join(", ")}.`);}let r=t[0];return {path:r,type:r.endsWith(".json")?"json":"jiti"}}function Ot(e,t){let r=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !r||typeof r!="object"||Array.isArray(r)?(P(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):r}function Mn(e){try{let t=readFileSync(e,"utf-8");return Ot(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function Fn(e){try{let t=createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return Ot(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function zn(e){return e.type==="json"?Mn(e.path):Fn(e.path)}function Dt(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function qn(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function jn(e,t){return {...It,...e,...t}}function Un(e,t){return {...Dn,...e,...t,retry:jn(e?.retry,t?.retry)}}function $n(e){let t=e.model??"blypLog",o=e.client?.[t];return !!o&&typeof o.create=="function"}function Hn(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function Wn(e,t){if(!e)return;let r=e.adapter,o=false;t==="json"?P("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?P(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):r?Dt(r)?(o=$n({...r,model:r.model??"blypLog"}),o||P("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${r.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):qn(r)&&(o=Hn(r),o||P("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):P("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let n=Dt(r)?{...r,model:r.model??"blypLog"}:r;return {dialect:e.dialect,adapter:n,delivery:Un(void 0,e.delivery),ready:o,status:o?"enabled":"missing"}}function Qn(e,t){return {...At,...e,...t}}function Jn(e,t){return {...Bt,...e,...t,rotation:Qn(e?.rotation,t?.rotation)}}function Gn(e,t){return {...je,...e,...t,path:t?.path??e?.path??je.path}}function Kn(e,t){return x(e,t)}function Xn(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??z.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??z.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??z.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??z.multiplier),jitter:t?.jitter??e?.jitter??z.jitter}}function Vn(e,t){let r=t?.durableQueuePath??e?.durableQueuePath??v.durableQueuePath;return {enabled:t?.enabled??e?.enabled??v.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??v.memoryBufferSize)),durableQueuePath:I(r)?r:v.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??v.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??v.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??v.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??v.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??v.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??v.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??v.overflowStrategy,retry:Xn(e?.retry,t?.retry),durableReady:false}}function Yn(e,t,r){if(!(!e&&!t))return Wn({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},r)}function Zn(e,t){let r=t?.enabled??e?.enabled??false,o=t?.projectKey??e?.projectKey,n=e?.enabled===true?e?.errorTracking:void 0,a=t?.errorTracking?.mode??n?.mode??"auto",i=t?.errorTracking?.enabled??n?.enabled??r,s=r&&i&&typeof o=="string"&&o.trim().length>0;return {enabled:r,mode:t?.mode??e?.mode??"auto",projectKey:o,host:t?.host??e?.host??xn,serviceName:t?.serviceName??e?.serviceName??$e(),errorTracking:{enabled:i,mode:a,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??n?.enableExceptionAutocapture??a==="auto",ready:s,status:s?"enabled":"missing"}}}function eo(e,t){let r=t?.enabled??e?.enabled??false,o=t?.apiKey??e?.apiKey,n=t?.websiteId??e?.websiteId,a=r&&I(o)&&I(n);return {enabled:r,mode:t?.mode??e?.mode??"auto",apiKey:o,websiteId:n,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:a,status:a?"enabled":"missing"}}function to(e,t){let r=t?.sourceToken??e?.sourceToken,o=t?.ingestingHost??e?.ingestingHost,n=t?.enabled??e?.enabled??false,a=e?.enabled===true?e?.errorTracking:void 0,i=ro(n,a,t?.errorTracking),s=n&&I(r)&&ze(o);return {enabled:n,mode:t?.mode??e?.mode??"auto",sourceToken:r,ingestingHost:o,serviceName:t?.serviceName??e?.serviceName??$e(),errorTracking:i,ready:s,status:s?"enabled":"missing"}}function ro(e,t,r){let o=r?.dsn??t?.dsn,n=r?.enabled??t?.enabled??e,a=n&&I(o);return {enabled:n,dsn:o,tracesSampleRate:r?.tracesSampleRate??t?.tracesSampleRate??1,environment:r?.environment??t?.environment,release:r?.release??t?.release,ready:a,status:a?"enabled":"missing"}}function no(e,t){let r=t?.dsn??e?.dsn,o=t?.enabled??e?.enabled??false,n=o&&typeof r=="string"&&r.trim().length>0;return {enabled:o,mode:t?.mode??e?.mode??"auto",dsn:r,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:n,status:n?"enabled":"missing"}}function oo(e,t){let r=t?.endpoint??e?.endpoint,o=t?.enabled??e?.enabled??false,n={...{},...t?.headers??{}},a=o&&ze(r);return {name:t?.name??e?.name??"",enabled:o,mode:t?.mode??e?.mode??"auto",endpoint:r,headers:n,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??$e(),ready:a,status:a?"enabled":"missing"}}function io(e,t){let r=t??e??[],o=new Map;for(let n of r)!n||typeof n.name!="string"||n.name.length===0||(o.has(n.name)&&P(`otlp-duplicate:${n.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${n.name}" found. Using the last definition.`),o.set(n.name,oo(void 0,n)));return Array.from(o.values())}function ao(e,t){return {betterstack:to(e?.betterstack,t?.betterstack),databuddy:eo(e?.databuddy,t?.databuddy),posthog:Zn(e?.posthog,t?.posthog),sentry:no(e?.sentry,t?.sentry),otlp:io(e?.otlp,t?.otlp),delivery:Vn(e?.delivery,t?.delivery)}}function Ue(e,t={},r={}){return {...e,...t,destination:t.destination??e.destination??"file",file:Jn(e.file,t.file),database:Yn(e.database,t.database,r.configFileType),clientLogging:Gn(e.clientLogging,t.clientLogging),redact:Kn(e.redact,t.redact),connectors:ao(e.connectors,t.connectors)}}function so(){if(K!==null)return K;In();let e=On();if(e){let t=zn(e);K=Ue(Et,t,{configFileType:e.type});}else K=Ue(Et);return K}function X(e={}){return Ue(so(),e)}function co(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function uo(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function He(e,t){if(!t||t.length===0)return false;let r=co(e);return t.some(o=>{let n=uo(o);if(n===r||n==="/**"||n==="**")return true;if(n==="/*")return r.split("/").filter(i=>i.length>0).length===1;if(n.endsWith("/*")&&!n.includes("**")){let a=n.slice(0,-1);return r.startsWith(a)?r.slice(a.length).split("/").filter(l=>l.length>0).length===1:false}if(n.includes("**")){if(n==="/**")return true;if(n.startsWith("/")&&n.endsWith("**")){let l=n.slice(0,-2);return l.endsWith("/")&&l.length>1&&(l=l.slice(0,-1)),l===r?true:r.startsWith(l+"/")}let a=n.indexOf("**"),i=n.substring(0,a),s=n.substring(a+2);return i.endsWith("/")&&i.length>1&&(i=i.slice(0,-1)),i===""&&s===""?true:i!==""&&s===""?r.startsWith(i+"/"):i===""&&s!==""?r.endsWith(s)||r.includes(s+"/"):i!==""&&s!==""?r.startsWith(i)&&(r.endsWith(s)||r.includes(s+"/")):false}if(n.includes("*")){let a=n.lastIndexOf("."),i=n.lastIndexOf("*");if(a>i&&i>0&&n[i-1]==="/"){let c=n.slice(i),p=r.slice(r.lastIndexOf("/")+1),m=p.lastIndexOf(".");if(m>0)return p.slice(m)===c}let s=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*");return new RegExp("^"+s+"$").test(r)}return false})}function go(e){return Buffer.from(gzipSync(e))}function po(e,t){console.warn(`[Blyp] Warning: ${e}`,t);}function he(e){S.mkdirSync(e,{recursive:true});}function fo(e){try{return S.statSync(e).size}catch{return 0}}function mo(e){let t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),o=String(e.getUTCDate()).padStart(2,"0"),n=String(e.getUTCHours()).padStart(2,"0"),a=String(e.getUTCMinutes()).padStart(2,"0"),i=String(e.getUTCSeconds()).padStart(2,"0");return `${t}${r}${o}T${n}${a}${i}Z`}function yo(e,t){let r=`${e}${t}`,o=1;for(;S.existsSync(r);)r=`${e}-${o}${t}`,o+=1;return r}function ho(e,t,r,o){let n=`${t}.`;try{let a=S.readdirSync(e).filter(s=>s.startsWith(n)&&(s.endsWith(".ndjson")||s.endsWith(".ndjson.gz"))).map(s=>U.join(e,s)).sort((s,l)=>S.statSync(s).mtimeMs-S.statSync(l).mtimeMs),i=Math.max(a.length-r,0);for(let s=0;s<i;s+=1)S.rmSync(a[s]);}catch(a){o(`Failed to prune archives for ${t}`,a);}}function bo(){let e=new WeakSet;return (t,r)=>{if(typeof r=="function")return `[Function: ${r.name||"anonymous"}]`;if(r===void 0)return "[undefined]";if(typeof r=="symbol")return r.toString();if(r!==null&&typeof r=="object"){if(e.has(r))return "[Circular]";e.add(r);}return r}}function Qe(e){return JSON.stringify(e,bo())}function Co(e){let t=e.file,r=t?.dir||e.logDir||U.join(process.cwd(),"logs"),o=t?.archiveDir||U.join(r,"archive"),n=t?.rotation;return {enabled:t?.enabled??true,dir:r,archiveDir:o,rotationEnabled:n?.enabled??true,maxSizeBytes:n?.maxSizeBytes??10*1024*1024,maxArchives:n?.maxArchives??5,compress:n?.compress??true}}var We=class{constructor(t,r={}){d(this,"config");d(this,"gzip");d(this,"warn");d(this,"combined");d(this,"error");this.config=Co(t),this.gzip=r.gzip??go,this.warn=r.warn??po,this.combined={activePath:U.join(this.config.dir,"log.ndjson"),archivePrefix:"log",bytes:0,queue:[],processing:false},this.error={activePath:U.join(this.config.dir,"log.error.ndjson"),archivePrefix:"log.error",bytes:0,queue:[],processing:false},this.config.enabled&&(he(this.config.dir),he(this.config.archiveDir),this.seedStream(this.combined),this.seedStream(this.error));}write(t){if(!this.config.enabled)return;let r=`${Qe(t)}
9
+ `;this.enqueue(this.combined,r),(t.level==="error"||t.level==="critical")&&this.enqueue(this.error,r);}enqueue(t,r){t.queue.push(r),this.processQueue(t);}processQueue(t){if(!t.processing){t.processing=true;try{for(;t.queue.length>0;){let r=t.queue.shift();if(r!==void 0)try{this.append(t,r);}catch(o){this.warn(`Failed writing log line for ${t.archivePrefix}`,o);}}}finally{t.processing=false;}}}seedStream(t){t.bytes=fo(t.activePath),this.config.rotationEnabled&&t.bytes>this.config.maxSizeBytes&&t.bytes>0&&(this.rotate(t),S.closeSync(S.openSync(t.activePath,"a")),t.bytes=0);}append(t,r){he(this.config.dir);let o=Buffer.byteLength(r,"utf8");this.config.rotationEnabled&&t.bytes>0&&t.bytes+o>this.config.maxSizeBytes&&this.rotate(t),S.appendFileSync(t.activePath,r,"utf8"),t.bytes+=o;}rotate(t){if(he(this.config.archiveDir),!S.existsSync(t.activePath)||t.bytes===0){t.bytes=0;return}let r=mo(new Date),o=U.join(this.config.archiveDir,`${t.archivePrefix}.${r}`),n=yo(o,".ndjson");if(S.renameSync(t.activePath,n),this.config.compress)try{let a=`${n}.gz`,i=this.gzip(S.readFileSync(n));S.writeFileSync(a,i),S.rmSync(n);}catch(a){this.warn(`Failed to gzip archive ${n}`,a);}t.bytes=0,ho(this.config.archiveDir,t.archivePrefix,this.config.maxArchives,this.warn);}};function Mt(e){return new We(e)}function Je(e){return F(e.data)?e.data:e}function A(e,t){if(t in e){let n=e[t];if(typeof n=="string"||typeof n=="number")return n}let o=Je(e)[t];if(typeof o=="string"||typeof o=="number")return o}function Ge(e,t){let r=Je(e),n=(F(r.page)?r.page:void 0)?.[t];return typeof n=="string"?n:void 0}function Ke(e,t){let r=Je(e),n=(F(r.session)?r.session:void 0)?.[t];return typeof n=="string"?n:void 0}function be(e){return A(e,"type")}function Lo(e,t){let r=be(e),o=typeof e.caller=="string"?e.caller:void 0,n=A(e,"groupId"),a=A(e,"traceId"),i=A(e,"method"),s=A(e,"path"),l=A(e,"status"),u=A(e,"duration"),c=Ge(e,"pathname"),p=Ge(e,"url"),m=Ke(e,"sessionId"),w=Ke(e,"pageId"),L={"blyp.level":e.level,"blyp.source":t,"blyp.payload":Qe(e)},f=[["blyp.type",r],["blyp.caller",o],["blyp.group_id",n],["blyp.trace_id",a],["http.method",i],["url.path",s],["client.page_path",c],["client.page_url",p],["client.session_id",m],["client.page_id",w]],g=[["http.status_code",l],["blyp.duration_ms",u]];for(let[y,R]of f)R&&(L[y]=R);for(let[y,R]of g)R!==void 0&&(L[y]=R);return L}function Xe(e,t,r={}){return {...Lo(e,t),...r}}var Ro=createJiti(typeof __filename=="string"?__filename:import.meta.url,{interopDefault:false,moduleCache:true,fsCache:false}),Ft=new Map;function So(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function $(e,t,r=`@blyp/core/${e}`){let o=`@blyp/core/${e}`,n=`${o}::${r}`,a=Ft.get(n);if(a)return a;try{let i=Ro(r);return Ft.set(n,i),i}catch(i){if(!So(i))throw i;let s=t.map(u=>`"${u}"`).join(", "),l=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${o}". Install ${s} to use this API. Example: bun add ${l}. You can also import directly from "${o}".`,{cause:i instanceof Error?i:void 0})}}var xo=createRequire(typeof __filename=="string"?__filename:import.meta.url),Ve=null;function To(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function ko(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 zt(){if(Ve)return Ve;let e;try{e=xo("pino-pretty");}catch(r){throw To(r)?new Error('[Blyp] Failed to initialize the pretty logger transport because pretty: true requires "pino-pretty" to be installed.',{cause:r instanceof Error?r:void 0}):new Error('[Blyp] Failed to initialize the pretty logger transport with "pino-pretty".',{cause:r instanceof Error?r:void 0})}let t=ko(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return Ve=t,t}var qt={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function Ce(e){return e.replace(/\\/g,"/")}function Eo(e){let t=Ce(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 Do(e){let t=Ce(e),r=Ce(process.cwd());return t.startsWith(`${r}/`)?t.slice(r.length+1):t}function jt(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
10
+ `),r=null;for(let o=2;o<t.length;o+=1){let n=t[o];if(!n)continue;let a=n.match(/\((.*):(\d+):\d+\)/)||n.match(/at\s+(.*):(\d+):(\d+)/);if(!a)continue;let i=a[1]||"",s=parseInt(a[2]||"0",10)||null;if(i&&!i.includes("node_modules")&&!Eo(i)){let l=Do(i);if(!Ce(l).startsWith("dist/"))return {file:l,line:s};r??(r={file:l,line:s});}}if(r)return r}catch{return {file:null,line:null}}return {file:null,line:null}}var Ut=N;function $t(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function Ht(e,t,r,o,n=x()){let{file:a,line:i}=jt(),s=Ut(t,n),l={timestamp:new Date().toISOString(),level:qt[e],message:$t(s)},u=E();return t instanceof Error&&(l.error=C(ce(t),n)),a&&(l.caller=i!==null?`${a}:${i}`:a),r.length===1?l.data=C(r[0],n):r.length>1&&(l.data=C(r,n)),Object.keys(o).length>0&&(l.bindings=C(o,n)),u&&(l.traceId=u),l}function Wt(e,t,r,o,n=x()){let{file:a,line:i}=jt(),s=C(r,n),l=E(),u={message:$t(Ut(t,n)),...s};return a&&(u.caller=i!==null?`${a}:${i}`:a),Object.keys(o).length>0&&(u.bindings=C(o,n)),l&&u.traceId===void 0&&(u.traceId=l),u.level=typeof s.level=="string"&&s.level.length>0?s.level:qt[e],u.timestamp=typeof s.timestamp=="string"&&s.timestamp.length>0?s.timestamp:new Date().toISOString(),u}function Qt(e){switch(e){case "debug":return "debug";case "warning":return "warning";case "warn":return "warn";case "error":return "error";case "success":return "success";case "critical":return "critical";case "table":return "table";default:return "info"}}var Ye=class{constructor(t){this.logger=t;d(this,"isAsync",false);d(this,"isReady",true);}write(t){this.logger.write(t);}async flush(){}async shutdown(){}};function Jt(e){return new Ye(Mt(e))}function Gt(e){let t=e.db;if(typeof t?.insert!="function"||e.table===void 0)throw new Error("[Blyp] Drizzle database adapter is missing a db.insert function or table reference.");return {async insert(r){r.length!==0&&await t.insert(e.table).values(r);}}}function _o(e){let t=String(e??"");return t.includes("createMany")||t.includes("Unknown argument")||t.includes("not supported")||t.includes("is not a function")}function Kt(e){let t=e.client,r=e.model??"blypLog",o=t[r];if(!o||typeof o.create!="function")throw new Error(`[Blyp] Prisma database adapter is missing the "${r}" delegate or its create method.`);let n=o,a=typeof n.createMany=="function";async function i(s){if(typeof t.$transaction=="function"){await t.$transaction(s.map(l=>n.create({data:l})));return}for(let l of s)await n.create({data:l});}return {async insert(s){if(s.length!==0){if(s.length===1){await n.create({data:s[0]});return}if(!a||typeof n.createMany!="function"){await i(s);return}try{await n.createMany({data:s});}catch(l){if(!_o(l))throw l;a=false,await i(s);}}}}}function Xt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function H(e){return typeof e=="string"&&e.length>0?e:null}function Ao(e){if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function Vt(e){let t=T(e);return {id:randomUUID(),timestamp:Ao(e.timestamp),level:e.level,message:e.message,caller:H(e.caller),type:H(e.type),traceId:H(e.traceId),groupId:H(e.groupId),method:H(e.method),path:H(e.path),status:Xt(e.status),duration:Xt(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 Bo(e){return !!e&&e.type==="prisma"}function No(e){return !!e&&e.type==="drizzle"}function Yt(e){if(Bo(e.adapter))return Kt(e.adapter);if(No(e.adapter))return Gt(e.adapter);throw new Error("[Blyp] Unsupported database adapter configuration.")}function Io(e){return new Promise(t=>{setTimeout(t,e);})}var Le=class{constructor(t){this.config=t;d(this,"isAsync",true);d(this,"isReady",true);d(this,"warnOnce",_(new Set));d(this,"queue",[]);d(this,"writer");d(this,"timer",null);d(this,"processing",false);d(this,"closed",false);d(this,"terminalError",null);d(this,"activeDispatch",null);this.writer=Yt(t);}write(t){this.closed||(this.enqueue(Vt(t)),this.scheduleDispatch());}async flush(){this.timer&&(clearTimeout(this.timer),this.timer=null);let t=(async()=>{if(await this.drain(),this.terminalError)throw this.terminalError})(),r=null;try{await Promise.race([t,new Promise((o,n)=>{r=setTimeout(()=>{this.warnOnce("database-flush-timeout",`[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`),n(new Error("[Blyp] Timed out flushing database logs."));},this.config.delivery.flushTimeoutMs);})]);}finally{r&&clearTimeout(r);}}async shutdown(){this.closed=true,await this.flush();}enqueue(t){this.queue.push(t);let r=this.queue.length-this.config.delivery.maxQueueSize;if(!(r<=0)){if(this.warnOnce("database-overflow",`[Blyp] Warning: Database log queue exceeded ${this.config.delivery.maxQueueSize} entries. Applying ${this.config.delivery.overflowStrategy} overflow handling.`),this.config.delivery.overflowStrategy==="drop-new"){this.queue.splice(this.config.delivery.maxQueueSize);return}this.queue.splice(0,r);}}scheduleDispatch(){if(!this.processing){if(this.config.delivery.strategy==="immediate"){this.drain();return}if(this.queue.length>=this.config.delivery.batchSize){this.drain();return}this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.drain();},this.config.delivery.flushIntervalMs));}}async drain(){if(this.processing){this.activeDispatch&&await this.activeDispatch;return}this.processing=true,this.activeDispatch=this.processQueue();try{await this.activeDispatch;}finally{this.processing=false,this.activeDispatch=null;}}async processQueue(){for(;this.queue.length>0;){let t=this.config.delivery.strategy==="batch"?Math.max(1,this.config.delivery.batchSize):1,r=this.queue.splice(0,t);try{await this.insertWithRetry(r);}catch(o){let n=o instanceof Error?o:new Error(String(o??"Unknown database logging failure"));throw this.terminalError=n,this.warnOnce("database-insert-failure",`[Blyp] Warning: Failed to persist logs to the ${this.config.dialect??"database"} database.`,n),n}}}async insertWithRetry(t){let r=Math.max(1,this.config.delivery.retry.maxRetries+1),o=0;for(;o<r;){o+=1;try{await this.writer.insert(t);return}catch(n){if(o>=r)throw n;await Io(this.config.delivery.retry.backoffMs);}}}};var Ze=class{constructor(){d(this,"isAsync",false);d(this,"isReady",false);}write(t){}async flush(){}async shutdown(){}},Oo=_(new Set);function Zt(e){if(e.destination!=="database")return Jt(e);let t=e.database;return t?.ready?new Le(t):(Oo("database-sink-disabled","[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."),new Ze)}function er(e,t){let r=Math.max(1,Math.floor(e)),o=Math.pow(t.multiplier,r-1),n=Math.min(Math.max(0,Math.floor(t.initialBackoffMs*o)),Math.max(0,t.maxBackoffMs));return t.jitter?Math.floor(Math.random()*(n+1)):n}var tr="bun:sqlite";var rr="node:sqlite";function nr(){return `
11
+ const { parentPort } = require('node:worker_threads');
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+
15
+ const NODE_SQLITE_MODULE = ${JSON.stringify(rr)};
16
+ const BUN_SQLITE_MODULE = ${JSON.stringify(tr)};
17
+ const CLAIM_LEASE_MS = 30000;
18
+
19
+ let db;
20
+ let runtime = 'unsupported';
21
+
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 {}
48
+
49
+ try {
50
+ const mod = await import(NODE_SQLITE_MODULE);
51
+ runtime = 'node';
52
+ return {
53
+ create(filePath) {
54
+ return new mod.DatabaseSync(filePath);
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 {}
73
+
74
+ throw new Error('No built-in SQLite runtime is available in this worker.');
75
+ }
76
+
77
+ let adapter;
78
+
79
+ function ensureReady() {
80
+ if (!db || !adapter) {
81
+ throw new Error('SQLite durable queue is not initialized.');
82
+ }
83
+ }
84
+
85
+ function normalizeConnectorTarget(value) {
86
+ return typeof value === 'string' && value.length > 0 ? value : null;
87
+ }
88
+
89
+ function createConnectorCondition() {
90
+ return '(connector_type = ? AND ((connector_target IS NULL AND ? IS NULL) OR connector_target = ?))';
91
+ }
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;
116
+ }
117
+
118
+ const insert = adapter.prepare(
119
+ db,
120
+ 'INSERT INTO connector_delivery_status (connector_type, connector_target, last_success_at, last_failure_at, last_error, updated_at) VALUES (?, ?, ?, ?, ?, ?)'
121
+ );
122
+
123
+ adapter.run(insert, [
124
+ item.connectorType,
125
+ connectorTarget,
126
+ success ? item.timestamp : null,
127
+ success ? null : item.timestamp,
128
+ success ? null : item.lastError ?? null,
129
+ item.timestamp,
130
+ ]);
131
+ }
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'));
182
+ }
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]);
191
+ }
192
+
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
+ ]);
222
+ }
223
+
224
+ adapter.exec(db, 'COMMIT');
225
+ } catch (error) {
226
+ adapter.exec(db, 'ROLLBACK');
227
+ throw error;
228
+ }
229
+ }
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 [];
243
+ }
244
+
245
+ adapter.exec(db, 'BEGIN');
246
+ try {
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;
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
+ }));
278
+ }
279
+
280
+ function ack(ids) {
281
+ ensureReady();
282
+ if (!Array.isArray(ids) || ids.length === 0) {
283
+ return;
284
+ }
285
+
286
+ adapter.exec(db, 'BEGIN');
287
+ try {
288
+ const statement = adapter.prepare(db, 'DELETE FROM connector_jobs WHERE id = ?');
289
+ for (const id of ids) {
290
+ adapter.run(statement, [id]);
291
+ }
292
+ adapter.exec(db, 'COMMIT');
293
+ } catch (error) {
294
+ adapter.exec(db, 'ROLLBACK');
295
+ throw error;
296
+ }
297
+ }
298
+
299
+ function reschedule(items, now) {
300
+ ensureReady();
301
+ if (!Array.isArray(items) || items.length === 0) {
302
+ return;
303
+ }
304
+
305
+ adapter.exec(db, 'BEGIN');
306
+ try {
307
+ const statement = adapter.prepare(
308
+ db,
309
+ 'UPDATE connector_jobs SET state = ?, attempt_count = ?, next_attempt_at = ?, last_error = ?, claimed_at = NULL, updated_at = ? WHERE id = ?'
310
+ );
311
+ for (const item of items) {
312
+ adapter.run(statement, [
313
+ 'pending',
314
+ item.attemptCount,
315
+ item.nextAttemptAt,
316
+ item.lastError ?? null,
317
+ now,
318
+ item.id,
319
+ ]);
320
+ }
321
+ adapter.exec(db, 'COMMIT');
322
+ } catch (error) {
323
+ adapter.exec(db, 'ROLLBACK');
324
+ throw error;
325
+ }
326
+ }
327
+
328
+ function deadLetter(items) {
329
+ ensureReady();
330
+ if (!Array.isArray(items) || items.length === 0) {
331
+ return;
332
+ }
333
+
334
+ adapter.exec(db, 'BEGIN');
335
+ try {
336
+ const insert = adapter.prepare(
337
+ db,
338
+ 'INSERT OR REPLACE INTO connector_dead_letters (id, connector_type, connector_target, operation, payload_json, attempt_count, max_attempts, last_error, first_enqueued_at, dead_lettered_at, last_attempt_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
339
+ );
340
+ const remove = adapter.prepare(db, 'DELETE FROM connector_jobs WHERE id = ?');
341
+
342
+ for (const item of items) {
343
+ adapter.run(insert, [
344
+ item.id,
345
+ item.connectorType,
346
+ normalizeConnectorTarget(item.connectorTarget),
347
+ item.operation,
348
+ item.payloadJson,
349
+ item.attemptCount,
350
+ item.maxAttempts,
351
+ item.lastError ?? null,
352
+ item.firstEnqueuedAt,
353
+ item.deadLetteredAt,
354
+ item.lastAttemptAt,
355
+ ]);
356
+ adapter.run(remove, [item.id]);
357
+ }
358
+
359
+ adapter.exec(db, 'COMMIT');
360
+ } catch (error) {
361
+ adapter.exec(db, 'ROLLBACK');
362
+ throw error;
363
+ }
364
+ }
365
+
366
+ function markSuccess(items) {
367
+ ensureReady();
368
+ if (!Array.isArray(items) || items.length === 0) {
369
+ return;
370
+ }
371
+
372
+ adapter.exec(db, 'BEGIN');
373
+ try {
374
+ for (const item of items) {
375
+ updateConnectorDeliveryStatus(item, true);
376
+ }
377
+ adapter.exec(db, 'COMMIT');
378
+ } catch (error) {
379
+ adapter.exec(db, 'ROLLBACK');
380
+ throw error;
381
+ }
382
+ }
383
+
384
+ function markFailure(items) {
385
+ ensureReady();
386
+ if (!Array.isArray(items) || items.length === 0) {
387
+ return;
388
+ }
389
+
390
+ adapter.exec(db, 'BEGIN');
391
+ try {
392
+ for (const item of items) {
393
+ updateConnectorDeliveryStatus(item, false);
394
+ }
395
+ adapter.exec(db, 'COMMIT');
396
+ } catch (error) {
397
+ adapter.exec(db, 'ROLLBACK');
398
+ throw error;
399
+ }
400
+ }
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);
429
+ }
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);
451
+ }
452
+ }
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
+ []
460
+ );
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);
474
+ }
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
+ });
482
+ }
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);
500
+ }
501
+ }
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
+
516
+ return {
517
+ items: rows.map((row) => ({
518
+ id: row.id,
519
+ connectorType: row.connector_type,
520
+ connectorTarget: row.connector_target ?? undefined,
521
+ operation: row.operation,
522
+ payloadJson: row.payload_json,
523
+ attemptCount: row.attempt_count,
524
+ maxAttempts: row.max_attempts,
525
+ lastError: row.last_error ?? undefined,
526
+ firstEnqueuedAt: row.first_enqueued_at,
527
+ deadLetteredAt: row.dead_lettered_at,
528
+ lastAttemptAt: row.last_attempt_at,
529
+ })),
530
+ total: Number(countRow?.count ?? 0),
531
+ };
532
+ }
533
+
534
+ function retryDeadLetters(ids, now) {
535
+ ensureReady();
536
+ if (!Array.isArray(ids) || ids.length === 0) {
537
+ return 0;
538
+ }
539
+
540
+ adapter.exec(db, 'BEGIN');
541
+ try {
542
+ const select = adapter.prepare(db, 'SELECT * FROM connector_dead_letters WHERE id = ?');
543
+ const insert = adapter.prepare(
544
+ db,
545
+ 'INSERT OR REPLACE INTO connector_jobs (id, connector_type, connector_target, operation, payload_json, attempt_count, max_attempts, next_attempt_at, state, last_error, created_at, updated_at, claimed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
546
+ );
547
+ const remove = adapter.prepare(db, 'DELETE FROM connector_dead_letters WHERE id = ?');
548
+ let count = 0;
549
+
550
+ for (const id of ids) {
551
+ const row = adapter.all(select, [id])[0];
552
+ if (!row) {
553
+ continue;
554
+ }
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;
573
+ }
574
+
575
+ adapter.exec(db, 'COMMIT');
576
+ return count;
577
+ } catch (error) {
578
+ adapter.exec(db, 'ROLLBACK');
579
+ throw error;
580
+ }
581
+ }
582
+
583
+ function clearDeadLetters(ids) {
584
+ ensureReady();
585
+ if (!Array.isArray(ids) || ids.length === 0) {
586
+ return 0;
587
+ }
588
+
589
+ adapter.exec(db, 'BEGIN');
590
+ try {
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;
601
+ }
602
+ adapter.exec(db, 'COMMIT');
603
+ return count;
604
+ } catch (error) {
605
+ adapter.exec(db, 'ROLLBACK');
606
+ throw error;
607
+ }
608
+ }
609
+
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);
615
+ }
616
+
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 } });
629
+ return;
630
+ }
631
+ case 'insert':
632
+ insertJobs(payload.jobs);
633
+ parentPort.postMessage({ id, ok: true, result: true });
634
+ return;
635
+ case 'claimDue':
636
+ parentPort.postMessage({ id, ok: true, result: claimDue(payload.limit, payload.now) });
637
+ return;
638
+ case 'ack':
639
+ ack(payload.ids);
640
+ parentPort.postMessage({ id, ok: true, result: true });
641
+ return;
642
+ case 'reschedule':
643
+ reschedule(payload.items, payload.now);
644
+ parentPort.postMessage({ id, ok: true, result: true });
645
+ return;
646
+ case 'deadLetter':
647
+ deadLetter(payload.items);
648
+ parentPort.postMessage({ id, ok: true, result: true });
649
+ return;
650
+ case 'markSuccess':
651
+ markSuccess(payload.items);
652
+ parentPort.postMessage({ id, ok: true, result: true });
653
+ return;
654
+ case 'markFailure':
655
+ markFailure(payload.items);
656
+ parentPort.postMessage({ id, ok: true, result: true });
657
+ return;
658
+ case 'getStatusSummary':
659
+ parentPort.postMessage({ id, ok: true, result: getStatusSummary() });
660
+ return;
661
+ case 'listDeadLetters':
662
+ parentPort.postMessage({
663
+ id,
664
+ ok: true,
665
+ result: listDeadLetters(
666
+ payload.limit,
667
+ payload.offset,
668
+ payload.connectorType,
669
+ payload.connectorTarget
670
+ ),
671
+ });
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;
686
+ }
687
+ parentPort.postMessage({ id, ok: true, result: true });
688
+ return;
689
+ default:
690
+ throw new Error('Unknown SQLite worker command: ' + type);
691
+ }
692
+ } catch (error) {
693
+ parentPort.postMessage({
694
+ id,
695
+ ok: false,
696
+ error: error instanceof Error ? error.message : String(error),
697
+ });
698
+ }
699
+ });
700
+ `}var we=class{constructor(t){this.path=t;d(this,"worker");d(this,"pending",new Map);d(this,"nextId",1);this.worker=new Worker(nr(),{eval:true}),this.worker.on("message",r=>{let o=this.pending.get(r.id);if(o){if(this.pending.delete(r.id),r.ok){o.resolve(r.result);return}o.reject(new Error(r.error??"SQLite worker request failed."));}}),this.worker.on("error",r=>{for(let o of this.pending.values())o.reject(r instanceof Error?r:new Error(String(r)));this.pending.clear();});}request(t,r={}){let o=this.nextId++;return new Promise((n,a)=>{this.pending.set(o,{resolve:n,reject:a}),this.worker.postMessage({id:o,type:t,payload:r});})}async init(){await this.request("init",{path:this.path});}async insert(t){await this.request("insert",{jobs:t});}async claimDue(t,r){return this.request("claimDue",{limit:t,now:r})}async ack(t){await this.request("ack",{ids:t});}async reschedule(t,r){await this.request("reschedule",{items:t,now:r});}async deadLetter(t){await this.request("deadLetter",{items:t});}async markSuccess(t){await this.request("markSuccess",{items:t});}async markFailure(t){await this.request("markFailure",{items:t});}async getStatusSummary(){return this.request("getStatusSummary")}async listDeadLetters(t){return this.request("listDeadLetters",t)}async retryDeadLetters(t,r){return this.request("retryDeadLetters",{ids:t,now:r})}async clearDeadLetters(t){return this.request("clearDeadLetters",{ids:t})}async count(){return this.request("count")}async shutdown(){try{await this.request("shutdown");}finally{await this.worker.terminate();}}};var or=Symbol("blyp.connector.batch-dispatch"),V=Symbol("blyp.connector.delivery-binder");function Y(e){return new Promise(t=>{setTimeout(t,e);})}function Fo(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function ir(e){return JSON.stringify(e)}function zo(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function ar(e){let t=new Map;for(let r of e){let o=`${r.connectorType}:${r.connectorTarget??""}`;t.has(o)||t.set(o,{connectorType:r.connectorType,connectorTarget:r.connectorTarget});}return [...t.values()]}var Re=class{constructor(t){this.config=t;d(this,"warnOnce",_(new Set));d(this,"memoryQueue",[]);d(this,"durableStaging",[]);d(this,"dispatchers",new Map);d(this,"activeDispatches",0);d(this,"flushPromise",null);d(this,"durableFlushPromise",null);d(this,"pollTimer",null);d(this,"durablePollRunning",false);d(this,"closed",false);d(this,"durableClient",null);d(this,"durableReady",false);d(this,"durableInitPromise",null);t.enabled&&(this.durableInitPromise=this.initializeDurableQueue());}bindTarget(t){typeof t[V]=="function"&&t[V](this);let r=t[or];r&&this.dispatchers.set(r.dispatchKey,r);}unbindTarget(t){typeof t[V]=="function"&&t[V](null);}enqueue(t,r,o,n){this.closed||!Fo(r)||(this.dispatchers.set(o.dispatchKey,o),this.memoryQueue.push({id:me(),connectorType:t,connectorTarget:n,source:"server",record:r,attemptCount:0,maxAttempts:this.config.retry.maxAttempts,nextAttemptAt:Date.now(),createdAt:Date.now(),dispatchKey:o.dispatchKey,dispatcher:o}),this.enforceMemoryCapacity(),this.scheduleDispatch());}async flush(){await this.durableInitPromise?.catch(()=>{}),await this.processUntilIdle(),await this.flushDurableStaging(),await this.drainDurableQueueForFlush(),await this.flushDurableStaging(),await this.processUntilIdle();}async shutdown(){if(this.closed=true,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),await this.durableInitPromise?.catch(()=>{}),this.durableReady){let t=this.memoryQueue.splice(0,this.memoryQueue.length);for(let r of t)this.stageDurableJob(r,r.attemptCount,Math.max(r.nextAttemptAt,Date.now()));await this.flushDurableStaging();}await this.processUntilIdle(),this.durableClient&&(await this.durableClient.shutdown().catch(()=>{}),this.durableClient=null);}async getDurableCountForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?0:this.durableClient.count()}async getStatusSummaryForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:this.durableClient.getStatusSummary()}async listDeadLettersForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:(await this.durableClient.listDeadLetters({limit:1e3,offset:0})).items}async initializeDurableQueue(){try{let t=new we(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 Y(10);}}takeNextMemoryBatch(){let t=Date.now(),r=this.memoryQueue.findIndex(a=>a.nextAttemptAt<=t);if(r===-1)return [];let o=this.memoryQueue[r],n=[o];this.memoryQueue.splice(r,1);for(let a=this.memoryQueue.length-1;a>=0;a-=1){let i=this.memoryQueue[a];i.dispatchKey===o.dispatchKey&&i.connectorTarget===o.connectorTarget&&i.nextAttemptAt<=t&&n.length<this.config.memoryBatchSize&&(n.push(i),this.memoryQueue.splice(a,1));}return n}async dispatchMemoryBatch(t){let r=t[0].dispatcher,o=Date.now(),n=await r.dispatch(t.map(a=>a.record),{source:"server",target:t[0].connectorTarget}).catch(a=>({ok:false,retryable:true,error:a instanceof Error?a.message:String(a)}));if(n.ok){await this.recordSuccessfulDispatch(t,o);return}await this.handleRetryableFailure(t,n,false,o);}async handleRetryableFailure(t,r,o,n){o||await this.durableInitPromise?.catch(()=>{});let a=[],i=[];await this.recordFailedDispatch(t,r,n);for(let s of t){let l=s.attemptCount+1;if(!r.retryable||l>=s.maxAttempts){i.push({id:s.id,connectorType:s.connectorType,connectorTarget:s.connectorTarget,operation:"send",payloadJson:ir({jobId:s.id,connectorType:s.connectorType,connectorTarget:s.connectorTarget,source:s.source,record:s.record,createdAt:s.createdAt}),attemptCount:l,maxAttempts:s.maxAttempts,lastError:r.error,firstEnqueuedAt:s.createdAt,deadLetteredAt:n,lastAttemptAt:n}),this.warnOnce(`connector-drop:${s.connectorType}:${s.connectorTarget??"default"}:${s.id}`,o&&this.durableReady?`[Blyp] Warning: Dead-lettered ${s.connectorType} connector job after ${l} failed attempt(s). ${r.error??"Connector delivery failed."}`:`[Blyp] Warning: Dropped ${s.connectorType} connector job after ${l} failed attempt(s). ${r.error??"Connector delivery failed."}`);continue}let u=n+er(l,this.config.retry);if(o){a.push({id:s.id,attemptCount:l,nextAttemptAt:u,lastError:r.error});continue}if(this.durableReady&&this.config.durableSpillStrategy==="after-first-failure"){this.stageDurableJob(s,l,u,r.error);continue}this.memoryQueue.push({...s,attemptCount:l,nextAttemptAt:u});}i.length>0&&await this.durableClient?.deadLetter(i).catch(s=>{this.warnOnce("connector-dead-letter-failure","[Blyp] Warning: Failed to persist dead-lettered connector queue jobs.",s);}),a.length>0&&await this.durableClient?.reschedule(a,n).catch(s=>{this.warnOnce("connector-reschedule-failure","[Blyp] Warning: Failed to reschedule durable connector queue jobs.",s);});}async recordSuccessfulDispatch(t,r){if(!this.durableReady||!this.durableClient||t.length===0)return;let o=ar(t).map(n=>({connectorType:n.connectorType,connectorTarget:n.connectorTarget,timestamp:r}));await this.durableClient.markSuccess(o).catch(n=>{this.warnOnce("connector-status-success-failure","[Blyp] Warning: Failed to record connector delivery success state.",n);});}async recordFailedDispatch(t,r,o){if(!this.durableReady||!this.durableClient||t.length===0)return;let n=ar(t).map(a=>({connectorType:a.connectorType,connectorTarget:a.connectorTarget,timestamp:o,lastError:r.error}));await this.durableClient.markFailure(n).catch(a=>{this.warnOnce("connector-status-failure-failure","[Blyp] Warning: Failed to record connector delivery failure state.",a);});}stageDurableJob(t,r,o,n){let a=ir({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:a,attemptCount:r,maxAttempts:t.maxAttempts,nextAttemptAt:o,state:"pending",lastError:n,createdAt:t.createdAt,updatedAt:Date.now()}),this.flushDurableStaging();}async flushDurableStaging(){if(!(!this.durableReady||!this.durableClient||this.durableStaging.length===0)){if(this.durableFlushPromise){await this.durableFlushPromise;return}this.durableFlushPromise=(async()=>{for(;this.durableStaging.length>0;){let t=this.durableStaging.splice(0,this.config.sqliteWriteBatchSize);try{await this.durableClient.insert(t);}catch(r){this.warnOnce("connector-durable-insert-failure","[Blyp] Warning: Failed to persist connector jobs into the durable SQLite queue.",r),this.durableStaging.unshift(...t);break}}})();try{await this.durableFlushPromise;}finally{this.durableFlushPromise=null;}}}async processDurableQueueOnce(){if(!(!this.durableReady||!this.durableClient||this.durablePollRunning)){this.durablePollRunning=true;try{for(;!this.closed;){let t=await this.durableClient.claimDue(this.config.sqliteReadBatchSize,Date.now());if(t.length===0)break;let r=new Map,o=[];for(let n of t){let a=zo(n.payloadJson);if(!a){o.push(n.id);continue}let i=n.connectorType==="otlp"?`otlp:${n.connectorTarget??""}`:n.connectorType,s=this.dispatchers.get(i);if(!s){o.push(n.id);continue}let l={id:n.id,connectorType:n.connectorType,connectorTarget:n.connectorTarget,source:a.source,record:a.record,attemptCount:n.attemptCount,maxAttempts:n.maxAttempts,nextAttemptAt:n.nextAttemptAt,createdAt:n.createdAt,dispatchKey:i,dispatcher:s},u=r.get(i)??[];u.push(l),r.set(i,u);}o.length>0&&await this.durableClient.ack(o);for(let n of r.values()){let i=await n[0].dispatcher.dispatch(n.map(s=>s.record),{source:"server",target:n[0].connectorTarget}).catch(s=>({ok:!1,retryable:!0,error:s instanceof Error?s.message:String(s)}));if(i.ok){await this.recordSuccessfulDispatch(n,Date.now()),await this.durableClient.ack(n.map(s=>s.id));continue}await this.handleRetryableFailure(n,i,!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 Y(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await Y(10);}}finally{this.closed||this.scheduleDurablePoll();}}}scheduleDurablePoll(){this.closed||!this.durableReady||this.pollTimer||(this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.flushDurableStaging(),await this.processDurableQueueOnce(),this.scheduleDurablePoll();},this.config.pollIntervalMs));}enforceMemoryCapacity(){for(;this.memoryQueue.length>this.config.memoryBufferSize;){let t=this.config.overflowStrategy==="drop-new"?this.memoryQueue.length-1:0,[r]=this.memoryQueue.splice(t,1);if(!r)break;if(this.durableReady){this.stageDurableJob(r,r.attemptCount,Math.max(Date.now(),r.nextAttemptAt),"spilled from in-memory buffer");continue}this.warnOnce(`connector-overflow:${r.connectorType}:${r.connectorTarget??"default"}:${t}`,`[Blyp] Warning: Connector queue overflow reached ${this.config.memoryBufferSize}. Dropping queued ${r.connectorType} job.`);}}hasReadyMemoryJobs(){let t=Date.now();return this.memoryQueue.some(r=>r.nextAttemptAt<=t)}async processUntilIdle(){for(;this.activeDispatches>0||this.memoryQueue.length>0||this.durableStaging.length>0||this.flushPromise!==null||this.durableFlushPromise!==null;){if(this.scheduleDispatch(),await this.flushPromise?.catch(()=>{}),await this.flushDurableStaging(),this.memoryQueue.some(t=>t.nextAttemptAt>Date.now())||await this.processDurableQueueOnce(),this.activeDispatches===0&&this.memoryQueue.length>0&&!this.hasReadyMemoryJobs()){let t=Math.min(...this.memoryQueue.map(r=>r.nextAttemptAt));await Y(Math.max(t-Date.now(),0));}else await Y(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var M=class M{constructor(){d(this,"_type",null);}static getInstance(){return M.instance||(M.instance=new M),M.instance}get type(){return this._type===null&&(this._type=this.detectRuntime()),this._type}get isBun(){return this.type==="bun"}get isNode(){return this.type==="node"}detectRuntime(){return typeof Bun<"u"&&typeof Bun.file=="function"?"bun":"node"}};d(M,"instance");var et=M,tt=class{constructor(){d(this,"type","bun");d(this,"isBun",true);d(this,"isNode",false);d(this,"file",{existsSync:t=>{try{let r=Bun.file(t);return r.size>0||r.name!==""}catch{return false}},mkdirSync:(t,r)=>{try{S.mkdirSync(t,r);}catch{}},writeFileSync:(t,r)=>{Bun.write(t,r);}});d(this,"path",{join:(...t)=>U.join(...t)});d(this,"env",{get:t=>Bun.env[t]});d(this,"cwd",()=>process.cwd());}},rt=class{constructor(){d(this,"type","node");d(this,"isBun",false);d(this,"isNode",true);d(this,"file",{existsSync:t=>S.existsSync(t),mkdirSync:(t,r)=>{S.mkdirSync(t,r);},writeFileSync:(t,r)=>{S.writeFileSync(t,r);}});d(this,"path",{join:(...t)=>U.join(...t)});d(this,"env",{get:t=>process.env[t]});d(this,"cwd",()=>process.cwd());}};function qo(){return et.getInstance().isBun?new tt:new rt}var cr=qo();function ur(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let r=[e,...t];return r.length===1?r[0]:r}function lr(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function jo(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let r=e;return {message:e.message,code:r.code,type:r.type??e.name??e.constructor?.name,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:lr(r.details),cause:r.cause}}if(typeof e=="object"){let r=e,o=typeof r.statusCode=="number"?r.statusCode:typeof r.status=="number"?r.status:t;return {message:typeof r.message=="string"?r.message:`HTTP ${o??500}`,code:typeof r.code=="string"||typeof r.code=="number"?r.code:o,type:typeof r.type=="string"?r.type:typeof r.name=="string"?r.name:"Error",stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:lr(r.details),cause:r.cause}}return {message:String(e),code:t,type:typeof e}}function Uo(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 dr(e,t){let r=t.redact??x(),o=performance.now(),n=C(t.initialFields??{},r),a=[],i;t.onCreate?.();let s=(u,c,p)=>(a.push({level:u,message:N(c,r),timestamp:new Date().toISOString(),...ur(c,p)===void 0?{}:{data:C(ur(c,p),r)}}),l),l={set(u){return Object.assign(n,C(u,r)),l},debug(u,...c){return s("debug",u,c)},info(u,...c){return s("info",u,c)},warn(u,...c){return s("warn",u,c)},warning(u,...c){return s("warning",u,c)},error(u,...c){return s("error",u,c)},success(u,...c){return s("success",u,c)},critical(u,...c){return s("critical",u,c)},table(u,c){return s("table",u,c===void 0?[]:[c])},emit(u={}){if(i)return i;let c=C(t.resolveDefaultFields?.()??{},r),p=Uo(u),m=C(jo(u.error,p),r),w=u.level??(m?"error":"info"),L=C({...c,...n,groupId:e,timestamp:new Date().toISOString(),level:w,duration:Math.round(performance.now()-o),...typeof p=="number"?{status:p}:{},...a.length>0?{events:[...a]}:{},...m?{error:m}:{}},r);return t.write(L,N(u.message??"structured_log",r)),i=L,t.onEmit?.(L),L}};return l}var it=Symbol("blyp.logger.factory"),pr={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},fr={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},$o="\x1B[35m",Ho="\x1B[0m";function Z(e){return be(e)==="client_log"}function Wo(){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 Qo(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Jo(){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 Go(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function Ko(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function Xo(){return {get:e=>Ko(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function Vo(e){return e.connectors?.betterstack?.enabled?$("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):Wo()}function Yo(e){return e.connectors?.databuddy?.enabled?$("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):Qo()}function Zo(e){return e.connectors?.posthog?.enabled?$("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):Jo()}function ei(e){return e.connectors?.sentry?.enabled?$("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):Go()}function ti(e){return e.connectors?.otlp?.some(t=>t.enabled)?$("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):Xo()}function ri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};t.data!==void 0&&(r.data=t.data);let o=typeof t.page?.pathname=="string"?t.page.pathname:void 0,n=typeof t.page?.url=="string"?t.page.url:void 0;return (o||n)&&(r.page=o??n),t.metadata!==void 0&&(r.metadata=t.metadata),Object.keys(r).length>0?r:null}function ni(e){if(!e||typeof e!="object"||Array.isArray(e))return {hidden:false,value:e};let t=e;if(t.type==="http_request"||t.type==="http_error")return {hidden:true};if(t.type==="client_log"){let r=ri(e);return r?{hidden:false,value:r}:{hidden:true}}return {hidden:false,value:e}}function oi(e){if(e.pretty){let r=zt()({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:(o,n)=>{let a=String(o[n]??""),i=typeof o.caller=="string"?o.caller.trim():"";return i?`${a} ${$o}${i}${Ho}`:a}});return gr({level:e.level,customLevels:pr},r)}return gr({level:e.level,customLevels:pr})}function k(e){let t=e[it];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function at(e){return k(e).posthog}function st(e){return k(e).betterstack}function ct(e){return k(e).databuddy}function Lr(e){try{return at(e)}catch{return null}}function wr(e){try{return st(e)}catch{return null}}function Rr(e){try{return ct(e)}catch{return null}}function Sr(e){return k(e).sentry}function vr(e){return k(e).otlp}function ve(e){try{return k(e).redact}catch{return X().redact}}function xr(e,t){let r=k(t);return Object.defineProperty(e,it,{value:r,enumerable:false,configurable:false,writable:false}),e}function Tr(e,t){let r=k(e);return r.create(t,r.bindings)}function ut(e,t,r={}){let o=k(e);return dr(t,{initialFields:r.initialFields,resolveDefaultFields:()=>({...o.bindings,...r.resolveDefaultFields?.()??{}}),write:(n,a)=>{o.writeStructured(n,a,"structured-flush");},onCreate:r.onCreate,onEmit:r.onEmit,redact:r.redact??o.redact})}function mr(e,t){if(!Z(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function yr(e,t){if(!Z(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function hr(e,t){if(!Z(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function br(e,t){if(!Z(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Cr(e,t){if(!Z(t))for(let r of e.getAutoForwardTargets())r.send(t,{source:"server",warnIfUnavailable:true});}function ot(e,t,r,o,n,a,i,s,l,u={},c="root"){let p=Object.keys(u).length>0?e.child(u):e,m=(f,g,y,R=c)=>{if(R==="root"&&oe())return;let h=Ht(f,g,y,u,l),W=h.message,Q={caller:h.caller},re=ni(h.data);!re.hidden&&re.value!==void 0&&(Q.data=re.value);let Lt=fr[f],Ee=p;(Ee[Lt]??Ee.info??((fi,mi)=>{})).call(p,Q,W),t.write(h),yr(o,h),hr(n,h),mr(a,h),br(i,h),Cr(s,h);},w=(f,g,y="structured-flush")=>{let R=Qt(f.level),h=Wt(R,g,f,u,l),W=fr[R],Q=p;(Q[W]??Q.info??((Lt,Ee)=>{})).call(p,{caller:h.caller,...h},h.message),(y!=="root"||!oe())&&t.write(h),yr(o,h),hr(n,h),mr(a,h),br(i,h),Cr(s,h);},L={success:(f,...g)=>{m("success",f,g);},critical:(f,...g)=>{m("critical",f,g);},warning:(f,...g)=>{m("warning",f,g);},info:(f,...g)=>{m("info",f,g);},debug:(f,...g)=>{m("debug",f,g);},error:(f,...g)=>{m("error",f,g);},warn:(f,...g)=>{m("warn",f,g);},table:(f,g)=>{g&&typeof g=="object"&&cr.env.get("NODE_ENV")!=="production"&&(console.log("TABLE:",f),console.table(C(g,l))),m("table",f,g===void 0?[]:[g]);},flush:async()=>{await t.flush(),r&&await r.flush(),await Promise.allSettled([o.flush(),n.flush(),a.flush(),i.flush(),s.flush()]);},shutdown:async()=>{await t.shutdown(),r&&await r.shutdown(),await Promise.allSettled([o.flush(),n.flush(),a.flush(),i.flush(),s.flush()]);},createStructuredLog:(f,g)=>ut(L,f,{initialFields:g}),child:f=>{let g={...u,...f};return ot(e,t,r,o,n,a,i,s,l,g,c)},[it]:{bindings:u,betterstack:o,databuddy:n,posthog:a,sentry:i,otlp:s,redact:l,sink:t,create:(f,g=u)=>ot(e,t,r,o,n,a,i,s,l,g,f),writeStructured:(f,g,y="structured-flush")=>{w(f,g,y);}}};return L}var nt=null;function lt(e){if(e===void 0&&nt)return nt;let t=X(e),r=oi(t),o=Zt(t),n=Vo(t),a=Yo(t),i=Zo(t),s=ei(t),l=ti(t),u=t.connectors.delivery.enabled?new Re(t.connectors.delivery):null;if(u){u.bindTarget(n),u.bindTarget(a),u.bindTarget(i),u.bindTarget(s);for(let p of l.getAutoForwardTargets())u.bindTarget(p);}let c=ot(r,o,u,n,a,i,s,l,t.redact);return e===void 0&&(nt=c),c}lt();function kr(e,t,r,o){let n=ie(e),a=ae(t),i=se(o);return `${n} ${r} ${a} ${i}`}function ii(e,t){let r=qe(t?.path??O),o=t?.enabled===false?null:{path:r};return e===false?null:e===void 0?o:e===true?{path:r}:{...o,...e,path:qe(e.path??r)}}function dt(e={},t){let r=X({...e.level!==void 0?{level:e.level}:{},...e.pretty!==void 0?{pretty:e.pretty}:{},...e.destination!==void 0?{destination:e.destination}:{},...e.logDir!==void 0?{logDir:e.logDir}:{},...e.file!==void 0?{file:e.file}:{},...e.database!==void 0?{database:e.database}:{},...e.redact!==void 0?{redact:e.redact}:{},...e.connectors!==void 0?{connectors:e.connectors}:{}}),{level:o=r.level,pretty:n=r.pretty,destination:a=r.destination,logDir:i=r.logDir,file:s=r.file,database:l=r.database,autoLogging:u=true,customProps:c,logErrors:p=true,includePaths:m,ignorePaths:w,clientLogging:L,connectors:f}=e,g=t??lt({level:o,pretty:n,destination:a,logDir:i,file:s,database:l,connectors:f}),y=ii(L,r.clientLogging),R=y?.path??O,h=m,W=y?Array.from(new Set([...w??[],R])):w;return {logger:g,betterstack:st(g),databuddy:ct(g),posthog:at(g),sentry:Sr(g),otlp:vr(g),resolvedConfig:r,level:o,pretty:n,logDir:i,file:s,autoLogging:u,customProps:c,logErrors:p,resolvedIncludePaths:h,resolvedIgnorePaths:W,resolvedClientLogging:y,ingestionPath:R}}function ai(e,t){return !t||t.length===0?true:He(e,t)}function Er(e,t,r){return ai(e,t)?He(e,r):true}function Dr(e,t,r){return e.autoLogging===false||typeof e.autoLogging=="object"&&e.autoLogging.ignore?.(t)?true:Er(r,e.resolvedIncludePaths,e.resolvedIgnorePaths)}function gt(e,t){return e.logErrors?Er(t,e.resolvedIncludePaths,e.resolvedIgnorePaths):true}function ee(e,t){return e.customProps?e.customProps(t):{}}function _r(e,t,r,o,n,a,i={}){let s=ge(r,"http_request",o,n,a,i,ve(e));return t==="info"?e.info(pe(r.method,n,o,a),s):(e.info(kr(r.method,n,o,a),s),Object.keys(i).length>0&&e.debug("Request context",i)),s}function pt(e,t,r,o,n,a,i,s={},l={}){let u=ge(r,"http_error",o,n,a,{error:i?.message??`HTTP ${n}`,stack:i?.stack,code:i?.code,why:i?.why,fix:i?.fix,link:i?.link,details:i?.details,...s},ve(e)),c=t==="info"?pe(r.method,n,o,a):kr(r.method,n,o,a);e.error(c,u);let p=Lr(e);p?.shouldAutoCaptureExceptions()&&p.captureException(l.error??i??c,{source:"server",warnIfUnavailable:true,distinctId:l.distinctId??b(r.headers,"x-posthog-distinct-id"),properties:Xe({timestamp:new Date().toISOString(),level:"error",message:c,data:u},"server",{$request_method:r.method,$request_path:o,$current_url:r.url,$response_status_code:n,...b(r.headers,"user-agent")?{$user_agent:b(r.headers,"user-agent")}:{},...u.ip?{$ip:u.ip}:{}})});let m=wr(e);m?.shouldAutoCaptureExceptions()&&m.captureException(l.error??i??c,{source:"server",warnIfUnavailable:true,context:{timestamp:new Date().toISOString(),level:"error",message:c,status:n,path:o,data:u}});let w=Rr(e);return w?.shouldAutoCaptureExceptions()&&w.captureException(l.error??i??c,{source:"server",warnIfUnavailable:true,properties:{method:r.method,path:o,status_code:n,...r.url?{current_url:r.url}:{},...b(r.headers,"user-agent")?{user_agent:b(r.headers,"user-agent")}:{},...u.ip?{ip:u.ip}:{},payload:u}}),u}async function si(e,t){if(t!==void 0)return typeof t=="string"?JSON.parse(t):t;if(typeof e.json=="function")return await e.json();throw new Error("Unable to parse client log payload")}function ci(e,t){switch(t){case "debug":return e.debug;case "info":return e.info;case "warning":return e.warning;case "error":return e.error;case "critical":return e.critical;case "success":return e.success}}async function Pr(e){let{config:t,ctx:r,request:o,body:n,deliveryPath:a}=e;if(!t.resolvedClientLogging)return {status:404};let i;try{i=await si(o,n);}catch{return {status:400}}if(!Tt(i))return {status:400};if(!(t.resolvedClientLogging.validate?await t.resolvedClientLogging.validate(r,i):true))return {status:403};let l=t.resolvedClientLogging.enrich?await t.resolvedClientLogging.enrich(r,i):void 0,u=ve(t.logger),c=C(i,u),p=C({...c,receivedAt:new Date().toISOString(),delivery:Ie(o,a??de(o.url),u)},u);l!==void 0&&(p.serverContext=C(l,u));let m=N(`[client] ${c.message}`,u),w=E(),L=typeof c.traceId=="string"&&c.traceId.length>0?c.traceId:w;try{L&&J(L),c.level==="table"?t.logger.table(m,p):ci(t.logger,c.level)(m,p);}finally{J(w);}let f={};if(c.connector==="betterstack"){if(f["x-blyp-betterstack-status"]=t.betterstack.ready?"enabled":"missing",t.betterstack.ready){let g={timestamp:p.receivedAt,level:c.level,message:m,data:p};if(t.betterstack.send(g,{source:"client"}),(c.level==="error"||c.level==="critical")&&t.betterstack.shouldAutoCaptureExceptions()){let y=c.data&&typeof c.data=="object"&&!Array.isArray(c.data)&&typeof c.data.message=="string"?c.data:c.message;t.betterstack.captureException(y,{source:"client",warnIfUnavailable:true,context:{sessionId:c.session.sessionId,pageUrl:c.page.url,pagePath:c.page.pathname,metadata:c.metadata,payload:p}});}}}else if(c.connector==="databuddy"){if(f["x-blyp-databuddy-status"]=t.databuddy.ready?"enabled":"missing",t.databuddy.ready){let g={timestamp:p.receivedAt,level:c.level,message:m,data:p};if(t.databuddy.send(g,{source:"client"}),(c.level==="error"||c.level==="critical")&&t.databuddy.shouldAutoCaptureExceptions()){let y=c.data&&typeof c.data=="object"&&!Array.isArray(c.data)&&typeof c.data.message=="string"?c.data:c.message;t.databuddy.captureException(y,{source:"client",warnIfUnavailable:true,sessionId:c.session.sessionId,properties:{page_url:c.page.url,page_path:c.page.pathname,client_runtime:c.device?.runtime,metadata:c.metadata,payload:p}});}}}else if(c.connector==="posthog"){if(f["x-blyp-posthog-status"]=t.posthog.ready?"enabled":"missing",t.posthog.ready){let g={timestamp:p.receivedAt,level:c.level,message:m,data:p};if(t.posthog.send(g,{source:"client"}),(c.level==="error"||c.level==="critical")&&t.posthog.shouldAutoCaptureExceptions()){let y=p.metadata,R=y&&typeof y=="object"&&!Array.isArray(y)&&typeof y.posthogDistinctId=="string"&&y.posthogDistinctId?String(y.posthogDistinctId):void 0,h=c.data&&typeof c.data=="object"&&!Array.isArray(c.data)&&typeof c.data.message=="string"?c.data:c.message;t.posthog.captureException(h,{source:"client",warnIfUnavailable:true,distinctId:R,properties:Xe(g,"client",{$session_id:c.session.sessionId,$current_url:c.page.url,$request_path:c.page.pathname,"client.runtime":c.device?.runtime,"client.metadata":c.metadata})});}}}else if(c.connector==="sentry")f["x-blyp-sentry-status"]=t.sentry.ready?"enabled":"missing",t.sentry.ready&&t.sentry.send({timestamp:p.receivedAt,level:c.level,message:m,data:p},{source:"client"});else if(c.connector?.type==="otlp"){let g=t.otlp.get(c.connector.name);f["x-blyp-otlp-status"]=g.ready?"enabled":"missing",g.ready&&g.send({timestamp:p.receivedAt,level:c.level,message:m,data:p},{source:"client"});}return Object.keys(f).length>0?{status:204,headers:f}:{status:204}}async function Ar(e){let t=[];for await(let r of e)t.push(Buffer.isBuffer(r)?r:Buffer.from(r));return Buffer.concat(t).toString("utf8")}function Br(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return e;let r=b(t,"x-forwarded-proto")??"http",o=b(t,"host")??"localhost";return `${r}://${o}${e.startsWith("/")?e:`/${e}`}`}function ui(e){return e.resolvedConfig.destination==="database"}async function xe(e){if(ui(e))try{await e.logger.flush();}catch(t){console.warn("[Blyp] Warning: Failed to flush database logs.",t);}}function ft(e,t={}){let r=Tr(e,"request-scoped"),o=xr({...r,createStructuredLog:(n,a)=>ut(o,n,{initialFields:a,resolveDefaultFields:()=>{let i=E();return {...t.resolveStructuredFields?.()??{},...i?{traceId:i}:{}}},onCreate:()=>{_e();},onEmit:()=>{Pe(),t.onStructuredEmit?.();}}),child(n){return ft(r.child(n),t)}},r);return De(o),o}var li="trace_";function mt(){return `${li}${me().replace(/[^a-z0-9]/gi,"").toLowerCase().slice(0,12)}`}function yt(e){J(e);}var Nr=Symbol.for("blyp.nitro.state");function te(e){return e.context[Nr]}function Ir(e,t){return e.context[Nr]=t,t}function ht(e){return e.method??e.node?.req?.method??e.request?.method??"GET"}function Or(e){return e.headers??e.node?.req?.headers??e.request?.headers}function di(e){if(e.request?.url)return e.request.url;let t=e.url??e.path??e.node?.req?.url??"/";return Br(t,Or(e))}function bt(e){if(typeof e.path=="string"&&e.path.length>0)return e.path;if(e.request?.url)return new URL(e.request.url).pathname;let t=e.url??e.node?.req?.url??"/";if(t.startsWith("http://")||t.startsWith("https://"))return new URL(t).pathname;let r=t.indexOf("?");return r>=0?t.slice(0,r):t}function Te(e){return Ne(ht(e),di(e),Or(e))}function Ct(e,t,r=200){return t instanceof Response||typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:typeof e.node?.res?.statusCode=="number"&&e.node.res.statusCode>0?e.node.res.statusCode:r}async function Mr(e){if(e.body!==void 0)return e.body;if(e.request){if((e.request.headers.get("content-type")??"").includes("application/json")){let r=e.request.clone();try{return await e.request.json()}catch{return await r.text()}}return await e.request.text()}if(e.node?.req)return await Ar(e.node.req);throw new Error("Unable to parse Nitro request body")}function ke(e,t,r){return {event:e,response:t,error:r}}function Fr(e){let t=n=>n.context.blypLog??e.logger,r=async(n,a)=>{let i=te(n);if(!i||i.structuredLogEmitted||i.errorLogged)return;let s=Te(n),l=Ct(n,a),u=Math.round(performance.now()-i.startTime),c=ke(n,a);Oe(l)?gt(e,i.path)||pt(e.logger,e.level,s,i.path,l,u,fe(void 0,l),ee(e,c)):Dr(e,c,i.path)||_r(e.logger,e.level,s,i.path,l,u,ee(e,c));},o=async(n,a,i)=>{let s=te(n);!s||s.structuredLogEmitted||s.errorLogged||gt(e,s.path)||(s.errorLogged=true,pt(e.logger,e.level,Te(n),s.path,Ct(n,i,500),Math.round(performance.now()-s.startTime),fe(a,500),ee(e,ke(n,i,a)),{error:a}));};return {logger:e.logger,getLogger:t,plugin:async n=>{await n.hooks.hook("request",async a=>{let i=a;ne();let s=mt();yt(s),typeof i.node?.res=="object"&&i.node.res&&"setHeader"in i.node.res&&i.node.res.setHeader?.("x-blyp-trace-id",s);let l=bt(i),u=Ir(i,{startTime:performance.now(),path:l,structuredLogEmitted:false});i.context.blypTraceId=s;let c=ft(e.logger,{resolveStructuredFields:()=>({method:ht(i),path:l,...ee(e,ke(i))}),onStructuredEmit:()=>{let p=te(i);p&&(p.structuredLogEmitted=true);}});i.context.blypLog=c,u.scopedLogger=c;}),await n.hooks.hook("beforeResponse",async(a,i)=>{await r(a,i);}),await n.hooks.hook("afterResponse",async a=>{await xe(e);let i=te(a);i&&(i.errorLogged=true);}),await n.hooks.hook("error",async(a,i)=>{i&&typeof i=="object"&&(await o(i,a),await xe(e));});},clientLogHandler:async n=>{ne();let a=mt();yt(a),n.context.blypTraceId=a;let i=bt(n);if(i!==e.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${i} does not match configured client logging path ${e.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":a}});let s=await Mr(n),l=await Pr({config:e,ctx:ke(n),request:{...Te(n),json:async()=>s},body:s,deliveryPath:i});return await xe(e),new Response(null,{status:l.status,headers:{...l.headers,"x-blyp-trace-id":a}})}}}function zr(e={}){let t=Fr(dt(e));return {logger:t.logger,serverPlugin:t.plugin,clientLogHandler:t.clientLogHandler,getLogger:r=>t.getLogger(r)}}var gi=zr;
701
+ export{gi as createLogger,zr as createNuxtLogger};