@brizz/sdk 0.1.28 → 0.1.30

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.
package/dist/index.cjs CHANGED
@@ -1,3155 +1,181 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }
2
+
3
+
32
4
 
33
- // src/internal/logger.ts
34
- function parseLogLevel(level) {
35
- if (!level) {
36
- return DEFAULT_LOG_LEVEL;
37
- }
38
- const normalizedLevel = level.toLowerCase().trim();
39
- switch (normalizedLevel) {
40
- case "debug":
41
- return 4 /* DEBUG */;
42
- case "info":
43
- return 3 /* INFO */;
44
- case "warn":
45
- case "warning":
46
- return 2 /* WARN */;
47
- case "error":
48
- return 1 /* ERROR */;
49
- case "none":
50
- case "off":
51
- case "silent":
52
- return 0 /* NONE */;
53
- default: {
54
- const numLevel = Number.parseInt(normalizedLevel, 10);
55
- if (!Number.isNaN(numLevel) && numLevel >= 0 && numLevel <= 4) {
56
- return numLevel;
57
- }
58
- return DEFAULT_LOG_LEVEL;
59
- }
60
- }
61
- }
62
- function setLogLevel(level) {
63
- const resolvedLevel = typeof level === "string" ? parseLogLevel(level) : level;
64
- logger.setLevel(resolvedLevel);
65
- }
66
- function getLogLevel() {
67
- return logger.getLevel();
68
- }
69
- var import_api, import_pino, LogLevel, DEFAULT_LOG_LEVEL, PinoLogger, logger;
70
- var init_logger = __esm({
71
- "src/internal/logger.ts"() {
72
- "use strict";
73
- import_api = require("@opentelemetry/api");
74
- import_pino = __toESM(require("pino"), 1);
75
- LogLevel = /* @__PURE__ */ ((LogLevel2) => {
76
- LogLevel2[LogLevel2["NONE"] = 0] = "NONE";
77
- LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR";
78
- LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
79
- LogLevel2[LogLevel2["INFO"] = 3] = "INFO";
80
- LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG";
81
- return LogLevel2;
82
- })(LogLevel || {});
83
- DEFAULT_LOG_LEVEL = 2 /* WARN */;
84
- PinoLogger = class {
85
- _level = DEFAULT_LOG_LEVEL;
86
- _pinoLogger = null;
87
- constructor() {
88
- const envLevel = this.getLogLevelFromEnv();
89
- this._level = envLevel;
90
- }
91
- /**
92
- * Lazy initialization of Pino logger to ensure it's created AFTER Jest spies
93
- * are set up during tests. This prevents the pino-pretty transport from
94
- * bypassing stdout/stderr spies.
95
- */
96
- ensurePinoLogger() {
97
- if (!this._pinoLogger) {
98
- this._pinoLogger = (0, import_pino.default)({
99
- name: "Brizz",
100
- level: this.logLevelToPino(this._level),
101
- // Disable transport in test environment to allow proper spy capture
102
- transport: this.isProduction() || this.isTest() ? void 0 : {
103
- target: "pino-pretty",
104
- options: {
105
- singleLine: true,
106
- colorize: true,
107
- translateTime: "HH:MM:ss",
108
- ignore: "pid,hostname",
109
- messageFormat: "[{name}] {msg}"
110
- }
111
- }
112
- });
113
- }
114
- return this._pinoLogger;
115
- }
116
- isProduction() {
117
- return process.env["NODE_ENV"] === "production";
118
- }
119
- isTest() {
120
- return process.env["NODE_ENV"] === "test";
121
- }
122
- getLogLevelFromEnv() {
123
- const envLevel = process.env["BRIZZ_LOG_LEVEL"];
124
- return envLevel ? parseLogLevel(envLevel) : DEFAULT_LOG_LEVEL;
125
- }
126
- logLevelToPino(level) {
127
- switch (level) {
128
- case 4 /* DEBUG */:
129
- return "debug";
130
- case 3 /* INFO */:
131
- return "info";
132
- case 2 /* WARN */:
133
- return "warn";
134
- case 1 /* ERROR */:
135
- return "error";
136
- default:
137
- return "silent";
138
- }
139
- }
140
- formatMeta(meta) {
141
- if (meta.length === 0) {
142
- return {};
143
- }
144
- if (meta.length === 1 && typeof meta[0] === "object" && meta[0] !== null) {
145
- return meta[0];
146
- }
147
- return { metadata: meta };
148
- }
149
- setLevel(level) {
150
- this._level = level;
151
- if (this._pinoLogger) {
152
- this._pinoLogger.level = this.logLevelToPino(level);
153
- }
154
- }
155
- getLevel() {
156
- return this._level;
157
- }
158
- debug = (msg, ...meta) => {
159
- if (this._level >= 4 /* DEBUG */) {
160
- this.ensurePinoLogger().debug(this.formatMeta(meta), msg);
161
- }
162
- };
163
- info = (msg, ...meta) => {
164
- if (this._level >= 3 /* INFO */) {
165
- this.ensurePinoLogger().info(this.formatMeta(meta), msg);
166
- }
167
- };
168
- warn = (msg, ...meta) => {
169
- if (this._level >= 2 /* WARN */) {
170
- this.ensurePinoLogger().warn(this.formatMeta(meta), msg);
171
- }
172
- };
173
- error = (msg, ...meta) => {
174
- if (this._level >= 1 /* ERROR */) {
175
- this.ensurePinoLogger().error(this.formatMeta(meta), msg);
176
- }
177
- };
178
- };
179
- logger = new PinoLogger();
180
- }
181
- });
182
5
 
183
- // src/internal/instrumentation/mcp/semantic-conventions.ts
184
- var MCP_TOOL_NAME, MCP_TOOL_ARGUMENTS, MCP_TOOL_RESULT, MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL, MCP_COMPONENT_TOOL_SCHEMA, MCP_TOOL_SCHEMA_PARAMETERS, MCP_TOOL_SCHEMA_OUTPUT, MCP_TOOL_DESCRIPTION, SPAN_NAME_TOOL_REGISTER, MCP_METHOD_NAME, MCP_REQUEST_ID, MCP_SESSION_ID, MCP_PROTOCOL_VERSION, MCP_RESOURCE_URI, RPC_SYSTEM, RPC_SYSTEM_MCP, RPC_RESPONSE_STATUS_CODE, GEN_AI_TOOL_NAME, GEN_AI_PROMPT_NAME, GEN_AI_OPERATION_NAME, GEN_AI_OPERATION_EXECUTE_TOOL, NETWORK_TRANSPORT, ERROR_TYPE, ERROR_TYPE_TOOL, JSONRPC_REQUEST_ID, SPAN_NAME_TOOLS_CALL, MAX_ATTRIBUTE_LENGTH, TRUNCATION_SUFFIX, METHOD_TOOLS_CALL, METHOD_TOOLS_LIST, METHOD_RESOURCES_READ, METHOD_PROMPTS_GET, METHOD_INITIALIZE;
185
- var init_semantic_conventions = __esm({
186
- "src/internal/instrumentation/mcp/semantic-conventions.ts"() {
187
- "use strict";
188
- MCP_TOOL_NAME = "mcp.tool.name";
189
- MCP_TOOL_ARGUMENTS = "mcp.tool.arguments";
190
- MCP_TOOL_RESULT = "mcp.tool.result";
191
- MCP_COMPONENT_TYPE = "mcp.component.type";
192
- MCP_COMPONENT_TOOL = "tool";
193
- MCP_COMPONENT_TOOL_SCHEMA = "tool_schema";
194
- MCP_TOOL_SCHEMA_PARAMETERS = "mcp.tool.schema.parameters";
195
- MCP_TOOL_SCHEMA_OUTPUT = "mcp.tool.schema.output";
196
- MCP_TOOL_DESCRIPTION = "mcp.tool.description";
197
- SPAN_NAME_TOOL_REGISTER = "mcp.tool.register";
198
- MCP_METHOD_NAME = "mcp.method.name";
199
- MCP_REQUEST_ID = "mcp.request.id";
200
- MCP_SESSION_ID = "mcp.session.id";
201
- MCP_PROTOCOL_VERSION = "mcp.protocol.version";
202
- MCP_RESOURCE_URI = "mcp.resource.uri";
203
- RPC_SYSTEM = "rpc.system";
204
- RPC_SYSTEM_MCP = "mcp";
205
- RPC_RESPONSE_STATUS_CODE = "rpc.response.status_code";
206
- GEN_AI_TOOL_NAME = "gen_ai.tool.name";
207
- GEN_AI_PROMPT_NAME = "gen_ai.prompt.name";
208
- GEN_AI_OPERATION_NAME = "gen_ai.operation.name";
209
- GEN_AI_OPERATION_EXECUTE_TOOL = "execute_tool";
210
- NETWORK_TRANSPORT = "network.transport";
211
- ERROR_TYPE = "error.type";
212
- ERROR_TYPE_TOOL = "tool_error";
213
- JSONRPC_REQUEST_ID = "jsonrpc.request.id";
214
- SPAN_NAME_TOOLS_CALL = "tools/call";
215
- MAX_ATTRIBUTE_LENGTH = 32 * 1024;
216
- TRUNCATION_SUFFIX = "\u2026(truncated)";
217
- METHOD_TOOLS_CALL = "tools/call";
218
- METHOD_TOOLS_LIST = "tools/list";
219
- METHOD_RESOURCES_READ = "resources/read";
220
- METHOD_PROMPTS_GET = "prompts/get";
221
- METHOD_INITIALIZE = "initialize";
222
- }
223
- });
224
6
 
225
- // src/internal/instrumentation/mcp/schemas.ts
226
- function truncateSchemaAttr(value) {
227
- if (value.length <= _MAX_SCHEMA_ATTR_BYTES) {
228
- return value;
229
- }
230
- return `{"_truncated":true,"original_length":${value.length}}`;
231
- }
232
- function safeStringify(value) {
233
- if (value === null || value === void 0) {
234
- return "";
235
- }
236
- try {
237
- return JSON.stringify(value);
238
- } catch {
239
- return "";
240
- }
241
- }
242
- function emitSchemaSpansFromListResponse(result, transportSessionId, tracer) {
243
- if (!transportSessionId) {
244
- return;
245
- }
246
- const tools = extractTools(result);
247
- if (tools === void 0) {
248
- return;
249
- }
250
- for (const tool of tools) {
251
- const name = typeof tool.name === "string" ? tool.name : void 0;
252
- if (!name) {
253
- continue;
254
- }
255
- const span = tracer.startSpan(`${SPAN_NAME_TOOL_REGISTER} ${name}`, {
256
- kind: import_api2.SpanKind.INTERNAL
257
- });
258
- try {
259
- stampSchemaAttributes(span, name, transportSessionId, tool);
260
- span.setStatus({ code: import_api2.SpanStatusCode.OK });
261
- } finally {
262
- span.end();
263
- }
264
- }
265
- }
266
- function stampSchemaAttributes(span, toolName, transportSessionId, tool) {
267
- if (!span.isRecording()) {
268
- logger.warn(
269
- `Brizz MCP: schema span is not recording; dropping attributes for ${toolName}`
270
- );
271
- return;
272
- }
273
- const description = typeof tool.description === "string" ? tool.description : "";
274
- const parameters = truncateSchemaAttr(safeStringify(tool.inputSchema));
275
- const outputSchema = tool.outputSchema !== void 0 && tool.outputSchema !== null ? truncateSchemaAttr(safeStringify(tool.outputSchema)) : "";
276
- span.setAttribute(RPC_SYSTEM, RPC_SYSTEM_MCP);
277
- span.setAttribute(MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL_SCHEMA);
278
- span.setAttribute(MCP_SESSION_ID, transportSessionId);
279
- span.setAttribute(MCP_TOOL_NAME, toolName);
280
- span.setAttribute(MCP_TOOL_SCHEMA_PARAMETERS, parameters);
281
- span.setAttribute(MCP_TOOL_SCHEMA_OUTPUT, outputSchema);
282
- span.setAttribute(MCP_TOOL_DESCRIPTION, description);
283
- }
284
- function extractTools(result) {
285
- if (!result || typeof result !== "object") {
286
- return void 0;
287
- }
288
- const tools = result.tools;
289
- if (!Array.isArray(tools)) {
290
- return void 0;
291
- }
292
- return tools.filter(
293
- (t) => t !== null && typeof t === "object"
294
- );
295
- }
296
- var import_api2, _MAX_SCHEMA_ATTR_BYTES;
297
- var init_schemas = __esm({
298
- "src/internal/instrumentation/mcp/schemas.ts"() {
299
- "use strict";
300
- import_api2 = require("@opentelemetry/api");
301
- init_logger();
302
- init_semantic_conventions();
303
- _MAX_SCHEMA_ATTR_BYTES = 4e3;
304
- }
305
- });
306
7
 
307
- // src/internal/semantic-conventions.ts
308
- var import_api3, BRIZZ, PROPERTIES, SESSION_ID, PROPERTIES_CONTEXT_KEY, SESSION_OBJECT_CONTEXT_KEY, SESSION_INPUT, SESSION_OUTPUT, SESSION_INPUT_CONTEXT, SESSION_OUTPUT_CONTEXT, SESSION_SPAN_NAME, MUTE_INPUT, MUTE_OUTPUT, SESSION_TITLE_SPAN_NAME, SESSION_TITLE_GENERATION, SESSION_TITLE, INTERRUPT_TOOLS, INTERNAL_EVENT_PREFIX, EXTERNAL_LINK_EVENT_NAME, EXTERNAL_LINK_URL, EXTERNAL_LINK_TITLE, EXTERNAL_LINK_TYPE;
309
- var init_semantic_conventions2 = __esm({
310
- "src/internal/semantic-conventions.ts"() {
311
- "use strict";
312
- import_api3 = require("@opentelemetry/api");
313
- BRIZZ = "brizz";
314
- PROPERTIES = "properties";
315
- SESSION_ID = "session.id";
316
- PROPERTIES_CONTEXT_KEY = (0, import_api3.createContextKey)(PROPERTIES);
317
- SESSION_OBJECT_CONTEXT_KEY = (0, import_api3.createContextKey)("brizz.session.object");
318
- SESSION_INPUT = "brizz.session.input";
319
- SESSION_OUTPUT = "brizz.session.output";
320
- SESSION_INPUT_CONTEXT = "brizz.session.input.context";
321
- SESSION_OUTPUT_CONTEXT = "brizz.session.output.context";
322
- SESSION_SPAN_NAME = "brizz.start_session";
323
- MUTE_INPUT = "mute.input";
324
- MUTE_OUTPUT = "mute.output";
325
- SESSION_TITLE_SPAN_NAME = "brizz.session_title";
326
- SESSION_TITLE_GENERATION = "session.title_generation";
327
- SESSION_TITLE = "brizz.session.title";
328
- INTERRUPT_TOOLS = "brizz.internal.interrupt";
329
- INTERNAL_EVENT_PREFIX = "brizz.internal.";
330
- EXTERNAL_LINK_EVENT_NAME = "brizz.internal.external_link";
331
- EXTERNAL_LINK_URL = "brizz.internal.external_link.url";
332
- EXTERNAL_LINK_TITLE = "brizz.internal.external_link.title";
333
- EXTERNAL_LINK_TYPE = "brizz.internal.external_link.type";
334
- }
335
- });
336
8
 
337
- // src/internal/instrumentation/mcp/session.ts
338
- function stampAndPropagateSession(span, sessionId, baseContext = import_api4.context.active()) {
339
- if (!sessionId) {
340
- return { context: baseContext, sessionId: null };
341
- }
342
- if (span.isRecording()) {
343
- try {
344
- span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
345
- } catch (error) {
346
- logger.warn(
347
- `Brizz MCP: failed to stamp session id on span: ${String(error)}`
348
- );
349
- }
350
- }
351
- try {
352
- const prev = baseContext.getValue(PROPERTIES_CONTEXT_KEY);
353
- const merged = prev ? { ...prev, [SESSION_ID]: sessionId } : { [SESSION_ID]: sessionId };
354
- return {
355
- context: baseContext.setValue(PROPERTIES_CONTEXT_KEY, merged),
356
- sessionId
357
- };
358
- } catch (error) {
359
- logger.warn(`Brizz MCP: failed to attach session context: ${String(error)}`);
360
- return { context: baseContext, sessionId };
361
- }
362
- }
363
- var import_api4;
364
- var init_session = __esm({
365
- "src/internal/instrumentation/mcp/session.ts"() {
366
- "use strict";
367
- import_api4 = require("@opentelemetry/api");
368
- init_logger();
369
- init_semantic_conventions2();
370
- }
371
- });
372
9
 
