|
| 1 | +import { instantiate } from "./instantiate.js" |
| 2 | +import * as WasmImportsParser from 'https://esm.run/wasm-imports-parser/polyfill.js'; |
| 3 | + |
| 4 | +// TODO: Remove this polyfill once the browser supports the WebAssembly Type Reflection JS API |
| 5 | +// https://chromestatus.com/feature/5725002447978496 |
| 6 | +globalThis.WebAssembly = WasmImportsParser.polyfill(globalThis.WebAssembly); |
| 7 | + |
| 8 | +class ThreadRegistry { |
| 9 | + workers = new Map(); |
| 10 | + nextTid = 1; |
| 11 | + |
| 12 | + constructor({ configuration }) { |
| 13 | + this.configuration = configuration; |
| 14 | + } |
| 15 | + |
| 16 | + spawnThread(worker, module, memory, startArg) { |
| 17 | + const tid = this.nextTid++; |
| 18 | + this.workers.set(tid, worker); |
| 19 | + worker.postMessage({ module, memory, tid, startArg, configuration: this.configuration }); |
| 20 | + return tid; |
| 21 | + } |
| 22 | + |
| 23 | + listenMessageFromWorkerThread(tid, listener) { |
| 24 | + const worker = this.workers.get(tid); |
| 25 | + worker.onmessage = (event) => { |
| 26 | + listener(event.data); |
| 27 | + }; |
| 28 | + } |
| 29 | + |
| 30 | + postMessageToWorkerThread(tid, data) { |
| 31 | + const worker = this.workers.get(tid); |
| 32 | + worker.postMessage(data); |
| 33 | + } |
| 34 | + |
| 35 | + terminateWorkerThread(tid) { |
| 36 | + const worker = this.workers.get(tid); |
| 37 | + worker.terminate(); |
| 38 | + this.workers.delete(tid); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +async function start(configuration = "release") { |
| 43 | + const response = await fetch(`./.build/${configuration}/MyApp.wasm`); |
| 44 | + const module = await WebAssembly.compileStreaming(response); |
| 45 | + const memoryImport = WebAssembly.Module.imports(module).find(i => i.module === "env" && i.name === "memory"); |
| 46 | + if (!memoryImport) { |
| 47 | + throw new Error("Memory import not found"); |
| 48 | + } |
| 49 | + if (!memoryImport.type) { |
| 50 | + throw new Error("Memory import type not found"); |
| 51 | + } |
| 52 | + const memoryType = memoryImport.type; |
| 53 | + const memory = new WebAssembly.Memory({ initial: memoryType.minimum, maximum: memoryType.maximum, shared: true }); |
| 54 | + const threads = new ThreadRegistry({ configuration }); |
| 55 | + const { instance, swiftRuntime, wasi } = await instantiate({ |
| 56 | + module, |
| 57 | + threadChannel: threads, |
| 58 | + addToImports(importObject) { |
| 59 | + importObject["env"] = { memory } |
| 60 | + importObject["wasi"] = { |
| 61 | + "thread-spawn": (startArg) => { |
| 62 | + const worker = new Worker("Sources/JavaScript/worker.js", { type: "module" }); |
| 63 | + return threads.spawnThread(worker, module, memory, startArg); |
| 64 | + } |
| 65 | + }; |
| 66 | + }, |
| 67 | + configuration |
| 68 | + }); |
| 69 | + wasi.initialize(instance); |
| 70 | + |
| 71 | + swiftRuntime.main(); |
| 72 | +} |
| 73 | + |
| 74 | +start(); |
0 commit comments