@desert-ant-labs/gist 0.1.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.
@@ -0,0 +1,981 @@
1
+ /// Memory lifetime of closures in Swift are managed by Swift side
2
+ class SwiftClosureDeallocator {
3
+ constructor(exports$1) {
4
+ if (typeof FinalizationRegistry === "undefined") {
5
+ throw new Error("The Swift part of JavaScriptKit was configured to require " +
6
+ "the availability of JavaScript WeakRefs. Please build " +
7
+ "with `-Xswiftc -DJAVASCRIPTKIT_WITHOUT_WEAKREFS` to " +
8
+ "disable features that use WeakRefs.");
9
+ }
10
+ this.functionRegistry = new FinalizationRegistry((id) => {
11
+ exports$1.swjs_free_host_function(id);
12
+ });
13
+ }
14
+ track(func, func_ref) {
15
+ this.functionRegistry.register(func, func_ref);
16
+ }
17
+ }
18
+
19
+ function assertNever(x, message) {
20
+ throw new Error(message);
21
+ }
22
+ const MAIN_THREAD_TID = -1;
23
+
24
+ const decode = (kind, payload1, payload2, objectSpace) => {
25
+ switch (kind) {
26
+ case 0 /* Kind.Boolean */:
27
+ switch (payload1) {
28
+ case 0:
29
+ return false;
30
+ case 1:
31
+ return true;
32
+ }
33
+ // falls through
34
+ case 2 /* Kind.Number */:
35
+ return payload2;
36
+ case 1 /* Kind.String */:
37
+ case 3 /* Kind.Object */:
38
+ case 7 /* Kind.Symbol */:
39
+ case 8 /* Kind.BigInt */:
40
+ return objectSpace.getObject(payload1);
41
+ case 4 /* Kind.Null */:
42
+ return null;
43
+ case 5 /* Kind.Undefined */:
44
+ return undefined;
45
+ default:
46
+ assertNever(kind, `JSValue Type kind "${kind}" is not supported`);
47
+ }
48
+ };
49
+ // Note:
50
+ // `decodeValues` assumes that the size of RawJSValue is 16.
51
+ const decodeArray = (ptr, length, memory, objectSpace) => {
52
+ // fast path for empty array
53
+ if (length === 0) {
54
+ return [];
55
+ }
56
+ let result = [];
57
+ for (let index = 0; index < length; index++) {
58
+ const base = ptr + 16 * index;
59
+ const kind = memory.getUint32(base, true);
60
+ const payload1 = memory.getUint32(base + 4, true);
61
+ const payload2 = memory.getFloat64(base + 8, true);
62
+ result.push(decode(kind, payload1, payload2, objectSpace));
63
+ }
64
+ return result;
65
+ };
66
+ // A helper function to encode a RawJSValue into a pointers.
67
+ // Please prefer to use `writeAndReturnKindBits` to avoid unnecessary
68
+ // memory stores.
69
+ // This function should be used only when kind flag is stored in memory.
70
+ const write = (value, kind_ptr, payload1_ptr, payload2_ptr, is_exception, memory, objectSpace) => {
71
+ const kind = writeAndReturnKindBits(value, payload1_ptr, payload2_ptr, is_exception, memory, objectSpace);
72
+ memory.setUint32(kind_ptr, kind, true);
73
+ };
74
+ const writeAndReturnKindBits = (value, payload1_ptr, payload2_ptr, is_exception, memory, objectSpace) => {
75
+ const exceptionBit = (is_exception ? 1 : 0) << 31;
76
+ if (value === null) {
77
+ return exceptionBit | 4 /* Kind.Null */;
78
+ }
79
+ const writeRef = (kind) => {
80
+ memory.setUint32(payload1_ptr, objectSpace.retain(value), true);
81
+ return exceptionBit | kind;
82
+ };
83
+ const type = typeof value;
84
+ switch (type) {
85
+ case "boolean": {
86
+ memory.setUint32(payload1_ptr, value ? 1 : 0, true);
87
+ return exceptionBit | 0 /* Kind.Boolean */;
88
+ }
89
+ case "number": {
90
+ memory.setFloat64(payload2_ptr, value, true);
91
+ return exceptionBit | 2 /* Kind.Number */;
92
+ }
93
+ case "string": {
94
+ return writeRef(1 /* Kind.String */);
95
+ }
96
+ case "undefined": {
97
+ return exceptionBit | 5 /* Kind.Undefined */;
98
+ }
99
+ case "object": {
100
+ return writeRef(3 /* Kind.Object */);
101
+ }
102
+ case "function": {
103
+ return writeRef(3 /* Kind.Object */);
104
+ }
105
+ case "symbol": {
106
+ return writeRef(7 /* Kind.Symbol */);
107
+ }
108
+ case "bigint": {
109
+ return writeRef(8 /* Kind.BigInt */);
110
+ }
111
+ default:
112
+ assertNever(type, `Type "${type}" is not supported yet`);
113
+ }
114
+ throw new Error("Unreachable");
115
+ };
116
+ function decodeObjectRefs(ptr, length, memory) {
117
+ const result = new Array(length);
118
+ for (let i = 0; i < length; i++) {
119
+ result[i] = memory.getUint32(ptr + 4 * i, true);
120
+ }
121
+ return result;
122
+ }
123
+
124
+ class ITCInterface {
125
+ constructor(memory) {
126
+ this.memory = memory;
127
+ }
128
+ send(sendingObject, transferringObjects, sendingContext) {
129
+ const object = this.memory.getObject(sendingObject);
130
+ const transfer = transferringObjects.map((ref) => this.memory.getObject(ref));
131
+ return { object, sendingContext, transfer };
132
+ }
133
+ sendObjects(sendingObjects, transferringObjects, sendingContext) {
134
+ const objects = sendingObjects.map((ref) => this.memory.getObject(ref));
135
+ const transfer = transferringObjects.map((ref) => this.memory.getObject(ref));
136
+ return { object: objects, sendingContext, transfer };
137
+ }
138
+ invokeRemoteJSObjectBody(invocationContext) {
139
+ return { object: undefined, transfer: [] };
140
+ }
141
+ release(objectRef) {
142
+ this.memory.release(objectRef);
143
+ return { object: undefined, transfer: [] };
144
+ }
145
+ }
146
+ class MessageBroker {
147
+ constructor(selfTid, threadChannel, handlers) {
148
+ this.selfTid = selfTid;
149
+ this.threadChannel = threadChannel;
150
+ this.handlers = handlers;
151
+ }
152
+ request(message) {
153
+ if (message.data.targetTid == this.selfTid) {
154
+ // The request is for the current thread
155
+ this.handlers.onRequest(message);
156
+ }
157
+ else if ("postMessageToWorkerThread" in this.threadChannel) {
158
+ // The request is for another worker thread sent from the main thread
159
+ this.threadChannel.postMessageToWorkerThread(message.data.targetTid, message, []);
160
+ }
161
+ else if ("postMessageToMainThread" in this.threadChannel) {
162
+ // The request is for other worker threads or the main thread sent from a worker thread
163
+ this.threadChannel.postMessageToMainThread(message, []);
164
+ }
165
+ else {
166
+ throw new Error("unreachable");
167
+ }
168
+ }
169
+ reply(message) {
170
+ if (message.data.sourceTid == this.selfTid) {
171
+ // The response is for the current thread
172
+ this.handlers.onResponse(message);
173
+ return;
174
+ }
175
+ const transfer = message.data.response.ok
176
+ ? message.data.response.value.transfer
177
+ : [];
178
+ if ("postMessageToWorkerThread" in this.threadChannel) {
179
+ // The response is for another worker thread sent from the main thread
180
+ this.threadChannel.postMessageToWorkerThread(message.data.sourceTid, message, transfer);
181
+ }
182
+ else if ("postMessageToMainThread" in this.threadChannel) {
183
+ // The response is for other worker threads or the main thread sent from a worker thread
184
+ this.threadChannel.postMessageToMainThread(message, transfer);
185
+ }
186
+ else {
187
+ throw new Error("unreachable");
188
+ }
189
+ }
190
+ onReceivingRequest(message) {
191
+ if (message.data.targetTid == this.selfTid) {
192
+ this.handlers.onRequest(message);
193
+ }
194
+ else if ("postMessageToWorkerThread" in this.threadChannel) {
195
+ // Receive a request from a worker thread to other worker on main thread.
196
+ // Proxy the request to the target worker thread.
197
+ this.threadChannel.postMessageToWorkerThread(message.data.targetTid, message, []);
198
+ }
199
+ else if ("postMessageToMainThread" in this.threadChannel) {
200
+ // A worker thread won't receive a request for other worker threads
201
+ throw new Error("unreachable");
202
+ }
203
+ }
204
+ onReceivingResponse(message) {
205
+ if (message.data.sourceTid == this.selfTid) {
206
+ this.handlers.onResponse(message);
207
+ }
208
+ else if ("postMessageToWorkerThread" in this.threadChannel) {
209
+ // Receive a response from a worker thread to other worker on main thread.
210
+ // Proxy the response to the target worker thread.
211
+ const transfer = message.data.response.ok
212
+ ? message.data.response.value.transfer
213
+ : [];
214
+ this.threadChannel.postMessageToWorkerThread(message.data.sourceTid, message, transfer);
215
+ }
216
+ else if ("postMessageToMainThread" in this.threadChannel) {
217
+ // A worker thread won't receive a response for other worker threads
218
+ throw new Error("unreachable");
219
+ }
220
+ }
221
+ }
222
+ function serializeError(error) {
223
+ if (error instanceof Error) {
224
+ return {
225
+ isError: true,
226
+ value: {
227
+ message: error.message,
228
+ name: error.name,
229
+ stack: error.stack,
230
+ },
231
+ };
232
+ }
233
+ return { isError: false, value: error };
234
+ }
235
+ function deserializeError(error) {
236
+ if (error.isError) {
237
+ return Object.assign(new Error(error.value.message), error.value);
238
+ }
239
+ return error.value;
240
+ }
241
+
242
+ const globalVariable = globalThis;
243
+
244
+ const SLOT_BITS = 24;
245
+ const SLOT_MASK = (1 << SLOT_BITS) - 1;
246
+ const GEN_MASK = (1 << (32 - SLOT_BITS)) - 1;
247
+ class JSObjectSpace {
248
+ constructor() {
249
+ this._slotByValue = new Map();
250
+ this._values = [];
251
+ this._stateBySlot = [];
252
+ this._freeSlotStack = [];
253
+ // Note: 0 is preserved for invalid references, 1 is preserved for globalThis
254
+ this._values[0] = undefined;
255
+ this._values[1] = globalVariable;
256
+ this._slotByValue.set(globalVariable, 1);
257
+ this._stateBySlot[1] = 1; // gen=0, rc=1
258
+ }
259
+ retain(value) {
260
+ const slot = this._slotByValue.get(value);
261
+ if (slot !== undefined) {
262
+ const state = this._stateBySlot[slot];
263
+ const nextState = (state + 1) >>> 0;
264
+ if ((nextState & SLOT_MASK) === 0) {
265
+ throw new RangeError(`Reference count overflow at slot ${slot}`);
266
+ }
267
+ this._stateBySlot[slot] = nextState;
268
+ return ((nextState & ~SLOT_MASK) | slot) >>> 0;
269
+ }
270
+ let newSlot;
271
+ let state;
272
+ if (this._freeSlotStack.length > 0) {
273
+ newSlot = this._freeSlotStack.pop();
274
+ const gen = this._stateBySlot[newSlot] >>> SLOT_BITS;
275
+ state = ((gen << SLOT_BITS) | 1) >>> 0;
276
+ }
277
+ else {
278
+ newSlot = this._values.length;
279
+ if (newSlot > SLOT_MASK) {
280
+ throw new RangeError(`Reference slot overflow: ${newSlot} exceeds ${SLOT_MASK}`);
281
+ }
282
+ state = 1;
283
+ }
284
+ this._stateBySlot[newSlot] = state;
285
+ this._values[newSlot] = value;
286
+ this._slotByValue.set(value, newSlot);
287
+ return ((state & ~SLOT_MASK) | newSlot) >>> 0;
288
+ }
289
+ retainByRef(reference) {
290
+ const state = this._getValidatedSlotState(reference);
291
+ const slot = reference & SLOT_MASK;
292
+ const nextState = (state + 1) >>> 0;
293
+ if ((nextState & SLOT_MASK) === 0) {
294
+ throw new RangeError(`Reference count overflow at slot ${slot}`);
295
+ }
296
+ this._stateBySlot[slot] = nextState;
297
+ return reference;
298
+ }
299
+ release(reference) {
300
+ const state = this._getValidatedSlotState(reference);
301
+ const slot = reference & SLOT_MASK;
302
+ if ((state & SLOT_MASK) > 1) {
303
+ this._stateBySlot[slot] = (state - 1) >>> 0;
304
+ return;
305
+ }
306
+ this._slotByValue.delete(this._values[slot]);
307
+ this._values[slot] = undefined;
308
+ const nextGen = ((state >>> SLOT_BITS) + 1) & GEN_MASK;
309
+ this._stateBySlot[slot] = (nextGen << SLOT_BITS) >>> 0;
310
+ this._freeSlotStack.push(slot);
311
+ }
312
+ getObject(reference) {
313
+ this._getValidatedSlotState(reference);
314
+ return this._values[reference & SLOT_MASK];
315
+ }
316
+ // Returns the packed state for the slot, after validating the reference.
317
+ _getValidatedSlotState(reference) {
318
+ const slot = reference & SLOT_MASK;
319
+ if (slot === 0)
320
+ throw new ReferenceError(`Attempted to use invalid reference ${reference}`);
321
+ const state = this._stateBySlot[slot];
322
+ if (state === undefined || (state & SLOT_MASK) === 0) {
323
+ throw new ReferenceError(`Attempted to use invalid reference ${reference}`);
324
+ }
325
+ if (state >>> SLOT_BITS !== reference >>> SLOT_BITS) {
326
+ throw new ReferenceError(`Attempted to use stale reference ${reference}`);
327
+ }
328
+ return state;
329
+ }
330
+ }
331
+
332
+ class SwiftRuntime {
333
+ constructor(options) {
334
+ this.version = 708;
335
+ this.textDecoder = new TextDecoder("utf-8");
336
+ this.textEncoder = new TextEncoder(); // Only support utf-8
337
+ this.UnsafeEventLoopYield = UnsafeEventLoopYield;
338
+ /** @deprecated Use `wasmImports` instead */
339
+ this.importObjects = () => this.wasmImports;
340
+ this._instance = null;
341
+ this.memory = new JSObjectSpace();
342
+ this._closureDeallocator = null;
343
+ this.tid = null;
344
+ this.options = options || {};
345
+ this.getDataView = () => {
346
+ throw new Error("Please call setInstance() before using any JavaScriptKit APIs from Swift.");
347
+ };
348
+ this.getUint8Array = () => {
349
+ throw new Error("Please call setInstance() before using any JavaScriptKit APIs from Swift.");
350
+ };
351
+ this.wasmMemory = null;
352
+ }
353
+ setInstance(instance) {
354
+ this._instance = instance;
355
+ const wasmMemory = instance.exports.memory;
356
+ if (wasmMemory instanceof WebAssembly.Memory) {
357
+ // Cache the DataView as it's not a cheap operation
358
+ let cachedDataView = new DataView(wasmMemory.buffer);
359
+ let cachedUint8Array = new Uint8Array(wasmMemory.buffer);
360
+ // Check the constructor name of the buffer to determine if it's backed by a SharedArrayBuffer.
361
+ // We can't reference SharedArrayBuffer directly here because:
362
+ // 1. It may not be available in the global scope if the context is not cross-origin isolated.
363
+ // 2. The underlying buffer may be still backed by SAB even if the context is not cross-origin
364
+ // isolated (e.g. localhost on Chrome on Android).
365
+ if (Object.getPrototypeOf(wasmMemory.buffer).constructor.name ===
366
+ "SharedArrayBuffer") {
367
+ // When the wasm memory is backed by a SharedArrayBuffer, growing the memory
368
+ // doesn't invalidate the data view by setting the byte length to 0. Instead,
369
+ // the data view points to an old buffer after growing the memory. So we have
370
+ // to check the buffer identity to determine if the data view is valid.
371
+ this.getDataView = () => {
372
+ if (cachedDataView.buffer !== wasmMemory.buffer) {
373
+ cachedDataView = new DataView(wasmMemory.buffer);
374
+ }
375
+ return cachedDataView;
376
+ };
377
+ this.getUint8Array = () => {
378
+ if (cachedUint8Array.buffer !== wasmMemory.buffer) {
379
+ cachedUint8Array = new Uint8Array(wasmMemory.buffer);
380
+ }
381
+ return cachedUint8Array;
382
+ };
383
+ }
384
+ else {
385
+ this.getDataView = () => {
386
+ if (cachedDataView.buffer.byteLength === 0) {
387
+ // If the wasm memory is grown, the data view is invalidated,
388
+ // so we need to create a new data view.
389
+ cachedDataView = new DataView(wasmMemory.buffer);
390
+ }
391
+ return cachedDataView;
392
+ };
393
+ this.getUint8Array = () => {
394
+ if (cachedUint8Array.byteLength === 0) {
395
+ cachedUint8Array = new Uint8Array(wasmMemory.buffer);
396
+ }
397
+ return cachedUint8Array;
398
+ };
399
+ }
400
+ this.wasmMemory = wasmMemory;
401
+ }
402
+ else {
403
+ throw new Error("instance.exports.memory is not a WebAssembly.Memory!?");
404
+ }
405
+ if (typeof this.exports._start === "function") {
406
+ throw new Error(`JavaScriptKit supports only WASI reactor ABI.
407
+ Please make sure you are building with:
408
+ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor
409
+ `);
410
+ }
411
+ if (this.exports.swjs_library_version() != this.version) {
412
+ throw new Error(`The versions of JavaScriptKit are incompatible.
413
+ WebAssembly runtime ${this.exports.swjs_library_version()} != JS runtime ${this.version}`);
414
+ }
415
+ }
416
+ main() {
417
+ const instance = this.instance;
418
+ try {
419
+ if (typeof instance.exports.main === "function") {
420
+ instance.exports.main();
421
+ }
422
+ else if (typeof instance.exports.__main_argc_argv === "function") {
423
+ // Swift 6.0 and later use `__main_argc_argv` instead of `main`.
424
+ instance.exports.__main_argc_argv(0, 0);
425
+ }
426
+ }
427
+ catch (error) {
428
+ if (error instanceof UnsafeEventLoopYield) {
429
+ // Ignore the error
430
+ return;
431
+ }
432
+ // Rethrow other errors
433
+ throw error;
434
+ }
435
+ }
436
+ /**
437
+ * Start a new thread with the given `tid` and `startArg`, which
438
+ * is forwarded to the `wasi_thread_start` function.
439
+ * This function is expected to be called from the spawned Web Worker thread.
440
+ */
441
+ startThread(tid, startArg) {
442
+ this.tid = tid;
443
+ const instance = this.instance;
444
+ try {
445
+ if (typeof instance.exports.wasi_thread_start === "function") {
446
+ instance.exports.wasi_thread_start(tid, startArg);
447
+ }
448
+ else {
449
+ throw new Error(`The WebAssembly module is not built for wasm32-unknown-wasip1-threads target.`);
450
+ }
451
+ }
452
+ catch (error) {
453
+ if (error instanceof UnsafeEventLoopYield) {
454
+ // Ignore the error
455
+ return;
456
+ }
457
+ // Rethrow other errors
458
+ throw error;
459
+ }
460
+ }
461
+ get instance() {
462
+ if (!this._instance)
463
+ throw new Error("WebAssembly instance is not set yet");
464
+ return this._instance;
465
+ }
466
+ get exports() {
467
+ return this.instance.exports;
468
+ }
469
+ get closureDeallocator() {
470
+ if (this._closureDeallocator)
471
+ return this._closureDeallocator;
472
+ const features = this.exports.swjs_library_features();
473
+ const librarySupportsWeakRef = (features & 1 /* LibraryFeatures.WeakRefs */) != 0;
474
+ if (librarySupportsWeakRef) {
475
+ this._closureDeallocator = new SwiftClosureDeallocator(this.exports);
476
+ }
477
+ return this._closureDeallocator;
478
+ }
479
+ callHostFunction(host_func_id, line, file, args) {
480
+ const argc = args.length;
481
+ const argv = this.exports.swjs_prepare_host_function_call(argc);
482
+ const memory = this.memory;
483
+ const dataView = this.getDataView();
484
+ for (let index = 0; index < args.length; index++) {
485
+ const argument = args[index];
486
+ const base = argv + 16 * index;
487
+ write(argument, base, base + 4, base + 8, false, dataView, memory);
488
+ }
489
+ let output;
490
+ // This ref is released by the swjs_call_host_function implementation
491
+ const callback_func_ref = memory.retain((result) => {
492
+ output = result;
493
+ });
494
+ const alreadyReleased = this.exports.swjs_call_host_function(host_func_id, argv, argc, callback_func_ref);
495
+ if (alreadyReleased) {
496
+ throw new Error(`The JSClosure has been already released by Swift side. The closure is created at ${file}:${line} @${host_func_id}`);
497
+ }
498
+ this.exports.swjs_cleanup_host_function_call(argv);
499
+ return output;
500
+ }
501
+ get wasmImports() {
502
+ let broker = null;
503
+ const getMessageBroker = (threadChannel) => {
504
+ var _a;
505
+ if (broker)
506
+ return broker;
507
+ const itcInterface = new ITCInterface(this.memory);
508
+ const defaultRequestHandler = (message) => {
509
+ const request = message.data.request;
510
+ // @ts-ignore dynamic dispatch by method name
511
+ const result = itcInterface[request.method].apply(itcInterface, request.parameters);
512
+ return { ok: true, value: result };
513
+ };
514
+ const requestHandlers = {
515
+ invokeRemoteJSObjectBody: (message) => {
516
+ const invocationContext = message.data.request
517
+ .parameters[0];
518
+ const hasError = this.exports.swjs_invoke_remote_jsobject_body(invocationContext);
519
+ return {
520
+ ok: true,
521
+ value: {
522
+ object: hasError,
523
+ sendingContext: message.data.context,
524
+ transfer: [],
525
+ },
526
+ };
527
+ },
528
+ };
529
+ const defaultResponseHandler = (message) => {
530
+ if (message.data.response.ok) {
531
+ const object = this.memory.retain(message.data.response.value.object);
532
+ this.exports.swjs_receive_response(object, message.data.context);
533
+ }
534
+ else {
535
+ const error = deserializeError(message.data.response.error);
536
+ const errorObject = this.memory.retain(error);
537
+ this.exports.swjs_receive_error(errorObject, message.data.context);
538
+ }
539
+ };
540
+ const responseHandlers = {
541
+ invokeRemoteJSObjectBody: (_message) => {
542
+ // Swift continuation is resumed on the owner thread.
543
+ },
544
+ };
545
+ const newBroker = new MessageBroker((_a = this.tid) !== null && _a !== void 0 ? _a : -1, threadChannel, {
546
+ onRequest: (message) => {
547
+ var _a;
548
+ let returnValue;
549
+ try {
550
+ const method = message.data.request.method;
551
+ const handler = (_a = requestHandlers[method]) !== null && _a !== void 0 ? _a : defaultRequestHandler;
552
+ returnValue = handler(message);
553
+ }
554
+ catch (error) {
555
+ returnValue = {
556
+ ok: false,
557
+ error: serializeError(error),
558
+ };
559
+ }
560
+ const responseMessage = {
561
+ type: "response",
562
+ data: {
563
+ sourceTid: message.data.sourceTid,
564
+ context: message.data.context,
565
+ requestMethod: message.data.request.method,
566
+ response: returnValue,
567
+ },
568
+ };
569
+ try {
570
+ newBroker.reply(responseMessage);
571
+ }
572
+ catch (error) {
573
+ responseMessage.data.response = {
574
+ ok: false,
575
+ error: serializeError(new TypeError(`Failed to serialize message: ${error}`)),
576
+ };
577
+ newBroker.reply(responseMessage);
578
+ }
579
+ },
580
+ onResponse: (message) => {
581
+ var _a;
582
+ const method = message.data.requestMethod;
583
+ const handler = (_a = responseHandlers[method]) !== null && _a !== void 0 ? _a : defaultResponseHandler;
584
+ handler(message);
585
+ },
586
+ });
587
+ broker = newBroker;
588
+ return newBroker;
589
+ };
590
+ return {
591
+ swjs_set_prop: (ref, name, kind, payload1, payload2) => {
592
+ const memory = this.memory;
593
+ const obj = memory.getObject(ref);
594
+ const key = memory.getObject(name);
595
+ const value = decode(kind, payload1, payload2, memory);
596
+ obj[key] = value;
597
+ },
598
+ swjs_get_prop: (ref, name, payload1_ptr, payload2_ptr) => {
599
+ const memory = this.memory;
600
+ const obj = memory.getObject(ref);
601
+ const key = memory.getObject(name);
602
+ const result = obj[key];
603
+ return writeAndReturnKindBits(result, payload1_ptr, payload2_ptr, false, this.getDataView(), this.memory);
604
+ },
605
+ swjs_set_subscript: (ref, index, kind, payload1, payload2) => {
606
+ const memory = this.memory;
607
+ const obj = memory.getObject(ref);
608
+ const value = decode(kind, payload1, payload2, memory);
609
+ obj[index] = value;
610
+ },
611
+ swjs_get_subscript: (ref, index, payload1_ptr, payload2_ptr) => {
612
+ const obj = this.memory.getObject(ref);
613
+ const result = obj[index];
614
+ return writeAndReturnKindBits(result, payload1_ptr, payload2_ptr, false, this.getDataView(), this.memory);
615
+ },
616
+ swjs_encode_string: (ref, bytes_ptr_result) => {
617
+ const memory = this.memory;
618
+ const bytes = this.textEncoder.encode(memory.getObject(ref));
619
+ const bytes_ptr = memory.retain(bytes);
620
+ this.getDataView().setUint32(bytes_ptr_result, bytes_ptr, true);
621
+ return bytes.length;
622
+ },
623
+ swjs_decode_string:
624
+ // NOTE: TextDecoder can't decode typed arrays backed by SharedArrayBuffer
625
+ this.options.sharedMemory == true
626
+ ? (bytes_ptr, length) => {
627
+ const bytes = this.getUint8Array().slice(bytes_ptr, bytes_ptr + length);
628
+ const string = this.textDecoder.decode(bytes);
629
+ return this.memory.retain(string);
630
+ }
631
+ : (bytes_ptr, length) => {
632
+ const bytes = this.getUint8Array().subarray(bytes_ptr, bytes_ptr + length);
633
+ const string = this.textDecoder.decode(bytes);
634
+ return this.memory.retain(string);
635
+ },
636
+ swjs_load_string: (ref, buffer) => {
637
+ const bytes = this.memory.getObject(ref);
638
+ this.getUint8Array().set(bytes, buffer);
639
+ },
640
+ swjs_call_function: (ref, argv, argc, payload1_ptr, payload2_ptr) => {
641
+ const memory = this.memory;
642
+ const func = memory.getObject(ref);
643
+ let result;
644
+ try {
645
+ const args = decodeArray(argv, argc, this.getDataView(), memory);
646
+ result = func(...args);
647
+ }
648
+ catch (error) {
649
+ return writeAndReturnKindBits(error, payload1_ptr, payload2_ptr, true, this.getDataView(), this.memory);
650
+ }
651
+ return writeAndReturnKindBits(result, payload1_ptr, payload2_ptr, false, this.getDataView(), this.memory);
652
+ },
653
+ swjs_call_function_no_catch: (ref, argv, argc, payload1_ptr, payload2_ptr) => {
654
+ const memory = this.memory;
655
+ const func = memory.getObject(ref);
656
+ const args = decodeArray(argv, argc, this.getDataView(), memory);
657
+ const result = func(...args);
658
+ return writeAndReturnKindBits(result, payload1_ptr, payload2_ptr, false, this.getDataView(), this.memory);
659
+ },
660
+ swjs_call_function_with_this: (obj_ref, func_ref, argv, argc, payload1_ptr, payload2_ptr) => {
661
+ const memory = this.memory;
662
+ const obj = memory.getObject(obj_ref);
663
+ const func = memory.getObject(func_ref);
664
+ let result;
665
+ try {
666
+ const args = decodeArray(argv, argc, this.getDataView(), memory);
667
+ result = func.apply(obj, args);
668
+ }
669
+ catch (error) {
670
+ return writeAndReturnKindBits(error, payload1_ptr, payload2_ptr, true, this.getDataView(), this.memory);
671
+ }
672
+ return writeAndReturnKindBits(result, payload1_ptr, payload2_ptr, false, this.getDataView(), this.memory);
673
+ },
674
+ swjs_call_function_with_this_no_catch: (obj_ref, func_ref, argv, argc, payload1_ptr, payload2_ptr) => {
675
+ const memory = this.memory;
676
+ const obj = memory.getObject(obj_ref);
677
+ const func = memory.getObject(func_ref);
678
+ const args = decodeArray(argv, argc, this.getDataView(), memory);
679
+ const result = func.apply(obj, args);
680
+ return writeAndReturnKindBits(result, payload1_ptr, payload2_ptr, false, this.getDataView(), this.memory);
681
+ },
682
+ swjs_call_new: (ref, argv, argc) => {
683
+ const memory = this.memory;
684
+ const constructor = memory.getObject(ref);
685
+ const args = decodeArray(argv, argc, this.getDataView(), memory);
686
+ const instance = new constructor(...args);
687
+ return this.memory.retain(instance);
688
+ },
689
+ swjs_call_throwing_new: (ref, argv, argc, exception_kind_ptr, exception_payload1_ptr, exception_payload2_ptr) => {
690
+ let memory = this.memory;
691
+ const constructor = memory.getObject(ref);
692
+ let result;
693
+ try {
694
+ const args = decodeArray(argv, argc, this.getDataView(), memory);
695
+ result = new constructor(...args);
696
+ }
697
+ catch (error) {
698
+ write(error, exception_kind_ptr, exception_payload1_ptr, exception_payload2_ptr, true, this.getDataView(), this.memory);
699
+ return -1;
700
+ }
701
+ memory = this.memory;
702
+ write(null, exception_kind_ptr, exception_payload1_ptr, exception_payload2_ptr, false, this.getDataView(), memory);
703
+ return memory.retain(result);
704
+ },
705
+ swjs_instanceof: (obj_ref, constructor_ref) => {
706
+ const memory = this.memory;
707
+ const obj = memory.getObject(obj_ref);
708
+ const constructor = memory.getObject(constructor_ref);
709
+ return obj instanceof constructor;
710
+ },
711
+ swjs_value_equals: (lhs_ref, rhs_ref) => {
712
+ const memory = this.memory;
713
+ const lhs = memory.getObject(lhs_ref);
714
+ const rhs = memory.getObject(rhs_ref);
715
+ return lhs == rhs;
716
+ },
717
+ swjs_create_function: (host_func_id, line, file) => {
718
+ var _a;
719
+ const fileString = this.memory.getObject(file);
720
+ const func = (...args) => this.callHostFunction(host_func_id, line, fileString, args);
721
+ const func_ref = this.memory.retain(func);
722
+ (_a = this.closureDeallocator) === null || _a === void 0 ? void 0 : _a.track(func, host_func_id);
723
+ return func_ref;
724
+ },
725
+ swjs_create_oneshot_function: (host_func_id, line, file) => {
726
+ const fileString = this.memory.getObject(file);
727
+ const func = (...args) => this.callHostFunction(host_func_id, line, fileString, args);
728
+ const func_ref = this.memory.retain(func);
729
+ return func_ref;
730
+ },
731
+ swjs_create_typed_array: (constructor_ref, elementsPtr, length) => {
732
+ const ArrayType = this.memory.getObject(constructor_ref);
733
+ if (length == 0) {
734
+ // The elementsPtr can be unaligned in Swift's Array
735
+ // implementation when the array is empty. However,
736
+ // TypedArray requires the pointer to be aligned.
737
+ // So, we need to create a new empty array without
738
+ // using the elementsPtr.
739
+ // See https://github.com/swiftwasm/swift/issues/5599
740
+ return this.memory.retain(new ArrayType());
741
+ }
742
+ const array = new ArrayType(this.wasmMemory.buffer, elementsPtr, length);
743
+ // Call `.slice()` to copy the memory
744
+ return this.memory.retain(array.slice());
745
+ },
746
+ swjs_create_object: () => {
747
+ return this.memory.retain({});
748
+ },
749
+ swjs_load_typed_array: (ref, buffer) => {
750
+ const memory = this.memory;
751
+ const typedArray = memory.getObject(ref);
752
+ const bytes = new Uint8Array(typedArray.buffer);
753
+ this.getUint8Array().set(bytes, buffer);
754
+ },
755
+ swjs_release: (ref) => {
756
+ this.memory.release(ref);
757
+ },
758
+ swjs_release_remote: (tid, ref) => {
759
+ var _a;
760
+ if (!this.options.threadChannel) {
761
+ throw new Error("threadChannel is not set in options given to SwiftRuntime. Please set it to release objects on remote threads.");
762
+ }
763
+ const broker = getMessageBroker(this.options.threadChannel);
764
+ broker.request({
765
+ type: "request",
766
+ data: {
767
+ sourceTid: (_a = this.tid) !== null && _a !== void 0 ? _a : MAIN_THREAD_TID,
768
+ targetTid: tid,
769
+ context: 0,
770
+ request: {
771
+ method: "release",
772
+ parameters: [ref],
773
+ },
774
+ },
775
+ });
776
+ },
777
+ swjs_i64_to_bigint: (value, signed) => {
778
+ return this.memory.retain(signed ? value : BigInt.asUintN(64, value));
779
+ },
780
+ swjs_bigint_to_i64: (ref, signed) => {
781
+ const object = this.memory.getObject(ref);
782
+ if (typeof object !== "bigint") {
783
+ throw new Error(`Expected a BigInt, but got ${typeof object}`);
784
+ }
785
+ if (signed) {
786
+ return object;
787
+ }
788
+ else {
789
+ if (object < BigInt(0)) {
790
+ return BigInt(0);
791
+ }
792
+ return BigInt.asIntN(64, object);
793
+ }
794
+ },
795
+ swjs_i64_to_bigint_slow: (lower, upper, signed) => {
796
+ const value = BigInt.asUintN(32, BigInt(lower)) +
797
+ (BigInt.asUintN(32, BigInt(upper)) << BigInt(32));
798
+ return this.memory.retain(signed
799
+ ? BigInt.asIntN(64, value)
800
+ : BigInt.asUintN(64, value));
801
+ },
802
+ swjs_unsafe_event_loop_yield: () => {
803
+ throw new UnsafeEventLoopYield();
804
+ },
805
+ swjs_send_job_to_main_thread: (unowned_job) => {
806
+ this.postMessageToMainThread({
807
+ type: "job",
808
+ data: unowned_job,
809
+ });
810
+ },
811
+ swjs_listen_message_from_main_thread: () => {
812
+ const threadChannel = this.options.threadChannel;
813
+ if (!(threadChannel &&
814
+ "listenMessageFromMainThread" in threadChannel)) {
815
+ throw new Error("listenMessageFromMainThread is not set in options given to SwiftRuntime. Please set it to listen to wake events from the main thread.");
816
+ }
817
+ const broker = getMessageBroker(threadChannel);
818
+ threadChannel.listenMessageFromMainThread((message) => {
819
+ switch (message.type) {
820
+ case "wake":
821
+ this.exports.swjs_wake_worker_thread();
822
+ break;
823
+ case "request": {
824
+ broker.onReceivingRequest(message);
825
+ break;
826
+ }
827
+ case "response": {
828
+ broker.onReceivingResponse(message);
829
+ break;
830
+ }
831
+ default: {
832
+ const unknownMessage = message;
833
+ throw new Error(`Unknown message type: ${unknownMessage}`);
834
+ }
835
+ }
836
+ });
837
+ },
838
+ swjs_wake_up_worker_thread: (tid) => {
839
+ this.postMessageToWorkerThread(tid, { type: "wake" });
840
+ },
841
+ swjs_listen_message_from_worker_thread: (tid) => {
842
+ const threadChannel = this.options.threadChannel;
843
+ if (!(threadChannel &&
844
+ "listenMessageFromWorkerThread" in threadChannel)) {
845
+ throw new Error("listenMessageFromWorkerThread is not set in options given to SwiftRuntime. Please set it to listen to jobs from worker threads.");
846
+ }
847
+ const broker = getMessageBroker(threadChannel);
848
+ threadChannel.listenMessageFromWorkerThread(tid, (message) => {
849
+ switch (message.type) {
850
+ case "job":
851
+ this.exports.swjs_enqueue_main_job_from_worker(message.data);
852
+ break;
853
+ case "request": {
854
+ broker.onReceivingRequest(message);
855
+ break;
856
+ }
857
+ case "response": {
858
+ broker.onReceivingResponse(message);
859
+ break;
860
+ }
861
+ default: {
862
+ const unknownMessage = message;
863
+ throw new Error(`Unknown message type: ${unknownMessage}`);
864
+ }
865
+ }
866
+ });
867
+ },
868
+ swjs_terminate_worker_thread: (tid) => {
869
+ var _a;
870
+ const threadChannel = this.options.threadChannel;
871
+ if (threadChannel && "terminateWorkerThread" in threadChannel) {
872
+ (_a = threadChannel.terminateWorkerThread) === null || _a === void 0 ? void 0 : _a.call(threadChannel, tid);
873
+ } // Otherwise, just ignore the termination request
874
+ },
875
+ swjs_get_worker_thread_id: () => {
876
+ // Main thread's tid is always -1
877
+ return this.tid || -1;
878
+ },
879
+ swjs_request_sending_object: (sending_object, transferring_objects, transferring_objects_count, object_source_tid, sending_context) => {
880
+ var _a;
881
+ if (!this.options.threadChannel) {
882
+ throw new Error("threadChannel is not set in options given to SwiftRuntime. Please set it to request transferring objects.");
883
+ }
884
+ const broker = getMessageBroker(this.options.threadChannel);
885
+ const transferringObjects = decodeObjectRefs(transferring_objects, transferring_objects_count, this.getDataView());
886
+ broker.request({
887
+ type: "request",
888
+ data: {
889
+ sourceTid: (_a = this.tid) !== null && _a !== void 0 ? _a : MAIN_THREAD_TID,
890
+ targetTid: object_source_tid,
891
+ context: sending_context,
892
+ request: {
893
+ method: "send",
894
+ parameters: [
895
+ sending_object,
896
+ transferringObjects,
897
+ sending_context,
898
+ ],
899
+ },
900
+ },
901
+ });
902
+ },
903
+ swjs_request_sending_objects: (sending_objects, sending_objects_count, transferring_objects, transferring_objects_count, object_source_tid, sending_context) => {
904
+ var _a;
905
+ if (!this.options.threadChannel) {
906
+ throw new Error("threadChannel is not set in options given to SwiftRuntime. Please set it to request transferring objects.");
907
+ }
908
+ const broker = getMessageBroker(this.options.threadChannel);
909
+ const dataView = this.getDataView();
910
+ const sendingObjects = decodeObjectRefs(sending_objects, sending_objects_count, dataView);
911
+ const transferringObjects = decodeObjectRefs(transferring_objects, transferring_objects_count, dataView);
912
+ broker.request({
913
+ type: "request",
914
+ data: {
915
+ sourceTid: (_a = this.tid) !== null && _a !== void 0 ? _a : MAIN_THREAD_TID,
916
+ targetTid: object_source_tid,
917
+ context: sending_context,
918
+ request: {
919
+ method: "sendObjects",
920
+ parameters: [
921
+ sendingObjects,
922
+ transferringObjects,
923
+ sending_context,
924
+ ],
925
+ },
926
+ },
927
+ });
928
+ },
929
+ swjs_request_remote_jsobject_body: (object_source_tid, invocation_context) => {
930
+ var _a;
931
+ if (!this.options.threadChannel) {
932
+ throw new Error("threadChannel is not set in options given to SwiftRuntime. Please set it to request remote JSObject access.");
933
+ }
934
+ const broker = getMessageBroker(this.options.threadChannel);
935
+ broker.request({
936
+ type: "request",
937
+ data: {
938
+ sourceTid: (_a = this.tid) !== null && _a !== void 0 ? _a : MAIN_THREAD_TID,
939
+ targetTid: object_source_tid,
940
+ context: invocation_context,
941
+ request: {
942
+ method: "invokeRemoteJSObjectBody",
943
+ parameters: [invocation_context],
944
+ },
945
+ },
946
+ });
947
+ },
948
+ };
949
+ }
950
+ postMessageToMainThread(message, transfer = []) {
951
+ const threadChannel = this.options.threadChannel;
952
+ if (!(threadChannel && "postMessageToMainThread" in threadChannel)) {
953
+ throw new Error("postMessageToMainThread is not set in options given to SwiftRuntime. Please set it to send messages to the main thread.");
954
+ }
955
+ threadChannel.postMessageToMainThread(message, transfer);
956
+ }
957
+ postMessageToWorkerThread(tid, message, transfer = []) {
958
+ const threadChannel = this.options.threadChannel;
959
+ if (!(threadChannel && "postMessageToWorkerThread" in threadChannel)) {
960
+ throw new Error("postMessageToWorkerThread is not set in options given to SwiftRuntime. Please set it to send messages to worker threads.");
961
+ }
962
+ threadChannel.postMessageToWorkerThread(tid, message, transfer);
963
+ }
964
+ }
965
+ /// This error is thrown when yielding event loop control from `swift_task_asyncMainDrainQueue`
966
+ /// to JavaScript. This is usually thrown when:
967
+ /// - The entry point of the Swift program is `func main() async`
968
+ /// - The Swift Concurrency's global executor is hooked by `JavaScriptEventLoop.installGlobalExecutor()`
969
+ /// - Calling exported `main` or `__main_argc_argv` function from JavaScript
970
+ ///
971
+ /// This exception must be caught by the caller of the exported function and the caller should
972
+ /// catch this exception and just ignore it.
973
+ ///
974
+ /// FAQ: Why this error is thrown?
975
+ /// This error is thrown to unwind the call stack of the Swift program and return the control to
976
+ /// the JavaScript side. Otherwise, the `swift_task_asyncMainDrainQueue` ends up with `abort()`
977
+ /// because the event loop expects `exit()` call before the end of the event loop.
978
+ class UnsafeEventLoopYield extends Error {
979
+ }
980
+
981
+ export { SwiftRuntime };