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