@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.
- package/README.md +273 -14
- package/STABILITY.md +56 -0
- package/dist/ai/anthropic/index.d.ts +3 -0
- package/dist/ai/anthropic/normalize.d.ts +9 -0
- package/dist/ai/anthropic/stream.d.ts +3 -0
- package/dist/ai/anthropic/wrap.d.ts +13 -0
- package/dist/ai/anthropic.js +701 -0
- package/dist/ai/anthropic.mjs +701 -0
- package/dist/ai/fetch.js +701 -0
- package/dist/ai/fetch.mjs +701 -0
- package/dist/ai/openai/index.d.ts +3 -0
- package/dist/ai/openai/normalize.d.ts +10 -0
- package/dist/ai/openai/stream.d.ts +3 -0
- package/dist/ai/openai/wrap.d.ts +24 -0
- package/dist/ai/openai.js +701 -0
- package/dist/ai/openai.mjs +701 -0
- package/dist/ai/shared/fetch.d.ts +5 -0
- package/dist/ai/shared/index.d.ts +2 -0
- package/dist/ai/shared/normalize.d.ts +17 -0
- package/dist/ai/shared/redaction.d.ts +6 -0
- package/dist/ai/shared/stream.d.ts +7 -0
- package/dist/ai/shared/trace.d.ts +116 -0
- package/dist/ai/shared/types.d.ts +161 -0
- package/dist/ai/shared.js +701 -0
- package/dist/ai/shared.mjs +701 -0
- package/dist/ai/vercel/index.d.ts +3 -0
- package/dist/ai/vercel/middleware.d.ts +3 -0
- package/dist/ai/vercel/model.d.ts +3 -0
- package/dist/ai/vercel.js +701 -0
- package/dist/ai/vercel.mjs +701 -0
- package/dist/astro.js +701 -0
- package/dist/astro.mjs +701 -0
- package/dist/client.js +1 -1132
- package/dist/client.mjs +1 -1125
- package/dist/connectors/betterstack.js +9 -1508
- package/dist/connectors/betterstack.mjs +9 -1483
- package/dist/connectors/databuddy/index.d.ts +7 -0
- package/dist/connectors/databuddy/sender.d.ts +5 -0
- package/dist/connectors/databuddy.js +9 -0
- package/dist/connectors/databuddy.mjs +9 -0
- package/dist/connectors/delivery/backoff.d.ts +2 -0
- package/dist/connectors/delivery/manager.d.ts +44 -0
- package/dist/connectors/delivery/queue-path.d.ts +1 -0
- package/dist/connectors/delivery/sqlite-adapter-bun.d.ts +1 -0
- package/dist/connectors/delivery/sqlite-adapter-node.d.ts +1 -0
- package/dist/connectors/delivery/sqlite-client.d.ts +37 -0
- package/dist/connectors/delivery/sqlite-worker.d.ts +1 -0
- package/dist/connectors/delivery/studio-queue.d.ts +12 -0
- package/dist/connectors/delivery/types.d.ts +98 -0
- package/dist/connectors/otlp/index.d.ts +1 -0
- package/dist/connectors/otlp.js +9 -1347
- package/dist/connectors/otlp.mjs +9 -1344
- package/dist/connectors/posthog/properties.d.ts +4 -0
- package/dist/connectors/posthog/sender.d.ts +0 -1
- package/dist/connectors/posthog.js +10 -1503
- package/dist/connectors/posthog.mjs +10 -1498
- package/dist/connectors/sentry.js +9 -1356
- package/dist/connectors/sentry.mjs +9 -1333
- package/dist/core/config.d.ts +7 -2
- package/dist/core/log-record.d.ts +5 -4
- package/dist/core/logger.d.ts +5 -0
- package/dist/core/optional-module.d.ts +1 -0
- package/dist/core/pino-pretty-loader.d.ts +4 -0
- package/dist/database.js +1 -24
- package/dist/database.mjs +1 -21
- package/dist/elysia.js +621 -4100
- package/dist/elysia.mjs +622 -4073
- package/dist/expo.js +1 -719
- package/dist/expo.mjs +1 -717
- package/dist/express.js +616 -4085
- package/dist/express.mjs +616 -4056
- package/dist/fastify.js +618 -4104
- package/dist/fastify.mjs +618 -4075
- package/dist/frameworks/astro/index.d.ts +2 -0
- package/dist/frameworks/astro/logger.d.ts +3 -0
- package/dist/frameworks/elysia/index.d.ts +1 -1
- package/dist/frameworks/elysia/logger.d.ts +2 -35
- package/dist/frameworks/nestjs/helpers.d.ts +2 -0
- package/dist/frameworks/nitro/index.d.ts +2 -0
- package/dist/frameworks/nitro/logger.d.ts +6 -0
- package/dist/frameworks/nuxt/index.d.ts +2 -0
- package/dist/frameworks/nuxt/logger.d.ts +3 -0
- package/dist/frameworks/react-router/index.d.ts +2 -0
- package/dist/frameworks/react-router/logger.d.ts +3 -0
- package/dist/frameworks/shared/h3.d.ts +19 -0
- package/dist/frameworks/shared/http.d.ts +3 -2
- package/dist/frameworks/shared/index.d.ts +2 -1
- package/dist/frameworks/shared/logger.d.ts +2 -0
- package/dist/frameworks/shared/request-context.d.ts +2 -0
- package/dist/frameworks/shared/trace.d.ts +6 -0
- package/dist/hono.js +624 -4079
- package/dist/hono.mjs +626 -4053
- package/dist/index.d.ts +57 -17
- package/dist/index.js +616 -6494
- package/dist/index.mjs +619 -6410
- package/dist/nestjs.js +626 -4574
- package/dist/nestjs.mjs +622 -4542
- package/dist/nextjs.js +625 -4107
- package/dist/nextjs.mjs +627 -4081
- package/dist/nitro.js +701 -0
- package/dist/nitro.mjs +701 -0
- package/dist/nuxt.js +701 -0
- package/dist/nuxt.mjs +701 -0
- package/dist/react-router.js +701 -0
- package/dist/react-router.mjs +701 -0
- package/dist/shared/redaction.d.ts +17 -0
- package/dist/standalone.js +606 -3258
- package/dist/standalone.mjs +611 -3234
- package/dist/sveltekit.js +625 -4106
- package/dist/sveltekit.mjs +626 -4079
- package/dist/tanstack-start.js +624 -4105
- package/dist/tanstack-start.mjs +626 -4079
- package/dist/types/connectors/databuddy.d.ts +52 -0
- package/dist/types/core/config.d.ts +89 -0
- package/dist/types/core/logger.d.ts +5 -0
- package/dist/types/core/structured-log.d.ts +2 -0
- package/dist/types/database.d.ts +1 -0
- package/dist/types/frameworks/astro.d.ts +33 -0
- package/dist/types/frameworks/client.d.ts +2 -0
- package/dist/types/frameworks/elysia.d.ts +2 -0
- package/dist/types/frameworks/express.d.ts +1 -0
- package/dist/types/frameworks/fastify.d.ts +1 -0
- package/dist/types/frameworks/hono.d.ts +1 -0
- package/dist/types/frameworks/http.d.ts +1 -0
- package/dist/types/frameworks/nestjs.d.ts +2 -0
- package/dist/types/frameworks/nextjs.d.ts +1 -0
- package/dist/types/frameworks/nitro.d.ts +63 -0
- package/dist/types/frameworks/nuxt.d.ts +12 -0
- package/dist/types/frameworks/react-router.d.ts +35 -0
- package/dist/types/frameworks/request-context.d.ts +1 -0
- package/dist/types/frameworks/shared.d.ts +28 -1
- package/dist/types/frameworks/standalone.d.ts +3 -2
- package/dist/types/frameworks/sveltekit.d.ts +1 -0
- package/dist/types/frameworks/tanstack-start.d.ts +9 -3
- package/dist/types/frameworks/workers.d.ts +3 -0
- package/dist/types/shared/client-log.d.ts +2 -1
- package/dist/workers.js +2 -626
- package/dist/workers.mjs +2 -623
- package/package.json +273 -143
- package/dist/client.js.map +0 -1
- package/dist/client.mjs.map +0 -1
- package/dist/connectors/betterstack.js.map +0 -1
- package/dist/connectors/betterstack.mjs.map +0 -1
- package/dist/connectors/otlp.js.map +0 -1
- package/dist/connectors/otlp.mjs.map +0 -1
- package/dist/connectors/posthog.js.map +0 -1
- package/dist/connectors/posthog.mjs.map +0 -1
- package/dist/connectors/sentry.js.map +0 -1
- package/dist/connectors/sentry.mjs.map +0 -1
- package/dist/database.js.map +0 -1
- package/dist/database.mjs.map +0 -1
- package/dist/elysia.js.map +0 -1
- package/dist/elysia.mjs.map +0 -1
- package/dist/expo.js.map +0 -1
- package/dist/expo.mjs.map +0 -1
- package/dist/express.js.map +0 -1
- package/dist/express.mjs.map +0 -1
- package/dist/fastify.js.map +0 -1
- package/dist/fastify.mjs.map +0 -1
- package/dist/hono.js.map +0 -1
- package/dist/hono.mjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/nestjs.js.map +0 -1
- package/dist/nestjs.mjs.map +0 -1
- package/dist/nextjs.js.map +0 -1
- package/dist/nextjs.mjs.map +0 -1
- package/dist/standalone.js.map +0 -1
- package/dist/standalone.mjs.map +0 -1
- package/dist/sveltekit.js.map +0 -1
- package/dist/sveltekit.mjs.map +0 -1
- package/dist/tanstack-start.js.map +0 -1
- package/dist/tanstack-start.mjs.map +0 -1
- package/dist/workers.js.map +0 -1
- package/dist/workers.mjs.map +0 -1
- package/exports/client.js +0 -3
- package/exports/client.mjs +0 -3
- package/exports/connectors/betterstack.js +0 -1
- package/exports/connectors/betterstack.mjs +0 -1
- package/exports/connectors/otlp.js +0 -1
- package/exports/connectors/otlp.mjs +0 -1
- package/exports/connectors/posthog.js +0 -1
- package/exports/connectors/posthog.mjs +0 -1
- package/exports/connectors/sentry.js +0 -1
- package/exports/connectors/sentry.mjs +0 -1
- package/exports/database.js +0 -1
- package/exports/database.mjs +0 -1
- package/exports/expo.js +0 -1
- package/exports/expo.mjs +0 -1
- package/exports/frameworks/elysia.js +0 -1
- package/exports/frameworks/elysia.mjs +0 -1
- package/exports/frameworks/express.js +0 -1
- package/exports/frameworks/express.mjs +0 -1
- package/exports/frameworks/fastify.js +0 -1
- package/exports/frameworks/fastify.mjs +0 -1
- package/exports/frameworks/hono.js +0 -1
- package/exports/frameworks/hono.mjs +0 -1
- package/exports/frameworks/nestjs.js +0 -1
- package/exports/frameworks/nestjs.mjs +0 -1
- package/exports/frameworks/nextjs.js +0 -1
- package/exports/frameworks/nextjs.mjs +0 -1
- package/exports/frameworks/standalone.js +0 -1
- package/exports/frameworks/standalone.mjs +0 -1
- package/exports/frameworks/sveltekit.js +0 -1
- package/exports/frameworks/sveltekit.mjs +0 -1
- package/exports/frameworks/tanstack-start.js +0 -1
- package/exports/frameworks/tanstack-start.mjs +0 -1
- package/exports/workers.js +0 -1
- package/exports/workers.mjs +0 -1
- package/types/client.d.ts +0 -34
- package/types/connectors/betterstack.d.ts +0 -1
- package/types/connectors/otlp.d.ts +0 -1
- package/types/connectors/posthog.d.ts +0 -1
- package/types/connectors/sentry.d.ts +0 -1
- package/types/database.d.ts +0 -1
- package/types/expo.d.ts +0 -17
- package/types/frameworks/client.d.ts +0 -160
- package/types/frameworks/elysia.d.ts +0 -1
- package/types/frameworks/expo.d.ts +0 -50
- package/types/frameworks/express.d.ts +0 -1
- package/types/frameworks/fastify.d.ts +0 -1
- package/types/frameworks/hono.d.ts +0 -1
- package/types/frameworks/nestjs.d.ts +0 -1
- package/types/frameworks/nextjs.d.ts +0 -1
- package/types/frameworks/standalone.d.ts +0 -1
- package/types/frameworks/sveltekit.d.ts +0 -1
- package/types/frameworks/tanstack-start.d.ts +0 -1
- package/types/frameworks/workers.d.ts +0 -115
- package/types/index.d.ts +0 -1
- package/types/workers.d.ts +0 -13
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type StructuredLog } from '../../core/structured-log';
|
|
2
|
+
import type { DatabuddyErrorTracker, DatabuddyExceptionCaptureOptions, DatabuddyLogger, DatabuddyLoggerConfig } from '../../types/connectors/databuddy';
|
|
3
|
+
export type { DatabuddyErrorTracker, DatabuddyExceptionCaptureOptions, DatabuddyLogger, DatabuddyLoggerConfig, } from '../../types/connectors/databuddy';
|
|
4
|
+
export declare function createDatabuddyLogger(config?: DatabuddyLoggerConfig): DatabuddyLogger;
|
|
5
|
+
export declare function createStructuredDatabuddyLogger<TFields extends Record<string, unknown> = Record<string, unknown>>(groupId: string, initial?: TFields, config?: DatabuddyLoggerConfig): StructuredLog<TFields>;
|
|
6
|
+
export declare function createDatabuddyErrorTracker(config?: DatabuddyLoggerConfig): DatabuddyErrorTracker;
|
|
7
|
+
export declare function captureDatabuddyException(error: unknown, options?: DatabuddyExceptionCaptureOptions, config?: DatabuddyLoggerConfig): void;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { BlypConfig, DatabuddyConnectorConfig, ResolvedDatabuddyConnectorConfig } from '../../core/config';
|
|
2
|
+
import type { DatabuddySender, DatabuddyTestHooks } from '../../types/connectors/databuddy';
|
|
3
|
+
export declare function createDatabuddySender(config: BlypConfig | ResolvedDatabuddyConnectorConfig | DatabuddyConnectorConfig): DatabuddySender;
|
|
4
|
+
export declare function setDatabuddyTestHooks(hooks: DatabuddyTestHooks): void;
|
|
5
|
+
export declare function resetDatabuddyTestHooks(): void;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
'use strict';var fs=require('fs'),jiti=require('jiti'),Oe=require('path'),_e=require('os'),zod=require('zod'),async_hooks=require('async_hooks'),node=require('@databuddy/sdk/node');require('fflate');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Oe__default=/*#__PURE__*/_interopDefault(Oe);var _e__default=/*#__PURE__*/_interopDefault(_e);function ne(){return Oe__default.default.join(_e__default.default.homedir(),".blyp","queue.db")}function F(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let n=e;return n.cause!==void 0&&(t.cause=h(n.cause)),t}function h(e,t=new WeakSet){if(e instanceof Error)return F(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(n=>h(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let n={};for(let[o,r]of Object.entries(e))n[o]=h(r,t);return t.delete(e),n}return e}function M(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=h(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var Ne=zod.z.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"}),re=zod.z.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),q=zod.z.string().trim().min(1);function $(e){return Ne.safeParse(e).success}function b(e){return re.safeParse(e).success}function f(e){return q.safeParse(e).success}var U="/inngest";zod.z.union([zod.z.literal("betterstack"),zod.z.literal("databuddy"),zod.z.literal("posthog"),zod.z.literal("sentry"),zod.z.undefined(),zod.z.object({type:zod.z.literal("otlp"),name:q})]);function oe(e,t=new Set){return (n,o,r)=>{if(t.has(n)||typeof console>"u")return;let i=console[e];if(typeof i=="function"){if(t.add(n),r===void 0){i.call(console,o);return}i.call(console,o,r);}}}function ie(e){return oe("warn",e)}function ae(e){return oe("error",e)}var Me="[REDACTED]",je=["password","passwd","pwd","secret","token","api_key","apikey","api_secret","authorization","auth","x-api-key","private_key","privatekey","access_token","refresh_token","client_secret","session","cookie","set-cookie","ssn","credit_card","card_number","cvv","cvc","otp","pin"];var qe=[{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}],$e=/\b(?:\d[ -]*?){16}\b/g;function se(e){let t=new Set,n=[];for(let o of e)typeof o!="string"||o.length===0||t.has(o)||(t.add(o),n.push(o));return n}function Ue(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function He(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function We(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Qe(e){return e.split(".").filter(Boolean)}function H(e,t,n=0,o=0){if(n===e.length)return o===t.length;let r=e[n];if(r==="**"){if(n===e.length-1)return true;for(let i=o;i<=t.length;i+=1)if(H(e,t,n+1,i))return true;return false}return o>=t.length||r!=="*"&&r!==t[o]?false:H(e,t,n+1,o+1)}function Ge(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>H(Qe(n),e))}function Ke(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,o=false;for(let r=t.length-1;r>=0;r-=1){let i=Number(t[r]);o&&(i*=2,i>9&&(i-=9)),n+=i,o=!o;}return n%10===0}function ce(e,t,n){if(n||t.disablePatternScanning)return e;let o=e;for(let{type:r,pattern:i}of qe)o=o.replace(i,`[REDACTED:${r}]`);o=o.replace($e,r=>Ke(r)?"[REDACTED:card]":r);for(let r of t.patterns)o=o.replace(Ue(r),"[REDACTED:pattern]");return o}function I(e,t,n,o){if(typeof e=="string")return ce(e,t,!!o.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((i,s)=>I(i,t,n,{path:[...o.path,String(s)],skipPatternScanning:o.skipPatternScanning}));if(!He(e))return e;let r={};for(let[i,s]of Object.entries(e)){let c=[...o.path,i];if(n.has(i.toLowerCase())||Ge(c,t)){if(s==null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[i]=Me;continue}r[i]=I(s,t,n,{path:c,skipPatternScanning:o.skipPatternScanning});continue}r[i]=I(s,t,n,{path:c,skipPatternScanning:o.skipPatternScanning});}return r}function L(e,t){return {keys:se([...je,...e?.keys??[],...t?.keys??[]]),paths:se([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(n=>n instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function y(e,t,n={path:[]}){let o=h(e);return I(o,t,We(t),n)}function A(e,t){return typeof e=="string"?ce(e,t,false):M(y(e,t))}var Ye="@blyp/core",Xe=".gitignore",ge=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],et="blyp.config.json",tt="https://us.i.posthog.com",nt="blyp-app",rt=nt,ot=new Set,D=ie(ot),fe={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},pe={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:fe},W={enabled:true,path:U},ye=L(),v={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},C={enabled:false,memoryBufferSize:500,durableQueuePath:ne(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:v},me={maxRetries:1,backoffMs:100},it={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:me},ue={pretty:true,level:"info",destination:"file",file:pe,clientLogging:W,redact:ye,connectors:{delivery:C}},z=null;function at(e){let t=e;for(;;){let n=Oe.resolve(t,"package.json");if(fs.existsSync(n))try{let r=JSON.parse(fs.readFileSync(n,"utf-8"));if(f(r.name))return r.name}catch{}let o=Oe.dirname(t);if(o===t)return;t=o;}}function G(e=process.cwd()){return at(e)??rt}function st(){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:U},redact:ye,connectors:{delivery:C}}}function ct(e){let t=Oe.resolve(e,"package.json");if(!fs.existsSync(t))return true;try{return JSON.parse(fs.readFileSync(t,"utf-8")).name!==Ye}catch{return true}}function ut(e){if(ge.some(n=>fs.existsSync(Oe.resolve(e,n))))return;let t=Oe.resolve(e,et);if(!fs.existsSync(t))try{fs.writeFileSync(t,`${JSON.stringify(st(),null,2)}
|
|
2
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to create blyp.config.json:",n);}}function dt(e){let t=Oe.resolve(e,Xe);if(!fs.existsSync(t)){try{fs.writeFileSync(t,`logs
|
|
3
|
+
.blyp
|
|
4
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to create .gitignore:",n);}return}try{let n=fs.readFileSync(t,"utf-8"),o=["logs",".blyp"].filter(i=>{let s=i.replace(".","\\.");return !new RegExp(`^(?:/?${s}/?)\\s*$`,"m").test(n)});if(o.length===0)return;let r=n.endsWith(`
|
|
5
|
+
`)?"":`
|
|
6
|
+
`;fs.appendFileSync(t,`${r}${o.join(`
|
|
7
|
+
`)}
|
|
8
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function lt(){let e=process.cwd();ct(e)&&(ut(e),dt(e));}function gt(){let e=process.cwd(),t=ge.map(o=>Oe.resolve(e,o)).filter(o=>fs.existsSync(o));if(t.length===0)return null;if(t.length>1){let o=t[0];D(`config-multiple:${o}`,`[Blyp] Warning: Multiple config files found. Using ${o} and ignoring ${t.slice(1).join(", ")}.`);}let n=t[0];return {path:n,type:n.endsWith(".json")?"json":"jiti"}}function Ce(e,t){let n=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !n||typeof n!="object"||Array.isArray(n)?(D(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):n}function ft(e){try{let t=fs.readFileSync(e,"utf-8");return Ce(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function pt(e){try{let t=jiti.createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return Ce(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function yt(e){return e.type==="json"?ft(e.path):pt(e.path)}function de(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function mt(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function Ct(e,t){return {...me,...e,...t}}function bt(e,t){return {...it,...e,...t,retry:Ct(e?.retry,t?.retry)}}function ht(e){let t=e.model??"blypLog",o=e.client?.[t];return !!o&&typeof o.create=="function"}function Rt(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function St(e,t){if(!e)return;let n=e.adapter,o=false;t==="json"?D("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?D(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):n?de(n)?(o=ht({...n,model:n.model??"blypLog"}),o||D("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${n.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):mt(n)&&(o=Rt(n),o||D("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):D("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let r=de(n)?{...n,model:n.model??"blypLog"}:n;return {dialect:e.dialect,adapter:r,delivery:bt(void 0,e.delivery),ready:o,status:o?"enabled":"missing"}}function Lt(e,t){return {...fe,...e,...t}}function Dt(e,t){return {...pe,...e,...t,rotation:Lt(e?.rotation,t?.rotation)}}function kt(e,t){return {...W,...e,...t,path:t?.path??e?.path??W.path}}function wt(e,t){return L(e,t)}function xt(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??v.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??v.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??v.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??v.multiplier),jitter:t?.jitter??e?.jitter??v.jitter}}function vt(e,t){let n=t?.durableQueuePath??e?.durableQueuePath??C.durableQueuePath;return {enabled:t?.enabled??e?.enabled??C.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??C.memoryBufferSize)),durableQueuePath:f(n)?n:C.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??C.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??C.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??C.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??C.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??C.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??C.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??C.overflowStrategy,retry:xt(e?.retry,t?.retry),durableReady:false}}function Et(e,t,n){if(!(!e&&!t))return St({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},n)}function Tt(e,t){let n=t?.enabled??e?.enabled??false,o=t?.projectKey??e?.projectKey,r=e?.enabled===true?e?.errorTracking:void 0,i=t?.errorTracking?.mode??r?.mode??"auto",s=t?.errorTracking?.enabled??r?.enabled??n,c=n&&s&&typeof o=="string"&&o.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",projectKey:o,host:t?.host??e?.host??tt,serviceName:t?.serviceName??e?.serviceName??G(),errorTracking:{enabled:s,mode:i,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??r?.enableExceptionAutocapture??i==="auto",ready:c,status:c?"enabled":"missing"}}}function Bt(e,t){let n=t?.enabled??e?.enabled??false,o=t?.apiKey??e?.apiKey,r=t?.websiteId??e?.websiteId,i=n&&f(o)&&f(r);return {enabled:n,mode:t?.mode??e?.mode??"auto",apiKey:o,websiteId:r,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:i,status:i?"enabled":"missing"}}function At(e,t){let n=t?.sourceToken??e?.sourceToken,o=t?.ingestingHost??e?.ingestingHost,r=t?.enabled??e?.enabled??false,i=e?.enabled===true?e?.errorTracking:void 0,s=zt(r,i,t?.errorTracking),c=r&&f(n)&&$(o);return {enabled:r,mode:t?.mode??e?.mode??"auto",sourceToken:n,ingestingHost:o,serviceName:t?.serviceName??e?.serviceName??G(),errorTracking:s,ready:c,status:c?"enabled":"missing"}}function zt(e,t,n){let o=n?.dsn??t?.dsn,r=n?.enabled??t?.enabled??e,i=r&&f(o);return {enabled:r,dsn:o,tracesSampleRate:n?.tracesSampleRate??t?.tracesSampleRate??1,environment:n?.environment??t?.environment,release:n?.release??t?.release,ready:i,status:i?"enabled":"missing"}}function Pt(e,t){let n=t?.dsn??e?.dsn,o=t?.enabled??e?.enabled??false,r=o&&typeof n=="string"&&n.trim().length>0;return {enabled:o,mode:t?.mode??e?.mode??"auto",dsn:n,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:r,status:r?"enabled":"missing"}}function Ft(e,t){let n=t?.endpoint??e?.endpoint,o=t?.enabled??e?.enabled??false,r={...{},...t?.headers??{}},i=o&&$(n);return {name:t?.name??e?.name??"",enabled:o,mode:t?.mode??e?.mode??"auto",endpoint:n,headers:r,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??G(),ready:i,status:i?"enabled":"missing"}}function It(e,t){let n=t??e??[],o=new Map;for(let r of n)!r||typeof r.name!="string"||r.name.length===0||(o.has(r.name)&&D(`otlp-duplicate:${r.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${r.name}" found. Using the last definition.`),o.set(r.name,Ft(void 0,r)));return Array.from(o.values())}function _t(e,t){return {betterstack:At(e?.betterstack,t?.betterstack),databuddy:Bt(e?.databuddy,t?.databuddy),posthog:Tt(e?.posthog,t?.posthog),sentry:Pt(e?.sentry,t?.sentry),otlp:It(e?.otlp,t?.otlp),delivery:vt(e?.delivery,t?.delivery)}}function Q(e,t={},n={}){return {...e,...t,destination:t.destination??e.destination??"file",file:Dt(e.file,t.file),database:Et(e.database,t.database,n.configFileType),clientLogging:kt(e.clientLogging,t.clientLogging),redact:wt(e.redact,t.redact),connectors:_t(e.connectors,t.connectors)}}function Ot(){if(z!==null)return z;lt();let e=gt();if(e){let t=yt(e);z=Q(ue,t,{configFileType:e.type});}else z=Q(ue);return z}function be(e={}){return Q(Ot(),e)}var Mt=new async_hooks.AsyncLocalStorage;function jt(){return Mt.getStore()}function K(){return jt()?.traceId}var he={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function O(e){return e.replace(/\\/g,"/")}function qt(e){let t=O(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 $t(e){let t=O(e),n=O(process.cwd());return t.startsWith(`${n}/`)?t.slice(n.length+1):t}function Re(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
|
|
9
|
+
`),n=null;for(let o=2;o<t.length;o+=1){let r=t[o];if(!r)continue;let i=r.match(/\((.*):(\d+):\d+\)/)||r.match(/at\s+(.*):(\d+):(\d+)/);if(!i)continue;let s=i[1]||"",c=parseInt(i[2]||"0",10)||null;if(s&&!s.includes("node_modules")&&!qt(s)){let d=$t(s);if(!O(d).startsWith("dist/"))return {file:d,line:c};n??(n={file:d,line:c});}}if(n)return n}catch{return {file:null,line:null}}return {file:null,line:null}}var Se=A;function Le(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function De(e,t,n,o,r=L()){let{file:i,line:s}=Re(),c=Se(t,r),d={timestamp:new Date().toISOString(),level:he[e],message:Le(c)},a=K();return t instanceof Error&&(d.error=y(F(t),r)),i&&(d.caller=s!==null?`${i}:${s}`:i),n.length===1?d.data=y(n[0],r):n.length>1&&(d.data=y(n,r)),Object.keys(o).length>0&&(d.bindings=y(o,r)),a&&(d.traceId=a),d}function J(e,t,n,o,r=L()){let{file:i,line:s}=Re(),c=y(n,r),d=K(),a={message:Le(Se(t,r)),...c};return i&&(a.caller=s!==null?`${i}:${s}`:i),Object.keys(o).length>0&&(a.bindings=y(o,r)),d&&a.traceId===void 0&&(a.traceId=d),a.level=typeof c.level=="string"&&c.level.length>0?c.level:he[e],a.timestamp=typeof c.timestamp=="string"&&c.timestamp.length>0?c.timestamp:new Date().toISOString(),a}function V(e){switch(e){case "debug":return "debug";case "warning":return "warning";case "warn":return "warn";case "error":return "error";case "success":return "success";case "critical":return "critical";case "table":return "table";default:return "info"}}function ke(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let n=[e,...t];return n.length===1?n[0]:n}function we(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Ut(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let n=e;return {message:e.message,code:n.code,type:n.type??e.name??e.constructor?.name,stack:e.stack,why:n.why,fix:n.fix,link:n.link,details:we(n.details),cause:n.cause}}if(typeof e=="object"){let n=e,o=typeof n.statusCode=="number"?n.statusCode:typeof n.status=="number"?n.status:t;return {message:typeof n.message=="string"?n.message:`HTTP ${o??500}`,code:typeof n.code=="string"||typeof n.code=="number"?n.code:o,type:typeof n.type=="string"?n.type:typeof n.name=="string"?n.name:"Error",stack:typeof n.stack=="string"?n.stack:void 0,why:typeof n.why=="string"?n.why:void 0,fix:typeof n.fix=="string"?n.fix:void 0,link:typeof n.link=="string"?n.link:void 0,details:we(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Ht(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 Z(e,t){let n=t.redact??L(),o=performance.now(),r=y(t.initialFields??{},n),i=[],s;t.onCreate?.();let c=(a,u,g)=>(i.push({level:a,message:A(u,n),timestamp:new Date().toISOString(),...ke(u,g)===void 0?{}:{data:y(ke(u,g),n)}}),d),d={set(a){return Object.assign(r,y(a,n)),d},debug(a,...u){return c("debug",a,u)},info(a,...u){return c("info",a,u)},warn(a,...u){return c("warn",a,u)},warning(a,...u){return c("warning",a,u)},error(a,...u){return c("error",a,u)},success(a,...u){return c("success",a,u)},critical(a,...u){return c("critical",a,u)},table(a,u){return c("table",a,u===void 0?[]:[u])},emit(a={}){if(s)return s;let u=y(t.resolveDefaultFields?.()??{},n),g=Ht(a),l=y(Ut(a.error,g),n),m=a.level??(l?"error":"info"),p=y({...u,...r,groupId:e,timestamp:new Date().toISOString(),level:m,duration:Math.round(performance.now()-o),...typeof g=="number"?{status:g}:{},...i.length>0?{events:[...i]}:{},...l?{error:l}:{}},n);return t.write(p,A(a.message??"structured_log",n)),s=p,t.onEmit?.(p),p}};return d}function Wt(){let e=new WeakSet;return (t,n)=>{if(typeof n=="function")return `[Function: ${n.name||"anonymous"}]`;if(n===void 0)return "[undefined]";if(typeof n=="symbol")return n.toString();if(n!==null&&typeof n=="object"){if(e.has(n))return "[Circular]";e.add(n);}return n}}function xe(e){return JSON.stringify(e,Wt())}var Y=Symbol("blyp.connector.batch-dispatch"),ve=Symbol("blyp.connector.delivery-binder");function Ee(e){return b(e)&&("connectors"in e||"pretty"in e||"level"in e)}function P(e){return b(e.data)?e.data:e}function R(e,t){if(t in e){let r=e[t];if(typeof r=="string"||typeof r=="number")return r}let o=P(e)[t];if(typeof o=="string"||typeof o=="number")return o}function X(e,t){let n=P(e),r=(b(n.page)?n.page:void 0)?.[t];return typeof r=="string"?r:void 0}function N(e,t){let n=P(e),r=(b(n.session)?n.session:void 0)?.[t];return typeof r=="string"?r:void 0}function ee(e){return R(e,"type")}var Gt=new Set,Te=new Map,Kt={},k=ae(Gt);function Jt(e,t){let n=["beforeExit","SIGINT","SIGTERM"];for(let o of n)process.once(o,()=>{t().catch(r=>{k(`${e}:shutdown`,"[Blyp] Failed to flush Databuddy telemetry during shutdown.",r);});});}function Vt(e){let t=Ee(e)?e.connectors?.databuddy:e,n=t?.enabled??false,o=t?.apiKey,r=t?.websiteId,i=n&&f(o)&&f(r);return {enabled:n,mode:t?.mode??"auto",apiKey:o,websiteId:r,namespace:t?.namespace,source:t?.source,apiUrl:t?.apiUrl,debug:t?.debug??false,enableBatching:t?.enableBatching??true,batchSize:t?.batchSize,batchTimeout:t?.batchTimeout,maxQueueSize:t?.maxQueueSize,ready:i,status:i?"enabled":"missing"}}function Zt(e){return new node.Databuddy({apiKey:e.apiKey??"",...e.websiteId?{websiteId:e.websiteId}:{},...e.namespace?{namespace:e.namespace}:{},...e.source?{source:e.source}:{},...e.apiUrl?{apiUrl:e.apiUrl}:{},debug:e.debug,enableBatching:e.enableBatching,...e.batchSize!==void 0?{batchSize:e.batchSize}:{},...e.batchTimeout!==void 0?{batchTimeout:e.batchTimeout}:{},...e.maxQueueSize!==void 0?{maxQueueSize:e.maxQueueSize}:{}})}function Yt(e){return JSON.stringify({enabled:e.enabled,mode:e.mode,apiKey:e.apiKey??null,websiteId:e.websiteId??null,namespace:e.namespace??null,source:e.source??null,apiUrl:e.apiUrl??null,debug:e.debug,enableBatching:e.enableBatching,batchSize:e.batchSize??null,batchTimeout:e.batchTimeout??null,maxQueueSize:e.maxQueueSize??null})}function Xt(e){let t=R(e,"sessionId");return f(t)?t:N(e,"sessionId")}function en(e){let t=R(e,"anonymousId");if(f(t))return t;let n=P(e);if(b(n.metadata)&&f(n.metadata.databuddyAnonymousId))return n.metadata.databuddyAnonymousId}function tn(e){let t=ee(e);return f(t)?t:"log"}function nn(e,t){let n={blyp_level:e.level,blyp_source:t,blyp_payload:xe(e),message:typeof e.message=="string"?e.message:String(e.message)},o=typeof e.caller=="string"?e.caller:void 0,r=R(e,"groupId"),i=R(e,"traceId"),s=R(e,"method"),c=R(e,"path"),d=R(e,"status"),a=R(e,"duration"),u=X(e,"pathname"),g=X(e,"url"),l=N(e,"sessionId"),m=N(e,"pageId"),p=[["blyp_type",ee(e)],["caller",o],["group_id",r],["trace_id",i],["method",s],["path",c],["page_path",u],["page_url",g],["session_id",l],["page_id",m]],w=[["status_code",d],["duration_ms",a]];for(let[x,B]of p)B&&(n[x]=B);for(let[x,B]of w)B!==void 0&&(n[x]=B);return n}function Be(e,t){return {name:tn(e),anonymousId:en(e),sessionId:Xt(e),properties:nn(e,t)}}function Ae(e){return b(e)?h(e):{}}function rn(e,t){return e instanceof Error?{message:e.message||t,properties:{error_type:e.name,...e.stack?{stack:e.stack}:{},...Ae(e)}}:b(e)?{message:f(e.message)?e.message:f(e.error)?e.error:t,properties:Ae(e)}:typeof e=="string"?{message:e,properties:{message:e}}:{message:t,properties:{value:h(e)}}}function ze(e){return !b(e)||e.success!==false?null:f(e.error)?e.error:f(e.message)?e.message:"Databuddy SDK reported delivery failure."}function Pe(e){let t=Vt(e),n=Yt(t),o=Te.get(n);if(o)return o;let r=`${t.apiUrl??"default"}:${t.mode}:${t.apiKey??"missing"}`,i=t.ready?Kt.createClient?.(t)??Zt(t):void 0;i&&Jt(r,async()=>{await i.flush();});let s=()=>{k(`databuddy-unavailable:${r}`,"[Blyp] Databuddy connector is not configured. Databuddy requires both apiKey and websiteId. Skipping Databuddy delivery.");},c=()=>{k(`databuddy-exception-unavailable:${r}`,"[Blyp] Databuddy error tracking is not configured. Databuddy requires both apiKey and websiteId. Skipping Databuddy exception capture.");},d=null,a=async g=>{if(!t.ready||!i)return {ok:false,retryable:false,error:"Databuddy connector is not configured."};try{let l=await Promise.all(g.map(w=>Promise.resolve(i.track(Be(w,"server")))));for(let w of l){let x=ze(w);if(x)return {ok:!1,retryable:!0,error:x}}let m=await i.flush(),p=ze(m);return p?{ok:!1,retryable:!0,error:p}:{ok:!0}}catch(l){return {ok:false,retryable:true,error:l instanceof Error?l.message:String(l)}}},u={enabled:t.enabled,ready:t.ready,mode:t.mode,status:t.status,shouldAutoForwardServerLogs(){return t.ready&&t.mode==="auto"},shouldAutoCaptureExceptions(){return t.ready&&t.mode==="auto"},send(g,l={}){if(l.source!=="client"&&d){d.enqueue("databuddy",g,u[Y]);return}if(!t.ready||!i){l.warnIfUnavailable&&s();return}try{let m=i.track(Be(g,l.source??"server"));m&&typeof m.catch=="function"&&m.catch(p=>{k(`databuddy-send:${r}`,"[Blyp] Failed to deliver log to Databuddy.",p);});}catch(m){k(`databuddy-send:${r}`,"[Blyp] Failed to deliver log to Databuddy.",m);}},captureException(g,l={}){if(!t.ready||!i){l.warnIfUnavailable&&c();return}let m=rn(g,l.source==="client"?"Client error":"Server error");try{let p=i.track({name:"error",anonymousId:l.anonymousId,sessionId:l.sessionId,properties:{message:m.message,blyp_source:l.source??"server",blyp_level:"error",...m.properties,...l.properties??{}}});p&&typeof p.catch=="function"&&p.catch(w=>{k(`databuddy-capture:${r}`,"[Blyp] Failed to capture exception in Databuddy.",w);});}catch(p){k(`databuddy-capture:${r}`,"[Blyp] Failed to capture exception in Databuddy.",p);}},async flush(){try{i&&await i.flush();}catch(g){k(`databuddy-flush:${r}`,"[Blyp] Failed to flush Databuddy telemetry.",g);}},[Y]:{dispatchKey:"databuddy",dispatch:g=>a(g)},[ve](g){d=g;}};return Te.set(n,u),u}function te(e={}){return Pe(be({...e.connectors?{connectors:e.connectors}:{}}))}function Fe(e,t={}){let n=(r,i,s)=>{e.send(De(r,i,s,t),{source:"server",warnIfUnavailable:true});},o=(r,i)=>{e.send(J(V(r.level),i,r,t),{source:"server",warnIfUnavailable:true});};return {debug:(r,...i)=>{n("debug",r,i);},info:(r,...i)=>{n("info",r,i);},error:(r,...i)=>{n("error",r,i);},warn:(r,...i)=>{n("warn",r,i);},warning:(r,...i)=>{n("warning",r,i);},success:(r,...i)=>{n("success",r,i);},critical:(r,...i)=>{n("critical",r,i);},table:(r,i)=>{n("table",r,i===void 0?[]:[i]);},flush:async()=>{await e.flush();},shutdown:async()=>{await e.flush();},createStructuredLog:(r,i)=>Z(r,{initialFields:i,write:o}),child:r=>Fe(e,{...t,...r})}}function Ie(e,t={}){return {capture:(n,o={})=>{e.captureException(n,{source:"server",warnIfUnavailable:true,properties:{...t,...o.properties??{},blyp_source:"server",blyp_manual:true}});},child:n=>Ie(e,{...t,...n})}}function or(e={}){return Fe(te(e))}function ir(e,t,n={}){let o=te(n);return Z(e,{initialFields:t,write:(r,i)=>{o.send(J(V(r.level),i,r,{}),{source:"server",warnIfUnavailable:true});}})}function on(e={}){return Ie(te(e))}function ar(e,t={},n={}){on(n).capture(e,t);}exports.captureDatabuddyException=ar;exports.createDatabuddyErrorTracker=on;exports.createDatabuddyLogger=or;exports.createStructuredDatabuddyLogger=ir;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import {existsSync,readFileSync,writeFileSync,appendFileSync}from'fs';import {createJiti}from'jiti';import Oe,{resolve,dirname}from'path';import _e from'os';import {z as z$1}from'zod';import {AsyncLocalStorage}from'async_hooks';import {Databuddy}from'@databuddy/sdk/node';import'fflate';function ne(){return Oe.join(_e.homedir(),".blyp","queue.db")}function F(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let n=e;return n.cause!==void 0&&(t.cause=h(n.cause)),t}function h(e,t=new WeakSet){if(e instanceof Error)return F(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(n=>h(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let n={};for(let[o,r]of Object.entries(e))n[o]=h(r,t);return t.delete(e),n}return e}function M(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=h(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var Ne=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"}),re=z$1.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),q=z$1.string().trim().min(1);function $(e){return Ne.safeParse(e).success}function b(e){return re.safeParse(e).success}function f(e){return q.safeParse(e).success}var U="/inngest";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:q})]);function oe(e,t=new Set){return (n,o,r)=>{if(t.has(n)||typeof console>"u")return;let i=console[e];if(typeof i=="function"){if(t.add(n),r===void 0){i.call(console,o);return}i.call(console,o,r);}}}function ie(e){return oe("warn",e)}function ae(e){return oe("error",e)}var Me="[REDACTED]",je=["password","passwd","pwd","secret","token","api_key","apikey","api_secret","authorization","auth","x-api-key","private_key","privatekey","access_token","refresh_token","client_secret","session","cookie","set-cookie","ssn","credit_card","card_number","cvv","cvc","otp","pin"];var qe=[{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}],$e=/\b(?:\d[ -]*?){16}\b/g;function se(e){let t=new Set,n=[];for(let o of e)typeof o!="string"||o.length===0||t.has(o)||(t.add(o),n.push(o));return n}function Ue(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function He(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function We(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Qe(e){return e.split(".").filter(Boolean)}function H(e,t,n=0,o=0){if(n===e.length)return o===t.length;let r=e[n];if(r==="**"){if(n===e.length-1)return true;for(let i=o;i<=t.length;i+=1)if(H(e,t,n+1,i))return true;return false}return o>=t.length||r!=="*"&&r!==t[o]?false:H(e,t,n+1,o+1)}function Ge(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>H(Qe(n),e))}function Ke(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,o=false;for(let r=t.length-1;r>=0;r-=1){let i=Number(t[r]);o&&(i*=2,i>9&&(i-=9)),n+=i,o=!o;}return n%10===0}function ce(e,t,n){if(n||t.disablePatternScanning)return e;let o=e;for(let{type:r,pattern:i}of qe)o=o.replace(i,`[REDACTED:${r}]`);o=o.replace($e,r=>Ke(r)?"[REDACTED:card]":r);for(let r of t.patterns)o=o.replace(Ue(r),"[REDACTED:pattern]");return o}function I(e,t,n,o){if(typeof e=="string")return ce(e,t,!!o.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((i,s)=>I(i,t,n,{path:[...o.path,String(s)],skipPatternScanning:o.skipPatternScanning}));if(!He(e))return e;let r={};for(let[i,s]of Object.entries(e)){let c=[...o.path,i];if(n.has(i.toLowerCase())||Ge(c,t)){if(s==null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[i]=Me;continue}r[i]=I(s,t,n,{path:c,skipPatternScanning:o.skipPatternScanning});continue}r[i]=I(s,t,n,{path:c,skipPatternScanning:o.skipPatternScanning});}return r}function L(e,t){return {keys:se([...je,...e?.keys??[],...t?.keys??[]]),paths:se([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(n=>n instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function y(e,t,n={path:[]}){let o=h(e);return I(o,t,We(t),n)}function A(e,t){return typeof e=="string"?ce(e,t,false):M(y(e,t))}var Ye="@blyp/core",Xe=".gitignore",ge=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],et="blyp.config.json",tt="https://us.i.posthog.com",nt="blyp-app",rt=nt,ot=new Set,D=ie(ot),fe={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},pe={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:fe},W={enabled:true,path:U},ye=L(),v={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},C={enabled:false,memoryBufferSize:500,durableQueuePath:ne(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:v},me={maxRetries:1,backoffMs:100},it={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:me},ue={pretty:true,level:"info",destination:"file",file:pe,clientLogging:W,redact:ye,connectors:{delivery:C}},z=null;function at(e){let t=e;for(;;){let n=resolve(t,"package.json");if(existsSync(n))try{let r=JSON.parse(readFileSync(n,"utf-8"));if(f(r.name))return r.name}catch{}let o=dirname(t);if(o===t)return;t=o;}}function G(e=process.cwd()){return at(e)??rt}function st(){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:U},redact:ye,connectors:{delivery:C}}}function ct(e){let t=resolve(e,"package.json");if(!existsSync(t))return true;try{return JSON.parse(readFileSync(t,"utf-8")).name!==Ye}catch{return true}}function ut(e){if(ge.some(n=>existsSync(resolve(e,n))))return;let t=resolve(e,et);if(!existsSync(t))try{writeFileSync(t,`${JSON.stringify(st(),null,2)}
|
|
2
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to create blyp.config.json:",n);}}function dt(e){let t=resolve(e,Xe);if(!existsSync(t)){try{writeFileSync(t,`logs
|
|
3
|
+
.blyp
|
|
4
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to create .gitignore:",n);}return}try{let n=readFileSync(t,"utf-8"),o=["logs",".blyp"].filter(i=>{let s=i.replace(".","\\.");return !new RegExp(`^(?:/?${s}/?)\\s*$`,"m").test(n)});if(o.length===0)return;let r=n.endsWith(`
|
|
5
|
+
`)?"":`
|
|
6
|
+
`;appendFileSync(t,`${r}${o.join(`
|
|
7
|
+
`)}
|
|
8
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function lt(){let e=process.cwd();ct(e)&&(ut(e),dt(e));}function gt(){let e=process.cwd(),t=ge.map(o=>resolve(e,o)).filter(o=>existsSync(o));if(t.length===0)return null;if(t.length>1){let o=t[0];D(`config-multiple:${o}`,`[Blyp] Warning: Multiple config files found. Using ${o} and ignoring ${t.slice(1).join(", ")}.`);}let n=t[0];return {path:n,type:n.endsWith(".json")?"json":"jiti"}}function Ce(e,t){let n=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !n||typeof n!="object"||Array.isArray(n)?(D(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):n}function ft(e){try{let t=readFileSync(e,"utf-8");return Ce(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function pt(e){try{let t=createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return Ce(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function yt(e){return e.type==="json"?ft(e.path):pt(e.path)}function de(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function mt(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function Ct(e,t){return {...me,...e,...t}}function bt(e,t){return {...it,...e,...t,retry:Ct(e?.retry,t?.retry)}}function ht(e){let t=e.model??"blypLog",o=e.client?.[t];return !!o&&typeof o.create=="function"}function Rt(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function St(e,t){if(!e)return;let n=e.adapter,o=false;t==="json"?D("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?D(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):n?de(n)?(o=ht({...n,model:n.model??"blypLog"}),o||D("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${n.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):mt(n)&&(o=Rt(n),o||D("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):D("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let r=de(n)?{...n,model:n.model??"blypLog"}:n;return {dialect:e.dialect,adapter:r,delivery:bt(void 0,e.delivery),ready:o,status:o?"enabled":"missing"}}function Lt(e,t){return {...fe,...e,...t}}function Dt(e,t){return {...pe,...e,...t,rotation:Lt(e?.rotation,t?.rotation)}}function kt(e,t){return {...W,...e,...t,path:t?.path??e?.path??W.path}}function wt(e,t){return L(e,t)}function xt(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??v.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??v.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??v.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??v.multiplier),jitter:t?.jitter??e?.jitter??v.jitter}}function vt(e,t){let n=t?.durableQueuePath??e?.durableQueuePath??C.durableQueuePath;return {enabled:t?.enabled??e?.enabled??C.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??C.memoryBufferSize)),durableQueuePath:f(n)?n:C.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??C.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??C.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??C.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??C.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??C.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??C.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??C.overflowStrategy,retry:xt(e?.retry,t?.retry),durableReady:false}}function Et(e,t,n){if(!(!e&&!t))return St({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},n)}function Tt(e,t){let n=t?.enabled??e?.enabled??false,o=t?.projectKey??e?.projectKey,r=e?.enabled===true?e?.errorTracking:void 0,i=t?.errorTracking?.mode??r?.mode??"auto",s=t?.errorTracking?.enabled??r?.enabled??n,c=n&&s&&typeof o=="string"&&o.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",projectKey:o,host:t?.host??e?.host??tt,serviceName:t?.serviceName??e?.serviceName??G(),errorTracking:{enabled:s,mode:i,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??r?.enableExceptionAutocapture??i==="auto",ready:c,status:c?"enabled":"missing"}}}function Bt(e,t){let n=t?.enabled??e?.enabled??false,o=t?.apiKey??e?.apiKey,r=t?.websiteId??e?.websiteId,i=n&&f(o)&&f(r);return {enabled:n,mode:t?.mode??e?.mode??"auto",apiKey:o,websiteId:r,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:i,status:i?"enabled":"missing"}}function At(e,t){let n=t?.sourceToken??e?.sourceToken,o=t?.ingestingHost??e?.ingestingHost,r=t?.enabled??e?.enabled??false,i=e?.enabled===true?e?.errorTracking:void 0,s=zt(r,i,t?.errorTracking),c=r&&f(n)&&$(o);return {enabled:r,mode:t?.mode??e?.mode??"auto",sourceToken:n,ingestingHost:o,serviceName:t?.serviceName??e?.serviceName??G(),errorTracking:s,ready:c,status:c?"enabled":"missing"}}function zt(e,t,n){let o=n?.dsn??t?.dsn,r=n?.enabled??t?.enabled??e,i=r&&f(o);return {enabled:r,dsn:o,tracesSampleRate:n?.tracesSampleRate??t?.tracesSampleRate??1,environment:n?.environment??t?.environment,release:n?.release??t?.release,ready:i,status:i?"enabled":"missing"}}function Pt(e,t){let n=t?.dsn??e?.dsn,o=t?.enabled??e?.enabled??false,r=o&&typeof n=="string"&&n.trim().length>0;return {enabled:o,mode:t?.mode??e?.mode??"auto",dsn:n,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:r,status:r?"enabled":"missing"}}function Ft(e,t){let n=t?.endpoint??e?.endpoint,o=t?.enabled??e?.enabled??false,r={...{},...t?.headers??{}},i=o&&$(n);return {name:t?.name??e?.name??"",enabled:o,mode:t?.mode??e?.mode??"auto",endpoint:n,headers:r,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??G(),ready:i,status:i?"enabled":"missing"}}function It(e,t){let n=t??e??[],o=new Map;for(let r of n)!r||typeof r.name!="string"||r.name.length===0||(o.has(r.name)&&D(`otlp-duplicate:${r.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${r.name}" found. Using the last definition.`),o.set(r.name,Ft(void 0,r)));return Array.from(o.values())}function _t(e,t){return {betterstack:At(e?.betterstack,t?.betterstack),databuddy:Bt(e?.databuddy,t?.databuddy),posthog:Tt(e?.posthog,t?.posthog),sentry:Pt(e?.sentry,t?.sentry),otlp:It(e?.otlp,t?.otlp),delivery:vt(e?.delivery,t?.delivery)}}function Q(e,t={},n={}){return {...e,...t,destination:t.destination??e.destination??"file",file:Dt(e.file,t.file),database:Et(e.database,t.database,n.configFileType),clientLogging:kt(e.clientLogging,t.clientLogging),redact:wt(e.redact,t.redact),connectors:_t(e.connectors,t.connectors)}}function Ot(){if(z!==null)return z;lt();let e=gt();if(e){let t=yt(e);z=Q(ue,t,{configFileType:e.type});}else z=Q(ue);return z}function be(e={}){return Q(Ot(),e)}var Mt=new AsyncLocalStorage;function jt(){return Mt.getStore()}function K(){return jt()?.traceId}var he={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function O(e){return e.replace(/\\/g,"/")}function qt(e){let t=O(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 $t(e){let t=O(e),n=O(process.cwd());return t.startsWith(`${n}/`)?t.slice(n.length+1):t}function Re(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
|
|
9
|
+
`),n=null;for(let o=2;o<t.length;o+=1){let r=t[o];if(!r)continue;let i=r.match(/\((.*):(\d+):\d+\)/)||r.match(/at\s+(.*):(\d+):(\d+)/);if(!i)continue;let s=i[1]||"",c=parseInt(i[2]||"0",10)||null;if(s&&!s.includes("node_modules")&&!qt(s)){let d=$t(s);if(!O(d).startsWith("dist/"))return {file:d,line:c};n??(n={file:d,line:c});}}if(n)return n}catch{return {file:null,line:null}}return {file:null,line:null}}var Se=A;function Le(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function De(e,t,n,o,r=L()){let{file:i,line:s}=Re(),c=Se(t,r),d={timestamp:new Date().toISOString(),level:he[e],message:Le(c)},a=K();return t instanceof Error&&(d.error=y(F(t),r)),i&&(d.caller=s!==null?`${i}:${s}`:i),n.length===1?d.data=y(n[0],r):n.length>1&&(d.data=y(n,r)),Object.keys(o).length>0&&(d.bindings=y(o,r)),a&&(d.traceId=a),d}function J(e,t,n,o,r=L()){let{file:i,line:s}=Re(),c=y(n,r),d=K(),a={message:Le(Se(t,r)),...c};return i&&(a.caller=s!==null?`${i}:${s}`:i),Object.keys(o).length>0&&(a.bindings=y(o,r)),d&&a.traceId===void 0&&(a.traceId=d),a.level=typeof c.level=="string"&&c.level.length>0?c.level:he[e],a.timestamp=typeof c.timestamp=="string"&&c.timestamp.length>0?c.timestamp:new Date().toISOString(),a}function V(e){switch(e){case "debug":return "debug";case "warning":return "warning";case "warn":return "warn";case "error":return "error";case "success":return "success";case "critical":return "critical";case "table":return "table";default:return "info"}}function ke(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let n=[e,...t];return n.length===1?n[0]:n}function we(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Ut(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let n=e;return {message:e.message,code:n.code,type:n.type??e.name??e.constructor?.name,stack:e.stack,why:n.why,fix:n.fix,link:n.link,details:we(n.details),cause:n.cause}}if(typeof e=="object"){let n=e,o=typeof n.statusCode=="number"?n.statusCode:typeof n.status=="number"?n.status:t;return {message:typeof n.message=="string"?n.message:`HTTP ${o??500}`,code:typeof n.code=="string"||typeof n.code=="number"?n.code:o,type:typeof n.type=="string"?n.type:typeof n.name=="string"?n.name:"Error",stack:typeof n.stack=="string"?n.stack:void 0,why:typeof n.why=="string"?n.why:void 0,fix:typeof n.fix=="string"?n.fix:void 0,link:typeof n.link=="string"?n.link:void 0,details:we(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Ht(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 Z(e,t){let n=t.redact??L(),o=performance.now(),r=y(t.initialFields??{},n),i=[],s;t.onCreate?.();let c=(a,u,g)=>(i.push({level:a,message:A(u,n),timestamp:new Date().toISOString(),...ke(u,g)===void 0?{}:{data:y(ke(u,g),n)}}),d),d={set(a){return Object.assign(r,y(a,n)),d},debug(a,...u){return c("debug",a,u)},info(a,...u){return c("info",a,u)},warn(a,...u){return c("warn",a,u)},warning(a,...u){return c("warning",a,u)},error(a,...u){return c("error",a,u)},success(a,...u){return c("success",a,u)},critical(a,...u){return c("critical",a,u)},table(a,u){return c("table",a,u===void 0?[]:[u])},emit(a={}){if(s)return s;let u=y(t.resolveDefaultFields?.()??{},n),g=Ht(a),l=y(Ut(a.error,g),n),m=a.level??(l?"error":"info"),p=y({...u,...r,groupId:e,timestamp:new Date().toISOString(),level:m,duration:Math.round(performance.now()-o),...typeof g=="number"?{status:g}:{},...i.length>0?{events:[...i]}:{},...l?{error:l}:{}},n);return t.write(p,A(a.message??"structured_log",n)),s=p,t.onEmit?.(p),p}};return d}function Wt(){let e=new WeakSet;return (t,n)=>{if(typeof n=="function")return `[Function: ${n.name||"anonymous"}]`;if(n===void 0)return "[undefined]";if(typeof n=="symbol")return n.toString();if(n!==null&&typeof n=="object"){if(e.has(n))return "[Circular]";e.add(n);}return n}}function xe(e){return JSON.stringify(e,Wt())}var Y=Symbol("blyp.connector.batch-dispatch"),ve=Symbol("blyp.connector.delivery-binder");function Ee(e){return b(e)&&("connectors"in e||"pretty"in e||"level"in e)}function P(e){return b(e.data)?e.data:e}function R(e,t){if(t in e){let r=e[t];if(typeof r=="string"||typeof r=="number")return r}let o=P(e)[t];if(typeof o=="string"||typeof o=="number")return o}function X(e,t){let n=P(e),r=(b(n.page)?n.page:void 0)?.[t];return typeof r=="string"?r:void 0}function N(e,t){let n=P(e),r=(b(n.session)?n.session:void 0)?.[t];return typeof r=="string"?r:void 0}function ee(e){return R(e,"type")}var Gt=new Set,Te=new Map,Kt={},k=ae(Gt);function Jt(e,t){let n=["beforeExit","SIGINT","SIGTERM"];for(let o of n)process.once(o,()=>{t().catch(r=>{k(`${e}:shutdown`,"[Blyp] Failed to flush Databuddy telemetry during shutdown.",r);});});}function Vt(e){let t=Ee(e)?e.connectors?.databuddy:e,n=t?.enabled??false,o=t?.apiKey,r=t?.websiteId,i=n&&f(o)&&f(r);return {enabled:n,mode:t?.mode??"auto",apiKey:o,websiteId:r,namespace:t?.namespace,source:t?.source,apiUrl:t?.apiUrl,debug:t?.debug??false,enableBatching:t?.enableBatching??true,batchSize:t?.batchSize,batchTimeout:t?.batchTimeout,maxQueueSize:t?.maxQueueSize,ready:i,status:i?"enabled":"missing"}}function Zt(e){return new Databuddy({apiKey:e.apiKey??"",...e.websiteId?{websiteId:e.websiteId}:{},...e.namespace?{namespace:e.namespace}:{},...e.source?{source:e.source}:{},...e.apiUrl?{apiUrl:e.apiUrl}:{},debug:e.debug,enableBatching:e.enableBatching,...e.batchSize!==void 0?{batchSize:e.batchSize}:{},...e.batchTimeout!==void 0?{batchTimeout:e.batchTimeout}:{},...e.maxQueueSize!==void 0?{maxQueueSize:e.maxQueueSize}:{}})}function Yt(e){return JSON.stringify({enabled:e.enabled,mode:e.mode,apiKey:e.apiKey??null,websiteId:e.websiteId??null,namespace:e.namespace??null,source:e.source??null,apiUrl:e.apiUrl??null,debug:e.debug,enableBatching:e.enableBatching,batchSize:e.batchSize??null,batchTimeout:e.batchTimeout??null,maxQueueSize:e.maxQueueSize??null})}function Xt(e){let t=R(e,"sessionId");return f(t)?t:N(e,"sessionId")}function en(e){let t=R(e,"anonymousId");if(f(t))return t;let n=P(e);if(b(n.metadata)&&f(n.metadata.databuddyAnonymousId))return n.metadata.databuddyAnonymousId}function tn(e){let t=ee(e);return f(t)?t:"log"}function nn(e,t){let n={blyp_level:e.level,blyp_source:t,blyp_payload:xe(e),message:typeof e.message=="string"?e.message:String(e.message)},o=typeof e.caller=="string"?e.caller:void 0,r=R(e,"groupId"),i=R(e,"traceId"),s=R(e,"method"),c=R(e,"path"),d=R(e,"status"),a=R(e,"duration"),u=X(e,"pathname"),g=X(e,"url"),l=N(e,"sessionId"),m=N(e,"pageId"),p=[["blyp_type",ee(e)],["caller",o],["group_id",r],["trace_id",i],["method",s],["path",c],["page_path",u],["page_url",g],["session_id",l],["page_id",m]],w=[["status_code",d],["duration_ms",a]];for(let[x,B]of p)B&&(n[x]=B);for(let[x,B]of w)B!==void 0&&(n[x]=B);return n}function Be(e,t){return {name:tn(e),anonymousId:en(e),sessionId:Xt(e),properties:nn(e,t)}}function Ae(e){return b(e)?h(e):{}}function rn(e,t){return e instanceof Error?{message:e.message||t,properties:{error_type:e.name,...e.stack?{stack:e.stack}:{},...Ae(e)}}:b(e)?{message:f(e.message)?e.message:f(e.error)?e.error:t,properties:Ae(e)}:typeof e=="string"?{message:e,properties:{message:e}}:{message:t,properties:{value:h(e)}}}function ze(e){return !b(e)||e.success!==false?null:f(e.error)?e.error:f(e.message)?e.message:"Databuddy SDK reported delivery failure."}function Pe(e){let t=Vt(e),n=Yt(t),o=Te.get(n);if(o)return o;let r=`${t.apiUrl??"default"}:${t.mode}:${t.apiKey??"missing"}`,i=t.ready?Kt.createClient?.(t)??Zt(t):void 0;i&&Jt(r,async()=>{await i.flush();});let s=()=>{k(`databuddy-unavailable:${r}`,"[Blyp] Databuddy connector is not configured. Databuddy requires both apiKey and websiteId. Skipping Databuddy delivery.");},c=()=>{k(`databuddy-exception-unavailable:${r}`,"[Blyp] Databuddy error tracking is not configured. Databuddy requires both apiKey and websiteId. Skipping Databuddy exception capture.");},d=null,a=async g=>{if(!t.ready||!i)return {ok:false,retryable:false,error:"Databuddy connector is not configured."};try{let l=await Promise.all(g.map(w=>Promise.resolve(i.track(Be(w,"server")))));for(let w of l){let x=ze(w);if(x)return {ok:!1,retryable:!0,error:x}}let m=await i.flush(),p=ze(m);return p?{ok:!1,retryable:!0,error:p}:{ok:!0}}catch(l){return {ok:false,retryable:true,error:l instanceof Error?l.message:String(l)}}},u={enabled:t.enabled,ready:t.ready,mode:t.mode,status:t.status,shouldAutoForwardServerLogs(){return t.ready&&t.mode==="auto"},shouldAutoCaptureExceptions(){return t.ready&&t.mode==="auto"},send(g,l={}){if(l.source!=="client"&&d){d.enqueue("databuddy",g,u[Y]);return}if(!t.ready||!i){l.warnIfUnavailable&&s();return}try{let m=i.track(Be(g,l.source??"server"));m&&typeof m.catch=="function"&&m.catch(p=>{k(`databuddy-send:${r}`,"[Blyp] Failed to deliver log to Databuddy.",p);});}catch(m){k(`databuddy-send:${r}`,"[Blyp] Failed to deliver log to Databuddy.",m);}},captureException(g,l={}){if(!t.ready||!i){l.warnIfUnavailable&&c();return}let m=rn(g,l.source==="client"?"Client error":"Server error");try{let p=i.track({name:"error",anonymousId:l.anonymousId,sessionId:l.sessionId,properties:{message:m.message,blyp_source:l.source??"server",blyp_level:"error",...m.properties,...l.properties??{}}});p&&typeof p.catch=="function"&&p.catch(w=>{k(`databuddy-capture:${r}`,"[Blyp] Failed to capture exception in Databuddy.",w);});}catch(p){k(`databuddy-capture:${r}`,"[Blyp] Failed to capture exception in Databuddy.",p);}},async flush(){try{i&&await i.flush();}catch(g){k(`databuddy-flush:${r}`,"[Blyp] Failed to flush Databuddy telemetry.",g);}},[Y]:{dispatchKey:"databuddy",dispatch:g=>a(g)},[ve](g){d=g;}};return Te.set(n,u),u}function te(e={}){return Pe(be({...e.connectors?{connectors:e.connectors}:{}}))}function Fe(e,t={}){let n=(r,i,s)=>{e.send(De(r,i,s,t),{source:"server",warnIfUnavailable:true});},o=(r,i)=>{e.send(J(V(r.level),i,r,t),{source:"server",warnIfUnavailable:true});};return {debug:(r,...i)=>{n("debug",r,i);},info:(r,...i)=>{n("info",r,i);},error:(r,...i)=>{n("error",r,i);},warn:(r,...i)=>{n("warn",r,i);},warning:(r,...i)=>{n("warning",r,i);},success:(r,...i)=>{n("success",r,i);},critical:(r,...i)=>{n("critical",r,i);},table:(r,i)=>{n("table",r,i===void 0?[]:[i]);},flush:async()=>{await e.flush();},shutdown:async()=>{await e.flush();},createStructuredLog:(r,i)=>Z(r,{initialFields:i,write:o}),child:r=>Fe(e,{...t,...r})}}function Ie(e,t={}){return {capture:(n,o={})=>{e.captureException(n,{source:"server",warnIfUnavailable:true,properties:{...t,...o.properties??{},blyp_source:"server",blyp_manual:true}});},child:n=>Ie(e,{...t,...n})}}function or(e={}){return Fe(te(e))}function ir(e,t,n={}){let o=te(n);return Z(e,{initialFields:t,write:(r,i)=>{o.send(J(V(r.level),i,r,{}),{source:"server",warnIfUnavailable:true});}})}function on(e={}){return Ie(te(e))}function ar(e,t={},n={}){on(n).capture(e,t);}export{ar as captureDatabuddyException,on as createDatabuddyErrorTracker,or as createDatabuddyLogger,ir as createStructuredDatabuddyLogger};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { LogRecord } from '../../core/file-logger';
|
|
2
|
+
import type { ResolvedConnectorDeliveryConfig } from '../../types/core/config';
|
|
3
|
+
import { type ConnectorBatchDispatcher, type ConnectorBatchDispatchTarget, type ConnectorDeliveryStatusRecord, type ConnectorDeliveryBinder, type DurableConnectorDeadLetterRecord, type QueuedConnectorType } from './types';
|
|
4
|
+
export declare class ConnectorDeliveryManager implements ConnectorDeliveryBinder {
|
|
5
|
+
private readonly config;
|
|
6
|
+
private readonly warnOnce;
|
|
7
|
+
private readonly memoryQueue;
|
|
8
|
+
private readonly durableStaging;
|
|
9
|
+
private readonly dispatchers;
|
|
10
|
+
private activeDispatches;
|
|
11
|
+
private flushPromise;
|
|
12
|
+
private durableFlushPromise;
|
|
13
|
+
private pollTimer;
|
|
14
|
+
private durablePollRunning;
|
|
15
|
+
private closed;
|
|
16
|
+
private durableClient;
|
|
17
|
+
private durableReady;
|
|
18
|
+
private durableInitPromise;
|
|
19
|
+
constructor(config: ResolvedConnectorDeliveryConfig);
|
|
20
|
+
bindTarget(target: ConnectorBatchDispatchTarget): void;
|
|
21
|
+
unbindTarget(target: ConnectorBatchDispatchTarget): void;
|
|
22
|
+
enqueue(connectorType: QueuedConnectorType, record: LogRecord, dispatcher: ConnectorBatchDispatcher, target?: string): void;
|
|
23
|
+
flush(): Promise<void>;
|
|
24
|
+
shutdown(): Promise<void>;
|
|
25
|
+
getDurableCountForTests(): Promise<number>;
|
|
26
|
+
getStatusSummaryForTests(): Promise<ConnectorDeliveryStatusRecord[]>;
|
|
27
|
+
listDeadLettersForTests(): Promise<DurableConnectorDeadLetterRecord[]>;
|
|
28
|
+
private initializeDurableQueue;
|
|
29
|
+
private scheduleDispatch;
|
|
30
|
+
private pumpMemoryQueue;
|
|
31
|
+
private takeNextMemoryBatch;
|
|
32
|
+
private dispatchMemoryBatch;
|
|
33
|
+
private handleRetryableFailure;
|
|
34
|
+
private recordSuccessfulDispatch;
|
|
35
|
+
private recordFailedDispatch;
|
|
36
|
+
private stageDurableJob;
|
|
37
|
+
private flushDurableStaging;
|
|
38
|
+
private processDurableQueueOnce;
|
|
39
|
+
private drainDurableQueueForFlush;
|
|
40
|
+
private scheduleDurablePoll;
|
|
41
|
+
private enforceMemoryCapacity;
|
|
42
|
+
private hasReadyMemoryJobs;
|
|
43
|
+
private processUntilIdle;
|
|
44
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function getDefaultConnectorQueuePath(): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const BUN_SQLITE_MODULE = "bun:sqlite";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const NODE_SQLITE_MODULE = "node:sqlite";
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { ConnectorDeliveryStatusRecord, DeadLetterListResult, DurableConnectorDeadLetterRecord, DurableConnectorJobRecord, DurableQueueRescheduleInput } from './types';
|
|
2
|
+
export declare class SQLiteWorkerClient {
|
|
3
|
+
private readonly path;
|
|
4
|
+
private readonly worker;
|
|
5
|
+
private readonly pending;
|
|
6
|
+
private nextId;
|
|
7
|
+
constructor(path: string);
|
|
8
|
+
private request;
|
|
9
|
+
init(): Promise<void>;
|
|
10
|
+
insert(jobs: DurableConnectorJobRecord[]): Promise<void>;
|
|
11
|
+
claimDue(limit: number, now: number): Promise<DurableConnectorJobRecord[]>;
|
|
12
|
+
ack(ids: string[]): Promise<void>;
|
|
13
|
+
reschedule(items: DurableQueueRescheduleInput[], now: number): Promise<void>;
|
|
14
|
+
deadLetter(items: DurableConnectorDeadLetterRecord[]): Promise<void>;
|
|
15
|
+
markSuccess(items: Array<{
|
|
16
|
+
connectorType: string;
|
|
17
|
+
connectorTarget?: string;
|
|
18
|
+
timestamp: number;
|
|
19
|
+
}>): Promise<void>;
|
|
20
|
+
markFailure(items: Array<{
|
|
21
|
+
connectorType: string;
|
|
22
|
+
connectorTarget?: string;
|
|
23
|
+
timestamp: number;
|
|
24
|
+
lastError?: string;
|
|
25
|
+
}>): Promise<void>;
|
|
26
|
+
getStatusSummary(): Promise<ConnectorDeliveryStatusRecord[]>;
|
|
27
|
+
listDeadLetters(input: {
|
|
28
|
+
limit: number;
|
|
29
|
+
offset: number;
|
|
30
|
+
connectorType?: string;
|
|
31
|
+
connectorTarget?: string;
|
|
32
|
+
}): Promise<DeadLetterListResult>;
|
|
33
|
+
retryDeadLetters(ids: string[], now: number): Promise<number>;
|
|
34
|
+
clearDeadLetters(ids: string[]): Promise<number>;
|
|
35
|
+
count(): Promise<number>;
|
|
36
|
+
shutdown(): Promise<void>;
|
|
37
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function buildSQLiteWorkerSource(): string;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ConnectorDeliveryStatusRecord, DeadLetterListResult } from './types';
|
|
2
|
+
export declare function getConnectorQueuePath(): string;
|
|
3
|
+
export declare function connectorQueueExists(queuePath?: string): boolean;
|
|
4
|
+
export declare function getConnectorDeliveryStatusSummary(queuePath?: string): Promise<ConnectorDeliveryStatusRecord[]>;
|
|
5
|
+
export declare function listConnectorDeadLetters(input?: {
|
|
6
|
+
limit?: number;
|
|
7
|
+
offset?: number;
|
|
8
|
+
connectorType?: string;
|
|
9
|
+
connectorTarget?: string;
|
|
10
|
+
}, queuePath?: string): Promise<DeadLetterListResult>;
|
|
11
|
+
export declare function retryConnectorDeadLetters(ids: string[], queuePath?: string): Promise<number>;
|
|
12
|
+
export declare function clearConnectorDeadLetters(ids: string[], queuePath?: string): Promise<number>;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { LogRecord } from '../../core/file-logger';
|
|
2
|
+
export declare const CONNECTOR_BATCH_DISPATCH: unique symbol;
|
|
3
|
+
export declare const CONNECTOR_DELIVERY_BINDER: unique symbol;
|
|
4
|
+
export type QueuedConnectorType = 'betterstack' | 'databuddy' | 'posthog' | 'sentry' | 'otlp';
|
|
5
|
+
export interface ConnectorDispatchContext {
|
|
6
|
+
source: 'server';
|
|
7
|
+
target?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ConnectorDispatchSuccess {
|
|
10
|
+
ok: true;
|
|
11
|
+
}
|
|
12
|
+
export interface ConnectorDispatchFailure {
|
|
13
|
+
ok: false;
|
|
14
|
+
retryable: boolean;
|
|
15
|
+
status?: number;
|
|
16
|
+
error?: string;
|
|
17
|
+
}
|
|
18
|
+
export type ConnectorDispatchResult = ConnectorDispatchSuccess | ConnectorDispatchFailure;
|
|
19
|
+
export interface ConnectorBatchDispatcher {
|
|
20
|
+
dispatchKey: string;
|
|
21
|
+
dispatch(records: LogRecord[], context: ConnectorDispatchContext): Promise<ConnectorDispatchResult>;
|
|
22
|
+
}
|
|
23
|
+
export interface ConnectorDeliveryJob {
|
|
24
|
+
id: string;
|
|
25
|
+
connectorType: QueuedConnectorType;
|
|
26
|
+
connectorTarget?: string;
|
|
27
|
+
source: 'server';
|
|
28
|
+
record: LogRecord;
|
|
29
|
+
attemptCount: number;
|
|
30
|
+
maxAttempts: number;
|
|
31
|
+
nextAttemptAt: number;
|
|
32
|
+
createdAt: number;
|
|
33
|
+
dispatchKey: string;
|
|
34
|
+
dispatcher: ConnectorBatchDispatcher;
|
|
35
|
+
}
|
|
36
|
+
export interface SerializedConnectorJobEnvelope {
|
|
37
|
+
jobId: string;
|
|
38
|
+
connectorType: QueuedConnectorType;
|
|
39
|
+
connectorTarget?: string;
|
|
40
|
+
source: 'server';
|
|
41
|
+
record: LogRecord;
|
|
42
|
+
createdAt: number;
|
|
43
|
+
}
|
|
44
|
+
export interface DurableConnectorJobRecord {
|
|
45
|
+
id: string;
|
|
46
|
+
connectorType: QueuedConnectorType;
|
|
47
|
+
connectorTarget?: string;
|
|
48
|
+
operation: 'send';
|
|
49
|
+
payloadJson: string;
|
|
50
|
+
attemptCount: number;
|
|
51
|
+
maxAttempts: number;
|
|
52
|
+
nextAttemptAt: number;
|
|
53
|
+
state: 'pending' | 'claimed';
|
|
54
|
+
lastError?: string;
|
|
55
|
+
createdAt: number;
|
|
56
|
+
updatedAt: number;
|
|
57
|
+
claimedAt?: number;
|
|
58
|
+
}
|
|
59
|
+
export interface DurableQueueRescheduleInput {
|
|
60
|
+
id: string;
|
|
61
|
+
attemptCount: number;
|
|
62
|
+
nextAttemptAt: number;
|
|
63
|
+
lastError?: string;
|
|
64
|
+
}
|
|
65
|
+
export interface DurableConnectorDeadLetterRecord {
|
|
66
|
+
id: string;
|
|
67
|
+
connectorType: QueuedConnectorType;
|
|
68
|
+
connectorTarget?: string;
|
|
69
|
+
operation: 'send';
|
|
70
|
+
payloadJson: string;
|
|
71
|
+
attemptCount: number;
|
|
72
|
+
maxAttempts: number;
|
|
73
|
+
lastError?: string;
|
|
74
|
+
firstEnqueuedAt: number;
|
|
75
|
+
deadLetteredAt: number;
|
|
76
|
+
lastAttemptAt: number;
|
|
77
|
+
}
|
|
78
|
+
export interface ConnectorDeliveryStatusRecord {
|
|
79
|
+
connectorType: QueuedConnectorType;
|
|
80
|
+
connectorTarget?: string;
|
|
81
|
+
pendingCount: number;
|
|
82
|
+
deadLetterCount: number;
|
|
83
|
+
lastSuccessAt?: number;
|
|
84
|
+
lastFailureAt?: number;
|
|
85
|
+
lastError?: string;
|
|
86
|
+
updatedAt?: number;
|
|
87
|
+
}
|
|
88
|
+
export interface DeadLetterListResult {
|
|
89
|
+
items: DurableConnectorDeadLetterRecord[];
|
|
90
|
+
total: number;
|
|
91
|
+
}
|
|
92
|
+
export interface ConnectorDeliveryBinder {
|
|
93
|
+
enqueue(connectorType: QueuedConnectorType, record: LogRecord, dispatcher: ConnectorBatchDispatcher, target?: string): void;
|
|
94
|
+
}
|
|
95
|
+
export type ConnectorBatchDispatchTarget = {
|
|
96
|
+
[CONNECTOR_BATCH_DISPATCH]?: ConnectorBatchDispatcher;
|
|
97
|
+
[CONNECTOR_DELIVERY_BINDER]?: (binder: ConnectorDeliveryBinder | null) => void;
|
|
98
|
+
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type StructuredLog } from '../../core/structured-log';
|
|
2
2
|
import type { OTLPLogger, OTLPLoggerConfig } from '../../types/connectors/otlp';
|
|
3
3
|
export type { OTLPLogger, OTLPLoggerConfig, } from '../../types/connectors/otlp';
|
|
4
|
+
export { normalizeOTLPRecord } from './sender';
|
|
4
5
|
export declare function createOtlpLogger(config?: OTLPLoggerConfig): OTLPLogger;
|
|
5
6
|
export declare function createStructuredOtlpLogger<TFields extends Record<string, unknown> = Record<string, unknown>>(groupId: string, initial?: TFields, config?: OTLPLoggerConfig): StructuredLog<TFields>;
|