@visibe.ai/node 0.1.16 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -1,4 +1,37 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.Visibe = void 0;
4
37
  exports.detectFrameworks = detectFrameworks;
@@ -10,30 +43,35 @@ const client_1 = require("./client");
10
43
  // ---------------------------------------------------------------------------
11
44
  let _globalClient = null;
12
45
  let _shutdownRegistered = false;
13
- // Saved original constructors so shutdown() can restore them.
14
- // Each is typed as `any` because we need to reassign imported class bindings.
46
+ // Saved originals so shutdown() can restore them.
15
47
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
16
48
  let _originalOpenAI = null;
17
49
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
- let _originalBedrockClient = null;
19
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
20
- let _originalCompiledStateGraph = null;
21
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
50
  let _originalAnthropic = null;
51
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
52
+ let _originalBedrockClient = null;
53
+ // Prototype-restore functions returned by patch helpers.
54
+ let _lgRestore = null;
55
+ let _lcRestore = null;
23
56
  let _vercelAIRestore = null;
57
+ let _autoPatchedFrameworks = [];
58
+ const ALL_FRAMEWORKS = ['openai', 'anthropic', 'bedrock', 'langgraph', 'langchain', 'vercel_ai'];
24
59
  // ---------------------------------------------------------------------------
25
- // detectFrameworks()
60
+ // detectFrameworks() — synchronous, CJS-only legacy helper
61
+ // Auto-patching now uses dynamic import() and works in both CJS and ESM.
26
62
  // ---------------------------------------------------------------------------