373
- // src/internal/instrumentation/mcp/patches/attributes.ts
374
- function deriveSpanName(method, params) {
375
- try {
376
- if (method === METHOD_TOOLS_CALL) {
377
- const name = typeof params?.["name"] === "string" ? params["name"] : "";
378
- return name ? `${SPAN_NAME_TOOLS_CALL} ${name}` : SPAN_NAME_TOOLS_CALL;
379
- }
380
- if (method === METHOD_RESOURCES_READ) {
381
- const uri = typeof params?.["uri"] === "string" ? params["uri"] : "";
382
- return uri ? `${METHOD_RESOURCES_READ} ${uri}` : METHOD_RESOURCES_READ;
383
- }
384
- if (method === METHOD_PROMPTS_GET) {
385
- const name = typeof params?.["name"] === "string" ? params["name"] : "";
386
- return name ? `${METHOD_PROMPTS_GET} ${name}` : METHOD_PROMPTS_GET;
387
- }
388
- return method;
389
- } catch {
390
- return method || "mcp";
391
- }
392
- }
393
- function applyBaseAttributes(span, request) {
394
- span.setAttribute(RPC_SYSTEM, RPC_SYSTEM_MCP);
395
- if (request.method) {
396
- span.setAttribute(MCP_METHOD_NAME, request.method);
397
- }
398
- if (request.id !== void 0 && request.id !== null) {
399
- const id = String(request.id);
400
- span.setAttribute(MCP_REQUEST_ID, id);
401
- span.setAttribute(JSONRPC_REQUEST_ID, id);
402
- }
403
- }
404
- function applyClientRequestAttributes(span, request, transportName) {
405
- applyBaseAttributes(span, request);
406
- applyMethodSpecificRequestAttributes(span, request);
407
- if (transportName) {
408
- const transport = normalizeTransport(transportName);
409
- if (transport) {
410
- span.setAttribute(NETWORK_TRANSPORT, transport);
411
- }
412
- }
413
- }
414
- function applyServerRequestAttributes(span, request, protocol) {
415
- applyBaseAttributes(span, request);
416
- applyMethodSpecificRequestAttributes(span, request);
417
- if (request.method === METHOD_TOOLS_CALL) {
418
- const args = request.params?.["arguments"];
419
- if (args !== void 0) {
420
- span.setAttribute(MCP_TOOL_ARGUMENTS, serializeForAttribute(args));
421
- }
422
- }
423
- const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;
424
- if (sessionId) {
425
- span.setAttribute(MCP_SESSION_ID, String(sessionId));
426
- }
427
- }
428
- function applyMethodSpecificRequestAttributes(span, request) {
429
- const params = request.params ?? {};
430
- switch (request.method) {
431
- case METHOD_TOOLS_CALL: {
432
- const name = typeof params["name"] === "string" ? params["name"] : "";
433
- if (name) {
434
- span.setAttribute(MCP_TOOL_NAME, name);
435
- span.setAttribute(GEN_AI_TOOL_NAME, name);
436
- }
437
- span.setAttribute(MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL);
438
- span.setAttribute(GEN_AI_OPERATION_NAME, GEN_AI_OPERATION_EXECUTE_TOOL);
439
- break;
440
- }
441
- case METHOD_RESOURCES_READ: {
442
- const uri = typeof params["uri"] === "string" ? params["uri"] : "";
443
- if (uri) {
444
- span.setAttribute(MCP_RESOURCE_URI, uri);
445
- }
446
- break;
447
- }
448
- case METHOD_PROMPTS_GET: {
449
- const name = typeof params["name"] === "string" ? params["name"] : "";
450
- if (name) {
451
- span.setAttribute(GEN_AI_PROMPT_NAME, name);
452
- }
453
- break;
454
- }
455
- default:
456
- break;
457
- }
458
- }
459
- function applyResultAttributes(span, method, result) {
460
- if (method === METHOD_INITIALIZE && result && typeof result === "object") {
461
- const protocolVersion = result["protocolVersion"];
462
- if (typeof protocolVersion === "string") {
463
- span.setAttribute(MCP_PROTOCOL_VERSION, protocolVersion);
464
- }
465
- return;
466
- }
467
- if (method !== METHOD_TOOLS_CALL) {
468
- return;
469
- }
470
- const obj = result && typeof result === "object" ? result : null;
471
- const content = obj?.["content"] ?? result;
472
- span.setAttribute(MCP_TOOL_RESULT, serializeForAttribute(content));
473
- if (obj && obj["isError"] === true) {
474
- span.setAttribute(ERROR_TYPE, ERROR_TYPE_TOOL);
475
- const message = extractToolErrorMessage(obj);
476
- span.setStatus({ code: import_api5.SpanStatusCode.ERROR, message });
477
- }
478
- }
479
- function applyErrorAttributes(span, err) {
480
- const error = err;
481
- const code = error?.code;
482
- if (typeof code === "number") {
483
- span.setAttribute(RPC_RESPONSE_STATUS_CODE, code);
484
- span.setAttribute(ERROR_TYPE, String(code));
485
- } else if (error?.name === "AbortError") {
486
- span.setAttribute(ERROR_TYPE, "cancelled");
487
- } else if (error?.name === "TimeoutError") {
488
- span.setAttribute(ERROR_TYPE, "timeout");
489
- } else {
490
- span.setAttribute(
491
- ERROR_TYPE,
492
- error?.constructor?.name || error?.name || "Error"
493
- );
494
- }
495
- try {
496
- span.recordException(error);
497
- } catch {
498
- }
499
- span.setStatus({
500
- code: import_api5.SpanStatusCode.ERROR,
501
- message: typeof error?.message === "string" ? error.message : void 0
502
- });
503
- }
504
- function serializeForAttribute(value) {
505
- const raw = rawSerialize(value);
506
- if (raw.length <= MAX_ATTRIBUTE_LENGTH) {
507
- return raw;
508
- }
509
- return raw.slice(0, MAX_ATTRIBUTE_LENGTH - TRUNCATION_SUFFIX.length) + TRUNCATION_SUFFIX;
510
- }
511
- function rawSerialize(value) {
512
- if (value === null || value === void 0) {
513
- return "";
514
- }
515
- if (typeof value === "string") {
516
- return value;
517
- }
518
- try {
519
- return JSON.stringify(value);
520
- } catch {
521
- try {
522
- if (value === null || value === void 0) {
523
- return "";
524
- }
525
- const tag = Object.prototype.toString.call(value);
526
- return typeof value.toString === "function" ? (
527
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
528
- String(value)
529
- ) : tag;
530
- } catch {
531
- return "";
532
- }
533
- }
534
- }
535
- function extractToolErrorMessage(result) {
536
- const content = result["content"];
537
- if (Array.isArray(content)) {
538
- for (const item of content) {
539
- if (item && typeof item === "object") {
540
- const text = item["text"];
541
- if (typeof text === "string") {
542
- return text;
543
- }
544
- }
545
- }
546
- }
547
- return void 0;
548
- }
549
- function normalizeTransport(ctorName) {
550
- const name = ctorName.toLowerCase();
551
- if (name.includes("stdio")) {
552
- return "stdio";
553
- }
554
- if (name.includes("sse")) {
555
- return "sse";
556
- }
557
- if (name.includes("streamablehttp") || name.includes("http")) {
558
- return "http";
559
- }
560
- return null;
561
- }
562
- var import_api5;
563
- var init_attributes = __esm({
564
- "src/internal/instrumentation/mcp/patches/attributes.ts"() {
565
- "use strict";
566
- import_api5 = require("@opentelemetry/api");
567
- init_semantic_conventions();
568
- }
569
- });
570
10
 
571
- // src/internal/instrumentation/mcp/patches/protocol.ts
572
- function patchProtocolPrototype(prototype, tracer) {
573
- if (!prototype || typeof prototype !== "object") {
574
- return false;
575
- }
576
- const proto = prototype;
577
- if (proto[PATCHED_FLAG]) {
578
- logger.debug("Brizz MCP: Protocol.prototype already patched, skipping");
579
- return false;
580
- }
581
- const originalRequest = proto["request"];
582
- const originalOnRequest = proto["_onrequest"];
583
- if (typeof originalRequest === "function") {
584
- proto["request"] = wrapRequest(originalRequest, tracer);
585
- } else {
586
- logger.debug(
587
- "Brizz MCP: Protocol.prototype.request missing \u2014 skipping CLIENT patch"
588
- );
589
- }
590
- if (typeof originalOnRequest === "function") {
591
- proto["_onrequest"] = wrapOnRequest(
592
- originalOnRequest,
593
- tracer
594
- );
595
- } else {
596
- logger.debug(
597
- "Brizz MCP: Protocol.prototype._onrequest missing \u2014 skipping SERVER patch"
598
- );
599
- }
600
- proto[PATCHED_FLAG] = true;
601
- return true;
602
- }
603
- function wrapRequest(original, tracer) {
604
- return function wrappedRequest(...args) {
605
- const request = args[0];
606
- if (!request || typeof request !== "object" || !request.method) {
607
- return original.apply(this, args);
608
- }
609
- const span = safeStartClientSpan(tracer, request, this);
610
- if (!span) {
611
- return original.apply(this, args);
612
- }
613
- return executeAroundSpan(span, request.method, () => {
614
- const ctx = import_api6.trace.setSpan(import_api6.context.active(), span);
615
- return import_api6.context.with(ctx, () => original.apply(this, args));
616
- });
617
- };
618
- }
619
- function wrapOnRequest(original, tracer) {
620
- return function wrappedOnRequest(...args) {
621
- const request = args[0];
622
- if (!request || typeof request !== "object" || !request.method) {
623
- return original.apply(this, args);
624
- }
625
- const handlers = this._requestHandlers;
626
- if (!handlers || typeof handlers.get !== "function") {
627
- return original.apply(this, args);
628
- }
629
- const method = request.method;
630
- const handler = handlers.get(method) ?? this.fallbackRequestHandler;
631
- if (!handler) {
632
- return original.apply(this, args);
633
- }
634
- const started = safeStartServerSpan(tracer, request, this);
635
- if (!started) {
636
- return original.apply(this, args);
637
- }
638
- const { span, spanCtx } = started;
639
- const transportSessionId = this.sessionId ?? this._transport?.sessionId;
640
- const postResult = method === METHOD_TOOLS_LIST ? (result) => {
641
- try {
642
- emitSchemaSpansFromListResponse(result, transportSessionId, tracer);
643
- } catch (error) {
644
- logger.warn(
645
- `Brizz MCP: failed to emit tools/list schema spans: ${String(error)}`
646
- );
647
- }
648
- } : void 0;
649
- const wrappedHandler = (req, extra) => import_api6.context.with(
650
- spanCtx,
651
- () => executeHandler(span, method, handler, req, extra, postResult)
652
- );
653
- const hadEntry = handlers.has(method);
654
- const prev = handlers.get(method);
655
- handlers.set(method, wrappedHandler);
656
- const usedFallback = !hadEntry && this.fallbackRequestHandler === handler;
657
- const fallbackPrev = usedFallback ? this.fallbackRequestHandler : void 0;
658
- if (usedFallback) {
659
- this.fallbackRequestHandler = wrappedHandler;
660
- }
661
- try {
662
- return original.apply(this, args);
663
- } finally {
664
- if (hadEntry) {
665
- handlers.set(method, prev);
666
- } else {
667
- handlers.delete(method);
668
- }
669
- if (usedFallback) {
670
- this.fallbackRequestHandler = fallbackPrev;
671
- }
672
- }
673
- };
674
- }
675
- function executeAroundSpan(span, method, run, postResult) {
676
- let result;
677
- try {
678
- result = run();
679
- } catch (error) {
680
- safeApplyErrorAttributes(span, error);
681
- safeEnd(span);
682
- throw error;
683
- }
684
- if (!isThenable(result)) {
685
- safeApplyResultAttributes(span, method, result);
686
- if (postResult) {
687
- postResult(result);
688
- }
689
- safeEnd(span);
690
- return result;
691
- }
692
- return result.then(
693
- (value) => {
694
- safeApplyResultAttributes(span, method, value);
695
- if (postResult) {
696
- postResult(value);
697
- }
698
- safeEnd(span);
699
- return value;
700
- },
701
- (error) => {
702
- safeApplyErrorAttributes(span, error);
703
- safeEnd(span);
704
- throw error;
705
- }
706
- );
707
- }
708
- function executeHandler(span, method, handler, req, extra, postResult) {
709
- return executeAroundSpan(span, method, () => handler(req, extra), postResult);
710
- }
711
- function safeStartClientSpan(tracer, request, protocol) {
712
- try {
713
- const spanName = deriveSpanName(request.method, request.params);
714
- const span = tracer.startSpan(spanName, { kind: import_api6.SpanKind.CLIENT });
715
- applyClientRequestAttributes(
716
- span,
717
- request,
718
- protocol._transport?.constructor?.name
719
- );
720
- return span;
721
- } catch (error) {
722
- logger.debug(`Brizz MCP: failed to open CLIENT span: ${String(error)}`);
723
- return null;
724
- }
725
- }
726
- function safeStartServerSpan(tracer, request, protocol) {
727
- try {
728
- const parentCtx = extractParentContext(request);
729
- const spanName = deriveSpanName(request.method, request.params);
730
- const span = tracer.startSpan(
731
- spanName,
732
- { kind: import_api6.SpanKind.SERVER },
733
- parentCtx
734
- );
735
- applyServerRequestAttributes(span, request, protocol);
736
- const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;
737
- const { context: sessCtx } = stampAndPropagateSession(span, sessionId, parentCtx);
738
- return { span, spanCtx: import_api6.trace.setSpan(sessCtx, span) };
739
- } catch (error) {
740
- logger.debug(`Brizz MCP: failed to open SERVER span: ${String(error)}`);
741
- return null;
742
- }
743
- }
744
- function extractParentContext(request) {
745
- try {
746
- const meta = request.params?._meta;
747
- if (meta && typeof meta === "object") {
748
- return import_api6.propagation.extract(import_api6.context.active(), meta);
749
- }
750
- } catch (error) {
751
- logger.debug(
752
- `Brizz MCP: failed to extract parent context from _meta: ${String(error)}`
753
- );
754
- }
755
- return import_api6.context.active();
756
- }
757
- function isThenable(value) {
758
- return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
759
- }
760
- function safeApplyResultAttributes(span, method, value) {
761
- try {
762
- applyResultAttributes(span, method, value);
763
- } catch (error) {
764
- logger.debug(
765
- `Brizz MCP: failed to apply result attributes: ${String(error)}`
766
- );
767
- }
768
- }
769
- function safeApplyErrorAttributes(span, err) {
770
- try {
771
- applyErrorAttributes(span, err);
772
- } catch (error) {
773
- logger.debug(
774
- `Brizz MCP: failed to apply error attributes: ${String(error)}`
775
- );
776
- }
777
- }
778
- function safeEnd(span) {
779
- try {
780
- span.end();
781
- } catch (error) {
782
- logger.debug(`Brizz MCP: failed to end span: ${String(error)}`);
783
- }
784
- }
785
- var import_api6, PATCHED_FLAG;
786
- var init_protocol = __esm({
787
- "src/internal/instrumentation/mcp/patches/protocol.ts"() {
788
- "use strict";
789
- import_api6 = require("@opentelemetry/api");
790
- init_logger();
791
- init_schemas();
792
- init_semantic_conventions();
793
- init_session();
794
- init_attributes();
795
- PATCHED_FLAG = /* @__PURE__ */ Symbol("brizz.mcp.protocol-patched");
796
- }
797
- });
798
11
 
799
- // src/internal/version.ts
800
- function getSDKVersion() {
801
- return "0.1.28";
802
- }
803
- var init_version = __esm({
804
- "src/internal/version.ts"() {
805
- "use strict";
806
- }
807
- });
808
12
 
809
- // src/internal/instrumentation/mcp/version.ts
810
- var INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION;
811
- var init_version2 = __esm({
812
- "src/internal/instrumentation/mcp/version.ts"() {
813
- "use strict";
814
- init_version();
815
- INSTRUMENTATION_NAME = "@brizz/sdk/mcp";
816
- INSTRUMENTATION_VERSION = getSDKVersion();
817
- }
818
- });
819
13
 
