CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-opentelemetry--core

OpenTelemetry Core provides constants and utilities shared by all OpenTelemetry SDK packages.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

platform.mddocs/

Platform Utilities

Cross-platform abstractions for environment variable access, performance measurement, SDK information, and timer utilities that work across Node.js and browser environments.

Capabilities

Environment Variable Access

Functions to safely access and parse environment variables with type conversion and fallback handling.

/**
 * Get boolean value from environment variable
 * @param key - Environment variable name
 * @returns Boolean value, undefined if not set or invalid
 */
function getBooleanFromEnv(key: string): boolean | undefined;

/**
 * Get string value from environment variable
 * @param key - Environment variable name
 * @returns String value, undefined if not set
 */
function getStringFromEnv(key: string): string | undefined;

/**
 * Get number value from environment variable
 * @param key - Environment variable name
 * @returns Number value, undefined if not set or invalid
 */
function getNumberFromEnv(key: string): number | undefined;

/**
 * Get comma-separated string list from environment variable
 * @param key - Environment variable name
 * @param separator - Optional separator (defaults to comma)
 * @returns Array of strings, empty array if not set
 */
function getStringListFromEnv(key: string, separator?: string): string[];

Usage Examples:

import {
  getBooleanFromEnv,
  getStringFromEnv,
  getNumberFromEnv,
  getStringListFromEnv
} from "@opentelemetry/core";

// Get configuration from environment variables
const debugEnabled = getBooleanFromEnv("OTEL_DEBUG");
const serviceName = getStringFromEnv("OTEL_SERVICE_NAME");
const samplingRatio = getNumberFromEnv("OTEL_TRACE_SAMPLING_RATIO");
const endpoints = getStringListFromEnv("OTEL_EXPORTER_OTLP_ENDPOINTS");

// Use with defaults
const config = {
  debug: debugEnabled ?? false,
  serviceName: serviceName ?? "unknown-service",
  samplingRatio: samplingRatio ?? 1.0,
  endpoints: endpoints.length > 0 ? endpoints : ["http://localhost:4318"]
};

console.log("Configuration:", config);

// Parse custom separators
const features = getStringListFromEnv("ENABLED_FEATURES", "|");
console.log("Enabled features:", features); // From "feature1|feature2|feature3"

// Boolean parsing examples
// "true", "TRUE", "1" -> true
// "false", "FALSE", "0" -> false
// anything else -> undefined
const sslEnabled = getBooleanFromEnv("SSL_ENABLED");
if (sslEnabled !== undefined) {
  console.log("SSL explicitly configured:", sslEnabled);
} else {
  console.log("SSL not configured, using default");
}

SDK Information

Access to SDK metadata and version information.

/**
 * SDK information object containing version and metadata
 */
const SDK_INFO: {
  name: string;
  version: string;
  language: string;
};

Usage Examples:

import { SDK_INFO } from "@opentelemetry/core";

// Access SDK information
console.log("SDK Name:", SDK_INFO.name);       // "@opentelemetry/core"
console.log("SDK Version:", SDK_INFO.version); // "2.1.0"
console.log("Language:", SDK_INFO.language);   // "javascript"

// Use in resource attributes
const resourceAttributes = {
  "telemetry.sdk.name": SDK_INFO.name,
  "telemetry.sdk.version": SDK_INFO.version,
  "telemetry.sdk.language": SDK_INFO.language
};

// Include in exported data
const exportData = {
  resource: resourceAttributes,
  // ... other data
};

Global Object Access

Cross-platform access to the global object.

/**
 * Cross-platform global object reference
 * Works in Node.js (global), Browser (window), Web Workers (self)
 */
const _globalThis: object;

Usage Examples:

import { _globalThis } from "@opentelemetry/core";

// Access global object safely across platforms
const globalObj = _globalThis as any;

// Store global state (use carefully)
globalObj.__OTEL_INITIALIZED__ = true;

// Check for global features
if (typeof globalObj.fetch === "function") {
  console.log("Fetch API available");
}

// Access platform-specific globals
if (typeof globalObj.process !== "undefined") {
  console.log("Running in Node.js");
} else if (typeof globalObj.window !== "undefined") {
  console.log("Running in browser");
} else if (typeof globalObj.self !== "undefined") {
  console.log("Running in web worker");
}

