@brizz/sdk 0.1.36 → 0.1.39

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 (102) hide show
  1. package/README.md +28 -125
  2. package/dist/{chunk-6OGRVH77.js → chunk-JBNWC4YN.js} +1 -1
  3. package/dist/{chunk-PXIW2K27.cjs → chunk-NMDPWJMU.cjs} +1 -1
  4. package/dist/index.cjs +2264 -15
  5. package/dist/index.js +2299 -50
  6. package/dist/{mcp-HAUJ3G4Q.cjs → mcp-3N3DAQGD.cjs} +2 -2
  7. package/dist/{mcp-ZCRMQV5L.js → mcp-EWOGAW4J.js} +1 -1
  8. package/dist/types/cjs/eve.d.ts +2 -0
  9. package/dist/types/cjs/google-genai.d.ts +1 -0
  10. package/dist/types/cjs/index.d.ts +15 -0
  11. package/dist/types/cjs/internal/config.d.ts +19 -0
  12. package/dist/types/cjs/internal/constants.d.ts +3 -0
  13. package/dist/types/cjs/internal/dsn.d.ts +13 -0
  14. package/dist/types/cjs/internal/instrumentation/auto-init.d.ts +8 -0
  15. package/dist/types/cjs/internal/instrumentation/google-genai.d.ts +13 -0
  16. package/dist/types/cjs/internal/instrumentation/index.d.ts +2 -0
  17. package/dist/types/cjs/internal/instrumentation/mcp/index.d.ts +2 -0
  18. package/dist/types/cjs/internal/instrumentation/mcp/instrumentation.d.ts +15 -0
  19. package/dist/types/cjs/internal/instrumentation/mcp/patches/attributes.d.ts +9 -0
  20. package/dist/types/cjs/internal/instrumentation/mcp/patches/protocol.d.ts +2 -0
  21. package/dist/types/cjs/internal/instrumentation/mcp/schemas.d.ts +2 -0
  22. package/dist/types/cjs/internal/instrumentation/mcp/semantic-conventions.d.ts +37 -0
  23. package/dist/types/cjs/internal/instrumentation/mcp/session.d.ts +6 -0
  24. package/dist/types/cjs/internal/instrumentation/mcp/types.d.ts +47 -0
  25. package/dist/types/cjs/internal/instrumentation/mcp/version.d.ts +2 -0
  26. package/dist/types/cjs/internal/instrumentation/registry.d.ts +29 -0
  27. package/dist/types/cjs/internal/instrumentation/vercel-ai/interrupt.d.ts +11 -0
  28. package/dist/types/cjs/internal/log/index.d.ts +1 -0
  29. package/dist/types/cjs/internal/log/logging.d.ts +21 -0
  30. package/dist/types/cjs/internal/log/processors/log-processor.d.ts +16 -0
  31. package/dist/types/cjs/internal/logger.d.ts +23 -0
  32. package/dist/types/cjs/internal/masking/index.d.ts +3 -0
  33. package/dist/types/cjs/internal/masking/patterns.d.ts +2 -0
  34. package/dist/types/cjs/internal/masking/types.d.ts +32 -0
  35. package/dist/types/cjs/internal/masking/utils.d.ts +5 -0
  36. package/dist/types/cjs/internal/metric/index.d.ts +1 -0
  37. package/dist/types/cjs/internal/metric/metrics.d.ts +17 -0
  38. package/dist/types/cjs/internal/sdk.d.ts +42 -0
  39. package/dist/types/cjs/internal/semantic-conventions.d.ts +54 -0
  40. package/dist/types/cjs/internal/trace/exporters/eve-trace-exporter.d.ts +18 -0
  41. package/dist/types/cjs/internal/trace/exporters/span-exporter.d.ts +12 -0
  42. package/dist/types/cjs/internal/trace/index.d.ts +4 -0
  43. package/dist/types/cjs/internal/trace/processors/eve-session-processor.d.ts +2 -0
  44. package/dist/types/cjs/internal/trace/processors/span-processor.d.ts +18 -0
  45. package/dist/types/cjs/internal/trace/session.d.ts +135 -0
  46. package/dist/types/cjs/internal/trace/tracing.d.ts +17 -0
  47. package/dist/types/cjs/internal/version.d.ts +1 -0
  48. package/dist/types/cjs/package.json +3 -0
  49. package/dist/types/esm/eve.d.ts +2 -0
  50. package/dist/types/esm/google-genai.d.ts +1 -0
  51. package/dist/types/esm/index.d.ts +15 -0
  52. package/dist/types/esm/internal/config.d.ts +19 -0
  53. package/dist/types/esm/internal/constants.d.ts +3 -0
  54. package/dist/types/esm/internal/dsn.d.ts +13 -0
  55. package/dist/types/esm/internal/instrumentation/auto-init.d.ts +8 -0
  56. package/dist/types/esm/internal/instrumentation/google-genai.d.ts +13 -0
  57. package/dist/types/esm/internal/instrumentation/index.d.ts +2 -0
  58. package/dist/types/esm/internal/instrumentation/mcp/index.d.ts +2 -0
  59. package/dist/types/esm/internal/instrumentation/mcp/instrumentation.d.ts +15 -0
  60. package/dist/types/esm/internal/instrumentation/mcp/patches/attributes.d.ts +9 -0
  61. package/dist/types/esm/internal/instrumentation/mcp/patches/protocol.d.ts +2 -0
  62. package/dist/types/esm/internal/instrumentation/mcp/schemas.d.ts +2 -0
  63. package/dist/types/esm/internal/instrumentation/mcp/semantic-conventions.d.ts +37 -0
  64. package/dist/types/esm/internal/instrumentation/mcp/session.d.ts +6 -0
  65. package/dist/types/esm/internal/instrumentation/mcp/types.d.ts +47 -0
  66. package/dist/types/esm/internal/instrumentation/mcp/version.d.ts +2 -0
  67. package/dist/types/esm/internal/instrumentation/registry.d.ts +29 -0
  68. package/dist/types/esm/internal/instrumentation/vercel-ai/interrupt.d.ts +11 -0
  69. package/dist/types/esm/internal/log/index.d.ts +1 -0
  70. package/dist/types/esm/internal/log/logging.d.ts +21 -0
  71. package/dist/types/esm/internal/log/processors/log-processor.d.ts +16 -0
  72. package/dist/types/esm/internal/logger.d.ts +23 -0
  73. package/dist/types/esm/internal/masking/index.d.ts +3 -0
  74. package/dist/types/esm/internal/masking/patterns.d.ts +2 -0
  75. package/dist/types/esm/internal/masking/types.d.ts +32 -0
  76. package/dist/types/esm/internal/masking/utils.d.ts +5 -0
  77. package/dist/types/esm/internal/metric/index.d.ts +1 -0
  78. package/dist/types/esm/internal/metric/metrics.d.ts +17 -0
  79. package/dist/types/esm/internal/sdk.d.ts +42 -0
  80. package/dist/types/esm/internal/semantic-conventions.d.ts +54 -0
  81. package/dist/types/esm/internal/trace/exporters/eve-trace-exporter.d.ts +18 -0
  82. package/dist/types/esm/internal/trace/exporters/span-exporter.d.ts +12 -0
  83. package/dist/types/esm/internal/trace/index.d.ts +4 -0
  84. package/dist/types/esm/internal/trace/processors/eve-session-processor.d.ts +2 -0
  85. package/dist/types/esm/internal/trace/processors/span-processor.d.ts +18 -0
  86. package/dist/types/esm/internal/trace/session.d.ts +135 -0
  87. package/dist/types/esm/internal/trace/tracing.d.ts +17 -0
  88. package/dist/types/esm/internal/version.d.ts +1 -0
  89. package/package.json +58 -58
  90. package/dist/chunk-CQDWK43A.cjs +0 -2368
  91. package/dist/chunk-YNCBWOHM.js +0 -2368
  92. package/dist/eve.d.cts +0 -19
  93. package/dist/eve.d.ts +0 -19
  94. package/dist/google-genai.d.cts +0 -7
  95. package/dist/google-genai.d.ts +0 -7
  96. package/dist/index.d.cts +0 -291
  97. package/dist/index.d.ts +0 -291
  98. package/dist/loader.mjs +0 -85
  99. package/dist/preload.cjs +0 -119
  100. package/dist/preload.d.cts +0 -2
  101. package/dist/preload.d.ts +0 -2
  102. package/dist/preload.js +0 -119
package/dist/index.js CHANGED
@@ -1,60 +1,85 @@
1
1
  import {
2
- Brizz,
3
- DEFAULT_PII_PATTERNS,
4
- Session,
5
- SessionTitle,
6
- addExternalLink,
7
- callWithMessageId,
8
- callWithMute,
9
- callWithOrganization,
10
- callWithProperties,
11
- callWithSessionId,
12
- callWithUser,
13
- detectRuntime,
14
- emitEvent,
15
- emitEventWithSessionId,
16
- getActiveSession,
17
- getMetricsExporter,
18
- getMetricsReader,
19
- getSpanExporter,
20
- getSpanProcessor,
21
- maskAttributes,
22
- maskValue,
23
- recordFeedback,
24
- recordMetric,
25
- setCurrentSpanCustomProperties,
26
- setMessageId,
27
- setOrganization,
28
- setUser,
29
- startSession,
30
- startSessionTitle,
31
- withMessageId,
32
- withMute,
33
- withOrganization,
34
- withProperties,
35
- withSessionId,
36
- withUser
37
- } from "./chunk-YNCBWOHM.js";
38
- import "./chunk-7SUF4VVI.js";
39
- import "./chunk-6OGRVH77.js";
2
+ SERVICE_NAME_HEADER,
3
+ parseDSN
4
+ } from "./chunk-7SUF4VVI.js";
40
5
  import {
6
+ getSDKVersion
7
+ } from "./chunk-JBNWC4YN.js";
8
+ import {
9
+ DEFAULT_LOG_LEVEL,
41
10
  LogLevel,
42
11
  getLogLevel,
43
12
  logger,
13
+ parseLogLevel,
44
14
  setLogLevel
45
15
  } from "./chunk-Y4HNUX3Q.js";
46
- import "./chunk-EC3MYSRM.js";
47
- import "./chunk-WII4R5RE.js";
48
- import "./chunk-3RG5ZIWI.js";
16
+ import {
17
+ InterruptPropagator
18
+ } from "./chunk-EC3MYSRM.js";
19
+ import {
20
+ BRIZZ,
21
+ EXTERNAL_LINK_EVENT_NAME,
22
+ EXTERNAL_LINK_TITLE,
23
+ EXTERNAL_LINK_TYPE,
24
+ EXTERNAL_LINK_URL,
25
+ FEEDBACK_ATTR_PREFIX,
26
+ FEEDBACK_COMMENT,
27
+ FEEDBACK_EVENT_NAME,
28
+ FEEDBACK_REASON,
29
+ FEEDBACK_SCORE,
30
+ FEEDBACK_SOURCE,
31
+ FEEDBACK_TYPE,
32
+ INTERNAL_EVENT_PREFIX,
33
+ MESSAGE_ID,
34
+ METRIC_ATTRIBUTE_PREFIX,
35
+ METRIC_COMMENT,
36
+ METRIC_EVENT_NAME,
37
+ METRIC_MAX,
38
+ METRIC_MIN,
39
+ METRIC_NAME,
40
+ METRIC_POLARITY,
41
+ METRIC_POLARITY_NEGATIVE,
42
+ METRIC_POLARITY_POSITIVE,
43
+ METRIC_TIMESTAMP,
44
+ METRIC_UNIT,
45
+ METRIC_VALUE,
46
+ MUTE_INPUT,
47
+ MUTE_OUTPUT,
48
+ MUTE_TOOLS,
49
+ ORGANIZATION_DOMAIN,
50
+ ORGANIZATION_ID,
51
+ ORGANIZATION_NAME,
52
+ ORGANIZATION_PLAN,
53
+ PROPERTIES_CONTEXT_KEY,
54
+ RESERVED_METRIC_NAMES,
55
+ SESSION_ID,
56
+ SESSION_INPUT,
57
+ SESSION_INPUT_CONTEXT,
58
+ SESSION_OBJECT_CONTEXT_KEY,
59
+ SESSION_OUTPUT,
60
+ SESSION_OUTPUT_CONTEXT,
61
+ SESSION_SPAN_NAME,
62
+ SESSION_TITLE,
63
+ SESSION_TITLE_GENERATION,
64
+ SESSION_TITLE_SPAN_NAME,
65
+ USER_EMAIL,
66
+ USER_ID,
67
+ USER_NAME,
68
+ USER_PLAN,
69
+ USER_ROLE
70
+ } from "./chunk-WII4R5RE.js";
71
+ import {
72
+ __require
73
+ } from "./chunk-3RG5ZIWI.js";
49
74
 
50
75
  // src/internal/instrumentation/auto-init.ts
76
+ import { OpenAIInstrumentation } from "@arizeai/openinference-instrumentation-openai";
51
77
  import { registerInstrumentations } from "@opentelemetry/instrumentation";
52
78
  import { AnthropicInstrumentation } from "@traceloop/instrumentation-anthropic";
53
79
  import { BedrockInstrumentation } from "@traceloop/instrumentation-bedrock";
54
80
  import { ChromaDBInstrumentation } from "@traceloop/instrumentation-chromadb";
55
81
  import { CohereInstrumentation } from "@traceloop/instrumentation-cohere";
56
82
  import { LlamaIndexInstrumentation } from "@traceloop/instrumentation-llamaindex";
57
- import { OpenAIInstrumentation } from "@traceloop/instrumentation-openai";
58
83
  import { PineconeInstrumentation } from "@traceloop/instrumentation-pinecone";
59
84
  import { QdrantInstrumentation } from "@traceloop/instrumentation-qdrant";
60
85
  import { TogetherInstrumentation } from "@traceloop/instrumentation-together";
@@ -63,8 +88,13 @@ var exceptionLogger = (error) => {
63
88
  };
