@tybys/wasm-util 0.4.0 → 0.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.
@@ -90,18 +90,20 @@ export class Asyncify {
90
90
  }
91
91
  }
92
92
  wrapImportFunction(f) {
93
- return ((...args) => {
93
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
94
+ const _this = this;
95
+ return (function () {
94
96
  // eslint-disable-next-line no-unreachable-loop
95
- while (this.exports.asyncify_get_state() === AsyncifyState.REWINDING) {
96
- this.exports.asyncify_stop_rewind();
97
- return this.value;
97
+ while (_this.exports.asyncify_get_state() === AsyncifyState.REWINDING) {
98
+ _this.exports.asyncify_stop_rewind();
99
+ return _this.value;
98
100
  }
99
- this.assertState();
100
- const v = f(...args);
101
+ _this.assertState();
102
+ const v = f.apply(this, arguments);
101
103
  if (!isPromiseLike(v))
102
104
  return v;
103
- this.exports.asyncify_start_unwind(this.dataPtr);
104
- this.value = v;
105
+ _this.exports.asyncify_start_unwind(_this.dataPtr);
106
+ _this.value = v;
105
107
  });
106
108
  }
107
109
  wrapImports(imports) {
@@ -123,17 +125,19 @@ export class Asyncify {
123
125
  return importObject;
124
126
  }
125
127
  wrapExportFunction(f) {
126
- return (async (...args) => {
127
- this.assertState();
128
- let ret = f(...args);
129
- while (this.exports.asyncify_get_state() === AsyncifyState.UNWINDING) {
130
- this.exports.asyncify_stop_unwind();
131
- this.value = await this.value;
132
- this.assertState();
133
- this.exports.asyncify_start_rewind(this.dataPtr);
134
- ret = f();
128
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
129
+ const _this = this;
130
+ return (async function () {
131
+ _this.assertState();
132
+ let ret = f.apply(this, arguments);
133
+ while (_this.exports.asyncify_get_state() === AsyncifyState.UNWINDING) {
134
+ _this.exports.asyncify_stop_unwind();
135
+ _this.value = await _this.value;
136
+ _this.assertState();
137
+ _this.exports.asyncify_start_rewind(_this.dataPtr);
138
+ ret = f.call(this);
135
139
  }
136
- this.assertState();
140
+ _this.assertState();
137
141
  return ret;
138
142
  });
139
143
  }
package/lib/mjs/load.mjs CHANGED
@@ -1,5 +1,10 @@
1
1
  import { _WebAssembly } from "./webassembly.mjs";
2
2
  import { Asyncify } from "./asyncify.mjs";
3
+ function validateImports(imports) {
4
+ if (imports && typeof imports !== 'object') {
5
+ throw new TypeError('imports must be an object or undefined');
6
+ }
7
+ }
3
8
  async function fetchWasm(urlOrBuffer, imports) {
4
9
  if (typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') {
5
10
  return await _WebAssembly.instantiate(urlOrBuffer, imports);
@@ -10,24 +15,12 @@ async function fetchWasm(urlOrBuffer, imports) {
10
15
  return source;
11
16
  }
12
17
  /** @public */
13
- export async function load(urlOrBuffer, imports, asyncify) {
14
- var _a, _b;
15
- if (imports && typeof imports !== 'object') {
16
- throw new TypeError('imports must be an object or undefined');
17
- }
18
+ export async function load(urlOrBuffer, imports) {
19
+ validateImports(imports);
18
20
  imports = imports !== null && imports !== void 0 ? imports : {};
19
- let asyncifyHelper;
20
21
  let source;
21
- if (asyncify) {
22
- asyncifyHelper = new Asyncify();
23
- imports = asyncifyHelper.wrapImports(imports);
24
- }
25
22
  if (urlOrBuffer instanceof ArrayBuffer || ArrayBuffer.isView(urlOrBuffer)) {
26
23
  source = await _WebAssembly.instantiate(urlOrBuffer, imports);
27
- if (asyncify) {
28
- const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory);
29
- return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) };
30
- }
31
24
  return source;
32
25
  }
33
26
  if (typeof urlOrBuffer !== 'string' && !(urlOrBuffer instanceof URL)) {
@@ -44,33 +37,39 @@ export async function load(urlOrBuffer, imports, asyncify) {
44
37
  else {
45
38
  source = await fetchWasm(urlOrBuffer, imports);
46
39
  }
47
- if (asyncify) {
48
- const memory = source.instance.exports.memory || ((_b = imports.env) === null || _b === void 0 ? void 0 : _b.memory);
49
- return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) };
50
- }
51
40
  return source;
52
41
  }
53
42
  /** @public */
54
- export function loadSync(buffer, imports, asyncify) {
43
+ export async function asyncifyLoad(asyncify, urlOrBuffer, imports) {
55
44
  var _a;
45
+ validateImports(imports);
46
+ imports = imports !== null && imports !== void 0 ? imports : {};
47
+ const asyncifyHelper = new Asyncify();
48
+ imports = asyncifyHelper.wrapImports(imports);
49
+ const source = await load(urlOrBuffer, imports);
50
+ const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory);
51
+ return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) };
52
+ }
53
+ /** @public */
54
+ export function loadSync(buffer, imports) {
56
55
  if ((buffer instanceof ArrayBuffer) && !ArrayBuffer.isView(buffer)) {
57
56
  throw new TypeError('Invalid source');
58
57
  }
59
- if (imports && typeof imports !== 'object') {
60
- throw new TypeError('imports must be an object or undefined');
61
- }
58
+ validateImports(imports);
62
59
  imports = imports !== null && imports !== void 0 ? imports : {};
63
- let asyncifyHelper;
64
- if (asyncify) {
65
- asyncifyHelper = new Asyncify();
66
- imports = asyncifyHelper.wrapImports(imports);
67
- }
68
60
  const module = new _WebAssembly.Module(buffer);
69
61
  const instance = new _WebAssembly.Instance(module, imports);
70
62
  const source = { instance, module };
71
- if (asyncify) {
72
- const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory);
73
- return { module: source.module, instance: asyncifyHelper.init(memory, instance, asyncify) };
74
- }
75
63
  return source;
76
64
  }
65
+ /** @public */
66
+ export function asyncifyLoadSync(asyncify, buffer, imports) {
67
+ var _a;
68
+ validateImports(imports);
69
+ imports = imports !== null && imports !== void 0 ? imports : {};
70
+ const asyncifyHelper = new Asyncify();
71
+ imports = asyncifyHelper.wrapImports(imports);
72
+ const source = loadSync(buffer, imports);
73
+ const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory);
74
+ return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) };
75
+ }
@@ -112,7 +112,6 @@ export class FileDescriptorTable {
112
112
  this.size = options.size;
113
113
  this.fds = Array(options.size);
114
114
  this.stdio = [options.in, options.out, options.err];
115
- this.fs = options.fs;
116
115
  this.print = options.print;
117
116
  this.printErr = options.printErr;
118
117
  this.insertStdio(options.in, 0, '<stdin>');
@@ -159,18 +158,6 @@ export class FileDescriptorTable {
159
158
  this.used++;
160
159
  return entry;
161
160
  }
162
- getFileTypeByFd(fd) {
163
- const stat = this.fs.fstatSync(fd);
164
- return toFileType(stat);
165
- }
166
- insertPreopen(fd, mappedPath, realPath) {
167
- const type = this.getFileTypeByFd(fd);
168
- if (type !== WasiFileType.DIRECTORY) {
169
- throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, WasiErrno.ENOTDIR);
170
- }
171
- const result = getRights(this.stdio, fd, 0, type);
172
- return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1);
173
- }
174
161
  get(id, base, inheriting) {
175
162
  if (id >= this.size) {
176
163
  throw new WasiError('Invalid fd', WasiErrno.EBADF);
@@ -196,6 +183,24 @@ export class FileDescriptorTable {
196
183
  this.fds[id] = undefined;
197
184
  this.used--;
198
185
  }
186
+ }
187
+ export class SyncTable extends FileDescriptorTable {
188
+ constructor(options) {
189
+ super(options);
190
+ this.fs = options.fs;
191
+ }
192
+ getFileTypeByFd(fd) {
193
+ const stats = this.fs.fstatSync(fd, { bigint: true });
194
+ return toFileType(stats);
195
+ }
196
+ insertPreopen(fd, mappedPath, realPath) {
197
+ const type = this.getFileTypeByFd(fd);
198
+ if (type !== WasiFileType.DIRECTORY) {
199
+ throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, WasiErrno.ENOTDIR);
200
+ }
201
+ const result = getRights(this.stdio, fd, 0, type);
202
+ return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1);
203
+ }
199
204
  renumber(dst, src) {
200
205
  if (dst === src)
201
206
  return;
@@ -214,3 +219,38 @@ export class FileDescriptorTable {
214
219
  this.used--;
215
220
  }
216
221
  }