820
- // src/internal/instrumentation/mcp/instrumentation.ts
821
- function isMCPInstrumentation(value) {
822
- return !!value && typeof value === "object" && typeof value.instrumentationName === "string";
823
- }
824
- var import_openinference_instrumentation_mcp, import_api7, import_instrumentation, PROTOCOL_MODULE_NAME, PROTOCOL_SUPPORTED_VERSIONS, MCPInstrumentation;
825
- var init_instrumentation = __esm({
826
- "src/internal/instrumentation/mcp/instrumentation.ts"() {
827
- "use strict";
828
- import_openinference_instrumentation_mcp = require("@arizeai/openinference-instrumentation-mcp");
829
- import_api7 = require("@opentelemetry/api");
830
- import_instrumentation = require("@opentelemetry/instrumentation");
831
- init_logger();
832
- init_protocol();
833
- init_version2();
834
- PROTOCOL_MODULE_NAME = "@modelcontextprotocol/sdk/shared/protocol.js";
835
- PROTOCOL_SUPPORTED_VERSIONS = [">=1.0.0 <2"];
836
- MCPInstrumentation = class extends import_openinference_instrumentation_mcp.MCPInstrumentation {
837
- /**
838
- * Dedicated Brizz-named tracer for our SERVER + CLIENT spans.
839
- *
840
- * Why a separate tracer from the parent class's one: Arize's inherited
841
- * transport patches don't emit spans (they only inject propagation
842
- * headers), so using our own tracer here keeps Brizz spans attributed to
843
- * `@brizz/sdk/mcp` in the dashboard. The parent's `tracer` is a
844
- * `protected get` (no setter), so fighting it with assignment is the
845
- * wrong tool.
846
- */
847
- brizzTracer;
848
- constructor(_config) {
849
- super({ instrumentationConfig: _config?.instrumentationConfig });
850
- this.brizzTracer = import_api7.trace.getTracer(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION);
851
- }
852
- /**
853
- * Extend `super.init()` with our protocol-layer module definition.
854
- *
855
- * Arize's `init()` returns definitions for the six transport modules
856
- * (SSE client/server, stdio client/server, streamable-HTTP client/server)
857
- * whose `send`/`start` methods get patched for W3C trace-context
858
- * injection. We append one more: `@modelcontextprotocol/sdk/shared/protocol.js`
859
- * where our patches open SERVER/CLIENT spans around the handler + outgoing
860
- * request. If `super.init()` throws (unlikely but possible across Arize
861
- * versions), we gracefully degrade to protocol-only instrumentation.
862
- *
863
- * The cast at the end satisfies the parent's strongly-typed generic
864
- * without leaking the cast into call sites.
865
- */
866
- init() {
867
- let base;
868
- try {
869
- base = super.init() ?? [];
870
- } catch (error) {
871
- logger.warn(
872
- `Brizz MCP: base Arize init() failed \u2014 transport context propagation disabled: ${String(error)}`
873
- );
874
- base = [];
875
- }
876
- const baseArr = Array.isArray(base) ? base : [base];
877
- const brizzDef = new import_instrumentation.InstrumentationNodeModuleDefinition(
878
- PROTOCOL_MODULE_NAME,
879
- PROTOCOL_SUPPORTED_VERSIONS,
880
- (module2) => {
881
- this.patchProtocolModule(module2);
882
- return module2;
883
- },
884
- (module2) => {
885
- this.unpatchProtocolModule(module2);
886
- return module2;
887
- }
888
- );
889
- return [...baseArr, brizzDef];
890
- }
891
- /**
892
- * Manually instrument MCP modules for Next.js/Webpack where the
893
- * auto-instrumentation module-load hook doesn't fire.
894
- *
895
- * Forwards the six transport module fields to the inherited Arize
896
- * `manuallyInstrument(...)` (context propagation) and applies our
897
- * protocol patch if `protocolModule` is provided (SERVER/CLIENT spans).
898
- * Both legs are try/catch-guarded — a failure in one shouldn't prevent
899
- * the other from taking effect.
900
- */
901
- manuallyInstrument(modules) {
902
- const {
903
- clientSSEModule,
904
- serverSSEModule,
905
- clientStdioModule,
906
- serverStdioModule,
907
- clientStreamableHTTPModule,
908
- serverStreamableHTTPModule,
909
- protocolModule
910
- } = modules;
911
- try {
912
- super.manuallyInstrument({
913
- clientSSEModule,
914
- serverSSEModule,
915
- clientStdioModule,
916
- serverStdioModule,
917
- clientStreamableHTTPModule,
918
- serverStreamableHTTPModule
919
- });
920
- } catch (error) {
921
- logger.warn(`Brizz MCP: Arize manuallyInstrument(...) failed: ${String(error)}`);
922
- }
923
- if (protocolModule) {
924
- try {
925
- this.patchProtocolModule(protocolModule);
926
- } catch (error) {
927
- logger.warn(
928
- `Brizz MCP: failed to manually patch Protocol module: ${String(error)}`
929
- );
930
- }
931
- }
932
- }
933
- /**
934
- * Apply the SERVER + CLIENT patch to a loaded `protocol.js` module. Shared
935
- * by both the automatic module-load callback in `init()` and the manual
936
- * `manuallyInstrument(...)` path above so there's exactly one place that
937
- * calls `patchProtocolPrototype`.
938
- */
939
- patchProtocolModule(module2) {
940
- const proto = module2?.Protocol?.prototype;
941
- if (!proto) {
942
- logger.debug(
943
- "Brizz MCP: module does not expose Protocol.prototype \u2014 skipping protocol patches"
944
- );
945
- return;
946
- }
947
- const ok = patchProtocolPrototype(proto, this.brizzTracer);
948
- if (ok) {
949
- logger.debug("Brizz MCP: patched Protocol.prototype for SERVER+CLIENT spans");
950
- }
951
- }
952
- /**
953
- * Unpatch is intentionally a no-op.
954
- *
955
- * `patchProtocolPrototype` wraps methods in place and sets a PATCHED_FLAG
956
- * Symbol on the prototype to prevent double-patching. Restoring the
957
- * originals would require us to hold references across module unloads,
958
- * which isn't a pattern we need — instrumentation rarely gets torn down
959
- * at runtime, and a process reload is the canonical way to detach.
960
- */
961
- unpatchProtocolModule(_module) {
962
- logger.debug(
963
- "Brizz MCP: unpatch is a no-op \u2014 reload the process to cleanly detach"
964
- );
965
- }
966
- };
967
- }
968
- });
969
14
 
970
- // src/internal/instrumentation/mcp/index.ts
971
- var mcp_exports = {};
972
- __export(mcp_exports, {
973
- MCPInstrumentation: () => MCPInstrumentation,
974
- isMCPInstrumentation: () => isMCPInstrumentation
975
- });
976
- var init_mcp = __esm({
977
- "src/internal/instrumentation/mcp/index.ts"() {
978
- "use strict";
979
- init_instrumentation();
980
- }
981
- });
982
15
 
983
- // src/internal/instrumentation/vercel-ai/interrupt.ts
984
- var interrupt_exports = {};
985
- __export(interrupt_exports, {
986
- InterruptPropagator: () => InterruptPropagator,
987
- _resetInterruptState: () => _resetInterruptState,
988
- createInterruptIntegration: () => createInterruptIntegration
989
- });
990
- function isInnerLLMSpan(span) {
991
- if (INNER_OPERATION_IDS.has(span.name)) {
992
- return true;
993
- }
994
- const opId = span.attributes["ai.operationId"];
995
- return typeof opId === "string" && INNER_OPERATION_IDS.has(opId);
996
- }
997
- function setPending(parentSpanId, value) {
998
- pendingByParentSpanId.set(parentSpanId, value);
999
- while (pendingByParentSpanId.size > MAX_PENDING_ENTRIES) {
1000
- const oldest = pendingByParentSpanId.keys().next().value;
1001
- if (oldest === void 0) {
1002
- break;
1003
- }
1004
- pendingByParentSpanId.delete(oldest);
1005
- }
1006
- }
1007
- function extractInterruptTools(tools) {
1008
- if (!tools || typeof tools !== "object") {
1009
- return [];
1010
- }
1011
- return Object.entries(tools).filter(
1012
- ([, t]) => !!t && typeof t === "object" && t.needsApproval
1013
- ).map(([name]) => name);
1014
- }
1015
- function createInterruptIntegration() {
1016
- const onStepStart = (event) => {
1017
- const names = extractInterruptTools(event.tools);
1018
- if (names.length === 0) {
1019
- return;
1020
- }
1021
- const value = JSON.stringify(names);
1022
- const span = import_api8.trace.getActiveSpan();
1023
- if (!span) {
1024
- return;
1025
- }
1026
- span.setAttribute(INTERRUPT_TOOLS, value);
1027
- setPending(span.spanContext().spanId, value);
1028
- };
1029
- return {
1030
- onStepStart
1031
- };
1032
- }
1033
- function _resetInterruptState() {
1034
- if (process.env["NODE_ENV"] !== "test") {
1035
- return;
1036
- }
1037
- pendingByParentSpanId.clear();
1038
- }
1039
- var import_api8, INNER_OPERATION_IDS, MAX_PENDING_ENTRIES, pendingByParentSpanId, InterruptPropagator;
1040
- var init_interrupt = __esm({
1041
- "src/internal/instrumentation/vercel-ai/interrupt.ts"() {
1042
- "use strict";
1043
- import_api8 = require("@opentelemetry/api");
1044
- init_semantic_conventions2();
1045
- INNER_OPERATION_IDS = /* @__PURE__ */ new Set([
1046
- "ai.generateText.doGenerate",
1047
- "ai.streamText.doStream"
1048
- ]);
1049
- MAX_PENDING_ENTRIES = 1024;
1050
- pendingByParentSpanId = /* @__PURE__ */ new Map();
1051
- InterruptPropagator = class {
1052
- onStart(span, _parentContext) {
1053
- if (!isInnerLLMSpan(span)) {
1054
- return;
1055
- }
1056
- const parentSpanId = span.parentSpanContext?.spanId;
1057
- if (!parentSpanId) {
1058
- return;
1059
- }
1060
- const value = pendingByParentSpanId.get(parentSpanId);
1061
- if (!value) {
1062
- return;
1063
- }
1064
- span.setAttribute(INTERRUPT_TOOLS, value);
1065
- pendingByParentSpanId.delete(parentSpanId);
1066
- }
1067
- onEnd() {
1068
- }
1069
- async shutdown() {
1070
- }
1071
- async forceFlush() {
1072
- }
1073
- };
1074
- }
1075
- });
1076
16
 
1077
- // src/index.ts
1078
- var src_exports = {};
1079
- __export(src_exports, {
1080
- Brizz: () => Brizz,
1081
- DEFAULT_PII_PATTERNS: () => DEFAULT_PII_PATTERNS,
1082
- LogLevel: () => LogLevel,
1083
- Session: () => Session,
1084
- SessionTitle: () => SessionTitle,
1085
- SeverityNumber: () => import_api_logs2.SeverityNumber,
1086
- addExternalLink: () => addExternalLink,
1087
- callWithMute: () => callWithMute,
1088
- callWithProperties: () => callWithProperties,
1089
- callWithSessionId: () => callWithSessionId,
1090
- detectRuntime: () => detectRuntime,
1091
- emitEvent: () => emitEvent,
1092
- emitEventWithSessionId: () => emitEventWithSessionId,
1093
- getActiveSession: () => getActiveSession,
1094
- getLogLevel: () => getLogLevel,
1095
- getMetricsExporter: () => getMetricsExporter,
1096
- getMetricsReader: () => getMetricsReader,
1097
- getSpanExporter: () => getSpanExporter,
1098
- getSpanProcessor: () => getSpanProcessor,
1099
- init: () => init_exports,
1100
- logger: () => logger,
1101
- maskAttributes: () => maskAttributes,
1102
- maskValue: () => maskValue,
1103
- setCurrentSpanCustomProperties: () => setCurrentSpanCustomProperties,
1104
- setLogLevel: () => setLogLevel,
1105
- startSession: () => startSession,
1106
- startSessionTitle: () => startSessionTitle,
1107
- withMute: () => withMute,
1108
- withProperties: () => withProperties,
1109
- withSessionId: () => withSessionId
1110
- });
1111
- module.exports = __toCommonJS(src_exports);
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+ var _chunkNUTJMVD4cjs = require('./chunk-NUTJMVD4.cjs');
27
+
28
+
29
+
30
+
31
+
32
+ var _chunkJB6MA2RVcjs = require('./chunk-JB6MA2RV.cjs');
33
+ require('./chunk-LTXMCGVQ.cjs');
34
+ require('./chunk-GCORRK6B.cjs');
1112
35
 
1113
36
  // src/internal/instrumentation/auto-init.ts
1114
- var import_auto_instrumentations_node = require("@opentelemetry/auto-instrumentations-node");
1115
- var import_instrumentation3 = require("@opentelemetry/instrumentation");
1116
- var import_instrumentation_anthropic = require("@traceloop/instrumentation-anthropic");
1117
- var import_instrumentation_bedrock = require("@traceloop/instrumentation-bedrock");
1118
- var import_instrumentation_chromadb = require("@traceloop/instrumentation-chromadb");
1119
- var import_instrumentation_cohere = require("@traceloop/instrumentation-cohere");
1120
- var import_instrumentation_llamaindex = require("@traceloop/instrumentation-llamaindex");
1121
- var import_instrumentation_openai = require("@traceloop/instrumentation-openai");
1122
- var import_instrumentation_pinecone = require("@traceloop/instrumentation-pinecone");
1123
- var import_instrumentation_qdrant = require("@traceloop/instrumentation-qdrant");
1124
- var import_instrumentation_together = require("@traceloop/instrumentation-together");
1125
- var import_instrumentation_vertexai = require("@traceloop/instrumentation-vertexai");
1126
- init_logger();
1127
- var autoInstrumentationsLoaded = false;
37
+ var _instrumentation = require('@opentelemetry/instrumentation');
38
+ var _instrumentationanthropic = require('@traceloop/instrumentation-anthropic');
39
+ var _instrumentationbedrock = require('@traceloop/instrumentation-bedrock');
40
+ var _instrumentationchromadb = require('@traceloop/instrumentation-chromadb');
41
+ var _instrumentationcohere = require('@traceloop/instrumentation-cohere');
42
+ var _instrumentationllamaindex = require('@traceloop/instrumentation-llamaindex');
43
+ var _instrumentationopenai = require('@traceloop/instrumentation-openai');
44
+ var _instrumentationpinecone = require('@traceloop/instrumentation-pinecone');
45
+ var _instrumentationqdrant = require('@traceloop/instrumentation-qdrant');
46
+ var _instrumentationtogether = require('@traceloop/instrumentation-together');
1128
47
  var exceptionLogger = (error) => {
1129
- logger.error(`Exception in instrumentation: ${String(error)}`);
48
+ _chunkJB6MA2RVcjs.logger.error(`Exception in instrumentation: ${String(error)}`);
1130
49
  };
1131
- function loadNodeAutoInstrumentations() {
1132
- try {
1133
- const nodeInstrumentations = (0, import_auto_instrumentations_node.getNodeAutoInstrumentations)({
1134
- // Disabled because @traceloop/instrumentation-openai wraps the same OpenAI
1135
- // prototype with richer span attributes (gen_ai.input.messages /
1136
- // gen_ai.output.messages). Leaving both enabled lets the official one win
1137
- // and route content to log events instead of span attributes, leaving the
1138
- // Brizz backend parser with no payload to read.
1139
- "@opentelemetry/instrumentation-openai": { enabled: false }
1140
- });
1141
- (0, import_instrumentation3.registerInstrumentations)({ instrumentations: nodeInstrumentations });
1142
- return nodeInstrumentations;
1143
- } catch (error) {
1144
- logger.error(`Failed to load Node.js auto-instrumentations: ${String(error)}`);
1145
- return [];
1146
- }
1147
- }
1148
50
  function loadGenAIInstrumentations() {
1149
51
  const instrumentations = [];
1150
52
  const genAIInstrumentationClasses = [
1151
- { class: import_instrumentation_openai.OpenAIInstrumentation, name: "OpenAI" },
1152
- { class: import_instrumentation_anthropic.AnthropicInstrumentation, name: "Anthropic" },
1153
- { class: import_instrumentation_cohere.CohereInstrumentation, name: "Cohere" },
1154
- { class: import_instrumentation_vertexai.VertexAIInstrumentation, name: "Vertex AI" },
1155
- { class: import_instrumentation_bedrock.BedrockInstrumentation, name: "Bedrock" },
1156
- { class: import_instrumentation_pinecone.PineconeInstrumentation, name: "Pinecone" },
1157
- { class: import_instrumentation_llamaindex.LlamaIndexInstrumentation, name: "LlamaIndex" },
1158
- { class: import_instrumentation_chromadb.ChromaDBInstrumentation, name: "ChromaDB" },
1159
- { class: import_instrumentation_qdrant.QdrantInstrumentation, name: "Qdrant" },
1160
- { class: import_instrumentation_together.TogetherInstrumentation, name: "Together" }
53
+ { class: _instrumentationopenai.OpenAIInstrumentation, name: "OpenAI" },
54
+ { class: _instrumentationanthropic.AnthropicInstrumentation, name: "Anthropic" },
55
+ { class: _instrumentationcohere.CohereInstrumentation, name: "Cohere" },
56
+ { class: _instrumentationbedrock.BedrockInstrumentation, name: "Bedrock" },
57
+ { class: _instrumentationpinecone.PineconeInstrumentation, name: "Pinecone" },
58
+ { class: _instrumentationllamaindex.LlamaIndexInstrumentation, name: "LlamaIndex" },
59
+ { class: _instrumentationchromadb.ChromaDBInstrumentation, name: "ChromaDB" },
60
+ { class: _instrumentationqdrant.QdrantInstrumentation, name: "Qdrant" },
61
+ { class: _instrumentationtogether.TogetherInstrumentation, name: "Together" }
1161
62
  ];
1162
63
  for (const config of genAIInstrumentationClasses) {
1163
64
  try {
1164
65
  const instrumentation = new config.class({ exceptionLogger });
1165
66
  instrumentations.push(instrumentation);
1166
- logger.debug(`Auto-loaded ${config.name} instrumentation`);
67
+ _chunkJB6MA2RVcjs.logger.debug(`Auto-loaded ${config.name} instrumentation`);
1167
68
  } catch (error) {
1168
- logger.error(`Failed to auto-load ${config.name} instrumentation: ${String(error)}`);
69
+ _chunkJB6MA2RVcjs.logger.error(`Failed to auto-load ${config.name} instrumentation: ${String(error)}`);
1169
70
  }
1170
71
  }
1171
72
  try {
1172
- (0, import_instrumentation3.registerInstrumentations)({ instrumentations });
1173
- logger.info(`Auto-registered ${instrumentations.length} GenAI instrumentations`);
73
+ _instrumentation.registerInstrumentations.call(void 0, { instrumentations });
74
+ _chunkJB6MA2RVcjs.logger.info(`Auto-registered ${instrumentations.length} GenAI instrumentations`);
1174
75
  } catch (error) {
1175
- logger.error(`Failed to register GenAI instrumentations: ${String(error)}`);
76
+ _chunkJB6MA2RVcjs.logger.error(`Failed to register GenAI instrumentations: ${String(error)}`);
1176
77
  }
1177
78
  return instrumentations;
1178
79
  }
