@superbased/sdk 0.0.0-stage → 0.1.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.
Files changed (119) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +438 -2
  4. package/dist/cjs/admit.d.ts +139 -0
  5. package/dist/cjs/admit.js +442 -0
  6. package/dist/cjs/admit.js.map +1 -0
  7. package/dist/cjs/attrs.d.ts +113 -0
  8. package/dist/cjs/attrs.js +183 -0
  9. package/dist/cjs/attrs.js.map +1 -0
  10. package/dist/cjs/config.d.ts +202 -0
  11. package/dist/cjs/config.js +386 -0
  12. package/dist/cjs/config.js.map +1 -0
  13. package/dist/cjs/context.d.ts +102 -0
  14. package/dist/cjs/context.js +234 -0
  15. package/dist/cjs/context.js.map +1 -0
  16. package/dist/cjs/control.d.ts +99 -0
  17. package/dist/cjs/control.js +243 -0
  18. package/dist/cjs/control.js.map +1 -0
  19. package/dist/cjs/cost.d.ts +108 -0
  20. package/dist/cjs/cost.js +211 -0
  21. package/dist/cjs/cost.js.map +1 -0
  22. package/dist/cjs/destination.d.ts +125 -0
  23. package/dist/cjs/destination.js +357 -0
  24. package/dist/cjs/destination.js.map +1 -0
  25. package/dist/cjs/experiments.d.ts +237 -0
  26. package/dist/cjs/experiments.js +678 -0
  27. package/dist/cjs/experiments.js.map +1 -0
  28. package/dist/cjs/export.d.ts +84 -0
  29. package/dist/cjs/export.js +328 -0
  30. package/dist/cjs/export.js.map +1 -0
  31. package/dist/cjs/index.d.ts +168 -0
  32. package/dist/cjs/index.js +581 -0
  33. package/dist/cjs/index.js.map +1 -0
  34. package/dist/cjs/instrument.d.ts +88 -0
  35. package/dist/cjs/instrument.js +397 -0
  36. package/dist/cjs/instrument.js.map +1 -0
  37. package/dist/cjs/package.json +1 -0
  38. package/dist/cjs/policy.d.ts +77 -0
  39. package/dist/cjs/policy.js +252 -0
  40. package/dist/cjs/policy.js.map +1 -0
  41. package/dist/cjs/prompts.d.ts +175 -0
  42. package/dist/cjs/prompts.js +476 -0
  43. package/dist/cjs/prompts.js.map +1 -0
  44. package/dist/cjs/propagation.d.ts +34 -0
  45. package/dist/cjs/propagation.js +151 -0
  46. package/dist/cjs/propagation.js.map +1 -0
  47. package/dist/cjs/req.d.ts +10 -0
  48. package/dist/cjs/req.js +3 -0
  49. package/dist/cjs/req.js.map +1 -0
  50. package/dist/cjs/runtime.d.ts +44 -0
  51. package/dist/cjs/runtime.js +67 -0
  52. package/dist/cjs/runtime.js.map +1 -0
  53. package/dist/cjs/scores.d.ts +102 -0
  54. package/dist/cjs/scores.js +226 -0
  55. package/dist/cjs/scores.js.map +1 -0
  56. package/dist/cjs/spans.d.ts +193 -0
  57. package/dist/cjs/spans.js +398 -0
  58. package/dist/cjs/spans.js.map +1 -0
  59. package/dist/cjs/vendor.d.ts +33 -0
  60. package/dist/cjs/vendor.js +67 -0
  61. package/dist/cjs/vendor.js.map +1 -0
  62. package/dist/esm/admit.d.ts +139 -0
  63. package/dist/esm/admit.js +432 -0
  64. package/dist/esm/admit.js.map +1 -0
  65. package/dist/esm/attrs.d.ts +113 -0
  66. package/dist/esm/attrs.js +179 -0
  67. package/dist/esm/attrs.js.map +1 -0
  68. package/dist/esm/config.d.ts +202 -0
  69. package/dist/esm/config.js +364 -0
  70. package/dist/esm/config.js.map +1 -0
  71. package/dist/esm/context.d.ts +102 -0
  72. package/dist/esm/context.js +221 -0
  73. package/dist/esm/context.js.map +1 -0
  74. package/dist/esm/control.d.ts +99 -0
  75. package/dist/esm/control.js +230 -0
  76. package/dist/esm/control.js.map +1 -0
  77. package/dist/esm/cost.d.ts +108 -0
  78. package/dist/esm/cost.js +202 -0
  79. package/dist/esm/cost.js.map +1 -0
  80. package/dist/esm/destination.d.ts +125 -0
  81. package/dist/esm/destination.js +346 -0
  82. package/dist/esm/destination.js.map +1 -0
  83. package/dist/esm/experiments.d.ts +237 -0
  84. package/dist/esm/experiments.js +666 -0
  85. package/dist/esm/experiments.js.map +1 -0
  86. package/dist/esm/export.d.ts +84 -0
  87. package/dist/esm/export.js +314 -0
  88. package/dist/esm/export.js.map +1 -0
  89. package/dist/esm/index.d.ts +168 -0
  90. package/dist/esm/index.js +500 -0
  91. package/dist/esm/index.js.map +1 -0
  92. package/dist/esm/instrument.d.ts +88 -0
  93. package/dist/esm/instrument.js +391 -0
  94. package/dist/esm/instrument.js.map +1 -0
  95. package/dist/esm/policy.d.ts +77 -0
  96. package/dist/esm/policy.js +240 -0
  97. package/dist/esm/policy.js.map +1 -0
  98. package/dist/esm/prompts.d.ts +175 -0
  99. package/dist/esm/prompts.js +460 -0
  100. package/dist/esm/prompts.js.map +1 -0
  101. package/dist/esm/propagation.d.ts +34 -0
  102. package/dist/esm/propagation.js +145 -0
  103. package/dist/esm/propagation.js.map +1 -0
  104. package/dist/esm/req.d.ts +10 -0
  105. package/dist/esm/req.js +2 -0
  106. package/dist/esm/req.js.map +1 -0
  107. package/dist/esm/runtime.d.ts +44 -0
  108. package/dist/esm/runtime.js +59 -0
  109. package/dist/esm/runtime.js.map +1 -0
  110. package/dist/esm/scores.d.ts +102 -0
  111. package/dist/esm/scores.js +219 -0
  112. package/dist/esm/scores.js.map +1 -0
  113. package/dist/esm/spans.d.ts +193 -0
  114. package/dist/esm/spans.js +378 -0
  115. package/dist/esm/spans.js.map +1 -0
  116. package/dist/esm/vendor.d.ts +33 -0
  117. package/dist/esm/vendor.js +61 -0
  118. package/dist/esm/vendor.js.map +1 -0
  119. package/package.json +130 -4
