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