1179
80
  function loadMCPInstrumentation() {
1180
81
  void (async () => {
1181
82
  try {
1182
- const { MCPInstrumentation: MCPInstrumentation2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
1183
- const mcp = new MCPInstrumentation2({ exceptionLogger });
1184
- (0, import_instrumentation3.registerInstrumentations)({ instrumentations: [mcp] });
1185
- logger.debug("Auto-loaded MCP instrumentation");
83
+ const { MCPInstrumentation } = await Promise.resolve().then(() => _interopRequireWildcard(require("./mcp-6BDG4SWY.cjs")));
84
+ const mcp = new MCPInstrumentation({ exceptionLogger });
85
+ _instrumentation.registerInstrumentations.call(void 0, { instrumentations: [mcp] });
86
+ _chunkJB6MA2RVcjs.logger.debug("Auto-loaded MCP instrumentation");
1186
87
  } catch (error) {
1187
- logger.debug(
88
+ _chunkJB6MA2RVcjs.logger.debug(
1188
89
  `MCP instrumentation not loaded (install @modelcontextprotocol/sdk and @arizeai/openinference-instrumentation-mcp if you want MCP support): ${String(error)}`
1189
90
  );
1190
91
  }
1191
92
  })();
1192
93
  }
94
+ function loadVertexAIInstrumentation() {
95
+ void (async () => {
96
+ try {
97
+ const { VertexAIInstrumentation } = await Promise.resolve().then(() => _interopRequireWildcard(require("@traceloop/instrumentation-vertexai")));
98
+ const vertexAI = new VertexAIInstrumentation({ exceptionLogger });
99
+ _instrumentation.registerInstrumentations.call(void 0, { instrumentations: [vertexAI] });
100
+ _chunkJB6MA2RVcjs.logger.debug("Auto-loaded Vertex AI instrumentation");
101
+ } catch (error) {
102
+ _chunkJB6MA2RVcjs.logger.debug(
103
+ `Vertex AI instrumentation not loaded (install @traceloop/instrumentation-vertexai if you want Vertex AI support): ${String(error)}`
104
+ );
105
+ }
106
+ })();
107
+ }
1193
108
  function loadVercelAIInterruptIntegration() {
1194
109
  void (async () => {
1195
110
  try {
1196
- const ai = await import("ai");
111
+ const ai = await Promise.resolve().then(() => _interopRequireWildcard(require("ai")));
1197
112
  if (typeof ai.registerTelemetryIntegration !== "function") {
1198
- logger.debug(
113
+ _chunkJB6MA2RVcjs.logger.debug(
1199
114
  "AI SDK present but lacks registerTelemetryIntegration (needs ai@>=6); skipping interrupt bridge"
1200
115
  );
1201
116
  return;
1202
117
  }
1203
- const { createInterruptIntegration: createInterruptIntegration2 } = await Promise.resolve().then(() => (init_interrupt(), interrupt_exports));
1204
- ai.registerTelemetryIntegration(createInterruptIntegration2());
1205
- logger.debug("Auto-loaded Vercel AI interrupt bridge");
118
+ const { createInterruptIntegration } = await Promise.resolve().then(() => _interopRequireWildcard(require("./interrupt-HOP3XPQF.cjs")));
119
+ ai.registerTelemetryIntegration(createInterruptIntegration());
120
+ _chunkJB6MA2RVcjs.logger.debug("Auto-loaded Vercel AI interrupt bridge");
1206
121
  } catch (error) {
1207
- logger.debug(
122
+ _chunkJB6MA2RVcjs.logger.debug(
1208
123
  `Vercel AI interrupt bridge not loaded (install ai@>=6 if you want HITL attribution): ${String(error)}`
1209
124
  );
1210
125
  }
1211
126
  })();
1212
127
  }
1213
128
  function autoInitializeInstrumentations() {
1214
- if (autoInstrumentationsLoaded) {
1215
- return;
1216
- }
1217
129
  try {
1218
- const nodeInstrumentations = loadNodeAutoInstrumentations();
1219
130
  const genAIInstrumentations = loadGenAIInstrumentations();
1220
131
  loadMCPInstrumentation();
132
+ loadVertexAIInstrumentation();
1221
133
  loadVercelAIInterruptIntegration();
1222
- autoInstrumentationsLoaded = true;
1223
- logger.info(
1224
- `Auto-initialization complete: ${nodeInstrumentations.length} node + ${genAIInstrumentations.length} GenAI instrumentations`
134
+ _chunkJB6MA2RVcjs.logger.info(
135
+ `Auto-initialization complete: ${genAIInstrumentations.length} GenAI instrumentations`
1225
136
  );
137
+ return true;
1226
138
  } catch (error) {
1227
- logger.error(`Auto-initialization failed: ${String(error)}`);
1228
- autoInstrumentationsLoaded = false;
139
+ _chunkJB6MA2RVcjs.logger.error(`Auto-initialization failed: ${String(error)}`);
140
+ return false;
1229
141
  }
1230
142
  }
1231
- autoInitializeInstrumentations();
143
+ var autoInstrumentationsLoaded = autoInitializeInstrumentations();
1232
144
 
1233
- // src/internal/sdk.ts
1234
- var import_resources3 = require("@opentelemetry/resources");
1235
- var import_sdk_node = require("@opentelemetry/sdk-node");
145
+ // src/index.ts
146
+ var _apilogs = require('@opentelemetry/api-logs');
1236
147
 
1237
- // src/internal/dsn.ts
1238
- var PLACEHOLDER_SERVICE = "<service-name>";
1239
- var SERVICE_NAME_HEADER = "X-Brizz-Service-Name";
1240
- function parseDSN(dsn) {
1241
- let parsed;
1242
- try {
1243
- parsed = new globalThis.URL(dsn);
1244
- } catch {
1245
- return null;
1246
- }
1247
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || !parsed.username || !parsed.host) {
1248
- return null;
1249
- }
1250
- const scheme = parsed.protocol === "https:" ? "https" : "http";
1251
- let service;
1252
- try {
1253
- service = decodeURIComponent(parsed.pathname.replace(/^\//, ""));
1254
- } catch {
1255
- return null;
1256
- }
1257
- if (service === "" || service === PLACEHOLDER_SERVICE) {
1258
- return null;
1259
- }
1260
- return {
1261
- scheme,
1262
- host: parsed.host,
1263
- bearer: decodeURIComponent(parsed.username),
1264
- service,
1265
- baseUrl: `${scheme}://${parsed.host}`
1266
- };
1267
- }
148
+ // src/init.ts
149
+ var init_exports = {};
1268
150
 
1269
- // src/internal/config.ts
1270
- init_logger();
1271
- function resolveConfig(options) {
1272
- const envLogLevel = process.env["BRIZZ_LOG_LEVEL"] || options.logLevel?.toString() || DEFAULT_LOG_LEVEL.toString();
1273
- let resolvedLogLevel;
1274
- if (envLogLevel) {
1275
- resolvedLogLevel = parseLogLevel(envLogLevel);
1276
- } else if (typeof options.logLevel === "string") {
1277
- resolvedLogLevel = parseLogLevel(options.logLevel);
1278
- } else {
1279
- resolvedLogLevel = options.logLevel || DEFAULT_LOG_LEVEL;
1280
- }
1281
- setLogLevel(resolvedLogLevel);
1282
- let maskingStatus;
1283
- if (options.masking === true) {
1284
- maskingStatus = "enabled";
1285
- } else if (options.masking === false) {
1286
- maskingStatus = "disabled";
1287
- } else if (typeof options.masking === "object") {
1288
- maskingStatus = "custom";
1289
- } else {
1290
- maskingStatus = "default-disabled";
1291
- }
1292
- logger.debug("Starting configuration resolution", {
1293
- appName: options.appName,
1294
- baseUrl: options.baseUrl,
1295
- hasApiKey: !!options.apiKey,
1296
- dsnProvided: !!(process.env["BRIZZ_DSN"] || options.dsn),
1297
- disableBatch: options.disableBatch,
1298
- logLevel: resolvedLogLevel,
1299
- headersCount: Object.keys(options.headers || {}).length,
1300
- masking: maskingStatus
1301
- });
1302
- let resolvedMasking;
1303
- if (options.masking === true) {
1304
- resolvedMasking = {
1305
- spanMasking: {},
1306
- eventMasking: {}
1307
- };
1308
- } else if (options.masking && typeof options.masking === "object") {
1309
- resolvedMasking = options.masking;
1310
- }
1311
- const resolvedConfig = {
1312
- ...options,
1313
- appName: process.env["BRIZZ_APP_NAME"] || options.appName || "unknown-app",
1314
- appVersion: process.env["BRIZZ_APP_VERSION"] || options.appVersion,
1315
- baseUrl: process.env["BRIZZ_BASE_URL"] || options.baseUrl || "https://telemetry.brizz.dev",
1316
- headers: { ...options.headers },
1317
- apiKey: process.env["BRIZZ_API_KEY"] || options.apiKey,
1318
- disableBatch: process.env["BRIZZ_DISABLE_BATCH"] === "true" || !!options.disableBatch,
1319
- disableSpanExporter: process.env["BRIZZ_DISABLE_SPAN_EXPORTER"] === "true" || !!options.disableSpanExporter,
1320
- environment: process.env["BRIZZ_ENVIRONMENT"] || options.environment,
1321
- logLevel: resolvedLogLevel,
1322
- masking: resolvedMasking
1323
- };
1324
- const dsnInput = process.env["BRIZZ_DSN"] || options.dsn;
1325
- let parsedDSN = null;
1326
- if (dsnInput) {
1327
- const kwargConflicts = [];
1328
- if (options.apiKey !== void 0) {
1329
- kwargConflicts.push("apiKey");
1330
- }
1331
- if (options.baseUrl !== void 0) {
1332
- kwargConflicts.push("baseUrl");
1333
- }
1334
- if (options.appName !== void 0) {
1335
- kwargConflicts.push("appName");
1336
- }
1337
- if (kwargConflicts.length > 0) {
1338
- throw new Error(
1339
- `dsn cannot be combined with kwargs ${kwargConflicts.join(", ")}. The DSN bundles bearer, gateway URL, and service name \u2014 choose one configuration style.`
1340
- );
1341
- }
1342
- const envConflicts = ["BRIZZ_API_KEY", "BRIZZ_BASE_URL", "BRIZZ_APP_NAME"].filter(
1343
- (name) => process.env[name] !== void 0
1344
- );
1345
- if (envConflicts.length > 0) {
1346
- logger.warn(
1347
- `Ignoring ${envConflicts.join(", ")} \u2014 dsn / BRIZZ_DSN takes precedence.`
1348
- );
1349
- }
1350
- resolvedConfig.apiKey = void 0;
1351
- resolvedConfig.baseUrl = "https://telemetry.brizz.dev";
1352
- resolvedConfig.appName = "unknown-app";
1353
- parsedDSN = parseDSN(dsnInput);
1354
- if (parsedDSN) {
1355
- resolvedConfig.appName = parsedDSN.service;
1356
- resolvedConfig.baseUrl = parsedDSN.baseUrl;
1357
- resolvedConfig.apiKey = parsedDSN.bearer;
1358
- }
1359
- } else if (resolvedConfig.apiKey) {
1360
- resolvedConfig.headers["Authorization"] = `Bearer ${resolvedConfig.apiKey}`;
1361
- }
1362
- if (process.env["BRIZZ_HEADERS"]) {
1363
- try {
1364
- const envHeaders = JSON.parse(process.env["BRIZZ_HEADERS"]);
1365
- Object.assign(resolvedConfig.headers, envHeaders);
1366
- logger.debug("Added headers from environment variable", {
1367
- headers: Object.keys(envHeaders)
1368
- });
1369
- } catch (error) {
1370
- logger.error("Failed to parse BRIZZ_HEADERS environment variable", { error });
1371
- throw new Error("Invalid JSON in BRIZZ_HEADERS environment variable", { cause: error });
1372
- }
1373
- }
1374
- if (dsnInput) {
1375
- const authHeaderKeys = /* @__PURE__ */ new Set(["authorization", SERVICE_NAME_HEADER.toLowerCase()]);
1376
- resolvedConfig.headers = Object.fromEntries(
1377
- Object.entries(resolvedConfig.headers).filter(
1378
- ([key]) => !authHeaderKeys.has(key.toLowerCase())
1379
- )
1380
- );
1381
- if (parsedDSN) {
1382
- resolvedConfig.headers["Authorization"] = `Bearer ${parsedDSN.bearer}`;
1383
- resolvedConfig.headers[SERVICE_NAME_HEADER] = parsedDSN.service;
1384
- }
1385
- }
1386
- logger.debug("Configuration resolved with environment variables", {
1387
- appName: resolvedConfig.appName,
1388
- baseUrl: resolvedConfig.baseUrl,
1389
- hasApiKey: !!resolvedConfig.apiKey,
1390
- dsnProvided: !!dsnInput,
1391
- disableBatch: resolvedConfig.disableBatch,
1392
- envOverrides: {
1393
- hasEnvApiKey: !!process.env["BRIZZ_API_KEY"],
1394
- hasEnvBaseUrl: !!process.env["BRIZZ_BASE_URL"],
1395
- hasEnvDsn: !!process.env["BRIZZ_DSN"],
1396
- hasEnvBatch: !!process.env["BRIZZ_DISABLE_BATCH"],
1397
- hasEnvHeaders: !!process.env["BRIZZ_HEADERS"]
1398
- }
1399
- });
1400
- return resolvedConfig;
1401
- }
1402
151
 
1403
- // src/internal/constants.ts
1404
- var BRIZZ_SDK_VERSION = "brizz.sdk.version";
1405
- var BRIZZ_SDK_LANGUAGE = "brizz.sdk.language";
1406
- var SDK_LANGUAGE = "typescript";
1407
152
 
1408
- // src/internal/instrumentation/registry.ts
1409
- var import_instrumentation_anthropic2 = require("@traceloop/instrumentation-anthropic");
1410
- var import_instrumentation_bedrock2 = require("@traceloop/instrumentation-bedrock");
1411
- var import_instrumentation_chromadb2 = require("@traceloop/instrumentation-chromadb");
1412
- var import_instrumentation_cohere2 = require("@traceloop/instrumentation-cohere");
1413
- var import_instrumentation_llamaindex2 = require("@traceloop/instrumentation-llamaindex");
1414
- var import_instrumentation_openai2 = require("@traceloop/instrumentation-openai");
1415
- var import_instrumentation_pinecone2 = require("@traceloop/instrumentation-pinecone");
1416
- var import_instrumentation_qdrant2 = require("@traceloop/instrumentation-qdrant");
1417
- var import_instrumentation_together2 = require("@traceloop/instrumentation-together");
1418
- var import_instrumentation_vertexai2 = require("@traceloop/instrumentation-vertexai");
1419
- init_logger();
1420
- init_mcp();
1421
- var InstrumentationRegistry = class _InstrumentationRegistry {
1422
- static instance;
1423
- manualModules = null;
1424
- static getInstance() {
1425
- if (!_InstrumentationRegistry.instance) {
1426
- _InstrumentationRegistry.instance = new _InstrumentationRegistry();
1427
- }
1428
- return _InstrumentationRegistry.instance;
1429
- }
1430
- /**
1431
- * Set manual instrumentation modules for Next.js/Webpack environments
1432
- */
1433
- setManualModules(modules) {
1434
- this.manualModules = modules;
1435
- logger.info("Manual instrumentation modules configured for Next.js/Webpack compatibility");
1436
- }
1437
- /**
1438
- * Helper to load instrumentation with optional manual module
1439
- */
1440
- loadInstrumentation(InstrumentationClass, name, manualModule, exceptionLogger2) {
1441
- try {
1442
- const inst = new InstrumentationClass({
1443
- exceptionLogger: exceptionLogger2 || ((error) => logger.error(`Exception in instrumentation: ${String(error)}`))
1444
- });
1445
- if (manualModule) {
1446
- inst.manuallyInstrument(manualModule);
1447
- logger.debug(`Manual instrumentation enabled for ${name}`);
1448
- }
1449
- return inst;
1450
- } catch (error) {
1451
- logger.error(`Failed to load ${name} instrumentation: ${String(error)}`);
1452
- return null;
1453
- }
1454
- }
1455
- /**
1456
- * Get manual instrumentations only.
1457
- * Auto-instrumentations are handled at import time.
1458
- */
1459
- getManualInstrumentations() {
1460
- if (!this.manualModules || Object.keys(this.manualModules).length === 0) {
1461
- logger.debug("No manual instrumentation modules configured");
1462
- return [];
1463
- }
1464
- const instrumentations = [];
1465
- const exceptionLogger2 = (error) => {
1466
- logger.error(`Exception in manual instrumentation: ${String(error)}`);
1467
- };
1468
- this.loadManualInstrumentations(instrumentations, exceptionLogger2);
1469
- logger.info(`Loaded ${instrumentations.length} manual instrumentations`);
1470
- return instrumentations;
1471
- }
1472
- /**
1473
- * Load manual instrumentations only (with modules provided by user).
1474
- * @private
1475
- */
1476
- loadManualInstrumentations(instrumentations, exceptionLogger2) {
1477
- const instrumentationConfigs = [
1478
- { class: import_instrumentation_openai2.OpenAIInstrumentation, name: "OpenAI", module: this.manualModules?.openAI },
1479
- { class: import_instrumentation_anthropic2.AnthropicInstrumentation, name: "Anthropic", module: this.manualModules?.anthropic },
1480
- { class: import_instrumentation_cohere2.CohereInstrumentation, name: "Cohere", module: this.manualModules?.cohere },
1481
- {
1482
- class: import_instrumentation_vertexai2.VertexAIInstrumentation,
1483
- name: "Vertex AI",
1484
- module: this.manualModules?.google_vertexai
1485
- },
1486
- { class: import_instrumentation_bedrock2.BedrockInstrumentation, name: "Bedrock", module: this.manualModules?.bedrock },
1487
- { class: import_instrumentation_pinecone2.PineconeInstrumentation, name: "Pinecone", module: this.manualModules?.pinecone },
1488
- {
1489
- class: import_instrumentation_llamaindex2.LlamaIndexInstrumentation,
1490
- name: "LlamaIndex",
1491
- module: this.manualModules?.llamaindex
1492
- },
1493
- { class: import_instrumentation_chromadb2.ChromaDBInstrumentation, name: "ChromaDB", module: this.manualModules?.chromadb },
1494
- { class: import_instrumentation_qdrant2.QdrantInstrumentation, name: "Qdrant", module: this.manualModules?.qdrant },
1495
- { class: import_instrumentation_together2.TogetherInstrumentation, name: "Together", module: this.manualModules?.together }
1496
- ];
1497
- for (const config of instrumentationConfigs) {
1498
- if (config.module) {
1499
- const instrumentation = this.loadInstrumentation(
1500
- config.class,
1501
- config.name,
1502
- config.module,
1503
- exceptionLogger2
1504
- );
1505
- if (instrumentation) {
1506
- instrumentations.push(instrumentation);
1507
- }
1508
- }
1509
- }
1510
- if (this.manualModules?.langchain?.callbackManagerModule) {
1511
- const callbackManagerModule = this.manualModules.langchain.callbackManagerModule;
1512
- void (async () => {
1513
- try {
1514
- const { LangChainInstrumentation } = await import("@arizeai/openinference-instrumentation-langchain");
1515
- const lcInst = new LangChainInstrumentation();
1516
- lcInst.manuallyInstrument(callbackManagerModule);
1517
- logger.debug("Manual instrumentation enabled for LangChain");
1518
- } catch (error) {
1519
- logger.error(
1520
- `Failed to load LangChain instrumentation. Ensure @langchain/core is installed: ${String(error)}`
1521
- );
1522
- }
1523
- })();
1524
- }
1525
- if (this.manualModules?.mcp) {
1526
- try {
1527
- new MCPInstrumentation({ exceptionLogger: exceptionLogger2 }).manuallyInstrument(this.manualModules.mcp);
1528
- logger.debug("Manual instrumentation enabled for MCP");
1529
- } catch (error) {
1530
- logger.error(`Failed to apply MCP instrumentation: ${String(error)}`);
1531
- }
1532
- }
1533
- }
1534
- };
1535
153
 
1536
- // src/internal/sdk.ts
1537
- init_interrupt();
1538
154
 
1539
- // src/internal/log/logging.ts
1540
- var import_api_logs = require("@opentelemetry/api-logs");
1541
- var import_exporter_logs_otlp_http = require("@opentelemetry/exporter-logs-otlp-http");
1542
- var import_resources = require("@opentelemetry/resources");
1543
- var import_sdk_logs2 = require("@opentelemetry/sdk-logs");
1544
- init_logger();
1545
155
 
1546
- // src/internal/trace/session.ts
1547
- var import_api9 = require("@opentelemetry/api");
1548
- init_logger();
1549
- init_semantic_conventions2();
1550
- function setCurrentSpanCustomProperties(properties) {
1551
- const current = import_api9.trace.getActiveSpan();
1552
- if (!current || !current.isRecording()) {
1553
- return;
1554
- }
1555
- for (const [key, value] of Object.entries(properties)) {
1556
- try {
1557
- current.setAttribute(`${BRIZZ}.${key}`, value);
1558
- } catch {
1559
- }
1560
- }
1561
- }
1562
- function callWithProperties(properties, fn, thisArg, ...args) {
1563
- const base = import_api9.context.active();
1564
- const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
1565
- const merged = prev ? { ...prev, ...properties } : properties;
1566
- const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);
1567
- return import_api9.context.with(next, fn, thisArg, ...args);
1568
- }
1569
- function withProperties(properties, fn, thisArg) {
1570
- return function wrapped(...args) {
1571
- return callWithProperties(
1572
- properties,
1573
- fn,
1574
- thisArg !== void 0 ? thisArg : this,
1575
- ...args
1576
- );
1577
- };
1578
- }
1579
- function muteProperties(options) {
1580
- const { input = true, output = true } = options;
1581
- const properties = {};
1582
- if (input) {
1583
- properties[MUTE_INPUT] = "true";
1584
- }
1585
- if (output) {
1586
- properties[MUTE_OUTPUT] = "true";
1587
- }
1588
- return properties;
1589
- }
1590
- function callWithMute(options, fn, thisArg, ...args) {
1591
- return callWithProperties(muteProperties(options), fn, thisArg, ...args);
1592
- }
1593
- function withMute(options, fn, thisArg) {
1594
- return withProperties(muteProperties(options), fn, thisArg);
1595
- }
1596
- function withSessionId(sessionId, fn, thisArg, extraProperties) {
1597
- const properties = { [SESSION_ID]: sessionId, ...extraProperties };
1598
- return withProperties(properties, fn, thisArg);
1599
- }
1600
- function callWithSessionId(sessionId, fn, thisArg, ...args) {
1601
- return callWithProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);
1602
- }
1603
- var Session = class {
1604
- sessionId;
1605
- span;
1606
- inputs = [];
1607
- outputs = [];
1608
- inputContexts = [];
1609
- outputContexts = [];
1610
- constructor(sessionId, span) {
1611
- this.sessionId = sessionId;
1612
- this.span = span;
1613
- }
1614
- /**
1615
- * Append a user turn to session input tracking.
1616
- *
1617
- * Each call appends one element to `brizz.session.input` (the text) AND one
1618
- * element to `brizz.session.input.context` (the per-turn context bag). The
1619
- * two arrays stay index-aligned — the ingestion pipeline zips them together
1620
- * so the i-th context bag lands on the i-th user_display conversation item's
1621
- * `span_attributes` map.
1622
- *
1623
- * @param text - Text to append (null becomes a null/"hide marker")
1624
- * @param context - Optional per-turn context bag to attach to this turn
1625
- */
1626
- setInput(text, context6) {
1627
- this.inputs.push(text);
1628
- this.inputContexts.push(context6 ?? {});
1629
- this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));
1630
- this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));
1631
- }
1632
- /**
1633
- * Append an assistant turn to session output tracking.
1634
- *
1635
- * Symmetric to {@link setInput} — appends one text element and one
1636
- * context-bag element to the index-aligned `brizz.session.output` /
1637
- * `brizz.session.output.context` arrays.
1638
- *
1639
- * @param text - Text to append (null becomes a null/"hide marker")
1640
- * @param context - Optional per-turn context bag to attach to this turn
1641
- */
1642
- setOutput(text, context6) {
1643
- this.outputs.push(text);
1644
- this.outputContexts.push(context6 ?? {});
1645
- this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));
1646
- this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));
1647
- }
1648
- /**
1649
- * Set the session title on the span.
1650
- *
1651
- * @param title - The generated title string
1652
- */
1653
- setTitle(title) {
1654
- this.span.setAttribute(SESSION_TITLE, title);
1655
- }
1656
- /**
1657
- * Update custom properties on the session span.
1658
- * Properties are prefixed with 'brizz.'.
1659
- *
1660
- * @param properties - Key-value properties to set on the session
1661
- */
1662
- updateProperties(properties) {
1663
- for (const [key, value] of Object.entries(properties)) {
1664
- this.span.setAttribute(`${BRIZZ}.${key}`, value);
1665
- }
1666
- }
1667
- /**
1668
- * Attach an external link (URL) to this session.
1669
- *
1670
- * The link surfaces on the session's detail panel in Brizz — use it to
1671
- * correlate a session with an external record such as a Datadog trace,
1672
- * Sentry issue, or internal dashboard. Re-sending the same URL is idempotent;
1673
- * distinct URLs add separate links.
1674
- *
1675
- * @param url - The link target
1676
- * @param options - Optional `title` (defaults to the URL host) and `linkType`
1677
- * (free-form category, defaults to `'generic'`)
1678
- */
1679
- addExternalLink(url, options) {
1680
- emitExternalLink(this.sessionId, url, options?.title, options?.linkType);
1681
- }
1682
- };
1683
- var SessionTitle = class {
1684
- span;
1685
- constructor(span) {
1686
- this.span = span;
1687
- }
1688
- /**
1689
- * Set the generated title on the wrapper span.
1690
- *
1691
- * @param title - The generated title string
1692
- */
1693
- setTitle(title) {
1694
- this.span.setAttribute(SESSION_TITLE, title);
1695
- }
1696
- };
1697
- function getActiveSession() {
1698
- return import_api9.context.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
1699
- }
1700
- function resolveSessionIdFromContext() {
1701
- const active = getActiveSession();
1702
- if (active) {
1703
- return active.sessionId;
1704
- }
1705
- const props = import_api9.context.active().getValue(PROPERTIES_CONTEXT_KEY);
1706
- return props?.[SESSION_ID];
1707
- }
1708
- function emitExternalLink(sessionId, url, title, linkType) {
1709
- try {
1710
- emitEventWithSessionId(sessionId, EXTERNAL_LINK_EVENT_NAME, {
1711
- [EXTERNAL_LINK_URL]: url,
1712
- [EXTERNAL_LINK_TITLE]: title ?? "",
1713
- [EXTERNAL_LINK_TYPE]: linkType ?? "generic"
1714
- });
1715
- } catch (error) {
1716
- logger.warn("addExternalLink: failed to emit external link", error);
1717
- }
1718
- }
1719
- function addExternalLink(url, options) {
1720
- const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
1721
- if (!sessionId) {
1722
- logger.warn(
1723
- "addExternalLink called without a resolvable session id; link dropped. Pass options.sessionId or call inside a startSession/callWithSessionId scope."
1724
- );
1725
- return;
1726
- }
1727
- emitExternalLink(sessionId, url, options?.title, options?.linkType);
1728
- }
1729
- function startSession(sessionId, callback, extraProperties, options) {
1730
- const isTitle = options?.mode === "title";
1731
- const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;
1732
- const tracer = import_api9.trace.getTracer("@brizz/sdk");
1733
- return tracer.startActiveSpan(spanName, (span) => {
1734
- span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
1735
- if (extraProperties) {
1736
- for (const [key, value] of Object.entries(extraProperties)) {
1737
- span.setAttribute(`${BRIZZ}.${key}`, value);
1738
- }
1739
- }
1740
- const session = new Session(sessionId, span);
1741
- const contextProperties = { [SESSION_ID]: sessionId };
1742
- if (isTitle) {
1743
- contextProperties[SESSION_TITLE_GENERATION] = "true";
1744
- }
1745
- if (extraProperties) {
1746
- for (const [key, value] of Object.entries(extraProperties)) {
1747
- contextProperties[key] = String(value);
1748
- }
1749
- }
1750
- return callWithProperties(contextProperties, () => {
1751
- const sessionCtx = import_api9.context.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
1752
- return import_api9.context.with(sessionCtx, () => {
1753
- try {
1754
- const result = callback(session);
1755
- if (result && typeof result.then === "function") {
1756
- return result.then((value) => {
1757
- span.end();
1758
- return value;
1759
- }).catch((error) => {
1760
- span.recordException(error);
1761
- span.setStatus({ code: import_api9.SpanStatusCode.ERROR });
1762
- span.end();
1763
- throw error;
1764
- });
1765
- }
1766
- span.end();
1767
- return result;
1768
- } catch (error) {
1769
- span.recordException(error);
1770
- span.setStatus({ code: import_api9.SpanStatusCode.ERROR });
1771
- span.end();
1772
- throw error;
1773
- }
1774
- });
1775
- });
1776
- });
1777
- }
1778
- function startSessionTitle(callback, options) {
1779
- const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;
1780
- const tracer = import_api9.trace.getTracer("@brizz/sdk");
1781
- return tracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {
1782
- if (resolvedSessionId) {
1783
- span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);
1784
- }
1785
- const sessionTitle = new SessionTitle(span);
1786
- const properties = { [SESSION_TITLE_GENERATION]: "true" };
1787
- if (resolvedSessionId) {
1788
- properties[SESSION_ID] = resolvedSessionId;
1789
- }
1790
- return callWithProperties(properties, () => {
1791
- try {
1792
- const result = callback(sessionTitle);
1793
- if (result && typeof result.then === "function") {
1794
- return result.then((value) => {
1795
- span.end();
1796
- return value;
1797
- }).catch((error) => {
1798
- span.recordException(error);
1799
- span.setStatus({ code: import_api9.SpanStatusCode.ERROR });
1800
- span.end();
1801
- throw error;
1802
- });
1803
- }
1804
- span.end();
1805
- return result;
1806
- } catch (error) {
1807
- span.recordException(error);
1808
- span.setStatus({ code: import_api9.SpanStatusCode.ERROR });
1809
- span.end();
1810
- throw error;
1811
- }
1812
- });
1813
- });
1814
- }
1815
156
 
