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