@@ -0,0 +1,168 @@
1
+ /**
2
+ * superbased SDK for TypeScript / Node: send LLM-app and agent traces to
3
+ * superbased over OpenTelemetry (OTLP/HTTP).
4
+ *
5
+ * A thin layer over OpenTelemetry JS 2.x that exports spans to the Observer
6
+ * on this machine (`http://127.0.0.1:4318/v1/traces` by default), to an org
7
+ * or SaaS OTLP gateway, or to both, and tags them with superbased attributes.
8
+ * Anything it does, a raw OTel exporter pointed at Observer does too.
9
+ *
10
+ * IMPORTANT: never set `sbo.emitted_by=observer`: that is Observer's own
11
+ * echo-guard marker and such a resource is DROPPED at ingestion.
12
+ */
13
+ import { type TracerProvider } from "@opentelemetry/api";
14
+ import { type SpanExporter, type SpanProcessor } from "@opentelemetry/sdk-trace-base";
15
+ import { type DestinationChoice, type Settings, type SettingsInput } from "./config.js";
16
+ import { type MaskFn, type ShouldExportFn } from "./policy.js";
17
+ import { type VendorTracing } from "./vendor.js";
18
+ export { VERSION } from "./runtime.js";
19
+ export { admit, Degraded, DEFAULT_ADMISSION_ENDPOINT, DEFAULT_ADMIT_TIMEOUT_MS, SDK_ADMIT_PATH, parseVerdict, type AdmitOptions, type Verdict, } from "./admit.js";
20
+ export { DEFAULT_DISCOVER_TIMEOUT_MS, DEFAULT_ENDPOINT, DEFAULT_EXPORT_TIMEOUT_MS, DEFAULT_MAX_CONTENT_CHARS, DEFAULT_API_TIMEOUT_MS, DEFAULT_NODE_URL, DEFAULT_PROMPT_CACHE_TTL_MS, DEFAULT_SERVICE_NAME, DEFAULT_SHUTDOWN_TIMEOUT_MS, DESTINATION_CHOICES, destinations, parseKvList, resolveSettings, type Destination, type DestinationChoice, type Settings, type SettingsInput, } from "./config.js";
21
+ export { K as Attr, LIMITS, REQUEST_PARAMS, SEMCONV_COMMIT, SEMCONV_SCHEMA_URL } from "./attrs.js";
22
+ export { getCurrentAttributes, identify, propagateAttributes, type AttributeScope, type PropagateOptions, type TraceAttributes, } from "./context.js";
23
+ export { DISCOVERY_PATH, isLoopbackUrl, parseDiscovery, readCredentialFile, type Discovered } from "./destination.js";
24
+ export { keepTrace, TRUNCATED_MARK, type MaskFn, type ShouldExportFn } from "./policy.js";
25
+ export { continueTrace, extract, getTraceparent, inject, type Carrier } from "./propagation.js";
26
+ export { Kind, getCurrentSpanId, getCurrentTraceId, observe, setContent, setDocuments, setInput, setOutput, setRequestParams, setToolResult, setUsage, withAgentSpan, withEmbeddingSpan, withLlmSpan, withRetrieverSpan, withSpan, withToolSpan, type AgentInfo, type Content, type Document, type EmbeddingInfo, type LlmInfo, type ObserveOptions, type PromptRef, type RequestParams, type RetrieverInfo, type SpanOptions, type SpanKind, type ToolInfo, type Usage, } from "./spans.js";
27
+ export * from "./scores.js";
28
+ export * from "./cost.js";
29
+ export * from "./prompts.js";
30
+ export * from "./experiments.js";
31
+ export * from "./instrument.js";
32
+ export interface InitOptions extends SettingsInput {
33
+ /** Also print spans to stdout (debugging). Env: SUPERBASED_CONSOLE. */
34
+ console?: boolean;
35
+ /** A SpanExporter to use instead of OTLP/HTTP (tests, custom transport). Replaces every destination. */
36
+ exporter?: SpanExporter;
37
+ /**
38
+ * A tracer provider to hold the SDK's spans instead of the global one. An
39
+ * OTel JS 1.x provider gets the SDK's processor added; a 2.x provider must
40
+ * have been built with `spanProcessors: [spanProcessor()]`.
41
+ */
42
+ tracerProvider?: TracerProvider;
43
+ /** Rewrite each content value before export (fail-safe: a throw withholds the value). Code only. */
44
+ mask?: MaskFn;
45
+ /** Return false to drop a finished span. Code only. */
46
+ shouldExport?: ShouldExportFn;
47
+ }
48
+ /** How the SDK holds spans: its own registered provider, the host's provider, or a private one. */
49
+ export type Mode = "" | "owned" | "attached" | "standalone";
50
+ /**
51
+ * The SDK's span processor, for an app on OpenTelemetry JS 2.x that builds its
52
+ * own provider (2.x providers take processors only at construction):
53
+ *
54
+ * ```ts
55
+ * const provider = new NodeTracerProvider({ spanProcessors: [spanProcessor(), ...yours] });
56
+ * provider.register();
57
+ * init({ serviceName: "my-app" }); // exports through that provider
58
+ * ```
59
+ */
60
+ export declare function spanProcessor(): SpanProcessor;
61
+ /**
62
+ * Configure tracing to export to superbased over OTLP/HTTP. Idempotent.
63
+ *
64
+ * Every option maps to an env var (`SUPERBASED_*`, then the standard `OTEL_*`
65
+ * one where it exists); an explicit option wins. See the README's settings
66
+ * table.
67
+ *
68
+ * Destination (D18): `local` (this machine), `online` (the org or SaaS
69
+ * gateway) or `both`, from the option, `SUPERBASED_DESTINATION`, the local
70
+ * Observer's default, then a fallback. See {@link ready}.
71
+ *
72
+ * - No provider registered yet: the SDK registers its own (mode `owned`).
73
+ * - An OTel JS 1.x SDK provider is registered: the SDK adds its processor to
74
+ * it (mode `attached`).
75
+ * - An OTel JS 2.x provider built with `spanProcessors: [spanProcessor()]`:
76
+ * the SDK exports through it (mode `attached`).
77
+ * - Any other provider is registered: the SDK keeps a private provider for
78
+ * its own spans (mode `standalone`); they still join the active trace.
79
+ *
80
+ * A second call with the same settings is a no-op; with different settings it
81
+ * replaces the SDK's exporters in place, shutting the previous ones down.
82
+ */
83
+ export declare function init(opts?: InitOptions): Settings;
84
+ /**
85
+ * Resolves once the destination is known (immediately unless init is asking
86
+ * the local Observer for its default, which takes at most
87
+ * `discoverTimeoutMs`). Spans finished before then are held, not lost.
88
+ */
89
+ export declare function ready(): Promise<DestinationChoice | "">;
90
+ /**
91
+ * The settings the last `init()` resolved (null before init). `apiKey` and the
92
+ * header maps are readable but not enumerable, so logging the object never
93
+ * prints the credential.
94
+ */
95
+ export declare function settings(): Settings | null;
96
+ /**
97
+ * Export every finished span now. Bounded by `timeoutMs` (default: the
98
+ * shutdownTimeoutMs setting). Resolves true when everything went out in time;
99
+ * never rejects. Await it at the end of a serverless handler.
100
+ */
101
+ export declare function flush(timeoutMs?: number): Promise<boolean>;
102
+ /**
103
+ * Flush and stop the SDK's exporters. Bounded by `timeoutMs` even when an
104
+ * endpoint is down; never rejects (ECONNREFUSED, 302 and 401 included). The
105
+ * host's provider, when the SDK attached to one, keeps running. A later
106
+ * `init()` starts exporting again.
107
+ */
108
+ export declare function shutdown(timeoutMs?: number): Promise<boolean>;
109
+ export interface Diagnostics {
110
+ mode: Mode;
111
+ initialized: boolean;
112
+ /** local, online or both, or "" while discovering (or before init). */
113
+ destination: DestinationChoice | "";
114
+ /** Where it came from: argument, env, machine, inferred, default, exporter, or discovering. */
115
+ destinationSource: string;
116
+ /** The exporters running now. */
117
+ destinations: Array<{
118
+ name: string;
119
+ endpoint: string;
120
+ }>;
121
+ /** Why the destination could not be honoured in full (also logged once as warnings). */
122
+ destinationProblems: string[];
123
+ /** The gateway's base URL in force ("" when none). */
124
+ gatewayUrl: string;
125
+ /** The degraded reason ("" when the destination is honoured in full; contract destination.md section 7). */
126
+ degraded: string;
127
+ /** Informational lines, for example why discovery got no answer. */
128
+ notes: string[];
129
+ /** What the machine reported about sign-in; null when no machine answered. */
130
+ signedIn: boolean | null;
131
+ /** Where the credential came from: argument, env, file, or "" (never the credential itself). */
132
+ credentialSource: string;
133
+ pendingSpans: number;
134
+ exportedSpans: number;
135
+ failedExports: number;
136
+ droppedSpans: number;
137
+ /** Spans left out by head sampling (sampleRate). */
138
+ sampledOutSpans: number;
139
+ /** Spans dropped by shouldExport. */
140
+ filteredSpans: number;
141
+ /** shouldExport hooks that threw (the span was kept). */
142
+ shouldExportErrors: number;
143
+ /** mask hooks that threw (that value was dropped). */
144
+ maskErrors: number;
145
+ lastHookError: string;
146
+ lastError: string;
147
+ /** Epoch ms of the last error, 0 when none. */
148
+ lastErrorAt: number;
149
+ /** Control API calls (scores, prompts, datasets, experiments) made and failed. */
150
+ controlCalls: number;
151
+ controlFailures: number;
152
+ controlLastError: string;
153
+ /** admit() calls that got no decision (admitted, or denied under failClosed), and why the last one (review E-39). */
154
+ admissionDegraded: number;
155
+ admissionLastError: string;
156
+ /** Epoch ms of that last one, 0 when none. */
157
+ admissionLastErrorAt: number;
158
+ /** Per model client library that traces itself (`anthropic`): `off` (init() turned its own spans off; `instrument([...])` records the calls) or `kept` (the app set its switch, e.g. `ANTHROPIC_OPEN_TELEMETRY=true`). */
159
+ vendorTracing: Record<string, VendorTracing>;
160
+ /** Spans from such a library dropped at export (a client built before init()). */
161
+ vendorSpansDropped: number;
162
+ /** setUsage calls whose inputTokens was below its cache parts, recorded as a net count (input + cache). */
163
+ usageNetInputCorrected: number;
164
+ }
165
+ /** A snapshot of the SDK's export health. */
166
+ export declare function diagnostics(): Diagnostics;
167
+ /** Forget all SDK state (tests only). Does not touch the global provider. */
168
+ export declare function _resetForTests(): Promise<void>;
@@ -0,0 +1,500 @@
1
+ /**
2
+ * superbased SDK for TypeScript / Node: send LLM-app and agent traces to
3
+ * superbased over OpenTelemetry (OTLP/HTTP).
4
+ *
5
+ * A thin layer over OpenTelemetry JS 2.x that exports spans to the Observer
6
+ * on this machine (`http://127.0.0.1:4318/v1/traces` by default), to an org
7
+ * or SaaS OTLP gateway, or to both, and tags them with superbased attributes.
8
+ * Anything it does, a raw OTel exporter pointed at Observer does too.
9
+ *
10
+ * IMPORTANT: never set `sbo.emitted_by=observer`: that is Observer's own
11
+ * echo-guard marker and such a resource is DROPPED at ingestion.
12
+ */
13
+ import { ProxyTracerProvider, trace } from "@opentelemetry/api";
14
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
15
+ import { defaultResource, resourceFromAttributes } from "@opentelemetry/resources";
16
+ import { BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor, } from "@opentelemetry/sdk-trace-base";
17
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
18
+ import { K } from "./attrs.js";
19
+ import { destinationProblems, destinations, localEndpointNamed, resolveDestinationChoice, resolveSettings, } from "./config.js";
20
+ import { _resetContextForTests, Scope } from "./context.js";
21
+ import { discoverDestination, PendingProcessor, withDiscovered } from "./destination.js";
22
+ import { bounded, CountingExporter, Fanout, SwitchableProcessor, flushBounded, maybeLogFailures, resetStats, shutdownBounded, snapshot, stats, } from "./export.js";
23
+ import { controlIdle, controlStats, resetControlForTests } from "./control.js";
24
+ import { policyStats, resetPolicyStats, SwitchableSampler } from "./policy.js";
25
+ import { applyVendorTracing, dropScopePrefixes, resetVendorTracingForTests } from "./vendor.js";
26
+ import { _resetNetInputWarningForTests } from "./spans.js";
27
+ import { clearPromptCache } from "./prompts.js";
28
+ import { resetRuntime, runtime, SDK_MARKER, TRACER_NAME, VERSION } from "./runtime.js";
29
+ export { VERSION } from "./runtime.js";
30
+ export { admit, Degraded, DEFAULT_ADMISSION_ENDPOINT, DEFAULT_ADMIT_TIMEOUT_MS, SDK_ADMIT_PATH, parseVerdict, } from "./admit.js";
31
+ import { admitStats, resetAdmitStats } from "./admit.js";
32
+ export { DEFAULT_DISCOVER_TIMEOUT_MS, DEFAULT_ENDPOINT, DEFAULT_EXPORT_TIMEOUT_MS, DEFAULT_MAX_CONTENT_CHARS, DEFAULT_API_TIMEOUT_MS, DEFAULT_NODE_URL, DEFAULT_PROMPT_CACHE_TTL_MS, DEFAULT_SERVICE_NAME, DEFAULT_SHUTDOWN_TIMEOUT_MS, DESTINATION_CHOICES, destinations, parseKvList, resolveSettings, } from "./config.js";
33
+ export { K as Attr, LIMITS, REQUEST_PARAMS, SEMCONV_COMMIT, SEMCONV_SCHEMA_URL } from "./attrs.js";
34
+ export { getCurrentAttributes, identify, propagateAttributes, } from "./context.js";
35
+ export { DISCOVERY_PATH, isLoopbackUrl, parseDiscovery, readCredentialFile } from "./destination.js";
36
+ export { keepTrace, TRUNCATED_MARK } from "./policy.js";
37
+ export { continueTrace, extract, getTraceparent, inject } from "./propagation.js";
38
+ export { Kind, getCurrentSpanId, getCurrentTraceId, observe, setContent, setDocuments, setInput, setOutput, setRequestParams, setToolResult, setUsage, withAgentSpan, withEmbeddingSpan, withLlmSpan, withRetrieverSpan, withSpan, withToolSpan, } from "./spans.js";
39
+ export * from "./scores.js";
40
+ export * from "./cost.js";
41
+ export * from "./prompts.js";
42
+ export * from "./experiments.js";
43
+ export * from "./instrument.js";
44
+ const processor = new SwitchableProcessor();
45
+ const sampler = new SwitchableSampler();
46
+ let processorHandedOut = false;
47
+ const state = {
48
+ provider: null,
49
+ ownProvider: null,
50
+ mode: "",
51
+ configKey: "",
52
+ exitHooked: false,
53
+ active: [],
54
+ problems: [],
55
+ notes: [],
56
+ signedIn: null,
57
+ effective: null,
58
+ ready: Promise.resolve(),
59
+ vendorTracing: {},
60
+ };
61
+ let ownResource = {};
62
+ const objectIds = new WeakMap();
63
+ let nextObjectId = 1;
64
+ let initGeneration = 0;
65
+ function oid(o) {
66
+ if (!o)
67
+ return 0;
68
+ let id = objectIds.get(o);
69
+ if (!id) {
70
+ id = nextObjectId++;
71
+ objectIds.set(o, id);
72
+ }
73
+ return id;
74
+ }
75
+ /**
76
+ * The SDK's span processor, for an app on OpenTelemetry JS 2.x that builds its
77
+ * own provider (2.x providers take processors only at construction):
78
+ *
79
+ * ```ts
80
+ * const provider = new NodeTracerProvider({ spanProcessors: [spanProcessor(), ...yours] });
81
+ * provider.register();
82
+ * init({ serviceName: "my-app" }); // exports through that provider
83
+ * ```
84
+ */
85
+ export function spanProcessor() {
86
+ processorHandedOut = true;
87
+ return processor;
88
+ }
89
+ function globalDelegate() {
90
+ const tp = trace.getTracerProvider();
91
+ const d = tp instanceof ProxyTracerProvider ? tp.getDelegate() : tp;
92
+ const noop = new ProxyTracerProvider().getDelegate();
93
+ if (!d || d.constructor === noop.constructor)
94
+ return null;
95
+ return d;
96
+ }
97
+ function addable(tp) {
98
+ return typeof tp.addSpanProcessor === "function";
99
+ }
100
+ function warnOnce(lines) {
101
+ for (const l of lines) {
102
+ stats.lastError = l;
103
+ stats.lastErrorAt = Date.now();
104
+ try {
105
+ console.warn(`@superbased/sdk: ${l}`);
106
+ }
107
+ catch {
108
+ // ignore
109
+ }
110
+ }
111
+ }
112
+ /** One exporter per destination; each on its own batch processor, so one failing never blocks another. */
113
+ function buildDelegate(dests, exporter, console) {
114
+ const targets = exporter ? [dests[0] ?? { name: "local", endpoint: "", headers: {}, timeoutMs: 5000 }] : dests;
115
+ const procs = targets.map((d) => new BatchSpanProcessor(new CountingExporter(exporter ?? new OTLPTraceExporter({ url: d.endpoint, headers: d.headers, timeoutMillis: d.timeoutMs })), { exportTimeoutMillis: d.timeoutMs }));
116
+ if (console)
117
+ procs.push(new SimpleSpanProcessor(new ConsoleSpanExporter()));
118
+ if (procs.length === 0)
119
+ return null;
120
+ // Each destination's CountingExporter counts a span on its own; the console
121
+ // processor counts nothing (review E-31).
122
+ if (procs.length === 1 && targets.length === 1)
123
+ return procs[0];
124
+ return new Fanout(procs, targets.length);
125
+ }
126
+ /** A delegate that drops (and counts) every span: an online-only choice with no online URL. */
127
+ class DroppingProcessor {
128
+ onStart() { }
129
+ onEnd() {
130
+ stats.droppedSpans += 1;
131
+ }
132
+ async forceFlush() { }
133
+ async shutdown() { }
134
+ }
135
+ function installExitHook() {
136
+ if (state.exitHooked || typeof process === "undefined" || typeof process.on !== "function")
137
+ return;
138
+ state.exitHooked = true;
139
+ let running = false;
140
+ process.on("beforeExit", () => {
141
+ // beforeExit fires again after the flush's work drains; only flush when
142
+ // something is pending, so the loop ends.
143
+ if (running || !runtime.settings?.exitHook || !processor.active)
144
+ return;
145
+ if (Number(snapshot().pendingSpans) === 0)
146
+ return;
147
+ running = true;
148
+ void flush().finally(() => {
149
+ running = false;
150
+ });
151
+ });
152
+ }
153
+ /**
154
+ * The destination when it can be known without the machine; null = ask the
155
+ * machine first (contract destination.md section 3; sdk-api-surface.md
156
+ * section 6). The machine is asked when nothing chose a destination, and
157
+ * also when an explicit `online` / `both` still lacks a gateway URL or a
158
+ * credential, which discovery supplies (review finding R-B09; Python does
159
+ * the same), and when an explicit `local` / `both` has no endpoint the app
160
+ * named for the local destination: the machine advertises its receiver
161
+ * (live finding L-01). A named endpoint (the option or
162
+ * SUPERBASED_OTLP_ENDPOINT, or under `local` an OTEL_* one) needs no answer.
163
+ */
164
+ function syncChoice(opts, env, s) {
165
+ const chosen = resolveDestinationChoice(opts.destination, env);
166
+ const onlineGap = (c) => (c === "online" || c === "both") && (!s.orgUrl || !s.apiKey);
167
+ // A local destination the app named no endpoint for exports to the receiver
168
+ // the machine advertises (a machine on other ports; live finding L-01).
169
+ const localGap = (c) => (c === "local" || c === "both") && !localEndpointNamed(s, c);
170
+ const canAsk = s.discover && s.discoverTimeoutMs > 0;
171
+ // A caller-supplied exporter takes every span; control calls follow the choice ("" = online when configured, else local).
172
+ if (opts.exporter)
173
+ return [chosen.choice, "exporter"];
174
+ if (chosen.choice && !(canAsk && (onlineGap(chosen.choice) || localGap(chosen.choice))))
175
+ return [chosen.choice, chosen.source];
176
+ if (!canAsk)
177
+ return chosen.choice ? [chosen.choice, chosen.source] : s.orgUrl && s.apiKey ? ["online", "inferred"] : ["local", "default"];
178
+ return null;
179
+ }
180
+ /** No destination chosen and no machine answered: a gateway and a credential given to the app mean `online`. */
181
+ function inferred(s, otherwise) {
182
+ return s.orgUrl && s.apiKey ? "online" : otherwise;
183
+ }
184
+ function activate(s, choice, source, opts, printSpans, extraProblems = [], notes = [], signedIn = null) {
185
+ runtime.settings = s;
186
+ runtime.resourceService = ""; // a new init: the next span says which service
187
+ state.effective = s;
188
+ state.notes = notes;
189
+ state.signedIn = signedIn;
190
+ if (s.debug)
191
+ for (const n of notes)
192
+ console.info(`@superbased/sdk: ${n}`);
193
+ runtime.destination = choice;
194
+ runtime.destinationSource = source;
195
+ const dests = destinations(s, choice);
196
+ state.active = opts.exporter ? dests.slice(0, 1) : dests;
197
+ state.problems = [
198
+ ...(s.destinationInvalid ? [s.destinationInvalid] : []),
199
+ ...(s.samplingInvalid ? [s.samplingInvalid] : []),
200
+ ...extraProblems,
201
+ ...(opts.exporter ? [] : destinationProblems(s, choice)),
202
+ ];
203
+ if (state.problems.length)
204
+ warnOnce(state.problems);
205
+ return buildDelegate(dests, opts.exporter, printSpans) ?? new DroppingProcessor();
206
+ }
207
+ /**
208
+ * Configure tracing to export to superbased over OTLP/HTTP. Idempotent.
209
+ *
210
+ * Every option maps to an env var (`SUPERBASED_*`, then the standard `OTEL_*`
211
+ * one where it exists); an explicit option wins. See the README's settings
212
+ * table.
213
+ *
214
+ * Destination (D18): `local` (this machine), `online` (the org or SaaS
215
+ * gateway) or `both`, from the option, `SUPERBASED_DESTINATION`, the local
216
+ * Observer's default, then a fallback. See {@link ready}.
217
+ *
218
+ * - No provider registered yet: the SDK registers its own (mode `owned`).
219
+ * - An OTel JS 1.x SDK provider is registered: the SDK adds its processor to
220
+ * it (mode `attached`).
221
+ * - An OTel JS 2.x provider built with `spanProcessors: [spanProcessor()]`:
222
+ * the SDK exports through it (mode `attached`).
223
+ * - Any other provider is registered: the SDK keeps a private provider for
224
+ * its own spans (mode `standalone`); they still join the active trace.
225
+ *
226
+ * A second call with the same settings is a no-op; with different settings it
227
+ * replaces the SDK's exporters in place, shutting the previous ones down.
228
+ */
229
+ export function init(opts = {}) {
230
+ const { console: consoleOpt, exporter, tracerProvider, mask, shouldExport, ...input } = opts;
231
+ const env = (typeof process !== "undefined" ? process.env : {});
232
+ const s = resolveSettings(env, input);
233
+ const printSpans = consoleOpt ?? ["1", "true", "yes", "on"].includes((env.SUPERBASED_CONSOLE ?? "").toLowerCase());
234
+ runtime.settings = s;
235
+ runtime.resourceService = ""; // a new init: the next span says which service
236
+ runtime.captureContent = s.captureContent;
237
+ runtime.maxContentChars = s.maxContentChars;
238
+ stats.debug = s.debug;
239
+ sampler.set(s.sampleRate, s.parentBased);
240
+ // A model client library that traces itself (the Anthropic SDKs) would
241
+ // record every call a second time on the provider registered below.
242
+ state.vendorTracing = applyVendorTracing();
243
+ processor.policy = {
244
+ captureContent: s.captureContent,
245
+ maxContentChars: s.maxContentChars,
246
+ mask,
247
+ shouldExport,
248
+ exportRatio: state.mode === "attached" ? s.sampleRate : undefined,
249
+ dropScopePrefixes: dropScopePrefixes(state.vendorTracing),
250
+ };
251
+ const { captureContent: _c, maxContentChars: _m, exitHook: _e, debug: _d, sampleRate: _r, parentBased: _pb, discoverTimeoutMs: _t, apiTimeoutMs: _a, promptCacheTtlMs: _p, ...exportShape } = s;
252
+ const configKey = JSON.stringify([exportShape, printSpans, oid(exporter), oid(tracerProvider)]);
253
+ if (processor.active && configKey === state.configKey)
254
+ return publicView(s);
255
+ // Process-wide identity on the resource (contract section 2): release and
256
+ // environment as the standard service.version / deployment.environment.name.
257
+ const base = new Scope().merged({ tenant: s.tenant, user: s.user, sessionId: s.sessionId, tags: s.tags, metadata: s.metadata });
258
+ const ident = { [K.sdk]: SDK_MARKER, ...base.attributes() };
259
+ if (s.release)
260
+ ident[K.serviceVersion] = s.release;
261
+ if (s.environment)
262
+ ident[K.deploymentEnvironment] = s.environment;
263
+ if (!state.provider || (tracerProvider && tracerProvider !== state.provider)) {
264
+ const candidate = tracerProvider ?? globalDelegate();
265
+ if (candidate && candidate === state.ownProvider) {
266
+ state.provider = candidate;
267
+ state.mode = "owned";
268
+ }
269
+ else if (candidate && addable(candidate)) {
270
+ candidate.addSpanProcessor(processor);
271
+ state.provider = candidate;
272
+ state.mode = "attached";
273
+ }
274
+ else if (candidate && processorHandedOut) {
275
+ state.provider = candidate;
276
+ state.mode = "attached";
277
+ }
278
+ else {
279
+ ownResource = { ...s.resourceAttributes, ...ident, "service.name": s.serviceName };
280
+ const own = new NodeTracerProvider({
281
+ resource: defaultResource().merge(resourceFromAttributes(ownResource)),
282
+ spanProcessors: [processor],
283
+ sampler,
284
+ });
285
+ state.ownProvider = own;
286
+ state.provider = own;
287
+ if (candidate) {
288
+ state.mode = "standalone";
289
+ }
290
+ else {
291
+ own.register();
292
+ state.mode = "owned";
293
+ }
294
+ }
295
+ }
296
+ const provider = state.provider;
297
+ processor.policy.exportRatio = state.mode === "attached" ? s.sampleRate : undefined;
298
+ // Identity the holding provider's resource does not carry is stamped on spans.
299
+ const resAttrs = state.mode === "owned" || state.mode === "standalone" ? ownResource : {};
300
+ const stamp = {};
301
+ for (const [k, v] of Object.entries(ident)) {
302
+ if (JSON.stringify(resAttrs[k]) !== JSON.stringify(v))
303
+ stamp[k] = v;
304
+ }
305
+ processor.shutdownTimeoutMs = s.shutdownTimeoutMs;
306
+ const gen = ++initGeneration;
307
+ const sync = syncChoice(opts, env, s);
308
+ let delegate;
309
+ runtime.admissionUrl = "";
310
+ if (sync) {
311
+ delegate = activate(s, sync[0], sync[1], opts, printSpans);
312
+ state.ready = Promise.resolve();
313
+ }
314
+ else {
315
+ const pending = new PendingProcessor();
316
+ delegate = pending;
317
+ runtime.destination = "";
318
+ runtime.destinationSource = "discovering";
319
+ state.active = [];
320
+ state.problems = [];
321
+ const chosen = resolveDestinationChoice(opts.destination, env);
322
+ state.ready = discoverDestination(s.nodeUrl, s.discoverTimeoutMs).then(({ found, error }) => {
323
+ if (gen !== initGeneration) {
324
+ pending.resolve(null);
325
+ return;
326
+ }
327
+ const notes = error && error !== "discovery off" ? [error] : [];
328
+ if (!found) {
329
+ // No machine answered: the explicit choice, else inferred online, else local (a NOTE, not a warning).
330
+ const choice = chosen.choice || inferred(s, "local");
331
+ const source = chosen.choice ? chosen.source : choice === "online" ? "inferred" : "default";
332
+ pending.resolve(activate(s, choice, source, opts, printSpans, [], notes));
333
+ return;
334
+ }
335
+ const choice = chosen.choice || found.destination;
336
+ const source = chosen.choice ? chosen.source : "machine";
337
+ const { settings: merged, problems } = withDiscovered(s, found, choice);
338
+ runtime.admissionUrl = found.admissionUrl;
339
+ pending.resolve(activate(merged, choice, source, opts, printSpans, problems, notes, found.signedIn));
340
+ });
341
+ }
342
+ // Control calls wait for the destination (review E-33); never rejects.
343
+ runtime.ready = state.ready.then(() => undefined, () => undefined);
344
+ const old = processor.swap(delegate, stamp);
345
+ if (old)
346
+ void shutdownBounded(old, s.shutdownTimeoutMs);
347
+ state.configKey = configKey;
348
+ runtime.tracer = provider.getTracer(TRACER_NAME, VERSION);
349
+ runtime.provider = provider;
350
+ installExitHook();
351
+ return publicView(s);
352
+ }
353
+ const views = new WeakMap();
354
+ /** The fields that carry the credential (Python's repr=False fields). */
355
+ const SECRET_FIELDS = ["apiKey", "headers", "onlineHeaders"];
356
+ /**
357
+ * The settings as handed to the app: the same values, with the credential
358
+ * fields (`apiKey`, and the header maps, which may carry `Authorization`)
359
+ * readable but not enumerable, so `console.log`, `JSON.stringify` and a
360
+ * spread never print the key (as Python's Settings repr hides it; review
361
+ * R-C33). The SDK's own copy is unchanged.
362
+ */
363
+ function publicView(s) {
364
+ let v = views.get(s);
365
+ if (!v) {
366
+ v = { ...s };
367
+ for (const f of SECRET_FIELDS)
368
+ Object.defineProperty(v, f, { value: s[f], enumerable: false, writable: false, configurable: false });
369
+ views.set(s, v);
370
+ }
371
+ return v;
372
+ }
373
+ /**
374
+ * Resolves once the destination is known (immediately unless init is asking
375
+ * the local Observer for its default, which takes at most
376
+ * `discoverTimeoutMs`). Spans finished before then are held, not lost.
377
+ */
378
+ export async function ready() {
379
+ await state.ready;
380
+ return runtime.destination;
381
+ }
382
+ /**
383
+ * The settings the last `init()` resolved (null before init). `apiKey` and the
384
+ * header maps are readable but not enumerable, so logging the object never
385
+ * prints the credential.
386
+ */
387
+ export function settings() {
388
+ return runtime.settings ? publicView(runtime.settings) : null;
389
+ }
390
+ /**
391
+ * Export every finished span now. Bounded by `timeoutMs` (default: the
392
+ * shutdownTimeoutMs setting). Resolves true when everything went out in time;
393
+ * never rejects. Await it at the end of a serverless handler.
394
+ */
395
+ export async function flush(timeoutMs) {
396
+ const ms = timeoutMs ?? runtime.settings?.shutdownTimeoutMs ?? 2000;
397
+ const control = bounded(controlIdle(), ms); // pending score / experiment writes
398
+ const d = processor.current;
399
+ let ok = true;
400
+ try {
401
+ if (d)
402
+ ok = await flushBounded(d, ms);
403
+ }
404
+ catch {
405
+ ok = false;
406
+ }
407
+ return (await control) && ok;
408
+ }
409
+ /**
410
+ * Flush and stop the SDK's exporters. Bounded by `timeoutMs` even when an
411
+ * endpoint is down; never rejects (ECONNREFUSED, 302 and 401 included). The
412
+ * host's provider, when the SDK attached to one, keeps running. A later
413
+ * `init()` starts exporting again.
414
+ */
415
+ export async function shutdown(timeoutMs) {
416
+ const old = processor.swap(null, {});
417
+ state.configKey = "";
418
+ if (!old)
419
+ return true;
420
+ try {
421
+ return await shutdownBounded(old, timeoutMs ?? runtime.settings?.shutdownTimeoutMs ?? 2000);
422
+ }
423
+ catch {
424
+ return false;
425
+ }
426
+ finally {
427
+ maybeLogFailures();
428
+ }
429
+ }
430
+ /** A snapshot of the SDK's export health. */
431
+ export function diagnostics() {
432
+ const snap = snapshot();
433
+ return {
434
+ mode: state.mode,
435
+ initialized: processor.active,
436
+ destination: runtime.destination,
437
+ destinationSource: runtime.destinationSource,
438
+ destinations: state.active.map((d) => ({ name: d.name, endpoint: d.endpoint })),
439
+ destinationProblems: [...state.problems],
440
+ gatewayUrl: state.effective?.orgUrl ?? "",
441
+ degraded: state.effective && runtime.destination ? (destinationProblems(state.effective, runtime.destination)[0] ?? "") : "",
442
+ notes: [...state.notes],
443
+ signedIn: state.signedIn,
444
+ credentialSource: state.effective?.credentialSource ?? "",
445
+ pendingSpans: Number(snap.pendingSpans),
446
+ exportedSpans: Number(snap.exportedSpans),
447
+ failedExports: Number(snap.failedExports),
448
+ droppedSpans: Number(snap.droppedSpans),
449
+ sampledOutSpans: Number(snap.sampledOutSpans),
450
+ filteredSpans: Number(snap.filteredSpans),
451
+ shouldExportErrors: Number(snap.shouldExportErrors),
452
+ maskErrors: Number(snap.maskErrors),
453
+ lastHookError: String(snap.lastHookError),
454
+ lastError: String(snap.lastError),
455
+ lastErrorAt: Number(snap.lastErrorAt),
456
+ controlCalls: controlStats.calls,
457
+ controlFailures: controlStats.failures,
458
+ controlLastError: controlStats.lastError,
459
+ admissionDegraded: admitStats.degraded,
460
+ admissionLastError: admitStats.lastError,
461
+ admissionLastErrorAt: admitStats.lastErrorAt,
462
+ vendorTracing: { ...state.vendorTracing },
463
+ vendorSpansDropped: policyStats.vendorSpansDropped,
464
+ usageNetInputCorrected: policyStats.usageNetInputCorrected,
465
+ };
466
+ }
467
+ /** Forget all SDK state (tests only). Does not touch the global provider. */
468
+ export async function _resetForTests() {
469
+ const old = processor.swap(null, {});
470
+ if (old)
471
+ await shutdownBounded(old, 1000);
472
+ Object.assign(state, {
473
+ provider: null,
474
+ ownProvider: null,
475
+ mode: "",
476
+ configKey: "",
477
+ active: [],
478
+ problems: [],
479
+ notes: [],
480
+ signedIn: null,
481
+ effective: null,
482
+ ready: Promise.resolve(),
483
+ vendorTracing: {},
484
+ });
485
+ resetVendorTracingForTests();
486
+ _resetNetInputWarningForTests();
487
+ initGeneration++;
488
+ processorHandedOut = false;
489
+ ownResource = {};
490
+ processor.policy = { captureContent: true, maxContentChars: 0 };
491
+ sampler.set(1, true);
492
+ resetRuntime();
493
+ resetStats();
494
+ resetPolicyStats();
495
+ _resetContextForTests();
496
+ resetControlForTests();
497
+ resetAdmitStats();
498
+ clearPromptCache();
499
+ }
500
+ //# sourceMappingURL=index.js.map