1816
- // src/internal/log/logging.ts
1817
- init_version();
1818
157
 
1819
- // src/internal/log/processors/log-processor.ts
1820
- var import_api10 = require("@opentelemetry/api");
1821
- var import_sdk_logs = require("@opentelemetry/sdk-logs");
1822
- init_logger();
1823
158
 
1824
- // src/internal/masking/patterns.ts
1825
- var DEFAULT_PII_PATTERNS = [
1826
- // Phone numbers (US format)
1827
- {
1828
- name: "us_phone_numbers",
1829
- 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]|$)`
1830
- },
1831
- // Credit card numbers
1832
- {
1833
- name: "credit_cards",
1834
- 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`
1835
- },
1836
- {
1837
- name: "credit_cards_with_separators",
1838
- 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`
1839
- },
1840
- // IP addresses (IPv4)
1841
- {
1842
- name: "ipv4_addresses",
1843
- 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`
1844
- },
1845
- // API keys/tokens
1846
- {
1847
- name: "generic_api_keys",
1848
- 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`
1849
- },
1850
- {
1851
- name: "openai_keys",
1852
- pattern: String.raw`\bsk[-_][a-zA-Z0-9]{20,}\b`
1853
- },
1854
- // AWS Keys
1855
- {
1856
- name: "aws_access_keys",
1857
- pattern: String.raw`\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b`
1858
- },
1859
- // GitHub tokens
1860
- {
1861
- name: "github_tokens",
1862
- pattern: String.raw`\bghp_[a-zA-Z0-9]{36}\b`
1863
- },
1864
- // Slack tokens
1865
- {
1866
- name: "slack_tokens",
1867
- pattern: String.raw`\bxox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24,34}\b`
1868
- },
1869
- // Stripe keys
1870
- {
1871
- name: "stripe_keys",
1872
- pattern: String.raw`\b(?:sk|pk)_(?:test|live)_[a-zA-Z0-9]{24,}\b`
1873
- },
1874
- // JWT tokens
1875
- {
1876
- name: "jwt_tokens",
1877
- pattern: String.raw`\beyJ[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\b`
1878
- },
1879
- // MAC addresses
1880
- {
1881
- name: "mac_addresses",
1882
- pattern: String.raw`\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b`
1883
- },
1884
- // IPv6 addresses
1885
- {
1886
- name: "ipv6_addresses",
1887
- pattern: String.raw`\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b`
1888
- },
1889
- // Bitcoin addresses
1890
- {
1891
- name: "bitcoin_addresses",
1892
- pattern: String.raw`\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b`
1893
- },
1894
- // Ethereum addresses
1895
- {
1896
- name: "ethereum_addresses",
1897
- pattern: String.raw`\b0x[a-fA-F0-9]{40}(?![a-fA-F0-9])\b`
1898
- },
1899
- // Database connection strings
1900
- {
1901
- name: "database_connections",
1902
- 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`
1903
- },
1904
- // Private keys
1905
- {
1906
- name: "rsa_private_keys",
1907
- pattern: "-----BEGIN (?:RSA )?PRIVATE KEY-----"
1908
- },
1909
- {
1910
- name: "pgp_private_keys",
1911
- pattern: "-----BEGIN PGP PRIVATE KEY BLOCK-----"
1912
- },
1913
- {
1914
- name: "certificates",
1915
- pattern: "-----BEGIN CERTIFICATE-----"
1916
- },
1917
- // Additional API Keys and Tokens
1918
- {
1919
- name: "google_oauth",
1920
- pattern: String.raw`\bya29\\.[a-zA-Z0-9_-]{60,}\b`
1921
- },
1922
- {
1923
- name: "firebase_tokens",
1924
- pattern: String.raw`\bAAAA[A-Za-z0-9_-]{100,}\b`
1925
- },
1926
- {
1927
- name: "google_app_ids",
1928
- pattern: String.raw`\b[0-9]+-\w+\.apps\.googleusercontent\.com\b`
1929
- },
1930
- {
1931
- name: "facebook_secrets",
1932
- 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]`
1933
- },
1934
- {
1935
- name: "github_keys",
1936
- 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]`
1937
- },
1938
- {
1939
- name: "heroku_keys",
1940
- 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\\-]`
1941
- },
1942
- {
1943
- name: "slack_api_keys",
1944
- 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]`
1945
- },
1946
- {
1947
- name: "slack_api_tokens",
1948
- pattern: String.raw`\b(xox[pb](?:-[a-zA-Z0-9]+){4,})\b`
1949
- },
1950
- // Extended Private Keys and Certificates
1951
- {
1952
- name: "dsa_private_keys",
1953
- pattern: String.raw`-----BEGIN DSA PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END DSA PRIVATE KEY-----`
1954
- },
1955
- {
1956
- name: "ec_private_keys",
1957
- pattern: String.raw`-----BEGIN (?:EC|ECDSA) PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END (?:EC|ECDSA) PRIVATE KEY-----`
1958
- },
1959
- {
1960
- name: "encrypted_private_keys",
1961
- pattern: String.raw`-----BEGIN ENCRYPTED PRIVATE KEY-----(?:.|\s)+?-----END ENCRYPTED PRIVATE KEY-----`
1962
- },
1963
- {
1964
- name: "ssl_certificates",
1965
- pattern: String.raw`-----BEGIN CERTIFICATE-----(?:.|\n)+?\s-----END CERTIFICATE-----`
1966
- },
1967
- {
1968
- name: "ssh_dss_public",
1969
- pattern: String.raw`\bssh-dss [0-9A-Za-z+/]+[=]{2}\b`
1970
- },
1971
- {
1972
- name: "ssh_rsa_public",
1973
- pattern: String.raw`\bssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3} [^@]+@[^@]+\b`
1974
- },
1975
- {
1976
- name: "putty_ssh_keys",
1977
- pattern: String.raw`PuTTY-User-Key-File-2: ssh-(?:rsa|dss)\s*Encryption: none(?:.|\s?)*?Private-MAC:`
1978
- },
1979
- // Security and Network
1980
- {
1981
- name: "cve_numbers",
1982
- pattern: String.raw`\b[Cc][Vv][Ee]-\\d{4}-\\d{4,7}\b`
1983
- },
1984
- {
1985
- name: "microsoft_oauth",
1986
- pattern: String.raw`https://login\.microsoftonline\.com/common/oauth2/v2\.0/token|https://login\.windows\.net/common/oauth2/token`
1987
- },
1988
- {
1989
- name: "postgres_connections",
1990
- pattern: String.raw`\b(?:[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Pp][Gg][Ss][Qq][Ll])\\:\\/\\/`
1991
- },
1992
- {
1993
- name: "box_links",
1994
- pattern: String.raw`https://app\.box\.com/[s|l]/\S+`
1995
- },
1996
- {
1997
- name: "dropbox_links",
1998
- pattern: String.raw`https://www\.dropbox\.com/(?:s|l)/\S+`
1999
- },
2000
- // Credit Card Variants
2001
- {
2002
- name: "amex_cards",
2003
- pattern: String.raw`\b3[47][0-9]{13}\b`
2004
- },
2005
- {
2006
- name: "visa_cards",
2007
- pattern: String.raw`\b4[0-9]{12}(?:[0-9]{3})?\b`
2008
- },
2009
- {
2010
- name: "discover_cards",
2011
- pattern: String.raw`\b65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}\b`
2012
- }
2013
- ];
2014
159
 
