@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
package/dist/client.js CHANGED
@@ -1,1139 +1 @@
1
- 'use strict';
2
-
3
- var zod = require('zod');
4
-
5
- var __defProp = Object.defineProperty;
6
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
-
9
- // src/shared/log-value.ts
10
- function normalizeError(error) {
11
- const normalized = {
12
- name: error.name,
13
- message: error.message
14
- };
15
- if (error.stack) {
16
- normalized.stack = error.stack;
17
- }
18
- const errorWithCause = error;
19
- if (errorWithCause.cause !== void 0) {
20
- normalized.cause = normalizeLogValue(errorWithCause.cause);
21
- }
22
- return normalized;
23
- }
24
- function normalizeLogValue(value, seen = /* @__PURE__ */ new WeakSet()) {
25
- if (value instanceof Error) {
26
- return normalizeError(value);
27
- }
28
- if (typeof value === "function") {
29
- return `[Function: ${value.name || "anonymous"}]`;
30
- }
31
- if (typeof value === "symbol") {
32
- return value.toString();
33
- }
34
- if (value === void 0 || value === null) {
35
- return value;
36
- }
37
- if (Array.isArray(value)) {
38
- return value.map((entry) => normalizeLogValue(entry, seen));
39
- }
40
- if (typeof value === "object") {
41
- if (seen.has(value)) {
42
- return "[Circular]";
43
- }
44
- seen.add(value);
45
- const normalized = {};
46
- for (const [key, entry] of Object.entries(value)) {
47
- normalized[key] = normalizeLogValue(entry, seen);
48
- }
49
- seen.delete(value);
50
- return normalized;
51
- }
52
- return value;
53
- }
54
- function serializeLogMessage(message) {
55
- if (typeof message === "string") {
56
- return message;
57
- }
58
- if (message instanceof Error) {
59
- return message.message || message.name;
60
- }
61
- const normalized = normalizeLogValue(message);
62
- if (typeof normalized === "string") {
63
- return normalized;
64
- }
65
- try {
66
- const serialized = JSON.stringify(normalized, null, 2);
67
- return serialized ?? String(normalized);
68
- } catch {
69
- return String(normalized);
70
- }
71
- }
72
- zod.z.string().url().refine((value) => {
73
- try {
74
- const url = new URL(value);
75
- return url.protocol === "http:" || url.protocol === "https:";
76
- } catch {
77
- return false;
78
- }
79
- }, {
80
- message: "Expected an absolute http(s) URL"
81
- });
82
- var plainObjectSchema = zod.z.custom(
83
- (value) => {
84
- return value !== null && typeof value === "object" && !Array.isArray(value);
85
- },
86
- {
87
- message: "Expected a plain object"
88
- }
89
- );
90
- var nonEmptyStringSchema = zod.z.string().trim().min(1);
91
- function isPlainObject(value) {
92
- return plainObjectSchema.safeParse(value).success;
93
- }
94
-
95
- // src/shared/client-log.ts
96
- var DEFAULT_CLIENT_LOG_ENDPOINT = "/inngest";
97
- var SESSION_STORAGE_KEY = "blyp:session-id";
98
- zod.z.union([
99
- zod.z.literal("betterstack"),
100
- zod.z.literal("databuddy"),
101
- zod.z.literal("posthog"),
102
- zod.z.literal("sentry"),
103
- zod.z.undefined(),
104
- zod.z.object({
105
- type: zod.z.literal("otlp"),
106
- name: nonEmptyStringSchema
107
- })
108
- ]);
109
- function safeGet(getter) {
110
- try {
111
- return getter();
112
- } catch {
113
- return void 0;
114
- }
115
- }
116
- function randomSegment() {
117
- return Math.random().toString(36).slice(2, 10);
118
- }
119
- function createRandomId() {
120
- const maybeCrypto = safeGet(() => globalThis.crypto);
121
- const randomUUID = maybeCrypto && typeof maybeCrypto.randomUUID === "function" ? maybeCrypto.randomUUID.bind(maybeCrypto) : void 0;
122
- if (randomUUID) {
123
- return randomUUID();
124
- }
125
- return `${Date.now().toString(36)}-${randomSegment()}`;
126
- }
127
- function normalizeClientLogLevel(level) {
128
- return level === "warn" ? "warning" : level;
129
- }
130
- function normalizeClientPayloadData(message, args) {
131
- const normalizedArgs = args.map((entry) => normalizeLogValue(entry));
132
- const messageData = message instanceof Error ? normalizeError(message) : void 0;
133
- if (messageData !== void 0 && normalizedArgs.length === 0) {
134
- return messageData;
135
- }
136
- const combined = messageData === void 0 ? normalizedArgs : [messageData, ...normalizedArgs];
137
- if (combined.length === 0) {
138
- return void 0;
139
- }
140
- if (combined.length === 1) {
141
- return combined[0];
142
- }
143
- return combined;
144
- }
145
- function getBrowserPageContext() {
146
- const location2 = safeGet(() => globalThis.location);
147
- const document = safeGet(() => globalThis.document);
148
- return {
149
- url: location2?.href,
150
- pathname: location2?.pathname,
151
- search: location2?.search,
152
- hash: location2?.hash,
153
- title: document?.title,
154
- referrer: document?.referrer
155
- };
156
- }
157
- function getBrowserContext() {
158
- const navigator2 = safeGet(() => globalThis.navigator);
159
- return {
160
- userAgent: navigator2?.userAgent,
161
- language: navigator2?.language,
162
- platform: navigator2?.platform
163
- };
164
- }
165
- function getClientSessionId() {
166
- const storage = safeGet(() => globalThis.sessionStorage);
167
- const existing = safeGet(() => storage?.getItem(SESSION_STORAGE_KEY));
168
- if (existing) {
169
- return existing;
170
- }
171
- const sessionId = createRandomId();
172
- safeGet(() => storage?.setItem(SESSION_STORAGE_KEY, sessionId));
173
- return sessionId;
174
- }
175
- function normalizeMetadata(metadata) {
176
- if (metadata === void 0) {
177
- return void 0;
178
- }
179
- const resolved = typeof metadata === "function" ? safeGet(metadata) : metadata;
180
- if (!isPlainObject(resolved)) {
181
- return void 0;
182
- }
183
- return normalizeLogValue(resolved);
184
- }
185
-
186
- // src/shared/remote-delivery.ts
187
- var DEFAULT_MAX_RETRIES = 3;
188
- var DEFAULT_RETRY_DELAY_MS = 5e3;
189
- var DEFAULT_MAX_QUEUE_SIZE = 100;
190
- function clampInteger(value, fallback, minimum) {
191
- if (!Number.isFinite(value)) {
192
- return fallback;
193
- }
194
- return Math.max(minimum, Math.floor(value));
195
- }
196
- function safeCall(callback, value) {
197
- if (!callback) {
198
- return;
199
- }
200
- try {
201
- callback(value);
202
- } catch {
203
- }
204
- }
205
- function warn(message) {
206
- if (typeof console === "undefined" || typeof console.warn !== "function") {
207
- return;
208
- }
209
- console.warn(message);
210
- }
211
- function formatWarningValue(value) {
212
- return value === void 0 ? "unknown" : String(value);
213
- }
214
- function createRemoteDeliveryManager(options) {
215
- const deliveryConfig = {
216
- maxRetries: clampInteger(options.delivery?.maxRetries, DEFAULT_MAX_RETRIES, 0),
217
- retryDelayMs: clampInteger(options.delivery?.retryDelayMs, DEFAULT_RETRY_DELAY_MS, 0),
218
- maxQueueSize: clampInteger(options.delivery?.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE, 1),
219
- warnOnFailure: options.delivery?.warnOnFailure ?? true,
220
- onSuccess: options.delivery?.onSuccess,
221
- onRetry: options.delivery?.onRetry,
222
- onFailure: options.delivery?.onFailure,
223
- onDrop: options.delivery?.onDrop
224
- };
225
- const queue = [];
226
- let inFlight;
227
- let flushTimer;
228
- let isProcessing = false;
229
- let unsubscribeFromResume;
230
- const runtimeLabel = options.runtime === "browser" ? "client" : options.runtime;
231
- const clearFlushTimer = () => {
232
- if (!flushTimer) {
233
- return;
234
- }
235
- clearTimeout(flushTimer);
236
- flushTimer = void 0;
237
- };
238
- const hasUnsentEvents = () => queue.length > 0 || inFlight !== void 0;
239
- const refreshResumeSubscription = (flush2) => {
240
- if (!options.subscribeToResume) {
241
- return;
242
- }
243
- if (hasUnsentEvents()) {
244
- if (!unsubscribeFromResume) {
245
- unsubscribeFromResume = options.subscribeToResume(() => {
246
- const now = Date.now();
247
- for (const item of queue) {
248
- item.nextAttemptAt = now;
249
- }
250
- clearFlushTimer();
251
- flush2();
252
- }) ?? void 0;
253
- }
254
- return;
255
- }
256
- if (unsubscribeFromResume) {
257
- unsubscribeFromResume();
258
- unsubscribeFromResume = void 0;
259
- }
260
- };
261
- const warnDrop = (ctx) => {
262
- if (!deliveryConfig.warnOnFailure) {
263
- return;
264
- }
265
- warn(
266
- `[blyp/${runtimeLabel}] Dropped queued log "${ctx.droppedEvent.message}" (id: ${ctx.droppedEvent.id}) because the delivery queue reached ${ctx.maxQueueSize}. Keeping "${ctx.replacementEvent.message}" (id: ${ctx.replacementEvent.id}) instead.`
267
- );
268
- };
269
- const warnFailure = (ctx, suppressWarning) => {
270
- if (!deliveryConfig.warnOnFailure || suppressWarning) {
271
- return;
272
- }
273
- const details = [
274
- `reason=${ctx.reason}`,
275
- `attempt=${formatWarningValue(ctx.attempt)}`,
276
- `status=${formatWarningValue(ctx.status)}`
277
- ];
278
- if (ctx.error) {
279
- details.push(`error=${ctx.error}`);
280
- }
281
- warn(
282
- `[blyp/${runtimeLabel}] Failed to deliver log "${ctx.event.message}" (id: ${ctx.event.id}, ${details.join(", ")})`
283
- );
284
- };
285
- const totalUnsentEvents = () => queue.length + (inFlight ? 1 : 0);
286
- const scheduleFlush = (flush2) => {
287
- clearFlushTimer();
288
- if (queue.length === 0) {
289
- refreshResumeSubscription(flush2);
290
- return;
291
- }
292
- const nextAttemptAt = queue.reduce((lowest, item) => {
293
- return Math.min(lowest, item.nextAttemptAt);
294
- }, Number.POSITIVE_INFINITY);
295
- const delay = Math.max(nextAttemptAt - Date.now(), 0);
296
- flushTimer = setTimeout(() => {
297
- flushTimer = void 0;
298
- flush2();
299
- }, delay);
300
- refreshResumeSubscription(flush2);
301
- };
302
- const emitDrop = (droppedEvent, replacementEvent) => {
303
- const context = {
304
- runtime: options.runtime,
305
- droppedEvent,
306
- replacementEvent,
307
- maxQueueSize: deliveryConfig.maxQueueSize,
308
- reason: "queue_overflow"
309
- };
310
- safeCall(deliveryConfig.onDrop, context);
311
- warnDrop(context);
312
- };
313
- const enforceQueueCapacity = () => {
314
- while (totalUnsentEvents() > deliveryConfig.maxQueueSize && queue.length > 0) {
315
- const droppedItem = queue.shift();
316
- const replacementEvent = queue[queue.length - 1]?.event ?? inFlight?.event;
317
- if (!droppedItem || !replacementEvent) {
318
- break;
319
- }
320
- emitDrop(droppedItem.event, replacementEvent);
321
- }
322
- };
323
- const getNextReadyIndex = () => {
324
- const now = Date.now();
325
- for (let index = 0; index < queue.length; index += 1) {
326
- if (queue[index].nextAttemptAt <= now) {
327
- return index;
328
- }
329
- }
330
- return -1;
331
- };
332
- const flush = async () => {
333
- if (isProcessing) {
334
- return;
335
- }
336
- isProcessing = true;
337
- try {
338
- while (true) {
339
- const nextIndex = getNextReadyIndex();
340
- if (nextIndex === -1) {
341
- break;
342
- }
343
- const item = queue.splice(nextIndex, 1)[0];
344
- if (!item) {
345
- continue;
346
- }
347
- inFlight = item;
348
- refreshResumeSubscription(() => {
349
- void flush();
350
- });
351
- item.attempt += 1;
352
- const result = await options.send(item.event);
353
- inFlight = void 0;
354
- if (result.outcome === "success") {
355
- const context = {
356
- runtime: options.runtime,
357
- event: item.event,
358
- attempt: item.attempt,
359
- status: result.status,
360
- transport: result.transport
361
- };
362
- safeCall(deliveryConfig.onSuccess, context);
363
- continue;
364
- }
365
- if (result.outcome === "retry" && item.attempt <= deliveryConfig.maxRetries) {
366
- item.nextAttemptAt = Date.now() + deliveryConfig.retryDelayMs;
367
- queue.push(item);
368
- const context = {
369
- runtime: options.runtime,
370
- event: item.event,
371
- attempt: item.attempt,
372
- retriesRemaining: deliveryConfig.maxRetries - (item.attempt - 1),
373
- nextRetryAt: new Date(item.nextAttemptAt).toISOString(),
374
- reason: result.reason,
375
- status: result.status,
376
- error: result.error
377
- };
378
- safeCall(deliveryConfig.onRetry, context);
379
- continue;
380
- }
381
- const failureContext = {
382
- runtime: options.runtime,
383
- event: item.event,
384
- attempt: item.attempt,
385
- reason: result.reason,
386
- status: result.status,
387
- error: result.error
388
- };
389
- safeCall(deliveryConfig.onFailure, failureContext);
390
- warnFailure(
391
- failureContext,
392
- result.outcome === "failure" ? result.suppressWarning : void 0
393
- );
394
- }
395
- } finally {
396
- isProcessing = false;
397
- scheduleFlush(() => {
398
- void flush();
399
- });
400
- }
401
- };
402
- return {
403
- enqueue(event) {
404
- queue.push({
405
- event,
406
- attempt: 0,
407
- nextAttemptAt: Date.now()
408
- });
409
- enforceQueueCapacity();
410
- scheduleFlush(() => {
411
- void flush();
412
- });
413
- void flush();
414
- }
415
- };
416
- }
417
-
418
- // src/shared/once.ts
419
- function createConsoleOnceLogger(method, warnedKeys = /* @__PURE__ */ new Set()) {
420
- return (key, message, error) => {
421
- if (warnedKeys.has(key) || typeof console === "undefined") {
422
- return;
423
- }
424
- const writer = console[method];
425
- if (typeof writer !== "function") {
426
- return;
427
- }
428
- warnedKeys.add(key);
429
- if (error === void 0) {
430
- writer.call(console, message);
431
- return;
432
- }
433
- writer.call(console, message, error);
434
- };
435
- }
436
- function createErrorOnceLogger(warnedKeys) {
437
- return createConsoleOnceLogger("error", warnedKeys);
438
- }
439
-
440
- // src/frameworks/client/logger.ts
441
- var warnedMessages = /* @__PURE__ */ new Set();
442
- var errorOnce = createErrorOnceLogger(warnedMessages);
443
- function resolveHeaders(headers) {
444
- return {
445
- "content-type": "application/json",
446
- ...headers ?? {}
447
- };
448
- }
449
- function shouldUseBeaconFallback(headers) {
450
- return Object.keys(headers ?? {}).length === 0;
451
- }
452
- function isRetryableStatus(status) {
453
- return status === 429 || status >= 500;
454
- }
455
- function isBrowserRuntime() {
456
- return typeof navigator !== "undefined" && typeof location !== "undefined";
457
- }
458
- async function sendRemoteLog(config, payload) {
459
- if (typeof navigator !== "undefined" && navigator.onLine === false) {
460
- return {
461
- outcome: "retry",
462
- reason: "offline"
463
- };
464
- }
465
- if (typeof fetch !== "function") {
466
- return {
467
- outcome: "failure",
468
- reason: "missing_transport",
469
- suppressWarning: true
470
- };
471
- }
472
- const body = JSON.stringify(payload);
473
- const headers = resolveHeaders(config.headers);
474
- const canUseBeacon = shouldUseBeaconFallback(config.headers) && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function" && typeof Blob !== "undefined";
475
- try {
476
- const response = await fetch(config.endpoint, {
477
- method: "POST",
478
- keepalive: true,
479
- credentials: config.credentials,
480
- headers,
481
- body
482
- });
483
- if (response.ok) {
484
- if (config.connector === "betterstack" && response.headers.get("x-blyp-betterstack-status") === "missing") {
485
- errorOnce(
486
- "betterstack-missing",
487
- "[blyp/client] Better Stack connector requested but not configured on the server. Continuing without Better Stack forwarding."
488
- );
489
- }
490
- if (config.connector === "databuddy" && response.headers.get("x-blyp-databuddy-status") === "missing") {
491
- errorOnce(
492
- "databuddy-missing",
493
- "[blyp/client] Databuddy connector requested but not configured on the server. Continuing without Databuddy forwarding."
494
- );
495
- }
496
- if (config.connector === "posthog" && response.headers.get("x-blyp-posthog-status") === "missing") {
497
- errorOnce(
498
- "posthog-missing",
499
- "[blyp/client] PostHog connector requested but not configured on the server. Continuing without PostHog forwarding."
500
- );
501
- }
502
- if (config.connector === "sentry" && response.headers.get("x-blyp-sentry-status") === "missing") {
503
- errorOnce(
504
- "sentry-missing",
505
- "[blyp/client] Sentry not setup. Continuing without Sentry forwarding."
506
- );
507
- }
508
- if (config.connector && typeof config.connector === "object" && config.connector.type === "otlp" && response.headers.get("x-blyp-otlp-status") === "missing") {
509
- errorOnce(
510
- `otlp-missing:${config.connector.name}`,
511
- `[blyp/client] OTLP target "${config.connector.name}" was requested but not configured on the server. Continuing without OTLP forwarding.`
512
- );
513
- }
514
- return {
515
- outcome: "success",
516
- transport: "fetch",
517
- status: response.status
518
- };
519
- }
520
- if (isRetryableStatus(response.status)) {
521
- return {
522
- outcome: "retry",
523
- reason: "response_status",
524
- status: response.status
525
- };
526
- }
527
- return {
528
- outcome: "failure",
529
- reason: "response_status",
530
- status: response.status
531
- };
532
- } catch (error) {
533
- if (canUseBeacon) {
534
- try {
535
- if (navigator.sendBeacon(
536
- config.endpoint,
537
- new Blob([body], { type: "application/json" })
538
- )) {
539
- return {
540
- outcome: "success",
541
- transport: "beacon"
542
- };
543
- }
544
- } catch {
545
- }
546
- }
547
- return {
548
- outcome: "retry",
549
- reason: "network_error",
550
- error: error instanceof Error ? error.message : String(error)
551
- };
552
- }
553
- }
554
- function emitLocalConsole(level, message, args) {
555
- if (typeof console === "undefined") {
556
- return;
557
- }
558
- const normalizedArgs = args.map((entry) => normalizeLogValue(entry));
559
- const text = serializeLogMessage(message);
560
- switch (level) {
561
- case "table":
562
- console.log(text);
563
- if (normalizedArgs.length > 0 && typeof console.table === "function") {
564
- console.table(normalizedArgs[0]);
565
- }
566
- return;
567
- case "warning":
568
- case "warn":
569
- console.warn(text, ...normalizedArgs);
570
- return;
571
- case "error":
572
- case "critical":
573
- console.error(text, ...normalizedArgs);
574
- return;
575
- case "debug":
576
- console.debug(text, ...normalizedArgs);
577
- return;
578
- case "success":
579
- console.log(text, ...normalizedArgs);
580
- return;
581
- case "info":
582
- default:
583
- console.info(text, ...normalizedArgs);
584
- }
585
- }
586
- function buildClientLogger(config, state) {
587
- const resolvedConfig = {
588
- endpoint: config.endpoint ?? DEFAULT_CLIENT_LOG_ENDPOINT,
589
- headers: config.headers,
590
- credentials: config.credentials ?? "same-origin",
591
- localConsole: config.localConsole ?? true,
592
- remoteSync: config.remoteSync ?? true,
593
- connector: config.connector,
594
- metadata: config.metadata
595
- };
596
- const delivery = state.delivery ?? (resolvedConfig.remoteSync && isBrowserRuntime() && typeof fetch === "function" ? createRemoteDeliveryManager({
597
- runtime: "browser",
598
- delivery: config.delivery,
599
- send: (event) => sendRemoteLog(resolvedConfig, event),
600
- subscribeToResume: (resume) => {
601
- if (typeof globalThis.addEventListener !== "function") {
602
- return;
603
- }
604
- const listener = () => {
605
- resume();
606
- };
607
- globalThis.addEventListener("online", listener);
608
- return () => {
609
- if (typeof globalThis.removeEventListener === "function") {
610
- globalThis.removeEventListener("online", listener);
611
- }
612
- };
613
- }
614
- }) : void 0);
615
- const writeLog = (level, message, args) => {
616
- if (resolvedConfig.localConsole) {
617
- emitLocalConsole(level, message, args);
618
- }
619
- if (!resolvedConfig.remoteSync) {
620
- return;
621
- }
622
- const normalizedLevel = normalizeClientLogLevel(level);
623
- const normalizedMessage = serializeLogMessage(message);
624
- const normalizedData = normalizeClientPayloadData(message, args);
625
- const metadata = normalizeMetadata(resolvedConfig.metadata);
626
- const payload = {
627
- type: "client_log",
628
- source: "client",
629
- id: createRandomId(),
630
- level: normalizedLevel,
631
- message: normalizedMessage,
632
- connector: resolvedConfig.connector,
633
- data: normalizedData,
634
- bindings: Object.keys(state.bindings).length > 0 ? normalizeLogValue(state.bindings) : void 0,
635
- clientTimestamp: (/* @__PURE__ */ new Date()).toISOString(),
636
- page: getBrowserPageContext(),
637
- browser: getBrowserContext(),
638
- session: {
639
- pageId: state.pageId,
640
- sessionId: state.sessionId
641
- },
642
- metadata
643
- };
644
- delivery?.enqueue(payload);
645
- };
646
- return {
647
- debug: (message, ...args) => {
648
- writeLog("debug", message, args);
649
- },
650
- info: (message, ...args) => {
651
- writeLog("info", message, args);
652
- },
653
- error: (message, ...args) => {
654
- writeLog("error", message, args);
655
- },
656
- warn: (message, ...args) => {
657
- writeLog("warn", message, args);
658
- },
659
- warning: (message, ...args) => {
660
- writeLog("warning", message, args);
661
- },
662
- success: (message, ...args) => {
663
- writeLog("success", message, args);
664
- },
665
- critical: (message, ...args) => {
666
- writeLog("critical", message, args);
667
- },
668
- table: (message, data) => {
669
- writeLog("table", message, data === void 0 ? [] : [data]);
670
- },
671
- child: (bindings) => {
672
- return buildClientLogger(config, {
673
- ...state,
674
- bindings: {
675
- ...state.bindings,
676
- ...bindings
677
- },
678
- delivery
679
- });
680
- }
681
- };
682
- }
683
- function createClientLogger(config = {}) {
684
- return buildClientLogger(config, {
685
- pageId: createRandomId(),
686
- sessionId: getClientSessionId(),
687
- bindings: {}
688
- });
689
- }
690
- var logger = createClientLogger();
691
-
692
- // src/shared/errors.ts
693
- var HTTP_STATUS_DEFINITIONS = {
694
- CONTINUE: { status: 100, message: "Continue" },
695
- SWITCHING_PROTOCOLS: { status: 101, message: "Switching Protocols" },
696
- PROCESSING: { status: 102, message: "Processing" },
697
- EARLY_HINTS: { status: 103, message: "Early Hints" },
698
- OK: { status: 200, message: "OK" },
699
- CREATED: { status: 201, message: "Created" },
700
- ACCEPTED: { status: 202, message: "Accepted" },
701
- NON_AUTHORITATIVE_INFORMATION: { status: 203, message: "Non-Authoritative Information" },
702
- NO_CONTENT: { status: 204, message: "No Content" },
703
- RESET_CONTENT: { status: 205, message: "Reset Content" },
704
- PARTIAL_CONTENT: { status: 206, message: "Partial Content" },
705
- MULTI_STATUS: { status: 207, message: "Multi-Status" },
706
- ALREADY_REPORTED: { status: 208, message: "Already Reported" },
707
- IM_USED: { status: 226, message: "IM Used" },
708
- MULTIPLE_CHOICES: { status: 300, message: "Multiple Choices" },
709
- MOVED_PERMANENTLY: { status: 301, message: "Moved Permanently" },
710
- FOUND: { status: 302, message: "Found" },
711
- SEE_OTHER: { status: 303, message: "See Other" },
712
- NOT_MODIFIED: { status: 304, message: "Not Modified" },
713
- USE_PROXY: { status: 305, message: "Use Proxy" },
714
- TEMPORARY_REDIRECT: { status: 307, message: "Temporary Redirect" },
715
- PERMANENT_REDIRECT: { status: 308, message: "Permanent Redirect" },
716
- BAD_REQUEST: { status: 400, message: "Bad Request" },
717
- UNAUTHORIZED: { status: 401, message: "Unauthorized" },
718
- PAYMENT_REQUIRED: { status: 402, message: "Payment Required" },
719
- FORBIDDEN: { status: 403, message: "Forbidden" },
720
- NOT_FOUND: { status: 404, message: "Not Found" },
721
- METHOD_NOT_ALLOWED: { status: 405, message: "Method Not Allowed" },
722
- NOT_ACCEPTABLE: { status: 406, message: "Not Acceptable" },
723
- PROXY_AUTHENTICATION_REQUIRED: { status: 407, message: "Proxy Authentication Required" },
724
- REQUEST_TIMEOUT: { status: 408, message: "Request Timeout" },
725
- CONFLICT: { status: 409, message: "Conflict" },
726
- GONE: { status: 410, message: "Gone" },
727
- LENGTH_REQUIRED: { status: 411, message: "Length Required" },
728
- PRECONDITION_FAILED: { status: 412, message: "Precondition Failed" },
729
- PAYLOAD_TOO_LARGE: { status: 413, message: "Payload Too Large" },
730
- URI_TOO_LONG: { status: 414, message: "URI Too Long" },
731
- UNSUPPORTED_MEDIA_TYPE: { status: 415, message: "Unsupported Media Type" },
732
- RANGE_NOT_SATISFIABLE: { status: 416, message: "Range Not Satisfiable" },
733
- EXPECTATION_FAILED: { status: 417, message: "Expectation Failed" },
734
- IM_A_TEAPOT: { status: 418, message: "I'm a Teapot" },
735
- MISDIRECTED_REQUEST: { status: 421, message: "Misdirected Request" },
736
- UNPROCESSABLE_ENTITY: { status: 422, message: "Unprocessable Entity" },
737
- LOCKED: { status: 423, message: "Locked" },
738
- FAILED_DEPENDENCY: { status: 424, message: "Failed Dependency" },
739
- TOO_EARLY: { status: 425, message: "Too Early" },
740
- UPGRADE_REQUIRED: { status: 426, message: "Upgrade Required" },
741
- PRECONDITION_REQUIRED: { status: 428, message: "Precondition Required" },
742
- TOO_MANY_REQUESTS: { status: 429, message: "Too Many Requests" },
743
- REQUEST_HEADER_FIELDS_TOO_LARGE: { status: 431, message: "Request Header Fields Too Large" },
744
- UNAVAILABLE_FOR_LEGAL_REASONS: { status: 451, message: "Unavailable For Legal Reasons" },
745
- INTERNAL_SERVER_ERROR: { status: 500, message: "Internal Server Error" },
746
- NOT_IMPLEMENTED: { status: 501, message: "Not Implemented" },
747
- BAD_GATEWAY: { status: 502, message: "Bad Gateway" },
748
- SERVICE_UNAVAILABLE: { status: 503, message: "Service Unavailable" },
749
- GATEWAY_TIMEOUT: { status: 504, message: "Gateway Timeout" },
750
- HTTP_VERSION_NOT_SUPPORTED: { status: 505, message: "HTTP Version Not Supported" },
751
- VARIANT_ALSO_NEGOTIATES: { status: 506, message: "Variant Also Negotiates" },
752
- INSUFFICIENT_STORAGE: { status: 507, message: "Insufficient Storage" },
753
- LOOP_DETECTED: { status: 508, message: "Loop Detected" },
754
- BANDWIDTH_LIMIT_EXCEEDED: { status: 509, message: "Bandwidth Limit Exceeded" },
755
- NOT_EXTENDED: { status: 510, message: "Not Extended" },
756
- NETWORK_AUTHENTICATION_REQUIRED: { status: 511, message: "Network Authentication Required" }
757
- };
758
- var ERROR_KEYS = [
759
- "status",
760
- "statusCode",
761
- "code",
762
- "message",
763
- "stack",
764
- "why",
765
- "fix",
766
- "link",
767
- "details",
768
- "cause",
769
- "title",
770
- "detail",
771
- "logLevel",
772
- "error",
773
- "data"
774
- ];
775
- function isErrorLogLevel(value) {
776
- return value === "debug" || value === "info" || value === "warning" || value === "error" || value === "critical";
777
- }
778
- function parseStatus(value) {
779
- if (typeof value === "number" && Number.isFinite(value)) {
780
- return value;
781
- }
782
- if (typeof value === "string" && /^\d+$/.test(value.trim())) {
783
- return Number.parseInt(value, 10);
784
- }
785
- return void 0;
786
- }
787
- function normalizeDetails(value) {
788
- return isPlainObject(value) ? value : void 0;
789
- }
790
- function hasMeaningfulErrorData(candidate) {
791
- return candidate.status !== void 0 || candidate.statusCode !== void 0 || candidate.code !== void 0 || candidate.message !== void 0 || candidate.stack !== void 0 || candidate.why !== void 0 || candidate.fix !== void 0 || candidate.link !== void 0 || candidate.details !== void 0 || candidate.cause !== void 0 || candidate.logLevel !== void 0;
792
- }
793
- function normalizeRecordCandidate(record) {
794
- const title = typeof record.title === "string" ? record.title : void 0;
795
- const detail = typeof record.detail === "string" ? record.detail : void 0;
796
- return {
797
- status: parseStatus(record.status),
798
- statusCode: parseStatus(record.statusCode),
799
- code: typeof record.code === "string" || typeof record.code === "number" ? record.code : void 0,
800
- message: typeof record.message === "string" ? record.message : title ?? detail,
801
- stack: typeof record.stack === "string" ? record.stack : void 0,
802
- why: typeof record.why === "string" ? record.why : void 0,
803
- fix: typeof record.fix === "string" ? record.fix : void 0,
804
- link: typeof record.link === "string" ? record.link : void 0,
805
- details: normalizeDetails(record.details),
806
- cause: record.cause,
807
- logLevel: isErrorLogLevel(record.logLevel) ? record.logLevel : void 0
808
- };
809
- }
810
- function mergeCandidates(container, nested) {
811
- const own = normalizeRecordCandidate(container);
812
- if (nested === void 0) {
813
- return hasMeaningfulErrorData(own) ? own : void 0;
814
- }
815
- if (typeof nested === "string") {
816
- if (hasMeaningfulErrorData(own)) {
817
- return {
818
- ...own,
819
- message: own.message ?? nested
820
- };
821
- }
822
- return nested;
823
- }
824
- return {
825
- status: own.status ?? nested.status,
826
- statusCode: own.statusCode ?? nested.statusCode,
827
- code: own.code ?? nested.code,
828
- message: own.message ?? nested.message,
829
- stack: own.stack ?? nested.stack,
830
- why: own.why ?? nested.why,
831
- fix: own.fix ?? nested.fix,
832
- link: own.link ?? nested.link,
833
- details: own.details ?? nested.details,
834
- cause: own.cause ?? nested.cause,
835
- logLevel: own.logLevel ?? nested.logLevel
836
- };
837
- }
838
- function hasErrorShape(record) {
839
- return ERROR_KEYS.some((key) => record[key] !== void 0);
840
- }
841
- function isResponseLike(input) {
842
- if (typeof Response !== "undefined" && input instanceof Response) {
843
- return true;
844
- }
845
- return isPlainObject(input) && typeof input.status === "number" && typeof input.statusText === "string" && typeof input.clone === "function" && typeof input.text === "function";
846
- }
847
- var BlypError = class _BlypError extends Error {
848
- constructor(config) {
849
- super(config.message);
850
- __publicField(this, "name", "BlypError");
851
- __publicField(this, "status");
852
- __publicField(this, "statusCode");
853
- __publicField(this, "code");
854
- __publicField(this, "why");
855
- __publicField(this, "fix");
856
- __publicField(this, "link");
857
- __publicField(this, "details");
858
- __publicField(this, "cause");
859
- __publicField(this, "logLevel");
860
- Object.setPrototypeOf(this, new.target.prototype);
861
- this.status = config.status;
862
- this.statusCode = config.statusCode;
863
- this.code = config.code;
864
- this.why = config.why;
865
- this.fix = config.fix;
866
- this.link = config.link;
867
- this.details = config.details;
868
- this.cause = config.cause;
869
- this.logLevel = config.logLevel;
870
- if (config.stack) {
871
- this.stack = config.stack;
872
- } else if (typeof Error.captureStackTrace === "function") {
873
- Error.captureStackTrace(this, _BlypError);
874
- }
875
- }
876
- toJSON() {
877
- return {
878
- name: "BlypError",
879
- message: this.message,
880
- status: this.status,
881
- statusCode: this.statusCode,
882
- ...this.code !== void 0 ? { code: this.code } : {},
883
- ...this.why !== void 0 ? { why: this.why } : {},
884
- ...this.fix !== void 0 ? { fix: this.fix } : {},
885
- ...this.link !== void 0 ? { link: this.link } : {},
886
- ...this.details !== void 0 ? { details: this.details } : {}
887
- };
888
- }
889
- };
890
- function resolveErrorLogLevel(status, explicit) {
891
- if (explicit) {
892
- return explicit;
893
- }
894
- if (status >= 500) {
895
- return "critical";
896
- }
897
- if (status >= 400) {
898
- return "error";
899
- }
900
- return "warning";
901
- }
902
- function normalizeCauseForLog(cause) {
903
- if (cause instanceof Error) {
904
- return {
905
- name: cause.name,
906
- message: cause.message,
907
- ...cause.stack ? { stack: cause.stack } : {}
908
- };
909
- }
910
- return cause;
911
- }
912
- function emitErrorLog(logger2, error, levelOverride) {
913
- const level = resolveErrorLogLevel(error.status, levelOverride ?? error.logLevel);
914
- const logMethod = (() => {
915
- switch (level) {
916
- case "debug":
917
- return logger2.debug;
918
- case "info":
919
- return logger2.info;
920
- case "warning":
921
- return logger2.warning;
922
- case "critical":
923
- return logger2.critical;
924
- case "error":
925
- default:
926
- return logger2.error;
927
- }
928
- })();
929
- logMethod(error.message, {
930
- type: "application_error",
931
- status: error.status,
932
- statusCode: error.statusCode,
933
- code: error.code,
934
- why: error.why,
935
- fix: error.fix,
936
- link: error.link,
937
- details: error.details,
938
- cause: normalizeCauseForLog(error.cause)
939
- });
940
- }
941
- function resolveErrorConfig(input, defaults = {}) {
942
- const candidateStatus = input.status ?? input.statusCode;
943
- const status = candidateStatus ?? defaults.status ?? defaults.statusCode ?? 500;
944
- const preset = getHttpCode(status);
945
- const message = input.message ?? defaults.message ?? preset?.message ?? `HTTP ${status}`;
946
- return {
947
- status,
948
- statusCode: status,
949
- message,
950
- code: input.code ?? defaults.code ?? preset?.code,
951
- why: input.why ?? defaults.why ?? preset?.why,
952
- fix: input.fix ?? defaults.fix ?? preset?.fix,
953
- link: input.link ?? defaults.link ?? preset?.link,
954
- details: input.details ?? defaults.details ?? preset?.details,
955
- cause: input.cause ?? defaults.cause,
956
- stack: input.stack ?? defaults.stack,
957
- logLevel: resolveErrorLogLevel(
958
- status,
959
- input.logLevel ?? defaults.logLevel ?? preset?.logLevel
960
- )
961
- };
962
- }
963
- function createBlypError(input, defaults = {}) {
964
- const error = new BlypError(resolveErrorConfig(input, defaults));
965
- if (input.skipLogging !== true && input.logger) {
966
- emitErrorLog(input.logger, error, input.logLevel);
967
- }
968
- return error;
969
- }
970
- function createErrorCode(definition, createErrorFromCode) {
971
- const errorCode = {
972
- ...definition,
973
- statusCode: definition.status,
974
- create(overrides = {}) {
975
- return createBlypError({
976
- status: definition.status,
977
- message: definition.message,
978
- code: overrides.code ?? definition.code,
979
- why: overrides.why ?? definition.why,
980
- fix: overrides.fix ?? definition.fix,
981
- link: overrides.link ?? definition.link,
982
- details: overrides.details ?? definition.details,
983
- cause: overrides.cause,
984
- stack: overrides.stack,
985
- logLevel: overrides.logLevel ?? definition.logLevel,
986
- logger: overrides.logger,
987
- skipLogging: overrides.skipLogging
988
- });
989
- },
990
- extend(extension) {
991
- return createErrorCode(
992
- {
993
- key: extension.code,
994
- status: definition.status,
995
- message: extension.message ?? definition.message,
996
- code: extension.code,
997
- why: extension.why ?? definition.why,
998
- fix: extension.fix ?? definition.fix,
999
- link: extension.link ?? definition.link,
1000
- details: extension.details ?? definition.details,
1001
- logLevel: extension.logLevel ?? definition.logLevel
1002
- });
1003
- }
1004
- };
1005
- return Object.freeze(errorCode);
1006
- }
1007
- function buildHttpCodeRegistry(createErrorFromCode) {
1008
- const entries = Object.entries(HTTP_STATUS_DEFINITIONS).map(([key, value]) => {
1009
- return [key, createErrorCode({ key, ...value })];
1010
- });
1011
- return Object.freeze(
1012
- Object.fromEntries(entries)
1013
- );
1014
- }
1015
- var HTTP_CODES = buildHttpCodeRegistry();
1016
- var httpCodeByStatus = new Map(
1017
- Object.values(HTTP_CODES).map((value) => [value.status, value])
1018
- );
1019
- function getHttpCode(status) {
1020
- return httpCodeByStatus.get(status);
1021
- }
1022
- function extractErrorCandidate(payload) {
1023
- if (typeof payload === "string") {
1024
- return payload;
1025
- }
1026
- if (!isPlainObject(payload)) {
1027
- return void 0;
1028
- }
1029
- if (payload.error !== void 0) {
1030
- const nested = payload.error;
1031
- if (typeof nested === "string") {
1032
- return mergeCandidates(payload, nested);
1033
- }
1034
- if (isPlainObject(nested)) {
1035
- return mergeCandidates(payload, extractErrorCandidate(nested));
1036
- }
1037
- }
1038
- if (isPlainObject(payload.data)) {
1039
- const nested = payload.data;
1040
- if (nested.error !== void 0 || hasErrorShape(nested)) {
1041
- return mergeCandidates(payload, extractErrorCandidate(nested));
1042
- }
1043
- }
1044
- if (hasErrorShape(payload)) {
1045
- return normalizeRecordCandidate(payload);
1046
- }
1047
- return void 0;
1048
- }
1049
- function coercePayloadToError(payload, options = {}, responseContext = {}) {
1050
- if (payload instanceof BlypError) {
1051
- return payload;
1052
- }
1053
- const candidate = (() => {
1054
- if (payload instanceof Error) {
1055
- const errorWithMetadata = payload;
1056
- return {
1057
- status: errorWithMetadata.status,
1058
- statusCode: errorWithMetadata.statusCode,
1059
- code: errorWithMetadata.code,
1060
- message: payload.message,
1061
- stack: payload.stack,
1062
- why: errorWithMetadata.why,
1063
- fix: errorWithMetadata.fix,
1064
- link: errorWithMetadata.link,
1065
- details: errorWithMetadata.details,
1066
- cause: errorWithMetadata.cause,
1067
- logLevel: errorWithMetadata.logLevel
1068
- };
1069
- }
1070
- return extractErrorCandidate(payload);
1071
- })();
1072
- const responseStatus = responseContext.status && responseContext.status > 0 ? responseContext.status : void 0;
1073
- const candidateStatus = typeof candidate === "string" ? void 0 : candidate?.status ?? candidate?.statusCode;
1074
- const status = responseStatus ?? candidateStatus ?? options.fallbackStatus ?? 500;
1075
- const textBody = typeof candidate === "string" ? candidate.trim() || void 0 : void 0;
1076
- const statusText = responseContext.statusText?.trim() || void 0;
1077
- return createBlypError(
1078
- typeof candidate === "string" ? { message: textBody, ...responseStatus !== void 0 ? { status: responseStatus } : {} } : {
1079
- ...candidate ?? {},
1080
- ...responseStatus !== void 0 ? {
1081
- status: responseStatus,
1082
- statusCode: responseStatus
1083
- } : {}
1084
- },
1085
- {
1086
- status,
1087
- message: (typeof candidate === "string" ? textBody : candidate?.message) ?? statusText ?? getHttpCode(status)?.message ?? `HTTP ${status}`
1088
- }
1089
- );
1090
- }
1091
- async function readResponseErrorPayload(response) {
1092
- const contentType = response.headers.get("content-type")?.toLowerCase();
1093
- const isJsonResponse = contentType?.includes("application/json") || contentType?.includes("+json");
1094
- if (isJsonResponse) {
1095
- try {
1096
- return await response.clone().json();
1097
- } catch {
1098
- try {
1099
- return await response.clone().text();
1100
- } catch {
1101
- return void 0;
1102
- }
1103
- }
1104
- }
1105
- try {
1106
- return await response.clone().text();
1107
- } catch {
1108
- return void 0;
1109
- }
1110
- }
1111
- function parseError(input, options = {}) {
1112
- if (isResponseLike(input)) {
1113
- return (async () => {
1114
- const payload = await readResponseErrorPayload(input).catch(() => void 0);
1115
- const error2 = coercePayloadToError(payload, options, {
1116
- status: input.status,
1117
- statusText: input.statusText
1118
- });
1119
- if (options.logger) {
1120
- emitErrorLog(options.logger, error2, options.logLevel);
1121
- }
1122
- return error2;
1123
- })();
1124
- }
1125
- const error = coercePayloadToError(input, options);
1126
- if (options.logger) {
1127
- emitErrorLog(options.logger, error, options.logLevel);
1128
- }
1129
- return error;
1130
- }
1131
-
1132
- exports.BlypError = BlypError;
1133
- exports.HTTP_CODES = HTTP_CODES;
1134
- exports.createClientLogger = createClientLogger;
1135
- exports.getHttpCode = getHttpCode;
1136
- exports.logger = logger;
1137
- exports.parseError = parseError;
1138
- //# sourceMappingURL=client.js.map
1139
- //# sourceMappingURL=client.js.map
1
+ 'use strict';var zod=require('zod');var Le=Object.defineProperty;var he=(e,t,n)=>t in e?Le(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var d=(e,t,n)=>he(e,typeof t!="symbol"?t+"":t,n);function _(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=f(n.cause)),t}function f(e,t=new WeakSet){if(e instanceof Error)return _(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=>f(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let n={};for(let[r,s]of Object.entries(e))n[r]=f(s,t);return t.delete(e),n}return e}function L(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=f(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}zod.z.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"});var q=zod.z.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),j=zod.z.string().trim().min(1);function m(e){return q.safeParse(e).success}var Q="/inngest",$="blyp:session-id";zod.z.union([zod.z.literal("betterstack"),zod.z.literal("databuddy"),zod.z.literal("posthog"),zod.z.literal("sentry"),zod.z.undefined(),zod.z.object({type:zod.z.literal("otlp"),name:j})]);function y(e){try{return e()}catch{return}}function we(){return Math.random().toString(36).slice(2,10)}function D(){let e=y(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${we()}`}function G(e){return e==="warn"?"warning":e}function Y(e,t){let n=t.map(o=>f(o)),r=e instanceof Error?_(e):void 0;if(r!==void 0&&n.length===0)return r;let s=r===void 0?n:[r,...n];if(s.length!==0)return s.length===1?s[0]:s}function V(){let e=y(()=>globalThis.location),t=y(()=>globalThis.document);return {url:e?.href,pathname:e?.pathname,search:e?.search,hash:e?.hash,title:t?.title,referrer:t?.referrer}}function W(){let e=y(()=>globalThis.navigator);return {userAgent:e?.userAgent,language:e?.language,platform:e?.platform}}function Z(){let e=y(()=>globalThis.sessionStorage),t=y(()=>e?.getItem($));if(t)return t;let n=D();return y(()=>e?.setItem($,n)),n}function X(e){if(e===void 0)return;let t=typeof e=="function"?y(e):e;if(m(t))return f(t)}function I(e,t,n){return Number.isFinite(e)?Math.max(n,Math.floor(e)):t}function S(e,t){if(e)try{e(t);}catch{}}function K(e){typeof console>"u"||typeof console.warn!="function"||console.warn(e);}function J(e){return e===void 0?"unknown":String(e)}function ee(e){let t={maxRetries:I(e.delivery?.maxRetries,3,0),retryDelayMs:I(e.delivery?.retryDelayMs,5e3,0),maxQueueSize:I(e.delivery?.maxQueueSize,100,1),warnOnFailure:e.delivery?.warnOnFailure??true,onSuccess:e.delivery?.onSuccess,onRetry:e.delivery?.onRetry,onFailure:e.delivery?.onFailure,onDrop:e.delivery?.onDrop},n=[],r,s,o=false,i,g=e.runtime==="browser"?"client":e.runtime,C=()=>{s&&(clearTimeout(s),s=void 0);},c=()=>n.length>0||r!==void 0,h=a=>{if(e.subscribeToResume){if(c()){i||(i=e.subscribeToResume(()=>{let u=Date.now();for(let l of n)l.nextAttemptAt=u;C(),a();})??void 0);return}i&&(i(),i=void 0);}},A=a=>{t.warnOnFailure&&K(`[blyp/${g}] Dropped queued log "${a.droppedEvent.message}" (id: ${a.droppedEvent.id}) because the delivery queue reached ${a.maxQueueSize}. Keeping "${a.replacementEvent.message}" (id: ${a.replacementEvent.id}) instead.`);},O=(a,u)=>{if(!t.warnOnFailure||u)return;let l=[`reason=${a.reason}`,`attempt=${J(a.attempt)}`,`status=${J(a.status)}`];a.error&&l.push(`error=${a.error}`),K(`[blyp/${g}] Failed to deliver log "${a.event.message}" (id: ${a.event.id}, ${l.join(", ")})`);},ye=()=>n.length+(r?1:0),H=a=>{if(C(),n.length===0){h(a);return}let u=n.reduce((v,w)=>Math.min(v,w.nextAttemptAt),Number.POSITIVE_INFINITY),l=Math.max(u-Date.now(),0);s=setTimeout(()=>{s=void 0,a();},l),h(a);},Ee=(a,u)=>{let l={runtime:e.runtime,droppedEvent:a,replacementEvent:u,maxQueueSize:t.maxQueueSize,reason:"queue_overflow"};S(t.onDrop,l),A(l);},Re=()=>{for(;ye()>t.maxQueueSize&&n.length>0;){let a=n.shift(),u=n[n.length-1]?.event??r?.event;if(!a||!u)break;Ee(a.event,u);}},Ce=()=>{let a=Date.now();for(let u=0;u<n.length;u+=1)if(n[u].nextAttemptAt<=a)return u;return -1},b=async()=>{if(!o){o=true;try{for(;;){let a=Ce();if(a===-1)break;let u=n.splice(a,1)[0];if(!u)continue;r=u,h(()=>{b();}),u.attempt+=1;let l=await e.send(u.event);if(r=void 0,l.outcome==="success"){let w={runtime:e.runtime,event:u.event,attempt:u.attempt,status:l.status,transport:l.transport};S(t.onSuccess,w);continue}if(l.outcome==="retry"&&u.attempt<=t.maxRetries){u.nextAttemptAt=Date.now()+t.retryDelayMs,n.push(u);let w={runtime:e.runtime,event:u.event,attempt:u.attempt,retriesRemaining:t.maxRetries-(u.attempt-1),nextRetryAt:new Date(u.nextAttemptAt).toISOString(),reason:l.reason,status:l.status,error:l.error};S(t.onRetry,w);continue}let v={runtime:e.runtime,event:u.event,attempt:u.attempt,reason:l.reason,status:l.status,error:l.error};S(t.onFailure,v),O(v,l.outcome==="failure"?l.suppressWarning:void 0);}}finally{o=false,H(()=>{b();});}}};return {enqueue(a){n.push({event:a,attempt:0,nextAttemptAt:Date.now()}),Re(),H(()=>{b();}),b();}}}var ke="[REDACTED]",Te=["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 be=[{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}],ve=/\b(?:\d[ -]*?){16}\b/g;function te(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 De(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Se(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function xe(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Ae(e){return e.split(".").filter(Boolean)}function N(e,t,n=0,r=0){if(n===e.length)return r===t.length;let s=e[n];if(s==="**"){if(n===e.length-1)return true;for(let o=r;o<=t.length;o+=1)if(N(e,t,n+1,o))return true;return false}return r>=t.length||s!=="*"&&s!==t[r]?false:N(e,t,n+1,r+1)}function Oe(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>N(Ae(n),e))}function _e(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,r=false;for(let s=t.length-1;s>=0;s-=1){let o=Number(t[s]);r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r;}return n%10===0}function ne(e,t,n){if(n||t.disablePatternScanning)return e;let r=e;for(let{type:s,pattern:o}of be)r=r.replace(o,`[REDACTED:${s}]`);r=r.replace(ve,s=>_e(s)?"[REDACTED:card]":s);for(let s of t.patterns)r=r.replace(De(s),"[REDACTED:pattern]");return r}function x(e,t,n,r){if(typeof e=="string")return ne(e,t,!!r.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((o,i)=>x(o,t,n,{path:[...r.path,String(i)],skipPatternScanning:r.skipPatternScanning}));if(!Se(e))return e;let s={};for(let[o,i]of Object.entries(e)){let g=[...r.path,o];if(n.has(o.toLowerCase())||Oe(g,t)){if(i==null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"){s[o]=ke;continue}s[o]=x(i,t,n,{path:g,skipPatternScanning:r.skipPatternScanning});continue}s[o]=x(i,t,n,{path:g,skipPatternScanning:r.skipPatternScanning});}return s}function re(e,t){return {keys:te([...Te,...[],...[]]),paths:te([...[],...[]]),patterns:[...[],...[]].filter(n=>n instanceof RegExp),disablePatternScanning:false}}function E(e,t,n={path:[]}){let r=f(e);return x(r,t,xe(t),n)}function U(e,t){return typeof e=="string"?ne(e,t,false):L(E(e,t))}function Pe(e,t=new Set){return (n,r,s)=>{if(t.has(n)||typeof console>"u")return;let o=console[e];if(typeof o=="function"){if(t.add(n),s===void 0){o.call(console,r);return}o.call(console,r,s);}}}function oe(e){return Pe("error",e)}var Ie=new Set,k=oe(Ie),R=re();function Ne(e){return {"content-type":"application/json",...e??{}}}function Ue(e){return Object.keys(e??{}).length===0}function Be(e){return e===429||e>=500}function ze(){return typeof navigator<"u"&&typeof location<"u"}async function Fe(e,t){if(typeof navigator<"u"&&navigator.onLine===false)return {outcome:"retry",reason:"offline"};if(typeof fetch!="function")return {outcome:"failure",reason:"missing_transport",suppressWarning:true};let n=JSON.stringify(t),r=Ne(e.headers),s=Ue(e.headers)&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&typeof Blob<"u";try{let o=await fetch(e.endpoint,{method:"POST",keepalive:!0,credentials:e.credentials,headers:r,body:n});return o.ok?(e.connector==="betterstack"&&o.headers.get("x-blyp-betterstack-status")==="missing"&&k("betterstack-missing","[blyp/client] Better Stack connector requested but not configured on the server. Continuing without Better Stack forwarding."),e.connector==="databuddy"&&o.headers.get("x-blyp-databuddy-status")==="missing"&&k("databuddy-missing","[blyp/client] Databuddy connector requested but not configured on the server. Continuing without Databuddy forwarding."),e.connector==="posthog"&&o.headers.get("x-blyp-posthog-status")==="missing"&&k("posthog-missing","[blyp/client] PostHog connector requested but not configured on the server. Continuing without PostHog forwarding."),e.connector==="sentry"&&o.headers.get("x-blyp-sentry-status")==="missing"&&k("sentry-missing","[blyp/client] Sentry not setup. Continuing without Sentry forwarding."),e.connector&&typeof e.connector=="object"&&e.connector.type==="otlp"&&o.headers.get("x-blyp-otlp-status")==="missing"&&k(`otlp-missing:${e.connector.name}`,`[blyp/client] OTLP target "${e.connector.name}" was requested but not configured on the server. Continuing without OTLP forwarding.`),{outcome:"success",transport:"fetch",status:o.status}):Be(o.status)?{outcome:"retry",reason:"response_status",status:o.status}:{outcome:"failure",reason:"response_status",status:o.status}}catch(o){if(s)try{if(navigator.sendBeacon(e.endpoint,new Blob([n],{type:"application/json"})))return {outcome:"success",transport:"beacon"}}catch{}return {outcome:"retry",reason:"network_error",error:o instanceof Error?o.message:String(o)}}}function Me(e,t,n){if(typeof console>"u")return;let r=n.map(i=>f(i)),s=r.map(i=>E(i,R)),o=U(L(t),R);switch(e){case "table":console.log(o),r.length>0&&typeof console.table=="function"&&console.table(s[0]);return;case "warning":case "warn":console.warn(o,...s);return;case "error":case "critical":console.error(o,...s);return;case "debug":console.debug(o,...s);return;case "success":console.log(o,...s);return;default:console.info(o,...s);}}function se(e,t){let n={endpoint:e.endpoint??Q,headers:e.headers,credentials:e.credentials??"same-origin",localConsole:e.localConsole??true,remoteSync:e.remoteSync??true,connector:e.connector,metadata:e.metadata},r=t.delivery??(n.remoteSync&&ze()&&typeof fetch=="function"?ee({runtime:"browser",delivery:e.delivery,send:o=>Fe(n,o),subscribeToResume:o=>{if(typeof globalThis.addEventListener!="function")return;let i=()=>{o();};return globalThis.addEventListener("online",i),()=>{typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("online",i);}}}):void 0),s=(o,i,g)=>{if(n.localConsole&&Me(o,i,g),!n.remoteSync)return;let C=G(o),c=U(L(i),R),h=E(Y(i,g),R),A=E(X(n.metadata),R),O={type:"client_log",source:"client",id:D(),traceId:t.traceId,level:C,message:c,connector:n.connector,data:h,bindings:Object.keys(t.bindings).length>0?E(t.bindings,R):void 0,clientTimestamp:new Date().toISOString(),page:V(),browser:W(),session:{pageId:t.pageId,sessionId:t.sessionId},metadata:A};r?.enqueue(E(O,R));};return {debug:(o,...i)=>{s("debug",o,i);},info:(o,...i)=>{s("info",o,i);},error:(o,...i)=>{s("error",o,i);},warn:(o,...i)=>{s("warn",o,i);},warning:(o,...i)=>{s("warning",o,i);},success:(o,...i)=>{s("success",o,i);},critical:(o,...i)=>{s("critical",o,i);},table:(o,i)=>{s("table",o,i===void 0?[]:[i]);},child:o=>se(e,{...t,bindings:{...t.bindings,...o},traceId:t.traceId,delivery:r})}}function ie(e={}){return se(e,{pageId:D(),sessionId:Z(),bindings:{},traceId:e.traceId})}var He=ie();var qe={CONTINUE:{status:100,message:"Continue"},SWITCHING_PROTOCOLS:{status:101,message:"Switching Protocols"},PROCESSING:{status:102,message:"Processing"},EARLY_HINTS:{status:103,message:"Early Hints"},OK:{status:200,message:"OK"},CREATED:{status:201,message:"Created"},ACCEPTED:{status:202,message:"Accepted"},NON_AUTHORITATIVE_INFORMATION:{status:203,message:"Non-Authoritative Information"},NO_CONTENT:{status:204,message:"No Content"},RESET_CONTENT:{status:205,message:"Reset Content"},PARTIAL_CONTENT:{status:206,message:"Partial Content"},MULTI_STATUS:{status:207,message:"Multi-Status"},ALREADY_REPORTED:{status:208,message:"Already Reported"},IM_USED:{status:226,message:"IM Used"},MULTIPLE_CHOICES:{status:300,message:"Multiple Choices"},MOVED_PERMANENTLY:{status:301,message:"Moved Permanently"},FOUND:{status:302,message:"Found"},SEE_OTHER:{status:303,message:"See Other"},NOT_MODIFIED:{status:304,message:"Not Modified"},USE_PROXY:{status:305,message:"Use Proxy"},TEMPORARY_REDIRECT:{status:307,message:"Temporary Redirect"},PERMANENT_REDIRECT:{status:308,message:"Permanent Redirect"},BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},PAYMENT_REQUIRED:{status:402,message:"Payment Required"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_ALLOWED:{status:405,message:"Method Not Allowed"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},PROXY_AUTHENTICATION_REQUIRED:{status:407,message:"Proxy Authentication Required"},REQUEST_TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},GONE:{status:410,message:"Gone"},LENGTH_REQUIRED:{status:411,message:"Length Required"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},URI_TOO_LONG:{status:414,message:"URI Too Long"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},RANGE_NOT_SATISFIABLE:{status:416,message:"Range Not Satisfiable"},EXPECTATION_FAILED:{status:417,message:"Expectation Failed"},IM_A_TEAPOT:{status:418,message:"I'm a Teapot"},MISDIRECTED_REQUEST:{status:421,message:"Misdirected Request"},UNPROCESSABLE_ENTITY:{status:422,message:"Unprocessable Entity"},LOCKED:{status:423,message:"Locked"},FAILED_DEPENDENCY:{status:424,message:"Failed Dependency"},TOO_EARLY:{status:425,message:"Too Early"},UPGRADE_REQUIRED:{status:426,message:"Upgrade Required"},PRECONDITION_REQUIRED:{status:428,message:"Precondition Required"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},REQUEST_HEADER_FIELDS_TOO_LARGE:{status:431,message:"Request Header Fields Too Large"},UNAVAILABLE_FOR_LEGAL_REASONS:{status:451,message:"Unavailable For Legal Reasons"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"},HTTP_VERSION_NOT_SUPPORTED:{status:505,message:"HTTP Version Not Supported"},VARIANT_ALSO_NEGOTIATES:{status:506,message:"Variant Also Negotiates"},INSUFFICIENT_STORAGE:{status:507,message:"Insufficient Storage"},LOOP_DETECTED:{status:508,message:"Loop Detected"},BANDWIDTH_LIMIT_EXCEEDED:{status:509,message:"Bandwidth Limit Exceeded"},NOT_EXTENDED:{status:510,message:"Not Extended"},NETWORK_AUTHENTICATION_REQUIRED:{status:511,message:"Network Authentication Required"}},je=["status","statusCode","code","message","stack","why","fix","link","details","cause","title","detail","logLevel","error","data"];function $e(e){return e==="debug"||e==="info"||e==="warning"||e==="error"||e==="critical"}function ae(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&/^\d+$/.test(e.trim()))return Number.parseInt(e,10)}function Qe(e){return m(e)?e:void 0}function ue(e){return e.status!==void 0||e.statusCode!==void 0||e.code!==void 0||e.message!==void 0||e.stack!==void 0||e.why!==void 0||e.fix!==void 0||e.link!==void 0||e.details!==void 0||e.cause!==void 0||e.logLevel!==void 0}function ge(e){let t=typeof e.title=="string"?e.title:void 0,n=typeof e.detail=="string"?e.detail:void 0;return {status:ae(e.status),statusCode:ae(e.statusCode),code:typeof e.code=="string"||typeof e.code=="number"?e.code:void 0,message:typeof e.message=="string"?e.message:t??n,stack:typeof e.stack=="string"?e.stack:void 0,why:typeof e.why=="string"?e.why:void 0,fix:typeof e.fix=="string"?e.fix:void 0,link:typeof e.link=="string"?e.link:void 0,details:Qe(e.details),cause:e.cause,logLevel:$e(e.logLevel)?e.logLevel:void 0}}function B(e,t){let n=ge(e);return t===void 0?ue(n)?n:void 0:typeof t=="string"?ue(n)?{...n,message:n.message??t}:t:{status:n.status??t.status,statusCode:n.statusCode??t.statusCode,code:n.code??t.code,message:n.message??t.message,stack:n.stack??t.stack,why:n.why??t.why,fix:n.fix??t.fix,link:n.link??t.link,details:n.details??t.details,cause:n.cause??t.cause,logLevel:n.logLevel??t.logLevel}}function le(e){return je.some(t=>e[t]!==void 0)}function Ge(e){return typeof Response<"u"&&e instanceof Response?true:m(e)&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.clone=="function"&&typeof e.text=="function"}var T=class e extends Error{constructor(n){super(n.message);d(this,"name","BlypError");d(this,"status");d(this,"statusCode");d(this,"code");d(this,"why");d(this,"fix");d(this,"link");d(this,"details");d(this,"cause");d(this,"logLevel");Object.setPrototypeOf(this,new.target.prototype),this.status=n.status,this.statusCode=n.statusCode,this.code=n.code,this.why=n.why,this.fix=n.fix,this.link=n.link,this.details=n.details,this.cause=n.cause,this.logLevel=n.logLevel,n.stack?this.stack=n.stack:typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,e);}toJSON(){return {name:"BlypError",message:this.message,status:this.status,statusCode:this.statusCode,...this.code!==void 0?{code:this.code}:{},...this.why!==void 0?{why:this.why}:{},...this.fix!==void 0?{fix:this.fix}:{},...this.link!==void 0?{link:this.link}:{},...this.details!==void 0?{details:this.details}:{}}}};function de(e,t){return t||(e>=500?"critical":e>=400?"error":"warning")}function Ye(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{}}:e}function z(e,t,n){let r=de(t.status,n??t.logLevel);(()=>{switch(r){case "debug":return e.debug;case "info":return e.info;case "warning":return e.warning;case "critical":return e.critical;default:return e.error}})()(t.message,{type:"application_error",status:t.status,statusCode:t.statusCode,code:t.code,why:t.why,fix:t.fix,link:t.link,details:t.details,cause:Ye(t.cause)});}function Ve(e,t={}){let r=e.status??e.statusCode??t.status??t.statusCode??500,s=M(r),o=e.message??t.message??s?.message??`HTTP ${r}`;return {status:r,statusCode:r,message:o,code:e.code??t.code??s?.code,why:e.why??t.why??s?.why,fix:e.fix??t.fix??s?.fix,link:e.link??t.link??s?.link,details:e.details??t.details??s?.details,cause:e.cause??t.cause,stack:e.stack??t.stack,logLevel:de(r,e.logLevel??t.logLevel??s?.logLevel)}}function fe(e,t={}){let n=new T(Ve(e,t));return e.skipLogging!==true&&e.logger&&z(e.logger,n,e.logLevel),n}function me(e,t){let n={...e,statusCode:e.status,create(r={}){return fe({status:e.status,message:e.message,code:r.code??e.code,why:r.why??e.why,fix:r.fix??e.fix,link:r.link??e.link,details:r.details??e.details,cause:r.cause,stack:r.stack,logLevel:r.logLevel??e.logLevel,logger:r.logger,skipLogging:r.skipLogging})},extend(r){return me({key:r.code,status:e.status,message:r.message??e.message,code:r.code,why:r.why??e.why,fix:r.fix??e.fix,link:r.link??e.link,details:r.details??e.details,logLevel:r.logLevel??e.logLevel})}};return Object.freeze(n)}function We(e){let t=Object.entries(qe).map(([n,r])=>[n,me({key:n,...r})]);return Object.freeze(Object.fromEntries(t))}var pe=We(),Ze=new Map(Object.values(pe).map(e=>[e.status,e]));function M(e){return Ze.get(e)}function F(e){if(typeof e=="string")return e;if(m(e)){if(e.error!==void 0){let t=e.error;if(typeof t=="string")return B(e,t);if(m(t))return B(e,F(t))}if(m(e.data)){let t=e.data;if(t.error!==void 0||le(t))return B(e,F(t))}if(le(e))return ge(e)}}function ce(e,t={},n={}){if(e instanceof T)return e;let r=(()=>{if(e instanceof Error){let c=e;return {status:c.status,statusCode:c.statusCode,code:c.code,message:e.message,stack:e.stack,why:c.why,fix:c.fix,link:c.link,details:c.details,cause:c.cause,logLevel:c.logLevel}}return F(e)})(),s=n.status&&n.status>0?n.status:void 0,o=typeof r=="string"?void 0:r?.status??r?.statusCode,i=s??o??t.fallbackStatus??500,g=typeof r=="string"&&r.trim()||void 0,C=n.statusText?.trim()||void 0;return fe(typeof r=="string"?{message:g,...s!==void 0?{status:s}:{}}:{...r??{},...s!==void 0?{status:s,statusCode:s}:{}},{status:i,message:(typeof r=="string"?g:r?.message)??C??M(i)?.message??`HTTP ${i}`})}async function Xe(e){let t=e.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")||t?.includes("+json"))try{return await e.clone().json()}catch{try{return await e.clone().text()}catch{return}}try{return await e.clone().text()}catch{return}}function Ke(e,t={}){if(Ge(e))return (async()=>{let r=await Xe(e).catch(()=>{}),s=ce(r,t,{status:e.status,statusText:e.statusText});return t.logger&&z(t.logger,s,t.logLevel),s})();let n=ce(e,t);return t.logger&&z(t.logger,n,t.logLevel),n}exports.BlypError=T;exports.HTTP_CODES=pe;exports.createClientLogger=ie;exports.getHttpCode=M;exports.logger=He;exports.parseError=Ke;