@atrim/instrument-node 0.5.2-dev.ac2fbfe.20251221205322 → 0.7.0-b9eaf74-20260108193056

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,915 @@
1
+ 'use strict';
2
+
3
+ var effect = require('effect');
4
+ var OtelApi = require('@opentelemetry/api');
5
+ var FileSystem = require('@effect/platform/FileSystem');
6
+ var HttpClient = require('@effect/platform/HttpClient');
7
+ var HttpClientRequest = require('@effect/platform/HttpClientRequest');
8
+ var yaml = require('yaml');
9
+ var zod = require('zod');
10
+ var path = require('path');
11
+
12
+ function _interopNamespace(e) {
13
+ if (e && e.__esModule) return e;
14
+ var n = Object.create(null);
15
+ if (e) {
16
+ Object.keys(e).forEach(function (k) {
17
+ if (k !== 'default') {
18
+ var d = Object.getOwnPropertyDescriptor(e, k);
19
+ Object.defineProperty(n, k, d.get ? d : {
20
+ enumerable: true,
21
+ get: function () { return e[k]; }
22
+ });
23
+ }
24
+ });
25
+ }
26
+ n.default = e;
27
+ return Object.freeze(n);
28
+ }
29
+
30
+ var OtelApi__namespace = /*#__PURE__*/_interopNamespace(OtelApi);
31
+ var HttpClient__namespace = /*#__PURE__*/_interopNamespace(HttpClient);
32
+ var HttpClientRequest__namespace = /*#__PURE__*/_interopNamespace(HttpClientRequest);
33
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
34
+
35
+ var __defProp = Object.defineProperty;
36
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
37
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
38
+ var __defProp2 = Object.defineProperty;
39
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
40
+ var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
41
+ var PatternConfigSchema = zod.z.object({
42
+ pattern: zod.z.string(),
43
+ enabled: zod.z.boolean().optional(),
44
+ description: zod.z.string().optional()
45
+ });
46
+ var AutoIsolationConfigSchema = zod.z.object({
47
+ // Global enable/disable for auto-isolation
48
+ enabled: zod.z.boolean().default(false),
49
+ // Which operators to auto-isolate
50
+ operators: zod.z.object({
51
+ fiberset_run: zod.z.boolean().default(true),
52
+ effect_fork: zod.z.boolean().default(true),
53
+ effect_fork_daemon: zod.z.boolean().default(true),
54
+ effect_fork_in: zod.z.boolean().default(false)
55
+ }).default({}),
56
+ // Virtual parent tracking configuration
57
+ tracking: zod.z.object({
58
+ use_span_links: zod.z.boolean().default(true),
59
+ use_attributes: zod.z.boolean().default(true),
60
+ capture_logical_parent: zod.z.boolean().default(true)
61
+ }).default({}),
62
+ // Span categorization
63
+ attributes: zod.z.object({
64
+ category: zod.z.string().default("background_task"),
65
+ add_metadata: zod.z.boolean().default(true)
66
+ }).default({})
67
+ });
68
+ var SpanNamingRuleSchema = zod.z.object({
69
+ // Match criteria (all specified criteria must match)
70
+ match: zod.z.object({
71
+ // Regex pattern to match file path
72
+ file: zod.z.string().optional(),
73
+ // Regex pattern to match function name
74
+ function: zod.z.string().optional(),
75
+ // Regex pattern to match module name
76
+ module: zod.z.string().optional()
77
+ }),
78
+ // Span name template with variables:
79
+ // {fiber_id} - Fiber ID
80
+ // {function} - Function name
81
+ // {module} - Module name
82
+ // {file} - File path
83
+ // {line} - Line number
84
+ // {operator} - Effect operator (gen, all, forEach, etc.)
85
+ // {match:field:N} - Captured regex group from match
86
+ name: zod.z.string()
87
+ });
88
+ var AutoInstrumentationConfigSchema = zod.z.object({
89
+ // Enable/disable auto-instrumentation
90
+ enabled: zod.z.boolean().default(false),
91
+ // Tracing granularity
92
+ // - 'fiber': Trace at fiber creation (recommended, lower overhead)
93
+ // - 'operator': Trace each Effect operator (higher granularity, more overhead)
94
+ granularity: zod.z.enum(["fiber", "operator"]).default("fiber"),
95
+ // Smart span naming configuration
96
+ span_naming: zod.z.object({
97
+ // Default span name template when no rules match
98
+ default: zod.z.string().default("effect.fiber.{fiber_id}"),
99
+ // Infer span names from source code (requires stack trace parsing)
100
+ // Adds ~50-100μs overhead per fiber
101
+ infer_from_source: zod.z.boolean().default(true),
102
+ // Naming rules (first match wins)
103
+ rules: zod.z.array(SpanNamingRuleSchema).default([])
104
+ }).default({}),
105
+ // Pattern-based filtering
106
+ filter: zod.z.object({
107
+ // Only trace spans matching these patterns (empty = trace all)
108
+ include: zod.z.array(zod.z.string()).default([]),
109
+ // Never trace spans matching these patterns
110
+ exclude: zod.z.array(zod.z.string()).default([])
111
+ }).default({}),
112
+ // Performance controls
113
+ performance: zod.z.object({
114
+ // Sample rate (0.0 - 1.0)
115
+ sampling_rate: zod.z.number().min(0).max(1).default(1),
116
+ // Skip fibers shorter than this duration (e.g., "10ms", "100 millis")
117
+ min_duration: zod.z.string().default("0ms"),
118
+ // Maximum concurrent traced fibers (0 = unlimited)
119
+ max_concurrent: zod.z.number().default(0)
120
+ }).default({}),
121
+ // Automatic metadata extraction
122
+ metadata: zod.z.object({
123
+ // Extract Effect fiber information
124
+ fiber_info: zod.z.boolean().default(true),
125
+ // Extract source location (file:line)
126
+ source_location: zod.z.boolean().default(true),
127
+ // Extract parent fiber information
128
+ parent_fiber: zod.z.boolean().default(true)
129
+ }).default({})
130
+ });
131
+ var HttpFilteringConfigSchema = zod.z.object({
132
+ // Patterns to ignore for outgoing HTTP requests (string patterns only in YAML)
133
+ ignore_outgoing_urls: zod.z.array(zod.z.string()).optional(),
134
+ // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)
135
+ ignore_incoming_paths: zod.z.array(zod.z.string()).optional(),
136
+ // Require parent span for outgoing requests (prevents root spans for HTTP calls)
137
+ require_parent_for_outgoing_spans: zod.z.boolean().optional(),
138
+ // Trace context propagation configuration
139
+ // Controls which cross-origin requests receive W3C Trace Context headers (traceparent, tracestate)
140
+ propagate_trace_context: zod.z.object({
141
+ // Strategy for trace propagation
142
+ // - "all": Propagate to all cross-origin requests (may cause CORS errors)
143
+ // - "none": Never propagate trace headers
144
+ // - "same-origin": Only propagate to same-origin requests (default, safe)
145
+ // - "patterns": Propagate based on include_urls patterns
146
+ strategy: zod.z.enum(["all", "none", "same-origin", "patterns"]).default("same-origin"),
147
+ // URL patterns to include when strategy is "patterns"
148
+ // Supports regex patterns (e.g., "^https://api\\.myapp\\.com")
149
+ include_urls: zod.z.array(zod.z.string()).optional()
150
+ }).optional()
151
+ });
152
+ var InstrumentationConfigSchema = zod.z.object({
153
+ version: zod.z.string(),
154
+ instrumentation: zod.z.object({
155
+ enabled: zod.z.boolean(),
156
+ description: zod.z.string().optional(),
157
+ logging: zod.z.enum(["on", "off", "minimal"]).optional().default("on"),
158
+ instrument_patterns: zod.z.array(PatternConfigSchema),
159
+ ignore_patterns: zod.z.array(PatternConfigSchema)
160
+ }),
161
+ effect: zod.z.object({
162
+ // Enable/disable Effect tracing entirely
163
+ // When false, EffectInstrumentationLive returns Layer.empty
164
+ enabled: zod.z.boolean().default(true),
165
+ // Exporter mode:
166
+ // - "unified": Use global TracerProvider from Node SDK (recommended, enables filtering)
167
+ // - "standalone": Use Effect's own OTLP exporter (bypasses Node SDK filtering)
168
+ exporter: zod.z.enum(["unified", "standalone"]).default("unified"),
169
+ auto_extract_metadata: zod.z.boolean(),
170
+ auto_isolation: AutoIsolationConfigSchema.optional(),
171
+ // Auto-instrumentation: automatic tracing of all Effect fibers
172
+ auto_instrumentation: AutoInstrumentationConfigSchema.optional()
173
+ }).optional(),
174
+ http: HttpFilteringConfigSchema.optional()
175
+ });
176
+ var defaultConfig = {
177
+ version: "1.0",
178
+ instrumentation: {
179
+ enabled: true,
180
+ logging: "on",
181
+ description: "Default instrumentation configuration",
182
+ instrument_patterns: [
183
+ { pattern: "^app\\.", enabled: true, description: "Application operations" },
184
+ { pattern: "^http\\.server\\.", enabled: true, description: "HTTP server operations" },
185
+ { pattern: "^http\\.client\\.", enabled: true, description: "HTTP client operations" }
186
+ ],
187
+ ignore_patterns: [
188
+ { pattern: "^test\\.", description: "Test utilities" },
189
+ { pattern: "^internal\\.", description: "Internal operations" },
190
+ { pattern: "^health\\.", description: "Health checks" }
191
+ ]
192
+ },
193
+ effect: {
194
+ enabled: true,
195
+ exporter: "unified",
196
+ auto_extract_metadata: true
197
+ }
198
+ };
199
+ function parseAndValidateConfig(content) {
200
+ let parsed;
201
+ if (typeof content === "string") {
202
+ parsed = yaml.parse(content);
203
+ } else {
204
+ parsed = content;
205
+ }
206
+ return InstrumentationConfigSchema.parse(parsed);
207
+ }
208
+ (class extends effect.Data.TaggedError("ConfigError") {
209
+ get message() {
210
+ return this.reason;
211
+ }
212
+ });
213
+ var ConfigUrlError = class extends effect.Data.TaggedError("ConfigUrlError") {
214
+ get message() {
215
+ return this.reason;
216
+ }
217
+ };
218
+ var ConfigValidationError = class extends effect.Data.TaggedError("ConfigValidationError") {
219
+ get message() {
220
+ return this.reason;
221
+ }
222
+ };
223
+ var ConfigFileError = class extends effect.Data.TaggedError("ConfigFileError") {
224
+ get message() {
225
+ return this.reason;
226
+ }
227
+ };
228
+ (class extends effect.Data.TaggedError("ServiceDetectionError") {
229
+ get message() {
230
+ return this.reason;
231
+ }
232
+ });
233
+ (class extends effect.Data.TaggedError("InitializationError") {
234
+ get message() {
235
+ return this.reason;
236
+ }
237
+ });
238
+ (class extends effect.Data.TaggedError("ExportError") {
239
+ get message() {
240
+ return this.reason;
241
+ }
242
+ });
243
+ (class extends effect.Data.TaggedError("ShutdownError") {
244
+ get message() {
245
+ return this.reason;
246
+ }
247
+ });
248
+ var SECURITY_DEFAULTS = {
249
+ maxConfigSize: 1e6,
250
+ // 1MB
251
+ requestTimeout: 5e3
252
+ // 5 seconds
253
+ };
254
+ var ConfigLoader = class extends effect.Context.Tag("ConfigLoader")() {
255
+ };
256
+ var parseYamlContent = (content, uri) => effect.Effect.gen(function* () {
257
+ const parsed = yield* effect.Effect.try({
258
+ try: () => yaml.parse(content),
259
+ catch: (error) => new ConfigValidationError({
260
+ reason: uri ? `Failed to parse YAML from ${uri}` : "Failed to parse YAML",
261
+ cause: error
262
+ })
263
+ });
264
+ return yield* effect.Effect.try({
265
+ try: () => InstrumentationConfigSchema.parse(parsed),
266
+ catch: (error) => new ConfigValidationError({
267
+ reason: uri ? `Invalid configuration schema from ${uri}` : "Invalid configuration schema",
268
+ cause: error
269
+ })
270
+ });
271
+ });
272
+ var loadFromFileWithFs = (fs, path2, uri) => effect.Effect.gen(function* () {
273
+ const content = yield* fs.readFileString(path2).pipe(
274
+ effect.Effect.mapError(
275
+ (error) => new ConfigFileError({
276
+ reason: `Failed to read config file at ${uri}`,
277
+ cause: error
278
+ })
279
+ )
280
+ );
281
+ if (content.length > SECURITY_DEFAULTS.maxConfigSize) {
282
+ return yield* effect.Effect.fail(
283
+ new ConfigFileError({
284
+ reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
285
+ })
286
+ );
287
+ }
288
+ return yield* parseYamlContent(content, uri);
289
+ });
290
+ var loadFromHttpWithClient = (client, url) => effect.Effect.scoped(
291
+ effect.Effect.gen(function* () {
292
+ if (url.startsWith("http://")) {
293
+ return yield* effect.Effect.fail(
294
+ new ConfigUrlError({
295
+ reason: "Insecure protocol: only HTTPS URLs are allowed"
296
+ })
297
+ );
298
+ }
299
+ const request = HttpClientRequest__namespace.get(url).pipe(
300
+ HttpClientRequest__namespace.setHeaders({
301
+ Accept: "application/yaml, text/yaml, application/x-yaml"
302
+ })
303
+ );
304
+ const response = yield* client.execute(request).pipe(
305
+ effect.Effect.timeout(`${SECURITY_DEFAULTS.requestTimeout} millis`),
306
+ effect.Effect.mapError((error) => {
307
+ if (error._tag === "TimeoutException") {
308
+ return new ConfigUrlError({
309
+ reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms from ${url}`
310
+ });
311
+ }
312
+ return new ConfigUrlError({
313
+ reason: `Failed to load config from URL: ${url}`,
314
+ cause: error
315
+ });
316
+ })
317
+ );
318
+ if (response.status >= 400) {
319
+ return yield* effect.Effect.fail(
320
+ new ConfigUrlError({
321
+ reason: `HTTP ${response.status} from ${url}`
322
+ })
323
+ );
324
+ }
325
+ const text = yield* response.text.pipe(
326
+ effect.Effect.mapError(
327
+ (error) => new ConfigUrlError({
328
+ reason: `Failed to read response body from ${url}`,
329
+ cause: error
330
+ })
331
+ )
332
+ );
333
+ if (text.length > SECURITY_DEFAULTS.maxConfigSize) {
334
+ return yield* effect.Effect.fail(
335
+ new ConfigUrlError({
336
+ reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
337
+ })
338
+ );
339
+ }
340
+ return yield* parseYamlContent(text, url);
341
+ })
342
+ );
343
+ var makeConfigLoader = effect.Effect.gen(function* () {
344
+ const fs = yield* effect.Effect.serviceOption(FileSystem.FileSystem);
345
+ const http = yield* HttpClient__namespace.HttpClient;
346
+ const loadFromUriUncached = (uri) => effect.Effect.gen(function* () {
347
+ if (uri.startsWith("file://")) {
348
+ const path2 = uri.slice(7);
349
+ if (fs._tag === "None") {
350
+ return yield* effect.Effect.fail(
351
+ new ConfigFileError({
352
+ reason: "FileSystem not available (browser environment?)",
353
+ cause: { uri }
354
+ })
355
+ );
356
+ }
357
+ return yield* loadFromFileWithFs(fs.value, path2, uri);
358
+ }
359
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
360
+ return yield* loadFromHttpWithClient(http, uri);
361
+ }
362
+ if (fs._tag === "Some") {
363
+ return yield* loadFromFileWithFs(fs.value, uri, uri);
364
+ } else {
365
+ return yield* loadFromHttpWithClient(http, uri);
366
+ }
367
+ });
368
+ const loadFromUriCached = yield* effect.Effect.cachedFunction(loadFromUriUncached);
369
+ return ConfigLoader.of({
370
+ loadFromUri: loadFromUriCached,
371
+ loadFromInline: (content) => effect.Effect.gen(function* () {
372
+ if (typeof content === "string") {
373
+ return yield* parseYamlContent(content);
374
+ }
375
+ return yield* effect.Effect.try({
376
+ try: () => InstrumentationConfigSchema.parse(content),
377
+ catch: (error) => new ConfigValidationError({
378
+ reason: "Invalid configuration schema",
379
+ cause: error
380
+ })
381
+ });
382
+ })
383
+ });
384
+ });
385
+ effect.Layer.effect(ConfigLoader, makeConfigLoader);
386
+ var Logger = class {
387
+ constructor() {
388
+ __publicField2(this, "level", "on");
389
+ __publicField2(this, "hasLoggedMinimal", false);
390
+ }
391
+ /**
392
+ * Set the logging level
393
+ */
394
+ setLevel(level) {
395
+ this.level = level;
396
+ this.hasLoggedMinimal = false;
397
+ }
398
+ /**
399
+ * Get the current logging level
400
+ */
401
+ getLevel() {
402
+ return this.level;
403
+ }
404
+ /**
405
+ * Log a minimal initialization message (only shown once in minimal mode)
406
+ */
407
+ minimal(message) {
408
+ if (this.level === "off") {
409
+ return;
410
+ }
411
+ if (this.level === "minimal" && !this.hasLoggedMinimal) {
412
+ console.log(message);
413
+ this.hasLoggedMinimal = true;
414
+ return;
415
+ }
416
+ if (this.level === "on") {
417
+ console.log(message);
418
+ }
419
+ }
420
+ /**
421
+ * Log an informational message
422
+ */
423
+ log(...args) {
424
+ if (this.level === "on") {
425
+ console.log(...args);
426
+ }
427
+ }
428
+ /**
429
+ * Log a warning message (shown in minimal mode)
430
+ */
431
+ warn(...args) {
432
+ if (this.level !== "off") {
433
+ console.warn(...args);
434
+ }
435
+ }
436
+ /**
437
+ * Log an error message (shown in minimal mode)
438
+ */
439
+ error(...args) {
440
+ if (this.level !== "off") {
441
+ console.error(...args);
442
+ }
443
+ }
444
+ /**
445
+ * Check if full logging is enabled
446
+ */
447
+ isEnabled() {
448
+ return this.level === "on";
449
+ }
450
+ /**
451
+ * Check if minimal logging is enabled
452
+ */
453
+ isMinimal() {
454
+ return this.level === "minimal";
455
+ }
456
+ /**
457
+ * Check if logging is completely disabled
458
+ */
459
+ isDisabled() {
460
+ return this.level === "off";
461
+ }
462
+ };
463
+ var logger = new Logger();
464
+ var compiledRulesCache = /* @__PURE__ */ new WeakMap();
465
+ function compileNamingRules(rules) {
466
+ const cached = compiledRulesCache.get(rules);
467
+ if (cached) return cached;
468
+ const compiled = rules.map((rule) => ({
469
+ original: rule,
470
+ filePattern: rule.match.file ? new RegExp(rule.match.file) : void 0,
471
+ functionPattern: rule.match.function ? new RegExp(rule.match.function) : void 0,
472
+ modulePattern: rule.match.module ? new RegExp(rule.match.module) : void 0
473
+ }));
474
+ compiledRulesCache.set(rules, compiled);
475
+ return compiled;
476
+ }
477
+ function extractModuleName(filePath) {
478
+ const basename2 = path__namespace.basename(filePath, path__namespace.extname(filePath));
479
+ return basename2.replace(/\.(service|controller|handler|util|helper|model|repo|repository)$/i, "").replace(/(Service|Controller|Handler|Util|Helper|Model|Repo|Repository)$/i, "");
480
+ }
481
+ function applyTemplate(template, variables, matchGroups) {
482
+ let result = template;
483
+ for (const [key, value] of Object.entries(variables)) {
484
+ result = result.replace(new RegExp(`\\{${key}\\}`, "g"), value);
485
+ }
486
+ if (matchGroups) {
487
+ result = result.replace(
488
+ /\{match:(\w+):(\d+)\}/g,
489
+ (_fullMatch, field, index) => {
490
+ const groups = matchGroups.get(field);
491
+ const idx = parseInt(index, 10);
492
+ if (groups && groups[idx]) {
493
+ return groups[idx];
494
+ }
495
+ return "";
496
+ }
497
+ );
498
+ }
499
+ return result;
500
+ }
501
+ function findMatchingRule(sourceInfo, config) {
502
+ const rules = config.span_naming?.rules;
503
+ if (!rules || rules.length === 0) return void 0;
504
+ const compiledRules = compileNamingRules(rules);
505
+ for (const rule of compiledRules) {
506
+ const matchGroups = /* @__PURE__ */ new Map();
507
+ let allMatched = true;
508
+ if (rule.filePattern) {
509
+ if (sourceInfo?.file) {
510
+ const match = sourceInfo.file.match(rule.filePattern);
511
+ if (match) {
512
+ matchGroups.set("file", match.slice(1));
513
+ } else {
514
+ allMatched = false;
515
+ }
516
+ } else {
517
+ allMatched = false;
518
+ }
519
+ }
520
+ if (rule.functionPattern && allMatched) {
521
+ if (sourceInfo?.function) {
522
+ const match = sourceInfo.function.match(rule.functionPattern);
523
+ if (match) {
524
+ matchGroups.set("function", match.slice(1));
525
+ } else {
526
+ allMatched = false;
527
+ }
528
+ } else {
529
+ allMatched = false;
530
+ }
531
+ }
532
+ if (rule.modulePattern && allMatched) {
533
+ const moduleName = sourceInfo?.file ? extractModuleName(sourceInfo.file) : "";
534
+ if (moduleName) {
535
+ const match = moduleName.match(rule.modulePattern);
536
+ if (match) {
537
+ matchGroups.set("module", match.slice(1));
538
+ } else {
539
+ allMatched = false;
540
+ }
541
+ } else {
542
+ allMatched = false;
543
+ }
544
+ }
545
+ if (allMatched) {
546
+ return { rule, matchGroups };
547
+ }
548
+ }
549
+ return void 0;
550
+ }
551
+ function inferSpanName(fiberId, sourceInfo, config) {
552
+ const variables = {
553
+ fiber_id: String(fiberId),
554
+ function: sourceInfo?.function || "anonymous",
555
+ module: sourceInfo?.file ? extractModuleName(sourceInfo.file) : "unknown",
556
+ file: sourceInfo?.file || "unknown",
557
+ line: sourceInfo?.line ? String(sourceInfo.line) : "0",
558
+ operator: "gen"
559
+ // Default operator, could be enhanced with more context
560
+ };
561
+ const match = findMatchingRule(sourceInfo, config);
562
+ if (match) {
563
+ return applyTemplate(match.rule.original.name, variables, match.matchGroups);
564
+ }
565
+ const defaultTemplate = config.span_naming?.default || "effect.fiber.{fiber_id}";
566
+ return applyTemplate(defaultTemplate, variables);
567
+ }
568
+ function sanitizeSpanName(name) {
569
+ if (!name) return "effect.fiber.unknown";
570
+ let sanitized = name.replace(/[^a-zA-Z0-9._-]/g, "_");
571
+ sanitized = sanitized.replace(/_+/g, "_");
572
+ sanitized = sanitized.replace(/^_+|_+$/g, "");
573
+ if (!sanitized) return "effect.fiber.unknown";
574
+ if (sanitized.length > 256) {
575
+ sanitized = sanitized.substring(0, 256);
576
+ }
577
+ return sanitized;
578
+ }
579
+ async function loadFromFile(filePath) {
580
+ const { readFile } = await import('fs/promises');
581
+ const content = await readFile(filePath, "utf-8");
582
+ return parseAndValidateConfig(content);
583
+ }
584
+ async function loadFromUrl(url) {
585
+ const response = await fetch(url);
586
+ if (!response.ok) {
587
+ throw new Error(`Failed to fetch config from ${url}: ${response.statusText}`);
588
+ }
589
+ const content = await response.text();
590
+ return parseAndValidateConfig(content);
591
+ }
592
+ async function loadConfig(uri, _options) {
593
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
594
+ return loadFromUrl(uri);
595
+ }
596
+ if (uri.startsWith("file://")) {
597
+ const filePath = uri.slice(7);
598
+ return loadFromFile(filePath);
599
+ }
600
+ return loadFromFile(uri);
601
+ }
602
+ async function loadConfigFromInline(content) {
603
+ return parseAndValidateConfig(content);
604
+ }
605
+ async function loadConfigWithOptions(options = {}) {
606
+ if (options.config) {
607
+ return loadConfigFromInline(options.config);
608
+ }
609
+ const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG;
610
+ if (envConfigPath) {
611
+ return loadConfig(envConfigPath);
612
+ }
613
+ if (options.configUrl) {
614
+ return loadConfig(options.configUrl);
615
+ }
616
+ if (options.configPath) {
617
+ return loadConfig(options.configPath);
618
+ }
619
+ const { existsSync } = await import('fs');
620
+ const { join } = await import('path');
621
+ const defaultPath = join(process.cwd(), "instrumentation.yaml");
622
+ if (existsSync(defaultPath)) {
623
+ return loadConfig(defaultPath);
624
+ }
625
+ return defaultConfig;
626
+ }
627
+
628
+ // src/integrations/effect/auto/config.ts
629
+ var defaultAutoTracingConfig = {
630
+ enabled: false,
631
+ granularity: "fiber",
632
+ span_naming: {
633
+ default: "effect.fiber.{fiber_id}",
634
+ infer_from_source: true,
635
+ rules: []
636
+ },
637
+ filter: {
638
+ include: [],
639
+ exclude: []
640
+ },
641
+ performance: {
642
+ sampling_rate: 1,
643
+ min_duration: "0ms",
644
+ max_concurrent: 0
645
+ },
646
+ metadata: {
647
+ fiber_info: true,
648
+ source_location: true,
649
+ parent_fiber: true
650
+ }
651
+ };
652
+ var AutoTracingConfig = class extends effect.Context.Tag("AutoTracingConfig")() {
653
+ };
654
+ var loadAutoTracingConfig = (options) => effect.Effect.gen(function* () {
655
+ const config = yield* effect.Effect.tryPromise({
656
+ try: () => loadConfigWithOptions(options),
657
+ catch: (error) => {
658
+ logger.log(`@atrim/auto-trace: Failed to load config: ${error}`);
659
+ return error;
660
+ }
661
+ }).pipe(effect.Effect.catchAll(() => effect.Effect.succeed(null)));
662
+ if (!config) {
663
+ logger.log("@atrim/auto-trace: No config found, using defaults");
664
+ return defaultAutoTracingConfig;
665
+ }
666
+ const autoConfig = config.effect?.auto_instrumentation;
667
+ if (!autoConfig) {
668
+ logger.log("@atrim/auto-trace: No auto_instrumentation config, using defaults");
669
+ return defaultAutoTracingConfig;
670
+ }
671
+ const parsed = AutoInstrumentationConfigSchema.safeParse(autoConfig);
672
+ if (!parsed.success) {
673
+ logger.log(`@atrim/auto-trace: Invalid config, using defaults: ${parsed.error.message}`);
674
+ return defaultAutoTracingConfig;
675
+ }
676
+ logger.log("@atrim/auto-trace: Loaded config from instrumentation.yaml");
677
+ return parsed.data;
678
+ });
679
+ var loadAutoTracingConfigSync = () => {
680
+ return defaultAutoTracingConfig;
681
+ };
682
+ var AutoTracingConfigLive = effect.Layer.effect(AutoTracingConfig, loadAutoTracingConfig());
683
+ var AutoTracingConfigLayer = (config) => effect.Layer.succeed(AutoTracingConfig, config);
684
+
685
+ // src/integrations/effect/auto/supervisor.ts
686
+ var AutoTracingEnabled = effect.FiberRef.unsafeMake(true);
687
+ var AutoTracingSpanName = effect.FiberRef.unsafeMake(effect.Option.none());
688
+ var AutoTracingSupervisor = class extends effect.Supervisor.AbstractSupervisor {
689
+ constructor(config) {
690
+ super();
691
+ this.config = config;
692
+ // WeakMap to associate fibers with their OTel spans
693
+ __publicField(this, "fiberSpans", /* @__PURE__ */ new WeakMap());
694
+ // WeakMap for fiber start times (for min_duration filtering)
695
+ __publicField(this, "fiberStartTimes", /* @__PURE__ */ new WeakMap());
696
+ // OpenTelemetry tracer
697
+ __publicField(this, "tracer");
698
+ // Compiled filter patterns
699
+ __publicField(this, "includePatterns");
700
+ __publicField(this, "excludePatterns");
701
+ // Active fiber count (for max_concurrent limiting)
702
+ __publicField(this, "activeFiberCount", 0);
703
+ this.tracer = OtelApi__namespace.trace.getTracer("@atrim/auto-trace", "1.0.0");
704
+ this.includePatterns = (config.filter?.include || []).map((p) => new RegExp(p));
705
+ this.excludePatterns = (config.filter?.exclude || []).map((p) => new RegExp(p));
706
+ logger.log("@atrim/auto-trace: Supervisor initialized");
707
+ logger.log(` Granularity: ${config.granularity || "fiber"}`);
708
+ logger.log(` Sampling rate: ${config.performance?.sampling_rate ?? 1}`);
709
+ logger.log(` Infer from source: ${config.span_naming?.infer_from_source ?? true}`);
710
+ }
711
+ /**
712
+ * Returns the current value (void for this supervisor)
713
+ */
714
+ get value() {
715
+ return effect.Effect.void;
716
+ }
717
+ /**
718
+ * Called when a fiber starts executing
719
+ */
720
+ onStart(_context, _effect, parent, fiber) {
721
+ const fiberRefsValue = fiber.getFiberRefs();
722
+ const enabled = effect.FiberRefs.getOrDefault(fiberRefsValue, AutoTracingEnabled);
723
+ if (!enabled) {
724
+ return;
725
+ }
726
+ const samplingRate = this.config.performance?.sampling_rate ?? 1;
727
+ if (samplingRate < 1 && Math.random() > samplingRate) {
728
+ return;
729
+ }
730
+ const maxConcurrent = this.config.performance?.max_concurrent ?? 0;
731
+ if (maxConcurrent > 0 && this.activeFiberCount >= maxConcurrent) {
732
+ return;
733
+ }
734
+ const nameOverride = effect.FiberRefs.getOrDefault(fiberRefsValue, AutoTracingSpanName);
735
+ let spanName;
736
+ if (effect.Option.isSome(nameOverride)) {
737
+ spanName = nameOverride.value;
738
+ } else {
739
+ const sourceInfo = this.config.span_naming?.infer_from_source ? this.parseStackTrace() : void 0;
740
+ spanName = inferSpanName(fiber.id().id, sourceInfo, this.config);
741
+ }
742
+ if (!this.shouldTrace(spanName)) {
743
+ return;
744
+ }
745
+ let parentContext = OtelApi__namespace.context.active();
746
+ if (effect.Option.isSome(parent)) {
747
+ const parentSpan = this.fiberSpans.get(parent.value);
748
+ if (parentSpan) {
749
+ parentContext = OtelApi__namespace.trace.setSpan(parentContext, parentSpan);
750
+ }
751
+ }
752
+ const span = this.tracer.startSpan(
753
+ spanName,
754
+ {
755
+ kind: OtelApi__namespace.SpanKind.INTERNAL,
756
+ attributes: this.getInitialAttributes(fiber)
757
+ },
758
+ parentContext
759
+ );
760
+ this.fiberSpans.set(fiber, span);
761
+ this.fiberStartTimes.set(fiber, process.hrtime.bigint());
762
+ this.activeFiberCount++;
763
+ }
764
+ /**
765
+ * Called when a fiber completes (success or failure)
766
+ */
767
+ onEnd(exit, fiber) {
768
+ const span = this.fiberSpans.get(fiber);
769
+ if (!span) {
770
+ return;
771
+ }
772
+ const startTime = this.fiberStartTimes.get(fiber);
773
+ if (startTime) {
774
+ const duration = process.hrtime.bigint() - startTime;
775
+ const minDuration = this.parseMinDuration(this.config.performance?.min_duration);
776
+ if (minDuration > 0 && duration < minDuration) {
777
+ this.fiberSpans.delete(fiber);
778
+ this.fiberStartTimes.delete(fiber);
779
+ this.activeFiberCount--;
780
+ return;
781
+ }
782
+ }
783
+ if (effect.Exit.isSuccess(exit)) {
784
+ span.setStatus({ code: OtelApi__namespace.SpanStatusCode.OK });
785
+ } else {
786
+ span.setStatus({
787
+ code: OtelApi__namespace.SpanStatusCode.ERROR,
788
+ message: "Fiber failed"
789
+ });
790
+ span.setAttribute("effect.fiber.failed", true);
791
+ }
792
+ span.end();
793
+ this.fiberSpans.delete(fiber);
794
+ this.fiberStartTimes.delete(fiber);
795
+ this.activeFiberCount--;
796
+ }
797
+ /**
798
+ * Check if a span name should be traced based on filter patterns
799
+ */
800
+ shouldTrace(spanName) {
801
+ for (const pattern of this.excludePatterns) {
802
+ if (pattern.test(spanName)) {
803
+ return false;
804
+ }
805
+ }
806
+ if (this.includePatterns.length > 0) {
807
+ for (const pattern of this.includePatterns) {
808
+ if (pattern.test(spanName)) {
809
+ return true;
810
+ }
811
+ }
812
+ return false;
813
+ }
814
+ return true;
815
+ }
816
+ /**
817
+ * Get initial span attributes for a fiber
818
+ */
819
+ getInitialAttributes(fiber) {
820
+ const attrs = {
821
+ "effect.auto_traced": true
822
+ };
823
+ if (this.config.metadata?.fiber_info !== false) {
824
+ attrs["effect.fiber.id"] = fiber.id().id;
825
+ }
826
+ return attrs;
827
+ }
828
+ /**
829
+ * Parse stack trace to get source info
830
+ */
831
+ parseStackTrace() {
832
+ const stack = new Error().stack;
833
+ if (!stack) return void 0;
834
+ const lines = stack.split("\n");
835
+ for (let i = 3; i < lines.length; i++) {
836
+ const line = lines[i];
837
+ if (line === void 0) continue;
838
+ if (!line.includes("node_modules/effect") && !line.includes("@atrim/instrument") && !line.includes("auto/supervisor")) {
839
+ const match = line.match(/at\s+(?:(.+?)\s+)?\(?(.+?):(\d+):(\d+)\)?/);
840
+ if (match) {
841
+ const [, funcName, filePath, lineNum, colNum] = match;
842
+ return {
843
+ function: funcName ?? "anonymous",
844
+ file: filePath ?? "unknown",
845
+ line: parseInt(lineNum ?? "0", 10),
846
+ column: parseInt(colNum ?? "0", 10)
847
+ };
848
+ }
849
+ }
850
+ }
851
+ return void 0;
852
+ }
853
+ /**
854
+ * Parse min_duration string to nanoseconds
855
+ */
856
+ parseMinDuration(duration) {
857
+ if (!duration || duration === "0ms") return BigInt(0);
858
+ const match = duration.match(/^(\d+)\s*(ms|millis|s|sec|seconds|us|micros)?$/i);
859
+ if (!match) return BigInt(0);
860
+ const value = parseInt(match[1] ?? "0", 10);
861
+ const unit = (match[2] ?? "ms").toLowerCase();
862
+ switch (unit) {
863
+ case "us":
864
+ case "micros":
865
+ return BigInt(value) * BigInt(1e3);
866
+ case "ms":
867
+ case "millis":
868
+ return BigInt(value) * BigInt(1e6);
869
+ case "s":
870
+ case "sec":
871
+ case "seconds":
872
+ return BigInt(value) * BigInt(1e9);
873
+ default:
874
+ return BigInt(value) * BigInt(1e6);
875
+ }
876
+ }
877
+ };
878
+ var createAutoTracingSupervisor = (config) => {
879
+ return new AutoTracingSupervisor(config);
880
+ };
881
+ var createAutoTracingLayer = (options) => {
882
+ return effect.Layer.unwrapEffect(
883
+ effect.Effect.gen(function* () {
884
+ const config = options?.config ?? (yield* loadAutoTracingConfig());
885
+ if (!config.enabled) {
886
+ logger.log("@atrim/auto-trace: Auto-tracing disabled via config");
887
+ return effect.Layer.empty;
888
+ }
889
+ const supervisor = createAutoTracingSupervisor(config);
890
+ return effect.Supervisor.addSupervisor(supervisor);
891
+ })
892
+ );
893
+ };
894
+ var AutoTracingLive = createAutoTracingLayer();
895
+ var withoutAutoTracing = (effect$1) => effect$1.pipe(effect.Effect.locally(AutoTracingEnabled, false));
896
+ var setSpanName = (name) => (effect$1) => effect$1.pipe(effect.Effect.locally(AutoTracingSpanName, effect.Option.some(name)));
897
+
898
+ exports.AutoTracingConfig = AutoTracingConfig;
899
+ exports.AutoTracingConfigLayer = AutoTracingConfigLayer;
900
+ exports.AutoTracingConfigLive = AutoTracingConfigLive;
901
+ exports.AutoTracingEnabled = AutoTracingEnabled;
902
+ exports.AutoTracingLive = AutoTracingLive;
903
+ exports.AutoTracingSpanName = AutoTracingSpanName;
904
+ exports.AutoTracingSupervisor = AutoTracingSupervisor;
905
+ exports.createAutoTracingLayer = createAutoTracingLayer;
906
+ exports.createAutoTracingSupervisor = createAutoTracingSupervisor;
907
+ exports.defaultAutoTracingConfig = defaultAutoTracingConfig;
908
+ exports.inferSpanName = inferSpanName;
909
+ exports.loadAutoTracingConfig = loadAutoTracingConfig;
910
+ exports.loadAutoTracingConfigSync = loadAutoTracingConfigSync;
911
+ exports.sanitizeSpanName = sanitizeSpanName;
912
+ exports.setSpanName = setSpanName;
913
+ exports.withoutAutoTracing = withoutAutoTracing;
914
+ //# sourceMappingURL=index.cjs.map
915
+ //# sourceMappingURL=index.cjs.map