@atrim/instrument-web 0.4.0-56522df-20251118051035 → 0.4.0-7fcca2c-20251118194325

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Atrim AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atrim/instrument-web",
3
- "version": "0.4.0-56522df-20251118051035",
3
+ "version": "0.4.0-7fcca2c-20251118194325",
4
4
  "description": "OpenTelemetry instrumentation for browsers with centralized YAML configuration",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -47,26 +47,9 @@
47
47
  "README.md",
48
48
  "LICENSE"
49
49
  ],
50
- "scripts": {
51
- "build": "tsup",
52
- "dev": "tsup --watch",
53
- "test": "vitest run",
54
- "test:watch": "vitest",
55
- "test:coverage": "vitest run --coverage",
56
- "typecheck": "tsc --noEmit",
57
- "lint": "eslint src",
58
- "lint:fix": "eslint src --fix",
59
- "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
60
- "format:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"",
61
- "clean": "rm -rf target",
62
- "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",
63
- "publish:dev:save": "node -p \"require('./package.json').version\" > .version",
64
- "publish:dev:publish": "pnpm build && npm publish --tag dev --access public",
65
- "publish:dev:reset": "npm version 0.1.0 --no-git-tag-version",
66
- "publish:dev": "pnpm publish:dev:version && pnpm publish:dev:save && pnpm publish:dev:publish && pnpm publish:dev:reset"
67
- },
68
50
  "dependencies": {
69
- "@atrim/instrument-core": "workspace:*",
51
+ "@effect/platform": "^0.93.0",
52
+ "effect": "^3.19.0",
70
53
  "@opentelemetry/api": "^1.9.0",
71
54
  "@opentelemetry/auto-instrumentations-web": "^0.54.0",
72
55
  "@opentelemetry/context-zone": "^2.2.0",
@@ -75,7 +58,8 @@
75
58
  "@opentelemetry/resources": "^2.2.0",
76
59
  "@opentelemetry/sdk-trace-base": "^2.2.0",
77
60
  "@opentelemetry/sdk-trace-web": "^2.2.0",
78
- "yaml": "^2.8.1"
61
+ "yaml": "^2.8.1",
62
+ "@atrim/instrument-core": "0.4.0"
79
63
  },
80
64
  "devDependencies": {
81
65
  "@opentelemetry/semantic-conventions": "^1.38.0",
@@ -85,5 +69,23 @@
85
69
  "tsup": "^8.0.1",
86
70
  "typescript": "^5.7.2",
87
71
  "vitest": "^4.0.8"
72
+ },
73
+ "scripts": {
74
+ "build": "tsup",
75
+ "dev": "tsup --watch",
76
+ "test": "vitest run",
77
+ "test:watch": "vitest",
78
+ "test:coverage": "vitest run --coverage",
79
+ "typecheck": "tsc --noEmit",
80
+ "lint": "eslint src",
81
+ "lint:fix": "eslint src --fix",
82
+ "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
83
+ "format:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"",
84
+ "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",
86
+ "publish:dev:save": "node -p \"require('./package.json').version\" > .version",
87
+ "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",
89
+ "publish:dev": "pnpm publish:dev:version && pnpm publish:dev:save && pnpm publish:dev:publish && pnpm publish:dev:reset"
88
90
  }
89
- }
91
+ }
@@ -1,7 +1,8 @@
1
1
  import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
2
- import { InstrumentationConfig } from '@atrim/instrument-core';
3
- export { ConfigError, ConfigFileError, ConfigLoaderOptions, ConfigUrlError, ConfigValidationError, ExportError, InitializationError, InstrumentationConfig, PatternConfig, PatternMatcher, ShutdownError, clearConfigCache, clearPatternMatcher, getPatternMatcher, initializePatternMatcher, loadConfig, shouldInstrumentSpan } from '@atrim/instrument-core';
2
+ import { InstrumentationConfig, ConfigLoader } from '@atrim/instrument-core';
3
+ export { ConfigError, ConfigFileError, ConfigUrlError, ConfigValidationError, ExportError, InitializationError, InstrumentationConfig, PatternConfig, PatternMatcher, ShutdownError, clearPatternMatcher, getPatternMatcher, initializePatternMatcher, shouldInstrumentSpan } from '@atrim/instrument-core';
4
4
  import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
