@blyp/core 0.1.21 → 0.1.23

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 (248) hide show
  1. package/README.md +54 -522
  2. package/STABILITY.md +56 -0
  3. package/dist/ai/anthropic/index.d.ts +3 -0
  4. package/dist/ai/anthropic/normalize.d.ts +9 -0
  5. package/dist/ai/anthropic/stream.d.ts +3 -0
  6. package/dist/ai/anthropic/wrap.d.ts +13 -0
  7. package/dist/ai/anthropic.js +701 -0
  8. package/dist/ai/anthropic.mjs +701 -0
  9. package/dist/ai/better-agent/index.d.ts +3 -0
  10. package/dist/ai/better-agent/normalize.d.ts +18 -0
  11. package/dist/ai/better-agent/plugin.d.ts +3 -0
  12. package/dist/ai/better-agent/tracker.d.ts +35 -0
  13. package/dist/ai/better-agent.js +701 -0
  14. package/dist/ai/better-agent.mjs +701 -0
  15. package/dist/ai/fetch.js +701 -0
  16. package/dist/ai/fetch.mjs +701 -0
  17. package/dist/ai/openai/index.d.ts +3 -0
  18. package/dist/ai/openai/normalize.d.ts +10 -0
  19. package/dist/ai/openai/stream.d.ts +3 -0
  20. package/dist/ai/openai/wrap.d.ts +24 -0
  21. package/dist/ai/openai.js +701 -0
  22. package/dist/ai/openai.mjs +701 -0
  23. package/dist/ai/shared/fetch.d.ts +5 -0
  24. package/dist/ai/shared/index.d.ts +2 -0
  25. package/dist/ai/shared/normalize.d.ts +17 -0
  26. package/dist/ai/shared/redaction.d.ts +6 -0
  27. package/dist/ai/shared/stream.d.ts +7 -0
  28. package/dist/ai/shared/trace.d.ts +119 -0
  29. package/dist/ai/shared/types.d.ts +171 -0
  30. package/dist/ai/shared.js +701 -0
  31. package/dist/ai/shared.mjs +701 -0
  32. package/dist/ai/vercel/index.d.ts +3 -0
  33. package/dist/ai/vercel/middleware.d.ts +3 -0
  34. package/dist/ai/vercel/model.d.ts +3 -0
  35. package/dist/ai/vercel.js +701 -0
  36. package/dist/ai/vercel.mjs +701 -0
  37. package/dist/astro.js +618 -4519
  38. package/dist/astro.mjs +618 -4491
  39. package/dist/client.js +1 -1139
  40. package/dist/client.mjs +1 -1132
  41. package/dist/connectors/betterstack.js +9 -1532
  42. package/dist/connectors/betterstack.mjs +9 -1507
  43. package/dist/connectors/databuddy.js +9 -1456
  44. package/dist/connectors/databuddy.mjs +9 -1451
  45. package/dist/connectors/delivery/backoff.d.ts +2 -0
  46. package/dist/connectors/delivery/manager.d.ts +44 -0
  47. package/dist/connectors/delivery/queue-path.d.ts +1 -0
  48. package/dist/connectors/delivery/sqlite-adapter-bun.d.ts +1 -0
  49. package/dist/connectors/delivery/sqlite-adapter-node.d.ts +1 -0
  50. package/dist/connectors/delivery/sqlite-client.d.ts +37 -0
  51. package/dist/connectors/delivery/sqlite-worker.d.ts +1 -0
  52. package/dist/connectors/delivery/studio-queue.d.ts +12 -0
  53. package/dist/connectors/delivery/types.d.ts +98 -0
  54. package/dist/connectors/otlp/index.d.ts +1 -0
  55. package/dist/connectors/otlp.js +9 -1371
  56. package/dist/connectors/otlp.mjs +9 -1368
  57. package/dist/connectors/posthog/properties.d.ts +4 -0
  58. package/dist/connectors/posthog/sender.d.ts +0 -1
  59. package/dist/connectors/posthog.js +10 -1527
  60. package/dist/connectors/posthog.mjs +10 -1522
  61. package/dist/connectors/sentry.js +9 -1380
  62. package/dist/connectors/sentry.mjs +9 -1357
  63. package/dist/core/config.d.ts +7 -2
  64. package/dist/core/log-record.d.ts +5 -4
  65. package/dist/core/logger.d.ts +2 -0
  66. package/dist/core/optional-module.d.ts +1 -0
  67. package/dist/core/pino-pretty-loader.d.ts +4 -0
  68. package/dist/database.js +1 -24
  69. package/dist/database.mjs +1 -21
  70. package/dist/elysia.js +613 -4517
  71. package/dist/elysia.mjs +615 -4491
  72. package/dist/expo.js +1 -726
  73. package/dist/expo.mjs +1 -724
  74. package/dist/express.js +613 -4507
  75. package/dist/express.mjs +615 -4480
  76. package/dist/fastify.js +615 -4526
  77. package/dist/fastify.mjs +617 -4499
  78. package/dist/frameworks/elysia/index.d.ts +1 -1
  79. package/dist/frameworks/elysia/logger.d.ts +2 -35
  80. package/dist/frameworks/nestjs/helpers.d.ts +2 -0
  81. package/dist/frameworks/shared/http.d.ts +3 -2
  82. package/dist/frameworks/shared/index.d.ts +2 -1
  83. package/dist/frameworks/shared/logger.d.ts +2 -0
  84. package/dist/frameworks/shared/request-context.d.ts +2 -0
  85. package/dist/frameworks/shared/trace.d.ts +6 -0
  86. package/dist/hono.js +616 -4496
  87. package/dist/hono.mjs +618 -4470
  88. package/dist/index.d.ts +49 -19
  89. package/dist/index.js +615 -7557
  90. package/dist/index.mjs +618 -7465
  91. package/dist/nestjs.js +626 -4999
  92. package/dist/nestjs.mjs +621 -4966
  93. package/dist/nextjs.js +618 -4525
  94. package/dist/nextjs.mjs +620 -4499
  95. package/dist/nitro.js +617 -4642
  96. package/dist/nitro.mjs +619 -4616
  97. package/dist/nuxt.js +617 -4649
  98. package/dist/nuxt.mjs +619 -4623
  99. package/dist/react-router.js +616 -4559
  100. package/dist/react-router.mjs +618 -4533
  101. package/dist/shared/redaction.d.ts +17 -0
  102. package/dist/standalone.js +606 -3628
  103. package/dist/standalone.mjs +610 -3603
  104. package/dist/sveltekit.js +617 -4523
  105. package/dist/sveltekit.mjs +619 -4497
  106. package/dist/tanstack-start.js +616 -4522
  107. package/dist/tanstack-start.mjs +618 -4496
  108. package/dist/types/core/config.d.ts +57 -0
  109. package/dist/types/core/logger.d.ts +3 -0
  110. package/dist/types/core/structured-log.d.ts +2 -0
  111. package/dist/types/database.d.ts +1 -0
  112. package/dist/types/frameworks/astro.d.ts +1 -0
  113. package/dist/types/frameworks/client.d.ts +2 -0
  114. package/dist/types/frameworks/elysia.d.ts +2 -0
  115. package/dist/types/frameworks/express.d.ts +1 -0
  116. package/dist/types/frameworks/fastify.d.ts +1 -0
  117. package/dist/types/frameworks/hono.d.ts +1 -0
  118. package/dist/types/frameworks/http.d.ts +1 -0
  119. package/dist/types/frameworks/nestjs.d.ts +2 -0
  120. package/dist/types/frameworks/nextjs.d.ts +1 -0
  121. package/dist/types/frameworks/nitro.d.ts +1 -0
  122. package/dist/types/frameworks/react-router.d.ts +2 -0
  123. package/dist/types/frameworks/request-context.d.ts +1 -0
  124. package/dist/types/frameworks/shared.d.ts +4 -1
  125. package/dist/types/frameworks/standalone.d.ts +3 -2
  126. package/dist/types/frameworks/sveltekit.d.ts +1 -0
  127. package/dist/types/frameworks/tanstack-start.d.ts +9 -3
  128. package/dist/types/frameworks/workers.d.ts +3 -0
  129. package/dist/types/shared/client-log.d.ts +1 -0
  130. package/dist/workers.js +2 -626
  131. package/dist/workers.mjs +2 -623
  132. package/package.json +259 -173
  133. package/dist/astro.js.map +0 -1
  134. package/dist/astro.mjs.map +0 -1
  135. package/dist/client.js.map +0 -1
  136. package/dist/client.mjs.map +0 -1
  137. package/dist/connectors/betterstack.js.map +0 -1
  138. package/dist/connectors/betterstack.mjs.map +0 -1
  139. package/dist/connectors/databuddy.js.map +0 -1
  140. package/dist/connectors/databuddy.mjs.map +0 -1
  141. package/dist/connectors/otlp.js.map +0 -1
  142. package/dist/connectors/otlp.mjs.map +0 -1
  143. package/dist/connectors/posthog.js.map +0 -1
  144. package/dist/connectors/posthog.mjs.map +0 -1
  145. package/dist/connectors/sentry.js.map +0 -1
  146. package/dist/connectors/sentry.mjs.map +0 -1
  147. package/dist/database.js.map +0 -1
  148. package/dist/database.mjs.map +0 -1
  149. package/dist/elysia.js.map +0 -1
  150. package/dist/elysia.mjs.map +0 -1
  151. package/dist/expo.js.map +0 -1
  152. package/dist/expo.mjs.map +0 -1
  153. package/dist/express.js.map +0 -1
  154. package/dist/express.mjs.map +0 -1
  155. package/dist/fastify.js.map +0 -1
  156. package/dist/fastify.mjs.map +0 -1
  157. package/dist/hono.js.map +0 -1
  158. package/dist/hono.mjs.map +0 -1
  159. package/dist/index.js.map +0 -1
  160. package/dist/index.mjs.map +0 -1
  161. package/dist/nestjs.js.map +0 -1
  162. package/dist/nestjs.mjs.map +0 -1
  163. package/dist/nextjs.js.map +0 -1
  164. package/dist/nextjs.mjs.map +0 -1
  165. package/dist/nitro.js.map +0 -1
  166. package/dist/nitro.mjs.map +0 -1
  167. package/dist/nuxt.js.map +0 -1
  168. package/dist/nuxt.mjs.map +0 -1
  169. package/dist/react-router.js.map +0 -1
  170. package/dist/react-router.mjs.map +0 -1
  171. package/dist/standalone.js.map +0 -1
  172. package/dist/standalone.mjs.map +0 -1
  173. package/dist/sveltekit.js.map +0 -1
  174. package/dist/sveltekit.mjs.map +0 -1
  175. package/dist/tanstack-start.js.map +0 -1
  176. package/dist/tanstack-start.mjs.map +0 -1
  177. package/dist/workers.js.map +0 -1
  178. package/dist/workers.mjs.map +0 -1
  179. package/exports/client.js +0 -3
  180. package/exports/client.mjs +0 -3
  181. package/exports/connectors/betterstack.js +0 -1
  182. package/exports/connectors/betterstack.mjs +0 -1
  183. package/exports/connectors/databuddy.js +0 -1
  184. package/exports/connectors/databuddy.mjs +0 -1
  185. package/exports/connectors/otlp.js +0 -1
  186. package/exports/connectors/otlp.mjs +0 -1
  187. package/exports/connectors/posthog.js +0 -1
  188. package/exports/connectors/posthog.mjs +0 -1
  189. package/exports/connectors/sentry.js +0 -1
  190. package/exports/connectors/sentry.mjs +0 -1
  191. package/exports/database.js +0 -1
  192. package/exports/database.mjs +0 -1
  193. package/exports/expo.js +0 -1
  194. package/exports/expo.mjs +0 -1
  195. package/exports/frameworks/astro.js +0 -1
  196. package/exports/frameworks/astro.mjs +0 -1
  197. package/exports/frameworks/elysia.js +0 -1
  198. package/exports/frameworks/elysia.mjs +0 -1
  199. package/exports/frameworks/express.js +0 -1
  200. package/exports/frameworks/express.mjs +0 -1
  201. package/exports/frameworks/fastify.js +0 -1
  202. package/exports/frameworks/fastify.mjs +0 -1
  203. package/exports/frameworks/hono.js +0 -1
  204. package/exports/frameworks/hono.mjs +0 -1
  205. package/exports/frameworks/nestjs.js +0 -1
  206. package/exports/frameworks/nestjs.mjs +0 -1
  207. package/exports/frameworks/nextjs.js +0 -1
  208. package/exports/frameworks/nextjs.mjs +0 -1
  209. package/exports/frameworks/nitro.js +0 -1
  210. package/exports/frameworks/nitro.mjs +0 -1
  211. package/exports/frameworks/nuxt.js +0 -1
  212. package/exports/frameworks/nuxt.mjs +0 -1
  213. package/exports/frameworks/react-router.js +0 -1
  214. package/exports/frameworks/react-router.mjs +0 -1
  215. package/exports/frameworks/standalone.js +0 -1
  216. package/exports/frameworks/standalone.mjs +0 -1
  217. package/exports/frameworks/sveltekit.js +0 -1
  218. package/exports/frameworks/sveltekit.mjs +0 -1
  219. package/exports/frameworks/tanstack-start.js +0 -1
  220. package/exports/frameworks/tanstack-start.mjs +0 -1
  221. package/exports/workers.js +0 -1
  222. package/exports/workers.mjs +0 -1
  223. package/types/client.d.ts +0 -34
  224. package/types/connectors/betterstack.d.ts +0 -1
  225. package/types/connectors/databuddy.d.ts +0 -1
  226. package/types/connectors/otlp.d.ts +0 -1
  227. package/types/connectors/posthog.d.ts +0 -1
  228. package/types/connectors/sentry.d.ts +0 -1
  229. package/types/database.d.ts +0 -1
  230. package/types/expo.d.ts +0 -17
  231. package/types/frameworks/astro.d.ts +0 -1
  232. package/types/frameworks/client.d.ts +0 -160
  233. package/types/frameworks/elysia.d.ts +0 -1
  234. package/types/frameworks/expo.d.ts +0 -50
  235. package/types/frameworks/express.d.ts +0 -1
  236. package/types/frameworks/fastify.d.ts +0 -1
  237. package/types/frameworks/hono.d.ts +0 -1
  238. package/types/frameworks/nestjs.d.ts +0 -1
  239. package/types/frameworks/nextjs.d.ts +0 -1
  240. package/types/frameworks/nitro.d.ts +0 -1
  241. package/types/frameworks/nuxt.d.ts +0 -1
  242. package/types/frameworks/react-router.d.ts +0 -1
  243. package/types/frameworks/standalone.d.ts +0 -1
  244. package/types/frameworks/sveltekit.d.ts +0 -1
  245. package/types/frameworks/tanstack-start.d.ts +0 -1
  246. package/types/frameworks/workers.d.ts +0 -115
  247. package/types/index.d.ts +0 -1
  248. package/types/workers.d.ts +0 -13
