@getargvio/argvio 0.1.0 → 0.5.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tier.ts","../src/options.ts","../src/otlp.ts","../src/resource.ts","../src/errors.ts","../src/consentEnv.ts","../src/taxonomy.ts","../src/safety.ts","../src/client.ts","../src/consent.ts","../src/consentFile.ts"],"names":["OTLPTraceExporterGrpc","OTLPMetricExporterGrpc","OTLPLogExporterGrpc","OTLPTraceExporterHttp","OTLPMetricExporterHttp","OTLPLogExporterHttp","readFileSync"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgBO,IAAM,IAAA,GAAO;AAAA;AAAA,EAElB,SAAA,EAAW,CAAA;AAAA;AAAA,EAEX,KAAA,EAAO,CAAA;AAAA;AAAA,EAEP,IAAA,EAAM,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMN,KAAA,EAAO;AACT;AAKO,IAAM,kBAAA,GAAqB;AAElC,IAAM,YAAA,GAAqC;AAAA,EACzC,CAAC,IAAA,CAAK,SAAS,GAAG,WAAA;AAAA,EAClB,CAAC,IAAA,CAAK,KAAK,GAAG,OAAA;AAAA,EACd,CAAC,IAAA,CAAK,IAAI,GAAG,MAAA;AAAA,EACb,CAAC,IAAA,CAAK,KAAK,GAAG;AAChB,CAAA;AAGO,SAAS,aAAa,IAAA,EAAoB;AAC/C,EAAA,OAAO,YAAA,CAAa,IAAI,CAAA,IAAK,SAAA;AAC/B;AAQO,SAAS,UAAU,KAAA,EAAiC;AACzD,EAAA,QAAQ,KAAA;AAAO,IACb,KAAK,WAAA;AACH,MAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IACd,KAAK,OAAA;AACH,MAAA,OAAO,IAAA,CAAK,KAAA;AAAA,IACd,KAAK,MAAA;AACH,MAAA,OAAO,IAAA,CAAK,IAAA;AAAA,IACd,KAAK,QAAA;AACH,MA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CAAM,IAAI,CAAA;AAC9B,IAAA,MAAM,IAAA,GAAO,SAAA,CAAU,MAAA,CAAO,IAAA,IAAQ,EAAE,CAAA;AACxC,IAAA,IAAI,IAAA,KAAS,QAAW,MAAM,mBAAA;AAC9B,IAAA,OAAO,IAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,IAAA,EAAkB;AACtB,IAAA,IAAI,CAAC,IAAA,CAAK,IAAA,EAAM,MAAM,gBAAA;AACtB,IAAA,IAAI,CAAC,WAAA,CAAY,IAAI,CAAA,EAAG,MAAM,mBAAA;AAC9B,IAAA,SAAA,CAAU,OAAA,CAAQ,KAAK,IAAI,CAAA,EAAG,EAAE,SAAA,EAAW,IAAA,EAAM,IAAA,EAAM,GAAA,EAAO,CAAA;AAC9D,IAAA,MAAM,QAAA,GAAgC,EAAE,IAAA,EAAM,YAAA,CAAa,IAAI,CAAA,EAAE;AACjE,IAAA,aAAA,CAAc,IAAA,CAAK,MAAM,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAA,EAAG,EAAE,IAAA,EAAM,GAAA,EAAO,CAAA;AAAA,EACpE;AACF","file":"index.js","sourcesContent":["/**\n * The consent tier a CLI user (or their organization) has granted for\n * telemetry collection. Gates both which `record*` calls are allowed to\n * emit which fields, and the value sent on the `cli.analytics.tier`\n * resource attribute, which the public ingest server re-validates and\n * enforces as a backstop.\n *\n * Tiers are strictly ordered: each tier is a superset of the fields\n * allowed at the tier below it. Compare with plain `<`/`<=`/`>=` — the\n * numeric values are significant, not just distinct enum tags.\n *\n * TODO(schema): the wire string values in {@link tierToString} are\n * provisional pending the server-side allowlist file being confirmed.\n * They MUST match the `public` server's semantic allowlist exactly, or\n * the server will reject/strip the resource attribute.\n */\nexport const Tier = {\n /** No persistent or cross-invocation identifiers; aggregate counts only. */\n Anonymous: 0,\n /** Adds command path, flag names (not values), exit code, and latency. */\n Basic: 1,\n /** Adds session correlation and classified (not raw) error signatures. */\n Full: 2,\n /**\n * The explicit opt-in tier: raw error detail (stack traces, messages)\n * and any other field the allowlist marks opt-in-only. Never the\n * default; a vendor or user must positively select it.\n */\n OptIn: 3,\n} as const\n\nexport type Tier = (typeof Tier)[keyof typeof Tier]\n\n/** The OTel resource attribute key the tier is reported under. */\nexport const RESOURCE_ATTR_TIER = 'cli.analytics.tier'\n\nconst TIER_STRINGS: Record<Tier, string> = {\n [Tier.Anonymous]: 'anonymous',\n [Tier.Basic]: 'basic',\n [Tier.Full]: 'full',\n [Tier.OptIn]: 'opt-in',\n}\n\n/** Returns the wire value sent on the `cli.analytics.tier` resource attribute. */\nexport function tierToString(tier: Tier): string {\n return TIER_STRINGS[tier] ?? 'unknown'\n}\n\n/**\n * Parses a wire tier string (as produced by {@link tierToString}) back\n * into a {@link Tier}. Returns `undefined` if `value` does not match a\n * known tier — callers should fail closed to `Tier.Anonymous` in that\n * case, never assume the highest tier.\n */\nexport function parseTier(value: string): Tier | undefined {\n switch (value) {\n case 'anonymous':\n return Tier.Anonymous\n case 'basic':\n return Tier.Basic\n case 'full':\n return Tier.Full\n case 'opt-in':\n return Tier.OptIn\n default:\n return undefined\n }\n}\n\n/** Reports whether `value` is a known {@link Tier}. */\nexport function isValidTier(value: number): value is Tier {\n return (\n value === Tier.Anonymous || value === Tier.Basic || value === Tier.Full || value === Tier.OptIn\n )\n}\n\n/**\n * Reports whether `tier` permits emitting a field scoped to `required`.\n * A session resolved to `Tier.Full`, for example, `tierAllows(Tier.Full,\n * Tier.Basic)` and `tierAllows(Tier.Full, Tier.Full)` but not\n * `tierAllows(Tier.Full, Tier.OptIn)`.\n */\nexport function tierAllows(tier: Tier, required: Tier): boolean {\n return tier >= required\n}\n\n/** Returns the lower of `tier` and `ceiling`. */\nexport function clampTier(tier: Tier, ceiling: Tier): Tier {\n return tier > ceiling ? ceiling : tier\n}\n\n/**\n * A coarse, vendor-assigned classification of an error — deliberately\n * not the error's message or type name, both of which can carry\n * arbitrary (and potentially sensitive) free-form text. This SDK does\n * not attempt to infer a category from an error value itself; the\n * vendor's own error handling already knows which of these applies.\n */\nexport const ErrorCategory = {\n Unknown: 'unknown',\n /** Bad input, invalid flags/args. */\n User: 'user',\n Validation: 'validation',\n Network: 'network',\n Auth: 'auth',\n Internal: 'internal',\n Timeout: 'timeout',\n Canceled: 'canceled',\n} as const\n\nexport type ErrorCategory = (typeof ErrorCategory)[keyof typeof ErrorCategory]\n\nconst ERROR_CATEGORY_VALUES: ReadonlySet<string> = new Set(Object.values(ErrorCategory))\n\nexport function isValidErrorCategory(value: string): value is ErrorCategory {\n return ERROR_CATEGORY_VALUES.has(value)\n}\n","import { Tier } from './tier.js'\nimport type { ConsentProvider } from './consent.js'\n\nexport type Transport = 'http' | 'grpc'\n\n/**\n * The hosted public ingest endpoint for OTLP/HTTP. Overridden by\n * `options.endpoint` for self-hosted/on-prem deployments.\n *\n * TODO(schema): confirm the production hostname; this is a placeholder.\n */\nexport const DEFAULT_ENDPOINT_HTTP = 'https://ingest.argvio.io:4318'\n\n/** The hosted public ingest endpoint for OTLP/gRPC. Same TODO(schema) status as above. */\nexport const DEFAULT_ENDPOINT_GRPC = 'ingest.argvio.io:4317'\n\n/**\n * The metadata/header key the API key is sent under.\n *\n * TODO(schema): confirm against the public server's actual auth\n * contract; placeholder pending that being pasted into this repo.\n */\nexport const DEFAULT_AUTH_HEADER = 'x-argvio-api-key'\n\nexport const DEFAULT_EXPORT_TIMEOUT_MS = 10_000\nexport const DEFAULT_SHUTDOWN_TIMEOUT_MS = 5_000\nexport const DEFAULT_QUEUE_SIZE = 2048\n\n/** Configures a {@link Client} constructed by `createClient`. */\nexport interface ClientOptions {\n /**\n * Overrides the OTLP collector endpoint. Defaults to the hosted\n * public endpoint appropriate for `transport`.\n */\n endpoint?: string\n /**\n * Selects the OTLP wire transport. Defaults to `'http'` so a CLI that\n * embeds it doesn't pull in a gRPC client stack by default. Pass\n * `'grpc'` if you need gRPC.\n */\n transport?: Transport\n /** Disables transport security. Only intended for local development against a self-hosted collector without TLS. */\n insecure?: boolean\n /** Overrides the header the API key is sent under. Rarely needed. */\n authHeader?: string\n /** The consent tier used when no `consentProvider` is supplied, or if it rejects/times out. Defaults to `Tier.Anonymous`. */\n defaultTier?: Tier\n /** Resolves the session's consent tier at construction time. If unset, `defaultTier` is used directly. */\n consentProvider?: ConsentProvider\n /**\n * Fully disables the client: `createClient` returns a Client that\n * performs zero network calls and whose `record*` methods are no-ops\n * with negligible overhead. Equivalent to setting `ARGVIO_DISABLED=1`,\n * and also engaged automatically when `DO_NOT_TRACK` requests it.\n */\n disabled?: boolean\n /** Bounds how long a single export attempt may take. */\n exportTimeoutMs?: number\n /** Bounds how long `flush`/`shutdown` may block waiting for in-flight data to be exported. */\n shutdownTimeoutMs?: number\n /** Bounds the number of pending records buffered before new records are dropped (counted, never blocking). */\n queueSize?: number\n /**\n * Additional static OTel resource attributes (e.g. a build channel or\n * distribution identifier). Not tier-gated and not part of the\n * taxonomy — use sparingly, for attributes that describe the CLI\n * build itself rather than any individual invocation.\n */\n resourceAttributes?: Record<string, string>\n}\n\nexport interface ResolvedConfig {\n apiKey: string\n cliName: string\n cliVersion: string\n endpoint: string\n transport: Transport\n insecure: boolean\n authHeader: string\n defaultTier: Tier\n consentProvider: ConsentProvider | undefined\n disabled: boolean\n exportTimeoutMs: number\n shutdownTimeoutMs: number\n queueSize: number\n resourceAttributes: Record<string, string>\n}\n\nexport function resolveConfig(\n apiKey: string,\n cliName: string,\n cliVersion: string,\n options: ClientOptions = {},\n): ResolvedConfig {\n const transport = options.transport ?? 'http'\n return {\n apiKey,\n cliName,\n cliVersion,\n transport,\n endpoint:\n options.endpoint || (transport === 'grpc' ? DEFAULT_ENDPOINT_GRPC : DEFAULT_ENDPOINT_HTTP),\n insecure: options.insecure ?? false,\n authHeader: options.authHeader || DEFAULT_AUTH_HEADER,\n defaultTier: options.defaultTier ?? Tier.Anonymous,\n consentProvider: options.consentProvider,\n disabled: options.disabled ?? false,\n exportTimeoutMs:\n options.exportTimeoutMs && options.exportTimeoutMs > 0\n ? options.exportTimeoutMs\n : DEFAULT_EXPORT_TIMEOUT_MS,\n shutdownTimeoutMs:\n options.shutdownTimeoutMs && options.shutdownTimeoutMs > 0\n ? options.shutdownTimeoutMs\n : DEFAULT_SHUTDOWN_TIMEOUT_MS,\n queueSize: options.queueSize && options.queueSize > 0 ? options.queueSize : DEFAULT_QUEUE_SIZE,\n resourceAttributes: options.resourceAttributes ?? {},\n }\n}\n","import { Metadata } from '@grpc/grpc-js'\nimport type { SpanExporter } from '@opentelemetry/sdk-trace-node'\nimport type { LogRecordExporter } from '@opentelemetry/sdk-logs'\nimport type { PushMetricExporter } from '@opentelemetry/sdk-metrics'\n\nimport { OTLPTraceExporter as OTLPTraceExporterHttp } from '@opentelemetry/exporter-trace-otlp-http'\nimport { OTLPTraceExporter as OTLPTraceExporterGrpc } from '@opentelemetry/exporter-trace-otlp-grpc'\nimport { OTLPMetricExporter as OTLPMetricExporterHttp } from '@opentelemetry/exporter-metrics-otlp-http'\nimport { OTLPMetricExporter as OTLPMetricExporterGrpc } from '@opentelemetry/exporter-metrics-otlp-grpc'\nimport { OTLPLogExporter as OTLPLogExporterHttp } from '@opentelemetry/exporter-logs-otlp-http'\nimport { OTLPLogExporter as OTLPLogExporterGrpc } from '@opentelemetry/exporter-logs-otlp-grpc'\n\nimport type { ResolvedConfig } from './options.js'\n\nexport interface Exporters {\n trace: SpanExporter\n metric: PushMetricExporter\n log: LogRecordExporter\n}\n\nconst SCHEME_RE = /^[a-z][a-z0-9+.-]*:\\/\\//i\n\n/**\n * Ensures `endpoint` carries an explicit scheme, downgrading to `http://`\n * when `insecure` is set (used for local development against a\n * self-hosted collector without TLS).\n */\nfunction withScheme(endpoint: string, insecure: boolean): string {\n if (!SCHEME_RE.test(endpoint)) {\n return `${insecure ? 'http' : 'https'}://${endpoint}`\n }\n return insecure ? endpoint.replace(/^https:\\/\\//i, 'http://') : endpoint\n}\n\nfunction grpcMetadata(cfg: ResolvedConfig): Metadata {\n const metadata = new Metadata()\n metadata.set(cfg.authHeader, cfg.apiKey)\n return metadata\n}\n\nfunction httpHeaders(cfg: ResolvedConfig): Record<string, string> {\n return { [cfg.authHeader]: cfg.apiKey }\n}\n\n/**\n * Builds the three signal-specific OTLP exporters for a single Client.\n * Each is independently constructed so a failure building one doesn't\n * necessarily prevent the others.\n */\nexport function buildExporters(cfg: ResolvedConfig): Exporters {\n if (cfg.transport === 'grpc') {\n const url = withScheme(cfg.endpoint, cfg.insecure)\n const metadata = grpcMetadata(cfg)\n return {\n trace: new OTLPTraceExporterGrpc({ url, metadata, timeoutMillis: cfg.exportTimeoutMs }),\n metric: new OTLPMetricExporterGrpc({ url, metadata, timeoutMillis: cfg.exportTimeoutMs }),\n log: new OTLPLogExporterGrpc({ url, metadata, timeoutMillis: cfg.exportTimeoutMs }),\n }\n }\n\n const base = withScheme(cfg.endpoint, cfg.insecure).replace(/\\/+$/, '')\n const headers = httpHeaders(cfg)\n return {\n trace: new OTLPTraceExporterHttp({\n url: `${base}/v1/traces`,\n headers,\n timeoutMillis: cfg.exportTimeoutMs,\n }),\n metric: new OTLPMetricExporterHttp({\n url: `${base}/v1/metrics`,\n headers,\n timeoutMillis: cfg.exportTimeoutMs,\n }),\n log: new OTLPLogExporterHttp({\n url: `${base}/v1/logs`,\n headers,\n timeoutMillis: cfg.exportTimeoutMs,\n }),\n }\n}\n","import { readFileSync } from 'node:fs'\n\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport type { Resource } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'\n\nimport type { ResolvedConfig } from './options.js'\n\n/** This package's own name, reported on `telemetry.sdk.name`. */\nconst SDK_NAME = '@getargvio/argvio'\n\n/**\n * Returns this package's own version, read from its `package.json` at\n * runtime rather than hardcoded, so the reported value always matches\n * what a vendor actually installed.\n */\nfunction sdkVersion(): string {\n try {\n const pkgUrl = new URL('../package.json', import.meta.url)\n const pkg = JSON.parse(readFileSync(pkgUrl, 'utf8')) as { version?: string }\n return pkg.version ?? 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\nexport function buildResource(cfg: ResolvedConfig): Resource {\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: cfg.cliName,\n [ATTR_SERVICE_VERSION]: cfg.cliVersion,\n 'telemetry.sdk.name': SDK_NAME,\n 'telemetry.sdk.version': sdkVersion(),\n 'telemetry.sdk.language': 'nodejs',\n ...cfg.resourceAttributes,\n })\n}\n","/**\n * Sentinel errors thrown/rejected internally. Never thrown across the\n * public API surface itself (every exported method swallows errors via\n * {@link safeRun}/{@link safeRunAsync} — see safety.ts) but used as\n * rejection reasons a {@link ConsentProvider} chain can inspect or a\n * vendor can `instanceof`-check if they care why resolution failed.\n */\n\nexport class ArgvioError extends Error {\n constructor(message: string) {\n super(`argvio: ${message}`)\n this.name = 'ArgvioError'\n }\n}\n\nexport const errNoProviderResolved = new ArgvioError('no consent provider resolved a tier')\nexport const errNoConsentFile = new ArgvioError('no consent config file path resolved')\nexport const errUnknownTierValue = new ArgvioError('unknown tier value in consent config')\n","import { Tier } from './tier.js'\nimport type { ConsentProvider } from './consent.js'\nimport { errNoProviderResolved } from './errors.js'\n\n/**\n * Environment variables commonly set to a truthy value by CI systems.\n * Presence of any of these (with a non-empty, non-\"false\"/\"0\" value) is\n * treated as \"running in CI\".\n */\nconst CI_ENV_VARS = [\n 'CI',\n 'CONTINUOUS_INTEGRATION',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'CIRCLECI',\n 'TRAVIS',\n 'JENKINS_URL',\n 'BUILDKITE',\n 'TEAMCITY_VERSION',\n 'APPVEYOR',\n 'TF_BUILD', // Azure Pipelines\n 'DRONE', // Drone CI\n 'CODEBUILD_BUILD_ID',\n 'BITBUCKET_BUILD_NUMBER',\n] as const\n\n/** Reports whether the current process appears to be running inside a CI system. */\nexport function isCI(): boolean {\n return CI_ENV_VARS.some((name) => {\n const value = process.env[name]\n return value !== undefined && value !== '' && value !== 'false' && value !== '0'\n })\n}\n\n/**\n * Reports whether the `DO_NOT_TRACK` environment variable\n * (https://do-not-track.dev) requests telemetry be disabled. Any value\n * other than unset, empty, \"0\", or \"false\" is treated as a request.\n */\nexport function isDoNotTrackRequested(): boolean {\n const value = process.env['DO_NOT_TRACK']\n if (value === undefined) return false\n return value !== '' && value !== '0' && value !== 'false'\n}\n\n/**\n * A {@link ConsentProvider} that caps the resolved tier at\n * `Tier.Anonymous` when the process appears to be running in a CI\n * environment. It resolves `Tier.Anonymous` in that case and rejects\n * otherwise, so it's meant to be placed ahead of other providers in a\n * {@link chainProviders} call — it \"wins\" only when CI is detected,\n * deferring to the next provider otherwise.\n *\n * Reasoning: CI runs are usually unattended, share no single human\n * user's stored consent preference, and can run at high volume (every\n * commit, every matrix leg). We still allow anonymous-tier telemetry\n * (e.g. install/build counts) by default rather than fully disabling,\n * because that data has real product value and carries no identifying\n * fields at `Tier.Anonymous` by construction. Vendors who want CI runs\n * fully silent can pass `disabled: true` or check `isCI()` themselves.\n *\n * `DO_NOT_TRACK` is handled separately (see {@link isDoNotTrackRequested})\n * and is enforced by the Client as a full disable, not a tier cap: it's\n * a standing, cross-tool opt-out signal a user or environment sets\n * deliberately, so it's honored as \"no telemetry\" rather than \"least\n * telemetry\".\n */\nexport class EnvConsentProvider implements ConsentProvider {\n resolve(): Tier {\n if (isCI()) return Tier.Anonymous\n throw errNoProviderResolved\n }\n}\n","import { randomBytes } from 'node:crypto'\n\n/**\n * Attribute keys used on emitted signals. Exported so vendors and tests\n * can assert on them without relying on string literals staying in\n * sync.\n *\n * TODO(schema): these keys are provisional and must be checked against\n * the authoritative server-side allowlist before v0.1.0 ships.\n */\nexport const AttrCommandPath = 'cli.command.path'\nexport const AttrCommandFlags = 'cli.command.flags'\nexport const AttrExitCode = 'cli.command.exit_code'\nexport const AttrHelpUsed = 'cli.command.help_used'\nexport const AttrSessionId = 'cli.session.id'\nexport const AttrErrorCategory = 'cli.error.category'\n/** TierOptIn only. */\nexport const AttrErrorMessage = 'cli.error.message'\n/** TierOptIn only. */\nexport const AttrErrorStack = 'cli.error.stack'\n\n/** The name of the histogram instrument `recordLatency` records to (unit: milliseconds). */\nexport const MetricCommandDuration = 'cli.command.duration'\n\n/** A random, non-persistent per-process session correlation ID. Not a user or device identifier. */\nexport function newSessionId(): string {\n try {\n return randomBytes(16).toString('hex')\n } catch {\n return ''\n }\n}\n","/**\n * No bug inside this SDK should ever throw into the host CLI. `safeRun`\n * is a try/catch guard installed at the top of every exported Client\n * method.\n */\n\n/** Prints recovered-error diagnostics to stderr. Off by default. */\nexport const ARGVIO_DEBUG = process.env['ARGVIO_DEBUG'] === '1'\n\n/** A snapshot of in-process telemetry-about-telemetry: never sent over the network. */\nexport interface Stats {\n /** Records dropped because a batch queue was full rather than blocking the host CLI. */\n queueOverflowDropped: number\n /** Records/fields dropped because the resolved consent tier didn't permit them. */\n belowTierDropped: number\n /** Internal errors recovered from; should always be zero. */\n recoveredErrors: number\n}\n\nexport class DroppedCounters {\n queueOverflow = 0\n belowTierCeil = 0\n recoveredErrors = 0\n\n snapshot(): Stats {\n return {\n queueOverflowDropped: this.queueOverflow,\n belowTierDropped: this.belowTierCeil,\n recoveredErrors: this.recoveredErrors,\n }\n }\n}\n\nfunction logRecovered(err: unknown): void {\n if (!ARGVIO_DEBUG) return\n const msg = err instanceof Error ? err.message : '(non-error thrown value)'\n process.stderr.write(`argvio: recovered internal error: ${msg}\\n`)\n}\n\n/** Runs `fn`, guaranteeing no synchronous throw escapes. */\nexport function safeRun(fn: () => void, counters?: DroppedCounters): void {\n try {\n fn()\n } catch (err) {\n if (counters) counters.recoveredErrors++\n logRecovered(err)\n }\n}\n","import type { Attributes, Counter, Histogram } from '@opentelemetry/api'\nimport { SeverityNumber } from '@opentelemetry/api-logs'\nimport type { Logger } from '@opentelemetry/api-logs'\nimport { LoggerProvider, BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'\nimport { NodeTracerProvider, BatchSpanProcessor } from '@opentelemetry/sdk-trace-node'\n\nimport type { ClientOptions } from './options.js'\nimport { resolveConfig } from './options.js'\nimport { buildExporters } from './otlp.js'\nimport { buildResource } from './resource.js'\nimport { isDoNotTrackRequested } from './consentEnv.js'\nimport { Tier, tierAllows, tierToString, isValidTier, RESOURCE_ATTR_TIER } from './tier.js'\nimport type { ErrorCategory } from './tier.js'\nimport { ErrorCategory as ErrorCategoryValues, isValidErrorCategory } from './tier.js'\nimport {\n AttrCommandFlags,\n AttrCommandPath,\n AttrErrorCategory,\n AttrErrorMessage,\n AttrErrorStack,\n AttrExitCode,\n AttrHelpUsed,\n AttrSessionId,\n MetricCommandDuration,\n newSessionId,\n} from './taxonomy.js'\nimport type { Stats } from './safety.js'\nimport { ARGVIO_DEBUG, DroppedCounters, safeRun } from './safety.js'\n\n/**\n * Identifies this SDK to the OTel SDKs it wraps (meter/logger name),\n * distinct from the CLI's own resource attributes.\n */\nconst INSTRUMENTATION_NAME = '@getargvio/argvio'\n\ntype Job = () => void | Promise<void>\n\n/**\n * A small in-process bounded async queue: `push` never blocks the\n * caller, and drops (counted, never applying backpressure) when full.\n * Jobs run on subsequent ticks via `setImmediate`, off the caller's\n * synchronous call stack.\n */\nclass JobQueue {\n private readonly items: Job[] = []\n private draining = false\n\n constructor(\n private readonly maxSize: number,\n private readonly counters: DroppedCounters,\n ) {}\n\n push(job: Job): void {\n if (this.items.length >= this.maxSize) {\n this.counters.queueOverflow++\n return\n }\n this.items.push(job)\n this.scheduleDrain()\n }\n\n /**\n * Enqueues a control signal (e.g. a drain sentinel) bypassing the size\n * bound, so `waitForDrain` waits for genuine backlog instead of\n * silently racing ahead when the queue happens to be full.\n */\n private pushControl(job: Job): void {\n this.items.push(job)\n this.scheduleDrain()\n }\n\n private scheduleDrain(): void {\n if (this.draining) return\n this.draining = true\n setImmediate(() => {\n void this.drain()\n })\n }\n\n private async drain(): Promise<void> {\n for (;;) {\n const job = this.items.shift()\n if (!job) break\n try {\n await job()\n } catch (err) {\n this.counters.recoveredErrors++\n if (ARGVIO_DEBUG) {\n const msg = err instanceof Error ? err.message : '(non-error thrown value)'\n process.stderr.write(`argvio: recovered internal error: ${msg}\\n`)\n }\n }\n }\n this.draining = false\n }\n\n /** Resolves once every job enqueued before this call has finished executing, or `timeoutMs` elapses. */\n async waitForDrain(timeoutMs: number): Promise<void> {\n const done = new Promise<void>((resolve) => {\n this.pushControl(() => {\n resolve()\n })\n })\n await withTimeout(done, timeoutMs)\n }\n}\n\nasync function withTimeout(promise: Promise<void>, timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, timeoutMs)\n })\n try {\n await Promise.race([promise, timeout])\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\ninterface ClientParams {\n disabled: boolean\n initError: Error | null\n tier: Tier\n queueSize: number\n shutdownTimeoutMs: number\n tracerProvider?: NodeTracerProvider\n meterProvider?: MeterProvider\n loggerProvider?: LoggerProvider\n logger?: Logger\n latencyHist?: Histogram\n invocationsCounter?: Counter\n sessionsCounter?: Counter\n errorEventsCounter?: Counter\n}\n\n/**\n * The entry point for emitting telemetry. Every method is safe to call\n * on a disabled Client (explicitly disabled, `DO_NOT_TRACK`/`ARGVIO_DISABLED`,\n * or degraded due to a construction error) — vendors never need to\n * check `disabled` before using a Client.\n *\n * Construct via {@link createClient}, never directly.\n */\nexport class Client {\n readonly tier: Tier\n readonly disabled: boolean\n /** Set if construction encountered a problem; the Client still degrades to a safe disabled no-op. */\n readonly initError: Error | null\n\n private readonly counters = new DroppedCounters()\n private readonly queue: JobQueue\n private readonly shutdownTimeoutMs: number\n private shuttingDown = false\n private shutdownStarted = false\n private sessionId: string | undefined\n\n private readonly tracerProvider: NodeTracerProvider | undefined\n private readonly meterProvider: MeterProvider | undefined\n private readonly loggerProvider: LoggerProvider | undefined\n private readonly logger: Logger | undefined\n private readonly latencyHist: Histogram | undefined\n private readonly invocationsCounter: Counter | undefined\n private readonly sessionsCounter: Counter | undefined\n private readonly errorEventsCounter: Counter | undefined\n\n /** @internal use {@link createClient} */\n constructor(params: ClientParams) {\n this.disabled = params.disabled\n this.initError = params.initError\n this.tier = params.tier\n this.shutdownTimeoutMs = params.shutdownTimeoutMs\n this.queue = new JobQueue(params.queueSize, this.counters)\n this.tracerProvider = params.tracerProvider\n this.meterProvider = params.meterProvider\n this.loggerProvider = params.loggerProvider\n this.logger = params.logger\n this.latencyHist = params.latencyHist\n this.invocationsCounter = params.invocationsCounter\n this.sessionsCounter = params.sessionsCounter\n this.errorEventsCounter = params.errorEventsCounter\n }\n\n private enabled(): boolean {\n return !this.disabled && !this.shuttingDown\n }\n\n /** A snapshot of in-process counters about dropped records. Never sent over the network. */\n stats(): Stats {\n return this.counters.snapshot()\n }\n\n private gate(required: Tier): boolean {\n if (!this.enabled()) return false\n if (!tierAllows(this.tier, required)) {\n this.counters.belowTierCeil++\n return false\n }\n return true\n }\n\n private tierAttr(): Attributes {\n return { [RESOURCE_ATTR_TIER]: tierToString(this.tier) }\n }\n\n private emitEvent(name: string, severity: SeverityNumber, attributes: Attributes = {}): void {\n this.queue.push(() => {\n this.logger?.emit({\n eventName: name,\n timestamp: Date.now(),\n severityNumber: severity,\n attributes: { ...this.tierAttr(), ...attributes },\n })\n })\n }\n\n /**\n * Lazily generates a session correlation ID at `Tier.Full`+. A random,\n * non-persistent identifier scoped to a single process invocation —\n * not a user or device identifier.\n */\n private ensureSessionId(): string {\n if (!tierAllows(this.tier, Tier.Full)) return ''\n if (this.sessionId === undefined) {\n this.sessionId = newSessionId()\n }\n return this.sessionId\n }\n\n /**\n * Records the start of a CLI process session. Call once, as early as\n * possible. At `Tier.Anonymous` this only increments an aggregate\n * session counter. At `Tier.Basic`+ it also emits a `cli.session_start`\n * event. At `Tier.Full`+ the event carries a per-process session\n * correlation ID.\n */\n recordSessionStart(): void {\n safeRun(() => {\n if (!this.enabled()) return\n this.queue.push(() => {\n this.sessionsCounter?.add(1, this.tierAttr())\n })\n if (!tierAllows(this.tier, Tier.Basic)) return\n const attrs: Attributes = {}\n const id = this.ensureSessionId()\n if (id) attrs[AttrSessionId] = id\n this.emitEvent('cli.session_start', SeverityNumber.INFO, attrs)\n }, this.counters)\n }\n\n /** Records the end of a CLI process session. Call once, symmetric with {@link recordSessionStart}. */\n recordSessionEnd(): void {\n safeRun(() => {\n if (!this.enabled() || !tierAllows(this.tier, Tier.Basic)) return\n const attrs: Attributes = {}\n const id = this.ensureSessionId()\n if (id) attrs[AttrSessionId] = id\n this.emitEvent('cli.session_end', SeverityNumber.INFO, attrs)\n }, this.counters)\n }\n\n /**\n * Records that a command began executing. `commandPath` should be the\n * full command path (e.g. `\"mycli sub subsub\"`), not just the leaf\n * command name. `flagNames` is the list of flag *names* the user set —\n * never flag values, which this SDK never accepts anywhere in the\n * taxonomy.\n *\n * At `Tier.Anonymous` this only increments an aggregate invocation\n * counter with no path/flag detail. At `Tier.Basic`+ the full command\n * path and flag names are included.\n */\n recordCommandInvocation(commandPath: string, flagNames: readonly string[] = []): void {\n safeRun(() => {\n if (!this.enabled()) return\n this.queue.push(() => {\n this.invocationsCounter?.add(1, this.tierAttr())\n })\n if (!tierAllows(this.tier, Tier.Basic)) return\n const attrs: Attributes = { [AttrCommandPath]: commandPath }\n if (flagNames.length > 0) attrs[AttrCommandFlags] = [...flagNames]\n this.emitEvent('cli.command_invocation', SeverityNumber.INFO, attrs)\n }, this.counters)\n }\n\n /**\n * Records the exit code a command finished with. Pass `\"\"` for\n * `commandPath` if unknown (e.g. a single-command CLI). At\n * `Tier.Anonymous` the exit code is recorded without a command path.\n * At `Tier.Basic`+ the command path is included.\n */\n recordExitCode(commandPath: string, code: number): void {\n safeRun(() => {\n if (!this.gate(Tier.Anonymous)) return\n const attrs: Attributes = { [AttrExitCode]: code }\n if (tierAllows(this.tier, Tier.Basic) && commandPath) {\n attrs[AttrCommandPath] = commandPath\n }\n const severity = code !== 0 ? SeverityNumber.WARN : SeverityNumber.INFO\n this.emitEvent('cli.exit_code', severity, attrs)\n }, this.counters)\n }\n\n /**\n * Records how long a command took to execute, in milliseconds, on a\n * histogram (`cli.command.duration`). Available at every tier.\n */\n recordLatency(commandPath: string, durationMs: number): void {\n safeRun(() => {\n if (!this.gate(Tier.Anonymous)) return\n const attrs: Attributes = { ...this.tierAttr() }\n if (tierAllows(this.tier, Tier.Basic) && commandPath) {\n attrs[AttrCommandPath] = commandPath\n }\n this.queue.push(() => {\n this.latencyHist?.record(durationMs, attrs)\n })\n }, this.counters)\n }\n\n /** Records that a command's help output was requested (`-h`/`--help` or an explicit help command). */\n recordHelpFlagUsage(commandPath: string): void {\n safeRun(() => {\n if (!this.gate(Tier.Anonymous)) return\n const attrs: Attributes = { [AttrHelpUsed]: true }\n if (tierAllows(this.tier, Tier.Basic) && commandPath) {\n attrs[AttrCommandPath] = commandPath\n }\n this.emitEvent('cli.help_flag_used', SeverityNumber.INFO, attrs)\n }, this.counters)\n }\n\n /**\n * Records that a command failed with an error, classified by\n * `category` rather than its raw message or stack trace — this is\n * deliberately the only error-recording capability available below\n * `Tier.OptIn`. Raw error detail is only reachable via {@link optIn}.\n *\n * Requires `Tier.Full`+; at lower tiers this is a no-op (counted in\n * `stats().belowTierDropped`).\n */\n recordError(commandPath: string, category: ErrorCategory = ErrorCategoryValues.Unknown): void {\n safeRun(() => {\n if (!this.gate(Tier.Full)) return\n const cat = isValidErrorCategory(category) ? category : ErrorCategoryValues.Unknown\n const attrs: Attributes = { [AttrErrorCategory]: cat }\n if (commandPath) attrs[AttrCommandPath] = commandPath\n this.queue.push(() => {\n this.errorEventsCounter?.add(1, { ...this.tierAttr(), [AttrErrorCategory]: cat })\n })\n this.emitEvent('cli.error', SeverityNumber.ERROR, attrs)\n }, this.counters)\n }\n\n /**\n * Returns an {@link OptInScope} if, and only if, this Client's resolved\n * consent tier is `Tier.OptIn`; otherwise returns `undefined`. There is\n * no other way to reach raw error detail (message, stack trace)\n * anywhere in this package — it's structurally impossible to pass that\n * data through {@link recordError}'s signature.\n */\n optIn(): OptInScope | undefined {\n if (this.enabled() && this.tier === Tier.OptIn) return new OptInScope(this)\n return undefined\n }\n\n /** @internal called only by {@link OptInScope}. */\n _recordErrorDetail(commandPath: string, err: Error, stack?: string): void {\n safeRun(() => {\n if (!this.gate(Tier.OptIn)) return\n const attrs: Attributes = { [AttrErrorMessage]: err.message }\n if (commandPath) attrs[AttrCommandPath] = commandPath\n if (stack) attrs[AttrErrorStack] = stack\n this.emitEvent('cli.error_detail', SeverityNumber.ERROR, attrs)\n }, this.counters)\n }\n\n /**\n * Blocks until all telemetry queued so far has been handed to the\n * exporters and an export attempt has completed, or `timeoutMs`\n * elapses, whichever comes first. Safe to call on a disabled Client\n * (a no-op).\n */\n async flush(timeoutMs: number = this.shutdownTimeoutMs): Promise<void> {\n if (!this.enabled()) return\n await this.queue.waitForDrain(timeoutMs)\n await withTimeout(\n Promise.all(\n [\n this.tracerProvider?.forceFlush(),\n this.meterProvider?.forceFlush(),\n this.loggerProvider?.forceFlush(),\n ].filter((p): p is Promise<void> => Boolean(p)),\n ).then(() => undefined),\n timeoutMs,\n )\n }\n\n /**\n * Flushes any queued telemetry (best-effort, bounded by `timeoutMs`)\n * and releases all background resources. After `shutdown`, the Client\n * permanently behaves as a disabled no-op. Safe to call on a disabled\n * Client, and safe to call more than once.\n */\n async shutdown(timeoutMs: number = this.shutdownTimeoutMs): Promise<void> {\n if (this.disabled || this.shutdownStarted) return\n this.shutdownStarted = true\n this.shuttingDown = true\n\n await this.queue.waitForDrain(timeoutMs)\n await withTimeout(\n Promise.all(\n [\n this.tracerProvider?.shutdown(),\n this.meterProvider?.shutdown(),\n this.loggerProvider?.shutdown(),\n ].filter((p): p is Promise<void> => Boolean(p)),\n ).then(() => undefined),\n timeoutMs,\n )\n }\n}\n\n/**\n * Exposes telemetry capabilities that require the user's explicit\n * `Tier.OptIn` consent, structurally separated from {@link Client} so\n * that raw error content (messages, stack traces) can never be passed\n * through a lower-tier code path by mistake or misuse.\n */\nexport class OptInScope {\n constructor(private readonly client: Client) {}\n\n /** Records an error's message at full fidelity. */\n recordErrorDetail(commandPath: string, err: Error): void {\n this.client._recordErrorDetail(commandPath, err)\n }\n\n /** Identical to {@link recordErrorDetail} but also attaches a raw stack trace. */\n recordErrorDetailWithStack(commandPath: string, err: Error, stack: string): void {\n this.client._recordErrorDetail(commandPath, err, stack)\n }\n}\n\nfunction resolveConsentTier(cfg: ReturnType<typeof resolveConfig>): Tier {\n if (!cfg.consentProvider) return cfg.defaultTier\n try {\n const tier = cfg.consentProvider.resolve()\n return isValidTier(tier) ? tier : cfg.defaultTier\n } catch {\n return cfg.defaultTier\n }\n}\n\nfunction disabledClient(initError: Error | null = null): Client {\n return new Client({\n disabled: true,\n initError,\n tier: Tier.Anonymous,\n queueSize: 0,\n shutdownTimeoutMs: 0,\n })\n}\n\n/**\n * Constructs a {@link Client}. `apiKey`, `cliName`, and `cliVersion` are\n * always required; everything else has a sane default and is set via\n * `options`.\n *\n * `createClient` is synchronous and **never throws**: if construction\n * encounters a problem (e.g. the exporter transport can't be built, or a\n * `ConsentProvider` throws), it returns a Client already degraded to a\n * disabled no-op, with `client.initError` describing why. Callers may\n * inspect `initError` but are not required to before using the returned\n * Client safely.\n *\n * `createClient` resolves consent through a synchronous\n * {@link ConsentProvider} — see that interface's doc comment for why\n * resolution has to be synchronous on Node's single-threaded event loop.\n */\nexport function createClient(\n apiKey: string,\n cliName: string,\n cliVersion: string,\n options: ClientOptions = {},\n): Client {\n try {\n const cfg = resolveConfig(apiKey, cliName, cliVersion, options)\n\n if (cfg.disabled || process.env['ARGVIO_DISABLED'] === '1' || isDoNotTrackRequested()) {\n return disabledClient()\n }\n\n const tier = resolveConsentTier(cfg)\n const exporters = buildExporters(cfg)\n const resource = buildResource(cfg)\n\n const tracerProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [\n new BatchSpanProcessor(exporters.trace, {\n maxQueueSize: cfg.queueSize,\n exportTimeoutMillis: cfg.exportTimeoutMs,\n }),\n ],\n })\n const meterProvider = new MeterProvider({\n resource,\n readers: [\n new PeriodicExportingMetricReader({\n exporter: exporters.metric,\n exportTimeoutMillis: cfg.exportTimeoutMs,\n }),\n ],\n })\n const loggerProvider = new LoggerProvider({\n resource,\n processors: [\n new BatchLogRecordProcessor({\n exporter: exporters.log,\n maxQueueSize: cfg.queueSize,\n exportTimeoutMillis: cfg.exportTimeoutMs,\n }),\n ],\n })\n\n const meter = meterProvider.getMeter(INSTRUMENTATION_NAME)\n const logger = loggerProvider.getLogger(INSTRUMENTATION_NAME)\n\n return new Client({\n disabled: false,\n initError: null,\n tier,\n queueSize: cfg.queueSize,\n shutdownTimeoutMs: cfg.shutdownTimeoutMs,\n tracerProvider,\n meterProvider,\n loggerProvider,\n logger,\n latencyHist: meter.createHistogram(MetricCommandDuration, {\n unit: 'ms',\n description: 'Duration of a CLI command invocation.',\n }),\n invocationsCounter: meter.createCounter('cli.invocations', {\n description: 'Count of CLI command invocations.',\n }),\n sessionsCounter: meter.createCounter('cli.sessions', {\n description: 'Count of CLI process sessions.',\n }),\n errorEventsCounter: meter.createCounter('cli.errors', {\n description: 'Count of recorded CLI errors.',\n }),\n })\n } catch (err) {\n return disabledClient(toError(err))\n }\n}\n","import { Tier, isValidTier } from './tier.js'\nimport { errNoProviderResolved } from './errors.js'\n\n/**\n * Resolves the consent tier that should be used for the current\n * process. Consulted once per {@link Client}, synchronously, at\n * construction time (cached for the process lifetime — consent is not\n * expected to change mid-invocation of a short-lived CLI command).\n *\n * `resolve` here is **synchronous**: Node's single-threaded event loop\n * has no way to synchronously await a Promise, and `createClient` must\n * return a fully\n * resolved, usable Client without an async round-trip (see the \"why\n * createClient is synchronous\" note in client.ts). Implementations must\n * therefore be fast and local only — env vars, an already-loaded config\n * object, a synchronous local file read — never network I/O. A provider\n * that throws is treated identically to `Tier.Anonymous` (fail closed).\n */\nexport interface ConsentProvider {\n resolve(): Tier\n}\n\n/**\n * A {@link ConsentProvider} that always resolves to a fixed tier. Useful\n * for tests, for vendors who resolve consent themselves before\n * constructing the Client, or as a fallback wrapped by\n * {@link chainProviders}.\n */\nexport class StaticProvider implements ConsentProvider {\n constructor(private readonly tier: Tier) {}\n\n resolve(): Tier {\n return isValidTier(this.tier) ? this.tier : Tier.Anonymous\n }\n}\n\n/**\n * A {@link ConsentProvider} that always resolves to `Tier.Anonymous`. It\n * exists as an explicit, self-documenting choice distinct from \"a\n * provider that happens to return anonymous\".\n */\nexport class DisabledProvider implements ConsentProvider {\n resolve(): Tier {\n return Tier.Anonymous\n }\n}\n\n/**\n * Returns a {@link ConsentProvider} that tries each provider in order\n * and returns the first successful (non-throwing) result. If all\n * providers throw, it throws {@link errNoProviderResolved} (the caller\n * treats that as `Tier.Anonymous`, same as any other thrown error). Lets\n * a vendor compose, e.g., \"env override, then config file, then\n * anonymous default\" without writing that logic themselves.\n */\nexport function chainProviders(\n ...providers: ReadonlyArray<ConsentProvider | null | undefined>\n): ConsentProvider {\n return {\n resolve(): Tier {\n for (const provider of providers) {\n if (!provider) continue\n try {\n return provider.resolve()\n } catch {\n continue\n }\n }\n throw errNoProviderResolved\n },\n }\n}\n","import { homedir } from 'node:os'\nimport { join, dirname } from 'node:path'\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\n\nimport type { Tier } from './tier.js'\nimport { isValidTier, parseTier, tierToString } from './tier.js'\nimport type { ConsentProvider } from './consent.js'\nimport { errNoConsentFile, errUnknownTierValue } from './errors.js'\n\n/**\n * Replicates Go's `os.UserConfigDir()` semantics without adding a\n * dependency: `$XDG_CONFIG_HOME` (or `~/.config`) on Linux/other,\n * `~/Library/Application Support` on macOS, `%APPDATA%` on Windows.\n */\nfunction userConfigDir(): string | undefined {\n switch (process.platform) {\n case 'win32':\n return process.env['APPDATA']\n case 'darwin':\n return join(homedir(), 'Library', 'Application Support')\n default:\n return process.env['XDG_CONFIG_HOME'] || join(homedir(), '.config')\n }\n}\n\nfunction defaultConsentPath(cliName: string): string | undefined {\n const dir = userConfigDir()\n if (!dir) return undefined\n return join(dir, cliName || 'argvio', 'argvio-consent.json')\n}\n\nexport interface FileConsentProviderOptions {\n /** Overrides the default config file location entirely. */\n path?: string\n}\n\ninterface ConsentFileContents {\n tier?: string\n}\n\n/**\n * The reference {@link ConsentProvider} implementation: reads a small\n * JSON file at a conventional per-CLI config location, namespaced under\n * the vendor's own CLI name to avoid collisions between unrelated CLIs\n * that both embed this SDK.\n *\n * Reads/writes are synchronous (see {@link ConsentProvider}'s doc\n * comment for why) — a small local JSON file read is cheap enough that\n * this doesn't meaningfully block startup.\n *\n * Use `options.path` to override the location entirely (e.g. a vendor\n * that already has its own config file and wants to store the tier\n * alongside it under a different mechanism should implement their own\n * {@link ConsentProvider} instead).\n */\nexport class FileConsentProvider implements ConsentProvider {\n /** The resolved config file path (after defaults/overrides), primarily for diagnostics and tests. */\n readonly path: string | undefined\n\n constructor(cliName: string, options: FileConsentProviderOptions = {}) {\n this.path = options.path || defaultConsentPath(cliName)\n }\n\n /**\n * A missing file, unreadable file, or malformed contents all throw\n * synchronously, so callers should place `FileConsentProvider` inside\n * `chainProviders` with a sane fallback (e.g.\n * `new StaticProvider(Tier.Anonymous)`).\n */\n resolve(): Tier {\n if (!this.path) throw errNoConsentFile\n const data = readFileSync(this.path, 'utf8')\n const parsed = JSON.parse(data) as ConsentFileContents\n const tier = parseTier(parsed.tier ?? '')\n if (tier === undefined) throw errUnknownTierValue\n return tier\n }\n\n /**\n * Persists `tier` as the chosen consent tier, creating the parent\n * directory if needed. Intended for use by a vendor's first-run\n * consent prompt. Does not itself enforce any tier ceiling — it's the\n * vendor's own UX writing the user's explicit choice.\n */\n store(tier: Tier): void {\n if (!this.path) throw errNoConsentFile\n if (!isValidTier(tier)) throw errUnknownTierValue\n mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 })\n const contents: ConsentFileContents = { tier: tierToString(tier) }\n writeFileSync(this.path, JSON.stringify(contents), { mode: 0o600 })\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/tier.ts","../src/errors.ts","../src/consentFile.ts","../src/options.ts","../src/otlp.ts","../src/consentEnv.ts","../src/resource.ts","../src/taxonomy.ts","../src/safety.ts","../src/client.ts","../src/consent.ts"],"names":["OTLPTraceExporterGrpc","OTLPMetricExporterGrpc","OTLPLogExporterGrpc","OTLPTraceExporterHttp","OTLPMetricExporterHttp","OTLPLogExporterHttp","readFileSync","mkdirSync","dirname","writeFileSync"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgBO,IAAM,IAAA,GAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAKlB,SAAA,EAAW,CAAA;AAAA;AAAA,EAEX,KAAA,EAAO,CAAA;AAAA;AAAA,EAEP,IAAA,EAAM,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMN,KAAA,EAAO;AACT;AAKO,IAAM,kBAAA,GAAqB;AAElC,IAAM,YAAA,GAAqC;AAAA,EACzC,CAAC,IAAA,CAAK,SAAS,GAAG,WAAA;AAAA,EAClB,CAAC,IAAA,CAAK,KAAK,GAAG,OAAA;AAAA,EACd,CAAC,IAAA,CAAK,IAAI,GAAG,MAAA;AAAA,EACb,CAAC,IAAA,CAAK,KAAK,GAAG;AAChB,CAAA;AAGO,SAAS,aAAa,IAAA,EAAoB;AAC/C,EAAA,OAAO,YAAA,CAAa,IAAI,CAAA,IAAK,SAAA;AAC/B;AAQO,SAAS,UAAU,KAAA,EAAiC;AACzD,EAAA,QAAQ,KAAA;AAAO,IACb,KAAK,WAAA;AACH,MAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IACd,KAAK,OAAA;AACH,MAAA,OAAO,IAAA,CAAK,KAAA;AAAA,IACd,KAAK,MAAA;AACH,MAAA,OAAO,IAAA,CAAK,IAAA;AAAA,IACd,KAAK,YA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A,IAAA,GAAA,IAAA;AAAA,EAAa;AAAA,EAAb,IAAA;AAAA,EAE7B,OAAA,GAAgB;AACd,IAAA,OAAO,YAAY,IAAA,CAAK,IAAI,CAAA,GAAI,IAAA,CAAK,OAAO,IAAA,CAAK,SAAA;AAAA,EACnD;AACF;AAOO,IAAM,mBAAN,MAAkD;AAAA,EACvD,OAAA,GAAgB;AACd,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EACd;AACF;AAUO,SAAS,kBACX,SAAA,EACc;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,GAAgB;AACd,MAAA,KAAA,MAAW,YAAY,SAAA,EAAW;AAChC,QAAA,IAAI,CAAC,QAAA,EAAU;AACf,QAAA,IAAI;AACF,UAAA,OAAO,SAAS,OAAA,EAAQ;AAAA,QAC1B,CAAA,CAAA,MAAQ;AACN,UAAA;AAAA,QACF;AAAA,MACF;AACA,MAAA,MAAM,qBAAA;AAAA,IACR;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * The consent tier a CLI user (or their organization) has granted for\n * telemetry collection. Gates both which `record*` calls are allowed to\n * emit which fields, and the value sent on the `cli.analytics.tier`\n * resource attribute, which the public ingest server re-validates and\n * enforces as a backstop.\n *\n * Tiers are strictly ordered: each tier is a superset of the fields\n * allowed at the tier below it. Compare with plain `<`/`<=`/`>=` — the\n * numeric values are significant, not just distinct enum tags.\n *\n * The wire string values in {@link tierToString} MUST match the\n * consent_tiers names in the `public` server's allowlist\n * (schema/allowlist/v1.yaml in getargvio/argvio) exactly, or the server\n * rejects the record.\n */\nexport const Tier = {\n /**\n * No persistent or cross-invocation identifiers: command name, exit\n * code, duration, CLI version, OS/arch and CI environment only.\n */\n Anonymous: 0,\n /** Adds an opaque per-process session ID, an opaque per-install ID, flag names (never values), and classified (not raw) error types. */\n Basic: 1,\n /** Reserved: the server allowlist permits some fields here, but this SDK sends nothing beyond `Tier.Basic`. */\n Full: 2,\n /**\n * The explicit opt-in tier: raw error detail (stack traces, messages)\n * and any other field the allowlist marks opt-in-only. Never the\n * default; a vendor or user must positively select it.\n */\n OptIn: 3,\n} as const\n\nexport type Tier = (typeof Tier)[keyof typeof Tier]\n\n/** The OTel resource attribute key the tier is reported under. */\nexport const RESOURCE_ATTR_TIER = 'cli.analytics.tier'\n\nconst TIER_STRINGS: Record<Tier, string> = {\n [Tier.Anonymous]: 'anonymous',\n [Tier.Basic]: 'basic',\n [Tier.Full]: 'full',\n [Tier.OptIn]: 'optin_plus',\n}\n\n/** Returns the wire value sent on the `cli.analytics.tier` resource attribute. */\nexport function tierToString(tier: Tier): string {\n return TIER_STRINGS[tier] ?? 'unknown'\n}\n\n/**\n * Parses a wire tier string (as produced by {@link tierToString}) back\n * into a {@link Tier}. Returns `undefined` if `value` does not match a\n * known tier — callers should fail closed to `Tier.Anonymous` in that\n * case, never assume the highest tier.\n */\nexport function parseTier(value: string): Tier | undefined {\n switch (value) {\n case 'anonymous':\n return Tier.Anonymous\n case 'basic':\n return Tier.Basic\n case 'full':\n return Tier.Full\n case 'optin_plus':\n case 'opt-in': // older SDKs' wire value, still accepted from consent files\n return Tier.OptIn\n default:\n return undefined\n }\n}\n\n/** Reports whether `value` is a known {@link Tier}. */\nexport function isValidTier(value: number): value is Tier {\n return (\n value === Tier.Anonymous || value === Tier.Basic || value === Tier.Full || value === Tier.OptIn\n )\n}\n\n/**\n * Reports whether `tier` permits emitting a field scoped to `required`.\n * A session resolved to `Tier.Full`, for example, `tierAllows(Tier.Full,\n * Tier.Basic)` and `tierAllows(Tier.Full, Tier.Full)` but not\n * `tierAllows(Tier.Full, Tier.OptIn)`.\n */\nexport function tierAllows(tier: Tier, required: Tier): boolean {\n return tier >= required\n}\n\n/** Returns the lower of `tier` and `ceiling`. */\nexport function clampTier(tier: Tier, ceiling: Tier): Tier {\n return tier > ceiling ? ceiling : tier\n}\n\n/**\n * A coarse, vendor-assigned classification of an error — deliberately\n * not the error's message or type name, both of which can carry\n * arbitrary (and potentially sensitive) free-form text. This SDK does\n * not attempt to infer a category from an error value itself; the\n * vendor's own error handling already knows which of these applies.\n */\nexport const ErrorCategory = {\n Unknown: 'unknown',\n /** Bad input, invalid flags/args. */\n User: 'user',\n Validation: 'validation',\n Network: 'network',\n Auth: 'auth',\n Internal: 'internal',\n Timeout: 'timeout',\n Canceled: 'canceled',\n} as const\n\nexport type ErrorCategory = (typeof ErrorCategory)[keyof typeof ErrorCategory]\n\nconst ERROR_CATEGORY_VALUES: ReadonlySet<string> = new Set(Object.values(ErrorCategory))\n\nexport function isValidErrorCategory(value: string): value is ErrorCategory {\n return ERROR_CATEGORY_VALUES.has(value)\n}\n\n/**\n * What a vendor's classifier returns for an error: the {@link ErrorCategory}\n * plus, optionally, a fixed-vocabulary `reason` that says more precisely\n * what failed (e.g. `\"no-token\"`, `\"invalid-url\"`). The reason must be an\n * identifier chosen in code (`^[a-z0-9][a-z0-9._-]*$`, at most 64 bytes),\n * never error text or anything derived from user input; one that doesn't\n * match is dropped, not rewritten. Sent at `Tier.Basic`+.\n */\nexport interface ErrorClassification {\n category: ErrorCategory\n reason?: string\n}\n","/**\n * Sentinel errors thrown/rejected internally. Never thrown across the\n * public API surface itself (every exported method swallows errors via\n * {@link safeRun}/{@link safeRunAsync} — see safety.ts) but used as\n * rejection reasons a {@link ConsentProvider} chain can inspect or a\n * vendor can `instanceof`-check if they care why resolution failed.\n */\n\nexport class ArgvioError extends Error {\n constructor(message: string) {\n super(`argvio: ${message}`)\n this.name = 'ArgvioError'\n }\n}\n\nexport const errNoProviderResolved = new ArgvioError('no consent provider resolved a tier')\nexport const errNoConsentFile = new ArgvioError('no consent config file path resolved')\nexport const errUnknownTierValue = new ArgvioError('unknown tier value in consent config')\n","import { homedir } from 'node:os'\nimport { join, dirname } from 'node:path'\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\n\nimport type { Tier } from './tier.js'\nimport { isValidTier, parseTier, tierToString } from './tier.js'\nimport type { ConsentProvider } from './consent.js'\nimport { errNoConsentFile, errUnknownTierValue } from './errors.js'\n\n/**\n * Replicates Go's `os.UserConfigDir()` semantics without adding a\n * dependency: `$XDG_CONFIG_HOME` (or `~/.config`) on Linux/other,\n * `~/Library/Application Support` on macOS, `%APPDATA%` on Windows.\n */\nfunction userConfigDir(): string | undefined {\n switch (process.platform) {\n case 'win32':\n return process.env['APPDATA']\n case 'darwin':\n return join(homedir(), 'Library', 'Application Support')\n default:\n return process.env['XDG_CONFIG_HOME'] || join(homedir(), '.config')\n }\n}\n\n/** The default path of the install ID file: next to the consent file. */\nexport function defaultInstallIdPath(cliName: string): string | undefined {\n const consentPath = defaultConsentPath(cliName)\n return consentPath ? join(dirname(consentPath), 'argvio-install-id') : undefined\n}\n\nfunction defaultConsentPath(cliName: string): string | undefined {\n const dir = userConfigDir()\n if (!dir) return undefined\n return join(dir, cliName || 'argvio', 'argvio-consent.json')\n}\n\nexport interface FileConsentProviderOptions {\n /** Overrides the default config file location entirely. */\n path?: string\n}\n\ninterface ConsentFileContents {\n tier?: string\n}\n\n/**\n * The reference {@link ConsentProvider} implementation: reads a small\n * JSON file at a conventional per-CLI config location, namespaced under\n * the vendor's own CLI name to avoid collisions between unrelated CLIs\n * that both embed this SDK.\n *\n * Reads/writes are synchronous (see {@link ConsentProvider}'s doc\n * comment for why) — a small local JSON file read is cheap enough that\n * this doesn't meaningfully block startup.\n *\n * Use `options.path` to override the location entirely (e.g. a vendor\n * that already has its own config file and wants to store the tier\n * alongside it under a different mechanism should implement their own\n * {@link ConsentProvider} instead).\n */\nexport class FileConsentProvider implements ConsentProvider {\n /** The resolved config file path (after defaults/overrides), primarily for diagnostics and tests. */\n readonly path: string | undefined\n\n constructor(cliName: string, options: FileConsentProviderOptions = {}) {\n this.path = options.path || defaultConsentPath(cliName)\n }\n\n /**\n * A missing file, unreadable file, or malformed contents all throw\n * synchronously, so callers should place `FileConsentProvider` inside\n * `chainProviders` with a sane fallback (e.g.\n * `new StaticProvider(Tier.Anonymous)`).\n */\n resolve(): Tier {\n if (!this.path) throw errNoConsentFile\n const data = readFileSync(this.path, 'utf8')\n const parsed = JSON.parse(data) as ConsentFileContents\n const tier = parseTier(parsed.tier ?? '')\n if (tier === undefined) throw errUnknownTierValue\n return tier\n }\n\n /**\n * Persists `tier` as the chosen consent tier, creating the parent\n * directory if needed. Intended for use by a vendor's first-run\n * consent prompt. Does not itself enforce any tier ceiling — it's the\n * vendor's own UX writing the user's explicit choice.\n */\n store(tier: Tier): void {\n if (!this.path) throw errNoConsentFile\n if (!isValidTier(tier)) throw errUnknownTierValue\n mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 })\n const contents: ConsentFileContents = { tier: tierToString(tier) }\n writeFileSync(this.path, JSON.stringify(contents), { mode: 0o600 })\n }\n}\n","import { Tier } from './tier.js'\nimport type { ConsentProvider } from './consent.js'\nimport { defaultInstallIdPath } from './consentFile.js'\n\nexport type Transport = 'http' | 'grpc'\n\n/**\n * The hosted public ingest endpoint for OTLP/HTTP. Overridden by\n * `options.endpoint` for self-hosted/on-prem deployments.\n *\n * TODO(schema): confirm the production hostname; this is a placeholder.\n */\nexport const DEFAULT_ENDPOINT_HTTP = 'https://ingest.argvio.io:4318'\n\n/** The hosted public ingest endpoint for OTLP/gRPC. Same TODO(schema) status as above. */\nexport const DEFAULT_ENDPOINT_GRPC = 'ingest.argvio.io:4317'\n\n/**\n * The metadata/header key the API key is sent under.\n *\n * TODO(schema): confirm against the public server's actual auth\n * contract; placeholder pending that being pasted into this repo.\n */\nexport const DEFAULT_AUTH_HEADER = 'x-argvio-api-key'\n\nexport const DEFAULT_EXPORT_TIMEOUT_MS = 10_000\nexport const DEFAULT_SHUTDOWN_TIMEOUT_MS = 5_000\nexport const DEFAULT_QUEUE_SIZE = 2048\n\n/** Configures a {@link Client} constructed by `createClient`. */\nexport interface ClientOptions {\n /**\n * Overrides the OTLP collector endpoint. Defaults to the hosted\n * public endpoint appropriate for `transport`.\n */\n endpoint?: string\n /**\n * Selects the OTLP wire transport. Defaults to `'http'` so a CLI that\n * embeds it doesn't pull in a gRPC client stack by default. Pass\n * `'grpc'` if you need gRPC.\n */\n transport?: Transport\n /** Disables transport security. Only intended for local development against a self-hosted collector without TLS. */\n insecure?: boolean\n /** Overrides the header the API key is sent under. Rarely needed. */\n authHeader?: string\n /** The consent tier used when no `consentProvider` is supplied, or if it rejects/times out. Defaults to `Tier.Anonymous`. */\n defaultTier?: Tier\n /** Resolves the session's consent tier at construction time. If unset, `defaultTier` is used directly. */\n consentProvider?: ConsentProvider\n /**\n * Fully disables the client: `createClient` returns a Client that\n * performs zero network calls and whose `record*` methods are no-ops\n * with negligible overhead. Equivalent to setting `ARGVIO_DISABLED=1`,\n * and also engaged automatically when `DO_NOT_TRACK` requests it.\n */\n disabled?: boolean\n /** Bounds how long a single export attempt may take. */\n exportTimeoutMs?: number\n /** Bounds how long `flush`/`shutdown` may block waiting for in-flight data to be exported. */\n shutdownTimeoutMs?: number\n /** Bounds the number of pending records buffered before new records are dropped (counted, never blocking). */\n queueSize?: number\n /**\n * Additional static OTel resource attributes (e.g. a build channel or\n * distribution identifier). Not tier-gated and not part of the\n * taxonomy — use sparingly, for attributes that describe the CLI\n * build itself rather than any individual invocation.\n */\n resourceAttributes?: Record<string, string>\n /**\n * Where the install ID (`cli.install_id`, `Tier.Basic`+) is persisted.\n * Defaults to `argvio-install-id` in the same per-CLI config directory\n * as `FileConsentProvider`'s consent file. `''` turns install IDs off.\n */\n installIdPath?: string\n /**\n * How this CLI was installed (for example `'brew'`, `'npm'`, `'curl'` or\n * `'binary'`), reported on the session start event at every consent tier.\n * The SDK can't tell on its own, so the vendor supplies it, typically from\n * a value stamped in at build time. Omit to send nothing.\n */\n installMethod?: string\n}\n\nexport interface ResolvedConfig {\n apiKey: string\n cliName: string\n cliVersion: string\n endpoint: string\n transport: Transport\n insecure: boolean\n authHeader: string\n defaultTier: Tier\n consentProvider: ConsentProvider | undefined\n disabled: boolean\n exportTimeoutMs: number\n shutdownTimeoutMs: number\n queueSize: number\n resourceAttributes: Record<string, string>\n installIdPath: string | undefined\n installMethod: string | undefined\n}\n\n/** The server's max_length for `cli.install.method`. */\nconst MAX_INSTALL_METHOD_LENGTH = 32\n\nexport function resolveConfig(\n apiKey: string,\n cliName: string,\n cliVersion: string,\n options: ClientOptions = {},\n): ResolvedConfig {\n const transport = options.transport ?? 'http'\n return {\n apiKey,\n cliName,\n cliVersion,\n transport,\n endpoint:\n options.endpoint || (transport === 'grpc' ? DEFAULT_ENDPOINT_GRPC : DEFAULT_ENDPOINT_HTTP),\n insecure: options.insecure ?? false,\n authHeader: options.authHeader || DEFAULT_AUTH_HEADER,\n defaultTier: options.defaultTier ?? Tier.Anonymous,\n consentProvider: options.consentProvider,\n disabled: options.disabled ?? false,\n exportTimeoutMs:\n options.exportTimeoutMs && options.exportTimeoutMs > 0\n ? options.exportTimeoutMs\n : DEFAULT_EXPORT_TIMEOUT_MS,\n shutdownTimeoutMs:\n options.shutdownTimeoutMs && options.shutdownTimeoutMs > 0\n ? options.shutdownTimeoutMs\n : DEFAULT_SHUTDOWN_TIMEOUT_MS,\n queueSize: options.queueSize && options.queueSize > 0 ? options.queueSize : DEFAULT_QUEUE_SIZE,\n resourceAttributes: options.resourceAttributes ?? {},\n installIdPath:\n options.installIdPath !== undefined\n ? options.installIdPath || undefined\n : defaultInstallIdPath(cliName),\n installMethod: options.installMethod?.slice(0, MAX_INSTALL_METHOD_LENGTH) || undefined,\n }\n}\n","import { Metadata } from '@grpc/grpc-js'\nimport type { SpanExporter } from '@opentelemetry/sdk-trace-node'\nimport type { LogRecordExporter } from '@opentelemetry/sdk-logs'\nimport type { PushMetricExporter } from '@opentelemetry/sdk-metrics'\n\nimport { OTLPTraceExporter as OTLPTraceExporterHttp } from '@opentelemetry/exporter-trace-otlp-http'\nimport { OTLPTraceExporter as OTLPTraceExporterGrpc } from '@opentelemetry/exporter-trace-otlp-grpc'\nimport { OTLPMetricExporter as OTLPMetricExporterHttp } from '@opentelemetry/exporter-metrics-otlp-http'\nimport { OTLPMetricExporter as OTLPMetricExporterGrpc } from '@opentelemetry/exporter-metrics-otlp-grpc'\nimport { OTLPLogExporter as OTLPLogExporterHttp } from '@opentelemetry/exporter-logs-otlp-http'\nimport { OTLPLogExporter as OTLPLogExporterGrpc } from '@opentelemetry/exporter-logs-otlp-grpc'\n\nimport type { ResolvedConfig } from './options.js'\n\nexport interface Exporters {\n trace: SpanExporter\n metric: PushMetricExporter\n log: LogRecordExporter\n}\n\nconst SCHEME_RE = /^[a-z][a-z0-9+.-]*:\\/\\//i\n\n/**\n * Ensures `endpoint` carries an explicit scheme, downgrading to `http://`\n * when `insecure` is set (used for local development against a\n * self-hosted collector without TLS).\n */\nfunction withScheme(endpoint: string, insecure: boolean): string {\n if (!SCHEME_RE.test(endpoint)) {\n return `${insecure ? 'http' : 'https'}://${endpoint}`\n }\n return insecure ? endpoint.replace(/^https:\\/\\//i, 'http://') : endpoint\n}\n\nfunction grpcMetadata(cfg: ResolvedConfig): Metadata {\n const metadata = new Metadata()\n metadata.set(cfg.authHeader, cfg.apiKey)\n return metadata\n}\n\nfunction httpHeaders(cfg: ResolvedConfig): Record<string, string> {\n return { [cfg.authHeader]: cfg.apiKey }\n}\n\n/**\n * Builds the three signal-specific OTLP exporters for a single Client.\n * Each is independently constructed so a failure building one doesn't\n * necessarily prevent the others.\n */\nexport function buildExporters(cfg: ResolvedConfig): Exporters {\n if (cfg.transport === 'grpc') {\n const url = withScheme(cfg.endpoint, cfg.insecure)\n const metadata = grpcMetadata(cfg)\n return {\n trace: new OTLPTraceExporterGrpc({ url, metadata, timeoutMillis: cfg.exportTimeoutMs }),\n metric: new OTLPMetricExporterGrpc({ url, metadata, timeoutMillis: cfg.exportTimeoutMs }),\n log: new OTLPLogExporterGrpc({ url, metadata, timeoutMillis: cfg.exportTimeoutMs }),\n }\n }\n\n const base = withScheme(cfg.endpoint, cfg.insecure).replace(/\\/+$/, '')\n const headers = httpHeaders(cfg)\n return {\n trace: new OTLPTraceExporterHttp({\n url: `${base}/v1/traces`,\n headers,\n timeoutMillis: cfg.exportTimeoutMs,\n }),\n metric: new OTLPMetricExporterHttp({\n url: `${base}/v1/metrics`,\n headers,\n timeoutMillis: cfg.exportTimeoutMs,\n }),\n log: new OTLPLogExporterHttp({\n url: `${base}/v1/logs`,\n headers,\n timeoutMillis: cfg.exportTimeoutMs,\n }),\n }\n}\n","import { Tier } from './tier.js'\nimport type { ConsentProvider } from './consent.js'\nimport { errNoProviderResolved } from './errors.js'\n\n/**\n * Environment variables commonly set to a truthy value by CI systems.\n * Presence of any of these (with a non-empty, non-\"false\"/\"0\" value) is\n * treated as \"running in CI\".\n */\nconst CI_ENV_VARS = [\n 'CI',\n 'CONTINUOUS_INTEGRATION',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'CIRCLECI',\n 'TRAVIS',\n 'JENKINS_URL',\n 'BUILDKITE',\n 'TEAMCITY_VERSION',\n 'APPVEYOR',\n 'TF_BUILD', // Azure Pipelines\n 'DRONE', // Drone CI\n 'CODEBUILD_BUILD_ID',\n 'BITBUCKET_BUILD_NUMBER',\n] as const\n\n/** Reports whether the current process appears to be running inside a CI system. */\nexport function isCI(): boolean {\n return CI_ENV_VARS.some((name) => {\n const value = process.env[name]\n return value !== undefined && value !== '' && value !== 'false' && value !== '0'\n })\n}\n\n/** CI providers reported on the `cli.ci_provider` resource attribute. */\nconst CI_PROVIDERS: ReadonlyArray<readonly [envVar: string, provider: string]> = [\n ['GITHUB_ACTIONS', 'github_actions'],\n ['GITLAB_CI', 'gitlab_ci'],\n ['CIRCLECI', 'circleci'],\n ['BUILDKITE', 'buildkite'],\n ['JENKINS_URL', 'jenkins'],\n ['TRAVIS', 'travis'],\n]\n\n/**\n * Returns which CI provider the process runs in, `'unknown'` for an\n * unrecognized CI system, or `undefined` outside CI.\n */\nexport function detectCIProvider(): string | undefined {\n for (const [envVar, provider] of CI_PROVIDERS) {\n const value = process.env[envVar]\n if (value && value !== 'false' && value !== '0') return provider\n }\n return isCI() ? 'unknown' : undefined\n}\n\n/**\n * Reports whether the `DO_NOT_TRACK` environment variable\n * (https://do-not-track.dev) requests telemetry be disabled. Any value\n * other than unset, empty, \"0\", or \"false\" is treated as a request.\n */\nexport function isDoNotTrackRequested(): boolean {\n const value = process.env['DO_NOT_TRACK']\n if (value === undefined) return false\n return value !== '' && value !== '0' && value !== 'false'\n}\n\n/**\n * A {@link ConsentProvider} that caps the resolved tier at\n * `Tier.Anonymous` when the process appears to be running in a CI\n * environment. It resolves `Tier.Anonymous` in that case and rejects\n * otherwise, so it's meant to be placed ahead of other providers in a\n * {@link chainProviders} call — it \"wins\" only when CI is detected,\n * deferring to the next provider otherwise.\n *\n * Reasoning: CI runs are usually unattended, share no single human\n * user's stored consent preference, and can run at high volume (every\n * commit, every matrix leg). We still allow anonymous-tier telemetry\n * (e.g. install/build counts) by default rather than fully disabling,\n * because that data has real product value and carries no identifying\n * fields at `Tier.Anonymous` by construction. Vendors who want CI runs\n * fully silent can pass `disabled: true` or check `isCI()` themselves.\n *\n * `DO_NOT_TRACK` is handled separately (see {@link isDoNotTrackRequested})\n * and is enforced by the Client as a full disable, not a tier cap: it's\n * a standing, cross-tool opt-out signal a user or environment sets\n * deliberately, so it's honored as \"no telemetry\" rather than \"least\n * telemetry\".\n */\nexport class EnvConsentProvider implements ConsentProvider {\n resolve(): Tier {\n if (isCI()) return Tier.Anonymous\n throw errNoProviderResolved\n }\n}\n","import { readFileSync } from 'node:fs'\n\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport type { Resource } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'\n\nimport type { ResolvedConfig } from './options.js'\nimport { detectCIProvider } from './consentEnv.js'\n\n/** Resource attribute keys describing the CLI build and host, promoted by the server into filterable columns. */\nexport const ResourceAttrCLIVersion = 'cli.version'\nexport const ResourceAttrOS = 'cli.os'\nexport const ResourceAttrArch = 'cli.arch'\nexport const ResourceAttrIsCI = 'cli.is_ci'\nexport const ResourceAttrCIProvider = 'cli.ci_provider'\n\n/** Maps `process.platform` onto the server's `cli.os` enum. */\nexport function normalizeOS(platform: string): string {\n switch (platform) {\n case 'linux':\n case 'darwin':\n return platform\n case 'win32':\n return 'windows'\n default:\n return 'other'\n }\n}\n\n/** Maps `process.arch` onto the server's `cli.arch` enum. */\nexport function normalizeArch(arch: string): string {\n switch (arch) {\n case 'x64':\n return 'amd64'\n case 'arm64':\n case 'arm':\n return arch\n case 'ia32':\n return '386'\n default:\n return 'other'\n }\n}\n\n/** This package's own name, reported on `telemetry.sdk.name`. */\nconst SDK_NAME = '@getargvio/argvio'\n\n/**\n * Returns this package's own version, read from its `package.json` at\n * runtime rather than hardcoded, so the reported value always matches\n * what a vendor actually installed.\n */\nfunction sdkVersion(): string {\n try {\n const pkgUrl = new URL('../package.json', import.meta.url)\n const pkg = JSON.parse(readFileSync(pkgUrl, 'utf8')) as { version?: string }\n return pkg.version ?? 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\nexport function buildResource(cfg: ResolvedConfig): Resource {\n const ciProvider = detectCIProvider()\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: cfg.cliName,\n [ATTR_SERVICE_VERSION]: cfg.cliVersion,\n 'telemetry.sdk.name': SDK_NAME,\n 'telemetry.sdk.version': sdkVersion(),\n 'telemetry.sdk.language': 'nodejs',\n [ResourceAttrCLIVersion]: cfg.cliVersion,\n [ResourceAttrOS]: normalizeOS(process.platform),\n [ResourceAttrArch]: normalizeArch(process.arch),\n [ResourceAttrIsCI]: ciProvider !== undefined,\n ...(ciProvider ? { [ResourceAttrCIProvider]: ciProvider } : {}),\n ...cfg.resourceAttributes,\n })\n}\n","import { randomBytes, randomUUID } from 'node:crypto'\nimport { mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\n/**\n * Attribute keys used on emitted signals. Exported so vendors and tests\n * can assert on them without relying on string literals staying in\n * sync.\n *\n * Every event, span, metric and attribute name in this file is taken from\n * the `public` server's allowlist (schema/allowlist/v1.yaml in\n * getargvio/argvio), which rejects anything else. Change them only\n * together with a server-side schema version.\n */\nexport const AttrCommandName = 'cli.command.name'\nexport const AttrExitCode = 'cli.command.exit_code'\nexport const AttrDurationMs = 'cli.command.duration_ms'\n/** `Tier.Basic`+. Peak resident set size of the process, in bytes. */\nexport const AttrPeakRssBytes = 'cli.process.peak_rss_bytes'\n/** `Tier.Basic`+. User plus system CPU time of the process, in milliseconds. */\nexport const AttrCpuTimeMs = 'cli.process.cpu_time_ms'\n/**\n * `Tier.Basic`+. Size of the CLI's binary, in bytes. Only on\n * `cli.session.started`, and only for a Node single executable application.\n */\nexport const AttrBinarySizeBytes = 'cli.binary.size_bytes'\n/**\n * `Tier.Basic`+. Time from process start to the point the command begins\n * running, in milliseconds. Only on `cli.session.started`.\n */\nexport const AttrStartupDurationMs = 'cli.startup.duration_ms'\n/** `Tier.Basic`+. */\nexport const AttrFlagNames = 'cli.flag.names'\n/** `Tier.Basic`+. */\nexport const AttrSessionId = 'cli.session_id'\n/** `Tier.Basic`+. */\nexport const AttrInstallId = 'cli.install_id'\nexport const AttrHelpFlag = 'cli.help.flag'\n/** How the CLI was installed; supplied by the vendor via the `installMethod` option. */\nexport const AttrInstallMethod = 'cli.install.method'\n/** `Tier.Basic`+. A fixed feature identifier supplied by the vendor. */\nexport const AttrActivationFeature = 'cli.activation.feature'\n/** `Tier.Basic`+. */\nexport const AttrErrorType = 'cli.error.type'\n/**\n * `Tier.Basic`+. A vendor-assigned reason from a fixed vocabulary, alongside\n * the error type. Never error text.\n */\nexport const AttrErrorReason = 'cli.error.reason'\n/** `Tier.OptIn` only. */\nexport const AttrErrorMessage = 'cli.error.message'\n/** `Tier.OptIn` only. */\nexport const AttrErrorStack = 'cli.error.stacktrace'\n\n/**\n * Every tier. The name of a vendor-defined counter, a fixed identifier\n * chosen in code. Sent on `cli.counter`.\n */\nexport const AttrCounterName = 'cli.counter.name'\n/**\n * Every tier. An optional fixed identifier that splits one counter into\n * series, chosen in code. Sent on `cli.counter`.\n */\nexport const AttrCounterLabel = 'cli.counter.label'\n\n/** Log event names. */\nexport const EventSessionStarted = 'cli.session.started'\nexport const EventCommandInvoked = 'cli.command.invoked'\nexport const EventCommandCompleted = 'cli.command.completed'\nexport const EventFeatureActivated = 'cli.feature.activated'\nexport const EventHelpViewed = 'cli.help.viewed'\nexport const EventErrorRaised = 'cli.error.raised'\n\n/**\n * Prefixes the name of the span `recordCommand` emits for each command\n * (e.g. `cli.command.deploy.push`). The server's command dashboards\n * (frequency, latency, error rate, exit codes) are built from these spans.\n */\nexport const SpanCommandPrefix = 'cli.command.'\n\n/** Metric instrument names. */\nexport const MetricCommandInvocations = 'cli.command.invocations'\n/** Unit: milliseconds. */\nexport const MetricCommandDuration = 'cli.command.duration'\nexport const MetricErrors = 'cli.errors'\n/** Unit: 1. A vendor-defined counter, see {@link Client.recordCounter}. */\nexport const MetricCounter = 'cli.counter'\n\n/** The server's max_length for `cli.command.name`. */\nconst MAX_COMMAND_NAME_LENGTH = 128\n\n/** The server's max_length for `cli.activation.feature`. */\nexport const MAX_ACTIVATION_FEATURE_LENGTH = 64\n\n/** The server's max_length for `cli.error.reason`, `cli.counter.name` and `cli.counter.label`. */\nconst MAX_IDENTIFIER_LENGTH = 64\n\n/** The server's pattern for `cli.error.reason`, `cli.counter.name` and `cli.counter.label`. */\nconst IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9._-]*$/\n\n/**\n * Reports whether `value` is acceptable as an error reason, counter name or\n * counter label: the server's `^[a-z0-9][a-z0-9._-]*$` and at most 64\n * bytes (the pattern is ASCII only, so that is 64 characters). A value that\n * fails is dropped by the caller, never trimmed or rewritten into shape.\n */\nexport function isValidIdentifier(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length <= MAX_IDENTIFIER_LENGTH &&\n IDENTIFIER_PATTERN.test(value)\n )\n}\n\n/**\n * Converts a command path as the CLI framework reports it\n * (`\"mycli deploy push\"`) into the dotted `cli.command.name` the server\n * expects (`\"deploy.push\"`). The CLI's own name is dropped, since every\n * record already carries it as `service.name`, except for the root command\n * itself, which keeps it so it still has a name.\n */\nexport function commandName(cliName: string, commandPath: string): string {\n let parts = commandPath.split(/\\s+/).filter(Boolean)\n if (parts.length > 1 && parts[0] === cliName) parts = parts.slice(1)\n const name = parts.join('.') || cliName || 'root'\n return name.slice(0, MAX_COMMAND_NAME_LENGTH)\n}\n\n/**\n * Process-wide resource usage so far. Both figures are cumulative for the\n * whole process, not per command; a CLI normally runs one command per\n * process, so they describe that command.\n */\nexport interface ProcessResourceUsage {\n /** Peak resident set size, in bytes. */\n peakRssBytes?: number\n /** User plus system CPU time, in milliseconds. */\n cpuTimeMs?: number\n}\n\n/**\n * Reads the process's peak RSS and CPU time with two cheap synchronous\n * calls: no sampling, no timers. A measure the platform can't provide (the\n * call throws, or reports zero, negative or non-finite) is omitted rather\n * than reported as 0, which the server treats as \"not reported\" anyway.\n * Never throws.\n */\nexport function readProcessResourceUsage(): ProcessResourceUsage {\n const usage: ProcessResourceUsage = {}\n try {\n // maxRSS is in kilobytes.\n const rssBytes = Math.round(process.resourceUsage().maxRSS * 1024)\n if (Number.isFinite(rssBytes) && rssBytes > 0) usage.peakRssBytes = rssBytes\n } catch {\n // unsupported platform or OS error: omit\n }\n try {\n // user and system are in microseconds.\n const { user, system } = process.cpuUsage()\n const cpuMs = Math.round((user + system) / 1000)\n if (Number.isFinite(cpuMs) && cpuMs > 0) usage.cpuTimeMs = cpuMs\n } catch {\n // unsupported platform or OS error: omit\n }\n return usage\n}\n\n/**\n * Milliseconds since this process started, which is how long module\n * loading and framework setup took when read as the command begins\n * running. Returns undefined, never 0, if the platform can't provide it.\n * Never throws.\n */\nexport function readStartupDurationMs(): number | undefined {\n try {\n const ms = Math.round(process.uptime() * 1000)\n return Number.isFinite(ms) && ms > 0 ? ms : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Size in bytes of the running binary, but only when this is a Node single\n * executable application (`node:sea` `isSea()`), where `process.execPath`\n * is the vendor's build. In any other case `process.execPath` is the\n * generic `node` binary, not the vendor's, so nothing is reported. At most\n * one `stat`. Returns undefined, never 0, on any failure. Never throws.\n */\nexport function readBinarySizeBytes(): number | undefined {\n try {\n const sea = process.getBuiltinModule?.('node:sea')\n if (!sea?.isSea()) return undefined\n const size = statSync(process.execPath).size\n return Number.isFinite(size) && size > 0 ? size : undefined\n } catch {\n return undefined\n }\n}\n\n/** A random, non-persistent per-process session correlation ID. Not a user or device identifier. */\nexport function newSessionId(): string {\n try {\n return randomBytes(16).toString('hex')\n } catch {\n return ''\n }\n}\n\nconst INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/\n\n/**\n * Returns the install ID stored at `path`, generating and persisting a new\n * random one on first use. Returns `''` whenever the ID can't be\n * persisted: an ID that changes on every run would count every invocation\n * as a new install, which is worse than no ID at all.\n */\nexport function loadOrCreateInstallId(path: string | undefined): string {\n if (!path) return ''\n try {\n const existing = readFileSync(path, 'utf8').trim()\n if (INSTALL_ID_PATTERN.test(existing)) return existing\n } catch {\n // missing or unreadable: create one below\n }\n try {\n const id = randomUUID()\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 })\n writeFileSync(path, `${id}\\n`, { mode: 0o600 })\n return id\n } catch {\n return ''\n }\n}\n","/**\n * No bug inside this SDK should ever throw into the host CLI. `safeRun`\n * is a try/catch guard installed at the top of every exported Client\n * method.\n */\n\n/** Prints recovered-error diagnostics to stderr. Off by default. */\nexport const ARGVIO_DEBUG = process.env['ARGVIO_DEBUG'] === '1'\n\n/** A snapshot of in-process telemetry-about-telemetry: never sent over the network. */\nexport interface Stats {\n /** Records dropped because a batch queue was full rather than blocking the host CLI. */\n queueOverflowDropped: number\n /** Records/fields dropped because the resolved consent tier didn't permit them. */\n belowTierDropped: number\n /** Internal errors recovered from; should always be zero. */\n recoveredErrors: number\n}\n\nexport class DroppedCounters {\n queueOverflow = 0\n belowTierCeil = 0\n recoveredErrors = 0\n\n snapshot(): Stats {\n return {\n queueOverflowDropped: this.queueOverflow,\n belowTierDropped: this.belowTierCeil,\n recoveredErrors: this.recoveredErrors,\n }\n }\n}\n\nfunction logRecovered(err: unknown): void {\n if (!ARGVIO_DEBUG) return\n const msg = err instanceof Error ? err.message : '(non-error thrown value)'\n process.stderr.write(`argvio: recovered internal error: ${msg}\\n`)\n}\n\n/** Runs `fn`, guaranteeing no synchronous throw escapes. */\nexport function safeRun(fn: () => void, counters?: DroppedCounters): void {\n try {\n fn()\n } catch (err) {\n if (counters) counters.recoveredErrors++\n logRecovered(err)\n }\n}\n","import { SpanStatusCode } from '@opentelemetry/api'\nimport type { Attributes, Counter, Histogram, Tracer } from '@opentelemetry/api'\nimport { SeverityNumber } from '@opentelemetry/api-logs'\nimport type { Logger } from '@opentelemetry/api-logs'\nimport { LoggerProvider, BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'\nimport { NodeTracerProvider, BatchSpanProcessor } from '@opentelemetry/sdk-trace-node'\n\nimport type { ClientOptions } from './options.js'\nimport { resolveConfig } from './options.js'\nimport { buildExporters } from './otlp.js'\nimport { buildResource } from './resource.js'\nimport { isDoNotTrackRequested } from './consentEnv.js'\nimport { Tier, tierAllows, tierToString, isValidTier, RESOURCE_ATTR_TIER } from './tier.js'\nimport type { ErrorCategory } from './tier.js'\nimport { ErrorCategory as ErrorCategoryValues, isValidErrorCategory } from './tier.js'\nimport {\n AttrActivationFeature,\n AttrCommandName,\n AttrCounterLabel,\n AttrCounterName,\n AttrDurationMs,\n AttrErrorMessage,\n AttrErrorReason,\n AttrErrorStack,\n AttrErrorType,\n AttrExitCode,\n AttrFlagNames,\n AttrHelpFlag,\n AttrInstallId,\n AttrInstallMethod,\n AttrPeakRssBytes,\n AttrCpuTimeMs,\n AttrBinarySizeBytes,\n AttrStartupDurationMs,\n AttrSessionId,\n EventCommandCompleted,\n EventCommandInvoked,\n EventErrorRaised,\n EventFeatureActivated,\n EventHelpViewed,\n EventSessionStarted,\n MetricCommandDuration,\n MetricCommandInvocations,\n MetricCounter,\n MetricErrors,\n MAX_ACTIVATION_FEATURE_LENGTH,\n SpanCommandPrefix,\n commandName,\n isValidIdentifier,\n loadOrCreateInstallId,\n newSessionId,\n readBinarySizeBytes,\n readProcessResourceUsage,\n readStartupDurationMs,\n} from './taxonomy.js'\nimport type { Stats } from './safety.js'\nimport { ARGVIO_DEBUG, DroppedCounters, safeRun } from './safety.js'\n\n/**\n * Identifies this SDK to the OTel SDKs it wraps (tracer/meter/logger name),\n * distinct from the CLI's own resource attributes.\n */\nconst INSTRUMENTATION_NAME = '@getargvio/argvio'\n\ntype Job = () => void | Promise<void>\n\n/**\n * A small in-process bounded async queue: `push` never blocks the\n * caller, and drops (counted, never applying backpressure) when full.\n * Jobs run on subsequent ticks via `setImmediate`, off the caller's\n * synchronous call stack.\n */\nclass JobQueue {\n private readonly items: Job[] = []\n private draining = false\n\n constructor(\n private readonly maxSize: number,\n private readonly counters: DroppedCounters,\n ) {}\n\n push(job: Job): void {\n if (this.items.length >= this.maxSize) {\n this.counters.queueOverflow++\n return\n }\n this.items.push(job)\n this.scheduleDrain()\n }\n\n /**\n * Enqueues a control signal (e.g. a drain sentinel) bypassing the size\n * bound, so `waitForDrain` waits for genuine backlog instead of\n * silently racing ahead when the queue happens to be full.\n */\n private pushControl(job: Job): void {\n this.items.push(job)\n this.scheduleDrain()\n }\n\n private scheduleDrain(): void {\n if (this.draining) return\n this.draining = true\n setImmediate(() => {\n void this.drain()\n })\n }\n\n private async drain(): Promise<void> {\n for (;;) {\n const job = this.items.shift()\n if (!job) break\n try {\n await job()\n } catch (err) {\n this.counters.recoveredErrors++\n if (ARGVIO_DEBUG) {\n const msg = err instanceof Error ? err.message : '(non-error thrown value)'\n process.stderr.write(`argvio: recovered internal error: ${msg}\\n`)\n }\n }\n }\n this.draining = false\n }\n\n /** Resolves once every job enqueued before this call has finished executing, or `timeoutMs` elapses. */\n async waitForDrain(timeoutMs: number): Promise<void> {\n const done = new Promise<void>((resolve) => {\n this.pushControl(() => {\n resolve()\n })\n })\n await withTimeout(done, timeoutMs)\n }\n}\n\nasync function withTimeout(promise: Promise<void>, timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, timeoutMs)\n })\n try {\n await Promise.race([promise, timeout])\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/** Options for {@link Client.recordCounter}. */\nexport interface CounterOptions {\n /**\n * Splits the counter into series (e.g. a tool or HTTP verb). A fixed\n * identifier chosen in code, subject to the same rules as the counter name.\n */\n label?: string\n}\n\n/** One completed command, for {@link Client.recordCommand}. */\nexport interface CommandResult {\n /** The full command path, as for {@link Client.recordCommandInvocation}. */\n path: string\n /** Names (never values) of the flags the user set. Only sent at `Tier.Basic`+. */\n flagNames?: readonly string[]\n /** When the command began, in epoch milliseconds. Defaults to `durationMs` before now. */\n startMs?: number\n /** How long the command ran, in milliseconds. */\n durationMs: number\n /** The command's exit code; non-zero counts as an error. */\n exitCode: number\n}\n\ninterface ClientParams {\n cliName?: string\n installIdPath?: string | undefined\n installMethod?: string | undefined\n tracer?: Tracer\n disabled: boolean\n initError: Error | null\n tier: Tier\n queueSize: number\n shutdownTimeoutMs: number\n tracerProvider?: NodeTracerProvider\n meterProvider?: MeterProvider\n loggerProvider?: LoggerProvider\n logger?: Logger\n latencyHist?: Histogram\n invocationsCounter?: Counter\n errorEventsCounter?: Counter\n productCounter?: Counter\n}\n\n/**\n * The entry point for emitting telemetry. Every method is safe to call\n * on a disabled Client (explicitly disabled, `DO_NOT_TRACK`/`ARGVIO_DISABLED`,\n * or degraded due to a construction error) — vendors never need to\n * check `disabled` before using a Client.\n *\n * Construct via {@link createClient}, never directly.\n */\nexport class Client {\n readonly tier: Tier\n readonly disabled: boolean\n /** Set if construction encountered a problem; the Client still degrades to a safe disabled no-op. */\n readonly initError: Error | null\n\n private readonly counters = new DroppedCounters()\n private readonly queue: JobQueue\n private readonly shutdownTimeoutMs: number\n private shuttingDown = false\n private shutdownStarted = false\n private sessionId: string | undefined\n private sessionStarted = false\n private readonly cliName: string\n private readonly installIdPath: string | undefined\n private readonly installMethod: string | undefined\n private installId: string | undefined\n private readonly activatedFeatures = new Set<string>()\n private readonly tracer: Tracer | undefined\n\n private readonly tracerProvider: NodeTracerProvider | undefined\n private readonly meterProvider: MeterProvider | undefined\n private readonly loggerProvider: LoggerProvider | undefined\n private readonly logger: Logger | undefined\n private readonly latencyHist: Histogram | undefined\n private readonly invocationsCounter: Counter | undefined\n private readonly errorEventsCounter: Counter | undefined\n private readonly productCounter: Counter | undefined\n\n /** @internal use {@link createClient} */\n constructor(params: ClientParams) {\n this.disabled = params.disabled\n this.initError = params.initError\n this.tier = params.tier\n this.shutdownTimeoutMs = params.shutdownTimeoutMs\n this.queue = new JobQueue(params.queueSize, this.counters)\n this.tracerProvider = params.tracerProvider\n this.meterProvider = params.meterProvider\n this.loggerProvider = params.loggerProvider\n this.logger = params.logger\n this.latencyHist = params.latencyHist\n this.invocationsCounter = params.invocationsCounter\n this.errorEventsCounter = params.errorEventsCounter\n this.productCounter = params.productCounter\n this.cliName = params.cliName ?? ''\n this.installIdPath = params.installIdPath\n this.installMethod = params.installMethod\n this.tracer = params.tracer\n }\n\n private enabled(): boolean {\n return !this.disabled && !this.shuttingDown\n }\n\n /** A snapshot of in-process counters about dropped records. Never sent over the network. */\n stats(): Stats {\n return this.counters.snapshot()\n }\n\n private gate(required: Tier): boolean {\n if (!this.enabled()) return false\n if (!tierAllows(this.tier, required)) {\n this.counters.belowTierCeil++\n return false\n }\n return true\n }\n\n private tierAttr(): Attributes {\n return { [RESOURCE_ATTR_TIER]: tierToString(this.tier) }\n }\n\n private emitEvent(name: string, severity: SeverityNumber, attributes: Attributes = {}): void {\n this.queue.push(() => {\n this.emitEventNow(name, severity, attributes)\n })\n }\n\n private emitEventNow(name: string, severity: SeverityNumber, attributes: Attributes = {}): void {\n this.logger?.emit({\n eventName: name,\n timestamp: Date.now(),\n severityNumber: severity,\n attributes: { ...this.tierAttr(), ...attributes },\n })\n }\n\n private name(commandPath: string): string {\n return commandName(this.cliName, commandPath)\n }\n\n /**\n * Lazily generates a session correlation ID at `Tier.Basic`+. A random,\n * non-persistent identifier scoped to a single process invocation —\n * not a user or device identifier.\n */\n private ensureSessionId(): string {\n if (!tierAllows(this.tier, Tier.Basic)) return ''\n if (this.sessionId === undefined) {\n this.sessionId = newSessionId()\n }\n return this.sessionId\n }\n\n /**\n * The session and install ID attributes for a record, empty below\n * `Tier.Basic`. May read or create the install ID file, so call it from\n * inside a queued job rather than on the caller's stack.\n */\n private identityAttrs(sessionId: string): Attributes {\n const attrs: Attributes = {}\n if (sessionId) attrs[AttrSessionId] = sessionId\n if (tierAllows(this.tier, Tier.Basic)) {\n this.installId ??= loadOrCreateInstallId(this.installIdPath)\n if (this.installId) attrs[AttrInstallId] = this.installId\n }\n return attrs\n }\n\n /**\n * Records the start of a CLI process session, which is what the server\n * counts sessions, active installs and retention from. Call it as early\n * as possible (the yargs/commander integrations do it for you); only the\n * first call per Client emits anything.\n *\n * At `Tier.Anonymous` the event carries no identifiers. At `Tier.Basic`+\n * it also carries the per-process session ID and the install ID, a\n * random UUID persisted in the CLI's config directory the first time it\n * is needed — never derived from the user or machine.\n *\n * At `Tier.Basic`+ it also carries startup overhead\n * (`cli.startup.duration_ms`): the time from process start to this call,\n * so it covers module loading and framework setup. Call it just before\n * the command runs, as the integrations do. And when running as a Node\n * single executable application, it carries the binary's size\n * (`cli.binary.size_bytes`). Either is omitted if unavailable, never 0.\n */\n recordSessionStart(): void {\n safeRun(() => {\n if (!this.enabled() || this.sessionStarted) return\n this.sessionStarted = true\n const sessionId = this.ensureSessionId()\n const basic = tierAllows(this.tier, Tier.Basic)\n // Read now rather than in the queued job, which runs on a later tick.\n const startupMs = basic ? readStartupDurationMs() : undefined\n this.queue.push(() => {\n const attrs = this.identityAttrs(sessionId)\n if (startupMs !== undefined) attrs[AttrStartupDurationMs] = startupMs\n if (basic) {\n const sizeBytes = readBinarySizeBytes()\n if (sizeBytes !== undefined) attrs[AttrBinarySizeBytes] = sizeBytes\n }\n if (this.installMethod) attrs[AttrInstallMethod] = this.installMethod\n this.emitEventNow(EventSessionStarted, SeverityNumber.INFO, attrs)\n })\n }, this.counters)\n }\n\n /**\n * Records that a command began executing. `commandPath` should be the\n * full command path (e.g. `\"mycli sub subsub\"`); it is reported as the\n * dotted command name (`\"sub.subsub\"`). `flagNames` is the list of flag\n * *names* the user set — never flag values, which this SDK never\n * accepts anywhere in the taxonomy.\n *\n * The command name is recorded at every tier; flag names and the\n * session ID at `Tier.Basic`+.\n */\n recordCommandInvocation(commandPath: string, flagNames: readonly string[] = []): void {\n safeRun(() => {\n if (!this.enabled()) return\n const attrs: Attributes = { [AttrCommandName]: this.name(commandPath) }\n if (tierAllows(this.tier, Tier.Basic) && flagNames.length > 0) {\n attrs[AttrFlagNames] = [...flagNames]\n }\n const sessionId = this.ensureSessionId()\n this.queue.push(() => {\n this.emitEventNow(EventCommandInvoked, SeverityNumber.INFO, {\n ...attrs,\n ...this.identityAttrs(sessionId),\n })\n })\n }, this.counters)\n }\n\n /**\n * Records a completed command: a `cli.command.<name>` span covering its\n * execution, plus the `cli.command.invocations` and\n * `cli.command.duration` metrics. This is what the server's command\n * frequency, latency, error-rate and exit-code dashboards are built\n * from, so call it once for every command that ran (the integrations\n * do). Available at every tier; flag names, peak memory and CPU time\n * only at `Tier.Basic`+.\n *\n * Peak memory (`cli.process.peak_rss_bytes`) and CPU time\n * (`cli.process.cpu_time_ms`) are read once from the process, so they are\n * process-wide and cumulative: right for a CLI that runs one command per\n * process, but in a long-lived or multi-command process each call\n * reports totals since the process started. A measure the platform can't\n * provide is omitted.\n */\n recordCommand(result: CommandResult): void {\n safeRun(() => {\n if (!this.enabled()) return\n const durationMs = Math.max(0, result.durationMs)\n const startMs = result.startMs ?? Date.now() - durationMs\n const name = this.name(result.path)\n const attrs: Attributes = {\n ...this.tierAttr(),\n [AttrCommandName]: name,\n [AttrExitCode]: result.exitCode,\n }\n const spanAttrs: Attributes = { ...attrs, [AttrDurationMs]: Math.round(durationMs) }\n if (tierAllows(this.tier, Tier.Basic) && result.flagNames && result.flagNames.length > 0) {\n spanAttrs[AttrFlagNames] = [...result.flagNames]\n }\n if (tierAllows(this.tier, Tier.Basic)) {\n // Read now, as the command completes, rather than in the queued job,\n // which runs on a later tick.\n const { peakRssBytes, cpuTimeMs } = readProcessResourceUsage()\n if (peakRssBytes !== undefined) spanAttrs[AttrPeakRssBytes] = peakRssBytes\n if (cpuTimeMs !== undefined) spanAttrs[AttrCpuTimeMs] = cpuTimeMs\n }\n const sessionId = this.ensureSessionId()\n this.queue.push(() => {\n const span = this.tracer?.startSpan(SpanCommandPrefix + name, {\n startTime: startMs,\n attributes: spanAttrs,\n })\n if (result.exitCode !== 0) span?.setStatus({ code: SpanStatusCode.ERROR })\n span?.end(startMs + durationMs)\n this.invocationsCounter?.add(1, attrs)\n this.latencyHist?.record(durationMs, attrs)\n\n // The completed event ties the outcome to the session and install,\n // which the span can't carry; the server's activation and friction\n // views are built from it.\n this.emitEventNow(EventCommandCompleted, SeverityNumber.INFO, {\n [AttrCommandName]: name,\n [AttrExitCode]: result.exitCode,\n [AttrDurationMs]: Math.round(durationMs),\n ...this.identityAttrs(sessionId),\n })\n })\n }, this.counters)\n }\n\n /**\n * Records that the user used one of the vendor's features, so the server\n * can tell which features an install has adopted and how soon after\n * installing. Emitted at `Tier.Basic`+ only; nothing is sent at\n * `Tier.Anonymous`. The event carries the feature name, the command name\n * when `commandPath` is given, and the session and install IDs.\n *\n * `feature` must be a fixed identifier chosen by the vendor in code\n * (e.g. `\"export-csv\"`), **never user input** such as a flag value, path\n * or argument. It is truncated to the server's 64 character limit.\n *\n * Each feature is reported at most once per process, however often this\n * is called, to keep volume down. The server derives \"first use\" per\n * install itself, so repeat reports within a run add nothing.\n */\n recordFeatureActivated(feature: string, commandPath?: string): void {\n safeRun(() => {\n if (!this.gate(Tier.Basic)) return\n const name = feature.slice(0, MAX_ACTIVATION_FEATURE_LENGTH)\n if (!name || this.activatedFeatures.has(name)) return\n this.activatedFeatures.add(name)\n const attrs: Attributes = { [AttrActivationFeature]: name }\n if (commandPath) attrs[AttrCommandName] = this.name(commandPath)\n const sessionId = this.ensureSessionId()\n this.queue.push(() => {\n this.emitEventNow(EventFeatureActivated, SeverityNumber.INFO, {\n ...attrs,\n ...this.identityAttrs(sessionId),\n })\n })\n }, this.counters)\n }\n\n /** Records that a command's help output was requested (`-h`/`--help` or an explicit help command). */\n recordHelpFlagUsage(commandPath: string): void {\n safeRun(() => {\n if (!this.gate(Tier.Anonymous)) return\n this.emitEvent(EventHelpViewed, SeverityNumber.INFO, {\n [AttrCommandName]: this.name(commandPath),\n [AttrHelpFlag]: 'help',\n })\n }, this.counters)\n }\n\n /**\n * Records that a command failed with an error, classified by\n * `category` rather than its raw message or stack trace — this is\n * deliberately the only error-recording capability available below\n * `Tier.OptIn`. Raw error detail is only reachable via {@link optIn}.\n *\n * At every tier this counts the error on the `cli.errors` metric by\n * command. At `Tier.Basic`+ the category is attached as the error type\n * and a `cli.error.raised` event is emitted too, tied to the session and\n * install.\n *\n * `reason` is an optional, finer classification from a fixed vocabulary\n * you define (e.g. `\"no-token\"`, `\"invalid-url\"`), sent at `Tier.Basic`+\n * as `cli.error.reason` on both of those. It must be an identifier chosen\n * in code, **never error text or user input**: this SDK does not scrub it.\n * It must match `^[a-z0-9][a-z0-9._-]*$` and be at most 64 bytes; one that\n * doesn't is dropped (the error is still recorded, without a reason).\n */\n recordError(\n commandPath: string,\n category: ErrorCategory = ErrorCategoryValues.Unknown,\n reason?: string,\n ): void {\n safeRun(() => {\n if (!this.enabled()) return\n const cat = isValidErrorCategory(category) ? category : ErrorCategoryValues.Unknown\n const basic = tierAllows(this.tier, Tier.Basic)\n const attrs: Attributes = { [AttrCommandName]: this.name(commandPath) }\n if (basic) {\n attrs[AttrErrorType] = cat\n if (isValidIdentifier(reason)) attrs[AttrErrorReason] = reason\n }\n const sessionId = this.ensureSessionId()\n this.queue.push(() => {\n this.errorEventsCounter?.add(1, { ...this.tierAttr(), ...attrs })\n if (basic) {\n this.emitEventNow(EventErrorRaised, SeverityNumber.ERROR, {\n ...attrs,\n ...this.identityAttrs(sessionId),\n })\n }\n })\n }, this.counters)\n }\n\n /**\n * Adds `n` to a vendor-defined counter, sent as the `cli.counter` metric\n * with the `cli.counter.name` and, if given, `cli.counter.label`\n * attributes. Increments are summed in memory: one data point per name\n * and label is sent at each export, however often this is called, so it\n * is cheap in a hot loop.\n *\n * **Counters are accepted at the anonymous tier.** They are sent at every\n * tier, including `Tier.Anonymous` and in CI, even when the user has made\n * no consent choice. Nothing identifies the user, but `name` and `label`\n * are strings you choose, so a mistake here puts text into anonymous\n * data. They must be fixed identifiers chosen in code, **never user\n * input, file paths, host names, URLs, tokens or anything derived from\n * them**. This SDK does not scrub them.\n *\n * `name` and `label` must match `^[a-z0-9][a-z0-9._-]*$` and be at most\n * 64 bytes. If either does not, nothing is recorded: the increment is\n * dropped, not trimmed or sent without its label. `n` must be a positive\n * integer; anything else is ignored. The server caps the number of\n * distinct names and labels per tenant and folds the rest into `other`.\n *\n * Never throws, and does nothing on a disabled Client.\n */\n recordCounter(name: string, n: number, options: CounterOptions = {}): void {\n safeRun(() => {\n if (!this.gate(Tier.Anonymous)) return\n if (!isValidIdentifier(name)) return\n if (typeof n !== 'number' || !Number.isSafeInteger(n) || n <= 0) return\n const label = options?.label\n if (label !== undefined && !isValidIdentifier(label)) return\n const attrs: Attributes = { ...this.tierAttr(), [AttrCounterName]: name }\n if (label !== undefined) attrs[AttrCounterLabel] = label\n // Straight into the OTel counter, not the job queue: it sums per\n // attribute set in memory, so a hot loop neither allocates a record\n // per call nor overflows the queue.\n this.productCounter?.add(n, attrs)\n }, this.counters)\n }\n\n /**\n * Returns an {@link OptInScope} if, and only if, this Client's resolved\n * consent tier is `Tier.OptIn`; otherwise returns `undefined`. There is\n * no other way to reach raw error detail (message, stack trace)\n * anywhere in this package — it's structurally impossible to pass that\n * data through {@link recordError}'s signature.\n */\n optIn(): OptInScope | undefined {\n if (this.enabled() && this.tier === Tier.OptIn) return new OptInScope(this)\n return undefined\n }\n\n /** @internal called only by {@link OptInScope}. */\n _recordErrorDetail(commandPath: string, err: Error, stack?: string): void {\n safeRun(() => {\n if (!this.gate(Tier.OptIn)) return\n const attrs: Attributes = {\n [AttrCommandName]: this.name(commandPath),\n [AttrErrorMessage]: err.message,\n }\n if (stack) attrs[AttrErrorStack] = stack\n this.emitEvent(EventErrorRaised, SeverityNumber.ERROR, attrs)\n }, this.counters)\n }\n\n /**\n * Blocks until all telemetry queued so far has been handed to the\n * exporters and an export attempt has completed, or `timeoutMs`\n * elapses, whichever comes first. Safe to call on a disabled Client\n * (a no-op).\n */\n async flush(timeoutMs: number = this.shutdownTimeoutMs): Promise<void> {\n if (!this.enabled()) return\n await this.queue.waitForDrain(timeoutMs)\n // allSettled: an unreachable collector must never make this reject.\n await withTimeout(\n Promise.allSettled([\n this.tracerProvider?.forceFlush(),\n this.meterProvider?.forceFlush(),\n this.loggerProvider?.forceFlush(),\n ]).then(() => undefined),\n timeoutMs,\n )\n }\n\n /**\n * Flushes any queued telemetry (best-effort, bounded by `timeoutMs`)\n * and releases all background resources. After `shutdown`, the Client\n * permanently behaves as a disabled no-op. Safe to call on a disabled\n * Client, and safe to call more than once.\n */\n async shutdown(timeoutMs: number = this.shutdownTimeoutMs): Promise<void> {\n if (this.disabled || this.shutdownStarted) return\n this.shutdownStarted = true\n this.shuttingDown = true\n\n await this.queue.waitForDrain(timeoutMs)\n // allSettled: an unreachable collector must never make this reject.\n await withTimeout(\n Promise.allSettled([\n this.tracerProvider?.shutdown(),\n this.meterProvider?.shutdown(),\n this.loggerProvider?.shutdown(),\n ]).then(() => undefined),\n timeoutMs,\n )\n }\n}\n\n/**\n * Exposes telemetry capabilities that require the user's explicit\n * `Tier.OptIn` consent, structurally separated from {@link Client} so\n * that raw error content (messages, stack traces) can never be passed\n * through a lower-tier code path by mistake or misuse.\n */\nexport class OptInScope {\n constructor(private readonly client: Client) {}\n\n /** Records an error's message at full fidelity. */\n recordErrorDetail(commandPath: string, err: Error): void {\n this.client._recordErrorDetail(commandPath, err)\n }\n\n /** Identical to {@link recordErrorDetail} but also attaches a raw stack trace. */\n recordErrorDetailWithStack(commandPath: string, err: Error, stack: string): void {\n this.client._recordErrorDetail(commandPath, err, stack)\n }\n}\n\nfunction resolveConsentTier(cfg: ReturnType<typeof resolveConfig>): Tier {\n if (!cfg.consentProvider) return cfg.defaultTier\n try {\n const tier = cfg.consentProvider.resolve()\n return isValidTier(tier) ? tier : cfg.defaultTier\n } catch {\n return cfg.defaultTier\n }\n}\n\nfunction disabledClient(initError: Error | null = null): Client {\n return new Client({\n disabled: true,\n initError,\n tier: Tier.Anonymous,\n queueSize: 0,\n shutdownTimeoutMs: 0,\n })\n}\n\n/**\n * Constructs a {@link Client}. `apiKey`, `cliName`, and `cliVersion` are\n * always required; everything else has a sane default and is set via\n * `options`.\n *\n * `createClient` is synchronous and **never throws**: if construction\n * encounters a problem (e.g. the exporter transport can't be built, or a\n * `ConsentProvider` throws), it returns a Client already degraded to a\n * disabled no-op, with `client.initError` describing why. Callers may\n * inspect `initError` but are not required to before using the returned\n * Client safely.\n *\n * `createClient` resolves consent through a synchronous\n * {@link ConsentProvider} — see that interface's doc comment for why\n * resolution has to be synchronous on Node's single-threaded event loop.\n */\nexport function createClient(\n apiKey: string,\n cliName: string,\n cliVersion: string,\n options: ClientOptions = {},\n): Client {\n try {\n const cfg = resolveConfig(apiKey, cliName, cliVersion, options)\n\n if (cfg.disabled || process.env['ARGVIO_DISABLED'] === '1' || isDoNotTrackRequested()) {\n return disabledClient()\n }\n\n const tier = resolveConsentTier(cfg)\n const exporters = buildExporters(cfg)\n const resource = buildResource(cfg)\n\n const tracerProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [\n new BatchSpanProcessor(exporters.trace, {\n maxQueueSize: cfg.queueSize,\n exportTimeoutMillis: cfg.exportTimeoutMs,\n }),\n ],\n })\n const meterProvider = new MeterProvider({\n resource,\n readers: [\n new PeriodicExportingMetricReader({\n exporter: exporters.metric,\n exportTimeoutMillis: cfg.exportTimeoutMs,\n }),\n ],\n })\n const loggerProvider = new LoggerProvider({\n resource,\n processors: [\n new BatchLogRecordProcessor({\n exporter: exporters.log,\n maxQueueSize: cfg.queueSize,\n exportTimeoutMillis: cfg.exportTimeoutMs,\n }),\n ],\n })\n\n const meter = meterProvider.getMeter(INSTRUMENTATION_NAME)\n const logger = loggerProvider.getLogger(INSTRUMENTATION_NAME)\n\n return new Client({\n cliName,\n installIdPath: cfg.installIdPath,\n installMethod: cfg.installMethod,\n tracer: tracerProvider.getTracer(INSTRUMENTATION_NAME),\n disabled: false,\n initError: null,\n tier,\n queueSize: cfg.queueSize,\n shutdownTimeoutMs: cfg.shutdownTimeoutMs,\n tracerProvider,\n meterProvider,\n loggerProvider,\n logger,\n latencyHist: meter.createHistogram(MetricCommandDuration, {\n unit: 'ms',\n description: 'Duration of a CLI command invocation.',\n }),\n invocationsCounter: meter.createCounter(MetricCommandInvocations, {\n unit: '1',\n description: 'Count of completed CLI command invocations.',\n }),\n errorEventsCounter: meter.createCounter(MetricErrors, {\n unit: '1',\n description: 'Count of recorded CLI errors.',\n }),\n productCounter: meter.createCounter(MetricCounter, {\n unit: '1',\n description: 'Vendor-defined counters, by fixed name and optional label.',\n }),\n })\n } catch (err) {\n return disabledClient(toError(err))\n }\n}\n","import { Tier, isValidTier } from './tier.js'\nimport { errNoProviderResolved } from './errors.js'\n\n/**\n * Resolves the consent tier that should be used for the current\n * process. Consulted once per {@link Client}, synchronously, at\n * construction time (cached for the process lifetime — consent is not\n * expected to change mid-invocation of a short-lived CLI command).\n *\n * `resolve` here is **synchronous**: Node's single-threaded event loop\n * has no way to synchronously await a Promise, and `createClient` must\n * return a fully\n * resolved, usable Client without an async round-trip (see the \"why\n * createClient is synchronous\" note in client.ts). Implementations must\n * therefore be fast and local only — env vars, an already-loaded config\n * object, a synchronous local file read — never network I/O. A provider\n * that throws is treated identically to `Tier.Anonymous` (fail closed).\n */\nexport interface ConsentProvider {\n resolve(): Tier\n}\n\n/**\n * A {@link ConsentProvider} that always resolves to a fixed tier. Useful\n * for tests, for vendors who resolve consent themselves before\n * constructing the Client, or as a fallback wrapped by\n * {@link chainProviders}.\n */\nexport class StaticProvider implements ConsentProvider {\n constructor(private readonly tier: Tier) {}\n\n resolve(): Tier {\n return isValidTier(this.tier) ? this.tier : Tier.Anonymous\n }\n}\n\n/**\n * A {@link ConsentProvider} that always resolves to `Tier.Anonymous`. It\n * exists as an explicit, self-documenting choice distinct from \"a\n * provider that happens to return anonymous\".\n */\nexport class DisabledProvider implements ConsentProvider {\n resolve(): Tier {\n return Tier.Anonymous\n }\n}\n\n/**\n * Returns a {@link ConsentProvider} that tries each provider in order\n * and returns the first successful (non-throwing) result. If all\n * providers throw, it throws {@link errNoProviderResolved} (the caller\n * treats that as `Tier.Anonymous`, same as any other thrown error). Lets\n * a vendor compose, e.g., \"env override, then config file, then\n * anonymous default\" without writing that logic themselves.\n */\nexport function chainProviders(\n ...providers: ReadonlyArray<ConsentProvider | null | undefined>\n): ConsentProvider {\n return {\n resolve(): Tier {\n for (const provider of providers) {\n if (!provider) continue\n try {\n return provider.resolve()\n } catch {\n continue\n }\n }\n throw errNoProviderResolved\n },\n }\n}\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@getargvio/argvio",
3
3
  "description": "Node.js SDK for emitting CLI usage telemetry to Argvio's ingest server, built around a client-enforced consent tier model",
4
- "version": "0.1.0",
4
+ "version": "0.5.0",
5
5
  "author": "getargvio",
6
6
  "type": "module",
7
7
  "license": "MIT",
@@ -43,13 +43,6 @@
43
43
  "engines": {
44
44
  "node": ">=22.0.0"
45
45
  },
46
- "scripts": {
47
- "build": "tsup",
48
- "typecheck": "tsc --noEmit",
49
- "test": "vitest run",
50
- "bench": "vitest bench",
51
- "prepublishOnly": "npm run build"
52
- },
53
46
  "dependencies": {
54
47
  "@grpc/grpc-js": "^1.9.0",
55
48
  "@opentelemetry/api": "^1.9.1",
@@ -70,5 +63,11 @@
70
63
  "@types/node": "^24",
71
64
  "typescript": "^5",
72
65
  "vitest": "^4.1.11"
66
+ },
67
+ "scripts": {
68
+ "build": "tsup",
69
+ "typecheck": "tsc --noEmit",
70
+ "test": "vitest run",
71
+ "bench": "vitest bench"
73
72
  }
74
- }
73
+ }