5
+ import { Layer } from 'effect';
5
6
  import { SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-base';
6
7
  import { Context, Span } from '@opentelemetry/api';
7
8
 
@@ -186,6 +187,39 @@ declare function createOtlpExporter(options?: OtlpExporterOptions): OTLPTraceExp
186
187
  */
187
188
  declare function getOtlpEndpoint(): string;
188
189
 
190
+ /**
191
+ * Browser configuration loader using Effect Platform
192
+ *
193
+ * Provides HttpClient layer for the core ConfigLoader service
194
+ * (No FileSystem in browser)
195
+ */
196
+
197
+ /**
198
+ * Complete ConfigLoader layer with browser platform dependencies
199
+ *
200
+ * Provides:
201
+ * - ConfigLoader service
202
+ * - HttpClient (from FetchHttpClient)
203
+ * - No FileSystem (browser doesn't have filesystem access)
204
+ */
205
+ declare const WebConfigLoaderLive: Layer.Layer<ConfigLoader, never, never>;
206
+ /**
207
+ * Load configuration from URI (Promise-based convenience API)
208
+ *
209
+ * Automatically provides browser platform layers (HttpClient only)
210
+ *
211
+ * @param uri - Configuration URI (http://, https://, or relative path)
212
+ * @returns Promise that resolves to validated configuration
213
+ */
214
+ declare function loadConfig(uri: string): Promise<InstrumentationConfig>;
215
+ /**
216
+ * Load configuration from inline content (Promise-based convenience API)
217
+ *
218
+ * @param content - YAML string, JSON string, or plain object
219
+ * @returns Promise that resolves to validated configuration
220
+ */
221
+ declare function loadConfigFromInline(content: string | unknown): Promise<InstrumentationConfig>;
222
+
189
223
  /**
190
224
  * Pattern-Based Span Processor for Browser
191
225
  *
@@ -376,4 +410,4 @@ declare function annotateNavigation(span: Span, options: {
376
410
  type?: 'client-side' | 'server-side' | 'initial';
377
411
  }): void;
378
412
 
379
- export { type OtlpExporterOptions, PatternSpanProcessor, type SdkInitializationOptions, annotateCacheOperation, annotateHttpRequest, annotateNavigation, annotateUserInteraction, createOtlpExporter, getOtlpEndpoint, getSdkInstance, initializeInstrumentation, markSpanError, markSpanSuccess, recordException, resetSdk, setSpanAttributes, shutdownSdk };
413
+ export { type OtlpExporterOptions, PatternSpanProcessor, type SdkInitializationOptions, WebConfigLoaderLive, annotateCacheOperation, annotateHttpRequest, annotateNavigation, annotateUserInteraction, createOtlpExporter, getOtlpEndpoint, getSdkInstance, initializeInstrumentation, loadConfig, loadConfigFromInline, markSpanError, markSpanSuccess, recordException, resetSdk, setSpanAttributes, shutdownSdk };
@@ -3,51 +3,28 @@ import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
3
3
  import { registerInstrumentations } from '@opentelemetry/instrumentation';
4
4
  import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
5
5
  import { ZoneContextManager } from '@opentelemetry/context-zone';
6
- import { InstrumentationConfigSchema, shouldInstrumentSpan, initializePatternMatcher } from '@atrim/instrument-core';
6
+ import { ConfigLoaderLive, ConfigLoader, shouldInstrumentSpan, initializePatternMatcher } from '@atrim/instrument-core';
7
7
  export { ConfigError, ConfigFileError, ConfigUrlError, ConfigValidationError, ExportError, InitializationError, PatternMatcher, ShutdownError, clearPatternMatcher, getPatternMatcher, initializePatternMatcher, shouldInstrumentSpan } from '@atrim/instrument-core';
8
- import { parse } from 'yaml';
8
+ import { Layer, Effect } from 'effect';
9
+ import { FetchHttpClient } from '@effect/platform';
9
10
  import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
10
11
  import { SpanStatusCode } from '@opentelemetry/api';
11
12
 
12
13
  // src/core/sdk-initializer.ts
13
- async function loadConfig(options) {
14
- if (options.config) {
15
- return validateConfig(options.config);
16
- }
17
- if (options.configUrl) {
18
- return await loadConfigFromUrl(options.configUrl);
19
- }
20
- throw new Error("No configuration provided. Use config or configUrl option.");
21
- }
22
- async function loadConfigFromUrl(url) {
23
- try {
24
- const response = await fetch(url, {
25
- method: "GET",
26
- headers: {
27
- Accept: "application/yaml, text/yaml, application/x-yaml"
28
- },
29
- // 5 second timeout
30
- signal: AbortSignal.timeout(5e3)
31
- });
32
- if (!response.ok) {
33
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
34
- }
35
- const yamlText = await response.text();
36
- if (yamlText.length > 1e6) {
37
- throw new Error("Configuration file too large (>1MB)");
38
- }
39
- const config = parse(yamlText);
40
- return validateConfig(config);
41
- } catch (error) {
42
- throw new Error(`Failed to load config from ${url}: ${error}`);
43
- }
14
+ var WebConfigLoaderLive = ConfigLoaderLive.pipe(Layer.provide(FetchHttpClient.layer));
15
+ async function loadConfig(uri) {
16
+ const program = Effect.gen(function* () {
17
+ const loader = yield* ConfigLoader;
18
+ return yield* loader.loadFromUri(uri);
19
+ });
20
+ return Effect.runPromise(program.pipe(Effect.provide(WebConfigLoaderLive)));
44
21
  }
45
- function validateConfig(config) {
46
- try {
47
- return InstrumentationConfigSchema.parse(config);
48
- } catch (error) {
49
- throw new Error(`Invalid configuration schema: ${error}`);
50
- }
22
+ async function loadConfigFromInline(content) {
23
+ const program = Effect.gen(function* () {
24
+ const loader = yield* ConfigLoader;
25
+ return yield* loader.loadFromInline(content);
26
+ });
27
+ return Effect.runPromise(program.pipe(Effect.provide(WebConfigLoaderLive)));
51
28
  }
52
29
  function createOtlpExporter(options = {}) {
53
30
  const endpoint = options.endpoint || getOtlpEndpoint();
@@ -115,11 +92,10 @@ async function initializeSdk(options) {
115
92
  try {
116
93
  let config = null;
117
94
  if (options.config) {
118
- config = options.config;
119
- } else if (options.configPath) {
120
- config = await loadConfig({ configPath: options.configPath });
121
- } else if (options.configUrl) {
122
- config = await loadConfig({ configUrl: options.configUrl });
95
+ config = await loadConfigFromInline(options.config);
96
+ } else if (options.configPath || options.configUrl) {
97
+ const url = options.configUrl || options.configPath;
98
+ config = await loadConfig(url);
123
99
  }
124
100
  if (config) {
125
101
  initializePatternMatcher(config);
@@ -250,6 +226,6 @@ function annotateNavigation(span, options) {
250
226
  setSpanAttributes(span, attrs);
251
227
  }
252
228
 
253
- export { PatternSpanProcessor, annotateCacheOperation, annotateHttpRequest, annotateNavigation, annotateUserInteraction, createOtlpExporter, getOtlpEndpoint, getSdkInstance, initializeInstrumentation, loadConfig, markSpanError, markSpanSuccess, recordException, resetSdk, setSpanAttributes, shutdownSdk };
229
+ export { PatternSpanProcessor, WebConfigLoaderLive, annotateCacheOperation, annotateHttpRequest, annotateNavigation, annotateUserInteraction, createOtlpExporter, getOtlpEndpoint, getSdkInstance, initializeInstrumentation, loadConfig, loadConfigFromInline, markSpanError, markSpanSuccess, recordException, resetSdk, setSpanAttributes, shutdownSdk };
254
230
  //# sourceMappingURL=index.js.map
255
231
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/config-loader.ts","../../src/core/exporter-factory.ts","../../src/core/span-processor.ts","../../src/core/sdk-initializer.ts","../../src/api.ts","../../src/integrations/standard/span-helpers.ts"],"names":["parseYAML"],"mappings":";;;;;;;;;;;;AA4BA,eAAsB,WAAW,OAAA,EAA8D;AAE7F,EAAA,IAAI,QAAQ,MAAA,EAAQ;AAClB,IAAA,OAAO,cAAA,CAAe,QAAQ,MAAM,CAAA;AAAA,EACtC;AAGA,EAAA,IAAI,QAAQ,SAAA,EAAW;AACrB,IAAA,OAAO,MAAM,iBAAA,CAAkB,OAAA,CAAQ,SAAS,CAAA;AAAA,EAClD;AAEA,EAAA,MAAM,IAAI,MAAM,4DAA4D,CAAA;AAC9E;AAKA,eAAe,kBAAkB,GAAA,EAA6C;AAC5E,EAAA,IAAI;AACF,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,GAAA,EAAK;AAAA,MAChC,MAAA,EAAQ,KAAA;AAAA,MACR,OAAA,EAAS;AAAA,QACP,MAAA,EAAQ;AAAA,OACV;AAAA;AAAA,MAEA,MAAA,EAAQ,WAAA,CAAY,OAAA,CAAQ,GAAI;AAAA,KACjC,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,MAAA,MAAM,IAAI,MAAM,CAAA,KAAA,EAAQ,QAAA,CAAS,MAAM,CAAA,EAAA,EAAK,QAAA,CAAS,UAAU,CAAA,CAAE,CAAA;AAAA,IACnE;AAEA,IAAA,MAAM,QAAA,GAAW,MAAM,QAAA,CAAS,IAAA,EAAK;AAGrC,IAAA,IAAI,QAAA,CAAS,SAAS,GAAA,EAAW;AAC/B,MAAA,MAAM,IAAI,MAAM,qCAAqC,CAAA;AAAA,IACvD;AAEA,IAAA,M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BAAA,CACd,MACA,OAAA,EAKM;AACN,EAAA,MAAM,KAAA,GAAgC;AAAA,IACpC,yBAAyB,OAAA,CAAQ;AAAA,GACnC;AAEA,EAAA,IAAI,OAAA,CAAQ,MAAA,EAAQ,KAAA,CAAM,yBAAyB,IAAI,OAAA,CAAQ,MAAA;AAC/D,EAAA,IAAI,OAAA,CAAQ,IAAA,EAAM,KAAA,CAAM,uBAAuB,IAAI,OAAA,CAAQ,IAAA;AAE3D,EAAA,iBAAA,CAAkB,MAAM,KAAK,CAAA;AAC/B;AAiBO,SAAS,kBAAA,CACd,MACA,OAAA,EAKM;AACN,EAAA,MAAM,QAAgC,EAAC;AAEvC,EAAA,IAAI,OAAA,CAAQ,IAAA,EAAM,KAAA,CAAM,iBAAiB,IAAI,OAAA,CAAQ,IAAA;AACrD,EAAA,IAAI,OAAA,CAAQ,EAAA,EAAI,KAAA,CAAM,eAAe,IAAI,OAAA,CAAQ,EAAA;AACjD,EAAA,IAAI,OAAA,CAAQ,IAAA,EAAM,KAAA,CAAM,iBAAiB,IAAI,OAAA,CAAQ,IAAA;AAErD,EAAA,iBAAA,CAAkB,MAAM,KAAK,CAAA;AAC/B","file":"index.js","sourcesContent":["/**\n * Browser-compatible configuration loader\n *\n * Only supports URL and inline config (no file system access in browser)\n */\n\nimport { parse as parseYAML } from 'yaml'\nimport type { InstrumentationConfig } from '@atrim/instrument-core'\nimport { InstrumentationConfigSchema } from '@atrim/instrument-core'\n\nexport interface ConfigLoaderOptions {\n configUrl?: string\n config?: InstrumentationConfig\n}\n\n/**\n * Load configuration for browser\n *\n * Supports:\n * 1. Inline config object (highest priority)\n * 2. Remote URL (fetch from server)\n *\n * Note: File system access is not available in browser\n *\n * @param options - Configuration options\n * @returns Parsed and validated configuration\n * @throws {Error} If config loading or validation fails\n */\nexport async function loadConfig(options: ConfigLoaderOptions): Promise<InstrumentationConfig> {\n // 1. Inline config (highest priority)\n if (options.config) {\n return validateConfig(options.config)\n }\n\n // 2. Remote URL\n if (options.configUrl) {\n return await loadConfigFromUrl(options.configUrl)\n }\n\n throw new Error('No configuration provided. Use config or configUrl option.')\n}\n\n/**\n * Load configuration from remote URL\n */\nasync function loadConfigFromUrl(url: string): Promise<InstrumentationConfig> {\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n Accept: 'application/yaml, text/yaml, application/x-yaml'\n },\n // 5 second timeout\n signal: AbortSignal.timeout(5000)\n })\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n }\n\n const yamlText = await response.text()\n\n // Validate size (max 1MB)\n if (yamlText.length > 1_000_000) {\n throw new Error('Configuration file too large (>1MB)')\n }\n\n const config = parseYAML(yamlText)\n return validateConfig(config)\n } catch (error) {\n throw new Error(`Failed to load config from ${url}: ${error}`)\n }\n}\n\n/**\n * Validate configuration against schema\n */\nfunction validateConfig(config: unknown): InstrumentationConfig {\n try {\n return InstrumentationConfigSchema.parse(config)\n } catch (error) {\n throw new Error(`Invalid configuration schema: ${error}`)\n }\n}\n","/**\n * OTLP Exporter Factory for Browser\n *\n * Creates OTLP HTTP exporters for sending traces from the browser.\n * Browser only supports HTTP/JSON protocol (no gRPC).\n */\n\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\n\nexport interface OtlpExporterOptions {\n /**\n * OTLP endpoint URL\n * Must end in /v1/traces for browser exporter\n * @default 'http://localhost:4318/v1/traces'\n */\n endpoint?: string\n\n /**\n * Custom HTTP headers (e.g., for authentication)\n * @example { 'Authorization': 'Bearer token' }\n */\n headers?: Record<string, string>\n\n /**\n * Request timeout in milliseconds\n * @default 10000\n */\n timeout?: number\n}\n\n/**\n * Create an OTLP HTTP trace exporter for browser\n *\n * @param options - Exporter configuration options\n * @returns OTLPTraceExporter instance\n *\n * @example\n * ```typescript\n * const exporter = createOtlpExporter({\n * endpoint: 'http://localhost:4318/v1/traces',\n * headers: { 'x-api-key': 'secret' }\n * })\n * ```\n */\nexport function createOtlpExporter(options: OtlpExporterOptions = {}): OTLPTraceExporter {\n const endpoint = options.endpoint || getOtlpEndpoint()\n\n return new OTLPTraceExporter({\n url: endpoint,\n headers: options.headers || {},\n timeoutMillis: options.timeout || 10000\n })\n}\n\n/**\n * Get OTLP endpoint from environment or use default\n *\n * Checks in order:\n * 1. import.meta.env.VITE_OTEL_EXPORTER_OTLP_ENDPOINT (Vite)\n * 2. window.OTEL_EXPORTER_OTLP_ENDPOINT (runtime config)\n * 3. Default: http://localhost:4318/v1/traces\n *\n * @returns OTLP endpoint URL\n */\nexport function getOtlpEndpoint(): string {\n // Check Vite environment variables\n try {\n if (typeof import.meta !== 'undefined') {\n const metaEnv = (import.meta as { env?: Record<string, unknown> }).env\n if (metaEnv && metaEnv.VITE_OTEL_EXPORTER_OTLP_ENDPOINT) {\n return String(metaEnv.VITE_OTEL_EXPORTER_OTLP_ENDPOINT)\n }\n }\n } catch {\n // import.meta may not be available in all environments\n }\n\n // Check window object (runtime config)\n if (typeof window !== 'undefined') {\n const windowConfig = (window as { OTEL_EXPORTER_OTLP_ENDPOINT?: unknown })\n .OTEL_EXPORTER_OTLP_ENDPOINT\n if (windowConfig) {\n return String(windowConfig)\n }\n }\n\n // Default endpoint\n return 'http://localhost:4318/v1/traces'\n}\n","/**\n * Pattern-Based Span Processor for Browser\n *\n * Filters spans based on patterns defined in instrumentation.yaml\n * Re-uses pattern matching logic from @atrim/instrument-core\n */\n\nimport { SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-base'\nimport { Context } from '@opentelemetry/api'\nimport { shouldInstrumentSpan } from '@atrim/instrument-core'\n\n/**\n * Span processor that filters spans based on pattern matching\n *\n * This processor runs BEFORE export and drops spans that don't match\n * the configured patterns in instrumentation.yaml.\n *\n * @example\n * ```yaml\n * # instrumentation.yaml\n * instrumentation:\n * instrument_patterns:\n * - pattern: \"^documentLoad\"\n * - pattern: \"^HTTP (GET|POST)\"\n * ignore_patterns:\n * - pattern: \"^HTTP GET /health\"\n * ```\n */\nexport class PatternSpanProcessor implements SpanProcessor {\n /**\n * Called when a span is started\n * No-op for this processor\n */\n onStart(_span: ReadableSpan, _parentContext: Context): void {\n // No-op\n }\n\n /**\n * Called when a span ends\n * Filters out spans that don't match patterns\n */\n onEnd(span: ReadableSpan): void {\n const spanName = span.name\n\n // Check if span should be instrumented\n if (!shouldInstrumentSpan(spanName)) {\n // Drop the span by not forwarding it\n // The span will not reach subsequent processors\n return\n }\n\n // Span passes filtering - will be processed by next processor\n }\n\n /**\n * Shutdown the processor\n * No-op for this processor\n */\n async shutdown(): Promise<void> {\n // No-op\n }\n\n /**\n * Force flush pending spans\n * No-op for this processor\n */\n async forceFlush(): Promise<void> {\n // No-op\n }\n}\n","/**\n * SDK Initializer for Browser\n *\n * Initializes the OpenTelemetry WebTracerProvider with:\n * - Auto-instrumentation (fetch, XHR, document load, user interactions)\n * - Pattern-based span filtering\n * - OTLP HTTP export\n */\n\nimport { WebTracerProvider } from '@opentelemetry/sdk-trace-web'\nimport { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'\nimport { registerInstrumentations } from '@opentelemetry/instrumentation'\nimport { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web'\nimport { ZoneContextManager } from '@opentelemetry/context-zone'\nimport type { InstrumentationConfig } from '@atrim/instrument-core'\nimport { initializePatternMatcher } from '@atrim/instrument-core'\nimport { loadConfig } from './config-loader.js'\nimport { createOtlpExporter, type OtlpExporterOptions } from './exporter-factory.js'\nimport { PatternSpanProcessor } from './span-processor.js'\n\nexport interface SdkInitializationOptions {\n /**\n * Service name (required for browser - no auto-detection)\n * @example 'my-app-frontend'\n */\n serviceName: string\n\n /**\n * Service version (optional)\n * @example '1.0.0'\n */\n serviceVersion?: string\n\n /**\n * Path to instrumentation.yaml file\n * Note: Only works if file is publicly accessible\n */\n configPath?: string\n\n /**\n * URL to remote instrumentation.yaml\n * @example 'https://config.company.com/instrumentation.yaml'\n */\n configUrl?: string\n\n /**\n * Inline configuration object (takes precedence over file/URL)\n */\n config?: InstrumentationConfig\n\n /**\n * OTLP endpoint URL\n * @default 'http://localhost:4318/v1/traces'\n */\n otlpEndpoint?: string\n\n /**\n * OTLP HTTP headers\n * @example { 'Authorization': 'Bearer token' }\n */\n otlpHeaders?: Record<string, string>\n\n /**\n * Enable document load instrumentation\n * @default true\n */\n enableDocumentLoad?: boolean\n\n /**\n * Enable user interaction instrumentation\n * @default true\n */\n enableUserInteraction?: boolean\n\n /**\n * Enable fetch API instrumentation\n * @default true\n */\n enableFetch?: boolean\n\n /**\n * Enable XMLHttpRequest instrumentation\n * @default true\n */\n enableXhr?: boolean\n}\n\n// Singleton instance\nlet sdkInstance: WebTracerProvider | null = null\n\n/**\n * Initialize the OpenTelemetry SDK for browser\n *\n * @param options - SDK initialization options\n * @returns WebTracerProvider instance\n * @throws {Error} If initialization fails\n *\n * @example\n * ```typescript\n * const provider = await initializeSdk({\n * serviceName: 'my-app',\n * otlpEndpoint: 'http://localhost:4318/v1/traces'\n * })\n * ```\n */\nexport async function initializeSdk(options: SdkInitializationOptions): Promise<WebTracerProvider> {\n if (sdkInstance) {\n return sdkInstance\n }\n\n try {\n // Load configuration (if specified)\n let config: InstrumentationConfig | null = null\n\n if (options.config) {\n config = options.config\n } else if (options.configPath) {\n config = await loadConfig({ configPath: options.configPath })\n } else if (options.configUrl) {\n config = await loadConfig({ configUrl: options.configUrl })\n }\n\n // Initialize pattern matcher (if config available)\n if (config) {\n initializePatternMatcher(config)\n }\n\n // Create OTLP exporter\n const exporterOptions: OtlpExporterOptions = {}\n if (options.otlpEndpoint) {\n exporterOptions.endpoint = options.otlpEndpoint\n }\n if (options.otlpHeaders) {\n exporterOptions.headers = options.otlpHeaders\n }\n const exporter = createOtlpExporter(exporterOptions)\n\n // Build span processors array\n const spanProcessors = []\n\n // 1. Pattern-based filtering (if config available)\n if (config) {\n spanProcessors.push(new PatternSpanProcessor())\n }\n\n // 2. OTLP export (SimpleSpanProcessor for browser - no batching)\n spanProcessors.push(new SimpleSpanProcessor(exporter))\n\n // Create WebTracerProvider with processors\n // Note: Resource configuration will be handled via environment or programmatically\n const provider = new WebTracerProvider({\n spanProcessors\n })\n\n // Note: Resource attributes (service name, version) should be set via:\n // 1. OTEL_RESOURCE_ATTRIBUTES environment variable\n // 2. Custom Resource passed to WebTracerProvider\n // 3. Collector configuration\n // For now, serviceName is used primarily for logging/debugging\n\n // Register the provider\n provider.register({\n contextManager: new ZoneContextManager()\n })\n\n // Register auto-instrumentations\n registerInstrumentations({\n instrumentations: [\n getWebAutoInstrumentations({\n '@opentelemetry/instrumentation-document-load': {\n enabled: options.enableDocumentLoad ?? true\n },\n '@opentelemetry/instrumentation-user-interaction': {\n enabled: options.enableUserInteraction ?? true,\n eventNames: ['click', 'submit']\n },\n '@opentelemetry/instrumentation-fetch': {\n enabled: options.enableFetch ?? true,\n propagateTraceHeaderCorsUrls: [/.*/], // Propagate to all origins\n clearTimingResources: true\n },\n '@opentelemetry/instrumentation-xml-http-request': {\n enabled: options.enableXhr ?? true,\n propagateTraceHeaderCorsUrls: [/.*/]\n }\n })\n ]\n })\n\n sdkInstance = provider\n return provider\n } catch (error) {\n throw new Error(`Failed to initialize OpenTelemetry SDK: ${error}`)\n }\n}\n\n/**\n * Get the current SDK instance\n *\n * @returns WebTracerProvider instance or null if not initialized\n */\nexport function getSdkInstance(): WebTracerProvider | null {\n return sdkInstance\n}\n\n/**\n * Shutdown the SDK gracefully\n *\n * Flushes pending spans and releases resources\n */\nexport async function shutdownSdk(): Promise<void> {\n if (sdkInstance) {\n await sdkInstance.shutdown()\n sdkInstance = null\n }\n}\n\n/**\n * Reset the SDK instance (for testing)\n *\n * Does not shutdown - just clears the singleton\n */\nexport function resetSdk(): void {\n sdkInstance = null\n}\n","/**\n * Public API for @atrim/instrument-web\n *\n * Main initialization functions for browser instrumentation\n */\n\nimport type { WebTracerProvider } from '@opentelemetry/sdk-trace-web'\nimport { initializeSdk, type SdkInitializationOptions } from './core/sdk-initializer.js'\n\n/**\n * Initialize OpenTelemetry instrumentation for browser\n *\n * This is the main entry point for setting up tracing in browser applications.\n * Call this function once at application startup, before any other code runs.\n *\n * @param options - Initialization options\n * @returns WebTracerProvider instance\n * @throws {Error} If initialization fails\n *\n * @example\n * ```typescript\n * import { initializeInstrumentation } from '@atrim/instrument-web'\n *\n * await initializeInstrumentation({\n * serviceName: 'my-app',\n * otlpEndpoint: 'http://localhost:4318/v1/traces'\n * })\n * ```\n *\n * @example With pattern-based filtering\n * ```typescript\n * await initializeInstrumentation({\n * serviceName: 'my-app',\n * configUrl: 'https://config.company.com/instrumentation.yaml'\n * })\n * ```\n *\n * @example Disable specific instrumentations\n * ```typescript\n * await initializeInstrumentation({\n * serviceName: 'my-app',\n * enableUserInteraction: false, // Disable click tracking\n * enableXhr: false // Disable XMLHttpRequest tracking\n * })\n * ```\n */\nexport async function initializeInstrumentation(\n options: SdkInitializationOptions\n): Promise<WebTracerProvider> {\n return await initializeSdk(options)\n}\n","/**\n * Browser Span Helpers\n *\n * Utility functions for adding metadata to spans in browser applications\n */\n\nimport { Span, SpanStatusCode } from '@opentelemetry/api'\n\n/**\n * Set multiple attributes on a span\n *\n * @param span - OpenTelemetry span\n * @param attributes - Key-value pairs to set as attributes\n *\n * @example\n * ```typescript\n * setSpanAttributes(span, {\n * 'user.id': '123',\n * 'page.url': window.location.href\n * })\n * ```\n */\nexport function setSpanAttributes(\n span: Span,\n attributes: Record<string, string | number | boolean>\n): void {\n for (const [key, value] of Object.entries(attributes)) {\n span.setAttribute(key, value)\n }\n}\n\n/**\n * Record an exception on a span\n *\n * @param span - OpenTelemetry span\n * @param error - Error object to record\n * @param context - Additional context attributes\n *\n * @example\n * ```typescript\n * try {\n * // ...\n * } catch (error) {\n * recordException(span, error, { 'page.url': window.location.href })\n * }\n * ```\n */\nexport function recordException(\n span: Span,\n error: Error,\n context?: Record<string, string | number | boolean>\n): void {\n span.recordException(error)\n\n if (context) {\n setSpanAttributes(span, context)\n }\n}\n\n/**\n * Mark a span as successful\n *\n * Sets status to OK and adds optional attributes\n *\n * @param span - OpenTelemetry span\n * @param attributes - Optional attributes to add\n */\nexport function markSpanSuccess(\n span: Span,\n attributes?: Record<string, string | number | boolean>\n): void {\n span.setStatus({ code: SpanStatusCode.OK })\n\n if (attributes) {\n setSpanAttributes(span, attributes)\n }\n}\n\n/**\n * Mark a span as failed\n *\n * Sets status to ERROR and adds optional error message/attributes\n *\n * @param span - OpenTelemetry span\n * @param message - Error message\n * @param attributes - Optional attributes to add\n */\nexport function markSpanError(\n span: Span,\n message?: string,\n attributes?: Record<string, string | number | boolean>\n): void {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: message || 'Operation failed'\n })\n\n if (attributes) {\n setSpanAttributes(span, attributes)\n }\n}\n\n/**\n * Annotate span with HTTP request details\n *\n * @param span - OpenTelemetry span\n * @param options - HTTP request details\n *\n * @example\n * ```typescript\n * annotateHttpRequest(span, {\n * method: 'GET',\n * url: 'https://api.example.com/users',\n * statusCode: 200,\n * responseTime: 150\n * })\n * ```\n */\nexport function annotateHttpRequest(\n span: Span,\n options: {\n method?: string\n url?: string\n statusCode?: number\n responseTime?: number\n requestSize?: number\n responseSize?: number\n }\n): void {\n const attrs: Record<string, string | number> = {}\n\n if (options.method) attrs['http.method'] = options.method\n if (options.url) attrs['http.url'] = options.url\n if (options.statusCode) attrs['http.status_code'] = options.statusCode\n if (options.responseTime) attrs['http.response_time_ms'] = options.responseTime\n if (options.requestSize) attrs['http.request.body.size'] = options.requestSize\n if (options.responseSize) attrs['http.response.body.size'] = options.responseSize\n\n setSpanAttributes(span, attrs)\n}\n\n/**\n * Annotate span with cache operation details\n *\n * @param span - OpenTelemetry span\n * @param options - Cache operation details\n *\n * @example\n * ```typescript\n * annotate CacheOperation(span, {\n * operation: 'get',\n * key: 'user:123',\n * hit: true\n * })\n * ```\n */\nexport function annotateCacheOperation(\n span: Span,\n options: {\n operation: 'get' | 'set' | 'delete' | 'clear'\n key?: string\n hit?: boolean\n size?: number\n }\n): void {\n const attrs: Record<string, string | number | boolean> = {\n 'cache.operation': options.operation\n }\n\n if (options.key) attrs['cache.key'] = options.key\n if (options.hit !== undefined) attrs['cache.hit'] = options.hit\n if (options.size) attrs['cache.size'] = options.size\n\n setSpanAttributes(span, attrs)\n}\n\n/**\n * Annotate span with user interaction details\n *\n * @param span - OpenTelemetry span\n * @param options - User interaction details\n *\n * @example\n * ```typescript\n * annotateUserInteraction(span, {\n * type: 'click',\n * target: 'button#submit',\n * page: '/checkout'\n * })\n * ```\n */\nexport function annotateUserInteraction(\n span: Span,\n options: {\n type: 'click' | 'submit' | 'input' | 'navigation'\n target?: string\n page?: string\n }\n): void {\n const attrs: Record<string, string> = {\n 'user.interaction.type': options.type\n }\n\n if (options.target) attrs['user.interaction.target'] = options.target\n if (options.page) attrs['user.interaction.page'] = options.page\n\n setSpanAttributes(span, attrs)\n}\n\n/**\n * Annotate span with page navigation details\n *\n * @param span - OpenTelemetry span\n * @param options - Navigation details\n *\n * @example\n * ```typescript\n * annotateNavigation(span, {\n * from: '/home',\n * to: '/profile',\n * type: 'client-side'\n * })\n * ```\n */\nexport function annotateNavigation(\n span: Span,\n options: {\n from?: string\n to?: string\n type?: 'client-side' | 'server-side' | 'initial'\n }\n): void {\n const attrs: Record<string, string> = {}\n\n if (options.from) attrs['navigation.from'] = options.from\n if (options.to) attrs['navigation.to'] = options.to\n if (options.type) attrs['navigation.type'] = options.type\n\n setSpanAttributes(span, attrs)\n}\n"]}
1
+ {"version":3,"sources":["../../src/services/config-loader.ts","../../src/core/exporter-factory.ts","../../src/core/span-processor.ts","../../src/core/sdk-initializer.ts","../../src/api.ts","../../src/integrations/standard/span-helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAmBO,IAAM,sBAAsB,gBAAA,CAAiB,IAAA,CAAK,MAAM,OAAA,CAAQ,eAAA,CAAgB,KAAK,CAAC;AAU7F,eAAsB,WAAW,GAAA,EAA6C;AAC5E,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,GAAA,CAAI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AA;AAEhD,EAAA,iBAAA,CAAkB,MAAM,KAAK,CAAA;AAC/B;AAiBO,SAAS,uBAAA,CACd,MACA,OAAA,EAKM;AACN,EAAA,MAAM,KAAA,GAAgC;AAAA,IACpC,yBAAyB,OAAA,CAAQ;AAAA,GACnC;AAEA,EAAA,IAAI,OAAA,CAAQ,MAAA,EAAQ,KAAA,CAAM,yBAAyB,IAAI,OAAA,CAAQ,MAAA;AAC/D,EAAA,IAAI,OAAA,CAAQ,IAAA,EAAM,KAAA,CAAM,uBAAuB,IAAI,OAAA,CAAQ,IAAA;AAE3D,EAAA,iBAAA,CAAkB,MAAM,KAAK,CAAA;AAC/B;AAiBO,SAAS,kBAAA,CACd,MACA,OAAA,EAKM;AACN,EAAA,MAAM,QAAgC,EAAC;AAEvC,EAAA,IAAI,OAAA,CAAQ,IAAA,EAAM,KAAA,CAAM,iBAAiB,IAAI,OAAA,CAAQ,IAAA;AACrD,EAAA,IAAI,OAAA,CAAQ,EAAA,EAAI,KAAA,CAAM,eAAe,IAAI,OAAA,CAAQ,EAAA;AACjD,EAAA,IAAI,OAAA,CAAQ,IAAA,EAAM,KAAA,CAAM,iBAAiB,IAAI,OAAA,CAAQ,IAAA;AAErD,EAAA,iBAAA,CAAkB,MAAM,KAAK,CAAA;AAC/B","file":"index.js","sourcesContent":["/**\n * Browser configuration loader using Effect Platform\n *\n * Provides HttpClient layer for the core ConfigLoader service\n * (No FileSystem in browser)\n */\n\nimport { Effect, Layer } from 'effect'\nimport { FetchHttpClient } from '@effect/platform'\nimport { ConfigLoader, ConfigLoaderLive, type InstrumentationConfig } from '@atrim/instrument-core'\n\n/**\n * Complete ConfigLoader layer with browser platform dependencies\n *\n * Provides:\n * - ConfigLoader service\n * - HttpClient (from FetchHttpClient)\n * - No FileSystem (browser doesn't have filesystem access)\n */\nexport const WebConfigLoaderLive = ConfigLoaderLive.pipe(Layer.provide(FetchHttpClient.layer))\n\n/**\n * Load configuration from URI (Promise-based convenience API)\n *\n * Automatically provides browser platform layers (HttpClient only)\n *\n * @param uri - Configuration URI (http://, https://, or relative path)\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfig(uri: string): Promise<InstrumentationConfig> {\n const program = Effect.gen(function* () {\n const loader = yield* ConfigLoader\n return yield* loader.loadFromUri(uri)\n })\n\n return Effect.runPromise(program.pipe(Effect.provide(WebConfigLoaderLive)))\n}\n\n/**\n * Load configuration from inline content (Promise-based convenience API)\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfigFromInline(\n content: string | unknown\n): Promise<InstrumentationConfig> {\n const program = Effect.gen(function* () {\n const loader = yield* ConfigLoader\n return yield* loader.loadFromInline(content)\n })\n\n return Effect.runPromise(program.pipe(Effect.provide(WebConfigLoaderLive)))\n}\n","/**\n * OTLP Exporter Factory for Browser\n *\n * Creates OTLP HTTP exporters for sending traces from the browser.\n * Browser only supports HTTP/JSON protocol (no gRPC).\n */\n\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\n\nexport interface OtlpExporterOptions {\n /**\n * OTLP endpoint URL\n * Must end in /v1/traces for browser exporter\n * @default 'http://localhost:4318/v1/traces'\n */\n endpoint?: string\n\n /**\n * Custom HTTP headers (e.g., for authentication)\n * @example { 'Authorization': 'Bearer token' }\n */\n headers?: Record<string, string>\n\n /**\n * Request timeout in milliseconds\n * @default 10000\n */\n timeout?: number\n}\n\n/**\n * Create an OTLP HTTP trace exporter for browser\n *\n * @param options - Exporter configuration options\n * @returns OTLPTraceExporter instance\n *\n * @example\n * ```typescript\n * const exporter = createOtlpExporter({\n * endpoint: 'http://localhost:4318/v1/traces',\n * headers: { 'x-api-key': 'secret' }\n * })\n * ```\n */\nexport function createOtlpExporter(options: OtlpExporterOptions = {}): OTLPTraceExporter {\n const endpoint = options.endpoint || getOtlpEndpoint()\n\n return new OTLPTraceExporter({\n url: endpoint,\n headers: options.headers || {},\n timeoutMillis: options.timeout || 10000\n })\n}\n\n/**\n * Get OTLP endpoint from environment or use default\n *\n * Checks in order:\n * 1. import.meta.env.VITE_OTEL_EXPORTER_OTLP_ENDPOINT (Vite)\n * 2. window.OTEL_EXPORTER_OTLP_ENDPOINT (runtime config)\n * 3. Default: http://localhost:4318/v1/traces\n *\n * @returns OTLP endpoint URL\n */\nexport function getOtlpEndpoint(): string {\n // Check Vite environment variables\n try {\n if (typeof import.meta !== 'undefined') {\n const metaEnv = (import.meta as { env?: Record<string, unknown> }).env\n if (metaEnv && metaEnv.VITE_OTEL_EXPORTER_OTLP_ENDPOINT) {\n return String(metaEnv.VITE_OTEL_EXPORTER_OTLP_ENDPOINT)\n }\n }\n } catch {\n // import.meta may not be available in all environments\n }\n\n // Check window object (runtime config)\n if (typeof window !== 'undefined') {\n const windowConfig = (window as { OTEL_EXPORTER_OTLP_ENDPOINT?: unknown })\n .OTEL_EXPORTER_OTLP_ENDPOINT\n if (windowConfig) {\n return String(windowConfig)\n }\n }\n\n // Default endpoint\n return 'http://localhost:4318/v1/traces'\n}\n","/**\n * Pattern-Based Span Processor for Browser\n *\n * Filters spans based on patterns defined in instrumentation.yaml\n * Re-uses pattern matching logic from @atrim/instrument-core\n */\n\nimport { SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-base'\nimport { Context } from '@opentelemetry/api'\nimport { shouldInstrumentSpan } from '@atrim/instrument-core'\n\n/**\n * Span processor that filters spans based on pattern matching\n *\n * This processor runs BEFORE export and drops spans that don't match\n * the configured patterns in instrumentation.yaml.\n *\n * @example\n * ```yaml\n * # instrumentation.yaml\n * instrumentation:\n * instrument_patterns:\n * - pattern: \"^documentLoad\"\n * - pattern: \"^HTTP (GET|POST)\"\n * ignore_patterns:\n * - pattern: \"^HTTP GET /health\"\n * ```\n */\nexport class PatternSpanProcessor implements SpanProcessor {\n /**\n * Called when a span is started\n * No-op for this processor\n */\n onStart(_span: ReadableSpan, _parentContext: Context): void {\n // No-op\n }\n\n /**\n * Called when a span ends\n * Filters out spans that don't match patterns\n */\n onEnd(span: ReadableSpan): void {\n const spanName = span.name\n\n // Check if span should be instrumented\n if (!shouldInstrumentSpan(spanName)) {\n // Drop the span by not forwarding it\n // The span will not reach subsequent processors\n return\n }\n\n // Span passes filtering - will be processed by next processor\n }\n\n /**\n * Shutdown the processor\n * No-op for this processor\n */\n async shutdown(): Promise<void> {\n // No-op\n }\n\n /**\n * Force flush pending spans\n * No-op for this processor\n */\n async forceFlush(): Promise<void> {\n // No-op\n }\n}\n","/**\n * SDK Initializer for Browser\n *\n * Initializes the OpenTelemetry WebTracerProvider with:\n * - Auto-instrumentation (fetch, XHR, document load, user interactions)\n * - Pattern-based span filtering\n * - OTLP HTTP export\n */\n\nimport { WebTracerProvider } from '@opentelemetry/sdk-trace-web'\nimport { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'\nimport { registerInstrumentations } from '@opentelemetry/instrumentation'\nimport { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web'\nimport { ZoneContextManager } from '@opentelemetry/context-zone'\nimport type { InstrumentationConfig } from '@atrim/instrument-core'\nimport { initializePatternMatcher } from '@atrim/instrument-core'\nimport { loadConfig, loadConfigFromInline } from '../services/config-loader.js'\nimport { createOtlpExporter, type OtlpExporterOptions } from './exporter-factory.js'\nimport { PatternSpanProcessor } from './span-processor.js'\n\nexport interface SdkInitializationOptions {\n /**\n * Service name (required for browser - no auto-detection)\n * @example 'my-app-frontend'\n */\n serviceName: string\n\n /**\n * Service version (optional)\n * @example '1.0.0'\n */\n serviceVersion?: string\n\n /**\n * Path to instrumentation.yaml file\n * Note: Only works if file is publicly accessible\n */\n configPath?: string\n\n /**\n * URL to remote instrumentation.yaml\n * @example 'https://config.company.com/instrumentation.yaml'\n */\n configUrl?: string\n\n /**\n * Inline configuration object (takes precedence over file/URL)\n */\n config?: InstrumentationConfig\n\n /**\n * OTLP endpoint URL\n * @default 'http://localhost:4318/v1/traces'\n */\n otlpEndpoint?: string\n\n /**\n * OTLP HTTP headers\n * @example { 'Authorization': 'Bearer token' }\n */\n otlpHeaders?: Record<string, string>\n\n /**\n * Enable document load instrumentation\n * @default true\n */\n enableDocumentLoad?: boolean\n\n /**\n * Enable user interaction instrumentation\n * @default true\n */\n enableUserInteraction?: boolean\n\n /**\n * Enable fetch API instrumentation\n * @default true\n */\n enableFetch?: boolean\n\n /**\n * Enable XMLHttpRequest instrumentation\n * @default true\n */\n enableXhr?: boolean\n}\n\n// Singleton instance\nlet sdkInstance: WebTracerProvider | null = null\n\n/**\n * Initialize the OpenTelemetry SDK for browser\n *\n * @param options - SDK initialization options\n * @returns WebTracerProvider instance\n * @throws {Error} If initialization fails\n *\n * @example\n * ```typescript\n * const provider = await initializeSdk({\n * serviceName: 'my-app',\n * otlpEndpoint: 'http://localhost:4318/v1/traces'\n * })\n * ```\n */\nexport async function initializeSdk(options: SdkInitializationOptions): Promise<WebTracerProvider> {\n if (sdkInstance) {\n return sdkInstance\n }\n\n try {\n // Load configuration (if specified)\n let config: InstrumentationConfig | null = null\n\n if (options.config) {\n config = await loadConfigFromInline(options.config)\n } else if (options.configPath || options.configUrl) {\n // In browser, configPath is treated as a URL (can be relative like '/instrumentation.yaml')\n const url = options.configUrl || options.configPath!\n config = await loadConfig(url)\n }\n\n // Initialize pattern matcher (if config available)\n if (config) {\n initializePatternMatcher(config)\n }\n\n // Create OTLP exporter\n const exporterOptions: OtlpExporterOptions = {}\n if (options.otlpEndpoint) {\n exporterOptions.endpoint = options.otlpEndpoint\n }\n if (options.otlpHeaders) {\n exporterOptions.headers = options.otlpHeaders\n }\n const exporter = createOtlpExporter(exporterOptions)\n\n // Build span processors array\n const spanProcessors = []\n\n // 1. Pattern-based filtering (if config available)\n if (config) {\n spanProcessors.push(new PatternSpanProcessor())\n }\n\n // 2. OTLP export (SimpleSpanProcessor for browser - no batching)\n spanProcessors.push(new SimpleSpanProcessor(exporter))\n\n // Create WebTracerProvider with processors\n // Note: Resource configuration will be handled via environment or programmatically\n const provider = new WebTracerProvider({\n spanProcessors\n })\n\n // Note: Resource attributes (service name, version) should be set via:\n // 1. OTEL_RESOURCE_ATTRIBUTES environment variable\n // 2. Custom Resource passed to WebTracerProvider\n // 3. Collector configuration\n // For now, serviceName is used primarily for logging/debugging\n\n // Register the provider\n provider.register({\n contextManager: new ZoneContextManager()\n })\n\n // Register auto-instrumentations\n registerInstrumentations({\n instrumentations: [\n getWebAutoInstrumentations({\n '@opentelemetry/instrumentation-document-load': {\n enabled: options.enableDocumentLoad ?? true\n },\n '@opentelemetry/instrumentation-user-interaction': {\n enabled: options.enableUserInteraction ?? true,\n eventNames: ['click', 'submit']\n },\n '@opentelemetry/instrumentation-fetch': {\n enabled: options.enableFetch ?? true,\n propagateTraceHeaderCorsUrls: [/.*/], // Propagate to all origins\n clearTimingResources: true\n },\n '@opentelemetry/instrumentation-xml-http-request': {\n enabled: options.enableXhr ?? true,\n propagateTraceHeaderCorsUrls: [/.*/]\n }\n })\n ]\n })\n\n sdkInstance = provider\n return provider\n } catch (error) {\n throw new Error(`Failed to initialize OpenTelemetry SDK: ${error}`)\n }\n}\n\n/**\n * Get the current SDK instance\n *\n * @returns WebTracerProvider instance or null if not initialized\n */\nexport function getSdkInstance(): WebTracerProvider | null {\n return sdkInstance\n}\n\n/**\n * Shutdown the SDK gracefully\n *\n * Flushes pending spans and releases resources\n */\nexport async function shutdownSdk(): Promise<void> {\n if (sdkInstance) {\n await sdkInstance.shutdown()\n sdkInstance = null\n }\n}\n\n/**\n * Reset the SDK instance (for testing)\n *\n * Does not shutdown - just clears the singleton\n */\nexport function resetSdk(): void {\n sdkInstance = null\n}\n","/**\n * Public API for @atrim/instrument-web\n *\n * Main initialization functions for browser instrumentation\n */\n\nimport type { WebTracerProvider } from '@opentelemetry/sdk-trace-web'\nimport { initializeSdk, type SdkInitializationOptions } from './core/sdk-initializer.js'\n\n/**\n * Initialize OpenTelemetry instrumentation for browser\n *\n * This is the main entry point for setting up tracing in browser applications.\n * Call this function once at application startup, before any other code runs.\n *\n * @param options - Initialization options\n * @returns WebTracerProvider instance\n * @throws {Error} If initialization fails\n *\n * @example\n * ```typescript\n * import { initializeInstrumentation } from '@atrim/instrument-web'\n *\n * await initializeInstrumentation({\n * serviceName: 'my-app',\n * otlpEndpoint: 'http://localhost:4318/v1/traces'\n * })\n * ```\n *\n * @example With pattern-based filtering\n * ```typescript\n * await initializeInstrumentation({\n * serviceName: 'my-app',\n * configUrl: 'https://config.company.com/instrumentation.yaml'\n * })\n * ```\n *\n * @example Disable specific instrumentations\n * ```typescript\n * await initializeInstrumentation({\n * serviceName: 'my-app',\n * enableUserInteraction: false, // Disable click tracking\n * enableXhr: false // Disable XMLHttpRequest tracking\n * })\n * ```\n */\nexport async function initializeInstrumentation(\n options: SdkInitializationOptions\n): Promise<WebTracerProvider> {\n return await initializeSdk(options)\n}\n","/**\n * Browser Span Helpers\n *\n * Utility functions for adding metadata to spans in browser applications\n */\n\nimport { Span, SpanStatusCode } from '@opentelemetry/api'\n\n/**\n * Set multiple attributes on a span\n *\n * @param span - OpenTelemetry span\n * @param attributes - Key-value pairs to set as attributes\n *\n * @example\n * ```typescript\n * setSpanAttributes(span, {\n * 'user.id': '123',\n * 'page.url': window.location.href\n * })\n * ```\n */\nexport function setSpanAttributes(\n span: Span,\n attributes: Record<string, string | number | boolean>\n): void {\n for (const [key, value] of Object.entries(attributes)) {\n span.setAttribute(key, value)\n }\n}\n\n/**\n * Record an exception on a span\n *\n * @param span - OpenTelemetry span\n * @param error - Error object to record\n * @param context - Additional context attributes\n *\n * @example\n * ```typescript\n * try {\n * // ...\n * } catch (error) {\n * recordException(span, error, { 'page.url': window.location.href })\n * }\n * ```\n */\nexport function recordException(\n span: Span,\n error: Error,\n context?: Record<string, string | number | boolean>\n): void {\n span.recordException(error)\n\n if (context) {\n setSpanAttributes(span, context)\n }\n}\n\n/**\n * Mark a span as successful\n *\n * Sets status to OK and adds optional attributes\n *\n * @param span - OpenTelemetry span\n * @param attributes - Optional attributes to add\n */\nexport function markSpanSuccess(\n span: Span,\n attributes?: Record<string, string | number | boolean>\n): void {\n span.setStatus({ code: SpanStatusCode.OK })\n\n if (attributes) {\n setSpanAttributes(span, attributes)\n }\n}\n\n/**\n * Mark a span as failed\n *\n * Sets status to ERROR and adds optional error message/attributes\n *\n * @param span - OpenTelemetry span\n * @param message - Error message\n * @param attributes - Optional attributes to add\n */\nexport function markSpanError(\n span: Span,\n message?: string,\n attributes?: Record<string, string | number | boolean>\n): void {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: message || 'Operation failed'\n })\n\n if (attributes) {\n setSpanAttributes(span, attributes)\n }\n}\n\n/**\n * Annotate span with HTTP request details\n *\n * @param span - OpenTelemetry span\n * @param options - HTTP request details\n *\n * @example\n * ```typescript\n * annotateHttpRequest(span, {\n * method: 'GET',\n * url: 'https://api.example.com/users',\n * statusCode: 200,\n * responseTime: 150\n * })\n * ```\n */\nexport function annotateHttpRequest(\n span: Span,\n options: {\n method?: string\n url?: string\n statusCode?: number\n responseTime?: number\n requestSize?: number\n responseSize?: number\n }\n): void {\n const attrs: Record<string, string | number> = {}\n\n if (options.method) attrs['http.method'] = options.method\n if (options.url) attrs['http.url'] = options.url\n if (options.statusCode) attrs['http.status_code'] = options.statusCode\n if (options.responseTime) attrs['http.response_time_ms'] = options.responseTime\n if (options.requestSize) attrs['http.request.body.size'] = options.requestSize\n if (options.responseSize) attrs['http.response.body.size'] = options.responseSize\n\n setSpanAttributes(span, attrs)\n}\n\n/**\n * Annotate span with cache operation details\n *\n * @param span - OpenTelemetry span\n * @param options - Cache operation details\n *\n * @example\n * ```typescript\n * annotate CacheOperation(span, {\n * operation: 'get',\n * key: 'user:123',\n * hit: true\n * })\n * ```\n */\nexport function annotateCacheOperation(\n span: Span,\n options: {\n operation: 'get' | 'set' | 'delete' | 'clear'\n key?: string\n hit?: boolean\n size?: number\n }\n): void {\n const attrs: Record<string, string | number | boolean> = {\n 'cache.operation': options.operation\n }\n\n if (options.key) attrs['cache.key'] = options.key\n if (options.hit !== undefined) attrs['cache.hit'] = options.hit\n if (options.size) attrs['cache.size'] = options.size\n\n setSpanAttributes(span, attrs)\n}\n\n/**\n * Annotate span with user interaction details\n *\n * @param span - OpenTelemetry span\n * @param options - User interaction details\n *\n * @example\n * ```typescript\n * annotateUserInteraction(span, {\n * type: 'click',\n * target: 'button#submit',\n * page: '/checkout'\n * })\n * ```\n */\nexport function annotateUserInteraction(\n span: Span,\n options: {\n type: 'click' | 'submit' | 'input' | 'navigation'\n target?: string\n page?: string\n }\n): void {\n const attrs: Record<string, string> = {\n 'user.interaction.type': options.type\n }\n\n if (options.target) attrs['user.interaction.target'] = options.target\n if (options.page) attrs['user.interaction.page'] = options.page\n\n setSpanAttributes(span, attrs)\n}\n\n/**\n * Annotate span with page navigation details\n *\n * @param span - OpenTelemetry span\n * @param options - Navigation details\n *\n * @example\n * ```typescript\n * annotateNavigation(span, {\n * from: '/home',\n * to: '/profile',\n * type: 'client-side'\n * })\n * ```\n */\nexport function annotateNavigation(\n span: Span,\n options: {\n from?: string\n to?: string\n type?: 'client-side' | 'server-side' | 'initial'\n }\n): void {\n const attrs: Record<string, string> = {}\n\n if (options.from) attrs['navigation.from'] = options.from\n if (options.to) attrs['navigation.to'] = options.to\n if (options.type) attrs['navigation.type'] = options.type\n\n setSpanAttributes(span, attrs)\n}\n"]}