14
14
* limitations under the License.
15
15
*/
16
16
17
- import URL , { fileURLToPath } from 'url' ;
17
+ import { URL , fileURLToPath , pathToFileURL } from 'url' ;
18
+ import path from 'path' ;
18
19
import fs from 'fs' ;
19
20
import VM from 'vm' ;
20
21
import threads from 'worker_threads' ;
@@ -73,7 +74,7 @@ function Event(type, target) {
73
74
// thread boundary, but behaves differently in each context.
74
75
export default threads . isMainThread ? mainThread ( ) : workerThread ( ) ;
75
76
76
- const baseUrl = URL . pathToFileURL ( process . cwd ( ) + '/' ) ;
77
+ const baseUrl = pathToFileURL ( process . cwd ( ) + '/' ) ;
77
78
78
79
function mainThread ( ) {
79
80
@@ -99,7 +100,7 @@ function mainThread() {
99
100
mod = url ;
100
101
}
101
102
else {
102
- mod = URL . fileURLToPath ( new URL . URL ( url , baseUrl ) ) ;
103
+ mod = fileURLToPath ( new URL ( url , baseUrl ) ) ;
103
104
}
104
105
const worker = new threads . Worker (
105
106
fileURLToPath ( import . meta. url ) ,
@@ -165,6 +166,22 @@ function workerThread() {
165
166
close ( ) {
166
167
process . exit ( ) ;
167
168
}
169
+ importScripts ( ) {
170
+ for ( let i = 0 ; i < arguments . length ; i ++ ) {
171
+ const url = arguments [ i ] ;
172
+ let code ;
173
+ if ( / ^ d a t a : / . test ( url ) ) {
174
+ code = parseDataUrl ( url ) . data ;
175
+ }
176
+ else {
177
+ code = fs . readFileSync (
178
+ new URL ( path . posix . normalize ( url ) , pathToFileURL ( mod ) ) ,
179
+ 'utf-8'
180
+ ) ;
181
+ }
182
+ VM . runInThisContext ( code , { filename : url } ) ;
183
+ }
184
+ }
168
185
}
169
186
let proto = Object . getPrototypeOf ( global ) ;
170
187
delete proto . constructor ;
@@ -177,7 +194,7 @@ function workerThread() {
177
194
178
195
const isDataUrl = / ^ d a t a : / . test ( mod ) ;
179
196
if ( type === 'module' ) {
180
- import ( isDataUrl ? mod : URL . pathToFileURL ( mod ) )
197
+ import ( isDataUrl ? mod : pathToFileURL ( mod ) )
181
198
. catch ( err => {
182
199
if ( isDataUrl && err . message === 'Not supported' ) {
183
200
console . warn ( 'Worker(): Importing data: URLs requires Node 12.10+. Falling back to classic worker.' ) ;
@@ -193,7 +210,7 @@ function workerThread() {
193
210
evaluateDataUrl ( mod , name ) ;
194
211
}
195
212
else {
196
- importScripts ( mod ) ;
213
+ global . importScripts ( mod ) ;
197
214
}
198
215
}
199
216
catch ( err ) {
@@ -222,17 +239,3 @@ function parseDataUrl(url) {
222
239
}
223
240
return { type, data } ;
224
241
}
225
-
226
- function importScripts ( ) {
227
- for ( let i = 0 ; i < arguments . length ; i ++ ) {
228
- const url = arguments [ i ] ;
229
- let code ;
230
- if ( / ^ d a t a : / . test ( url ) ) {
231
- code = parseDataUrl ( url ) . data ;
232
- }
233
- else {
234
- code = fs . readFileSync ( url , 'utf-8' ) ;
235
- }
236
- VM . runInThisContext ( code , { filename : url } ) ;
237
- }
238
- }
0 commit comments