| 1 | import { fileURLToPath } from "node:url"; |
| 2 | import { defineConfig } from "vitest/config"; |
| 3 | import { timeouts } from "../../vitest.shared"; |
| 4 | |
| 5 | // The path is base64-encoded so the id does not look like a node_modules file, which vitest would hand to Node unprocessed. |
| 6 | const PREFIX = "virtual:wasm-module/"; |
| 7 | |
| 8 | export default defineConfig({ |
| 9 | test: timeouts, |
| 10 | resolve: { |
| 11 | alias: { |
| 12 | "cloudflare:workflows": fileURLToPath(new URL("./test/unit/stubs/cloudflare-workflows.ts", import.meta.url)), |
| 13 | "cloudflare:workers": fileURLToPath(new URL("./test/unit/stubs/cloudflare-workers.ts", import.meta.url)), |
| 14 | }, |
| 15 | }, |
| 16 | plugins: [ |
| 17 | { |
| 18 | // `import text from "x.txt"` gives the file's text and `import data from "x.bin"` an ArrayBuffer, |
| 19 | // like wrangler's Text and Data rules in the Worker (vite would otherwise give an asset URL). |
| 20 | name: "diffinery:text-and-data-modules", |
| 21 | enforce: "pre", |
| 22 | load(id) { |
| 23 | if (id.endsWith(".txt")) return `import { readFileSync } from "node:fs";\nexport default readFileSync(${JSON.stringify(id)}, "utf8");`; |
| 24 | if (id.endsWith(".bin")) return `import { readFileSync } from "node:fs";\nconst b = readFileSync(${JSON.stringify(id)});\nexport default b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);`; |
| 25 | return null; |
| 26 | }, |
| 27 | }, |
| 28 | { |
| 29 | // `import mod from "x.wasm?module"` gives a compiled WebAssembly.Module, like wrangler's CompiledWasm rule in the Worker. |
| 30 | name: "diffinery:wasm-module", |
| 31 | enforce: "pre", |
| 32 | async resolveId(source, importer) { |
| 33 | if (!source.endsWith(".wasm?module")) return null; |
| 34 | const file = await this.resolve(source.slice(0, -"?module".length), importer, { skipSelf: true }); |
| 35 | return file ? PREFIX + Buffer.from(file.id).toString("base64url") : null; |
| 36 | }, |
| 37 | load(id) { |
| 38 | if (!id.startsWith(PREFIX)) return null; |
| 39 | return `import { readFileSync } from "node:fs";\nexport default new WebAssembly.Module(readFileSync(${JSON.stringify(Buffer.from(id.slice(PREFIX.length), "base64url").toString())}));`; |
| 40 | }, |
| 41 | }, |
| 42 | ], |
| 43 | }); |