bare-module 7.3.0 → 7.5.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.
package/README.md CHANGED
@@ -303,11 +303,32 @@ options = {
303
303
  // `binary` and `text`. A type that is not one of them is turned down rather
304
304
  // than passed over, as is a `type` that is not a string. `imports` is the
305
305
  // specifier of an "imports" map to apply to the module and its dependencies,
306
- // resolved relative to the module calling `require()`.
306
+ // resolved relative to the module calling `require()`. `host` is the host to
307
+ // resolve the addons of the module and its dependencies for, and must be one
308
+ // that loads on any platform, such as `wasi-wasm32`. The conditions of the
309
+ // host, such as `wasi` and `wasm32`, may then also be targeted alongside
310
+ // those of the native host, in the order a package lists them. `wasi` is the
311
+ // specifier of a module providing the WASI capabilities of the WebAssembly
312
+ // addons of the module and its dependencies, in place of the loader's `wasi`
313
+ // option.
307
314
  with: { type: 'json' }
308
315
  }
309
316
  ```
310
317
 
318
+ A package's addons load in one context per loader, being the host and WASI provider it's first imported under. Importing it under another throws.
319
+
320
+ A WASI provider exports a function, as `module.exports` or its default export, which is called with the URL of each WebAssembly addon and returns the options for [`bare-wasi`](https://github.com/holepunchto/bare-wasi):
321
+
322
+ ```js
323
+ const { MemoryDirectory } = require('bare-wasi/memory')
324
+
325
+ module.exports = (url) => ({
326
+ version: 'preview1',
327
+ preopens: { '/data': new MemoryDirectory() },
328
+ random: (data) => crypto.getRandomValues(data)
329
+ })
330
+ ```
331
+
311
332
  ### `require.main`
312
333
 
313
334
  The module representing the entry script where the program was launched.
@@ -597,7 +618,12 @@ options = {
597
618
  // A map of preresolved imports with keys being serialized parent URLs and
598
619
  // values being "imports" maps. Like the cache it is an object or omitted, and
599
620
  // omitting it gives a fresh map scoped to this loader.
600
- resolutions
621
+ resolutions,
622
+ // A function returning the WASI options of a WebAssembly addon, given its
623
+ // URL, for addons not imported with a `wasi` attribute. Without it, they get
624
+ // no capabilities. The options are versioned, so `version` must be
625
+ // `'preview1'`. A cache is read with a single `wasi`, like a single protocol.
626
+ wasi
601
627
  }
602
628
  ```
603
629
 
package/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import Buffer from 'bare-buffer'
2
+ import Bundle from 'bare-bundle'
2
3
  import URL from 'bare-url'
3
4
  import { ResolutionsMap } from 'bare-module-resolve'
4
5
  import { constants } from 'bare-module-traverse'
@@ -28,6 +29,17 @@ interface Attributes {
28
29
  * relative to the parent URL.
29
30
  */
30
31
  imports?: string
32
+ /**
33
+ * The host to resolve the addons of the module and its dependencies for, such as `wasi-wasm32`.
34
+ * The conditions of the host may then also be targeted alongside those of the native host, in the
35
+ * order a package lists them.
36
+ */
37
+ host?: string
38
+ /**
39
+ * The specifier of a module providing the WASI capabilities of the WebAssembly addons of the
40
+ * module and its dependencies, resolved relative to the parent URL.
41
+ */
42
+ wasi?: string
31
43
  }
32
44
 
