@brizz/sdk 0.1.29 → 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.
@@ -0,0 +1,1970 @@
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; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;
2
+
3
+
4
+
5
+
6
+
7
+ var _chunkJB6MA2RVcjs = require('./chunk-JB6MA2RV.cjs');
8
+
9
+
10
+ var _chunkLTXMCGVQcjs = require('./chunk-LTXMCGVQ.cjs');
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+ var _chunkGCORRK6Bcjs = require('./chunk-GCORRK6B.cjs');
33
+
34
+ // src/internal/instrumentation/registry.ts
35
+ var _instrumentationanthropic = require('@traceloop/instrumentation-anthropic');
36
+ var _instrumentationbedrock = require('@traceloop/instrumentation-bedrock');
37
+ var _instrumentationchromadb = require('@traceloop/instrumentation-chromadb');
38
+ var _instrumentationcohere = require('@traceloop/instrumentation-cohere');
39
+ var _instrumentationllamaindex = require('@traceloop/instrumentation-llamaindex');
40
+ var _instrumentationopenai = require('@traceloop/instrumentation-openai');
41
+ var _instrumentationpinecone = require('@traceloop/instrumentation-pinecone');
42
+ var _instrumentationqdrant = require('@traceloop/instrumentation-qdrant');
43
+ var _instrumentationtogether = require('@traceloop/instrumentation-together');
44
+ var InstrumentationRegistry = (_class = class _InstrumentationRegistry {constructor() { _class.prototype.__init.call(this); }
45
+
46
+ static getInstance() {
47
+ if (!this.instance) {
48
+ this.instance = new _InstrumentationRegistry();
49
+ }
50
+ return this.instance;
51
+ }
52
+ __init() {this.manualModules = null}
53
+ /**
54
+ * Helper to load instrumentation with optional manual module
55
+ */
56
+ loadInstrumentation(InstrumentationClass, name, manualModule, exceptionLogger) {
57
+ try {
58
+ const inst = new InstrumentationClass({
59
+ exceptionLogger: exceptionLogger || ((error) => _chunkJB6MA2RVcjs.logger.error(`Exception in instrumentation: ${String(error)}`))
60
+ });
61
+ if (manualModule) {
62
+ inst.manuallyInstrument(manualModule);
63
+ _chunkJB6MA2RVcjs.logger.debug(`Manual instrumentation enabled for ${name}`);
64
+ }
65
+ return inst;
66
+ } catch (error) {
67
+ _chunkJB6MA2RVcjs.logger.error(`Failed to load ${name} instrumentation: ${String(error)}`);
68
+ return null;
69
+ }
70
+ }
71
+ /**
72
+ * Load manual instrumentations only (with modules provided by user).
73
+ * @private
74
+ */
75
+ loadManualInstrumentations(instrumentations, exceptionLogger) {
76
+ const instrumentationConfigs = [
77
+ { class: _instrumentationopenai.OpenAIInstrumentation, name: "OpenAI", module: _optionalChain([this, 'access', _2 => _2.manualModules, 'optionalAccess', _3 => _3.openAI]) },
78
+ { class: _instrumentationanthropic.AnthropicInstrumentation, name: "Anthropic", module: _optionalChain([this, 'access', _4 => _4.manualModules, 'optionalAccess', _5 => _5.anthropic]) },
79
+ { class: _instrumentationcohere.CohereInstrumentation, name: "Cohere", module: _optionalChain([this, 'access', _6 => _6.manualModules, 'optionalAccess', _7 => _7.cohere]) },
80
+ { class: _instrumentationbedrock.BedrockInstrumentation, name: "Bedrock", module: _optionalChain([this, 'access', _8 => _8.manualModules, 'optionalAccess', _9 => _9.bedrock]) },
81
+ { class: _instrumentationpinecone.PineconeInstrumentation, name: "Pinecone", module: _optionalChain([this, 'access', _10 => _10.manualModules, 'optionalAccess', _11 => _11.pinecone]) },
82
+ {
83
+ class: _instrumentationllamaindex.LlamaIndexInstrumentation,
84
+ name: "LlamaIndex",
85
+ module: _optionalChain([this, 'access', _12 => _12.manualModules, 'optionalAccess', _13 => _13.llamaindex])
86
+ },
87
+ { class: _instrumentationchromadb.ChromaDBInstrumentation, name: "ChromaDB", module: _optionalChain([this, 'access', _14 => _14.manualModules, 'optionalAccess', _15 => _15.chromadb]) },
88
+ { class: _instrumentationqdrant.QdrantInstrumentation, name: "Qdrant", module: _optionalChain([this, 'access', _16 => _16.manualModules, 'optionalAccess', _17 => _17.qdrant]) },
89
+ { class: _instrumentationtogether.TogetherInstrumentation, name: "Together", module: _optionalChain([this, 'access', _18 => _18.manualModules, 'optionalAccess', _19 => _19.together]) }
90
+ ];
91
+ for (const config of instrumentationConfigs) {
92
+ if (!config.module) {
93
+ continue;
94
+ }
95
+ const instrumentation = this.loadInstrumentation(
96
+ config.class,
97
+ config.name,
98
+ config.module,
99
+ exceptionLogger
100
+ );
101
+ if (instrumentation) {
102
+ instrumentations.push(instrumentation);
103
+ }
104
+ }
105
+ if (_optionalChain([this, 'access', _20 => _20.manualModules, 'optionalAccess', _21 => _21.langchain, 'optionalAccess', _22 => _22.callbackManagerModule])) {
106
+ const callbackManagerModule = this.manualModules.langchain.callbackManagerModule;
107
+ void (async () => {
108
+ try {
109
+ const { LangChainInstrumentation } = await Promise.resolve().then(() => _interopRequireWildcard(require("@arizeai/openinference-instrumentation-langchain")));
110
+ const lcInst = new LangChainInstrumentation();
111
+ lcInst.manuallyInstrument(callbackManagerModule);
112
+ _chunkJB6MA2RVcjs.logger.debug("Manual instrumentation enabled for LangChain");
113
+ } catch (error) {
114
+ _chunkJB6MA2RVcjs.logger.error(
115
+ `Failed to load LangChain instrumentation. Ensure @langchain/core is installed: ${String(error)}`
116
+ );
117
+ }
118
+ })();
119
+ }
120
+ if (_optionalChain([this, 'access', _23 => _23.manualModules, 'optionalAccess', _24 => _24.google_vertexai])) {
121
+ const vertexModule = this.manualModules.google_vertexai;
122
+ void (async () => {
123
+ try {
124
+ const { VertexAIInstrumentation } = await Promise.resolve().then(() => _interopRequireWildcard(require("@traceloop/instrumentation-vertexai")));
125
+ const vertexInst = new VertexAIInstrumentation({ exceptionLogger });
126
+ vertexInst.manuallyInstrument(vertexModule);
127
+ _chunkJB6MA2RVcjs.logger.debug("Manual instrumentation enabled for Vertex AI");
128
+ } catch (error) {
129
+ _chunkJB6MA2RVcjs.logger.error(
130
+ `Failed to load Vertex AI instrumentation. Ensure @traceloop/instrumentation-vertexai is installed: ${String(error)}`
131
+ );
132
+ }
133
+ })();
134
+ }
135
+ if (_optionalChain([this, 'access', _25 => _25.manualModules, 'optionalAccess', _26 => _26.mcp])) {
136
+ const mcpModules = this.manualModules.mcp;
137
+ void (async () => {
138
+ try {
139
+ const { MCPInstrumentation } = await Promise.resolve().then(() => _interopRequireWildcard(require("./mcp-6BDG4SWY.cjs")));
140
+ const instrumentation = new MCPInstrumentation({ exceptionLogger });
141
+ instrumentation.manuallyInstrument(mcpModules);
142
+ _chunkJB6MA2RVcjs.logger.debug("Manual instrumentation enabled for MCP");
143
+ } catch (error) {
144
+ _chunkJB6MA2RVcjs.logger.error(`Failed to apply MCP instrumentation: ${String(error)}`);
145
+ }
146
+ })();
147
+ }
148
+ }
149
+ /**
150
+ * Set manual instrumentation modules for Next.js/Webpack environments
151
+ */
152
+ setManualModules(modules) {
153
+ this.manualModules = modules;
154
+ _chunkJB6MA2RVcjs.logger.info("Manual instrumentation modules configured for Next.js/Webpack compatibility");
155
+ }
156
+ /**
157
+ * Get manual instrumentations only.
158
+ * Auto-instrumentations are handled at import time.
159
+ */
160
+ getManualInstrumentations() {
161
+ if (!this.manualModules || Object.keys(this.manualModules).length === 0) {
162
+ _chunkJB6MA2RVcjs.logger.debug("No manual instrumentation modules configured");
163
+ return [];
164
+ }
165
+ const instrumentations = [];
166
+ const exceptionLogger = (error) => {
167
+ _chunkJB6MA2RVcjs.logger.error(`Exception in manual instrumentation: ${String(error)}`);
168
+ };
169
+ this.loadManualInstrumentations(instrumentations, exceptionLogger);
170
+ _chunkJB6MA2RVcjs.logger.info(`Loaded ${instrumentations.length} manual instrumentations`);
171
+ return instrumentations;
172
+ }
173
+ }, _class);
174
+
175
+ // src/internal/trace/session.ts
176
+ var _api = require('@opentelemetry/api');
177
+
178
+ // src/internal/log/logging.ts
179
+ var _apilogs = require('@opentelemetry/api-logs');
180
+ var _exporterlogsotlphttp = require('@opentelemetry/exporter-logs-otlp-http');
181
+ var _resources = require('@opentelemetry/resources');
182
+
183
+
184
+ var _sdklogs = require('@opentelemetry/sdk-logs');
185
+
186
+ // src/internal/constants.ts
187
+ var BRIZZ_SDK_VERSION = "brizz.sdk.version";
188
+ var BRIZZ_SDK_LANGUAGE = "brizz.sdk.language";
189
+ var SDK_LANGUAGE = "typescript";
190
+
191
+ // src/internal/log/processors/log-processor.ts
192
+
193
+
194
+
195
+ // src/internal/masking/patterns.ts
196
+ var DEFAULT_PII_PATTERNS = [
197
+ // Phone numbers (US format)
198
+ {
199
+ name: "us_phone_numbers",
200
+ 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]|$)`
201
+ },
202
+ // Credit card numbers
203
+ {
204
+ name: "credit_cards",
205
+ 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`
206
+ },
207
+ {
208
+ name: "credit_cards_with_separators",
209
+ 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`
210
+ },
211
+ // IP addresses (IPv4)
212
+ {
213
+ name: "ipv4_addresses",
214
+ 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`
215
+ },
216
+ // API keys/tokens
217
+ {
218
+ name: "generic_api_keys",
219
+ 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`
220
+ },
221
+ {
222
+ name: "openai_keys",
223
+ pattern: String.raw`\bsk[-_][a-zA-Z0-9]{20,}\b`
224
+ },
225
+ // AWS Keys
226
+ {
227
+ name: "aws_access_keys",
228
+ pattern: String.raw`\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b`
229
+ },
230
+ // GitHub tokens
231
+ {
232
+ name: "github_tokens",
233
+ pattern: String.raw`\bghp_[a-zA-Z0-9]{36}\b`
234
+ },
235
+ // Slack tokens
236
+ {
237
+ name: "slack_tokens",
238
+ pattern: String.raw`\bxox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24,34}\b`
239
+ },
240
+ // Stripe keys
241
+ {
242
+ name: "stripe_keys",
243
+ pattern: String.raw`\b(?:sk|pk)_(?:test|live)_[a-zA-Z0-9]{24,}\b`
244
+ },
245
+ // JWT tokens
246
+ {
247
+ name: "jwt_tokens",
248
+ pattern: String.raw`\beyJ[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\b`
249
+ },
250
+ // MAC addresses
251
+ {
252
+ name: "mac_addresses",
253
+ pattern: String.raw`\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b`
254
+ },
255
+ // IPv6 addresses
256
+ {
257
+ name: "ipv6_addresses",
258
+ pattern: String.raw`\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b`
259
+ },
260
+ // Bitcoin addresses
261
+ {
262
+ name: "bitcoin_addresses",
263
+ pattern: String.raw`\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b`
264
+ },
265
+ // Ethereum addresses
266
+ {
267
+ name: "ethereum_addresses",
268
+ pattern: String.raw`\b0x[a-fA-F0-9]{40}(?![a-fA-F0-9])\b`
269
+ },
270
+ // Database connection strings
271
+ {
272
+ name: "database_connections",
273
+ 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`
274
+ },
275
+ // Private keys
276
+ {
277
+ name: "rsa_private_keys",
278
+ pattern: "-----BEGIN (?:RSA )?PRIVATE KEY-----"
279
+ },
280
+ {
281
+ name: "pgp_private_keys",
282
+ pattern: "-----BEGIN PGP PRIVATE KEY BLOCK-----"
283
+ },
284
+ // Additional API Keys and Tokens
285
+ {
286
+ name: "google_oauth",
287
+ pattern: String.raw`\bya29\\.[a-zA-Z0-9_-]{60,}\b`
288
+ },
289
+ {
290
+ name: "firebase_tokens",
291
+ pattern: String.raw`\bAAAA[A-Za-z0-9_-]{100,}\b`
292
+ },
293
+ {
294
+ name: "google_app_ids",
295
+ pattern: String.raw`\b[0-9]+-\w+\.apps\.googleusercontent\.com\b`
296
+ },
297
+ {
298
+ name: "facebook_secrets",
299
+ 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]`
300
+ },
301
+ {
302
+ name: "github_keys",
303
+ 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]`
304
+ },
305
+ {
306
+ name: "heroku_keys",
307
+ 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\\-]`
308
+ },
309
+ {
310
+ name: "slack_api_keys",
311
+ 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]`
312
+ },
313
+ {
314
+ name: "slack_api_tokens",
315
+ pattern: String.raw`\b(xox[pb](?:-[a-zA-Z0-9]+){4,})\b`
316
+ },
317
+ // Extended Private Keys and Certificates
318
+ {
319
+ name: "dsa_private_keys",
320
+ pattern: String.raw`-----BEGIN DSA PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END DSA PRIVATE KEY-----`
321
+ },
322
+ {
323
+ name: "ec_private_keys",
324
+ pattern: String.raw`-----BEGIN (?:EC|ECDSA) PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END (?:EC|ECDSA) PRIVATE KEY-----`
325
+ },
326
+ {
327
+ name: "encrypted_private_keys",
328
+ pattern: String.raw`-----BEGIN ENCRYPTED PRIVATE KEY-----(?:.|\s)+?-----END ENCRYPTED PRIVATE KEY-----`
329
+ },
330
+ {
331
+ name: "ssl_certificates",
332
+ pattern: String.raw`-----BEGIN CERTIFICATE-----(?:.|\n)+?\s*-----END CERTIFICATE-----`
333
+ },
334
+ {
335
+ name: "ssh_dss_public",
336
+ pattern: String.raw`\bssh-dss [0-9A-Za-z+/]+[=]{2}\b`
337
+ },
338
+ {
339
+ name: "ssh_rsa_public",
340
+ pattern: String.raw`\bssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3} [^@]+@[^@]+\b`
341
+ },
342
+ {
343
+ name: "putty_ssh_keys",
344
+ pattern: String.raw`PuTTY-User-Key-File-2: ssh-(?:rsa|dss)\s*Encryption: none(?:.|\s?)*?Private-MAC:`
345
+ },
346
+ // Security and Network
347
+ {
348
+ name: "cve_numbers",
349
+ pattern: String.raw`\b[Cc][Vv][Ee]-\\d{4}-\\d{4,7}\b`
350
+ },
351
+ {
352
+ name: "microsoft_oauth",
353
+ pattern: String.raw`https://login\.microsoftonline\.com/common/oauth2/v2\.0/token|https://login\.windows\.net/common/oauth2/token`
354
+ },
355
+ {
356
+ name: "postgres_connections",
357
+ pattern: String.raw`\b(?:[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Pp][Gg][Ss][Qq][Ll])\\:\\/\\/`
358
+ },
359
+ {
360
+ name: "box_links",
361
+ pattern: String.raw`https://app\.box\.com/[s|l]/\S+`
362
+ },
363
+ {
364
+ name: "dropbox_links",
365
+ pattern: String.raw`https://www\.dropbox\.com/(?:s|l)/\S+`
366
+ },
367
+ // Credit Card Variants
368
+ {
369
+ name: "amex_cards",
370
+ pattern: String.raw`\b3[47][0-9]{13}\b`
371
+ },
372
+ {
373
+ name: "visa_cards",
374
+ pattern: String.raw`\b4[0-9]{12}(?:[0-9]{3})?\b`
375
+ },
376
+ {
377
+ name: "discover_cards",
378
+ pattern: String.raw`\b65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}\b`
379
+ }
380
+ ];
381
+
382
+ // src/internal/masking/utils.ts
383
+ function isValidPatternName(name) {
384
+ return /^[a-zA-Z0-9_]+$/.test(name);
385
+ }
386
+ function isLikelyReDoSPattern(pattern) {
387
+ const dangerousPatterns = [
388
+ // Nested quantifiers like (a+)+, (a*)+, (a+)*
389
+ /\([^)]*[+*]\)[+*]/,
390
+ // Overlapping alternation under an outer quantifier like (a|a)+, (\w|\d)+. Scoped to
391
+ // capturing groups so the lazy (?:…)+? built-ins aren't false-flagged.
392
+ /\((?!\?)[^)]*\|[^)]*\)[+*]/,
393
+ // Complex backtracking patterns - but more specific
394
+ /\([^)]*[+*][^)]*[+*][^)]*\)[+*]/
395
+ ];
396
+ return dangerousPatterns.some((dangerous) => dangerous.test(pattern));
397
+ }
398
+ function getGroupedPattern(patternEntry) {
399
+ let name = patternEntry.name;
400
+ if (!name || name === "") {
401
+ name = `pattern_${Math.random().toString(16).slice(2)}`;
402
+ }
403
+ if (!isValidPatternName(name)) {
404
+ throw new Error(
405
+ `Pattern name '${name}' must only contain alphanumeric characters and underscores`
406
+ );
407
+ }
408
+ if (isLikelyReDoSPattern(patternEntry.pattern)) {
409
+ throw new Error(`Potentially dangerous ReDoS pattern detected: '${patternEntry.pattern}'`);
410
+ }
411
+ try {
412
+ new RegExp(patternEntry.pattern);
413
+ } catch (error) {
414
+ throw new Error(`Invalid regex pattern '${patternEntry.pattern}': ${String(error)}`, {
415
+ cause: error
416
+ });
417
+ }
418
+ return `(?<${name}>${patternEntry.pattern})`;
419
+ }
420
+ function isIPatternEntry(obj) {
421
+ return typeof obj === "object" && obj !== null && typeof obj.pattern === "string" && (obj.name === void 0 || typeof obj.name === "string");
422
+ }
423
+ function isIEventMaskingRule(obj) {
424
+ return typeof obj === "object" && obj !== null && typeof obj.mode === "string" && Array.isArray(obj.patterns) && obj.patterns.every(
425
+ (p) => isIPatternEntry(p) || typeof p === "string"
426
+ ) && (obj.attributePattern === void 0 || typeof obj.attributePattern === "string");
427
+ }
428
+ function convertPatternsToPatternEntries(patterns) {
429
+ const patternEntries = [];
430
+ for (const pattern of patterns) {
431
+ if (typeof pattern === "string") {
432
+ patternEntries.push({ pattern, name: "" });
433
+ } else if (isIPatternEntry(pattern)) {
434
+ patternEntries.push(pattern);
435
+ } else {
436
+ throw new Error("Patterns must be either strings or PatternEntry instances");
437
+ }
438
+ }
439
+ return patternEntries;
440
+ }
441
+ function compilePatternEntries(patternEntries) {
442
+ const patternGroups = [];
443
+ for (const patternEntry of patternEntries) {
444
+ try {
445
+ patternGroups.push(getGroupedPattern(patternEntry));
446
+ } catch (error) {
447
+ _chunkJB6MA2RVcjs.logger.warn(`Invalid pattern '${patternEntry.name}': ${patternEntry.pattern}`, error);
448
+ continue;
449
+ }
450
+ }
451
+ if (patternGroups.length === 0) {
452
+ return null;
453
+ }
454
+ try {
455
+ return new RegExp(patternGroups.join("|"));
456
+ } catch (error) {
457
+ _chunkJB6MA2RVcjs.logger.warn("Failed to compile pattern entries into regex", error);
458
+ return null;
459
+ }
460
+ }
461
+ var compiledPatternCache = /* @__PURE__ */ new WeakMap();
462
+ function getCompiledPatternsForRule(rule) {
463
+ const key = rule.patterns;
464
+ if (compiledPatternCache.has(key)) {
465
+ return _nullishCoalesce(compiledPatternCache.get(key), () => ( null));
466
+ }
467
+ const compiled = compilePatternEntries(convertPatternsToPatternEntries(rule.patterns));
468
+ compiledPatternCache.set(key, compiled);
469
+ return compiled;
470
+ }
471
+ function getCompiledAttributeNamePattern(rule) {
472
+ if (!rule.attributePattern) {
473
+ _chunkJB6MA2RVcjs.logger.debug("No attribute pattern provided, using default .*");
474
+ return /.*/;
475
+ }
476
+ let compiledPatternString = rule.attributePattern;
477
+ if (isIEventMaskingRule(rule) && rule.eventNamePattern) {
478
+ compiledPatternString = `(${compiledPatternString})|(${rule.eventNamePattern})`;
479
+ }
480
+ return new RegExp(compiledPatternString);
481
+ }
482
+ function shouldContinueExecution(startTime, iterations, timeoutMs) {
483
+ if (Date.now() - startTime > timeoutMs) {
484
+ _chunkJB6MA2RVcjs.logger.warn("Regex execution timed out - potential ReDoS pattern detected");
485
+ return false;
486
+ }
487
+ const maxIterations = 1e3;
488
+ if (iterations > maxIterations) {
489
+ _chunkJB6MA2RVcjs.logger.warn("Regex execution exceeded maximum iterations - potential ReDoS pattern detected");
490
+ return false;
491
+ }
492
+ return true;
493
+ }
494
+ function createGlobalPattern(pattern) {
495
+ return new RegExp(
496
+ pattern.source,
497
+ pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g"
498
+ );
499
+ }
500
+ function executeRegexWithTimeout(pattern, value, timeoutMs = 100) {
501
+ const matches = [];
502
+ const globalPattern = createGlobalPattern(pattern);
503
+ const startTime = Date.now();
504
+ let match;
505
+ let iterations = 0;
506
+ while ((match = globalPattern.exec(value)) !== null) {
507
+ if (!shouldContinueExecution(startTime, ++iterations, timeoutMs)) {
508
+ break;
509
+ }
510
+ matches.push(match);
511
+ if (match[0].length === 0) {
512
+ globalPattern.lastIndex = match.index + 1;
513
+ }
514
+ }
515
+ return matches;
516
+ }
517
+ function maskStringByPattern(value, pattern, mode = "full") {
518
+ const matches = [];
519
+ try {
520
+ const regexMatches = executeRegexWithTimeout(pattern, value);
521
+ for (const match of regexMatches) {
522
+ matches.push({
523
+ start: match.index,
524
+ end: match.index + match[0].length,
525
+ text: match[0],
526
+ groups: match.groups
527
+ });
528
+ }
529
+ } catch (error) {
530
+ _chunkJB6MA2RVcjs.logger.warn("Regex execution failed, skipping masking", error);
531
+ return value;
532
+ }
533
+ for (const matchInfo of matches.toReversed()) {
534
+ let patternName = "unknown";
535
+ if (matchInfo.groups) {
536
+ const firstDefined = Object.entries(matchInfo.groups).find(
537
+ ([, groupValue]) => groupValue !== void 0
538
+ );
539
+ if (firstDefined) {
540
+ const [groupName] = firstDefined;
541
+ if (groupName.includes("_") && /\d$/.test(groupName)) {
542
+ const parts = groupName.split("_");
543
+ patternName = parts[0] || groupName;
544
+ } else {
545
+ patternName = groupName;
546
+ }
547
+ }
548
+ }
549
+ _chunkJB6MA2RVcjs.logger.info(`Masking detected: pattern '${patternName}' found match in value`);
550
+ const masked = mode === "partial" ? matchInfo.text.at(0) + "*****" : "*****";
551
+ value = value.slice(0, matchInfo.start) + masked + value.slice(matchInfo.end);
552
+ }
553
+ return value;
554
+ }
555
+ function maskStringByPatternBasedRule(value, rule) {
556
+ const patternEntries = convertPatternsToPatternEntries(rule.patterns);
557
+ if (patternEntries.length === 0) {
558
+ _chunkJB6MA2RVcjs.logger.warn("No patterns provided for masking rule, returning original value");
559
+ return value;
560
+ }
561
+ const mode = rule.mode;
562
+ if (!patternEntries || patternEntries.length === 0) {
563
+ return mode === "partial" && value ? value.at(0) + "*****" : "*****";
564
+ }
565
+ const compiledPatterns = getCompiledPatternsForRule(rule);
566
+ if (!compiledPatterns) {
567
+ return value;
568
+ }
569
+ return maskStringByPattern(value, compiledPatterns, mode);
570
+ }
571
+ function maskValue(value, rule) {
572
+ if (typeof value === "string") {
573
+ return maskStringByPatternBasedRule(value, rule);
574
+ }
575
+ if (typeof value === "boolean" || typeof value === "number") {
576
+ return maskStringByPatternBasedRule(String(value), rule);
577
+ }
578
+ if (Array.isArray(value)) {
579
+ return value.map((v) => maskStringByPatternBasedRule(String(v), rule));
580
+ }
581
+ if (value !== null && typeof value === "object") {
582
+ const result = {};
583
+ for (const [k, v] of Object.entries(value)) {
584
+ result[k] = maskValue(v, rule);
585
+ }
586
+ return result;
587
+ }
588
+ throw new Error(`Unsupported value type for masking: ${typeof value}`);
589
+ }
590
+ function maskAttributes(attributes, rules, outputOriginalValue = false) {
591
+ if (!attributes || Object.keys(attributes).length === 0) {
592
+ return {};
593
+ }
594
+ const maskedAttributes = { ...attributes };
595
+ for (const rule of rules) {
596
+ const compiledAttributeNamePattern = getCompiledAttributeNamePattern(rule);
597
+ const attributesToMask = compiledAttributeNamePattern ? Object.keys(maskedAttributes).filter((attr) => compiledAttributeNamePattern.test(attr)) : Object.keys(maskedAttributes);
598
+ for (const attribute of attributesToMask) {
599
+ const value = maskedAttributes[attribute];
600
+ if (value !== null && value !== void 0) {
601
+ if (outputOriginalValue) {
602
+ _chunkJB6MA2RVcjs.logger.debug(`Masking attribute '${attribute}' with original value`, { value });
603
+ }
604
+ maskedAttributes[attribute] = maskValue(value, rule);
605
+ }
606
+ }
607
+ }
608
+ return maskedAttributes;
609
+ }
610
+
611
+ // src/internal/log/processors/log-processor.ts
612
+ var DEFAULT_LOG_MASKING_RULES = [
613
+ {
614
+ mode: "partial",
615
+ attributePattern: "event.name",
616
+ patterns: DEFAULT_PII_PATTERNS
617
+ }
618
+ ];
619
+ var BrizzSimpleLogRecordProcessor = class extends _sdklogs.SimpleLogRecordProcessor {
620
+
621
+ constructor(exporter, config) {
622
+ super(exporter);
623
+ this.config = config;
624
+ }
625
+ onEmit(logRecord) {
626
+ const maskingConfig = _optionalChain([this, 'access', _27 => _27.config, 'access', _28 => _28.masking, 'optionalAccess', _29 => _29.eventMasking]);
627
+ if (maskingConfig) {
628
+ maskLog(logRecord, maskingConfig);
629
+ }
630
+ const associationProperties = _api.context.active().getValue(_chunkGCORRK6Bcjs.PROPERTIES_CONTEXT_KEY);
631
+ if (associationProperties) {
632
+ for (const [key, value] of Object.entries(associationProperties)) {
633
+ logRecord.setAttribute(`${_chunkGCORRK6Bcjs.BRIZZ}.${key}`, value);
634
+ }
635
+ }
636
+ super.onEmit(logRecord);
637
+ }
638
+ };
639
+ var BrizzBatchLogRecordProcessor = class extends _sdklogs.BatchLogRecordProcessor {
640
+
641
+ constructor(exporter, config) {
642
+ super(exporter);
643
+ this.config = config;
644
+ }
645
+ onEmit(logRecord) {
646
+ const maskingConfig = _optionalChain([this, 'access', _30 => _30.config, 'access', _31 => _31.masking, 'optionalAccess', _32 => _32.eventMasking]);
647
+ if (maskingConfig) {
648
+ maskLog(logRecord, maskingConfig);
649
+ }
650
+ const associationProperties = _api.context.active().getValue(_chunkGCORRK6Bcjs.PROPERTIES_CONTEXT_KEY);
651
+ if (associationProperties) {
652
+ for (const [key, value] of Object.entries(associationProperties)) {
653
+ logRecord.setAttribute(`${_chunkGCORRK6Bcjs.BRIZZ}.${key}`, value);
654
+ }
655
+ }
656
+ super.onEmit(logRecord);
657
+ }
658
+ };
659
+ function maskLog(logRecord, config) {
660
+ if (!logRecord.attributes) {
661
+ return logRecord;
662
+ }
663
+ let rules = config.rules || [];
664
+ if (!config.disableDefaultRules) {
665
+ rules = [...DEFAULT_LOG_MASKING_RULES, ...rules];
666
+ }
667
+ try {
668
+ if (logRecord.attributes && Object.keys(logRecord.attributes).length > 0) {
669
+ const attributesRecord = {};
670
+ for (const [key, value] of Object.entries(logRecord.attributes)) {
671
+ attributesRecord[key] = value;
672
+ }
673
+ const maskedAttributes = maskAttributes(attributesRecord, rules);
674
+ if (maskedAttributes) {
675
+ const newAttributes = {};
676
+ for (const [key, value] of Object.entries(maskedAttributes)) {
677
+ newAttributes[key] = value;
678
+ }
679
+ for (const [key, value] of Object.entries(logRecord.attributes)) {
680
+ if (key.startsWith(_chunkGCORRK6Bcjs.INTERNAL_EVENT_PREFIX)) {
681
+ newAttributes[key] = value;
682
+ }
683
+ }
684
+ logRecord.setAttributes(newAttributes);
685
+ }
686
+ }
687
+ if (config.maskBody && logRecord.body !== void 0 && logRecord.body !== null) {
688
+ let maskedBody = logRecord.body;
689
+ for (const rule of rules) {
690
+ maskedBody = maskValue(maskedBody, rule);
691
+ }
692
+ logRecord.setBody(maskedBody);
693
+ }
694
+ return logRecord;
695
+ } catch (error) {
696
+ _chunkJB6MA2RVcjs.logger.error("Error masking log record:", error);
697
+ return logRecord;
698
+ }
699
+ }
700
+
701
+ // src/internal/log/logging.ts
702
+ var LoggingModule = (_class2 = class _LoggingModule {constructor() { _class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this); }
703
+ static __initStatic() {this.instance = null}
704
+ static getInstance() {
705
+ if (!this.instance) {
706
+ throw new Error("Brizz must be initialized before accessing LoggingModule");
707
+ }
708
+ return this.instance;
709
+ }
710
+ __init2() {this.logExporter = null}
711
+ __init3() {this.logProcessor = null}
712
+ __init4() {this.loggerProvider = null}
713
+ /**
714
+ * Initialize the log exporter
715
+ */
716
+ initLogExporter(config) {
717
+ if (this.logExporter) {
718
+ _chunkJB6MA2RVcjs.logger.debug("Log exporter already initialized, skipping re-initialization");
719
+ return;
720
+ }
721
+ if (config.customLogExporter) {
722
+ _chunkJB6MA2RVcjs.logger.debug("Using custom log exporter");
723
+ this.logExporter = config.customLogExporter;
724
+ _chunkJB6MA2RVcjs.logger.debug("Custom log exporter initialized successfully");
725
+ return;
726
+ }
727
+ const logsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/logs";
728
+ _chunkJB6MA2RVcjs.logger.debug("Initializing default OTLP log exporter", { url: logsUrl });
729
+ const headers = { ...config.headers };
730
+ this.logExporter = new (0, _exporterlogsotlphttp.OTLPLogExporter)({
731
+ url: logsUrl,
732
+ headers
733
+ });
734
+ _chunkJB6MA2RVcjs.logger.debug("OTLP log exporter initialized successfully");
735
+ }
736
+ /**
737
+ * Initialize the log processor with masking support
738
+ */
739
+ initLogProcessor(config) {
740
+ if (this.logProcessor) {
741
+ _chunkJB6MA2RVcjs.logger.debug("Log processor already initialized, skipping re-initialization");
742
+ return;
743
+ }
744
+ if (!this.logExporter) {
745
+ throw new Error("Log exporter must be initialized before processor");
746
+ }
747
+ _chunkJB6MA2RVcjs.logger.debug("Initializing log processor", {
748
+ disableBatch: config.disableBatch,
749
+ hasMasking: !!_optionalChain([config, 'access', _33 => _33.masking, 'optionalAccess', _34 => _34.eventMasking])
750
+ });
751
+ this.logProcessor = config.disableBatch ? new BrizzSimpleLogRecordProcessor(this.logExporter, config) : new BrizzBatchLogRecordProcessor(this.logExporter, config);
752
+ _chunkJB6MA2RVcjs.logger.debug("Log processor initialized successfully");
753
+ }
754
+ /**
755
+ * Initialize the logger provider
756
+ */
757
+ initLoggerProvider(config) {
758
+ if (this.loggerProvider) {
759
+ _chunkJB6MA2RVcjs.logger.debug("Logger provider already initialized, skipping re-initialization");
760
+ return;
761
+ }
762
+ if (!this.logProcessor) {
763
+ throw new Error("Log processor must be initialized before logger provider");
764
+ }
765
+ _chunkJB6MA2RVcjs.logger.debug("Creating resource with service name", {
766
+ serviceName: config.appName
767
+ });
768
+ const resourceAttributes = {
769
+ ...config.resourceAttributes,
770
+ "service.name": config.appName,
771
+ [BRIZZ_SDK_VERSION]: _chunkJB6MA2RVcjs.getSDKVersion.call(void 0, ),
772
+ [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
773
+ };
774
+ if (config.environment) {
775
+ resourceAttributes["deployment.environment"] = config.environment;
776
+ }
777
+ if (config.appVersion) {
778
+ resourceAttributes["service.version"] = config.appVersion;
779
+ }
780
+ const resource = _resources.resourceFromAttributes.call(void 0, resourceAttributes);
781
+ _chunkJB6MA2RVcjs.logger.debug("Creating logger provider with resource");
782
+ this.loggerProvider = new (0, _sdklogs.LoggerProvider)({
783
+ resource,
784
+ processors: [this.logProcessor]
785
+ });
786
+ _chunkJB6MA2RVcjs.logger.debug("Logger provider initialization completed");
787
+ }
788
+ /**
789
+ * Initialize the logging module with the provided configuration
790
+ */
791
+ setup(config) {
792
+ _chunkJB6MA2RVcjs.logger.info("Setting up logging module");
793
+ this.initLogExporter(config);
794
+ this.initLogProcessor(config);
795
+ this.initLoggerProvider(config);
796
+ _LoggingModule.instance = this;
797
+ _chunkJB6MA2RVcjs.logger.info("Logging module setup completed");
798
+ }
799
+ /**
800
+ * Emit a custom event to the telemetry pipeline
801
+ */
802
+ emitEvent(name, attributes, body, severityNumber = _apilogs.SeverityNumber.INFO) {
803
+ _chunkJB6MA2RVcjs.logger.debug("Attempting to emit event", {
804
+ name,
805
+ hasAttributes: !!attributes,
806
+ attributesCount: attributes ? Object.keys(attributes).length : 0,
807
+ hasBody: !!body,
808
+ severityNumber
809
+ });
810
+ if (!this.loggerProvider) {
811
+ _chunkJB6MA2RVcjs.logger.error("Cannot emit event: Logger provider not initialized");
812
+ throw new Error("Logging module not initialized");
813
+ }
814
+ const logAttributes = { "event.name": name };
815
+ if (attributes) {
816
+ Object.assign(logAttributes, attributes);
817
+ _chunkJB6MA2RVcjs.logger.debug("Combined log attributes", { attributes: Object.keys(logAttributes) });
818
+ }
819
+ _chunkJB6MA2RVcjs.logger.debug("Getting logger instance for brizz_events");
820
+ const eventLogger = this.loggerProvider.getLogger("brizz.events");
821
+ _chunkJB6MA2RVcjs.logger.debug("Emitting log record with eventName", { eventName: name });
822
+ try {
823
+ eventLogger.emit({
824
+ eventName: name,
825
+ attributes: logAttributes,
826
+ severityNumber,
827
+ body
828
+ });
829
+ _chunkJB6MA2RVcjs.logger.debug("Event successfully emitted", { eventName: name });
830
+ } catch (error) {
831
+ _chunkJB6MA2RVcjs.logger.error(`Failed to emit event '${name}'`, { error, eventName: name });
832
+ _chunkJB6MA2RVcjs.logger.error("Log record that failed", {
833
+ eventName: name,
834
+ hasAttributes: logAttributes,
835
+ severityNumber,
836
+ hasBody: body
837
+ });
838
+ throw error instanceof Error ? error : new Error(String(error));
839
+ }
840
+ }
841
+ /**
842
+ * Check if the module is initialized
843
+ */
844
+ isInitialized() {
845
+ return this.loggerProvider !== null;
846
+ }
847
+ /**
848
+ * Get the logger provider
849
+ */
850
+ getLoggerProvider() {
851
+ return this.loggerProvider;
852
+ }
853
+ /**
854
+ * Shutdown the logging module
855
+ */
856
+ async shutdown() {
857
+ _chunkJB6MA2RVcjs.logger.debug("Shutting down logging module");
858
+ if (this.loggerProvider) {
859
+ await this.loggerProvider.shutdown();
860
+ this.loggerProvider = null;
861
+ }
862
+ this.logProcessor = null;
863
+ this.logExporter = null;
864
+ if (_LoggingModule.instance === this) {
865
+ _LoggingModule.instance = null;
866
+ }
867
+ _chunkJB6MA2RVcjs.logger.debug("Logging module shutdown completed");
868
+ }
869
+ }, _class2.__initStatic(), _class2);
870
+ function emitEvent(name, attributes, body, severityNumber = _apilogs.SeverityNumber.INFO) {
871
+ return LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
872
+ }
873
+ function emitEventWithSessionId(sessionId, name, attributes, body, severityNumber = _apilogs.SeverityNumber.INFO) {
874
+ return callWithSessionId(sessionId, () => {
875
+ LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
876
+ });
877
+ }
878
+
879
+ // src/internal/trace/session.ts
880
+ function setCurrentSpanCustomProperties(properties) {
881
+ const current = _api.trace.getActiveSpan();
882
+ if (!current || !current.isRecording()) {
883
+ return;
884
+ }
885
+ for (const [key, value] of Object.entries(properties)) {
886
+ try {
887
+ current.setAttribute(`${_chunkGCORRK6Bcjs.BRIZZ}.${key}`, value);
888
+ } catch (e) {
889
+ }
890
+ }
891
+ }
892
+ function callWithProperties(properties, fn, thisArg, ...args) {
893
+ const base = _api.context.active();
894
+ const prev = base.getValue(_chunkGCORRK6Bcjs.PROPERTIES_CONTEXT_KEY);
895
+ const merged = prev ? { ...prev, ...properties } : properties;
896
+ const next = base.setValue(_chunkGCORRK6Bcjs.PROPERTIES_CONTEXT_KEY, merged);
897
+ return _api.context.with(next, fn, thisArg, ...args);
898
+ }
899
+ function withProperties(properties, fn, thisArg) {
900
+ return function wrapped(...args) {
901
+ return callWithProperties(
902
+ properties,
903
+ fn,
904
+ thisArg !== void 0 ? thisArg : this,
905
+ ...args
906
+ );
907
+ };
908
+ }
909
+ function muteProperties(options) {
910
+ const { input = true, output = true } = options;
911
+ const properties = {};
912
+ if (input) {
913
+ properties[_chunkGCORRK6Bcjs.MUTE_INPUT] = "true";
914
+ }
915
+ if (output) {
916
+ properties[_chunkGCORRK6Bcjs.MUTE_OUTPUT] = "true";
917
+ }
918
+ return properties;
919
+ }
920
+ function callWithMute(options, fn, thisArg, ...args) {
921
+ return callWithProperties(muteProperties(options), fn, thisArg, ...args);
922
+ }
923
+ function withMute(options, fn, thisArg) {
924
+ return withProperties(muteProperties(options), fn, thisArg);
925
+ }
926
+ function withSessionId(sessionId, fn, thisArg, extraProperties) {
927
+ const properties = { [_chunkGCORRK6Bcjs.SESSION_ID]: sessionId, ...extraProperties };
928
+ return withProperties(properties, fn, thisArg);
929
+ }
930
+ function callWithSessionId(sessionId, fn, thisArg, ...args) {
931
+ return callWithProperties({ [_chunkGCORRK6Bcjs.SESSION_ID]: sessionId }, fn, thisArg, ...args);
932
+ }
933
+ var Session = (_class3 = class {
934
+
935
+ __init5() {this.inputs = []}
936
+ __init6() {this.outputs = []}
937
+ __init7() {this.inputContexts = []}
938
+ __init8() {this.outputContexts = []}
939
+
940
+ constructor(sessionId, span) {;_class3.prototype.__init5.call(this);_class3.prototype.__init6.call(this);_class3.prototype.__init7.call(this);_class3.prototype.__init8.call(this);
941
+ this.sessionId = sessionId;
942
+ this.span = span;
943
+ }
944
+ /**
945
+ * Append a user turn to session input tracking.
946
+ *
947
+ * Each call appends one element to `brizz.session.input` (the text) AND one
948
+ * element to `brizz.session.input.context` (the per-turn context bag). The
949
+ * two arrays stay index-aligned — the ingestion pipeline zips them together
950
+ * so the i-th context bag lands on the i-th user_display conversation item's
951
+ * `span_attributes` map.
952
+ *
953
+ * @param text - Text to append (null becomes a null/"hide marker")
954
+ * @param context - Optional per-turn context bag to attach to this turn
955
+ */
956
+ setInput(text, context4) {
957
+ this.inputs.push(text);
958
+ this.inputContexts.push(_nullishCoalesce(context4, () => ( {})));
959
+ this.span.setAttribute(_chunkGCORRK6Bcjs.SESSION_INPUT, JSON.stringify(this.inputs));
960
+ this.span.setAttribute(_chunkGCORRK6Bcjs.SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));
961
+ }
962
+ /**
963
+ * Append an assistant turn to session output tracking.
964
+ *
965
+ * Symmetric to {@link setInput} — appends one text element and one
966
+ * context-bag element to the index-aligned `brizz.session.output` /
967
+ * `brizz.session.output.context` arrays.
968
+ *
969
+ * @param text - Text to append (null becomes a null/"hide marker")
970
+ * @param context - Optional per-turn context bag to attach to this turn
971
+ */
972
+ setOutput(text, context4) {
973
+ this.outputs.push(text);
974
+ this.outputContexts.push(_nullishCoalesce(context4, () => ( {})));
975
+ this.span.setAttribute(_chunkGCORRK6Bcjs.SESSION_OUTPUT, JSON.stringify(this.outputs));
976
+ this.span.setAttribute(_chunkGCORRK6Bcjs.SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));
977
+ }
978
+ /**
979
+ * Set the session title on the span.
980
+ *
981
+ * @param title - The generated title string
982
+ */
983
+ setTitle(title) {
984
+ this.span.setAttribute(_chunkGCORRK6Bcjs.SESSION_TITLE, title);
985
+ }
986
+ /**
987
+ * Update custom properties on the session span.
988
+ * Properties are prefixed with 'brizz.'.
989
+ *
990
+ * @param properties - Key-value properties to set on the session
991
+ */
992
+ updateProperties(properties) {
993
+ for (const [key, value] of Object.entries(properties)) {
994
+ this.span.setAttribute(`${_chunkGCORRK6Bcjs.BRIZZ}.${key}`, value);
995
+ }
996
+ }
997
+ /**
998
+ * Attach an external link (URL) to this session.
999
+ *
1000
+ * The link surfaces on the session's detail panel in Brizz — use it to
1001
+ * correlate a session with an external record such as a Datadog trace,
1002
+ * Sentry issue, or internal dashboard. Re-sending the same URL is idempotent;
1003
+ * distinct URLs add separate links.
1004
+ *
1005
+ * @param url - The link target
1006
+ * @param options - Optional `title` (defaults to the URL host) and `linkType`
1007
+ * (free-form category, defaults to `'generic'`)
1008
+ */
1009
+ addExternalLink(url, options) {
1010
+ emitExternalLink(this.sessionId, url, _optionalChain([options, 'optionalAccess', _35 => _35.title]), _optionalChain([options, 'optionalAccess', _36 => _36.linkType]));
1011
+ }
1012
+ }, _class3);
1013
+ var SessionTitle = class {
1014
+
1015
+ constructor(span) {
1016
+ this.span = span;
1017
+ }
1018
+ /**
1019
+ * Set the generated title on the wrapper span.
1020
+ *
1021
+ * @param title - The generated title string
1022
+ */
1023
+ setTitle(title) {
1024
+ this.span.setAttribute(_chunkGCORRK6Bcjs.SESSION_TITLE, title);
1025
+ }
1026
+ };
1027
+ function getActiveSession() {
1028
+ return _api.context.active().getValue(_chunkGCORRK6Bcjs.SESSION_OBJECT_CONTEXT_KEY);
1029
+ }
1030
+ function resolveSessionIdFromContext() {
1031
+ const active = getActiveSession();
1032
+ if (active) {
1033
+ return active.sessionId;
1034
+ }
1035
+ const props = _api.context.active().getValue(_chunkGCORRK6Bcjs.PROPERTIES_CONTEXT_KEY);
1036
+ return _optionalChain([props, 'optionalAccess', _37 => _37[_chunkGCORRK6Bcjs.SESSION_ID]]);
1037
+ }
1038
+ function emitExternalLink(sessionId, url, title, linkType) {
1039
+ try {
1040
+ emitEventWithSessionId(sessionId, _chunkGCORRK6Bcjs.EXTERNAL_LINK_EVENT_NAME, {
1041
+ [_chunkGCORRK6Bcjs.EXTERNAL_LINK_URL]: url,
1042
+ [_chunkGCORRK6Bcjs.EXTERNAL_LINK_TITLE]: _nullishCoalesce(title, () => ( "")),
1043
+ [_chunkGCORRK6Bcjs.EXTERNAL_LINK_TYPE]: _nullishCoalesce(linkType, () => ( "generic"))
1044
+ });
1045
+ } catch (error) {
1046
+ _chunkJB6MA2RVcjs.logger.warn("addExternalLink: failed to emit external link", error);
1047
+ }
1048
+ }
1049
+ function addExternalLink(url, options) {
1050
+ const sessionId = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _38 => _38.sessionId]), () => ( resolveSessionIdFromContext()));
1051
+ if (!sessionId) {
1052
+ _chunkJB6MA2RVcjs.logger.warn(
1053
+ "addExternalLink called without a resolvable session id; link dropped. Pass options.sessionId or call inside a startSession/callWithSessionId scope."
1054
+ );
1055
+ return;
1056
+ }
1057
+ emitExternalLink(sessionId, url, _optionalChain([options, 'optionalAccess', _39 => _39.title]), _optionalChain([options, 'optionalAccess', _40 => _40.linkType]));
1058
+ }
1059
+ function startSession(sessionId, callback, extraProperties, options) {
1060
+ const isTitle = _optionalChain([options, 'optionalAccess', _41 => _41.mode]) === "title";
1061
+ const spanName = isTitle ? _chunkGCORRK6Bcjs.SESSION_TITLE_SPAN_NAME : _chunkGCORRK6Bcjs.SESSION_SPAN_NAME;
1062
+ const tracer = _api.trace.getTracer("@brizz/sdk");
1063
+ return tracer.startActiveSpan(spanName, (span) => {
1064
+ span.setAttribute(`${_chunkGCORRK6Bcjs.BRIZZ}.${_chunkGCORRK6Bcjs.SESSION_ID}`, sessionId);
1065
+ if (extraProperties) {
1066
+ for (const [key, value] of Object.entries(extraProperties)) {
1067
+ span.setAttribute(`${_chunkGCORRK6Bcjs.BRIZZ}.${key}`, value);
1068
+ }
1069
+ }
1070
+ const session = new Session(sessionId, span);
1071
+ const contextProperties = { [_chunkGCORRK6Bcjs.SESSION_ID]: sessionId };
1072
+ if (isTitle) {
1073
+ contextProperties[_chunkGCORRK6Bcjs.SESSION_TITLE_GENERATION] = "true";
1074
+ }
1075
+ if (extraProperties) {
1076
+ for (const [key, value] of Object.entries(extraProperties)) {
1077
+ contextProperties[key] = String(value);
1078
+ }
1079
+ }
1080
+ return callWithProperties(contextProperties, () => {
1081
+ const sessionCtx = _api.context.active().setValue(_chunkGCORRK6Bcjs.SESSION_OBJECT_CONTEXT_KEY, session);
1082
+ return _api.context.with(sessionCtx, () => {
1083
+ try {
1084
+ const result = callback(session);
1085
+ if (result && typeof result.then === "function") {
1086
+ return result.then((value) => {
1087
+ span.end();
1088
+ return value;
1089
+ }).catch((error) => {
1090
+ span.recordException(error);
1091
+ span.setStatus({ code: _api.SpanStatusCode.ERROR });
1092
+ span.end();
1093
+ throw error;
1094
+ });
1095
+ }
1096
+ span.end();
1097
+ return result;
1098
+ } catch (error) {
1099
+ span.recordException(error);
1100
+ span.setStatus({ code: _api.SpanStatusCode.ERROR });
1101
+ span.end();
1102
+ throw error;
1103
+ }
1104
+ });
1105
+ });
1106
+ });
1107
+ }
1108
+ function startSessionTitle(callback, options) {
1109
+ const resolvedSessionId = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _42 => _42.sessionId]), () => ( _optionalChain([getActiveSession, 'call', _43 => _43(), 'optionalAccess', _44 => _44.sessionId])));
1110
+ const tracer = _api.trace.getTracer("@brizz/sdk");
1111
+ return tracer.startActiveSpan(_chunkGCORRK6Bcjs.SESSION_TITLE_SPAN_NAME, (span) => {
1112
+ if (resolvedSessionId) {
1113
+ span.setAttribute(`${_chunkGCORRK6Bcjs.BRIZZ}.${_chunkGCORRK6Bcjs.SESSION_ID}`, resolvedSessionId);
1114
+ }
1115
+ const sessionTitle = new SessionTitle(span);
1116
+ const properties = { [_chunkGCORRK6Bcjs.SESSION_TITLE_GENERATION]: "true" };
1117
+ if (resolvedSessionId) {
1118
+ properties[_chunkGCORRK6Bcjs.SESSION_ID] = resolvedSessionId;
1119
+ }
1120
+ return callWithProperties(properties, () => {
1121
+ try {
1122
+ const result = callback(sessionTitle);
1123
+ if (result && typeof result.then === "function") {
1124
+ return result.then((value) => {
1125
+ span.end();
1126
+ return value;
1127
+ }).catch((error) => {
1128
+ span.recordException(error);
1129
+ span.setStatus({ code: _api.SpanStatusCode.ERROR });
1130
+ span.end();
1131
+ throw error;
1132
+ });
1133
+ }
1134
+ span.end();
1135
+ return result;
1136
+ } catch (error) {
1137
+ span.recordException(error);
1138
+ span.setStatus({ code: _api.SpanStatusCode.ERROR });
1139
+ span.end();
1140
+ throw error;
1141
+ }
1142
+ });
1143
+ });
1144
+ }
1145
+
1146
+ // src/internal/metric/metrics.ts
1147
+ var _exportermetricsotlphttp = require('@opentelemetry/exporter-metrics-otlp-http');
1148
+ var _sdkmetrics = require('@opentelemetry/sdk-metrics');
1149
+ var MetricsModule = (_class4 = class _MetricsModule {constructor() { _class4.prototype.__init9.call(this);_class4.prototype.__init10.call(this); }
1150
+ static __initStatic2() {this.instance = null}
1151
+ static getInstance() {
1152
+ if (!this.instance) {
1153
+ throw new Error("Brizz must be initialized before accessing MetricsModule");
1154
+ }
1155
+ return this.instance;
1156
+ }
1157
+ __init9() {this.metricsExporter = null}
1158
+ __init10() {this.metricsReader = null}
1159
+ /**
1160
+ * Initialize the metrics exporter
1161
+ */
1162
+ initMetricsExporter(config) {
1163
+ if (this.metricsExporter) {
1164
+ _chunkJB6MA2RVcjs.logger.debug("Metrics exporter already initialized, skipping re-initialization");
1165
+ return;
1166
+ }
1167
+ const metricsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/metrics";
1168
+ _chunkJB6MA2RVcjs.logger.debug("Initializing metrics exporter", { url: metricsUrl });
1169
+ this.metricsExporter = new (0, _exportermetricsotlphttp.OTLPMetricExporter)({
1170
+ url: metricsUrl,
1171
+ headers: config.headers
1172
+ });
1173
+ _chunkJB6MA2RVcjs.logger.debug("Metrics exporter initialized successfully");
1174
+ }
1175
+ /**
1176
+ * Initialize the metrics reader
1177
+ */
1178
+ initMetricsReader(config) {
1179
+ if (this.metricsReader) {
1180
+ _chunkJB6MA2RVcjs.logger.debug("Metrics reader already initialized, skipping re-initialization");
1181
+ return;
1182
+ }
1183
+ if (config.customMetricReader) {
1184
+ _chunkJB6MA2RVcjs.logger.debug("Using custom metric reader");
1185
+ this.metricsReader = config.customMetricReader;
1186
+ _chunkJB6MA2RVcjs.logger.debug("Custom metric reader initialized successfully");
1187
+ return;
1188
+ }
1189
+ _chunkJB6MA2RVcjs.logger.debug(
1190
+ "Using default metrics flow - creating OTLP exporter and PeriodicExportingMetricReader"
1191
+ );
1192
+ this.initMetricsExporter(config);
1193
+ if (!this.metricsExporter) {
1194
+ throw new Error("Failed to initialize metrics exporter");
1195
+ }
1196
+ this.metricsReader = new (0, _sdkmetrics.PeriodicExportingMetricReader)({
1197
+ exporter: this.metricsExporter
1198
+ });
1199
+ _chunkJB6MA2RVcjs.logger.debug("Default metrics reader initialized successfully");
1200
+ }
1201
+ /**
1202
+ * Initialize the metrics module with the provided configuration
1203
+ */
1204
+ setup(config) {
1205
+ _chunkJB6MA2RVcjs.logger.info("Setting up metrics module");
1206
+ this.initMetricsReader(config);
1207
+ _MetricsModule.instance = this;
1208
+ _chunkJB6MA2RVcjs.logger.info("Metrics module setup completed");
1209
+ }
1210
+ /**
1211
+ * Get the metrics exporter
1212
+ */
1213
+ getMetricsExporter() {
1214
+ if (!this.metricsExporter) {
1215
+ throw new Error("Metrics module not initialized");
1216
+ }
1217
+ return this.metricsExporter;
1218
+ }
1219
+ /**
1220
+ * Get the metrics reader
1221
+ */
1222
+ getMetricsReader() {
1223
+ if (!this.metricsReader) {
1224
+ throw new Error("Metrics module not initialized");
1225
+ }
1226
+ return this.metricsReader;
1227
+ }
1228
+ /**
1229
+ * Shutdown the metrics module
1230
+ */
1231
+ shutdown() {
1232
+ _chunkJB6MA2RVcjs.logger.debug("Shutting down metrics module");
1233
+ this.metricsReader = null;
1234
+ this.metricsExporter = null;
1235
+ if (_MetricsModule.instance === this) {
1236
+ _MetricsModule.instance = null;
1237
+ }
1238
+ _chunkJB6MA2RVcjs.logger.debug("Metrics module shutdown completed");
1239
+ }
1240
+ }, _class4.__initStatic2(), _class4);
1241
+ function getMetricsExporter() {
1242
+ return MetricsModule.getInstance().getMetricsExporter();
1243
+ }
1244
+ function getMetricsReader() {
1245
+ return MetricsModule.getInstance().getMetricsReader();
1246
+ }
1247
+
1248
+ // src/internal/trace/tracing.ts
1249
+ var _exportertraceotlpproto = require('@opentelemetry/exporter-trace-otlp-proto');
1250
+
1251
+ // src/internal/trace/exporters/span-exporter.ts
1252
+ var _core = require('@opentelemetry/core');
1253
+
1254
+ var BrizzSpanExporter = class {
1255
+
1256
+
1257
+
1258
+ constructor(delegate, config) {
1259
+ this._delegate = delegate;
1260
+ const resourceAttrs = {
1261
+ ...config.resourceAttributes,
1262
+ "service.name": config.appName,
1263
+ [BRIZZ_SDK_VERSION]: _chunkJB6MA2RVcjs.getSDKVersion.call(void 0, ),
1264
+ [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
1265
+ };
1266
+ if (config.environment) {
1267
+ resourceAttrs["deployment.environment"] = config.environment;
1268
+ }
1269
+ if (config.appVersion) {
1270
+ resourceAttrs["service.version"] = config.appVersion;
1271
+ }
1272
+ this._brizzResource = _resources.resourceFromAttributes.call(void 0, resourceAttrs);
1273
+ this._beforeSendSpan = config.beforeSendSpan;
1274
+ }
1275
+ export(spans, resultCallback) {
1276
+ if (spans.length === 0) {
1277
+ resultCallback({ code: _core.ExportResultCode.SUCCESS });
1278
+ return;
1279
+ }
1280
+ const patchedSpans = spans.map((span) => ({
1281
+ ...span,
1282
+ resource: span.resource.merge(this._brizzResource),
1283
+ spanContext: span.spanContext.bind(span)
1284
+ }));
1285
+ const filter = this._beforeSendSpan;
1286
+ if (!filter) {
1287
+ this._delegate.export(patchedSpans, resultCallback);
1288
+ return;
1289
+ }
1290
+ const verdicts = patchedSpans.map((span) => {
1291
+ try {
1292
+ return Promise.resolve(filter(span));
1293
+ } catch (error) {
1294
+ _chunkJB6MA2RVcjs.logger.warn("beforeSendSpan threw; span will be kept", { error });
1295
+ return Promise.resolve(true);
1296
+ }
1297
+ });
1298
+ Promise.all(verdicts).then((keep) => {
1299
+ const filtered = patchedSpans.filter((_, i) => keep[i] !== false);
1300
+ if (filtered.length === 0) {
1301
+ resultCallback({ code: _core.ExportResultCode.SUCCESS });
1302
+ return;
1303
+ }
1304
+ this._delegate.export(filtered, resultCallback);
1305
+ return;
1306
+ }).catch((error) => {
1307
+ _chunkJB6MA2RVcjs.logger.warn("beforeSendSpan rejected; all spans will be kept", { error });
1308
+ this._delegate.export(patchedSpans, resultCallback);
1309
+ });
1310
+ }
1311
+ async shutdown() {
1312
+ return this._delegate.shutdown();
1313
+ }
1314
+ async forceFlush() {
1315
+ return _optionalChain([this, 'access', _45 => _45._delegate, 'access', _46 => _46.forceFlush, 'optionalCall', _47 => _47()]);
1316
+ }
1317
+ };
1318
+
1319
+ // src/internal/trace/processors/span-processor.ts
1320
+
1321
+
1322
+
1323
+
1324
+ var _sdktracebase = require('@opentelemetry/sdk-trace-base');
1325
+ function applyContextAttributes(span) {
1326
+ const sessionProperties = _api.context.active().getValue(_chunkGCORRK6Bcjs.PROPERTIES_CONTEXT_KEY);
1327
+ if (sessionProperties) {
1328
+ for (const [key, value] of Object.entries(sessionProperties)) {
1329
+ span.setAttribute(`${_chunkGCORRK6Bcjs.BRIZZ}.${key}`, value);
1330
+ }
1331
+ }
1332
+ }
1333
+ var DEFAULT_MASKING_RULES = [
1334
+ {
1335
+ mode: "partial",
1336
+ patterns: DEFAULT_PII_PATTERNS
1337
+ }
1338
+ ];
1339
+ var BrizzSimpleSpanProcessor = class extends _sdktracebase.SimpleSpanProcessor {
1340
+
1341
+ constructor(spanExporter, config) {
1342
+ super(spanExporter);
1343
+ this.config = config;
1344
+ }
1345
+ onStart(span, parentContext) {
1346
+ applyContextAttributes(span);
1347
+ super.onStart(span, parentContext);
1348
+ }
1349
+ onEnd(span) {
1350
+ const maskingConfig = _optionalChain([this, 'access', _48 => _48.config, 'access', _49 => _49.masking, 'optionalAccess', _50 => _50.spanMasking]);
1351
+ if (maskingConfig) {
1352
+ maskReadableSpan(span, maskingConfig);
1353
+ }
1354
+ super.onEnd(span);
1355
+ }
1356
+ };
1357
+ var BrizzBatchSpanProcessor = class extends _sdktracebase.BatchSpanProcessor {
1358
+
1359
+ constructor(spanExporter, config) {
1360
+ super(spanExporter);
1361
+ this.config = config;
1362
+ }
1363
+ onStart(span, parentContext) {
1364
+ applyContextAttributes(span);
1365
+ super.onStart(span, parentContext);
1366
+ }
1367
+ onEnd(span) {
1368
+ const maskingConfig = _optionalChain([this, 'access', _51 => _51.config, 'access', _52 => _52.masking, 'optionalAccess', _53 => _53.spanMasking]);
1369
+ if (maskingConfig) {
1370
+ maskReadableSpan(span, maskingConfig);
1371
+ }
1372
+ super.onEnd(span);
1373
+ }
1374
+ };
1375
+ function maskReadableSpan(span, config) {
1376
+ const attrs = span.attributes;
1377
+ if (!attrs || Object.keys(attrs).length === 0) {
1378
+ return;
1379
+ }
1380
+ let rules = config.rules ? [...config.rules] : [];
1381
+ if (!config.disableDefaultRules) {
1382
+ rules = [...rules, ...DEFAULT_MASKING_RULES];
1383
+ }
1384
+ try {
1385
+ const input = {};
1386
+ for (const [k, v] of Object.entries(attrs)) {
1387
+ input[k] = v;
1388
+ }
1389
+ const masked = maskAttributes(input, rules);
1390
+ const maskedEntries = Object.entries(_nullishCoalesce(masked, () => ( {})));
1391
+ for (const [k, v] of maskedEntries) {
1392
+ if (attrs[k] !== v) {
1393
+ attrs[k] = v;
1394
+ }
1395
+ }
1396
+ } catch (error) {
1397
+ _chunkJB6MA2RVcjs.logger.error("Error masking span", { err: error });
1398
+ }
1399
+ }
1400
+
1401
+ // src/internal/trace/tracing.ts
1402
+ var TracingModule = (_class5 = class _TracingModule {constructor() { _class5.prototype.__init11.call(this);_class5.prototype.__init12.call(this); }
1403
+ static __initStatic3() {this.instance = null}
1404
+ static getInstance() {
1405
+ if (!this.instance) {
1406
+ throw new Error("Brizz must be initialized before accessing TracingModule");
1407
+ }
1408
+ return this.instance;
1409
+ }
1410
+ __init11() {this.spanExporter = null}
1411
+ __init12() {this.spanProcessor = null}
1412
+ /**
1413
+ * Initialize the span exporter
1414
+ */
1415
+ initSpanExporter(config) {
1416
+ if (this.spanExporter) {
1417
+ _chunkJB6MA2RVcjs.logger.debug("Span exporter already initialized, skipping re-initialization");
1418
+ return;
1419
+ }
1420
+ if (config.customSpanExporter) {
1421
+ _chunkJB6MA2RVcjs.logger.debug("Using custom span exporter");
1422
+ this.spanExporter = new BrizzSpanExporter(config.customSpanExporter, config);
1423
+ _chunkJB6MA2RVcjs.logger.debug("Custom span exporter initialized successfully");
1424
+ return;
1425
+ }
1426
+ const tracesUrl = config.baseUrl.replace(/\/$/, "") + "/v1/traces";
1427
+ _chunkJB6MA2RVcjs.logger.debug("Initializing default OTLP span exporter", { url: tracesUrl });
1428
+ const otlpExporter = new (0, _exportertraceotlpproto.OTLPTraceExporter)({
1429
+ url: tracesUrl,
1430
+ headers: config.headers
1431
+ });
1432
+ this.spanExporter = new BrizzSpanExporter(otlpExporter, config);
1433
+ _chunkJB6MA2RVcjs.logger.debug("OTLP span exporter initialized successfully");
1434
+ }
1435
+ /**
1436
+ * Initialize the span processor with masking support
1437
+ */
1438
+ initSpanProcessor(config) {
1439
+ if (this.spanProcessor) {
1440
+ _chunkJB6MA2RVcjs.logger.debug("Span processor already initialized, skipping re-initialization");
1441
+ return;
1442
+ }
1443
+ if (!this.spanExporter) {
1444
+ throw new Error("Span exporter must be initialized before processor");
1445
+ }
1446
+ _chunkJB6MA2RVcjs.logger.debug("Initializing span processor", {
1447
+ disableBatch: config.disableBatch,
1448
+ hasMasking: !!_optionalChain([config, 'access', _54 => _54.masking, 'optionalAccess', _55 => _55.spanMasking])
1449
+ });
1450
+ const spanProcessor = config.disableBatch ? new BrizzSimpleSpanProcessor(this.spanExporter, config) : new BrizzBatchSpanProcessor(this.spanExporter, config);
1451
+ _chunkJB6MA2RVcjs.logger.debug("Span processor initialized successfully");
1452
+ this.spanProcessor = spanProcessor;
1453
+ }
1454
+ /**
1455
+ * Initialize the tracing module with the provided configuration
1456
+ */
1457
+ setup(config) {
1458
+ _chunkJB6MA2RVcjs.logger.info("Setting up tracing module");
1459
+ if (config.disableSpanExporter) {
1460
+ _chunkJB6MA2RVcjs.logger.info(
1461
+ "Span exporter disabled via disableSpanExporter; skipping exporter and processor setup"
1462
+ );
1463
+ this.spanExporter = null;
1464
+ this.spanProcessor = null;
1465
+ _TracingModule.instance = this;
1466
+ return;
1467
+ }
1468
+ this.initSpanExporter(config);
1469
+ this.initSpanProcessor(config);
1470
+ _TracingModule.instance = this;
1471
+ _chunkJB6MA2RVcjs.logger.info("Tracing module setup completed");
1472
+ }
1473
+ /**
1474
+ * Get the span exporter
1475
+ */
1476
+ getSpanExporter() {
1477
+ if (!this.spanExporter) {
1478
+ throw new Error("Tracing module not initialized");
1479
+ }
1480
+ return this.spanExporter;
1481
+ }
1482
+ /**
1483
+ * Get the span processor
1484
+ */
1485
+ getSpanProcessor() {
1486
+ if (!this.spanProcessor) {
1487
+ throw new Error("Tracing module not initialized");
1488
+ }
1489
+ return this.spanProcessor;
1490
+ }
1491
+ async shutdown() {
1492
+ _chunkJB6MA2RVcjs.logger.debug("Shutting down tracing module");
1493
+ if (this.spanProcessor) {
1494
+ await this.spanProcessor.shutdown();
1495
+ this.spanProcessor = null;
1496
+ }
1497
+ if (this.spanExporter) {
1498
+ await this.spanExporter.shutdown();
1499
+ this.spanExporter = null;
1500
+ }
1501
+ _TracingModule.instance = null;
1502
+ _chunkJB6MA2RVcjs.logger.debug("Tracing module shutdown completed");
1503
+ }
1504
+ }, _class5.__initStatic3(), _class5);
1505
+ function getSpanExporter() {
1506
+ return TracingModule.getInstance().getSpanExporter();
1507
+ }
1508
+ function getSpanProcessor() {
1509
+ return TracingModule.getInstance().getSpanProcessor();
1510
+ }
1511
+
1512
+ // src/internal/sdk.ts
1513
+
1514
+ var _instrumentation = require('@opentelemetry/instrumentation');
1515
+
1516
+
1517
+
1518
+
1519
+
1520
+
1521
+
1522
+
1523
+
1524
+ var _sdktracenode = require('@opentelemetry/sdk-trace-node');
1525
+
1526
+ // src/internal/dsn.ts
1527
+ var PLACEHOLDER_SERVICE = "<service-name>";
1528
+ var SERVICE_NAME_HEADER = "X-Brizz-Service-Name";
1529
+ function parseDSN(dsn) {
1530
+ let parsed;
1531
+ try {
1532
+ parsed = new globalThis.URL(dsn);
1533
+ } catch (e2) {
1534
+ return null;
1535
+ }
1536
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || !parsed.username || !parsed.host) {
1537
+ return null;
1538
+ }
1539
+ const scheme = parsed.protocol === "https:" ? "https" : "http";
1540
+ let service;
1541
+ try {
1542
+ service = decodeURIComponent(parsed.pathname.replace(/^\//, ""));
1543
+ } catch (e3) {
1544
+ return null;
1545
+ }
1546
+ if (service === "" || service === PLACEHOLDER_SERVICE) {
1547
+ return null;
1548
+ }
1549
+ return {
1550
+ scheme,
1551
+ host: parsed.host,
1552
+ bearer: decodeURIComponent(parsed.username),
1553
+ service,
1554
+ baseUrl: `${scheme}://${parsed.host}`
1555
+ };
1556
+ }
1557
+
1558
+ // src/internal/config.ts
1559
+ function resolveConfig(options) {
1560
+ const envLogLevel = process.env["BRIZZ_LOG_LEVEL"] || _optionalChain([options, 'access', _56 => _56.logLevel, 'optionalAccess', _57 => _57.toString, 'call', _58 => _58()]) || _chunkJB6MA2RVcjs.DEFAULT_LOG_LEVEL.toString();
1561
+ let resolvedLogLevel;
1562
+ if (envLogLevel) {
1563
+ resolvedLogLevel = _chunkJB6MA2RVcjs.parseLogLevel.call(void 0, envLogLevel);
1564
+ } else if (typeof options.logLevel === "string") {
1565
+ resolvedLogLevel = _chunkJB6MA2RVcjs.parseLogLevel.call(void 0, options.logLevel);
1566
+ } else {
1567
+ resolvedLogLevel = options.logLevel || _chunkJB6MA2RVcjs.DEFAULT_LOG_LEVEL;
1568
+ }
1569
+ _chunkJB6MA2RVcjs.setLogLevel.call(void 0, resolvedLogLevel);
1570
+ let maskingStatus;
1571
+ if (options.masking === true) {
1572
+ maskingStatus = "enabled";
1573
+ } else if (options.masking === false) {
1574
+ maskingStatus = "disabled";
1575
+ } else if (typeof options.masking === "object") {
1576
+ maskingStatus = "custom";
1577
+ } else {
1578
+ maskingStatus = "default-disabled";
1579
+ }
1580
+ _chunkJB6MA2RVcjs.logger.debug("Starting configuration resolution", {
1581
+ appName: options.appName,
1582
+ baseUrl: options.baseUrl,
1583
+ hasApiKey: !!options.apiKey,
1584
+ dsnProvided: !!(process.env["BRIZZ_DSN"] || options.dsn),
1585
+ disableBatch: options.disableBatch,
1586
+ logLevel: resolvedLogLevel,
1587
+ headersCount: Object.keys(options.headers || {}).length,
1588
+ masking: maskingStatus
1589
+ });
1590
+ let resolvedMasking;
1591
+ if (options.masking === true) {
1592
+ resolvedMasking = {
1593
+ spanMasking: {},
1594
+ eventMasking: {}
1595
+ };
1596
+ } else if (options.masking && typeof options.masking === "object") {
1597
+ resolvedMasking = options.masking;
1598
+ }
1599
+ const resolvedConfig = {
1600
+ ...options,
1601
+ appName: process.env["BRIZZ_APP_NAME"] || options.appName || "unknown-app",
1602
+ appVersion: process.env["BRIZZ_APP_VERSION"] || options.appVersion,
1603
+ baseUrl: process.env["BRIZZ_BASE_URL"] || options.baseUrl || "https://telemetry.brizz.dev",
1604
+ headers: { ...options.headers },
1605
+ apiKey: process.env["BRIZZ_API_KEY"] || options.apiKey,
1606
+ disableBatch: process.env["BRIZZ_DISABLE_BATCH"] === "true" || !!options.disableBatch,
1607
+ disableSpanExporter: process.env["BRIZZ_DISABLE_SPAN_EXPORTER"] === "true" || !!options.disableSpanExporter,
1608
+ environment: process.env["BRIZZ_ENVIRONMENT"] || options.environment,
1609
+ logLevel: resolvedLogLevel,
1610
+ masking: resolvedMasking
1611
+ };
1612
+ const dsnInput = process.env["BRIZZ_DSN"] || options.dsn;
1613
+ let parsedDSN = null;
1614
+ if (dsnInput) {
1615
+ const kwargConflicts = [];
1616
+ if (options.apiKey !== void 0) {
1617
+ kwargConflicts.push("apiKey");
1618
+ }
1619
+ if (options.baseUrl !== void 0) {
1620
+ kwargConflicts.push("baseUrl");
1621
+ }
1622
+ if (options.appName !== void 0) {
1623
+ kwargConflicts.push("appName");
1624
+ }
1625
+ if (kwargConflicts.length > 0) {
1626
+ throw new Error(
1627
+ `dsn cannot be combined with kwargs ${kwargConflicts.join(", ")}. The DSN bundles bearer, gateway URL, and service name \u2014 choose one configuration style.`
1628
+ );
1629
+ }
1630
+ const envConflicts = ["BRIZZ_API_KEY", "BRIZZ_BASE_URL", "BRIZZ_APP_NAME"].filter(
1631
+ (name) => process.env[name] !== void 0
1632
+ );
1633
+ if (envConflicts.length > 0) {
1634
+ _chunkJB6MA2RVcjs.logger.warn(
1635
+ `Ignoring ${envConflicts.join(", ")} \u2014 dsn / BRIZZ_DSN takes precedence.`
1636
+ );
1637
+ }
1638
+ resolvedConfig.apiKey = void 0;
1639
+ resolvedConfig.baseUrl = "https://telemetry.brizz.dev";
1640
+ resolvedConfig.appName = "unknown-app";
1641
+ parsedDSN = parseDSN(dsnInput);
1642
+ if (parsedDSN) {
1643
+ resolvedConfig.appName = parsedDSN.service;
1644
+ resolvedConfig.baseUrl = parsedDSN.baseUrl;
1645
+ resolvedConfig.apiKey = parsedDSN.bearer;
1646
+ }
1647
+ } else if (resolvedConfig.apiKey) {
1648
+ resolvedConfig.headers["Authorization"] = `Bearer ${resolvedConfig.apiKey}`;
1649
+ }
1650
+ if (process.env["BRIZZ_HEADERS"]) {
1651
+ try {
1652
+ const envHeaders = JSON.parse(process.env["BRIZZ_HEADERS"]);
1653
+ Object.assign(resolvedConfig.headers, envHeaders);
1654
+ _chunkJB6MA2RVcjs.logger.debug("Added headers from environment variable", {
1655
+ headers: Object.keys(envHeaders)
1656
+ });
1657
+ } catch (error) {
1658
+ _chunkJB6MA2RVcjs.logger.error("Failed to parse BRIZZ_HEADERS environment variable", { error });
1659
+ throw new Error("Invalid JSON in BRIZZ_HEADERS environment variable", { cause: error });
1660
+ }
1661
+ }
1662
+ if (dsnInput) {
1663
+ const authHeaderKeys = /* @__PURE__ */ new Set(["authorization", SERVICE_NAME_HEADER.toLowerCase()]);
1664
+ resolvedConfig.headers = Object.fromEntries(
1665
+ Object.entries(resolvedConfig.headers).filter(
1666
+ ([key]) => !authHeaderKeys.has(key.toLowerCase())
1667
+ )
1668
+ );
1669
+ if (parsedDSN) {
1670
+ resolvedConfig.headers["Authorization"] = `Bearer ${parsedDSN.bearer}`;
1671
+ resolvedConfig.headers[SERVICE_NAME_HEADER] = parsedDSN.service;
1672
+ }
1673
+ }
1674
+ _chunkJB6MA2RVcjs.logger.debug("Configuration resolved with environment variables", {
1675
+ appName: resolvedConfig.appName,
1676
+ baseUrl: resolvedConfig.baseUrl,
1677
+ hasApiKey: !!resolvedConfig.apiKey,
1678
+ dsnProvided: !!dsnInput,
1679
+ disableBatch: resolvedConfig.disableBatch,
1680
+ envOverrides: {
1681
+ hasEnvApiKey: !!process.env["BRIZZ_API_KEY"],
1682
+ hasEnvBaseUrl: !!process.env["BRIZZ_BASE_URL"],
1683
+ hasEnvDsn: !!process.env["BRIZZ_DSN"],
1684
+ hasEnvBatch: !!process.env["BRIZZ_DISABLE_BATCH"],
1685
+ hasEnvHeaders: !!process.env["BRIZZ_HEADERS"]
1686
+ }
1687
+ });
1688
+ return resolvedConfig;
1689
+ }
1690
+
1691
+ // src/internal/sdk.ts
1692
+ var _Brizz = (_class6 = class __Brizz {constructor() { _class6.prototype.__init13.call(this);_class6.prototype.__init14.call(this);_class6.prototype.__init15.call(this); }
1693
+ static __initStatic4() {this.instance = null}
1694
+ static getInstance() {
1695
+ if (!this.instance) {
1696
+ throw new Error("Brizz must be initialized before accessing TracingModule");
1697
+ }
1698
+ return this.instance;
1699
+ }
1700
+ /** Flag indicating if SDK initialization has completed successfully */
1701
+ __init13() {this._initialized = false}
1702
+ /** OpenTelemetry tracer provider */
1703
+ __init14() {this._tracerProvider = null}
1704
+ /** OpenTelemetry meter provider */
1705
+ __init15() {this._meterProvider = null}
1706
+ /**
1707
+ * Set up instrumentation registry and configure manual modules.
1708
+ * @private
1709
+ */
1710
+ setupInstrumentation(options) {
1711
+ const registry = InstrumentationRegistry.getInstance();
1712
+ if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {
1713
+ registry.setManualModules(options.instrumentModules);
1714
+ }
1715
+ }
1716
+ /**
1717
+ * Create and register the tracer + meter providers if not disabled.
1718
+ * Only handles manual instrumentations now - auto instrumentations are loaded at import time.
1719
+ * @private
1720
+ */
1721
+ createAndStartProviders(options, resolvedConfig) {
1722
+ if (options.disableNodeSdk) {
1723
+ _chunkJB6MA2RVcjs.logger.info("NodeSDK disabled - only telemetry modules initialized");
1724
+ return;
1725
+ }
1726
+ const registry = InstrumentationRegistry.getInstance();
1727
+ const manualInstrumentations = registry.getManualInstrumentations();
1728
+ const resourceAttributes = {
1729
+ ...resolvedConfig.resourceAttributes,
1730
+ "service.name": resolvedConfig.appName,
1731
+ [BRIZZ_SDK_VERSION]: _chunkJB6MA2RVcjs.getSDKVersion.call(void 0, ),
1732
+ [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
1733
+ };
1734
+ if (resolvedConfig.environment) {
1735
+ resourceAttributes["deployment.environment"] = resolvedConfig.environment;
1736
+ }
1737
+ if (resolvedConfig.appVersion) {
1738
+ resourceAttributes["service.version"] = resolvedConfig.appVersion;
1739
+ }
1740
+ const resource = _resources.defaultResource.call(void 0, ).merge(_resources.detectResources.call(void 0, { detectors: [_resources.envDetector, _resources.hostDetector, _resources.processDetector] })).merge(_resources.resourceFromAttributes.call(void 0, resourceAttributes));
1741
+ this._tracerProvider = new (0, _sdktracenode.NodeTracerProvider)({
1742
+ resource,
1743
+ spanProcessors: resolvedConfig.disableSpanExporter ? [] : [new (0, _chunkLTXMCGVQcjs.InterruptPropagator)(), getSpanProcessor()]
1744
+ });
1745
+ this._tracerProvider.register();
1746
+ this._meterProvider = new (0, _sdkmetrics.MeterProvider)({ resource, readers: [getMetricsReader()] });
1747
+ _api.metrics.setGlobalMeterProvider(this._meterProvider);
1748
+ if (manualInstrumentations.length > 0) {
1749
+ _instrumentation.registerInstrumentations.call(void 0, { instrumentations: manualInstrumentations });
1750
+ _chunkJB6MA2RVcjs.logger.info(
1751
+ `Telemetry providers started with ${manualInstrumentations.length} manual instrumentations`
1752
+ );
1753
+ } else {
1754
+ _chunkJB6MA2RVcjs.logger.info(
1755
+ "Telemetry providers started - using auto-instrumentations loaded at import time"
1756
+ );
1757
+ }
1758
+ }
1759
+ /**
1760
+ * Initialize telemetry modules.
1761
+ *
1762
+ * Sets up the tracing, metrics, and logging modules with their
1763
+ * respective exporters and processors.
1764
+ *
1765
+ * @param {IResolvedBrizzConfig} config - Resolved configuration
1766
+ * @private
1767
+ */
1768
+ initializeModules(config) {
1769
+ _chunkJB6MA2RVcjs.logger.info("Initializing telemetry modules");
1770
+ _chunkJB6MA2RVcjs.logger.debug("Initializing tracing module");
1771
+ const tracingModule = new TracingModule();
1772
+ tracingModule.setup(config);
1773
+ _chunkJB6MA2RVcjs.logger.debug("Initializing metrics module");
1774
+ const metricsModule = new MetricsModule();
1775
+ metricsModule.setup(config);
1776
+ _chunkJB6MA2RVcjs.logger.debug("Initializing logging module");
1777
+ const loggingModule = new LoggingModule();
1778
+ loggingModule.setup(config);
1779
+ _chunkJB6MA2RVcjs.logger.info("All telemetry modules initialized successfully");
1780
+ }
1781
+ /**
1782
+ * Detect the current module system (ESM or CJS) using reliable indicators
1783
+ *
1784
+ * @returns {string} - 'ESM' or 'CJS'
1785
+ * @private
1786
+ */
1787
+ detectModuleSystem() {
1788
+ const inCJS = typeof module !== "undefined" && typeof exports !== "undefined" && typeof _chunkGCORRK6Bcjs.__require === "function" && typeof __filename === "string" && typeof __dirname === "string" && this === (typeof exports !== "undefined" ? exports : void 0);
1789
+ return inCJS ? "CJS" : "ESM";
1790
+ }
1791
+ /**
1792
+ * Shutdown all telemetry modules.
1793
+ * @private
1794
+ */
1795
+ async shutdownModules() {
1796
+ _chunkJB6MA2RVcjs.logger.info("Shutting down telemetry modules");
1797
+ try {
1798
+ try {
1799
+ const tracingModule = TracingModule.getInstance();
1800
+ await tracingModule.shutdown();
1801
+ } catch (e4) {
1802
+ _chunkJB6MA2RVcjs.logger.debug("Tracing module already shut down or not initialized");
1803
+ }
1804
+ try {
1805
+ const metricsModule = MetricsModule.getInstance();
1806
+ metricsModule.shutdown();
1807
+ } catch (e5) {
1808
+ _chunkJB6MA2RVcjs.logger.debug("Metrics module already shut down or not initialized");
1809
+ }
1810
+ try {
1811
+ const loggingModule = LoggingModule.getInstance();
1812
+ await loggingModule.shutdown();
1813
+ } catch (e6) {
1814
+ _chunkJB6MA2RVcjs.logger.debug("Logging module already shut down or not initialized");
1815
+ }
1816
+ _chunkJB6MA2RVcjs.logger.info("All telemetry modules shut down successfully");
1817
+ } catch (error) {
1818
+ _chunkJB6MA2RVcjs.logger.error("Error shutting down modules", { error });
1819
+ throw error;
1820
+ }
1821
+ }
1822
+ /**
1823
+ * Initialize the Brizz SDK with the provided configuration.
1824
+ *
1825
+ * @param {IBrizzInitializeOptions} options - Configuration options for the SDK
1826
+ * @throws {Error} - If initialization fails
1827
+ *
1828
+ * @example
1829
+ * ```typescript
1830
+ * Brizz.initialize({
1831
+ * appName: 'my-app',
1832
+ * baseUrl: 'http://localhost:4318',
1833
+ * apiKey: 'your-api-key'
1834
+ * });
1835
+ * ```
1836
+ */
1837
+ initialize(options) {
1838
+ if (this._initialized) {
1839
+ _chunkJB6MA2RVcjs.logger.warn("Brizz SDK already initialized");
1840
+ return;
1841
+ }
1842
+ _chunkJB6MA2RVcjs.logger.info("Starting Brizz SDK initialization");
1843
+ try {
1844
+ const resolvedConfig = resolveConfig(options);
1845
+ this.initializeModules(resolvedConfig);
1846
+ this.setupInstrumentation(options);
1847
+ this.createAndStartProviders(options, resolvedConfig);
1848
+ this._initialized = true;
1849
+ _chunkJB6MA2RVcjs.logger.info("Brizz SDK initialization completed successfully", {
1850
+ moduleSystem: this.detectModuleSystem()
1851
+ });
1852
+ } catch (error) {
1853
+ _chunkJB6MA2RVcjs.logger.error("Failed to initialize Brizz SDK", { error });
1854
+ throw new Error(`Failed to initialize SDK: ${String(error)}`, { cause: error });
1855
+ }
1856
+ }
1857
+ /**
1858
+ * Gracefully shutdown the Brizz SDK.
1859
+ *
1860
+ * This method stops all telemetry collection, flushes any pending data,
1861
+ * and releases resources. Should be called before app termination.
1862
+ *
1863
+ * @returns {Promise<void>} - Resolves when shutdown is complete
1864
+ * @throws {Error} - If shutdown fails
1865
+ *
1866
+ * @example
1867
+ * ```typescript
1868
+ * // Shutdown before app exit
1869
+ * await Brizz.shutdown();
1870
+ * ```
1871
+ */
1872
+ async shutdown() {
1873
+ if (!this._initialized) {
1874
+ _chunkJB6MA2RVcjs.logger.warn("Brizz SDK not initialized");
1875
+ return;
1876
+ }
1877
+ try {
1878
+ await this.shutdownModules();
1879
+ await _optionalChain([this, 'access', _59 => _59._tracerProvider, 'optionalAccess', _60 => _60.forceFlush, 'call', _61 => _61()]);
1880
+ await _optionalChain([this, 'access', _62 => _62._tracerProvider, 'optionalAccess', _63 => _63.shutdown, 'call', _64 => _64()]);
1881
+ await _optionalChain([this, 'access', _65 => _65._meterProvider, 'optionalAccess', _66 => _66.forceFlush, 'call', _67 => _67()]);
1882
+ await _optionalChain([this, 'access', _68 => _68._meterProvider, 'optionalAccess', _69 => _69.shutdown, 'call', _70 => _70()]);
1883
+ this._initialized = false;
1884
+ this._tracerProvider = null;
1885
+ this._meterProvider = null;
1886
+ __Brizz.instance = null;
1887
+ _chunkJB6MA2RVcjs.logger.info("Brizz SDK shut down successfully");
1888
+ } catch (error) {
1889
+ if (error instanceof Error && error.message.includes("ENOTFOUND")) {
1890
+ _chunkJB6MA2RVcjs.logger.debug(`Network error during shutdown (expected in tests): ${error.message}`);
1891
+ } else {
1892
+ _chunkJB6MA2RVcjs.logger.error(`Failed to shutdown Brizz SDK: ${String(error)}`);
1893
+ throw error;
1894
+ }
1895
+ }
1896
+ }
1897
+ }, _class6.__initStatic4(), _class6);
1898
+ var Brizz = new _Brizz();
1899
+
1900
+ // src/node/runtime.ts
1901
+ function detectRuntime() {
1902
+ const [major, minor] = process.versions.node.split(".").map(Number);
1903
+ const noNodeJSGlobals = typeof __filename === "undefined" && typeof __dirname === "undefined";
1904
+ const noModuleSystem = typeof module === "undefined" && typeof exports === "undefined";
1905
+ const hasRequire = typeof _chunkGCORRK6Bcjs.__require === "function";
1906
+ const isESM = noNodeJSGlobals && noModuleSystem;
1907
+ const isCJS = hasRequire && typeof module !== "undefined" && typeof exports !== "undefined" && typeof __filename === "string" && typeof __dirname === "string";
1908
+ const supportsLoaderAPI = (_nullishCoalesce(major, () => ( 0))) >= 21 || (_nullishCoalesce(major, () => ( 0))) === 20 && (_nullishCoalesce(minor, () => ( 0))) >= 6 || (_nullishCoalesce(major, () => ( 0))) === 18 && (_nullishCoalesce(minor, () => ( 0))) >= 19;
1909
+ const supportsRegister = (
1910
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1911
+ !!_optionalChain([process, 'access', _71 => _71.features, 'optionalAccess', _72 => _72.typescript]) || !!_optionalChain([globalThis, 'access', _73 => _73.module, 'optionalAccess', _74 => _74.register])
1912
+ );
1913
+ _chunkJB6MA2RVcjs.logger.debug("Runtime detection results:", {
1914
+ nodeVersion: `${_nullishCoalesce(major, () => ( 0))}.${_nullishCoalesce(minor, () => ( 0))}`,
1915
+ isESM,
1916
+ isCJS,
1917
+ supportsLoaderAPI,
1918
+ supportsRegister,
1919
+ detectionLogic: {
1920
+ noNodeJSGlobals,
1921
+ noModuleSystem,
1922
+ hasRequire,
1923
+ esmCondition: `${noNodeJSGlobals} && ${noModuleSystem} = ${isESM}`,
1924
+ cjsCondition: `require && module && exports && __filename && __dirname = ${isCJS}`
1925
+ },
1926
+ checks: {
1927
+ __filename: typeof __filename,
1928
+ __dirname: typeof __dirname,
1929
+ require: typeof _chunkGCORRK6Bcjs.__require,
1930
+ module: typeof module,
1931
+ exports: typeof exports,
1932
+ "process.features": process.features,
1933
+ "globalThis.module": Reflect.get(globalThis, "module")
1934
+ }
1935
+ });
1936
+ return {
1937
+ isESM,
1938
+ isCJS,
1939
+ nodeVersion: process.versions.node,
1940
+ supportsLoaderAPI,
1941
+ supportsRegister
1942
+ };
1943
+ }
1944
+
1945
+
1946
+
1947
+
1948
+
1949
+
1950
+
1951
+
1952
+
1953
+
1954
+
1955
+
1956
+
1957
+
1958
+
1959
+
1960
+
1961
+
1962
+
1963
+
1964
+
1965
+
1966
+
1967
+
1968
+
1969
+
1970
+ exports.setCurrentSpanCustomProperties = setCurrentSpanCustomProperties; exports.callWithProperties = callWithProperties; exports.withProperties = withProperties; exports.callWithMute = callWithMute; exports.withMute = withMute; exports.withSessionId = withSessionId; exports.callWithSessionId = callWithSessionId; exports.Session = Session; exports.SessionTitle = SessionTitle; exports.getActiveSession = getActiveSession; exports.addExternalLink = addExternalLink; exports.startSession = startSession; exports.startSessionTitle = startSessionTitle; exports.DEFAULT_PII_PATTERNS = DEFAULT_PII_PATTERNS; exports.maskValue = maskValue; exports.maskAttributes = maskAttributes; exports.emitEvent = emitEvent; exports.emitEventWithSessionId = emitEventWithSessionId; exports.getMetricsExporter = getMetricsExporter; exports.getMetricsReader = getMetricsReader; exports.getSpanExporter = getSpanExporter; exports.getSpanProcessor = getSpanProcessor; exports.Brizz = Brizz; exports.detectRuntime = detectRuntime;