@@ -1,1507 +1,9 @@
1
- import { existsSync, readFileSync, writeFileSync, appendFileSync } from 'fs';
2
- import { createJiti } from 'jiti';
3
- import { resolve, dirname } from 'path';
4
- import { z } from 'zod';
5
- import * as Sentry from '@sentry/node';
6
- import { Logtail } from '@logtail/node';
7
- import 'fflate';
8
-
9
- // src/core/config.ts
10
-
11
- // src/shared/log-value.ts
12
- function normalizeError(error) {
13
- const normalized = {
14
- name: error.name,
15
- message: error.message
16
- };
17
- if (error.stack) {
18
- normalized.stack = error.stack;
19
- }
20
- const errorWithCause = error;
21
- if (errorWithCause.cause !== void 0) {
22
- normalized.cause = normalizeLogValue(errorWithCause.cause);
23
- }
24
- return normalized;
25
- }
26
- function normalizeLogValue(value, seen = /* @__PURE__ */ new WeakSet()) {
27
- if (value instanceof Error) {
28
- return normalizeError(value);
29
- }
30
- if (typeof value === "function") {
31
- return `[Function: ${value.name || "anonymous"}]`;
32
- }
33
- if (typeof value === "symbol") {
34
- return value.toString();
35
- }
36
- if (value === void 0 || value === null) {
37
- return value;
38
- }
39
- if (Array.isArray(value)) {
40
- return value.map((entry) => normalizeLogValue(entry, seen));
41
- }
42
- if (typeof value === "object") {
43
- if (seen.has(value)) {
44
- return "[Circular]";
45
- }
46
- seen.add(value);
47
- const normalized = {};
48
- for (const [key, entry] of Object.entries(value)) {
49
- normalized[key] = normalizeLogValue(entry, seen);
50
- }
51
- seen.delete(value);
52
- return normalized;
53
- }
54
- return value;
55
- }
56
- function serializeLogMessage(message) {
57
- if (typeof message === "string") {
58
- return message;
59
- }
60
- if (message instanceof Error) {
61
- return message.message || message.name;
62
- }
63
- const normalized = normalizeLogValue(message);
64
- if (typeof normalized === "string") {
65
- return normalized;
66
- }
67
- try {
68
- const serialized = JSON.stringify(normalized, null, 2);
69
- return serialized ?? String(normalized);
70
- } catch {
71
- return String(normalized);
72
- }
73
- }
74
- var absoluteHttpUrlSchema = z.string().url().refine((value) => {
75
- try {
76
- const url = new URL(value);
77
- return url.protocol === "http:" || url.protocol === "https:";
78
- } catch {
79
- return false;
80
- }
81
- }, {
82
- message: "Expected an absolute http(s) URL"
83
- });
84
- var plainObjectSchema = z.custom(
85
- (value) => {
86
- return value !== null && typeof value === "object" && !Array.isArray(value);
87
- },
88
- {
89
- message: "Expected a plain object"
90
- }
91
- );
92
- var nonEmptyStringSchema = z.string().trim().min(1);
93
- function isAbsoluteHttpUrl(value) {
94
- return absoluteHttpUrlSchema.safeParse(value).success;
95
- }
96
- function isPlainObject(value) {
97
- return plainObjectSchema.safeParse(value).success;
98
- }
99
- function hasNonEmptyString(value) {
100
- return nonEmptyStringSchema.safeParse(value).success;
101
- }
102
-
103
- // src/shared/client-log.ts
104
- var DEFAULT_CLIENT_LOG_ENDPOINT = "/inngest";
105
- z.union([
106
- z.literal("betterstack"),
107
- z.literal("databuddy"),
108
- z.literal("posthog"),
109
- z.literal("sentry"),
110
- z.undefined(),
111
- z.object({
112
- type: z.literal("otlp"),
113
- name: nonEmptyStringSchema
114
- })
115
- ]);
116
-
117
- // src/shared/once.ts
118
- function createConsoleOnceLogger(method, warnedKeys3 = /* @__PURE__ */ new Set()) {
119
- return (key, message, error) => {
120
- if (warnedKeys3.has(key) || typeof console === "undefined") {
121
- return;
122
- }
123
- const writer = console[method];
124
- if (typeof writer !== "function") {
125
- return;
126
- }
127
- warnedKeys3.add(key);
128
- if (error === void 0) {
129
- writer.call(console, message);
130
- return;
131
- }
132
- writer.call(console, message, error);
133
- };
134
- }
135
- function createWarnOnceLogger(warnedKeys3) {
136
- return createConsoleOnceLogger("warn", warnedKeys3);
137
- }
138
- function createErrorOnceLogger(warnedKeys3) {
139
- return createConsoleOnceLogger("error", warnedKeys3);
140
- }
141
-
142
- // src/core/config.ts
143
- var PACKAGE_NAME = "@blyp/core";
144
- var GITIGNORE_FILE_NAME = ".gitignore";
145
- var CONFIG_FILE_NAMES = [
146
- "blyp.config.ts",
147
- "blyp.config.mts",
148
- "blyp.config.cts",
149
- "blyp.config.js",
150
- "blyp.config.mjs",
151
- "blyp.config.cjs",
152
- "blyp.config.json"
153
- ];
154
- var CONFIG_FILE_NAME = "blyp.config.json";
155
- var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
156
- var DEFAULT_CONNECTOR_SERVICE_NAME = "blyp-app";
157
- var DEFAULT_POSTHOG_SERVICE_NAME = DEFAULT_CONNECTOR_SERVICE_NAME;
158
- var warnedKeys = /* @__PURE__ */ new Set();
159
- var warnOnce = createWarnOnceLogger(warnedKeys);
160
- var DEFAULT_ROTATION_CONFIG = {
161
- enabled: true,
162
- maxSizeBytes: 10 * 1024 * 1024,
163
- maxArchives: 5,
164
- compress: true
165
- };
166
- var DEFAULT_FILE_CONFIG = {
167
- enabled: true,
168
- dir: "",
169
- archiveDir: "",
170
- format: "ndjson",
171
- rotation: DEFAULT_ROTATION_CONFIG
172
- };
173
- var DEFAULT_CLIENT_LOGGING_CONFIG = {
174
- enabled: true,
175
- path: DEFAULT_CLIENT_LOG_ENDPOINT
176
- };
177
- var DEFAULT_DATABASE_RETRY_CONFIG = {
178
- maxRetries: 1,
179
- backoffMs: 100
180
- };
181
- var DEFAULT_DATABASE_DELIVERY_CONFIG = {
182
- strategy: "immediate",
183
- batchSize: 1,
184
- flushIntervalMs: 250,
185
- maxQueueSize: 1e3,
186
- overflowStrategy: "drop-oldest",
187
- flushTimeoutMs: 5e3,
188
- retry: DEFAULT_DATABASE_RETRY_CONFIG
189
- };
190
- var DEFAULT_CONFIG = {
191
- pretty: true,
192
- level: "info",
193
- destination: "file",
194
- file: DEFAULT_FILE_CONFIG,
195
- clientLogging: DEFAULT_CLIENT_LOGGING_CONFIG,
196
- connectors: {}
197
- };
198
- var cachedConfig = null;
199
- function findNearestPackageName(startDir) {
200
- let currentDir = startDir;
201
- while (true) {
202
- const packageJsonPath = resolve(currentDir, "package.json");
203
- if (existsSync(packageJsonPath)) {
204
- try {
205
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
206
- if (hasNonEmptyString(packageJson.name)) {
207
- return packageJson.name;
208
- }
209
- } catch {
210
- }
211
- }
212
- const parentDir = dirname(currentDir);
213
- if (parentDir === currentDir) {
214
- return void 0;
215
- }
216
- currentDir = parentDir;
217
- }
218
- }
219
- function resolveDefaultConnectorServiceName(cwd = process.cwd()) {
220
- return findNearestPackageName(cwd) ?? DEFAULT_POSTHOG_SERVICE_NAME;
221
- }
222
- function getBootstrapConfig() {
223
- return {
224
- pretty: true,
225
- level: "info",
226
- destination: "file",
227
- file: {
228
- enabled: true,
229
- format: "ndjson",
230
- rotation: {
231
- enabled: true,
232
- maxSizeBytes: 10 * 1024 * 1024,
233
- maxArchives: 5,
234
- compress: true
235
- }
236
- },
237
- clientLogging: {
238
- enabled: true,
239
- path: DEFAULT_CLIENT_LOG_ENDPOINT
240
- },
241
- connectors: {}
242
- };
243
- }
244
- function shouldBootstrapProjectFiles(cwd) {
245
- const packageJsonPath = resolve(cwd, "package.json");
246
- if (!existsSync(packageJsonPath)) {
247
- return true;
248
- }
249
- try {
250
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
251
- return packageJson.name !== PACKAGE_NAME;
252
- } catch {
253
- return true;
254
- }
255
- }
256
- function ensureConfigFile(cwd) {
257
- if (CONFIG_FILE_NAMES.some((fileName) => existsSync(resolve(cwd, fileName)))) {
258
- return;
259
- }
260
- const configPath = resolve(cwd, CONFIG_FILE_NAME);
261
- if (existsSync(configPath)) {
262
- return;
263
- }
264
- try {
265
- writeFileSync(configPath, `${JSON.stringify(getBootstrapConfig(), null, 2)}
266
- `);
267
- } catch (error) {
268
- console.error("[Blyp] Warning: Failed to create blyp.config.json:", error);
269
- }
270
- }
271
- function ensureLogsIgnored(cwd) {
272
- const gitignorePath = resolve(cwd, GITIGNORE_FILE_NAME);
273
- if (!existsSync(gitignorePath)) {
274
- try {
275
- writeFileSync(gitignorePath, "logs\n");
276
- } catch (error) {
277
- console.error("[Blyp] Warning: Failed to create .gitignore:", error);
278
- }
279
- return;
280
- }
281
- try {
282
- const currentContent = readFileSync(gitignorePath, "utf-8");
283
- if (/^(?:\/?logs\/?)\s*$/m.test(currentContent)) {
284
- return;
285
- }
286
- const separator = currentContent.endsWith("\n") ? "" : "\n";
287
- appendFileSync(gitignorePath, `${separator}logs
288
- `);
289
- } catch (error) {
290
- console.error("[Blyp] Warning: Failed to update .gitignore:", error);
291
- }
292
- }
293
- function bootstrapProjectFiles() {
294
- const cwd = process.cwd();
295
- if (!shouldBootstrapProjectFiles(cwd)) {
296
- return;
297
- }
298
- ensureConfigFile(cwd);
299
- ensureLogsIgnored(cwd);
300
- }
301
- function findConfigFile() {
302
- const cwd = process.cwd();
303
- const matches = CONFIG_FILE_NAMES.map((fileName) => resolve(cwd, fileName)).filter((filePath) => existsSync(filePath));
304
- if (matches.length === 0) {
305
- return null;
306
- }
307
- if (matches.length > 1) {
308
- const preferred = matches[0];
309
- warnOnce(
310
- `config-multiple:${preferred}`,
311
- `[Blyp] Warning: Multiple config files found. Using ${preferred} and ignoring ${matches.slice(1).join(", ")}.`
312
- );
313
- }
314
- const selectedPath = matches[0];
315
- return {
316
- path: selectedPath,
317
- type: selectedPath.endsWith(".json") ? "json" : "jiti"
318
- };
319
- }
320
- function normalizeLoadedConfig(value, configPath) {
321
- const normalized = value && typeof value === "object" && "default" in value && value.default !== void 0 ? value.default : value;
322
- if (!normalized || typeof normalized !== "object" || Array.isArray(normalized)) {
323
- warnOnce(
324
- `config-invalid:${configPath}`,
325
- `[Blyp] Warning: Config file ${configPath} did not export an object. Falling back to defaults.`
326
- );
327
- return {};
328
- }
329
- return normalized;
330
- }
331
- function parseJsonConfigFile(configPath) {
332
- try {
333
- const content = readFileSync(configPath, "utf-8");
334
- return normalizeLoadedConfig(JSON.parse(content), configPath);
335
- } catch (error) {
336
- console.error("[Blyp] Warning: Failed to parse blyp.config.json:", error);
337
- return {};
338
- }
339
- }
340
- function parseExecutableConfigFile(configPath) {
341
- try {
342
- const jiti = createJiti(process.cwd(), {
343
- interopDefault: true,
344
- moduleCache: false,
345
- fsCache: false
346
- });
347
- return normalizeLoadedConfig(jiti(configPath), configPath);
348
- } catch (error) {
349
- console.error(`[Blyp] Warning: Failed to load ${configPath}:`, error);
350
- return {};
351
- }
352
- }
353
- function parseConfigFile(config) {
354
- return config.type === "json" ? parseJsonConfigFile(config.path) : parseExecutableConfigFile(config.path);
355
- }
356
- function isPrismaAdapter(value) {
357
- return !!value && typeof value === "object" && value.type === "prisma";
358
- }
359
- function isDrizzleAdapter(value) {
360
- return !!value && typeof value === "object" && value.type === "drizzle";
361
- }
362
- function mergeDatabaseRetryConfig(base, override) {
363
- return {
364
- ...DEFAULT_DATABASE_RETRY_CONFIG,
365
- ...base,
366
- ...override
367
- };
368
- }
369
- function mergeDatabaseDeliveryConfig(base, override) {
370
- return {
371
- ...DEFAULT_DATABASE_DELIVERY_CONFIG,
372
- ...base,
373
- ...override,
374
- retry: mergeDatabaseRetryConfig(base?.retry, override?.retry)
375
- };
376
- }
377
- function hasPrismaDelegate(adapter) {
378
- const model = adapter.model ?? "blypLog";
379
- const client = adapter.client;
380
- const delegate = client?.[model];
381
- return !!delegate && typeof delegate.create === "function";
382
- }
383
- function hasDrizzleAdapterShape(adapter) {
384
- const db = adapter.db;
385
- return !!db && typeof db.insert === "function" && adapter.table !== void 0;
386
- }
387
- function resolveDatabaseLoggerConfig(config, sourceType) {
388
- if (!config) {
389
- return void 0;
390
- }
391
- const adapter = config.adapter;
392
- let ready = false;
393
- if (sourceType === "json") {
394
- warnOnce(
395
- "database-json-config",
396
- "[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."
397
- );
398
- } else if (config.dialect !== "postgres" && config.dialect !== "mysql") {
399
- warnOnce(
400
- `database-dialect:${String(config.dialect)}`,
401
- `[Blyp] Warning: Unsupported database dialect "${String(config.dialect)}". Database logging is disabled.`
402
- );
403
- } else if (!adapter) {
404
- warnOnce(
405
- "database-adapter-missing",
406
- "[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled."
407
- );
408
- } else if (isPrismaAdapter(adapter)) {
409
- ready = hasPrismaDelegate({
410
- ...adapter,
411
- model: adapter.model ?? "blypLog"
412
- });
413
- if (!ready) {
414
- warnOnce(
415
- "database-prisma-missing",
416
- `[Blyp] Warning: Prisma database adapter is missing the "${adapter.model ?? "blypLog"}" delegate or its create method. Database logging is disabled.`
417
- );
418
- }
419
- } else if (isDrizzleAdapter(adapter)) {
420
- ready = hasDrizzleAdapterShape(adapter);
421
- if (!ready) {
422
- warnOnce(
423
- "database-drizzle-missing",
424
- "[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled."
425
- );
426
- }
427
- }
428
- const normalizedAdapter = isPrismaAdapter(adapter) ? {
429
- ...adapter,
430
- model: adapter.model ?? "blypLog"
431
- } : adapter;
432
- return {
433
- dialect: config.dialect,
434
- adapter: normalizedAdapter,
435
- delivery: mergeDatabaseDeliveryConfig(void 0, config.delivery),
436
- ready,
437
- status: ready ? "enabled" : "missing"
438
- };
439
- }
440
- function mergeRotationConfig(base, override) {
441
- return {
442
- ...DEFAULT_ROTATION_CONFIG,
443
- ...base,
444
- ...override
445
- };
446
- }
447
- function mergeFileConfig(base, override) {
448
- return {
449
- ...DEFAULT_FILE_CONFIG,
450
- ...base,
451
- ...override,
452
- rotation: mergeRotationConfig(base?.rotation, override?.rotation)
453
- };
454
- }
455
- function mergeClientLoggingConfig(base, override) {
456
- return {
457
- ...DEFAULT_CLIENT_LOGGING_CONFIG,
458
- ...base,
459
- ...override,
460
- path: override?.path ?? base?.path ?? DEFAULT_CLIENT_LOGGING_CONFIG.path
461
- };
462
- }
463
- function mergeDatabaseLoggerConfig(base, override, sourceType) {
464
- if (!base && !override) {
465
- return void 0;
466
- }
467
- return resolveDatabaseLoggerConfig(
468
- {
469
- dialect: override?.dialect ?? base?.dialect,
470
- adapter: override?.adapter ?? base?.adapter,
471
- delivery: {
472
- ...base?.delivery ?? {},
473
- ...override?.delivery ?? {},
474
- retry: {
475
- ...base?.delivery?.retry ?? {},
476
- ...override?.delivery?.retry ?? {}
477
- }
478
- }
479
- },
480
- sourceType
481
- );
482
- }
483
- function mergePostHogConnectorConfig(base, override) {
484
- const enabled = override?.enabled ?? base?.enabled ?? false;
485
- const projectKey = override?.projectKey ?? base?.projectKey;
486
- const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
487
- const errorTrackingMode = override?.errorTracking?.mode ?? baseErrorTracking?.mode ?? "auto";
488
- const errorTrackingEnabled = override?.errorTracking?.enabled ?? baseErrorTracking?.enabled ?? enabled;
489
- const errorTrackingReady = enabled && errorTrackingEnabled && typeof projectKey === "string" && projectKey.trim().length > 0;
490
- return {
491
- enabled,
492
- mode: override?.mode ?? base?.mode ?? "auto",
493
- projectKey,
494
- host: override?.host ?? base?.host ?? DEFAULT_POSTHOG_HOST,
495
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
496
- errorTracking: {
497
- enabled: errorTrackingEnabled,
498
- mode: errorTrackingMode,
499
- enableExceptionAutocapture: override?.errorTracking?.enableExceptionAutocapture ?? baseErrorTracking?.enableExceptionAutocapture ?? errorTrackingMode === "auto",
500
- ready: errorTrackingReady,
501
- status: errorTrackingReady ? "enabled" : "missing"
502
- }
503
- };
504
- }
505
- function mergeDatabuddyConnectorConfig(base, override) {
506
- const enabled = override?.enabled ?? base?.enabled ?? false;
507
- const apiKey = override?.apiKey ?? base?.apiKey;
508
- const websiteId = override?.websiteId ?? base?.websiteId;
509
- const ready = enabled && hasNonEmptyString(apiKey) && hasNonEmptyString(websiteId);
510
- return {
511
- enabled,
512
- mode: override?.mode ?? base?.mode ?? "auto",
513
- apiKey,
514
- websiteId,
515
- namespace: override?.namespace ?? base?.namespace,
516
- source: override?.source ?? base?.source,
517
- apiUrl: override?.apiUrl ?? base?.apiUrl,
518
- debug: override?.debug ?? base?.debug ?? false,
519
- enableBatching: override?.enableBatching ?? base?.enableBatching ?? true,
520
- batchSize: override?.batchSize ?? base?.batchSize,
521
- batchTimeout: override?.batchTimeout ?? base?.batchTimeout,
522
- maxQueueSize: override?.maxQueueSize ?? base?.maxQueueSize,
523
- ready,
524
- status: ready ? "enabled" : "missing"
525
- };
526
- }
527
- function mergeBetterStackConnectorConfig(base, override) {
528
- const sourceToken = override?.sourceToken ?? base?.sourceToken;
529
- const ingestingHost = override?.ingestingHost ?? base?.ingestingHost;
530
- const enabled = override?.enabled ?? base?.enabled ?? false;
531
- const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
532
- const errorTracking = mergeBetterStackErrorTrackingConfig(
533
- enabled,
534
- baseErrorTracking,
535
- override?.errorTracking
536
- );
537
- const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
538
- return {
539
- enabled,
540
- mode: override?.mode ?? base?.mode ?? "auto",
541
- sourceToken,
542
- ingestingHost,
543
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
544
- errorTracking,
545
- ready,
546
- status: ready ? "enabled" : "missing"
547
- };
548
- }
549
- function mergeBetterStackErrorTrackingConfig(connectorEnabled, base, override) {
550
- const dsn = override?.dsn ?? base?.dsn;
551
- const enabled = override?.enabled ?? base?.enabled ?? connectorEnabled;
552
- const ready = enabled && hasNonEmptyString(dsn);
553
- return {
554
- enabled,
555
- dsn,
556
- tracesSampleRate: override?.tracesSampleRate ?? base?.tracesSampleRate ?? 1,
557
- environment: override?.environment ?? base?.environment,
558
- release: override?.release ?? base?.release,
559
- ready,
560
- status: ready ? "enabled" : "missing"
561
- };
562
- }
563
- function mergeSentryConnectorConfig(base, override) {
564
- const dsn = override?.dsn ?? base?.dsn;
565
- const enabled = override?.enabled ?? base?.enabled ?? false;
566
- const ready = enabled && typeof dsn === "string" && dsn.trim().length > 0;
567
- return {
568
- enabled,
569
- mode: override?.mode ?? base?.mode ?? "auto",
570
- dsn,
571
- environment: override?.environment ?? base?.environment,
572
- release: override?.release ?? base?.release,
573
- ready,
574
- status: ready ? "enabled" : "missing"
575
- };
576
- }
577
- function mergeOTLPConnectorConfig(base, override) {
578
- const endpoint = override?.endpoint ?? base?.endpoint;
579
- const enabled = override?.enabled ?? base?.enabled ?? false;
580
- const resolvedHeaders = {
581
- ...{},
582
- ...override?.headers ?? {}
583
- };
584
- const ready = enabled && isAbsoluteHttpUrl(endpoint);
585
- return {
586
- name: override?.name ?? base?.name ?? "",
587
- enabled,
588
- mode: override?.mode ?? base?.mode ?? "auto",
589
- endpoint,
590
- headers: resolvedHeaders,
591
- auth: override?.auth ?? base?.auth,
592
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
593
- ready,
594
- status: ready ? "enabled" : "missing"
595
- };
596
- }
597
- function mergeOTLPConnectorsConfig(base, override) {
598
- const source = override ?? base ?? [];
599
- const deduped = /* @__PURE__ */ new Map();
600
- for (const connector of source) {
601
- if (!connector || typeof connector.name !== "string" || connector.name.length === 0) {
602
- continue;
603
- }
604
- if (deduped.has(connector.name)) {
605
- warnOnce(
606
- `otlp-duplicate:${connector.name}`,
607
- `[Blyp] Warning: Duplicate OTLP connector name "${connector.name}" found. Using the last definition.`
608
- );
609
- }
610
- deduped.set(connector.name, mergeOTLPConnectorConfig(void 0, connector));
611
- }
612
- return Array.from(deduped.values());
613
- }
614
- function mergeConnectorsConfig(base, override) {
615
- return {
616
- betterstack: mergeBetterStackConnectorConfig(base?.betterstack, override?.betterstack),
617
- databuddy: mergeDatabuddyConnectorConfig(base?.databuddy, override?.databuddy),
618
- posthog: mergePostHogConnectorConfig(base?.posthog, override?.posthog),
619
- sentry: mergeSentryConnectorConfig(base?.sentry, override?.sentry),
620
- otlp: mergeOTLPConnectorsConfig(base?.otlp, override?.otlp)
621
- };
622
- }
623
- function mergeBlypConfig(base, override = {}, options = {}) {
624
- return {
625
- ...base,
626
- ...override,
627
- destination: override.destination ?? base.destination ?? "file",
628
- file: mergeFileConfig(base.file, override.file),
629
- database: mergeDatabaseLoggerConfig(base.database, override.database, options.configFileType),
630
- clientLogging: mergeClientLoggingConfig(base.clientLogging, override.clientLogging),
631
- connectors: mergeConnectorsConfig(base.connectors, override.connectors)
632
- };
633
- }
634
- function loadConfig() {
635
- if (cachedConfig !== null) {
636
- return cachedConfig;
637
- }
638
- bootstrapProjectFiles();
639
- const configFile = findConfigFile();
640
- if (configFile) {
641
- const userConfig = parseConfigFile(configFile);
642
- cachedConfig = mergeBlypConfig(DEFAULT_CONFIG, userConfig, {
643
- configFileType: configFile.type
644
- });
645
- } else {
646
- cachedConfig = mergeBlypConfig(DEFAULT_CONFIG);
647
- }
648
- return cachedConfig;
649
- }
650
- function resolveConfig(overrides = {}) {
651
- return mergeBlypConfig(loadConfig(), overrides);
652
- }
653
-
654
- // src/core/log-record.ts
655
- var RECORD_LEVELS = {
656
- success: "success",
657
- critical: "critical",
658
- warning: "warning",
659
- info: "info",
660
- debug: "debug",
661
- error: "error",
662
- warn: "warning",
663
- table: "table"
664
- };
665
- function normalizePath(filePath) {
666
- return filePath.replace(/\\/g, "/");
667
- }
668
- function isInternalLoggerFrame(filePath) {
669
- const normalizedPath = normalizePath(filePath);
670
- 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/");
671
- }
672
- function formatCallerPath(filePath) {
673
- const normalizedPath = normalizePath(filePath);
674
- const normalizedCwd = normalizePath(process.cwd());
675
- return normalizedPath.startsWith(`${normalizedCwd}/`) ? normalizedPath.slice(normalizedCwd.length + 1) : normalizedPath;
676
- }
677
- function getCallerLocation() {
678
- try {
679
- const stack = new Error().stack;
680
- if (!stack) {
681
- return { file: null, line: null };
682
- }
683
- const lines = stack.split("\n");
684
- let fallback = null;
685
- for (let index = 2; index < lines.length; index += 1) {
686
- const line = lines[index];
687
- if (!line) {
688
- continue;
689
- }
690
- const match = line.match(/\((.*):(\d+):\d+\)/) || line.match(/at\s+(.*):(\d+):(\d+)/);
691
- if (!match) {
692
- continue;
693
- }
694
- const fileName = match[1] || "";
695
- const lineNumber = parseInt(match[2] || "0", 10) || null;
696
- if (fileName && !fileName.includes("node_modules") && !isInternalLoggerFrame(fileName)) {
697
- const formattedPath = formatCallerPath(fileName);
698
- const normalizedFormattedPath = normalizePath(formattedPath);
699
- if (!normalizedFormattedPath.startsWith("dist/")) {
700
- return { file: formattedPath, line: lineNumber };
701
- }
702
- fallback ?? (fallback = { file: formattedPath, line: lineNumber });
703
- }
704
- }
705
- if (fallback) {
706
- return fallback;
707
- }
708
- } catch {
709
- return { file: null, line: null };
710
- }
711
- return { file: null, line: null };
712
- }
713
- var serializeMessage = serializeLogMessage;
714
- function stripAnsi(value) {
715
- return value.replace(/\u001b\[[0-9;]*m/g, "");
716
- }
717
- function buildRecord(level, message, args, bindings) {
718
- const { file, line } = getCallerLocation();
719
- const serializedMessage = serializeMessage(message);
720
- const record = {
721
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
722
- level: RECORD_LEVELS[level],
723
- message: stripAnsi(serializedMessage)
724
- };
725
- if (message instanceof Error) {
726
- record.error = normalizeError(message);
727
- }
728
- if (file) {
729
- record.caller = line !== null ? `${file}:${line}` : file;
730
- }
731
- if (args.length === 1) {
732
- record.data = normalizeLogValue(args[0]);
733
- } else if (args.length > 1) {
734
- record.data = normalizeLogValue(args);
735
- }
736
- if (Object.keys(bindings).length > 0) {
737
- record.bindings = normalizeLogValue(bindings);
738
- }
739
- return record;
740
- }
741
- function buildStructuredRecord(level, message, payload, bindings) {
742
- const { file, line } = getCallerLocation();
743
- const normalizedPayload = normalizeLogValue(payload);
744
- const record = {
745
- message: stripAnsi(message),
746
- ...normalizedPayload
747
- };
748
- if (file) {
749
- record.caller = line !== null ? `${file}:${line}` : file;
750
- }
751
- if (Object.keys(bindings).length > 0) {
752
- record.bindings = normalizeLogValue(bindings);
753
- }
754
- record.level = typeof normalizedPayload.level === "string" && normalizedPayload.level.length > 0 ? normalizedPayload.level : RECORD_LEVELS[level];
755
- record.timestamp = typeof normalizedPayload.timestamp === "string" && normalizedPayload.timestamp.length > 0 ? normalizedPayload.timestamp : (/* @__PURE__ */ new Date()).toISOString();
756
- return record;
757
- }
758
- function resolveStructuredWriteLevel(level) {
759
- switch (level) {
760
- case "debug":
761
- return "debug";
762
- case "warning":
763
- return "warning";
764
- case "warn":
765
- return "warn";
766
- case "error":
767
- return "error";
768
- case "success":
769
- return "success";
770
- case "critical":
771
- return "critical";
772
- case "table":
773
- return "table";
774
- case "info":
775
- default:
776
- return "info";
777
- }
778
- }
779
-
780
- // src/core/structured-log.ts
781
- function serializeMessage2(message) {
782
- if (typeof message === "string") {
783
- return message;
784
- }
785
- if (message !== null && typeof message === "object") {
786
- try {
787
- return JSON.stringify(
788
- message,
789
- (_key, value) => {
790
- if (typeof value === "function") {
791
- return `[Function: ${value.name || "anonymous"}]`;
792
- }
793
- if (value === void 0) {
794
- return "[undefined]";
795
- }
796
- if (typeof value === "symbol") {
797
- return value.toString();
798
- }
799
- return value;
800
- },
801
- 2
802
- );
803
- } catch {
804
- return "[Object]";
805
- }
806
- }
807
- return String(message);
808
- }
809
- function normalizeEventData(message, args) {
810
- if (typeof message === "string") {
811
- if (args.length === 0) {
812
- return void 0;
813
- }
814
- return args.length === 1 ? args[0] : args;
815
- }
816
- const values = [message, ...args];
817
- return values.length === 1 ? values[0] : values;
818
- }
819
- function normalizeDetails(value) {
820
- if (!value || typeof value !== "object" || Array.isArray(value)) {
821
- return void 0;
822
- }
823
- return value;
824
- }
825
- function normalizeError2(error, fallbackStatus) {
826
- if (error === void 0 || error === null) {
827
- return fallbackStatus === void 0 || fallbackStatus < 400 ? void 0 : {
828
- message: `HTTP ${fallbackStatus}`,
829
- code: fallbackStatus,
830
- type: "HttpError"
831
- };
832
- }
833
- if (error instanceof Error) {
834
- const errorLike = error;
835
- return {
836
- message: error.message,
837
- code: errorLike.code,
838
- type: errorLike.type ?? error.name ?? error.constructor?.name,
839
- stack: error.stack,
840
- why: errorLike.why,
841
- fix: errorLike.fix,
842
- link: errorLike.link,
843
- details: normalizeDetails(errorLike.details),
844
- cause: errorLike.cause
845
- };
846
- }
847
- if (typeof error === "object") {
848
- const record = error;
849
- const statusCode = typeof record.statusCode === "number" ? record.statusCode : typeof record.status === "number" ? record.status : fallbackStatus;
850
- return {
851
- message: typeof record.message === "string" ? record.message : `HTTP ${statusCode ?? 500}`,
852
- code: typeof record.code === "string" || typeof record.code === "number" ? record.code : statusCode,
853
- type: typeof record.type === "string" ? record.type : typeof record.name === "string" ? record.name : "Error",
854
- stack: typeof record.stack === "string" ? record.stack : void 0,
855
- why: typeof record.why === "string" ? record.why : void 0,
856
- fix: typeof record.fix === "string" ? record.fix : void 0,
857
- link: typeof record.link === "string" ? record.link : void 0,
858
- details: normalizeDetails(record.details),
859
- cause: record.cause
860
- };
861
- }
862
- return {
863
- message: String(error),
864
- code: fallbackStatus,
865
- type: typeof error
866
- };
867
- }
868
- function resolveEmitStatus(options) {
869
- if (options.response && typeof options.response.status === "number") {
870
- return options.response.status;
871
- }
872
- if (typeof options.status === "number") {
873
- return options.status;
874
- }
875
- if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.statusCode === "number") {
876
- return options.error.statusCode;
877
- }
878
- if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.status === "number") {
879
- return options.error.status;
880
- }
881
- return options.error ? 500 : void 0;
882
- }
883
- function createStructuredLog(groupId, options) {
884
- const startedAt = performance.now();
885
- const fields = { ...options.initialFields ?? {} };
886
- const events = [];
887
- let emittedPayload;
888
- options.onCreate?.();
889
- const appendEvent = (level, message, args) => {
890
- events.push({
891
- level,
892
- message: serializeMessage2(message),
893
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
894
- ...normalizeEventData(message, args) === void 0 ? {} : { data: normalizeEventData(message, args) }
895
- });
896
- return structuredLog;
897
- };
898
- const structuredLog = {
899
- set(extraFields) {
900
- Object.assign(fields, extraFields);
901
- return structuredLog;
902
- },
903
- debug(message, ...args) {
904
- return appendEvent("debug", message, args);
905
- },
906
- info(message, ...args) {
907
- return appendEvent("info", message, args);
908
- },
909
- warn(message, ...args) {
910
- return appendEvent("warn", message, args);
911
- },
912
- warning(message, ...args) {
913
- return appendEvent("warning", message, args);
914
- },
915
- error(message, ...args) {
916
- return appendEvent("error", message, args);
917
- },
918
- success(message, ...args) {
919
- return appendEvent("success", message, args);
920
- },
921
- critical(message, ...args) {
922
- return appendEvent("critical", message, args);
923
- },
924
- table(message, data) {
925
- return appendEvent("table", message, data === void 0 ? [] : [data]);
926
- },
927
- emit(emitOptions = {}) {
928
- if (emittedPayload) {
929
- return emittedPayload;
930
- }
931
- const defaultFields = options.resolveDefaultFields?.() ?? {};
932
- const status = resolveEmitStatus(emitOptions);
933
- const error = normalizeError2(emitOptions.error, status);
934
- const level = emitOptions.level ?? (error ? "error" : "info");
935
- const payload = {
936
- ...defaultFields,
937
- ...fields,
938
- groupId,
939
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
940
- level,
941
- duration: Math.round(performance.now() - startedAt),
942
- ...typeof status === "number" ? { status } : {},
943
- ...events.length > 0 ? { events: [...events] } : {},
944
- ...error ? { error } : {}
945
- };
946
- options.write(payload, emitOptions.message ?? "structured_log");
947
- emittedPayload = payload;
948
- options.onEmit?.(payload);
949
- return payload;
950
- }
951
- };
952
- return structuredLog;
953
- }
954
- function createSafeReplacer() {
955
- const seen = /* @__PURE__ */ new WeakSet();
956
- return (_key, value) => {
957
- if (typeof value === "function") {
958
- return `[Function: ${value.name || "anonymous"}]`;
959
- }
960
- if (value === void 0) {
961
- return "[undefined]";
962
- }
963
- if (typeof value === "symbol") {
964
- return value.toString();
965
- }
966
- if (value !== null && typeof value === "object") {
967
- if (seen.has(value)) {
968
- return "[Circular]";
969
- }
970
- seen.add(value);
971
- }
972
- return value;
973
- };
974
- }
975
- function serializeLogRecord(record) {
976
- return JSON.stringify(record, createSafeReplacer());
977
- }
978
-
979
- // src/connectors/shared.ts
980
- function isBlypConfig(config) {
981
- return isPlainObject(config) && ("connectors" in config || "pretty" in config || "level" in config);
982
- }
983
- function getPrimaryPayload(record) {
984
- return isPlainObject(record.data) ? record.data : record;
985
- }
986
- function getField(record, key) {
987
- if (key in record) {
988
- const direct = record[key];
989
- if (typeof direct === "string" || typeof direct === "number") {
990
- return direct;
991
- }
992
- }
993
- const payload = getPrimaryPayload(record);
994
- const nested = payload[key];
995
- if (typeof nested === "string" || typeof nested === "number") {
996
- return nested;
997
- }
998
- return void 0;
999
- }
1000
- function getClientPageField(record, key) {
1001
- const payload = getPrimaryPayload(record);
1002
- const page = isPlainObject(payload.page) ? payload.page : void 0;
1003
- const value = page?.[key];
1004
- return typeof value === "string" ? value : void 0;
1005
- }
1006
- function getClientSessionField(record, key) {
1007
- const payload = getPrimaryPayload(record);
1008
- const session = isPlainObject(payload.session) ? payload.session : void 0;
1009
- const value = session?.[key];
1010
- return typeof value === "string" ? value : void 0;
1011
- }
1012
- function getRecordType(record) {
1013
- return getField(record, "type");
1014
- }
1015
-
1016
- // src/connectors/betterstack/sender.ts
1017
- var PREVIOUSLY_CAPTURED_ERROR_KEY = "__betterstack_previously_captured_error";
1018
- var warnedKeys2 = /* @__PURE__ */ new Set();
1019
- var testHooks = {};
1020
- var warnOnce2 = createErrorOnceLogger(warnedKeys2);
1021
- function getSentryModule() {
1022
- return testHooks.module ?? Sentry;
1023
- }
1024
- function resolveConnectorConfig(config) {
1025
- const connector = isBlypConfig(config) ? config.connectors?.betterstack : config;
1026
- const enabled = connector?.enabled ?? false;
1027
- const sourceToken = connector?.sourceToken;
1028
- const ingestingHost = connector?.ingestingHost;
1029
- const errorTrackingEnabled = connector?.errorTracking?.enabled ?? enabled;
1030
- const errorTrackingDsn = connector?.errorTracking?.dsn;
1031
- const errorTrackingReady = enabled && errorTrackingEnabled && hasNonEmptyString(errorTrackingDsn);
1032
- const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
1033
- return {
1034
- enabled,
1035
- mode: connector?.mode ?? "auto",
1036
- sourceToken,
1037
- ingestingHost,
1038
- serviceName: connector?.serviceName ?? "blyp-app",
1039
- errorTracking: {
1040
- enabled: errorTrackingEnabled,
1041
- dsn: errorTrackingDsn,
1042
- tracesSampleRate: connector?.errorTracking?.tracesSampleRate ?? 1,
1043
- environment: connector?.errorTracking?.environment,
1044
- release: connector?.errorTracking?.release,
1045
- ready: errorTrackingReady,
1046
- status: errorTrackingReady ? "enabled" : "missing"
1047
- },
1048
- ready,
1049
- status: ready ? "enabled" : "missing"
1050
- };
1051
- }
1052
- function resolveBetterStackLevel(level) {
1053
- switch (level) {
1054
- case "debug":
1055
- return "debug";
1056
- case "warning":
1057
- case "warn":
1058
- return "warn";
1059
- case "error":
1060
- return "error";
1061
- case "critical":
1062
- return "fatal";
1063
- case "success":
1064
- case "table":
1065
- case "info":
1066
- default:
1067
- return "info";
1068
- }
1069
- }
1070
- function parseCaller(caller) {
1071
- if (typeof caller !== "string" || caller.trim().length === 0) {
1072
- return {};
1073
- }
1074
- const match = caller.match(/^(.*):(\d+)$/);
1075
- if (!match) {
1076
- return {};
1077
- }
1078
- const file = match[1]?.trim();
1079
- const line = Number.parseInt(match[2] ?? "", 10);
1080
- return {
1081
- ...file ? { file } : {},
1082
- ...Number.isFinite(line) ? { line } : {}
1083
- };
1084
- }
1085
- function buildContext(record, connector, source) {
1086
- const recordType = getRecordType(record);
1087
- const groupId = getField(record, "groupId");
1088
- const method = getField(record, "method");
1089
- const path = getField(record, "path");
1090
- const status = getField(record, "status");
1091
- const duration = getField(record, "duration");
1092
- const pagePath = getClientPageField(record, "pathname");
1093
- const pageUrl = getClientPageField(record, "url");
1094
- const sessionId = getClientSessionField(record, "sessionId");
1095
- const pageId = getClientSessionField(record, "pageId");
1096
- const runtime = parseCaller(record.caller);
1097
- return {
1098
- service: connector.serviceName,
1099
- context: {
1100
- blyp: {
1101
- level: record.level,
1102
- source,
1103
- ...recordType ? { type: recordType } : {},
1104
- ...groupId ? { group_id: groupId } : {},
1105
- ...record.caller ? { caller: record.caller } : {},
1106
- ...duration !== void 0 ? { duration_ms: duration } : {},
1107
- ...record.bindings ? { bindings: record.bindings } : {},
1108
- payload: serializeLogRecord(record)
1109
- },
1110
- ...method || path || status !== void 0 ? {
1111
- http: {
1112
- ...method ? { method } : {},
1113
- ...path ? { path } : {},
1114
- ...status !== void 0 ? { status_code: status } : {}
1115
- }
1116
- } : {},
1117
- ...pagePath || pageUrl || sessionId || pageId ? {
1118
- client: {
1119
- ...pagePath ? { page_path: pagePath } : {},
1120
- ...pageUrl ? { page_url: pageUrl } : {},
1121
- ...sessionId ? { session_id: sessionId } : {},
1122
- ...pageId ? { page_id: pageId } : {}
1123
- }
1124
- } : {},
1125
- ...Object.keys(runtime).length > 0 ? { runtime } : {},
1126
- ...record.data !== void 0 ? { data: record.data } : {},
1127
- ...record.error !== void 0 ? { error: record.error } : {}
1128
- }
1129
- };
1130
- }
1131
- function toExceptionCandidate(value) {
1132
- if (!isPlainObject(value)) {
1133
- return void 0;
1134
- }
1135
- const message = typeof value.message === "string" ? value.message : void 0;
1136
- const name = typeof value.name === "string" ? value.name : void 0;
1137
- const stack = typeof value.stack === "string" ? value.stack : void 0;
1138
- if (!message && !name && !stack) {
1139
- return void 0;
1140
- }
1141
- const error = new Error(message ?? name ?? "Unknown error");
1142
- error.name = name ?? "Error";
1143
- if (stack) {
1144
- error.stack = stack;
1145
- }
1146
- for (const [key, entry] of Object.entries(value)) {
1147
- if (key === "message" || key === "name" || key === "stack") {
1148
- continue;
1149
- }
1150
- error[key] = entry;
1151
- }
1152
- return error;
1153
- }
1154
- function normalizeScopeLevel(level) {
1155
- switch (level) {
1156
- case "debug":
1157
- return "debug";
1158
- case "warning":
1159
- case "warn":
1160
- return "warning";
1161
- case "critical":
1162
- return "fatal";
1163
- case "error":
1164
- return "error";
1165
- case "success":
1166
- case "table":
1167
- case "info":
1168
- default:
1169
- return "info";
1170
- }
1171
- }
1172
- function normalizeExceptionInput(input) {
1173
- if (input instanceof Error) {
1174
- return input;
1175
- }
1176
- const direct = toExceptionCandidate(input);
1177
- if (direct) {
1178
- return direct;
1179
- }
1180
- if (typeof input === "string") {
1181
- return new Error(input);
1182
- }
1183
- return new Error("Unknown Better Stack exception");
1184
- }
1185
- function isPreviouslyCapturedError(value) {
1186
- return isPlainObject(value) && value[PREVIOUSLY_CAPTURED_ERROR_KEY] === true;
1187
- }
1188
- function markCapturedError(value) {
1189
- if (!isPlainObject(value) || isPreviouslyCapturedError(value)) {
1190
- return;
1191
- }
1192
- try {
1193
- Object.defineProperty(value, PREVIOUSLY_CAPTURED_ERROR_KEY, {
1194
- value: true,
1195
- enumerable: false,
1196
- configurable: true,
1197
- writable: true
1198
- });
1199
- } catch {
1200
- try {
1201
- value[PREVIOUSLY_CAPTURED_ERROR_KEY] = true;
1202
- } catch {
1203
- }
1204
- }
1205
- }
1206
- function createDefaultClient(connector) {
1207
- return new Logtail(connector.sourceToken ?? "", {
1208
- endpoint: connector.ingestingHost,
1209
- captureStackContext: false
1210
- });
1211
- }
1212
- function getClientOptions(client) {
1213
- return client?.getOptions?.() ?? {};
1214
- }
1215
- function registerShutdownHooks(key, flush) {
1216
- const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
1217
- for (const event of handlers) {
1218
- process.once(event, () => {
1219
- void flush().catch((error) => {
1220
- warnOnce2(
1221
- `${key}:shutdown`,
1222
- "[Blyp] Failed to flush Better Stack logs during shutdown.",
1223
- error
1224
- );
1225
- });
1226
- });
1227
- }
1228
- }
1229
- function createBetterStackSender(config) {
1230
- const connector = resolveConnectorConfig(config);
1231
- const key = `${connector.serviceName}:${connector.ingestingHost ?? "missing"}:${connector.mode}`;
1232
- const sentryModule = getSentryModule();
1233
- const client = connector.ready ? testHooks.createClient?.(connector) ?? createDefaultClient(connector) : void 0;
1234
- let sentryClient = connector.errorTracking.enabled ? sentryModule?.getClient?.() : void 0;
1235
- if (sentryClient) {
1236
- const options = getClientOptions(sentryClient);
1237
- 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) {
1238
- warnOnce2(
1239
- `betterstack-error-mismatch:${key}`,
1240
- "[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client for Better Stack error tracking."
1241
- );
1242
- }
1243
- }
1244
- if (!sentryClient && connector.errorTracking.enabled && hasNonEmptyString(connector.errorTracking.dsn) && sentryModule) {
1245
- try {
1246
- sentryModule.init({
1247
- dsn: connector.errorTracking.dsn,
1248
- tracesSampleRate: connector.errorTracking.tracesSampleRate,
1249
- environment: connector.errorTracking.environment,
1250
- release: connector.errorTracking.release
1251
- });
1252
- sentryClient = sentryModule.getClient();
1253
- } catch (error) {
1254
- warnOnce2(
1255
- `betterstack-error-init:${key}`,
1256
- "[Blyp] Failed to initialize Better Stack error tracking.",
1257
- error
1258
- );
1259
- }
1260
- }
1261
- const errorTrackingReady = connector.errorTracking.enabled && sentryClient !== void 0;
1262
- if (client || errorTrackingReady) {
1263
- registerShutdownHooks(key, async () => {
1264
- if (client) {
1265
- await client.flush();
1266
- }
1267
- if (errorTrackingReady) {
1268
- await sentryModule.flush(2e3);
1269
- }
1270
- });
1271
- }
1272
- const emitUnavailableWarning = () => {
1273
- warnOnce2(
1274
- `betterstack-unavailable:${key}`,
1275
- "[Blyp] Better Stack connector is not configured or not ready. Skipping Better Stack delivery."
1276
- );
1277
- };
1278
- const emitExceptionUnavailableWarning = () => {
1279
- warnOnce2(
1280
- `betterstack-exception-unavailable:${key}`,
1281
- "[Blyp] Better Stack error tracking is not configured. Skipping Better Stack exception capture."
1282
- );
1283
- };
1284
- return {
1285
- enabled: connector.enabled,
1286
- ready: connector.ready,
1287
- mode: connector.mode,
1288
- serviceName: connector.serviceName,
1289
- ingestingHost: connector.ingestingHost,
1290
- status: connector.status,
1291
- errorTracking: {
1292
- enabled: connector.errorTracking.enabled,
1293
- ready: errorTrackingReady,
1294
- status: errorTrackingReady ? "enabled" : "missing",
1295
- dsn: connector.errorTracking.dsn,
1296
- tracesSampleRate: connector.errorTracking.tracesSampleRate,
1297
- environment: connector.errorTracking.environment,
1298
- release: connector.errorTracking.release
1299
- },
1300
- shouldAutoForwardServerLogs() {
1301
- return connector.ready && connector.mode === "auto";
1302
- },
1303
- shouldAutoCaptureExceptions() {
1304
- return errorTrackingReady;
1305
- },
1306
- send(record, options = {}) {
1307
- if (!connector.ready || !client) {
1308
- if (options.warnIfUnavailable) {
1309
- emitUnavailableWarning();
1310
- }
1311
- return;
1312
- }
1313
- const source = options.source ?? "server";
1314
- void client.log(
1315
- record.message,
1316
- resolveBetterStackLevel(record.level),
1317
- buildContext(record, connector, source)
1318
- ).catch((error) => {
1319
- warnOnce2(
1320
- `betterstack-send:${key}`,
1321
- "[Blyp] Failed to deliver log to Better Stack.",
1322
- error
1323
- );
1324
- });
1325
- },
1326
- captureException(error, options = {}) {
1327
- if (!errorTrackingReady || !sentryModule) {
1328
- if (options.warnIfUnavailable) {
1329
- emitExceptionUnavailableWarning();
1330
- }
1331
- return;
1332
- }
1333
- if (isPreviouslyCapturedError(error)) {
1334
- return;
1335
- }
1336
- try {
1337
- const exception = normalizeExceptionInput(error);
1338
- sentryModule.withScope((scope) => {
1339
- scope.setLevel(
1340
- normalizeScopeLevel(
1341
- options.source === "client" ? "error" : "error"
1342
- )
1343
- );
1344
- scope.setContext("blyp", {
1345
- source: options.source ?? "server",
1346
- ...options.context ? { context: options.context } : {}
1347
- });
1348
- sentryModule.captureException(exception);
1349
- });
1350
- markCapturedError(error);
1351
- markCapturedError(exception);
1352
- } catch (captureError) {
1353
- warnOnce2(
1354
- `betterstack-manual-capture:${key}`,
1355
- "[Blyp] Failed to capture exception in Better Stack error tracking.",
1356
- captureError
1357
- );
1358
- }
1359
- },
1360
- async flush() {
1361
- if (!client) {
1362
- if (!errorTrackingReady || !sentryModule) {
1363
- return;
1364
- }
1365
- }
1366
- try {
1367
- if (client) {
1368
- await client.flush();
1369
- }
1370
- if (errorTrackingReady && sentryModule) {
1371
- await sentryModule.flush(2e3);
1372
- }
1373
- } catch (error) {
1374
- warnOnce2(
1375
- `betterstack-flush:${key}`,
1376
- "[Blyp] Failed to flush Better Stack logs.",
1377
- error
1378
- );
1379
- }
1380
- }
1381
- };
1382
- }
1383
-
1384
- // src/connectors/betterstack/index.ts
1385
- function resolveSender(config = {}) {
1386
- return createBetterStackSender(resolveConfig({
1387
- ...config.connectors ? { connectors: config.connectors } : {}
1388
- }));
1389
- }
1390
- function createBetterStackLoggerInstance(sender, bindings = {}) {
1391
- const writeRecord = (level, message, args) => {
1392
- sender.send(buildRecord(level, message, args, bindings), {
1393
- source: "server",
1394
- warnIfUnavailable: true
1395
- });
1396
- };
1397
- const writeStructured = (payload, message) => {
1398
- sender.send(
1399
- buildStructuredRecord(
1400
- resolveStructuredWriteLevel(payload.level),
1401
- message,
1402
- payload,
1403
- bindings
1404
- ),
1405
- {
1406
- source: "server",
1407
- warnIfUnavailable: true
1408
- }
1409
- );
1410
- };
1411
- return {
1412
- debug: (message, ...args) => {
1413
- writeRecord("debug", message, args);
1414
- },
1415
- info: (message, ...args) => {
1416
- writeRecord("info", message, args);
1417
- },
1418
- error: (message, ...args) => {
1419
- writeRecord("error", message, args);
1420
- },
1421
- warn: (message, ...args) => {
1422
- writeRecord("warn", message, args);
1423
- },
1424
- warning: (message, ...args) => {
1425
- writeRecord("warning", message, args);
1426
- },
1427
- success: (message, ...args) => {
1428
- writeRecord("success", message, args);
1429
- },
1430
- critical: (message, ...args) => {
1431
- writeRecord("critical", message, args);
1432
- },
1433
- table: (message, data) => {
1434
- writeRecord("table", message, data === void 0 ? [] : [data]);
1435
- },
1436
- flush: async () => {
1437
- },
1438
- shutdown: async () => {
1439
- },
1440
- createStructuredLog: (groupId, initial) => {
1441
- return createStructuredLog(groupId, {
1442
- initialFields: initial,
1443
- write: writeStructured
1444
- });
1445
- },
1446
- child: (childBindings) => {
1447
- return createBetterStackLoggerInstance(sender, {
1448
- ...bindings,
1449
- ...childBindings
1450
- });
1451
- }
1452
- };
1453
- }
1454
- function createBetterStackErrorTrackerInstance(sender, bindings = {}) {
1455
- return {
1456
- capture: (error, options = {}) => {
1457
- sender.captureException(error, {
1458
- source: options.source ?? "server",
1459
- warnIfUnavailable: options.warnIfUnavailable ?? true,
1460
- context: {
1461
- ...bindings,
1462
- ...options.context ?? {},
1463
- "blyp.manual": true
1464
- }
1465
- });
1466
- },
1467
- child: (childBindings) => {
1468
- return createBetterStackErrorTrackerInstance(sender, {
1469
- ...bindings,
1470
- ...childBindings
1471
- });
1472
- }
1473
- };
1474
- }
1475
- function createBetterStackLogger(config = {}) {
1476
- return createBetterStackLoggerInstance(resolveSender(config));
1477
- }
1478
- function createBetterStackErrorTracker(config = {}) {
1479
- return createBetterStackErrorTrackerInstance(resolveSender(config));
1480
- }
1481
- function captureBetterStackException(error, options = {}, config = {}) {
1482
- createBetterStackErrorTracker(config).capture(error, options);
1483
- }
1484
- function createStructuredBetterStackLogger(groupId, initial, config = {}) {
1485
- const sender = resolveSender(config);
1486
- return createStructuredLog(groupId, {
1487
- initialFields: initial,
1488
- write: (payload, message) => {
1489
- sender.send(
1490
- buildStructuredRecord(
1491
- resolveStructuredWriteLevel(payload.level),
1492
- message,
1493
- payload,
1494
- {}
1495
- ),
1496
- {
1497
- source: "server",
1498
- warnIfUnavailable: true
1499
- }
1500
- );
1501
- }
1502
- });
1503
- }
1504
-
1505
- export { captureBetterStackException, createBetterStackErrorTracker, createBetterStackLogger, createStructuredBetterStackLogger };
1506
- //# sourceMappingURL=betterstack.mjs.map
1507
- //# sourceMappingURL=betterstack.mjs.map
1
+ import {existsSync,readFileSync,writeFileSync,appendFileSync}from'fs';import {createJiti}from'jiti';import Ne,{resolve,dirname}from'path';import _e from'os';import {z as z$1}from'zod';import {AsyncLocalStorage}from'async_hooks';import*as Gt from'@sentry/node';import {Logtail}from'@logtail/node';import'fflate';function ee(){return Ne.join(_e.homedir(),".blyp","queue.db")}function P(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let n=e;return n.cause!==void 0&&(t.cause=w(n.cause)),t}function w(e,t=new WeakSet){if(e instanceof Error)return P(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(n=>w(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let n={};for(let[r,o]of Object.entries(e))n[r]=w(o,t);return t.delete(e),n}return e}function _(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=w(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var Ie=z$1.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"}),te=z$1.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),I=z$1.string().trim().min(1);function T(e){return Ie.safeParse(e).success}function h(e){return te.safeParse(e).success}function y(e){return I.safeParse(e).success}var M="/inngest";z$1.union([z$1.literal("betterstack"),z$1.literal("databuddy"),z$1.literal("posthog"),z$1.literal("sentry"),z$1.undefined(),z$1.object({type:z$1.literal("otlp"),name:I})]);function ne(e,t=new Set){return (n,r,o)=>{if(t.has(n)||typeof console>"u")return;let i=console[e];if(typeof i=="function"){if(t.add(n),o===void 0){i.call(console,r);return}i.call(console,r,o);}}}function re(e){return ne("warn",e)}function oe(e){return ne("error",e)}var Me="[REDACTED]",je=["password","passwd","pwd","secret","token","api_key","apikey","api_secret","authorization","auth","x-api-key","private_key","privatekey","access_token","refresh_token","client_secret","session","cookie","set-cookie","ssn","credit_card","card_number","cvv","cvc","otp","pin"];var qe=[{type:"bearer",pattern:/\bBearer\s+(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Za-z0-9._~+/-]{20,})\b/g},{type:"jwt",pattern:/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"api_key",pattern:/\b(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,})\b/g}],$e=/\b(?:\d[ -]*?){16}\b/g;function ie(e){let t=new Set,n=[];for(let r of e)typeof r!="string"||r.length===0||t.has(r)||(t.add(r),n.push(r));return n}function He(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Ue(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function We(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Ge(e){return e.split(".").filter(Boolean)}function j(e,t,n=0,r=0){if(n===e.length)return r===t.length;let o=e[n];if(o==="**"){if(n===e.length-1)return true;for(let i=r;i<=t.length;i+=1)if(j(e,t,n+1,i))return true;return false}return r>=t.length||o!=="*"&&o!==t[r]?false:j(e,t,n+1,r+1)}function Qe(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>j(Ge(n),e))}function Je(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,r=false;for(let o=t.length-1;o>=0;o-=1){let i=Number(t[o]);r&&(i*=2,i>9&&(i-=9)),n+=i,r=!r;}return n%10===0}function ae(e,t,n){if(n||t.disablePatternScanning)return e;let r=e;for(let{type:o,pattern:i}of qe)r=r.replace(i,`[REDACTED:${o}]`);r=r.replace($e,o=>Je(o)?"[REDACTED:card]":o);for(let o of t.patterns)r=r.replace(He(o),"[REDACTED:pattern]");return r}function z(e,t,n,r){if(typeof e=="string")return ae(e,t,!!r.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((i,a)=>z(i,t,n,{path:[...r.path,String(a)],skipPatternScanning:r.skipPatternScanning}));if(!Ue(e))return e;let o={};for(let[i,a]of Object.entries(e)){let c=[...r.path,i];if(n.has(i.toLowerCase())||Qe(c,t)){if(a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){o[i]=Me;continue}o[i]=z(a,t,n,{path:c,skipPatternScanning:r.skipPatternScanning});continue}o[i]=z(a,t,n,{path:c,skipPatternScanning:r.skipPatternScanning});}return o}function k(e,t){return {keys:ie([...je,...e?.keys??[],...t?.keys??[]]),paths:ie([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(n=>n instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function f(e,t,n={path:[]}){let r=w(e);return z(r,t,We(t),n)}function D(e,t){return typeof e=="string"?ae(e,t,false):_(f(e,t))}var Ze="@blyp/core",Xe=".gitignore",le=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],et="blyp.config.json",tt="https://us.i.posthog.com",nt="blyp-app",rt=nt,ot=new Set,b=re(ot),ge={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},de={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:ge},q={enabled:true,path:M},fe=k(),x={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},C={enabled:false,memoryBufferSize:500,durableQueuePath:ee(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:x},pe={maxRetries:1,backoffMs:100},it={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:pe},se={pretty:true,level:"info",destination:"file",file:de,clientLogging:q,redact:fe,connectors:{delivery:C}},E=null;function at(e){let t=e;for(;;){let n=resolve(t,"package.json");if(existsSync(n))try{let o=JSON.parse(readFileSync(n,"utf-8"));if(y(o.name))return o.name}catch{}let r=dirname(t);if(r===t)return;t=r;}}function H(e=process.cwd()){return at(e)??rt}function st(){return {pretty:true,level:"info",destination:"file",file:{enabled:true,format:"ndjson",rotation:{enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true}},clientLogging:{enabled:true,path:M},redact:fe,connectors:{delivery:C}}}function ct(e){let t=resolve(e,"package.json");if(!existsSync(t))return true;try{return JSON.parse(readFileSync(t,"utf-8")).name!==Ze}catch{return true}}function ut(e){if(le.some(n=>existsSync(resolve(e,n))))return;let t=resolve(e,et);if(!existsSync(t))try{writeFileSync(t,`${JSON.stringify(st(),null,2)}
2
+ `);}catch(n){console.error("[Blyp] Warning: Failed to create blyp.config.json:",n);}}function lt(e){let t=resolve(e,Xe);if(!existsSync(t)){try{writeFileSync(t,`logs
3
+ .blyp
4
+ `);}catch(n){console.error("[Blyp] Warning: Failed to create .gitignore:",n);}return}try{let n=readFileSync(t,"utf-8"),r=["logs",".blyp"].filter(i=>{let a=i.replace(".","\\.");return !new RegExp(`^(?:/?${a}/?)\\s*$`,"m").test(n)});if(r.length===0)return;let o=n.endsWith(`
5
+ `)?"":`
6
+ `;appendFileSync(t,`${o}${r.join(`
7
+ `)}
8
+ `);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function gt(){let e=process.cwd();ct(e)&&(ut(e),lt(e));}function dt(){let e=process.cwd(),t=le.map(r=>resolve(e,r)).filter(r=>existsSync(r));if(t.length===0)return null;if(t.length>1){let r=t[0];b(`config-multiple:${r}`,`[Blyp] Warning: Multiple config files found. Using ${r} and ignoring ${t.slice(1).join(", ")}.`);}let n=t[0];return {path:n,type:n.endsWith(".json")?"json":"jiti"}}function ye(e,t){let n=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !n||typeof n!="object"||Array.isArray(n)?(b(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):n}function ft(e){try{let t=readFileSync(e,"utf-8");return ye(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function pt(e){try{let t=createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return ye(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function yt(e){return e.type==="json"?ft(e.path):pt(e.path)}function ce(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function mt(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function Ct(e,t){return {...pe,...e,...t}}function ht(e,t){return {...it,...e,...t,retry:Ct(e?.retry,t?.retry)}}function St(e){let t=e.model??"blypLog",r=e.client?.[t];return !!r&&typeof r.create=="function"}function kt(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function bt(e,t){if(!e)return;let n=e.adapter,r=false;t==="json"?b("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?b(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):n?ce(n)?(r=St({...n,model:n.model??"blypLog"}),r||b("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${n.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):mt(n)&&(r=kt(n),r||b("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):b("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let o=ce(n)?{...n,model:n.model??"blypLog"}:n;return {dialect:e.dialect,adapter:o,delivery:ht(void 0,e.delivery),ready:r,status:r?"enabled":"missing"}}function Rt(e,t){return {...ge,...e,...t}}function Lt(e,t){return {...de,...e,...t,rotation:Rt(e?.rotation,t?.rotation)}}function wt(e,t){return {...q,...e,...t,path:t?.path??e?.path??q.path}}function xt(e,t){return k(e,t)}function vt(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??x.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??x.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??x.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??x.multiplier),jitter:t?.jitter??e?.jitter??x.jitter}}function Bt(e,t){let n=t?.durableQueuePath??e?.durableQueuePath??C.durableQueuePath;return {enabled:t?.enabled??e?.enabled??C.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??C.memoryBufferSize)),durableQueuePath:y(n)?n:C.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??C.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??C.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??C.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??C.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??C.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??C.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??C.overflowStrategy,retry:vt(e?.retry,t?.retry),durableReady:false}}function Tt(e,t,n){if(!(!e&&!t))return bt({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},n)}function Dt(e,t){let n=t?.enabled??e?.enabled??false,r=t?.projectKey??e?.projectKey,o=e?.enabled===true?e?.errorTracking:void 0,i=t?.errorTracking?.mode??o?.mode??"auto",a=t?.errorTracking?.enabled??o?.enabled??n,c=n&&a&&typeof r=="string"&&r.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",projectKey:r,host:t?.host??e?.host??tt,serviceName:t?.serviceName??e?.serviceName??H(),errorTracking:{enabled:a,mode:i,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??o?.enableExceptionAutocapture??i==="auto",ready:c,status:c?"enabled":"missing"}}}function Et(e,t){let n=t?.enabled??e?.enabled??false,r=t?.apiKey??e?.apiKey,o=t?.websiteId??e?.websiteId,i=n&&y(r)&&y(o);return {enabled:n,mode:t?.mode??e?.mode??"auto",apiKey:r,websiteId:o,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:i,status:i?"enabled":"missing"}}function At(e,t){let n=t?.sourceToken??e?.sourceToken,r=t?.ingestingHost??e?.ingestingHost,o=t?.enabled??e?.enabled??false,i=e?.enabled===true?e?.errorTracking:void 0,a=Pt(o,i,t?.errorTracking),c=o&&y(n)&&T(r);return {enabled:o,mode:t?.mode??e?.mode??"auto",sourceToken:n,ingestingHost:r,serviceName:t?.serviceName??e?.serviceName??H(),errorTracking:a,ready:c,status:c?"enabled":"missing"}}function Pt(e,t,n){let r=n?.dsn??t?.dsn,o=n?.enabled??t?.enabled??e,i=o&&y(r);return {enabled:o,dsn:r,tracesSampleRate:n?.tracesSampleRate??t?.tracesSampleRate??1,environment:n?.environment??t?.environment,release:n?.release??t?.release,ready:i,status:i?"enabled":"missing"}}function zt(e,t){let n=t?.dsn??e?.dsn,r=t?.enabled??e?.enabled??false,o=r&&typeof n=="string"&&n.trim().length>0;return {enabled:r,mode:t?.mode??e?.mode??"auto",dsn:n,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:o,status:o?"enabled":"missing"}}function Ot(e,t){let n=t?.endpoint??e?.endpoint,r=t?.enabled??e?.enabled??false,o={...{},...t?.headers??{}},i=r&&T(n);return {name:t?.name??e?.name??"",enabled:r,mode:t?.mode??e?.mode??"auto",endpoint:n,headers:o,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??H(),ready:i,status:i?"enabled":"missing"}}function Ft(e,t){let n=t??e??[],r=new Map;for(let o of n)!o||typeof o.name!="string"||o.name.length===0||(r.has(o.name)&&b(`otlp-duplicate:${o.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${o.name}" found. Using the last definition.`),r.set(o.name,Ot(void 0,o)));return Array.from(r.values())}function _t(e,t){return {betterstack:At(e?.betterstack,t?.betterstack),databuddy:Et(e?.databuddy,t?.databuddy),posthog:Dt(e?.posthog,t?.posthog),sentry:zt(e?.sentry,t?.sentry),otlp:Ft(e?.otlp,t?.otlp),delivery:Bt(e?.delivery,t?.delivery)}}function $(e,t={},n={}){return {...e,...t,destination:t.destination??e.destination??"file",file:Lt(e.file,t.file),database:Tt(e.database,t.database,n.configFileType),clientLogging:wt(e.clientLogging,t.clientLogging),redact:xt(e.redact,t.redact),connectors:_t(e.connectors,t.connectors)}}function Nt(){if(E!==null)return E;gt();let e=dt();if(e){let t=yt(e);E=$(se,t,{configFileType:e.type});}else E=$(se);return E}function me(e={}){return $(Nt(),e)}var Mt=new AsyncLocalStorage;function jt(){return Mt.getStore()}function U(){return jt()?.traceId}var Ce={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function F(e){return e.replace(/\\/g,"/")}function qt(e){let t=F(e);return t.startsWith("node:")||t.includes("/node_modules/pino")||t.includes("/node_modules/pino-pretty")||t.includes("/node_modules/@blyp/core/")||t.includes("/blyp/src/core/")||t.includes("/blyp/src/frameworks/")||t.includes("/blyp/src/posthog/")||t.includes("/blyp/dist/")}function $t(e){let t=F(e),n=F(process.cwd());return t.startsWith(`${n}/`)?t.slice(n.length+1):t}function he(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
9
+ `),n=null;for(let r=2;r<t.length;r+=1){let o=t[r];if(!o)continue;let i=o.match(/\((.*):(\d+):\d+\)/)||o.match(/at\s+(.*):(\d+):(\d+)/);if(!i)continue;let a=i[1]||"",c=parseInt(i[2]||"0",10)||null;if(a&&!a.includes("node_modules")&&!qt(a)){let g=$t(a);if(!F(g).startsWith("dist/"))return {file:g,line:c};n??(n={file:g,line:c});}}if(n)return n}catch{return {file:null,line:null}}return {file:null,line:null}}var Se=D;function ke(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function be(e,t,n,r,o=k()){let{file:i,line:a}=he(),c=Se(t,o),g={timestamp:new Date().toISOString(),level:Ce[e],message:ke(c)},s=U();return t instanceof Error&&(g.error=f(P(t),o)),i&&(g.caller=a!==null?`${i}:${a}`:i),n.length===1?g.data=f(n[0],o):n.length>1&&(g.data=f(n,o)),Object.keys(r).length>0&&(g.bindings=f(r,o)),s&&(g.traceId=s),g}function W(e,t,n,r,o=k()){let{file:i,line:a}=he(),c=f(n,o),g=U(),s={message:ke(Se(t,o)),...c};return i&&(s.caller=a!==null?`${i}:${a}`:i),Object.keys(r).length>0&&(s.bindings=f(r,o)),g&&s.traceId===void 0&&(s.traceId=g),s.level=typeof c.level=="string"&&c.level.length>0?c.level:Ce[e],s.timestamp=typeof c.timestamp=="string"&&c.timestamp.length>0?c.timestamp:new Date().toISOString(),s}function G(e){switch(e){case "debug":return "debug";case "warning":return "warning";case "warn":return "warn";case "error":return "error";case "success":return "success";case "critical":return "critical";case "table":return "table";default:return "info"}}function Re(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let n=[e,...t];return n.length===1?n[0]:n}function Le(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Ht(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let n=e;return {message:e.message,code:n.code,type:n.type??e.name??e.constructor?.name,stack:e.stack,why:n.why,fix:n.fix,link:n.link,details:Le(n.details),cause:n.cause}}if(typeof e=="object"){let n=e,r=typeof n.statusCode=="number"?n.statusCode:typeof n.status=="number"?n.status:t;return {message:typeof n.message=="string"?n.message:`HTTP ${r??500}`,code:typeof n.code=="string"||typeof n.code=="number"?n.code:r,type:typeof n.type=="string"?n.type:typeof n.name=="string"?n.name:"Error",stack:typeof n.stack=="string"?n.stack:void 0,why:typeof n.why=="string"?n.why:void 0,fix:typeof n.fix=="string"?n.fix:void 0,link:typeof n.link=="string"?n.link:void 0,details:Le(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Ut(e){return e.response&&typeof e.response.status=="number"?e.response.status:typeof e.status=="number"?e.status:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.statusCode=="number"?e.error.statusCode:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.status=="number"?e.error.status:e.error?500:void 0}function Q(e,t){let n=t.redact??k(),r=performance.now(),o=f(t.initialFields??{},n),i=[],a;t.onCreate?.();let c=(s,l,m)=>(i.push({level:s,message:D(l,n),timestamp:new Date().toISOString(),...Re(l,m)===void 0?{}:{data:f(Re(l,m),n)}}),g),g={set(s){return Object.assign(o,f(s,n)),g},debug(s,...l){return c("debug",s,l)},info(s,...l){return c("info",s,l)},warn(s,...l){return c("warn",s,l)},warning(s,...l){return c("warning",s,l)},error(s,...l){return c("error",s,l)},success(s,...l){return c("success",s,l)},critical(s,...l){return c("critical",s,l)},table(s,l){return c("table",s,l===void 0?[]:[l])},emit(s={}){if(a)return a;let l=f(t.resolveDefaultFields?.()??{},n),m=Ut(s),u=f(Ht(s.error,m),n),d=s.level??(u?"error":"info"),p=f({...l,...o,groupId:e,timestamp:new Date().toISOString(),level:d,duration:Math.round(performance.now()-r),...typeof m=="number"?{status:m}:{},...i.length>0?{events:[...i]}:{},...u?{error:u}:{}},n);return t.write(p,D(s.message??"structured_log",n)),a=p,t.onEmit?.(p),p}};return g}function Wt(){let e=new WeakSet;return (t,n)=>{if(typeof n=="function")return `[Function: ${n.name||"anonymous"}]`;if(n===void 0)return "[undefined]";if(typeof n=="symbol")return n.toString();if(n!==null&&typeof n=="object"){if(e.has(n))return "[Circular]";e.add(n);}return n}}function we(e){return JSON.stringify(e,Wt())}var J=Symbol("blyp.connector.batch-dispatch"),xe=Symbol("blyp.connector.delivery-binder");function ve(e){return h(e)&&("connectors"in e||"pretty"in e||"level"in e)}function V(e){return h(e.data)?e.data:e}function R(e,t){if(t in e){let o=e[t];if(typeof o=="string"||typeof o=="number")return o}let r=V(e)[t];if(typeof r=="string"||typeof r=="number")return r}function K(e,t){let n=V(e),o=(h(n.page)?n.page:void 0)?.[t];return typeof o=="string"?o:void 0}function Y(e,t){let n=V(e),o=(h(n.session)?n.session:void 0)?.[t];return typeof o=="string"?o:void 0}function Be(e){return R(e,"type")}var Z="__betterstack_previously_captured_error",Jt=new Set,Ae={},L=oe(Jt);function Vt(){return Ae.module??Gt}function Kt(e){let t=ve(e)?e.connectors?.betterstack:e,n=t?.enabled??false,r=t?.sourceToken,o=t?.ingestingHost,i=t?.errorTracking?.enabled??n,a=t?.errorTracking?.dsn,c=n&&i&&y(a),g=n&&y(r)&&T(o);return {enabled:n,mode:t?.mode??"auto",sourceToken:r,ingestingHost:o,serviceName:t?.serviceName??"blyp-app",errorTracking:{enabled:i,dsn:a,tracesSampleRate:t?.errorTracking?.tracesSampleRate??1,environment:t?.errorTracking?.environment,release:t?.errorTracking?.release,ready:c,status:c?"enabled":"missing"},ready:g,status:g?"enabled":"missing"}}function Te(e){switch(e){case "debug":return "debug";case "warning":case "warn":return "warn";case "error":return "error";case "critical":return "fatal";default:return "info"}}function Yt(e){if(typeof e!="string"||e.trim().length===0)return {};let t=e.match(/^(.*):(\d+)$/);if(!t)return {};let n=t[1]?.trim(),r=Number.parseInt(t[2]??"",10);return {...n?{file:n}:{},...Number.isFinite(r)?{line:r}:{}}}function De(e,t,n){let r=Be(e),o=R(e,"groupId"),i=R(e,"traceId"),a=R(e,"method"),c=R(e,"path"),g=R(e,"status"),s=R(e,"duration"),l=K(e,"pathname"),m=K(e,"url"),u=Y(e,"sessionId"),d=Y(e,"pageId"),p=Yt(e.caller);return {service:t.serviceName,context:{blyp:{level:e.level,source:n,...r?{type:r}:{},...o?{group_id:o}:{},...i?{trace_id:i}:{},...e.caller?{caller:e.caller}:{},...s!==void 0?{duration_ms:s}:{},...e.bindings?{bindings:e.bindings}:{},payload:we(e)},...a||c||g!==void 0?{http:{...a?{method:a}:{},...c?{path:c}:{},...g!==void 0?{status_code:g}:{}}}:{},...l||m||u||d?{client:{...l?{page_path:l}:{},...m?{page_url:m}:{},...u?{session_id:u}:{},...d?{page_id:d}:{}}}:{},...Object.keys(p).length>0?{runtime:p}:{},...e.data!==void 0?{data:e.data}:{},...e.error!==void 0?{error:e.error}:{}}}}function Zt(e){if(!h(e))return;let t=typeof e.message=="string"?e.message:void 0,n=typeof e.name=="string"?e.name:void 0,r=typeof e.stack=="string"?e.stack:void 0;if(!t&&!n&&!r)return;let o=new Error(t??n??"Unknown error");o.name=n??"Error",r&&(o.stack=r);for(let[i,a]of Object.entries(e))i==="message"||i==="name"||i==="stack"||(o[i]=a);return o}function Xt(e){switch(e){case "debug":return "debug";case "warning":case "warn":return "warning";case "critical":return "fatal";case "error":return "error";default:return "info"}}function en(e){if(e instanceof Error)return e;let t=Zt(e);return t||(typeof e=="string"?new Error(e):new Error("Unknown Better Stack exception"))}function Pe(e){return h(e)&&e[Z]===true}function Ee(e){if(!(!h(e)||Pe(e)))try{Object.defineProperty(e,Z,{value:!0,enumerable:!1,configurable:!0,writable:!0});}catch{try{e[Z]=!0;}catch{}}}function tn(e){return new Logtail(e.sourceToken??"",{endpoint:e.ingestingHost,captureStackContext:false})}function nn(e){return e?.getOptions?.()??{}}function rn(e,t){let n=["beforeExit","SIGINT","SIGTERM"];for(let r of n)process.once(r,()=>{t().catch(o=>{L(`${e}:shutdown`,"[Blyp] Failed to flush Better Stack logs during shutdown.",o);});});}function ze(e){let t=Kt(e),n=`${t.serviceName}:${t.ingestingHost??"missing"}:${t.mode}`,r=Vt(),o=t.ready?Ae.createClient?.(t)??tn(t):void 0,i=t.errorTracking.enabled?r?.getClient?.():void 0;if(i){let u=nn(i);(y(t.errorTracking.dsn)&&t.errorTracking.dsn!==u.dsn||y(t.errorTracking.environment)&&t.errorTracking.environment!==u.environment||y(t.errorTracking.release)&&t.errorTracking.release!==u.release)&&L(`betterstack-error-mismatch:${n}`,"[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client for Better Stack error tracking.");}if(!i&&t.errorTracking.enabled&&y(t.errorTracking.dsn)&&r)try{r.init({dsn:t.errorTracking.dsn,tracesSampleRate:t.errorTracking.tracesSampleRate,environment:t.errorTracking.environment,release:t.errorTracking.release}),i=r.getClient();}catch(u){L(`betterstack-error-init:${n}`,"[Blyp] Failed to initialize Better Stack error tracking.",u);}let a=t.errorTracking.enabled&&i!==void 0;(o||a)&&rn(n,async()=>{o&&await o.flush(),a&&await r.flush(2e3);});let c=()=>{L(`betterstack-unavailable:${n}`,"[Blyp] Better Stack connector is not configured or not ready. Skipping Better Stack delivery.");},g=()=>{L(`betterstack-exception-unavailable:${n}`,"[Blyp] Better Stack error tracking is not configured. Skipping Better Stack exception capture.");},s=null,l=async u=>{if(!t.ready||!o)return {ok:false,retryable:false,error:"Better Stack connector is not configured."};try{return await Promise.all(u.map(d=>o.log(d.message,Te(d.level),De(d,t,"server")))),await o.flush(),{ok:!0}}catch(d){return {ok:false,retryable:true,error:d instanceof Error?d.message:String(d)}}},m={enabled:t.enabled,ready:t.ready,mode:t.mode,serviceName:t.serviceName,ingestingHost:t.ingestingHost,status:t.status,errorTracking:{enabled:t.errorTracking.enabled,ready:a,status:a?"enabled":"missing",dsn:t.errorTracking.dsn,tracesSampleRate:t.errorTracking.tracesSampleRate,environment:t.errorTracking.environment,release:t.errorTracking.release},shouldAutoForwardServerLogs(){return t.ready&&t.mode==="auto"},shouldAutoCaptureExceptions(){return a},send(u,d={}){if(d.source!=="client"&&s){s.enqueue("betterstack",u,m[J]);return}if(!t.ready||!o){d.warnIfUnavailable&&c();return}let p=d.source??"server";o.log(u.message,Te(u.level),De(u,t,p)).catch(A=>{L(`betterstack-send:${n}`,"[Blyp] Failed to deliver log to Better Stack.",A);});},captureException(u,d={}){if(!a||!r){d.warnIfUnavailable&&g();return}if(!Pe(u))try{let p=en(u);r.withScope(A=>{A.setLevel(Xt((d.source==="client","error"))),A.setContext("blyp",{source:d.source??"server",...d.context?{context:d.context}:{}}),r.captureException(p);}),Ee(u),Ee(p);}catch(p){L(`betterstack-manual-capture:${n}`,"[Blyp] Failed to capture exception in Better Stack error tracking.",p);}},async flush(){if(!(!o&&(!a||!r)))try{o&&await o.flush(),a&&r&&await r.flush(2e3);}catch(u){L(`betterstack-flush:${n}`,"[Blyp] Failed to flush Better Stack logs.",u);}},[J]:{dispatchKey:"betterstack",dispatch:u=>l(u)},[xe](u){s=u;}};return m}function X(e={}){return ze(me({...e.connectors?{connectors:e.connectors}:{}}))}function Oe(e,t={}){let n=(o,i,a)=>{e.send(be(o,i,a,t),{source:"server",warnIfUnavailable:true});},r=(o,i)=>{e.send(W(G(o.level),i,o,t),{source:"server",warnIfUnavailable:true});};return {debug:(o,...i)=>{n("debug",o,i);},info:(o,...i)=>{n("info",o,i);},error:(o,...i)=>{n("error",o,i);},warn:(o,...i)=>{n("warn",o,i);},warning:(o,...i)=>{n("warning",o,i);},success:(o,...i)=>{n("success",o,i);},critical:(o,...i)=>{n("critical",o,i);},table:(o,i)=>{n("table",o,i===void 0?[]:[i]);},flush:async()=>{},shutdown:async()=>{},createStructuredLog:(o,i)=>Q(o,{initialFields:i,write:r}),child:o=>Oe(e,{...t,...o})}}function Fe(e,t={}){return {capture:(n,r={})=>{e.captureException(n,{source:r.source??"server",warnIfUnavailable:r.warnIfUnavailable??true,context:{...t,...r.context??{},"blyp.manual":true}});},child:n=>Fe(e,{...t,...n})}}function or(e={}){return Oe(X(e))}function on(e={}){return Fe(X(e))}function ir(e,t={},n={}){on(n).capture(e,t);}function ar(e,t,n={}){let r=X(n);return Q(e,{initialFields:t,write:(o,i)=>{r.send(W(G(o.level),i,o,{}),{source:"server",warnIfUnavailable:true});}})}export{ir as captureBetterStackException,on as createBetterStackErrorTracker,or as createBetterStackLogger,ar as createStructuredBetterStackLogger};