1- import type { Client , IntegrationFn } from '@sentry/core' ;
1+ import type { IntegrationFn } from '@sentry/core' ;
22import { addVercelAiProcessors , defineIntegration } from '@sentry/core' ;
3- import { generateInstrumentOnce , type modulesIntegration } from '@sentry/node-core' ;
3+ import { generateInstrumentOnce } from '@sentry/node-core' ;
44import { INTEGRATION_NAME } from './constants' ;
55import { SentryVercelAiInstrumentation } from './instrumentation' ;
66import type { VercelAiOptions } from './types' ;
77
88export const instrumentVercelAi = generateInstrumentOnce ( INTEGRATION_NAME , ( ) => new SentryVercelAiInstrumentation ( { } ) ) ;
99
1010/**
11- * Determines if the integration should be forced based on environment and package availability.
12- * Returns true if the 'ai' package is available.
11+ * Determines if the 'ai' package is installed and available.
12+ *
13+ * Uses require.resolve() to check for package availability without loading it.
14+ * This approach avoids race conditions that can occur with filesystem-based
15+ * detection during initialization in serverless environments (Lambda/Vercel).
16+ *
17+ * @returns true if the 'ai' package can be resolved, false otherwise
1318 */
14- function shouldForceIntegration ( client : Client ) : boolean {
15- const modules = client . getIntegrationByName < ReturnType < typeof modulesIntegration > > ( 'Modules' ) ;
16- return ! ! modules ?. getModules ?.( ) ?. ai ;
19+ function shouldForceIntegration ( ) : boolean {
20+ try {
21+ require . resolve ( 'ai' ) ;
22+ return true ;
23+ } catch {
24+ return false ;
25+ }
1726}
1827
1928const _vercelAIIntegration = ( ( options : VercelAiOptions = { } ) => {
@@ -26,13 +35,14 @@ const _vercelAIIntegration = ((options: VercelAiOptions = {}) => {
2635 instrumentation = instrumentVercelAi ( ) ;
2736 } ,
2837 afterAllSetup ( client ) {
29- // Auto-detect if we should force the integration when running with 'ai' package available
30- // Note that this can only be detected if the 'Modules' integration is available, and running in CJS mode
31- const shouldForce = options . force ?? shouldForceIntegration ( client ) ;
38+ // Auto-detect if we should force the integration when the 'ai' package is available
39+ // Uses require.resolve() for reliable detection in all environments
40+ const shouldForce = options . force ?? shouldForceIntegration ( ) ;
3241
3342 if ( shouldForce ) {
3443 addVercelAiProcessors ( client ) ;
3544 } else {
45+ // Lazy registration - only registers when 'ai' package is actually imported
3646 instrumentation ?. callWhenPatched ( ( ) => addVercelAiProcessors ( client ) ) ;
3747 }
3848 } ,
0 commit comments