|
1 | | -import * as imports from "./shim.mjs"; |
2 | | -import mod from "./app.wasm"; |
| 1 | +import "./wasm_exec.js"; |
| 2 | +import { createRuntimeContext, loadModule } from "./runtime.mjs"; |
3 | 3 |
|
4 | | -imports.init(mod); |
| 4 | +let mod; |
5 | 5 |
|
6 | | -export default { fetch: imports.fetch, scheduled: imports.scheduled, queue: imports.queue }; |
| 6 | +globalThis.tryCatch = (fn) => { |
| 7 | + try { |
| 8 | + return { |
| 9 | + result: fn(), |
| 10 | + }; |
| 11 | + } catch (e) { |
| 12 | + return { |
| 13 | + error: e, |
| 14 | + }; |
| 15 | + } |
| 16 | +}; |
| 17 | + |
| 18 | +async function run(ctx) { |
| 19 | + if (mod === undefined) { |
| 20 | + mod = await loadModule(); |
| 21 | + } |
| 22 | + const go = new Go(); |
| 23 | + |
| 24 | + let ready; |
| 25 | + const readyPromise = new Promise((resolve) => { |
| 26 | + ready = resolve; |
| 27 | + }); |
| 28 | + const instance = new WebAssembly.Instance(mod, { |
| 29 | + ...go.importObject, |
| 30 | + workers: { |
| 31 | + ready: () => { |
| 32 | + ready(); |
| 33 | + }, |
| 34 | + }, |
| 35 | + }); |
| 36 | + go.run(instance, ctx); |
| 37 | + await readyPromise; |
| 38 | +} |
| 39 | + |
| 40 | +async function fetch(req, env, ctx) { |
| 41 | + const binding = {}; |
| 42 | + await run(createRuntimeContext({ env, ctx, binding })); |
| 43 | + return binding.handleRequest(req); |
| 44 | +} |
| 45 | + |
| 46 | +async function scheduled(event, env, ctx) { |
| 47 | + const binding = {}; |
| 48 | + await run(createRuntimeContext({ env, ctx, binding })); |
| 49 | + return binding.runScheduler(event); |
| 50 | +} |
| 51 | + |
| 52 | +async function queue(batch, env, ctx) { |
| 53 | + const binding = {}; |
| 54 | + await run(createRuntimeContext({ env, ctx, binding })); |
| 55 | + return binding.handleQueueMessageBatch(batch); |
| 56 | +} |
| 57 | + |
| 58 | +// onRequest handles request to Cloudflare Pages |
| 59 | +async function onRequest(ctx) { |
| 60 | + const binding = {}; |
| 61 | + const { request, env } = ctx; |
| 62 | + await run(createRuntimeContext({ env, ctx, binding })); |
| 63 | + return binding.handleRequest(request); |
| 64 | +} |
| 65 | + |
| 66 | +export default { |
| 67 | + fetch, |
| 68 | + scheduled, |
| 69 | + queue, |
| 70 | + onRequest, |
| 71 | +}; |
0 commit comments