bare-module 6.4.0 → 7.0.0

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.
Files changed (38) hide show
  1. package/README.md +237 -270
  2. package/binding.c +623 -333
  3. package/index.d.ts +156 -63
  4. package/index.js +87 -1002
  5. package/lib/errors.js +27 -10
  6. package/lib/loader.d.ts +56 -0
  7. package/lib/loader.js +1192 -0
  8. package/lib/module/addon.js +7 -0
  9. package/lib/module/binary.js +7 -0
  10. package/lib/module/builtin.js +19 -0
  11. package/lib/module/bundle.js +47 -0
  12. package/lib/module/json.js +19 -0
  13. package/lib/module/script.js +23 -0
  14. package/lib/module/source-text.js +13 -0
  15. package/lib/module/synthetic.js +20 -0
  16. package/lib/module/text.js +7 -0
  17. package/lib/module/value.js +27 -0
  18. package/lib/module.js +392 -0
  19. package/lib/protocol.d.ts +56 -8
  20. package/lib/protocol.js +93 -26
  21. package/lib/source.js +18 -0
  22. package/lib/url.js +52 -0
  23. package/package.json +18 -8
  24. package/prebuilds/android-arm/bare-module.bare +0 -0
  25. package/prebuilds/android-arm64/bare-module.bare +0 -0
  26. package/prebuilds/android-ia32/bare-module.bare +0 -0
  27. package/prebuilds/android-x64/bare-module.bare +0 -0
  28. package/prebuilds/darwin-arm64/bare-module.bare +0 -0
  29. package/prebuilds/darwin-x64/bare-module.bare +0 -0
  30. package/prebuilds/ios-arm64/bare-module.bare +0 -0
  31. package/prebuilds/ios-arm64-simulator/bare-module.bare +0 -0
  32. package/prebuilds/ios-x64-simulator/bare-module.bare +0 -0
  33. package/prebuilds/linux-arm64/bare-module.bare +0 -0
  34. package/prebuilds/linux-x64/bare-module.bare +0 -0
  35. package/prebuilds/win32-arm64/bare-module.bare +0 -0
  36. package/prebuilds/win32-x64/bare-module.bare +0 -0
  37. package/lib/constants.d.ts +0 -19
  38. package/lib/constants.js +0 -17
package/index.js CHANGED
@@ -1,1065 +1,150 @@
1
- const path = require('bare-path')
2
- const resolve = require('bare-module-resolve')
3
- const lex = require('bare-module-lexer')
4
- const strip = require('bare-type-stripper')
5
- const { isURL, fileURLToPath, pathToFileURL } = require('bare-url')
6
- const Bundle = require('bare-bundle')
7
- const Protocol = require('./lib/protocol')
8
- const constants = require('./lib/constants')
9
- const errors = require('./lib/errors')
10
- const binding = require('./binding')
1
+ const { isURL, pathToFileURL } = require('bare-url')
2
+ const { constants } = require('bare-module-traverse')
3
+ const Module = require('./lib/module')
4
+ const ModuleProtocol = require('./lib/protocol')
5
+ const ModuleLoader = require('./lib/loader')
6
+ const ModuleSource = require('./lib/source')
11
7
 
12
- const kind = Symbol.for('bare.module.kind')
8
+ module.exports = exports = Module
13
9
 
14
- const isWindows = Bare.platform === 'win32'
10
+ exports.Protocol = ModuleProtocol
11
+ exports.Loader = ModuleLoader
15
12
 
