1
- import { existsSync , readFileSync } from 'node:fs' ;
2
- import { dirname , join } from 'node:path' ;
1
+ import type * as NodeFs from 'node:fs' ;
2
+ import type * as NodePath from 'node:path' ;
3
3
import type { IntegrationFn } from '@sentry/core' ;
4
4
import { isCjs } from '../utils/commonjs' ;
5
5
@@ -11,13 +11,27 @@ const INTEGRATION_NAME = 'Modules';
11
11
12
12
declare const __SENTRY_SERVER_MODULES__ : Record < string , string > ;
13
13
14
+ // Node utils are not available in the worker runtime, so we need to import them dynamically
15
+ // So this may or may not be available at runtime
16
+ let nodeUtils :
17
+ | undefined
18
+ | {
19
+ dirname : typeof NodePath . dirname ;
20
+ join : typeof NodePath . join ;
21
+ existsSync : typeof NodeFs . existsSync ;
22
+ readFileSync : typeof NodeFs . readFileSync ;
23
+ } ;
24
+
14
25
/**
15
26
* `__SENTRY_SERVER_MODULES__` can be replaced at build time with the modules loaded by the server.
16
27
* Right now, we leverage this in Next.js to circumvent the problem that we do not get access to these things at runtime.
17
28
*/
18
29
const SERVER_MODULES = typeof __SENTRY_SERVER_MODULES__ === 'undefined' ? { } : __SENTRY_SERVER_MODULES__ ;
19
30
20
31
const _modulesIntegration = ( ( ) => {
32
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
33
+ getNodeUtils ( ) ;
34
+
21
35
return {
22
36
name : INTEGRATION_NAME ,
23
37
processEvent ( event ) {
@@ -58,6 +72,22 @@ function collectModules(): ModuleInfo {
58
72
} ;
59
73
}
60
74
75
+ async function getNodeUtils ( ) : Promise < void > {
76
+ try {
77
+ const { existsSync, readFileSync } = await import ( 'node:fs' ) ;
78
+ // eslint-disable-next-line @typescript-eslint/unbound-method
79
+ const { dirname, join } = await import ( 'node:path' ) ;
80
+
81
+ nodeUtils = {
82
+ dirname,
83
+ join,
84
+ existsSync,
85
+ readFileSync,
86
+ } ;
87
+ } catch {
88
+ // no-empty
89
+ }
90
+ }
61
91
/** Extract information about package.json modules from require.cache */
62
92
function collectRequireModules ( ) : ModuleInfo {
63
93
const mainPaths = require . main ?. paths || [ ] ;
@@ -68,6 +98,12 @@ function collectRequireModules(): ModuleInfo {
68
98
const infos : ModuleInfo = { } ;
69
99
const seen = new Set < string > ( ) ;
70
100
101
+ if ( ! nodeUtils ) {
102
+ return infos ;
103
+ }
104
+
105
+ const { dirname, join, existsSync, readFileSync } = nodeUtils ;
106
+
71
107
paths . forEach ( path => {
72
108
let dir = path ;
73
109
@@ -121,6 +157,12 @@ interface PackageJson {
121
157
}
122
158
123
159
function getPackageJson ( ) : PackageJson {
160
+ if ( ! nodeUtils ) {
161
+ return { } ;
162
+ }
163
+
164
+ const { join, readFileSync } = nodeUtils ;
165
+
124
166
try {
125
167
const filePath = join ( process . cwd ( ) , 'package.json' ) ;
126
168
const packageJson = JSON . parse ( readFileSync ( filePath , 'utf8' ) ) as PackageJson ;
0 commit comments