Performance Utilities

Cross-platform performance measurement utilities.

/**
 * Cross-platform performance object with timing capabilities
 */
const otperformance: {
  now(): number;
  timeOrigin?: number;
};

Usage Examples:

import { otperformance } from "@opentelemetry/core";

// High-precision timing
const startTime = otperformance.now();

// Simulate some work
await new Promise(resolve => setTimeout(resolve, 100));

const endTime = otperformance.now();
const duration = endTime - startTime;

console.log(`Operation took ${duration.toFixed(3)}ms`);

// Access time origin if available
if (otperformance.timeOrigin) {
  const absoluteTime = otperformance.timeOrigin + otperformance.now();
  console.log("Absolute timestamp:", absoluteTime);
}

// Use for span timing
function createTimingSpan(name: string) {
  const startTime = otperformance.now();
  
  return {
    name,
    startTime,
    end() {
      const endTime = otperformance.now();
      const duration = endTime - startTime;
      console.log(`Span ${name} duration: ${duration.toFixed(3)}ms`);
      return duration;
    }
  };
}

const span = createTimingSpan("database-query");
// ... perform database query ...
span.end();

Timer Utilities

Timer functions that don't keep the Node.js process alive.

/**
 * Create a timer that doesn't keep the Node.js process alive
 * @param fn - Function to execute
 * @param delay - Delay in milliseconds
 * @returns Timer reference (platform-specific)
 */
function unrefTimer(fn: Function, delay: number): any;

Usage Examples:

import { unrefTimer } from "@opentelemetry/core";

// Create timer that won't prevent process exit
const timer = unrefTimer(() => {
  console.log("Periodic cleanup task");
}, 5000);

// Timer runs every 5 seconds but won't keep process alive
console.log("Timer created, process can exit naturally");

// Use for background telemetry tasks
function startPeriodicExport() {
  return unrefTimer(() => {
    // Export telemetry data
    console.log("Exporting telemetry data...");
    
    // This won't prevent the application from shutting down
    exportTelemetryData().catch(console.error);
  }, 30000); // Every 30 seconds
}

const exportTimer = startPeriodicExport();

// Use for connection health checks
function startHealthCheck(connection: any) {
  return unrefTimer(() => {
    if (connection.isConnected()) {
      console.log("Connection healthy");
    } else {
      console.warn("Connection lost, attempting reconnect");
      connection.reconnect().catch(console.error);
    }
  }, 10000); // Every 10 seconds
}

// In Node.js, this prevents the timer from keeping the process alive
// In browsers, this works like regular setTimeout

Platform Detection

Utilities for detecting the current platform and environment.

Usage Examples:

import { _globalThis, otperformance } from "@opentelemetry/core";

function detectPlatform() {
  const globalObj = _globalThis as any;
  
  if (typeof globalObj.process !== "undefined" && globalObj.process.versions?.node) {
    return {
      platform: "node",
      version: globalObj.process.versions.node,
      hasPerformanceHooks: typeof globalObj.process.hrtime === "function"
    };
  }
  
  if (typeof globalObj.window !== "undefined") {
    return {
      platform: "browser",
      userAgent: globalObj.navigator?.userAgent,
      hasPerformanceAPI: typeof otperformance.now === "function"
    };
  }
  
  if (typeof globalObj.self !== "undefined") {
    return {
      platform: "webworker",
      hasPerformanceAPI: typeof otperformance.now === "function"
    };
  }
  
  return {
    platform: "unknown"
  };
}

const platformInfo = detectPlatform();
console.log("Platform info:", platformInfo);

// Use platform info for conditional behavior
if (platformInfo.platform === "node") {
  // Use Node.js specific features
  console.log("Using Node.js optimizations");
} else if (platformInfo.platform === "browser") {
  // Use browser specific features
  console.log("Using browser optimizations");
}

Install with Tessl CLI

npx tessl i tessl/npm-opentelemetry--core

docs

context.md

index.md

platform.md

propagation.md

timing.md

trace-state.md

utilities.md

validation.md

tile.json