222
+ export class AsyncTable extends FileDescriptorTable {
223
+ // eslint-disable-next-line @typescript-eslint/no-useless-constructor
224
+ constructor(options) {
225
+ super(options);
226
+ }
227
+ async getFileTypeByFd(fd) {
228
+ const stats = await fd.stat({ bigint: true });
229
+ return toFileType(stats);
230
+ }
231
+ async insertPreopen(fd, mappedPath, realPath) {
232
+ const type = await this.getFileTypeByFd(fd);
233
+ if (type !== WasiFileType.DIRECTORY) {
234
+ throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, WasiErrno.ENOTDIR);
235
+ }
236
+ const result = getRights(this.stdio, fd.fd, 0, type);
237
+ return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1);
238
+ }
239
+ async renumber(dst, src) {
240
+ if (dst === src)
241
+ return;
242
+ if (dst >= this.size || src >= this.size) {
243
+ throw new WasiError('Invalid fd', WasiErrno.EBADF);
244
+ }
245
+ const dstEntry = this.fds[dst];
246
+ const srcEntry = this.fds[src];
247
+ if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) {
248
+ throw new WasiError('Invalid fd', WasiErrno.EBADF);
249
+ }
250
+ await dstEntry.fd.close();
251
+ this.fds[dst] = this.fds[src];
252
+ this.fds[dst].id = dst;
253
+ this.fds[src] = undefined;
254
+ this.used--;
255
+ }
256
+ }
@@ -1,5 +1,5 @@
1
1
  import { WASI as _WASI } from "./preview1.mjs";
