@@ -133,7 +133,26 @@ export function createScriptNode(
133
133
} ;
134
134
135
135
getFetch ( )
136
- . then ( ( f ) => handleScriptFetch ( f , urlObj ) )
136
+ . then ( async ( f ) => {
137
+ if ( attrs ?. [ 'type' ] === 'esm' || attrs ?. [ 'type' ] === 'module' ) {
138
+ return loadModule ( urlObj . href , {
139
+ fetch : f ,
140
+ vm : await importNodeModule < typeof import ( 'vm' ) > ( 'vm' ) ,
141
+ } )
142
+ . then ( async ( module ) => {
143
+ await module . evaluate ( ) ;
144
+ cb ( undefined , module . namespace ) ;
145
+ } )
146
+ . catch ( ( e ) => {
147
+ cb (
148
+ e instanceof Error
149
+ ? e
150
+ : new Error ( `Script execution error: ${ e } ` ) ,
151
+ ) ;
152
+ } ) ;
153
+ }
154
+ handleScriptFetch ( f , urlObj ) ;
155
+ } )
137
156
. catch ( ( err ) => {
138
157
cb ( err ) ;
139
158
} ) ;
@@ -166,3 +185,31 @@ export function loadScriptNode(
166
185
) ;
167
186
} ) ;
168
187
}
188
+
189
+ async function loadModule (
190
+ url : string ,
191
+ options : {
192
+ vm : any ;
193
+ fetch : any ;
194
+ } ,
195
+ ) {
196
+ const { fetch, vm } = options ;
197
+ const response = await fetch ( url ) ;
198
+ const code = await response . text ( ) ;
199
+
200
+ const module : any = new vm . SourceTextModule ( code , {
201
+ // @ts -ignore
202
+ importModuleDynamically : async ( specifier , script ) => {
203
+ const resolvedUrl = new URL ( specifier , url ) . href ;
204
+ return loadModule ( resolvedUrl , options ) ;
205
+ } ,
206
+ } ) ;
207
+
208
+ await module . link ( async ( specifier : string ) => {
209
+ const resolvedUrl = new URL ( specifier , url ) . href ;
210
+ const module = await loadModule ( resolvedUrl , options ) ;
211
+ return module ;
212
+ } ) ;
213
+
214
+ return module ;
215
+ }
0 commit comments