33
45
  interface Module {
@@ -151,7 +163,7 @@ declare namespace Module {
151
163
  export function load(url: URL, opts: LoadOptions): Promise<Module>
152
164
  export function load(
153
165
  url: URL,
154
- source?: Buffer | string | null,
166
+ source?: Buffer | Bundle | string | null,
155
167
  opts?: LoadOptions
156
168
  ): Promise<Module>
157
169
 
@@ -169,7 +181,11 @@ declare namespace Module {
169
181
  * the requested `type`.
170
182
  */
171
183
  export function loadSync(url: URL, opts: LoadOptions): Module
172
- export function loadSync(url: URL, source?: Buffer | string | null, opts?: LoadOptions): Module
184
+ export function loadSync(
185
+ url: URL,
186
+ source?: Buffer | Bundle | string | null,
187
+ opts?: LoadOptions
188
+ ): Module
173
189
 
174
190
  /**
175
191
  * Resolve the module `specifier` relative to the `parentURL`. `specifier` is a string and
package/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const { isURL, pathToFileURL } = require('bare-url')
2
+ const Bundle = require('bare-bundle')
2
3
  const { constants } = require('bare-module-traverse')
3
4
  const Module = require('./lib/module')
4
5
  const ModuleProtocol = require('./lib/protocol')
@@ -15,7 +16,7 @@ exports.constants = constants
15
16
  exports.load = async function load(url, source = null, opts = {}) {
16
17
  if (typeof url === 'string') url = new URL(url)
17
18
 
18
- if (source !== null && typeof source !== 'string' && !ArrayBuffer.isView(source)) {
19
+ if (source !== null && !isSource(source)) {
19
20
  opts = source
20
21
  source = null
21
22
  }
@@ -32,7 +33,7 @@ exports.load = async function load(url, source = null, opts = {}) {
32
33
  exports.loadSync = function loadSync(url, source = null, opts = {}) {
33
34
  if (typeof url === 'string') url = new URL(url)
34
35
 
35
- if (source !== null && typeof source !== 'string' && !ArrayBuffer.isView(source)) {
36
+ if (source !== null && !isSource(source)) {
36
37
  opts = source
37
38
  source = null
38
39
  }
@@ -102,6 +103,10 @@ function assertURL(url, name) {
102
103
  throw new TypeError(`${name} must be a URL. Received type ${typeof url} (${url})`)
103
104
  }
104
105
 
106
+ function isSource(value) {
107
+ return typeof value === 'string' || ArrayBuffer.isView(value) || Bundle.isBundle(value)
108
+ }
109
+
105
110
  function optionsFor(opts) {
106
111
  if (opts === undefined || opts === null) return {}
107
112
 
package/lib/errors.js CHANGED
@@ -65,6 +65,14 @@ module.exports = class ModuleError extends Error {
65
65
  return new ModuleError(msg, ModuleError.UNEXPECTED_PROMISE)
66
66
  }
67
67
 
68
+ static ADDON_HOST_INCOMPATIBLE(msg) {
69
+ return new ModuleError(msg, ModuleError.ADDON_HOST_INCOMPATIBLE)
70
+ }
71
+
72
+ static ADDON_WASI_INCOMPATIBLE(msg) {
73
+ return new ModuleError(msg, ModuleError.ADDON_WASI_INCOMPATIBLE)
74
+ }
75
+
68
76
  static UNKNOWN_MODULE_TYPE(msg) {
69
77
  return new ModuleError(msg, ModuleError.UNKNOWN_MODULE_TYPE)
70
78
  }
package/lib/loader.d.ts CHANGED
@@ -57,6 +57,7 @@ declare namespace ModuleLoader {
57
57
  imports?: ImportsMap
58
58
  protocol?: Protocol
59
59
  resolutions?: ResolutionsMap
60
+ wasi?: (url: URL) => object
60
61
  }
61
62
 
62
63
  export interface LinkOptions {
package/lib/loader.js CHANGED
@@ -66,6 +66,14 @@ function builtinsFor(builtins) {
66
66
  throw new TypeError(`Builtins must be an object. Received type ${typeof builtins} (${builtins})`)
67
67
  }
68
68
 
69
+ function wasiFor(wasi) {
70
+ if (wasi === undefined || wasi === null) return null
71
+
72
+ if (typeof wasi === 'function') return wasi
73
+
74
+ throw new TypeError(`WASI must be a function. Received type ${typeof wasi} (${wasi})`)
75
+ }
76
+
69
77
  function importsFor(imports) {
70
78
  if (imports === undefined || imports === null) return null
71
79
 
@@ -108,6 +116,23 @@ function* eachURL(urls) {
108
116
  }
109
117
  }
110
118
 
119
+ function withContext(attributes, context) {
120
+ const { host, wasi } = context
121
+
122
+ if (host === null && wasi === null) return attributes
123
+
124
+ attributes = { ...attributes }
125
+
126
+ if (host !== null) attributes.host = host
127
+ if (wasi !== null) attributes.wasi = wasi
128
+
129
+ return attributes
130
+ }
131
+
132
+ function sameContext(a, b) {
133
+ return a.host === b.host && a.wasi === b.wasi
134
+ }
135
+
111
136
  function typeAttributeFor(attributes) {
112
137
  if (attributes === undefined || attributes === null) return undefined
113
138
 
@@ -133,7 +158,8 @@ const loaderOptions = [
133
158
  'defaultType',
134
159
  'imports',
135
160
  'protocol',
136
- 'resolutions'
161
+ 'resolutions',
162
+ 'wasi'
137
163
  ]
138
164
 
139
165
  const recordClasses = {
@@ -177,13 +203,15 @@ module.exports = class ModuleLoader {
177
203
  imports,
178
204
  resolutions,
179
205
  cache,
180
- concurrency
206
+ concurrency,
207
+ wasi
181
208
  } = opts
182
209
 
183
210
  this._protocol = protocol === null ? defaultProtocol : assertProtocol(protocol)
184
211
  this._defaultType = defaultTypeFor(defaultType)
185
212
  this._builtins = builtinsFor(builtins)
186
213
  this._imports = importsFor(imports)
214
+ this._wasi = wasiFor(wasi)
187
215
  this._concurrency = concurrencyFor(concurrency)
188
216
  this._main = null
189
217
  this._cache = cacheFor(cache)
@@ -192,6 +220,9 @@ module.exports = class ModuleLoader {
192
220
  this._bundles = []
193
221
  this._mounts = new Map()
194
222
  this._visited = new Set()
223
+ this._defaultContext = { host: null, wasi: null, visited: this._visited }
224
+ this._contexts = new Map([[JSON.stringify([null, null]), this._defaultContext]])
225
+ this._addonContexts = new Map()
195
226
  this._packages = new Map()
196
227
  this._prefixes = new Map()
197
228
  this._answers = { listed: new Map(), resolved: new Map(), exists: new Map() }
@@ -359,7 +390,10 @@ module.exports = class ModuleLoader {
359
390
  // loader read belongs to what it could reach, so a fork that reaches
360
391
  // elsewhere gets neither the cache it read into nor the resolutions it
361
392
  // resolved through.
362
- const reaches = options.protocol === this._protocol && options.builtins === this._builtins
393
+ const reaches =
394
+ options.protocol === this._protocol &&
395
+ options.builtins === this._builtins &&
396
+ options.wasi === this._wasi
363
397
 
364
398
  if (!reaches) options.cache = opts.cache
365
399
 
@@ -476,9 +510,10 @@ module.exports = class ModuleLoader {
476
510
 
477
511
  delete this._cache[href]
478
512
 
479
- this._visited.delete(href)
480
513
  this._packages.delete(href)
481
514
 
515
+ for (const { visited } of this._contexts.values()) visited.delete(href)
516
+
482
517
  this._answers.listed.delete(href)
483
518
  this._answers.resolved.delete(href)
484
519
  this._answers.exists.delete(href)
@@ -510,13 +545,14 @@ module.exports = class ModuleLoader {
510
545
  return record
511
546
  }
512
547
 
513
- _addonRecord(url) {
548
+ _addonRecord(url, wasi = null) {
514
549
  const source = new ModuleSource({
515
550
  url,
516
551
  type: type.ADDON,
517
552
  source: null,
518
553
  imports: {},
519
- lexer: { imports: [], exports: [] }
554
+ lexer: { imports: [], exports: [] },
555
+ wasi
520
556
  })
521
557
 
522
558
  const record = new AddonModule(this, source)
@@ -544,7 +580,10 @@ module.exports = class ModuleLoader {
544
580
  resolutions: this._resolutions,
545
581
  packages: this._packages,
546
582
  prefixes: this._prefixes,
547
- resolve: traverse.resolve.bare
583
+ contexts: this._contexts,
584
+ addonContexts: this._addonContexts,
585
+ resolve: traverse.resolve.bare,
586
+ loadable: isLoadable
548
587
  }
549
588
 
550
589
  if (this._builtins !== null) opts.builtins = Object.keys(this._builtins)
@@ -618,12 +657,12 @@ module.exports = class ModuleLoader {
618
657
  driveSync(this._drive(link, onChild, onBundle), protocol, driveLink, answers)
619
658
 
620
659
  while (queue.length > 0 || deferred.length > 0) {
621
- const generator = queue.length > 0 ? queue.pop() : deferred.shift()
660
+ const generator = queue.length > 0 ? queue.shift() : deferred.shift()
622
661
 
623
662
  driveSync(this._drive(generator, onChild, onBundle), protocol, driveLink, answers)
624
663
  }
625
664
 
626
- for (const record of bundles) record._mount()
665
+ for (const record of bundles) record._mountSync()
627
666
  }
628
667
 
629
668
  async _link(root, protocol) {
@@ -631,40 +670,32 @@ module.exports = class ModuleLoader {
631
670
 
632
671
  const semaphore = this._concurrency > 0 ? new Semaphore(this._concurrency) : null
633
672
 
673
+ const queue = [root]
634
674
  const deferred = []
635
675
  const bundles = []
636
676
 
637
- const onBundle = (record) => bundles.push(record)
638
-
639
- const collect = async (generator) => {
640
- const queue = []
641
-
642
- const onChild = (children, isDeferred) => {
643
- if (isDeferred) deferred.push(children)
644
- else queue.push(children)
645
- }
677
+ const onChild = (children, isDeferred) => {
678
+ if (isDeferred) deferred.push(children)
679
+ else queue.push(children)
680
+ }
646
681
 
647
- const driveLink = (link) =>
648
- drive(this._drive(link, onChild, onBundle), protocol, driveLink, semaphore, answers)
682
+ const onBundle = (record) => bundles.push(record)
649
683
 
650
- await drive(
651
- this._drive(generator, onChild, onBundle),
652
- protocol,
653
- driveLink,
654
- semaphore,
655
- answers
656
- )
684
+ const driveLink = (link) =>
685
+ drive(this._drive(link, onChild, onBundle), protocol, driveLink, semaphore, answers)
657
686
 
658
- if (queue.length > 0) await Promise.all(queue.map(collect))
659
- }
687
+ const collect = (generator) =>
688
+ drive(this._drive(generator, onChild, onBundle), protocol, driveLink, semaphore, answers)
660
689
 
661
- await collect(root)
690
+ // Each round is driven concurrently, but only once the one before it is
691
+ // done, so that children are linked in the order they were reached.
692
+ while (queue.length > 0 || deferred.length > 0) {
693
+ const round = queue.length > 0 ? queue.splice(0) : deferred.splice(0)
662
694
 
663
- while (deferred.length > 0) {
664
- await Promise.all(deferred.splice(0, deferred.length).map(collect))
695
+ await Promise.all(round.map(collect))
665
696
  }
666
697
 
667
- for (const record of bundles) await record._mountAsync()
698
+ for (const record of bundles) await record._mount()
668
699
  }
669
700
 
670
701
  _addBundle(bundle) {
@@ -776,6 +807,8 @@ module.exports = class ModuleLoader {
776
807
 
777
808
  if (record === null) {
778
809
  record = loader._requireSync(specifier, referrer.url, attributes)
810
+ } else {
811
+ loader._linkForSync(url, referrer.url, attributes, lex.constants.REQUIRE)
779
812
  }
780
813
 
781
814
  loader._assertType(record, attributes)
@@ -810,30 +843,17 @@ module.exports = class ModuleLoader {
810
843
  _importSync(specifier, parentURL) {
811
844
  const url = this._resolveSync(specifier, parentURL, 'import')
812
845
 
813
- let record = this._lookup(url)
846
+ this._linkForSync(url, parentURL, null, lex.constants.IMPORT)
814
847
 
815
- if (record === null) {
816
- this.linkSync(url, null, { importType: lex.constants.IMPORT })
817
-
818
- record = this.get(url)
819
- }
820
-
821
- return record
848
+ return this._lookup(url)
822
849
  }
823
850
 
824
851
  _requireSync(specifier, parentURL, attributes = null) {
825
852
  const url = this._resolveSync(specifier, parentURL, 'require')
826
853
 
827
- let record = this._lookup(url)
828
-
829
- if (record === null) {
830
- this.linkSync(url, null, {
831
- attributes: this._resolveAttributesSync(attributes, parentURL),
832
- importType: lex.constants.REQUIRE
833
- })
854
+ this._linkForSync(url, parentURL, attributes, lex.constants.REQUIRE)
834
855
 
835
- record = this.get(url)
836
- }
856
+ const record = this._lookup(url)
837
857
 
838
858
  if (record === null) {
839
859
  throw errors.MODULE_NOT_FOUND(
@@ -846,6 +866,99 @@ module.exports = class ModuleLoader {
846
866
  return record
847
867
  }
848
868
 
869
+ _linkForSync(url, parentURL, attributes, importType) {
870
+ attributes = this._resolveAttributeSync(attributes, 'wasi', parentURL)
871
+
872
+ const contexts = this._unlinkedContexts(url, parentURL, attributes)
873
+
874
+ if (contexts.length === 0) return
875
+
876
+ attributes = this._resolveAttributeSync(attributes, 'imports', parentURL)
877
+
878
+ if (hasAttribute(attributes, 'wasi')) {
879
+ this._linkForSync(new URL(attributes.wasi), parentURL, null, 0)
880
+ }
881
+
882
+ for (const context of contexts) {
883
+ this.linkSync(url, null, { attributes: withContext(attributes, context), importType })
884
+ }
885
+ }
886
+
887
+ async _linkFor(url, parentURL, attributes, importType) {
888
+ attributes = await this._resolveAttribute(attributes, 'wasi', parentURL)
889
+
890
+ const contexts = this._unlinkedContexts(url, parentURL, attributes)
891
+
892
+ if (contexts.length === 0) return
893
+
894
+ attributes = await this._resolveAttribute(attributes, 'imports', parentURL)
895
+
896
+ if (hasAttribute(attributes, 'wasi')) {
897
+ await this._linkFor(new URL(attributes.wasi), parentURL, null, 0)
898
+ }
899
+
900
+ for (const context of contexts) {
901
+ await this.link(url, null, { attributes: withContext(attributes, context), importType })
902
+ }
903
+ }
904
+
905
+ _unlinkedContexts(url, parentURL, attributes) {
906
+ const { host, wasi } = attributes || {}
907
+
908
+ const linked = this._lookup(url) === null ? [] : this._contextsOf(url)
909
+
910
+ const unlinked = []
911
+
912
+ for (const context of this._contextsOf(parentURL)) {
913
+ const requested = {
914
+ host: host === undefined ? context.host : host,
915
+ wasi: wasi === undefined ? context.wasi : wasi
916
+ }
917
+
918
+ const known = (other) => sameContext(other, requested)
919
+
920
+ if (linked.some(known) || unlinked.some(known)) continue
921
+
922
+ unlinked.push(requested)
923
+ }
924
+
925
+ return unlinked
926
+ }
927
+
928
+ _contextsOf(url) {
929
+ const contexts = []
930
+
931
+ for (const context of this._contexts.values()) {
932
+ if (context.visited.has(url.href)) contexts.push(context)
933
+ }
934
+
935
+ return contexts.length === 0 ? [this._defaultContext] : contexts
936
+ }
937
+
938
+ _hostOf(url) {
939
+ for (const { host, visited } of this._contexts.values()) {
940
+ if (host !== null && visited.has(url.href)) return host
941
+ }
942
+
943
+ return null
944
+ }
945
+
946
+ _wasiFor(record) {
947
+ const { wasi } = record._source
948
+
949
+ if (wasi === null) return this._wasi === null ? null : this._wasi(record.url)
950
+
951
+ let provider = this._lookup(new URL(wasi))._evaluate()
952
+
953
+ if (typeof provider === 'object' && provider !== null) provider = provider.default
954
+
955
+ if (typeof provider !== 'function') {
956
+ throw new TypeError(`WASI provider '${wasi}' must export a function`)
957
+ }
958
+
959
+ return provider(record.url)
960
+ }
961
+
849
962
  _cacheResolution(parentURL, specifier, condition, url) {
850
963
  const imports = this._resolutions[parentURL.href]
851
964
 
@@ -856,22 +969,28 @@ module.exports = class ModuleLoader {
856
969
  imports[specifier] = { [condition]: url.href }
857
970
  }
858
971
 
859
- _resolveOptions() {
972
+ _resolveOptions(host, condition) {
860
973
  const opts = { resolutions: this._resolutions, engines: Bare.versions }
861
974
 
975
+ if (host !== null) {
976
+ opts.conditions = host.split('-')
977
+
978
+ if (condition === 'addon') opts.hosts = [host]
979
+ }
980
+
862
981
  if (this._builtins !== null) opts.builtins = Object.keys(this._builtins)
863
982
 
864
983
  return opts
865
984
  }
866
985
 
867
- _resolveSync(specifier, parentURL, condition) {
986
+ _resolveSync(specifier, parentURL, condition, host = this._hostOf(parentURL)) {
868
987
  const protocol = this._protocolFor(parentURL)
869
988
  const answers = this._answersFor(protocol)
870
989
 
871
990
  const resolver = traverse.resolve.bare(
872
991
  resolveEntry(specifier, condition),
873
992
  parentURL,
874
- this._resolveOptions()
993
+ this._resolveOptions(host, condition)
875
994
  )
876
995
 
877
996
  const candidates = []
@@ -909,9 +1028,11 @@ module.exports = class ModuleLoader {
909
1028
  if (existsSync(protocol, url, condition, answers)) {
910
1029
  const resolution = protocol.resolveSync(url)
911
1030
 
912
- this._cacheResolution(parentURL, specifier, condition, resolution)
1031
+ if (condition !== 'addon' || isLoadable(resolution)) {
1032
+ this._cacheResolution(parentURL, specifier, condition, resolution)
913
1033
 
914
- return resolution
1034
+ return resolution
1035
+ }
915
1036
  }
916
1037
 
917
1038
  next = resolver.next(false)
@@ -921,13 +1042,13 @@ module.exports = class ModuleLoader {
921
1042
  throw notFound(condition, specifier, parentURL, candidates)
922
1043
  }
923
1044
 
924
- async _resolve(specifier, parentURL, condition) {
1045
+ async _resolve(specifier, parentURL, condition, host = this._hostOf(parentURL)) {
925
1046
  const protocol = this._protocolFor(parentURL)
926
1047
 
927
1048
  const resolver = traverse.resolve.bare(
928
1049
  resolveEntry(specifier, condition),
929
1050
  parentURL,
930
- this._resolveOptions()
1051
+ this._resolveOptions(host, condition)
931
1052
  )
932
1053
 
933
1054
  const candidates = []
@@ -975,9 +1096,11 @@ module.exports = class ModuleLoader {
975
1096
 
976
1097
  if (isThenable(resolution)) resolution = await resolution
977
1098
 
978
- this._cacheResolution(parentURL, specifier, condition, resolution)
1099
+ if (condition !== 'addon' || isLoadable(resolution)) {
1100
+ this._cacheResolution(parentURL, specifier, condition, resolution)
979
1101
 
980
- return resolution
1102
+ return resolution
1103
+ }
981
1104
  }
982
1105
 
983
1106
  next = resolver.next(false)
@@ -995,7 +1118,7 @@ module.exports = class ModuleLoader {
995
1118
 
996
1119
  parentURL = parentURLFor(referrer, parentURL)
997
1120
 
998
- const url = this._resolveSync(specifier, parentURL, condition)
1121
+ const url = this._resolveSync(specifier, parentURL, condition, this._hostOf(referrer.url))
999
1122
 
1000
1123
  const attributes = opts && opts.with
1001
1124
 
@@ -1007,36 +1130,36 @@ module.exports = class ModuleLoader {
1007
1130
  lex.constants.RESOLVE |
1008
1131
  (condition === 'require' ? lex.constants.REQUIRE : lex.constants.IMPORT)
1009
1132
 
1010
- this._linkResolved(url, parentURL, attributes, importType)
1133
+ this._linkForSync(url, parentURL, attributes, importType)
1011
1134
  }
1012
1135
 
1013
1136
  return url
1014
1137
  }
1015
1138
 
1016
- _linkResolved(url, parentURL, attributes, importType) {
1017
- if (this._lookup(url) !== null) return
1139
+ _resolveAttributeSync(attributes, name, parentURL) {
1140
+ if (!hasAttribute(attributes, name)) return attributes
1018
1141
 
1019
- attributes = this._resolveAttributesSync(attributes, parentURL)
1142
+ const url =
1143
+ this._resolveRecorded(attributes[name], parentURL) ||
1144
+ this._resolveSync(attributes[name], parentURL, 'default')
1020
1145
 
1021
- this._linkSync(this._root(url, null, { attributes, importType }), this._protocolFor(url))
1022
-
1023
- this._instantiate()
1146
+ return { ...attributes, [name]: url.href }
1024
1147
  }
1025
1148
 
1026
- _resolveAttributesSync(attributes, parentURL) {
1027
- if (!hasImportsAttribute(attributes)) return attributes
1149
+ async _resolveAttribute(attributes, name, parentURL) {
1150
+ if (!hasAttribute(attributes, name)) return attributes
1028
1151
 
1029
- const url = this._resolveSync(attributes.imports, parentURL, 'default')
1152
+ const url =
1153
+ this._resolveRecorded(attributes[name], parentURL) ||
1154
+ (await this._resolve(attributes[name], parentURL, 'default'))
1030
1155
 
1031
- return { ...attributes, imports: url.href }
1156
+ return { ...attributes, [name]: url.href }
1032
1157
  }
1033
1158
 
1034
- async _resolveAttributes(attributes, parentURL) {
1035
- if (!hasImportsAttribute(attributes)) return attributes
1159
+ _resolveRecorded(specifier, parentURL) {
1160
+ const parent = this._lookup(parentURL)
1036
1161
 
1037
- const url = await this._resolve(attributes.imports, parentURL, 'default')
1038
-
1039
- return { ...attributes, imports: url.href }
1162
+ return parent === null ? null : parent._resolve(specifier, 'default')
1040
1163
  }
1041
1164
 
1042
1165
  _resolveArtifact(referrer, specifier, condition, parentURL) {
@@ -1044,13 +1167,43 @@ module.exports = class ModuleLoader {
1044
1167
 
1045
1168
  const url = parentURL === referrer.url ? referrer._resolve(specifier, condition) : null
1046
1169
 
1047
- return url === null ? this._resolveSync(specifier, parentURL, condition) : url
1170
+ if (url !== null) return url
1171
+
1172
+ if (condition === 'addon') return this._resolveAddon(referrer, specifier, parentURL)
1173
+
1174
+ return this._resolveSync(specifier, parentURL, condition, this._hostOf(referrer.url))
1175
+ }
1176
+
1177
+ _resolveAddon(referrer, specifier, parentURL) {
1178
+ const contexts = this._contextsOf(referrer.url)
1179
+
1180
+ if (contexts.length > 1) {
1181
+ throw errors.ADDON_HOST_INCOMPATIBLE(
1182
+ `Cannot resolve addon '${specifier}' from '${referrer.url.href}', which is linked in several contexts`
1183
+ )
1184
+ }
1185
+
1186
+ const [context] = contexts
1187
+
1188
+ const url = this._resolveSync(specifier, parentURL, 'addon', context.host)
1189
+
1190
+ const imports = this._resolutions[referrer.url.href]
1191
+
1192
+ traverse.assertAddonContext(
1193
+ url,
1194
+ (imports && imports['#package']) || referrer.url.href,
1195
+ context,
1196
+ this._addonContexts
1197
+ )
1198
+
1199
+ return url
1048
1200
  }
1049
1201
 
1050
1202
  _addon(referrer, specifier, parentURL) {
1051
1203
  const url = this._resolveArtifact(referrer, specifier, 'addon', parentURL)
1052
1204
 
1053
- const record = this._lookup(url) || this._addonRecord(url)
1205
+ const record =
1206
+ this._lookup(url) || this._addonRecord(url, this._contextsOf(referrer.url)[0].wasi)
1054
1207
 
1055
1208
  return record._evaluate()
1056
1209
  }
@@ -1155,6 +1308,7 @@ function claimCache(loader) {
1155
1308
  const graph = {
1156
1309
  protocol: loader._protocol,
1157
1310
  builtins: loader._builtins,
1311
+ wasi: loader._wasi,
1158
1312
  patches: null,
1159
1313
  reader: loader._protocol
1160
1314
  }
@@ -1172,6 +1326,10 @@ function claimCache(loader) {
1172
1326
  throw errors.CACHE_INCOMPATIBLE('Cache is read with different builtins')
1173
1327
  }
1174
1328
 
1329
+ if (owner.wasi !== loader._wasi) {
1330
+ throw errors.CACHE_INCOMPATIBLE('Cache is read with different WASI capabilities')
1331
+ }
1332
+
1175
1333
  return owner
1176
1334
  }
1177
1335
 
@@ -1187,6 +1345,12 @@ function assertCompatible(loader, href, record) {
1187
1345
  if (other._builtins !== loader._builtins) {
1188
1346
  throw errors.CACHE_INCOMPATIBLE(`Cache holds '${href}', which was read with different builtins`)
1189
1347
  }
1348
+
1349
+ if (other._wasi !== loader._wasi) {
1350
+ throw errors.CACHE_INCOMPATIBLE(
1351
+ `Cache holds '${href}', which was read with different WASI capabilities`
1352
+ )
1353
+ }
1190
1354
  }
1191
1355
 
1192
1356
  function readSync(protocol, url, answers = null) {
@@ -1423,9 +1587,9 @@ function isOptions(value) {
1423
1587
  return typeof value === 'object' && value !== null && !URL.isURL(value)
1424
1588
  }
1425
1589
 
1426
- function hasImportsAttribute(attributes) {
1590
+ function hasAttribute(attributes, name) {
1427
1591
  return (
1428
- typeof attributes === 'object' && attributes !== null && typeof attributes.imports === 'string'
1592
+ typeof attributes === 'object' && attributes !== null && typeof attributes[name] === 'string'
1429
1593
  )
1430
1594
  }
1431
1595
 
@@ -1437,6 +1601,13 @@ function isTerminalResolution(url, condition) {
1437
1601
  return protocol === 'linked:' && condition === 'addon'
1438
1602
  }
1439
1603
 
1604
+ // Once sealed, only native addons that were already loaded can be loaded.
1605
+ function isLoadable(url) {
1606
+ if (url.pathname.endsWith('.wasm') || Bare.Addon.sealed !== true) return true
1607
+
1608
+ return Bare.Addon.loaded(url)
1609
+ }
1610
+
1440
1611
  function isThenable(value) {
1441
1612
  return value !== null && typeof value === 'object' && typeof value.then === 'function'
1442
1613
  }
@@ -1,7 +1,14 @@
1
+ const instantiate = require('bare-wasm-abi')
1
2
  const SyntheticModule = require('./synthetic')
2
3
 
3
4
  module.exports = class AddonModule extends SyntheticModule {
4
5
  _execute() {
5
- this.exports = new Bare.Addon(this.url).exports
6
+ if (this.url.pathname.endsWith('.wasm')) {
7
+ this.exports = instantiate(this._source.bytes || this.protocol.readSync(this.url), {
8
+ wasi: this._loader._wasiFor(this)
9
+ })
10
+ } else {
11
+ this.exports = new Bare.Addon(this.url).exports
12
+ }
6
13
  }
7
14
  }
@@ -27,7 +27,7 @@ module.exports = class BundleModule extends SyntheticModule {
27
27
  return bundle
28
28
  }
29
29
 
30
- _mount() {
30
+ _mountSync() {
31
31
  if (this._linked) return
32
32
 
33
33
  if (this._open().main) this._loader._linkBundleSync(this._bundle)
@@ -35,17 +35,17 @@ module.exports = class BundleModule extends SyntheticModule {
35
35
  this._linked = true
36
36
  }
37
37
 
38
- _mountAsync() {
39
- if (this._linking === null) this._linking = this._linkAsync()
38
+ _mount() {
39
+ if (this._linking === null) this._linking = this._link()
40
40
 
41
41
  return this._linking
42
42
  }
43
43
 
44
44
  _ensureMounted() {
45
- if (this._linking === null) this._mount()
45
+ if (this._linking === null) this._mountSync()
46
46
  }
47
47
 
48
- async _linkAsync() {
48
+ async _link() {
49
49
  if (this._open().main) await this._loader._linkBundle(this._bundle)
50
50
 
51
51
  this._linked = true
package/lib/module.js CHANGED
@@ -9,7 +9,7 @@ const { REEXPORT, ADDON, ASSET } = lex.constants
9
9
 
10
10
  const DEFERRED_PROTOCOL = 'deferred:'
11
11
 
12
- const hostConditions = ['bare', 'node', ...Bare.Addon.host.split('-')]
12
+ const nativeConditions = Bare.Addon.host.split('-')
13
13
 
14
14
  const UNLINKED = 0
15
15
  const LINKED = 1
@@ -101,7 +101,10 @@ module.exports = exports = class Module {
101
101
 
102
102
  if (entry === undefined) return null
103
103
 
104
- const href = pickCondition(entry, condition)
104
+ const href =
105
+ typeof entry === 'string'
106
+ ? entry
107
+ : pickCondition(entry, conditionsFor(condition, this._loader._hostOf(this.url)))
105
108
 
106
109
  if (href === null) return null
107
110
 
@@ -279,18 +282,13 @@ async function ondynamicimport(specifier, attributes, referrerName, id) {
279
282
 
280
283
  let url = referrer._resolve(specifier, 'import')
281
284
 
282
- let record = loader._lookup(url)
285
+ if (loader._lookup(url) === null) url = await loader._resolve(specifier, referrer.url, 'import')
283
286
 
284
- if (record === null) {
285
- url = await loader._resolve(specifier, referrer.url, 'import')
287
+ await loader._linkFor(url, referrer.url, attributes, lex.constants.IMPORT | lex.constants.DYNAMIC)
286
288
 
287
- record = await loader.link(url, null, {
288
- attributes: await loader._resolveAttributes(attributes, referrer.url),
289
- importType: lex.constants.IMPORT | lex.constants.DYNAMIC
290
- })
291
- } else {
292
- record._instantiate()
293
- }
289
+ const record = loader._lookup(url)
290
+
291
+ record._instantiate()
294
292
 
295
293
  loader._assertType(record, attributes)
296
294
 
@@ -370,13 +368,30 @@ function onrun(reason, promise, err = reason) {
370
368
  }
371
369
  }
372
370
 
373
- function pickCondition(entry, condition) {
371
+ function conditionsFor(condition, host) {
372
+ const base = [condition, 'bare', 'node']
373
+
374
+ if (host === null) {
375
+ return [
376
+ [...base, ...nativeConditions],
377
+ [...base, 'wasi', 'wasm32']
378
+ ]
379
+ }
380
+
381
+ if (condition === 'addon') return [[...base, ...host.split('-')]]
382
+
383
+ return [[...base, ...nativeConditions, ...host.split('-')]]
384
+ }
385
+
386
+ function pickCondition(entry, conditions) {
374
387
  if (typeof entry === 'string') return entry
375
388
 
376
389
  if (entry === null || typeof entry !== 'object') return null
377
390
 
378
- for (const [, target] of conditionMatches(entry, [condition, ...hostConditions])) {
379
- return pickCondition(target, condition)
391
+ for (const [, target, subset] of conditionMatches(entry, conditions)) {
392
+ const href = pickCondition(target, subset)
393
+
394
+ if (href !== null) return href
380
395
  }
381
396
 
382
397
  return null
package/lib/source.js CHANGED
@@ -6,6 +6,7 @@ module.exports = class ModuleSource {
6
6
  this.bytes = toBuffer(dependency.source)
7
7
  this.imports = dependency.imports
8
8
  this.lexer = dependency.lexer
9
+ this.wasi = dependency.wasi || null
9
10
  }
10
11
 
11
12
  get exports() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bare-module",
3
- "version": "7.3.0",
3
+ "version": "7.5.0",
4
4
  "description": "The module system that powers Bare",
5
5
  "exports": {
6
6
  "./package": "./package.json",
@@ -43,16 +43,17 @@
43
43
  },
44
44
  "homepage": "https://github.com/holepunchto/bare-module#readme",
45
45
  "engines": {
46
- "bare": ">=1.32.0"
46
+ "bare": ">=1.35.0"
47
47
  },
48
48
  "dependencies": {
49
49
  "bare-bundle": "^1.11.0",
50
50
  "bare-module-lexer": "^1.7.0",
51
51
  "bare-module-resolve": "^1.12.6",
52
- "bare-module-traverse": "~2.6.0",
52
+ "bare-module-traverse": "~2.7.0",
53
53
  "bare-path": "^3.0.0",
54
54
  "bare-type-stripper": "^0.1.2",
55
55
  "bare-url": "^2.0.1",
56
+ "bare-wasm-abi": "^0.1.0",
56
57
  "promaphore": "^1.0.0"
57
58
  },
58
59
  "devDependencies": {