27
- function tryRequire(pkg) {
28
- try {
29
- require(pkg);
30
- return true;
31
- }
32
- catch {
33
- return false;
34
- }
35
- }
36
63
  function detectFrameworks() {
64
+ const tryRequire = (pkg) => {
65
+ try {
66
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
67
+ if (typeof require !== 'undefined') {
68
+ require(pkg);
69
+ return true;
70
+ }
71
+ }
72
+ catch { /* not installed */ }
73
+ return false;
74
+ };
37
75
  return {
38
76
  openai: tryRequire('openai'),
39
77
  langchain: tryRequire('@langchain/core'),
@@ -41,20 +79,32 @@ function detectFrameworks() {
41
79
  bedrock: tryRequire('@aws-sdk/client-bedrock-runtime'),
42
80
  vercel_ai: tryRequire('ai'),
43
81
  anthropic: tryRequire('@anthropic-ai/sdk'),
44
- // crewai and autogen are Python-only — no Node.js equivalent
45
82
  };
46
83
  }
47
84
  // ---------------------------------------------------------------------------
48
- // patchFramework() — auto-instruments a framework at the constructor level
85
+ // patchFramework() — async, uses dynamic import() for CJS + ESM compat.
86
+ //
87
+ // Key design notes:
88
+ // - dynamic import() in CJS builds: TypeScript compiles to require()-based
89
+ // Promise, so we get the same mutable module object as require().
90
+ // - dynamic import() in ESM builds: gives the live ESM namespace (same
91
+ // instance as the user's own `import`).
92
+ // - Prototype patching (langgraph, langchain) works in both envs — prototypes
93
+ // are shared mutable objects regardless of CJS/ESM.
94
+ // - Module-export patching (openai, anthropic, bedrock) only works in CJS
95
+ // because ESM namespace objects are sealed. We try and silently skip in ESM.
49
96
  // ---------------------------------------------------------------------------
50
- function patchFramework(framework, client) {
97
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
98
+ const _setProp = (obj, key, val) => Object.defineProperty(obj, key, { value: val, configurable: true, writable: true, enumerable: true });
99
+ async function patchFramework(framework, client) {
51
100
  try {
52
101
  switch (framework) {
53
102
  case 'openai': {
54
- const openaiModule = require('openai');
55
- _originalOpenAI = openaiModule.OpenAI;
56
- // Named 'OpenAI' so client.constructor.name === 'OpenAI' after construction.
57
- // applyIntegration() in client.ts uses constructor.name to detect the client type.
103
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
104
+ const openaiModule = await Promise.resolve().then(() => __importStar(require('openai')));
105
+ _originalOpenAI = openaiModule.OpenAI ?? openaiModule.default;
106
+ if (!_originalOpenAI)
107
+ return;
58
108
  const PatchedOpenAI = class OpenAI extends _originalOpenAI {
59
109
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
60
110
  constructor(...args) {
@@ -65,19 +115,24 @@ function patchFramework(framework, client) {
65
115
  catch { /* never crash new OpenAI() */ }
66
116
  }
67
117
  };
68
- // Use defineProperty because openai exports OpenAI/default as getter-only properties
69
- // (no setter). Direct assignment silently fails in that case.
70
- const setProp = (obj, key, val) => Object.defineProperty(obj, key, { value: val, configurable: true, writable: true, enumerable: true });
71
- setProp(openaiModule, 'OpenAI', PatchedOpenAI);
72
- // Also patch .default so that `import OpenAI from 'openai'` (esModuleInterop)
73
- // picks up the instrumented class — TypeScript compiles default imports to .default.
74
- setProp(openaiModule, 'default', PatchedOpenAI);
118
+ // In ESM, the namespace object is sealed defineProperty throws TypeError.
119
+ // We catch that and skip (user must call client.instrument() explicitly).
120
+ try {
121
+ _setProp(openaiModule, 'OpenAI', PatchedOpenAI);
122
+ _setProp(openaiModule, 'default', PatchedOpenAI);
123
+ }
124
+ catch {
125
+ _originalOpenAI = null;
126
+ return;
127
+ }
75
128
  break;
76
129
  }
77
130
  case 'anthropic': {
78
- const anthropicModule = require('@anthropic-ai/sdk');
79
- _originalAnthropic = anthropicModule.Anthropic;
80
- // Named 'Anthropic' so constructor.name check in applyIntegration() matches.
131
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
132
+ const anthropicModule = await Promise.resolve().then(() => __importStar(require('@anthropic-ai/sdk')));
133
+ _originalAnthropic = anthropicModule.Anthropic ?? anthropicModule.default;
134
+ if (!_originalAnthropic)
135
+ return;
81
136
  const PatchedAnthropic = class Anthropic extends _originalAnthropic {
82
137
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
138
  constructor(...args) {
@@ -88,17 +143,23 @@ function patchFramework(framework, client) {
88
143
  catch { /* never crash new Anthropic() */ }
89
144
  }
90
145
  };
91
- // Same getter-only issue as openai — use defineProperty.
92
- const setAnthropicProp = (obj, key, val) => Object.defineProperty(obj, key, { value: val, configurable: true, writable: true, enumerable: true });
93
- setAnthropicProp(anthropicModule, 'Anthropic', PatchedAnthropic);
94
- // Also patch .default for esModuleInterop default import support.
95
- setAnthropicProp(anthropicModule, 'default', PatchedAnthropic);
146
+ try {
147
+ _setProp(anthropicModule, 'Anthropic', PatchedAnthropic);
148
+ _setProp(anthropicModule, 'default', PatchedAnthropic);
149
+ }
150
+ catch {
151
+ _originalAnthropic = null;
152
+ return;
153
+ }
96
154
  break;
97
155
  }
98
156
  case 'bedrock': {
99
- const bedrockModule = require('@aws-sdk/client-bedrock-runtime');
157
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
158
+ const bedrockModule = await Promise.resolve().then(() => __importStar(require('@aws-sdk/client-bedrock-runtime')));
100
159
  _originalBedrockClient = bedrockModule.BedrockRuntimeClient;
101
- bedrockModule.BedrockRuntimeClient = class BedrockRuntimeClient extends _originalBedrockClient {
160
+ if (!_originalBedrockClient)
161
+ return;
162
+ const PatchedBedrock = class BedrockRuntimeClient extends _originalBedrockClient {
102
163
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
103
164
  constructor(...args) {
104
165
  super(...args);
@@ -108,39 +169,61 @@ function patchFramework(framework, client) {
108
169
  catch { /* never crash new BedrockRuntimeClient() */ }
109
170
  }
110
171
  };
172
+ try {
173
+ bedrockModule.BedrockRuntimeClient = PatchedBedrock;
174
+ }
175
+ catch {
176
+ _originalBedrockClient = null;
177
+ return;
178
+ }
111
179
  break;
112
180
  }
113
181
  case 'langgraph': {
114
- const lgModule = require('@langchain/langgraph');
115
- _originalCompiledStateGraph = lgModule.CompiledStateGraph;
116
- // LangGraph instrumentation is applied via LangChainCallback at the class level.
117
- // The actual patching happens inside the langgraph integration module.
118
- const { patchCompiledStateGraph } = require('./integrations/langgraph');
119
- patchCompiledStateGraph(lgModule, client);
182
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
183
+ const lgModule = await Promise.resolve().then(() => __importStar(require('@langchain/langgraph')));
184
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
185
+ const { patchCompiledStateGraph } = await Promise.resolve().then(() => __importStar(require('./integrations/langgraph')));
186
+ // patchCompiledStateGraph modifies CompiledStateGraph.prototype — prototype
187
+ // patching works in ESM because prototypes are shared mutable objects.
188
+ _lgRestore = patchCompiledStateGraph(lgModule, client);
120
189
  break;
121
190
  }
122
191
  case 'langchain': {
123
- // LangChain is instrumented via RunnableSequence constructor patching.
124
- const { patchRunnableSequence } = require('./integrations/langchain');
125
- const lcModule = require('@langchain/core/runnables');
126
- patchRunnableSequence(lcModule, client);
192
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
193
+ const { patchRunnableSequence } = await Promise.resolve().then(() => __importStar(require('./integrations/langchain')));
194
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
195
+ const lcModule = await Promise.resolve().then(() => __importStar(require('@langchain/core/runnables')));
196
+ const result = patchRunnableSequence(lcModule, client);
197
+ if (typeof result === 'function')
198
+ _lcRestore = result;
127
199
  break;
128
200
  }
129
201
  case 'vercel_ai': {
130
- const { patchVercelAI } = require('./integrations/vercel-ai');
131
- const aiModule = require('ai');
202
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
203
+ const { patchVercelAI } = await Promise.resolve().then(() => __importStar(require('./integrations/vercel-ai')));
204
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
205
+ const aiModule = await Promise.resolve().then(() => __importStar(require('ai')));
132
206
  _vercelAIRestore = patchVercelAI(aiModule, client);
133
207
  break;
134
208
  }
135
209
  }
136
- // Record which frameworks were successfully patched for the startup log.
137
210
  _autoPatchedFrameworks.push(framework);
138
211
  }
139
212
  catch {
140
213
  // Package not installed or patch failed — skip silently.
141
214
  }
142
215
  }
143
- let _autoPatchedFrameworks = [];
216
+ // ---------------------------------------------------------------------------
217
+ // _autoPatch() — async; fires from init() without blocking it
218
+ // ---------------------------------------------------------------------------
219
+ async function _autoPatch(client, frameworks) {
220
+ for (const fw of frameworks) {
221
+ await patchFramework(fw, client);
222
+ }
223
+ if (_autoPatchedFrameworks.length > 0) {
224
+ console.log(`[Visibe] Auto-instrumented: ${_autoPatchedFrameworks.join(', ')}`);
225
+ }
226
+ }
144
227
  // ---------------------------------------------------------------------------
145
228
  // init()
146
229
  // ---------------------------------------------------------------------------
@@ -150,17 +233,11 @@ function init(options) {
150
233
  return _globalClient;
151
234
  }
152
235
  _globalClient = new client_1.Visibe(options ?? {});
153
- const detected = detectFrameworks();
154
- const toInstrument = options?.frameworks
155
- ?? Object.keys(detected).filter(k => detected[k]);
156
- for (const fw of toInstrument) {
157
- patchFramework(fw, _globalClient);
158
- }
159
- // Register graceful shutdown handlers.
160
- // NOTE: process.on('exit') fires synchronously — async HTTP requests cannot
161
- // complete there. SIGTERM is what Docker/Kubernetes send before killing a
162
- // container; without handling it all buffered spans are lost.
163
- // We await shutdown() so the batcher's 300 ms window completes before exit.
236
+ // Fire async patching — works in both CJS and ESM via dynamic import().
237
+ // Patching typically completes within microseconds (cached modules) so there
238
+ // is no practical race condition for normal usage patterns.
239
+ const frameworksToTry = options?.frameworks ?? ALL_FRAMEWORKS;
240
+ _autoPatch(_globalClient, frameworksToTry).catch(() => { });
164
241
  if (!_shutdownRegistered) {
165
242
  const graceful = async () => { await shutdown(); process.exit(0); };
166
243
  process.on('SIGTERM', graceful);
@@ -168,9 +245,6 @@ function init(options) {
168
245
  process.on('beforeExit', () => { shutdown().catch(() => { }); });
169
246
  _shutdownRegistered = true;
170
247
  }
171
- if (_autoPatchedFrameworks.length > 0) {
172
- console.log(`[Visibe] Auto-instrumented: ${_autoPatchedFrameworks.join(', ')}`);
173
- }
174
248
  return _globalClient;
175
249
  }
176
250
  // ---------------------------------------------------------------------------
@@ -179,53 +253,65 @@ function init(options) {
179
253
  async function shutdown() {
180
254
  if (_globalClient === null)
181
255
  return;
182
- // Capture the client reference and clear global state immediately so that
183
- // re-init() calls work without needing to await this function.
184
256
  const client = _globalClient;
185
257
  _globalClient = null;
186
258
  _autoPatchedFrameworks = [];
187
- // Restore patched constructors so the SDK leaves no trace after shutdown.
188
- try {
189
- if (_originalOpenAI) {
190
- const m = require('openai');
259
+ // Restore patched module exports (works in CJS; silently no-ops in ESM).
260
+ if (_originalOpenAI) {
261
+ try {
262
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
263
+ const m = await Promise.resolve().then(() => __importStar(require('openai')));
191
264
  Object.defineProperty(m, 'OpenAI', { value: _originalOpenAI, configurable: true, writable: true, enumerable: true });
192
265
  Object.defineProperty(m, 'default', { value: _originalOpenAI, configurable: true, writable: true, enumerable: true });
193
- _originalOpenAI = null;
194
266
  }
267
+ catch { /* ignore */ }
268
+ _originalOpenAI = null;
195
269
  }
196
- catch { /* package may have been unloaded */ }
197
- try {
198
- if (_originalAnthropic) {
199
- const m = require('@anthropic-ai/sdk');
270
+ if (_originalAnthropic) {
271
+ try {
272
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
273
+ const m = await Promise.resolve().then(() => __importStar(require('@anthropic-ai/sdk')));
200
274
  Object.defineProperty(m, 'Anthropic', { value: _originalAnthropic, configurable: true, writable: true, enumerable: true });
201
275
  Object.defineProperty(m, 'default', { value: _originalAnthropic, configurable: true, writable: true, enumerable: true });
202
- _originalAnthropic = null;
203
276
  }
277
+ catch { /* ignore */ }
278
+ _originalAnthropic = null;
204
279
  }
205
- catch { /* package may have been unloaded */ }
206
- try {
207
- if (_originalBedrockClient) {
208
- require('@aws-sdk/client-bedrock-runtime').BedrockRuntimeClient = _originalBedrockClient;
209
- _originalBedrockClient = null;
280
+ if (_originalBedrockClient) {
281
+ try {
282
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
283
+ const m = await Promise.resolve().then(() => __importStar(require('@aws-sdk/client-bedrock-runtime')));
284
+ m.BedrockRuntimeClient = _originalBedrockClient;
210
285
  }
286
+ catch { /* ignore */ }
287
+ _originalBedrockClient = null;
211
288
  }
212
- catch { /* package may have been unloaded */ }
213
- try {
214
- if (_originalCompiledStateGraph) {
215
- require('@langchain/langgraph').CompiledStateGraph = _originalCompiledStateGraph;
216
- _originalCompiledStateGraph = null;
289
+ // Restore prototype patches via stored cleanup functions.
290
+ if (_lgRestore) {
291
+ try {
292
+ _lgRestore();
217
293
  }
294
+ catch { /* ignore */ }
295
+ ;
296
+ _lgRestore = null;
218
297
  }
219
- catch { /* package may have been unloaded */ }
220
- try {
221
- if (_vercelAIRestore) {
298
+ if (_lcRestore) {
299
+ try {
300
+ _lcRestore();
301
+ }
302
+ catch { /* ignore */ }
303
+ ;
304
+ _lcRestore = null;
305
+ }
306
+ if (_vercelAIRestore) {
307
+ try {
222
308
  _vercelAIRestore();
223
- _vercelAIRestore = null;
224
309
  }
310
+ catch { /* ignore */ }
311
+ ;
312
+ _vercelAIRestore = null;
225
313
  }
226
- catch { /* package may have been unloaded */ }
227
- // Flush buffered spans and wait up to 300 ms for in-flight HTTP requests to
228
- // complete. This prevents spans from being lost on SIGTERM.
314
+ // Flush buffered spans and wait up to 300 ms for in-flight HTTP requests.
229
315
  await client.batcher.shutdown();
230
316
  }
231
317
  // ---------------------------------------------------------------------------
package/dist/esm/index.js CHANGED
@@ -4,30 +4,35 @@ import { Visibe } from './client.js';
4
4
  // ---------------------------------------------------------------------------
5
5
  let _globalClient = null;
6
6
  let _shutdownRegistered = false;
7
- // Saved original constructors so shutdown() can restore them.
8
- // Each is typed as `any` because we need to reassign imported class bindings.
7
+ // Saved originals so shutdown() can restore them.
9
8
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
9
  let _originalOpenAI = null;
11
10
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
12
- let _originalBedrockClient = null;
13
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
- let _originalCompiledStateGraph = null;
15
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
16
11
  let _originalAnthropic = null;
12
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
13
+ let _originalBedrockClient = null;
14
+ // Prototype-restore functions returned by patch helpers.
15
+ let _lgRestore = null;
16
+ let _lcRestore = null;
17
17
  let _vercelAIRestore = null;
18
+ let _autoPatchedFrameworks = [];
19
+ const ALL_FRAMEWORKS = ['openai', 'anthropic', 'bedrock', 'langgraph', 'langchain', 'vercel_ai'];
18
20
  // ---------------------------------------------------------------------------
19
- // detectFrameworks()
21
+ // detectFrameworks() — synchronous, CJS-only legacy helper
22
+ // Auto-patching now uses dynamic import() and works in both CJS and ESM.
20
23
  // ---------------------------------------------------------------------------
21
- function tryRequire(pkg) {
22
- try {
23
- require(pkg);
24
- return true;
25
- }
26
- catch {
27
- return false;
28
- }
29
- }
30
24
  export function detectFrameworks() {
25
+ const tryRequire = (pkg) => {
26
+ try {
27
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
28
+ if (typeof require !== 'undefined') {
29
+ require(pkg);
30
+ return true;
31
+ }
32
+ }
33
+ catch { /* not installed */ }
34
+ return false;
35
+ };
31
36
  return {
32
37
  openai: tryRequire('openai'),
33
38
  langchain: tryRequire('@langchain/core'),
@@ -35,20 +40,32 @@ export function detectFrameworks() {
35
40
  bedrock: tryRequire('@aws-sdk/client-bedrock-runtime'),
36
41
  vercel_ai: tryRequire('ai'),
37
42
  anthropic: tryRequire('@anthropic-ai/sdk'),
38
- // crewai and autogen are Python-only — no Node.js equivalent
39
43
  };
40
44
  }
41
45
  // ---------------------------------------------------------------------------
42
- // patchFramework() — auto-instruments a framework at the constructor level
46
+ // patchFramework() — async, uses dynamic import() for CJS + ESM compat.
47
+ //
48
+ // Key design notes:
49
+ // - dynamic import() in CJS builds: TypeScript compiles to require()-based
50
+ // Promise, so we get the same mutable module object as require().
51
+ // - dynamic import() in ESM builds: gives the live ESM namespace (same
52
+ // instance as the user's own `import`).
53
+ // - Prototype patching (langgraph, langchain) works in both envs — prototypes
54
+ // are shared mutable objects regardless of CJS/ESM.
55
+ // - Module-export patching (openai, anthropic, bedrock) only works in CJS
56
+ // because ESM namespace objects are sealed. We try and silently skip in ESM.
43
57
  // ---------------------------------------------------------------------------
44
- function patchFramework(framework, client) {
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ const _setProp = (obj, key, val) => Object.defineProperty(obj, key, { value: val, configurable: true, writable: true, enumerable: true });
60
+ async function patchFramework(framework, client) {
45
61
  try {
46
62
  switch (framework) {
47
63
  case 'openai': {
48
- const openaiModule = require('openai');
49
- _originalOpenAI = openaiModule.OpenAI;
50
- // Named 'OpenAI' so client.constructor.name === 'OpenAI' after construction.
51
- // applyIntegration() in client.ts uses constructor.name to detect the client type.
64
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
65
+ const openaiModule = await import('openai');
66
+ _originalOpenAI = openaiModule.OpenAI ?? openaiModule.default;
67
+ if (!_originalOpenAI)
68
+ return;
52
69
  const PatchedOpenAI = class OpenAI extends _originalOpenAI {
53
70
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
71
  constructor(...args) {
@@ -59,19 +76,24 @@ function patchFramework(framework, client) {
59
76
  catch { /* never crash new OpenAI() */ }
60
77
  }
61
78
  };
62
- // Use defineProperty because openai exports OpenAI/default as getter-only properties
63
- // (no setter). Direct assignment silently fails in that case.
64
- const setProp = (obj, key, val) => Object.defineProperty(obj, key, { value: val, configurable: true, writable: true, enumerable: true });
65
- setProp(openaiModule, 'OpenAI', PatchedOpenAI);
66
- // Also patch .default so that `import OpenAI from 'openai'` (esModuleInterop)
67
- // picks up the instrumented class — TypeScript compiles default imports to .default.
68
- setProp(openaiModule, 'default', PatchedOpenAI);
79
+ // In ESM, the namespace object is sealed defineProperty throws TypeError.
80
+ // We catch that and skip (user must call client.instrument() explicitly).
81
+ try {
82
+ _setProp(openaiModule, 'OpenAI', PatchedOpenAI);
83
+ _setProp(openaiModule, 'default', PatchedOpenAI);
84
+ }
85
+ catch {
86
+ _originalOpenAI = null;
87
+ return;
88
+ }
69
89
  break;
70
90
  }
71
91
  case 'anthropic': {
72
- const anthropicModule = require('@anthropic-ai/sdk');
73
- _originalAnthropic = anthropicModule.Anthropic;
74
- // Named 'Anthropic' so constructor.name check in applyIntegration() matches.
92
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
93
+ const anthropicModule = await import('@anthropic-ai/sdk');
94
+ _originalAnthropic = anthropicModule.Anthropic ?? anthropicModule.default;
95
+ if (!_originalAnthropic)
96
+ return;
75
97
  const PatchedAnthropic = class Anthropic extends _originalAnthropic {
76
98
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
99
  constructor(...args) {
@@ -82,17 +104,23 @@ function patchFramework(framework, client) {
82
104
  catch { /* never crash new Anthropic() */ }
83
105
  }
84
106
  };
85
- // Same getter-only issue as openai — use defineProperty.
86
- const setAnthropicProp = (obj, key, val) => Object.defineProperty(obj, key, { value: val, configurable: true, writable: true, enumerable: true });
87
- setAnthropicProp(anthropicModule, 'Anthropic', PatchedAnthropic);
88
- // Also patch .default for esModuleInterop default import support.
89
- setAnthropicProp(anthropicModule, 'default', PatchedAnthropic);
107
+ try {
108
+ _setProp(anthropicModule, 'Anthropic', PatchedAnthropic);
109
+ _setProp(anthropicModule, 'default', PatchedAnthropic);
110
+ }
111
+ catch {
112
+ _originalAnthropic = null;
113
+ return;
114
+ }
90
115
  break;
91
116
  }
92
117
  case 'bedrock': {
93
- const bedrockModule = require('@aws-sdk/client-bedrock-runtime');
118
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
119
+ const bedrockModule = await import('@aws-sdk/client-bedrock-runtime');
94
120
  _originalBedrockClient = bedrockModule.BedrockRuntimeClient;
95
- bedrockModule.BedrockRuntimeClient = class BedrockRuntimeClient extends _originalBedrockClient {
121
+ if (!_originalBedrockClient)
122
+ return;
123
+ const PatchedBedrock = class BedrockRuntimeClient extends _originalBedrockClient {
96
124
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
125
  constructor(...args) {
98
126
  super(...args);
@@ -102,39 +130,61 @@ function patchFramework(framework, client) {
102
130
  catch { /* never crash new BedrockRuntimeClient() */ }
103
131
  }
104
132
  };
133
+ try {
134
+ bedrockModule.BedrockRuntimeClient = PatchedBedrock;
135
+ }
136
+ catch {
137
+ _originalBedrockClient = null;
138
+ return;
139
+ }
105
140
  break;
106
141
  }
107
142
  case 'langgraph': {
108
- const lgModule = require('@langchain/langgraph');
109
- _originalCompiledStateGraph = lgModule.CompiledStateGraph;
110
- // LangGraph instrumentation is applied via LangChainCallback at the class level.
111
- // The actual patching happens inside the langgraph integration module.
112
- const { patchCompiledStateGraph } = require('./integrations/langgraph');
113
- patchCompiledStateGraph(lgModule, client);
143
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
144
+ const lgModule = await import('@langchain/langgraph');
145
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
146
+ const { patchCompiledStateGraph } = await import('./integrations/langgraph.js');
147
+ // patchCompiledStateGraph modifies CompiledStateGraph.prototype — prototype
148
+ // patching works in ESM because prototypes are shared mutable objects.
149
+ _lgRestore = patchCompiledStateGraph(lgModule, client);
114
150
  break;
115
151
  }
116
152
  case 'langchain': {
117
- // LangChain is instrumented via RunnableSequence constructor patching.
118
- const { patchRunnableSequence } = require('./integrations/langchain');
119
- const lcModule = require('@langchain/core/runnables');
120
- patchRunnableSequence(lcModule, client);
153
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
154
+ const { patchRunnableSequence } = await import('./integrations/langchain.js');
155
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
156
+ const lcModule = await import('@langchain/core/runnables');
157
+ const result = patchRunnableSequence(lcModule, client);
158
+ if (typeof result === 'function')
159
+ _lcRestore = result;
121
160
  break;
122
161
  }
123
162
  case 'vercel_ai': {
124
- const { patchVercelAI } = require('./integrations/vercel-ai');
125
- const aiModule = require('ai');
163
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
164
+ const { patchVercelAI } = await import('./integrations/vercel-ai.js');
165
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
166
+ const aiModule = await import('ai');
126
167
  _vercelAIRestore = patchVercelAI(aiModule, client);
127
168
  break;
128
169
  }
129
170
  }
130
- // Record which frameworks were successfully patched for the startup log.
131
171
  _autoPatchedFrameworks.push(framework);
132
172
  }
133
173
  catch {
134
174
  // Package not installed or patch failed — skip silently.
135
175
  }
136
176
  }
137
- let _autoPatchedFrameworks = [];
177
+ // ---------------------------------------------------------------------------
178
+ // _autoPatch() — async; fires from init() without blocking it
179
+ // ---------------------------------------------------------------------------
180
+ async function _autoPatch(client, frameworks) {
181
+ for (const fw of frameworks) {
182
+ await patchFramework(fw, client);
183
+ }
184
+ if (_autoPatchedFrameworks.length > 0) {
185
+ console.log(`[Visibe] Auto-instrumented: ${_autoPatchedFrameworks.join(', ')}`);
186
+ }
187
+ }
138
188
  // ---------------------------------------------------------------------------
139
189
  // init()
140
190
  // ---------------------------------------------------------------------------
@@ -144,17 +194,11 @@ export function init(options) {
144
194
  return _globalClient;
145
195
  }
146
196
  _globalClient = new Visibe(options ?? {});
147
- const detected = detectFrameworks();
148
- const toInstrument = options?.frameworks
149
- ?? Object.keys(detected).filter(k => detected[k]);
150
- for (const fw of toInstrument) {
151
- patchFramework(fw, _globalClient);
152
- }
153
- // Register graceful shutdown handlers.
154
- // NOTE: process.on('exit') fires synchronously — async HTTP requests cannot
155
- // complete there. SIGTERM is what Docker/Kubernetes send before killing a
156
- // container; without handling it all buffered spans are lost.
157
- // We await shutdown() so the batcher's 300 ms window completes before exit.
197
+ // Fire async patching — works in both CJS and ESM via dynamic import().
198
+ // Patching typically completes within microseconds (cached modules) so there
199
+ // is no practical race condition for normal usage patterns.
200
+ const frameworksToTry = options?.frameworks ?? ALL_FRAMEWORKS;
201
+ _autoPatch(_globalClient, frameworksToTry).catch(() => { });
158
202
  if (!_shutdownRegistered) {
159
203
  const graceful = async () => { await shutdown(); process.exit(0); };
160
204
  process.on('SIGTERM', graceful);
@@ -162,9 +206,6 @@ export function init(options) {
162
206
  process.on('beforeExit', () => { shutdown().catch(() => { }); });
163
207
  _shutdownRegistered = true;
164
208
  }
165
- if (_autoPatchedFrameworks.length > 0) {
166
- console.log(`[Visibe] Auto-instrumented: ${_autoPatchedFrameworks.join(', ')}`);
167
- }
168
209
  return _globalClient;
169
210
  }
170
211
  // ---------------------------------------------------------------------------
@@ -173,53 +214,65 @@ export function init(options) {
173
214
  export async function shutdown() {
174
215
  if (_globalClient === null)
175
216
  return;
176
- // Capture the client reference and clear global state immediately so that
177
- // re-init() calls work without needing to await this function.
178
217
  const client = _globalClient;
179
218
  _globalClient = null;
180
219
  _autoPatchedFrameworks = [];
181
- // Restore patched constructors so the SDK leaves no trace after shutdown.
182
- try {
183
- if (_originalOpenAI) {
184
- const m = require('openai');
220
+ // Restore patched module exports (works in CJS; silently no-ops in ESM).
221
+ if (_originalOpenAI) {
222
+ try {
223
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
224
+ const m = await import('openai');
185
225
  Object.defineProperty(m, 'OpenAI', { value: _originalOpenAI, configurable: true, writable: true, enumerable: true });
186
226
  Object.defineProperty(m, 'default', { value: _originalOpenAI, configurable: true, writable: true, enumerable: true });
187
- _originalOpenAI = null;
188
227
  }
228
+ catch { /* ignore */ }
229
+ _originalOpenAI = null;
189
230
  }
190
- catch { /* package may have been unloaded */ }
191
- try {
192
- if (_originalAnthropic) {
193
- const m = require('@anthropic-ai/sdk');
231
+ if (_originalAnthropic) {
232
+ try {
233
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
234
+ const m = await import('@anthropic-ai/sdk');
194
235
  Object.defineProperty(m, 'Anthropic', { value: _originalAnthropic, configurable: true, writable: true, enumerable: true });
195
236
  Object.defineProperty(m, 'default', { value: _originalAnthropic, configurable: true, writable: true, enumerable: true });
196
- _originalAnthropic = null;
197
237
  }
238
+ catch { /* ignore */ }
239
+ _originalAnthropic = null;
198
240
  }
199
- catch { /* package may have been unloaded */ }
200
- try {
201
- if (_originalBedrockClient) {
202
- require('@aws-sdk/client-bedrock-runtime').BedrockRuntimeClient = _originalBedrockClient;
203
- _originalBedrockClient = null;
241
+ if (_originalBedrockClient) {
242
+ try {
243
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
244
+ const m = await import('@aws-sdk/client-bedrock-runtime');
245
+ m.BedrockRuntimeClient = _originalBedrockClient;
204
246
  }
247
+ catch { /* ignore */ }
248
+ _originalBedrockClient = null;
205
249
  }
206
- catch { /* package may have been unloaded */ }
207
- try {
208
- if (_originalCompiledStateGraph) {
209
- require('@langchain/langgraph').CompiledStateGraph = _originalCompiledStateGraph;
210
- _originalCompiledStateGraph = null;
250
+ // Restore prototype patches via stored cleanup functions.
251
+ if (_lgRestore) {
252
+ try {
253
+ _lgRestore();
211
254
  }
255
+ catch { /* ignore */ }
256
+ ;
257
+ _lgRestore = null;
212
258
  }
213
- catch { /* package may have been unloaded */ }
214
- try {
215
- if (_vercelAIRestore) {
259
+ if (_lcRestore) {
260
+ try {
261
+ _lcRestore();
262
+ }
263
+ catch { /* ignore */ }
264
+ ;
265
+ _lcRestore = null;
266
+ }
267
+ if (_vercelAIRestore) {
268
+ try {
216
269
  _vercelAIRestore();
217
- _vercelAIRestore = null;
218
270
  }
271
+ catch { /* ignore */ }
272
+ ;
273
+ _vercelAIRestore = null;
219
274
  }
220
- catch { /* package may have been unloaded */ }
221
- // Flush buffered spans and wait up to 300 ms for in-flight HTTP requests to
222
- // complete. This prevents spans from being lost on SIGTERM.
275
+ // Flush buffered spans and wait up to 300 ms for in-flight HTTP requests.
223
276
  await client.batcher.shutdown();
224
277
  }
225
278
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visibe.ai/node",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
4
4
  "description": "AI Agent Observability — Track OpenAI, LangChain, LangGraph, Bedrock, Vercel AI, Anthropic",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",