2015
- // src/internal/masking/utils.ts
2016
- init_logger();
2017
- function isValidPatternName(name) {
2018
- return /^[a-zA-Z0-9_]+$/.test(name);
2019
- }
2020
- function isLikelyReDoSPattern(pattern) {
2021
- const dangerousPatterns = [
2022
- // Nested quantifiers like (a+)+, (a*)+, (a+)*
2023
- /\([^)]*[+*]\)[+*]/,
2024
- // Alternation with overlapping groups like (a|a)*
2025
- /\([^)]*\|[^)]*\)[+*]/,
2026
- // Complex backtracking patterns - but more specific
2027
- /\([^)]*[+*][^)]*[+*][^)]*\)[+*]/
2028
- ];
2029
- return dangerousPatterns.some((dangerous) => dangerous.test(pattern));
2030
- }
2031
- function getGroupedPattern(patternEntry) {
2032
- let name = patternEntry.name;
2033
- if (!name || name === "") {
2034
- name = `pattern_${Math.random().toString(16).slice(2)}`;
2035
- }
2036
- if (!isValidPatternName(name)) {
2037
- throw new Error(
2038
- `Pattern name '${name}' must only contain alphanumeric characters and underscores`
2039
- );
2040
- }
2041
- if (isLikelyReDoSPattern(patternEntry.pattern)) {
2042
- throw new Error(`Potentially dangerous ReDoS pattern detected: '${patternEntry.pattern}'`);
2043
- }
2044
- try {
2045
- new RegExp(patternEntry.pattern);
2046
- } catch (error) {
2047
- throw new Error(`Invalid regex pattern '${patternEntry.pattern}': ${String(error)}`, {
2048
- cause: error
2049
- });
2050
- }
2051
- return `(?<${name}>${patternEntry.pattern})`;
2052
- }
2053
- function isIPatternEntry(obj) {
2054
- return typeof obj === "object" && obj !== null && typeof obj.pattern === "string" && (obj.name === void 0 || typeof obj.name === "string");
2055
- }
2056
- function isIEventMaskingRule(obj) {
2057
- return typeof obj === "object" && obj !== null && typeof obj.mode === "string" && Array.isArray(obj.patterns) && obj.patterns.every(
2058
- (p) => isIPatternEntry(p) || typeof p === "string"
2059
- ) && (obj.attributePattern === void 0 || typeof obj.attributePattern === "string");
2060
- }
2061
- function convertPatternsToPatternEntries(patterns) {
2062
- const patternEntries = [];
2063
- for (const pattern of patterns) {
2064
- if (typeof pattern === "string") {
2065
- patternEntries.push({ pattern, name: "" });
2066
- } else if (isIPatternEntry(pattern)) {
2067
- patternEntries.push(pattern);
2068
- } else {
2069
- throw new Error("Patterns must be either strings or PatternEntry instances");
2070
- }
2071
- }
2072
- return patternEntries;
2073
- }
2074
- function compilePatternEntries(patternEntries) {
2075
- const patternGroups = [];
2076
- for (const patternEntry of patternEntries) {
2077
- try {
2078
- patternGroups.push(getGroupedPattern(patternEntry));
2079
- } catch (error) {
2080
- logger.warn(`Invalid pattern '${patternEntry.name}': ${patternEntry.pattern}`, error);
2081
- continue;
2082
- }
2083
- }
2084
- if (patternGroups.length === 0) {
2085
- return null;
2086
- }
2087
- try {
2088
- return new RegExp(patternGroups.join("|"));
2089
- } catch (error) {
2090
- logger.warn("Failed to compile pattern entries into regex", error);
2091
- return null;
2092
- }
2093
- }
2094
- function getCompiledAttributeNamePattern(rule) {
2095
- if (!rule.attributePattern) {
2096
- logger.debug("No attribute pattern provided, using default .*");
2097
- return /.*/;
2098
- }
2099
- let compiledPatternString = rule.attributePattern;
2100
- if (isIEventMaskingRule(rule) && rule.eventNamePattern) {
2101
- compiledPatternString = `(${compiledPatternString})|(${rule.eventNamePattern})`;
2102
- }
2103
- return new RegExp(compiledPatternString);
2104
- }
2105
- function shouldContinueExecution(startTime, iterations, timeoutMs) {
2106
- if (Date.now() - startTime > timeoutMs) {
2107
- logger.warn("Regex execution timed out - potential ReDoS pattern detected");
2108
- return false;
2109
- }
2110
- const maxIterations = 1e3;
2111
- if (iterations > maxIterations) {
2112
- logger.warn("Regex execution exceeded maximum iterations - potential ReDoS pattern detected");
2113
- return false;
2114
- }
2115
- return true;
2116
- }
2117
- function createGlobalPattern(pattern) {
2118
- return new RegExp(
2119
- pattern.source,
2120
- pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g"
2121
- );
2122
- }
2123
- function executeRegexWithTimeout(pattern, value, timeoutMs = 100) {
2124
- const matches = [];
2125
- const globalPattern = createGlobalPattern(pattern);
2126
- const startTime = Date.now();
2127
- let match;
2128
- let iterations = 0;
2129
- while ((match = globalPattern.exec(value)) !== null) {
2130
- if (!shouldContinueExecution(startTime, ++iterations, timeoutMs)) {
2131
- break;
2132
- }
2133
- matches.push(match);
2134
- if (match[0].length === 0) {
2135
- globalPattern.lastIndex = match.index + 1;
2136
- }
2137
- }
2138
- return matches;
2139
- }
2140
- function maskStringByPattern(value, pattern, mode = "full") {
2141
- const matches = [];
2142
- try {
2143
- const regexMatches = executeRegexWithTimeout(pattern, value);
2144
- for (const match of regexMatches) {
2145
- matches.push({
2146
- start: match.index,
2147
- end: match.index + match[0].length,
2148
- text: match[0],
2149
- groups: match.groups
2150
- });
2151
- }
2152
- } catch (error) {
2153
- logger.warn("Regex execution failed, skipping masking", error);
2154
- return value;
2155
- }
2156
- for (const matchInfo of matches.toReversed()) {
2157
- let patternName = "unknown";
2158
- if (matchInfo.groups) {
2159
- for (const [groupName, groupValue] of Object.entries(matchInfo.groups)) {
2160
- if (groupValue !== void 0) {
2161
- if (groupName.includes("_") && /\d$/.test(groupName)) {
2162
- const parts = groupName.split("_");
2163
- patternName = parts[0] || groupName;
2164
- } else {
2165
- patternName = groupName;
2166
- }
2167
- break;
2168
- }
2169
- }
2170
- }
2171
- logger.info(`Masking detected: pattern '${patternName}' found match in value`);
2172
- const masked = mode === "partial" ? matchInfo.text[0] + "*****" : "*****";
2173
- value = value.slice(0, matchInfo.start) + masked + value.slice(matchInfo.end);
2174
- }
2175
- return value;
2176
- }
2177
- function maskStringByPatternBasedRule(value, rule) {
2178
- const patternEntries = convertPatternsToPatternEntries(rule.patterns);
2179
- if (patternEntries.length === 0) {
2180
- logger.warn("No patterns provided for masking rule, returning original value");
2181
- return value;
2182
- }
2183
- const mode = rule.mode;
2184
- if (!patternEntries || patternEntries.length === 0) {
2185
- return mode === "partial" && value ? value[0] + "*****" : "*****";
2186
- }
2187
- const compiledPatterns = compilePatternEntries(patternEntries);
2188
- if (!compiledPatterns) {
2189
- return value;
2190
- }
2191
- return maskStringByPattern(value, compiledPatterns, mode);
2192
- }
2193
- function maskValue(value, rule) {
2194
- if (typeof value === "string") {
2195
- return maskStringByPatternBasedRule(value, rule);
2196
- } else if (typeof value === "boolean" || typeof value === "number") {
2197
- return maskStringByPatternBasedRule(String(value), rule);
2198
- } else if (Array.isArray(value)) {
2199
- return value.map((v) => maskStringByPatternBasedRule(String(v), rule));
2200
- } else if (value !== null && typeof value === "object") {
2201
- const result = {};
2202
- for (const [k, v] of Object.entries(value)) {
2203
- result[k] = maskValue(v, rule);
2204
- }
2205
- return result;
2206
- } else {
2207
- throw new Error(`Unsupported value type for masking: ${typeof value}`);
2208
- }
2209
- }
2210
- function maskAttributes(attributes, rules, outputOriginalValue = false) {
2211
- if (!attributes || Object.keys(attributes).length === 0) {
2212
- return {};
2213
- }
2214
- const maskedAttributes = { ...attributes };
2215
- for (const rule of rules) {
2216
- const compiledAttributeNamePattern = getCompiledAttributeNamePattern(rule);
2217
- const attributesToMask = compiledAttributeNamePattern ? Object.keys(maskedAttributes).filter((attr) => compiledAttributeNamePattern.test(attr)) : Object.keys(maskedAttributes);
2218
- for (const attribute of attributesToMask) {
2219
- const value = maskedAttributes[attribute];
2220
- if (value === null || value === void 0) {
2221
- continue;
2222
- }
2223
- if (outputOriginalValue) {
2224
- logger.debug(`Masking attribute '${attribute}' with original value`, { value });
2225
- }
2226
- maskedAttributes[attribute] = maskValue(value, rule);
2227
- }
2228
- }
2229
- return maskedAttributes;
2230
- }
2231
160
 
2232
- // src/internal/log/processors/log-processor.ts
2233
- init_semantic_conventions2();
2234
- var DEFAULT_LOG_MASKING_RULES = [
2235
- {
2236
- mode: "partial",
2237
- attributePattern: "event.name",
2238
- patterns: DEFAULT_PII_PATTERNS
2239
- }
2240
- ];
2241
- var BrizzSimpleLogRecordProcessor = class extends import_sdk_logs.SimpleLogRecordProcessor {
2242
- config;
2243
- constructor(exporter, config) {
2244
- super(exporter);
2245
- this.config = config;
2246
- }
2247
- onEmit(logRecord) {
2248
- const maskingConfig = this.config.masking?.eventMasking;
2249
- if (maskingConfig) {
2250
- maskLog(logRecord, maskingConfig);
2251
- }
2252
- const associationProperties = import_api10.context.active().getValue(PROPERTIES_CONTEXT_KEY);
2253
- if (associationProperties) {
2254
- for (const [key, value] of Object.entries(associationProperties)) {
2255
- logRecord.setAttribute(`${BRIZZ}.${key}`, value);
2256
- }
2257
- }
2258
- super.onEmit(logRecord);
2259
- }
2260
- };
2261
- var BrizzBatchLogRecordProcessor = class extends import_sdk_logs.BatchLogRecordProcessor {
2262
- config;
2263
- constructor(exporter, config) {
2264
- super(exporter);
2265
- this.config = config;
2266
- }
2267
- onEmit(logRecord) {
2268
- const maskingConfig = this.config.masking?.eventMasking;
2269
- if (maskingConfig) {
2270
- maskLog(logRecord, maskingConfig);
2271
- }
2272
- const associationProperties = import_api10.context.active().getValue(PROPERTIES_CONTEXT_KEY);
2273
- if (associationProperties) {
2274
- for (const [key, value] of Object.entries(associationProperties)) {
2275
- logRecord.setAttribute(`${BRIZZ}.${key}`, value);
2276
- }
2277
- }
2278
- super.onEmit(logRecord);
2279
- }
2280
- };
2281
- function maskLog(logRecord, config) {
2282
- if (!logRecord.attributes) {
2283
- return logRecord;
2284
- }
2285
- let rules = config.rules || [];
2286
- if (!config.disableDefaultRules) {
2287
- rules = [...DEFAULT_LOG_MASKING_RULES, ...rules];
2288
- }
2289
- try {
2290
- if (logRecord.attributes && Object.keys(logRecord.attributes).length > 0) {
2291
- const attributesRecord = {};
2292
- for (const [key, value] of Object.entries(logRecord.attributes)) {
2293
- attributesRecord[key] = value;
2294
- }
2295
- const maskedAttributes = maskAttributes(attributesRecord, rules);
2296
- if (maskedAttributes) {
2297
- const newAttributes = {};
2298
- for (const [key, value] of Object.entries(maskedAttributes)) {
2299
- newAttributes[key] = value;
2300
- }
2301
- for (const [key, value] of Object.entries(logRecord.attributes)) {
2302
- if (key.startsWith(INTERNAL_EVENT_PREFIX)) {
2303
- newAttributes[key] = value;
2304
- }
2305
- }
2306
- logRecord.setAttributes(newAttributes);
2307
- }
2308
- }
2309
- if (config.maskBody && logRecord.body !== void 0 && logRecord.body !== null) {
2310
- let maskedBody = logRecord.body;
2311
- for (const rule of rules) {
2312
- maskedBody = maskValue(maskedBody, rule);
2313
- }
2314
- logRecord.setBody(maskedBody);
2315
- }
2316
- return logRecord;
2317
- } catch (error) {
2318
- logger.error("Error masking log record:", error);
2319
- return logRecord;
2320
- }
2321
- }
2322
161
 
