vite-plugin-wat2wasm 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 osoclos
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # vite-plugin-wat2wasm
2
+
3
+ Enable `.wat` compilation and integrate generated WebAssembly modules into your codebase with type support
4
+
5
+ ## Installation
6
+
7
+ ``` bash
8
+ $ <your-preferred-package-manager> install -D vite-plugin-wat2wasm
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Adding into your Vite configuration
14
+
15
+ ``` ts
16
+ import { defineConfig } from "vite";
17
+ import watVitePlugin from "vite-plugin-wat2wasm";
18
+
19
+ export default defineConfig({
20
+ plugins: [
21
+ watVitePlugins(
22
+ { /* ...wasm features to include */ },
23
+ { /* ...wasm generation settings */ }
24
+ ),
25
+ /* ...other plugins */
26
+ ],
27
+
28
+ // ... other configuration settings
29
+ });
30
+ ```
31
+
32
+ ### Adding types for import statements
33
+
34
+ Reference it as a comment...
35
+
36
+ ``` ts
37
+ /// <reference types="vite-plugin-wat2wasm/module-types" />
38
+ ```
39
+
40
+ or include it in your `tsconfig.json` file
41
+
42
+ ``` json
43
+ {
44
+ "include": ["src"],
45
+ "compilerOptions": {
46
+ "types": ["vite-plugin-wat2wasm/module-types", /* ... other type files/packages */]
47
+ // ... other options for Typescript
48
+ }
49
+ }
50
+ ```
51
+
52
+ ### Using it in your application/library
53
+
54
+ ``` ts
55
+ import initFoo from "./foo.wat"
56
+
57
+ const bar = new WebAssembly.Global("i32");
58
+
59
+ const foo = await initFoo<FooExports, FooImports>({
60
+ bar: { val: bar },
61
+
62
+ console: {
63
+ log(a: number) {
64
+ console.log(a);
65
+ }
66
+ }
67
+ });
68
+
69
+ console.log(foo.add(21, 46)); // returns 67
70
+ foo.logBar();
71
+
72
+ // In Typescript, you can also specify the types of your .wat file module.
73
+ interface FooExports {
74
+ add(a: number, b: number): number;
75
+ logBar(): void;
76
+ }
77
+
78
+ interface FooImports {
79
+ bar: { val: WebAssembly.Global<"i32">; };
80
+ console: { log(a: number): void; };
81
+ }
82
+ ```
@@ -0,0 +1,11 @@
1
+ import initWabt from "wabt";
2
+ import { Plugin } from "vite";
3
+
4
+ //#region src/index.d.ts
5
+ type WabtParserFunc = Awaited<ReturnType<typeof initWabt>>["parseWat"];
6
+ type WasmParserOptions = Parameters<WabtParserFunc>[2];
7
+ type WasmGeneratorOptions = Parameters<ReturnType<WabtParserFunc>["toBinary"]>[0];
8
+ declare const watCompilerPlugin: (parserOptions?: WasmParserOptions, generatorOptions?: WasmGeneratorOptions) => Plugin;
9
+ //#endregion
10
+ export { watCompilerPlugin as default };
11
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ import e from"fs";import t from"path";import n from"crypto";import r from"wabt";const i=/(^|\s)import\s+([A-Za-z_$][\w$]*)\s+from\s*['"]([^'"\n]*\.wat)['"](\s*;|$)/m,a=/(^|\s)import\s*\*\s*as\s+([A-Za-z_$][\w$]*)\s+from\s*['"]([^'"\n]*\.wat)[;"](\s*;|$)/m,o=/\.([mc]?[jt]sx?)$/i,s=await r();var c=(r={},c={})=>{let l=new Map,u=n=>{let i=t.basename(n,`.wat`),a=e.readFileSync(n,{encoding:`utf-8`});return s.parseWat(i,a,r).toBinary(c).buffer},d=async(e,r,i,a,o)=>{for(let s=r.match(a);s!==null;s=r.match(a)){s.index??=0;let a=s[3],c=(await e.resolve(a,i))?.id??null;if(c===null)continue;let d=u(c),f=n.createHash(`sha-256`);f.update(d);let p=f.digest(`base64url`).slice(0,8),m=t.basename(a,`.wat`)+`-`+p,h=t.dirname(a),g=t.posix.join(h,m+`.wasm`);l.has(g)||l.set(g,d);let _=s[2],v=s[1],y=s[4],b=s.index??0,x=b+s[0].length;r=r.slice(0,b)+v+o(g,_)+y+r.slice(x)}return r};return{name:`wat-compiler`,enforce:`post`,load(e){if(!e.endsWith(`.wat`))return null;let n=u(e),r=new TextDecoder(`utf-8`).decode(n).replaceAll("`","\\`").replaceAll(`
2
+ `,`\\n`).replaceAll(`\r`,`\\r`);return`let hasInitialized = false;
3
+
4
+ export default async function init(imports = {}) {
5
+ if (hasInitialized) throw new Error("Module at \\"${t.resolve(this.environment.config.base,e)}\\" has already been initialized!");
6
+ hasInitialized = true;
7
+
8
+ return WebAssembly.instantiate(new TextEncoder().encode(\`${r}\`), imports).then(({ instance: { exports } }) => exports);
9
+ }
10
+ `},async transform(e,t){return this.environment.mode!==`build`||!o.test(t)?null:(e=await d(this,e,t,i,(e,t)=>`const ${t} = async (imports) => WebAssembly.instantiateStreaming(fetch("${e}"), imports).then(({ instance: { exports } }) => exports);`),e=await d(this,e,t,a,(e,t)=>`const ${t} = { default: async (imports) => WebAssembly.instantiateStreaming(fetch("${e}"), imports).then(({ instance: { exports } }) => exports) };`),e)},generateBundle(){for(let[e,t]of l)this.emitFile({type:`asset`,fileName:e,source:t})}}};export{c as default};
11
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["path"],"sources":["../src/index.ts"],"sourcesContent":["import fs from \"fs\";\r\nimport path from \"path\";\r\n\r\nimport crypto from \"crypto\";\r\n\r\nimport type { Plugin } from \"vite\";\r\nimport type { TransformPluginContext } from \"rolldown\";\r\n\r\nimport initWabt from \"wabt\";\r\n\r\nconst IMPORT_DEFAULT_REG = /(^|\\s)import\\s+([A-Za-z_$][\\w$]*)\\s+from\\s*['\"]([^'\"\\n]*\\.wat)['\"](\\s*;|$)/m;\r\nconst IMPORT_STAR_REG = /(^|\\s)import\\s*\\*\\s*as\\s+([A-Za-z_$][\\w$]*)\\s+from\\s*['\"]([^'\"\\n]*\\.wat)[;\"](\\s*;|$)/m;\r\n\r\nconst JS_FILE_EXT_REG = /\\.([mc]?[jt]sx?)$/i;\r\n\r\nconst wabt = await initWabt();\r\n\r\ntype WabtParserFunc = Awaited<ReturnType<typeof initWabt>>[\"parseWat\"];\r\n\r\ntype WasmParserOptions = Parameters<WabtParserFunc>[2];\r\ntype WasmGeneratorOptions = Parameters<ReturnType<WabtParserFunc>[\"toBinary\"]>[0];\r\n\r\nconst watCompilerPlugin = (parserOptions: WasmParserOptions = {}, generatorOptions: WasmGeneratorOptions = {}): Plugin => {\r\n const importedWatFiles = new Map<string, Uint8Array>();\r\n\r\n const compileWat = (watPath: string): Uint8Array => {\r\n const name = path.basename(watPath, \".wat\");\r\n const textBfr = fs.readFileSync(watPath, { encoding: \"utf-8\" });\r\n\r\n const module = wabt.parseWat(name, textBfr, parserOptions);\r\n const bfr = module.toBinary(generatorOptions).buffer;\r\n\r\n return bfr;\r\n };\r\n\r\n const transformImports = async (ctx: TransformPluginContext, code: string, codePath: string, statementReg: RegExp, replacement: (importPath: string, name: string) => string): Promise<string> => {\r\n for (let match = code.match(statementReg); match !== null; match = code.match(statementReg)) {\r\n match.index ??= 0;\r\n\r\n const watRelPath = match[3];\r\n\r\n const watAbsPath = (await ctx.resolve(watRelPath, codePath))?.id ?? null;\r\n if (watAbsPath === null) continue;\r\n\r\n const bfr = compileWat(watAbsPath);\r\n\r\n const hasher = crypto.createHash(\"sha-256\");\r\n hasher.update(bfr);\r\n\r\n const hash = hasher.digest(\"base64url\").slice(0, 8);\r\n\r\n const watName = path.basename(watRelPath, \".wat\") + \"-\" + hash;\r\n const watParent = path.dirname(watRelPath);\r\n\r\n const wasmFilePath = path.posix.join(watParent, watName + \".wasm\");\r\n if (!importedWatFiles.has(wasmFilePath)) importedWatFiles.set(wasmFilePath, bfr);\r\n\r\n const importName = match[2];\r\n\r\n const preSpacing = match[1];\r\n const postSpacing = match[4];\r\n\r\n const statementStart = match.index ?? 0;\r\n const statementEnd = statementStart + match[0].length;\r\n\r\n code = code.slice(0, statementStart) + preSpacing + replacement(wasmFilePath, importName) + postSpacing + code.slice(statementEnd);\r\n }\r\n\r\n return code;\r\n };\r\n\r\n return {\r\n name: \"wat-compiler\",\r\n enforce: \"post\",\r\n\r\n load(id: string) {\r\n if (!id.endsWith(\".wat\")) return null;\r\n\r\n const bfr = compileWat(id);\r\n const str = new TextDecoder(\"utf-8\").decode(bfr).replaceAll(\"`\", \"\\\\`\").replaceAll(\"\\n\", \"\\\\n\").replaceAll(\"\\r\", \"\\\\r\");\r\n\r\n return (\r\n \"let hasInitialized = false;\" + \"\\n\" +\r\n \"\" + \"\\n\" +\r\n \"export default async function init(imports = {}) {\" + \"\\n\" +\r\n ` if (hasInitialized) throw new Error(\"Module at \\\\\"${path.resolve(this.environment.config.base, id)}\\\\\" has already been initialized!\");` + \"\\n\" +\r\n \" hasInitialized = true;\" + \"\\n\" +\r\n \"\" + \"\\n\" +\r\n ` return WebAssembly.instantiate(new TextEncoder().encode(\\`${str}\\`), imports).then(({ instance: { exports } }) => exports);` + \"\\n\" +\r\n \"}\" + \"\\n\"\r\n );\r\n },\r\n\r\n async transform(code: string, id: string) {\r\n if (this.environment.mode !== \"build\" || !JS_FILE_EXT_REG.test(id)) return null;\r\n\r\n code = await transformImports(this as any, code, id, IMPORT_DEFAULT_REG, (path, name) => `const ${name} = async (imports) => WebAssembly.instantiateStreaming(fetch(\"${path}\"), imports).then(({ instance: { exports } }) => exports);`);\r\n code = await transformImports(this as any, code, id, IMPORT_STAR_REG , (path, name) => `const ${name} = { default: async (imports) => WebAssembly.instantiateStreaming(fetch(\"${path}\"), imports).then(({ instance: { exports } }) => exports) };`);\r\n\r\n return code;\r\n },\r\n\r\n generateBundle() {\r\n for (const [distPath, bfr] of importedWatFiles)\r\n this.emitFile({\r\n type: \"asset\",\r\n\r\n fileName: distPath,\r\n source: bfr\r\n });\r\n }\r\n };\r\n};\r\n\r\nexport default watCompilerPlugin;\r\n"],"mappings":"gFAUA,MAAM,EAAqB,8EACrB,EAAqB,wFAErB,EAAkB,qBAElB,EAAO,MAAM,GAAU,CAmG7B,IAAA,GA5F2B,EAAmC,EAAE,CAAE,EAAyC,EAAE,GAAa,CACtH,IAAM,EAAmB,IAAI,IAEvB,EAAc,GAAgC,CAChD,IAAM,EAAO,EAAK,SAAS,EAAS,OAAO,CACrC,EAAU,EAAG,aAAa,EAAS,CAAE,SAAU,QAAS,CAAC,CAK/D,OAHe,EAAK,SAAS,EAAM,EAAS,EAAc,CACvC,SAAS,EAAiB,CAAC,QAK5C,EAAmB,MAAO,EAA6B,EAAc,EAAkB,EAAsB,IAA+E,CAC9L,IAAK,IAAI,EAAQ,EAAK,MAAM,EAAa,CAAE,IAAU,KAAM,EAAQ,EAAK,MAAM,EAAa,CAAE,CACzF,EAAM,QAAU,EAEhB,IAAM,EAAa,EAAM,GAEnB,GAAc,MAAM,EAAI,QAAQ,EAAY,EAAS,GAAG,IAAM,KACpE,GAAI,IAAe,KAAM,SAEzB,IAAM,EAAM,EAAW,EAAW,CAE5B,EAAS,EAAO,WAAW,UAAU,C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EN,SAAU,EACV,OAAQ,EACX,CAAC,EAEb"}
@@ -0,0 +1,6 @@
1
+ declare module "*.wat" {
2
+ type ModuleObject = Record<string, any>;
3
+
4
+ export default function init<T extends ModuleObject = ModuleObject >( ): Promise<T>;
5
+ export default function init<T extends ModuleObject = ModuleObject, I extends ModuleObject = {}>(imports : I): Promise<T>;
6
+ }
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "vite-plugin-wat2wasm",
3
+ "type": "module",
4
+ "version": "1.0.0",
5
+ "description": "Enable .wat compilation and integrate generated WebAssembly modules into your codebase with type support",
6
+ "author": "osoclos",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/osoclos/vite-plugin-wat2wasm#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/osoclos/vite-plugin-wat2wasm.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/osoclos/vite-plugin-wat2wasm/issues"
15
+ },
16
+ "main": "./dist/index.js",
17
+ "module": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "files": ["dist"],
20
+ "exports": {
21
+ ".": "./dist/index.js",
22
+ "./module-types": "./dist/modules.d.ts",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "scripts": {
26
+ "dev": "tsdown --watch && bun run scripts/post-build.ts",
27
+ "test": "vitest",
28
+ "build": "tsdown && bun run scripts/post-build.ts",
29
+ "prepublishOnly": "bun run build",
30
+ "check-types": "tsc --noEmit"
31
+ },
32
+ "dependencies": {
33
+ "wabt": "^1.0.39"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^25.0.3",
37
+ "@vitest/browser-preview": "^4.0.17",
38
+ "bumpp": "^10.3.2",
39
+ "rolldown": "^1.0.0-beta.60",
40
+ "tsdown": "^0.18.3",
41
+ "typescript": "~5.9.3",
42
+ "vite": "^7.3.1",
43
+ "vitest": "^4.0.16"
44
+ }
45
+ }