@atrim/instrument-node 0.4.1 → 0.5.0-14fdea7-20260109020503

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,1276 @@
1
+ 'use strict';
2
+
3
+ var effect = require('effect');
4
+ var opentelemetry = require('@effect/opentelemetry');
5
+ var sdkTraceBase = require('@opentelemetry/sdk-trace-base');
6
+ var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
7
+ var FileSystem = require('@effect/platform/FileSystem');
8
+ var HttpClient = require('@effect/platform/HttpClient');
9
+ var HttpClientRequest = require('@effect/platform/HttpClientRequest');
10
+ var yaml = require('yaml');
11
+ var zod = require('zod');
12
+ var OtelApi = require('@opentelemetry/api');
13
+ var resources = require('@opentelemetry/resources');
14
+ var semanticConventions = require('@opentelemetry/semantic-conventions');
15
+ var path = require('path');
16
+
17
+ function _interopNamespace(e) {
18
+ if (e && e.__esModule) return e;
19
+ var n = Object.create(null);
20
+ if (e) {
21
+ Object.keys(e).forEach(function (k) {
22
+ if (k !== 'default') {
23
+ var d = Object.getOwnPropertyDescriptor(e, k);
24
+ Object.defineProperty(n, k, d.get ? d : {
25
+ enumerable: true,
26
+ get: function () { return e[k]; }
27
+ });
28
+ }
29
+ });
30
+ }
31
+ n.default = e;
32
+ return Object.freeze(n);
33
+ }
34
+
35
+ var HttpClient__namespace = /*#__PURE__*/_interopNamespace(HttpClient);
36
+ var HttpClientRequest__namespace = /*#__PURE__*/_interopNamespace(HttpClientRequest);
37
+ var OtelApi__namespace = /*#__PURE__*/_interopNamespace(OtelApi);
38
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
39
+
40
+ var __defProp = Object.defineProperty;
41
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
42
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
43
+ var __defProp2 = Object.defineProperty;
44
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
45
+ var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
46
+ var PatternConfigSchema = zod.z.object({
47
+ pattern: zod.z.string(),
48
+ enabled: zod.z.boolean().optional(),
49
+ description: zod.z.string().optional()
50
+ });
51
+ var AutoIsolationConfigSchema = zod.z.object({
52
+ // Global enable/disable for auto-isolation
53
+ enabled: zod.z.boolean().default(false),
54
+ // Which operators to auto-isolate
55
+ operators: zod.z.object({
56
+ fiberset_run: zod.z.boolean().default(true),
57
+ effect_fork: zod.z.boolean().default(true),
58
+ effect_fork_daemon: zod.z.boolean().default(true),
59
+ effect_fork_in: zod.z.boolean().default(false)
60
+ }).default({}),
61
+ // Virtual parent tracking configuration
62
+ tracking: zod.z.object({
63
+ use_span_links: zod.z.boolean().default(true),
64
+ use_attributes: zod.z.boolean().default(true),
65
+ capture_logical_parent: zod.z.boolean().default(true)
66
+ }).default({}),
67
+ // Span categorization
68
+ attributes: zod.z.object({
69
+ category: zod.z.string().default("background_task"),
70
+ add_metadata: zod.z.boolean().default(true)
71
+ }).default({})
72
+ });
73
+ var SpanNamingRuleSchema = zod.z.object({
74
+ // Match criteria (all specified criteria must match)
75
+ match: zod.z.object({
76
+ // Regex pattern to match file path
77
+ file: zod.z.string().optional(),
78
+ // Regex pattern to match function name
79
+ function: zod.z.string().optional(),
80
+ // Regex pattern to match module name
81
+ module: zod.z.string().optional()
82
+ }),
83
+ // Span name template with variables:
84
+ // {fiber_id} - Fiber ID
85
+ // {function} - Function name
86
+ // {module} - Module name
87
+ // {file} - File path
88
+ // {line} - Line number
89
+ // {operator} - Effect operator (gen, all, forEach, etc.)
90
+ // {match:field:N} - Captured regex group from match
91
+ name: zod.z.string()
92
+ });
93
+ var AutoInstrumentationConfigSchema = zod.z.object({
94
+ // Enable/disable auto-instrumentation
95
+ enabled: zod.z.boolean().default(false),
96
+ // Tracing granularity
97
+ // - 'fiber': Trace at fiber creation (recommended, lower overhead)
98
+ // - 'operator': Trace each Effect operator (higher granularity, more overhead)
99
+ granularity: zod.z.enum(["fiber", "operator"]).default("fiber"),
100
+ // Smart span naming configuration
101
+ span_naming: zod.z.object({
102
+ // Default span name template when no rules match
103
+ default: zod.z.string().default("effect.fiber.{fiber_id}"),
104
+ // Infer span names from source code (requires stack trace parsing)
105
+ // Adds ~50-100μs overhead per fiber
106
+ infer_from_source: zod.z.boolean().default(true),
107
+ // Naming rules (first match wins)
108
+ rules: zod.z.array(SpanNamingRuleSchema).default([])
109
+ }).default({}),
110
+ // Pattern-based filtering
111
+ filter: zod.z.object({
112
+ // Only trace spans matching these patterns (empty = trace all)
113
+ include: zod.z.array(zod.z.string()).default([]),
114
+ // Never trace spans matching these patterns
115
+ exclude: zod.z.array(zod.z.string()).default([])
116
+ }).default({}),
117
+ // Performance controls
118
+ performance: zod.z.object({
119
+ // Sample rate (0.0 - 1.0)
120
+ sampling_rate: zod.z.number().min(0).max(1).default(1),
121
+ // Skip fibers shorter than this duration (e.g., "10ms", "100 millis")
122
+ min_duration: zod.z.string().default("0ms"),
123
+ // Maximum concurrent traced fibers (0 = unlimited)
124
+ max_concurrent: zod.z.number().default(0)
125
+ }).default({}),
126
+ // Automatic metadata extraction
127
+ metadata: zod.z.object({
128
+ // Extract Effect fiber information
129
+ fiber_info: zod.z.boolean().default(true),
130
+ // Extract source location (file:line)
131
+ source_location: zod.z.boolean().default(true),
132
+ // Extract parent fiber information
133
+ parent_fiber: zod.z.boolean().default(true)
134
+ }).default({})
135
+ });
136
+ var HttpFilteringConfigSchema = zod.z.object({
137
+ // Patterns to ignore for outgoing HTTP requests (string patterns only in YAML)
138
+ ignore_outgoing_urls: zod.z.array(zod.z.string()).optional(),
139
+ // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)
140
+ ignore_incoming_paths: zod.z.array(zod.z.string()).optional(),
141
+ // Require parent span for outgoing requests (prevents root spans for HTTP calls)
142
+ require_parent_for_outgoing_spans: zod.z.boolean().optional(),
143
+ // Trace context propagation configuration
144
+ // Controls which cross-origin requests receive W3C Trace Context headers (traceparent, tracestate)
145
+ propagate_trace_context: zod.z.object({
146
+ // Strategy for trace propagation
147
+ // - "all": Propagate to all cross-origin requests (may cause CORS errors)
148
+ // - "none": Never propagate trace headers
149
+ // - "same-origin": Only propagate to same-origin requests (default, safe)
150
+ // - "patterns": Propagate based on include_urls patterns
151
+ strategy: zod.z.enum(["all", "none", "same-origin", "patterns"]).default("same-origin"),
152
+ // URL patterns to include when strategy is "patterns"
153
+ // Supports regex patterns (e.g., "^https://api\\.myapp\\.com")
154
+ include_urls: zod.z.array(zod.z.string()).optional()
155
+ }).optional()
156
+ });
157
+ var ExporterConfigSchema = zod.z.object({
158
+ // Exporter type: 'otlp' | 'console' | 'none'
159
+ // - 'otlp': Export to OTLP endpoint (production)
160
+ // - 'console': Log spans to console (development)
161
+ // - 'none': No export (disable tracing)
162
+ type: zod.z.enum(["otlp", "console", "none"]).default("otlp"),
163
+ // OTLP endpoint URL (for type: otlp)
164
+ // Defaults to OTEL_EXPORTER_OTLP_ENDPOINT env var or http://localhost:4318
165
+ endpoint: zod.z.string().optional(),
166
+ // Custom headers to send with OTLP requests (for type: otlp)
167
+ // Useful for authentication (x-api-key, Authorization, etc.)
168
+ headers: zod.z.record(zod.z.string()).optional(),
169
+ // Span processor type
170
+ // - 'batch': Batch spans for export (production, lower overhead)
171
+ // - 'simple': Export immediately (development, no batching delay)
172
+ processor: zod.z.enum(["batch", "simple"]).default("batch"),
173
+ // Batch processor settings (for processor: batch)
174
+ batch: zod.z.object({
175
+ // Max time to wait before exporting (milliseconds)
176
+ scheduled_delay_millis: zod.z.number().default(1e3),
177
+ // Max batch size
178
+ max_export_batch_size: zod.z.number().default(100)
179
+ }).optional()
180
+ });
181
+ var InstrumentationConfigSchema = zod.z.object({
182
+ version: zod.z.string(),
183
+ instrumentation: zod.z.object({
184
+ enabled: zod.z.boolean(),
185
+ description: zod.z.string().optional(),
186
+ logging: zod.z.enum(["on", "off", "minimal"]).optional().default("on"),
187
+ instrument_patterns: zod.z.array(PatternConfigSchema),
188
+ ignore_patterns: zod.z.array(PatternConfigSchema)
189
+ }),
190
+ effect: zod.z.object({
191
+ // Enable/disable Effect tracing entirely
192
+ // When false, EffectInstrumentationLive returns Layer.empty
193
+ enabled: zod.z.boolean().default(true),
194
+ // Exporter mode (legacy - use exporter.type instead):
195
+ // - "unified": Use global TracerProvider from Node SDK (recommended, enables filtering)
196
+ // - "standalone": Use Effect's own OTLP exporter (bypasses Node SDK filtering)
197
+ exporter: zod.z.enum(["unified", "standalone"]).default("unified"),
198
+ // Exporter configuration (for auto-instrumentation)
199
+ exporter_config: ExporterConfigSchema.optional(),
200
+ auto_extract_metadata: zod.z.boolean(),
201
+ auto_isolation: AutoIsolationConfigSchema.optional(),
202
+ // Auto-instrumentation: automatic tracing of all Effect fibers
203
+ auto_instrumentation: AutoInstrumentationConfigSchema.optional()
204
+ }).optional(),
205
+ http: HttpFilteringConfigSchema.optional()
206
+ });
207
+ var defaultConfig = {
208
+ version: "1.0",
209
+ instrumentation: {
210
+ enabled: true,
211
+ logging: "on",
212
+ description: "Default instrumentation configuration",
213
+ instrument_patterns: [
214
+ { pattern: "^app\\.", enabled: true, description: "Application operations" },
215
+ { pattern: "^http\\.server\\.", enabled: true, description: "HTTP server operations" },
216
+ { pattern: "^http\\.client\\.", enabled: true, description: "HTTP client operations" }
217
+ ],
218
+ ignore_patterns: [
219
+ { pattern: "^test\\.", description: "Test utilities" },
220
+ { pattern: "^internal\\.", description: "Internal operations" },
221
+ { pattern: "^health\\.", description: "Health checks" }
222
+ ]
223
+ },
224
+ effect: {
225
+ enabled: true,
226
+ exporter: "unified",
227
+ auto_extract_metadata: true
228
+ }
229
+ };
230
+ function parseAndValidateConfig(content) {
231
+ let parsed;
232
+ if (typeof content === "string") {
233
+ parsed = yaml.parse(content);
234
+ } else {
235
+ parsed = content;
236
+ }
237
+ return InstrumentationConfigSchema.parse(parsed);
238
+ }
239
+ (class extends effect.Data.TaggedError("ConfigError") {
240
+ get message() {
241
+ return this.reason;
242
+ }
243
+ });
244
+ var ConfigUrlError = class extends effect.Data.TaggedError("ConfigUrlError") {
245
+ get message() {
246
+ return this.reason;
247
+ }
248
+ };
249
+ var ConfigValidationError = class extends effect.Data.TaggedError("ConfigValidationError") {
250
+ get message() {
251
+ return this.reason;
252
+ }
253
+ };
254
+ var ConfigFileError = class extends effect.Data.TaggedError("ConfigFileError") {
255
+ get message() {
256
+ return this.reason;
257
+ }
258
+ };
259
+ (class extends effect.Data.TaggedError("ServiceDetectionError") {
260
+ get message() {
261
+ return this.reason;
262
+ }
263
+ });
264
+ (class extends effect.Data.TaggedError("InitializationError") {
265
+ get message() {
266
+ return this.reason;
267
+ }
268
+ });
269
+ (class extends effect.Data.TaggedError("ExportError") {
270
+ get message() {
271
+ return this.reason;
272
+ }
273
+ });
274
+ (class extends effect.Data.TaggedError("ShutdownError") {
275
+ get message() {
276
+ return this.reason;
277
+ }
278
+ });
279
+ var SECURITY_DEFAULTS = {
280
+ maxConfigSize: 1e6,
281
+ // 1MB
282
+ requestTimeout: 5e3
283
+ // 5 seconds
284
+ };
285
+ var ConfigLoader = class extends effect.Context.Tag("ConfigLoader")() {
286
+ };
287
+ var parseYamlContent = (content, uri) => effect.Effect.gen(function* () {
288
+ const parsed = yield* effect.Effect.try({
289
+ try: () => yaml.parse(content),
290
+ catch: (error) => new ConfigValidationError({
291
+ reason: uri ? `Failed to parse YAML from ${uri}` : "Failed to parse YAML",
292
+ cause: error
293
+ })
294
+ });
295
+ return yield* effect.Effect.try({
296
+ try: () => InstrumentationConfigSchema.parse(parsed),
297
+ catch: (error) => new ConfigValidationError({
298
+ reason: uri ? `Invalid configuration schema from ${uri}` : "Invalid configuration schema",
299
+ cause: error
300
+ })
301
+ });
302
+ });
303
+ var loadFromFileWithFs = (fs, path2, uri) => effect.Effect.gen(function* () {
304
+ const content = yield* fs.readFileString(path2).pipe(
305
+ effect.Effect.mapError(
306
+ (error) => new ConfigFileError({
307
+ reason: `Failed to read config file at ${uri}`,
308
+ cause: error
309
+ })
310
+ )
311
+ );
312
+ if (content.length > SECURITY_DEFAULTS.maxConfigSize) {
313
+ return yield* effect.Effect.fail(
314
+ new ConfigFileError({
315
+ reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
316
+ })
317
+ );
318
+ }
319
+ return yield* parseYamlContent(content, uri);
320
+ });
321
+ var loadFromHttpWithClient = (client, url) => effect.Effect.scoped(
322
+ effect.Effect.gen(function* () {
323
+ if (url.startsWith("http://")) {
324
+ return yield* effect.Effect.fail(
325
+ new ConfigUrlError({
326
+ reason: "Insecure protocol: only HTTPS URLs are allowed"
327
+ })
328
+ );
329
+ }
330
+ const request = HttpClientRequest__namespace.get(url).pipe(
331
+ HttpClientRequest__namespace.setHeaders({
332
+ Accept: "application/yaml, text/yaml, application/x-yaml"
333
+ })
334
+ );
335
+ const response = yield* client.execute(request).pipe(
336
+ effect.Effect.timeout(`${SECURITY_DEFAULTS.requestTimeout} millis`),
337
+ effect.Effect.mapError((error) => {
338
+ if (error._tag === "TimeoutException") {
339
+ return new ConfigUrlError({
340
+ reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms from ${url}`
341
+ });
342
+ }
343
+ return new ConfigUrlError({
344
+ reason: `Failed to load config from URL: ${url}`,
345
+ cause: error
346
+ });
347
+ })
348
+ );
349
+ if (response.status >= 400) {
350
+ return yield* effect.Effect.fail(
351
+ new ConfigUrlError({
352
+ reason: `HTTP ${response.status} from ${url}`
353
+ })
354
+ );
355
+ }
356
+ const text = yield* response.text.pipe(
357
+ effect.Effect.mapError(
358
+ (error) => new ConfigUrlError({
359
+ reason: `Failed to read response body from ${url}`,
360
+ cause: error
361
+ })
362
+ )
363
+ );
364
+ if (text.length > SECURITY_DEFAULTS.maxConfigSize) {
365
+ return yield* effect.Effect.fail(
366
+ new ConfigUrlError({
367
+ reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
368
+ })
369
+ );
370
+ }
371
+ return yield* parseYamlContent(text, url);
372
+ })
373
+ );
374
+ var makeConfigLoader = effect.Effect.gen(function* () {
375
+ const fs = yield* effect.Effect.serviceOption(FileSystem.FileSystem);
376
+ const http = yield* HttpClient__namespace.HttpClient;
377
+ const loadFromUriUncached = (uri) => effect.Effect.gen(function* () {
378
+ if (uri.startsWith("file://")) {
379
+ const path2 = uri.slice(7);
380
+ if (fs._tag === "None") {
381
+ return yield* effect.Effect.fail(
382
+ new ConfigFileError({
383
+ reason: "FileSystem not available (browser environment?)",
384
+ cause: { uri }
385
+ })
386
+ );
387
+ }
388
+ return yield* loadFromFileWithFs(fs.value, path2, uri);
389
+ }
390
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
391
+ return yield* loadFromHttpWithClient(http, uri);
392
+ }
393
+ if (fs._tag === "Some") {
394
+ return yield* loadFromFileWithFs(fs.value, uri, uri);
395
+ } else {
396
+ return yield* loadFromHttpWithClient(http, uri);
397
+ }
398
+ });
399
+ const loadFromUriCached = yield* effect.Effect.cachedFunction(loadFromUriUncached);
400
+ return ConfigLoader.of({
401
+ loadFromUri: loadFromUriCached,
402
+ loadFromInline: (content) => effect.Effect.gen(function* () {
403
+ if (typeof content === "string") {
404
+ return yield* parseYamlContent(content);
405
+ }
406
+ return yield* effect.Effect.try({
407
+ try: () => InstrumentationConfigSchema.parse(content),
408
+ catch: (error) => new ConfigValidationError({
409
+ reason: "Invalid configuration schema",
410
+ cause: error
411
+ })
412
+ });
413
+ })
414
+ });
415
+ });
416
+ effect.Layer.effect(ConfigLoader, makeConfigLoader);
417
+ var Logger = class {
418
+ constructor() {
419
+ __publicField2(this, "level", "on");
420
+ __publicField2(this, "hasLoggedMinimal", false);
421
+ }
422
+ /**
423
+ * Set the logging level
424
+ */
425
+ setLevel(level) {
426
+ this.level = level;
427
+ this.hasLoggedMinimal = false;
428
+ }
429
+ /**
430
+ * Get the current logging level
431
+ */
432
+ getLevel() {
433
+ return this.level;
434
+ }
435
+ /**
436
+ * Log a minimal initialization message (only shown once in minimal mode)
437
+ */
438
+ minimal(message) {
439
+ if (this.level === "off") {
440
+ return;
441
+ }
442
+ if (this.level === "minimal" && !this.hasLoggedMinimal) {
443
+ console.log(message);
444
+ this.hasLoggedMinimal = true;
445
+ return;
446
+ }
447
+ if (this.level === "on") {
448
+ console.log(message);
449
+ }
450
+ }
451
+ /**
452
+ * Log an informational message
453
+ */
454
+ log(...args) {
455
+ if (this.level === "on") {
456
+ console.log(...args);
457
+ }
458
+ }
459
+ /**
460
+ * Log a warning message (shown in minimal mode)
461
+ */
462
+ warn(...args) {
463
+ if (this.level !== "off") {
464
+ console.warn(...args);
465
+ }
466
+ }
467
+ /**
468
+ * Log an error message (shown in minimal mode)
469
+ */
470
+ error(...args) {
471
+ if (this.level !== "off") {
472
+ console.error(...args);
473
+ }
474
+ }
475
+ /**
476
+ * Check if full logging is enabled
477
+ */
478
+ isEnabled() {
479
+ return this.level === "on";
480
+ }
481
+ /**
482
+ * Check if minimal logging is enabled
483
+ */
484
+ isMinimal() {
485
+ return this.level === "minimal";
486
+ }
487
+ /**
488
+ * Check if logging is completely disabled
489
+ */
490
+ isDisabled() {
491
+ return this.level === "off";
492
+ }
493
+ };
494
+ var logger = new Logger();
495
+ async function loadFromFile(filePath) {
496
+ const { readFile } = await import('fs/promises');
497
+ const content = await readFile(filePath, "utf-8");
498
+ return parseAndValidateConfig(content);
499
+ }
500
+ async function loadFromUrl(url) {
501
+ const response = await fetch(url);
502
+ if (!response.ok) {
503
+ throw new Error(`Failed to fetch config from ${url}: ${response.statusText}`);
504
+ }
505
+ const content = await response.text();
506
+ return parseAndValidateConfig(content);
507
+ }
508
+ async function loadConfig(uri, _options) {
509
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
510
+ return loadFromUrl(uri);
511
+ }
512
+ if (uri.startsWith("file://")) {
513
+ const filePath = uri.slice(7);
514
+ return loadFromFile(filePath);
515
+ }
516
+ return loadFromFile(uri);
517
+ }
518
+ async function loadConfigFromInline(content) {
519
+ return parseAndValidateConfig(content);
520
+ }
521
+ async function loadConfigWithOptions(options = {}) {
522
+ if (options.config) {
523
+ return loadConfigFromInline(options.config);
524
+ }
525
+ const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG;
526
+ if (envConfigPath) {
527
+ return loadConfig(envConfigPath);
528
+ }
529
+ if (options.configUrl) {
530
+ return loadConfig(options.configUrl);
531
+ }
532
+ if (options.configPath) {
533
+ return loadConfig(options.configPath);
534
+ }
535
+ const { existsSync } = await import('fs');
536
+ const { join } = await import('path');
537
+ const defaultPath = join(process.cwd(), "instrumentation.yaml");
538
+ if (existsSync(defaultPath)) {
539
+ return loadConfig(defaultPath);
540
+ }
541
+ return defaultConfig;
542
+ }
543
+
544
+ // src/integrations/effect/auto/config.ts
545
+ var defaultAutoTracingConfig = {
546
+ enabled: false,
547
+ granularity: "fiber",
548
+ span_naming: {
549
+ default: "effect.fiber.{fiber_id}",
550
+ infer_from_source: true,
551
+ rules: []
552
+ },
553
+ filter: {
554
+ include: [],
555
+ exclude: []
556
+ },
557
+ performance: {
558
+ sampling_rate: 1,
559
+ min_duration: "0ms",
560
+ max_concurrent: 0
561
+ },
562
+ metadata: {
563
+ fiber_info: true,
564
+ source_location: true,
565
+ parent_fiber: true
566
+ }
567
+ };
568
+ var AutoTracingConfig = class extends effect.Context.Tag("AutoTracingConfig")() {
569
+ };
570
+ var loadAutoTracingConfig = (options) => effect.Effect.gen(function* () {
571
+ const config = yield* effect.Effect.tryPromise({
572
+ try: () => loadConfigWithOptions(options),
573
+ catch: (error) => {
574
+ logger.log(`@atrim/auto-trace: Failed to load config: ${error}`);
575
+ return error;
576
+ }
577
+ }).pipe(effect.Effect.catchAll(() => effect.Effect.succeed(null)));
578
+ if (!config) {
579
+ logger.log("@atrim/auto-trace: No config found, using defaults");
580
+ return defaultAutoTracingConfig;
581
+ }
582
+ const autoConfig = config.effect?.auto_instrumentation;
583
+ if (!autoConfig) {
584
+ logger.log("@atrim/auto-trace: No auto_instrumentation config, using defaults");
585
+ return defaultAutoTracingConfig;
586
+ }
587
+ const parsed = AutoInstrumentationConfigSchema.safeParse(autoConfig);
588
+ if (!parsed.success) {
589
+ logger.log(`@atrim/auto-trace: Invalid config, using defaults: ${parsed.error.message}`);
590
+ return defaultAutoTracingConfig;
591
+ }
592
+ logger.log("@atrim/auto-trace: Loaded config from instrumentation.yaml");
593
+ return parsed.data;
594
+ });
595
+ var loadAutoTracingConfigSync = () => {
596
+ return defaultAutoTracingConfig;
597
+ };
598
+ var AutoTracingConfigLive = effect.Layer.effect(AutoTracingConfig, loadAutoTracingConfig());
599
+ var AutoTracingConfigLayer = (config) => effect.Layer.succeed(AutoTracingConfig, config);
600
+ var loadFullConfig = (options) => effect.Effect.gen(function* () {
601
+ const config = yield* effect.Effect.tryPromise({
602
+ try: () => loadConfigWithOptions(options),
603
+ catch: (error) => {
604
+ logger.log(`@atrim/auto-trace: Failed to load config: ${error}`);
605
+ return error;
606
+ }
607
+ }).pipe(effect.Effect.catchAll(() => effect.Effect.succeed(null)));
608
+ if (!config) {
609
+ logger.log("@atrim/auto-trace: No config found, using defaults");
610
+ return defaultConfig;
611
+ }
612
+ return config;
613
+ });
614
+ var compiledRulesCache = /* @__PURE__ */ new WeakMap();
615
+ function compileNamingRules(rules) {
616
+ const cached = compiledRulesCache.get(rules);
617
+ if (cached) return cached;
618
+ const compiled = rules.map((rule) => ({
619
+ original: rule,
620
+ filePattern: rule.match.file ? new RegExp(rule.match.file) : void 0,
621
+ functionPattern: rule.match.function ? new RegExp(rule.match.function) : void 0,
622
+ modulePattern: rule.match.module ? new RegExp(rule.match.module) : void 0
623
+ }));
624
+ compiledRulesCache.set(rules, compiled);
625
+ return compiled;
626
+ }
627
+ function extractModuleName(filePath) {
628
+ const basename2 = path__namespace.basename(filePath, path__namespace.extname(filePath));
629
+ return basename2.replace(/\.(service|controller|handler|util|helper|model|repo|repository)$/i, "").replace(/(Service|Controller|Handler|Util|Helper|Model|Repo|Repository)$/i, "");
630
+ }
631
+ function applyTemplate(template, variables, matchGroups) {
632
+ let result = template;
633
+ for (const [key, value] of Object.entries(variables)) {
634
+ result = result.replace(new RegExp(`\\{${key}\\}`, "g"), value);
635
+ }
636
+ if (matchGroups) {
637
+ result = result.replace(
638
+ /\{match:(\w+):(\d+)\}/g,
639
+ (_fullMatch, field, index) => {
640
+ const groups = matchGroups.get(field);
641
+ const idx = parseInt(index, 10);
642
+ if (groups && groups[idx]) {
643
+ return groups[idx];
644
+ }
645
+ return "";
646
+ }
647
+ );
648
+ }
649
+ return result;
650
+ }
651
+ function findMatchingRule(sourceInfo, config) {
652
+ const rules = config.span_naming?.rules;
653
+ if (!rules || rules.length === 0) return void 0;
654
+ const compiledRules = compileNamingRules(rules);
655
+ for (const rule of compiledRules) {
656
+ const matchGroups = /* @__PURE__ */ new Map();
657
+ let allMatched = true;
658
+ if (rule.filePattern) {
659
+ if (sourceInfo?.file) {
660
+ const match = sourceInfo.file.match(rule.filePattern);
661
+ if (match) {
662
+ matchGroups.set("file", match.slice(1));
663
+ } else {
664
+ allMatched = false;
665
+ }
666
+ } else {
667
+ allMatched = false;
668
+ }
669
+ }
670
+ if (rule.functionPattern && allMatched) {
671
+ if (sourceInfo?.function) {
672
+ const match = sourceInfo.function.match(rule.functionPattern);
673
+ if (match) {
674
+ matchGroups.set("function", match.slice(1));
675
+ } else {
676
+ allMatched = false;
677
+ }
678
+ } else {
679
+ allMatched = false;
680
+ }
681
+ }
682
+ if (rule.modulePattern && allMatched) {
683
+ const moduleName = sourceInfo?.file ? extractModuleName(sourceInfo.file) : "";
684
+ if (moduleName) {
685
+ const match = moduleName.match(rule.modulePattern);
686
+ if (match) {
687
+ matchGroups.set("module", match.slice(1));
688
+ } else {
689
+ allMatched = false;
690
+ }
691
+ } else {
692
+ allMatched = false;
693
+ }
694
+ }
695
+ if (allMatched) {
696
+ return { rule, matchGroups };
697
+ }
698
+ }
699
+ return void 0;
700
+ }
701
+ function inferSpanName(fiberId, sourceInfo, config) {
702
+ const variables = {
703
+ fiber_id: String(fiberId),
704
+ function: sourceInfo?.function || "anonymous",
705
+ module: sourceInfo?.file ? extractModuleName(sourceInfo.file) : "unknown",
706
+ file: sourceInfo?.file || "unknown",
707
+ line: sourceInfo?.line ? String(sourceInfo.line) : "0",
708
+ operator: "gen"
709
+ // Default operator, could be enhanced with more context
710
+ };
711
+ const match = findMatchingRule(sourceInfo, config);
712
+ if (match) {
713
+ return applyTemplate(match.rule.original.name, variables, match.matchGroups);
714
+ }
715
+ const defaultTemplate = config.span_naming?.default || "effect.fiber.{fiber_id}";
716
+ return applyTemplate(defaultTemplate, variables);
717
+ }
718
+ function sanitizeSpanName(name) {
719
+ if (!name) return "effect.fiber.unknown";
720
+ let sanitized = name.replace(/[^a-zA-Z0-9._-]/g, "_");
721
+ sanitized = sanitized.replace(/_+/g, "_");
722
+ sanitized = sanitized.replace(/^_+|_+$/g, "");
723
+ if (!sanitized) return "effect.fiber.unknown";
724
+ if (sanitized.length > 256) {
725
+ sanitized = sanitized.substring(0, 256);
726
+ }
727
+ return sanitized;
728
+ }
729
+
730
+ // src/integrations/effect/auto/supervisor.ts
731
+ var AutoTracingEnabled = effect.FiberRef.unsafeMake(true);
732
+ var AutoTracingSpanName = effect.FiberRef.unsafeMake(effect.Option.none());
733
+ var AutoTracingSupervisor = class extends effect.Supervisor.AbstractSupervisor {
734
+ constructor(config) {
735
+ super();
736
+ this.config = config;
737
+ // WeakMap to associate fibers with their OTel spans
738
+ __publicField(this, "fiberSpans", /* @__PURE__ */ new WeakMap());
739
+ // WeakMap for fiber start times (for min_duration filtering)
740
+ __publicField(this, "fiberStartTimes", /* @__PURE__ */ new WeakMap());
741
+ // OpenTelemetry tracer - lazily initialized
742
+ __publicField(this, "_tracer", null);
743
+ // Compiled filter patterns
744
+ __publicField(this, "includePatterns");
745
+ __publicField(this, "excludePatterns");
746
+ // Active fiber count (for max_concurrent limiting)
747
+ __publicField(this, "activeFiberCount", 0);
748
+ // Root span for parent context (set by withAutoTracing)
749
+ __publicField(this, "_rootSpan", null);
750
+ this.includePatterns = (config.filter?.include || []).map((p) => new RegExp(p));
751
+ this.excludePatterns = (config.filter?.exclude || []).map((p) => new RegExp(p));
752
+ logger.log("@atrim/auto-trace: Supervisor initialized");
753
+ logger.log(` Granularity: ${config.granularity || "fiber"}`);
754
+ logger.log(` Sampling rate: ${config.performance?.sampling_rate ?? 1}`);
755
+ logger.log(` Infer from source: ${config.span_naming?.infer_from_source ?? true}`);
756
+ }
757
+ /**
758
+ * Set the root span for parent context propagation
759
+ */
760
+ setRootSpan(span) {
761
+ this._rootSpan = span;
762
+ }
763
+ /**
764
+ * Get the tracer lazily - this allows time for the NodeSdk layer to register the global provider
765
+ */
766
+ get tracer() {
767
+ if (!this._tracer) {
768
+ this._tracer = OtelApi__namespace.trace.getTracer("@atrim/auto-trace", "1.0.0");
769
+ }
770
+ return this._tracer;
771
+ }
772
+ /**
773
+ * Returns the current value (void for this supervisor)
774
+ */
775
+ get value() {
776
+ return effect.Effect.void;
777
+ }
778
+ /**
779
+ * Called when a fiber starts executing
780
+ */
781
+ onStart(_context, _effect, parent, fiber) {
782
+ logger.log(`@atrim/auto-trace: onStart called for fiber ${fiber.id().id}`);
783
+ const fiberRefsValue = fiber.getFiberRefs();
784
+ const enabled = effect.FiberRefs.getOrDefault(fiberRefsValue, AutoTracingEnabled);
785
+ if (!enabled) {
786
+ logger.log(`@atrim/auto-trace: Auto-tracing disabled for fiber ${fiber.id().id}`);
787
+ return;
788
+ }
789
+ const samplingRate = this.config.performance?.sampling_rate ?? 1;
790
+ if (samplingRate < 1 && Math.random() > samplingRate) {
791
+ return;
792
+ }
793
+ const maxConcurrent = this.config.performance?.max_concurrent ?? 0;
794
+ if (maxConcurrent > 0 && this.activeFiberCount >= maxConcurrent) {
795
+ return;
796
+ }
797
+ const nameOverride = effect.FiberRefs.getOrDefault(fiberRefsValue, AutoTracingSpanName);
798
+ const sourceInfo = this.config.span_naming?.infer_from_source ? this.parseStackTrace() : void 0;
799
+ let spanName;
800
+ if (effect.Option.isSome(nameOverride)) {
801
+ spanName = nameOverride.value;
802
+ } else {
803
+ spanName = inferSpanName(fiber.id().id, sourceInfo, this.config);
804
+ }
805
+ if (!this.shouldTrace(spanName)) {
806
+ return;
807
+ }
808
+ let parentContext = OtelApi__namespace.ROOT_CONTEXT;
809
+ let parentFiberId;
810
+ const maybeEffectParentSpan = effect.Context.getOption(_context, effect.Tracer.ParentSpan);
811
+ if (effect.Option.isSome(maybeEffectParentSpan)) {
812
+ const effectSpan = maybeEffectParentSpan.value;
813
+ logger.log(`@atrim/auto-trace: Found ParentSpan - traceId=${effectSpan.traceId.slice(0, 8)}..., spanId=${effectSpan.spanId.slice(0, 8)}...`);
814
+ const otelSpanContext = {
815
+ traceId: effectSpan.traceId,
816
+ spanId: effectSpan.spanId,
817
+ traceFlags: effectSpan.sampled ? OtelApi__namespace.TraceFlags.SAMPLED : OtelApi__namespace.TraceFlags.NONE,
818
+ isRemote: false
819
+ };
820
+ const wrappedSpan = OtelApi__namespace.trace.wrapSpanContext(otelSpanContext);
821
+ parentContext = OtelApi__namespace.trace.setSpan(OtelApi__namespace.ROOT_CONTEXT, wrappedSpan);
822
+ } else if (effect.Option.isSome(parent)) {
823
+ parentFiberId = parent.value.id().id;
824
+ const parentSpan = this.fiberSpans.get(parent.value);
825
+ if (parentSpan) {
826
+ parentContext = OtelApi__namespace.trace.setSpan(OtelApi__namespace.ROOT_CONTEXT, parentSpan);
827
+ } else if (this._rootSpan) {
828
+ parentContext = OtelApi__namespace.trace.setSpan(OtelApi__namespace.ROOT_CONTEXT, this._rootSpan);
829
+ }
830
+ } else if (this._rootSpan) {
831
+ parentContext = OtelApi__namespace.trace.setSpan(OtelApi__namespace.ROOT_CONTEXT, this._rootSpan);
832
+ }
833
+ if (effect.Option.isSome(parent)) {
834
+ parentFiberId = parent.value.id().id;
835
+ }
836
+ const span = this.tracer.startSpan(
837
+ spanName,
838
+ {
839
+ kind: OtelApi__namespace.SpanKind.INTERNAL,
840
+ attributes: this.getInitialAttributes(fiber, sourceInfo, parentFiberId)
841
+ },
842
+ parentContext
843
+ );
844
+ logger.log(`@atrim/auto-trace: Created span "${spanName}" for fiber ${fiber.id().id}`);
845
+ this.fiberSpans.set(fiber, span);
846
+ this.fiberStartTimes.set(fiber, process.hrtime.bigint());
847
+ this.activeFiberCount++;
848
+ }
849
+ /**
850
+ * Called when a fiber completes (success or failure)
851
+ */
852
+ onEnd(exit, fiber) {
853
+ const span = this.fiberSpans.get(fiber);
854
+ if (!span) {
855
+ return;
856
+ }
857
+ const startTime = this.fiberStartTimes.get(fiber);
858
+ if (startTime) {
859
+ const duration = process.hrtime.bigint() - startTime;
860
+ const minDuration = this.parseMinDuration(this.config.performance?.min_duration);
861
+ if (minDuration > 0 && duration < minDuration) {
862
+ this.fiberSpans.delete(fiber);
863
+ this.fiberStartTimes.delete(fiber);
864
+ this.activeFiberCount--;
865
+ return;
866
+ }
867
+ }
868
+ if (effect.Exit.isSuccess(exit)) {
869
+ span.setStatus({ code: OtelApi__namespace.SpanStatusCode.OK });
870
+ } else {
871
+ span.setStatus({
872
+ code: OtelApi__namespace.SpanStatusCode.ERROR,
873
+ message: "Fiber failed"
874
+ });
875
+ span.setAttribute("effect.fiber.failed", true);
876
+ }
877
+ span.end();
878
+ this.fiberSpans.delete(fiber);
879
+ this.fiberStartTimes.delete(fiber);
880
+ this.activeFiberCount--;
881
+ }
882
+ /**
883
+ * Check if a span name should be traced based on filter patterns
884
+ */
885
+ shouldTrace(spanName) {
886
+ for (const pattern of this.excludePatterns) {
887
+ if (pattern.test(spanName)) {
888
+ return false;
889
+ }
890
+ }
891
+ if (this.includePatterns.length > 0) {
892
+ for (const pattern of this.includePatterns) {
893
+ if (pattern.test(spanName)) {
894
+ return true;
895
+ }
896
+ }
897
+ return false;
898
+ }
899
+ return true;
900
+ }
901
+ /**
902
+ * Get initial span attributes for a fiber
903
+ */
904
+ getInitialAttributes(fiber, sourceInfo, parentFiberId) {
905
+ const attrs = {
906
+ "effect.auto_traced": true
907
+ };
908
+ if (this.config.metadata?.fiber_info !== false) {
909
+ attrs["effect.fiber.id"] = fiber.id().id;
910
+ }
911
+ if (this.config.metadata?.source_location !== false && sourceInfo) {
912
+ attrs["code.function"] = sourceInfo.function;
913
+ attrs["code.filepath"] = sourceInfo.file;
914
+ attrs["code.lineno"] = sourceInfo.line;
915
+ attrs["code.column"] = sourceInfo.column;
916
+ }
917
+ if (this.config.metadata?.parent_fiber !== false && parentFiberId !== void 0) {
918
+ attrs["effect.fiber.parent_id"] = parentFiberId;
919
+ }
920
+ return attrs;
921
+ }
922
+ /**
923
+ * Parse stack trace to get source info
924
+ */
925
+ parseStackTrace() {
926
+ const stack = new Error().stack;
927
+ if (!stack) return void 0;
928
+ const lines = stack.split("\n");
929
+ for (let i = 3; i < lines.length; i++) {
930
+ const line = lines[i];
931
+ if (line === void 0) continue;
932
+ if (!line.includes("node_modules/effect") && !line.includes("@atrim/instrument") && !line.includes("auto/supervisor")) {
933
+ const match = line.match(/at\s+(?:(.+?)\s+)?\(?(.+?):(\d+):(\d+)\)?/);
934
+ if (match) {
935
+ const [, funcName, filePath, lineNum, colNum] = match;
936
+ return {
937
+ function: funcName ?? "anonymous",
938
+ file: filePath ?? "unknown",
939
+ line: parseInt(lineNum ?? "0", 10),
940
+ column: parseInt(colNum ?? "0", 10)
941
+ };
942
+ }
943
+ }
944
+ }
945
+ return void 0;
946
+ }
947
+ /**
948
+ * Parse min_duration string to nanoseconds
949
+ */
950
+ parseMinDuration(duration) {
951
+ if (!duration || duration === "0ms") return BigInt(0);
952
+ const match = duration.match(/^(\d+)\s*(ms|millis|s|sec|seconds|us|micros)?$/i);
953
+ if (!match) return BigInt(0);
954
+ const value = parseInt(match[1] ?? "0", 10);
955
+ const unit = (match[2] ?? "ms").toLowerCase();
956
+ switch (unit) {
957
+ case "us":
958
+ case "micros":
959
+ return BigInt(value) * BigInt(1e3);
960
+ case "ms":
961
+ case "millis":
962
+ return BigInt(value) * BigInt(1e6);
963
+ case "s":
964
+ case "sec":
965
+ case "seconds":
966
+ return BigInt(value) * BigInt(1e9);
967
+ default:
968
+ return BigInt(value) * BigInt(1e6);
969
+ }
970
+ }
971
+ };
972
+ var createAutoTracingSupervisor = (config) => {
973
+ return new AutoTracingSupervisor(config);
974
+ };
975
+ var createAutoTracingLayer = (options) => {
976
+ return effect.Layer.unwrapEffect(
977
+ effect.Effect.gen(function* () {
978
+ const config = options?.config ?? (yield* loadAutoTracingConfig());
979
+ if (!config.enabled) {
980
+ logger.log("@atrim/auto-trace: Auto-tracing disabled via config");
981
+ return effect.Layer.empty;
982
+ }
983
+ const supervisor = createAutoTracingSupervisor(config);
984
+ return effect.Supervisor.addSupervisor(supervisor);
985
+ })
986
+ );
987
+ };
988
+ var withAutoTracing = (effect$1, config, mainSpanName) => {
989
+ if (!config.enabled) {
990
+ logger.log("@atrim/auto-trace: Auto-tracing disabled via config");
991
+ return effect$1;
992
+ }
993
+ const supervisor = createAutoTracingSupervisor(config);
994
+ const tracer = OtelApi__namespace.trace.getTracer("@atrim/auto-trace", "1.0.0");
995
+ const spanName = mainSpanName ?? inferSpanName(0, void 0, config);
996
+ const mainSpan = tracer.startSpan(spanName, {
997
+ kind: OtelApi__namespace.SpanKind.INTERNAL,
998
+ attributes: {
999
+ "effect.auto_traced": true,
1000
+ "effect.fiber.id": 0,
1001
+ // Main fiber
1002
+ "effect.main_fiber": true
1003
+ }
1004
+ });
1005
+ supervisor.setRootSpan(mainSpan);
1006
+ return effect.Effect.acquireUseRelease(
1007
+ // Acquire: return the span (already started)
1008
+ effect.Effect.succeed(mainSpan),
1009
+ // Use: run the supervised effect
1010
+ () => effect.Effect.supervised(supervisor)(effect$1),
1011
+ // Release: end the span
1012
+ (span, exit) => effect.Effect.sync(() => {
1013
+ if (effect.Exit.isSuccess(exit)) {
1014
+ span.setStatus({ code: OtelApi__namespace.SpanStatusCode.OK });
1015
+ } else {
1016
+ span.setStatus({
1017
+ code: OtelApi__namespace.SpanStatusCode.ERROR,
1018
+ message: "Effect failed"
1019
+ });
1020
+ }
1021
+ span.end();
1022
+ })
1023
+ );
1024
+ };
1025
+ var AutoTracingLive = createAutoTracingLayer();
1026
+ var withoutAutoTracing = (effect$1) => effect$1.pipe(effect.Effect.locally(AutoTracingEnabled, false));
1027
+ var setSpanName = (name) => (effect$1) => effect$1.pipe(effect.Effect.locally(AutoTracingSpanName, effect.Option.some(name)));
1028
+ var createExporterLayer = (exporterConfig, serviceName, serviceVersion) => {
1029
+ const config = exporterConfig ?? {
1030
+ type: "otlp",
1031
+ processor: "batch",
1032
+ batch: {
1033
+ scheduled_delay_millis: 1e3,
1034
+ max_export_batch_size: 100
1035
+ }
1036
+ };
1037
+ if (config.type === "none") {
1038
+ logger.log('@atrim/auto-trace: Exporter type is "none", no spans will be exported');
1039
+ return effect.Layer.empty;
1040
+ }
1041
+ const createSpanExporter = () => {
1042
+ if (config.type === "console") {
1043
+ logger.log("@atrim/auto-trace: Using ConsoleSpanExporter");
1044
+ return new sdkTraceBase.ConsoleSpanExporter();
1045
+ }
1046
+ const endpoint = config.endpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318";
1047
+ logger.log(`@atrim/auto-trace: Using OTLPTraceExporter (${endpoint})`);
1048
+ const exporterConfig2 = {
1049
+ url: `${endpoint}/v1/traces`
1050
+ };
1051
+ if (config.headers) {
1052
+ exporterConfig2.headers = config.headers;
1053
+ logger.log(`@atrim/auto-trace: Using custom headers: ${Object.keys(config.headers).join(", ")}`);
1054
+ }
1055
+ return new exporterTraceOtlpHttp.OTLPTraceExporter(exporterConfig2);
1056
+ };
1057
+ const createSpanProcessor = () => {
1058
+ const exporter = createSpanExporter();
1059
+ if (config.processor === "simple" || config.type === "console") {
1060
+ logger.log("@atrim/auto-trace: Using SimpleSpanProcessor");
1061
+ return new sdkTraceBase.SimpleSpanProcessor(exporter);
1062
+ }
1063
+ const batchConfig = config.batch ?? {
1064
+ scheduled_delay_millis: 1e3,
1065
+ max_export_batch_size: 100
1066
+ };
1067
+ logger.log("@atrim/auto-trace: Using BatchSpanProcessor");
1068
+ return new sdkTraceBase.BatchSpanProcessor(exporter, {
1069
+ scheduledDelayMillis: batchConfig.scheduled_delay_millis,
1070
+ maxExportBatchSize: batchConfig.max_export_batch_size
1071
+ });
1072
+ };
1073
+ return effect.Layer.effectDiscard(
1074
+ effect.Effect.sync(() => {
1075
+ const provider = new sdkTraceBase.BasicTracerProvider({
1076
+ resource: resources.resourceFromAttributes({
1077
+ [semanticConventions.ATTR_SERVICE_NAME]: serviceName,
1078
+ [semanticConventions.ATTR_SERVICE_VERSION]: serviceVersion
1079
+ }),
1080
+ spanProcessors: [createSpanProcessor()]
1081
+ });
1082
+ OtelApi__namespace.trace.setGlobalTracerProvider(provider);
1083
+ logger.log("@atrim/auto-trace: Global TracerProvider registered");
1084
+ return () => {
1085
+ provider.shutdown().catch((err) => {
1086
+ logger.log(`@atrim/auto-trace: Error shutting down provider: ${err}`);
1087
+ });
1088
+ };
1089
+ })
1090
+ );
1091
+ };
1092
+ var createFullAutoTracingLayer = () => {
1093
+ return effect.Layer.unwrapEffect(
1094
+ effect.Effect.gen(function* () {
1095
+ const config = yield* loadFullConfig();
1096
+ const serviceName = process.env.OTEL_SERVICE_NAME || "effect-service";
1097
+ const serviceVersion = process.env.npm_package_version || "1.0.0";
1098
+ const autoConfig = config.effect?.auto_instrumentation;
1099
+ if (!autoConfig?.enabled) {
1100
+ logger.log("@atrim/auto-trace: Auto-instrumentation disabled via config");
1101
+ return effect.Layer.empty;
1102
+ }
1103
+ const exporterConfig = config.effect?.exporter_config;
1104
+ logger.log("@atrim/auto-trace: Full auto-instrumentation enabled");
1105
+ logger.log(` Service: ${serviceName}`);
1106
+ logger.log(` Exporter: ${exporterConfig?.type ?? "otlp"}`);
1107
+ const exporterLayer = createExporterLayer(exporterConfig, serviceName, serviceVersion);
1108
+ const supervisor = createAutoTracingSupervisor(autoConfig);
1109
+ const supervisorLayer = effect.Supervisor.addSupervisor(supervisor);
1110
+ return effect.Layer.mergeAll(exporterLayer, supervisorLayer);
1111
+ })
1112
+ );
1113
+ };
1114
+ var FullAutoTracingLive = createFullAutoTracingLayer();
1115
+
1116
+ // src/integrations/effect/auto/effect-tracing.ts
1117
+ var createEffectTracingLayer = () => {
1118
+ return effect.Layer.unwrapEffect(
1119
+ effect.Effect.gen(function* () {
1120
+ const config = yield* loadFullConfig();
1121
+ const serviceName = process.env.OTEL_SERVICE_NAME || "effect-service";
1122
+ const serviceVersion = process.env.npm_package_version || "1.0.0";
1123
+ const exporterConfig = config.effect?.exporter_config ?? {
1124
+ type: "otlp",
1125
+ processor: "batch"
1126
+ };
1127
+ logger.log("@atrim/auto-trace: Effect-native tracing enabled");
1128
+ logger.log(` Service: ${serviceName}`);
1129
+ logger.log(` Exporter: ${exporterConfig.type}`);
1130
+ if (exporterConfig.type === "none") {
1131
+ logger.log('@atrim/auto-trace: Exporter type is "none", using empty layer');
1132
+ return effect.Layer.empty;
1133
+ }
1134
+ const createSpanProcessor = () => {
1135
+ if (exporterConfig.type === "console") {
1136
+ logger.log("@atrim/auto-trace: Using ConsoleSpanExporter with SimpleSpanProcessor");
1137
+ return new sdkTraceBase.SimpleSpanProcessor(new sdkTraceBase.ConsoleSpanExporter());
1138
+ }
1139
+ const endpoint = exporterConfig.endpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318";
1140
+ logger.log(`@atrim/auto-trace: Using OTLPTraceExporter (${endpoint})`);
1141
+ const otlpConfig = {
1142
+ url: `${endpoint}/v1/traces`
1143
+ };
1144
+ if (exporterConfig.headers) {
1145
+ otlpConfig.headers = exporterConfig.headers;
1146
+ logger.log(`@atrim/auto-trace: Using custom headers: ${Object.keys(exporterConfig.headers).join(", ")}`);
1147
+ }
1148
+ const exporter = new exporterTraceOtlpHttp.OTLPTraceExporter(otlpConfig);
1149
+ if (exporterConfig.processor === "simple") {
1150
+ logger.log("@atrim/auto-trace: Using SimpleSpanProcessor");
1151
+ return new sdkTraceBase.SimpleSpanProcessor(exporter);
1152
+ }
1153
+ const batchConfig = exporterConfig.batch ?? {
1154
+ scheduled_delay_millis: 1e3,
1155
+ max_export_batch_size: 100
1156
+ };
1157
+ logger.log("@atrim/auto-trace: Using BatchSpanProcessor");
1158
+ return new sdkTraceBase.BatchSpanProcessor(exporter, {
1159
+ scheduledDelayMillis: batchConfig.scheduled_delay_millis,
1160
+ maxExportBatchSize: batchConfig.max_export_batch_size
1161
+ });
1162
+ };
1163
+ const sdkLayer = opentelemetry.NodeSdk.layer(() => ({
1164
+ resource: {
1165
+ serviceName,
1166
+ serviceVersion
1167
+ },
1168
+ spanProcessor: createSpanProcessor()
1169
+ }));
1170
+ logger.log("@atrim/auto-trace: NodeSdk layer created - HTTP requests will be auto-traced");
1171
+ return effect.Layer.discard(sdkLayer);
1172
+ })
1173
+ );
1174
+ };
1175
+ var EffectTracingLive = createEffectTracingLayer();
1176
+ var createCombinedTracingLayer = () => {
1177
+ return effect.Layer.unwrapEffect(
1178
+ effect.Effect.gen(function* () {
1179
+ const config = yield* loadFullConfig();
1180
+ const serviceName = process.env.OTEL_SERVICE_NAME || "effect-service";
1181
+ const serviceVersion = process.env.npm_package_version || "1.0.0";
1182
+ const exporterConfig = config.effect?.exporter_config ?? {
1183
+ type: "otlp",
1184
+ processor: "batch"
1185
+ };
1186
+ const autoConfig = config.effect?.auto_instrumentation ?? {
1187
+ enabled: true,
1188
+ granularity: "fiber",
1189
+ span_naming: {
1190
+ default: "effect.{function}",
1191
+ infer_from_source: true,
1192
+ rules: []
1193
+ },
1194
+ filter: { include: [], exclude: [] },
1195
+ performance: { sampling_rate: 1, min_duration: "0ms", max_concurrent: 0 },
1196
+ metadata: { fiber_info: true, source_location: true, parent_fiber: true }
1197
+ };
1198
+ logger.log("@atrim/auto-trace: Combined tracing enabled (HTTP + Fiber)");
1199
+ logger.log(` Service: ${serviceName}`);
1200
+ logger.log(` Exporter: ${exporterConfig.type}`);
1201
+ if (exporterConfig.type === "none") {
1202
+ logger.log('@atrim/auto-trace: Exporter type is "none", using empty layer');
1203
+ return effect.Layer.empty;
1204
+ }
1205
+ const createSpanProcessor = () => {
1206
+ if (exporterConfig.type === "console") {
1207
+ logger.log("@atrim/auto-trace: Using ConsoleSpanExporter with SimpleSpanProcessor");
1208
+ return new sdkTraceBase.SimpleSpanProcessor(new sdkTraceBase.ConsoleSpanExporter());
1209
+ }
1210
+ const endpoint = exporterConfig.endpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318";
1211
+ logger.log(`@atrim/auto-trace: Using OTLPTraceExporter (${endpoint})`);
1212
+ const otlpConfig = {
1213
+ url: `${endpoint}/v1/traces`
1214
+ };
1215
+ if (exporterConfig.headers) {
1216
+ otlpConfig.headers = exporterConfig.headers;
1217
+ logger.log(`@atrim/auto-trace: Using custom headers: ${Object.keys(exporterConfig.headers).join(", ")}`);
1218
+ }
1219
+ const exporter = new exporterTraceOtlpHttp.OTLPTraceExporter(otlpConfig);
1220
+ if (exporterConfig.processor === "simple") {
1221
+ logger.log("@atrim/auto-trace: Using SimpleSpanProcessor");
1222
+ return new sdkTraceBase.SimpleSpanProcessor(exporter);
1223
+ }
1224
+ const batchConfig = exporterConfig.batch ?? {
1225
+ scheduled_delay_millis: 1e3,
1226
+ max_export_batch_size: 100
1227
+ };
1228
+ logger.log("@atrim/auto-trace: Using BatchSpanProcessor");
1229
+ return new sdkTraceBase.BatchSpanProcessor(exporter, {
1230
+ scheduledDelayMillis: batchConfig.scheduled_delay_millis,
1231
+ maxExportBatchSize: batchConfig.max_export_batch_size
1232
+ });
1233
+ };
1234
+ const sdkLayer = opentelemetry.NodeSdk.layer(() => ({
1235
+ resource: {
1236
+ serviceName,
1237
+ serviceVersion
1238
+ },
1239
+ spanProcessor: createSpanProcessor()
1240
+ }));
1241
+ const supervisor = createAutoTracingSupervisor(autoConfig);
1242
+ const supervisorLayer = effect.Supervisor.addSupervisor(supervisor);
1243
+ logger.log("@atrim/auto-trace: Combined layer created");
1244
+ logger.log(" - HTTP requests: auto-traced via Effect platform");
1245
+ logger.log(" - Forked fibers: auto-traced via Supervisor");
1246
+ return supervisorLayer.pipe(effect.Layer.provideMerge(effect.Layer.discard(sdkLayer)));
1247
+ })
1248
+ );
1249
+ };
1250
+ var CombinedTracingLive = createCombinedTracingLayer();
1251
+
1252
+ exports.AutoTracingConfig = AutoTracingConfig;
1253
+ exports.AutoTracingConfigLayer = AutoTracingConfigLayer;
1254
+ exports.AutoTracingConfigLive = AutoTracingConfigLive;
1255
+ exports.AutoTracingEnabled = AutoTracingEnabled;
1256
+ exports.AutoTracingLive = AutoTracingLive;
1257
+ exports.AutoTracingSpanName = AutoTracingSpanName;
1258
+ exports.AutoTracingSupervisor = AutoTracingSupervisor;
1259
+ exports.CombinedTracingLive = CombinedTracingLive;
1260
+ exports.EffectTracingLive = EffectTracingLive;
1261
+ exports.FullAutoTracingLive = FullAutoTracingLive;
1262
+ exports.createAutoTracingLayer = createAutoTracingLayer;
1263
+ exports.createAutoTracingSupervisor = createAutoTracingSupervisor;
1264
+ exports.createCombinedTracingLayer = createCombinedTracingLayer;
1265
+ exports.createEffectTracingLayer = createEffectTracingLayer;
1266
+ exports.createFullAutoTracingLayer = createFullAutoTracingLayer;
1267
+ exports.defaultAutoTracingConfig = defaultAutoTracingConfig;
1268
+ exports.inferSpanName = inferSpanName;
1269
+ exports.loadAutoTracingConfig = loadAutoTracingConfig;
1270
+ exports.loadAutoTracingConfigSync = loadAutoTracingConfigSync;
1271
+ exports.sanitizeSpanName = sanitizeSpanName;
1272
+ exports.setSpanName = setSpanName;
1273
+ exports.withAutoTracing = withAutoTracing;
1274
+ exports.withoutAutoTracing = withoutAutoTracing;
1275
+ //# sourceMappingURL=index.cjs.map
1276
+ //# sourceMappingURL=index.cjs.map