@posthog/ai 8.18.2 → 8.18.3

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.
@@ -0,0 +1,1075 @@
1
+ /*! Includes OpenTelemetry code. Copyright The OpenTelemetry Authors. Licensed under Apache-2.0. */
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ let _opentelemetry_exporter_trace_otlp_http = require("@opentelemetry/exporter-trace-otlp-http");
4
+ let _opentelemetry_api = require("@opentelemetry/api");
5
+ //#region src/sanitization/base64_recognizer.ts
6
+ const DATA_URL_PREFIX_RE = /^data:([^;,\s]+)(?:;[^;,\s]+)*;base64,/i;
7
+ const BASE64_ALPHABET_RE = /^[A-Za-z0-9+/_=-]+$/;
8
+ var Base64Recognizer = class {
9
+ recognize(value, minLength) {
10
+ const dataUrl = DATA_URL_PREFIX_RE.exec(value);
11
+ if (dataUrl) return {
12
+ kind: "data-url",
13
+ mediaType: dataUrl[1]
14
+ };
15
+ if (value.length < minLength) return { kind: "none" };
16
+ const confidencePrefix = value.slice(0, minLength);
17
+ if (BASE64_ALPHABET_RE.test(confidencePrefix)) return { kind: "raw" };
18
+ else return { kind: "none" };
19
+ }
20
+ };
21
+ //#endregion
22
+ //#region src/sanitization/media_type_context.ts
23
+ const MIME_HINT_KEYS = [
24
+ "mediaType",
25
+ "media_type",
26
+ "mimeType",
27
+ "mime_type"
28
+ ];
29
+ const STRONG_CONTEXT_KEYS = /* @__PURE__ */ new Set([
30
+ "data",
31
+ "file_data",
32
+ "fileData",
33
+ "image_url",
34
+ "imageUrl",
35
+ "video_url",
36
+ "videoUrl",
37
+ "audio",
38
+ "audio_data",
39
+ "audioData",
40
+ "inline_data",
41
+ "inlineData",
42
+ "source",
43
+ "result"
44
+ ]);
45
+ const STRONG_CONTEXT_TYPES = /* @__PURE__ */ new Set([
46
+ "image",
47
+ "image_url",
48
+ "input_image",
49
+ "audio",
50
+ "input_audio",
51
+ "video",
52
+ "video_url",
53
+ "file",
54
+ "input_file",
55
+ "document",
56
+ "media",
57
+ "file-data"
58
+ ]);
59
+ const FILE_FAMILY_TYPES = /* @__PURE__ */ new Set([
60
+ "file",
61
+ "input_file",
62
+ "document",
63
+ "media",
64
+ "file-data"
65
+ ]);
66
+ const TYPED_BINARY_DATA_TYPES = /* @__PURE__ */ new Set([
67
+ "image",
68
+ "audio",
69
+ "video",
70
+ "document"
71
+ ]);
72
+ const KNOWN_AUDIO_FORMATS = /* @__PURE__ */ new Set([
73
+ "wav",
74
+ "mp3",
75
+ "ogg",
76
+ "flac",
77
+ "m4a",
78
+ "aac",
79
+ "webm"
80
+ ]);
81
+ var MediaTypeContext = class MediaTypeContext {
82
+ static {
83
+ this.EMPTY = new MediaTypeContext(void 0, void 0);
84
+ }
85
+ constructor(parent, key, explicitMediaType) {
86
+ this.parent = parent;
87
+ this.key = key;
88
+ this.explicitMediaType = explicitMediaType;
89
+ }
90
+ inferMediaType() {
91
+ return this.inferFromSiblingMime() ?? this.inferFromSiblingFormat() ?? this.inferFromParentType() ?? this.inferFromKey();
92
+ }
93
+ inferFromSiblingMime() {
94
+ if (this.explicitMediaType) return this.explicitMediaType;
95
+ if (!this.parent) return void 0;
96
+ for (const hint of MIME_HINT_KEYS) {
97
+ const v = this.parent[hint];
98
+ if (typeof v === "string") return v;
99
+ }
100
+ }
101
+ inferFromSiblingFormat() {
102
+ if (!this.parent) return void 0;
103
+ const fmt = this.parent.format;
104
+ if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return `audio/${fmt.toLowerCase()}`;
105
+ }
106
+ inferFromParentType() {
107
+ if (!this.parent) return void 0;
108
+ const t = this.parent.type;
109
+ if (typeof t !== "string") return void 0;
110
+ if (t === "image" || t === "image_url" || t === "input_image") return "image";
111
+ if (t === "audio" || t === "input_audio") return "audio";
112
+ if (t === "video" || t === "video_url") return "video";
113
+ if (FILE_FAMILY_TYPES.has(t)) return "application/octet-stream";
114
+ }
115
+ inferFromKey() {
116
+ if (!this.key) return void 0;
117
+ const key = this.key.toLowerCase();
118
+ if (key.includes("audio")) return "audio";
119
+ if (key.includes("video")) return "video";
120
+ if (key.includes("image")) return "image";
121
+ if (key.includes("file") || key.includes("document")) return "application/octet-stream";
122
+ }
123
+ hasDefiniteBinaryData() {
124
+ if (this.parent && this.key === "data" && typeof this.parent.type === "string" && TYPED_BINARY_DATA_TYPES.has(this.parent.type)) return true;
125
+ if (!this.explicitMediaType && (!this.parent || !this.key || !STRONG_CONTEXT_KEYS.has(this.key))) return false;
126
+ const mediaType = this.inferFromSiblingMime();
127
+ return mediaType !== void 0 && !mediaType.toLowerCase().startsWith("text/");
128
+ }
129
+ signalsBinary() {
130
+ if (this.explicitMediaType) return true;
131
+ if (this.parent) {
132
+ for (const hint of MIME_HINT_KEYS) if (typeof this.parent[hint] === "string") return true;
133
+ const fmt = this.parent.format;
134
+ if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return true;
135
+ const t = this.parent.type;
136
+ if (typeof t === "string" && STRONG_CONTEXT_TYPES.has(t)) return true;
137
+ }
138
+ if (this.key && STRONG_CONTEXT_KEYS.has(this.key)) return true;
139
+ return false;
140
+ }
141
+ };
142
+ //#endregion
143
+ //#region src/sanitization/binary_content_redactor.ts
144
+ const STRONG_CONTEXT_MIN_LENGTH = 64;
145
+ const WEAK_CONTEXT_MIN_LENGTH = 1024;
146
+ var BinaryContentRedactor = class {
147
+ constructor(recognizer = new Base64Recognizer()) {
148
+ this.recognizer = recognizer;
149
+ this.visited = /* @__PURE__ */ new WeakSet();
150
+ }
151
+ redact(value, mediaType) {
152
+ this.visited = /* @__PURE__ */ new WeakSet();
153
+ return this.walk(value, mediaType ? new MediaTypeContext(void 0, void 0, mediaType) : MediaTypeContext.EMPTY);
154
+ }
155
+ /** Redact one leaf while a caller owns bounded, type-preserving traversal. @internal */
156
+ redactLeaf(value, context) {
157
+ return typeof value === "string" ? this.redactString(value, context) : this.placeholderFor(context.inferMediaType());
158
+ }
159
+ walk(value, ctx) {
160
+ if (value === null || value === void 0) return value;
161
+ if (typeof value === "string") return this.redactLeaf(value, ctx);
162
+ if (typeof value !== "object") return value;
163
+ if (typeof Uint8Array !== "undefined" && value instanceof Uint8Array) return this.redactLeaf(value, ctx);
164
+ if (this.visited.has(value)) return null;
165
+ this.visited.add(value);
166
+ if (Array.isArray(value)) return value.map((item) => this.walk(item, ctx));
167
+ const obj = value;
168
+ const out = {};
169
+ for (const k of Object.keys(obj)) Object.defineProperty(out, k, {
170
+ value: this.walk(obj[k], new MediaTypeContext(obj, k)),
171
+ enumerable: true,
172
+ writable: true,
173
+ configurable: true
174
+ });
175
+ return out;
176
+ }
177
+ redactString(value, ctx) {
178
+ const hasDefiniteBinaryData = ctx.hasDefiniteBinaryData();
179
+ const recognitionValue = hasDefiniteBinaryData ? value.replace(/[\r\n]/g, "") : value;
180
+ const minLength = hasDefiniteBinaryData ? Math.min(recognitionValue.length, STRONG_CONTEXT_MIN_LENGTH) : ctx.signalsBinary() ? STRONG_CONTEXT_MIN_LENGTH : WEAK_CONTEXT_MIN_LENGTH;
181
+ const recognition = this.recognizer.recognize(recognitionValue, minLength);
182
+ switch (recognition.kind) {
183
+ case "data-url": return this.placeholderFor(recognition.mediaType);
184
+ case "raw": return this.placeholderFor(ctx.inferMediaType());
185
+ case "none": return value;
186
+ }
187
+ }
188
+ placeholderFor(mediaType) {
189
+ if (!mediaType) return "[base64 redacted]";
190
+ if (mediaType === "application/octet-stream") return "[base64 file redacted]";
191
+ return `[base64 ${mediaType} redacted]`;
192
+ }
193
+ };
194
+ //#endregion
195
+ //#region src/otel/spans.ts
196
+ const AI_SPAN_PREFIXES = [
197
+ "gen_ai.",
198
+ "llm.",
199
+ "ai.",
200
+ "traceloop."
201
+ ];
202
+ /**
203
+ * Returns `true` when the span is AI-related — its name or any attribute
204
+ * key starts with `gen_ai.`, `llm.`, `ai.`, or `traceloop.`.
205
+ */
206
+ function isAISpan(span) {
207
+ if (AI_SPAN_PREFIXES.some((prefix) => span.name.startsWith(prefix))) return true;
208
+ const attributes = span.attributes;
209
+ if (attributes) return Object.keys(attributes).some((key) => AI_SPAN_PREFIXES.some((prefix) => key.startsWith(prefix)));
210
+ return false;
211
+ }
212
+ /** Copies rather than mutates: the span is shared across every registered processor/exporter. */
213
+ function withAttributes(span, attributes, events) {
214
+ return Object.create(span, {
215
+ attributes: {
216
+ value: attributes,
217
+ enumerable: true,
218
+ configurable: true
219
+ },
220
+ ...events ? { events: {
221
+ value: events,
222
+ enumerable: true,
223
+ configurable: true
224
+ } } : {}
225
+ });
226
+ }
227
+ //#endregion
228
+ //#region src/typeGuards.ts
229
+ const isObject = (value) => {
230
+ return value !== null && typeof value === "object" && !Array.isArray(value);
231
+ };
232
+ //#endregion
233
+ //#region src/mcpCredentials.ts
234
+ const MCP_CREDENTIAL_FIELDS = ["headers", "authorization"];
235
+ const MCP_PROVIDER_TOOL_IDS = /* @__PURE__ */ new Set([
236
+ "openai.mcp",
237
+ "xai.mcp",
238
+ "google.mcp_server"
239
+ ]);
240
+ const isMcpProviderTool = (tool) => (tool.type === "provider" || tool.type === "provider-defined") && typeof tool.id === "string" && MCP_PROVIDER_TOOL_IDS.has(tool.id);
241
+ const withoutMcpCredentials = (config) => {
242
+ const redacted = { ...config };
243
+ for (const field of MCP_CREDENTIAL_FIELDS) if (field in redacted) redacted[field] = "[REDACTED]";
244
+ return redacted;
245
+ };
246
+ /** Hides the credentials of a remote MCP tool definition; everything else is kept as sent. */
247
+ function redactMcpToolDefinition(tool) {
248
+ if (!isObject(tool)) return tool;
249
+ if (tool.type === "mcp") return withoutMcpCredentials(tool);
250
+ if (isMcpProviderTool(tool) && isObject(tool.args)) return {
251
+ ...tool,
252
+ args: withoutMcpCredentials(tool.args)
253
+ };
254
+ return tool;
255
+ }
256
+ function redactMcpToolCredentials(tools) {
257
+ return Array.isArray(tools) ? tools.map(redactMcpToolDefinition) : tools;
258
+ }
259
+ //#endregion
260
+ //#region src/otel/toolDefinitions.ts
261
+ const TOOL_DEFINITION_ATTRIBUTES = /* @__PURE__ */ new Set(["gen_ai.tool.definitions", "ai.prompt.tools"]);
262
+ const TOOL_DEFINITION_PATTERN = /^llm\.tools\.\d+\.tool\.json_schema$/;
263
+ const isToolDefinitionAttribute = (key) => TOOL_DEFINITION_ATTRIBUTES.has(key) || TOOL_DEFINITION_PATTERN.test(key);
264
+ const parseToolDefinitionJson = (value) => {
265
+ try {
266
+ const parsed = JSON.parse(value);
267
+ return parsed !== null && typeof parsed === "object" ? parsed : void 0;
268
+ } catch {
269
+ return;
270
+ }
271
+ };
272
+ const redactJson$1 = (value) => {
273
+ const parsed = parseToolDefinitionJson(value);
274
+ if (parsed === void 0) return value;
275
+ const redacted = JSON.stringify(Array.isArray(parsed) ? redactMcpToolCredentials(parsed) : redactMcpToolDefinition(parsed));
276
+ return redacted === JSON.stringify(parsed) ? value : redacted;
277
+ };
278
+ /** Replaces MCP credentials in a tool definition attribute; values that are not JSON are kept as is. */
279
+ function redactToolDefinitionCredentials(value) {
280
+ if (typeof value === "string") return redactJson$1(value);
281
+ if (Array.isArray(value) && value.every((item) => typeof item === "string" || item == null)) {
282
+ const redacted = value.map((item) => typeof item === "string" ? redactJson$1(item) : item);
283
+ return redacted.some((item, index) => item !== value[index]) ? redacted : value;
284
+ }
285
+ return value;
286
+ }
287
+ /** Drops the parts of a tool definition attribute that are not JSON, since their credentials cannot be found. */
288
+ function withoutUnparseableToolDefinitions(value) {
289
+ if (typeof value === "string") return parseToolDefinitionJson(value) === void 0 ? void 0 : value;
290
+ if (Array.isArray(value)) return value.filter((item) => typeof item === "string" && parseToolDefinitionJson(item) !== void 0);
291
+ }
292
+ //#endregion
293
+ //#region src/otel/redact.ts
294
+ const redactor = new BinaryContentRedactor();
295
+ function redactSpan(span) {
296
+ const attributes = span.attributes ? redactAttributes(span.attributes) : span.attributes;
297
+ const events = span.events ? redactEvents(span.events) : span.events;
298
+ if (attributes === span.attributes && events === span.events) return span;
299
+ return withAttributes(span, attributes, events);
300
+ }
301
+ function redactAttributes(attributes) {
302
+ let changed = false;
303
+ const out = {};
304
+ for (const key of Object.keys(attributes)) {
305
+ const original = attributes[key];
306
+ const value = original !== void 0 && isToolDefinitionAttribute(key) ? redactToolDefinitionCredentials(original) : original;
307
+ const redacted = value === void 0 ? value : redactAttributeValue(value);
308
+ if (redacted !== original) changed = true;
309
+ out[key] = redacted;
310
+ }
311
+ return changed ? out : attributes;
312
+ }
313
+ function redactEvents(events) {
314
+ let changed = false;
315
+ const out = events.map((event) => {
316
+ if (!event.attributes) return event;
317
+ const attributes = redactAttributes(event.attributes);
318
+ if (attributes === event.attributes) return event;
319
+ changed = true;
320
+ return {
321
+ ...event,
322
+ attributes
323
+ };
324
+ });
325
+ return changed ? out : events;
326
+ }
327
+ function redactAttributeValue(value) {
328
+ if (typeof value === "string") return redactString(value);
329
+ if (isStringArray(value)) {
330
+ let changed = false;
331
+ const out = value.map((item) => {
332
+ if (typeof item !== "string") return item;
333
+ const redacted = redactString(item);
334
+ if (redacted !== item) changed = true;
335
+ return redacted;
336
+ });
337
+ return changed ? out : value;
338
+ }
339
+ return value;
340
+ }
341
+ function isStringArray(value) {
342
+ return Array.isArray(value) && value.every((item) => typeof item !== "number" && typeof item !== "boolean");
343
+ }
344
+ function redactString(value) {
345
+ const trimmed = value.trimStart();
346
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
347
+ const redacted = redactJson(value);
348
+ if (redacted !== void 0) return redacted;
349
+ }
350
+ return redactor.redact(value);
351
+ }
352
+ function redactJson(value) {
353
+ let parsed;
354
+ try {
355
+ parsed = JSON.parse(value);
356
+ } catch {
357
+ return;
358
+ }
359
+ if (parsed === null || typeof parsed !== "object") return;
360
+ const redactedStr = JSON.stringify(redactor.redact(parsed));
361
+ return redactedStr === JSON.stringify(parsed) ? value : redactedStr;
362
+ }
363
+ //#endregion
364
+ //#region src/otel/privacy.ts
365
+ const CONTENT_ATTRIBUTES = /* @__PURE__ */ new Set([
366
+ "ai.prompt",
367
+ "ai.prompt.messages",
368
+ "ai.response.text",
369
+ "ai.response.object",
370
+ "ai.response.toolCalls",
371
+ "ai.response.reasoning",
372
+ "ai.response.reasoningDetails",
373
+ "ai.response.files",
374
+ "ai.toolCall.args",
375
+ "ai.toolCall.result",
376
+ "ai.value",
377
+ "ai.values",
378
+ "ai.embedding",
379
+ "ai.embeddings",
380
+ "ai.documents",
381
+ "ai.request.text",
382
+ "ai.decision.state",
383
+ "ai.decision.questions",
384
+ "ai.decision.answers",
385
+ "gen_ai.input.messages",
386
+ "gen_ai.output.messages",
387
+ "gen_ai.system_instructions",
388
+ "gen_ai.prompt",
389
+ "gen_ai.completion",
390
+ "gen_ai.tool.call.arguments",
391
+ "gen_ai.tool.call.result",
392
+ "gen_ai.retrieval.documents",
393
+ "gen_ai.retrieval.query.text",
394
+ "gen_ai.memory.query.text",
395
+ "gen_ai.memory.records",
396
+ "gen_ai.evaluation.explanation",
397
+ "traceloop.entity.input",
398
+ "traceloop.entity.output",
399
+ "traceloop.prompt.template",
400
+ "gen_ai.task.input",
401
+ "gen_ai.task.output",
402
+ "gen_ai.guardrail.input",
403
+ "gen_ai.guardrail.output",
404
+ "gen_ai.guardrail.error.message",
405
+ "gen_ai.response.revised_prompt",
406
+ "mcp.response.value",
407
+ "db.marqo.search.query",
408
+ "anthropic.tool_result.content",
409
+ "pydantic_ai.all_messages",
410
+ "final_result",
411
+ "tool_arguments",
412
+ "tool_response",
413
+ "events",
414
+ "model_request_parameters",
415
+ "inputs",
416
+ "prompt",
417
+ "input.value",
418
+ "output.value",
419
+ "llm.function_call",
420
+ "llm.prompt_template.template",
421
+ "llm.prompt_template.variables",
422
+ "llm.invocation_parameters",
423
+ "reranker.query",
424
+ "langfuse.trace.input",
425
+ "langfuse.trace.output",
426
+ "langfuse.observation.input",
427
+ "langfuse.observation.output",
428
+ "langfuse.observation.status_message",
429
+ "langfuse.experiment.item.expected_output",
430
+ "exception.message",
431
+ "exception.stacktrace",
432
+ "error.message"
433
+ ]);
434
+ const CONTENT_ATTRIBUTE_PREFIXES = [
435
+ "gen_ai.prompt.",
436
+ "gen_ai.completion.",
437
+ "llm.prompts.",
438
+ "llm.completions.",
439
+ "llm.input_messages.",
440
+ "llm.output_messages.",
441
+ "llm.choices.",
442
+ "traceloop.prompt.template_variables."
443
+ ];
444
+ const CONTENT_ATTRIBUTE_PATTERNS = [
445
+ /^db\.chroma\.(query|get|delete)\.where_document$/,
446
+ /^embedding\.embeddings\.\d+\.embedding\.(text|vector)$/,
447
+ /^retrieval\.documents\.\d+\.document\.(content|metadata)$/,
448
+ /^reranker\.(input|output)_documents\.\d+\.document\.content$/,
449
+ /^(input|output)\.images\.\d+\.image\.url$/,
450
+ /^mastra\.[a-z_]+\.(input|output)$/
451
+ ];
452
+ const NON_CONTENT_ATTRIBUTES = /* @__PURE__ */ new Set(["gen_ai.prompt.name", "gen_ai.prompt.version"]);
453
+ const EXCEPTION_EVENT_NAME = "exception";
454
+ const PROVIDER_METADATA_ATTRIBUTE = "ai.response.providerMetadata";
455
+ const isContentAttribute = (key) => !NON_CONTENT_ATTRIBUTES.has(key) && (CONTENT_ATTRIBUTES.has(key) || CONTENT_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix) || prefix === `${key}.`) || CONTENT_ATTRIBUTE_PATTERNS.some((pattern) => pattern.test(key)));
456
+ function gatewayCostOnly(value) {
457
+ if (typeof value !== "string") return;
458
+ try {
459
+ const cost = JSON.parse(value)?.gateway?.cost;
460
+ return typeof cost === "number" || typeof cost === "string" ? JSON.stringify({ gateway: { cost } }) : void 0;
461
+ } catch {
462
+ return;
463
+ }
464
+ }
465
+ function stripAttributes(attributes) {
466
+ const out = {};
467
+ for (const [key, value] of Object.entries(attributes)) {
468
+ if (isContentAttribute(key)) continue;
469
+ if (isToolDefinitionAttribute(key)) {
470
+ const definitions = value === void 0 ? void 0 : withoutUnparseableToolDefinitions(value);
471
+ if (definitions !== void 0) out[key] = definitions;
472
+ continue;
473
+ }
474
+ if (key === PROVIDER_METADATA_ATTRIBUTE) {
475
+ const metadata = gatewayCostOnly(value);
476
+ if (metadata !== void 0) out[key] = metadata;
477
+ continue;
478
+ }
479
+ out[key] = value;
480
+ }
481
+ return out;
482
+ }
483
+ function stripEvents(events) {
484
+ return events.filter((event) => event.name === EXCEPTION_EVENT_NAME).map((event) => event.attributes ? {
485
+ ...event,
486
+ attributes: stripAttributes(event.attributes)
487
+ } : event);
488
+ }
489
+ /** Returns a copy of the span without the attributes, events and status message that carry content. */
490
+ function stripContent(span) {
491
+ const stripped = withAttributes(span, span.attributes ? stripAttributes(span.attributes) : span.attributes, span.events ? stripEvents(span.events) : span.events);
492
+ if (span.status?.message) Object.defineProperty(stripped, "status", {
493
+ value: { code: span.status.code },
494
+ enumerable: true,
495
+ configurable: true
496
+ });
497
+ return stripped;
498
+ }
499
+ //#endregion
500
+ //#region src/gatewayWarning.ts
501
+ const POSTHOG_AI_GATEWAY_HOSTS = [
502
+ "gateway.posthog.com",
503
+ "gateway.us.posthog.com",
504
+ "gateway.eu.posthog.com",
505
+ "ai-gateway.us.posthog.com",
506
+ "ai-gateway.eu.posthog.com"
507
+ ];
508
+ const GATEWAY_DOCS_URL = "https://posthog.com/docs/ai-observability";
509
+ const extractHost = (baseURL) => {
510
+ try {
511
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseURL);
512
+ return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
513
+ } catch {
514
+ return;
515
+ }
516
+ };
517
+ const isPostHogAiGatewayUrl = (baseURL) => {
518
+ if (!baseURL) return false;
519
+ const host = extractHost(baseURL);
520
+ return host !== void 0 && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
521
+ };
522
+ const warnIfPostHogAiGateway = (baseURL) => {
523
+ if (!isPostHogAiGatewayUrl(baseURL)) return;
524
+ console.warn(`[PostHog] The PostHog AI wrapper is pointed at the PostHog AI Gateway. Both capture \$ai_generation, so every call is double-counted and double-billed. Use one or the other — see ${GATEWAY_DOCS_URL}.`);
525
+ };
526
+ const OTEL_GATEWAY_URL_ATTRIBUTES = ["server.address", "url.full"];
527
+ const warnIfPostHogAiGatewayOtelAttributes = (attributes) => {
528
+ if (!attributes) return;
529
+ for (const key of OTEL_GATEWAY_URL_ATTRIBUTES) {
530
+ const value = attributes[key];
531
+ if (typeof value === "string" && isPostHogAiGatewayUrl(value)) {
532
+ warnIfPostHogAiGateway(value);
533
+ return;
534
+ }
535
+ }
536
+ };
537
+ //#endregion
538
+ //#region src/otel/exporter.ts
539
+ const DEFAULT_OTEL_HOST$1 = "https://us.i.posthog.com";
540
+ const EXPORT_SUCCESS = 0;
541
+ function normalizeToken$1(value) {
542
+ return typeof value === "string" ? value.trim() : "";
543
+ }
544
+ function normalizeHost$1(value) {
545
+ return (typeof value === "string" ? value.trim() : "") || DEFAULT_OTEL_HOST$1;
546
+ }
547
+ /**
548
+ * An OpenTelemetry `TraceExporter` that sends AI traces to PostHog's OTLP
549
+ * ingestion endpoint. PostHog converts `gen_ai.*` spans into
550
+ * `$ai_generation` events server-side.
551
+ *
552
+ * Only AI-related spans (those whose name or attribute keys start with
553
+ * `gen_ai.`, `llm.`, `ai.`, or `traceloop.`) are exported; all other
554
+ * spans are silently dropped.
555
+ *
556
+ * Use this when the API you're integrating with only accepts a
557
+ * `TraceExporter` (e.g. Vercel's `registerOTel`) or when you need to
558
+ * plug PostHog into an existing processor chain. Otherwise prefer
559
+ * {@link PostHogSpanProcessor}, which is self-contained.
560
+ *
561
+ * `projectToken` is required; a blank token disables the exporter as a defensive no-op.
562
+ * You can also optionally override the `host` URL.
563
+ *
564
+ * Exporters only see finished spans, so they can't add per-request PostHog context;
565
+ * use {@link PostHogSpanProcessor} with `client` for that.
566
+ *
567
+ * @example
568
+ * ```ts
569
+ * import { PostHogTraceExporter } from '@posthog/ai/otel'
570
+ * import { registerOTel } from '@vercel/otel'
571
+ *
572
+ * registerOTel({
573
+ * serviceName: 'my-app',
574
+ * traceExporter: new PostHogTraceExporter({ projectToken: 'phc_...' }),
575
+ * })
576
+ * ```
577
+ */
578
+ var PostHogTraceExporter = class extends _opentelemetry_exporter_trace_otlp_http.OTLPTraceExporter {
579
+ constructor(options) {
580
+ const token = normalizeToken$1(options.projectToken);
581
+ const disabled = !token;
582
+ const host = token ? new URL(normalizeHost$1(options.host)).origin : DEFAULT_OTEL_HOST$1;
583
+ super({
584
+ url: `${host}/i/v0/ai/otel`,
585
+ headers: token ? { Authorization: `Bearer ${token}` } : {}
586
+ });
587
+ this.disabled = disabled;
588
+ this.privacyMode = options.privacyMode === true;
589
+ if (this.disabled) console.warn("[PostHogTraceExporter] projectToken is missing or blank; the exporter will be disabled.");
590
+ }
591
+ export(spans, resultCallback) {
592
+ if (this.disabled) {
593
+ resultCallback({ code: EXPORT_SUCCESS });
594
+ return;
595
+ }
596
+ const aiSpans = spans.filter(isAISpan);
597
+ if (aiSpans.length === 0) {
598
+ resultCallback({ code: EXPORT_SUCCESS });
599
+ return;
600
+ }
601
+ for (const span of aiSpans) warnIfPostHogAiGatewayOtelAttributes(span.attributes);
602
+ const shareable = this.privacyMode ? aiSpans.map(stripContent) : aiSpans;
603
+ super.export(shareable.map(redactSpan), resultCallback);
604
+ }
605
+ };
606
+ //#endregion
607
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/core/2.2.0/b871f22d07b51323f729d44d521414927172cbc0ddfdf1942304eca90488e96b/node_modules/@opentelemetry/core/build/esm/trace/suppress-tracing.js
608
+ const SUPPRESS_TRACING_KEY = (0, _opentelemetry_api.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
609
+ function suppressTracing(context) {
610
+ return context.setValue(SUPPRESS_TRACING_KEY, true);
611
+ }
612
+ //#endregion
613
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/core/2.2.0/b871f22d07b51323f729d44d521414927172cbc0ddfdf1942304eca90488e96b/node_modules/@opentelemetry/core/build/esm/common/logging-error-handler.js
614
+ /**
615
+ * Returns a function that logs an error using the provided logger, or a
616
+ * console logger if one was not provided.
617
+ */
618
+ function loggingErrorHandler() {
619
+ return (ex) => {
620
+ _opentelemetry_api.diag.error(stringifyException(ex));
621
+ };
622
+ }
623
+ /**
624
+ * Converts an exception into a string representation
625
+ * @param {Exception} ex
626
+ */
627
+ function stringifyException(ex) {
628
+ if (typeof ex === "string") return ex;
629
+ else return JSON.stringify(flattenException(ex));
630
+ }
631
+ /**
632
+ * Flattens an exception into key-value pairs by traversing the prototype chain
633
+ * and coercing values to strings. Duplicate properties will not be overwritten;
634
+ * the first insert wins.
635
+ */
636
+ function flattenException(ex) {
637
+ const result = {};
638
+ let current = ex;
639
+ while (current !== null) {
640
+ Object.getOwnPropertyNames(current).forEach((propertyName) => {
641
+ if (result[propertyName]) return;
642
+ const value = current[propertyName];
643
+ if (value) result[propertyName] = String(value);
644
+ });
645
+ current = Object.getPrototypeOf(current);
646
+ }
647
+ return result;
648
+ }
649
+ //#endregion
650
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/core/2.2.0/b871f22d07b51323f729d44d521414927172cbc0ddfdf1942304eca90488e96b/node_modules/@opentelemetry/core/build/esm/common/global-error-handler.js
651
+ /** The global error handler delegate */
652
+ let delegateHandler = loggingErrorHandler();
653
+ /**
654
+ * Return the global error handler
655
+ * @param {Exception} ex
656
+ */
657
+ function globalErrorHandler(ex) {
658
+ try {
659
+ delegateHandler(ex);
660
+ } catch {}
661
+ }
662
+ //#endregion
663
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/core/2.2.0/b871f22d07b51323f729d44d521414927172cbc0ddfdf1942304eca90488e96b/node_modules/@opentelemetry/core/build/esm/ExportResult.js
664
+ var ExportResultCode;
665
+ (function(ExportResultCode) {
666
+ ExportResultCode[ExportResultCode["SUCCESS"] = 0] = "SUCCESS";
667
+ ExportResultCode[ExportResultCode["FAILED"] = 1] = "FAILED";
668
+ })(ExportResultCode || (ExportResultCode = {}));
669
+ //#endregion
670
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/core/2.2.0/b871f22d07b51323f729d44d521414927172cbc0ddfdf1942304eca90488e96b/node_modules/@opentelemetry/core/build/esm/utils/promise.js
671
+ var Deferred = class {
672
+ _promise;
673
+ _resolve;
674
+ _reject;
675
+ constructor() {
676
+ this._promise = new Promise((resolve, reject) => {
677
+ this._resolve = resolve;
678
+ this._reject = reject;
679
+ });
680
+ }
681
+ get promise() {
682
+ return this._promise;
683
+ }
684
+ resolve(val) {
685
+ this._resolve(val);
686
+ }
687
+ reject(err) {
688
+ this._reject(err);
689
+ }
690
+ };
691
+ //#endregion
692
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/core/2.2.0/b871f22d07b51323f729d44d521414927172cbc0ddfdf1942304eca90488e96b/node_modules/@opentelemetry/core/build/esm/utils/callback.js
693
+ /**
694
+ * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.
695
+ */
696
+ var BindOnceFuture = class {
697
+ _callback;
698
+ _that;
699
+ _isCalled = false;
700
+ _deferred = new Deferred();
701
+ constructor(_callback, _that) {
702
+ this._callback = _callback;
703
+ this._that = _that;
704
+ }
705
+ get isCalled() {
706
+ return this._isCalled;
707
+ }
708
+ get promise() {
709
+ return this._deferred.promise;
710
+ }
711
+ call(...args) {
712
+ if (!this._isCalled) {
713
+ this._isCalled = true;
714
+ try {
715
+ Promise.resolve(this._callback.call(this._that, ...args)).then((val) => this._deferred.resolve(val), (err) => this._deferred.reject(err));
716
+ } catch (err) {
717
+ this._deferred.reject(err);
718
+ }
719
+ }
720
+ return this._deferred.promise;
721
+ }
722
+ };
723
+ //#endregion
724
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/sdk-trace-base/2.2.0/fa825708a19b4d5944c83585f1de1744c29637446df5cfc986c5a1263b781148/node_modules/@opentelemetry/sdk-trace-base/build/esm/export/BatchSpanProcessorBase.js
725
+ /**
726
+ * Implementation of the {@link SpanProcessor} that batches spans exported by
727
+ * the SDK then pushes them to the exporter pipeline.
728
+ */
729
+ var BatchSpanProcessorBase = class {
730
+ _exporter;
731
+ _maxExportBatchSize;
732
+ _maxQueueSize;
733
+ _scheduledDelayMillis;
734
+ _exportTimeoutMillis;
735
+ _isExporting = false;
736
+ _finishedSpans = [];
737
+ _timer;
738
+ _shutdownOnce;
739
+ _droppedSpansCount = 0;
740
+ constructor(_exporter, config) {
741
+ this._exporter = _exporter;
742
+ this._maxExportBatchSize = typeof config?.maxExportBatchSize === "number" ? config.maxExportBatchSize : 512;
743
+ this._maxQueueSize = typeof config?.maxQueueSize === "number" ? config.maxQueueSize : 2048;
744
+ this._scheduledDelayMillis = typeof config?.scheduledDelayMillis === "number" ? config.scheduledDelayMillis : 5e3;
745
+ this._exportTimeoutMillis = typeof config?.exportTimeoutMillis === "number" ? config.exportTimeoutMillis : 3e4;
746
+ this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
747
+ if (this._maxExportBatchSize > this._maxQueueSize) {
748
+ _opentelemetry_api.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
749
+ this._maxExportBatchSize = this._maxQueueSize;
750
+ }
751
+ }
752
+ forceFlush() {
753
+ if (this._shutdownOnce.isCalled) return this._shutdownOnce.promise;
754
+ return this._flushAll();
755
+ }
756
+ onStart(_span, _parentContext) {}
757
+ onEnd(span) {
758
+ if (this._shutdownOnce.isCalled) return;
759
+ if ((span.spanContext().traceFlags & _opentelemetry_api.TraceFlags.SAMPLED) === 0) return;
760
+ this._addToBuffer(span);
761
+ }
762
+ shutdown() {
763
+ return this._shutdownOnce.call();
764
+ }
765
+ _shutdown() {
766
+ return Promise.resolve().then(() => {
767
+ return this.onShutdown();
768
+ }).then(() => {
769
+ return this._flushAll();
770
+ }).then(() => {
771
+ return this._exporter.shutdown();
772
+ });
773
+ }
774
+ /** Add a span in the buffer. */
775
+ _addToBuffer(span) {
776
+ if (this._finishedSpans.length >= this._maxQueueSize) {
777
+ if (this._droppedSpansCount === 0) _opentelemetry_api.diag.debug("maxQueueSize reached, dropping spans");
778
+ this._droppedSpansCount++;
779
+ return;
780
+ }
781
+ if (this._droppedSpansCount > 0) {
782
+ _opentelemetry_api.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
783
+ this._droppedSpansCount = 0;
784
+ }
785
+ this._finishedSpans.push(span);
786
+ this._maybeStartTimer();
787
+ }
788
+ /**
789
+ * Send all spans to the exporter respecting the batch size limit
790
+ * This function is used only on forceFlush or shutdown,
791
+ * for all other cases _flush should be used
792
+ * */
793
+ _flushAll() {
794
+ return new Promise((resolve, reject) => {
795
+ const promises = [];
796
+ const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
797
+ for (let i = 0, j = count; i < j; i++) promises.push(this._flushOneBatch());
798
+ Promise.all(promises).then(() => {
799
+ resolve();
800
+ }).catch(reject);
801
+ });
802
+ }
803
+ _flushOneBatch() {
804
+ this._clearTimer();
805
+ if (this._finishedSpans.length === 0) return Promise.resolve();
806
+ return new Promise((resolve, reject) => {
807
+ const timer = setTimeout(() => {
808
+ reject(/* @__PURE__ */ new Error("Timeout"));
809
+ }, this._exportTimeoutMillis);
810
+ _opentelemetry_api.context.with(suppressTracing(_opentelemetry_api.context.active()), () => {
811
+ let spans;
812
+ if (this._finishedSpans.length <= this._maxExportBatchSize) {
813
+ spans = this._finishedSpans;
814
+ this._finishedSpans = [];
815
+ } else spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
816
+ const doExport = () => this._exporter.export(spans, (result) => {
817
+ clearTimeout(timer);
818
+ if (result.code === ExportResultCode.SUCCESS) resolve();
819
+ else reject(result.error ?? /* @__PURE__ */ new Error("BatchSpanProcessor: span export failed"));
820
+ });
821
+ let pendingResources = null;
822
+ for (let i = 0, len = spans.length; i < len; i++) {
823
+ const span = spans[i];
824
+ if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) {
825
+ pendingResources ??= [];
826
+ pendingResources.push(span.resource.waitForAsyncAttributes());
827
+ }
828
+ }
829
+ if (pendingResources === null) doExport();
830
+ else Promise.all(pendingResources).then(doExport, (err) => {
831
+ globalErrorHandler(err);
832
+ reject(err);
833
+ });
834
+ });
835
+ });
836
+ }
837
+ _maybeStartTimer() {
838
+ if (this._isExporting) return;
839
+ const flush = () => {
840
+ this._isExporting = true;
841
+ this._flushOneBatch().finally(() => {
842
+ this._isExporting = false;
843
+ if (this._finishedSpans.length > 0) {
844
+ this._clearTimer();
845
+ this._maybeStartTimer();
846
+ }
847
+ }).catch((e) => {
848
+ this._isExporting = false;
849
+ globalErrorHandler(e);
850
+ });
851
+ };
852
+ if (this._finishedSpans.length >= this._maxExportBatchSize) return flush();
853
+ if (this._timer !== void 0) return;
854
+ this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
855
+ if (typeof this._timer !== "number") this._timer.unref();
856
+ }
857
+ _clearTimer() {
858
+ if (this._timer !== void 0) {
859
+ clearTimeout(this._timer);
860
+ this._timer = void 0;
861
+ }
862
+ }
863
+ };
864
+ //#endregion
865
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/sdk-trace-base/2.2.0/fa825708a19b4d5944c83585f1de1744c29637446df5cfc986c5a1263b781148/node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/browser/export/BatchSpanProcessor.js
866
+ var BatchSpanProcessor = class extends BatchSpanProcessorBase {
867
+ _visibilityChangeListener;
868
+ _pageHideListener;
869
+ constructor(_exporter, config) {
870
+ super(_exporter, config);
871
+ this.onInit(config);
872
+ }
873
+ onInit(config) {
874
+ if (config?.disableAutoFlushOnDocumentHide !== true && typeof document !== "undefined") {
875
+ this._visibilityChangeListener = () => {
876
+ if (document.visibilityState === "hidden") this.forceFlush().catch((error) => {
877
+ globalErrorHandler(error);
878
+ });
879
+ };
880
+ this._pageHideListener = () => {
881
+ this.forceFlush().catch((error) => {
882
+ globalErrorHandler(error);
883
+ });
884
+ };
885
+ document.addEventListener("visibilitychange", this._visibilityChangeListener);
886
+ document.addEventListener("pagehide", this._pageHideListener);
887
+ }
888
+ }
889
+ onShutdown() {
890
+ if (typeof document !== "undefined") {
891
+ if (this._visibilityChangeListener) document.removeEventListener("visibilitychange", this._visibilityChangeListener);
892
+ if (this._pageHideListener) document.removeEventListener("pagehide", this._pageHideListener);
893
+ }
894
+ }
895
+ };
896
+ //#endregion
897
+ //#region src/privacyMode.ts
898
+ /** Per-call settings can turn redaction on but never off. */
899
+ const isPrivacyModeEnabled = (client, privacyMode = false) => privacyMode === true || client?.privacyMode === true || client?.privacy_mode === true || client?.options?.privacyMode === true;
900
+ //#endregion
901
+ //#region src/otel/requestContext.ts
902
+ const DISTINCT_ID_ATTRIBUTE = "posthog.distinct_id";
903
+ const SESSION_ID_ATTRIBUTE = "$session_id";
904
+ const IDENTITY_ATTRIBUTES = [
905
+ DISTINCT_ID_ATTRIBUTE,
906
+ "user.id",
907
+ "ai.telemetry.metadata.posthog_distinct_id",
908
+ "ai.settings.context.posthog_distinct_id"
909
+ ];
910
+ function isPrimitive(value) {
911
+ return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
912
+ }
913
+ function isHomogeneousPrimitiveArray(value) {
914
+ return Array.isArray(value) && value.every((item) => isPrimitive(item) && typeof item === typeof value[0]);
915
+ }
916
+ function rejectNonFinite(_key, value) {
917
+ if (typeof value === "number" && !Number.isFinite(value)) throw new TypeError("non-finite number");
918
+ return value;
919
+ }
920
+ function toAttributeValue(value) {
921
+ if (value === void 0 || value === null || value === "") return;
922
+ if (isPrimitive(value) || isHomogeneousPrimitiveArray(value)) return value;
923
+ try {
924
+ const json = JSON.stringify(value, rejectNonFinite);
925
+ if (json === void 0 || json === "null") return;
926
+ return json.startsWith("\"") ? String(JSON.parse(json)) || void 0 : json;
927
+ } catch {
928
+ return;
929
+ }
930
+ }
931
+ function hasValues(context) {
932
+ return Boolean(context.distinctId || context.sessionId || Object.keys(context.properties ?? {}).length > 0);
933
+ }
934
+ function captureContext(client) {
935
+ try {
936
+ if (typeof client.getContext !== "function") return;
937
+ const context = client.getContext();
938
+ return context && hasValues(context) ? context : void 0;
939
+ } catch {
940
+ return;
941
+ }
942
+ }
943
+ function toAttributes(context, spanAttributes) {
944
+ const hasIdentity = IDENTITY_ATTRIBUTES.some((key) => spanAttributes[key] !== void 0);
945
+ const values = {
946
+ ...context.distinctId && !hasIdentity ? { [DISTINCT_ID_ATTRIBUTE]: context.distinctId } : {},
947
+ ...context.sessionId ? { [SESSION_ID_ATTRIBUTE]: context.sessionId } : {},
948
+ ...context.properties
949
+ };
950
+ const attributes = {};
951
+ for (const [key, value] of Object.entries(values)) {
952
+ if (hasIdentity && key === DISTINCT_ID_ATTRIBUTE) continue;
953
+ const attribute = toAttributeValue(value);
954
+ if (attribute !== void 0) attributes[key] = attribute;
955
+ }
956
+ return attributes;
957
+ }
958
+ function withRequestContext(span, context) {
959
+ try {
960
+ const attributes = toAttributes(context, span.attributes);
961
+ if (Object.keys(attributes).length === 0) return span;
962
+ return withAttributes(span, {
963
+ ...attributes,
964
+ ...span.attributes
965
+ });
966
+ } catch {
967
+ return span;
968
+ }
969
+ }
970
+ //#endregion
971
+ //#region src/otel/processor.ts
972
+ const DEFAULT_OTEL_HOST = "https://us.i.posthog.com";
973
+ function normalizeToken(value) {
974
+ return typeof value === "string" ? value.trim() : "";
975
+ }
976
+ function normalizeHost(value) {
977
+ return (typeof value === "string" ? value.trim() : "") || DEFAULT_OTEL_HOST;
978
+ }
979
+ var NoopSpanProcessor = class {
980
+ onStart(_span, _parentContext) {}
981
+ onEnd(_span) {}
982
+ shutdown() {
983
+ return Promise.resolve();
984
+ }
985
+ forceFlush() {
986
+ return Promise.resolve();
987
+ }
988
+ };
989
+ /**
990
+ * An OpenTelemetry `SpanProcessor` that sends AI traces to PostHog.
991
+ *
992
+ * `projectToken` is required; a blank token disables the processor as a defensive no-op.
993
+ *
994
+ * Internally batches spans and exports them to PostHog's OTLP ingestion
995
+ * endpoint. Only AI-related spans (those whose name or attribute keys
996
+ * start with `gen_ai.`, `llm.`, `ai.`, or `traceloop.`) are exported;
997
+ * all other spans are silently dropped.
998
+ *
999
+ * Request-scoped and serverless runtimes should keep a reference to this
1000
+ * processor and await {@link PostHogSpanProcessor.forceFlush} before the request
1001
+ * lifecycle ends. This waits for queued exports without sending one request per span.
1002
+ *
1003
+ * This is the recommended integration point when your setup accepts a
1004
+ * `SpanProcessor`. If you need a `TraceExporter` instead (e.g. for
1005
+ * Vercel's `registerOTel`), use {@link PostHogTraceExporter}.
1006
+ *
1007
+ * @example
1008
+ * ```ts
1009
+ * import { PostHogSpanProcessor } from '@posthog/ai/otel'
1010
+ * import { NodeSDK } from '@opentelemetry/sdk-node'
1011
+ *
1012
+ * const processor = new PostHogSpanProcessor({ projectToken: 'phc_...' })
1013
+ * const sdk = new NodeSDK({ spanProcessors: [processor] })
1014
+ * sdk.start()
1015
+ *
1016
+ * // In request-scoped runtimes, wait for queued exports before returning.
1017
+ * await processor.forceFlush()
1018
+ * ```
1019
+ *
1020
+ * @example
1021
+ * ```ts
1022
+ * // Per request: pass your posthog-node client, then wrap the work in a context.
1023
+ * const processor = new PostHogSpanProcessor({ projectToken: 'phc_...', client: posthog })
1024
+ * await posthog.withContext({ distinctId: user.id, properties: { plan: 'pro' } }, () => handleRequest())
1025
+ * ```
1026
+ */
1027
+ var PostHogSpanProcessor = class {
1028
+ constructor(options) {
1029
+ this.privacyMode = false;
1030
+ this.capturedContexts = /* @__PURE__ */ new WeakMap();
1031
+ const token = normalizeToken(options.projectToken);
1032
+ if (!token) {
1033
+ console.warn("[PostHogSpanProcessor] projectToken is missing or blank; the processor will be disabled.");
1034
+ this.inner = new NoopSpanProcessor();
1035
+ return;
1036
+ }
1037
+ this.client = options.client;
1038
+ this.privacyMode = options.privacyMode === true;
1039
+ if (options._spanProcessor) this.inner = options._spanProcessor;
1040
+ else {
1041
+ const host = new URL(normalizeHost(options.host)).origin;
1042
+ const exporter = new _opentelemetry_exporter_trace_otlp_http.OTLPTraceExporter({
1043
+ url: `${host}/i/v0/ai/otel`,
1044
+ headers: { Authorization: `Bearer ${token}` }
1045
+ });
1046
+ this.inner = new BatchSpanProcessor(exporter);
1047
+ }
1048
+ }
1049
+ onStart(span, parentContext) {
1050
+ const captured = this.client && captureContext(this.client);
1051
+ if (captured) this.capturedContexts.set(span, captured);
1052
+ this.inner.onStart(span, parentContext);
1053
+ }
1054
+ onEnd(span) {
1055
+ const captured = this.capturedContexts.get(span);
1056
+ this.capturedContexts.delete(span);
1057
+ if (isAISpan(span)) {
1058
+ warnIfPostHogAiGatewayOtelAttributes(span.attributes);
1059
+ const contextual = captured ? withRequestContext(span, captured) : span;
1060
+ const shareable = isPrivacyModeEnabled(this.client, this.privacyMode) ? stripContent(contextual) : contextual;
1061
+ this.inner.onEnd(redactSpan(shareable));
1062
+ }
1063
+ }
1064
+ shutdown() {
1065
+ return this.inner.shutdown();
1066
+ }
1067
+ forceFlush() {
1068
+ return this.inner.forceFlush();
1069
+ }
1070
+ };
1071
+ //#endregion
1072
+ exports.PostHogSpanProcessor = PostHogSpanProcessor;
1073
+ exports.PostHogTraceExporter = PostHogTraceExporter;
1074
+
1075
+ //# sourceMappingURL=index.browser.cjs.map