@ruby/head-wasm-wasi 2.4.1 → 2.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/dist/index.umd.js CHANGED
@@ -2,1348 +2,1381 @@ console.warn(`DEPRECATED(ruby-head-wasm-wasi): "dist/index.umd" will be mov
2
2
  Please replace your \`require('ruby-head-wasm-wasi/dist/index.umd');\` with \`require('@ruby/wasm-wasi/dist/index.umd');\``);
3
3
 
4
4
  (function (global, factory) {
5
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
6
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
7
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["ruby-wasm-wasi"] = {}));
5
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
6
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
7
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["ruby-wasm-wasi"] = {}));
8
8
  })(this, (function (exports) { 'use strict';
9
9
 
10
- let DATA_VIEW = new DataView(new ArrayBuffer());
11
-
12
- function data_view(mem) {
13
- if (DATA_VIEW.buffer !== mem.buffer) DATA_VIEW = new DataView(mem.buffer);
14
- return DATA_VIEW;
15
- }
16
-
17
- function to_uint32(val) {
18
- return val >>> 0;
19
- }
20
- const UTF8_DECODER = new TextDecoder('utf-8');
10
+ /**
11
+ * Create a console printer that can be used as an overlay of WASI imports.
12
+ * See the example below for how to use it.
13
+ *
14
+ * ```javascript
15
+ * const imports = {
16
+ * "wasi_snapshot_preview1": wasi.wasiImport,
17
+ * }
18
+ * const printer = consolePrinter();
19
+ * printer.addToImports(imports);
20
+ *
21
+ * const instance = await WebAssembly.instantiate(module, imports);
22
+ * printer.setMemory(instance.exports.memory);
23
+ * ```
24
+ *
25
+ * Note that the `stdout` and `stderr` functions are called with text, not
26
+ * bytes. This means that bytes written to stdout/stderr will be decoded as
27
+ * UTF-8 and then passed to the `stdout`/`stderr` functions every time a write
28
+ * occurs without buffering.
29
+ *
30
+ * @param stdout A function that will be called when stdout is written to.
31
+ * Defaults to `console.log`.
32
+ * @param stderr A function that will be called when stderr is written to.
33
+ * Defaults to `console.warn`.
34
+ * @returns An object that can be used as an overlay of WASI imports.
35
+ */
36
+ function consolePrinter({ stdout, stderr, } = {
37
+ stdout: console.log,
38
+ stderr: console.warn,
39
+ }) {
40
+ let memory = undefined;
41
+ let _view = undefined;
42
+ function getMemoryView() {
43
+ if (typeof memory === "undefined") {
44
+ throw new Error("Memory is not set");
45
+ }
46
+ if (_view === undefined || _view.buffer.byteLength === 0) {
47
+ _view = new DataView(memory.buffer);
48
+ }
49
+ return _view;
50
+ }
51
+ const decoder = new TextDecoder();
52
+ return {
53
+ addToImports(imports) {
54
+ const wasiImport = imports.wasi_snapshot_preview1;
55
+ const original_fd_write = wasiImport.fd_write;
56
+ wasiImport.fd_write = (fd, iovs, iovsLen, nwritten) => {
57
+ if (fd !== 1 && fd !== 2) {
58
+ return original_fd_write(fd, iovs, iovsLen, nwritten);
59
+ }
60
+ const view = getMemoryView();
61
+ const buffers = Array.from({ length: iovsLen }, (_, i) => {
62
+ const ptr = iovs + i * 8;
63
+ const buf = view.getUint32(ptr, true);
64
+ const bufLen = view.getUint32(ptr + 4, true);
65
+ return new Uint8Array(memory.buffer, buf, bufLen);
66
+ });
67
+ let written = 0;
68
+ let str = "";
69
+ for (const buffer of buffers) {
70
+ str += decoder.decode(buffer);
71
+ written += buffer.byteLength;
72
+ }
73
+ view.setUint32(nwritten, written, true);
74
+ const log = fd === 1 ? stdout : stderr;
75
+ log(str);
76
+ return 0;
77
+ };
78
+ const original_fd_filestat_get = wasiImport.fd_filestat_get;
79
+ wasiImport.fd_filestat_get = (fd, filestat) => {
80
+ if (fd !== 1 && fd !== 2) {
81
+ return original_fd_filestat_get(fd, filestat);
82
+ }
83
+ const view = getMemoryView();
84
+ const result = original_fd_filestat_get(fd, filestat);
85
+ if (result !== 0) {
86
+ return result;
87
+ }
88
+ const filetypePtr = filestat + 0;
89
+ view.setUint8(filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
90
+ return 0;
91
+ };
92
+ const original_fd_fdstat_get = wasiImport.fd_fdstat_get;
93
+ wasiImport.fd_fdstat_get = (fd, fdstat) => {
94
+ if (fd !== 1 && fd !== 2) {
95
+ return original_fd_fdstat_get(fd, fdstat);
96
+ }
97
+ const view = getMemoryView();
98
+ const fs_filetypePtr = fdstat + 0;
99
+ view.setUint8(fs_filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
100
+ const fs_rights_basePtr = fdstat + 8;
101
+ view.setBigUint64(fs_rights_basePtr, BigInt(1)); // RIGHTS_FD_WRITE
102
+ return 0;
103
+ };
104
+ },
105
+ setMemory(m) {
106
+ memory = m;
107
+ },
108
+ };
109
+ }
21
110
 
22
- const UTF8_ENCODER = new TextEncoder('utf-8');
111
+ let DATA_VIEW = new DataView(new ArrayBuffer());
23
112
 
24
- function utf8_encode(s, realloc, memory) {
25
- if (typeof s !== 'string') throw new TypeError('expected a string');
26
-
27
- if (s.length === 0) {
28
- UTF8_ENCODED_LEN = 0;
29
- return 1;
113
+ function data_view(mem) {
114
+ if (DATA_VIEW.buffer !== mem.buffer) DATA_VIEW = new DataView(mem.buffer);
115
+ return DATA_VIEW;
30
116
  }
31
-
32
- let alloc_len = 0;
33
- let ptr = 0;
34
- let writtenTotal = 0;
35
- while (s.length > 0) {
36
- ptr = realloc(ptr, alloc_len, 1, alloc_len + s.length);
37
- alloc_len += s.length;
38
- const { read, written } = UTF8_ENCODER.encodeInto(
39
- s,
40
- new Uint8Array(memory.buffer, ptr + writtenTotal, alloc_len - writtenTotal),
41
- );
42
- writtenTotal += written;
43
- s = s.slice(read);
44
- }
45
- if (alloc_len > writtenTotal)
46
- ptr = realloc(ptr, alloc_len, 1, writtenTotal);
47
- UTF8_ENCODED_LEN = writtenTotal;
48
- return ptr;
49
- }
50
- let UTF8_ENCODED_LEN = 0;
51
117
 
52
- class Slab {
53
- constructor() {
54
- this.list = [];
55
- this.head = 0;
56
- }
57
-
58
- insert(val) {
59
- if (this.head >= this.list.length) {
60
- this.list.push({
61
- next: this.list.length + 1,
62
- val: undefined,
63
- });
64
- }
65
- const ret = this.head;
66
- const slot = this.list[ret];
67
- this.head = slot.next;
68
- slot.next = -1;
69
- slot.val = val;
70
- return ret;
118
+ function to_uint32(val) {
119
+ return val >>> 0;
71
120
  }
72
-
73
- get(idx) {
74
- if (idx >= this.list.length)
75
- throw new RangeError('handle index not valid');
76
- const slot = this.list[idx];
77
- if (slot.next === -1)
78
- return slot.val;
79
- throw new RangeError('handle index not valid');
80
- }
81
-
82
- remove(idx) {
83
- const ret = this.get(idx); // validate the slot
84
- const slot = this.list[idx];
85
- slot.val = undefined;
86
- slot.next = this.head;
87
- this.head = idx;
88
- return ret;
89
- }
90
- }
121
+ const UTF8_DECODER = new TextDecoder('utf-8');
91
122
 
92
- function throw_invalid_bool() {
93
- throw new RangeError("invalid variant discriminant for bool");
94
- }
123
+ const UTF8_ENCODER = new TextEncoder('utf-8');
95
124
 
96
- class RbAbiGuest {
97
- constructor() {
98
- this._resource0_slab = new Slab();
99
- this._resource1_slab = new Slab();
100
- }
101
- addToImports(imports) {
102
- if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
125
+ function utf8_encode(s, realloc, memory) {
126
+ if (typeof s !== 'string') throw new TypeError('expected a string');
103
127
 
104
- imports.canonical_abi['resource_drop_rb-iseq'] = i => {
105
- this._resource0_slab.remove(i).drop();
106
- };
107
- imports.canonical_abi['resource_clone_rb-iseq'] = i => {
108
- const obj = this._resource0_slab.get(i);
109
- return this._resource0_slab.insert(obj.clone())
110
- };
111
- imports.canonical_abi['resource_get_rb-iseq'] = i => {
112
- return this._resource0_slab.get(i)._wasm_val;
113
- };
114
- imports.canonical_abi['resource_new_rb-iseq'] = i => {
115
- this._registry0;
116
- return this._resource0_slab.insert(new RbIseq(i, this));
117
- };
118
-
119
- imports.canonical_abi['resource_drop_rb-abi-value'] = i => {
120
- this._resource1_slab.remove(i).drop();
121
- };
122
- imports.canonical_abi['resource_clone_rb-abi-value'] = i => {
123
- const obj = this._resource1_slab.get(i);
124
- return this._resource1_slab.insert(obj.clone())
125
- };
126
- imports.canonical_abi['resource_get_rb-abi-value'] = i => {
127
- return this._resource1_slab.get(i)._wasm_val;
128
- };
129
- imports.canonical_abi['resource_new_rb-abi-value'] = i => {
130
- this._registry1;
131
- return this._resource1_slab.insert(new RbAbiValue(i, this));
132
- };
133
- }
134
-
135
- async instantiate(module, imports) {
136
- imports = imports || {};
137
- this.addToImports(imports);
128
+ if (s.length === 0) {
129
+ UTF8_ENCODED_LEN = 0;
130
+ return 1;
131
+ }
138
132
 
139
- if (module instanceof WebAssembly.Instance) {
140
- this.instance = module;
141
- } else if (module instanceof WebAssembly.Module) {
142
- this.instance = await WebAssembly.instantiate(module, imports);
143
- } else if (module instanceof ArrayBuffer || module instanceof Uint8Array) {
144
- const { instance } = await WebAssembly.instantiate(module, imports);
145
- this.instance = instance;
146
- } else {
147
- const { instance } = await WebAssembly.instantiateStreaming(module, imports);
148
- this.instance = instance;
133
+ let alloc_len = 0;
134
+ let ptr = 0;
135
+ let writtenTotal = 0;
136
+ while (s.length > 0) {
137
+ ptr = realloc(ptr, alloc_len, 1, alloc_len + s.length);
138
+ alloc_len += s.length;
139
+ const { read, written } = UTF8_ENCODER.encodeInto(
140
+ s,
141
+ new Uint8Array(memory.buffer, ptr + writtenTotal, alloc_len - writtenTotal),
142
+ );
143
+ writtenTotal += written;
144
+ s = s.slice(read);
149
145
  }
150
- this._exports = this.instance.exports;
151
- this._registry0 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-iseq']);
152
- this._registry1 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-abi-value']);
153
- }
154
- rubyShowVersion() {
155
- this._exports['ruby-show-version: func() -> ()']();
146
+ if (alloc_len > writtenTotal)
147
+ ptr = realloc(ptr, alloc_len, 1, writtenTotal);
148
+ UTF8_ENCODED_LEN = writtenTotal;
149
+ return ptr;
156
150
  }
157
- rubyInit() {
158
- this._exports['ruby-init: func() -> ()']();
159
- }
160
- rubySysinit(arg0) {
161
- const memory = this._exports.memory;
162
- const realloc = this._exports["cabi_realloc"];
163
- const vec1 = arg0;
164
- const len1 = vec1.length;
165
- const result1 = realloc(0, 0, 4, len1 * 8);
166
- for (let i = 0; i < vec1.length; i++) {
167
- const e = vec1[i];
168
- const base = result1 + i * 8;
169
- const ptr0 = utf8_encode(e, realloc, memory);
170
- const len0 = UTF8_ENCODED_LEN;
171
- data_view(memory).setInt32(base + 4, len0, true);
172
- data_view(memory).setInt32(base + 0, ptr0, true);
151
+ let UTF8_ENCODED_LEN = 0;
152
+
153
+ class Slab {
154
+ constructor() {
155
+ this.list = [];
156
+ this.head = 0;
173
157
  }
174
- this._exports['ruby-sysinit: func(args: list<string>) -> ()'](result1, len1);
175
- }
176
- rubyOptions(arg0) {
177
- const memory = this._exports.memory;
178
- const realloc = this._exports["cabi_realloc"];
179
- const vec1 = arg0;
180
- const len1 = vec1.length;
181
- const result1 = realloc(0, 0, 4, len1 * 8);
182
- for (let i = 0; i < vec1.length; i++) {
183
- const e = vec1[i];
184
- const base = result1 + i * 8;
185
- const ptr0 = utf8_encode(e, realloc, memory);
186
- const len0 = UTF8_ENCODED_LEN;
187
- data_view(memory).setInt32(base + 4, len0, true);
188
- data_view(memory).setInt32(base + 0, ptr0, true);
158
+
159
+ insert(val) {
160
+ if (this.head >= this.list.length) {
161
+ this.list.push({
162
+ next: this.list.length + 1,
163
+ val: undefined,
164
+ });
165
+ }
166
+ const ret = this.head;
167
+ const slot = this.list[ret];
168
+ this.head = slot.next;
169
+ slot.next = -1;
170
+ slot.val = val;
171
+ return ret;
189
172
  }
190
- const ret = this._exports['ruby-options: func(args: list<string>) -> handle<rb-iseq>'](result1, len1);
191
- return this._resource0_slab.remove(ret);
192
- }
193
- rubyScript(arg0) {
194
- const memory = this._exports.memory;
195
- const realloc = this._exports["cabi_realloc"];
196
- const ptr0 = utf8_encode(arg0, realloc, memory);
197
- const len0 = UTF8_ENCODED_LEN;
198
- this._exports['ruby-script: func(name: string) -> ()'](ptr0, len0);
199
- }
200
- rubyInitLoadpath() {
201
- this._exports['ruby-init-loadpath: func() -> ()']();
202
- }
203
- rbEvalStringProtect(arg0) {
204
- const memory = this._exports.memory;
205
- const realloc = this._exports["cabi_realloc"];
206
- const ptr0 = utf8_encode(arg0, realloc, memory);
207
- const len0 = UTF8_ENCODED_LEN;
208
- const ret = this._exports['rb-eval-string-protect: func(str: string) -> tuple<handle<rb-abi-value>, s32>'](ptr0, len0);
209
- return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
210
- }
211
- rbFuncallvProtect(arg0, arg1, arg2) {
212
- const memory = this._exports.memory;
213
- const realloc = this._exports["cabi_realloc"];
214
- const obj0 = arg0;
215
- if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
216
- const vec2 = arg2;
217
- const len2 = vec2.length;
218
- const result2 = realloc(0, 0, 4, len2 * 4);
219
- for (let i = 0; i < vec2.length; i++) {
220
- const e = vec2[i];
221
- const base = result2 + i * 4;
222
- const obj1 = e;
223
- if (!(obj1 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
224
- data_view(memory).setInt32(base + 0, this._resource1_slab.insert(obj1.clone()), true);
173
+
174
+ get(idx) {
175
+ if (idx >= this.list.length)
176
+ throw new RangeError('handle index not valid');
177
+ const slot = this.list[idx];
178
+ if (slot.next === -1)
179
+ return slot.val;
180
+ throw new RangeError('handle index not valid');
181
+ }
182
+
183
+ remove(idx) {
184
+ const ret = this.get(idx); // validate the slot
185
+ const slot = this.list[idx];
186
+ slot.val = undefined;
187
+ slot.next = this.head;
188
+ this.head = idx;
189
+ return ret;
225
190
  }
226
- const ret = this._exports['rb-funcallv-protect: func(recv: handle<rb-abi-value>, mid: u32, args: list<handle<rb-abi-value>>) -> tuple<handle<rb-abi-value>, s32>'](this._resource1_slab.insert(obj0.clone()), to_uint32(arg1), result2, len2);
227
- return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
228
- }
229
- rbIntern(arg0) {
230
- const memory = this._exports.memory;
231
- const realloc = this._exports["cabi_realloc"];
232
- const ptr0 = utf8_encode(arg0, realloc, memory);
233
- const len0 = UTF8_ENCODED_LEN;
234
- const ret = this._exports['rb-intern: func(name: string) -> u32'](ptr0, len0);
235
- return ret >>> 0;
236
- }
237
- rbErrinfo() {
238
- const ret = this._exports['rb-errinfo: func() -> handle<rb-abi-value>']();
239
- return this._resource1_slab.remove(ret);
240
- }
241
- rbClearErrinfo() {
242
- this._exports['rb-clear-errinfo: func() -> ()']();
243
- }
244
- rstringPtr(arg0) {
245
- const memory = this._exports.memory;
246
- const obj0 = arg0;
247
- if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
248
- const ret = this._exports['rstring-ptr: func(value: handle<rb-abi-value>) -> string'](this._resource1_slab.insert(obj0.clone()));
249
- const ptr1 = data_view(memory).getInt32(ret + 0, true);
250
- const len1 = data_view(memory).getInt32(ret + 4, true);
251
- const result1 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr1, len1));
252
- this._exports["cabi_post_rstring-ptr"](ret);
253
- return result1;
254
- }
255
- rbVmBugreport() {
256
- this._exports['rb-vm-bugreport: func() -> ()']();
257
- }
258
- rbGcEnable() {
259
- const ret = this._exports['rb-gc-enable: func() -> bool']();
260
- const bool0 = ret;
261
- return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
262
- }
263
- rbGcDisable() {
264
- const ret = this._exports['rb-gc-disable: func() -> bool']();
265
- const bool0 = ret;
266
- return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
267
- }
268
- rbSetShouldProhibitRewind(arg0) {
269
- const ret = this._exports['rb-set-should-prohibit-rewind: func(new-value: bool) -> bool'](arg0 ? 1 : 0);
270
- const bool0 = ret;
271
- return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
272
- }
273
- }
274
-
275
- class RbIseq {
276
- constructor(wasm_val, obj) {
277
- this._wasm_val = wasm_val;
278
- this._obj = obj;
279
- this._refcnt = 1;
280
- obj._registry0.register(this, wasm_val, this);
281
- }
282
-
283
- clone() {
284
- this._refcnt += 1;
285
- return this;
286
- }
287
-
288
- drop() {
289
- this._refcnt -= 1;
290
- if (this._refcnt !== 0)
291
- return;
292
- this._obj._registry0.unregister(this);
293
- const dtor = this._obj._exports['canonical_abi_drop_rb-iseq'];
294
- const wasm_val = this._wasm_val;
295
- delete this._obj;
296
- delete this._refcnt;
297
- delete this._wasm_val;
298
- dtor(wasm_val);
299
191
  }
300
- }
301
192
 
302
- class RbAbiValue {
303
- constructor(wasm_val, obj) {
304
- this._wasm_val = wasm_val;
305
- this._obj = obj;
306
- this._refcnt = 1;
307
- obj._registry1.register(this, wasm_val, this);
308
- }
309
-
310
- clone() {
311
- this._refcnt += 1;
312
- return this;
193
+ function throw_invalid_bool() {
194
+ throw new RangeError("invalid variant discriminant for bool");
313
195
  }
314
-
315
- drop() {
316
- this._refcnt -= 1;
317
- if (this._refcnt !== 0)
318
- return;
319
- this._obj._registry1.unregister(this);
320
- const dtor = this._obj._exports['canonical_abi_drop_rb-abi-value'];
321
- const wasm_val = this._wasm_val;
322
- delete this._obj;
323
- delete this._refcnt;
324
- delete this._wasm_val;
325
- dtor(wasm_val);
326
- }
327
- }
328
196
 
329
- function addRbJsAbiHostToImports(imports, obj, get_export) {
330
- if (!("rb-js-abi-host" in imports)) imports["rb-js-abi-host"] = {};
331
- imports["rb-js-abi-host"]["eval-js: func(code: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2) {
332
- const memory = get_export("memory");
333
- const ptr0 = arg0;
334
- const len0 = arg1;
335
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
336
- const ret0 = obj.evalJs(result0);
337
- const variant1 = ret0;
338
- switch (variant1.tag) {
339
- case "success": {
340
- const e = variant1.val;
341
- data_view(memory).setInt8(arg2 + 0, 0, true);
342
- data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
343
- break;
344
- }
345
- case "failure": {
346
- const e = variant1.val;
347
- data_view(memory).setInt8(arg2 + 0, 1, true);
348
- data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
349
- break;
350
- }
351
- default:
352
- throw new RangeError("invalid variant specified for JsAbiResult");
353
- }
354
- };
355
- imports["rb-js-abi-host"]["is-js: func(value: handle<js-abi-value>) -> bool"] = function(arg0) {
356
- const ret0 = obj.isJs(resources0.get(arg0));
357
- return ret0 ? 1 : 0;
358
- };
359
- imports["rb-js-abi-host"]["instance-of: func(value: handle<js-abi-value>, klass: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
360
- const ret0 = obj.instanceOf(resources0.get(arg0), resources0.get(arg1));
361
- return ret0 ? 1 : 0;
362
- };
363
- imports["rb-js-abi-host"]["global-this: func() -> handle<js-abi-value>"] = function() {
364
- const ret0 = obj.globalThis();
365
- return resources0.insert(ret0);
366
- };
367
- imports["rb-js-abi-host"]["int-to-js-number: func(value: s32) -> handle<js-abi-value>"] = function(arg0) {
368
- const ret0 = obj.intToJsNumber(arg0);
369
- return resources0.insert(ret0);
370
- };
371
- imports["rb-js-abi-host"]["float-to-js-number: func(value: float64) -> handle<js-abi-value>"] = function(arg0) {
372
- const ret0 = obj.floatToJsNumber(arg0);
373
- return resources0.insert(ret0);
374
- };
375
- imports["rb-js-abi-host"]["string-to-js-string: func(value: string) -> handle<js-abi-value>"] = function(arg0, arg1) {
376
- const memory = get_export("memory");
377
- const ptr0 = arg0;
378
- const len0 = arg1;
379
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
380
- const ret0 = obj.stringToJsString(result0);
381
- return resources0.insert(ret0);
382
- };
383
- imports["rb-js-abi-host"]["bool-to-js-bool: func(value: bool) -> handle<js-abi-value>"] = function(arg0) {
384
- const bool0 = arg0;
385
- const ret0 = obj.boolToJsBool(bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool()));
386
- return resources0.insert(ret0);
387
- };
388
- imports["rb-js-abi-host"]["proc-to-js-function: func(value: u32) -> handle<js-abi-value>"] = function(arg0) {
389
- const ret0 = obj.procToJsFunction(arg0 >>> 0);
390
- return resources0.insert(ret0);
391
- };
392
- imports["rb-js-abi-host"]["rb-object-to-js-rb-value: func(raw-rb-abi-value: u32) -> handle<js-abi-value>"] = function(arg0) {
393
- const ret0 = obj.rbObjectToJsRbValue(arg0 >>> 0);
394
- return resources0.insert(ret0);
395
- };
396
- imports["rb-js-abi-host"]["js-value-to-string: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
397
- const memory = get_export("memory");
398
- const realloc = get_export("cabi_realloc");
399
- const ret0 = obj.jsValueToString(resources0.get(arg0));
400
- const ptr0 = utf8_encode(ret0, realloc, memory);
401
- const len0 = UTF8_ENCODED_LEN;
402
- data_view(memory).setInt32(arg1 + 4, len0, true);
403
- data_view(memory).setInt32(arg1 + 0, ptr0, true);
404
- };
405
- imports["rb-js-abi-host"]["js-value-to-integer: func(value: handle<js-abi-value>) -> variant { f64(float64), bignum(string) }"] = function(arg0, arg1) {
406
- const memory = get_export("memory");
407
- const realloc = get_export("cabi_realloc");
408
- const ret0 = obj.jsValueToInteger(resources0.get(arg0));
409
- const variant1 = ret0;
410
- switch (variant1.tag) {
411
- case "f64": {
412
- const e = variant1.val;
413
- data_view(memory).setInt8(arg1 + 0, 0, true);
414
- data_view(memory).setFloat64(arg1 + 8, +e, true);
415
- break;
416
- }
417
- case "bignum": {
418
- const e = variant1.val;
419
- data_view(memory).setInt8(arg1 + 0, 1, true);
420
- const ptr0 = utf8_encode(e, realloc, memory);
421
- const len0 = UTF8_ENCODED_LEN;
422
- data_view(memory).setInt32(arg1 + 12, len0, true);
423
- data_view(memory).setInt32(arg1 + 8, ptr0, true);
424
- break;
425
- }
426
- default:
427
- throw new RangeError("invalid variant specified for RawInteger");
197
+ class RbAbiGuest {
198
+ constructor() {
199
+ this._resource0_slab = new Slab();
200
+ this._resource1_slab = new Slab();
428
201
  }
429
- };
430
- imports["rb-js-abi-host"]["export-js-value-to-host: func(value: handle<js-abi-value>) -> ()"] = function(arg0) {
431
- obj.exportJsValueToHost(resources0.get(arg0));
432
- };
433
- imports["rb-js-abi-host"]["import-js-value-from-host: func() -> handle<js-abi-value>"] = function() {
434
- const ret0 = obj.importJsValueFromHost();
435
- return resources0.insert(ret0);
436
- };
437
- imports["rb-js-abi-host"]["js-value-typeof: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
438
- const memory = get_export("memory");
439
- const realloc = get_export("cabi_realloc");
440
- const ret0 = obj.jsValueTypeof(resources0.get(arg0));
441
- const ptr0 = utf8_encode(ret0, realloc, memory);
442
- const len0 = UTF8_ENCODED_LEN;
443
- data_view(memory).setInt32(arg1 + 4, len0, true);
444
- data_view(memory).setInt32(arg1 + 0, ptr0, true);
445
- };
446
- imports["rb-js-abi-host"]["js-value-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
447
- const ret0 = obj.jsValueEqual(resources0.get(arg0), resources0.get(arg1));
448
- return ret0 ? 1 : 0;
449
- };
450
- imports["rb-js-abi-host"]["js-value-strictly-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
451
- const ret0 = obj.jsValueStrictlyEqual(resources0.get(arg0), resources0.get(arg1));
452
- return ret0 ? 1 : 0;
453
- };
454
- imports["rb-js-abi-host"]["reflect-apply: func(target: handle<js-abi-value>, this-argument: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
455
- const memory = get_export("memory");
456
- const len0 = arg3;
457
- const base0 = arg2;
458
- const result0 = [];
459
- for (let i = 0; i < len0; i++) {
460
- const base = base0 + i * 4;
461
- result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
202
+ addToImports(imports) {
203
+ if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
204
+
205
+ imports.canonical_abi['resource_drop_rb-iseq'] = i => {
206
+ this._resource0_slab.remove(i).drop();
207
+ };
208
+ imports.canonical_abi['resource_clone_rb-iseq'] = i => {
209
+ const obj = this._resource0_slab.get(i);
210
+ return this._resource0_slab.insert(obj.clone())
211
+ };
212
+ imports.canonical_abi['resource_get_rb-iseq'] = i => {
213
+ return this._resource0_slab.get(i)._wasm_val;
214
+ };
215
+ imports.canonical_abi['resource_new_rb-iseq'] = i => {
216
+ this._registry0;
217
+ return this._resource0_slab.insert(new RbIseq(i, this));
218
+ };
219
+
220
+ imports.canonical_abi['resource_drop_rb-abi-value'] = i => {
221
+ this._resource1_slab.remove(i).drop();
222
+ };
223
+ imports.canonical_abi['resource_clone_rb-abi-value'] = i => {
224
+ const obj = this._resource1_slab.get(i);
225
+ return this._resource1_slab.insert(obj.clone())
226
+ };
227
+ imports.canonical_abi['resource_get_rb-abi-value'] = i => {
228
+ return this._resource1_slab.get(i)._wasm_val;
229
+ };
230
+ imports.canonical_abi['resource_new_rb-abi-value'] = i => {
231
+ this._registry1;
232
+ return this._resource1_slab.insert(new RbAbiValue(i, this));
233
+ };
462
234
  }
463
- const ret0 = obj.reflectApply(resources0.get(arg0), resources0.get(arg1), result0);
464
- const variant1 = ret0;
465
- switch (variant1.tag) {
466
- case "success": {
467
- const e = variant1.val;
468
- data_view(memory).setInt8(arg4 + 0, 0, true);
469
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
470
- break;
471
- }
472
- case "failure": {
473
- const e = variant1.val;
474
- data_view(memory).setInt8(arg4 + 0, 1, true);
475
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
476
- break;
235
+
236
+ async instantiate(module, imports) {
237
+ imports = imports || {};
238
+ this.addToImports(imports);
239
+
240
+ if (module instanceof WebAssembly.Instance) {
241
+ this.instance = module;
242
+ } else if (module instanceof WebAssembly.Module) {
243
+ this.instance = await WebAssembly.instantiate(module, imports);
244
+ } else if (module instanceof ArrayBuffer || module instanceof Uint8Array) {
245
+ const { instance } = await WebAssembly.instantiate(module, imports);
246
+ this.instance = instance;
247
+ } else {
248
+ const { instance } = await WebAssembly.instantiateStreaming(module, imports);
249
+ this.instance = instance;
477
250
  }
478
- default:
479
- throw new RangeError("invalid variant specified for JsAbiResult");
251
+ this._exports = this.instance.exports;
252
+ this._registry0 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-iseq']);
253
+ this._registry1 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-abi-value']);
480
254
  }
481
- };
482
- imports["rb-js-abi-host"]["reflect-construct: func(target: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
483
- const memory = get_export("memory");
484
- const len0 = arg2;
485
- const base0 = arg1;
486
- const result0 = [];
487
- for (let i = 0; i < len0; i++) {
488
- const base = base0 + i * 4;
489
- result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
255
+ rubyShowVersion() {
256
+ this._exports['ruby-show-version: func() -> ()']();
490
257
  }
491
- const ret0 = obj.reflectConstruct(resources0.get(arg0), result0);
492
- return resources0.insert(ret0);
493
- };
494
- imports["rb-js-abi-host"]["reflect-delete-property: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
495
- const memory = get_export("memory");
496
- const ptr0 = arg1;
497
- const len0 = arg2;
498
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
499
- const ret0 = obj.reflectDeleteProperty(resources0.get(arg0), result0);
500
- return ret0 ? 1 : 0;
501
- };
502
- imports["rb-js-abi-host"]["reflect-get: func(target: handle<js-abi-value>, property-key: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3) {
503
- const memory = get_export("memory");
504
- const ptr0 = arg1;
505
- const len0 = arg2;
506
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
507
- const ret0 = obj.reflectGet(resources0.get(arg0), result0);
508
- const variant1 = ret0;
509
- switch (variant1.tag) {
510
- case "success": {
511
- const e = variant1.val;
512
- data_view(memory).setInt8(arg3 + 0, 0, true);
513
- data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
514
- break;
515
- }
516
- case "failure": {
517
- const e = variant1.val;
518
- data_view(memory).setInt8(arg3 + 0, 1, true);
519
- data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
520
- break;
521
- }
522
- default:
523
- throw new RangeError("invalid variant specified for JsAbiResult");
524
- }
525
- };
526
- imports["rb-js-abi-host"]["reflect-get-own-property-descriptor: func(target: handle<js-abi-value>, property-key: string) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
527
- const memory = get_export("memory");
528
- const ptr0 = arg1;
529
- const len0 = arg2;
530
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
531
- const ret0 = obj.reflectGetOwnPropertyDescriptor(resources0.get(arg0), result0);
532
- return resources0.insert(ret0);
533
- };
534
- imports["rb-js-abi-host"]["reflect-get-prototype-of: func(target: handle<js-abi-value>) -> handle<js-abi-value>"] = function(arg0) {
535
- const ret0 = obj.reflectGetPrototypeOf(resources0.get(arg0));
536
- return resources0.insert(ret0);
537
- };
538
- imports["rb-js-abi-host"]["reflect-has: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
539
- const memory = get_export("memory");
540
- const ptr0 = arg1;
541
- const len0 = arg2;
542
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
543
- const ret0 = obj.reflectHas(resources0.get(arg0), result0);
544
- return ret0 ? 1 : 0;
545
- };
546
- imports["rb-js-abi-host"]["reflect-is-extensible: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
547
- const ret0 = obj.reflectIsExtensible(resources0.get(arg0));
548
- return ret0 ? 1 : 0;
549
- };
550
- imports["rb-js-abi-host"]["reflect-own-keys: func(target: handle<js-abi-value>) -> list<handle<js-abi-value>>"] = function(arg0, arg1) {
551
- const memory = get_export("memory");
552
- const realloc = get_export("cabi_realloc");
553
- const ret0 = obj.reflectOwnKeys(resources0.get(arg0));
554
- const vec0 = ret0;
555
- const len0 = vec0.length;
556
- const result0 = realloc(0, 0, 4, len0 * 4);
557
- for (let i = 0; i < vec0.length; i++) {
558
- const e = vec0[i];
559
- const base = result0 + i * 4;
560
- data_view(memory).setInt32(base + 0, resources0.insert(e), true);
258
+ rubyInit() {
259
+ this._exports['ruby-init: func() -> ()']();
561
260
  }
562
- data_view(memory).setInt32(arg1 + 4, len0, true);
563
- data_view(memory).setInt32(arg1 + 0, result0, true);
564
- };
565
- imports["rb-js-abi-host"]["reflect-prevent-extensions: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
566
- const ret0 = obj.reflectPreventExtensions(resources0.get(arg0));
567
- return ret0 ? 1 : 0;
568
- };
569
- imports["rb-js-abi-host"]["reflect-set: func(target: handle<js-abi-value>, property-key: string, value: handle<js-abi-value>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
570
- const memory = get_export("memory");
571
- const ptr0 = arg1;
572
- const len0 = arg2;
573
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
574
- const ret0 = obj.reflectSet(resources0.get(arg0), result0, resources0.get(arg3));
575
- const variant1 = ret0;
576
- switch (variant1.tag) {
577
- case "success": {
578
- const e = variant1.val;
579
- data_view(memory).setInt8(arg4 + 0, 0, true);
580
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
581
- break;
582
- }
583
- case "failure": {
584
- const e = variant1.val;
585
- data_view(memory).setInt8(arg4 + 0, 1, true);
586
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
587
- break;
261
+ rubySysinit(arg0) {
262
+ const memory = this._exports.memory;
263
+ const realloc = this._exports["cabi_realloc"];
264
+ const vec1 = arg0;
265
+ const len1 = vec1.length;
266
+ const result1 = realloc(0, 0, 4, len1 * 8);
267
+ for (let i = 0; i < vec1.length; i++) {
268
+ const e = vec1[i];
269
+ const base = result1 + i * 8;
270
+ const ptr0 = utf8_encode(e, realloc, memory);
271
+ const len0 = UTF8_ENCODED_LEN;
272
+ data_view(memory).setInt32(base + 4, len0, true);
273
+ data_view(memory).setInt32(base + 0, ptr0, true);
588
274
  }
589
- default:
590
- throw new RangeError("invalid variant specified for JsAbiResult");
591
- }
592
- };
593
- imports["rb-js-abi-host"]["reflect-set-prototype-of: func(target: handle<js-abi-value>, prototype: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
594
- const ret0 = obj.reflectSetPrototypeOf(resources0.get(arg0), resources0.get(arg1));
595
- return ret0 ? 1 : 0;
596
- };
597
- if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
598
-
599
- const resources0 = new Slab();
600
- imports.canonical_abi["resource_drop_js-abi-value"] = (i) => {
601
- const val = resources0.remove(i);
602
- if (obj.dropJsAbiValue)
603
- obj.dropJsAbiValue(val);
604
- };
605
- }
606
-
607
- /**
608
- * Create a console printer that can be used as an overlay of WASI imports.
609
- * See the example below for how to use it.
610
- *
611
- * ```javascript
612
- * const imports = {
613
- * "wasi_snapshot_preview1": wasi.wasiImport,
614
- * }
615
- * const printer = consolePrinter();
616
- * printer.addToImports(imports);
617
- *
618
- * const instance = await WebAssembly.instantiate(module, imports);
619
- * printer.setMemory(instance.exports.memory);
620
- * ```
621
- *
622
- * Note that the `stdout` and `stderr` functions are called with text, not
623
- * bytes. This means that bytes written to stdout/stderr will be decoded as
624
- * UTF-8 and then passed to the `stdout`/`stderr` functions every time a write
625
- * occurs without buffering.
626
- *
627
- * @param stdout A function that will be called when stdout is written to.
628
- * Defaults to `console.log`.
629
- * @param stderr A function that will be called when stderr is written to.
630
- * Defaults to `console.warn`.
631
- * @returns An object that can be used as an overlay of WASI imports.
632
- */
633
- function consolePrinter({ stdout, stderr, } = {
634
- stdout: console.log,
635
- stderr: console.warn,
636
- }) {
637
- let memory = undefined;
638
- let _view = undefined;
639
- function getMemoryView() {
640
- if (typeof memory === "undefined") {
641
- throw new Error("Memory is not set");
642
- }
643
- if (_view === undefined || _view.buffer.byteLength === 0) {
644
- _view = new DataView(memory.buffer);
645
- }
646
- return _view;
275
+ this._exports['ruby-sysinit: func(args: list<string>) -> ()'](result1, len1);
647
276
  }
648
- const decoder = new TextDecoder();
649
- return {
650
- addToImports(imports) {
651
- const wasiImport = imports.wasi_snapshot_preview1;
652
- const original_fd_write = wasiImport.fd_write;
653
- wasiImport.fd_write = (fd, iovs, iovsLen, nwritten) => {
654
- if (fd !== 1 && fd !== 2) {
655
- return original_fd_write(fd, iovs, iovsLen, nwritten);
656
- }
657
- const view = getMemoryView();
658
- const buffers = Array.from({ length: iovsLen }, (_, i) => {
659
- const ptr = iovs + i * 8;
660
- const buf = view.getUint32(ptr, true);
661
- const bufLen = view.getUint32(ptr + 4, true);
662
- return new Uint8Array(memory.buffer, buf, bufLen);
663
- });
664
- let written = 0;
665
- let str = "";
666
- for (const buffer of buffers) {
667
- str += decoder.decode(buffer);
668
- written += buffer.byteLength;
669
- }
670
- view.setUint32(nwritten, written, true);
671
- const log = fd === 1 ? stdout : stderr;
672
- log(str);
673
- return 0;
674
- };
675
- const original_fd_filestat_get = wasiImport.fd_filestat_get;
676
- wasiImport.fd_filestat_get = (fd, filestat) => {
677
- if (fd !== 1 && fd !== 2) {
678
- return original_fd_filestat_get(fd, filestat);
679
- }
680
- const view = getMemoryView();
681
- const result = original_fd_filestat_get(fd, filestat);
682
- if (result !== 0) {
683
- return result;
684
- }
685
- const filetypePtr = filestat + 0;
686
- view.setUint8(filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
687
- return 0;
688
- };
689
- const original_fd_fdstat_get = wasiImport.fd_fdstat_get;
690
- wasiImport.fd_fdstat_get = (fd, fdstat) => {
691
- if (fd !== 1 && fd !== 2) {
692
- return original_fd_fdstat_get(fd, fdstat);
693
- }
694
- const view = getMemoryView();
695
- const fs_filetypePtr = fdstat + 0;
696
- view.setUint8(fs_filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
697
- const fs_rights_basePtr = fdstat + 8;
698
- view.setBigUint64(fs_rights_basePtr, BigInt(1)); // RIGHTS_FD_WRITE
699
- return 0;
700
- };
701
- },
702
- setMemory(m) {
703
- memory = m;
704
- },
705
- };
706
- }
707
-
708
- /**
709
- * A Ruby VM instance
710
- *
711
- * @example
712
- *
713
- * const wasi = new WASI();
714
- * const vm = new RubyVM();
715
- * const imports = {
716
- * wasi_snapshot_preview1: wasi.wasiImport,
717
- * };
718
- *
719
- * vm.addToImports(imports);
720
- *
721
- * const instance = await WebAssembly.instantiate(rubyModule, imports);
722
- * await vm.setInstance(instance);
723
- * wasi.initialize(instance);
724
- * vm.initialize();
725
- *
726
- */
727
- class RubyVM {
728
- constructor() {
729
- this.instance = null;
730
- this.interfaceState = {
731
- hasJSFrameAfterRbFrame: false,
732
- };
733
- // Wrap exported functions from Ruby VM to prohibit nested VM operation
734
- // if the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby.
735
- const proxyExports = (exports) => {
736
- const excludedMethods = [
737
- "addToImports",
738
- "instantiate",
739
- "rbSetShouldProhibitRewind",
740
- "rbGcDisable",
741
- "rbGcEnable",
742
- ];
743
- const excluded = ["constructor"].concat(excludedMethods);
744
- // wrap all methods in RbAbi.RbAbiGuest class
745
- for (const key of Object.getOwnPropertyNames(RbAbiGuest.prototype)) {
746
- if (excluded.includes(key)) {
747
- continue;
748
- }
749
- const value = exports[key];
750
- if (typeof value === "function") {
751
- exports[key] = (...args) => {
752
- const isNestedVMCall = this.interfaceState.hasJSFrameAfterRbFrame;
753
- if (isNestedVMCall) {
754
- const oldShouldProhibitRewind = this.guest.rbSetShouldProhibitRewind(true);
755
- const oldIsDisabledGc = this.guest.rbGcDisable();
756
- const result = Reflect.apply(value, exports, args);
757
- this.guest.rbSetShouldProhibitRewind(oldShouldProhibitRewind);
758
- if (!oldIsDisabledGc) {
759
- this.guest.rbGcEnable();
760
- }
761
- return result;
762
- }
763
- else {
764
- return Reflect.apply(value, exports, args);
765
- }
766
- };
767
- }
768
- }
769
- return exports;
770
- };
771
- this.guest = proxyExports(new RbAbiGuest());
772
- this.transport = new JsValueTransport();
773
- this.exceptionFormatter = new RbExceptionFormatter();
774
- }
775
- /**
776
- * Initialize the Ruby VM with the given command line arguments
777
- * @param args The command line arguments to pass to Ruby. Must be
778
- * an array of strings starting with the Ruby program name.
779
- */
780
- initialize(args = ["ruby.wasm", "--disable-gems", "-EUTF-8", "-e_=0"]) {
781
- const c_args = args.map((arg) => arg + "\0");
782
- this.guest.rubyInit();
783
- this.guest.rubySysinit(c_args);
784
- this.guest.rubyOptions(c_args);
785
- }
786
- /**
787
- * Set a given instance to interact JavaScript and Ruby's
788
- * WebAssembly instance. This method must be called before calling
789
- * Ruby API.
790
- *
791
- * @param instance The WebAssembly instance to interact with. Must
792
- * be instantiated from a Ruby built with JS extension, and built
793
- * with Reactor ABI instead of command line.
794
- */
795
- async setInstance(instance) {
796
- this.instance = instance;
797
- await this.guest.instantiate(instance);
798
- }
799
- /**
800
- * Add intrinsic import entries, which is necessary to interact JavaScript
801
- * and Ruby's WebAssembly instance.
802
- * @param imports The import object to add to the WebAssembly instance
803
- */
804
- addToImports(imports) {
805
- this.guest.addToImports(imports);
806
- function wrapTry(f) {
807
- return (...args) => {
808
- try {
809
- return { tag: "success", val: f(...args) };
810
- }
811
- catch (e) {
812
- if (e instanceof RbFatalError) {
813
- // RbFatalError should not be caught by Ruby because it Ruby VM
814
- // can be already in an inconsistent state.
815
- throw e;
816
- }
817
- return { tag: "failure", val: e };
818
- }
819
- };
820
- }
821
- imports["rb-js-abi-host"] = {
822
- rb_wasm_throw_prohibit_rewind_exception: (messagePtr, messageLen) => {
823
- const memory = this.instance.exports.memory;
824
- const str = new TextDecoder().decode(new Uint8Array(memory.buffer, messagePtr, messageLen));
825
- throw new RbFatalError("Ruby APIs that may rewind the VM stack are prohibited under nested VM operation " +
826
- `(${str})\n` +
827
- "Nested VM operation means that the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby " +
828
- "caused by something like `window.rubyVM.eval(\"JS.global[:rubyVM].eval('Fiber.yield')\")`\n" +
829
- "\n" +
830
- "Please check your call stack and make sure that you are **not** doing any of the following inside the nested Ruby frame:\n" +
831
- " 1. Switching fibers (e.g. Fiber#resume, Fiber.yield, and Fiber#transfer)\n" +
832
- " Note that `evalAsync` JS API switches fibers internally\n" +
833
- " 2. Raising uncaught exceptions\n" +
834
- " Please catch all exceptions inside the nested operation\n" +
835
- " 3. Calling Continuation APIs\n");
836
- },
837
- };
838
- // NOTE: The GC may collect objects that are still referenced by Wasm
839
- // locals because Asyncify cannot scan the Wasm stack above the JS frame.
840
- // So we need to keep track whether the JS frame is sandwitched by Ruby
841
- // frames or not, and prohibit nested VM operation if it is.
842
- const proxyImports = (imports) => {
843
- for (const [key, value] of Object.entries(imports)) {
844
- if (typeof value === "function") {
845
- imports[key] = (...args) => {
846
- const oldValue = this.interfaceState.hasJSFrameAfterRbFrame;
847
- this.interfaceState.hasJSFrameAfterRbFrame = true;
848
- const result = Reflect.apply(value, imports, args);
849
- this.interfaceState.hasJSFrameAfterRbFrame = oldValue;
850
- return result;
851
- };
852
- }
853
- }
854
- return imports;
855
- };
856
- addRbJsAbiHostToImports(imports, proxyImports({
857
- evalJs: wrapTry((code) => {
858
- return Function(code)();
859
- }),
860
- isJs: (value) => {
861
- // Just for compatibility with the old JS API
862
- return true;
863
- },
864
- globalThis: () => {
865
- if (typeof globalThis !== "undefined") {
866
- return globalThis;
867
- }
868
- else if (typeof global !== "undefined") {
869
- return global;
870
- }
871
- else if (typeof window !== "undefined") {
872
- return window;
873
- }
874
- throw new Error("unable to locate global object");
875
- },
876
- intToJsNumber: (value) => {
877
- return value;
878
- },
879
- floatToJsNumber: (value) => {
880
- return value;
881
- },
882
- stringToJsString: (value) => {
883
- return value;
884
- },
885
- boolToJsBool: (value) => {
886
- return value;
887
- },
888
- procToJsFunction: (rawRbAbiValue) => {
889
- const rbValue = this.rbValueOfPointer(rawRbAbiValue);
890
- return (...args) => {
891
- rbValue.call("call", ...args.map((arg) => this.wrap(arg)));
892
- };
893
- },
894
- rbObjectToJsRbValue: (rawRbAbiValue) => {
895
- return this.rbValueOfPointer(rawRbAbiValue);
896
- },
897
- jsValueToString: (value) => {
898
- // According to the [spec](https://tc39.es/ecma262/multipage/text-processing.html#sec-string-constructor-string-value)
899
- // `String(value)` always returns a string.
900
- return String(value);
901
- },
902
- jsValueToInteger(value) {
903
- if (typeof value === "number") {
904
- return { tag: "f64", val: value };
905
- }
906
- else if (typeof value === "bigint") {
907
- return { tag: "bignum", val: BigInt(value).toString(10) + "\0" };
908
- }
909
- else if (typeof value === "string") {
910
- return { tag: "bignum", val: value + "\0" };
911
- }
912
- else if (typeof value === "undefined") {
913
- return { tag: "f64", val: 0 };
914
- }
915
- else {
916
- return { tag: "f64", val: Number(value) };
917
- }
918
- },
919
- exportJsValueToHost: (value) => {
920
- // See `JsValueExporter` for the reason why we need to do this
921
- this.transport.takeJsValue(value);
922
- },
923
- importJsValueFromHost: () => {
924
- return this.transport.consumeJsValue();
925
- },
926
- instanceOf: (value, klass) => {
927
- if (typeof klass === "function") {
928
- return value instanceof klass;
929
- }
930
- else {
931
- return false;
932
- }
933
- },
934
- jsValueTypeof(value) {
935
- return typeof value;
936
- },
937
- jsValueEqual(lhs, rhs) {
938
- return lhs == rhs;
939
- },
940
- jsValueStrictlyEqual(lhs, rhs) {
941
- return lhs === rhs;
942
- },
943
- reflectApply: wrapTry((target, thisArgument, args) => {
944
- return Reflect.apply(target, thisArgument, args);
945
- }),
946
- reflectConstruct: function (target, args) {
947
- throw new Error("Function not implemented.");
948
- },
949
- reflectDeleteProperty: function (target, propertyKey) {
950
- throw new Error("Function not implemented.");
951
- },
952
- reflectGet: wrapTry((target, propertyKey) => {
953
- return target[propertyKey];
954
- }),
955
- reflectGetOwnPropertyDescriptor: function (target, propertyKey) {
956
- throw new Error("Function not implemented.");
957
- },
958
- reflectGetPrototypeOf: function (target) {
959
- throw new Error("Function not implemented.");
960
- },
961
- reflectHas: function (target, propertyKey) {
962
- throw new Error("Function not implemented.");
963
- },
964
- reflectIsExtensible: function (target) {
965
- throw new Error("Function not implemented.");
966
- },
967
- reflectOwnKeys: function (target) {
968
- throw new Error("Function not implemented.");
969
- },
970
- reflectPreventExtensions: function (target) {
971
- throw new Error("Function not implemented.");
972
- },
973
- reflectSet: wrapTry((target, propertyKey, value) => {
974
- return Reflect.set(target, propertyKey, value);
975
- }),
976
- reflectSetPrototypeOf: function (target, prototype) {
977
- throw new Error("Function not implemented.");
978
- },
979
- }), (name) => {
980
- return this.instance.exports[name];
981
- });
277
+ rubyOptions(arg0) {
278
+ const memory = this._exports.memory;
279
+ const realloc = this._exports["cabi_realloc"];
280
+ const vec1 = arg0;
281
+ const len1 = vec1.length;
282
+ const result1 = realloc(0, 0, 4, len1 * 8);
283
+ for (let i = 0; i < vec1.length; i++) {
284
+ const e = vec1[i];
285
+ const base = result1 + i * 8;
286
+ const ptr0 = utf8_encode(e, realloc, memory);
287
+ const len0 = UTF8_ENCODED_LEN;
288
+ data_view(memory).setInt32(base + 4, len0, true);
289
+ data_view(memory).setInt32(base + 0, ptr0, true);
290
+ }
291
+ const ret = this._exports['ruby-options: func(args: list<string>) -> handle<rb-iseq>'](result1, len1);
292
+ return this._resource0_slab.remove(ret);
982
293
  }
983
- /**
984
- * Print the Ruby version to stdout
985
- */
986
- printVersion() {
987
- this.guest.rubyShowVersion();
294
+ rubyScript(arg0) {
295
+ const memory = this._exports.memory;
296
+ const realloc = this._exports["cabi_realloc"];
297
+ const ptr0 = utf8_encode(arg0, realloc, memory);
298
+ const len0 = UTF8_ENCODED_LEN;
299
+ this._exports['ruby-script: func(name: string) -> ()'](ptr0, len0);
988
300
  }
989
- /**
990
- * Runs a string of Ruby code from JavaScript
991
- * @param code The Ruby code to run
992
- * @returns the result of the last expression
993
- *
994
- * @example
995
- * vm.eval("puts 'hello world'");
996
- * const result = vm.eval("1 + 2");
997
- * console.log(result.toString()); // 3
998
- *
999
- */
1000
- eval(code) {
1001
- return evalRbCode(this, this.privateObject(), code);
301
+ rubyInitLoadpath() {
302
+ this._exports['ruby-init-loadpath: func() -> ()']();
1002
303
  }
1003
- /**
1004
- * Runs a string of Ruby code with top-level `JS::Object#await`
1005
- * Returns a promise that resolves when execution completes.
1006
- * @param code The Ruby code to run
1007
- * @returns a promise that resolves to the result of the last expression
1008
- *
1009
- * @example
1010
- * const text = await vm.evalAsync(`
1011
- * require 'js'
1012
- * response = JS.global.fetch('https://example.com').await
1013
- * response.text.await
1014
- * `);
1015
- * console.log(text.toString()); // <html>...</html>
1016
- */
1017
- evalAsync(code) {
1018
- const JS = this.eval("require 'js'; JS");
1019
- return new Promise((resolve, reject) => {
1020
- JS.call("__eval_async_rb", this.wrap(code), this.wrap({
1021
- resolve,
1022
- reject: (error) => {
1023
- reject(new RbError(this.exceptionFormatter.format(error, this, this.privateObject())));
1024
- },
1025
- }));
1026
- });
304
+ rbEvalStringProtect(arg0) {
305
+ const memory = this._exports.memory;
306
+ const realloc = this._exports["cabi_realloc"];
307
+ const ptr0 = utf8_encode(arg0, realloc, memory);
308
+ const len0 = UTF8_ENCODED_LEN;
309
+ const ret = this._exports['rb-eval-string-protect: func(str: string) -> tuple<handle<rb-abi-value>, s32>'](ptr0, len0);
310
+ return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
1027
311
  }
1028
- /**
1029
- * Wrap a JavaScript value into a Ruby JS::Object
1030
- * @param value The value to convert to RbValue
1031
- * @returns the RbValue object representing the given JS value
1032
- *
1033
- * @example
1034
- * const hash = vm.eval(`Hash.new`)
1035
- * hash.call("store", vm.eval(`"key1"`), vm.wrap(new Object()));
1036
- */
1037
- wrap(value) {
1038
- return this.transport.importJsValue(value, this);
312
+ rbFuncallvProtect(arg0, arg1, arg2) {
313
+ const memory = this._exports.memory;
314
+ const realloc = this._exports["cabi_realloc"];
315
+ const obj0 = arg0;
316
+ if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
317
+ const vec2 = arg2;
318
+ const len2 = vec2.length;
319
+ const result2 = realloc(0, 0, 4, len2 * 4);
320
+ for (let i = 0; i < vec2.length; i++) {
321
+ const e = vec2[i];
322
+ const base = result2 + i * 4;
323
+ const obj1 = e;
324
+ if (!(obj1 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
325
+ data_view(memory).setInt32(base + 0, this._resource1_slab.insert(obj1.clone()), true);
326
+ }
327
+ const ret = this._exports['rb-funcallv-protect: func(recv: handle<rb-abi-value>, mid: u32, args: list<handle<rb-abi-value>>) -> tuple<handle<rb-abi-value>, s32>'](this._resource1_slab.insert(obj0.clone()), to_uint32(arg1), result2, len2);
328
+ return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
1039
329
  }
1040
- /** @private */
1041
- privateObject() {
1042
- return {
1043
- transport: this.transport,
1044
- exceptionFormatter: this.exceptionFormatter,
1045
- };
330
+ rbIntern(arg0) {
331
+ const memory = this._exports.memory;
332
+ const realloc = this._exports["cabi_realloc"];
333
+ const ptr0 = utf8_encode(arg0, realloc, memory);
334
+ const len0 = UTF8_ENCODED_LEN;
335
+ const ret = this._exports['rb-intern: func(name: string) -> u32'](ptr0, len0);
336
+ return ret >>> 0;
1046
337
  }
1047
- /** @private */
1048
- rbValueOfPointer(pointer) {
1049
- const abiValue = new RbAbiValue(pointer, this.guest);
1050
- return new RbValue(abiValue, this, this.privateObject());
338
+ rbErrinfo() {
339
+ const ret = this._exports['rb-errinfo: func() -> handle<rb-abi-value>']();
340
+ return this._resource1_slab.remove(ret);
1051
341
  }
1052
- }
1053
- /**
1054
- * Export a JS value held by the Ruby VM to the JS environment.
1055
- * This is implemented in a dirty way since wit cannot reference resources
1056
- * defined in other interfaces.
1057
- * In our case, we can't express `function(v: rb-abi-value) -> js-abi-value`
1058
- * because `rb-js-abi-host.wit`, that defines `js-abi-value`, is implemented
1059
- * by embedder side (JS) but `rb-abi-guest.wit`, that defines `rb-abi-value`
1060
- * is implemented by guest side (Wasm).
1061
- *
1062
- * This class is a helper to export by:
1063
- * 1. Call `function __export_to_js(v: rb-abi-value)` defined in guest from embedder side.
1064
- * 2. Call `function takeJsValue(v: js-abi-value)` defined in embedder from guest side with
1065
- * underlying JS value of given `rb-abi-value`.
1066
- * 3. Then `takeJsValue` implementation escapes the given JS value to the `_takenJsValues`
1067
- * stored in embedder side.
1068
- * 4. Finally, embedder side can take `_takenJsValues`.
1069
- *
1070
- * Note that `exportJsValue` is not reentrant.
1071
- *
1072
- * @private
1073
- */
1074
- class JsValueTransport {
1075
- constructor() {
1076
- this._takenJsValue = null;
342
+ rbClearErrinfo() {
343
+ this._exports['rb-clear-errinfo: func() -> ()']();
1077
344
  }
1078
- takeJsValue(value) {
1079
- this._takenJsValue = value;
345
+ rstringPtr(arg0) {
346
+ const memory = this._exports.memory;
347
+ const obj0 = arg0;
348
+ if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
349
+ const ret = this._exports['rstring-ptr: func(value: handle<rb-abi-value>) -> string'](this._resource1_slab.insert(obj0.clone()));
350
+ const ptr1 = data_view(memory).getInt32(ret + 0, true);
351
+ const len1 = data_view(memory).getInt32(ret + 4, true);
352
+ const result1 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr1, len1));
353
+ this._exports["cabi_post_rstring-ptr"](ret);
354
+ return result1;
1080
355
  }
1081
- consumeJsValue() {
1082
- return this._takenJsValue;
356
+ rbVmBugreport() {
357
+ this._exports['rb-vm-bugreport: func() -> ()']();
1083
358
  }
1084
- exportJsValue(value) {
1085
- value.call("__export_to_js");
1086
- return this._takenJsValue;
359
+ rbGcEnable() {
360
+ const ret = this._exports['rb-gc-enable: func() -> bool']();
361
+ const bool0 = ret;
362
+ return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
1087
363
  }
1088
- importJsValue(value, vm) {
1089
- this._takenJsValue = value;
1090
- return vm.eval('require "js"; JS::Object').call("__import_from_js");
364
+ rbGcDisable() {
365
+ const ret = this._exports['rb-gc-disable: func() -> bool']();
366
+ const bool0 = ret;
367
+ return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
1091
368
  }
1092
- }
1093
- /**
1094
- * A RbValue is an object that represents a value in Ruby
1095
- */
1096
- class RbValue {
1097
- /**
1098
- * @hideconstructor
1099
- */
1100
- constructor(inner, vm, privateObject) {
1101
- this.inner = inner;
1102
- this.vm = vm;
1103
- this.privateObject = privateObject;
369
+ rbSetShouldProhibitRewind(arg0) {
370
+ const ret = this._exports['rb-set-should-prohibit-rewind: func(new-value: bool) -> bool'](arg0 ? 1 : 0);
371
+ const bool0 = ret;
372
+ return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
1104
373
  }
1105
- /**
1106
- * Call a given method with given arguments
1107
- *
1108
- * @param callee name of the Ruby method to call
1109
- * @param args arguments to pass to the method. Must be an array of RbValue
1110
- *
1111
- * @example
1112
- * const ary = vm.eval("[1, 2, 3]");
1113
- * ary.call("push", 4);
1114
- * console.log(ary.call("sample").toString());
1115
- *
1116
- */
1117
- call(callee, ...args) {
1118
- const innerArgs = args.map((arg) => arg.inner);
1119
- return new RbValue(callRbMethod(this.vm, this.privateObject, this.inner, callee, innerArgs), this.vm, this.privateObject);
374
+ }
375
+
376
+ class RbIseq {
377
+ constructor(wasm_val, obj) {
378
+ this._wasm_val = wasm_val;
379
+ this._obj = obj;
380
+ this._refcnt = 1;
381
+ obj._registry0.register(this, wasm_val, this);
1120
382
  }
1121
- /**
1122
- * @see {@link https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive}
1123
- * @param hint Preferred type of the result primitive value. `"number"`, `"string"`, or `"default"`.
1124
- */
1125
- [Symbol.toPrimitive](hint) {
1126
- if (hint === "string" || hint === "default") {
1127
- return this.toString();
1128
- }
1129
- else if (hint === "number") {
1130
- return null;
1131
- }
1132
- return null;
383
+
384
+ clone() {
385
+ this._refcnt += 1;
386
+ return this;
1133
387
  }
1134
- /**
1135
- * Returns a string representation of the value by calling `to_s`
1136
- */
1137
- toString() {
1138
- const rbString = callRbMethod(this.vm, this.privateObject, this.inner, "to_s", []);
1139
- return this.vm.guest.rstringPtr(rbString);
388
+
389
+ drop() {
390
+ this._refcnt -= 1;
391
+ if (this._refcnt !== 0)
392
+ return;
393
+ this._obj._registry0.unregister(this);
394
+ const dtor = this._obj._exports['canonical_abi_drop_rb-iseq'];
395
+ const wasm_val = this._wasm_val;
396
+ delete this._obj;
397
+ delete this._refcnt;
398
+ delete this._wasm_val;
399
+ dtor(wasm_val);
1140
400
  }
1141
- /**
1142
- * Returns a JavaScript object representation of the value
1143
- * by calling `to_js`.
1144
- *
1145
- * Returns null if the value is not convertible to a JavaScript object.
1146
- */
1147
- toJS() {
1148
- const JS = this.vm.eval("JS");
1149
- const jsValue = JS.call("try_convert", this);
1150
- if (jsValue.call("nil?").toString() === "true") {
1151
- return null;
1152
- }
1153
- return this.privateObject.transport.exportJsValue(jsValue);
401
+ }
402
+
403
+ class RbAbiValue {
404
+ constructor(wasm_val, obj) {
405
+ this._wasm_val = wasm_val;
406
+ this._obj = obj;
407
+ this._refcnt = 1;
408
+ obj._registry1.register(this, wasm_val, this);
1154
409
  }
1155
- }
1156
- var ruby_tag_type;
1157
- (function (ruby_tag_type) {
1158
- ruby_tag_type[ruby_tag_type["None"] = 0] = "None";
1159
- ruby_tag_type[ruby_tag_type["Return"] = 1] = "Return";
1160
- ruby_tag_type[ruby_tag_type["Break"] = 2] = "Break";
1161
- ruby_tag_type[ruby_tag_type["Next"] = 3] = "Next";
1162
- ruby_tag_type[ruby_tag_type["Retry"] = 4] = "Retry";
1163
- ruby_tag_type[ruby_tag_type["Redo"] = 5] = "Redo";
1164
- ruby_tag_type[ruby_tag_type["Raise"] = 6] = "Raise";
1165
- ruby_tag_type[ruby_tag_type["Throw"] = 7] = "Throw";
1166
- ruby_tag_type[ruby_tag_type["Fatal"] = 8] = "Fatal";
1167
- ruby_tag_type[ruby_tag_type["Mask"] = 15] = "Mask";
1168
- })(ruby_tag_type || (ruby_tag_type = {}));
1169
- class RbExceptionFormatter {
1170
- constructor() {
1171
- this.literalsCache = null;
1172
- this.isFormmatting = false;
410
+
411
+ clone() {
412
+ this._refcnt += 1;
413
+ return this;
1173
414
  }
1174
- format(error, vm, privateObject) {
1175
- // All Ruby exceptions raised during formatting exception message should
1176
- // be caught and return a fallback message.
1177
- // Therefore, we don't need to worry about infinite recursion here ideally
1178
- // but checking re-entrancy just in case.
1179
- class RbExceptionFormatterError extends Error {
1180
- }
1181
- if (this.isFormmatting) {
1182
- throw new RbExceptionFormatterError("Unexpected exception occurred during formatting exception message");
1183
- }
1184
- this.isFormmatting = true;
1185
- try {
1186
- return this._format(error, vm, privateObject);
1187
- }
1188
- finally {
1189
- this.isFormmatting = false;
1190
- }
415
+
416
+ drop() {
417
+ this._refcnt -= 1;
418
+ if (this._refcnt !== 0)
419
+ return;
420
+ this._obj._registry1.unregister(this);
421
+ const dtor = this._obj._exports['canonical_abi_drop_rb-abi-value'];
422
+ const wasm_val = this._wasm_val;
423
+ delete this._obj;
424
+ delete this._refcnt;
425
+ delete this._wasm_val;
426
+ dtor(wasm_val);
1191
427
  }
1192
- _format(error, vm, privateObject) {
1193
- const [zeroLiteral, oneLiteral, newLineLiteral] = (() => {
1194
- if (this.literalsCache == null) {
1195
- const zeroOneNewLine = [
1196
- evalRbCode(vm, privateObject, "0"),
1197
- evalRbCode(vm, privateObject, "1"),
1198
- evalRbCode(vm, privateObject, `"\n"`),
1199
- ];
1200
- this.literalsCache = zeroOneNewLine;
1201
- return zeroOneNewLine;
1202
- }
1203
- else {
1204
- return this.literalsCache;
1205
- }
1206
- })();
1207
- let className;
1208
- let backtrace;
1209
- let message;
1210
- try {
1211
- className = error.call("class").toString();
1212
- }
1213
- catch (e) {
1214
- className = "unknown";
1215
- }
1216
- try {
1217
- message = error.toString();
1218
- }
1219
- catch (e) {
1220
- message = "unknown";
428
+ }
429
+
430
+ function addRbJsAbiHostToImports(imports, obj, get_export) {
431
+ if (!("rb-js-abi-host" in imports)) imports["rb-js-abi-host"] = {};
432
+ imports["rb-js-abi-host"]["eval-js: func(code: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2) {
433
+ const memory = get_export("memory");
434
+ const ptr0 = arg0;
435
+ const len0 = arg1;
436
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
437
+ const ret0 = obj.evalJs(result0);
438
+ const variant1 = ret0;
439
+ switch (variant1.tag) {
440
+ case "success": {
441
+ const e = variant1.val;
442
+ data_view(memory).setInt8(arg2 + 0, 0, true);
443
+ data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
444
+ break;
1221
445
  }
1222
- try {
1223
- backtrace = error.call("backtrace");
446
+ case "failure": {
447
+ const e = variant1.val;
448
+ data_view(memory).setInt8(arg2 + 0, 1, true);
449
+ data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
450
+ break;
1224
451
  }
1225
- catch (e) {
1226
- return this.formatString(className, message);
452
+ default:
453
+ throw new RangeError("invalid variant specified for JsAbiResult");
454
+ }
455
+ };
456
+ imports["rb-js-abi-host"]["is-js: func(value: handle<js-abi-value>) -> bool"] = function(arg0) {
457
+ const ret0 = obj.isJs(resources0.get(arg0));
458
+ return ret0 ? 1 : 0;
459
+ };
460
+ imports["rb-js-abi-host"]["instance-of: func(value: handle<js-abi-value>, klass: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
461
+ const ret0 = obj.instanceOf(resources0.get(arg0), resources0.get(arg1));
462
+ return ret0 ? 1 : 0;
463
+ };
464
+ imports["rb-js-abi-host"]["global-this: func() -> handle<js-abi-value>"] = function() {
465
+ const ret0 = obj.globalThis();
466
+ return resources0.insert(ret0);
467
+ };
468
+ imports["rb-js-abi-host"]["int-to-js-number: func(value: s32) -> handle<js-abi-value>"] = function(arg0) {
469
+ const ret0 = obj.intToJsNumber(arg0);
470
+ return resources0.insert(ret0);
471
+ };
472
+ imports["rb-js-abi-host"]["float-to-js-number: func(value: float64) -> handle<js-abi-value>"] = function(arg0) {
473
+ const ret0 = obj.floatToJsNumber(arg0);
474
+ return resources0.insert(ret0);
475
+ };
476
+ imports["rb-js-abi-host"]["string-to-js-string: func(value: string) -> handle<js-abi-value>"] = function(arg0, arg1) {
477
+ const memory = get_export("memory");
478
+ const ptr0 = arg0;
479
+ const len0 = arg1;
480
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
481
+ const ret0 = obj.stringToJsString(result0);
482
+ return resources0.insert(ret0);
483
+ };
484
+ imports["rb-js-abi-host"]["bool-to-js-bool: func(value: bool) -> handle<js-abi-value>"] = function(arg0) {
485
+ const bool0 = arg0;
486
+ const ret0 = obj.boolToJsBool(bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool()));
487
+ return resources0.insert(ret0);
488
+ };
489
+ imports["rb-js-abi-host"]["proc-to-js-function: func(value: u32) -> handle<js-abi-value>"] = function(arg0) {
490
+ const ret0 = obj.procToJsFunction(arg0 >>> 0);
491
+ return resources0.insert(ret0);
492
+ };
493
+ imports["rb-js-abi-host"]["rb-object-to-js-rb-value: func(raw-rb-abi-value: u32) -> handle<js-abi-value>"] = function(arg0) {
494
+ const ret0 = obj.rbObjectToJsRbValue(arg0 >>> 0);
495
+ return resources0.insert(ret0);
496
+ };
497
+ imports["rb-js-abi-host"]["js-value-to-string: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
498
+ const memory = get_export("memory");
499
+ const realloc = get_export("cabi_realloc");
500
+ const ret0 = obj.jsValueToString(resources0.get(arg0));
501
+ const ptr0 = utf8_encode(ret0, realloc, memory);
502
+ const len0 = UTF8_ENCODED_LEN;
503
+ data_view(memory).setInt32(arg1 + 4, len0, true);
504
+ data_view(memory).setInt32(arg1 + 0, ptr0, true);
505
+ };
506
+ imports["rb-js-abi-host"]["js-value-to-integer: func(value: handle<js-abi-value>) -> variant { f64(float64), bignum(string) }"] = function(arg0, arg1) {
507
+ const memory = get_export("memory");
508
+ const realloc = get_export("cabi_realloc");
509
+ const ret0 = obj.jsValueToInteger(resources0.get(arg0));
510
+ const variant1 = ret0;
511
+ switch (variant1.tag) {
512
+ case "f64": {
513
+ const e = variant1.val;
514
+ data_view(memory).setInt8(arg1 + 0, 0, true);
515
+ data_view(memory).setFloat64(arg1 + 8, +e, true);
516
+ break;
1227
517
  }
1228
- if (backtrace.call("nil?").toString() === "true") {
1229
- return this.formatString(className, message);
518
+ case "bignum": {
519
+ const e = variant1.val;
520
+ data_view(memory).setInt8(arg1 + 0, 1, true);
521
+ const ptr0 = utf8_encode(e, realloc, memory);
522
+ const len0 = UTF8_ENCODED_LEN;
523
+ data_view(memory).setInt32(arg1 + 12, len0, true);
524
+ data_view(memory).setInt32(arg1 + 8, ptr0, true);
525
+ break;
1230
526
  }
1231
- try {
1232
- const firstLine = backtrace.call("at", zeroLiteral);
1233
- const restLines = backtrace
1234
- .call("drop", oneLiteral)
1235
- .call("join", newLineLiteral);
1236
- return this.formatString(className, message, [
1237
- firstLine.toString(),
1238
- restLines.toString(),
1239
- ]);
527
+ default:
528
+ throw new RangeError("invalid variant specified for RawInteger");
529
+ }
530
+ };
531
+ imports["rb-js-abi-host"]["export-js-value-to-host: func(value: handle<js-abi-value>) -> ()"] = function(arg0) {
532
+ obj.exportJsValueToHost(resources0.get(arg0));
533
+ };
534
+ imports["rb-js-abi-host"]["import-js-value-from-host: func() -> handle<js-abi-value>"] = function() {
535
+ const ret0 = obj.importJsValueFromHost();
536
+ return resources0.insert(ret0);
537
+ };
538
+ imports["rb-js-abi-host"]["js-value-typeof: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
539
+ const memory = get_export("memory");
540
+ const realloc = get_export("cabi_realloc");
541
+ const ret0 = obj.jsValueTypeof(resources0.get(arg0));
542
+ const ptr0 = utf8_encode(ret0, realloc, memory);
543
+ const len0 = UTF8_ENCODED_LEN;
544
+ data_view(memory).setInt32(arg1 + 4, len0, true);
545
+ data_view(memory).setInt32(arg1 + 0, ptr0, true);
546
+ };
547
+ imports["rb-js-abi-host"]["js-value-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
548
+ const ret0 = obj.jsValueEqual(resources0.get(arg0), resources0.get(arg1));
549
+ return ret0 ? 1 : 0;
550
+ };
551
+ imports["rb-js-abi-host"]["js-value-strictly-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
552
+ const ret0 = obj.jsValueStrictlyEqual(resources0.get(arg0), resources0.get(arg1));
553
+ return ret0 ? 1 : 0;
554
+ };
555
+ imports["rb-js-abi-host"]["reflect-apply: func(target: handle<js-abi-value>, this-argument: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
556
+ const memory = get_export("memory");
557
+ const len0 = arg3;
558
+ const base0 = arg2;
559
+ const result0 = [];
560
+ for (let i = 0; i < len0; i++) {
561
+ const base = base0 + i * 4;
562
+ result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
563
+ }
564
+ const ret0 = obj.reflectApply(resources0.get(arg0), resources0.get(arg1), result0);
565
+ const variant1 = ret0;
566
+ switch (variant1.tag) {
567
+ case "success": {
568
+ const e = variant1.val;
569
+ data_view(memory).setInt8(arg4 + 0, 0, true);
570
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
571
+ break;
1240
572
  }
1241
- catch (e) {
1242
- return this.formatString(className, message);
573
+ case "failure": {
574
+ const e = variant1.val;
575
+ data_view(memory).setInt8(arg4 + 0, 1, true);
576
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
577
+ break;
1243
578
  }
1244
- }
1245
- formatString(klass, message, backtrace) {
1246
- if (backtrace) {
1247
- return `${backtrace[0]}: ${message} (${klass})\n${backtrace[1]}`;
579
+ default:
580
+ throw new RangeError("invalid variant specified for JsAbiResult");
581
+ }
582
+ };
583
+ imports["rb-js-abi-host"]["reflect-construct: func(target: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
584
+ const memory = get_export("memory");
585
+ const len0 = arg2;
586
+ const base0 = arg1;
587
+ const result0 = [];
588
+ for (let i = 0; i < len0; i++) {
589
+ const base = base0 + i * 4;
590
+ result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
591
+ }
592
+ const ret0 = obj.reflectConstruct(resources0.get(arg0), result0);
593
+ return resources0.insert(ret0);
594
+ };
595
+ imports["rb-js-abi-host"]["reflect-delete-property: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
596
+ const memory = get_export("memory");
597
+ const ptr0 = arg1;
598
+ const len0 = arg2;
599
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
600
+ const ret0 = obj.reflectDeleteProperty(resources0.get(arg0), result0);
601
+ return ret0 ? 1 : 0;
602
+ };
603
+ imports["rb-js-abi-host"]["reflect-get: func(target: handle<js-abi-value>, property-key: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3) {
604
+ const memory = get_export("memory");
605
+ const ptr0 = arg1;
606
+ const len0 = arg2;
607
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
608
+ const ret0 = obj.reflectGet(resources0.get(arg0), result0);
609
+ const variant1 = ret0;
610
+ switch (variant1.tag) {
611
+ case "success": {
612
+ const e = variant1.val;
613
+ data_view(memory).setInt8(arg3 + 0, 0, true);
614
+ data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
615
+ break;
1248
616
  }
1249
- else {
1250
- return `${klass}: ${message}`;
617
+ case "failure": {
618
+ const e = variant1.val;
619
+ data_view(memory).setInt8(arg3 + 0, 1, true);
620
+ data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
621
+ break;
1251
622
  }
1252
- }
1253
- }
1254
- const checkStatusTag = (rawTag, vm, privateObject) => {
1255
- switch (rawTag & ruby_tag_type.Mask) {
1256
- case ruby_tag_type.None:
1257
- break;
1258
- case ruby_tag_type.Return:
1259
- throw new RbError("unexpected return");
1260
- case ruby_tag_type.Next:
1261
- throw new RbError("unexpected next");
1262
- case ruby_tag_type.Break:
1263
- throw new RbError("unexpected break");
1264
- case ruby_tag_type.Redo:
1265
- throw new RbError("unexpected redo");
1266
- case ruby_tag_type.Retry:
1267
- throw new RbError("retry outside of rescue clause");
1268
- case ruby_tag_type.Throw:
1269
- throw new RbError("unexpected throw");
1270
- case ruby_tag_type.Raise:
1271
- case ruby_tag_type.Fatal:
1272
- const error = new RbValue(vm.guest.rbErrinfo(), vm, privateObject);
1273
- if (error.call("nil?").toString() === "true") {
1274
- throw new RbError("no exception object");
1275
- }
1276
- // clear errinfo if got exception due to no rb_jump_tag
1277
- vm.guest.rbClearErrinfo();
1278
- throw new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
1279
623
  default:
1280
- throw new RbError(`unknown error tag: ${rawTag}`);
1281
- }
1282
- };
1283
- function wrapRbOperation(vm, body) {
1284
- try {
1285
- return body();
1286
- }
1287
- catch (e) {
1288
- if (e instanceof RbError) {
1289
- throw e;
1290
- }
1291
- // All JS exceptions triggered by Ruby code are translated to Ruby exceptions,
1292
- // so non-RbError exceptions are unexpected.
1293
- vm.guest.rbVmBugreport();
1294
- if (e instanceof WebAssembly.RuntimeError && e.message === "unreachable") {
1295
- const error = new RbError(`Something went wrong in Ruby VM: ${e}`);
1296
- error.stack = e.stack;
1297
- throw error;
624
+ throw new RangeError("invalid variant specified for JsAbiResult");
625
+ }
626
+ };
627
+ imports["rb-js-abi-host"]["reflect-get-own-property-descriptor: func(target: handle<js-abi-value>, property-key: string) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
628
+ const memory = get_export("memory");
629
+ const ptr0 = arg1;
630
+ const len0 = arg2;
631
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
632
+ const ret0 = obj.reflectGetOwnPropertyDescriptor(resources0.get(arg0), result0);
633
+ return resources0.insert(ret0);
634
+ };
635
+ imports["rb-js-abi-host"]["reflect-get-prototype-of: func(target: handle<js-abi-value>) -> handle<js-abi-value>"] = function(arg0) {
636
+ const ret0 = obj.reflectGetPrototypeOf(resources0.get(arg0));
637
+ return resources0.insert(ret0);
638
+ };
639
+ imports["rb-js-abi-host"]["reflect-has: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
640
+ const memory = get_export("memory");
641
+ const ptr0 = arg1;
642
+ const len0 = arg2;
643
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
644
+ const ret0 = obj.reflectHas(resources0.get(arg0), result0);
645
+ return ret0 ? 1 : 0;
646
+ };
647
+ imports["rb-js-abi-host"]["reflect-is-extensible: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
648
+ const ret0 = obj.reflectIsExtensible(resources0.get(arg0));
649
+ return ret0 ? 1 : 0;
650
+ };
651
+ imports["rb-js-abi-host"]["reflect-own-keys: func(target: handle<js-abi-value>) -> list<handle<js-abi-value>>"] = function(arg0, arg1) {
652
+ const memory = get_export("memory");
653
+ const realloc = get_export("cabi_realloc");
654
+ const ret0 = obj.reflectOwnKeys(resources0.get(arg0));
655
+ const vec0 = ret0;
656
+ const len0 = vec0.length;
657
+ const result0 = realloc(0, 0, 4, len0 * 4);
658
+ for (let i = 0; i < vec0.length; i++) {
659
+ const e = vec0[i];
660
+ const base = result0 + i * 4;
661
+ data_view(memory).setInt32(base + 0, resources0.insert(e), true);
662
+ }
663
+ data_view(memory).setInt32(arg1 + 4, len0, true);
664
+ data_view(memory).setInt32(arg1 + 0, result0, true);
665
+ };
666
+ imports["rb-js-abi-host"]["reflect-prevent-extensions: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
667
+ const ret0 = obj.reflectPreventExtensions(resources0.get(arg0));
668
+ return ret0 ? 1 : 0;
669
+ };
670
+ imports["rb-js-abi-host"]["reflect-set: func(target: handle<js-abi-value>, property-key: string, value: handle<js-abi-value>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
671
+ const memory = get_export("memory");
672
+ const ptr0 = arg1;
673
+ const len0 = arg2;
674
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
675
+ const ret0 = obj.reflectSet(resources0.get(arg0), result0, resources0.get(arg3));
676
+ const variant1 = ret0;
677
+ switch (variant1.tag) {
678
+ case "success": {
679
+ const e = variant1.val;
680
+ data_view(memory).setInt8(arg4 + 0, 0, true);
681
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
682
+ break;
1298
683
  }
1299
- else {
1300
- throw e;
684
+ case "failure": {
685
+ const e = variant1.val;
686
+ data_view(memory).setInt8(arg4 + 0, 1, true);
687
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
688
+ break;
1301
689
  }
1302
- }
1303
- }
1304
- const callRbMethod = (vm, privateObject, recv, callee, args) => {
1305
- const mid = vm.guest.rbIntern(callee + "\0");
1306
- return wrapRbOperation(vm, () => {
1307
- const [value, status] = vm.guest.rbFuncallvProtect(recv, mid, args);
1308
- checkStatusTag(status, vm, privateObject);
1309
- return value;
1310
- });
1311
- };
1312
- const evalRbCode = (vm, privateObject, code) => {
1313
- return wrapRbOperation(vm, () => {
1314
- const [value, status] = vm.guest.rbEvalStringProtect(code + "\0");
1315
- checkStatusTag(status, vm, privateObject);
1316
- return new RbValue(value, vm, privateObject);
1317
- });
1318
- };
1319
- /**
1320
- * Error class thrown by Ruby execution
1321
- */
1322
- class RbError extends Error {
1323
- /**
1324
- * @hideconstructor
1325
- */
1326
- constructor(message) {
1327
- super(message);
1328
- }
1329
- }
1330
- /**
1331
- * Error class thrown by Ruby execution when it is not possible to recover.
1332
- * This is usually caused when Ruby VM is in an inconsistent state.
1333
- */
1334
- class RbFatalError extends RbError {
1335
- /**
1336
- * @hideconstructor
1337
- */
1338
- constructor(message) {
1339
- super("Ruby Fatal Error: " + message);
1340
- }
1341
- }
690
+ default:
691
+ throw new RangeError("invalid variant specified for JsAbiResult");
692
+ }
693
+ };
694
+ imports["rb-js-abi-host"]["reflect-set-prototype-of: func(target: handle<js-abi-value>, prototype: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
695
+ const ret0 = obj.reflectSetPrototypeOf(resources0.get(arg0), resources0.get(arg1));
696
+ return ret0 ? 1 : 0;
697
+ };
698
+ if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
699
+
700
+ const resources0 = new Slab();
701
+ imports.canonical_abi["resource_drop_js-abi-value"] = (i) => {
702
+ const val = resources0.remove(i);
703
+ if (obj.dropJsAbiValue)
704
+ obj.dropJsAbiValue(val);
705
+ };
706
+ }
707
+
708
+ /**
709
+ * A Ruby VM instance
710
+ *
711
+ * @example
712
+ *
713
+ * const wasi = new WASI();
714
+ * const vm = new RubyVM();
715
+ * const imports = {
716
+ * wasi_snapshot_preview1: wasi.wasiImport,
717
+ * };
718
+ *
719
+ * vm.addToImports(imports);
720
+ *
721
+ * const instance = await WebAssembly.instantiate(rubyModule, imports);
722
+ * await vm.setInstance(instance);
723
+ * wasi.initialize(instance);
724
+ * vm.initialize();
725
+ *
726
+ */
727
+ class RubyVM {
728
+ constructor() {
729
+ this.instance = null;
730
+ this.interfaceState = {
731
+ hasJSFrameAfterRbFrame: false,
732
+ };
733
+ // Wrap exported functions from Ruby VM to prohibit nested VM operation
734
+ // if the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby.
735
+ const proxyExports = (exports) => {
736
+ const excludedMethods = [
737
+ "addToImports",
738
+ "instantiate",
739
+ "rbSetShouldProhibitRewind",
740
+ "rbGcDisable",
741
+ "rbGcEnable",
742
+ ];
743
+ const excluded = ["constructor"].concat(excludedMethods);
744
+ // wrap all methods in RbAbi.RbAbiGuest class
745
+ for (const key of Object.getOwnPropertyNames(RbAbiGuest.prototype)) {
746
+ if (excluded.includes(key)) {
747
+ continue;
748
+ }
749
+ const value = exports[key];
750
+ if (typeof value === "function") {
751
+ exports[key] = (...args) => {
752
+ const isNestedVMCall = this.interfaceState.hasJSFrameAfterRbFrame;
753
+ if (isNestedVMCall) {
754
+ const oldShouldProhibitRewind = this.guest.rbSetShouldProhibitRewind(true);
755
+ const oldIsDisabledGc = this.guest.rbGcDisable();
756
+ const result = Reflect.apply(value, exports, args);
757
+ this.guest.rbSetShouldProhibitRewind(oldShouldProhibitRewind);
758
+ if (!oldIsDisabledGc) {
759
+ this.guest.rbGcEnable();
760
+ }
761
+ return result;
762
+ }
763
+ else {
764
+ return Reflect.apply(value, exports, args);
765
+ }
766
+ };
767
+ }
768
+ }
769
+ return exports;
770
+ };
771
+ this.guest = proxyExports(new RbAbiGuest());
772
+ this.transport = new JsValueTransport();
773
+ this.exceptionFormatter = new RbExceptionFormatter();
774
+ }
775
+ /**
776
+ * Initialize the Ruby VM with the given command line arguments
777
+ * @param args The command line arguments to pass to Ruby. Must be
778
+ * an array of strings starting with the Ruby program name.
779
+ */
780
+ initialize(args = ["ruby.wasm", "-EUTF-8", "-e_=0"]) {
781
+ const c_args = args.map((arg) => arg + "\0");
782
+ this.guest.rubyInit();
783
+ this.guest.rubySysinit(c_args);
784
+ this.guest.rubyOptions(c_args);
785
+ this.eval(`require "/bundle/setup"`);
786
+ }
787
+ /**
788
+ * Set a given instance to interact JavaScript and Ruby's
789
+ * WebAssembly instance. This method must be called before calling
790
+ * Ruby API.
791
+ *
792
+ * @param instance The WebAssembly instance to interact with. Must
793
+ * be instantiated from a Ruby built with JS extension, and built
794
+ * with Reactor ABI instead of command line.
795
+ */
796
+ async setInstance(instance) {
797
+ this.instance = instance;
798
+ await this.guest.instantiate(instance);
799
+ }
800
+ /**
801
+ * Add intrinsic import entries, which is necessary to interact JavaScript
802
+ * and Ruby's WebAssembly instance.
803
+ * @param imports The import object to add to the WebAssembly instance
804
+ */
805
+ addToImports(imports) {
806
+ this.guest.addToImports(imports);
807
+ function wrapTry(f) {
808
+ return (...args) => {
809
+ try {
810
+ return { tag: "success", val: f(...args) };
811
+ }
812
+ catch (e) {
813
+ if (e instanceof RbFatalError) {
814
+ // RbFatalError should not be caught by Ruby because it Ruby VM
815
+ // can be already in an inconsistent state.
816
+ throw e;
817
+ }
818
+ return { tag: "failure", val: e };
819
+ }
820
+ };
821
+ }
822
+ imports["rb-js-abi-host"] = {
823
+ rb_wasm_throw_prohibit_rewind_exception: (messagePtr, messageLen) => {
824
+ const memory = this.instance.exports.memory;
825
+ const str = new TextDecoder().decode(new Uint8Array(memory.buffer, messagePtr, messageLen));
826
+ throw new RbFatalError("Ruby APIs that may rewind the VM stack are prohibited under nested VM operation " +
827
+ `(${str})\n` +
828
+ "Nested VM operation means that the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby " +
829
+ "caused by something like `window.rubyVM.eval(\"JS.global[:rubyVM].eval('Fiber.yield')\")`\n" +
830
+ "\n" +
831
+ "Please check your call stack and make sure that you are **not** doing any of the following inside the nested Ruby frame:\n" +
832
+ " 1. Switching fibers (e.g. Fiber#resume, Fiber.yield, and Fiber#transfer)\n" +
833
+ " Note that `evalAsync` JS API switches fibers internally\n" +
834
+ " 2. Raising uncaught exceptions\n" +
835
+ " Please catch all exceptions inside the nested operation\n" +
836
+ " 3. Calling Continuation APIs\n");
837
+ },
838
+ };
839
+ // NOTE: The GC may collect objects that are still referenced by Wasm
840
+ // locals because Asyncify cannot scan the Wasm stack above the JS frame.
841
+ // So we need to keep track whether the JS frame is sandwitched by Ruby
842
+ // frames or not, and prohibit nested VM operation if it is.
843
+ const proxyImports = (imports) => {
844
+ for (const [key, value] of Object.entries(imports)) {
845
+ if (typeof value === "function") {
846
+ imports[key] = (...args) => {
847
+ const oldValue = this.interfaceState.hasJSFrameAfterRbFrame;
848
+ this.interfaceState.hasJSFrameAfterRbFrame = true;
849
+ const result = Reflect.apply(value, imports, args);
850
+ this.interfaceState.hasJSFrameAfterRbFrame = oldValue;
851
+ return result;
852
+ };
853
+ }
854
+ }
855
+ return imports;
856
+ };
857
+ addRbJsAbiHostToImports(imports, proxyImports({
858
+ evalJs: wrapTry((code) => {
859
+ return Function(code)();
860
+ }),
861
+ isJs: (value) => {
862
+ // Just for compatibility with the old JS API
863
+ return true;
864
+ },
865
+ globalThis: () => {
866
+ if (typeof globalThis !== "undefined") {
867
+ return globalThis;
868
+ }
869
+ else if (typeof global !== "undefined") {
870
+ return global;
871
+ }
872
+ else if (typeof window !== "undefined") {
873
+ return window;
874
+ }
875
+ throw new Error("unable to locate global object");
876
+ },
877
+ intToJsNumber: (value) => {
878
+ return value;
879
+ },
880
+ floatToJsNumber: (value) => {
881
+ return value;
882
+ },
883
+ stringToJsString: (value) => {
884
+ return value;
885
+ },
886
+ boolToJsBool: (value) => {
887
+ return value;
888
+ },
889
+ procToJsFunction: (rawRbAbiValue) => {
890
+ const rbValue = this.rbValueOfPointer(rawRbAbiValue);
891
+ return (...args) => {
892
+ rbValue.call("call", ...args.map((arg) => this.wrap(arg)));
893
+ };
894
+ },
895
+ rbObjectToJsRbValue: (rawRbAbiValue) => {
896
+ return this.rbValueOfPointer(rawRbAbiValue);
897
+ },
898
+ jsValueToString: (value) => {
899
+ // According to the [spec](https://tc39.es/ecma262/multipage/text-processing.html#sec-string-constructor-string-value)
900
+ // `String(value)` always returns a string.
901
+ return String(value);
902
+ },
903
+ jsValueToInteger(value) {
904
+ if (typeof value === "number") {
905
+ return { tag: "f64", val: value };
906
+ }
907
+ else if (typeof value === "bigint") {
908
+ return { tag: "bignum", val: BigInt(value).toString(10) + "\0" };
909
+ }
910
+ else if (typeof value === "string") {
911
+ return { tag: "bignum", val: value + "\0" };
912
+ }
913
+ else if (typeof value === "undefined") {
914
+ return { tag: "f64", val: 0 };
915
+ }
916
+ else {
917
+ return { tag: "f64", val: Number(value) };
918
+ }
919
+ },
920
+ exportJsValueToHost: (value) => {
921
+ // See `JsValueExporter` for the reason why we need to do this
922
+ this.transport.takeJsValue(value);
923
+ },
924
+ importJsValueFromHost: () => {
925
+ return this.transport.consumeJsValue();
926
+ },
927
+ instanceOf: (value, klass) => {
928
+ if (typeof klass === "function") {
929
+ return value instanceof klass;
930
+ }
931
+ else {
932
+ return false;
933
+ }
934
+ },
935
+ jsValueTypeof(value) {
936
+ return typeof value;
937
+ },
938
+ jsValueEqual(lhs, rhs) {
939
+ return lhs == rhs;
940
+ },
941
+ jsValueStrictlyEqual(lhs, rhs) {
942
+ return lhs === rhs;
943
+ },
944
+ reflectApply: wrapTry((target, thisArgument, args) => {
945
+ return Reflect.apply(target, thisArgument, args);
946
+ }),
947
+ reflectConstruct: function (target, args) {
948
+ throw new Error("Function not implemented.");
949
+ },
950
+ reflectDeleteProperty: function (target, propertyKey) {
951
+ throw new Error("Function not implemented.");
952
+ },
953
+ reflectGet: wrapTry((target, propertyKey) => {
954
+ return target[propertyKey];
955
+ }),
956
+ reflectGetOwnPropertyDescriptor: function (target, propertyKey) {
957
+ throw new Error("Function not implemented.");
958
+ },
959
+ reflectGetPrototypeOf: function (target) {
960
+ throw new Error("Function not implemented.");
961
+ },
962
+ reflectHas: function (target, propertyKey) {
963
+ throw new Error("Function not implemented.");
964
+ },
965
+ reflectIsExtensible: function (target) {
966
+ throw new Error("Function not implemented.");
967
+ },
968
+ reflectOwnKeys: function (target) {
969
+ throw new Error("Function not implemented.");
970
+ },
971
+ reflectPreventExtensions: function (target) {
972
+ throw new Error("Function not implemented.");
973
+ },
974
+ reflectSet: wrapTry((target, propertyKey, value) => {
975
+ return Reflect.set(target, propertyKey, value);
976
+ }),
977
+ reflectSetPrototypeOf: function (target, prototype) {
978
+ throw new Error("Function not implemented.");
979
+ },
980
+ }), (name) => {
981
+ return this.instance.exports[name];
982
+ });
983
+ }
984
+ /**
985
+ * Print the Ruby version to stdout
986
+ */
987
+ printVersion() {
988
+ this.guest.rubyShowVersion();
989
+ }
990
+ /**
991
+ * Runs a string of Ruby code from JavaScript
992
+ * @param code The Ruby code to run
993
+ * @returns the result of the last expression
994
+ *
995
+ * @example
996
+ * vm.eval("puts 'hello world'");
997
+ * const result = vm.eval("1 + 2");
998
+ * console.log(result.toString()); // 3
999
+ *
1000
+ */
1001
+ eval(code) {
1002
+ return evalRbCode(this, this.privateObject(), code);
1003
+ }
1004
+ /**
1005
+ * Runs a string of Ruby code with top-level `JS::Object#await`
1006
+ * Returns a promise that resolves when execution completes.
1007
+ * @param code The Ruby code to run
1008
+ * @returns a promise that resolves to the result of the last expression
1009
+ *
1010
+ * @example
1011
+ * const text = await vm.evalAsync(`
1012
+ * require 'js'
1013
+ * response = JS.global.fetch('https://example.com').await
1014
+ * response.text.await
1015
+ * `);
1016
+ * console.log(text.toString()); // <html>...</html>
1017
+ */
1018
+ evalAsync(code) {
1019
+ const JS = this.eval("require 'js'; JS");
1020
+ return newRbPromise(this, this.privateObject(), (future) => {
1021
+ JS.call("__eval_async_rb", this.wrap(code), future);
1022
+ });
1023
+ }
1024
+ /**
1025
+ * Wrap a JavaScript value into a Ruby JS::Object
1026
+ * @param value The value to convert to RbValue
1027
+ * @returns the RbValue object representing the given JS value
1028
+ *
1029
+ * @example
1030
+ * const hash = vm.eval(`Hash.new`)
1031
+ * hash.call("store", vm.eval(`"key1"`), vm.wrap(new Object()));
1032
+ */
1033
+ wrap(value) {
1034
+ return this.transport.importJsValue(value, this);
1035
+ }
1036
+ /** @private */
1037
+ privateObject() {
1038
+ return {
1039
+ transport: this.transport,
1040
+ exceptionFormatter: this.exceptionFormatter,
1041
+ };
1042
+ }
1043
+ /** @private */
1044
+ rbValueOfPointer(pointer) {
1045
+ const abiValue = new RbAbiValue(pointer, this.guest);
1046
+ return new RbValue(abiValue, this, this.privateObject());
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Export a JS value held by the Ruby VM to the JS environment.
1051
+ * This is implemented in a dirty way since wit cannot reference resources
1052
+ * defined in other interfaces.
1053
+ * In our case, we can't express `function(v: rb-abi-value) -> js-abi-value`
1054
+ * because `rb-js-abi-host.wit`, that defines `js-abi-value`, is implemented
1055
+ * by embedder side (JS) but `rb-abi-guest.wit`, that defines `rb-abi-value`
1056
+ * is implemented by guest side (Wasm).
1057
+ *
1058
+ * This class is a helper to export by:
1059
+ * 1. Call `function __export_to_js(v: rb-abi-value)` defined in guest from embedder side.
1060
+ * 2. Call `function takeJsValue(v: js-abi-value)` defined in embedder from guest side with
1061
+ * underlying JS value of given `rb-abi-value`.
1062
+ * 3. Then `takeJsValue` implementation escapes the given JS value to the `_takenJsValues`
1063
+ * stored in embedder side.
1064
+ * 4. Finally, embedder side can take `_takenJsValues`.
1065
+ *
1066
+ * Note that `exportJsValue` is not reentrant.
1067
+ *
1068
+ * @private
1069
+ */
1070
+ class JsValueTransport {
1071
+ constructor() {
1072
+ this._takenJsValue = null;
1073
+ }
1074
+ takeJsValue(value) {
1075
+ this._takenJsValue = value;
1076
+ }
1077
+ consumeJsValue() {
1078
+ return this._takenJsValue;
1079
+ }
1080
+ exportJsValue(value) {
1081
+ value.call("__export_to_js");
1082
+ return this._takenJsValue;
1083
+ }
1084
+ importJsValue(value, vm) {
1085
+ this._takenJsValue = value;
1086
+ return vm.eval('require "js"; JS::Object').call("__import_from_js");
1087
+ }
1088
+ }
1089
+ /**
1090
+ * A RbValue is an object that represents a value in Ruby
1091
+ */
1092
+ class RbValue {
1093
+ /**
1094
+ * @hideconstructor
1095
+ */
1096
+ constructor(inner, vm, privateObject) {
1097
+ this.inner = inner;
1098
+ this.vm = vm;
1099
+ this.privateObject = privateObject;
1100
+ }
1101
+ /**
1102
+ * Call a given method with given arguments
1103
+ *
1104
+ * @param callee name of the Ruby method to call
1105
+ * @param args arguments to pass to the method. Must be an array of RbValue
1106
+ * @returns The result of the method call as a new RbValue.
1107
+ *
1108
+ * @example
1109
+ * const ary = vm.eval("[1, 2, 3]");
1110
+ * ary.call("push", 4);
1111
+ * console.log(ary.call("sample").toString());
1112
+ */
1113
+ call(callee, ...args) {
1114
+ const innerArgs = args.map((arg) => arg.inner);
1115
+ return new RbValue(callRbMethod(this.vm, this.privateObject, this.inner, callee, innerArgs), this.vm, this.privateObject);
1116
+ }
1117
+ /**
1118
+ * Call a given method that may call `JS::Object#await` with given arguments
1119
+ *
1120
+ * @param callee name of the Ruby method to call
1121
+ * @param args arguments to pass to the method. Must be an array of RbValue
1122
+ * @returns A Promise that resolves to the result of the method call as a new RbValue.
1123
+ *
1124
+ * @example
1125
+ * const client = vm.eval(`
1126
+ * require 'js'
1127
+ * class HttpClient
1128
+ * def get(url)
1129
+ * JS.global.fetch(url).await
1130
+ * end
1131
+ * end
1132
+ * HttpClient.new
1133
+ * `);
1134
+ * const response = await client.callAsync("get", vm.eval(`"https://example.com"`));
1135
+ */
1136
+ callAsync(callee, ...args) {
1137
+ const JS = this.vm.eval("require 'js'; JS");
1138
+ return newRbPromise(this.vm, this.privateObject, (future) => {
1139
+ JS.call("__call_async_method", this, this.vm.wrap(callee), future, ...args);
1140
+ });
1141
+ }
1142
+ /**
1143
+ * @see {@link https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive}
1144
+ * @param hint Preferred type of the result primitive value. `"number"`, `"string"`, or `"default"`.
1145
+ */
1146
+ [Symbol.toPrimitive](hint) {
1147
+ if (hint === "string" || hint === "default") {
1148
+ return this.toString();
1149
+ }
1150
+ else if (hint === "number") {
1151
+ return null;
1152
+ }
1153
+ return null;
1154
+ }
1155
+ /**
1156
+ * Returns a string representation of the value by calling `to_s`
1157
+ */
1158
+ toString() {
1159
+ const rbString = callRbMethod(this.vm, this.privateObject, this.inner, "to_s", []);
1160
+ return this.vm.guest.rstringPtr(rbString);
1161
+ }
1162
+ /**
1163
+ * Returns a JavaScript object representation of the value
1164
+ * by calling `to_js`.
1165
+ *
1166
+ * Returns null if the value is not convertible to a JavaScript object.
1167
+ */
1168
+ toJS() {
1169
+ const JS = this.vm.eval("JS");
1170
+ const jsValue = JS.call("try_convert", this);
1171
+ if (jsValue.call("nil?").toString() === "true") {
1172
+ return null;
1173
+ }
1174
+ return this.privateObject.transport.exportJsValue(jsValue);
1175
+ }
1176
+ }
1177
+ var ruby_tag_type;
1178
+ (function (ruby_tag_type) {
1179
+ ruby_tag_type[ruby_tag_type["None"] = 0] = "None";
1180
+ ruby_tag_type[ruby_tag_type["Return"] = 1] = "Return";
1181
+ ruby_tag_type[ruby_tag_type["Break"] = 2] = "Break";
1182
+ ruby_tag_type[ruby_tag_type["Next"] = 3] = "Next";
1183
+ ruby_tag_type[ruby_tag_type["Retry"] = 4] = "Retry";
1184
+ ruby_tag_type[ruby_tag_type["Redo"] = 5] = "Redo";
1185
+ ruby_tag_type[ruby_tag_type["Raise"] = 6] = "Raise";
1186
+ ruby_tag_type[ruby_tag_type["Throw"] = 7] = "Throw";
1187
+ ruby_tag_type[ruby_tag_type["Fatal"] = 8] = "Fatal";
1188
+ ruby_tag_type[ruby_tag_type["Mask"] = 15] = "Mask";
1189
+ })(ruby_tag_type || (ruby_tag_type = {}));
1190
+ class RbExceptionFormatter {
1191
+ constructor() {
1192
+ this.literalsCache = null;
1193
+ this.isFormmatting = false;
1194
+ }
1195
+ format(error, vm, privateObject) {
1196
+ // All Ruby exceptions raised during formatting exception message should
1197
+ // be caught and return a fallback message.
1198
+ // Therefore, we don't need to worry about infinite recursion here ideally
1199
+ // but checking re-entrancy just in case.
1200
+ class RbExceptionFormatterError extends Error {
1201
+ }
1202
+ if (this.isFormmatting) {
1203
+ throw new RbExceptionFormatterError("Unexpected exception occurred during formatting exception message");
1204
+ }
1205
+ this.isFormmatting = true;
1206
+ try {
1207
+ return this._format(error, vm, privateObject);
1208
+ }
1209
+ finally {
1210
+ this.isFormmatting = false;
1211
+ }
1212
+ }
1213
+ _format(error, vm, privateObject) {
1214
+ const [zeroLiteral, oneLiteral, newLineLiteral] = (() => {
1215
+ if (this.literalsCache == null) {
1216
+ const zeroOneNewLine = [
1217
+ evalRbCode(vm, privateObject, "0"),
1218
+ evalRbCode(vm, privateObject, "1"),
1219
+ evalRbCode(vm, privateObject, `"\n"`),
1220
+ ];
1221
+ this.literalsCache = zeroOneNewLine;
1222
+ return zeroOneNewLine;
1223
+ }
1224
+ else {
1225
+ return this.literalsCache;
1226
+ }
1227
+ })();
1228
+ let className;
1229
+ let backtrace;
1230
+ let message;
1231
+ try {
1232
+ className = error.call("class").toString();
1233
+ }
1234
+ catch (e) {
1235
+ className = "unknown";
1236
+ }
1237
+ try {
1238
+ message = error.toString();
1239
+ }
1240
+ catch (e) {
1241
+ message = "unknown";
1242
+ }
1243
+ try {
1244
+ backtrace = error.call("backtrace");
1245
+ }
1246
+ catch (e) {
1247
+ return this.formatString(className, message);
1248
+ }
1249
+ if (backtrace.call("nil?").toString() === "true") {
1250
+ return this.formatString(className, message);
1251
+ }
1252
+ try {
1253
+ const firstLine = backtrace.call("at", zeroLiteral);
1254
+ const restLines = backtrace
1255
+ .call("drop", oneLiteral)
1256
+ .call("join", newLineLiteral);
1257
+ return this.formatString(className, message, [
1258
+ firstLine.toString(),
1259
+ restLines.toString(),
1260
+ ]);
1261
+ }
1262
+ catch (e) {
1263
+ return this.formatString(className, message);
1264
+ }
1265
+ }
1266
+ formatString(klass, message, backtrace) {
1267
+ if (backtrace) {
1268
+ return `${backtrace[0]}: ${message} (${klass})\n${backtrace[1]}`;
1269
+ }
1270
+ else {
1271
+ return `${klass}: ${message}`;
1272
+ }
1273
+ }
1274
+ }
1275
+ const checkStatusTag = (rawTag, vm, privateObject) => {
1276
+ switch (rawTag & ruby_tag_type.Mask) {
1277
+ case ruby_tag_type.None:
1278
+ break;
1279
+ case ruby_tag_type.Return:
1280
+ throw new RbError("unexpected return");
1281
+ case ruby_tag_type.Next:
1282
+ throw new RbError("unexpected next");
1283
+ case ruby_tag_type.Break:
1284
+ throw new RbError("unexpected break");
1285
+ case ruby_tag_type.Redo:
1286
+ throw new RbError("unexpected redo");
1287
+ case ruby_tag_type.Retry:
1288
+ throw new RbError("retry outside of rescue clause");
1289
+ case ruby_tag_type.Throw:
1290
+ throw new RbError("unexpected throw");
1291
+ case ruby_tag_type.Raise:
1292
+ case ruby_tag_type.Fatal:
1293
+ const error = new RbValue(vm.guest.rbErrinfo(), vm, privateObject);
1294
+ if (error.call("nil?").toString() === "true") {
1295
+ throw new RbError("no exception object");
1296
+ }
1297
+ // clear errinfo if got exception due to no rb_jump_tag
1298
+ vm.guest.rbClearErrinfo();
1299
+ throw new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
1300
+ default:
1301
+ throw new RbError(`unknown error tag: ${rawTag}`);
1302
+ }
1303
+ };
1304
+ function wrapRbOperation(vm, body) {
1305
+ try {
1306
+ return body();
1307
+ }
1308
+ catch (e) {
1309
+ if (e instanceof RbError) {
1310
+ throw e;
1311
+ }
1312
+ // All JS exceptions triggered by Ruby code are translated to Ruby exceptions,
1313
+ // so non-RbError exceptions are unexpected.
1314
+ vm.guest.rbVmBugreport();
1315
+ if (e instanceof WebAssembly.RuntimeError && e.message === "unreachable") {
1316
+ const error = new RbError(`Something went wrong in Ruby VM: ${e}`);
1317
+ error.stack = e.stack;
1318
+ throw error;
1319
+ }
1320
+ else {
1321
+ throw e;
1322
+ }
1323
+ }
1324
+ }
1325
+ const callRbMethod = (vm, privateObject, recv, callee, args) => {
1326
+ const mid = vm.guest.rbIntern(callee + "\0");
1327
+ return wrapRbOperation(vm, () => {
1328
+ const [value, status] = vm.guest.rbFuncallvProtect(recv, mid, args);
1329
+ checkStatusTag(status, vm, privateObject);
1330
+ return value;
1331
+ });
1332
+ };
1333
+ const evalRbCode = (vm, privateObject, code) => {
1334
+ return wrapRbOperation(vm, () => {
1335
+ const [value, status] = vm.guest.rbEvalStringProtect(code + "\0");
1336
+ checkStatusTag(status, vm, privateObject);
1337
+ return new RbValue(value, vm, privateObject);
1338
+ });
1339
+ };
1340
+ function newRbPromise(vm, privateObject, body) {
1341
+ return new Promise((resolve, reject) => {
1342
+ const future = vm.wrap({
1343
+ resolve,
1344
+ reject: (error) => {
1345
+ const rbError = new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
1346
+ reject(rbError);
1347
+ },
1348
+ });
1349
+ body(future);
1350
+ });
1351
+ }
1352
+ /**
1353
+ * Error class thrown by Ruby execution
1354
+ */
1355
+ class RbError extends Error {
1356
+ /**
1357
+ * @hideconstructor
1358
+ */
1359
+ constructor(message) {
1360
+ super(message);
1361
+ }
1362
+ }
1363
+ /**
1364
+ * Error class thrown by Ruby execution when it is not possible to recover.
1365
+ * This is usually caused when Ruby VM is in an inconsistent state.
1366
+ */
1367
+ class RbFatalError extends RbError {
1368
+ /**
1369
+ * @hideconstructor
1370
+ */
1371
+ constructor(message) {
1372
+ super("Ruby Fatal Error: " + message);
1373
+ }
1374
+ }
1342
1375
 
1343
- exports.RbError = RbError;
1344
- exports.RbFatalError = RbFatalError;
1345
- exports.RbValue = RbValue;
1346
- exports.RubyVM = RubyVM;
1347
- exports.consolePrinter = consolePrinter;
1376
+ exports.RbError = RbError;
1377
+ exports.RbFatalError = RbFatalError;
1378
+ exports.RbValue = RbValue;
1379
+ exports.RubyVM = RubyVM;
1380
+ exports.consolePrinter = consolePrinter;
1348
1381
 
1349
1382
  }));