"import wasmModule from \"./app.wasm\";\n\n// app.wasm は definy のコンパイラ (core.compile-to-wasm) が出す Wasm GC のモジュール。\n// 値は GC のヒープにあるので, エクスポートしたランタイム関数で作って読む\nconst TAG_NUMBER = 0;\nconst TAG_BOOLEAN = 1;\nconst TAG_STRING = 2;\nconst TAG_LIST = 3;\nconst TAG_RECORD = 4;\nconst TAG_CLOSURE = 5;\nconst TAG_VARIANT = 6;\nconst TAG_FLOAT = 7;\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nfunction writeString(exports, value) {\n const maxBytes = value.length * 3;\n if (exports.memory.buffer.byteLength < maxBytes) {\n exports.memory.grow(Math.ceil((maxBytes - exports.memory.buffer.byteLength) / 65536));\n }\n const { written } = encoder.encodeInto(value, new Uint8Array(exports.memory.buffer, 0, maxBytes));\n return exports.string_from_memory(written);\n}\n\nfunction readString(exports, ref) {\n const length = exports.string_to_memory(ref);\n return decoder.decode(new Uint8Array(exports.memory.buffer, 0, length));\n}\n\nfunction valuesOf(exports, ref) {\n const array = exports.values_of(ref);\n if (array === null) return [];\n const length = exports.values_length(array);\n const items = [];\n for (let i = 0; i < length; i++) items.push(exports.values_get(array, i));\n return items;\n}\n\nfunction writeValues(exports, items) {\n const array = exports.values_new(items.length);\n items.forEach((item, i) => exports.values_set(array, i, item));\n return array;\n}\n\nfunction writeRecord(exports, entries) {\n return exports.record_new(\n writeValues(exports, entries.flatMap(([key, value]) => [writeString(exports, key), value]))\n );\n}\n\nfunction recordField(exports, ref, key) {\n if (ref === null || exports.value_tag(ref) !== TAG_RECORD) return null;\n const items = valuesOf(exports, ref);\n for (let i = 0; i + 1 < items.length; i += 2) {\n if (readString(exports, items[i]) === key) return items[i + 1];\n }\n return null;\n}\n\nfunction readDefinyValue(exports, ref) {\n if (ref === null) return null;\n switch (exports.value_tag(ref)) {\n case TAG_NUMBER:\n return Number(exports.number_value(ref));\n case TAG_BOOLEAN:\n return exports.bool_value(ref) !== 0;\n case TAG_FLOAT:\n return exports.float_value(ref);\n case TAG_STRING:\n return readString(exports, ref);\n case TAG_LIST:\n return valuesOf(exports, ref).map((item) => readDefinyValue(exports, item));\n case TAG_RECORD: {\n const items = valuesOf(exports, ref);\n const obj = {};\n for (let i = 0; i + 1 < items.length; i += 2) {\n obj[readString(exports, items[i])] = readDefinyValue(exports, items[i + 1]);\n }\n return obj;\n }\n case TAG_CLOSURE:\n return { __closure: true };\n case TAG_VARIANT: {\n const payload = exports.variant_payload(ref);\n return {\n tag: readString(exports, exports.variant_tag(ref)),\n payload: payload === null ? null : readDefinyValue(exports, payload),\n };\n }\n }\n return null;\n}\n\nfunction callClosure(exports, closure, args) {\n const fn = exports.table.get(exports.closure_index(closure));\n return fn(exports.values_of(closure), writeValues(exports, args));\n}\n\nfunction writeHttpRequest(exports, request, bodyBytes) {\n const headers = [];\n request.headers.forEach((value, name) => {\n headers.push(\n writeRecord(exports, [\n [\"name\", writeString(exports, name)],\n [\"value\", writeString(exports, value)],\n ])\n );\n });\n const bytes = writeValues(\n exports,\n Array.from(bodyBytes, (byte) => exports.box_number(BigInt(byte)))\n );\n return writeRecord(exports, [\n [\"method\", writeString(exports, request.method)],\n [\"url\", writeString(exports, request.url)],\n [\"headers\", exports.list_new(writeValues(exports, headers))],\n [\n \"body\",\n writeRecord(exports, [\n [\"initialState\", exports.box_number(0n)],\n [\"bytes\", exports.list_new(bytes)],\n [\"text\", writeString(exports, decoder.decode(bodyBytes))],\n ]),\n ],\n ]);\n}\n\nfunction createPullByteReadableStream(exports, body) {\n const next = recordField(exports, body, \"next\");\n let state = recordField(exports, body, \"initialState\");\n let steps = 0;\n return new ReadableStream({\n pull(controller) {\n while (state !== null && steps < 10000) {\n steps++;\n const step = callClosure(exports, next, [state]);\n if (step === null || exports.value_tag(step) !== TAG_VARIANT) break;\n const payload = exports.variant_payload(step);\n if (readString(exports, exports.variant_tag(step)) !== \"yield\" || payload === null) break;\n state = recordField(exports, payload, \"nextState\");\n const chunk = readDefinyValue(exports, recordField(exports, payload, \"chunk\"));\n if (Array.isArray(chunk) && chunk.length > 0) {\n controller.enqueue(new Uint8Array(chunk.map((n) => Number(n) & 0xff)));\n return;\n }\n }\n state = null;\n controller.close();\n },\n });\n}\n\n// definy.worker-step: #respond(レスポンス) か #fetch({request, then}). fetch なら HTTP リクエストを送り,\n// 応答 { status, text } で then を呼んで続ける (definy.deploy-fetch-worker)。100 回で打ち切る\nasync function runWorkerSteps(exports, result) {\n for (let i = 0; i < 100; i++) {\n if (result === null || exports.value_tag(result) !== TAG_VARIANT) return result;\n const tag = readString(exports, exports.variant_tag(result));\n const payload = exports.variant_payload(result);\n if (tag === \"respond\") return payload;\n if (tag !== \"fetch\" || payload === null) return result;\n const request = readDefinyValue(exports, recordField(exports, payload, \"request\")) ?? {};\n const method = typeof request.method === \"string\" ? request.method : \"GET\";\n let status = 0;\n let text = \"\";\n try {\n const response = await fetch(request.url, {\n method,\n headers: Array.isArray(request.headers) ? request.headers.map((h) => [h.name, h.value]) : [],\n body: method === \"GET\" || method === \"HEAD\" ? undefined : request.body,\n });\n status = response.status;\n text = await response.text();\n } catch (e) {\n text = String(e);\n }\n result = callClosure(exports, recordField(exports, payload, \"then\"), [\n writeRecord(exports, [\n [\"status\", exports.box_number(BigInt(status))],\n [\"text\", writeString(exports, text)],\n ]),\n ]);\n }\n return null;\n}\n\nasync function evaluateWasmRequest(request) {\n const instance = await WebAssembly.instantiate(wasmModule, {});\n const exports = instance.exports;\n let result = exports.evaluate();\n if (result !== null && exports.value_tag(result) === TAG_CLOSURE) {\n const bodyBytes =\n request.body && request.method !== \"GET\" && request.method !== \"HEAD\"\n ? new Uint8Array(await request.clone().arrayBuffer())\n : new Uint8Array(0);\n result = callClosure(exports, result, [writeHttpRequest(exports, request, bodyBytes)]);\n result = await runWorkerSteps(exports, result);\n }\n\n const status = recordField(exports, result, \"status\");\n const body = recordField(exports, result, \"body\");\n if (status !== null && exports.value_tag(status) === TAG_NUMBER && body !== null) {\n const headers = new Headers({ \"access-control-allow-origin\": \"*\" });\n const headerList = readDefinyValue(exports, recordField(exports, result, \"headers\"));\n if (Array.isArray(headerList)) {\n for (const h of headerList) {\n if (h && typeof h.name === \"string\" && typeof h.value === \"string\") {\n headers.set(h.name, h.value);\n }\n }\n }\n const bodyPayload =\n exports.value_tag(body) === TAG_STRING\n ? readString(exports, body)\n : recordField(exports, body, \"next\") !== null\n ? createPullByteReadableStream(exports, body)\n : \"\";\n return {\n evalResult: null,\n httpResponse: new Response(bodyPayload, {\n status: Number(exports.number_value(status)),\n headers,\n }),\n };\n }\n\n return { evalResult: readDefinyValue(exports, result), httpResponse: null };\n}\n\nexport default {\n async fetch(request) {\n const url = new URL(request.url);\n try {\n const { evalResult, httpResponse } = await evaluateWasmRequest(request);\n if (httpResponse) {\n return httpResponse;\n }\n if (url.pathname === \"/healthz\") {\n return new Response(JSON.stringify({ status: \"ok\", runtime: \"cloudflare-workers\", has_wasm: true }), {\n headers: { \"Content-Type\": \"application/json; charset=utf-8\" },\n });\n }\n return new Response(\n JSON.stringify({\n service: \"definy-cloudflare-workers\",\n message: \"Hello from Definy on Cloudflare Workers!\",\n evaluatedResult: evalResult,\n pathname: url.pathname,\n has_wasm: true,\n }),\n {\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n },\n );\n } catch (e) {\n return new Response(\n JSON.stringify({ error: String(e) }),\n {\n status: 500,\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n },\n );\n }\n },\n};\n"