16
- const { startsWithWindowsDriveLetter } = resolve
17
-
18
- module.exports = exports = class Module {
19
- static get [kind]() {
20
- return 1 // Compatibility version
21
- }
22
-
23
- constructor(url) {
24
- this._url = url
25
- this._state = 0
26
- this._type = 0
27
- this._defaultType = 0
28
- this._main = null
29
- this._exports = null
30
- this._imports = null
31
- this._resolutions = null
32
- this._builtins = null
33
- this._conditions = null
34
- this._protocol = null
35
- this._cache = null
36
- this._source = null
37
- this._function = null
38
- this._names = null
39
- this._promise = null
40
- this._handle = null
41
-
42
- Object.preventExtensions(this)
43
- }
44
-
45
- get [kind]() {
46
- return Module[kind]
47
- }
48
-
49
- get url() {
50
- return this._url
51
- }
52
-
53
- get type() {
54
- return this._type
55
- }
56
-
57
- get defaultType() {
58
- return this._defaultType
59
- }
60
-
61
- get main() {
62
- return this._main
63
- }
64
-
65
- get exports() {
66
- return this._exports
67
- }
68
-
69
- set exports(value) {
70
- this._exports = value
71
- }
72
-
73
- get imports() {
74
- return this._imports
75
- }
76
-
77
- get resolutions() {
78
- return this._resolutions
79
- }
80
-
81
- get builtins() {
82
- return this._builtins
83
- }
84
-
85
- get conditions() {
86
- return Array.from(this._conditions)
87
- }
88
-
89
- get protocol() {
90
- return this._protocol
91
- }
92
-
93
- get cache() {
94
- return this._cache
95
- }
96
-
97
- // For Node.js compatibility
98
- get filename() {
99
- return urlToPath(this._url)
100
- }
101
-
102
- // For Node.js compatibility
103
- get dirname() {
104
- return urlToDirname(this._url)
105
- }
106
-
107
- // For Node.js compatibility
108
- get id() {
109
- return this.filename
110
- }
111
-
112
- // For Node.js compatibility
113
- get path() {
114
- return this.dirname
115
- }
116
-
117
- _transform(isImport, isDynamicImport) {
118
- if (isDynamicImport) {
119
- this._run()
120
- } else if (isImport) {
121
- this._synthesize()
122
- } else {
123
- this._evaluate()
124
- }
125
-
126
- return this
127
- }
128
-
129
- _synthesize() {
130
- if ((this._state & constants.states.SYNTHESIZED) !== 0) return
131
-
132
- this._state |= constants.states.SYNTHESIZED
133
-
134
- if (this._type === constants.types.MODULE) return
135
-
136
- const names = new Set(['default'])
137
- const queue = [this]
138
- const seen = new Set()
139
-
140
- while (queue.length) {
141
- const module = queue.pop()
142
-
143
- if (seen.has(module)) continue
144
-
145
- seen.add(module)
146
-
147
- switch (module._type) {
148
- case constants.types.SCRIPT: {
149
- const result = lex(module._source)
150
-
151
- for (const { name } of result.exports) names.add(name)
152
-
153
- const referrer = module
154
-
155
- for (const { specifier, type } of result.imports) {
156
- if (
157
- (type & lex.constants.REEXPORT) !== 0 &&
158
- (type & lex.constants.ADDON) === 0 &&
159
- (type & lex.constants.ASSET) === 0
160
- ) {
161
- const resolved = Module.resolve(specifier, referrer._url, {
162
- isImport: true,
163
- referrer
164
- })
165
-
166
- const module = Module.load(resolved, {
167
- isImport: true,
168
- referrer
169
- })
170
-
171
- if (module._names) {
172
- for (const name of module._names) names.add(name)
173
- } else {
174
- queue.push(module)
175
- }
176
- }
177
- }
178
-
179
- break
180
- }
181
-
182
- case constants.types.MODULE:
183
- module._evaluate()
184
-
185
- for (const name of Object.keys(module._exports)) names.add(name)
186
-
187
- break
188
-
189
- case constants.types.JSON:
190
- for (const name of Object.keys(module._exports)) names.add(name)
191
- }
192
- }
193
-
194
- this._names = Array.from(names)
195
-
196
- this._handle = binding.createSyntheticModule(this._url.href, this._names, Module._handle)
197
-
198
- const id = binding.getModuleID(this._handle)
199
-
200
- Module._registry.set(id, this)
201
- }
202
-
203
- _evaluate() {
204
- if ((this._state & constants.states.EVALUATED) !== 0) return
205
-
206
- this._state |= constants.states.EVALUATED
207
-
208
- if (this._type === constants.types.SCRIPT) {
209
- const require = exports.createRequire(this._url, { module: this })
210
-
211
- this._exports = {}
212
-
213
- const fn = this._function // Bind to variable to ensure proper stack trace
214
-
215
- fn(require, this, this._exports, urlToPath(this._url), urlToDirname(this._url))
216
- } else if (this._type === constants.types.MODULE) {
217
- this._run()
218
-
219
- this._exports = binding.getModuleNamespace(this._handle)
220
- }
221
- }
222
-
223
- _run() {
224
- if ((this._state & constants.states.RUN) !== 0) return
225
-
226
- this._state |= constants.states.RUN
227
-
228
- this._synthesize()
229
-
230
- this._promise = binding.runModule(this._handle, Module._handle, Module._onrun)
231
- }
232
-
233
- [Symbol.for('bare.inspect')]() {
234
- return {
235
- __proto__: { constructor: Module },
236
-
237
- url: this.url,
238
- type: this.type,
239
- defaultType: this.defaultType,
240
- main: this.main,
241
- exports: this.exports,
242
- imports: this.imports,
243
- resolutions: this.resolutions,
244
- builtins: this.builtins,
245
- conditions: this.conditions
246
- }
247
- }
248
-
249
- static _extensions = Object.create(null)
250
-
251
- static _protocol = null
252
-
253
- static _registry = new WeakMap()
254
-
255
- static _cache =
256
- module[kind] === Module[kind] ? module.cache || Object.create(null) : Object.create(null)
257
-
258
- static _conditions = ['bare', 'node', ...Bare.Addon.host.split('-')]
259
-
260
- static _handle = binding.init(this, this._onimport, this._onevaluate, this._onmeta)
261
-
262
- static _onimport(specifier, attributes, referrerName, id, isDynamicImport) {
263
- const referrer = this._registry.get(id) || null
264
-
265
- let parentURL
266
-
267
- if (referrer !== null) {
268
- parentURL = referrer._url
269
- } else if (isDynamicImport) {
270
- parentURL = referrerName ? toURL(referrerName) : pathToFileURL('./')
271
- } else {
272
- throw errors.MODULE_NOT_FOUND(`Cannot find referrer for module '${specifier}'`, specifier)
273
- }
274
-
275
- const resolved = this.resolve(specifier, parentURL, {
276
- isImport: true,
277
- referrer,
278
- attributes
279
- })
280
-
281
- const module = this.load(resolved, {
282
- isImport: true,
283
- isDynamicImport,
284
- referrer,
285
- attributes
286
- })
287
-
288
- return isDynamicImport
289
- ? module._promise.then(() => binding.getModuleNamespace(module._handle))
290
- : module._handle
291
- }
292
-
293
- static _onevaluate(id) {
294
- const module = this._registry.get(id) || null
295
-
296
- if (module === null) {
297
- throw errors.MODULE_NOT_FOUND('Cannot find module')
298
- }
299
-
300
- module._evaluate()
301
-
302
- for (const name of module._names) {
303
- let value
304
-
305
- if (
306
- name === 'default' &&
307
- (typeof module._exports !== 'object' ||
308
- module._exports === null ||
309
- name in module._exports === false)
310
- ) {
311
- value = module._exports
312
- } else {
313
- value = module._exports[name]
314
- }
315
-
316
- binding.setModuleExport(module._handle, name, value)
317
- }
318
- }
319
-
320
- static _onmeta(id, meta) {
321
- const module = this._registry.get(id) || null
322
-
323
- if (module === null) {
324
- throw errors.MODULE_NOT_FOUND('Cannot find module')
325
- }
326
-
327
- const referrer = module
328
-
329
- meta.url = module._url.href
330
- meta.main = module._main === module
331
- meta.cache = module._cache
332
-
333
- meta.dirname = module.dirname // For Node.js compatibility
334
- meta.filename = module.filename // For Node.js compatibility
335
-
336
- meta.resolve = function resolve(specifier, parentURL = referrer._url) {
337
- return Module.resolve(specifier, toURL(parentURL, referrer._url), {
338
- referrer
339
- }).href
340
- }
341
-
342
- meta.addon = function addon(specifier = '.', parentURL = referrer._url) {
343
- const resolved = Bare.Addon.resolve(specifier, toURL(parentURL, referrer._url), { referrer })
344
-
345
- const addon = Bare.Addon.load(resolved, { referrer })
346
-
347
- return addon._exports
348
- }
349
-
350
- meta.addon.resolve = function resolve(specifier = '.', parentURL = referrer._url) {
351
- return Bare.Addon.resolve(specifier, toURL(parentURL, referrer._url), {
352
- referrer
353
- }).href
354
- }
355
-
356
- meta.addon.host = Bare.Addon.host
357
-
358
- meta.asset = function asset(specifier, parentURL = referrer._url) {
359
- return Module.asset(specifier, toURL(parentURL, referrer._url), {
360
- referrer
361
- }).href
362
- }
363
- }
364
-
365
- static _onrun(reason, promise, err = reason) {
366
- if (err) {
367
- promise.catch(() => {}) // Don't leak the rejection
368
-
369
- throw err
370
- } else {
371
- promise.catch((err) =>
372
- queueMicrotask(() => {
373
- throw err
374
- })
375
- )
376
- }
377
- }
378
-
379
- static get protocol() {
380
- return this._protocol
381
- }
382
-
383
- static get cache() {
384
- return this._cache
385
- }
386
-
387
- static load(url, source = null, opts = {}) {
388
- if (
389
- !ArrayBuffer.isView(source) &&
390
- !Bundle.isBundle(source) &&
391
- typeof source !== 'string' &&
392
- source !== null
393
- ) {
394
- opts = source
395
- source = null
396
- }
397
-
398
- const referrer = opts.referrer || null
399
- const inherited = inherit(referrer)
400
-
401
- const {
402
- isImport = false,
403
- isDynamicImport = false,
404
- attributes,
405
- type = typeForAttributes(attributes),
406
- defaultType = inherited.defaultType,
407
- cache = inherited.cache,
408
- main = inherited.main,
409
- protocol = inherited.protocol,
410
- imports = inherited.imports,
411
- resolutions = inherited.resolutions,
412
- builtins = inherited.builtins,
413
- conditions = inherited.conditions
414
- } = opts
415
-
416
- let module = cache[url.href] || null
417
-
418
- if (module !== null) {
419
- if (type !== 0 && type !== module._type) {
420
- throw errors.TYPE_INCOMPATIBLE(
421
- `Module '${module.url.href}' is not of type '${nameOfType(type)}'`
422
- )
423
- }
424
-
425
- return module._transform(isImport, isDynamicImport)
426
- }
427
-
428
- module = cache[url.href] = new Module(url)
429
-
430
- try {
431
- switch (url.protocol) {
432
- case 'builtin:':
433
- module._exports = builtins[url.pathname]
434
- break
435
-
436
- default: {
437
- module._defaultType = defaultType
438
- module._cache = cache
439
- module._main = main || module
440
- module._protocol = protocol
441
- module._imports = imports
442
- module._resolutions = resolutions
443
- module._builtins = builtins
444
- module._conditions = conditions
445
-
446
- if (
447
- typeof attributes === 'object' &&
448
- attributes !== null &&
449
- typeof attributes.imports === 'string'
450
- ) {
451
- const resolved = Module.resolve(attributes.imports, referrer._url, {
452
- referrer: module
453
- })
454
-
455
- const imports = Module.load(resolved, {
456
- referrer: module,
457
- type: constants.types.JSON
458
- })
459
-
460
- module._imports = mixinImports(module._imports, imports._exports, resolved)
461
- }
462
-
463
- let extension = canonicalExtensionForType(type) || path.extname(url.pathname)
464
-
465
- if (extension in Module._extensions === false) {
466
- if (defaultType) {
467
- extension = canonicalExtensionForType(defaultType) || '.js'
468
- } else {
469
- extension = '.js'
470
- }
471
- }
472
-
473
- Module._extensions[extension](module, source, referrer)
474
- }
475
- }
476
-
477
- return module._transform(isImport, isDynamicImport)
478
- } catch (err) {
479
- delete cache[url.href]
480
-
481
- throw err
482
- }
483
- }
484
-
485
- static resolve(specifier, parentURL, opts = {}) {
486
- if (typeof specifier !== 'string') {
487
- throw new TypeError(
488
- `Specifier must be a string. Received type ${typeof specifier} (${specifier})`
489
- )
490
- }
491
-
492
- const referrer = opts.referrer || null
493
- const inherited = inherit(referrer)
494
-
495
- const {
496
- isImport = false,
497
- attributes,
498
- type = typeForAttributes(attributes),
499
- extensions = extensionsForType(type),
500
- cache = referrer ? referrer._cache : Object.create(null),
501
- protocol = inherited.protocol,
502
- imports = inherited.imports,
503
- resolutions = inherited.resolutions,
504
- builtins = inherited.builtins,
505
- conditions = inherited.conditions
506
- } = opts
507
-
508
- const resolved = protocol.preresolve(specifier, parentURL)
509
-
510
- const [resolution] = protocol.resolve(resolved, parentURL, imports)
511
-
512
- if (resolution) return protocol.postresolve(resolution)
513
-
514
- const candidates = []
515
-
516
- for (const resolution of resolve(
517
- resolved,
518
- parentURL,
519
- {
520
- conditions: isImport ? ['import', ...conditions] : ['require', ...conditions],
521
- imports,
522
- resolutions,
523
- extensions,
524
- builtins: builtins ? Object.keys(builtins) : [],
525
- engines: Bare.versions
526
- },
527
- readPackageFor(protocol, cache)
528
- )) {
529
- candidates.push(resolution)
530
-
531
- const condition = isImport ? 'import' : 'require'
532
-
533
- switch (resolution.protocol) {
534
- case 'builtin:':
535
- cacheResolution(resolutions, parentURL, resolved, condition, resolution)
536
-
537
- return resolution
538
- default:
539
- if (protocol.exists(resolution, type)) {
540
- const postresolved = protocol.postresolve(resolution)
541
-
542
- cacheResolution(resolutions, parentURL, resolved, condition, postresolved)
13
+ exports.constants = constants
543
14
 
544
- return postresolved
545
- }
546
- }
547
- }
15
+ exports.load = async function load(url, source = null, opts = {}) {
16
+ if (typeof url === 'string') url = new URL(url)
548
17
 
549
- throw errors.MODULE_NOT_FOUND(
550
- notFound('module', specifier, parentURL, candidates),
551
- specifier,
552
- parentURL,
553
- candidates
554
- )
18
+ if (source !== null && typeof source !== 'string' && !ArrayBuffer.isView(source)) {
19
+ opts = source
20
+ source = null
555
21
  }
556
22
 
557
- static asset(specifier, parentURL, opts = {}) {
558
- if (typeof specifier !== 'string') {
559
- throw new TypeError(
560
- `Specifier must be a string. Received type ${typeof specifier} (${specifier})`
561
- )
562
- }
563
-
564
- const referrer = opts.referrer || null
565
- const inherited = inherit(referrer)
566
-
567
- const {
568
- cache = referrer ? referrer._cache : Object.create(null),
569
- protocol = inherited.protocol,
570
- imports = inherited.imports,
571
- resolutions = inherited.resolutions,
572
- conditions = inherited.conditions
573
- } = opts
574
-
575
- const resolved = protocol.preresolve(specifier, parentURL)
576
-
577
- const [resolution] = protocol.resolve(resolved, parentURL, imports)
578
-
579
- if (resolution) return protocol.postresolve(resolution)
580
-
581
- const candidates = []
582
-
583
- for (const resolution of resolve(
584
- resolved,
585
- parentURL,
586
- {
587
- conditions: ['asset', ...conditions],
588
- imports,
589
- resolutions,
590
- engines: Bare.versions
591
- },
592
- readPackageFor(protocol, cache)
593
- )) {
594
- candidates.push(resolution)
23
+ opts = optionsFor(opts)
595
24
 
596
- if (protocol.exists(resolution, constants.types.ASSET)) {
597
- const postresolved = protocol.postresolve(
598
- protocol.asset ? protocol.asset(resolution) : resolution
599
- )
25
+ const loader = loaderFor(opts)
600
26
 
601
- cacheResolution(resolutions, parentURL, resolved, 'asset', postresolved)
27
+ const record = await loader.link(url, source, opts)
602
28
 
603
- return postresolved
604
- }
605
- }
606
-
607
- throw errors.ASSET_NOT_FOUND(
608
- notFound('asset', specifier, parentURL, candidates),
609
- specifier,
610
- parentURL,
611
- candidates
612
- )
613
- }
29
+ return loader._evaluate(record)
614
30
  }
615
31
 
616
- const Module = exports
32
+ exports.loadSync = function loadSync(url, source = null, opts = {}) {
33
+ if (typeof url === 'string') url = new URL(url)
617
34
 
618
- function inherit(referrer) {
619
- return {
620
- defaultType: referrer ? referrer._defaultType : 0,
621
- cache: referrer ? referrer._cache : Module._cache,
622
- main: referrer ? referrer._main : null,
623
- protocol: referrer ? referrer._protocol : Module._protocol,
624
- imports: referrer ? referrer._imports : null,
625
- resolutions: referrer ? referrer._resolutions : Object.create(null),
626
- builtins: referrer ? referrer._builtins : null,
627
- conditions: referrer ? referrer._conditions : Module._conditions
35
+ if (source !== null && typeof source !== 'string' && !ArrayBuffer.isView(source)) {
36
+ opts = source
37
+ source = null
628
38
  }
629
- }
630
39
 
631
- function readPackageFor(protocol, cache) {
632
- return function readPackage(packageURL) {
633
- if (protocol.exists(packageURL, constants.types.JSON)) {
634
- return Module.load(packageURL, { protocol, cache })._exports
635
- }
40
+ opts = optionsFor(opts)
636
41
 
637
- return null
638
- }
639
- }
42
+ const loader = loaderFor(opts)
640
43
 
641
- function notFound(kind, specifier, parentURL, candidates) {
642
- let message = `Cannot find ${kind} '${specifier}' imported from '${parentURL.href}'`
44
+ const record = loader.linkSync(url, source, opts)
643
45
 
644
- if (candidates.length > 0) {
645
- message += '\nCandidates:'
646
- message += '\n' + candidates.map((url) => '- ' + url.href).join('\n')
647
- }
46
+ record._evaluate()
648
47
 
649
- return message
48
+ return record
650
49
  }
651
50
 
652
- const typeInfo = {
653
- [constants.types.SCRIPT]: {
654
- name: 'script',
655
- attribute: 'script',
656
- canonicalExtension: '.cjs',
657
- extensions: ['.js', '.cjs', '.ts', '.cts']
658
- },
659
- [constants.types.MODULE]: {
660
- name: 'module',
661
- attribute: 'module',
662
- canonicalExtension: '.mjs',
663
- extensions: ['.js', '.mjs', '.ts', '.mts']
664
- },
665
- [constants.types.JSON]: {
666
- name: 'json',
667
- attribute: 'json',
668
- canonicalExtension: '.json',
669
- extensions: ['.json']
670
- },
671
- [constants.types.BUNDLE]: {
672
- name: 'bundle',
673
- attribute: 'bundle',
674
- canonicalExtension: '.bundle',
675
- extensions: ['.bundle']
676
- },
677
- [constants.types.ADDON]: {
678
- name: 'bare',
679
- attribute: 'addon',
680
- canonicalExtension: '.bare',
681
- extensions: ['.bare', '.node']
682
- },
683
- [constants.types.BINARY]: {
684
- name: 'binary',
685
- attribute: 'binary',
686
- canonicalExtension: '.bin',
687
- extensions: ['.bin']
688
- },
689
- [constants.types.TEXT]: {
690
- name: 'text',
691
- attribute: 'text',
692
- canonicalExtension: '.txt',
693
- extensions: ['.txt']
51
+ exports.resolve = async function resolve(specifier, parentURL, condition = 'require', opts = {}) {
52
+ if (typeof condition === 'object' && condition !== null) {
53
+ opts = condition
54
+ condition = 'require'
694
55
  }
695
- }
696
-
697
- const defaultExtensions = ['.js', '.cjs', '.mjs', '.ts', '.cts', '.mts', '.json', '.bare', '.node']
698
-
699
- const typeByAttribute = Object.create(null)
700
-
701
- for (const type in typeInfo) {
702
- typeByAttribute[typeInfo[type].attribute] = +type
703
- }
704
56
 
705
- function extensionsForType(type) {
706
- return type in typeInfo ? typeInfo[type].extensions : defaultExtensions
707
- }
708
-
709
- function canonicalExtensionForType(type) {
710
- return type in typeInfo ? typeInfo[type].canonicalExtension : null
711
- }
57
+ const { loader, parent } = resolveWith(specifier, parentURL, condition, optionsFor(opts))
712
58
 
713
- function nameOfType(type) {
714
- return type in typeInfo ? typeInfo[type].name : null
59
+ return await loader._resolve(specifier, parent, condition)
715
60
  }
716
61
 
717
- function typeForAttributes(attributes) {
718
- if (typeof attributes !== 'object' || attributes === null) return 0
719
-
720
- return typeByAttribute[attributes.type] || 0
721
- }
722
-
723
- function mixinImports(target, imports, url) {
724
- if (typeof imports === 'object' && imports !== null && 'imports' in imports) {
725
- imports = imports.imports
726
- }
727
-
728
- if (typeof imports !== 'object' || imports === null) {
729
- throw errors.INVALID_IMPORTS_MAP(`Imports map at '${url.href}' is not valid`)
730
- }
731
-
732
- return { ...target, ...imports }
733
- }
734
-
735
- function cacheResolution(resolutions, parentURL, specifier, condition, resolved) {
736
- if (resolutions === null) return
737
-
738
- let imports = resolutions[parentURL.href]
739
-
740
- if (typeof imports !== 'object' || imports === null) {
741
- imports = resolutions[parentURL.href] = Object.create(null)
62
+ exports.resolveSync = function resolveSync(specifier, parentURL, condition = 'require', opts = {}) {
63
+ if (typeof condition === 'object' && condition !== null) {
64
+ opts = condition
65
+ condition = 'require'
742
66
  }
743
67
 
744
- // Don't overwrite any preexisting entries, such as those from a bundle, as
745
- // they take precedence over what we resolve ourselves.
746
- if (specifier in imports) return
68
+ const { loader, parent } = resolveWith(specifier, parentURL, condition, optionsFor(opts))
747
69
 
748
- // Cache the resolution behind the condition that produced it as the same
749
- // specifier may resolve differently depending on whether it is imported,
750
- // required, or resolved as an asset.
751
- imports[specifier] = { [condition]: resolved.href }
70
+ return loader._resolveSync(specifier, parent, condition)
752
71
  }
753
72
 
754
- exports.Protocol = Protocol
755
-
756
- exports.constants = constants
757
-
758
- // For Node.js compatibility
759
- exports.builtinModules = []
760
-
761
- // For Node.js compatibility
762
- exports.isBuiltin = function isBuiltin() {
763
- return false
764
- }
765
-
766
- exports.createRequire = function createRequire(parentURL, opts = {}) {
767
- const inherited = inherit(opts.referrer)
768
-
769
- const {
770
- type = constants.types.SCRIPT,
771
- defaultType = inherited.defaultType || constants.types.SCRIPT,
772
- cache = inherited.cache,
773
- main = inherited.main,
774
- protocol = inherited.protocol,
775
- imports = inherited.imports,
776
- resolutions = inherited.resolutions,
777
- builtins = inherited.builtins,
778
- conditions = inherited.conditions
779
- } = opts
780
-
781
- let module = opts.module || null
782
-
783
- if (module === null) {
784
- module = new Module(toURL(parentURL))
785
-
786
- module._type = type
787
- module._defaultType = defaultType
788
- module._cache = cache
789
- module._main = main || module
790
- module._protocol = protocol
791
- module._imports = imports
792
- module._resolutions = resolutions
793
- module._builtins = builtins
794
- module._conditions = conditions
795
- }
796
-
797
- const referrer = module
798
-
799
- function require(specifier, opts = {}) {
800
- const attributes = opts && opts.with
801
-
802
- const resolved = Module.resolve(specifier, referrer._url, {
803
- referrer,
804
- attributes
805
- })
806
-
807
- const module = Module.load(resolved, { referrer, attributes })
808
-
809
- return module._exports
810
- }
73
+ const conditions = ['require', 'import', 'asset', 'addon']
811
74
 
812
- require.main = module._main
813
- require.cache = module._cache
814
-
815
- require.resolve = function resolve(specifier, parentURL = referrer._url) {
816
- return urlToPath(Module.resolve(specifier, toURL(parentURL, referrer._url), { referrer }))
817
- }
818
-
819
- require.addon = function addon(specifier = '.', parentURL = referrer._url) {
820
- const resolved = Bare.Addon.resolve(specifier, toURL(parentURL, referrer._url), { referrer })
821
-
822
- const addon = Bare.Addon.load(resolved, { referrer })
823
-
824
- return addon._exports
825
- }
826
-
827
- require.addon.host = Bare.Addon.host
828
-
829
- require.addon.resolve = function resolve(specifier = '.', parentURL = referrer._url) {
830
- return urlToPath(
831
- Bare.Addon.resolve(specifier, toURL(parentURL, referrer._url), {
832
- referrer
833
- })
75
+ function resolveWith(specifier, parentURL, condition, opts) {
76
+ if (typeof specifier !== 'string') {
77
+ throw new TypeError(
78
+ `Specifier must be a string. Received type ${typeof specifier} (${specifier})`
834
79
  )
835
80
  }
836
81
 
837
- require.asset = function asset(specifier, parentURL = referrer._url) {
838
- return urlToPath(Module.asset(specifier, toURL(parentURL, referrer._url), { referrer }))
839
- }
840
-
841
- return require
842
- }
843
-
844
- function readSource(module, source) {
845
- if (source === null) source = module._protocol.read(module._url)
846
-
847
- if (typeof source === 'string') source = Buffer.from(source)
848
-
849
- return source
850
- }
851
-
852
- Module._extensions['.js'] = function (module, source, referrer) {
853
- const cache = module._cache
854
- const protocol = module._protocol
855
- const resolutions = module._resolutions
856
-
857
- let pkg
858
-
859
- for (const packageURL of resolve.lookupPackageScope(module._url, {
860
- resolutions
861
- })) {
862
- if (cache[packageURL.href]) {
863
- pkg = cache[packageURL.href]
864
- break
865
- }
866
-
867
- if (protocol.exists(packageURL, constants.types.JSON)) {
868
- pkg = Module.load(packageURL, { protocol, cache })
869
- break
870
- }
82
+ if (conditions.includes(condition) === false) {
83
+ throw new TypeError(
84
+ `Condition must be one of ${conditions.join(', ')}. Received type ${typeof condition} (${condition})`
85
+ )
871
86
  }
872
87
 
873
- const info = (pkg && pkg._exports) || {}
874
-
875
- const isESM =
876
- // The default type is ES modules.
877
- constants.types.MODULE === module._defaultType ||
878
- // The package is explicitly declared as an ES module.
879
- (info && info.type === 'module')
880
-
881
- return Module._extensions[isESM ? '.mjs' : '.cjs'](module, source, referrer)
882
- }
883
-
884
- Module._extensions['.cjs'] = function (module, source, referrer) {
885
- module._type = constants.types.SCRIPT
886
-
887
- source = readSource(module, source)
888
-
889
- module._source = source
890
-
891
- module._function = binding.createFunction(
892
- module._url.href,
893
- ['require', 'module', 'exports', '__filename', '__dirname'],
894
- source.toString(),
895
- 0
896
- )
897
-
898
- const id = binding.getFunctionID(module._function)
899
-
900
- Module._registry.set(id, module)
901
- }
902
-
903
- Module._extensions['.mjs'] = function (module, source, referrer) {
904
- module._type = constants.types.MODULE
905
-
906
- source = readSource(module, source)
907
-
908
- module._source = source
909
-
910
- module._handle = binding.createModule(module._url.href, source.toString(), 0, Module._handle)
88
+ const referrer = opts.referrer || null
911
89
 
912
- const id = binding.getModuleID(module._handle)
913
-
914
- Module._registry.set(id, module)
915
- }
916
-
917
- for (const [typescript, javascript] of [
918
- ['.ts', '.js'],
919
- ['.cts', '.cjs'],
920
- ['.mts', '.mjs']
921
- ]) {
922
- Module._extensions[typescript] = function (module, source, referrer) {
923
- return Module._extensions[javascript](module, strip(readSource(module, source)), referrer)
90
+ if (parentURL === undefined || parentURL === null) {
91
+ parentURL = referrer ? referrer.url : pathToFileURL('./')
92
+ } else if (typeof parentURL === 'string') {
93
+ parentURL = new URL(parentURL)
924
94
  }
925
- }
926
-
927
- Module._extensions['.json'] = function (module, source, referrer) {
928
- module._type = constants.types.JSON
929
95
 
930
- source = readSource(module, source)
931
-
932
- module._source = source
933
- module._exports = JSON.parse(source.toString())
96
+ return { loader: loaderFor(opts), parent: assertURL(parentURL, 'Parent URL') }
934
97
  }
935
98
 
936
- Module._extensions['.bare'] = Module._extensions['.node'] = function (module, source, referrer) {
937
- module._type = constants.types.ADDON
938
-
939
- referrer = module
99
+ function assertURL(url, name) {
100
+ if (isURL(url)) return url
940
101
 
941
- module._exports = Bare.Addon.load(module._url, { referrer }).exports
102
+ throw new TypeError(`${name} must be a URL. Received type ${typeof url} (${url})`)
942
103
  }
943
104
 
944
- Module._extensions['.bundle'] = function (module, source, referrer) {
945
- const protocol = module._protocol
946
-
947
- module._type = constants.types.BUNDLE
948
-
949
- source = readSource(module, source)
950
-
951
- referrer = module
105
+ function optionsFor(opts) {
106
+ if (opts === undefined || opts === null) return {}
952
107
 
953
- const bundle = Bundle.from(source).mount(module._url.href + '/')
108
+ if (typeof opts === 'object') return opts
954
109
 
955
- module._source = source
956
- module._imports = bundle.imports
957
- module._resolutions = bundle.resolutions
958
-
959
- module._protocol = protocol.extend({
960
- postresolve(context, url) {
961
- return bundle.exists(url.href) ? url : context.postresolve(url)
962
- },
963
-
964
- exists(context, url, type) {
965
- return bundle.exists(url.href) || context.exists(url, type)
966
- },
967
-
968
- read(context, url) {
969
- return bundle.read(url.href) || context.read(url)
970
- }
971
- })
972
-
973
- if (bundle.main) {
974
- module._exports = Module.load(new URL(bundle.main), bundle.read(bundle.main), {
975
- referrer
976
- })._exports
977
- }
110
+ throw new TypeError(`Options must be an object. Received type ${typeof opts} (${opts})`)
978
111
  }
979
112
 
980
- Module._extensions['.bin'] = function (module, source, referrer) {
981
- module._type = constants.types.BINARY
982
-
983
- source = readSource(module, source)
984
-
985
- module._source = module._exports = source
986
- }
987
-
988
- Module._extensions['.txt'] = function (module, source, referrer) {
989
- module._type = constants.types.TEXT
113
+ exports.createRequire = function createRequire(parentURL, opts = {}) {
114
+ opts = optionsFor(opts)
990
115
 
991
- source = readSource(module, source)
116
+ let referrer = opts.referrer || null
992
117
 
993
- module._source = source
994
- module._exports = source.toString()
995
- }
118
+ const loader = loaderFor(opts)
996
119
 
997
- Module._protocol = new Protocol({
998
- postresolve(url) {
999
- switch (url.protocol) {
1000
- case 'file:':
1001
- return pathToFileURL(binding.realpath(path.toNamespacedPath(fileURLToPath(url))))
1002
- default:
1003
- return url
120
+ if (referrer === null) {
121
+ if (typeof parentURL === 'string') {
122
+ parentURL = URL.parse(parentURL) || pathToFileURL(parentURL)
1004
123
  }
1005
- },
1006
124
 
1007
- exists(url, type = 0) {
1008
- switch (url.protocol) {
1009
- case 'file:':
1010
- return binding.exists(
1011
- path.toNamespacedPath(fileURLToPath(url)),
1012
- type === constants.types.ASSET ? binding.FILE | binding.DIR : binding.FILE
1013
- )
1014
- default:
1015
- return false
1016
- }
1017
- },
125
+ assertURL(parentURL, 'Parent URL')
1018
126
 
1019
- read(url) {
1020
- switch (url.protocol) {
1021
- case 'file:':
1022
- return Buffer.from(binding.read(path.toNamespacedPath(fileURLToPath(url))))
1023
- default:
1024
- throw errors.UNKNOWN_PROTOCOL(`Cannot load module '${url.href}'`)
1025
- }
1026
- }
1027
- })
1028
-
1029
- function toURL(value, base) {
1030
- if (isURL(value)) return value
127
+ referrer = new Module(
128
+ loader,
129
+ new ModuleSource({
130
+ url: parentURL,
131
+ type: 0,
132
+ source: Buffer.alloc(0),
133
+ imports: {},
134
+ lexer: { imports: [], exports: [] }
135
+ })
136
+ )
1031
137
 
1032
- if (startsWithWindowsDriveLetter(value)) {
1033
- return pathToFileURL(value)
138
+ if (loader.main === null) loader._main = referrer
1034
139
  }
1035
140
 
1036
- return URL.parse(value, base) || pathToFileURL(value)
141
+ return loader._createRequire(referrer)
1037
142
  }
1038
143
 
1039
- function urlToPath(url) {
1040
- if (url.protocol === 'file:') return fileURLToPath(url)
144
+ function loaderFor(opts) {
145
+ const referrer = opts.referrer || null
1041
146
 
1042
- assertValidURLPath(url)
147
+ if (referrer === null) return new ModuleLoader(opts)
1043
148
 
1044
- return decodeURIComponent(url.pathname)
1045
- }
1046
-
1047
- function urlToDirname(url) {
1048
- if (url.protocol === 'file:') return path.dirname(fileURLToPath(url))
1049
-
1050
- assertValidURLPath(url)
1051
-
1052
- return decodeURIComponent(new URL('.', url).pathname).replace(/\/$/, '')
1053
- }
1054
-
1055
- function assertValidURLPath(url) {
1056
- if (isWindows) {
1057
- if (/%2f|%5c/i.test(url.pathname)) {
1058
- throw errors.INVALID_URL_PATH('The URL path must not include encoded \\ or / characters')
1059
- }
1060
- } else {
1061
- if (/%2f/i.test(url.pathname)) {
1062
- throw errors.INVALID_URL_PATH('The URL path must not include encoded / characters')
1063
- }
1064
- }
149
+ return referrer._loader._fork(opts)
1065
150
  }