@pingops/sdk 0.3.0 → 0.4.0
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/README.md +12 -26
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +3 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{pingops-BzTLP70O.cjs → pingops-D7n9pxch.cjs} +22 -31
- package/dist/pingops-D7n9pxch.cjs.map +1 -0
- package/dist/{pingops-DyKGq6Vr.mjs → pingops-DDeCBa2d.mjs} +21 -30
- package/dist/pingops-DDeCBa2d.mjs.map +1 -0
- package/dist/register.cjs +1 -1
- package/dist/register.mjs +1 -1
- package/package.json +3 -3
- package/dist/pingops-BzTLP70O.cjs.map +0 -1
- package/dist/pingops-DyKGq6Vr.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -135,15 +135,12 @@ Configuration can be provided via:
|
|
|
135
135
|
| `baseUrl` | `string` | **required** | Backend base URL |
|
|
136
136
|
| `serviceName` | `string` | **required** | Service name |
|
|
137
137
|
| `debug` | `boolean` | `false` | Enable debug logs (`PINGOPS_DEBUG=true`) |
|
|
138
|
-
| `headersAllowList` | `string[]` | — | Headers to include (case-insensitive) |
|
|
139
|
-
| `headersDenyList` | `string[]` | — | Headers to exclude (overrides allow) |
|
|
140
138
|
| `captureRequestBody` | `boolean` | `false` | Capture request bodies (global) |
|
|
141
139
|
| `captureResponseBody` | `boolean` | `false` | Capture response bodies (global) |
|
|
142
|
-
| `maxRequestBodySize` | `number` | `10240` | Max request body size in bytes |
|
|
143
|
-
| `maxResponseBodySize` | `number` | `10240` | Max response body size in bytes |
|
|
144
140
|
| `domainAllowList` | `DomainRule[]` | — | Domains (and optional rules) to allow |
|
|
145
141
|
| `domainDenyList` | `DomainRule[]` | — | Domains to exclude |
|
|
146
|
-
| `
|
|
142
|
+
| `llmMonitoring` | `LlmMonitoringConfig` | disabled | Opt-in GenAI token enrichment |
|
|
143
|
+
| `transforms` | `HttpTransformConfig` | — | Outbound transform rules for headers/body/query |
|
|
147
144
|
| `batchSize` | `number` | `50` | Spans per batch (`PINGOPS_BATCH_SIZE`) |
|
|
148
145
|
| `batchTimeout` | `number` | `5000` | Flush interval in ms (`PINGOPS_BATCH_TIMEOUT`) |
|
|
149
146
|
| `exportMode` | `"batched"` \| `"immediate"` | `"batched"` | `PINGOPS_EXPORT_MODE` |
|
|
@@ -155,6 +152,12 @@ Configuration can be provided via:
|
|
|
155
152
|
- **`batched`** — Best for long-running processes; spans are sent in batches (default).
|
|
156
153
|
- **`immediate`** — Best for serverless/short-lived processes; each span is sent as it finishes to reduce loss on freeze/exit.
|
|
157
154
|
|
|
155
|
+
**LLM monitoring (opt-in):**
|
|
156
|
+
|
|
157
|
+
- Enable with `llmMonitoring.enabled: true`.
|
|
158
|
+
- Supported providers auto-detected in v1: `openai`, `anthropic`, `gemini`, `xai`.
|
|
159
|
+
- Captures GenAI token attributes even when request/response body capture is disabled. Costs are computed on backend.
|
|
160
|
+
|
|
158
161
|
### Config file examples
|
|
159
162
|
|
|
160
163
|
**JSON (`pingops.config.json`):**
|
|
@@ -277,7 +280,7 @@ const data = await startTrace(
|
|
|
277
280
|
|
|
278
281
|
---
|
|
279
282
|
|
|
280
|
-
### `
|
|
283
|
+
### `suppressInstrumentation(fn)`
|
|
281
284
|
|
|
282
285
|
Runs `fn` in an intentionally tracing-suppressed context.
|
|
283
286
|
|
|
@@ -292,9 +295,9 @@ Use this to exclude a specific code block from telemetry capture. Any spans star
|
|
|
292
295
|
**Example:**
|
|
293
296
|
|
|
294
297
|
```typescript
|
|
295
|
-
import {
|
|
298
|
+
import { suppressInstrumentation } from "@pingops/sdk";
|
|
296
299
|
|
|
297
|
-
await
|
|
300
|
+
await suppressInstrumentation(async () => {
|
|
298
301
|
await fetch("https://internal.example.com/health");
|
|
299
302
|
// any outbound API calls here are intentionally not captured
|
|
300
303
|
});
|
|
@@ -418,23 +421,8 @@ Each rule in `domainAllowList` / `domainDenyList` can include:
|
|
|
418
421
|
|
|
419
422
|
- `domain` — Exact or suffix (e.g. `.openai.com`) match.
|
|
420
423
|
- `paths` — Optional path prefixes to allow/deny.
|
|
421
|
-
- `headersAllowList` / `headersDenyList` — Header rules for that domain.
|
|
422
424
|
- `captureRequestBody` / `captureResponseBody` — Override body capture for that domain.
|
|
423
|
-
|
|
424
|
-
### Header allow/deny lists
|
|
425
|
-
|
|
426
|
-
Control which headers are included on captured spans (global default; domain rules can refine):
|
|
427
|
-
|
|
428
|
-
```typescript
|
|
429
|
-
initializePingops({
|
|
430
|
-
baseUrl: "https://api.pingops.com",
|
|
431
|
-
serviceName: "my-service",
|
|
432
|
-
headersAllowList: ["user-agent", "x-request-id", "content-type"],
|
|
433
|
-
headersDenyList: ["authorization", "cookie", "x-api-key"],
|
|
434
|
-
});
|
|
435
|
-
```
|
|
436
|
-
|
|
437
|
-
Deny list takes precedence over allow list. Sensitive headers are redacted by default; use `headerRedaction` in config for custom behavior.
|
|
425
|
+
- `transforms` — Domain-specific transform configuration (overrides global `transforms` for matching spans).
|
|
438
426
|
|
|
439
427
|
### Request/response body capture
|
|
440
428
|
|
|
@@ -442,8 +430,6 @@ Deny list takes precedence over allow list. Sensitive headers are redacted by de
|
|
|
442
430
|
- **Per-domain:** Same flags on a [DomainRule](#domain-allowdeny-lists).
|
|
443
431
|
- **Per-trace:** `captureRequestBody` / `captureResponseBody` in [PingopsTraceAttributes](#pingopstraceattributes) in `startTrace`.
|
|
444
432
|
|
|
445
|
-
Body size is capped by `maxRequestBodySize` and `maxResponseBodySize` (default 10240 bytes each). Larger bodies are truncated.
|
|
446
|
-
|
|
447
433
|
---
|
|
448
434
|
|
|
449
435
|
## Integration with Existing OpenTelemetry
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
const require_pingops = require('./pingops-
|
|
1
|
+
const require_pingops = require('./pingops-D7n9pxch.cjs');
|
|
2
2
|
|
|
3
3
|
exports.getActiveSpanId = require_pingops.getActiveSpanId;
|
|
4
4
|
exports.getActiveTraceId = require_pingops.getActiveTraceId;
|
|
5
5
|
exports.initializePingops = require_pingops.initializePingops;
|
|
6
6
|
exports.shutdownPingops = require_pingops.shutdownPingops;
|
|
7
7
|
exports.startTrace = require_pingops.startTrace;
|
|
8
|
-
exports.
|
|
8
|
+
exports.suppressInstrumentation = require_pingops.suppressInstrumentation;
|
package/dist/index.d.cts
CHANGED
|
@@ -40,8 +40,8 @@ declare function getActiveSpanId(): string | undefined;
|
|
|
40
40
|
* Any spans started in this callback (including auto-instrumented outbound HTTP/fetch spans)
|
|
41
41
|
* are intentionally dropped and not exported.
|
|
42
42
|
*/
|
|
43
|
-
declare function
|
|
44
|
-
declare function
|
|
43
|
+
declare function suppressInstrumentation<T>(fn: () => T): T;
|
|
44
|
+
declare function suppressInstrumentation<T>(fn: () => Promise<T>): Promise<T>;
|
|
45
45
|
/**
|
|
46
46
|
* Starts a new trace using the PingOps tracer provider and runs the callback within that trace.
|
|
47
47
|
* Sets attributes (traceId, userId, sessionId, tags, metadata, etc.) in context so they are
|
|
@@ -76,5 +76,5 @@ declare function startTrace<T>(options: {
|
|
|
76
76
|
seed?: string;
|
|
77
77
|
}, fn: () => T | Promise<T>): Promise<T>;
|
|
78
78
|
//#endregion
|
|
79
|
-
export { type PingopsTraceAttributes, getActiveSpanId, getActiveTraceId, initializePingops, shutdownPingops, startTrace,
|
|
79
|
+
export { type PingopsTraceAttributes, getActiveSpanId, getActiveTraceId, initializePingops, shutdownPingops, startTrace, suppressInstrumentation };
|
|
80
80
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/pingops.ts"],"sourcesContent":[],"mappings":";;;;;AAsTA;AAOA;AAUA;AACA;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/pingops.ts"],"sourcesContent":[],"mappings":";;;;;AAsTA;AAOA;AAUA;AACA;;;;;;AAwCA;;;;;AAMW,iBAhTK,iBAAA,CAgTL,MAAA,EA/SD,sBA+SC,EAAA,QAAA,CAAA,EAAA,OAAA,CAAA,EAAA,IAAA;AAAR,iBA5Sa,iBAAA,CA4Sb,cAAA,EAAA,MAAA,EAAA,QAAA,CAAA,EAAA,OAAA,CAAA,EAAA,IAAA;AAAO,iBAxSM,iBAAA,CAwSN,MAAA,EAAA;;;;;;iBA9LY,eAAA,CAAA,GAAmB;;;;iBA8HzB,gBAAA,CAAA;;;;iBAOA,eAAA,CAAA;;;;;;;iBAUA,qCAAqC,IAAI;iBACzC,qCAAqC,QAAQ,KAAK,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAwCpD;eAEL;;aAGL,IAAI,QAAQ,KACrB,QAAQ"}
|
package/dist/index.d.mts
CHANGED
|
@@ -40,8 +40,8 @@ declare function getActiveSpanId(): string | undefined;
|
|
|
40
40
|
* Any spans started in this callback (including auto-instrumented outbound HTTP/fetch spans)
|
|
41
41
|
* are intentionally dropped and not exported.
|
|
42
42
|
*/
|
|
43
|
-
declare function
|
|
44
|
-
declare function
|
|
43
|
+
declare function suppressInstrumentation<T>(fn: () => T): T;
|
|
44
|
+
declare function suppressInstrumentation<T>(fn: () => Promise<T>): Promise<T>;
|
|
45
45
|
/**
|
|
46
46
|
* Starts a new trace using the PingOps tracer provider and runs the callback within that trace.
|
|
47
47
|
* Sets attributes (traceId, userId, sessionId, tags, metadata, etc.) in context so they are
|
|
@@ -76,5 +76,5 @@ declare function startTrace<T>(options: {
|
|
|
76
76
|
seed?: string;
|
|
77
77
|
}, fn: () => T | Promise<T>): Promise<T>;
|
|
78
78
|
//#endregion
|
|
79
|
-
export { type PingopsTraceAttributes, getActiveSpanId, getActiveTraceId, initializePingops, shutdownPingops, startTrace,
|
|
79
|
+
export { type PingopsTraceAttributes, getActiveSpanId, getActiveTraceId, initializePingops, shutdownPingops, startTrace, suppressInstrumentation };
|
|
80
80
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/pingops.ts"],"sourcesContent":[],"mappings":";;;;;AAsTA;AAOA;AAUA;AACA;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/pingops.ts"],"sourcesContent":[],"mappings":";;;;;AAsTA;AAOA;AAUA;AACA;;;;;;AAwCA;;;;;AAMW,iBAhTK,iBAAA,CAgTL,MAAA,EA/SD,sBA+SC,EAAA,QAAA,CAAA,EAAA,OAAA,CAAA,EAAA,IAAA;AAAR,iBA5Sa,iBAAA,CA4Sb,cAAA,EAAA,MAAA,EAAA,QAAA,CAAA,EAAA,OAAA,CAAA,EAAA,IAAA;AAAO,iBAxSM,iBAAA,CAwSN,MAAA,EAAA;;;;;;iBA9LY,eAAA,CAAA,GAAmB;;;;iBA8HzB,gBAAA,CAAA;;;;iBAOA,eAAA,CAAA;;;;;;;iBAUA,qCAAqC,IAAI;iBACzC,qCAAqC,QAAQ,KAAK,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAwCpD;eAEL;;aAGL,IAAI,QAAQ,KACrB,QAAQ"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as startTrace, i as shutdownPingops, n as getActiveTraceId, o as
|
|
1
|
+
import { a as startTrace, i as shutdownPingops, n as getActiveTraceId, o as suppressInstrumentation, r as initializePingops, t as getActiveSpanId } from "./pingops-DDeCBa2d.mjs";
|
|
2
2
|
|
|
3
|
-
export { getActiveSpanId, getActiveTraceId, initializePingops, shutdownPingops, startTrace,
|
|
3
|
+
export { getActiveSpanId, getActiveTraceId, initializePingops, shutdownPingops, startTrace, suppressInstrumentation };
|
|
@@ -72,7 +72,7 @@ function setSdkInitialized(initialized) {
|
|
|
72
72
|
|
|
73
73
|
//#endregion
|
|
74
74
|
//#region package.json
|
|
75
|
-
var version = "0.
|
|
75
|
+
var version = "0.4.0";
|
|
76
76
|
|
|
77
77
|
//#endregion
|
|
78
78
|
//#region src/sdk-version.ts
|
|
@@ -241,7 +241,7 @@ function getActiveTraceId() {
|
|
|
241
241
|
function getActiveSpanId() {
|
|
242
242
|
return _opentelemetry_api.trace.getActiveSpan()?.spanContext().spanId;
|
|
243
243
|
}
|
|
244
|
-
function
|
|
244
|
+
function suppressInstrumentation(fn) {
|
|
245
245
|
const untrackedContext = (0, _opentelemetry_core.suppressTracing)(_opentelemetry_api.context.active()).setValue(_pingops_core.PINGOPS_INTENTIONAL_SUPPRESSION, true);
|
|
246
246
|
return _opentelemetry_api.context.with(untrackedContext, fn);
|
|
247
247
|
}
|
|
@@ -287,33 +287,24 @@ async function startTrace(options, fn) {
|
|
|
287
287
|
logger.warn("startTrace detected a suppressed active context and is running on ROOT_CONTEXT to prevent suppression leakage into user outbound instrumentation");
|
|
288
288
|
hasLoggedSuppressedStartTraceWarning = true;
|
|
289
289
|
} else logger.debug("startTrace received a suppressed active context; running trace on ROOT_CONTEXT");
|
|
290
|
-
const
|
|
291
|
-
|
|
290
|
+
const runWithAttributes = () => {
|
|
291
|
+
let contextWithAttributes = _opentelemetry_api.context.active();
|
|
292
|
+
const attrs = options.attributes;
|
|
293
|
+
if (attrs) contextWithAttributes = setAttributesInContext(contextWithAttributes, attrs);
|
|
294
|
+
contextWithAttributes = contextWithAttributes.setValue(_pingops_core.PINGOPS_TRACE_ID, traceId);
|
|
295
|
+
return _opentelemetry_api.context.with(contextWithAttributes, fn);
|
|
296
|
+
};
|
|
292
297
|
return new Promise((resolve$1, reject) => {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
resolve$1(v);
|
|
304
|
-
}).catch((err) => {
|
|
305
|
-
span.end();
|
|
306
|
-
reject(err instanceof Error ? err : new Error(String(err)));
|
|
307
|
-
});
|
|
308
|
-
else {
|
|
309
|
-
span.end();
|
|
310
|
-
resolve$1(result);
|
|
311
|
-
}
|
|
312
|
-
} catch (err) {
|
|
313
|
-
span.end();
|
|
314
|
-
reject(err instanceof Error ? err : new Error(String(err)));
|
|
315
|
-
}
|
|
316
|
-
});
|
|
298
|
+
const nonRecordingParent = _opentelemetry_api.trace.wrapSpanContext(spanContext);
|
|
299
|
+
const contextWithParentSpan = _opentelemetry_api.trace.setSpan(traceExecutionBaseContext, nonRecordingParent);
|
|
300
|
+
const contextWithTrace = _opentelemetry_api.trace.setSpanContext(contextWithParentSpan, spanContext);
|
|
301
|
+
try {
|
|
302
|
+
const result = _opentelemetry_api.context.with(contextWithTrace, runWithAttributes);
|
|
303
|
+
if (result instanceof Promise) result.then((v) => resolve$1(v)).catch((err) => reject(err instanceof Error ? err : new Error(String(err))));
|
|
304
|
+
else resolve$1(result);
|
|
305
|
+
} catch (err) {
|
|
306
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
307
|
+
}
|
|
317
308
|
});
|
|
318
309
|
}
|
|
319
310
|
function getUnsuppressedContext() {
|
|
@@ -374,10 +365,10 @@ Object.defineProperty(exports, 'startTrace', {
|
|
|
374
365
|
return startTrace;
|
|
375
366
|
}
|
|
376
367
|
});
|
|
377
|
-
Object.defineProperty(exports, '
|
|
368
|
+
Object.defineProperty(exports, 'suppressInstrumentation', {
|
|
378
369
|
enumerable: true,
|
|
379
370
|
get: function () {
|
|
380
|
-
return
|
|
371
|
+
return suppressInstrumentation;
|
|
381
372
|
}
|
|
382
373
|
});
|
|
383
|
-
//# sourceMappingURL=pingops-
|
|
374
|
+
//# sourceMappingURL=pingops-D7n9pxch.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pingops-D7n9pxch.cjs","names":["isSdkInitializedFlag","(sdkPackageJson as PackageJsonWithVersion).version","ATTR_SERVICE_NAME","PingopsSpanProcessor","NodeSDK","NodeTracerProvider","trace","context","PINGOPS_INTENTIONAL_SUPPRESSION","ROOT_CONTEXT","PINGOPS_TRACE_ID","resolve","PINGOPS_USER_ID","PINGOPS_SESSION_ID","PINGOPS_TAGS","PINGOPS_METADATA","PINGOPS_CAPTURE_REQUEST_BODY","PINGOPS_CAPTURE_RESPONSE_BODY"],"sources":["../src/config-loader.ts","../src/init-state.ts","../package.json","../src/sdk-version.ts","../src/pingops.ts"],"sourcesContent":["/**\n * Configuration loader for reading PingOps config from JSON/YAML files\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { load as loadYaml } from \"js-yaml\";\nimport type { PingopsProcessorConfig } from \"@pingops/otel\";\n\n/**\n * Loads configuration from a JSON or YAML file\n *\n * @param filePath - Path to the config file (JSON or YAML)\n * @returns Parsed configuration object\n * @throws Error if file cannot be read or parsed\n */\nexport function loadConfigFromFile(\n filePath: string\n): Partial<PingopsProcessorConfig> {\n const resolvedPath = resolve(filePath);\n const fileContent = readFileSync(resolvedPath, \"utf-8\");\n\n const ext = resolvedPath.toLowerCase();\n if (ext.endsWith(\".yaml\") || ext.endsWith(\".yml\")) {\n return (loadYaml(fileContent) as Partial<PingopsProcessorConfig>) || {};\n } else if (ext.endsWith(\".json\")) {\n return JSON.parse(fileContent) as Partial<PingopsProcessorConfig>;\n } else {\n // Try to parse as JSON first, then YAML\n try {\n return JSON.parse(fileContent) as Partial<PingopsProcessorConfig>;\n } catch {\n return (loadYaml(fileContent) as Partial<PingopsProcessorConfig>) || {};\n }\n }\n}\n\n/**\n * Merges configuration from file and environment variables.\n * Environment variables take precedence over file config.\n *\n * @param fileConfig - Configuration loaded from file\n * @returns Merged configuration with env vars taking precedence\n */\nexport function mergeConfigWithEnv(\n fileConfig: Partial<PingopsProcessorConfig>\n): Partial<PingopsProcessorConfig> {\n const envConfig: Partial<PingopsProcessorConfig> = {};\n\n // Read from environment variables\n if (process.env.PINGOPS_API_KEY) {\n envConfig.apiKey = process.env.PINGOPS_API_KEY;\n }\n if (process.env.PINGOPS_BASE_URL) {\n envConfig.baseUrl = process.env.PINGOPS_BASE_URL;\n }\n if (process.env.PINGOPS_SERVICE_NAME) {\n envConfig.serviceName = process.env.PINGOPS_SERVICE_NAME;\n }\n if (process.env.PINGOPS_DEBUG) {\n envConfig.debug = process.env.PINGOPS_DEBUG === \"true\";\n }\n if (process.env.PINGOPS_BATCH_SIZE) {\n envConfig.batchSize = parseInt(process.env.PINGOPS_BATCH_SIZE, 10);\n }\n if (process.env.PINGOPS_BATCH_TIMEOUT) {\n envConfig.batchTimeout = parseInt(process.env.PINGOPS_BATCH_TIMEOUT, 10);\n }\n if (process.env.PINGOPS_EXPORT_MODE) {\n envConfig.exportMode = process.env.PINGOPS_EXPORT_MODE as\n | \"batched\"\n | \"immediate\";\n }\n\n // Merge: env vars override file config\n return {\n ...fileConfig,\n ...envConfig,\n };\n}\n","/**\n * Shared state for tracking SDK initialization\n * This module exists to avoid circular dependencies between pingops.ts and instrumentation.ts\n */\n\nlet isSdkInitializedFlag = false;\n\n/**\n * Returns whether the SDK has been initialized.\n */\nexport function isSdkInitialized(): boolean {\n return isSdkInitializedFlag;\n}\n\n/**\n * Sets the SDK initialization flag.\n * Called by initializePingops when the SDK is initialized.\n */\nexport function setSdkInitialized(initialized: boolean): void {\n isSdkInitializedFlag = initialized;\n}\n","","import sdkPackageJson from \"../package.json\";\n\ntype PackageJsonWithVersion = {\n version?: string;\n};\n\nconst packageVersion = (sdkPackageJson as PackageJsonWithVersion).version;\n\nexport const SDK_VERSION =\n typeof packageVersion === \"string\" ? packageVersion : \"unknown\";\n","/**\n * PingOps SDK singleton for manual instrumentation\n *\n * Provides initializePingops, shutdownPingops, startTrace, getActiveTraceId,\n * and getActiveSpanId. startTrace can auto-initialize from environment variables if needed.\n */\n\nimport { ROOT_CONTEXT, context, trace } from \"@opentelemetry/api\";\nimport { isTracingSuppressed, suppressTracing } from \"@opentelemetry/core\";\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport { ATTR_SERVICE_NAME } from \"@opentelemetry/semantic-conventions\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\nimport type { PingopsProcessorConfig } from \"@pingops/otel\";\nimport {\n setPingopsTracerProvider,\n shutdownTracerProvider,\n PingopsSpanProcessor,\n} from \"@pingops/otel\";\nimport {\n createLogger,\n createTraceId,\n uint8ArrayToHex,\n type PingopsTraceAttributes,\n} from \"@pingops/core\";\nimport {\n PINGOPS_TRACE_ID,\n PINGOPS_USER_ID,\n PINGOPS_SESSION_ID,\n PINGOPS_TAGS,\n PINGOPS_METADATA,\n PINGOPS_CAPTURE_REQUEST_BODY,\n PINGOPS_CAPTURE_RESPONSE_BODY,\n PINGOPS_INTENTIONAL_SUPPRESSION,\n} from \"@pingops/core\";\nimport { loadConfigFromFile, mergeConfigWithEnv } from \"./config-loader\";\nimport { setSdkInitialized } from \"./init-state\";\nimport { getPingopsTracerProvider } from \"@pingops/otel\";\nimport { getInstrumentations } from \"@pingops/otel\";\nimport { SDK_VERSION } from \"./sdk-version\";\n\nconst TRACE_FLAG_SAMPLED = 1;\n\nconst initLogger = createLogger(\"[PingOps Initialize]\");\nconst logger = createLogger(\"[PingOps Pingops]\");\n\nlet sdkInstance: NodeSDK | null = null;\nlet isSdkInitializedFlag = false;\n\n/**\n * Global state to track initialization\n */\nlet isInitialized = false;\nlet initializationPromise: Promise<void> | null = null;\nlet hasLoggedSuppressedStartTraceWarning = false;\n\n/**\n * Initializes PingOps SDK\n *\n * This function:\n * 1. Creates an OpenTelemetry NodeSDK instance\n * 2. Configures Resource with service.name\n * 3. Registers PingopsSpanProcessor\n * 4. Enables HTTP/fetch/GenAI instrumentation\n * 5. Starts the SDK\n *\n * @param config - Configuration object, config file path, or config file wrapper\n * @param explicit - Whether this is an explicit call (default: true).\n * Set to false when called internally by startTrace auto-initialization.\n */\nexport function initializePingops(\n config: PingopsProcessorConfig,\n explicit?: boolean\n): void;\nexport function initializePingops(\n configFilePath: string,\n explicit?: boolean\n): void;\nexport function initializePingops(\n config: { configFile: string },\n explicit?: boolean\n): void;\nexport function initializePingops(\n config:\n | PingopsProcessorConfig\n | string\n | {\n configFile: string;\n },\n explicit: boolean = true\n): void {\n void explicit; // Ignored: SDK always uses global instrumentation\n const resolvedConfig: PingopsProcessorConfig =\n typeof config === \"string\"\n ? resolveConfigFromFile(config)\n : \"configFile\" in config\n ? resolveConfigFromFile(config.configFile)\n : config;\n\n if (isSdkInitializedFlag) {\n if (resolvedConfig.debug) {\n initLogger.warn(\"[PingOps] SDK already initialized, skipping\");\n }\n return;\n }\n\n // Create resource with service name\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: resolvedConfig.serviceName,\n });\n\n const processor = new PingopsSpanProcessor({\n ...resolvedConfig,\n sdkVersion: SDK_VERSION,\n });\n const instrumentations = getInstrumentations();\n\n // Node.js SDK\n const nodeSdk = new NodeSDK({\n resource,\n spanProcessors: [processor],\n instrumentations,\n });\n\n nodeSdk.start();\n sdkInstance = nodeSdk;\n\n // Mark SDK as initialized\n isSdkInitializedFlag = true;\n\n setSdkInitialized(true);\n\n // Initialize isolated TracerProvider for manual spans AFTER NodeSDK starts\n // This ensures manual spans created via startSpan are processed by the same processor\n // We register it after NodeSDK so it takes precedence as the global provider\n try {\n // In version 2.2.0, span processors are passed in the constructor\n const isolatedProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [processor],\n });\n\n // Register the provider globally\n isolatedProvider.register();\n\n // Set it in global state\n setPingopsTracerProvider(isolatedProvider);\n } catch (error) {\n if (resolvedConfig.debug) {\n initLogger.error(\n \"[PingOps] Failed to create isolated TracerProvider:\",\n error instanceof Error ? error.message : String(error)\n );\n }\n // Continue without isolated provider - manual spans will use global provider\n }\n\n if (resolvedConfig.debug) {\n initLogger.info(\"[PingOps] SDK initialized\");\n }\n}\n\nfunction resolveConfigFromFile(configFilePath: string): PingopsProcessorConfig {\n const fileConfig = loadConfigFromFile(configFilePath);\n const mergedConfig = mergeConfigWithEnv(fileConfig);\n\n if (!mergedConfig.baseUrl || !mergedConfig.serviceName) {\n const missing = [\n !mergedConfig.baseUrl && \"baseUrl (or PINGOPS_BASE_URL)\",\n !mergedConfig.serviceName && \"serviceName (or PINGOPS_SERVICE_NAME)\",\n ].filter(Boolean);\n\n throw new Error(\n `initializePingops(configFile) requires ${missing.join(\" and \")}. ` +\n `Provide them in the config file or via environment variables.`\n );\n }\n\n return mergedConfig as PingopsProcessorConfig;\n}\n\n/**\n * Shuts down the SDK and flushes remaining spans\n */\nexport async function shutdownPingops(): Promise<void> {\n // Shutdown isolated TracerProvider first\n await shutdownTracerProvider();\n\n if (!sdkInstance) {\n return;\n }\n\n await sdkInstance.shutdown();\n sdkInstance = null;\n isSdkInitializedFlag = false;\n setSdkInitialized(false);\n}\n\n/**\n * Checks if the SDK is already initialized by checking if a NodeTracerProvider is available\n */\nfunction isSdkInitialized(): boolean {\n try {\n const provider = getPingopsTracerProvider();\n // If we have a NodeTracerProvider (not the default NoOpTracerProvider), SDK is initialized\n const initialized = provider instanceof NodeTracerProvider;\n logger.debug(\"Checked SDK initialization status\", {\n initialized,\n providerType: provider.constructor.name,\n });\n return initialized;\n } catch (error) {\n logger.debug(\"Error checking SDK initialization status\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Auto-initializes the SDK from environment variables if not already initialized\n */\nasync function ensureInitialized(): Promise<void> {\n // Check if SDK is already initialized (e.g., by calling initializePingops directly)\n if (isSdkInitialized()) {\n logger.debug(\"SDK already initialized, skipping auto-initialization\");\n isInitialized = true;\n return;\n }\n\n if (isInitialized) {\n logger.debug(\"SDK initialization flag already set, skipping\");\n return;\n }\n\n // If initialization is in progress, wait for it\n if (initializationPromise) {\n logger.debug(\"SDK initialization already in progress, waiting...\");\n return initializationPromise;\n }\n\n // Start initialization\n logger.info(\"Starting SDK auto-initialization from environment variables\");\n initializationPromise = Promise.resolve().then(() => {\n const apiKey = process.env.PINGOPS_API_KEY;\n const baseUrl = process.env.PINGOPS_BASE_URL;\n const serviceName = process.env.PINGOPS_SERVICE_NAME;\n const debug = process.env.PINGOPS_DEBUG === \"true\";\n\n logger.debug(\"Reading environment variables\", {\n hasApiKey: !!apiKey,\n hasBaseUrl: !!baseUrl,\n hasServiceName: !!serviceName,\n debug,\n });\n\n if (!apiKey || !baseUrl || !serviceName) {\n const missing = [\n !apiKey && \"PINGOPS_API_KEY\",\n !baseUrl && \"PINGOPS_BASE_URL\",\n !serviceName && \"PINGOPS_SERVICE_NAME\",\n ].filter(Boolean);\n\n logger.error(\n \"Missing required environment variables for auto-initialization\",\n {\n missing,\n }\n );\n\n throw new Error(\n `PingOps SDK auto-initialization requires PINGOPS_API_KEY, PINGOPS_BASE_URL, and PINGOPS_SERVICE_NAME environment variables. Missing: ${missing.join(\", \")}`\n );\n }\n\n const config: PingopsProcessorConfig = {\n apiKey,\n baseUrl,\n serviceName,\n debug,\n };\n\n logger.info(\"Initializing SDK with config\", {\n baseUrl,\n serviceName,\n debug,\n });\n\n // Call initializePingops with explicit=false since this is auto-initialization\n initializePingops(config, false);\n isInitialized = true;\n\n logger.info(\"SDK auto-initialization completed successfully\");\n });\n\n try {\n await initializationPromise;\n } catch (error) {\n logger.error(\"SDK auto-initialization failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n initializationPromise = null;\n }\n}\n\n/**\n * Returns the trace ID of the currently active span, if any.\n */\nexport function getActiveTraceId(): string | undefined {\n return trace.getActiveSpan()?.spanContext().traceId;\n}\n\n/**\n * Returns the span ID of the currently active span, if any.\n */\nexport function getActiveSpanId(): string | undefined {\n return trace.getActiveSpan()?.spanContext().spanId;\n}\n\n/**\n * Runs the callback in an intentionally tracing-suppressed context.\n *\n * Any spans started in this callback (including auto-instrumented outbound HTTP/fetch spans)\n * are intentionally dropped and not exported.\n */\nexport function suppressInstrumentation<T>(fn: () => T): T;\nexport function suppressInstrumentation<T>(fn: () => Promise<T>): Promise<T>;\nexport function suppressInstrumentation<T>(\n fn: () => T | Promise<T>\n): T | Promise<T> {\n const untrackedContext = suppressTracing(context.active()).setValue(\n PINGOPS_INTENTIONAL_SUPPRESSION,\n true\n );\n return context.with(untrackedContext, fn);\n}\n\n/**\n * Starts a new trace using the PingOps tracer provider and runs the callback within that trace.\n * Sets attributes (traceId, userId, sessionId, tags, metadata, etc.) in context so they are\n * propagated to spans created within the callback.\n *\n * @param options - Options including optional attributes and optional seed for deterministic traceId\n * @param fn - Function to execute within the trace and attribute context\n * @returns Promise resolving to the result of the function\n *\n * @example\n * ```typescript\n * import { startTrace, initializePingops } from '@pingops/sdk';\n *\n * initializePingops({ ... });\n *\n * const result = await startTrace({\n * attributes: {\n * userId: 'user-123',\n * sessionId: 'session-456',\n * tags: ['production', 'api'],\n * metadata: { environment: 'prod', version: '1.0.0' }\n * },\n * seed: 'request-123' // optional: deterministic traceId from this seed\n * }, async () => {\n * const response = await fetch('https://api.example.com/users/123');\n * return response.json();\n * });\n * ```\n */\nexport async function startTrace<T>(\n options: {\n attributes?: PingopsTraceAttributes;\n seed?: string;\n },\n fn: () => T | Promise<T>\n): Promise<T> {\n if (!isSdkInitialized()) {\n await ensureInitialized();\n }\n\n const traceId =\n options.attributes?.traceId ?? (await createTraceId(options?.seed));\n const parentSpanId = uint8ArrayToHex(\n crypto.getRandomValues(new Uint8Array(8))\n );\n\n const spanContext = {\n traceId,\n spanId: parentSpanId,\n traceFlags: TRACE_FLAG_SAMPLED,\n };\n\n const traceExecutionBaseContext = getUnsuppressedContext();\n if (traceExecutionBaseContext === ROOT_CONTEXT) {\n if (!hasLoggedSuppressedStartTraceWarning) {\n logger.warn(\n \"startTrace detected a suppressed active context and is running on ROOT_CONTEXT to prevent suppression leakage into user outbound instrumentation\"\n );\n hasLoggedSuppressedStartTraceWarning = true;\n } else {\n logger.debug(\n \"startTrace received a suppressed active context; running trace on ROOT_CONTEXT\"\n );\n }\n }\n const runWithAttributes = (): T | Promise<T> => {\n let contextWithAttributes = context.active();\n const attrs = options.attributes;\n if (attrs) {\n contextWithAttributes = setAttributesInContext(\n contextWithAttributes,\n attrs\n );\n }\n contextWithAttributes = contextWithAttributes.setValue(\n PINGOPS_TRACE_ID,\n traceId\n );\n return context.with(contextWithAttributes, fn);\n };\n\n return new Promise((resolve, reject) => {\n const nonRecordingParent = trace.wrapSpanContext(spanContext);\n const contextWithParentSpan = trace.setSpan(\n traceExecutionBaseContext,\n nonRecordingParent\n );\n const contextWithTrace = trace.setSpanContext(\n contextWithParentSpan,\n spanContext\n );\n try {\n const result = context.with(contextWithTrace, runWithAttributes);\n if (result instanceof Promise) {\n result\n .then((v) => resolve(v))\n .catch((err) =>\n reject(err instanceof Error ? err : new Error(String(err)))\n );\n } else {\n resolve(result);\n }\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n });\n}\n\nfunction getUnsuppressedContext(): ReturnType<typeof context.active> {\n const activeContext = context.active();\n if (activeContext.getValue(PINGOPS_INTENTIONAL_SUPPRESSION) === true) {\n return activeContext;\n }\n return isTracingSuppressed(activeContext) ? ROOT_CONTEXT : activeContext;\n}\n\nfunction setAttributesInContext(\n ctx: ReturnType<typeof context.active>,\n attrs: PingopsTraceAttributes\n): ReturnType<typeof context.active> {\n if (attrs.userId !== undefined) {\n ctx = ctx.setValue(PINGOPS_USER_ID, attrs.userId);\n }\n if (attrs.sessionId !== undefined) {\n ctx = ctx.setValue(PINGOPS_SESSION_ID, attrs.sessionId);\n }\n if (attrs.tags !== undefined) {\n ctx = ctx.setValue(PINGOPS_TAGS, attrs.tags);\n }\n if (attrs.metadata !== undefined) {\n ctx = ctx.setValue(PINGOPS_METADATA, attrs.metadata);\n }\n if (attrs.captureRequestBody !== undefined) {\n ctx = ctx.setValue(PINGOPS_CAPTURE_REQUEST_BODY, attrs.captureRequestBody);\n }\n if (attrs.captureResponseBody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,WAAS,WAAW;EACtC,MAAM,qBAAqBD,yBAAM,gBAAgB,YAAY;EAC7D,MAAM,wBAAwBA,yBAAM,QAClC,2BACA,mBACD;EACD,MAAM,mBAAmBA,yBAAM,eAC7B,uBACA,YACD;AACD,MAAI;GACF,MAAM,SAASC,2BAAQ,KAAK,kBAAkB,kBAAkB;AAChE,OAAI,kBAAkB,QACpB,QACG,MAAM,MAAMI,UAAQ,EAAE,CAAC,CACvB,OAAO,QACN,OAAO,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,IAAI,CAAC,CAAC,CAC5D;OAEH,WAAQ,OAAO;WAEV,KAAK;AACZ,UAAO,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,IAAI,CAAC,CAAC;;GAE7D;;AAGJ,SAAS,yBAA4D;CACnE,MAAM,gBAAgBJ,2BAAQ,QAAQ;AACtC,KAAI,cAAc,SAASC,8CAAgC,KAAK,KAC9D,QAAO;AAET,qDAA2B,cAAc,GAAGC,kCAAe;;AAG7D,SAAS,uBACP,KACA,OACmC;AACnC,KAAI,MAAM,WAAW,OACnB,OAAM,IAAI,SAASG,+BAAiB,MAAM,OAAO;AAEnD,KAAI,MAAM,cAAc,OACtB,OAAM,IAAI,SAASC,kCAAoB,MAAM,UAAU;AAEzD,KAAI,MAAM,SAAS,OACjB,OAAM,IAAI,SAASC,4BAAc,MAAM,KAAK;AAE9C,KAAI,MAAM,aAAa,OACrB,OAAM,IAAI,SAASC,gCAAkB,MAAM,SAAS;AAEtD,KAAI,MAAM,uBAAuB,OAC/B,OAAM,IAAI,SAASC,4CAA8B,MAAM,mBAAmB;AAE5E,KAAI,MAAM,wBAAwB,OAChC,OAAM,IAAI,SACRC,6CACA,MAAM,oBACP;AAEH,QAAO"}
|
|
@@ -72,7 +72,7 @@ function setSdkInitialized(initialized) {
|
|
|
72
72
|
|
|
73
73
|
//#endregion
|
|
74
74
|
//#region package.json
|
|
75
|
-
var version = "0.
|
|
75
|
+
var version = "0.4.0";
|
|
76
76
|
|
|
77
77
|
//#endregion
|
|
78
78
|
//#region src/sdk-version.ts
|
|
@@ -241,7 +241,7 @@ function getActiveTraceId() {
|
|
|
241
241
|
function getActiveSpanId() {
|
|
242
242
|
return trace.getActiveSpan()?.spanContext().spanId;
|
|
243
243
|
}
|
|
244
|
-
function
|
|
244
|
+
function suppressInstrumentation(fn) {
|
|
245
245
|
const untrackedContext = suppressTracing(context.active()).setValue(PINGOPS_INTENTIONAL_SUPPRESSION, true);
|
|
246
246
|
return context.with(untrackedContext, fn);
|
|
247
247
|
}
|
|
@@ -287,33 +287,24 @@ async function startTrace(options, fn) {
|
|
|
287
287
|
logger.warn("startTrace detected a suppressed active context and is running on ROOT_CONTEXT to prevent suppression leakage into user outbound instrumentation");
|
|
288
288
|
hasLoggedSuppressedStartTraceWarning = true;
|
|
289
289
|
} else logger.debug("startTrace received a suppressed active context; running trace on ROOT_CONTEXT");
|
|
290
|
-
const
|
|
291
|
-
|
|
290
|
+
const runWithAttributes = () => {
|
|
291
|
+
let contextWithAttributes = context.active();
|
|
292
|
+
const attrs = options.attributes;
|
|
293
|
+
if (attrs) contextWithAttributes = setAttributesInContext(contextWithAttributes, attrs);
|
|
294
|
+
contextWithAttributes = contextWithAttributes.setValue(PINGOPS_TRACE_ID, traceId);
|
|
295
|
+
return context.with(contextWithAttributes, fn);
|
|
296
|
+
};
|
|
292
297
|
return new Promise((resolve$1, reject) => {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
resolve$1(v);
|
|
304
|
-
}).catch((err) => {
|
|
305
|
-
span.end();
|
|
306
|
-
reject(err instanceof Error ? err : new Error(String(err)));
|
|
307
|
-
});
|
|
308
|
-
else {
|
|
309
|
-
span.end();
|
|
310
|
-
resolve$1(result);
|
|
311
|
-
}
|
|
312
|
-
} catch (err) {
|
|
313
|
-
span.end();
|
|
314
|
-
reject(err instanceof Error ? err : new Error(String(err)));
|
|
315
|
-
}
|
|
316
|
-
});
|
|
298
|
+
const nonRecordingParent = trace.wrapSpanContext(spanContext);
|
|
299
|
+
const contextWithParentSpan = trace.setSpan(traceExecutionBaseContext, nonRecordingParent);
|
|
300
|
+
const contextWithTrace = trace.setSpanContext(contextWithParentSpan, spanContext);
|
|
301
|
+
try {
|
|
302
|
+
const result = context.with(contextWithTrace, runWithAttributes);
|
|
303
|
+
if (result instanceof Promise) result.then((v) => resolve$1(v)).catch((err) => reject(err instanceof Error ? err : new Error(String(err))));
|
|
304
|
+
else resolve$1(result);
|
|
305
|
+
} catch (err) {
|
|
306
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
307
|
+
}
|
|
317
308
|
});
|
|
318
309
|
}
|
|
319
310
|
function getUnsuppressedContext() {
|
|
@@ -332,5 +323,5 @@ function setAttributesInContext(ctx, attrs) {
|
|
|
332
323
|
}
|
|
333
324
|
|
|
334
325
|
//#endregion
|
|
335
|
-
export { startTrace as a, mergeConfigWithEnv as c, shutdownPingops as i, getActiveTraceId as n,
|
|
336
|
-
//# sourceMappingURL=pingops-
|
|
326
|
+
export { startTrace as a, mergeConfigWithEnv as c, shutdownPingops as i, getActiveTraceId as n, suppressInstrumentation as o, initializePingops as r, loadConfigFromFile as s, getActiveSpanId as t };
|
|
327
|
+
//# sourceMappingURL=pingops-DDeCBa2d.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pingops-DDeCBa2d.mjs","names":["loadYaml","isSdkInitializedFlag","(sdkPackageJson as PackageJsonWithVersion).version","resolve"],"sources":["../src/config-loader.ts","../src/init-state.ts","../package.json","../src/sdk-version.ts","../src/pingops.ts"],"sourcesContent":["/**\n * Configuration loader for reading PingOps config from JSON/YAML files\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { load as loadYaml } from \"js-yaml\";\nimport type { PingopsProcessorConfig } from \"@pingops/otel\";\n\n/**\n * Loads configuration from a JSON or YAML file\n *\n * @param filePath - Path to the config file (JSON or YAML)\n * @returns Parsed configuration object\n * @throws Error if file cannot be read or parsed\n */\nexport function loadConfigFromFile(\n filePath: string\n): Partial<PingopsProcessorConfig> {\n const resolvedPath = resolve(filePath);\n const fileContent = readFileSync(resolvedPath, \"utf-8\");\n\n const ext = resolvedPath.toLowerCase();\n if (ext.endsWith(\".yaml\") || ext.endsWith(\".yml\")) {\n return (loadYaml(fileContent) as Partial<PingopsProcessorConfig>) || {};\n } else if (ext.endsWith(\".json\")) {\n return JSON.parse(fileContent) as Partial<PingopsProcessorConfig>;\n } else {\n // Try to parse as JSON first, then YAML\n try {\n return JSON.parse(fileContent) as Partial<PingopsProcessorConfig>;\n } catch {\n return (loadYaml(fileContent) as Partial<PingopsProcessorConfig>) || {};\n }\n }\n}\n\n/**\n * Merges configuration from file and environment variables.\n * Environment variables take precedence over file config.\n *\n * @param fileConfig - Configuration loaded from file\n * @returns Merged configuration with env vars taking precedence\n */\nexport function mergeConfigWithEnv(\n fileConfig: Partial<PingopsProcessorConfig>\n): Partial<PingopsProcessorConfig> {\n const envConfig: Partial<PingopsProcessorConfig> = {};\n\n // Read from environment variables\n if (process.env.PINGOPS_API_KEY) {\n envConfig.apiKey = process.env.PINGOPS_API_KEY;\n }\n if (process.env.PINGOPS_BASE_URL) {\n envConfig.baseUrl = process.env.PINGOPS_BASE_URL;\n }\n if (process.env.PINGOPS_SERVICE_NAME) {\n envConfig.serviceName = process.env.PINGOPS_SERVICE_NAME;\n }\n if (process.env.PINGOPS_DEBUG) {\n envConfig.debug = process.env.PINGOPS_DEBUG === \"true\";\n }\n if (process.env.PINGOPS_BATCH_SIZE) {\n envConfig.batchSize = parseInt(process.env.PINGOPS_BATCH_SIZE, 10);\n }\n if (process.env.PINGOPS_BATCH_TIMEOUT) {\n envConfig.batchTimeout = parseInt(process.env.PINGOPS_BATCH_TIMEOUT, 10);\n }\n if (process.env.PINGOPS_EXPORT_MODE) {\n envConfig.exportMode = process.env.PINGOPS_EXPORT_MODE as\n | \"batched\"\n | \"immediate\";\n }\n\n // Merge: env vars override file config\n return {\n ...fileConfig,\n ...envConfig,\n };\n}\n","/**\n * Shared state for tracking SDK initialization\n * This module exists to avoid circular dependencies between pingops.ts and instrumentation.ts\n */\n\nlet isSdkInitializedFlag = false;\n\n/**\n * Returns whether the SDK has been initialized.\n */\nexport function isSdkInitialized(): boolean {\n return isSdkInitializedFlag;\n}\n\n/**\n * Sets the SDK initialization flag.\n * Called by initializePingops when the SDK is initialized.\n */\nexport function setSdkInitialized(initialized: boolean): void {\n isSdkInitializedFlag = initialized;\n}\n","","import sdkPackageJson from \"../package.json\";\n\ntype PackageJsonWithVersion = {\n version?: string;\n};\n\nconst packageVersion = (sdkPackageJson as PackageJsonWithVersion).version;\n\nexport const SDK_VERSION =\n typeof packageVersion === \"string\" ? packageVersion : \"unknown\";\n","/**\n * PingOps SDK singleton for manual instrumentation\n *\n * Provides initializePingops, shutdownPingops, startTrace, getActiveTraceId,\n * and getActiveSpanId. startTrace can auto-initialize from environment variables if needed.\n */\n\nimport { ROOT_CONTEXT, context, trace } from \"@opentelemetry/api\";\nimport { isTracingSuppressed, suppressTracing } from \"@opentelemetry/core\";\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport { ATTR_SERVICE_NAME } from \"@opentelemetry/semantic-conventions\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\nimport type { PingopsProcessorConfig } from \"@pingops/otel\";\nimport {\n setPingopsTracerProvider,\n shutdownTracerProvider,\n PingopsSpanProcessor,\n} from \"@pingops/otel\";\nimport {\n createLogger,\n createTraceId,\n uint8ArrayToHex,\n type PingopsTraceAttributes,\n} from \"@pingops/core\";\nimport {\n PINGOPS_TRACE_ID,\n PINGOPS_USER_ID,\n PINGOPS_SESSION_ID,\n PINGOPS_TAGS,\n PINGOPS_METADATA,\n PINGOPS_CAPTURE_REQUEST_BODY,\n PINGOPS_CAPTURE_RESPONSE_BODY,\n PINGOPS_INTENTIONAL_SUPPRESSION,\n} from \"@pingops/core\";\nimport { loadConfigFromFile, mergeConfigWithEnv } from \"./config-loader\";\nimport { setSdkInitialized } from \"./init-state\";\nimport { getPingopsTracerProvider } from \"@pingops/otel\";\nimport { getInstrumentations } from \"@pingops/otel\";\nimport { SDK_VERSION } from \"./sdk-version\";\n\nconst TRACE_FLAG_SAMPLED = 1;\n\nconst initLogger = createLogger(\"[PingOps Initialize]\");\nconst logger = createLogger(\"[PingOps Pingops]\");\n\nlet sdkInstance: NodeSDK | null = null;\nlet isSdkInitializedFlag = false;\n\n/**\n * Global state to track initialization\n */\nlet isInitialized = false;\nlet initializationPromise: Promise<void> | null = null;\nlet hasLoggedSuppressedStartTraceWarning = false;\n\n/**\n * Initializes PingOps SDK\n *\n * This function:\n * 1. Creates an OpenTelemetry NodeSDK instance\n * 2. Configures Resource with service.name\n * 3. Registers PingopsSpanProcessor\n * 4. Enables HTTP/fetch/GenAI instrumentation\n * 5. Starts the SDK\n *\n * @param config - Configuration object, config file path, or config file wrapper\n * @param explicit - Whether this is an explicit call (default: true).\n * Set to false when called internally by startTrace auto-initialization.\n */\nexport function initializePingops(\n config: PingopsProcessorConfig,\n explicit?: boolean\n): void;\nexport function initializePingops(\n configFilePath: string,\n explicit?: boolean\n): void;\nexport function initializePingops(\n config: { configFile: string },\n explicit?: boolean\n): void;\nexport function initializePingops(\n config:\n | PingopsProcessorConfig\n | string\n | {\n configFile: string;\n },\n explicit: boolean = true\n): void {\n void explicit; // Ignored: SDK always uses global instrumentation\n const resolvedConfig: PingopsProcessorConfig =\n typeof config === \"string\"\n ? resolveConfigFromFile(config)\n : \"configFile\" in config\n ? resolveConfigFromFile(config.configFile)\n : config;\n\n if (isSdkInitializedFlag) {\n if (resolvedConfig.debug) {\n initLogger.warn(\"[PingOps] SDK already initialized, skipping\");\n }\n return;\n }\n\n // Create resource with service name\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: resolvedConfig.serviceName,\n });\n\n const processor = new PingopsSpanProcessor({\n ...resolvedConfig,\n sdkVersion: SDK_VERSION,\n });\n const instrumentations = getInstrumentations();\n\n // Node.js SDK\n const nodeSdk = new NodeSDK({\n resource,\n spanProcessors: [processor],\n instrumentations,\n });\n\n nodeSdk.start();\n sdkInstance = nodeSdk;\n\n // Mark SDK as initialized\n isSdkInitializedFlag = true;\n\n setSdkInitialized(true);\n\n // Initialize isolated TracerProvider for manual spans AFTER NodeSDK starts\n // This ensures manual spans created via startSpan are processed by the same processor\n // We register it after NodeSDK so it takes precedence as the global provider\n try {\n // In version 2.2.0, span processors are passed in the constructor\n const isolatedProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [processor],\n });\n\n // Register the provider globally\n isolatedProvider.register();\n\n // Set it in global state\n setPingopsTracerProvider(isolatedProvider);\n } catch (error) {\n if (resolvedConfig.debug) {\n initLogger.error(\n \"[PingOps] Failed to create isolated TracerProvider:\",\n error instanceof Error ? error.message : String(error)\n );\n }\n // Continue without isolated provider - manual spans will use global provider\n }\n\n if (resolvedConfig.debug) {\n initLogger.info(\"[PingOps] SDK initialized\");\n }\n}\n\nfunction resolveConfigFromFile(configFilePath: string): PingopsProcessorConfig {\n const fileConfig = loadConfigFromFile(configFilePath);\n const mergedConfig = mergeConfigWithEnv(fileConfig);\n\n if (!mergedConfig.baseUrl || !mergedConfig.serviceName) {\n const missing = [\n !mergedConfig.baseUrl && \"baseUrl (or PINGOPS_BASE_URL)\",\n !mergedConfig.serviceName && \"serviceName (or PINGOPS_SERVICE_NAME)\",\n ].filter(Boolean);\n\n throw new Error(\n `initializePingops(configFile) requires ${missing.join(\" and \")}. ` +\n `Provide them in the config file or via environment variables.`\n );\n }\n\n return mergedConfig as PingopsProcessorConfig;\n}\n\n/**\n * Shuts down the SDK and flushes remaining spans\n */\nexport async function shutdownPingops(): Promise<void> {\n // Shutdown isolated TracerProvider first\n await shutdownTracerProvider();\n\n if (!sdkInstance) {\n return;\n }\n\n await sdkInstance.shutdown();\n sdkInstance = null;\n isSdkInitializedFlag = false;\n setSdkInitialized(false);\n}\n\n/**\n * Checks if the SDK is already initialized by checking if a NodeTracerProvider is available\n */\nfunction isSdkInitialized(): boolean {\n try {\n const provider = getPingopsTracerProvider();\n // If we have a NodeTracerProvider (not the default NoOpTracerProvider), SDK is initialized\n const initialized = provider instanceof NodeTracerProvider;\n logger.debug(\"Checked SDK initialization status\", {\n initialized,\n providerType: provider.constructor.name,\n });\n return initialized;\n } catch (error) {\n logger.debug(\"Error checking SDK initialization status\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Auto-initializes the SDK from environment variables if not already initialized\n */\nasync function ensureInitialized(): Promise<void> {\n // Check if SDK is already initialized (e.g., by calling initializePingops directly)\n if (isSdkInitialized()) {\n logger.debug(\"SDK already initialized, skipping auto-initialization\");\n isInitialized = true;\n return;\n }\n\n if (isInitialized) {\n logger.debug(\"SDK initialization flag already set, skipping\");\n return;\n }\n\n // If initialization is in progress, wait for it\n if (initializationPromise) {\n logger.debug(\"SDK initialization already in progress, waiting...\");\n return initializationPromise;\n }\n\n // Start initialization\n logger.info(\"Starting SDK auto-initialization from environment variables\");\n initializationPromise = Promise.resolve().then(() => {\n const apiKey = process.env.PINGOPS_API_KEY;\n const baseUrl = process.env.PINGOPS_BASE_URL;\n const serviceName = process.env.PINGOPS_SERVICE_NAME;\n const debug = process.env.PINGOPS_DEBUG === \"true\";\n\n logger.debug(\"Reading environment variables\", {\n hasApiKey: !!apiKey,\n hasBaseUrl: !!baseUrl,\n hasServiceName: !!serviceName,\n debug,\n });\n\n if (!apiKey || !baseUrl || !serviceName) {\n const missing = [\n !apiKey && \"PINGOPS_API_KEY\",\n !baseUrl && \"PINGOPS_BASE_URL\",\n !serviceName && \"PINGOPS_SERVICE_NAME\",\n ].filter(Boolean);\n\n logger.error(\n \"Missing required environment variables for auto-initialization\",\n {\n missing,\n }\n );\n\n throw new Error(\n `PingOps SDK auto-initialization requires PINGOPS_API_KEY, PINGOPS_BASE_URL, and PINGOPS_SERVICE_NAME environment variables. Missing: ${missing.join(\", \")}`\n );\n }\n\n const config: PingopsProcessorConfig = {\n apiKey,\n baseUrl,\n serviceName,\n debug,\n };\n\n logger.info(\"Initializing SDK with config\", {\n baseUrl,\n serviceName,\n debug,\n });\n\n // Call initializePingops with explicit=false since this is auto-initialization\n initializePingops(config, false);\n isInitialized = true;\n\n logger.info(\"SDK auto-initialization completed successfully\");\n });\n\n try {\n await initializationPromise;\n } catch (error) {\n logger.error(\"SDK auto-initialization failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n initializationPromise = null;\n }\n}\n\n/**\n * Returns the trace ID of the currently active span, if any.\n */\nexport function getActiveTraceId(): string | undefined {\n return trace.getActiveSpan()?.spanContext().traceId;\n}\n\n/**\n * Returns the span ID of the currently active span, if any.\n */\nexport function getActiveSpanId(): string | undefined {\n return trace.getActiveSpan()?.spanContext().spanId;\n}\n\n/**\n * Runs the callback in an intentionally tracing-suppressed context.\n *\n * Any spans started in this callback (including auto-instrumented outbound HTTP/fetch spans)\n * are intentionally dropped and not exported.\n */\nexport function suppressInstrumentation<T>(fn: () => T): T;\nexport function suppressInstrumentation<T>(fn: () => Promise<T>): Promise<T>;\nexport function suppressInstrumentation<T>(\n fn: () => T | Promise<T>\n): T | Promise<T> {\n const untrackedContext = suppressTracing(context.active()).setValue(\n PINGOPS_INTENTIONAL_SUPPRESSION,\n true\n );\n return context.with(untrackedContext, fn);\n}\n\n/**\n * Starts a new trace using the PingOps tracer provider and runs the callback within that trace.\n * Sets attributes (traceId, userId, sessionId, tags, metadata, etc.) in context so they are\n * propagated to spans created within the callback.\n *\n * @param options - Options including optional attributes and optional seed for deterministic traceId\n * @param fn - Function to execute within the trace and attribute context\n * @returns Promise resolving to the result of the function\n *\n * @example\n * ```typescript\n * import { startTrace, initializePingops } from '@pingops/sdk';\n *\n * initializePingops({ ... });\n *\n * const result = await startTrace({\n * attributes: {\n * userId: 'user-123',\n * sessionId: 'session-456',\n * tags: ['production', 'api'],\n * metadata: { environment: 'prod', version: '1.0.0' }\n * },\n * seed: 'request-123' // optional: deterministic traceId from this seed\n * }, async () => {\n * const response = await fetch('https://api.example.com/users/123');\n * return response.json();\n * });\n * ```\n */\nexport async function startTrace<T>(\n options: {\n attributes?: PingopsTraceAttributes;\n seed?: string;\n },\n fn: () => T | Promise<T>\n): Promise<T> {\n if (!isSdkInitialized()) {\n await ensureInitialized();\n }\n\n const traceId =\n options.attributes?.traceId ?? (await createTraceId(options?.seed));\n const parentSpanId = uint8ArrayToHex(\n crypto.getRandomValues(new Uint8Array(8))\n );\n\n const spanContext = {\n traceId,\n spanId: parentSpanId,\n traceFlags: TRACE_FLAG_SAMPLED,\n };\n\n const traceExecutionBaseContext = getUnsuppressedContext();\n if (traceExecutionBaseContext === ROOT_CONTEXT) {\n if (!hasLoggedSuppressedStartTraceWarning) {\n logger.warn(\n \"startTrace detected a suppressed active context and is running on ROOT_CONTEXT to prevent suppression leakage into user outbound instrumentation\"\n );\n hasLoggedSuppressedStartTraceWarning = true;\n } else {\n logger.debug(\n \"startTrace received a suppressed active context; running trace on ROOT_CONTEXT\"\n );\n }\n }\n const runWithAttributes = (): T | Promise<T> => {\n let contextWithAttributes = context.active();\n const attrs = options.attributes;\n if (attrs) {\n contextWithAttributes = setAttributesInContext(\n contextWithAttributes,\n attrs\n );\n }\n contextWithAttributes = contextWithAttributes.setValue(\n PINGOPS_TRACE_ID,\n traceId\n );\n return context.with(contextWithAttributes, fn);\n };\n\n return new Promise((resolve, reject) => {\n const nonRecordingParent = trace.wrapSpanContext(spanContext);\n const contextWithParentSpan = trace.setSpan(\n traceExecutionBaseContext,\n nonRecordingParent\n );\n const contextWithTrace = trace.setSpanContext(\n contextWithParentSpan,\n spanContext\n );\n try {\n const result = context.with(contextWithTrace, runWithAttributes);\n if (result instanceof Promise) {\n result\n .then((v) => resolve(v))\n .catch((err) =>\n reject(err instanceof Error ? err : new Error(String(err)))\n );\n } else {\n resolve(result);\n }\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n });\n}\n\nfunction getUnsuppressedContext(): ReturnType<typeof context.active> {\n const activeContext = context.active();\n if (activeContext.getValue(PINGOPS_INTENTIONAL_SUPPRESSION) === true) {\n return activeContext;\n }\n return isTracingSuppressed(activeContext) ? ROOT_CONTEXT : activeContext;\n}\n\nfunction setAttributesInContext(\n ctx: ReturnType<typeof context.active>,\n attrs: PingopsTraceAttributes\n): ReturnType<typeof context.active> {\n if (attrs.userId !== undefined) {\n ctx = ctx.setValue(PINGOPS_USER_ID, attrs.userId);\n }\n if (attrs.sessionId !== undefined) {\n ctx = ctx.setValue(PINGOPS_SESSION_ID, attrs.sessionId);\n }\n if (attrs.tags !== undefined) {\n ctx = ctx.setValue(PINGOPS_TAGS, attrs.tags);\n }\n if (attrs.metadata !== undefined) {\n ctx = ctx.setValue(PINGOPS_METADATA, attrs.metadata);\n }\n if (attrs.captureRequestBody !== undefined) {\n ctx = ctx.setValue(PINGOPS_CAPTURE_REQUEST_BODY, attrs.captureRequestBody);\n }\n if (attrs.captureResponseBody !== undefined) {\n ctx = ctx.setValue(\n PINGOPS_CAPTURE_RESPONSE_BODY,\n attrs.captureResponseBody\n );\n }\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,mBACd,UACiC;CACjC,MAAM,eAAe,QAAQ,SAAS;CACtC,MAAM,cAAc,aAAa,cAAc,QAAQ;CAEvD,MAAM,MAAM,aAAa,aAAa;AACtC,KAAI,IAAI,SAAS,QAAQ,IAAI,IAAI,SAAS,OAAO,CAC/C,QAAQA,KAAS,YAAY,IAAwC,EAAE;UAC9D,IAAI,SAAS,QAAQ,CAC9B,QAAO,KAAK,MAAM,YAAY;KAG9B,KAAI;AACF,SAAO,KAAK,MAAM,YAAY;SACxB;AACN,SAAQA,KAAS,YAAY,IA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C,CAAC;;GAE7D;;AAGJ,SAAS,yBAA4D;CACnE,MAAM,gBAAgB,QAAQ,QAAQ;AACtC,KAAI,cAAc,SAAS,gCAAgC,KAAK,KAC9D,QAAO;AAET,QAAO,oBAAoB,cAAc,GAAG,eAAe;;AAG7D,SAAS,uBACP,KACA,OACmC;AACnC,KAAI,MAAM,WAAW,OACnB,OAAM,IAAI,SAAS,iBAAiB,MAAM,OAAO;AAEnD,KAAI,MAAM,cAAc,OACtB,OAAM,IAAI,SAAS,oBAAoB,MAAM,UAAU;AAEzD,KAAI,MAAM,SAAS,OACjB,OAAM,IAAI,SAAS,cAAc,MAAM,KAAK;AAE9C,KAAI,MAAM,aAAa,OACrB,OAAM,IAAI,SAAS,kBAAkB,MAAM,SAAS;AAEtD,KAAI,MAAM,uBAAuB,OAC/B,OAAM,IAAI,SAAS,8BAA8B,MAAM,mBAAmB;AAE5E,KAAI,MAAM,wBAAwB,OAChC,OAAM,IAAI,SACR,+BACA,MAAM,oBACP;AAEH,QAAO"}
|
package/dist/register.cjs
CHANGED
package/dist/register.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pingops/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20"
|
|
@@ -45,8 +45,8 @@
|
|
|
45
45
|
"@opentelemetry/sdk-trace-node": "^2.2.0",
|
|
46
46
|
"@opentelemetry/semantic-conventions": "^1.38.0",
|
|
47
47
|
"js-yaml": "^4.1.0",
|
|
48
|
-
"@pingops/core": "^0.
|
|
49
|
-
"@pingops/otel": "^0.
|
|
48
|
+
"@pingops/core": "^0.4.0",
|
|
49
|
+
"@pingops/otel": "^0.4.0"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@types/js-yaml": "^4.0.9",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pingops-BzTLP70O.cjs","names":["isSdkInitializedFlag","(sdkPackageJson as PackageJsonWithVersion).version","ATTR_SERVICE_NAME","PingopsSpanProcessor","NodeSDK","NodeTracerProvider","trace","context","PINGOPS_INTENTIONAL_SUPPRESSION","ROOT_CONTEXT","PINGOPS_TRACE_ID","PINGOPS_USER_ID","PINGOPS_SESSION_ID","PINGOPS_TAGS","PINGOPS_METADATA","PINGOPS_CAPTURE_REQUEST_BODY","PINGOPS_CAPTURE_RESPONSE_BODY"],"sources":["../src/config-loader.ts","../src/init-state.ts","../package.json","../src/sdk-version.ts","../src/pingops.ts"],"sourcesContent":["/**\n * Configuration loader for reading PingOps config from JSON/YAML files\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { load as loadYaml } from \"js-yaml\";\nimport type { PingopsProcessorConfig } from \"@pingops/otel\";\n\n/**\n * Loads configuration from a JSON or YAML file\n *\n * @param filePath - Path to the config file (JSON or YAML)\n * @returns Parsed configuration object\n * @throws Error if file cannot be read or parsed\n */\nexport function loadConfigFromFile(\n filePath: string\n): Partial<PingopsProcessorConfig> {\n const resolvedPath = resolve(filePath);\n const fileContent = readFileSync(resolvedPath, \"utf-8\");\n\n const ext = resolvedPath.toLowerCase();\n if (ext.endsWith(\".yaml\") || ext.endsWith(\".yml\")) {\n return (loadYaml(fileContent) as Partial<PingopsProcessorConfig>) || {};\n } else if (ext.endsWith(\".json\")) {\n return JSON.parse(fileContent) as Partial<PingopsProcessorConfig>;\n } else {\n // Try to parse as JSON first, then YAML\n try {\n return JSON.parse(fileContent) as Partial<PingopsProcessorConfig>;\n } catch {\n return (loadYaml(fileContent) as Partial<PingopsProcessorConfig>) || {};\n }\n }\n}\n\n/**\n * Merges configuration from file and environment variables.\n * Environment variables take precedence over file config.\n *\n * @param fileConfig - Configuration loaded from file\n * @returns Merged configuration with env vars taking precedence\n */\nexport function mergeConfigWithEnv(\n fileConfig: Partial<PingopsProcessorConfig>\n): Partial<PingopsProcessorConfig> {\n const envConfig: Partial<PingopsProcessorConfig> = {};\n\n // Read from environment variables\n if (process.env.PINGOPS_API_KEY) {\n envConfig.apiKey = process.env.PINGOPS_API_KEY;\n }\n if (process.env.PINGOPS_BASE_URL) {\n envConfig.baseUrl = process.env.PINGOPS_BASE_URL;\n }\n if (process.env.PINGOPS_SERVICE_NAME) {\n envConfig.serviceName = process.env.PINGOPS_SERVICE_NAME;\n }\n if (process.env.PINGOPS_DEBUG) {\n envConfig.debug = process.env.PINGOPS_DEBUG === \"true\";\n }\n if (process.env.PINGOPS_BATCH_SIZE) {\n envConfig.batchSize = parseInt(process.env.PINGOPS_BATCH_SIZE, 10);\n }\n if (process.env.PINGOPS_BATCH_TIMEOUT) {\n envConfig.batchTimeout = parseInt(process.env.PINGOPS_BATCH_TIMEOUT, 10);\n }\n if (process.env.PINGOPS_EXPORT_MODE) {\n envConfig.exportMode = process.env.PINGOPS_EXPORT_MODE as\n | \"batched\"\n | \"immediate\";\n }\n\n // Merge: env vars override file config\n return {\n ...fileConfig,\n ...envConfig,\n };\n}\n","/**\n * Shared state for tracking SDK initialization\n * This module exists to avoid circular dependencies between pingops.ts and instrumentation.ts\n */\n\nlet isSdkInitializedFlag = false;\n\n/**\n * Returns whether the SDK has been initialized.\n */\nexport function isSdkInitialized(): boolean {\n return isSdkInitializedFlag;\n}\n\n/**\n * Sets the SDK initialization flag.\n * Called by initializePingops when the SDK is initialized.\n */\nexport function setSdkInitialized(initialized: boolean): void {\n isSdkInitializedFlag = initialized;\n}\n","","import sdkPackageJson from \"../package.json\";\n\ntype PackageJsonWithVersion = {\n version?: string;\n};\n\nconst packageVersion = (sdkPackageJson as PackageJsonWithVersion).version;\n\nexport const SDK_VERSION =\n typeof packageVersion === \"string\" ? packageVersion : \"unknown\";\n","/**\n * PingOps SDK singleton for manual instrumentation\n *\n * Provides initializePingops, shutdownPingops, startTrace, getActiveTraceId,\n * and getActiveSpanId. startTrace can auto-initialize from environment variables if needed.\n */\n\nimport { ROOT_CONTEXT, context, trace } from \"@opentelemetry/api\";\nimport { isTracingSuppressed, suppressTracing } from \"@opentelemetry/core\";\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport { ATTR_SERVICE_NAME } from \"@opentelemetry/semantic-conventions\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\nimport type { PingopsProcessorConfig } from \"@pingops/otel\";\nimport {\n setPingopsTracerProvider,\n shutdownTracerProvider,\n PingopsSpanProcessor,\n} from \"@pingops/otel\";\nimport {\n createLogger,\n createTraceId,\n uint8ArrayToHex,\n type PingopsTraceAttributes,\n} from \"@pingops/core\";\nimport {\n PINGOPS_TRACE_ID,\n PINGOPS_USER_ID,\n PINGOPS_SESSION_ID,\n PINGOPS_TAGS,\n PINGOPS_METADATA,\n PINGOPS_CAPTURE_REQUEST_BODY,\n PINGOPS_CAPTURE_RESPONSE_BODY,\n PINGOPS_INTENTIONAL_SUPPRESSION,\n} from \"@pingops/core\";\nimport { loadConfigFromFile, mergeConfigWithEnv } from \"./config-loader\";\nimport { setSdkInitialized } from \"./init-state\";\nimport { getPingopsTracerProvider } from \"@pingops/otel\";\nimport { getInstrumentations } from \"@pingops/otel\";\nimport { SDK_VERSION } from \"./sdk-version\";\n\nconst TRACE_FLAG_SAMPLED = 1;\n\nconst initLogger = createLogger(\"[PingOps Initialize]\");\nconst logger = createLogger(\"[PingOps Pingops]\");\n\nlet sdkInstance: NodeSDK | null = null;\nlet isSdkInitializedFlag = false;\n\n/**\n * Global state to track initialization\n */\nlet isInitialized = false;\nlet initializationPromise: Promise<void> | null = null;\nlet hasLoggedSuppressedStartTraceWarning = false;\n\n/**\n * Initializes PingOps SDK\n *\n * This function:\n * 1. Creates an OpenTelemetry NodeSDK instance\n * 2. Configures Resource with service.name\n * 3. Registers PingopsSpanProcessor\n * 4. Enables HTTP/fetch/GenAI instrumentation\n * 5. Starts the SDK\n *\n * @param config - Configuration object, config file path, or config file wrapper\n * @param explicit - Whether this is an explicit call (default: true).\n * Set to false when called internally by startTrace auto-initialization.\n */\nexport function initializePingops(\n config: PingopsProcessorConfig,\n explicit?: boolean\n): void;\nexport function initializePingops(\n configFilePath: string,\n explicit?: boolean\n): void;\nexport function initializePingops(\n config: { configFile: string },\n explicit?: boolean\n): void;\nexport function initializePingops(\n config:\n | PingopsProcessorConfig\n | string\n | {\n configFile: string;\n },\n explicit: boolean = true\n): void {\n void explicit; // Ignored: SDK always uses global instrumentation\n const resolvedConfig: PingopsProcessorConfig =\n typeof config === \"string\"\n ? resolveConfigFromFile(config)\n : \"configFile\" in config\n ? resolveConfigFromFile(config.configFile)\n : config;\n\n if (isSdkInitializedFlag) {\n if (resolvedConfig.debug) {\n initLogger.warn(\"[PingOps] SDK already initialized, skipping\");\n }\n return;\n }\n\n // Create resource with service name\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: resolvedConfig.serviceName,\n });\n\n const processor = new PingopsSpanProcessor({\n ...resolvedConfig,\n sdkVersion: SDK_VERSION,\n });\n const instrumentations = getInstrumentations();\n\n // Node.js SDK\n const nodeSdk = new NodeSDK({\n resource,\n spanProcessors: [processor],\n instrumentations,\n });\n\n nodeSdk.start();\n sdkInstance = nodeSdk;\n\n // Mark SDK as initialized\n isSdkInitializedFlag = true;\n\n setSdkInitialized(true);\n\n // Initialize isolated TracerProvider for manual spans AFTER NodeSDK starts\n // This ensures manual spans created via startSpan are processed by the same processor\n // We register it after NodeSDK so it takes precedence as the global provider\n try {\n // In version 2.2.0, span processors are passed in the constructor\n const isolatedProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [processor],\n });\n\n // Register the provider globally\n isolatedProvider.register();\n\n // Set it in global state\n setPingopsTracerProvider(isolatedProvider);\n } catch (error) {\n if (resolvedConfig.debug) {\n initLogger.error(\n \"[PingOps] Failed to create isolated TracerProvider:\",\n error instanceof Error ? error.message : String(error)\n );\n }\n // Continue without isolated provider - manual spans will use global provider\n }\n\n if (resolvedConfig.debug) {\n initLogger.info(\"[PingOps] SDK initialized\");\n }\n}\n\nfunction resolveConfigFromFile(configFilePath: string): PingopsProcessorConfig {\n const fileConfig = loadConfigFromFile(configFilePath);\n const mergedConfig = mergeConfigWithEnv(fileConfig);\n\n if (!mergedConfig.baseUrl || !mergedConfig.serviceName) {\n const missing = [\n !mergedConfig.baseUrl && \"baseUrl (or PINGOPS_BASE_URL)\",\n !mergedConfig.serviceName && \"serviceName (or PINGOPS_SERVICE_NAME)\",\n ].filter(Boolean);\n\n throw new Error(\n `initializePingops(configFile) requires ${missing.join(\" and \")}. ` +\n `Provide them in the config file or via environment variables.`\n );\n }\n\n return mergedConfig as PingopsProcessorConfig;\n}\n\n/**\n * Shuts down the SDK and flushes remaining spans\n */\nexport async function shutdownPingops(): Promise<void> {\n // Shutdown isolated TracerProvider first\n await shutdownTracerProvider();\n\n if (!sdkInstance) {\n return;\n }\n\n await sdkInstance.shutdown();\n sdkInstance = null;\n isSdkInitializedFlag = false;\n setSdkInitialized(false);\n}\n\n/**\n * Checks if the SDK is already initialized by checking if a NodeTracerProvider is available\n */\nfunction isSdkInitialized(): boolean {\n try {\n const provider = getPingopsTracerProvider();\n // If we have a NodeTracerProvider (not the default NoOpTracerProvider), SDK is initialized\n const initialized = provider instanceof NodeTracerProvider;\n logger.debug(\"Checked SDK initialization status\", {\n initialized,\n providerType: provider.constructor.name,\n });\n return initialized;\n } catch (error) {\n logger.debug(\"Error checking SDK initialization status\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Auto-initializes the SDK from environment variables if not already initialized\n */\nasync function ensureInitialized(): Promise<void> {\n // Check if SDK is already initialized (e.g., by calling initializePingops directly)\n if (isSdkInitialized()) {\n logger.debug(\"SDK already initialized, skipping auto-initialization\");\n isInitialized = true;\n return;\n }\n\n if (isInitialized) {\n logger.debug(\"SDK initialization flag already set, skipping\");\n return;\n }\n\n // If initialization is in progress, wait for it\n if (initializationPromise) {\n logger.debug(\"SDK initialization already in progress, waiting...\");\n return initializationPromise;\n }\n\n // Start initialization\n logger.info(\"Starting SDK auto-initialization from environment variables\");\n initializationPromise = Promise.resolve().then(() => {\n const apiKey = process.env.PINGOPS_API_KEY;\n const baseUrl = process.env.PINGOPS_BASE_URL;\n const serviceName = process.env.PINGOPS_SERVICE_NAME;\n const debug = process.env.PINGOPS_DEBUG === \"true\";\n\n logger.debug(\"Reading environment variables\", {\n hasApiKey: !!apiKey,\n hasBaseUrl: !!baseUrl,\n hasServiceName: !!serviceName,\n debug,\n });\n\n if (!apiKey || !baseUrl || !serviceName) {\n const missing = [\n !apiKey && \"PINGOPS_API_KEY\",\n !baseUrl && \"PINGOPS_BASE_URL\",\n !serviceName && \"PINGOPS_SERVICE_NAME\",\n ].filter(Boolean);\n\n logger.error(\n \"Missing required environment variables for auto-initialization\",\n {\n missing,\n }\n );\n\n throw new Error(\n `PingOps SDK auto-initialization requires PINGOPS_API_KEY, PINGOPS_BASE_URL, and PINGOPS_SERVICE_NAME environment variables. Missing: ${missing.join(\", \")}`\n );\n }\n\n const config: PingopsProcessorConfig = {\n apiKey,\n baseUrl,\n serviceName,\n debug,\n };\n\n logger.info(\"Initializing SDK with config\", {\n baseUrl,\n serviceName,\n debug,\n });\n\n // Call initializePingops with explicit=false since this is auto-initialization\n initializePingops(config, false);\n isInitialized = true;\n\n logger.info(\"SDK auto-initialization completed successfully\");\n });\n\n try {\n await initializationPromise;\n } catch (error) {\n logger.error(\"SDK auto-initialization failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n initializationPromise = null;\n }\n}\n\n/**\n * Returns the trace ID of the currently active span, if any.\n */\nexport function getActiveTraceId(): string | undefined {\n return trace.getActiveSpan()?.spanContext().traceId;\n}\n\n/**\n * Returns the span ID of the currently active span, if any.\n */\nexport function getActiveSpanId(): string | undefined {\n return trace.getActiveSpan()?.spanContext().spanId;\n}\n\n/**\n * Runs the callback in an intentionally tracing-suppressed context.\n *\n * Any spans started in this callback (including auto-instrumented outbound HTTP/fetch spans)\n * are intentionally dropped and not exported.\n */\nexport function withUntracked<T>(fn: () => T): T;\nexport function withUntracked<T>(fn: () => Promise<T>): Promise<T>;\nexport function withUntracked<T>(fn: () => T | Promise<T>): T | Promise<T> {\n const untrackedContext = suppressTracing(context.active()).setValue(\n PINGOPS_INTENTIONAL_SUPPRESSION,\n true\n );\n return context.with(untrackedContext, fn);\n}\n\n/**\n * Starts a new trace using the PingOps tracer provider and runs the callback within that trace.\n * Sets attributes (traceId, userId, sessionId, tags, metadata, etc.) in context so they are\n * propagated to spans created within the callback.\n *\n * @param options - Options including optional attributes and optional seed for deterministic traceId\n * @param fn - Function to execute within the trace and attribute context\n * @returns Promise resolving to the result of the function\n *\n * @example\n * ```typescript\n * import { startTrace, initializePingops } from '@pingops/sdk';\n *\n * initializePingops({ ... });\n *\n * const result = await startTrace({\n * attributes: {\n * userId: 'user-123',\n * sessionId: 'session-456',\n * tags: ['production', 'api'],\n * metadata: { environment: 'prod', version: '1.0.0' }\n * },\n * seed: 'request-123' // optional: deterministic traceId from this seed\n * }, async () => {\n * const response = await fetch('https://api.example.com/users/123');\n * return response.json();\n * });\n * ```\n */\nexport async function startTrace<T>(\n options: { attributes?: PingopsTraceAttributes; seed?: string },\n fn: () => T | Promise<T>\n): Promise<T> {\n if (!isSdkInitialized()) {\n await ensureInitialized();\n }\n\n const traceId =\n options.attributes?.traceId ?? (await createTraceId(options?.seed));\n const parentSpanId = uint8ArrayToHex(\n crypto.getRandomValues(new Uint8Array(8))\n );\n\n const spanContext = {\n traceId,\n spanId: parentSpanId,\n traceFlags: TRACE_FLAG_SAMPLED,\n };\n\n const traceExecutionBaseContext = getUnsuppressedContext();\n if (traceExecutionBaseContext === ROOT_CONTEXT) {\n if (!hasLoggedSuppressedStartTraceWarning) {\n logger.warn(\n \"startTrace detected a suppressed active context and is running on ROOT_CONTEXT to prevent suppression leakage into user outbound instrumentation\"\n );\n hasLoggedSuppressedStartTraceWarning = true;\n } else {\n logger.debug(\n \"startTrace received a suppressed active context; running trace on ROOT_CONTEXT\"\n );\n }\n }\n const contextWithSpanContext = trace.setSpanContext(\n traceExecutionBaseContext,\n spanContext\n );\n\n const tracer = getPingopsTracerProvider().getTracer(\"pingops-sdk\", \"1.0.0\");\n\n return new Promise((resolve, reject) => {\n tracer.startActiveSpan(\n \"pingops-trace\",\n {},\n contextWithSpanContext,\n (span) => {\n let contextWithAttributes = context.active();\n const attrs = options.attributes;\n if (attrs) {\n contextWithAttributes = setAttributesInContext(\n contextWithAttributes,\n attrs\n );\n }\n contextWithAttributes = contextWithAttributes.setValue(\n PINGOPS_TRACE_ID,\n traceId\n );\n\n const run = () => fn();\n\n try {\n const result = context.with(contextWithAttributes, run);\n if (result instanceof Promise) {\n result\n .then((v) => {\n span.end();\n resolve(v);\n })\n .catch((err) => {\n span.end();\n reject(err instanceof Error ? err : new Error(String(err)));\n });\n } else {\n span.end();\n resolve(result);\n }\n } catch (err) {\n span.end();\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n }\n );\n });\n}\n\nfunction getUnsuppressedContext(): ReturnType<typeof context.active> {\n const activeContext = context.active();\n if (activeContext.getValue(PINGOPS_INTENTIONAL_SUPPRESSION) === true) {\n return activeContext;\n }\n return isTracingSuppressed(activeContext) ? ROOT_CONTEXT : activeContext;\n}\n\nfunction setAttributesInContext(\n ctx: ReturnType<typeof context.active>,\n attrs: PingopsTraceAttributes\n): ReturnType<typeof context.active> {\n if (attrs.userId !== undefined) {\n ctx = ctx.setValue(PINGOPS_USER_ID, attrs.userId);\n }\n if (attrs.sessionId !== undefined) {\n ctx = ctx.setValue(PINGOPS_SESSION_ID, attrs.sessionId);\n }\n if (attrs.tags !== undefined) {\n ctx = ctx.setValue(PINGOPS_TAGS, attrs.tags);\n }\n if (attrs.metadata !== undefined) {\n ctx = ctx.setValue(PINGOPS_METADATA, attrs.metadata);\n }\n if (attrs.captureRequestBody !== undefined) {\n ctx = ctx.setVal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3,"file":"pingops-DyKGq6Vr.mjs","names":["loadYaml","isSdkInitializedFlag","(sdkPackageJson as PackageJsonWithVersion).version"],"sources":["../src/config-loader.ts","../src/init-state.ts","../package.json","../src/sdk-version.ts","../src/pingops.ts"],"sourcesContent":["/**\n * Configuration loader for reading PingOps config from JSON/YAML files\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { load as loadYaml } from \"js-yaml\";\nimport type { PingopsProcessorConfig } from \"@pingops/otel\";\n\n/**\n * Loads configuration from a JSON or YAML file\n *\n * @param filePath - Path to the config file (JSON or YAML)\n * @returns Parsed configuration object\n * @throws Error if file cannot be read or parsed\n */\nexport function loadConfigFromFile(\n filePath: string\n): Partial<PingopsProcessorConfig> {\n const resolvedPath = resolve(filePath);\n const fileContent = readFileSync(resolvedPath, \"utf-8\");\n\n const ext = resolvedPath.toLowerCase();\n if (ext.endsWith(\".yaml\") || ext.endsWith(\".yml\")) {\n return (loadYaml(fileContent) as Partial<PingopsProcessorConfig>) || {};\n } else if (ext.endsWith(\".json\")) {\n return JSON.parse(fileContent) as Partial<PingopsProcessorConfig>;\n } else {\n // Try to parse as JSON first, then YAML\n try {\n return JSON.parse(fileContent) as Partial<PingopsProcessorConfig>;\n } catch {\n return (loadYaml(fileContent) as Partial<PingopsProcessorConfig>) || {};\n }\n }\n}\n\n/**\n * Merges configuration from file and environment variables.\n * Environment variables take precedence over file config.\n *\n * @param fileConfig - Configuration loaded from file\n * @returns Merged configuration with env vars taking precedence\n */\nexport function mergeConfigWithEnv(\n fileConfig: Partial<PingopsProcessorConfig>\n): Partial<PingopsProcessorConfig> {\n const envConfig: Partial<PingopsProcessorConfig> = {};\n\n // Read from environment variables\n if (process.env.PINGOPS_API_KEY) {\n envConfig.apiKey = process.env.PINGOPS_API_KEY;\n }\n if (process.env.PINGOPS_BASE_URL) {\n envConfig.baseUrl = process.env.PINGOPS_BASE_URL;\n }\n if (process.env.PINGOPS_SERVICE_NAME) {\n envConfig.serviceName = process.env.PINGOPS_SERVICE_NAME;\n }\n if (process.env.PINGOPS_DEBUG) {\n envConfig.debug = process.env.PINGOPS_DEBUG === \"true\";\n }\n if (process.env.PINGOPS_BATCH_SIZE) {\n envConfig.batchSize = parseInt(process.env.PINGOPS_BATCH_SIZE, 10);\n }\n if (process.env.PINGOPS_BATCH_TIMEOUT) {\n envConfig.batchTimeout = parseInt(process.env.PINGOPS_BATCH_TIMEOUT, 10);\n }\n if (process.env.PINGOPS_EXPORT_MODE) {\n envConfig.exportMode = process.env.PINGOPS_EXPORT_MODE as\n | \"batched\"\n | \"immediate\";\n }\n\n // Merge: env vars override file config\n return {\n ...fileConfig,\n ...envConfig,\n };\n}\n","/**\n * Shared state for tracking SDK initialization\n * This module exists to avoid circular dependencies between pingops.ts and instrumentation.ts\n */\n\nlet isSdkInitializedFlag = false;\n\n/**\n * Returns whether the SDK has been initialized.\n */\nexport function isSdkInitialized(): boolean {\n return isSdkInitializedFlag;\n}\n\n/**\n * Sets the SDK initialization flag.\n * Called by initializePingops when the SDK is initialized.\n */\nexport function setSdkInitialized(initialized: boolean): void {\n isSdkInitializedFlag = initialized;\n}\n","","import sdkPackageJson from \"../package.json\";\n\ntype PackageJsonWithVersion = {\n version?: string;\n};\n\nconst packageVersion = (sdkPackageJson as PackageJsonWithVersion).version;\n\nexport const SDK_VERSION =\n typeof packageVersion === \"string\" ? packageVersion : \"unknown\";\n","/**\n * PingOps SDK singleton for manual instrumentation\n *\n * Provides initializePingops, shutdownPingops, startTrace, getActiveTraceId,\n * and getActiveSpanId. startTrace can auto-initialize from environment variables if needed.\n */\n\nimport { ROOT_CONTEXT, context, trace } from \"@opentelemetry/api\";\nimport { isTracingSuppressed, suppressTracing } from \"@opentelemetry/core\";\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport { ATTR_SERVICE_NAME } from \"@opentelemetry/semantic-conventions\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\nimport type { PingopsProcessorConfig } from \"@pingops/otel\";\nimport {\n setPingopsTracerProvider,\n shutdownTracerProvider,\n PingopsSpanProcessor,\n} from \"@pingops/otel\";\nimport {\n createLogger,\n createTraceId,\n uint8ArrayToHex,\n type PingopsTraceAttributes,\n} from \"@pingops/core\";\nimport {\n PINGOPS_TRACE_ID,\n PINGOPS_USER_ID,\n PINGOPS_SESSION_ID,\n PINGOPS_TAGS,\n PINGOPS_METADATA,\n PINGOPS_CAPTURE_REQUEST_BODY,\n PINGOPS_CAPTURE_RESPONSE_BODY,\n PINGOPS_INTENTIONAL_SUPPRESSION,\n} from \"@pingops/core\";\nimport { loadConfigFromFile, mergeConfigWithEnv } from \"./config-loader\";\nimport { setSdkInitialized } from \"./init-state\";\nimport { getPingopsTracerProvider } from \"@pingops/otel\";\nimport { getInstrumentations } from \"@pingops/otel\";\nimport { SDK_VERSION } from \"./sdk-version\";\n\nconst TRACE_FLAG_SAMPLED = 1;\n\nconst initLogger = createLogger(\"[PingOps Initialize]\");\nconst logger = createLogger(\"[PingOps Pingops]\");\n\nlet sdkInstance: NodeSDK | null = null;\nlet isSdkInitializedFlag = false;\n\n/**\n * Global state to track initialization\n */\nlet isInitialized = false;\nlet initializationPromise: Promise<void> | null = null;\nlet hasLoggedSuppressedStartTraceWarning = false;\n\n/**\n * Initializes PingOps SDK\n *\n * This function:\n * 1. Creates an OpenTelemetry NodeSDK instance\n * 2. Configures Resource with service.name\n * 3. Registers PingopsSpanProcessor\n * 4. Enables HTTP/fetch/GenAI instrumentation\n * 5. Starts the SDK\n *\n * @param config - Configuration object, config file path, or config file wrapper\n * @param explicit - Whether this is an explicit call (default: true).\n * Set to false when called internally by startTrace auto-initialization.\n */\nexport function initializePingops(\n config: PingopsProcessorConfig,\n explicit?: boolean\n): void;\nexport function initializePingops(\n configFilePath: string,\n explicit?: boolean\n): void;\nexport function initializePingops(\n config: { configFile: string },\n explicit?: boolean\n): void;\nexport function initializePingops(\n config:\n | PingopsProcessorConfig\n | string\n | {\n configFile: string;\n },\n explicit: boolean = true\n): void {\n void explicit; // Ignored: SDK always uses global instrumentation\n const resolvedConfig: PingopsProcessorConfig =\n typeof config === \"string\"\n ? resolveConfigFromFile(config)\n : \"configFile\" in config\n ? resolveConfigFromFile(config.configFile)\n : config;\n\n if (isSdkInitializedFlag) {\n if (resolvedConfig.debug) {\n initLogger.warn(\"[PingOps] SDK already initialized, skipping\");\n }\n return;\n }\n\n // Create resource with service name\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: resolvedConfig.serviceName,\n });\n\n const processor = new PingopsSpanProcessor({\n ...resolvedConfig,\n sdkVersion: SDK_VERSION,\n });\n const instrumentations = getInstrumentations();\n\n // Node.js SDK\n const nodeSdk = new NodeSDK({\n resource,\n spanProcessors: [processor],\n instrumentations,\n });\n\n nodeSdk.start();\n sdkInstance = nodeSdk;\n\n // Mark SDK as initialized\n isSdkInitializedFlag = true;\n\n setSdkInitialized(true);\n\n // Initialize isolated TracerProvider for manual spans AFTER NodeSDK starts\n // This ensures manual spans created via startSpan are processed by the same processor\n // We register it after NodeSDK so it takes precedence as the global provider\n try {\n // In version 2.2.0, span processors are passed in the constructor\n const isolatedProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [processor],\n });\n\n // Register the provider globally\n isolatedProvider.register();\n\n // Set it in global state\n setPingopsTracerProvider(isolatedProvider);\n } catch (error) {\n if (resolvedConfig.debug) {\n initLogger.error(\n \"[PingOps] Failed to create isolated TracerProvider:\",\n error instanceof Error ? error.message : String(error)\n );\n }\n // Continue without isolated provider - manual spans will use global provider\n }\n\n if (resolvedConfig.debug) {\n initLogger.info(\"[PingOps] SDK initialized\");\n }\n}\n\nfunction resolveConfigFromFile(configFilePath: string): PingopsProcessorConfig {\n const fileConfig = loadConfigFromFile(configFilePath);\n const mergedConfig = mergeConfigWithEnv(fileConfig);\n\n if (!mergedConfig.baseUrl || !mergedConfig.serviceName) {\n const missing = [\n !mergedConfig.baseUrl && \"baseUrl (or PINGOPS_BASE_URL)\",\n !mergedConfig.serviceName && \"serviceName (or PINGOPS_SERVICE_NAME)\",\n ].filter(Boolean);\n\n throw new Error(\n `initializePingops(configFile) requires ${missing.join(\" and \")}. ` +\n `Provide them in the config file or via environment variables.`\n );\n }\n\n return mergedConfig as PingopsProcessorConfig;\n}\n\n/**\n * Shuts down the SDK and flushes remaining spans\n */\nexport async function shutdownPingops(): Promise<void> {\n // Shutdown isolated TracerProvider first\n await shutdownTracerProvider();\n\n if (!sdkInstance) {\n return;\n }\n\n await sdkInstance.shutdown();\n sdkInstance = null;\n isSdkInitializedFlag = false;\n setSdkInitialized(false);\n}\n\n/**\n * Checks if the SDK is already initialized by checking if a NodeTracerProvider is available\n */\nfunction isSdkInitialized(): boolean {\n try {\n const provider = getPingopsTracerProvider();\n // If we have a NodeTracerProvider (not the default NoOpTracerProvider), SDK is initialized\n const initialized = provider instanceof NodeTracerProvider;\n logger.debug(\"Checked SDK initialization status\", {\n initialized,\n providerType: provider.constructor.name,\n });\n return initialized;\n } catch (error) {\n logger.debug(\"Error checking SDK initialization status\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Auto-initializes the SDK from environment variables if not already initialized\n */\nasync function ensureInitialized(): Promise<void> {\n // Check if SDK is already initialized (e.g., by calling initializePingops directly)\n if (isSdkInitialized()) {\n logger.debug(\"SDK already initialized, skipping auto-initialization\");\n isInitialized = true;\n return;\n }\n\n if (isInitialized) {\n logger.debug(\"SDK initialization flag already set, skipping\");\n return;\n }\n\n // If initialization is in progress, wait for it\n if (initializationPromise) {\n logger.debug(\"SDK initialization already in progress, waiting...\");\n return initializationPromise;\n }\n\n // Start initialization\n logger.info(\"Starting SDK auto-initialization from environment variables\");\n initializationPromise = Promise.resolve().then(() => {\n const apiKey = process.env.PINGOPS_API_KEY;\n const baseUrl = process.env.PINGOPS_BASE_URL;\n const serviceName = process.env.PINGOPS_SERVICE_NAME;\n const debug = process.env.PINGOPS_DEBUG === \"true\";\n\n logger.debug(\"Reading environment variables\", {\n hasApiKey: !!apiKey,\n hasBaseUrl: !!baseUrl,\n hasServiceName: !!serviceName,\n debug,\n });\n\n if (!apiKey || !baseUrl || !serviceName) {\n const missing = [\n !apiKey && \"PINGOPS_API_KEY\",\n !baseUrl && \"PINGOPS_BASE_URL\",\n !serviceName && \"PINGOPS_SERVICE_NAME\",\n ].filter(Boolean);\n\n logger.error(\n \"Missing required environment variables for auto-initialization\",\n {\n missing,\n }\n );\n\n throw new Error(\n `PingOps SDK auto-initialization requires PINGOPS_API_KEY, PINGOPS_BASE_URL, and PINGOPS_SERVICE_NAME environment variables. Missing: ${missing.join(\", \")}`\n );\n }\n\n const config: PingopsProcessorConfig = {\n apiKey,\n baseUrl,\n serviceName,\n debug,\n };\n\n logger.info(\"Initializing SDK with config\", {\n baseUrl,\n serviceName,\n debug,\n });\n\n // Call initializePingops with explicit=false since this is auto-initialization\n initializePingops(config, false);\n isInitialized = true;\n\n logger.info(\"SDK auto-initialization completed successfully\");\n });\n\n try {\n await initializationPromise;\n } catch (error) {\n logger.error(\"SDK auto-initialization failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n initializationPromise = null;\n }\n}\n\n/**\n * Returns the trace ID of the currently active span, if any.\n */\nexport function getActiveTraceId(): string | undefined {\n return trace.getActiveSpan()?.spanContext().traceId;\n}\n\n/**\n * Returns the span ID of the currently active span, if any.\n */\nexport function getActiveSpanId(): string | undefined {\n return trace.getActiveSpan()?.spanContext().spanId;\n}\n\n/**\n * Runs the callback in an intentionally tracing-suppressed context.\n *\n * Any spans started in this callback (including auto-instrumented outbound HTTP/fetch spans)\n * are intentionally dropped and not exported.\n */\nexport function withUntracked<T>(fn: () => T): T;\nexport function withUntracked<T>(fn: () => Promise<T>): Promise<T>;\nexport function withUntracked<T>(fn: () => T | Promise<T>): T | Promise<T> {\n const untrackedContext = suppressTracing(context.active()).setValue(\n PINGOPS_INTENTIONAL_SUPPRESSION,\n true\n );\n return context.with(untrackedContext, fn);\n}\n\n/**\n * Starts a new trace using the PingOps tracer provider and runs the callback within that trace.\n * Sets attributes (traceId, userId, sessionId, tags, metadata, etc.) in context so they are\n * propagated to spans created within the callback.\n *\n * @param options - Options including optional attributes and optional seed for deterministic traceId\n * @param fn - Function to execute within the trace and attribute context\n * @returns Promise resolving to the result of the function\n *\n * @example\n * ```typescript\n * import { startTrace, initializePingops } from '@pingops/sdk';\n *\n * initializePingops({ ... });\n *\n * const result = await startTrace({\n * attributes: {\n * userId: 'user-123',\n * sessionId: 'session-456',\n * tags: ['production', 'api'],\n * metadata: { environment: 'prod', version: '1.0.0' }\n * },\n * seed: 'request-123' // optional: deterministic traceId from this seed\n * }, async () => {\n * const response = await fetch('https://api.example.com/users/123');\n * return response.json();\n * });\n * ```\n */\nexport async function startTrace<T>(\n options: { attributes?: PingopsTraceAttributes; seed?: string },\n fn: () => T | Promise<T>\n): Promise<T> {\n if (!isSdkInitialized()) {\n await ensureInitialized();\n }\n\n const traceId =\n options.attributes?.traceId ?? (await createTraceId(options?.seed));\n const parentSpanId = uint8ArrayToHex(\n crypto.getRandomValues(new Uint8Array(8))\n );\n\n const spanContext = {\n traceId,\n spanId: parentSpanId,\n traceFlags: TRACE_FLAG_SAMPLED,\n };\n\n const traceExecutionBaseContext = getUnsuppressedContext();\n if (traceExecutionBaseContext === ROOT_CONTEXT) {\n if (!hasLoggedSuppressedStartTraceWarning) {\n logger.warn(\n \"startTrace detected a suppressed active context and is running on ROOT_CONTEXT to prevent suppression leakage into user outbound instrumentation\"\n );\n hasLoggedSuppressedStartTraceWarning = true;\n } else {\n logger.debug(\n \"startTrace received a suppressed active context; running trace on ROOT_CONTEXT\"\n );\n }\n }\n const contextWithSpanContext = trace.setSpanContext(\n traceExecutionBaseContext,\n spanContext\n );\n\n const tracer = getPingopsTracerProvider().getTracer(\"pingops-sdk\", \"1.0.0\");\n\n return new Promise((resolve, reject) => {\n tracer.startActiveSpan(\n \"pingops-trace\",\n {},\n contextWithSpanContext,\n (span) => {\n let contextWithAttributes = context.active();\n const attrs = options.attributes;\n if (attrs) {\n contextWithAttributes = setAttributesInContext(\n contextWithAttributes,\n attrs\n );\n }\n contextWithAttributes = contextWithAttributes.setValue(\n PINGOPS_TRACE_ID,\n traceId\n );\n\n const run = () => fn();\n\n try {\n const result = context.with(contextWithAttributes, run);\n if (result instanceof Promise) {\n result\n .then((v) => {\n span.end();\n resolve(v);\n })\n .catch((err) => {\n span.end();\n reject(err instanceof Error ? err : new Error(String(err)));\n });\n } else {\n span.end();\n resolve(result);\n }\n } catch (err) {\n span.end();\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n }\n );\n });\n}\n\nfunction getUnsuppressedContext(): ReturnType<typeof context.active> {\n const activeContext = context.active();\n if (activeContext.getValue(PINGOPS_INTENTIONAL_SUPPRESSION) === true) {\n return activeContext;\n }\n return isTracingSuppressed(activeContext) ? ROOT_CONTEXT : activeContext;\n}\n\nfunction setAttributesInContext(\n ctx: ReturnType<typeof context.active>,\n attrs: PingopsTraceAttributes\n): ReturnType<typeof context.active> {\n if (attrs.userId !== undefined) {\n ctx = ctx.setValue(PINGOPS_USER_ID, attrs.userId);\n }\n if (attrs.sessionId !== undefined) {\n ctx = ctx.setValue(PINGOPS_SESSION_ID, attrs.sessionId);\n }\n if (attrs.tags !== undefined) {\n ctx = ctx.setValue(PINGOPS_TAGS, attrs.tags);\n }\n if (attrs.metadata !== undefined) {\n ctx = ctx.setValue(PINGOPS_METADATA, attrs.metadata);\n }\n if (attrs.captureRequestBody !== undefined) {\n ctx = ctx.setValue(PINGOPS_CAPTURE_REQUEST_BODY, attrs.captureRequestBody);\n }\n if (attrs.captureResponseBody !== undefined) {\n ctx = ctx.setValue(\n PINGOPS_CAPTURE_RESPONSE_BODY,\n attrs.captureResponseBody\n );\n }\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,mBACd,UACiC;CACjC,MAAM,eAAe,QA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