@blyp/core 0.1.2

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