@lelemon-ai/trace 0.0.0-stage → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1183 -2
- package/dist/anthropic.d.mts +25 -0
- package/dist/anthropic.d.ts +25 -0
- package/dist/anthropic.js +4 -0
- package/dist/anthropic.mjs +4 -0
- package/dist/bedrock.d.mts +25 -0
- package/dist/bedrock.d.ts +25 -0
- package/dist/bedrock.js +4 -0
- package/dist/bedrock.mjs +4 -0
- package/dist/capture-CC6pIfa4.d.mts +354 -0
- package/dist/capture-CC6pIfa4.d.ts +354 -0
- package/dist/express-BrfMWEVl.d.mts +67 -0
- package/dist/express-BrfMWEVl.d.ts +67 -0
- package/dist/express.d.mts +1 -0
- package/dist/express.d.ts +1 -0
- package/dist/express.js +3 -0
- package/dist/express.mjs +3 -0
- package/dist/gemini.d.mts +28 -0
- package/dist/gemini.d.ts +28 -0
- package/dist/gemini.js +4 -0
- package/dist/gemini.mjs +4 -0
- package/dist/google-genai.d.mts +31 -0
- package/dist/google-genai.d.ts +31 -0
- package/dist/google-genai.js +4 -0
- package/dist/google-genai.mjs +4 -0
- package/dist/hono-MTDbviM5.d.mts +80 -0
- package/dist/hono-MTDbviM5.d.ts +80 -0
- package/dist/hono.d.mts +1 -0
- package/dist/hono.d.ts +1 -0
- package/dist/hono.js +3 -0
- package/dist/hono.mjs +3 -0
- package/dist/index.d.mts +40 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.js +4 -0
- package/dist/index.mjs +4 -0
- package/dist/integrations.d.mts +4 -0
- package/dist/integrations.d.ts +4 -0
- package/dist/integrations.js +3 -0
- package/dist/integrations.mjs +3 -0
- package/dist/lambda-Drx54kXf.d.mts +79 -0
- package/dist/lambda-Drx54kXf.d.ts +79 -0
- package/dist/lambda.d.mts +1 -0
- package/dist/lambda.d.ts +1 -0
- package/dist/lambda.js +3 -0
- package/dist/lambda.mjs +3 -0
- package/dist/next-DONwf0f5.d.mts +100 -0
- package/dist/next-DONwf0f5.d.ts +100 -0
- package/dist/next.d.mts +1 -0
- package/dist/next.d.ts +1 -0
- package/dist/next.js +3 -0
- package/dist/next.mjs +3 -0
- package/dist/openai.d.mts +25 -0
- package/dist/openai.d.ts +25 -0
- package/dist/openai.js +4 -0
- package/dist/openai.mjs +4 -0
- package/dist/openrouter.d.mts +33 -0
- package/dist/openrouter.d.ts +33 -0
- package/dist/openrouter.js +4 -0
- package/dist/openrouter.mjs +4 -0
- package/package.json +173 -4
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Next.js App Router Integration
|
|
3
|
+
*
|
|
4
|
+
* Wraps route handlers to automatically flush traces.
|
|
5
|
+
* Supports Next.js 15+ `after()` and Vercel's `waitUntil()`.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* import { withObserve } from '@lelemon-ai/trace/next';
|
|
9
|
+
*
|
|
10
|
+
* export const POST = withObserve(async (req) => {
|
|
11
|
+
* const openai = observe(new OpenAI());
|
|
12
|
+
* const result = await openai.chat.completions.create({...});
|
|
13
|
+
* return Response.json(result);
|
|
14
|
+
* });
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Next.js App Router handler type
|
|
18
|
+
*
|
|
19
|
+
* @typeParam TContext - Optional context type for dynamic route parameters
|
|
20
|
+
*/
|
|
21
|
+
type NextRouteHandler<TContext = unknown> = (request: Request, context?: TContext) => Response | Promise<Response>;
|
|
22
|
+
/**
|
|
23
|
+
* Options for the Next.js wrapper
|
|
24
|
+
*/
|
|
25
|
+
interface NextObserveOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Next.js 15+ after() function from 'next/server'
|
|
28
|
+
* Preferred method - runs after response without blocking
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* import { after } from 'next/server';
|
|
32
|
+
* export const POST = withObserve(handler, { after });
|
|
33
|
+
*/
|
|
34
|
+
after?: (callback: () => void | Promise<void>) => void;
|
|
35
|
+
/**
|
|
36
|
+
* Vercel's waitUntil() from '@vercel/functions'
|
|
37
|
+
* Alternative for Vercel deployments
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* import { waitUntil } from '@vercel/functions';
|
|
41
|
+
* export const POST = withObserve(handler, { waitUntil });
|
|
42
|
+
*/
|
|
43
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Wrap a Next.js App Router handler with automatic trace flushing
|
|
47
|
+
*
|
|
48
|
+
* @param handler - Your route handler function
|
|
49
|
+
* @param options - Optional: pass `after` (Next.js 15+) or `waitUntil` (Vercel)
|
|
50
|
+
* @returns Wrapped handler that auto-flushes traces
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* // Basic usage (blocking flush)
|
|
54
|
+
* export const POST = withObserve(async (req) => {
|
|
55
|
+
* return Response.json({ ok: true });
|
|
56
|
+
* });
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* // Next.js 15+ with after() - non-blocking (recommended)
|
|
60
|
+
* import { after } from 'next/server';
|
|
61
|
+
*
|
|
62
|
+
* export const POST = withObserve(
|
|
63
|
+
* async (req) => Response.json({ ok: true }),
|
|
64
|
+
* { after }
|
|
65
|
+
* );
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* // Vercel with waitUntil() - non-blocking
|
|
69
|
+
* import { waitUntil } from '@vercel/functions';
|
|
70
|
+
*
|
|
71
|
+
* export const POST = withObserve(
|
|
72
|
+
* async (req) => Response.json({ ok: true }),
|
|
73
|
+
* { waitUntil }
|
|
74
|
+
* );
|
|
75
|
+
*/
|
|
76
|
+
declare function withObserve<TContext = unknown>(handler: NextRouteHandler<TContext>, options?: NextObserveOptions): NextRouteHandler<TContext>;
|
|
77
|
+
/**
|
|
78
|
+
* Create a pre-configured wrapper with default options
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* import { after } from 'next/server';
|
|
82
|
+
* import { createWrapper } from '@lelemon-ai/trace/next';
|
|
83
|
+
*
|
|
84
|
+
* const withObserve = createWrapper({ after });
|
|
85
|
+
*
|
|
86
|
+
* export const POST = withObserve(async (req) => {
|
|
87
|
+
* return Response.json({ ok: true });
|
|
88
|
+
* });
|
|
89
|
+
*/
|
|
90
|
+
declare function createWrapper(defaultOptions: NextObserveOptions): <TContext = unknown>(handler: NextRouteHandler<TContext>, options?: NextObserveOptions) => NextRouteHandler<TContext>;
|
|
91
|
+
|
|
92
|
+
type next_NextObserveOptions = NextObserveOptions;
|
|
93
|
+
type next_NextRouteHandler<TContext = unknown> = NextRouteHandler<TContext>;
|
|
94
|
+
declare const next_createWrapper: typeof createWrapper;
|
|
95
|
+
declare const next_withObserve: typeof withObserve;
|
|
96
|
+
declare namespace next {
|
|
97
|
+
export { type next_NextObserveOptions as NextObserveOptions, type next_NextRouteHandler as NextRouteHandler, next_createWrapper as createWrapper, next_withObserve as withObserve };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export { type NextRouteHandler as N, type NextObserveOptions as a, createWrapper as c, next as n, withObserve as w };
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Next.js App Router Integration
|
|
3
|
+
*
|
|
4
|
+
* Wraps route handlers to automatically flush traces.
|
|
5
|
+
* Supports Next.js 15+ `after()` and Vercel's `waitUntil()`.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* import { withObserve } from '@lelemon-ai/trace/next';
|
|
9
|
+
*
|
|
10
|
+
* export const POST = withObserve(async (req) => {
|
|
11
|
+
* const openai = observe(new OpenAI());
|
|
12
|
+
* const result = await openai.chat.completions.create({...});
|
|
13
|
+
* return Response.json(result);
|
|
14
|
+
* });
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Next.js App Router handler type
|
|
18
|
+
*
|
|
19
|
+
* @typeParam TContext - Optional context type for dynamic route parameters
|
|
20
|
+
*/
|
|
21
|
+
type NextRouteHandler<TContext = unknown> = (request: Request, context?: TContext) => Response | Promise<Response>;
|
|
22
|
+
/**
|
|
23
|
+
* Options for the Next.js wrapper
|
|
24
|
+
*/
|
|
25
|
+
interface NextObserveOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Next.js 15+ after() function from 'next/server'
|
|
28
|
+
* Preferred method - runs after response without blocking
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* import { after } from 'next/server';
|
|
32
|
+
* export const POST = withObserve(handler, { after });
|
|
33
|
+
*/
|
|
34
|
+
after?: (callback: () => void | Promise<void>) => void;
|
|
35
|
+
/**
|
|
36
|
+
* Vercel's waitUntil() from '@vercel/functions'
|
|
37
|
+
* Alternative for Vercel deployments
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* import { waitUntil } from '@vercel/functions';
|
|
41
|
+
* export const POST = withObserve(handler, { waitUntil });
|
|
42
|
+
*/
|
|
43
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Wrap a Next.js App Router handler with automatic trace flushing
|
|
47
|
+
*
|
|
48
|
+
* @param handler - Your route handler function
|
|
49
|
+
* @param options - Optional: pass `after` (Next.js 15+) or `waitUntil` (Vercel)
|
|
50
|
+
* @returns Wrapped handler that auto-flushes traces
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* // Basic usage (blocking flush)
|
|
54
|
+
* export const POST = withObserve(async (req) => {
|
|
55
|
+
* return Response.json({ ok: true });
|
|
56
|
+
* });
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* // Next.js 15+ with after() - non-blocking (recommended)
|
|
60
|
+
* import { after } from 'next/server';
|
|
61
|
+
*
|
|
62
|
+
* export const POST = withObserve(
|
|
63
|
+
* async (req) => Response.json({ ok: true }),
|
|
64
|
+
* { after }
|
|
65
|
+
* );
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* // Vercel with waitUntil() - non-blocking
|
|
69
|
+
* import { waitUntil } from '@vercel/functions';
|
|
70
|
+
*
|
|
71
|
+
* export const POST = withObserve(
|
|
72
|
+
* async (req) => Response.json({ ok: true }),
|
|
73
|
+
* { waitUntil }
|
|
74
|
+
* );
|
|
75
|
+
*/
|
|
76
|
+
declare function withObserve<TContext = unknown>(handler: NextRouteHandler<TContext>, options?: NextObserveOptions): NextRouteHandler<TContext>;
|
|
77
|
+
/**
|
|
78
|
+
* Create a pre-configured wrapper with default options
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* import { after } from 'next/server';
|
|
82
|
+
* import { createWrapper } from '@lelemon-ai/trace/next';
|
|
83
|
+
*
|
|
84
|
+
* const withObserve = createWrapper({ after });
|
|
85
|
+
*
|
|
86
|
+
* export const POST = withObserve(async (req) => {
|
|
87
|
+
* return Response.json({ ok: true });
|
|
88
|
+
* });
|
|
89
|
+
*/
|
|
90
|
+
declare function createWrapper(defaultOptions: NextObserveOptions): <TContext = unknown>(handler: NextRouteHandler<TContext>, options?: NextObserveOptions) => NextRouteHandler<TContext>;
|
|
91
|
+
|
|
92
|
+
type next_NextObserveOptions = NextObserveOptions;
|
|
93
|
+
type next_NextRouteHandler<TContext = unknown> = NextRouteHandler<TContext>;
|
|
94
|
+
declare const next_createWrapper: typeof createWrapper;
|
|
95
|
+
declare const next_withObserve: typeof withObserve;
|
|
96
|
+
declare namespace next {
|
|
97
|
+
export { type next_NextObserveOptions as NextObserveOptions, type next_NextRouteHandler as NextRouteHandler, next_createWrapper as createWrapper, next_withObserve as withObserve };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export { type NextRouteHandler as N, type NextObserveOptions as a, createWrapper as c, next as n, withObserve as w };
|
package/dist/next.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { a as NextObserveOptions, N as NextRouteHandler, c as createWrapper, w as withObserve } from './next-DONwf0f5.mjs';
|
package/dist/next.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { a as NextObserveOptions, N as NextRouteHandler, c as createWrapper, w as withObserve } from './next-DONwf0f5.js';
|
package/dist/next.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
async function t(){}function a(n,e){return async(r,o)=>{try{return await n(r,o)}finally{e?.after?e.after(()=>t()):e?.waitUntil?e.waitUntil(t()):await t();}}}function p(n){return function(e,r){return a(e,{...n,...r})}}exports.createWrapper=p;exports.withObserve=a;//# sourceMappingURL=next.js.map
|
|
3
|
+
//# sourceMappingURL=next.js.map
|
package/dist/next.mjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
async function t(){}function l(n,e){return async(r,o)=>{try{return await n(r,o)}finally{e?.after?e.after(()=>t()):e?.waitUntil?e.waitUntil(t()):await t();}}}function u(n){return function(e,r){return l(e,{...n,...r})}}export{u as createWrapper,l as withObserve};//# sourceMappingURL=next.mjs.map
|
|
3
|
+
//# sourceMappingURL=next.mjs.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { O as ObserveOptions } from './capture-CC6pIfa4.mjs';
|
|
2
|
+
export { C as CaptureSpanOptions, L as LelemonConfig, h as SpanOptions, d as SpanType, T as TraceContext, e as TraceOptions, c as captureSpan, f as flush, g as getTraceContext, i as init, a as isEnabled, s as span, t as trace } from './capture-CC6pIfa4.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* OpenAI Provider Entry Point
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { init, observe, flush } from '@lelemon-ai/trace/openai';
|
|
10
|
+
* import OpenAI from 'openai';
|
|
11
|
+
*
|
|
12
|
+
* init({ apiKey: process.env.LELEMON_API_KEY });
|
|
13
|
+
* const client = observe(new OpenAI());
|
|
14
|
+
*
|
|
15
|
+
* await client.chat.completions.create({...});
|
|
16
|
+
* await flush();
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Wrap an OpenAI client with automatic tracing
|
|
22
|
+
*/
|
|
23
|
+
declare function observe<T>(client: T, options?: ObserveOptions): T;
|
|
24
|
+
|
|
25
|
+
export { ObserveOptions, observe };
|
package/dist/openai.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { O as ObserveOptions } from './capture-CC6pIfa4.js';
|
|
2
|
+
export { C as CaptureSpanOptions, L as LelemonConfig, h as SpanOptions, d as SpanType, T as TraceContext, e as TraceOptions, c as captureSpan, f as flush, g as getTraceContext, i as init, a as isEnabled, s as span, t as trace } from './capture-CC6pIfa4.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* OpenAI Provider Entry Point
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { init, observe, flush } from '@lelemon-ai/trace/openai';
|
|
10
|
+
* import OpenAI from 'openai';
|
|
11
|
+
*
|
|
12
|
+
* init({ apiKey: process.env.LELEMON_API_KEY });
|
|
13
|
+
* const client = observe(new OpenAI());
|
|
14
|
+
*
|
|
15
|
+
* await client.chat.completions.create({...});
|
|
16
|
+
* await flush();
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Wrap an OpenAI client with automatic tracing
|
|
22
|
+
*/
|
|
23
|
+
declare function observe<T>(client: T, options?: ObserveOptions): T;
|
|
24
|
+
|
|
25
|
+
export { ObserveOptions, observe };
|
package/dist/openai.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var async_hooks=require('async_hooks');/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
var U=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var me=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var J=me((an,he)=>{he.exports={name:"@lelemon-ai/trace",version:"0.12.0",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/Lelemon-studio/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/Lelemon-studio/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],"google-genai":["./dist/google-genai.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@anthropic-ai/sdk":"^0.82.0","@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.18",typescript:"^6.0.0",vite:"^6.0.0",vitest:"^4.0.0"}};});var V=false;function B(e){V=e;}function y(){return V?true:ge("LELEMON_DEBUG")==="true"}var m="[Lelemon]";function p(e,n){y()&&P("debug",e,n);}function M(e,n){y()&&P("info",e,n);}function E(e,n){P("warn",e,n);}function D(e,n,t,r){y()&&console.log(`${m} Captured trace: provider=${e} model=${n} duration=${t}ms status=${r}`);}function x(e,n){console.error(`${m} Failed to capture trace: provider=${e} error=${n.message}`);}function H(e){y()&&console.log(`${m} Wrapped client: provider=${e}`);}function G(e,n){y()&&console.log(`${m} Sending batch: count=${e} endpoint=${n}`);}function W(e,n){y()&&console.log(`${m} Batch sent successfully: count=${e} duration=${n}ms`);}function Y(e,n){let t=n instanceof Error?n.message:String(n);console.error(`${m} Batch send failed: count=${e} error=${t}`);}function Z(e,n,t){y()&&console.log(`${m} Request: ${e} ${n} (${t} bytes)`);}function X(e,n){y()&&console.log(`${m} Response: status=${e} duration=${n}ms`);}function P(e,n,t){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;t!==void 0?r(`${m} ${n}`,t):r(`${m} ${n}`);}function ge(e){if(typeof process<"u"&&process.env)return process.env[e]}var we=10,ye=1e3,be=1e4,O=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(n){this.config={apiKey:n.apiKey,endpoint:n.endpoint,debug:n.debug,disabled:n.disabled,batchSize:n.batchSize??we,flushIntervalMs:n.flushIntervalMs??ye,requestTimeoutMs:n.requestTimeoutMs??be};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(n){this.config.disabled||(this.queue.push(n),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let n=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(n).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(n){if(n.length===0)return;let t=Date.now();G(n.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:n}),W(n.length,Date.now()-t);}catch(r){Y(n.length,r);}}async request(n,t,r){let s=`${this.config.endpoint}${t}`,o=new AbortController,i=r?JSON.stringify(r):void 0;Z(n,s,i?.length??0);let a=setTimeout(()=>{o.abort();},this.config.requestTimeoutMs),c=Date.now();try{let u=await fetch(s,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:i,signal:o.signal});if(clearTimeout(a),X(u.status,Date.now()-c),!u.ok){let l=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${l}`)}let d=await u.text();return d?JSON.parse(d):{}}catch(u){throw clearTimeout(a),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var ke="@lelemon-ai/trace",Te="nodejs";function ve(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function Ie(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function Ce(){try{if(typeof U<"u")return J().version??"unknown"}catch{}return "unknown"}var I=null;function ee(e){if(!I){let t=ve(),r=Ie();I={"telemetry.sdk.name":ke,"telemetry.sdk.version":Ce(),"telemetry.sdk.language":Te},t&&(I["process.runtime.name"]=t.name,I["process.runtime.version"]=t.version),r&&(I["os.type"]=r);}let n={...I};return e?.name&&(n["service.name"]=e.name),e?.version&&(n["service.version"]=e.version),e?.environment&&(n["deployment.environment"]=e.environment),n}var j={},h=null,q=null,ne="https://api.lelemon.dev";function Ee(e={}){j=e,e.debug&&B(true),q=ee(e.service),M("Initializing SDK",{endpoint:e.endpoint??ne,debug:e.debug??false,disabled:e.disabled??false,telemetry:q}),h=te(e),h.isEnabled()?M("SDK initialized - tracing enabled"):p("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function R(){return j}function _(){return q}function xe(){return k().isEnabled()}function k(){return h||(h=te(j)),h}async function Oe(){h&&await h.flush();}function te(e){let n=e.apiKey??Re("LELEMON_API_KEY");return !n&&!e.disabled&&E("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new O({apiKey:n??"",endpoint:e.endpoint??ne,debug:e.debug??false,disabled:e.disabled??!n,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function Re(e){if(typeof process<"u"&&process.env)return process.env[e]}function T(e){try{let n=k();if(!n.isEnabled()){p("Transport disabled, skipping trace capture");return}let t=e.context??{},r=g(),s=C(),o=_(),i={provider:e.provider,model:e.model,input:N(e.input),rawResponse:e.rawResponse?S(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:s,parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:t.tags??r?.tags,spanType:e.spanType,name:e.name};return D(e.provider,e.model,e.durationMs,e.status),n.enqueue(i),s}catch(n){x(e.provider,n instanceof Error?n:new Error(String(n)));return}}function v(e){try{let n=k();if(!n.isEnabled()){p("Transport disabled, skipping error capture");return}let t=e.context??{},r=g(),s=_(),o={provider:e.provider,model:e.model,input:N(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:C(),parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:t.tags??r?.tags};D(e.provider,e.model,e.durationMs,"error"),p("Error details",{message:e.error.message,stack:e.error.stack}),n.enqueue(o);}catch(n){x(e.provider,n instanceof Error?n:new Error(String(n)));}}function $(e){try{let n=k();if(!n.isEnabled()){p("Transport disabled, skipping span capture");return}let t=e.context??{},r=g(),s=e.metadata?._traceId,o=e.metadata?._parentSpanId,i=_(),a={...t.metadata,...e.metadata,...i?{_telemetry:i}:{}};delete a._traceId,delete a._parentSpanId;let c={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:N(e.input),output:S(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:s??r?.traceId,spanId:C(),parentSpanId:o??r?.currentSpanId,toolCallId:e.toolCallId,metadata:a,tags:t.tags??r?.tags};p(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),n.enqueue(c);}catch(n){x("unknown",n instanceof Error?n:new Error(String(n)));}}var re=1e5,_e=["api_key","apikey","password","secret","authorization"],Ae=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],Me=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],oe={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function se(){return R().redaction??{}}function De(e){let n=e.toLowerCase();return Me.includes(n)?false:!!(_e.some(r=>n.includes(r))||Ae.some(r=>n.includes(r))||(se().keys??[]).some(r=>n.includes(r.toLowerCase())))}function Pe(e){let n=se(),t=e;for(let r of n.patterns??[])r.lastIndex=0,t=t.replace(r,"[REDACTED]");return n.emails&&(t=t.replace(oe.emails,"[EMAIL]")),n.phones&&(t=t.replace(oe.phones,"[PHONE]")),t}function N(e){return S(e,0)}function S(e,n){if(n>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let t=Pe(e);return t.length>re&&(t=t.slice(0,re)+"...[truncated]"),t}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(t=>S(t,n+1));if(typeof e=="object"){let t={};for(let[r,s]of Object.entries(e))De(r)?t[r]="[REDACTED]":t[r]=S(s,n+1);return t}return String(e)}var K=Symbol.for("@lelemondev/sdk:traceStorage");function je(){let e=globalThis;return e[K]||(e[K]=new async_hooks.AsyncLocalStorage),e[K]}var ie=je();function C(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function g(){return ie.getStore()}function L(e,n){let t=g();if(t)for(let r of e)t.pendingToolCalls.set(r,n),p(`Registered tool call ${r} \u2192 LLM span ${n}`);}function $e(e){let n=g();if(n)return e&&n.pendingToolCalls.has(e)?n.pendingToolCalls.get(e):n.currentSpanId}function Ne(e){let n=g();n&&n.pendingToolCalls.delete(e);}async function Ke(e,n){let t=typeof e=="string"?{name:e}:e,r=g(),s=r?.traceId??C(),o=C(),i={traceId:s,rootSpanId:o,currentSpanId:o,parentSpanId:r?.currentSpanId,name:t.name,startTime:Date.now(),input:t.input,metadata:t.metadata,tags:t.tags,outputKey:t.outputKey,outputTransform:t.outputTransform,sessionId:t.sessionId,userId:t.userId,style:t.style,pendingToolCalls:new Map};return ie.run(i,async()=>{let a,c;try{return a=await n(),a}catch(u){throw c=u instanceof Error?u:new Error(String(u)),u}finally{Fe(i,c?void 0:a,c);}})}var Le=["text","content","message","output","response","result","answer"];function ze(e,n,t){if(t)try{return t(e)}catch{return e}if(n===false)return e;if(typeof n=="string"&&e&&typeof e=="object"){let s=e;return n in s?s[n]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let s of Le)if(s in r&&typeof r[s]=="string")return r[s];return e}function Fe(e,n,t){let r=k();if(!r.isEnabled()){p("Transport disabled, skipping root span");return}let s=Date.now()-e.startTime,o=t?null:ze(n,e.outputKey,e.outputTransform),i={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:o,inputTokens:0,outputTokens:0,durationMs:s,status:t?"error":"success",errorMessage:t?.message,streaming:false,sessionId:e.sessionId,userId:e.userId,metadata:{...e.metadata,...e.style?{_style:e.style}:{}},tags:e.tags};p(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!t}),r.enqueue(i);}function Ue(e){let n=g();if(!n){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let t=$e(e.toolCallId);$({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:n.traceId,_parentSpanId:t,...e.style?{_style:e.style}:{}}}),e.toolCallId&&Ne(e.toolCallId);}var f="openai";function ae(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="OpenAI")return true;let t=e;return !!(t.chat&&t.completions)||!!t.responses}function ue(e,n){return async function(...r){let s=Date.now(),o=r[0]||{},i=o.stream===true;try{let a=await e(...r);if(i&&ce(a))return Ve(a,o,s,n);let c=Date.now()-s,u=a,d=T({provider:f,model:o.model||u.model||"unknown",input:o.messages,rawResponse:a,durationMs:c,status:"success",streaming:!1,context:n});if(d){let l=fe(u);l.length>0&&L(l,d);}return a}catch(a){let c=Date.now()-s;throw v({provider:f,model:o.model||"unknown",input:o.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:i,context:n}),a}}}function ce(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Ve(e,n,t,r){let s={choices:[{message:{content:"",tool_calls:[]},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},o=null,i,a=false,c=new Map;try{for await(let u of e){let d=u,l=d?.choices?.[0]?.delta?.content;l&&(a||(a=!0,i=Date.now()-t),s.choices[0].message.content+=l);let z=d?.choices?.[0]?.delta?.tool_calls;if(z)for(let w of z){c.has(w.index)||c.set(w.index,{id:"",function:{name:"",arguments:""}});let A=c.get(w.index);w.id&&(A.id=w.id),w.function?.name&&(A.function.name=w.function.name),w.function?.arguments&&(A.function.arguments+=w.function.arguments);}let F=d?.choices?.[0]?.finish_reason;F&&(s.choices[0].finish_reason=F),d?.usage&&(s.usage=d.usage),yield u;}}catch(u){throw o=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-t;if(c.size>0&&(s.choices[0].message.tool_calls=Array.from(c.entries()).sort((d,l)=>d[0]-l[0]).map(([,d])=>d)),o)v({provider:f,model:n.model||"unknown",input:n.messages,error:o,durationMs:u,streaming:true,context:r});else {let d=T({provider:f,model:n.model||"unknown",input:n.messages,rawResponse:s,durationMs:u,status:"success",streaming:true,firstTokenMs:i,context:r});if(d){let l=fe(s);l.length>0&&L(l,d);}}}}function de(e,n){return async function(...r){let s=Date.now(),o=r[0]||{},i=o.stream===true;try{let a=await e(...r);if(i&&ce(a))return Be(a,o,s,n);let c=Date.now()-s;return T({provider:f,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},rawResponse:a,durationMs:c,status:"success",streaming:!1,context:n}),a}catch(a){let c=Date.now()-s;throw v({provider:f,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:i,context:n}),a}}}async function*Be(e,n,t,r){let s=[],o=null,i=null;try{for await(let a of e){s.push(a);let c=a;c.type==="response.done"&&c.response&&(o=c.response),yield a;}}catch(a){throw i=a instanceof Error?a:new Error(String(a)),a}finally{let a=Date.now()-t;i?v({provider:f,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},error:i,durationMs:a,streaming:true,context:r}):T({provider:f,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},rawResponse:o||{streamEvents:s},durationMs:a,status:"success",streaming:true,context:r});}}function pe(e,n){return async function(...r){let s=Date.now(),o=r[0]||{};try{let i=await e(...r),a=Date.now()-s;return T({provider:f,model:o.model||"unknown",input:o.prompt,rawResponse:i,durationMs:a,status:"success",streaming:!1,context:n}),i}catch(i){let a=Date.now()-s;throw v({provider:f,model:o.model||"unknown",input:o.prompt,error:i instanceof Error?i:new Error(String(i)),durationMs:a,streaming:false,context:n}),i}}}function le(e,n){return async function(...r){let s=Date.now(),o=r[0]||{};try{let i=await e(...r),a=Date.now()-s;return T({provider:f,model:o.model||"unknown",input:o.input,rawResponse:i,durationMs:a,status:"success",streaming:!1,spanType:"embedding",context:n}),i}catch(i){let a=Date.now()-s;throw v({provider:f,model:o.model||"unknown",input:o.input,error:i instanceof Error?i:new Error(String(i)),durationMs:a,streaming:false,context:n}),i}}}function fe(e){let n=[],t=e.choices?.[0]?.message?.tool_calls;if(Array.isArray(t))for(let r of t)r.id&&n.push(r.id);return n}function Mn(e,n){return R().disabled?(p("Tracing disabled, returning unwrapped client"),e):ae(e)?(H("openai"),Ge(e,n)):(E("Client is not an OpenAI client. Use @lelemon-ai/trace/openai only with OpenAI SDK."),e)}function Ge(e,n){let t=e;return new Proxy(t,{get(r,s,o){let i=Reflect.get(r,s,o);return s==="chat"&&i&&typeof i=="object"?We(i,n):s==="responses"&&i&&typeof i=="object"?Ze(i,n):s==="completions"&&i&&typeof i=="object"?Xe(i,n):s==="embeddings"&&i&&typeof i=="object"?Je(i,n):i}})}function We(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="completions"&&o&&typeof o=="object"?Ye(o,n):o}})}function Ye(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="create"&&typeof o=="function"?ue(o.bind(t),n):o}})}function Ze(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="create"&&typeof o=="function"?de(o.bind(t),n):o}})}function Xe(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="create"&&typeof o=="function"?pe(o.bind(t),n):o}})}function Je(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="create"&&typeof o=="function"?le(o.bind(t),n):o}})}
|
|
3
|
+
exports.captureSpan=$;exports.flush=Oe;exports.getTraceContext=g;exports.init=Ee;exports.isEnabled=xe;exports.observe=Mn;exports.span=Ue;exports.trace=Ke;//# sourceMappingURL=openai.js.map
|
|
4
|
+
//# sourceMappingURL=openai.js.map
|
package/dist/openai.mjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {AsyncLocalStorage}from'async_hooks';/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
var F=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var fe=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var X=fe((rn,be)=>{be.exports={name:"@lelemon-ai/trace",version:"0.12.0",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/Lelemon-studio/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/Lelemon-studio/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],"google-genai":["./dist/google-genai.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@anthropic-ai/sdk":"^0.82.0","@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.18",typescript:"^6.0.0",vite:"^6.0.0",vitest:"^4.0.0"}};});var U=false;function V(e){U=e;}function y(){return U?true:me("LELEMON_DEBUG")==="true"}var m="[Lelemon]";function p(e,n){y()&&D("debug",e,n);}function A(e,n){y()&&D("info",e,n);}function S(e,n){D("warn",e,n);}function M(e,n,t,r){y()&&console.log(`${m} Captured trace: provider=${e} model=${n} duration=${t}ms status=${r}`);}function E(e,n){console.error(`${m} Failed to capture trace: provider=${e} error=${n.message}`);}function B(e){y()&&console.log(`${m} Wrapped client: provider=${e}`);}function H(e,n){y()&&console.log(`${m} Sending batch: count=${e} endpoint=${n}`);}function G(e,n){y()&&console.log(`${m} Batch sent successfully: count=${e} duration=${n}ms`);}function W(e,n){let t=n instanceof Error?n.message:String(n);console.error(`${m} Batch send failed: count=${e} error=${t}`);}function Y(e,n,t){y()&&console.log(`${m} Request: ${e} ${n} (${t} bytes)`);}function Z(e,n){y()&&console.log(`${m} Response: status=${e} duration=${n}ms`);}function D(e,n,t){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;t!==void 0?r(`${m} ${n}`,t):r(`${m} ${n}`);}function me(e){if(typeof process<"u"&&process.env)return process.env[e]}var ge=10,we=1e3,ye=1e4,x=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(n){this.config={apiKey:n.apiKey,endpoint:n.endpoint,debug:n.debug,disabled:n.disabled,batchSize:n.batchSize??ge,flushIntervalMs:n.flushIntervalMs??we,requestTimeoutMs:n.requestTimeoutMs??ye};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(n){this.config.disabled||(this.queue.push(n),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let n=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(n).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(n){if(n.length===0)return;let t=Date.now();H(n.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:n}),G(n.length,Date.now()-t);}catch(r){W(n.length,r);}}async request(n,t,r){let s=`${this.config.endpoint}${t}`,o=new AbortController,i=r?JSON.stringify(r):void 0;Y(n,s,i?.length??0);let a=setTimeout(()=>{o.abort();},this.config.requestTimeoutMs),c=Date.now();try{let u=await fetch(s,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:i,signal:o.signal});if(clearTimeout(a),Z(u.status,Date.now()-c),!u.ok){let l=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${l}`)}let d=await u.text();return d?JSON.parse(d):{}}catch(u){throw clearTimeout(a),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var he="@lelemon-ai/trace",ke="nodejs";function Te(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function ve(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function Ie(){try{if(typeof F<"u")return X().version??"unknown"}catch{}return "unknown"}var v=null;function Q(e){if(!v){let t=Te(),r=ve();v={"telemetry.sdk.name":he,"telemetry.sdk.version":Ie(),"telemetry.sdk.language":ke},t&&(v["process.runtime.name"]=t.name,v["process.runtime.version"]=t.version),r&&(v["os.type"]=r);}let n={...v};return e?.name&&(n["service.name"]=e.name),e?.version&&(n["service.version"]=e.version),e?.environment&&(n["deployment.environment"]=e.environment),n}var q={},b=null,P=null,ee="https://api.lelemon.dev";function Se(e={}){q=e,e.debug&&V(true),P=Q(e.service),A("Initializing SDK",{endpoint:e.endpoint??ee,debug:e.debug??false,disabled:e.disabled??false,telemetry:P}),b=ne(e),b.isEnabled()?A("SDK initialized - tracing enabled"):p("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function O(){return q}function R(){return P}function Ee(){return h().isEnabled()}function h(){return b||(b=ne(q)),b}async function xe(){b&&await b.flush();}function ne(e){let n=e.apiKey??Oe("LELEMON_API_KEY");return !n&&!e.disabled&&S("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new x({apiKey:n??"",endpoint:e.endpoint??ee,debug:e.debug??false,disabled:e.disabled??!n,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function Oe(e){if(typeof process<"u"&&process.env)return process.env[e]}function k(e){try{let n=h();if(!n.isEnabled()){p("Transport disabled, skipping trace capture");return}let t=e.context??{},r=g(),s=I(),o=R(),i={provider:e.provider,model:e.model,input:$(e.input),rawResponse:e.rawResponse?C(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:s,parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:t.tags??r?.tags,spanType:e.spanType,name:e.name};return M(e.provider,e.model,e.durationMs,e.status),n.enqueue(i),s}catch(n){E(e.provider,n instanceof Error?n:new Error(String(n)));return}}function T(e){try{let n=h();if(!n.isEnabled()){p("Transport disabled, skipping error capture");return}let t=e.context??{},r=g(),s=R(),o={provider:e.provider,model:e.model,input:$(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:I(),parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:t.tags??r?.tags};M(e.provider,e.model,e.durationMs,"error"),p("Error details",{message:e.error.message,stack:e.error.stack}),n.enqueue(o);}catch(n){E(e.provider,n instanceof Error?n:new Error(String(n)));}}function j(e){try{let n=h();if(!n.isEnabled()){p("Transport disabled, skipping span capture");return}let t=e.context??{},r=g(),s=e.metadata?._traceId,o=e.metadata?._parentSpanId,i=R(),a={...t.metadata,...e.metadata,...i?{_telemetry:i}:{}};delete a._traceId,delete a._parentSpanId;let c={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:$(e.input),output:C(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:s??r?.traceId,spanId:I(),parentSpanId:o??r?.currentSpanId,toolCallId:e.toolCallId,metadata:a,tags:t.tags??r?.tags};p(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),n.enqueue(c);}catch(n){E("unknown",n instanceof Error?n:new Error(String(n)));}}var te=1e5,Re=["api_key","apikey","password","secret","authorization"],_e=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],Ae=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],re={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function oe(){return O().redaction??{}}function Me(e){let n=e.toLowerCase();return Ae.includes(n)?false:!!(Re.some(r=>n.includes(r))||_e.some(r=>n.includes(r))||(oe().keys??[]).some(r=>n.includes(r.toLowerCase())))}function De(e){let n=oe(),t=e;for(let r of n.patterns??[])r.lastIndex=0,t=t.replace(r,"[REDACTED]");return n.emails&&(t=t.replace(re.emails,"[EMAIL]")),n.phones&&(t=t.replace(re.phones,"[PHONE]")),t}function $(e){return C(e,0)}function C(e,n){if(n>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let t=De(e);return t.length>te&&(t=t.slice(0,te)+"...[truncated]"),t}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(t=>C(t,n+1));if(typeof e=="object"){let t={};for(let[r,s]of Object.entries(e))Me(r)?t[r]="[REDACTED]":t[r]=C(s,n+1);return t}return String(e)}var N=Symbol.for("@lelemondev/sdk:traceStorage");function qe(){let e=globalThis;return e[N]||(e[N]=new AsyncLocalStorage),e[N]}var se=qe();function I(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function g(){return se.getStore()}function K(e,n){let t=g();if(t)for(let r of e)t.pendingToolCalls.set(r,n),p(`Registered tool call ${r} \u2192 LLM span ${n}`);}function je(e){let n=g();if(n)return e&&n.pendingToolCalls.has(e)?n.pendingToolCalls.get(e):n.currentSpanId}function $e(e){let n=g();n&&n.pendingToolCalls.delete(e);}async function Ne(e,n){let t=typeof e=="string"?{name:e}:e,r=g(),s=r?.traceId??I(),o=I(),i={traceId:s,rootSpanId:o,currentSpanId:o,parentSpanId:r?.currentSpanId,name:t.name,startTime:Date.now(),input:t.input,metadata:t.metadata,tags:t.tags,outputKey:t.outputKey,outputTransform:t.outputTransform,sessionId:t.sessionId,userId:t.userId,style:t.style,pendingToolCalls:new Map};return se.run(i,async()=>{let a,c;try{return a=await n(),a}catch(u){throw c=u instanceof Error?u:new Error(String(u)),u}finally{ze(i,c?void 0:a,c);}})}var Ke=["text","content","message","output","response","result","answer"];function Le(e,n,t){if(t)try{return t(e)}catch{return e}if(n===false)return e;if(typeof n=="string"&&e&&typeof e=="object"){let s=e;return n in s?s[n]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let s of Ke)if(s in r&&typeof r[s]=="string")return r[s];return e}function ze(e,n,t){let r=h();if(!r.isEnabled()){p("Transport disabled, skipping root span");return}let s=Date.now()-e.startTime,o=t?null:Le(n,e.outputKey,e.outputTransform),i={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:o,inputTokens:0,outputTokens:0,durationMs:s,status:t?"error":"success",errorMessage:t?.message,streaming:false,sessionId:e.sessionId,userId:e.userId,metadata:{...e.metadata,...e.style?{_style:e.style}:{}},tags:e.tags};p(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!t}),r.enqueue(i);}function Fe(e){let n=g();if(!n){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let t=je(e.toolCallId);j({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:n.traceId,_parentSpanId:t,...e.style?{_style:e.style}:{}}}),e.toolCallId&&$e(e.toolCallId);}var f="openai";function ie(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="OpenAI")return true;let t=e;return !!(t.chat&&t.completions)||!!t.responses}function ae(e,n){return async function(...r){let s=Date.now(),o=r[0]||{},i=o.stream===true;try{let a=await e(...r);if(i&&ue(a))return Ue(a,o,s,n);let c=Date.now()-s,u=a,d=k({provider:f,model:o.model||u.model||"unknown",input:o.messages,rawResponse:a,durationMs:c,status:"success",streaming:!1,context:n});if(d){let l=le(u);l.length>0&&K(l,d);}return a}catch(a){let c=Date.now()-s;throw T({provider:f,model:o.model||"unknown",input:o.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:i,context:n}),a}}}function ue(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Ue(e,n,t,r){let s={choices:[{message:{content:"",tool_calls:[]},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},o=null,i,a=false,c=new Map;try{for await(let u of e){let d=u,l=d?.choices?.[0]?.delta?.content;l&&(a||(a=!0,i=Date.now()-t),s.choices[0].message.content+=l);let L=d?.choices?.[0]?.delta?.tool_calls;if(L)for(let w of L){c.has(w.index)||c.set(w.index,{id:"",function:{name:"",arguments:""}});let _=c.get(w.index);w.id&&(_.id=w.id),w.function?.name&&(_.function.name=w.function.name),w.function?.arguments&&(_.function.arguments+=w.function.arguments);}let z=d?.choices?.[0]?.finish_reason;z&&(s.choices[0].finish_reason=z),d?.usage&&(s.usage=d.usage),yield u;}}catch(u){throw o=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-t;if(c.size>0&&(s.choices[0].message.tool_calls=Array.from(c.entries()).sort((d,l)=>d[0]-l[0]).map(([,d])=>d)),o)T({provider:f,model:n.model||"unknown",input:n.messages,error:o,durationMs:u,streaming:true,context:r});else {let d=k({provider:f,model:n.model||"unknown",input:n.messages,rawResponse:s,durationMs:u,status:"success",streaming:true,firstTokenMs:i,context:r});if(d){let l=le(s);l.length>0&&K(l,d);}}}}function ce(e,n){return async function(...r){let s=Date.now(),o=r[0]||{},i=o.stream===true;try{let a=await e(...r);if(i&&ue(a))return Ve(a,o,s,n);let c=Date.now()-s;return k({provider:f,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},rawResponse:a,durationMs:c,status:"success",streaming:!1,context:n}),a}catch(a){let c=Date.now()-s;throw T({provider:f,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:i,context:n}),a}}}async function*Ve(e,n,t,r){let s=[],o=null,i=null;try{for await(let a of e){s.push(a);let c=a;c.type==="response.done"&&c.response&&(o=c.response),yield a;}}catch(a){throw i=a instanceof Error?a:new Error(String(a)),a}finally{let a=Date.now()-t;i?T({provider:f,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},error:i,durationMs:a,streaming:true,context:r}):k({provider:f,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},rawResponse:o||{streamEvents:s},durationMs:a,status:"success",streaming:true,context:r});}}function de(e,n){return async function(...r){let s=Date.now(),o=r[0]||{};try{let i=await e(...r),a=Date.now()-s;return k({provider:f,model:o.model||"unknown",input:o.prompt,rawResponse:i,durationMs:a,status:"success",streaming:!1,context:n}),i}catch(i){let a=Date.now()-s;throw T({provider:f,model:o.model||"unknown",input:o.prompt,error:i instanceof Error?i:new Error(String(i)),durationMs:a,streaming:false,context:n}),i}}}function pe(e,n){return async function(...r){let s=Date.now(),o=r[0]||{};try{let i=await e(...r),a=Date.now()-s;return k({provider:f,model:o.model||"unknown",input:o.input,rawResponse:i,durationMs:a,status:"success",streaming:!1,spanType:"embedding",context:n}),i}catch(i){let a=Date.now()-s;throw T({provider:f,model:o.model||"unknown",input:o.input,error:i instanceof Error?i:new Error(String(i)),durationMs:a,streaming:false,context:n}),i}}}function le(e){let n=[],t=e.choices?.[0]?.message?.tool_calls;if(Array.isArray(t))for(let r of t)r.id&&n.push(r.id);return n}function Cn(e,n){return O().disabled?(p("Tracing disabled, returning unwrapped client"),e):ie(e)?(B("openai"),He(e,n)):(S("Client is not an OpenAI client. Use @lelemon-ai/trace/openai only with OpenAI SDK."),e)}function He(e,n){let t=e;return new Proxy(t,{get(r,s,o){let i=Reflect.get(r,s,o);return s==="chat"&&i&&typeof i=="object"?Ge(i,n):s==="responses"&&i&&typeof i=="object"?Ye(i,n):s==="completions"&&i&&typeof i=="object"?Ze(i,n):s==="embeddings"&&i&&typeof i=="object"?Xe(i,n):i}})}function Ge(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="completions"&&o&&typeof o=="object"?We(o,n):o}})}function We(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="create"&&typeof o=="function"?ae(o.bind(t),n):o}})}function Ye(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="create"&&typeof o=="function"?ce(o.bind(t),n):o}})}function Ze(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="create"&&typeof o=="function"?de(o.bind(t),n):o}})}function Xe(e,n){return new Proxy(e,{get(t,r,s){let o=Reflect.get(t,r,s);return r==="create"&&typeof o=="function"?pe(o.bind(t),n):o}})}
|
|
3
|
+
export{j as captureSpan,xe as flush,g as getTraceContext,Se as init,Ee as isEnabled,Cn as observe,Fe as span,Ne as trace};//# sourceMappingURL=openai.mjs.map
|
|
4
|
+
//# sourceMappingURL=openai.mjs.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { O as ObserveOptions } from './capture-CC6pIfa4.mjs';
|
|
2
|
+
export { C as CaptureSpanOptions, L as LelemonConfig, h as SpanOptions, d as SpanType, T as TraceContext, e as TraceOptions, c as captureSpan, f as flush, g as getTraceContext, i as init, a as isEnabled, s as span, t as trace } from './capture-CC6pIfa4.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* OpenRouter Provider Entry Point
|
|
6
|
+
*
|
|
7
|
+
* OpenRouter uses the OpenAI SDK but routes to different model providers.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { init, observe, flush } from '@lelemon-ai/trace/openrouter';
|
|
12
|
+
* import OpenAI from 'openai';
|
|
13
|
+
*
|
|
14
|
+
* init({ apiKey: process.env.LELEMON_API_KEY });
|
|
15
|
+
* const client = observe(new OpenAI({
|
|
16
|
+
* baseURL: 'https://openrouter.ai/api/v1',
|
|
17
|
+
* apiKey: process.env.OPENROUTER_API_KEY,
|
|
18
|
+
* }));
|
|
19
|
+
*
|
|
20
|
+
* await client.chat.completions.create({
|
|
21
|
+
* model: 'anthropic/claude-3-opus',
|
|
22
|
+
* messages: [{...}],
|
|
23
|
+
* });
|
|
24
|
+
* await flush();
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Wrap an OpenRouter client (OpenAI SDK with OpenRouter baseURL) with automatic tracing
|
|
30
|
+
*/
|
|
31
|
+
declare function observe<T>(client: T, options?: ObserveOptions): T;
|
|
32
|
+
|
|
33
|
+
export { ObserveOptions, observe };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { O as ObserveOptions } from './capture-CC6pIfa4.js';
|
|
2
|
+
export { C as CaptureSpanOptions, L as LelemonConfig, h as SpanOptions, d as SpanType, T as TraceContext, e as TraceOptions, c as captureSpan, f as flush, g as getTraceContext, i as init, a as isEnabled, s as span, t as trace } from './capture-CC6pIfa4.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* OpenRouter Provider Entry Point
|
|
6
|
+
*
|
|
7
|
+
* OpenRouter uses the OpenAI SDK but routes to different model providers.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { init, observe, flush } from '@lelemon-ai/trace/openrouter';
|
|
12
|
+
* import OpenAI from 'openai';
|
|
13
|
+
*
|
|
14
|
+
* init({ apiKey: process.env.LELEMON_API_KEY });
|
|
15
|
+
* const client = observe(new OpenAI({
|
|
16
|
+
* baseURL: 'https://openrouter.ai/api/v1',
|
|
17
|
+
* apiKey: process.env.OPENROUTER_API_KEY,
|
|
18
|
+
* }));
|
|
19
|
+
*
|
|
20
|
+
* await client.chat.completions.create({
|
|
21
|
+
* model: 'anthropic/claude-3-opus',
|
|
22
|
+
* messages: [{...}],
|
|
23
|
+
* });
|
|
24
|
+
* await flush();
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Wrap an OpenRouter client (OpenAI SDK with OpenRouter baseURL) with automatic tracing
|
|
30
|
+
*/
|
|
31
|
+
declare function observe<T>(client: T, options?: ObserveOptions): T;
|
|
32
|
+
|
|
33
|
+
export { ObserveOptions, observe };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var async_hooks=require('async_hooks');/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
var L=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var G=oe((We,de)=>{de.exports={name:"@lelemon-ai/trace",version:"0.12.0",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/Lelemon-studio/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/Lelemon-studio/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],"google-genai":["./dist/google-genai.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@anthropic-ai/sdk":"^0.82.0","@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.18",typescript:"^6.0.0",vite:"^6.0.0",vitest:"^4.0.0"}};});var K=false;function N(e){K=e;}function f(){return K?true:se("LELEMON_DEBUG")==="true"}var p="[Lelemon]";function c(e,t){f()&&O("debug",e,t);}function R(e,t){f()&&O("info",e,t);}function v(e,t){O("warn",e,t);}function _(e,t,n,r){f()&&console.log(`${p} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function S(e,t){console.error(`${p} Failed to capture trace: provider=${e} error=${t.message}`);}function U(e){f()&&console.log(`${p} Wrapped client: provider=${e}`);}function z(e,t){f()&&console.log(`${p} Sending batch: count=${e} endpoint=${t}`);}function F(e,t){f()&&console.log(`${p} Batch sent successfully: count=${e} duration=${t}ms`);}function B(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${p} Batch send failed: count=${e} error=${n}`);}function V(e,t,n){f()&&console.log(`${p} Request: ${e} ${t} (${n} bytes)`);}function H(e,t){f()&&console.log(`${p} Response: status=${e} duration=${t}ms`);}function O(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${p} ${t}`,n):r(`${p} ${t}`);}function se(e){if(typeof process<"u"&&process.env)return process.env[e]}var ie=10,ae=1e3,ue=1e4,I=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(t){this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??ie,flushIntervalMs:t.flushIntervalMs??ae,requestTimeoutMs:t.requestTimeoutMs??ue};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(t){this.config.disabled||(this.queue.push(t),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let t=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(t).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(t){if(t.length===0)return;let n=Date.now();z(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),F(t.length,Date.now()-n);}catch(r){B(t.length,r);}}async request(t,n,r){let o=`${this.config.endpoint}${n}`,s=new AbortController,a=r?JSON.stringify(r):void 0;V(t,o,a?.length??0);let i=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),d=Date.now();try{let u=await fetch(o,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:s.signal});if(clearTimeout(i),H(u.status,Date.now()-d),!u.ok){let k=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${k}`)}let T=await u.text();return T?JSON.parse(T):{}}catch(u){throw clearTimeout(i),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var ce="@lelemon-ai/trace",pe="nodejs";function le(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function fe(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function me(){try{if(typeof L<"u")return G().version??"unknown"}catch{}return "unknown"}var h=null;function Y(e){if(!h){let n=le(),r=fe();h={"telemetry.sdk.name":ce,"telemetry.sdk.version":me(),"telemetry.sdk.language":pe},n&&(h["process.runtime.name"]=n.name,h["process.runtime.version"]=n.version),r&&(h["os.type"]=r);}let t={...h};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var q={},g=null,M=null,Z="https://api.lelemon.dev";function ye(e={}){q=e,e.debug&&N(true),M=Y(e.service),R("Initializing SDK",{endpoint:e.endpoint??Z,debug:e.debug??false,disabled:e.disabled??false,telemetry:M}),g=X(e),g.isEnabled()?R("SDK initialized - tracing enabled"):c("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function C(){return q}function x(){return M}function he(){return y().isEnabled()}function y(){return g||(g=X(q)),g}async function be(){g&&await g.flush();}function X(e){let t=e.apiKey??Te("LELEMON_API_KEY");return !t&&!e.disabled&&v("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new I({apiKey:t??"",endpoint:e.endpoint??Z,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function Te(e){if(typeof process<"u"&&process.env)return process.env[e]}function D(e){try{let t=y();if(!t.isEnabled()){c("Transport disabled, skipping trace capture");return}let n=e.context??{},r=l(),o=b(),s=x(),a={provider:e.provider,model:e.model,input:$(e.input),rawResponse:e.rawResponse?w(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags??r?.tags,spanType:e.spanType,name:e.name};return _(e.provider,e.model,e.durationMs,e.status),t.enqueue(a),o}catch(t){S(e.provider,t instanceof Error?t:new Error(String(t)));return}}function A(e){try{let t=y();if(!t.isEnabled()){c("Transport disabled, skipping error capture");return}let n=e.context??{},r=l(),o=x(),s={provider:e.provider,model:e.model,input:$(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:b(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:n.tags??r?.tags};_(e.provider,e.model,e.durationMs,"error"),c("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(s);}catch(t){S(e.provider,t instanceof Error?t:new Error(String(t)));}}function P(e){try{let t=y();if(!t.isEnabled()){c("Transport disabled, skipping span capture");return}let n=e.context??{},r=l(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,a=x(),i={...n.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete i._traceId,delete i._parentSpanId;let d={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:$(e.input),output:w(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:o??r?.traceId,spanId:b(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:i,tags:n.tags??r?.tags};c(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(d);}catch(t){S("unknown",t instanceof Error?t:new Error(String(t)));}}var J=1e5,we=["api_key","apikey","password","secret","authorization"],ke=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],ve=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],Q={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function ee(){return C().redaction??{}}function Se(e){let t=e.toLowerCase();return ve.includes(t)?false:!!(we.some(r=>t.includes(r))||ke.some(r=>t.includes(r))||(ee().keys??[]).some(r=>t.includes(r.toLowerCase())))}function Ie(e){let t=ee(),n=e;for(let r of t.patterns??[])r.lastIndex=0,n=n.replace(r,"[REDACTED]");return t.emails&&(n=n.replace(Q.emails,"[EMAIL]")),t.phones&&(n=n.replace(Q.phones,"[PHONE]")),n}function $(e){return w(e,0)}function w(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let n=Ie(e);return n.length>J&&(n=n.slice(0,J)+"...[truncated]"),n}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>w(n,t+1));if(typeof e=="object"){let n={};for(let[r,o]of Object.entries(e))Se(r)?n[r]="[REDACTED]":n[r]=w(o,t+1);return n}return String(e)}var j=Symbol.for("@lelemondev/sdk:traceStorage");function xe(){let e=globalThis;return e[j]||(e[j]=new async_hooks.AsyncLocalStorage),e[j]}var te=xe();function b(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function l(){return te.getStore()}function Ee(e){let t=l();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function Re(e){let t=l();t&&t.pendingToolCalls.delete(e);}async function _e(e,t){let n=typeof e=="string"?{name:e}:e,r=l(),o=r?.traceId??b(),s=b(),a={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,outputKey:n.outputKey,outputTransform:n.outputTransform,sessionId:n.sessionId,userId:n.userId,style:n.style,pendingToolCalls:new Map};return te.run(a,async()=>{let i,d;try{return i=await t(),i}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{qe(a,d?void 0:i,d);}})}var Oe=["text","content","message","output","response","result","answer"];function Me(e,t,n){if(n)try{return n(e)}catch{return e}if(t===false)return e;if(typeof t=="string"&&e&&typeof e=="object"){let o=e;return t in o?o[t]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let o of Oe)if(o in r&&typeof r[o]=="string")return r[o];return e}function qe(e,t,n){let r=y();if(!r.isEnabled()){c("Transport disabled, skipping root span");return}let o=Date.now()-e.startTime,s=n?null:Me(t,e.outputKey,e.outputTransform),a={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:s,inputTokens:0,outputTokens:0,durationMs:o,status:n?"error":"success",errorMessage:n?.message,streaming:false,sessionId:e.sessionId,userId:e.userId,metadata:{...e.metadata,...e.style?{_style:e.style}:{}},tags:e.tags};c(`Sending root span: ${e.name}`,{durationMs:o,hasError:!!n}),r.enqueue(a);}function De(e){let t=l();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=Ee(e.toolCallId);P({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:t.traceId,_parentSpanId:n,...e.style?{_style:e.style}:{}}}),e.toolCallId&&Re(e.toolCallId);}var Ae="openrouter.ai",E="openrouter";function ne(e){if(!e||typeof e!="object")return false;let t=e;return t.chat?.completions?.create?(t.baseURL||"").includes(Ae):false}function re(e,t){let n=e;return new Proxy(n,{get(r,o,s){let a=Reflect.get(r,o,s);return o==="chat"&&a&&typeof a=="object"?Pe(a,t):a}})}function Pe(e,t){return e&&new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="completions"&&s&&typeof s=="object"?$e(s,t):s}})}function $e(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="create"&&typeof s=="function"?je(s.bind(n),t):s}})}function je(e,t){return async function(...r){let o=Date.now(),s=r[0]||{},a=s.stream===true;try{let i=await e(...r);if(a&&Le(i))return Ke(i,s,o,t);let d=Date.now()-o,u=i;return D({provider:E,model:s.model||u.model||"unknown",input:s.messages,rawResponse:i,durationMs:d,status:"success",streaming:!1,context:t}),i}catch(i){let d=Date.now()-o;throw A({provider:E,model:s.model||"unknown",input:s.messages,error:i instanceof Error?i:new Error(String(i)),durationMs:d,streaming:a,context:t}),i}}}function Le(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Ke(e,t,n,r){let o={choices:[{message:{content:"",role:"assistant"},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},s=null,a,i=false;try{for await(let d of e){let u=d;!o.id&&u.id&&(o.id=u.id);let T=u.choices?.[0]?.delta?.content;T&&(i||(i=!0,a=Date.now()-n),o.choices[0].message.content+=T);let k=u.choices?.[0]?.finish_reason;k&&(o.choices[0].finish_reason=k),u.usage&&(o.usage=u.usage),yield d;}}catch(d){throw s=d instanceof Error?d:new Error(String(d)),d}finally{let d=Date.now()-n;s?A({provider:E,model:t.model||"unknown",input:t.messages,error:s,durationMs:d,streaming:true,context:r}):D({provider:E,model:t.model||"unknown",input:t.messages,rawResponse:o,durationMs:d,status:"success",streaming:true,firstTokenMs:a,context:r});}}function bt(e,t){return C().disabled?(c("Tracing disabled, returning unwrapped client"),e):ne(e)?(U("openrouter"),re(e,t)):(v("Client is not configured for OpenRouter. Ensure baseURL is set to openrouter.ai."),e)}
|
|
3
|
+
exports.captureSpan=P;exports.flush=be;exports.getTraceContext=l;exports.init=ye;exports.isEnabled=he;exports.observe=bt;exports.span=De;exports.trace=_e;//# sourceMappingURL=openrouter.js.map
|
|
4
|
+
//# sourceMappingURL=openrouter.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {AsyncLocalStorage}from'async_hooks';/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
var j=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var re=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var H=re((Ve,ue)=>{ue.exports={name:"@lelemon-ai/trace",version:"0.12.0",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/Lelemon-studio/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/Lelemon-studio/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],"google-genai":["./dist/google-genai.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@anthropic-ai/sdk":"^0.82.0","@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.18",typescript:"^6.0.0",vite:"^6.0.0",vitest:"^4.0.0"}};});var L=false;function K(e){L=e;}function f(){return L?true:oe("LELEMON_DEBUG")==="true"}var p="[Lelemon]";function c(e,t){f()&&_("debug",e,t);}function E(e,t){f()&&_("info",e,t);}function k(e,t){_("warn",e,t);}function R(e,t,n,r){f()&&console.log(`${p} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function v(e,t){console.error(`${p} Failed to capture trace: provider=${e} error=${t.message}`);}function N(e){f()&&console.log(`${p} Wrapped client: provider=${e}`);}function U(e,t){f()&&console.log(`${p} Sending batch: count=${e} endpoint=${t}`);}function z(e,t){f()&&console.log(`${p} Batch sent successfully: count=${e} duration=${t}ms`);}function F(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${p} Batch send failed: count=${e} error=${n}`);}function B(e,t,n){f()&&console.log(`${p} Request: ${e} ${t} (${n} bytes)`);}function V(e,t){f()&&console.log(`${p} Response: status=${e} duration=${t}ms`);}function _(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${p} ${t}`,n):r(`${p} ${t}`);}function oe(e){if(typeof process<"u"&&process.env)return process.env[e]}var se=10,ie=1e3,ae=1e4,S=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(t){this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??se,flushIntervalMs:t.flushIntervalMs??ie,requestTimeoutMs:t.requestTimeoutMs??ae};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(t){this.config.disabled||(this.queue.push(t),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let t=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(t).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(t){if(t.length===0)return;let n=Date.now();U(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),z(t.length,Date.now()-n);}catch(r){F(t.length,r);}}async request(t,n,r){let o=`${this.config.endpoint}${n}`,s=new AbortController,a=r?JSON.stringify(r):void 0;B(t,o,a?.length??0);let i=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),d=Date.now();try{let u=await fetch(o,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:s.signal});if(clearTimeout(i),V(u.status,Date.now()-d),!u.ok){let w=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${w}`)}let b=await u.text();return b?JSON.parse(b):{}}catch(u){throw clearTimeout(i),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var de="@lelemon-ai/trace",ce="nodejs";function pe(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function le(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function fe(){try{if(typeof j<"u")return H().version??"unknown"}catch{}return "unknown"}var y=null;function W(e){if(!y){let n=pe(),r=le();y={"telemetry.sdk.name":de,"telemetry.sdk.version":fe(),"telemetry.sdk.language":ce},n&&(y["process.runtime.name"]=n.name,y["process.runtime.version"]=n.version),r&&(y["os.type"]=r);}let t={...y};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var M={},m=null,O=null,Y="https://api.lelemon.dev";function ge(e={}){M=e,e.debug&&K(true),O=W(e.service),E("Initializing SDK",{endpoint:e.endpoint??Y,debug:e.debug??false,disabled:e.disabled??false,telemetry:O}),m=Z(e),m.isEnabled()?E("SDK initialized - tracing enabled"):c("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function I(){return M}function C(){return O}function ye(){return g().isEnabled()}function g(){return m||(m=Z(M)),m}async function he(){m&&await m.flush();}function Z(e){let t=e.apiKey??be("LELEMON_API_KEY");return !t&&!e.disabled&&k("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new S({apiKey:t??"",endpoint:e.endpoint??Y,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function be(e){if(typeof process<"u"&&process.env)return process.env[e]}function q(e){try{let t=g();if(!t.isEnabled()){c("Transport disabled, skipping trace capture");return}let n=e.context??{},r=l(),o=h(),s=C(),a={provider:e.provider,model:e.model,input:P(e.input),rawResponse:e.rawResponse?T(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags??r?.tags,spanType:e.spanType,name:e.name};return R(e.provider,e.model,e.durationMs,e.status),t.enqueue(a),o}catch(t){v(e.provider,t instanceof Error?t:new Error(String(t)));return}}function D(e){try{let t=g();if(!t.isEnabled()){c("Transport disabled, skipping error capture");return}let n=e.context??{},r=l(),o=C(),s={provider:e.provider,model:e.model,input:P(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:h(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:n.tags??r?.tags};R(e.provider,e.model,e.durationMs,"error"),c("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(s);}catch(t){v(e.provider,t instanceof Error?t:new Error(String(t)));}}function A(e){try{let t=g();if(!t.isEnabled()){c("Transport disabled, skipping span capture");return}let n=e.context??{},r=l(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,a=C(),i={...n.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete i._traceId,delete i._parentSpanId;let d={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:P(e.input),output:T(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:o??r?.traceId,spanId:h(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:i,tags:n.tags??r?.tags};c(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(d);}catch(t){v("unknown",t instanceof Error?t:new Error(String(t)));}}var X=1e5,Te=["api_key","apikey","password","secret","authorization"],we=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],ke=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],J={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function Q(){return I().redaction??{}}function ve(e){let t=e.toLowerCase();return ke.includes(t)?false:!!(Te.some(r=>t.includes(r))||we.some(r=>t.includes(r))||(Q().keys??[]).some(r=>t.includes(r.toLowerCase())))}function Se(e){let t=Q(),n=e;for(let r of t.patterns??[])r.lastIndex=0,n=n.replace(r,"[REDACTED]");return t.emails&&(n=n.replace(J.emails,"[EMAIL]")),t.phones&&(n=n.replace(J.phones,"[PHONE]")),n}function P(e){return T(e,0)}function T(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let n=Se(e);return n.length>X&&(n=n.slice(0,X)+"...[truncated]"),n}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>T(n,t+1));if(typeof e=="object"){let n={};for(let[r,o]of Object.entries(e))ve(r)?n[r]="[REDACTED]":n[r]=T(o,t+1);return n}return String(e)}var $=Symbol.for("@lelemondev/sdk:traceStorage");function Ce(){let e=globalThis;return e[$]||(e[$]=new AsyncLocalStorage),e[$]}var ee=Ce();function h(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function l(){return ee.getStore()}function xe(e){let t=l();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function Ee(e){let t=l();t&&t.pendingToolCalls.delete(e);}async function Re(e,t){let n=typeof e=="string"?{name:e}:e,r=l(),o=r?.traceId??h(),s=h(),a={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,outputKey:n.outputKey,outputTransform:n.outputTransform,sessionId:n.sessionId,userId:n.userId,style:n.style,pendingToolCalls:new Map};return ee.run(a,async()=>{let i,d;try{return i=await t(),i}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{Me(a,d?void 0:i,d);}})}var _e=["text","content","message","output","response","result","answer"];function Oe(e,t,n){if(n)try{return n(e)}catch{return e}if(t===false)return e;if(typeof t=="string"&&e&&typeof e=="object"){let o=e;return t in o?o[t]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let o of _e)if(o in r&&typeof r[o]=="string")return r[o];return e}function Me(e,t,n){let r=g();if(!r.isEnabled()){c("Transport disabled, skipping root span");return}let o=Date.now()-e.startTime,s=n?null:Oe(t,e.outputKey,e.outputTransform),a={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:s,inputTokens:0,outputTokens:0,durationMs:o,status:n?"error":"success",errorMessage:n?.message,streaming:false,sessionId:e.sessionId,userId:e.userId,metadata:{...e.metadata,...e.style?{_style:e.style}:{}},tags:e.tags};c(`Sending root span: ${e.name}`,{durationMs:o,hasError:!!n}),r.enqueue(a);}function qe(e){let t=l();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=xe(e.toolCallId);A({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:t.traceId,_parentSpanId:n,...e.style?{_style:e.style}:{}}}),e.toolCallId&&Ee(e.toolCallId);}var De="openrouter.ai",x="openrouter";function te(e){if(!e||typeof e!="object")return false;let t=e;return t.chat?.completions?.create?(t.baseURL||"").includes(De):false}function ne(e,t){let n=e;return new Proxy(n,{get(r,o,s){let a=Reflect.get(r,o,s);return o==="chat"&&a&&typeof a=="object"?Ae(a,t):a}})}function Ae(e,t){return e&&new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="completions"&&s&&typeof s=="object"?Pe(s,t):s}})}function Pe(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="create"&&typeof s=="function"?$e(s.bind(n),t):s}})}function $e(e,t){return async function(...r){let o=Date.now(),s=r[0]||{},a=s.stream===true;try{let i=await e(...r);if(a&&je(i))return Le(i,s,o,t);let d=Date.now()-o,u=i;return q({provider:x,model:s.model||u.model||"unknown",input:s.messages,rawResponse:i,durationMs:d,status:"success",streaming:!1,context:t}),i}catch(i){let d=Date.now()-o;throw D({provider:x,model:s.model||"unknown",input:s.messages,error:i instanceof Error?i:new Error(String(i)),durationMs:d,streaming:a,context:t}),i}}}function je(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Le(e,t,n,r){let o={choices:[{message:{content:"",role:"assistant"},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},s=null,a,i=false;try{for await(let d of e){let u=d;!o.id&&u.id&&(o.id=u.id);let b=u.choices?.[0]?.delta?.content;b&&(i||(i=!0,a=Date.now()-n),o.choices[0].message.content+=b);let w=u.choices?.[0]?.finish_reason;w&&(o.choices[0].finish_reason=w),u.usage&&(o.usage=u.usage),yield d;}}catch(d){throw s=d instanceof Error?d:new Error(String(d)),d}finally{let d=Date.now()-n;s?D({provider:x,model:t.model||"unknown",input:t.messages,error:s,durationMs:d,streaming:true,context:r}):q({provider:x,model:t.model||"unknown",input:t.messages,rawResponse:o,durationMs:d,status:"success",streaming:true,firstTokenMs:a,context:r});}}function ct(e,t){return I().disabled?(c("Tracing disabled, returning unwrapped client"),e):te(e)?(N("openrouter"),ne(e,t)):(k("Client is not configured for OpenRouter. Ensure baseURL is set to openrouter.ai."),e)}
|
|
3
|
+
export{A as captureSpan,he as flush,l as getTraceContext,ge as init,ye as isEnabled,ct as observe,qe as span,Re as trace};//# sourceMappingURL=openrouter.mjs.map
|
|
4
|
+
//# sourceMappingURL=openrouter.mjs.map
|