2
- import { validateObject, validateArray, validateBoolean, validateFunction, validateUndefined, validateString } from "./util.mjs";
2
+ import { validateObject, validateArray, validateBoolean, validateFunction, validateUndefined } from "./util.mjs";
3
3
  const kEmptyObject = Object.freeze(Object.create(null));
4
4
  const kExitCode = Symbol('kExitCode');
5
5
  const kSetMemory = Symbol('kSetMemory');
@@ -13,74 +13,105 @@ function setupInstance(self, instance) {
13
13
  }
14
14
  // /** @public */
15
15
  // export type WasiSnapshotPreview1 = Omit<_WASI, '_setMemory'>
16
- /** @public */
17
- export class WASI {
18
- constructor(options = kEmptyObject) {
19
- var _a;
20
- validateObject(options, 'options');
21
- if (options.args !== undefined) {
22
- validateArray(options.args, 'options.args');
23
- }
24
- const args = ((_a = options.args) !== null && _a !== void 0 ? _a : []).map(String);
25
- const env = [];
26
- if (options.env !== undefined) {
27
- validateObject(options.env, 'options.env');
28
- Object.entries(options.env).forEach(({ 0: key, 1: value }) => {
29
- if (value !== undefined) {
30
- env.push(`${key}=${value}`);
31
- }
32
- });
33
- }
34
- const preopens = [];
35
- if (options.preopens !== undefined) {
36
- validateObject(options.preopens, 'options.preopens');
37
- Object.entries(options.preopens).forEach(({ 0: key, 1: value }) => preopens.push({ mappedPath: String(key), realPath: String(value) }));
38
- }
39
- if (preopens.length > 0) {
40
- if (options.filesystem === undefined) {
41
- throw new Error('filesystem is disabled, can not preopen directory');
16
+ function validateOptions(options) {
17
+ var _a;
18
+ validateObject(options, 'options');
19
+ if (options.args !== undefined) {
20
+ validateArray(options.args, 'options.args');
21
+ }
22
+ const args = ((_a = options.args) !== null && _a !== void 0 ? _a : []).map(String);
23
+ const env = [];
24
+ if (options.env !== undefined) {
25
+ validateObject(options.env, 'options.env');
26
+ Object.entries(options.env).forEach(({ 0: key, 1: value }) => {
27
+ if (value !== undefined) {
28
+ env.push(`${key}=${value}`);
42
29
  }
30
+ });
31
+ }
32
+ const preopens = [];
33
+ if (options.preopens !== undefined) {
34
+ validateObject(options.preopens, 'options.preopens');
35
+ Object.entries(options.preopens).forEach(({ 0: key, 1: value }) => preopens.push({ mappedPath: String(key), realPath: String(value) }));
36
+ }
37
+ if (preopens.length > 0) {
38
+ if (options.fs === undefined) {
39
+ throw new Error('filesystem is disabled, can not preopen directory');
43
40
  }
44
- if (options.filesystem !== undefined) {
45
- validateObject(options.filesystem, 'options.filesystem');
46
- validateString(options.filesystem.type, 'options.filesystem.type');
47
- if (options.filesystem.type !== 'memfs') {
48
- throw new Error(`Filesystem type ${options.filesystem.type} is not supported, only "memfs" is supported currently`);
49
- }
50
- try {
51
- validateObject(options.filesystem.fs, 'options.filesystem.fs');
52
- }
53
- catch (_) {
54
- throw new Error('Node.js fs like implementation is not provided');
55
- }
41
+ try {
42
+ validateObject(options.fs, 'options.fs');
56
43
  }
57
- if (options.print !== undefined)
58
- validateFunction(options.print, 'options.print');
59
- if (options.printErr !== undefined)
60
- validateFunction(options.printErr, 'options.printErr');
61
- // const { stdin = 0, stdout = 1, stderr = 2 } = options
62
- // validateInt32(stdin, 'options.stdin', 0)
63
- // validateInt32(stdout, 'options.stdout', 0)
64
- // validateInt32(stderr, 'options.stderr', 0)
65
- // const stdio = [stdin, stdout, stderr] as const
66
- const stdio = [0, 1, 2];
67
- const wrap = new _WASI(args, env, preopens, stdio, options.filesystem, options.print, options.printErr);
68
- for (const prop in wrap) {
69
- wrap[prop] = wrap[prop].bind(wrap);
44
+ catch (_) {
45
+ throw new TypeError('Node.js fs like implementation is not provided');
70
46
  }
71
- if (options.returnOnExit !== undefined) {
72
- validateBoolean(options.returnOnExit, 'options.returnOnExit');
73
- if (options.returnOnExit) {
74
- wrap.proc_exit = wasiReturnOnProcExit.bind(this);
75
- }
76
- }
77
- this[kSetMemory] = wrap._setMemory;
78
- delete wrap._setMemory;
47
+ }
48
+ // if (options.filesystem !== undefined) {
49
+ // validateObject(options.filesystem, 'options.filesystem')
50
+ // validateString(options.filesystem.type, 'options.filesystem.type')
51
+ // if (options.filesystem.type !== 'memfs' && options.filesystem.type !== 'file-system-access-api') {
52
+ // throw new Error(`Filesystem type ${(options.filesystem as any).type as string} is not supported, only "memfs" and "file-system-access-api" is supported currently`)
53
+ // }
54
+ // try {
55
+ // validateObject(options.filesystem.fs, 'options.filesystem.fs')
56
+ // } catch (_) {
57
+ // throw new Error('Node.js fs like implementation is not provided')
58
+ // }
59
+ // }
60
+ if (options.print !== undefined)
61
+ validateFunction(options.print, 'options.print');
62
+ if (options.printErr !== undefined)
63
+ validateFunction(options.printErr, 'options.printErr');
64
+ if (options.returnOnExit !== undefined) {
65
+ validateBoolean(options.returnOnExit, 'options.returnOnExit');
66
+ }
67
+ // const { stdin = 0, stdout = 1, stderr = 2 } = options
68
+ // validateInt32(stdin, 'options.stdin', 0)
69
+ // validateInt32(stdout, 'options.stdout', 0)
70
+ // validateInt32(stderr, 'options.stderr', 0)
71
+ // const stdio = [stdin, stdout, stderr] as const
72
+ const stdio = [0, 1, 2];
73
+ return {
74
+ args,
75
+ env,
76
+ preopens,
77
+ stdio
78
+ };
79
+ }
80
+ /** @public */
81
+ export class WASI {
82
+ constructor(setMemory, wrap) {
83
+ this[kSetMemory] = setMemory;
79
84
  this.wasiImport = wrap;
80
85
  this[kStarted] = false;
81
86
  this[kExitCode] = 0;
82
87
  this[kInstance] = undefined;
83
88
  }
89
+ static createSync(options = kEmptyObject) {
90
+ const { args, env, preopens, stdio } = validateOptions(options);
91
+ const wrap = _WASI.createSync(args, env, preopens, stdio, options.fs, options.print, options.printErr);
92
+ const setMemory = wrap._setMemory;
93
+ delete wrap._setMemory;
94
+ const _this = new WASI(setMemory, wrap);
95
+ if (options.returnOnExit) {
96
+ wrap.proc_exit = wasiReturnOnProcExit.bind(_this);
97
+ }
98
+ return _this;
99
+ }
100
+ static async createAsync(options = kEmptyObject) {
101
+ const { args, env, preopens, stdio } = validateOptions(options);
102
+ if (options.asyncify !== undefined) {
103
+ validateObject(options.asyncify, 'options.asyncify');
104
+ validateFunction(options.asyncify.wrapImportFunction, 'options.asyncify.wrapImportFunction');
105
+ }
106
+ const wrap = await _WASI.createAsync(args, env, preopens, stdio, options.fs, options.print, options.printErr, options.asyncify);
107
+ const setMemory = wrap._setMemory;
108
+ delete wrap._setMemory;
109
+ const _this = new WASI(setMemory, wrap);
110
+ if (options.returnOnExit) {
111
+ wrap.proc_exit = wasiReturnOnProcExit.bind(_this);
112
+ }
113
+ return _this;
114
+ }
84
115
  // Must not export _initialize, must export _start
85
116
  start(instance) {
86
117
  if (this[kStarted]) {