64
89
  function loadGenAIInstrumentations() {
65
90
  const instrumentations = [];
91
+ try {
92
+ instrumentations.push(new OpenAIInstrumentation());
93
+ logger.debug("Auto-loaded OpenAI instrumentation");
94
+ } catch (error) {
95
+ logger.error(`Failed to auto-load OpenAI instrumentation: ${String(error)}`);
96
+ }
66
97
  const genAIInstrumentationClasses = [
67
- { class: OpenAIInstrumentation, name: "OpenAI" },
68
98
  { class: AnthropicInstrumentation, name: "Anthropic" },
69
99
  { class: CohereInstrumentation, name: "Cohere" },
70
100
  { class: BedrockInstrumentation, name: "Bedrock" },
@@ -94,7 +124,7 @@ function loadGenAIInstrumentations() {
94
124
  function loadMCPInstrumentation() {
95
125
  void (async () => {
96
126
  try {
97
- const { MCPInstrumentation } = await import("./mcp-ZCRMQV5L.js");
127
+ const { MCPInstrumentation } = await import("./mcp-EWOGAW4J.js");
98
128
  const mcp = new MCPInstrumentation({ exceptionLogger });
99
129
  registerInstrumentations({ instrumentations: [mcp] });
100
130
  logger.debug("Auto-loaded MCP instrumentation");
@@ -196,18 +226,2239 @@ function autoInitializeInstrumentations() {
196
226
  }
197
227
  var autoInstrumentationsLoaded = autoInitializeInstrumentations();
198
228
 
199
- // src/index.ts
229
+ // src/internal/sdk.ts
230
+ import { metrics } from "@opentelemetry/api";
231
+ import { registerInstrumentations as registerInstrumentations2 } from "@opentelemetry/instrumentation";
232
+ import {
233
+ defaultResource,
234
+ detectResources,
235
+ envDetector,
236
+ hostDetector,
237
+ processDetector,
238
+ resourceFromAttributes as resourceFromAttributes3
239
+ } from "@opentelemetry/resources";
240
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
241
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
242
+
243
+ // src/internal/config.ts
244
+ function resolveConfig(options) {
245
+ const envLogLevel = process.env["BRIZZ_LOG_LEVEL"] || options.logLevel?.toString() || DEFAULT_LOG_LEVEL.toString();
246
+ let resolvedLogLevel;
247
+ if (envLogLevel) {
248
+ resolvedLogLevel = parseLogLevel(envLogLevel);
249
+ } else if (typeof options.logLevel === "string") {
250
+ resolvedLogLevel = parseLogLevel(options.logLevel);
251
+ } else {
252
+ resolvedLogLevel = options.logLevel || DEFAULT_LOG_LEVEL;
253
+ }
254
+ setLogLevel(resolvedLogLevel);
255
+ let maskingStatus;
256
+ if (options.masking === true) {
257
+ maskingStatus = "enabled";
258
+ } else if (options.masking === false) {
259
+ maskingStatus = "disabled";
260
+ } else if (typeof options.masking === "object") {
261
+ maskingStatus = "custom";
262
+ } else {
263
+ maskingStatus = "default-disabled";
264
+ }
265
+ logger.debug("Starting configuration resolution", {
266
+ appName: options.appName,
267
+ baseUrl: options.baseUrl,
268
+ hasApiKey: !!options.apiKey,
269
+ dsnProvided: !!(process.env["BRIZZ_DSN"] || options.dsn),
270
+ disableBatch: options.disableBatch,
271
+ logLevel: resolvedLogLevel,
272
+ headersCount: Object.keys(options.headers || {}).length,
273
+ masking: maskingStatus
274
+ });
275
+ let resolvedMasking;
276
+ if (options.masking === true) {
277
+ resolvedMasking = {
278
+ spanMasking: {},
279
+ eventMasking: {}
280
+ };
281
+ } else if (options.masking && typeof options.masking === "object") {
282
+ resolvedMasking = options.masking;
283
+ }
284
+ const resolvedConfig = {
285
+ ...options,
286
+ appName: process.env["BRIZZ_APP_NAME"] || process.env["OTEL_SERVICE_NAME"] || options.appName || "unknown-app",
287
+ appVersion: process.env["BRIZZ_APP_VERSION"] || options.appVersion,
288
+ baseUrl: process.env["BRIZZ_BASE_URL"] || options.baseUrl || "https://telemetry.brizz.dev",
289
+ headers: { ...options.headers },
290
+ apiKey: process.env["BRIZZ_API_KEY"] || options.apiKey,
291
+ disableBatch: process.env["BRIZZ_DISABLE_BATCH"] === "true" || !!options.disableBatch,
292
+ disableSpanExporter: process.env["BRIZZ_DISABLE_SPAN_EXPORTER"] === "true" || !!options.disableSpanExporter,
293
+ environment: process.env["BRIZZ_ENVIRONMENT"] || options.environment,
294
+ logLevel: resolvedLogLevel,
295
+ masking: resolvedMasking
296
+ };
297
+ const dsnInput = process.env["BRIZZ_DSN"] || options.dsn;
298
+ let parsedDSN = null;
299
+ if (dsnInput) {
300
+ const kwargConflicts = [];
301
+ if (options.apiKey !== void 0) {
302
+ kwargConflicts.push("apiKey");
303
+ }
304
+ if (options.baseUrl !== void 0) {
305
+ kwargConflicts.push("baseUrl");
306
+ }
307
+ if (options.appName !== void 0) {
308
+ kwargConflicts.push("appName");
309
+ }
310
+ if (kwargConflicts.length > 0) {
311
+ throw new Error(
312
+ `dsn cannot be combined with kwargs ${kwargConflicts.join(", ")}. The DSN bundles bearer, gateway URL, and service name \u2014 choose one configuration style.`
313
+ );
314
+ }
315
+ const envConflicts = ["BRIZZ_API_KEY", "BRIZZ_BASE_URL", "BRIZZ_APP_NAME"].filter(
316
+ (name) => process.env[name] !== void 0
317
+ );
318
+ if (envConflicts.length > 0) {
319
+ logger.warn(
320
+ `Ignoring ${envConflicts.join(", ")} \u2014 dsn / BRIZZ_DSN takes precedence.`
321
+ );
322
+ }
323
+ resolvedConfig.apiKey = void 0;
324
+ resolvedConfig.baseUrl = "https://telemetry.brizz.dev";
325
+ resolvedConfig.appName = "unknown-app";
326
+ parsedDSN = parseDSN(dsnInput);
327
+ if (parsedDSN) {
328
+ resolvedConfig.appName = parsedDSN.service;
329
+ resolvedConfig.baseUrl = parsedDSN.baseUrl;
330
+ resolvedConfig.apiKey = parsedDSN.bearer;
331
+ }
332
+ } else if (resolvedConfig.apiKey) {
333
+ resolvedConfig.headers["Authorization"] = `Bearer ${resolvedConfig.apiKey}`;
334
+ }
335
+ if (process.env["BRIZZ_HEADERS"]) {
336
+ try {
337
+ const envHeaders = JSON.parse(process.env["BRIZZ_HEADERS"]);
338
+ Object.assign(resolvedConfig.headers, envHeaders);
339
+ logger.debug("Added headers from environment variable", {
340
+ headers: Object.keys(envHeaders)
341
+ });
342
+ } catch (error) {
343
+ logger.error("Failed to parse BRIZZ_HEADERS environment variable", { error });
344
+ throw new Error("Invalid JSON in BRIZZ_HEADERS environment variable", { cause: error });
345
+ }
346
+ }
347
+ if (dsnInput) {
348
+ const authHeaderKeys = /* @__PURE__ */ new Set(["authorization", SERVICE_NAME_HEADER.toLowerCase()]);
349
+ resolvedConfig.headers = Object.fromEntries(
350
+ Object.entries(resolvedConfig.headers).filter(
351
+ ([key]) => !authHeaderKeys.has(key.toLowerCase())
352
+ )
353
+ );
354
+ if (parsedDSN) {
355
+ resolvedConfig.headers["Authorization"] = `Bearer ${parsedDSN.bearer}`;
356
+ resolvedConfig.headers[SERVICE_NAME_HEADER] = parsedDSN.service;
357
+ }
358
+ }
359
+ logger.debug("Configuration resolved with environment variables", {
360
+ appName: resolvedConfig.appName,
361
+ baseUrl: resolvedConfig.baseUrl,
362
+ hasApiKey: !!resolvedConfig.apiKey,
363
+ dsnProvided: !!dsnInput,
364
+ disableBatch: resolvedConfig.disableBatch,
365
+ envOverrides: {
366
+ hasEnvApiKey: !!process.env["BRIZZ_API_KEY"],
367
+ hasEnvBaseUrl: !!process.env["BRIZZ_BASE_URL"],
368
+ hasEnvDsn: !!process.env["BRIZZ_DSN"],
369
+ hasEnvBatch: !!process.env["BRIZZ_DISABLE_BATCH"],
370
+ hasEnvHeaders: !!process.env["BRIZZ_HEADERS"]
371
+ }
372
+ });
373
+ return resolvedConfig;
374
+ }
375
+
376
+ // src/internal/constants.ts
377
+ var BRIZZ_SDK_VERSION = "brizz.sdk.version";
378
+ var BRIZZ_SDK_LANGUAGE = "brizz.sdk.language";
379
+ var SDK_LANGUAGE = "typescript";
380
+
381
+ // src/internal/instrumentation/registry.ts
382
+ import { OpenAIInstrumentation as OpenAIInstrumentation2 } from "@arizeai/openinference-instrumentation-openai";
383
+ import { AnthropicInstrumentation as AnthropicInstrumentation2 } from "@traceloop/instrumentation-anthropic";
384
+ import { BedrockInstrumentation as BedrockInstrumentation2 } from "@traceloop/instrumentation-bedrock";
385
+ import { ChromaDBInstrumentation as ChromaDBInstrumentation2 } from "@traceloop/instrumentation-chromadb";
386
+ import { CohereInstrumentation as CohereInstrumentation2 } from "@traceloop/instrumentation-cohere";
387
+ import { LlamaIndexInstrumentation as LlamaIndexInstrumentation2 } from "@traceloop/instrumentation-llamaindex";
388
+ import { PineconeInstrumentation as PineconeInstrumentation2 } from "@traceloop/instrumentation-pinecone";
389
+ import { QdrantInstrumentation as QdrantInstrumentation2 } from "@traceloop/instrumentation-qdrant";
390
+ import { TogetherInstrumentation as TogetherInstrumentation2 } from "@traceloop/instrumentation-together";
391
+ var InstrumentationRegistry = class _InstrumentationRegistry {
392
+ static instance;
393
+ static getInstance() {
394
+ if (!this.instance) {
395
+ this.instance = new _InstrumentationRegistry();
396
+ }
397
+ return this.instance;
398
+ }
399
+ manualModules = null;
400
+ /**
401
+ * Helper to load instrumentation with optional manual module
402
+ */
403
+ loadInstrumentation(InstrumentationClass, name, manualModule, exceptionLogger2) {
404
+ try {
405
+ const inst = new InstrumentationClass({
406
+ exceptionLogger: exceptionLogger2 || ((error) => logger.error(`Exception in instrumentation: ${String(error)}`))
407
+ });
408
+ if (manualModule) {
409
+ inst.manuallyInstrument(manualModule);
410
+ logger.debug(`Manual instrumentation enabled for ${name}`);
411
+ }
412
+ return inst;
413
+ } catch (error) {
414
+ logger.error(`Failed to load ${name} instrumentation: ${String(error)}`);
415
+ return null;
416
+ }
417
+ }
418
+ /**
419
+ * Load manual instrumentations only (with modules provided by user).
420
+ * @private
421
+ */
422
+ loadManualInstrumentations(instrumentations, exceptionLogger2) {
423
+ if (this.manualModules?.openAI) {
424
+ try {
425
+ const openAIInst = new OpenAIInstrumentation2();
426
+ openAIInst.manuallyInstrument(this.manualModules.openAI);
427
+ instrumentations.push(openAIInst);
428
+ logger.debug("Manual instrumentation enabled for OpenAI");
429
+ } catch (error) {
430
+ logger.error(`Failed to load OpenAI instrumentation: ${String(error)}`);
431
+ }
432
+ }
433
+ const instrumentationConfigs = [
434
+ { class: AnthropicInstrumentation2, name: "Anthropic", module: this.manualModules?.anthropic },
435
+ { class: CohereInstrumentation2, name: "Cohere", module: this.manualModules?.cohere },
436
+ { class: BedrockInstrumentation2, name: "Bedrock", module: this.manualModules?.bedrock },
437
+ { class: PineconeInstrumentation2, name: "Pinecone", module: this.manualModules?.pinecone },
438
+ {
439
+ class: LlamaIndexInstrumentation2,
440
+ name: "LlamaIndex",
441
+ module: this.manualModules?.llamaindex
442
+ },
443
+ { class: ChromaDBInstrumentation2, name: "ChromaDB", module: this.manualModules?.chromadb },
444
+ { class: QdrantInstrumentation2, name: "Qdrant", module: this.manualModules?.qdrant },
445
+ { class: TogetherInstrumentation2, name: "Together", module: this.manualModules?.together }
446
+ ];
447
+ for (const config of instrumentationConfigs) {
448
+ if (!config.module) {
449
+ continue;
450
+ }
451
+ const instrumentation = this.loadInstrumentation(
452
+ config.class,
453
+ config.name,
454
+ config.module,
455
+ exceptionLogger2
456
+ );
457
+ if (instrumentation) {
458
+ instrumentations.push(instrumentation);
459
+ }
460
+ }
461
+ if (this.manualModules?.langchain?.callbackManagerModule) {
462
+ const callbackManagerModule = this.manualModules.langchain.callbackManagerModule;
463
+ void (async () => {
464
+ try {
465
+ const { LangChainInstrumentation } = await import("@arizeai/openinference-instrumentation-langchain");
466
+ const lcInst = new LangChainInstrumentation();
467
+ lcInst.manuallyInstrument(callbackManagerModule);
468
+ logger.debug("Manual instrumentation enabled for LangChain");
469
+ } catch (error) {
470
+ logger.error(
471
+ `Failed to load LangChain instrumentation. Ensure @langchain/core is installed: ${String(error)}`
472
+ );
473
+ }
474
+ })();
475
+ }
476
+ if (this.manualModules?.google_vertexai) {
477
+ const vertexModule = this.manualModules.google_vertexai;
478
+ void (async () => {
479
+ try {
480
+ const { VertexAIInstrumentation } = await import("@traceloop/instrumentation-vertexai");
481
+ const vertexInst = new VertexAIInstrumentation({ exceptionLogger: exceptionLogger2 });
482
+ vertexInst.manuallyInstrument(vertexModule);
483
+ logger.debug("Manual instrumentation enabled for Vertex AI");
484
+ } catch (error) {
485
+ logger.error(
486
+ `Failed to load Vertex AI instrumentation. Ensure @traceloop/instrumentation-vertexai is installed: ${String(error)}`
487
+ );
488
+ }
489
+ })();
490
+ }
491
+ if (this.manualModules?.google_genai) {
492
+ const genaiModule = this.manualModules.google_genai;
493
+ void (async () => {
494
+ try {
495
+ const { GoogleGenAIInstrumentation } = await import("./google-genai-T7I4FFIP.js");
496
+ const genaiInst = new GoogleGenAIInstrumentation({ exceptionLogger: exceptionLogger2 });
497
+ genaiInst.manuallyInstrument(genaiModule);
498
+ logger.debug("Manual instrumentation enabled for Google GenAI");
499
+ } catch (error) {
500
+ logger.error(
501
+ `Failed to apply Google GenAI instrumentation. Ensure @traceloop/instrumentation-google-generativeai is installed; on a read-only ESM module namespace use instrumentGoogleGenAI from @brizz/sdk/google-genai instead: ${String(error)}`
502
+ );
503
+ }
504
+ })();
505
+ }
506
+ if (this.manualModules?.mcp) {
507
+ const mcpModules = this.manualModules.mcp;
508
+ void (async () => {
509
+ try {
510
+ const { MCPInstrumentation } = await import("./mcp-EWOGAW4J.js");
511
+ const instrumentation = new MCPInstrumentation({ exceptionLogger: exceptionLogger2 });
512
+ instrumentation.manuallyInstrument(mcpModules);
513
+ logger.debug("Manual instrumentation enabled for MCP");
514
+ } catch (error) {
515
+ logger.error(`Failed to apply MCP instrumentation: ${String(error)}`);
516
+ }
517
+ })();
518
+ }
519
+ }
520
+ /**
521
+ * Set manual instrumentation modules for Next.js/Webpack environments
522
+ */
523
+ setManualModules(modules) {
524
+ this.manualModules = modules;
525
+ logger.info("Manual instrumentation modules configured for Next.js/Webpack compatibility");
526
+ }
527
+ /**
528
+ * Get manual instrumentations only.
529
+ * Auto-instrumentations are handled at import time.
530
+ */
531
+ getManualInstrumentations() {
532
+ if (!this.manualModules || Object.keys(this.manualModules).length === 0) {
533
+ logger.debug("No manual instrumentation modules configured");
534
+ return [];
535
+ }
536
+ const instrumentations = [];
537
+ const exceptionLogger2 = (error) => {
538
+ logger.error(`Exception in manual instrumentation: ${String(error)}`);
539
+ };
540
+ this.loadManualInstrumentations(instrumentations, exceptionLogger2);
541
+ logger.info(`Loaded ${instrumentations.length} manual instrumentations`);
542
+ return instrumentations;
543
+ }
544
+ };
545
+
546
+ // src/internal/log/logging.ts
200
547
  import { SeverityNumber } from "@opentelemetry/api-logs";
548
+ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
549
+ import { resourceFromAttributes } from "@opentelemetry/resources";
550
+ import {
551
+ LoggerProvider
552
+ } from "@opentelemetry/sdk-logs";
553
+
554
+ // src/internal/trace/session.ts
555
+ import { context, trace, SpanStatusCode } from "@opentelemetry/api";
556
+ function setCurrentSpanCustomProperties(properties) {
557
+ const current = trace.getActiveSpan();
558
+ if (!current || !current.isRecording()) {
559
+ return;
560
+ }
561
+ for (const [key, value] of Object.entries(properties)) {
562
+ try {
563
+ current.setAttribute(`${BRIZZ}.${key}`, value);
564
+ } catch {
565
+ }
566
+ }
567
+ }
568
+ function callWithProperties(properties, fn, thisArg, ...args) {
569
+ const base = context.active();
570
+ const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
571
+ const merged = prev ? { ...prev, ...properties } : properties;
572
+ const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);
573
+ return context.with(next, fn, thisArg, ...args);
574
+ }
575
+ function withProperties(properties, fn, thisArg) {
576
+ return function wrapped(...args) {
577
+ return callWithProperties(
578
+ properties,
579
+ fn,
580
+ thisArg !== void 0 ? thisArg : this,
581
+ ...args
582
+ );
583
+ };
584
+ }
585
+ function propagatePropertiesImperatively(properties) {
586
+ try {
587
+ const manager = context;
588
+ const mgr = manager._getContextManager?.();
589
+ const store = mgr?._asyncLocalStorage;
590
+ if (!store || typeof store.enterWith !== "function") {
591
+ return;
592
+ }
593
+ const base = context.active();
594
+ const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
595
+ const merged = prev ? { ...prev, ...properties } : properties;
596
+ store.enterWith(base.setValue(PROPERTIES_CONTEXT_KEY, merged));
597
+ } catch {
598
+ }
599
+ }
600
+ function setUser(user) {
601
+ const properties = { [USER_ID]: user.id };
602
+ if (user.email !== void 0) {
603
+ properties[USER_EMAIL] = user.email;
604
+ }
605
+ if (user.name !== void 0) {
606
+ properties[USER_NAME] = user.name;
607
+ }
608
+ if (user.role !== void 0) {
609
+ properties[USER_ROLE] = user.role;
610
+ }
611
+ if (user.plan !== void 0) {
612
+ properties[USER_PLAN] = user.plan;
613
+ }
614
+ if (user.traits) {
615
+ for (const [key, value] of Object.entries(user.traits)) {
616
+ const k = `user.${key}`;
617
+ if (properties[k] === void 0) {
618
+ properties[k] = value;
619
+ }
620
+ }
621
+ }
622
+ setCurrentSpanCustomProperties(properties);
623
+ propagatePropertiesImperatively(properties);
624
+ }
625
+ function setOrganization(org) {
626
+ const properties = { [ORGANIZATION_ID]: org.id };
627
+ if (org.name !== void 0) {
628
+ properties[ORGANIZATION_NAME] = org.name;
629
+ }
630
+ if (org.plan !== void 0) {
631
+ properties[ORGANIZATION_PLAN] = org.plan;
632
+ }
633
+ if (org.domain !== void 0) {
634
+ properties[ORGANIZATION_DOMAIN] = org.domain;
635
+ }
636
+ if (org.traits) {
637
+ for (const [key, value] of Object.entries(org.traits)) {
638
+ const k = `organization.${key}`;
639
+ if (properties[k] === void 0) {
640
+ properties[k] = value;
641
+ }
642
+ }
643
+ }
644
+ setCurrentSpanCustomProperties(properties);
645
+ propagatePropertiesImperatively(properties);
646
+ }
647
+ function setMessageId(id) {
648
+ const properties = { [MESSAGE_ID]: id };
649
+ setCurrentSpanCustomProperties(properties);
650
+ propagatePropertiesImperatively(properties);
651
+ }
652
+ function userProperties(user) {
653
+ const properties = { [USER_ID]: user.id };
654
+ if (user.email !== void 0) {
655
+ properties[USER_EMAIL] = user.email;
656
+ }
657
+ if (user.name !== void 0) {
658
+ properties[USER_NAME] = user.name;
659
+ }
660
+ if (user.role !== void 0) {
661
+ properties[USER_ROLE] = user.role;
662
+ }
663
+ if (user.plan !== void 0) {
664
+ properties[USER_PLAN] = user.plan;
665
+ }
666
+ if (user.traits) {
667
+ for (const [key, value] of Object.entries(user.traits)) {
668
+ const k = `user.${key}`;
669
+ if (properties[k] === void 0) {
670
+ properties[k] = value;
671
+ }
672
+ }
673
+ }
674
+ return properties;
675
+ }
676
+ function organizationProperties(org) {
677
+ const properties = { [ORGANIZATION_ID]: org.id };
678
+ if (org.name !== void 0) {
679
+ properties[ORGANIZATION_NAME] = org.name;
680
+ }
681
+ if (org.plan !== void 0) {
682
+ properties[ORGANIZATION_PLAN] = org.plan;
683
+ }
684
+ if (org.domain !== void 0) {
685
+ properties[ORGANIZATION_DOMAIN] = org.domain;
686
+ }
687
+ if (org.traits) {
688
+ for (const [key, value] of Object.entries(org.traits)) {
689
+ const k = `organization.${key}`;
690
+ if (properties[k] === void 0) {
691
+ properties[k] = value;
692
+ }
693
+ }
694
+ }
695
+ return properties;
696
+ }
697
+ function callWithUser(user, fn, thisArg, ...args) {
698
+ return callWithProperties(userProperties(user), fn, thisArg, ...args);
699
+ }
700
+ function withUser(user, fn, thisArg) {
701
+ return withProperties(userProperties(user), fn, thisArg);
702
+ }
703
+ function callWithOrganization(org, fn, thisArg, ...args) {
704
+ return callWithProperties(organizationProperties(org), fn, thisArg, ...args);
705
+ }
706
+ function withOrganization(org, fn, thisArg) {
707
+ return withProperties(organizationProperties(org), fn, thisArg);
708
+ }
709
+ function callWithMessageId(id, fn, thisArg, ...args) {
710
+ return callWithProperties({ [MESSAGE_ID]: id }, fn, thisArg, ...args);
711
+ }
712
+ function withMessageId(id, fn, thisArg) {
713
+ return withProperties({ [MESSAGE_ID]: id }, fn, thisArg);
714
+ }
715
+ function inheritedMuteTools() {
716
+ const properties = context.active().getValue(PROPERTIES_CONTEXT_KEY);
717
+ return properties?.[MUTE_TOOLS];
718
+ }
719
+ function muteProperties(options) {
720
+ const { input = true, output = true, tools = output } = options;
721
+ const properties = {};
722
+ if (input) {
723
+ properties[MUTE_INPUT] = "true";
724
+ }
725
+ if (output) {
726
+ properties[MUTE_OUTPUT] = "true";
727
+ }
728
+ if (tools !== output) {
729
+ properties[MUTE_TOOLS] = String(tools);
730
+ } else {
731
+ const inherited = inheritedMuteTools();
732
+ if (tools && inherited === "false") {
733
+ properties[MUTE_TOOLS] = "true";
734
+ } else if (options.tools === false && inherited === "true") {
735
+ properties[MUTE_TOOLS] = "false";
736
+ }
737
+ }
738
+ return properties;
739
+ }
740
+ function callWithMute(options, fn, thisArg, ...args) {
741
+ return callWithProperties(muteProperties(options), fn, thisArg, ...args);
742
+ }
743
+ function withMute(options, fn, thisArg) {
744
+ return withProperties(muteProperties(options), fn, thisArg);
745
+ }
746
+ function withSessionId(sessionId, fn, thisArg, extraProperties) {
747
+ const properties = { [SESSION_ID]: sessionId, ...extraProperties };
748
+ return withProperties(properties, fn, thisArg);
749
+ }
750
+ function callWithSessionId(sessionId, fn, thisArg, ...args) {
751
+ return callWithProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);
752
+ }
753
+ var Session = class {
754
+ span;
755
+ inputs = [];
756
+ outputs = [];
757
+ inputContexts = [];
758
+ outputContexts = [];
759
+ sessionId;
760
+ constructor(sessionId, span) {
761
+ this.sessionId = sessionId;
762
+ this.span = span;
763
+ }
764
+ /**
765
+ * Append a user turn to session input tracking.
766
+ *
767
+ * Each call appends one element to `brizz.session.input` (the text) AND one
768
+ * element to `brizz.session.input.context` (the per-turn context bag). The
769
+ * two arrays stay index-aligned — the ingestion pipeline zips them together
770
+ * so the i-th context bag lands on the i-th user_display conversation item's
771
+ * `span_attributes` map.
772
+ *
773
+ * @param text - Text to append (null becomes a null/"hide marker")
774
+ * @param context - Optional per-turn context bag to attach to this turn
775
+ */
776
+ setInput(text, context4) {
777
+ this.inputs.push(text);
778
+ this.inputContexts.push(context4 ?? {});
779
+ this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));
780
+ this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));
781
+ }
782
+ /**
783
+ * Append an assistant turn to session output tracking.
784
+ *
785
+ * Symmetric to {@link setInput} — appends one text element and one
786
+ * context-bag element to the index-aligned `brizz.session.output` /
787
+ * `brizz.session.output.context` arrays.
788
+ *
789
+ * @param text - Text to append (null becomes a null/"hide marker")
790
+ * @param context - Optional per-turn context bag to attach to this turn
791
+ */
792
+ setOutput(text, context4) {
793
+ this.outputs.push(text);
794
+ this.outputContexts.push(context4 ?? {});
795
+ this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));
796
+ this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));
797
+ }
798
+ /**
799
+ * Set the session title on the span.
800
+ *
801
+ * @param title - The generated title string
802
+ */
803
+ setTitle(title) {
804
+ this.span.setAttribute(SESSION_TITLE, title);
805
+ }
806
+ /**
807
+ * Update custom properties on the session span.
808
+ * Properties are prefixed with 'brizz.'.
809
+ *
810
+ * @param properties - Key-value properties to set on the session
811
+ */
812
+ updateProperties(properties) {
813
+ for (const [key, value] of Object.entries(properties)) {
814
+ this.span.setAttribute(`${BRIZZ}.${key}`, value);
815
+ }
816
+ }
817
+ /**
818
+ * Set end-user identity on the session span: `brizz.user.id` and, when
819
+ * provided, `brizz.user.email` / `brizz.user.name`. Undefined fields are omitted.
820
+ *
821
+ * @param user - User identity (`id` required; `email` / `name` optional)
822
+ */
823
+ setUser(user) {
824
+ if (user.traits) {
825
+ for (const [key, value] of Object.entries(user.traits)) {
826
+ this.span.setAttribute(`${BRIZZ}.user.${key}`, value);
827
+ }
828
+ }
829
+ this.span.setAttribute(`${BRIZZ}.${USER_ID}`, user.id);
830
+ if (user.email !== void 0) {
831
+ this.span.setAttribute(`${BRIZZ}.${USER_EMAIL}`, user.email);
832
+ }
833
+ if (user.name !== void 0) {
834
+ this.span.setAttribute(`${BRIZZ}.${USER_NAME}`, user.name);
835
+ }
836
+ if (user.role !== void 0) {
837
+ this.span.setAttribute(`${BRIZZ}.${USER_ROLE}`, user.role);
838
+ }
839
+ if (user.plan !== void 0) {
840
+ this.span.setAttribute(`${BRIZZ}.${USER_PLAN}`, user.plan);
841
+ }
842
+ }
843
+ /**
844
+ * Set organization identity on the session span: `brizz.organization.id` and,
845
+ * when provided, `brizz.organization.name`. Undefined fields are omitted.
846
+ *
847
+ * @param org - Organization identity (`id` required; `name` optional)
848
+ */
849
+ setOrganization(org) {
850
+ if (org.traits) {
851
+ for (const [key, value] of Object.entries(org.traits)) {
852
+ this.span.setAttribute(`${BRIZZ}.organization.${key}`, value);
853
+ }
854
+ }
855
+ this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_ID}`, org.id);
856
+ if (org.name !== void 0) {
857
+ this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_NAME}`, org.name);
858
+ }
859
+ if (org.plan !== void 0) {
860
+ this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_PLAN}`, org.plan);
861
+ }
862
+ if (org.domain !== void 0) {
863
+ this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_DOMAIN}`, org.domain);
864
+ }
865
+ }
866
+ /**
867
+ * Attach an external link (URL) to this session.
868
+ *
869
+ * The link surfaces on the session's detail panel in Brizz — use it to
870
+ * correlate a session with an external record such as a Datadog trace,
871
+ * Sentry issue, or internal dashboard. Re-sending the same URL is idempotent;
872
+ * distinct URLs add separate links.
873
+ *
874
+ * @param url - The link target
875
+ * @param options - Optional `title` (defaults to the URL host) and `linkType`
876
+ * (free-form category, defaults to `'generic'`)
877
+ */
878
+ addExternalLink(url, options) {
879
+ emitExternalLink(this.sessionId, url, options?.title, options?.linkType);
880
+ }
881
+ };
882
+ var SessionTitle = class {
883
+ span;
884
+ constructor(span) {
885
+ this.span = span;
886
+ }
887
+ /**
888
+ * Set the generated title on the wrapper span.
889
+ *
890
+ * @param title - The generated title string
891
+ */
892
+ setTitle(title) {
893
+ this.span.setAttribute(SESSION_TITLE, title);
894
+ }
895
+ };
896
+ function getActiveSession() {
897
+ return context.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
898
+ }
899
+ function resolveSessionIdFromContext() {
900
+ const active = getActiveSession();
901
+ if (active) {
902
+ return active.sessionId;
903
+ }
904
+ const props = context.active().getValue(PROPERTIES_CONTEXT_KEY);
905
+ return props?.[SESSION_ID];
906
+ }
907
+ function resolveMessageIdFromContext() {
908
+ const props = context.active().getValue(PROPERTIES_CONTEXT_KEY);
909
+ return props?.[MESSAGE_ID];
910
+ }
911
+ function emitExternalLink(sessionId, url, title, linkType) {
912
+ try {
913
+ emitEventWithSessionId(sessionId, EXTERNAL_LINK_EVENT_NAME, {
914
+ [EXTERNAL_LINK_URL]: url,
915
+ [EXTERNAL_LINK_TITLE]: title ?? "",
916
+ [EXTERNAL_LINK_TYPE]: linkType ?? "generic"
917
+ });
918
+ } catch (error) {
919
+ logger.warn("addExternalLink: failed to emit external link", error);
920
+ }
921
+ }
922
+ function addExternalLink(url, options) {
923
+ const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
924
+ if (!sessionId) {
925
+ logger.warn(
926
+ "addExternalLink called without a resolvable session id; link dropped. Pass options.sessionId or call inside a startSession/callWithSessionId scope."
927
+ );
928
+ return;
929
+ }
930
+ emitExternalLink(sessionId, url, options?.title, options?.linkType);
931
+ }
932
+ function recordFeedback(type, options) {
933
+ const eventAttributes = { [FEEDBACK_TYPE]: type };
934
+ if (options?.score !== void 0) {
935
+ eventAttributes[FEEDBACK_SCORE] = options.score;
936
+ }
937
+ if (options?.reason !== void 0) {
938
+ eventAttributes[FEEDBACK_REASON] = options.reason;
939
+ }
940
+ if (options?.comment !== void 0) {
941
+ eventAttributes[FEEDBACK_COMMENT] = options.comment;
942
+ }
943
+ if (options?.source !== void 0) {
944
+ eventAttributes[FEEDBACK_SOURCE] = options.source;
945
+ }
946
+ if (options?.attributes) {
947
+ for (const [key, value] of Object.entries(options.attributes)) {
948
+ const k = `${FEEDBACK_ATTR_PREFIX}${key}`;
949
+ if (eventAttributes[k] === void 0) {
950
+ eventAttributes[k] = value;
951
+ }
952
+ }
953
+ }
954
+ const messageId = options?.messageId ?? resolveMessageIdFromContext();
955
+ const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
956
+ if (messageId === void 0 && sessionId === void 0) {
957
+ logger.warn(
958
+ "recordFeedback called with no resolvable message id or session id; the feedback cannot be attributed to a message or conversation. Pass options.messageId / options.sessionId or call inside a startSession/callWithMessageId scope."
959
+ );
960
+ }
961
+ const anchor = {};
962
+ if (messageId !== void 0) {
963
+ anchor[MESSAGE_ID] = messageId;
964
+ }
965
+ if (sessionId !== void 0) {
966
+ anchor[SESSION_ID] = sessionId;
967
+ }
968
+ try {
969
+ if (Object.keys(anchor).length === 0) {
970
+ emitEvent(FEEDBACK_EVENT_NAME, eventAttributes);
971
+ } else {
972
+ callWithProperties(anchor, () => emitEvent(FEEDBACK_EVENT_NAME, eventAttributes));
973
+ }
974
+ } catch (error) {
975
+ logger.warn("recordFeedback: failed to emit feedback event", error);
976
+ }
977
+ }
978
+ var METRIC_NAME_PATTERN = /^[a-z][a-z0-9_.-]{0,63}$/;
979
+ var METRIC_COMMENT_MAX_LEN = 4096;
980
+ var METRIC_ATTRIBUTES_MAX = 20;
981
+ var METRIC_ATTRIBUTE_VALUE_MAX_LEN = 256;
982
+ function recordMetric(options) {
983
+ try {
984
+ recordMetricImpl(options);
985
+ } catch (error) {
986
+ logger.warn(`recordMetric(${JSON.stringify(options?.name)}) failed; metric dropped.`, error);
987
+ }
988
+ }
989
+ function recordMetricImpl(options) {
990
+ const name = typeof options.name === "string" ? options.name.toLowerCase() : "";
991
+ if (!METRIC_NAME_PATTERN.test(name)) {
992
+ logger.warn(
993
+ `recordMetric called with an invalid name ${JSON.stringify(options.name)}; metric dropped. Names must match ${METRIC_NAME_PATTERN.source} after lowercasing.`
994
+ );
995
+ return;
996
+ }
997
+ if (RESERVED_METRIC_NAMES.has(name)) {
998
+ logger.warn(
999
+ `recordMetric called with the reserved name ${JSON.stringify(name)}; metric dropped. Brizz computes this metric itself \u2014 pick a different name.`
1000
+ );
1001
+ return;
1002
+ }
1003
+ const { value } = options;
1004
+ let numericValue;
1005
+ if (typeof value === "boolean") {
1006
+ numericValue = value ? 1 : 0;
1007
+ } else if (typeof value === "number" && Number.isFinite(value)) {
1008
+ numericValue = value;
1009
+ } else {
1010
+ logger.warn(
1011
+ `recordMetric(${name}) called with a non-finite or non-numeric value ${JSON.stringify(value)}; metric dropped.`
1012
+ );
1013
+ return;
1014
+ }
1015
+ const eventAttributes = {
1016
+ [METRIC_NAME]: name,
1017
+ [METRIC_VALUE]: numericValue
1018
+ };
1019
+ if (options.unit !== void 0) {
1020
+ eventAttributes[METRIC_UNIT] = options.unit;
1021
+ }
1022
+ if (options.minValue !== void 0) {
1023
+ eventAttributes[METRIC_MIN] = options.minValue;
1024
+ }
1025
+ if (options.maxValue !== void 0) {
1026
+ eventAttributes[METRIC_MAX] = options.maxValue;
1027
+ }
1028
+ if (options.comment !== void 0) {
1029
+ let comment = options.comment;
1030
+ if (comment.length > METRIC_COMMENT_MAX_LEN) {
1031
+ logger.warn(
1032
+ `recordMetric(${name}) comment exceeds ${METRIC_COMMENT_MAX_LEN} characters; truncated.`
1033
+ );
1034
+ comment = comment.slice(0, METRIC_COMMENT_MAX_LEN);
1035
+ }
1036
+ eventAttributes[METRIC_COMMENT] = comment;
1037
+ }
1038
+ if (options.polarity !== void 0) {
1039
+ const polarity = options.polarity;
1040
+ if (polarity === METRIC_POLARITY_POSITIVE || polarity === METRIC_POLARITY_NEGATIVE) {
1041
+ eventAttributes[METRIC_POLARITY] = polarity;
1042
+ } else {
1043
+ logger.warn(
1044
+ `recordMetric(${name}) called with an invalid polarity ${JSON.stringify(polarity)}; expected '${METRIC_POLARITY_POSITIVE}' or '${METRIC_POLARITY_NEGATIVE}'. Emitting the metric without it.`
1045
+ );
1046
+ }
1047
+ }
1048
+ if (options.timestamp !== void 0) {
1049
+ if (Number.isFinite(options.timestamp.getTime())) {
1050
+ eventAttributes[METRIC_TIMESTAMP] = options.timestamp.toISOString();
1051
+ } else {
1052
+ logger.warn(
1053
+ `recordMetric(${name}) called with an invalid timestamp; emitting the metric without it.`
1054
+ );
1055
+ }
1056
+ }
1057
+ if (options.attributes) {
1058
+ let accepted = 0;
1059
+ for (const [key, attrValue] of Object.entries(options.attributes)) {
1060
+ if (accepted >= METRIC_ATTRIBUTES_MAX) {
1061
+ logger.warn(
1062
+ `recordMetric(${name}) called with more than ${METRIC_ATTRIBUTES_MAX} attributes; the excess was dropped.`
1063
+ );
1064
+ break;
1065
+ }
1066
+ const normalizedKey = key.toLowerCase();
1067
+ if (!METRIC_NAME_PATTERN.test(normalizedKey)) {
1068
+ logger.warn(
1069
+ `recordMetric(${name}) called with an invalid attribute key ${JSON.stringify(key)}; that attribute was dropped. Keys must match ${METRIC_NAME_PATTERN.source} after lowercasing.`
1070
+ );
1071
+ continue;
1072
+ }
1073
+ let text = typeof attrValue === "string" ? attrValue : String(attrValue);
1074
+ if (text.length > METRIC_ATTRIBUTE_VALUE_MAX_LEN) {
1075
+ logger.warn(
1076
+ `recordMetric(${name}) attribute ${JSON.stringify(normalizedKey)} exceeds ${METRIC_ATTRIBUTE_VALUE_MAX_LEN} characters; truncated.`
1077
+ );
1078
+ text = text.slice(0, METRIC_ATTRIBUTE_VALUE_MAX_LEN);
1079
+ }
1080
+ eventAttributes[`${METRIC_ATTRIBUTE_PREFIX}${normalizedKey}`] = text;
1081
+ accepted += 1;
1082
+ }
1083
+ }
1084
+ const sessionId = options.sessionId ?? resolveSessionIdFromContext();
1085
+ if (sessionId === void 0) {
1086
+ logger.warn(
1087
+ `recordMetric(${name}) called with no resolvable session id; the metric cannot be attributed to a conversation and is dropped. Pass options.sessionId or call inside a startSession/callWithSessionId scope.`
1088
+ );
1089
+ return;
1090
+ }
1091
+ try {
1092
+ callWithProperties(
1093
+ { [SESSION_ID]: sessionId },
1094
+ () => emitEvent(METRIC_EVENT_NAME, eventAttributes)
1095
+ );
1096
+ } catch (error) {
1097
+ logger.warn("recordMetric: failed to emit metric event", error);
1098
+ }
1099
+ }
1100
+ function startSession(sessionId, callback, extraProperties, options) {
1101
+ const isTitle = options?.mode === "title";
1102
+ const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;
1103
+ const tracer = trace.getTracer("@brizz/sdk");
1104
+ return tracer.startActiveSpan(spanName, (span) => {
1105
+ span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
1106
+ if (extraProperties) {
1107
+ for (const [key, value] of Object.entries(extraProperties)) {
1108
+ span.setAttribute(`${BRIZZ}.${key}`, value);
1109
+ }
1110
+ }
1111
+ const session = new Session(sessionId, span);
1112
+ const contextProperties = { [SESSION_ID]: sessionId };
1113
+ if (isTitle) {
1114
+ contextProperties[SESSION_TITLE_GENERATION] = "true";
1115
+ }
1116
+ if (extraProperties) {
1117
+ for (const [key, value] of Object.entries(extraProperties)) {
1118
+ contextProperties[key] = String(value);
1119
+ }
1120
+ }
1121
+ return callWithProperties(contextProperties, () => {
1122
+ const sessionCtx = context.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
1123
+ return context.with(sessionCtx, () => {
1124
+ try {
1125
+ const result = callback(session);
1126
+ if (result && typeof result.then === "function") {
1127
+ return result.then((value) => {
1128
+ span.end();
1129
+ return value;
1130
+ }).catch((error) => {
1131
+ span.recordException(error);
1132
+ span.setStatus({ code: SpanStatusCode.ERROR });
1133
+ span.end();
1134
+ throw error;
1135
+ });
1136
+ }
1137
+ span.end();
1138
+ return result;
1139
+ } catch (error) {
1140
+ span.recordException(error);
1141
+ span.setStatus({ code: SpanStatusCode.ERROR });
1142
+ span.end();
1143
+ throw error;
1144
+ }
1145
+ });
1146
+ });
1147
+ });
1148
+ }
1149
+ function startSessionTitle(callback, options) {
1150
+ const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;
1151
+ const tracer = trace.getTracer("@brizz/sdk");
1152
+ return tracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {
1153
+ if (resolvedSessionId) {
1154
+ span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);
1155
+ }
1156
+ const sessionTitle = new SessionTitle(span);
1157
+ const properties = { [SESSION_TITLE_GENERATION]: "true" };
1158
+ if (resolvedSessionId) {
1159
+ properties[SESSION_ID] = resolvedSessionId;
1160
+ }
1161
+ return callWithProperties(properties, () => {
1162
+ try {
1163
+ const result = callback(sessionTitle);
1164
+ if (result && typeof result.then === "function") {
1165
+ return result.then((value) => {
1166
+ span.end();
1167
+ return value;
1168
+ }).catch((error) => {
1169
+ span.recordException(error);
1170
+ span.setStatus({ code: SpanStatusCode.ERROR });
1171
+ span.end();
1172
+ throw error;
1173
+ });
1174
+ }
1175
+ span.end();
1176
+ return result;
1177
+ } catch (error) {
1178
+ span.recordException(error);
1179
+ span.setStatus({ code: SpanStatusCode.ERROR });
1180
+ span.end();
1181
+ throw error;
1182
+ }
1183
+ });
1184
+ });
1185
+ }
1186
+
1187
+ // src/internal/log/processors/log-processor.ts
1188
+ import { context as context2 } from "@opentelemetry/api";
1189
+ import { BatchLogRecordProcessor, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
1190
+
1191
+ // src/internal/masking/patterns.ts
1192
+ var DEFAULT_PII_PATTERNS = [
1193
+ // Phone numbers (US format)
1194
+ {
1195
+ name: "us_phone_numbers",
1196
+ pattern: String.raw`(?:^|[\s])(?:\+?1[-.\s]*)?(?:\([0-9]{3}\)\s?[0-9]{3}[-.\s]?[0-9]{4}|[0-9]{3}[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}|[0-9]{10})(?=[\s]|$)`
1197
+ },
1198
+ // Credit card numbers
1199
+ {
1200
+ name: "credit_cards",
1201
+ pattern: String.raw`\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\\d{3})\\d{11})\b`
1202
+ },
1203
+ {
1204
+ name: "credit_cards_with_separators",
1205
+ pattern: String.raw`\b(?:4\\d{3}|5[1-5]\\d{2}|3[47]\\d{2})[-\s]?\\d{4}[-\s]?\\d{4}[-\s]?\\d{4}\b`
1206
+ },
1207
+ // IP addresses (IPv4)
1208
+ {
1209
+ name: "ipv4_addresses",
1210
+ pattern: String.raw`\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?!\.[0-9])\b`
1211
+ },
1212
+ // API keys/tokens
1213
+ {
1214
+ name: "generic_api_keys",
1215
+ pattern: String.raw`\b(?:[Aa][Pp][Ii][_-]?[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt])[_-]?[=:]?\s*["']?(?:[a-zA-Z0-9\-_.]{20,})["']?\b`
1216
+ },
1217
+ {
1218
+ name: "openai_keys",
1219
+ pattern: String.raw`\bsk[-_][a-zA-Z0-9]{20,}\b`
1220
+ },
1221
+ // AWS Keys
1222
+ {
1223
+ name: "aws_access_keys",
1224
+ pattern: String.raw`\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b`
1225
+ },
1226
+ // GitHub tokens
1227
+ {
1228
+ name: "github_tokens",
1229
+ pattern: String.raw`\bghp_[a-zA-Z0-9]{36}\b`
1230
+ },
1231
+ // Slack tokens
1232
+ {
1233
+ name: "slack_tokens",
1234
+ pattern: String.raw`\bxox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24,34}\b`
1235
+ },
1236
+ // Stripe keys
1237
+ {
1238
+ name: "stripe_keys",
1239
+ pattern: String.raw`\b(?:sk|pk)_(?:test|live)_[a-zA-Z0-9]{24,}\b`
1240
+ },
1241
+ // JWT tokens
1242
+ {
1243
+ name: "jwt_tokens",
1244
+ pattern: String.raw`\beyJ[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\b`
1245
+ },
1246
+ // MAC addresses
1247
+ {
1248
+ name: "mac_addresses",
1249
+ pattern: String.raw`\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b`
1250
+ },
1251
+ // IPv6 addresses
1252
+ {
1253
+ name: "ipv6_addresses",
1254
+ pattern: String.raw`\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b`
1255
+ },
1256
+ // Bitcoin addresses
1257
+ {
1258
+ name: "bitcoin_addresses",
1259
+ pattern: String.raw`\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b`
1260
+ },
1261
+ // Ethereum addresses
1262
+ {
1263
+ name: "ethereum_addresses",
1264
+ pattern: String.raw`\b0x[a-fA-F0-9]{40}(?![a-fA-F0-9])\b`
1265
+ },
1266
+ // Database connection strings
1267
+ {
1268
+ name: "database_connections",
1269
+ pattern: String.raw`\b(?:[Mm][Oo][Nn][Gg][Oo][Dd][Bb]|[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Mm][Yy][Ss][Qq][Ll]|[Rr][Ee][Dd][Ii][Ss]|[Mm][Ss][Ss][Qq][Ll]|[Oo][Rr][Aa][Cc][Ll][Ee]):\\/\\/[^\\s]+\b`
1270
+ },
1271
+ // Private keys
1272
+ {
1273
+ name: "rsa_private_keys",
1274
+ pattern: "-----BEGIN (?:RSA )?PRIVATE KEY-----"
1275
+ },
1276
+ {
1277
+ name: "pgp_private_keys",
1278
+ pattern: "-----BEGIN PGP PRIVATE KEY BLOCK-----"
1279
+ },
1280
+ // Additional API Keys and Tokens
1281
+ {
1282
+ name: "google_oauth",
1283
+ pattern: String.raw`\bya29\\.[a-zA-Z0-9_-]{60,}\b`
1284
+ },
1285
+ {
1286
+ name: "firebase_tokens",
1287
+ pattern: String.raw`\bAAAA[A-Za-z0-9_-]{100,}\b`
1288
+ },
1289
+ {
1290
+ name: "google_app_ids",
1291
+ pattern: String.raw`\b[0-9]+-\w+\.apps\.googleusercontent\.com\b`
1292
+ },
1293
+ {
1294
+ name: "facebook_secrets",
1295
+ pattern: String.raw`\b(facebook_secret|FACEBOOK_SECRET|facebook_app_secret|FACEBOOK_APP_SECRET)[a-z_ =\\s"'\\:]{0,5}[^a-zA-Z0-9][a-f0-9]{32}[^a-zA-Z0-9]`
1296
+ },
1297
+ {
1298
+ name: "github_keys",
1299
+ pattern: String.raw`\b(GITHUB_SECRET|GITHUB_KEY|github_secret|github_key|github_token|GITHUB_TOKEN|github_api_key|GITHUB_API_KEY)[a-z_ =\\s\"'\\:]{0,10}[^a-zA-Z0-9][a-zA-Z0-9]{40}[^a-zA-Z0-9]`
1300
+ },
1301
+ {
1302
+ name: "heroku_keys",
1303
+ pattern: String.raw`\b(heroku_api_key|HEROKU_API_KEY|heroku_secret|HEROKU_SECRET)[a-z_ =\\s\"'\\:]{0,10}[^a-zA-Z0-9-]\\w{8}(?:-\\w{4}){3}-\\w{12}[^a-zA-Z0-9\\-]`
1304
+ },
1305
+ {
1306
+ name: "slack_api_keys",
1307
+ pattern: String.raw`\b(slack_api_key|SLACK_API_KEY|slack_key|SLACK_KEY)[a-z_ =\\s\"'\\:]{0,10}[^a-f0-9][a-f0-9]{32}[^a-f0-9]`
1308
+ },
1309
+ {
1310
+ name: "slack_api_tokens",
1311
+ pattern: String.raw`\b(xox[pb](?:-[a-zA-Z0-9]+){4,})\b`
1312
+ },
1313
+ // Extended Private Keys and Certificates
1314
+ {
1315
+ name: "dsa_private_keys",
1316
+ pattern: String.raw`-----BEGIN DSA PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END DSA PRIVATE KEY-----`
1317
+ },
1318
+ {
1319
+ name: "ec_private_keys",
1320
+ pattern: String.raw`-----BEGIN (?:EC|ECDSA) PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END (?:EC|ECDSA) PRIVATE KEY-----`
1321
+ },
1322
+ {
1323
+ name: "encrypted_private_keys",
1324
+ pattern: String.raw`-----BEGIN ENCRYPTED PRIVATE KEY-----(?:.|\s)+?-----END ENCRYPTED PRIVATE KEY-----`
1325
+ },
1326
+ {
1327
+ name: "ssl_certificates",
1328
+ pattern: String.raw`-----BEGIN CERTIFICATE-----(?:.|\n)+?\s*-----END CERTIFICATE-----`
1329
+ },
1330
+ {
1331
+ name: "ssh_dss_public",
1332
+ pattern: String.raw`\bssh-dss [0-9A-Za-z+/]+[=]{2}\b`
1333
+ },
1334
+ {
1335
+ name: "ssh_rsa_public",
1336
+ pattern: String.raw`\bssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3} [^@]+@[^@]+\b`
1337
+ },
1338
+ {
1339
+ name: "putty_ssh_keys",
1340
+ pattern: String.raw`PuTTY-User-Key-File-2: ssh-(?:rsa|dss)\s*Encryption: none(?:.|\s?)*?Private-MAC:`
1341
+ },
1342
+ // Security and Network
1343
+ {
1344
+ name: "cve_numbers",
1345
+ pattern: String.raw`\b[Cc][Vv][Ee]-\\d{4}-\\d{4,7}\b`
1346
+ },
1347
+ {
1348
+ name: "microsoft_oauth",
1349
+ pattern: String.raw`https://login\.microsoftonline\.com/common/oauth2/v2\.0/token|https://login\.windows\.net/common/oauth2/token`
1350
+ },
1351
+ {
1352
+ name: "postgres_connections",
1353
+ pattern: String.raw`\b(?:[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Pp][Gg][Ss][Qq][Ll])\\:\\/\\/`
1354
+ },
1355
+ {
1356
+ name: "box_links",
1357
+ pattern: String.raw`https://app\.box\.com/[s|l]/\S+`
1358
+ },
1359
+ {
1360
+ name: "dropbox_links",
1361
+ pattern: String.raw`https://www\.dropbox\.com/(?:s|l)/\S+`
1362
+ },
1363
+ // Credit Card Variants
1364
+ {
1365
+ name: "amex_cards",
1366
+ pattern: String.raw`\b3[47][0-9]{13}\b`
1367
+ },
1368
+ {
1369
+ name: "visa_cards",
1370
+ pattern: String.raw`\b4[0-9]{12}(?:[0-9]{3})?\b`
1371
+ },
1372
+ {
1373
+ name: "discover_cards",
1374
+ pattern: String.raw`\b65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}\b`
1375
+ }
1376
+ ];
1377
+
1378
+ // src/internal/masking/utils.ts
1379
+ function isValidPatternName(name) {
1380
+ return /^[a-zA-Z0-9_]+$/.test(name);
1381
+ }
1382
+ function isLikelyReDoSPattern(pattern) {
1383
+ const dangerousPatterns = [
1384
+ // Nested quantifiers like (a+)+, (a*)+, (a+)*
1385
+ /\([^)]*[+*]\)[+*]/,
1386
+ // Overlapping alternation under an outer quantifier like (a|a)+, (\w|\d)+. Scoped to
1387
+ // capturing groups so the lazy (?:…)+? built-ins aren't false-flagged.
1388
+ /\((?!\?)[^)]*\|[^)]*\)[+*]/,
1389
+ // Complex backtracking patterns - but more specific
1390
+ /\([^)]*[+*][^)]*[+*][^)]*\)[+*]/
1391
+ ];
1392
+ return dangerousPatterns.some((dangerous) => dangerous.test(pattern));
1393
+ }
1394
+ function getGroupedPattern(patternEntry) {
1395
+ let name = patternEntry.name;
1396
+ if (!name || name === "") {
1397
+ name = `pattern_${Math.random().toString(16).slice(2)}`;
1398
+ }
1399
+ if (!isValidPatternName(name)) {
1400
+ throw new Error(
1401
+ `Pattern name '${name}' must only contain alphanumeric characters and underscores`
1402
+ );
1403
+ }
1404
+ if (isLikelyReDoSPattern(patternEntry.pattern)) {
1405
+ throw new Error(`Potentially dangerous ReDoS pattern detected: '${patternEntry.pattern}'`);
1406
+ }
1407
+ try {
1408
+ new RegExp(patternEntry.pattern);
1409
+ } catch (error) {
1410
+ throw new Error(`Invalid regex pattern '${patternEntry.pattern}': ${String(error)}`, {
1411
+ cause: error
1412
+ });
1413
+ }
1414
+ return `(?<${name}>${patternEntry.pattern})`;
1415
+ }
1416
+ function isIPatternEntry(obj) {
1417
+ return typeof obj === "object" && obj !== null && typeof obj.pattern === "string" && (obj.name === void 0 || typeof obj.name === "string");
1418
+ }
1419
+ function isIEventMaskingRule(obj) {
1420
+ return typeof obj === "object" && obj !== null && typeof obj.mode === "string" && Array.isArray(obj.patterns) && obj.patterns.every(
1421
+ (p) => isIPatternEntry(p) || typeof p === "string"
1422
+ ) && (obj.attributePattern === void 0 || typeof obj.attributePattern === "string");
1423
+ }
1424
+ function convertPatternsToPatternEntries(patterns) {
1425
+ const patternEntries = [];
1426
+ for (const pattern of patterns) {
1427
+ if (typeof pattern === "string") {
1428
+ patternEntries.push({ pattern, name: "" });
1429
+ } else if (isIPatternEntry(pattern)) {
1430
+ patternEntries.push(pattern);
1431
+ } else {
1432
+ throw new Error("Patterns must be either strings or PatternEntry instances");
1433
+ }
1434
+ }
1435
+ return patternEntries;
1436
+ }
1437
+ function compilePatternEntries(patternEntries) {
1438
+ const patternGroups = [];
1439
+ for (const patternEntry of patternEntries) {
1440
+ try {
1441
+ patternGroups.push(getGroupedPattern(patternEntry));
1442
+ } catch (error) {
1443
+ logger.warn(`Invalid pattern '${patternEntry.name}': ${patternEntry.pattern}`, error);
1444
+ continue;
1445
+ }
1446
+ }
1447
+ if (patternGroups.length === 0) {
1448
+ return null;
1449
+ }
1450
+ try {
1451
+ return new RegExp(patternGroups.join("|"));
1452
+ } catch (error) {
1453
+ logger.warn("Failed to compile pattern entries into regex", error);
1454
+ return null;
1455
+ }
1456
+ }
1457
+ var compiledPatternCache = /* @__PURE__ */ new WeakMap();
1458
+ function getCompiledPatternsForRule(rule) {
1459
+ const key = rule.patterns;
1460
+ if (compiledPatternCache.has(key)) {
1461
+ return compiledPatternCache.get(key) ?? null;
1462
+ }
1463
+ const compiled = compilePatternEntries(convertPatternsToPatternEntries(rule.patterns));
1464
+ compiledPatternCache.set(key, compiled);
1465
+ return compiled;
1466
+ }
1467
+ function getCompiledAttributeNamePattern(rule) {
1468
+ if (!rule.attributePattern) {
1469
+ logger.debug("No attribute pattern provided, using default .*");
1470
+ return /.*/;
1471
+ }
1472
+ let compiledPatternString = rule.attributePattern;
1473
+ if (isIEventMaskingRule(rule) && rule.eventNamePattern) {
1474
+ compiledPatternString = `(${compiledPatternString})|(${rule.eventNamePattern})`;
1475
+ }
1476
+ return new RegExp(compiledPatternString);
1477
+ }
1478
+ function shouldContinueExecution(startTime, iterations, timeoutMs) {
1479
+ if (Date.now() - startTime > timeoutMs) {
1480
+ logger.warn("Regex execution timed out - potential ReDoS pattern detected");
1481
+ return false;
1482
+ }
1483
+ const maxIterations = 1e3;
1484
+ if (iterations > maxIterations) {
1485
+ logger.warn("Regex execution exceeded maximum iterations - potential ReDoS pattern detected");
1486
+ return false;
1487
+ }
1488
+ return true;
1489
+ }
1490
+ function createGlobalPattern(pattern) {
1491
+ return new RegExp(
1492
+ pattern.source,
1493
+ pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g"
1494
+ );
1495
+ }
1496
+ function executeRegexWithTimeout(pattern, value, timeoutMs = 100) {
1497
+ const matches = [];
1498
+ const globalPattern = createGlobalPattern(pattern);
1499
+ const startTime = Date.now();
1500
+ let match;
1501
+ let iterations = 0;
1502
+ while ((match = globalPattern.exec(value)) !== null) {
1503
+ if (!shouldContinueExecution(startTime, ++iterations, timeoutMs)) {
1504
+ break;
1505
+ }
1506
+ matches.push(match);
1507
+ if (match[0].length === 0) {
1508
+ globalPattern.lastIndex = match.index + 1;
1509
+ }
1510
+ }
1511
+ return matches;
1512
+ }
1513
+ function maskStringByPattern(value, pattern, mode = "full") {
1514
+ const matches = [];
1515
+ try {
1516
+ const regexMatches = executeRegexWithTimeout(pattern, value);
1517
+ for (const match of regexMatches) {
1518
+ matches.push({
1519
+ start: match.index,
1520
+ end: match.index + match[0].length,
1521
+ text: match[0],
1522
+ groups: match.groups
1523
+ });
1524
+ }
1525
+ } catch (error) {
1526
+ logger.warn("Regex execution failed, skipping masking", error);
1527
+ return value;
1528
+ }
1529
+ for (const matchInfo of matches.toReversed()) {
1530
+ let patternName = "unknown";
1531
+ if (matchInfo.groups) {
1532
+ const firstDefined = Object.entries(matchInfo.groups).find(
1533
+ ([, groupValue]) => groupValue !== void 0
1534
+ );
1535
+ if (firstDefined) {
1536
+ const [groupName] = firstDefined;
1537
+ if (groupName.includes("_") && /\d$/.test(groupName)) {
1538
+ const parts = groupName.split("_");
1539
+ patternName = parts[0] || groupName;
1540
+ } else {
1541
+ patternName = groupName;
1542
+ }
1543
+ }
1544
+ }
1545
+ logger.info(`Masking detected: pattern '${patternName}' found match in value`);
1546
+ const masked = mode === "partial" ? matchInfo.text.at(0) + "*****" : "*****";
1547
+ value = value.slice(0, matchInfo.start) + masked + value.slice(matchInfo.end);
1548
+ }
1549
+ return value;
1550
+ }
1551
+ function maskStringByPatternBasedRule(value, rule) {
1552
+ const patternEntries = convertPatternsToPatternEntries(rule.patterns);
1553
+ if (patternEntries.length === 0) {
1554
+ logger.warn("No patterns provided for masking rule, returning original value");
1555
+ return value;
1556
+ }
1557
+ const mode = rule.mode;
1558
+ if (!patternEntries || patternEntries.length === 0) {
1559
+ return mode === "partial" && value ? value.at(0) + "*****" : "*****";
1560
+ }
1561
+ const compiledPatterns = getCompiledPatternsForRule(rule);
1562
+ if (!compiledPatterns) {
1563
+ return value;
1564
+ }
1565
+ return maskStringByPattern(value, compiledPatterns, mode);
1566
+ }
1567
+ function maskValue(value, rule) {
1568
+ if (typeof value === "string") {
1569
+ return maskStringByPatternBasedRule(value, rule);
1570
+ }
1571
+ if (typeof value === "boolean" || typeof value === "number") {
1572
+ return maskStringByPatternBasedRule(String(value), rule);
1573
+ }
1574
+ if (Array.isArray(value)) {
1575
+ return value.map((v) => maskStringByPatternBasedRule(String(v), rule));
1576
+ }
1577
+ if (value !== null && typeof value === "object") {
1578
+ const result = {};
1579
+ for (const [k, v] of Object.entries(value)) {
1580
+ result[k] = maskValue(v, rule);
1581
+ }
1582
+ return result;
1583
+ }
1584
+ throw new Error(`Unsupported value type for masking: ${typeof value}`);
1585
+ }
1586
+ function maskAttributes(attributes, rules, outputOriginalValue = false) {
1587
+ if (!attributes || Object.keys(attributes).length === 0) {
1588
+ return {};
1589
+ }
1590
+ const maskedAttributes = { ...attributes };
1591
+ for (const rule of rules) {
1592
+ const compiledAttributeNamePattern = getCompiledAttributeNamePattern(rule);
1593
+ const attributesToMask = compiledAttributeNamePattern ? Object.keys(maskedAttributes).filter((attr) => compiledAttributeNamePattern.test(attr)) : Object.keys(maskedAttributes);
1594
+ for (const attribute of attributesToMask) {
1595
+ const value = maskedAttributes[attribute];
1596
+ if (value !== null && value !== void 0) {
1597
+ if (outputOriginalValue) {
1598
+ logger.debug(`Masking attribute '${attribute}' with original value`, { value });
1599
+ }
1600
+ maskedAttributes[attribute] = maskValue(value, rule);
1601
+ }
1602
+ }
1603
+ }
1604
+ return maskedAttributes;
1605
+ }
1606
+
1607
+ // src/internal/log/processors/log-processor.ts
1608
+ var DEFAULT_LOG_MASKING_RULES = [
1609
+ {
1610
+ mode: "partial",
1611
+ attributePattern: "event.name",
1612
+ patterns: DEFAULT_PII_PATTERNS
1613
+ }
1614
+ ];
1615
+ var BrizzSimpleLogRecordProcessor = class extends SimpleLogRecordProcessor {
1616
+ config;
1617
+ constructor(exporter, config) {
1618
+ super({ exporter });
1619
+ this.config = config;
1620
+ }
1621
+ onEmit(logRecord) {
1622
+ const maskingConfig = this.config.masking?.eventMasking;
1623
+ if (maskingConfig) {
1624
+ maskLog(logRecord, maskingConfig);
1625
+ }
1626
+ const associationProperties = context2.active().getValue(PROPERTIES_CONTEXT_KEY);
1627
+ if (associationProperties) {
1628
+ for (const [key, value] of Object.entries(associationProperties)) {
1629
+ logRecord.setAttribute(`${BRIZZ}.${key}`, value);
1630
+ }
1631
+ }
1632
+ super.onEmit(logRecord);
1633
+ }
1634
+ };
1635
+ var BrizzBatchLogRecordProcessor = class extends BatchLogRecordProcessor {
1636
+ config;
1637
+ constructor(exporter, config) {
1638
+ super({ exporter });
1639
+ this.config = config;
1640
+ }
1641
+ onEmit(logRecord) {
1642
+ const maskingConfig = this.config.masking?.eventMasking;
1643
+ if (maskingConfig) {
1644
+ maskLog(logRecord, maskingConfig);
1645
+ }
1646
+ const associationProperties = context2.active().getValue(PROPERTIES_CONTEXT_KEY);
1647
+ if (associationProperties) {
1648
+ for (const [key, value] of Object.entries(associationProperties)) {
1649
+ logRecord.setAttribute(`${BRIZZ}.${key}`, value);
1650
+ }
1651
+ }
1652
+ super.onEmit(logRecord);
1653
+ }
1654
+ };
1655
+ function maskLog(logRecord, config) {
1656
+ if (!logRecord.attributes) {
1657
+ return logRecord;
1658
+ }
1659
+ let rules = config.rules || [];
1660
+ if (!config.disableDefaultRules) {
1661
+ rules = [...DEFAULT_LOG_MASKING_RULES, ...rules];
1662
+ }
1663
+ try {
1664
+ if (logRecord.attributes && Object.keys(logRecord.attributes).length > 0) {
1665
+ const attributesRecord = {};
1666
+ for (const [key, value] of Object.entries(logRecord.attributes)) {
1667
+ attributesRecord[key] = value;
1668
+ }
1669
+ const maskedAttributes = maskAttributes(attributesRecord, rules);
1670
+ if (maskedAttributes) {
1671
+ const newAttributes = {};
1672
+ for (const [key, value] of Object.entries(maskedAttributes)) {
1673
+ newAttributes[key] = value;
1674
+ }
1675
+ for (const [key, value] of Object.entries(logRecord.attributes)) {
1676
+ if (key.startsWith(INTERNAL_EVENT_PREFIX)) {
1677
+ newAttributes[key] = value;
1678
+ }
1679
+ }
1680
+ logRecord.setAttributes(newAttributes);
1681
+ }
1682
+ }
1683
+ if (config.maskBody && logRecord.body !== void 0 && logRecord.body !== null) {
1684
+ let maskedBody = logRecord.body;
1685
+ for (const rule of rules) {
1686
+ maskedBody = maskValue(maskedBody, rule);
1687
+ }
1688
+ logRecord.setBody(maskedBody);
1689
+ }
1690
+ return logRecord;
1691
+ } catch (error) {
1692
+ logger.error("Error masking log record:", error);
1693
+ return logRecord;
1694
+ }
1695
+ }
1696
+
1697
+ // src/internal/log/logging.ts
1698
+ var LoggingModule = class _LoggingModule {
1699
+ static instance = null;
1700
+ static getInstance() {
1701
+ if (!this.instance) {
1702
+ throw new Error("Brizz must be initialized before accessing LoggingModule");
1703
+ }
1704
+ return this.instance;
1705
+ }
1706
+ logExporter = null;
1707
+ logProcessor = null;
1708
+ loggerProvider = null;
1709
+ /**
1710
+ * Initialize the log exporter
1711
+ */
1712
+ initLogExporter(config) {
1713
+ if (this.logExporter) {
1714
+ logger.debug("Log exporter already initialized, skipping re-initialization");
1715
+ return;
1716
+ }
1717
+ if (config.customLogExporter) {
1718
+ logger.debug("Using custom log exporter");
1719
+ this.logExporter = config.customLogExporter;
1720
+ logger.debug("Custom log exporter initialized successfully");
1721
+ return;
1722
+ }
1723
+ const logsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/logs";
1724
+ logger.debug("Initializing default OTLP log exporter", { url: logsUrl });
1725
+ const headers = { ...config.headers };
1726
+ this.logExporter = new OTLPLogExporter({
1727
+ url: logsUrl,
1728
+ headers
1729
+ });
1730
+ logger.debug("OTLP log exporter initialized successfully");
1731
+ }
1732
+ /**
1733
+ * Initialize the log processor with masking support
1734
+ */
1735
+ initLogProcessor(config) {
1736
+ if (this.logProcessor) {
1737
+ logger.debug("Log processor already initialized, skipping re-initialization");
1738
+ return;
1739
+ }
1740
+ if (!this.logExporter) {
1741
+ throw new Error("Log exporter must be initialized before processor");
1742
+ }
1743
+ logger.debug("Initializing log processor", {
1744
+ disableBatch: config.disableBatch,
1745
+ hasMasking: !!config.masking?.eventMasking
1746
+ });
1747
+ this.logProcessor = config.disableBatch ? new BrizzSimpleLogRecordProcessor(this.logExporter, config) : new BrizzBatchLogRecordProcessor(this.logExporter, config);
1748
+ logger.debug("Log processor initialized successfully");
1749
+ }
1750
+ /**
1751
+ * Initialize the logger provider
1752
+ */
1753
+ initLoggerProvider(config) {
1754
+ if (this.loggerProvider) {
1755
+ logger.debug("Logger provider already initialized, skipping re-initialization");
1756
+ return;
1757
+ }
1758
+ if (!this.logProcessor) {
1759
+ throw new Error("Log processor must be initialized before logger provider");
1760
+ }
1761
+ logger.debug("Creating resource with service name", {
1762
+ serviceName: config.appName
1763
+ });
1764
+ const resourceAttributes = {
1765
+ ...config.resourceAttributes,
1766
+ "service.name": config.appName,
1767
+ [BRIZZ_SDK_VERSION]: getSDKVersion(),
1768
+ [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
1769
+ };
1770
+ if (config.environment) {
1771
+ resourceAttributes["deployment.environment"] = config.environment;
1772
+ }
1773
+ if (config.appVersion) {
1774
+ resourceAttributes["service.version"] = config.appVersion;
1775
+ }
1776
+ const resource = resourceFromAttributes(resourceAttributes);
1777
+ logger.debug("Creating logger provider with resource");
1778
+ this.loggerProvider = new LoggerProvider({
1779
+ resource,
1780
+ processors: [this.logProcessor]
1781
+ });
1782
+ logger.debug("Logger provider initialization completed");
1783
+ }
1784
+ /**
1785
+ * Initialize the logging module with the provided configuration
1786
+ */
1787
+ setup(config) {
1788
+ logger.info("Setting up logging module");
1789
+ this.initLogExporter(config);
1790
+ this.initLogProcessor(config);
1791
+ this.initLoggerProvider(config);
1792
+ _LoggingModule.instance = this;
1793
+ logger.info("Logging module setup completed");
1794
+ }
1795
+ /**
1796
+ * Emit a custom event to the telemetry pipeline
1797
+ */
1798
+ emitEvent(name, attributes, body, severityNumber = SeverityNumber.INFO) {
1799
+ logger.debug("Attempting to emit event", {
1800
+ name,
1801
+ hasAttributes: !!attributes,
1802
+ attributesCount: attributes ? Object.keys(attributes).length : 0,
1803
+ hasBody: !!body,
1804
+ severityNumber
1805
+ });
1806
+ if (!this.loggerProvider) {
1807
+ logger.error("Cannot emit event: Logger provider not initialized");
1808
+ throw new Error("Logging module not initialized");
1809
+ }
1810
+ const logAttributes = { "event.name": name };
1811
+ if (attributes) {
1812
+ Object.assign(logAttributes, attributes);
1813
+ logger.debug("Combined log attributes", { attributes: Object.keys(logAttributes) });
1814
+ }
1815
+ logger.debug("Getting logger instance for brizz_events");
1816
+ const eventLogger = this.loggerProvider.getLogger("brizz.events");
1817
+ logger.debug("Emitting log record with eventName", { eventName: name });
1818
+ try {
1819
+ eventLogger.emit({
1820
+ eventName: name,
1821
+ attributes: logAttributes,
1822
+ severityNumber,
1823
+ body
1824
+ });
1825
+ logger.debug("Event successfully emitted", { eventName: name });
1826
+ } catch (error) {
1827
+ logger.error(`Failed to emit event '${name}'`, { error, eventName: name });
1828
+ logger.error("Log record that failed", {
1829
+ eventName: name,
1830
+ hasAttributes: logAttributes,
1831
+ severityNumber,
1832
+ hasBody: body
1833
+ });
1834
+ throw error instanceof Error ? error : new Error(String(error));
1835
+ }
1836
+ }
1837
+ /**
1838
+ * Check if the module is initialized
1839
+ */
1840
+ isInitialized() {
1841
+ return this.loggerProvider !== null;
1842
+ }
1843
+ /**
1844
+ * Get the logger provider
1845
+ */
1846
+ getLoggerProvider() {
1847
+ return this.loggerProvider;
1848
+ }
1849
+ /**
1850
+ * Shutdown the logging module
1851
+ */
1852
+ async shutdown() {
1853
+ logger.debug("Shutting down logging module");
1854
+ if (this.loggerProvider) {
1855
+ await this.loggerProvider.shutdown();
1856
+ this.loggerProvider = null;
1857
+ }
1858
+ this.logProcessor = null;
1859
+ this.logExporter = null;
1860
+ if (_LoggingModule.instance === this) {
1861
+ _LoggingModule.instance = null;
1862
+ }
1863
+ logger.debug("Logging module shutdown completed");
1864
+ }
1865
+ };
1866
+ function emitEvent(name, attributes, body, severityNumber = SeverityNumber.INFO) {
1867
+ return LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
1868
+ }
1869
+ function emitEventWithSessionId(sessionId, name, attributes, body, severityNumber = SeverityNumber.INFO) {
1870
+ return callWithSessionId(sessionId, () => {
1871
+ LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
1872
+ });
1873
+ }
1874
+
1875
+ // src/internal/metric/metrics.ts
1876
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
1877
+ import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
1878
+ var MetricsModule = class _MetricsModule {
1879
+ static instance = null;
1880
+ static getInstance() {
1881
+ if (!this.instance) {
1882
+ throw new Error("Brizz must be initialized before accessing MetricsModule");
1883
+ }
1884
+ return this.instance;
1885
+ }
1886
+ metricsExporter = null;
1887
+ metricsReader = null;
1888
+ /**
1889
+ * Initialize the metrics exporter
1890
+ */
1891
+ initMetricsExporter(config) {
1892
+ if (this.metricsExporter) {
1893
+ logger.debug("Metrics exporter already initialized, skipping re-initialization");
1894
+ return;
1895
+ }
1896
+ const metricsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/metrics";
1897
+ logger.debug("Initializing metrics exporter", { url: metricsUrl });
1898
+ this.metricsExporter = new OTLPMetricExporter({
1899
+ url: metricsUrl,
1900
+ headers: config.headers
1901
+ });
1902
+ logger.debug("Metrics exporter initialized successfully");
1903
+ }
1904
+ /**
1905
+ * Initialize the metrics reader
1906
+ */
1907
+ initMetricsReader(config) {
1908
+ if (this.metricsReader) {
1909
+ logger.debug("Metrics reader already initialized, skipping re-initialization");
1910
+ return;
1911
+ }
1912
+ if (config.customMetricReader) {
1913
+ logger.debug("Using custom metric reader");
1914
+ this.metricsReader = config.customMetricReader;
1915
+ logger.debug("Custom metric reader initialized successfully");
1916
+ return;
1917
+ }
1918
+ logger.debug(
1919
+ "Using default metrics flow - creating OTLP exporter and PeriodicExportingMetricReader"
1920
+ );
1921
+ this.initMetricsExporter(config);
1922
+ if (!this.metricsExporter) {
1923
+ throw new Error("Failed to initialize metrics exporter");
1924
+ }
1925
+ this.metricsReader = new PeriodicExportingMetricReader({
1926
+ exporter: this.metricsExporter
1927
+ });
1928
+ logger.debug("Default metrics reader initialized successfully");
1929
+ }
1930
+ /**
1931
+ * Initialize the metrics module with the provided configuration
1932
+ */
1933
+ setup(config) {
1934
+ logger.info("Setting up metrics module");
1935
+ this.initMetricsReader(config);
1936
+ _MetricsModule.instance = this;
1937
+ logger.info("Metrics module setup completed");
1938
+ }
1939
+ /**
1940
+ * Get the metrics exporter
1941
+ */
1942
+ getMetricsExporter() {
1943
+ if (!this.metricsExporter) {
1944
+ throw new Error("Metrics module not initialized");
1945
+ }
1946
+ return this.metricsExporter;
1947
+ }
1948
+ /**
1949
+ * Get the metrics reader
1950
+ */
1951
+ getMetricsReader() {
1952
+ if (!this.metricsReader) {
1953
+ throw new Error("Metrics module not initialized");
1954
+ }
1955
+ return this.metricsReader;
1956
+ }
1957
+ /**
1958
+ * Shutdown the metrics module
1959
+ */
1960
+ shutdown() {
1961
+ logger.debug("Shutting down metrics module");
1962
+ this.metricsReader = null;
1963
+ this.metricsExporter = null;
1964
+ if (_MetricsModule.instance === this) {
1965
+ _MetricsModule.instance = null;
1966
+ }
1967
+ logger.debug("Metrics module shutdown completed");
1968
+ }
1969
+ };
1970
+ function getMetricsExporter() {
1971
+ return MetricsModule.getInstance().getMetricsExporter();
1972
+ }
1973
+ function getMetricsReader() {
1974
+ return MetricsModule.getInstance().getMetricsReader();
1975
+ }
1976
+
1977
+ // src/internal/trace/tracing.ts
1978
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
1979
+
1980
+ // src/internal/trace/exporters/span-exporter.ts
1981
+ import { ExportResultCode } from "@opentelemetry/core";
1982
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
1983
+ var BrizzSpanExporter = class {
1984
+ _delegate;
1985
+ _brizzResource;
1986
+ _beforeSendSpan;
1987
+ constructor(delegate, config) {
1988
+ this._delegate = delegate;
1989
+ const resourceAttrs = {
1990
+ ...config.resourceAttributes,
1991
+ "service.name": config.appName,
1992
+ [BRIZZ_SDK_VERSION]: getSDKVersion(),
1993
+ [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
1994
+ };
1995
+ if (config.environment) {
1996
+ resourceAttrs["deployment.environment"] = config.environment;
1997
+ }
1998
+ if (config.appVersion) {
1999
+ resourceAttrs["service.version"] = config.appVersion;
2000
+ }
2001
+ this._brizzResource = resourceFromAttributes2(resourceAttrs);
2002
+ this._beforeSendSpan = config.beforeSendSpan;
2003
+ }
2004
+ export(spans, resultCallback) {
2005
+ if (spans.length === 0) {
2006
+ resultCallback({ code: ExportResultCode.SUCCESS });
2007
+ return;
2008
+ }
2009
+ const patchedSpans = spans.map((span) => ({
2010
+ ...span,
2011
+ resource: span.resource.merge(this._brizzResource),
2012
+ spanContext: span.spanContext.bind(span)
2013
+ }));
2014
+ const filter = this._beforeSendSpan;
2015
+ if (!filter) {
2016
+ this._delegate.export(patchedSpans, resultCallback);
2017
+ return;
2018
+ }
2019
+ const verdicts = patchedSpans.map((span) => {
2020
+ try {
2021
+ return Promise.resolve(filter(span));
2022
+ } catch (error) {
2023
+ logger.warn("beforeSendSpan threw; span will be kept", { error });
2024
+ return Promise.resolve(true);
2025
+ }
2026
+ });
2027
+ Promise.all(verdicts).then((keep) => {
2028
+ const filtered = patchedSpans.filter((_, i) => keep[i] !== false);
2029
+ if (filtered.length === 0) {
2030
+ resultCallback({ code: ExportResultCode.SUCCESS });
2031
+ return;
2032
+ }
2033
+ this._delegate.export(filtered, resultCallback);
2034
+ return;
2035
+ }).catch((error) => {
2036
+ logger.warn("beforeSendSpan rejected; all spans will be kept", { error });
2037
+ this._delegate.export(patchedSpans, resultCallback);
2038
+ });
2039
+ }
2040
+ async shutdown() {
2041
+ return this._delegate.shutdown();
2042
+ }
2043
+ async forceFlush() {
2044
+ return this._delegate.forceFlush?.();
2045
+ }
2046
+ };
2047
+
2048
+ // src/internal/trace/processors/span-processor.ts
2049
+ import { context as context3 } from "@opentelemetry/api";
2050
+ import {
2051
+ BatchSpanProcessor,
2052
+ SimpleSpanProcessor
2053
+ } from "@opentelemetry/sdk-trace-base";
2054
+ function applyContextAttributes(span) {
2055
+ const sessionProperties = context3.active().getValue(PROPERTIES_CONTEXT_KEY);
2056
+ if (sessionProperties) {
2057
+ for (const [key, value] of Object.entries(sessionProperties)) {
2058
+ span.setAttribute(`${BRIZZ}.${key}`, value);
2059
+ }
2060
+ }
2061
+ }
2062
+ var DEFAULT_MASKING_RULES = [
2063
+ {
2064
+ mode: "partial",
2065
+ patterns: DEFAULT_PII_PATTERNS
2066
+ }
2067
+ ];
2068
+ var BrizzSimpleSpanProcessor = class extends SimpleSpanProcessor {
2069
+ config;
2070
+ constructor(spanExporter, config) {
2071
+ super(spanExporter);
2072
+ this.config = config;
2073
+ }
2074
+ onStart(span, parentContext) {
2075
+ applyContextAttributes(span);
2076
+ super.onStart(span, parentContext);
2077
+ }
2078
+ onEnd(span) {
2079
+ const maskingConfig = this.config.masking?.spanMasking;
2080
+ if (maskingConfig) {
2081
+ maskReadableSpan(span, maskingConfig);
2082
+ }
2083
+ super.onEnd(span);
2084
+ }
2085
+ };
2086
+ var BrizzBatchSpanProcessor = class extends BatchSpanProcessor {
2087
+ config;
2088
+ constructor(spanExporter, config) {
2089
+ super(spanExporter);
2090
+ this.config = config;
2091
+ }
2092
+ onStart(span, parentContext) {
2093
+ applyContextAttributes(span);
2094
+ super.onStart(span, parentContext);
2095
+ }
2096
+ onEnd(span) {
2097
+ const maskingConfig = this.config.masking?.spanMasking;
2098
+ if (maskingConfig) {
2099
+ maskReadableSpan(span, maskingConfig);
2100
+ }
2101
+ super.onEnd(span);
2102
+ }
2103
+ };
2104
+ function maskReadableSpan(span, config) {
2105
+ const attrs = span.attributes;
2106
+ if (!attrs || Object.keys(attrs).length === 0) {
2107
+ return;
2108
+ }
2109
+ let rules = config.rules ? [...config.rules] : [];
2110
+ if (!config.disableDefaultRules) {
2111
+ rules = [...rules, ...DEFAULT_MASKING_RULES];
2112
+ }
2113
+ try {
2114
+ const input = {};
2115
+ for (const [k, v] of Object.entries(attrs)) {
2116
+ input[k] = v;
2117
+ }
2118
+ const masked = maskAttributes(input, rules);
2119
+ const maskedEntries = Object.entries(masked ?? {});
2120
+ for (const [k, v] of maskedEntries) {
2121
+ if (attrs[k] !== v) {
2122
+ attrs[k] = v;
2123
+ }
2124
+ }
2125
+ } catch (error) {
2126
+ logger.error("Error masking span", { err: error });
2127
+ }
2128
+ }
201
2129
 
202
- // src/init.ts
203
- var init_exports = {};
2130
+ // src/internal/trace/tracing.ts
2131
+ var TracingModule = class _TracingModule {
2132
+ static instance = null;
2133
+ static getInstance() {
2134
+ if (!this.instance) {
2135
+ throw new Error("Brizz must be initialized before accessing TracingModule");
2136
+ }
2137
+ return this.instance;
2138
+ }
2139
+ spanExporter = null;
2140
+ spanProcessor = null;
2141
+ /**
2142
+ * Initialize the span exporter
2143
+ */
2144
+ initSpanExporter(config) {
2145
+ if (this.spanExporter) {
2146
+ logger.debug("Span exporter already initialized, skipping re-initialization");
2147
+ return;
2148
+ }
2149
+ if (config.customSpanExporter) {
2150
+ logger.debug("Using custom span exporter");
2151
+ this.spanExporter = new BrizzSpanExporter(config.customSpanExporter, config);
2152
+ logger.debug("Custom span exporter initialized successfully");
2153
+ return;
2154
+ }
2155
+ const tracesUrl = config.baseUrl.replace(/\/$/, "") + "/v1/traces";
2156
+ logger.debug("Initializing default OTLP span exporter", { url: tracesUrl });
2157
+ const otlpExporter = new OTLPTraceExporter({
2158
+ url: tracesUrl,
2159
+ headers: config.headers
2160
+ });
2161
+ this.spanExporter = new BrizzSpanExporter(otlpExporter, config);
2162
+ logger.debug("OTLP span exporter initialized successfully");
2163
+ }
2164
+ /**
2165
+ * Initialize the span processor with masking support
2166
+ */
2167
+ initSpanProcessor(config) {
2168
+ if (this.spanProcessor) {
2169
+ logger.debug("Span processor already initialized, skipping re-initialization");
2170
+ return;
2171
+ }
2172
+ if (!this.spanExporter) {
2173
+ throw new Error("Span exporter must be initialized before processor");
2174
+ }
2175
+ logger.debug("Initializing span processor", {
2176
+ disableBatch: config.disableBatch,
2177
+ hasMasking: !!config.masking?.spanMasking
2178
+ });
2179
+ const spanProcessor = config.disableBatch ? new BrizzSimpleSpanProcessor(this.spanExporter, config) : new BrizzBatchSpanProcessor(this.spanExporter, config);
2180
+ logger.debug("Span processor initialized successfully");
2181
+ this.spanProcessor = spanProcessor;
2182
+ }
2183
+ /**
2184
+ * Initialize the tracing module with the provided configuration
2185
+ */
2186
+ setup(config) {
2187
+ logger.info("Setting up tracing module");
2188
+ if (config.disableSpanExporter) {
2189
+ logger.info(
2190
+ "Span exporter disabled via disableSpanExporter; skipping exporter and processor setup"
2191
+ );
2192
+ this.spanExporter = null;
2193
+ this.spanProcessor = null;
2194
+ _TracingModule.instance = this;
2195
+ return;
2196
+ }
2197
+ this.initSpanExporter(config);
2198
+ this.initSpanProcessor(config);
2199
+ _TracingModule.instance = this;
2200
+ logger.info("Tracing module setup completed");
2201
+ }
2202
+ /**
2203
+ * Get the span exporter
2204
+ */
2205
+ getSpanExporter() {
2206
+ if (!this.spanExporter) {
2207
+ throw new Error("Tracing module not initialized");
2208
+ }
2209
+ return this.spanExporter;
2210
+ }
2211
+ /**
2212
+ * Get the span processor
2213
+ */
2214
+ getSpanProcessor() {
2215
+ if (!this.spanProcessor) {
2216
+ throw new Error("Tracing module not initialized");
2217
+ }
2218
+ return this.spanProcessor;
2219
+ }
2220
+ async shutdown() {
2221
+ logger.debug("Shutting down tracing module");
2222
+ if (this.spanProcessor) {
2223
+ await this.spanProcessor.shutdown();
2224
+ this.spanProcessor = null;
2225
+ }
2226
+ if (this.spanExporter) {
2227
+ await this.spanExporter.shutdown();
2228
+ this.spanExporter = null;
2229
+ }
2230
+ _TracingModule.instance = null;
2231
+ logger.debug("Tracing module shutdown completed");
2232
+ }
2233
+ };
2234
+ function getSpanExporter() {
2235
+ return TracingModule.getInstance().getSpanExporter();
2236
+ }
2237
+ function getSpanProcessor() {
2238
+ return TracingModule.getInstance().getSpanProcessor();
2239
+ }
2240
+
2241
+ // src/internal/sdk.ts
2242
+ var _Brizz = class __Brizz {
2243
+ static instance = null;
2244
+ static getInstance() {
2245
+ if (!this.instance) {
2246
+ throw new Error("Brizz must be initialized before accessing TracingModule");
2247
+ }
2248
+ return this.instance;
2249
+ }
2250
+ /** Flag indicating if SDK initialization has completed successfully */
2251
+ _initialized = false;
2252
+ /** OpenTelemetry tracer provider */
2253
+ _tracerProvider = null;
2254
+ /** OpenTelemetry meter provider */
2255
+ _meterProvider = null;
2256
+ /**
2257
+ * Set up instrumentation registry and configure manual modules.
2258
+ * @private
2259
+ */
2260
+ setupInstrumentation(options) {
2261
+ const registry = InstrumentationRegistry.getInstance();
2262
+ if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {
2263
+ registry.setManualModules(options.instrumentModules);
2264
+ }
2265
+ }
2266
+ /**
2267
+ * Create and register the tracer + meter providers if not disabled.
2268
+ * Only handles manual instrumentations now - auto instrumentations are loaded at import time.
2269
+ * @private
2270
+ */
2271
+ createAndStartProviders(options, resolvedConfig) {
2272
+ const registry = InstrumentationRegistry.getInstance();
2273
+ const manualInstrumentations = registry.getManualInstrumentations();
2274
+ if (options.disableNodeSdk) {
2275
+ if (manualInstrumentations.length > 0) {
2276
+ registerInstrumentations2({ instrumentations: manualInstrumentations });
2277
+ }
2278
+ logger.info("NodeSDK disabled - only telemetry modules initialized");
2279
+ return;
2280
+ }
2281
+ const resourceAttributes = {
2282
+ ...resolvedConfig.resourceAttributes,
2283
+ "service.name": resolvedConfig.appName,
2284
+ [BRIZZ_SDK_VERSION]: getSDKVersion(),
2285
+ [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
2286
+ };
2287
+ if (resolvedConfig.environment) {
2288
+ resourceAttributes["deployment.environment"] = resolvedConfig.environment;
2289
+ }
2290
+ if (resolvedConfig.appVersion) {
2291
+ resourceAttributes["service.version"] = resolvedConfig.appVersion;
2292
+ }
2293
+ const resource = defaultResource().merge(detectResources({ detectors: [envDetector, hostDetector, processDetector] })).merge(resourceFromAttributes3(resourceAttributes));
2294
+ this._tracerProvider = new NodeTracerProvider({
2295
+ resource,
2296
+ spanProcessors: resolvedConfig.disableSpanExporter ? [] : [new InterruptPropagator(), getSpanProcessor()]
2297
+ });
2298
+ this._tracerProvider.register();
2299
+ this._meterProvider = new MeterProvider({ resource, readers: [getMetricsReader()] });
2300
+ metrics.setGlobalMeterProvider(this._meterProvider);
2301
+ if (manualInstrumentations.length > 0) {
2302
+ registerInstrumentations2({ instrumentations: manualInstrumentations });
2303
+ logger.info(
2304
+ `Telemetry providers started with ${manualInstrumentations.length} manual instrumentations`
2305
+ );
2306
+ } else {
2307
+ logger.info(
2308
+ "Telemetry providers started - using auto-instrumentations loaded at import time"
2309
+ );
2310
+ }
2311
+ }
2312
+ /**
2313
+ * Initialize telemetry modules.
2314
+ *
2315
+ * Sets up the tracing, metrics, and logging modules with their
2316
+ * respective exporters and processors.
2317
+ *
2318
+ * @param {IResolvedBrizzConfig} config - Resolved configuration
2319
+ * @private
2320
+ */
2321
+ initializeModules(config) {
2322
+ logger.info("Initializing telemetry modules");
2323
+ logger.debug("Initializing tracing module");
2324
+ const tracingModule = new TracingModule();
2325
+ tracingModule.setup(config);
2326
+ logger.debug("Initializing metrics module");
2327
+ const metricsModule = new MetricsModule();
2328
+ metricsModule.setup(config);
2329
+ logger.debug("Initializing logging module");
2330
+ const loggingModule = new LoggingModule();
2331
+ loggingModule.setup(config);
2332
+ logger.info("All telemetry modules initialized successfully");
2333
+ }
2334
+ /**
2335
+ * Detect the current module system (ESM or CJS) using reliable indicators
2336
+ *
2337
+ * @returns {string} - 'ESM' or 'CJS'
2338
+ * @private
2339
+ */
2340
+ detectModuleSystem() {
2341
+ const inCJS = typeof module !== "undefined" && typeof exports !== "undefined" && typeof __require === "function" && typeof __filename === "string" && typeof __dirname === "string" && this === (typeof exports !== "undefined" ? exports : void 0);
2342
+ return inCJS ? "CJS" : "ESM";
2343
+ }
2344
+ /**
2345
+ * Shutdown all telemetry modules.
2346
+ * @private
2347
+ */
2348
+ async shutdownModules() {
2349
+ logger.info("Shutting down telemetry modules");
2350
+ try {
2351
+ try {
2352
+ const tracingModule = TracingModule.getInstance();
2353
+ await tracingModule.shutdown();
2354
+ } catch {
2355
+ logger.debug("Tracing module already shut down or not initialized");
2356
+ }
2357
+ try {
2358
+ const metricsModule = MetricsModule.getInstance();
2359
+ metricsModule.shutdown();
2360
+ } catch {
2361
+ logger.debug("Metrics module already shut down or not initialized");
2362
+ }
2363
+ try {
2364
+ const loggingModule = LoggingModule.getInstance();
2365
+ await loggingModule.shutdown();
2366
+ } catch {
2367
+ logger.debug("Logging module already shut down or not initialized");
2368
+ }
2369
+ logger.info("All telemetry modules shut down successfully");
2370
+ } catch (error) {
2371
+ logger.error("Error shutting down modules", { error });
2372
+ throw error;
2373
+ }
2374
+ }
2375
+ /**
2376
+ * Initialize the Brizz SDK with the provided configuration.
2377
+ *
2378
+ * @param {IBrizzInitializeOptions} options - Configuration options for the SDK
2379
+ * @throws {Error} - If initialization fails
2380
+ *
2381
+ * @example
2382
+ * ```typescript
2383
+ * Brizz.initialize({
2384
+ * appName: 'my-app',
2385
+ * baseUrl: 'http://localhost:4318',
2386
+ * apiKey: 'your-api-key'
2387
+ * });
2388
+ * ```
2389
+ */
2390
+ initialize(options) {
2391
+ if (this._initialized) {
2392
+ logger.warn("Brizz SDK already initialized");
2393
+ return;
2394
+ }
2395
+ logger.info("Starting Brizz SDK initialization");
2396
+ try {
2397
+ const resolvedConfig = resolveConfig(options);
2398
+ this.initializeModules(resolvedConfig);
2399
+ this.setupInstrumentation(options);
2400
+ this.createAndStartProviders(options, resolvedConfig);
2401
+ this._initialized = true;
2402
+ logger.info("Brizz SDK initialization completed successfully", {
2403
+ moduleSystem: this.detectModuleSystem()
2404
+ });
2405
+ } catch (error) {
2406
+ logger.error("Failed to initialize Brizz SDK", { error });
2407
+ throw new Error(`Failed to initialize SDK: ${String(error)}`, { cause: error });
2408
+ }
2409
+ }
2410
+ /**
2411
+ * Gracefully shutdown the Brizz SDK.
2412
+ *
2413
+ * This method stops all telemetry collection, flushes any pending data,
2414
+ * and releases resources. Should be called before app termination.
2415
+ *
2416
+ * @returns {Promise<void>} - Resolves when shutdown is complete
2417
+ * @throws {Error} - If shutdown fails
2418
+ *
2419
+ * @example
2420
+ * ```typescript
2421
+ * // Shutdown before app exit
2422
+ * await Brizz.shutdown();
2423
+ * ```
2424
+ */
2425
+ async shutdown() {
2426
+ if (!this._initialized) {
2427
+ logger.warn("Brizz SDK not initialized");
2428
+ return;
2429
+ }
2430
+ try {
2431
+ await this.shutdownModules();
2432
+ await this._tracerProvider?.forceFlush();
2433
+ await this._tracerProvider?.shutdown();
2434
+ await this._meterProvider?.forceFlush();
2435
+ await this._meterProvider?.shutdown();
2436
+ this._initialized = false;
2437
+ this._tracerProvider = null;
2438
+ this._meterProvider = null;
2439
+ __Brizz.instance = null;
2440
+ logger.info("Brizz SDK shut down successfully");
2441
+ } catch (error) {
2442
+ if (error instanceof Error && error.message.includes("ENOTFOUND")) {
2443
+ logger.debug(`Network error during shutdown (expected in tests): ${error.message}`);
2444
+ } else {
2445
+ logger.error(`Failed to shutdown Brizz SDK: ${String(error)}`);
2446
+ throw error;
2447
+ }
2448
+ }
2449
+ }
2450
+ };
2451
+ var Brizz = new _Brizz();
2452
+
2453
+ // src/index.ts
2454
+ import { SeverityNumber as SeverityNumber2 } from "@opentelemetry/api-logs";
204
2455
  export {
205
2456
  Brizz,
206
2457
  DEFAULT_PII_PATTERNS,
207
2458
  LogLevel,
208
2459
  Session,
209
2460
  SessionTitle,
210
- SeverityNumber,
2461
+ SeverityNumber2 as SeverityNumber,
211
2462
  addExternalLink,
212
2463
  callWithMessageId,
213
2464
  callWithMute,
@@ -215,7 +2466,6 @@ export {
215
2466
  callWithProperties,
216
2467
  callWithSessionId,
217
2468
  callWithUser,
218
- detectRuntime,
219
2469
  emitEvent,
220
2470
  emitEventWithSessionId,
221
2471
  getActiveSession,
@@ -224,7 +2474,6 @@ export {
224
2474
  getMetricsReader,
225
2475
  getSpanExporter,
226
2476
  getSpanProcessor,
227
- init_exports as init,
228
2477
  logger,
229
2478
  maskAttributes,
230
2479
  maskValue,