@atrim/instrument-web 0.5.0 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atrim/instrument-web",
3
- "version": "0.5.0",
3
+ "version": "0.5.3",
4
4
  "description": "OpenTelemetry instrumentation for browsers with centralized YAML configuration",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -52,7 +52,6 @@
52
52
  "effect": "^3.19.0",
53
53
  "@opentelemetry/api": "^1.9.0",
54
54
  "@opentelemetry/auto-instrumentations-web": "^0.54.0",
55
- "@opentelemetry/context-zone": "^2.2.0",
56
55
  "@opentelemetry/exporter-trace-otlp-http": "^0.208.0",
57
56
  "@opentelemetry/instrumentation": "^0.208.0",
58
57
  "@opentelemetry/resources": "^2.2.0",
@@ -60,7 +59,16 @@
60
59
  "@opentelemetry/sdk-trace-web": "^2.2.0",
61
60
  "yaml": "^2.8.1"
62
61
  },
62
+ "peerDependencies": {
63
+ "@opentelemetry/context-zone": "^2.0.0"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "@opentelemetry/context-zone": {
67
+ "optional": true
68
+ }
69
+ },
63
70
  "devDependencies": {
71
+ "@opentelemetry/context-zone": "^2.2.0",
64
72
  "@opentelemetry/semantic-conventions": "^1.38.0",
65
73
  "@types/node": "^20.10.0",
66
74
  "@vitest/coverage-v8": "^4.0.8",
@@ -82,10 +90,10 @@
82
90
  "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
83
91
  "format:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"",
84
92
  "clean": "rm -rf target",
85
- "publish:dev:version": "npm version $(git describe --tags --abbrev=0 | sed 's/^.*@//' | sed 's/^v//')-$(git rev-parse --short HEAD)-$(date -u +%Y%m%d%H%M%S) --no-git-tag-version",
93
+ "publish:dev:version": "pnpm version $(node -p \"require('./package.json').version\")-$(git rev-parse --short HEAD)-$(date -u +%Y%m%d%H%M%S) --no-git-tag-version",
86
94
  "publish:dev:save": "node -p \"require('./package.json').version\" > .version",
87
95
  "publish:dev:publish": "pnpm build && pnpm publish --tag dev --access public --no-git-checks",
88
- "publish:dev:reset": "npm version 0.1.0 --no-git-tag-version",
96
+ "publish:dev:reset": "pnpm version 0.5.0 --no-git-tag-version",
89
97
  "publish:dev": "pnpm publish:dev:version && pnpm publish:dev:save && pnpm publish:dev:publish && pnpm publish:dev:reset"
90
98
  }
91
99
  }
@@ -70,6 +70,54 @@ interface SdkInitializationOptions {
70
70
  * @default true
71
71
  */
72
72
  enableXhr?: boolean;
73
+ /**
74
+ * Control trace context propagation for cross-origin requests
75
+ *
76
+ * Determines which cross-origin requests receive W3C Trace Context headers
77
+ * (traceparent, tracestate). Note: Backends must allow these headers in CORS
78
+ * configuration or requests will fail with CORS errors.
79
+ *
80
+ * - 'all': Propagate to all cross-origin requests (may cause CORS errors)
81
+ * - 'none': Never propagate trace headers
82
+ * - 'same-origin': Only propagate to same-origin requests (default)
83
+ * - Array of URL patterns: Custom propagation patterns (regex strings)
84
+ *
85
+ * @default 'same-origin'
86
+ *
87
+ * @example Propagate to specific API domains
88
+ * ```typescript
89
+ * propagateTraceContext: ['^https://api\\.myapp\\.com', '^http://localhost:300[0-9]']
90
+ * ```
91
+ *
92
+ * @example Disable propagation (for debugging CORS issues)
93
+ * ```typescript
94
+ * propagateTraceContext: 'none'
95
+ * ```
96
+ */
97
+ propagateTraceContext?: 'all' | 'none' | 'same-origin' | string[];
98
+ /**
99
+ * Use Zone.js-based context manager for async context propagation
100
+ *
101
+ * By default, we use StackContextManager which is lightweight and doesn't
102
+ * interfere with application behavior. However, it has limited async context
103
+ * propagation.
104
+ *
105
+ * Enable this option if you need context to propagate across async boundaries
106
+ * (e.g., setTimeout, Promise chains). Note that Zone.js monkey-patches many
107
+ * browser APIs which can cause issues with some libraries:
108
+ *
109
+ * - Libraries that call preventDefault() on wheel/touch events may fail
110
+ * - Some React patterns may lose context
111
+ * - Bundle size increases due to Zone.js dependency
112
+ *
113
+ * @default false
114
+ *
115
+ * @example Enable Zone.js context (use with caution)
116
+ * ```typescript
117
+ * useZoneContext: true
118
+ * ```
119
+ */
120
+ useZoneContext?: boolean;
73
121
  }