2323
- // src/internal/log/logging.ts
2324
- var LoggingModule = class _LoggingModule {
2325
- static instance = null;
2326
- logExporter = null;
2327
- logProcessor = null;
2328
- loggerProvider = null;
2329
- static getInstance() {
2330
- if (!_LoggingModule.instance) {
2331
- throw new Error("Brizz must be initialized before accessing LoggingModule");
2332
- }
2333
- return _LoggingModule.instance;
2334
- }
2335
- /**
2336
- * Initialize the logging module with the provided configuration
2337
- */
2338
- setup(config) {
2339
- logger.info("Setting up logging module");
2340
- this.initLogExporter(config);
2341
- this.initLogProcessor(config);
2342
- this.initLoggerProvider(config);
2343
- _LoggingModule.instance = this;
2344
- logger.info("Logging module setup completed");
2345
- }
2346
- /**
2347
- * Initialize the log exporter
2348
- */
2349
- initLogExporter(config) {
2350
- if (this.logExporter) {
2351
- logger.debug("Log exporter already initialized, skipping re-initialization");
2352
- return;
2353
- }
2354
- if (config.customLogExporter) {
2355
- logger.debug("Using custom log exporter");
2356
- this.logExporter = config.customLogExporter;
2357
- logger.debug("Custom log exporter initialized successfully");
2358
- return;
2359
- }
2360
- const logsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/logs";
2361
- logger.debug("Initializing default OTLP log exporter", { url: logsUrl });
2362
- const headers = { ...config.headers };
2363
- this.logExporter = new import_exporter_logs_otlp_http.OTLPLogExporter({
2364
- url: logsUrl,
2365
- headers
2366
- });
2367
- logger.debug("OTLP log exporter initialized successfully");
2368
- }
2369
- /**
2370
- * Initialize the log processor with masking support
2371
- */
2372
- initLogProcessor(config) {
2373
- if (this.logProcessor) {
2374
- logger.debug("Log processor already initialized, skipping re-initialization");
2375
- return;
2376
- }
2377
- if (!this.logExporter) {
2378
- throw new Error("Log exporter must be initialized before processor");
2379
- }
2380
- logger.debug("Initializing log processor", {
2381
- disableBatch: config.disableBatch,
2382
- hasMasking: !!config.masking?.eventMasking
2383
- });
2384
- this.logProcessor = config.disableBatch ? new BrizzSimpleLogRecordProcessor(this.logExporter, config) : new BrizzBatchLogRecordProcessor(this.logExporter, config);
2385
- logger.debug("Log processor initialized successfully");
2386
- }
2387
- /**
2388
- * Initialize the logger provider
2389
- */
2390
- initLoggerProvider(config) {
2391
- if (this.loggerProvider) {
2392
- logger.debug("Logger provider already initialized, skipping re-initialization");
2393
- return;
2394
- }
2395
- if (!this.logProcessor) {
2396
- throw new Error("Log processor must be initialized before logger provider");
2397
- }
2398
- logger.debug("Creating resource with service name", {
2399
- serviceName: config.appName
2400
- });
2401
- const resourceAttributes = {
2402
- ...config.resourceAttributes,
2403
- "service.name": config.appName,
2404
- [BRIZZ_SDK_VERSION]: getSDKVersion(),
2405
- [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
2406
- };
2407
- if (config.environment) {
2408
- resourceAttributes["deployment.environment"] = config.environment;
2409
- }
2410
- if (config.appVersion) {
2411
- resourceAttributes["service.version"] = config.appVersion;
2412
- }
2413
- const resource = (0, import_resources.resourceFromAttributes)(resourceAttributes);
2414
- logger.debug("Creating logger provider with resource");
2415
- this.loggerProvider = new import_sdk_logs2.LoggerProvider({
2416
- resource,
2417
- processors: [this.logProcessor]
2418
- });
2419
- logger.debug("Logger provider initialization completed");
2420
- }
2421
- /**
2422
- * Emit a custom event to the telemetry pipeline
2423
- */
2424
- emitEvent(name, attributes, body, severityNumber = import_api_logs.SeverityNumber.INFO) {
2425
- logger.debug("Attempting to emit event", {
2426
- name,
2427
- hasAttributes: !!attributes,
2428
- attributesCount: attributes ? Object.keys(attributes).length : 0,
2429
- hasBody: !!body,
2430
- severityNumber
2431
- });
2432
- if (!this.loggerProvider) {
2433
- logger.error("Cannot emit event: Logger provider not initialized");
2434
- throw new Error("Logging module not initialized");
2435
- }
2436
- const logAttributes = { "event.name": name };
2437
- if (attributes) {
2438
- Object.assign(logAttributes, attributes);
2439
- logger.debug("Combined log attributes", { attributes: Object.keys(logAttributes) });
2440
- }
2441
- logger.debug("Getting logger instance for brizz_events");
2442
- const eventLogger = this.loggerProvider.getLogger("brizz.events");
2443
- logger.debug("Emitting log record with eventName", { eventName: name });
2444
- try {
2445
- eventLogger.emit({
2446
- eventName: name,
2447
- attributes: logAttributes,
2448
- severityNumber,
2449
- body
2450
- });
2451
- logger.debug("Event successfully emitted", { eventName: name });
2452
- } catch (error) {
2453
- logger.error(`Failed to emit event '${name}'`, { error, eventName: name });
2454
- logger.error("Log record that failed", {
2455
- eventName: name,
2456
- hasAttributes: logAttributes,
2457
- severityNumber,
2458
- hasBody: body
2459
- });
2460
- throw error instanceof Error ? error : new Error(String(error));
2461
- }
2462
- }
2463
- /**
2464
- * Check if the module is initialized
2465
- */
2466
- isInitialized() {
2467
- return this.loggerProvider !== null;
2468
- }
2469
- /**
2470
- * Get the logger provider
2471
- */
2472
- getLoggerProvider() {
2473
- return this.loggerProvider;
2474
- }
2475
- /**
2476
- * Shutdown the logging module
2477
- */
2478
- async shutdown() {
2479
- logger.debug("Shutting down logging module");
2480
- if (this.loggerProvider) {
2481
- await this.loggerProvider.shutdown();
2482
- this.loggerProvider = null;
2483
- }
2484
- this.logProcessor = null;
2485
- this.logExporter = null;
2486
- if (_LoggingModule.instance === this) {
2487
- _LoggingModule.instance = null;
2488
- }
2489
- logger.debug("Logging module shutdown completed");
2490
- }
2491
- };
2492
- function emitEvent(name, attributes, body, severityNumber = import_api_logs.SeverityNumber.INFO) {
2493
- return LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
2494
- }
2495
- function emitEventWithSessionId(sessionId, name, attributes, body, severityNumber = import_api_logs.SeverityNumber.INFO) {
2496
- return callWithSessionId(sessionId, () => {
2497
- LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
2498
- });
2499
- }
2500
162
 
2501
- // src/internal/sdk.ts
2502
- init_logger();
2503
163
 
2504
- // src/internal/metric/metrics.ts
2505
- var import_exporter_metrics_otlp_http = require("@opentelemetry/exporter-metrics-otlp-http");
2506
- var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
2507
- init_logger();
2508
- var MetricsModule = class _MetricsModule {
2509
- static instance = null;
2510
- metricsExporter = null;
2511
- metricsReader = null;
2512
- static getInstance() {
2513
- if (!_MetricsModule.instance) {
2514
- throw new Error("Brizz must be initialized before accessing MetricsModule");
2515
- }
2516
- return _MetricsModule.instance;
2517
- }
2518
- /**
2519
- * Initialize the metrics module with the provided configuration
2520
- */
2521
- setup(config) {
2522
- logger.info("Setting up metrics module");
2523
- this.initMetricsReader(config);
2524
- _MetricsModule.instance = this;
2525
- logger.info("Metrics module setup completed");
2526
- }
2527
- /**
2528
- * Initialize the metrics exporter
2529
- */
2530
- initMetricsExporter(config) {
2531
- if (this.metricsExporter) {
2532
- logger.debug("Metrics exporter already initialized, skipping re-initialization");
2533
- return;
2534
- }
2535
- const metricsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/metrics";
2536
- logger.debug("Initializing metrics exporter", { url: metricsUrl });
2537
- this.metricsExporter = new import_exporter_metrics_otlp_http.OTLPMetricExporter({
2538
- url: metricsUrl,
2539
- headers: config.headers
2540
- });
2541
- logger.debug("Metrics exporter initialized successfully");
2542
- }
2543
- /**
2544
- * Initialize the metrics reader
2545
- */
2546
- initMetricsReader(config) {
2547
- if (this.metricsReader) {
2548
- logger.debug("Metrics reader already initialized, skipping re-initialization");
2549
- return;
2550
- }
2551
- if (config.customMetricReader) {
2552
- logger.debug("Using custom metric reader");
2553
- this.metricsReader = config.customMetricReader;
2554
- logger.debug("Custom metric reader initialized successfully");
2555
- return;
2556
- }
2557
- logger.debug(
2558
- "Using default metrics flow - creating OTLP exporter and PeriodicExportingMetricReader"
2559
- );
2560
- this.initMetricsExporter(config);
2561
- if (!this.metricsExporter) {
2562
- throw new Error("Failed to initialize metrics exporter");
2563
- }
2564
- this.metricsReader = new import_sdk_metrics.PeriodicExportingMetricReader({
2565
- exporter: this.metricsExporter
2566
- });
2567
- logger.debug("Default metrics reader initialized successfully");
2568
- }
2569
- /**
2570
- * Get the metrics exporter
2571
- */
2572
- getMetricsExporter() {
2573
- if (!this.metricsExporter) {
2574
- throw new Error("Metrics module not initialized");
2575
- }
2576
- return this.metricsExporter;
2577
- }
2578
- /**
2579
- * Get the metrics reader
2580
- */
2581
- getMetricsReader() {
2582
- if (!this.metricsReader) {
2583
- throw new Error("Metrics module not initialized");
2584
- }
2585
- return this.metricsReader;
2586
- }
2587
- /**
2588
- * Shutdown the metrics module
2589
- */
2590
- shutdown() {
2591
- logger.debug("Shutting down metrics module");
2592
- this.metricsReader = null;
2593
- this.metricsExporter = null;
2594
- if (_MetricsModule.instance === this) {
2595
- _MetricsModule.instance = null;
2596
- }
2597
- logger.debug("Metrics module shutdown completed");
2598
- }
2599
- };
2600
- function getMetricsExporter() {
2601
- return MetricsModule.getInstance().getMetricsExporter();
2602
- }
2603
- function getMetricsReader() {
2604
- return MetricsModule.getInstance().getMetricsReader();
2605
- }
2606
164
 
2607
- // src/internal/trace/tracing.ts
2608
- var import_exporter_trace_otlp_proto = require("@opentelemetry/exporter-trace-otlp-proto");
2609
- init_logger();
2610
165
 
2611
- // src/internal/trace/exporters/span-exporter.ts
2612
- var import_core = require("@opentelemetry/core");
2613
- var import_resources2 = require("@opentelemetry/resources");
2614
- init_logger();
2615
- init_version();
2616
- var BrizzSpanExporter = class {
2617
- _delegate;
2618
- _brizzResource;
2619
- _beforeSendSpan;
2620
- constructor(delegate, config) {
2621
- this._delegate = delegate;
2622
- const resourceAttrs = {
2623
- ...config.resourceAttributes,
2624
- "service.name": config.appName,
2625
- [BRIZZ_SDK_VERSION]: getSDKVersion(),
2626
- [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
2627
- };
2628
- if (config.environment) {
2629
- resourceAttrs["deployment.environment"] = config.environment;
2630
- }
2631
- if (config.appVersion) {
2632
- resourceAttrs["service.version"] = config.appVersion;
2633
- }
2634
- this._brizzResource = (0, import_resources2.resourceFromAttributes)(resourceAttrs);
2635
- this._beforeSendSpan = config.beforeSendSpan;
2636
- }
2637
- export(spans, resultCallback) {
2638
- if (spans.length === 0) {
2639
- resultCallback({ code: import_core.ExportResultCode.SUCCESS });
2640
- return;
2641
- }
2642
- const patchedSpans = spans.map((span) => ({
2643
- ...span,
2644
- resource: span.resource.merge(this._brizzResource),
2645
- spanContext: span.spanContext.bind(span)
2646
- }));
2647
- const filter = this._beforeSendSpan;
2648
- if (!filter) {
2649
- this._delegate.export(patchedSpans, resultCallback);
2650
- return;
2651
- }
2652
- const verdicts = patchedSpans.map((span) => {
2653
- try {
2654
- return Promise.resolve(filter(span));
2655
- } catch (error) {
2656
- logger.warn("beforeSendSpan threw; span will be kept", { error });
2657
- return Promise.resolve(true);
2658
- }
2659
- });
2660
- Promise.all(verdicts).then((keep) => {
2661
- const filtered = patchedSpans.filter((_, i) => keep[i] !== false);
2662
- if (filtered.length === 0) {
2663
- resultCallback({ code: import_core.ExportResultCode.SUCCESS });
2664
- return;
2665
- }
2666
- this._delegate.export(filtered, resultCallback);
2667
- return;
2668
- }).catch((error) => {
2669
- logger.warn("beforeSendSpan rejected; all spans will be kept", { error });
2670
- this._delegate.export(patchedSpans, resultCallback);
2671
- });
2672
- }
2673
- async shutdown() {
2674
- return this._delegate.shutdown();
2675
- }
2676
- async forceFlush() {
2677
- return this._delegate.forceFlush?.();
2678
- }
2679
- };
2680
166
 
2681
- // src/internal/trace/processors/span-processor.ts
2682
- var import_api11 = require("@opentelemetry/api");
2683
- var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
2684
- init_logger();
2685
- init_semantic_conventions2();
2686
- function applyContextAttributes(span) {
2687
- const sessionProperties = import_api11.context.active().getValue(PROPERTIES_CONTEXT_KEY);
2688
- if (sessionProperties) {
2689
- for (const [key, value] of Object.entries(sessionProperties)) {
2690
- span.setAttribute(`${BRIZZ}.${key}`, value);
2691
- }
2692
- }
2693
- }
2694
- var DEFAULT_MASKING_RULES = [
2695
- {
2696
- mode: "partial",
2697
- patterns: DEFAULT_PII_PATTERNS
2698
- }
2699
- ];
2700
- var BrizzSimpleSpanProcessor = class extends import_sdk_trace_base.SimpleSpanProcessor {
2701
- config;
2702
- constructor(spanExporter, config) {
2703
- super(spanExporter);
2704
- this.config = config;
2705
- }
2706
- onStart(span, parentContext) {
2707
- applyContextAttributes(span);
2708
- super.onStart(span, parentContext);
2709
- }
2710
- onEnd(span) {
2711
- const maskingConfig = this.config.masking?.spanMasking;
2712
- if (maskingConfig) {
2713
- maskReadableSpan(span, maskingConfig);
2714
- }
2715
- super.onEnd(span);
2716
- }
2717
- };
2718
- var BrizzBatchSpanProcessor = class extends import_sdk_trace_base.BatchSpanProcessor {
2719
- config;
2720
- constructor(spanExporter, config) {
2721
- super(spanExporter);
2722
- this.config = config;
2723
- }
2724
- onStart(span, parentContext) {
2725
- applyContextAttributes(span);
2726
- super.onStart(span, parentContext);
2727
- }
2728
- onEnd(span) {
2729
- const maskingConfig = this.config.masking?.spanMasking;
2730
- if (maskingConfig) {
2731
- maskReadableSpan(span, maskingConfig);
2732
- }
2733
- super.onEnd(span);
2734
- }
2735
- };
2736
- function maskReadableSpan(span, config) {
2737
- const attrs = span.attributes;
2738
- if (!attrs || Object.keys(attrs).length === 0) {
2739
- return;
2740
- }
2741
- let rules = config.rules ? [...config.rules] : [];
2742
- if (!config.disableDefaultRules) {
2743
- rules = [...rules, ...DEFAULT_MASKING_RULES];
2744
- }
2745
- try {
2746
- const input = {};
2747
- for (const [k, v] of Object.entries(attrs)) {
2748
- input[k] = v;
2749
- }
2750
- const masked = maskAttributes(input, rules);
2751
- for (const [k, v] of Object.entries(masked ?? {})) {
2752
- if (attrs[k] !== v) {
2753
- attrs[k] = v;
2754
- }
2755
- }
2756
- } catch (error) {
2757
- logger.error("Error masking span", { err: error });
2758
- }
2759
- }
2760
167
 
2761
- // src/internal/trace/tracing.ts
2762
- var TracingModule = class _TracingModule {
2763
- static instance = null;
2764
- spanExporter = null;
2765
- spanProcessor = null;
2766
- static getInstance() {
2767
- if (!_TracingModule.instance) {
2768
- throw new Error("Brizz must be initialized before accessing TracingModule");
2769
- }
2770
- return _TracingModule.instance;
2771
- }
2772
- /**
2773
- * Initialize the tracing module with the provided configuration
2774
- */
2775
- setup(config) {
2776
- logger.info("Setting up tracing module");
2777
- if (config.disableSpanExporter) {
2778
- logger.info(
2779
- "Span exporter disabled via disableSpanExporter; skipping exporter and processor setup"
2780
- );
2781
- this.spanExporter = null;
2782
- this.spanProcessor = null;
2783
- _TracingModule.instance = this;
2784
- return;
2785
- }
2786
- this.initSpanExporter(config);
2787
- this.initSpanProcessor(config);
2788
- _TracingModule.instance = this;
2789
- logger.info("Tracing module setup completed");
2790
- }
2791
- /**
2792
- * Initialize the span exporter
2793
- */
2794
- initSpanExporter(config) {
2795
- if (this.spanExporter) {
2796
- logger.debug("Span exporter already initialized, skipping re-initialization");
2797
- return;
2798
- }
2799
- if (config.customSpanExporter) {
2800
- logger.debug("Using custom span exporter");
2801
- this.spanExporter = new BrizzSpanExporter(config.customSpanExporter, config);
2802
- logger.debug("Custom span exporter initialized successfully");
2803
- return;
2804
- }
2805
- const tracesUrl = config.baseUrl.replace(/\/$/, "") + "/v1/traces";
2806
- logger.debug("Initializing default OTLP span exporter", { url: tracesUrl });
2807
- const otlpExporter = new import_exporter_trace_otlp_proto.OTLPTraceExporter({
2808
- url: tracesUrl,
2809
- headers: config.headers
2810
- });
2811
- this.spanExporter = new BrizzSpanExporter(otlpExporter, config);
2812
- logger.debug("OTLP span exporter initialized successfully");
2813
- }
2814
- /**
2815
- * Initialize the span processor with masking support
2816
- */
2817
- initSpanProcessor(config) {
2818
- if (this.spanProcessor) {
2819
- logger.debug("Span processor already initialized, skipping re-initialization");
2820
- return;
2821
- }
2822
- if (!this.spanExporter) {
2823
- throw new Error("Span exporter must be initialized before processor");
2824
- }
2825
- logger.debug("Initializing span processor", {
2826
- disableBatch: config.disableBatch,
2827
- hasMasking: !!config.masking?.spanMasking
2828
- });
2829
- const spanProcessor = config.disableBatch ? new BrizzSimpleSpanProcessor(this.spanExporter, config) : new BrizzBatchSpanProcessor(this.spanExporter, config);
2830
- logger.debug("Span processor initialized successfully");
2831
- this.spanProcessor = spanProcessor;
2832
- }
2833
- /**
2834
- * Get the span exporter
2835
- */
2836
- getSpanExporter() {
2837
- if (!this.spanExporter) {
2838
- throw new Error("Tracing module not initialized");
2839
- }
2840
- return this.spanExporter;
2841
- }
2842
- /**
2843
- * Get the span processor
2844
- */
2845
- getSpanProcessor() {
2846
- if (!this.spanProcessor) {
2847
- throw new Error("Tracing module not initialized");
2848
- }
2849
- return this.spanProcessor;
2850
- }
2851
- async shutdown() {
2852
- logger.debug("Shutting down tracing module");
2853
- if (this.spanProcessor) {
2854
- await this.spanProcessor.shutdown();
2855
- this.spanProcessor = null;
2856
- }
2857
- if (this.spanExporter) {
2858
- await this.spanExporter.shutdown();
2859
- this.spanExporter = null;
2860
- }
2861
- _TracingModule.instance = null;
2862
- logger.debug("Tracing module shutdown completed");
2863
- }
2864
- };
2865
- function getSpanExporter() {
2866
- return TracingModule.getInstance().getSpanExporter();
2867
- }
2868
- function getSpanProcessor() {
2869
- return TracingModule.getInstance().getSpanProcessor();
2870
- }
2871
168
 
2872
- // src/internal/sdk.ts
2873
- init_version();
2874
- var _Brizz = class __Brizz {
2875
- static instance = null;
2876
- /** Flag indicating if SDK initialization has completed successfully */
2877
- _initialized = false;
2878
- /** OpenTelemetry sdk instance */
2879
- _sdk = null;
2880
- static getInstance() {
2881
- if (!__Brizz.instance) {
2882
- throw new Error("Brizz must be initialized before accessing TracingModule");
2883
- }
2884
- return __Brizz.instance;
2885
- }
2886
- /**
2887
- * Initialize the Brizz SDK with the provided configuration.
2888
- *
2889
- * @param {IBrizzInitializeOptions} options - Configuration options for the SDK
2890
- * @throws {Error} - If initialization fails
2891
- *
2892
- * @example
2893
- * ```typescript
2894
- * Brizz.initialize({
2895
- * appName: 'my-app',
2896
- * baseUrl: 'http://localhost:4318',
2897
- * apiKey: 'your-api-key'
2898
- * });
2899
- * ```
2900
- */
2901
- initialize(options) {
2902
- if (this._initialized) {
2903
- logger.warn("Brizz SDK already initialized");
2904
- return;
2905
- }
2906
- logger.info("Starting Brizz SDK initialization");
2907
- try {
2908
- const resolvedConfig = resolveConfig(options);
2909
- this.initializeModules(resolvedConfig);
2910
- this.setupInstrumentation(options);
2911
- this.createAndStartNodeSDK(options, resolvedConfig);
2912
- this._initialized = true;
2913
- logger.info("Brizz SDK initialization completed successfully", {
2914
- moduleSystem: this.detectModuleSystem()
2915
- });
2916
- } catch (error) {
2917
- logger.error("Failed to initialize Brizz SDK", { error });
2918
- throw new Error(`Failed to initialize SDK: ${String(error)}`, { cause: error });
2919
- }
2920
- }
2921
- /**
2922
- * Set up instrumentation registry and configure manual modules.
2923
- * @private
2924
- */
2925
- setupInstrumentation(options) {
2926
- const registry = InstrumentationRegistry.getInstance();
2927
- if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {
2928
- registry.setManualModules(options.instrumentModules);
2929
- }
2930
- }
2931
- /**
2932
- * Create and start NodeSDK if not disabled.
2933
- * Only handles manual instrumentations now - auto instrumentations are loaded at import time.
2934
- * @private
2935
- */
2936
- createAndStartNodeSDK(options, resolvedConfig) {
2937
- if (options.disableNodeSdk) {
2938
- logger.info("NodeSDK disabled - only telemetry modules initialized");
2939
- return;
2940
- }
2941
- const registry = InstrumentationRegistry.getInstance();
2942
- const manualInstrumentations = registry.getManualInstrumentations();
2943
- const resourceAttributes = {
2944
- ...resolvedConfig.resourceAttributes,
2945
- "service.name": resolvedConfig.appName,
2946
- [BRIZZ_SDK_VERSION]: getSDKVersion(),
2947
- [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
2948
- };
2949
- if (resolvedConfig.environment) {
2950
- resourceAttributes["deployment.environment"] = resolvedConfig.environment;
2951
- }
2952
- if (resolvedConfig.appVersion) {
2953
- resourceAttributes["service.version"] = resolvedConfig.appVersion;
2954
- }
2955
- this._sdk = new import_sdk_node.NodeSDK({
2956
- spanProcessors: resolvedConfig.disableSpanExporter ? [] : [new InterruptPropagator(), getSpanProcessor()],
2957
- metricReader: getMetricsReader(),
2958
- resource: (0, import_resources3.resourceFromAttributes)(resourceAttributes),
2959
- instrumentations: manualInstrumentations
2960
- });
2961
- this._sdk.start();
2962
- if (manualInstrumentations.length > 0) {
2963
- logger.info(`NodeSDK started with ${manualInstrumentations.length} manual instrumentations`);
2964
- } else {
2965
- logger.info("NodeSDK started - using auto-instrumentations loaded at import time");
2966
- }
2967
- }
2968
- /**
2969
- * Initialize telemetry modules.
2970
- *
2971
- * Sets up the tracing, metrics, and logging modules with their
2972
- * respective exporters and processors.
2973
- *
2974
- * @param {IResolvedBrizzConfig} config - Resolved configuration
2975
- * @private
2976
- */
2977
- initializeModules(config) {
2978
- logger.info("Initializing telemetry modules");
2979
- logger.debug("Initializing tracing module");
2980
- const tracingModule = new TracingModule();
2981
- tracingModule.setup(config);
2982
- logger.debug("Initializing metrics module");
2983
- const metricsModule = new MetricsModule();
2984
- metricsModule.setup(config);
2985
- logger.debug("Initializing logging module");
2986
- const loggingModule = new LoggingModule();
2987
- loggingModule.setup(config);
2988
- logger.info("All telemetry modules initialized successfully");
2989
- }
2990
- /**
2991
- * Detect the current module system (ESM or CJS) using reliable indicators
2992
- *
2993
- * @returns {string} - 'ESM' or 'CJS'
2994
- * @private
2995
- */
2996
- detectModuleSystem() {
2997
- const inCJS = typeof module !== "undefined" && typeof exports !== "undefined" && typeof require === "function" && typeof __filename === "string" && typeof __dirname === "string" && this === (typeof exports !== "undefined" ? exports : void 0);
2998
- return inCJS ? "CJS" : "ESM";
2999
- }
3000
- /**
3001
- * Gracefully shutdown the Brizz SDK.
3002
- *
3003
- * This method stops all telemetry collection, flushes any pending data,
3004
- * and releases resources. Should be called before application termination.
3005
- *
3006
- * @returns {Promise<void>} - Resolves when shutdown is complete
3007
- * @throws {Error} - If shutdown fails
3008
- *
3009
- * @example
3010
- * ```typescript
3011
- * // Shutdown before app exit
3012
- * await Brizz.shutdown();
3013
- * ```
3014
- */
3015
- async shutdown() {
3016
- if (!this._initialized) {
3017
- logger.warn("Brizz SDK not initialized");
3018
- return;
3019
- }
3020
- try {
3021
- await this.shutdownModules();
3022
- await this._sdk?.shutdown();
3023
- this._initialized = false;
3024
- this._sdk = null;
3025
- __Brizz.instance = null;
3026
- logger.info("Brizz SDK shut down successfully");
3027
- } catch (error) {
3028
- if (error instanceof Error && error.message.includes("ENOTFOUND")) {
3029
- logger.debug(`Network error during shutdown (expected in tests): ${error.message}`);
3030
- } else {
3031
- logger.error(`Failed to shutdown Brizz SDK: ${String(error)}`);
3032
- throw error;
3033
- }
3034
- }
3035
- }
3036
- /**
3037
- * Shutdown all telemetry modules.
3038
- * @private
3039
- */
3040
- async shutdownModules() {
3041
- logger.info("Shutting down telemetry modules");
3042
- try {
3043
- try {
3044
- const tracingModule = TracingModule.getInstance();
3045
- await tracingModule.shutdown();
3046
- } catch {
3047
- logger.debug("Tracing module already shut down or not initialized");
3048
- }
3049
- try {
3050
- const metricsModule = MetricsModule.getInstance();
3051
- metricsModule.shutdown();
3052
- } catch {
3053
- logger.debug("Metrics module already shut down or not initialized");
3054
- }
3055
- try {
3056
- const loggingModule = LoggingModule.getInstance();
3057
- await loggingModule.shutdown();
3058
- } catch {
3059
- logger.debug("Logging module already shut down or not initialized");
3060
- }
3061
- logger.info("All telemetry modules shut down successfully");
3062
- } catch (error) {
3063
- logger.error("Error shutting down modules", { error });
3064
- throw error;
3065
- }
3066
- }
3067
- };
3068
- var Brizz = new _Brizz();
3069
169
 
3070
- // src/index.ts
3071
- init_logger();
3072
- var import_api_logs2 = require("@opentelemetry/api-logs");
3073
170
 
3074
- // src/node/runtime.ts
3075
- init_logger();
3076
- function detectRuntime() {
3077
- const [major, minor] = process.versions.node.split(".").map(Number);
3078
- const noNodeJSGlobals = typeof __filename === "undefined" && typeof __dirname === "undefined";
3079
- const noModuleSystem = typeof module === "undefined" && typeof exports === "undefined";
3080
- const hasRequire = typeof require === "function";
3081
- const isESM = noNodeJSGlobals && noModuleSystem;
3082
- const isCJS = hasRequire && typeof module !== "undefined" && typeof exports !== "undefined" && typeof __filename === "string" && typeof __dirname === "string";
3083
- const supportsLoaderAPI = (major ?? 0) >= 21 || (major ?? 0) === 20 && (minor ?? 0) >= 6 || (major ?? 0) === 18 && (minor ?? 0) >= 19;
3084
- const supportsRegister = (
3085
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3086
- !!process.features?.typescript || !!globalThis.module?.register
3087
- );
3088
- logger.debug("Runtime detection results:", {
3089
- nodeVersion: `${major ?? 0}.${minor ?? 0}`,
3090
- isESM,
3091
- isCJS,
3092
- supportsLoaderAPI,
3093
- supportsRegister,
3094
- detectionLogic: {
3095
- noNodeJSGlobals,
3096
- noModuleSystem,
3097
- hasRequire,
3098
- esmCondition: `${noNodeJSGlobals} && ${noModuleSystem} = ${isESM}`,
3099
- cjsCondition: `require && module && exports && __filename && __dirname = ${isCJS}`
3100
- },
3101
- checks: {
3102
- __filename: typeof __filename,
3103
- __dirname: typeof __dirname,
3104
- require: typeof require,
3105
- module: typeof module,
3106
- exports: typeof exports,
3107
- "process.features": process.features,
3108
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3109
- "globalThis.module": globalThis.module
3110
- }
3111
- });
3112
- return {
3113
- isESM,
3114
- isCJS,
3115
- nodeVersion: process.versions.node,
3116
- supportsLoaderAPI,
3117
- supportsRegister
3118
- };
3119
- }
3120
171
 
3121
- // src/init.ts
3122
- var init_exports = {};
3123
- // Annotate the CommonJS export names for ESM import in node:
3124
- 0 && (module.exports = {
3125
- Brizz,
3126
- DEFAULT_PII_PATTERNS,
3127
- LogLevel,
3128
- Session,
3129
- SessionTitle,
3130
- SeverityNumber,
3131
- addExternalLink,
3132
- callWithMute,
3133
- callWithProperties,
3134
- callWithSessionId,
3135
- detectRuntime,
3136
- emitEvent,
3137
- emitEventWithSessionId,
3138
- getActiveSession,
3139
- getLogLevel,
3140
- getMetricsExporter,
3141
- getMetricsReader,
3142
- getSpanExporter,
3143
- getSpanProcessor,
3144
- init,
3145
- logger,
3146
- maskAttributes,
3147
- maskValue,
3148
- setCurrentSpanCustomProperties,
3149
- setLogLevel,
3150
- startSession,
3151
- startSessionTitle,
3152
- withMute,
3153
- withProperties,
3154
- withSessionId
3155
- });
172
+
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+ exports.Brizz = _chunkNUTJMVD4cjs.Brizz; exports.DEFAULT_PII_PATTERNS = _chunkNUTJMVD4cjs.DEFAULT_PII_PATTERNS; exports.LogLevel = _chunkJB6MA2RVcjs.LogLevel; exports.Session = _chunkNUTJMVD4cjs.Session; exports.SessionTitle = _chunkNUTJMVD4cjs.SessionTitle; exports.SeverityNumber = _apilogs.SeverityNumber; exports.addExternalLink = _chunkNUTJMVD4cjs.addExternalLink; exports.callWithMute = _chunkNUTJMVD4cjs.callWithMute; exports.callWithProperties = _chunkNUTJMVD4cjs.callWithProperties; exports.callWithSessionId = _chunkNUTJMVD4cjs.callWithSessionId; exports.detectRuntime = _chunkNUTJMVD4cjs.detectRuntime; exports.emitEvent = _chunkNUTJMVD4cjs.emitEvent; exports.emitEventWithSessionId = _chunkNUTJMVD4cjs.emitEventWithSessionId; exports.getActiveSession = _chunkNUTJMVD4cjs.getActiveSession; exports.getLogLevel = _chunkJB6MA2RVcjs.getLogLevel; exports.getMetricsExporter = _chunkNUTJMVD4cjs.getMetricsExporter; exports.getMetricsReader = _chunkNUTJMVD4cjs.getMetricsReader; exports.getSpanExporter = _chunkNUTJMVD4cjs.getSpanExporter; exports.getSpanProcessor = _chunkNUTJMVD4cjs.getSpanProcessor; exports.init = init_exports; exports.logger = _chunkJB6MA2RVcjs.logger; exports.maskAttributes = _chunkNUTJMVD4cjs.maskAttributes; exports.maskValue = _chunkNUTJMVD4cjs.maskValue; exports.setCurrentSpanCustomProperties = _chunkNUTJMVD4cjs.setCurrentSpanCustomProperties; exports.setLogLevel = _chunkJB6MA2RVcjs.setLogLevel; exports.startSession = _chunkNUTJMVD4cjs.startSession; exports.startSessionTitle = _chunkNUTJMVD4cjs.startSessionTitle; exports.withMute = _chunkNUTJMVD4cjs.withMute; exports.withProperties = _chunkNUTJMVD4cjs.withProperties; exports.withSessionId = _chunkNUTJMVD4cjs.withSessionId;