autotel 3.0.7 → 3.1.1
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/auto.cjs +5 -5
- package/dist/auto.js +3 -3
- package/dist/{chunk-BGAR6MCX.cjs → chunk-2GIBANLB.cjs} +4 -4
- package/dist/{chunk-BGAR6MCX.cjs.map → chunk-2GIBANLB.cjs.map} +1 -1
- package/dist/{chunk-ISEHXVMD.cjs → chunk-45B2GD4P.cjs} +16 -16
- package/dist/{chunk-ISEHXVMD.cjs.map → chunk-45B2GD4P.cjs.map} +1 -1
- package/dist/{chunk-I7ODAZJL.js → chunk-52ALHU7T.js} +3 -3
- package/dist/{chunk-I7ODAZJL.js.map → chunk-52ALHU7T.js.map} +1 -1
- package/dist/{chunk-7NDHLHZK.js → chunk-643PQG3Y.js} +3 -3
- package/dist/{chunk-7NDHLHZK.js.map → chunk-643PQG3Y.js.map} +1 -1
- package/dist/{chunk-KGBRZ7J5.js → chunk-6TFJF7SS.js} +3 -3
- package/dist/{chunk-KGBRZ7J5.js.map → chunk-6TFJF7SS.js.map} +1 -1
- package/dist/{chunk-LOTJ7SDI.cjs → chunk-6X2GG65S.cjs} +5 -5
- package/dist/{chunk-LOTJ7SDI.cjs.map → chunk-6X2GG65S.cjs.map} +1 -1
- package/dist/{chunk-BTEPYWDF.cjs → chunk-FEEVB2GV.cjs} +4 -4
- package/dist/{chunk-BTEPYWDF.cjs.map → chunk-FEEVB2GV.cjs.map} +1 -1
- package/dist/{chunk-IC4AZUGC.js → chunk-FTBBBPT6.js} +3 -3
- package/dist/{chunk-IC4AZUGC.js.map → chunk-FTBBBPT6.js.map} +1 -1
- package/dist/{chunk-MBEHEGQE.js → chunk-HLZ7H3VZ.js} +3 -3
- package/dist/{chunk-MBEHEGQE.js.map → chunk-HLZ7H3VZ.js.map} +1 -1
- package/dist/{chunk-EQIY6C3X.cjs → chunk-HR5YFXZW.cjs} +5 -3
- package/dist/chunk-HR5YFXZW.cjs.map +1 -0
- package/dist/{chunk-VNMT2TDZ.cjs → chunk-KPDIEVVV.cjs} +50 -36
- package/dist/chunk-KPDIEVVV.cjs.map +1 -0
- package/dist/{chunk-KPNV2GPW.js → chunk-KVDA4HX2.js} +5 -3
- package/dist/chunk-KVDA4HX2.js.map +1 -0
- package/dist/{chunk-KAELJC6T.cjs → chunk-LIYNUGML.cjs} +13 -13
- package/dist/{chunk-KAELJC6T.cjs.map → chunk-LIYNUGML.cjs.map} +1 -1
- package/dist/{chunk-MAITXZFR.js → chunk-MHPYLMQS.js} +4 -4
- package/dist/{chunk-MAITXZFR.js.map → chunk-MHPYLMQS.js.map} +1 -1
- package/dist/{chunk-NC5BG7B3.cjs → chunk-MXO6LXV5.cjs} +11 -11
- package/dist/{chunk-NC5BG7B3.cjs.map → chunk-MXO6LXV5.cjs.map} +1 -1
- package/dist/{chunk-SIMG4IGE.js → chunk-MYWQELNY.js} +4 -4
- package/dist/{chunk-SIMG4IGE.js.map → chunk-MYWQELNY.js.map} +1 -1
- package/dist/{chunk-6VVEOLG5.js → chunk-PEEUMQ3R.js} +4 -4
- package/dist/{chunk-6VVEOLG5.js.map → chunk-PEEUMQ3R.js.map} +1 -1
- package/dist/{chunk-JITYRSI4.js → chunk-T7CPAGOI.js} +19 -6
- package/dist/chunk-T7CPAGOI.js.map +1 -0
- package/dist/{chunk-727YZJUB.cjs → chunk-YPQMAE6U.cjs} +7 -7
- package/dist/{chunk-727YZJUB.cjs.map → chunk-YPQMAE6U.cjs.map} +1 -1
- package/dist/{chunk-ADZDAWNV.cjs → chunk-ZPERWNOP.cjs} +17 -17
- package/dist/{chunk-ADZDAWNV.cjs.map → chunk-ZPERWNOP.cjs.map} +1 -1
- package/dist/correlation-id.cjs +12 -12
- package/dist/correlation-id.js +4 -4
- package/dist/decorators.cjs +7 -7
- package/dist/decorators.js +6 -6
- package/dist/event.cjs +8 -8
- package/dist/event.js +5 -5
- package/dist/functional.cjs +17 -13
- package/dist/functional.d.cts +21 -1
- package/dist/functional.d.ts +21 -1
- package/dist/functional.js +6 -6
- package/dist/http.cjs +5 -5
- package/dist/http.js +4 -4
- package/dist/index.cjs +86 -82
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +14 -14
- package/dist/instrumentation.cjs +11 -11
- package/dist/instrumentation.js +3 -3
- package/dist/messaging.cjs +10 -10
- package/dist/messaging.js +7 -7
- package/dist/semantic-helpers.cjs +11 -11
- package/dist/semantic-helpers.js +7 -7
- package/dist/trace-helpers.cjs +14 -14
- package/dist/trace-helpers.js +2 -2
- package/dist/webhook.cjs +8 -8
- package/dist/webhook.js +6 -6
- package/dist/workflow-distributed.cjs +8 -8
- package/dist/workflow-distributed.js +6 -6
- package/dist/workflow.cjs +11 -11
- package/dist/workflow.js +7 -7
- package/dist/yaml-config.cjs +5 -5
- package/dist/yaml-config.js +2 -2
- package/package.json +1 -1
- package/src/functional.test.ts +25 -0
- package/src/functional.ts +49 -0
- package/src/index.ts +1 -0
- package/src/node-require.ts +15 -7
- package/dist/chunk-EQIY6C3X.cjs.map +0 -1
- package/dist/chunk-JITYRSI4.js.map +0 -1
- package/dist/chunk-KPNV2GPW.js.map +0 -1
- package/dist/chunk-VNMT2TDZ.cjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { trace } from './chunk-
|
|
1
|
+
import { trace } from './chunk-T7CPAGOI.js';
|
|
2
2
|
|
|
3
3
|
// src/semantic-helpers.ts
|
|
4
4
|
function traceLLM(config) {
|
|
@@ -91,5 +91,5 @@ function traceMessaging(config) {
|
|
|
91
91
|
}
|
|
92
92
|
|
|
93
93
|
export { traceDB, traceHTTP, traceLLM, traceMessaging };
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
95
|
-
//# sourceMappingURL=chunk-
|
|
94
|
+
//# sourceMappingURL=chunk-52ALHU7T.js.map
|
|
95
|
+
//# sourceMappingURL=chunk-52ALHU7T.js.map
|
|
@@ -1 +1 @@
|
|
|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IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-I7ODAZJL.js","sourcesContent":["/**\n * Semantic convention helpers for OpenTelemetry\n *\n * Pre-configured trace helpers that follow OpenTelemetry semantic conventions\n * for common operation types. Reduces boilerplate and ensures consistency.\n *\n * Based on: https://opentelemetry.io/docs/specs/semconv/\n */\n\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport type { Attributes } from '@opentelemetry/api';\n\n/**\n * Configuration for LLM (Large Language Model) operations\n *\n * Follows Gen AI semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nexport interface LLMConfig {\n /** Model name (e.g., 'gpt-4', 'claude-3-opus') */\n model: string;\n /** Operation type */\n operation?: 'chat' | 'completion' | 'embedding';\n /** Model provider (e.g., 'openai', 'anthropic', 'cohere') - maps to gen.ai.system */\n provider?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for database operations\n *\n * Follows DB semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/database/\n */\nexport interface DBConfig {\n /** Database system (e.g., 'postgresql', 'mongodb', 'redis') */\n system: string;\n /** Operation type (e.g., 'SELECT', 'INSERT', 'find', 'get') */\n operation?: string;\n /** Database name */\n database?: string;\n /** Collection/table name */\n collection?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for HTTP client operations\n *\n * Follows HTTP semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/http/\n */\nexport interface HTTPConfig {\n /** HTTP method (e.g., 'GET', 'POST') */\n method?: string;\n /** Target URL or URL template */\n url?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for messaging operations\n *\n * Follows Messaging semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/messaging/\n */\nexport interface MessagingConfig {\n /** Messaging system (e.g., 'kafka', 'rabbitmq', 'sqs') */\n system: string;\n /** Operation type */\n operation?: 'publish' | 'receive' | 'process';\n /** Destination name (queue/topic) */\n destination?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Trace LLM operations with Gen AI semantic conventions\n *\n * Automatically adds standard attributes for LLM operations:\n * - gen.ai.request.model\n * - gen.ai.operation.name\n * - gen.ai.system\n *\n * **Use Cases:**\n * - Chat completions\n * - Text generation\n * - Embeddings\n * - Multi-step LLM workflows\n *\n * @param config - LLM operation configuration\n * @returns Traced function factory with Gen AI attributes\n *\n * @example Chat completion with OpenAI\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import OpenAI from 'openai'\n *\n * const openai = new OpenAI()\n *\n * export const generateResponse = traceLLM({\n * model: 'gpt-4-turbo',\n * operation: 'chat',\n * provider: 'openai'\n * })(ctx => async (prompt: string) => {\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4-turbo',\n * messages: [{ role: 'user', content: prompt }]\n * })\n *\n * // Add usage metrics to span\n * ctx.setAttribute('gen.ai.usage.completion_tokens', response.usage?.completion_tokens)\n * ctx.setAttribute('gen.ai.usage.prompt_tokens', response.usage?.prompt_tokens)\n *\n * return response.choices[0].message.content\n * })\n * ```\n *\n * @example Anthropic Claude with streaming\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import Anthropic from '@anthropic-ai/sdk'\n *\n * const anthropic = new Anthropic()\n *\n * export const streamResponse = traceLLM({\n * model: 'claude-3-opus-20240229',\n * operation: 'chat',\n * provider: 'anthropic'\n * })(ctx => async function* (prompt: string) {\n * const stream = await anthropic.messages.create({\n * model: 'claude-3-opus-20240229',\n * messages: [{ role: 'user', content: prompt }],\n * stream: true,\n * max_tokens: 1024\n * })\n *\n * let totalTokens = 0\n * for await (const event of stream) {\n * if (event.type === 'content_block_delta') {\n * yield event.delta.text\n * }\n * if (event.type === 'message_stop') {\n * ctx.setAttribute('gen.ai.usage.completion_tokens', event.message.usage.output_tokens)\n * totalTokens = event.message.usage.output_tokens\n * }\n * }\n *\n * return totalTokens\n * })\n * ```\n *\n * @example Embeddings\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import { OpenAIEmbeddings } from '@langchain/openai'\n *\n * const embeddings = new OpenAIEmbeddings()\n *\n * export const embed = traceLLM({\n * model: 'text-embedding-3-small',\n * operation: 'embedding',\n * provider: 'openai'\n * })(ctx => async (text: string) => {\n * const result = await embeddings.embedQuery(text)\n * ctx.setAttribute('gen.ai.response.embedding_length', result.length)\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceLLM<TArgs extends unknown[], TReturn>(config: LLMConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('gen.ai.request.model', config.model);\n ctx.setAttribute('gen.ai.operation.name', config.operation || 'chat');\n if (config.provider) {\n ctx.setAttribute('gen.ai.system', config.provider);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace database operations with DB semantic conventions\n *\n * Automatically adds standard attributes for database operations:\n * - db.system\n * - db.operation\n * - db.name\n * - db.collection.name (for NoSQL)\n *\n * **Use Cases:**\n * - SQL queries (PostgreSQL, MySQL, SQLite)\n * - NoSQL operations (MongoDB, DynamoDB, Redis)\n * - ORM queries (Prisma, TypeORM, Drizzle)\n *\n * @param config - Database operation configuration\n * @returns Traced function factory with DB attributes\n *\n * @example PostgreSQL query\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { pool } from './db'\n *\n * export const getUser = traceDB({\n * system: 'postgresql',\n * operation: 'SELECT',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (userId: string) => {\n * const query = 'SELECT * FROM users WHERE id = $1'\n * ctx.setAttribute('db.statement', query)\n *\n * const result = await pool.query(query, [userId])\n * ctx.setAttribute('db.rows_affected', result.rowCount)\n *\n * return result.rows[0]\n * })\n * ```\n *\n * @example MongoDB with Mongoose\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { User } from './models/User'\n *\n * export const findUsers = traceDB({\n * system: 'mongodb',\n * operation: 'find',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (filter: object) => {\n * ctx.setAttribute('db.mongodb.filter', JSON.stringify(filter))\n *\n * const users = await User.find(filter).limit(100)\n * ctx.setAttribute('db.response.count', users.length)\n *\n * return users\n * })\n * ```\n *\n * @example Redis operations\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { redis } from './redis'\n *\n * export const cacheGet = traceDB({\n * system: 'redis',\n * operation: 'GET'\n * })(ctx => async (key: string) => {\n * ctx.setAttribute('db.redis.key', key)\n *\n * const value = await redis.get(key)\n * ctx.setAttribute('db.response.cache_hit', value !== null)\n *\n * return value\n * })\n * ```\n *\n * @example Prisma with detailed query info\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { prisma } from './prisma'\n *\n * export const createPost = traceDB({\n * system: 'postgresql',\n * operation: 'INSERT',\n * database: 'app_db',\n * collection: 'posts'\n * })(ctx => async (data: { title: string; content: string; authorId: string }) => {\n * ctx.setAttribute('db.prisma.model', 'Post')\n * ctx.setAttribute('db.prisma.action', 'create')\n *\n * const post = await prisma.post.create({ data })\n *\n * ctx.setAttribute('db.response.id', post.id)\n * return post\n * })\n * ```\n *\n * @public\n */\nexport function traceDB<TArgs extends unknown[], TReturn>(config: DBConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('db.system', config.system);\n if (config.operation) {\n ctx.setAttribute('db.operation', config.operation);\n }\n if (config.database) {\n ctx.setAttribute('db.name', config.database);\n }\n if (config.collection) {\n ctx.setAttribute('db.collection.name', config.collection);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace HTTP client operations with HTTP semantic conventions\n *\n * Automatically adds standard attributes for HTTP requests:\n * - http.request.method\n * - url.full\n *\n * **Use Cases:**\n * - External API calls\n * - Microservice communication\n * - Third-party integrations\n *\n * @param config - HTTP operation configuration\n * @returns Traced function factory with HTTP attributes\n *\n * @example Fetch API\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n *\n * export const fetchUser = traceHTTP({\n * method: 'GET',\n * url: 'https://api.example.com/users/:id'\n * })(ctx => async (userId: string) => {\n * const url = `https://api.example.com/users/${userId}`\n * ctx.setAttribute('url.full', url)\n *\n * const response = await fetch(url)\n * ctx.setAttribute('http.response.status_code', response.status)\n *\n * if (!response.ok) {\n * ctx.setAttribute('error', true)\n * throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n * }\n *\n * return response.json()\n * })\n * ```\n *\n * @example Axios with retry logic\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n * import axios from 'axios'\n *\n * export const sendWebhook = traceHTTP({\n * method: 'POST',\n * url: 'https://webhook.example.com/events'\n * })(ctx => async (payload: object) => {\n * let attempts = 0\n * const maxAttempts = 3\n *\n * while (attempts < maxAttempts) {\n * try {\n * attempts++\n * ctx.setAttribute('http.request.resend_count', attempts - 1)\n *\n * const response = await axios.post('https://webhook.example.com/events', payload)\n * ctx.setAttribute('http.response.status_code', response.status)\n * return response.data\n * } catch (error) {\n * if (attempts >= maxAttempts) throw error\n * await new Promise(resolve => setTimeout(resolve, 1000 * attempts))\n * }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function traceHTTP<TArgs extends unknown[], TReturn>(\n config: HTTPConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n if (config.method) {\n ctx.setAttribute('http.request.method', config.method);\n }\n if (config.url) {\n ctx.setAttribute('url.full', config.url);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace messaging operations with Messaging semantic conventions\n *\n * Automatically adds standard attributes for messaging:\n * - messaging.system\n * - messaging.operation\n * - messaging.destination.name\n *\n * **Use Cases:**\n * - Publishing messages to queues/topics\n * - Consuming messages from queues/topics\n * - Event-driven architectures\n *\n * @param config - Messaging operation configuration\n * @returns Traced function factory with Messaging attributes\n *\n * @example Publishing to Kafka\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { kafka } from './kafka'\n *\n * const producer = kafka.producer()\n *\n * export const publishEvent = traceMessaging({\n * system: 'kafka',\n * operation: 'publish',\n * destination: 'user-events'\n * })(ctx => async (event: { type: string; userId: string; data: object }) => {\n * ctx.setAttribute('messaging.message.type', event.type)\n * ctx.setAttribute('messaging.kafka.partition', 0)\n *\n * await producer.send({\n * topic: 'user-events',\n * messages: [\n * {\n * key: event.userId,\n * value: JSON.stringify(event.data)\n * }\n * ]\n * })\n *\n * ctx.setAttribute('messaging.message.id', event.userId)\n * })\n * ```\n *\n * @example Consuming from RabbitMQ\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { channel } from './rabbitmq'\n *\n * export const processOrder = traceMessaging({\n * system: 'rabbitmq',\n * operation: 'process',\n * destination: 'orders'\n * })(ctx => async (message: { orderId: string; items: object[] }) => {\n * ctx.setAttribute('messaging.message.id', message.orderId)\n * ctx.setAttribute('messaging.message.body.size', JSON.stringify(message).length)\n *\n * // Process order logic\n * const result = await processOrderInternal(message)\n *\n * ctx.setAttribute('messaging.operation.result', 'success')\n * return result\n * })\n * ```\n *\n * @example AWS SQS with batch processing\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { SQS } from '@aws-sdk/client-sqs'\n *\n * const sqs = new SQS()\n *\n * export const sendBatch = traceMessaging({\n * system: 'aws_sqs',\n * operation: 'publish',\n * destination: 'notifications-queue'\n * })(ctx => async (messages: Array<{ id: string; body: object }>) => {\n * ctx.setAttribute('messaging.batch.message_count', messages.length)\n *\n * const result = await sqs.sendMessageBatch({\n * QueueUrl: process.env.QUEUE_URL,\n * Entries: messages.map(msg => ({\n * Id: msg.id,\n * MessageBody: JSON.stringify(msg.body)\n * }))\n * })\n *\n * ctx.setAttribute('messaging.operation.success_count', result.Successful?.length || 0)\n * ctx.setAttribute('messaging.operation.failed_count', result.Failed?.length || 0)\n *\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceMessaging<TArgs extends unknown[], TReturn>(\n config: MessagingConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('messaging.system', config.system);\n if (config.operation) {\n ctx.setAttribute('messaging.operation', config.operation);\n }\n if (config.destination) {\n ctx.setAttribute('messaging.destination.name', config.destination);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/semantic-helpers.ts"],"names":[],"mappings":";;;AAiLO,SAAS,SAA2C,MAAA,EAAmB;AAC5E,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,sBAAA,EAAwB,MAAA,CAAO,KAAK,CAAA;AACrD,MAAA,GAAA,CAAI,YAAA,CAAa,uBAAA,EAAyB,MAAA,CAAO,SAAA,IAAa,MAAM,CAAA;AACpE,MAAA,IAAI,OAAO,QAAA,EAAU;AACnB,QAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,MAAA,CAAO,QAAQ,CAAA;AAAA,MACnD;AACA,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,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AAa,kBAAA,EAAoB,MAAA,CAAO,MAAM,CAAA;AAClD,MAAA,IAAI,OAAO,SAAA,EAAW;AACpB,QAAA,GAAA,CAAI,YAAA,CAAa,qBAAA,EAAuB,MAAA,CAAO,SAAS,CAAA;AAAA,MAC1D;AACA,MAAA,IAAI,OAAO,WAAA,EAAa;AACtB,QAAA,GAAA,CAAI,YAAA,CAAa,4BAAA,EAA8B,MAAA,CAAO,WAAW,CAAA;AAAA,MACnE;AACA,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-52ALHU7T.js","sourcesContent":["/**\n * Semantic convention helpers for OpenTelemetry\n *\n * Pre-configured trace helpers that follow OpenTelemetry semantic conventions\n * for common operation types. Reduces boilerplate and ensures consistency.\n *\n * Based on: https://opentelemetry.io/docs/specs/semconv/\n */\n\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport type { Attributes } from '@opentelemetry/api';\n\n/**\n * Configuration for LLM (Large Language Model) operations\n *\n * Follows Gen AI semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nexport interface LLMConfig {\n /** Model name (e.g., 'gpt-4', 'claude-3-opus') */\n model: string;\n /** Operation type */\n operation?: 'chat' | 'completion' | 'embedding';\n /** Model provider (e.g., 'openai', 'anthropic', 'cohere') - maps to gen.ai.system */\n provider?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for database operations\n *\n * Follows DB semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/database/\n */\nexport interface DBConfig {\n /** Database system (e.g., 'postgresql', 'mongodb', 'redis') */\n system: string;\n /** Operation type (e.g., 'SELECT', 'INSERT', 'find', 'get') */\n operation?: string;\n /** Database name */\n database?: string;\n /** Collection/table name */\n collection?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for HTTP client operations\n *\n * Follows HTTP semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/http/\n */\nexport interface HTTPConfig {\n /** HTTP method (e.g., 'GET', 'POST') */\n method?: string;\n /** Target URL or URL template */\n url?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for messaging operations\n *\n * Follows Messaging semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/messaging/\n */\nexport interface MessagingConfig {\n /** Messaging system (e.g., 'kafka', 'rabbitmq', 'sqs') */\n system: string;\n /** Operation type */\n operation?: 'publish' | 'receive' | 'process';\n /** Destination name (queue/topic) */\n destination?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Trace LLM operations with Gen AI semantic conventions\n *\n * Automatically adds standard attributes for LLM operations:\n * - gen.ai.request.model\n * - gen.ai.operation.name\n * - gen.ai.system\n *\n * **Use Cases:**\n * - Chat completions\n * - Text generation\n * - Embeddings\n * - Multi-step LLM workflows\n *\n * @param config - LLM operation configuration\n * @returns Traced function factory with Gen AI attributes\n *\n * @example Chat completion with OpenAI\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import OpenAI from 'openai'\n *\n * const openai = new OpenAI()\n *\n * export const generateResponse = traceLLM({\n * model: 'gpt-4-turbo',\n * operation: 'chat',\n * provider: 'openai'\n * })(ctx => async (prompt: string) => {\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4-turbo',\n * messages: [{ role: 'user', content: prompt }]\n * })\n *\n * // Add usage metrics to span\n * ctx.setAttribute('gen.ai.usage.completion_tokens', response.usage?.completion_tokens)\n * ctx.setAttribute('gen.ai.usage.prompt_tokens', response.usage?.prompt_tokens)\n *\n * return response.choices[0].message.content\n * })\n * ```\n *\n * @example Anthropic Claude with streaming\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import Anthropic from '@anthropic-ai/sdk'\n *\n * const anthropic = new Anthropic()\n *\n * export const streamResponse = traceLLM({\n * model: 'claude-3-opus-20240229',\n * operation: 'chat',\n * provider: 'anthropic'\n * })(ctx => async function* (prompt: string) {\n * const stream = await anthropic.messages.create({\n * model: 'claude-3-opus-20240229',\n * messages: [{ role: 'user', content: prompt }],\n * stream: true,\n * max_tokens: 1024\n * })\n *\n * let totalTokens = 0\n * for await (const event of stream) {\n * if (event.type === 'content_block_delta') {\n * yield event.delta.text\n * }\n * if (event.type === 'message_stop') {\n * ctx.setAttribute('gen.ai.usage.completion_tokens', event.message.usage.output_tokens)\n * totalTokens = event.message.usage.output_tokens\n * }\n * }\n *\n * return totalTokens\n * })\n * ```\n *\n * @example Embeddings\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import { OpenAIEmbeddings } from '@langchain/openai'\n *\n * const embeddings = new OpenAIEmbeddings()\n *\n * export const embed = traceLLM({\n * model: 'text-embedding-3-small',\n * operation: 'embedding',\n * provider: 'openai'\n * })(ctx => async (text: string) => {\n * const result = await embeddings.embedQuery(text)\n * ctx.setAttribute('gen.ai.response.embedding_length', result.length)\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceLLM<TArgs extends unknown[], TReturn>(config: LLMConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('gen.ai.request.model', config.model);\n ctx.setAttribute('gen.ai.operation.name', config.operation || 'chat');\n if (config.provider) {\n ctx.setAttribute('gen.ai.system', config.provider);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace database operations with DB semantic conventions\n *\n * Automatically adds standard attributes for database operations:\n * - db.system\n * - db.operation\n * - db.name\n * - db.collection.name (for NoSQL)\n *\n * **Use Cases:**\n * - SQL queries (PostgreSQL, MySQL, SQLite)\n * - NoSQL operations (MongoDB, DynamoDB, Redis)\n * - ORM queries (Prisma, TypeORM, Drizzle)\n *\n * @param config - Database operation configuration\n * @returns Traced function factory with DB attributes\n *\n * @example PostgreSQL query\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { pool } from './db'\n *\n * export const getUser = traceDB({\n * system: 'postgresql',\n * operation: 'SELECT',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (userId: string) => {\n * const query = 'SELECT * FROM users WHERE id = $1'\n * ctx.setAttribute('db.statement', query)\n *\n * const result = await pool.query(query, [userId])\n * ctx.setAttribute('db.rows_affected', result.rowCount)\n *\n * return result.rows[0]\n * })\n * ```\n *\n * @example MongoDB with Mongoose\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { User } from './models/User'\n *\n * export const findUsers = traceDB({\n * system: 'mongodb',\n * operation: 'find',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (filter: object) => {\n * ctx.setAttribute('db.mongodb.filter', JSON.stringify(filter))\n *\n * const users = await User.find(filter).limit(100)\n * ctx.setAttribute('db.response.count', users.length)\n *\n * return users\n * })\n * ```\n *\n * @example Redis operations\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { redis } from './redis'\n *\n * export const cacheGet = traceDB({\n * system: 'redis',\n * operation: 'GET'\n * })(ctx => async (key: string) => {\n * ctx.setAttribute('db.redis.key', key)\n *\n * const value = await redis.get(key)\n * ctx.setAttribute('db.response.cache_hit', value !== null)\n *\n * return value\n * })\n * ```\n *\n * @example Prisma with detailed query info\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { prisma } from './prisma'\n *\n * export const createPost = traceDB({\n * system: 'postgresql',\n * operation: 'INSERT',\n * database: 'app_db',\n * collection: 'posts'\n * })(ctx => async (data: { title: string; content: string; authorId: string }) => {\n * ctx.setAttribute('db.prisma.model', 'Post')\n * ctx.setAttribute('db.prisma.action', 'create')\n *\n * const post = await prisma.post.create({ data })\n *\n * ctx.setAttribute('db.response.id', post.id)\n * return post\n * })\n * ```\n *\n * @public\n */\nexport function traceDB<TArgs extends unknown[], TReturn>(config: DBConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('db.system', config.system);\n if (config.operation) {\n ctx.setAttribute('db.operation', config.operation);\n }\n if (config.database) {\n ctx.setAttribute('db.name', config.database);\n }\n if (config.collection) {\n ctx.setAttribute('db.collection.name', config.collection);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace HTTP client operations with HTTP semantic conventions\n *\n * Automatically adds standard attributes for HTTP requests:\n * - http.request.method\n * - url.full\n *\n * **Use Cases:**\n * - External API calls\n * - Microservice communication\n * - Third-party integrations\n *\n * @param config - HTTP operation configuration\n * @returns Traced function factory with HTTP attributes\n *\n * @example Fetch API\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n *\n * export const fetchUser = traceHTTP({\n * method: 'GET',\n * url: 'https://api.example.com/users/:id'\n * })(ctx => async (userId: string) => {\n * const url = `https://api.example.com/users/${userId}`\n * ctx.setAttribute('url.full', url)\n *\n * const response = await fetch(url)\n * ctx.setAttribute('http.response.status_code', response.status)\n *\n * if (!response.ok) {\n * ctx.setAttribute('error', true)\n * throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n * }\n *\n * return response.json()\n * })\n * ```\n *\n * @example Axios with retry logic\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n * import axios from 'axios'\n *\n * export const sendWebhook = traceHTTP({\n * method: 'POST',\n * url: 'https://webhook.example.com/events'\n * })(ctx => async (payload: object) => {\n * let attempts = 0\n * const maxAttempts = 3\n *\n * while (attempts < maxAttempts) {\n * try {\n * attempts++\n * ctx.setAttribute('http.request.resend_count', attempts - 1)\n *\n * const response = await axios.post('https://webhook.example.com/events', payload)\n * ctx.setAttribute('http.response.status_code', response.status)\n * return response.data\n * } catch (error) {\n * if (attempts >= maxAttempts) throw error\n * await new Promise(resolve => setTimeout(resolve, 1000 * attempts))\n * }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function traceHTTP<TArgs extends unknown[], TReturn>(\n config: HTTPConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n if (config.method) {\n ctx.setAttribute('http.request.method', config.method);\n }\n if (config.url) {\n ctx.setAttribute('url.full', config.url);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace messaging operations with Messaging semantic conventions\n *\n * Automatically adds standard attributes for messaging:\n * - messaging.system\n * - messaging.operation\n * - messaging.destination.name\n *\n * **Use Cases:**\n * - Publishing messages to queues/topics\n * - Consuming messages from queues/topics\n * - Event-driven architectures\n *\n * @param config - Messaging operation configuration\n * @returns Traced function factory with Messaging attributes\n *\n * @example Publishing to Kafka\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { kafka } from './kafka'\n *\n * const producer = kafka.producer()\n *\n * export const publishEvent = traceMessaging({\n * system: 'kafka',\n * operation: 'publish',\n * destination: 'user-events'\n * })(ctx => async (event: { type: string; userId: string; data: object }) => {\n * ctx.setAttribute('messaging.message.type', event.type)\n * ctx.setAttribute('messaging.kafka.partition', 0)\n *\n * await producer.send({\n * topic: 'user-events',\n * messages: [\n * {\n * key: event.userId,\n * value: JSON.stringify(event.data)\n * }\n * ]\n * })\n *\n * ctx.setAttribute('messaging.message.id', event.userId)\n * })\n * ```\n *\n * @example Consuming from RabbitMQ\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { channel } from './rabbitmq'\n *\n * export const processOrder = traceMessaging({\n * system: 'rabbitmq',\n * operation: 'process',\n * destination: 'orders'\n * })(ctx => async (message: { orderId: string; items: object[] }) => {\n * ctx.setAttribute('messaging.message.id', message.orderId)\n * ctx.setAttribute('messaging.message.body.size', JSON.stringify(message).length)\n *\n * // Process order logic\n * const result = await processOrderInternal(message)\n *\n * ctx.setAttribute('messaging.operation.result', 'success')\n * return result\n * })\n * ```\n *\n * @example AWS SQS with batch processing\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { SQS } from '@aws-sdk/client-sqs'\n *\n * const sqs = new SQS()\n *\n * export const sendBatch = traceMessaging({\n * system: 'aws_sqs',\n * operation: 'publish',\n * destination: 'notifications-queue'\n * })(ctx => async (messages: Array<{ id: string; body: object }>) => {\n * ctx.setAttribute('messaging.batch.message_count', messages.length)\n *\n * const result = await sqs.sendMessageBatch({\n * QueueUrl: process.env.QUEUE_URL,\n * Entries: messages.map(msg => ({\n * Id: msg.id,\n * MessageBody: JSON.stringify(msg.body)\n * }))\n * })\n *\n * ctx.setAttribute('messaging.operation.success_count', result.Successful?.length || 0)\n * ctx.setAttribute('messaging.operation.failed_count', result.Failed?.length || 0)\n *\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceMessaging<TArgs extends unknown[], TReturn>(\n config: MessagingConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('messaging.system', config.system);\n if (config.operation) {\n ctx.setAttribute('messaging.operation', config.operation);\n }\n if (config.destination) {\n ctx.setAttribute('messaging.destination.name', config.destination);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { requireModule } from './chunk-
|
|
1
|
+
import { requireModule } from './chunk-KVDA4HX2.js';
|
|
2
2
|
import { AdaptiveSampler, RandomSampler, NeverSampler, AlwaysSampler } from './chunk-DPSA4QLA.js';
|
|
3
3
|
import { readFileSync, existsSync } from 'fs';
|
|
4
4
|
import path from 'path';
|
|
@@ -166,5 +166,5 @@ function hasYamlConfig() {
|
|
|
166
166
|
}
|
|
167
167
|
|
|
168
168
|
export { hasYamlConfig, loadYamlConfig, loadYamlConfigFromFile };
|
|
169
|
-
//# sourceMappingURL=chunk-
|
|
170
|
-
//# sourceMappingURL=chunk-
|
|
169
|
+
//# sourceMappingURL=chunk-643PQG3Y.js.map
|
|
170
|
+
//# sourceMappingURL=chunk-643PQG3Y.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/yaml-config.ts"],"names":[],"mappings":";;;;;AAwCA,SAAS,cAAA,GAA+C;AACtD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,cAAuD,MAAM,CAAA;AACzE,IAAA,OAAO,GAAA,CAAI,KAAA;AAAA,EACb,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,MAAM,oDAAoD,CAAA;AAAA,EACtE;AACF;AAmCA,IAAM,eAAA,GAAkB,mDAAA;AAYxB,SAAS,kBAAkB,KAAA,EAAuB;AAChD,EAAA,OAAO,KAAA,CAAM,UAAA;AAAA,IACX,eAAA;AAAA,IACA,CAAC,MAAA,EAAQ,OAAA,EAAiB,YAAA,KAA0B;AAClD,MAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,OAAO,CAAA;AACpC,MAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,MAAA,IAAI,YAAA,KAAiB,QAAW,OAAO,YAAA;AACvC,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN,kCAAkC,OAAO,CAAA,gCAAA;AAAA,OAC3C;AACA,MAAA,OAAO,EAAA;AAAA,IACT;AAAA,GACF;AACF;AAQA,SAAS,sBAAsB,GAAA,EAAuB;AACpD,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AAC3B,IAAA,O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U,OAAO,CAAA;AACjC,EAAA,MAAM,WAAA,GAAc,sBAAsB,OAAO,CAAA;AACjD,EAAA,OAAO,oBAAoB,WAAW,CAAA;AACxC;AAOO,SAAS,aAAA,GAAyB;AACvC,EAAA,OAAO,gBAAe,KAAM,IAAA;AAC9B","file":"chunk-7NDHLHZK.js","sourcesContent":["/**\n * YAML configuration loader for autotel\n *\n * Supports:\n * - Auto-discovery of autotel.yaml in cwd\n * - AUTOTEL_CONFIG_FILE env var override\n * - Environment variable substitution: ${env:VAR} and ${env:VAR:-default}\n *\n * @example Auto-discovery\n * ```yaml\n * # autotel.yaml in project root\n * service:\n * name: my-service\n * exporter:\n * endpoint: ${env:OTEL_EXPORTER_OTLP_ENDPOINT:-http://localhost:4318}\n * ```\n *\n * @example Explicit path\n * ```bash\n * AUTOTEL_CONFIG_FILE=./config/otel.yaml tsx --import autotel/auto src/index.ts\n * ```\n */\n\nimport { readFileSync, existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type { AutotelConfig } from './init';\nimport {\n AdaptiveSampler,\n AlwaysSampler,\n NeverSampler,\n RandomSampler,\n type SamplingPreset,\n} from './sampling';\n\n/**\n * Lazy-load yaml parser (optional peer dependency)\n * Only loads when a YAML config file is actually found\n */\nimport { requireModule } from './node-require';\n\nfunction loadYamlParser(): (content: string) => unknown {\n try {\n const mod = requireModule<{ parse: (content: string) => unknown }>('yaml');\n return mod.parse;\n } catch {\n throw new Error('YAML parser not found. Install with: pnpm add yaml');\n }\n}\n\n/**\n * YAML config structure\n * Maps to AutotelConfig with user-friendly naming\n */\nexport interface YamlConfig {\n service?: {\n name?: string;\n version?: string;\n environment?: string;\n };\n exporter?: {\n endpoint?: string;\n protocol?: 'http' | 'grpc';\n headers?: Record<string, string>;\n };\n resource?: Record<string, string | number | boolean>;\n sampling?: {\n preset?: SamplingPreset;\n type?: 'adaptive' | 'always_on' | 'always_off' | 'ratio';\n ratio?: number;\n baseline_rate?: number;\n always_sample_errors?: boolean;\n always_sample_slow?: boolean;\n slow_threshold_ms?: number;\n };\n autoInstrumentations?: string[] | Record<string, { enabled?: boolean }>;\n debug?: boolean;\n}\n\n/**\n * Environment variable substitution regex\n * Matches ${env:VAR_NAME} and ${env:VAR_NAME:-default}\n */\nconst ENV_VAR_PATTERN = /\\$\\{env:([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\\}/g;\n\n/**\n * Substitute ${env:VAR} and ${env:VAR:-default} in a string\n *\n * @param value - String potentially containing env var references\n * @returns String with env vars substituted\n *\n * @example\n * substituteEnvVars('${env:NODE_ENV:-development}')\n * // Returns 'production' if NODE_ENV=production, else 'development'\n */\nfunction substituteEnvVars(value: string): string {\n return value.replaceAll(\n ENV_VAR_PATTERN,\n (_match, varName: string, defaultValue?: string) => {\n const envValue = process.env[varName];\n if (envValue !== undefined) return envValue;\n if (defaultValue !== undefined) return defaultValue;\n console.warn(\n `[autotel] Environment variable ${varName} not set and no default provided`,\n );\n return '';\n },\n );\n}\n\n/**\n * Recursively substitute env vars in an object\n *\n * @param obj - Object to process\n * @returns Object with all string values having env vars substituted\n */\nfunction substituteEnvVarsDeep(obj: unknown): unknown {\n if (typeof obj === 'string') {\n return substituteEnvVars(obj);\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => substituteEnvVarsDeep(item));\n }\n if (obj && typeof obj === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = substituteEnvVarsDeep(value);\n }\n return result;\n }\n return obj;\n}\n\n/**\n * Find YAML config file path\n *\n * Priority:\n * 1. AUTOTEL_CONFIG_FILE env var (explicit path)\n * 2. autotel.yaml in cwd (convention)\n * 3. autotel.yml in cwd (alternative extension)\n *\n * @returns File path if found, null otherwise\n */\nfunction findConfigFile(): string | null {\n // Check env var first (explicit takes priority)\n const envPath = process.env.AUTOTEL_CONFIG_FILE;\n if (envPath) {\n const resolved = path.resolve(envPath);\n if (existsSync(resolved)) return resolved;\n console.warn(`[autotel] Config file not found: ${envPath}`);\n return null;\n }\n\n // Auto-discover autotel.yaml in cwd\n const conventionPath = path.resolve(process.cwd(), 'autotel.yaml');\n if (existsSync(conventionPath)) return conventionPath;\n\n // Also check .yml extension\n const altPath = path.resolve(process.cwd(), 'autotel.yml');\n if (existsSync(altPath)) return altPath;\n\n return null;\n}\n\n/**\n * Convert YAML config structure to AutotelConfig\n *\n * @param yaml - Parsed and env-substituted YAML config\n * @returns Partial AutotelConfig ready for merging\n */\nfunction yamlToAutotelConfig(yaml: YamlConfig): Partial<AutotelConfig> {\n const config: Partial<AutotelConfig> = {};\n\n // Service configuration\n if (yaml.service?.name) config.service = yaml.service.name;\n if (yaml.service?.version) config.version = yaml.service.version;\n if (yaml.service?.environment) config.environment = yaml.service.environment;\n\n // Exporter configuration\n if (yaml.exporter?.endpoint) config.endpoint = yaml.exporter.endpoint;\n if (yaml.exporter?.protocol) config.protocol = yaml.exporter.protocol;\n if (yaml.exporter?.headers) config.headers = yaml.exporter.headers;\n\n // Resource attributes (flattened)\n if (yaml.resource) config.resourceAttributes = yaml.resource;\n\n // Integrations\n if (yaml.autoInstrumentations)\n config.autoInstrumentations = yaml.autoInstrumentations;\n\n // Debug mode\n if (yaml.debug !== undefined) config.debug = yaml.debug;\n\n // Sampling configuration\n if (yaml.sampling?.preset) {\n warnOnIgnoredPresetOverrides(yaml.sampling);\n config.sampling = yaml.sampling.preset;\n } else {\n const sampler = createSamplerFromYaml(yaml.sampling);\n if (sampler) config.sampler = sampler;\n }\n\n return config;\n}\n\nfunction createSamplerFromYaml(\n sampling?: YamlConfig['sampling'],\n): AutotelConfig['sampler'] {\n if (!sampling) return undefined;\n if (sampling.preset) return undefined;\n\n const type = sampling.type ?? 'adaptive';\n\n try {\n switch (type) {\n case 'adaptive': {\n return new AdaptiveSampler({\n baselineSampleRate: sampling.baseline_rate,\n alwaysSampleErrors: sampling.always_sample_errors,\n alwaysSampleSlow: sampling.always_sample_slow,\n slowThresholdMs: sampling.slow_threshold_ms,\n });\n }\n case 'always_on': {\n return new AlwaysSampler();\n }\n case 'always_off': {\n return new NeverSampler();\n }\n case 'ratio': {\n if (sampling.ratio === undefined) {\n console.warn(\n '[autotel] sampling.ratio missing in YAML sampling config. Falling back to adaptive sampler.',\n );\n return new AdaptiveSampler();\n }\n return new RandomSampler(sampling.ratio);\n }\n default: {\n console.warn(\n `[autotel] Unknown sampling type \"${type}\" in YAML config. Falling back to defaults.`,\n );\n return undefined;\n }\n }\n } catch (error) {\n console.warn(\n `[autotel] Failed to configure sampling from YAML: ${error instanceof Error ? error.message : String(error)}`,\n );\n return undefined;\n }\n}\n\nfunction warnOnIgnoredPresetOverrides(\n sampling: NonNullable<YamlConfig['sampling']>,\n): void {\n const ignoredFields = [\n 'type',\n 'ratio',\n 'baseline_rate',\n 'always_sample_errors',\n 'always_sample_slow',\n 'slow_threshold_ms',\n ].filter((field) => sampling[field as keyof typeof sampling] !== undefined);\n\n if (ignoredFields.length === 0) {\n return;\n }\n\n console.warn(\n `[autotel] sampling.preset=\"${sampling.preset}\" ignores these YAML fields: ${ignoredFields.join(', ')}. ` +\n 'Use the programmatic API with sampler or samplingPresets.*(...) for tuned presets.',\n );\n}\n\n/**\n * Load and parse YAML config file (auto-discovery)\n *\n * Automatically finds and loads autotel.yaml or uses AUTOTEL_CONFIG_FILE.\n * Returns null if no config file found (not an error - YAML config is optional).\n *\n * @returns Partial AutotelConfig or null if no config file found\n *\n * @example\n * const yamlConfig = loadYamlConfig();\n * if (yamlConfig) {\n * init({ ...yamlConfig, debug: true });\n * }\n */\nexport function loadYamlConfig(): Partial<AutotelConfig> | null {\n const filePath = findConfigFile();\n if (!filePath) return null;\n\n try {\n const content = readFileSync(filePath, 'utf8');\n const parseYaml = loadYamlParser();\n const rawYaml = parseYaml(content) as YamlConfig;\n const substituted = substituteEnvVarsDeep(rawYaml) as YamlConfig;\n return yamlToAutotelConfig(substituted);\n } catch (error) {\n console.error(\n `[autotel] Failed to load YAML config from ${filePath}:`,\n error,\n );\n return null;\n }\n}\n\n/**\n * Load YAML config from a specific file path\n *\n * Unlike loadYamlConfig(), this throws if the file cannot be read.\n *\n * @param filePath - Path to YAML config file\n * @returns Partial AutotelConfig\n * @throws Error if file cannot be read or parsed\n *\n * @example\n * import { loadYamlConfigFromFile } from 'autotel/yaml';\n * import { init } from 'autotel';\n *\n * const config = loadYamlConfigFromFile('./config/otel.yaml');\n * init({ ...config, debug: true });\n */\nexport function loadYamlConfigFromFile(\n filePath: string,\n): Partial<AutotelConfig> {\n const resolved = path.resolve(filePath);\n const content = readFileSync(resolved, 'utf8');\n const parseYaml = loadYamlParser();\n const rawYaml = parseYaml(content) as YamlConfig;\n const substituted = substituteEnvVarsDeep(rawYaml) as YamlConfig;\n return yamlToAutotelConfig(substituted);\n}\n\n/**\n * Check if a YAML config file exists (without loading it)\n *\n * @returns true if a config file would be found by loadYamlConfig()\n */\nexport function hasYamlConfig(): boolean {\n return findConfigFile() !== null;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/yaml-config.ts"],"names":[],"mappings":";;;;;AAwCA,SAAS,cAAA,GAA+C;AACtD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,cAAuD,MAAM,CAAA;AACzE,IAAA,OAAO,GAAA,CAAI,KAAA;AAAA,EACb,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,MAAM,oDAAoD,CAAA;AAAA,EACtE;AACF;AAmCA,IAAM,eAAA,GAAkB,mDAAA;AAYxB,SAAS,kBAAkB,KAAA,EAAuB;AAChD,EAAA,OAAO,KAAA,CAAM,UAAA;AAAA,IACX,eAAA;AAAA,IACA,CAAC,MAAA,EAAQ,OAAA,EAAiB,YAAA,KAA0B;AAClD,MAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,OAAO,CAAA;AACpC,MAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,MAAA,IAAI,YAAA,KAAiB,QAAW,OAAO,YAAA;AACvC,MAAA,OAAA,CAAQ,IAAA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MAAM,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA;AACtC,EAAA,MAAM,OAAA,GAAU,YAAA,CAAa,QAAA,EAAU,MAAM,CAAA;AAC7C,EAAA,MAAM,YAAY,cAAA,EAAe;AACjC,EAAA,MAAM,OAAA,GAAU,UAAU,OAAO,CAAA;AACjC,EAAA,MAAM,WAAA,GAAc,sBAAsB,OAAO,CAAA;AACjD,EAAA,OAAO,oBAAoB,WAAW,CAAA;AACxC;AAOO,SAAS,aAAA,GAAyB;AACvC,EAAA,OAAO,gBAAe,KAAM,IAAA;AAC9B","file":"chunk-643PQG3Y.js","sourcesContent":["/**\n * YAML configuration loader for autotel\n *\n * Supports:\n * - Auto-discovery of autotel.yaml in cwd\n * - AUTOTEL_CONFIG_FILE env var override\n * - Environment variable substitution: ${env:VAR} and ${env:VAR:-default}\n *\n * @example Auto-discovery\n * ```yaml\n * # autotel.yaml in project root\n * service:\n * name: my-service\n * exporter:\n * endpoint: ${env:OTEL_EXPORTER_OTLP_ENDPOINT:-http://localhost:4318}\n * ```\n *\n * @example Explicit path\n * ```bash\n * AUTOTEL_CONFIG_FILE=./config/otel.yaml tsx --import autotel/auto src/index.ts\n * ```\n */\n\nimport { readFileSync, existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type { AutotelConfig } from './init';\nimport {\n AdaptiveSampler,\n AlwaysSampler,\n NeverSampler,\n RandomSampler,\n type SamplingPreset,\n} from './sampling';\n\n/**\n * Lazy-load yaml parser (optional peer dependency)\n * Only loads when a YAML config file is actually found\n */\nimport { requireModule } from './node-require';\n\nfunction loadYamlParser(): (content: string) => unknown {\n try {\n const mod = requireModule<{ parse: (content: string) => unknown }>('yaml');\n return mod.parse;\n } catch {\n throw new Error('YAML parser not found. Install with: pnpm add yaml');\n }\n}\n\n/**\n * YAML config structure\n * Maps to AutotelConfig with user-friendly naming\n */\nexport interface YamlConfig {\n service?: {\n name?: string;\n version?: string;\n environment?: string;\n };\n exporter?: {\n endpoint?: string;\n protocol?: 'http' | 'grpc';\n headers?: Record<string, string>;\n };\n resource?: Record<string, string | number | boolean>;\n sampling?: {\n preset?: SamplingPreset;\n type?: 'adaptive' | 'always_on' | 'always_off' | 'ratio';\n ratio?: number;\n baseline_rate?: number;\n always_sample_errors?: boolean;\n always_sample_slow?: boolean;\n slow_threshold_ms?: number;\n };\n autoInstrumentations?: string[] | Record<string, { enabled?: boolean }>;\n debug?: boolean;\n}\n\n/**\n * Environment variable substitution regex\n * Matches ${env:VAR_NAME} and ${env:VAR_NAME:-default}\n */\nconst ENV_VAR_PATTERN = /\\$\\{env:([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\\}/g;\n\n/**\n * Substitute ${env:VAR} and ${env:VAR:-default} in a string\n *\n * @param value - String potentially containing env var references\n * @returns String with env vars substituted\n *\n * @example\n * substituteEnvVars('${env:NODE_ENV:-development}')\n * // Returns 'production' if NODE_ENV=production, else 'development'\n */\nfunction substituteEnvVars(value: string): string {\n return value.replaceAll(\n ENV_VAR_PATTERN,\n (_match, varName: string, defaultValue?: string) => {\n const envValue = process.env[varName];\n if (envValue !== undefined) return envValue;\n if (defaultValue !== undefined) return defaultValue;\n console.warn(\n `[autotel] Environment variable ${varName} not set and no default provided`,\n );\n return '';\n },\n );\n}\n\n/**\n * Recursively substitute env vars in an object\n *\n * @param obj - Object to process\n * @returns Object with all string values having env vars substituted\n */\nfunction substituteEnvVarsDeep(obj: unknown): unknown {\n if (typeof obj === 'string') {\n return substituteEnvVars(obj);\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => substituteEnvVarsDeep(item));\n }\n if (obj && typeof obj === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = substituteEnvVarsDeep(value);\n }\n return result;\n }\n return obj;\n}\n\n/**\n * Find YAML config file path\n *\n * Priority:\n * 1. AUTOTEL_CONFIG_FILE env var (explicit path)\n * 2. autotel.yaml in cwd (convention)\n * 3. autotel.yml in cwd (alternative extension)\n *\n * @returns File path if found, null otherwise\n */\nfunction findConfigFile(): string | null {\n // Check env var first (explicit takes priority)\n const envPath = process.env.AUTOTEL_CONFIG_FILE;\n if (envPath) {\n const resolved = path.resolve(envPath);\n if (existsSync(resolved)) return resolved;\n console.warn(`[autotel] Config file not found: ${envPath}`);\n return null;\n }\n\n // Auto-discover autotel.yaml in cwd\n const conventionPath = path.resolve(process.cwd(), 'autotel.yaml');\n if (existsSync(conventionPath)) return conventionPath;\n\n // Also check .yml extension\n const altPath = path.resolve(process.cwd(), 'autotel.yml');\n if (existsSync(altPath)) return altPath;\n\n return null;\n}\n\n/**\n * Convert YAML config structure to AutotelConfig\n *\n * @param yaml - Parsed and env-substituted YAML config\n * @returns Partial AutotelConfig ready for merging\n */\nfunction yamlToAutotelConfig(yaml: YamlConfig): Partial<AutotelConfig> {\n const config: Partial<AutotelConfig> = {};\n\n // Service configuration\n if (yaml.service?.name) config.service = yaml.service.name;\n if (yaml.service?.version) config.version = yaml.service.version;\n if (yaml.service?.environment) config.environment = yaml.service.environment;\n\n // Exporter configuration\n if (yaml.exporter?.endpoint) config.endpoint = yaml.exporter.endpoint;\n if (yaml.exporter?.protocol) config.protocol = yaml.exporter.protocol;\n if (yaml.exporter?.headers) config.headers = yaml.exporter.headers;\n\n // Resource attributes (flattened)\n if (yaml.resource) config.resourceAttributes = yaml.resource;\n\n // Integrations\n if (yaml.autoInstrumentations)\n config.autoInstrumentations = yaml.autoInstrumentations;\n\n // Debug mode\n if (yaml.debug !== undefined) config.debug = yaml.debug;\n\n // Sampling configuration\n if (yaml.sampling?.preset) {\n warnOnIgnoredPresetOverrides(yaml.sampling);\n config.sampling = yaml.sampling.preset;\n } else {\n const sampler = createSamplerFromYaml(yaml.sampling);\n if (sampler) config.sampler = sampler;\n }\n\n return config;\n}\n\nfunction createSamplerFromYaml(\n sampling?: YamlConfig['sampling'],\n): AutotelConfig['sampler'] {\n if (!sampling) return undefined;\n if (sampling.preset) return undefined;\n\n const type = sampling.type ?? 'adaptive';\n\n try {\n switch (type) {\n case 'adaptive': {\n return new AdaptiveSampler({\n baselineSampleRate: sampling.baseline_rate,\n alwaysSampleErrors: sampling.always_sample_errors,\n alwaysSampleSlow: sampling.always_sample_slow,\n slowThresholdMs: sampling.slow_threshold_ms,\n });\n }\n case 'always_on': {\n return new AlwaysSampler();\n }\n case 'always_off': {\n return new NeverSampler();\n }\n case 'ratio': {\n if (sampling.ratio === undefined) {\n console.warn(\n '[autotel] sampling.ratio missing in YAML sampling config. Falling back to adaptive sampler.',\n );\n return new AdaptiveSampler();\n }\n return new RandomSampler(sampling.ratio);\n }\n default: {\n console.warn(\n `[autotel] Unknown sampling type \"${type}\" in YAML config. Falling back to defaults.`,\n );\n return undefined;\n }\n }\n } catch (error) {\n console.warn(\n `[autotel] Failed to configure sampling from YAML: ${error instanceof Error ? error.message : String(error)}`,\n );\n return undefined;\n }\n}\n\nfunction warnOnIgnoredPresetOverrides(\n sampling: NonNullable<YamlConfig['sampling']>,\n): void {\n const ignoredFields = [\n 'type',\n 'ratio',\n 'baseline_rate',\n 'always_sample_errors',\n 'always_sample_slow',\n 'slow_threshold_ms',\n ].filter((field) => sampling[field as keyof typeof sampling] !== undefined);\n\n if (ignoredFields.length === 0) {\n return;\n }\n\n console.warn(\n `[autotel] sampling.preset=\"${sampling.preset}\" ignores these YAML fields: ${ignoredFields.join(', ')}. ` +\n 'Use the programmatic API with sampler or samplingPresets.*(...) for tuned presets.',\n );\n}\n\n/**\n * Load and parse YAML config file (auto-discovery)\n *\n * Automatically finds and loads autotel.yaml or uses AUTOTEL_CONFIG_FILE.\n * Returns null if no config file found (not an error - YAML config is optional).\n *\n * @returns Partial AutotelConfig or null if no config file found\n *\n * @example\n * const yamlConfig = loadYamlConfig();\n * if (yamlConfig) {\n * init({ ...yamlConfig, debug: true });\n * }\n */\nexport function loadYamlConfig(): Partial<AutotelConfig> | null {\n const filePath = findConfigFile();\n if (!filePath) return null;\n\n try {\n const content = readFileSync(filePath, 'utf8');\n const parseYaml = loadYamlParser();\n const rawYaml = parseYaml(content) as YamlConfig;\n const substituted = substituteEnvVarsDeep(rawYaml) as YamlConfig;\n return yamlToAutotelConfig(substituted);\n } catch (error) {\n console.error(\n `[autotel] Failed to load YAML config from ${filePath}:`,\n error,\n );\n return null;\n }\n}\n\n/**\n * Load YAML config from a specific file path\n *\n * Unlike loadYamlConfig(), this throws if the file cannot be read.\n *\n * @param filePath - Path to YAML config file\n * @returns Partial AutotelConfig\n * @throws Error if file cannot be read or parsed\n *\n * @example\n * import { loadYamlConfigFromFile } from 'autotel/yaml';\n * import { init } from 'autotel';\n *\n * const config = loadYamlConfigFromFile('./config/otel.yaml');\n * init({ ...config, debug: true });\n */\nexport function loadYamlConfigFromFile(\n filePath: string,\n): Partial<AutotelConfig> {\n const resolved = path.resolve(filePath);\n const content = readFileSync(resolved, 'utf8');\n const parseYaml = loadYamlParser();\n const rawYaml = parseYaml(content) as YamlConfig;\n const substituted = substituteEnvVarsDeep(rawYaml) as YamlConfig;\n return yamlToAutotelConfig(substituted);\n}\n\n/**\n * Check if a YAML config file exists (without loading it)\n *\n * @returns true if a config file would be found by loadYamlConfig()\n */\nexport function hasYamlConfig(): boolean {\n return findConfigFile() !== null;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { emitCorrelatedEvent } from './chunk-KIL5CUN6.js';
|
|
2
|
-
import { trace } from './chunk-
|
|
2
|
+
import { trace } from './chunk-T7CPAGOI.js';
|
|
3
3
|
import { extractLinksFromBatch, createLinkFromHeaders } from './chunk-DPSA4QLA.js';
|
|
4
4
|
import { SpanKind, propagation, context } from '@opentelemetry/api';
|
|
5
5
|
|
|
@@ -791,5 +791,5 @@ function clearOrderingState() {
|
|
|
791
791
|
}
|
|
792
792
|
|
|
793
793
|
export { clearOrderingState, traceConsumer, traceProducer };
|
|
794
|
-
//# sourceMappingURL=chunk-
|
|
795
|
-
//# sourceMappingURL=chunk-
|
|
794
|
+
//# sourceMappingURL=chunk-6TFJF7SS.js.map
|
|
795
|
+
//# sourceMappingURL=chunk-6TFJF7SS.js.map
|