74
122
  /**
75
123
  * Get the current SDK instance
@@ -1,8 +1,7 @@
1
- import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
1
+ import { WebTracerProvider, StackContextManager } from '@opentelemetry/sdk-trace-web';
2
2
  import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
3
3
  import { registerInstrumentations } from '@opentelemetry/instrumentation';
4
4
  import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
5
- import { ZoneContextManager } from '@opentelemetry/context-zone';
6
5
  import { Data, Context, Effect, Layer } from 'effect';
7
6
  import { FileSystem } from '@effect/platform/FileSystem';
8
7
  import * as HttpClient from '@effect/platform/HttpClient';
@@ -3845,7 +3844,7 @@ ZodNaN.create = (params) => {
3845
3844
  ...processCreateParams(params)
3846
3845
  });
3847
3846
  };
3848
- var BRAND = Symbol("zod_brand");
3847
+ var BRAND = /* @__PURE__ */ Symbol("zod_brand");
3849
3848
  var ZodBranded = class extends ZodType {
3850
3849
  _parse(input) {
3851
3850
  const { ctx } = this._processInputParams(input);
@@ -4095,7 +4094,20 @@ var HttpFilteringConfigSchema = external_exports.object({
4095
4094
  // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)
4096
4095
  ignore_incoming_paths: external_exports.array(external_exports.string()).optional(),
4097
4096
  // Require parent span for outgoing requests (prevents root spans for HTTP calls)
4098
- require_parent_for_outgoing_spans: external_exports.boolean().optional()
4097
+ require_parent_for_outgoing_spans: external_exports.boolean().optional(),
4098
+ // Trace context propagation configuration
4099
+ // Controls which cross-origin requests receive W3C Trace Context headers (traceparent, tracestate)
4100
+ propagate_trace_context: external_exports.object({
4101
+ // Strategy for trace propagation
4102
+ // - "all": Propagate to all cross-origin requests (may cause CORS errors)
4103
+ // - "none": Never propagate trace headers
4104
+ // - "same-origin": Only propagate to same-origin requests (default, safe)
4105
+ // - "patterns": Propagate based on include_urls patterns
4106
+ strategy: external_exports.enum(["all", "none", "same-origin", "patterns"]).default("same-origin"),
4107
+ // URL patterns to include when strategy is "patterns"
4108
+ // Supports regex patterns (e.g., "^https://api\\.myapp\\.com")
4109
+ include_urls: external_exports.array(external_exports.string()).optional()
4110
+ }).optional()
4099
4111
  });
4100
4112
  var InstrumentationConfigSchema = external_exports.object({
4101
4113
  version: external_exports.string(),
@@ -4526,6 +4538,75 @@ var PatternSpanProcessor = class {
4526
4538
 
4527
4539
  // src/core/sdk-initializer.ts
4528
4540
  var sdkInstance = null;
4541
+ function buildPropagateTraceUrls(options, config) {
4542
+ const apiOption = options.propagateTraceContext;
4543
+ const yamlStrategy = config?.http?.propagate_trace_context?.strategy;
4544
+ const yamlIncludeUrls = config?.http?.propagate_trace_context?.include_urls;
4545
+ let effectiveStrategy;
4546
+ let patterns = [];
4547
+ if (apiOption !== void 0) {
4548
+ if (typeof apiOption === "string") {
4549
+ effectiveStrategy = apiOption;
4550
+ } else {
4551
+ effectiveStrategy = "patterns";
4552
+ patterns = apiOption;
4553
+ }
4554
+ } else if (yamlStrategy) {
4555
+ effectiveStrategy = yamlStrategy;
4556
+ if (effectiveStrategy === "patterns" && yamlIncludeUrls) {
4557
+ patterns = yamlIncludeUrls;
4558
+ }
4559
+ } else {
4560
+ effectiveStrategy = "same-origin";
4561
+ }
4562
+ switch (effectiveStrategy) {
4563
+ case "all":
4564
+ return [/.*/];
4565
+ case "none":
4566
+ case "same-origin":
4567
+ return [];
4568
+ case "patterns": {
4569
+ const regexes = [];
4570
+ for (const pattern of patterns) {
4571
+ try {
4572
+ regexes.push(new RegExp(pattern));
4573
+ } catch (error) {
4574
+ console.warn(
4575
+ `[@atrim/instrument-web] Invalid trace propagation pattern: "${pattern}"`,
4576
+ error
4577
+ );
4578
+ }
4579
+ }
4580
+ return regexes;
4581
+ }
4582
+ default:
4583
+ console.warn(
4584
+ `[@atrim/instrument-web] Unknown trace propagation strategy: "${effectiveStrategy}". Defaulting to same-origin only.`
4585
+ );
4586
+ return [];
4587
+ }
4588
+ }
4589
+ async function createContextManager(useZoneContext) {
4590
+ if (!useZoneContext) {
4591
+ return new StackContextManager();
4592
+ }
4593
+ if (typeof window !== "undefined") {
4594
+ window.__zone_symbol__PASSIVE_EVENTS = [];
4595
+ console.info(
4596
+ "[@atrim/instrument-web] Zone.js context enabled. Passive events disabled for wheel/touch events to prevent breaking preventDefault()."
4597
+ );
4598
+ }
4599
+ try {
4600
+ const { ZoneContextManager } = await import('@opentelemetry/context-zone');
4601
+ return new ZoneContextManager();
4602
+ } catch (error) {
4603
+ console.warn(
4604
+ "[@atrim/instrument-web] Failed to load ZoneContextManager. Falling back to StackContextManager. Make sure @opentelemetry/context-zone is installed if you need async context propagation.",
4605
+ error
4606
+ );
4607
+ return new StackContextManager();
4608
+ }
4609
+ }
4529
4610
  async function initializeSdk(options) {
4530
4611
  if (sdkInstance) {
4531
4612
  return sdkInstance;
@@ -4563,6 +4644,7 @@ async function initializeSdk(options) {
4563
4644
  "[@atrim/instrument-web] Missing http.ignore_outgoing_urls in instrumentation.yaml. Using default OTLP endpoint patterns only. Consider adding http filtering to your config for better control."
4564
4645
  );
4565
4646
  }
4647
+ const propagateTraceUrls = buildPropagateTraceUrls(options, config);
4566
4648
  const exporterOptions = {};
4567
4649
  if (options.otlpEndpoint) {
4568
4650
  exporterOptions.endpoint = options.otlpEndpoint;
@@ -4579,8 +4661,11 @@ async function initializeSdk(options) {
4579
4661
  const provider = new WebTracerProvider({
4580
4662
  spanProcessors
4581
4663
  });
4664
+ const contextManager = await createContextManager(
4665
+ options.useZoneContext ?? false
4666
+ );
4582
4667
  provider.register({
4583
- contextManager: new ZoneContextManager()
4668
+ contextManager
4584
4669
  });
4585
4670
  registerInstrumentations({
4586
4671
  instrumentations: [
@@ -4594,15 +4679,16 @@ async function initializeSdk(options) {
4594
4679
  },
4595
4680
  "@opentelemetry/instrumentation-fetch": {
4596
4681
  enabled: options.enableFetch ?? true,
4597
- propagateTraceHeaderCorsUrls: [/.*/],
4598
- // Propagate to all origins
4682
+ propagateTraceHeaderCorsUrls: propagateTraceUrls,
4683
+ // Controlled by config/API
4599
4684
  clearTimingResources: true,
4600
4685
  ignoreUrls
4601
4686
  // Prevent self-instrumentation of OTLP exports
4602
4687
  },
4603
4688
  "@opentelemetry/instrumentation-xml-http-request": {
4604
4689
  enabled: options.enableXhr ?? true,
4605
- propagateTraceHeaderCorsUrls: [/.*/]
4690
+ propagateTraceHeaderCorsUrls: propagateTraceUrls
4691
+ // Controlled by config/API
4606
4692
  }
4607
4693
  })
4608
4694
  ]