vite-plugin-wat2wasm 1.2.1 → 1.2.2
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/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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(),c=[`browser`,`node`];var l=(r={})=>{let{target:l=`all`,parser:u={},generator:d={}}=r,f=l===`all`?c:typeof l==`string`?[l]:l.length===0?c:l,p=new Map,m=n=>{let r=t.basename(n,`.wat`),i=e.readFileSync(n,{encoding:`utf-8`});return s.parseWat(r,i,u).toBinary(d).buffer},h=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)return r;let l=m(c),u=n.createHash(`sha-256`);u.update(l);let d=u.digest(`base64url`).slice(0,8),f=t.posix.relative(
|
|
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(),c=[`browser`,`node`];var l=(r={})=>{let{target:l=`all`,parser:u={},generator:d={}}=r,f=l===`all`?c:typeof l==`string`?[l]:l.length===0?c:l,p=new Map,m=n=>{let r=t.basename(n,`.wat`),i=e.readFileSync(n,{encoding:`utf-8`});return s.parseWat(r,i,u).toBinary(d).buffer},h=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.replaceAll(`\\`,`/`)??null;if(c===null)return r;let l=m(c),u=n.createHash(`sha-256`);u.update(l);let d=u.digest(`base64url`).slice(0,8),f=`environment`in e?e.environment.config.root:process.cwd(),h=t.posix.relative(f,c);h.startsWith(`.`)&&(h=t.win32.relative(f,c).replaceAll(`\\`,`/`));let g=t.basename(h,`.wat`)+`-`+d,_=t.dirname(h),v=t.posix.join(_,g+`.wasm`);p.has(v)||p.set(v,l);let y=s[2],b=s[1],x=s[4],S=s.index??0,C=S+s[0].length;r=r.slice(0,S)+b+o(v,y)+x+r.slice(C)}return r};return{name:`wat-compiler`,enforce:`post`,async load(e){if((r.emitWasm??(`environment`in this&&this.environment.mode===`build`))||!e.endsWith(`.wat`))return null;let t=m(e);return`const str = atob("${btoa(String.fromCharCode(...t))}");
|
|
2
2
|
|
|
3
3
|
const init = async (imports = {}) => {
|
|
4
4
|
return WebAssembly.instantiate(new Uint8Array(str.length).fill(0x00).map((_, i) => str.charCodeAt(i)).buffer, imports).then(({ instance: { exports } }) => exports).catch(({ message }) => {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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\n/** See @see {@link https://github.com/AssemblyScript/wabt.js/blob/main/README.md|`wabt.WasmFeatures`} for more info. @see WasmParserOptions */\r\ntype WasmParserOptions = Parameters<WabtParserFunc>[2];\r\n\r\n/** See @see {@link https://github.com/AssemblyScript/wabt.js/blob/main/README.md|`wabt.ToBinaryOptions`} for more info. @see WasmGeneratorOptions */\r\ntype WasmGeneratorOptions = Parameters<ReturnType<WabtParserFunc>[\"toBinary\"]>[0];\r\n\r\nconst WASM_TARGETS = [\"browser\", \"node\"] as const;\r\n\r\n/** The available targets that is supported by `vite-plugin-wat2wasm`. @see WasmTarget */\r\ntype WasmTarget = typeof WASM_TARGETS[number];\r\n\r\n/** The configuration settings for `vite-plugin-wat2wasm`. @see Wat2WasmOptions */\r\ninterface Wat2WasmOptions {\r\n /** Determines whether `.wasm` files will be outputted after compiling `.wat` files during build. Useful if you want other bundlers/compilers to take over generation of `.wasm` files. @default true */\r\n emitWasm?: boolean;\r\n\r\n /** Selects the targets that can use the `.wat` modules. \"all\" means that all targets available in @see {@link WasmTarget|`WasmTarget`} can use said modules. @default \"all\" */\r\n target?: \"all\" | WasmTarget | WasmTarget[];\r\n\r\n /** Configures `.wasm` features you wish to enable for `vite-plugin-wat2wasm`. @default {} @see {@link WasmParserOptions|`WasmParserOptions`} */\r\n parser?: WasmParserOptions;\r\n\r\n /** Configures how `vite-plugin-wat2wasm` to generate `.wasm` files. @default {} @see {@link WasmGeneratorOptions|`WasmGeneratorOptions`} */\r\n generator?: WasmGeneratorOptions;\r\n}\r\n\r\n/** Enables compilation of `.wat` files and generation of `.wasm`, with modifiable settings.\r\n *\r\n * @param options - the configuration options for `vite-plugin-wat2wasm`. @see {@link Wat2WasmOptions|`Wat2WasmOptions`}\r\n * @returns a Vite plugin object that allows for compilation of `.wat` files. @see {@link https://vite.dev/guide/api-plugin|`Plugin`}\r\n */\r\nconst watCompilerPlugin = (options: Wat2WasmOptions = {}): Plugin => {\r\n const {\r\n target: optionsTarget = \"all\",\r\n\r\n parser: parserOptions = {},\r\n generator: generatorOptions = {}\r\n } = options;\r\n\r\n const targets =\r\n optionsTarget === \"all\"\r\n ? WASM_TARGETS as unknown as WasmTarget[] :\r\n typeof optionsTarget === \"string\"\r\n ? [optionsTarget] :\r\n optionsTarget.length === 0\r\n ? WASM_TARGETS as unknown as WasmTarget[]\r\n : optionsTarget;\r\n\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) return code;\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 distRelPath = path.posix.relative(ctx.environment?.config?.root ?? __dirname, watAbsPath);\r\n\r\n const watName = path.basename(distRelPath, \".wat\") + \"-\" + hash;\r\n const watParent = path.dirname(distRelPath);\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 async load(id: string) {\r\n const emitWasm = options.emitWasm ?? (\"environment\" in this && this.environment.mode === \"build\");\r\n\r\n if (emitWasm || !id.endsWith(\".wat\")) return null;\r\n\r\n const bfr = compileWat(id);\r\n const str = btoa(String.fromCharCode(...bfr));\r\n\r\n return (\r\n `const str = atob(\"${str}\");` + \"\\n\" +\r\n \"\" + \"\\n\" +\r\n \"const init = async (imports = {}) => {\" + \"\\n\" +\r\n \" return WebAssembly.instantiate(new Uint8Array(str.length).fill(0x00).map((_, i) => str.charCodeAt(i)).buffer, imports).then(({ instance: { exports } }) => exports).catch(({ message }) => {\" + \"\\n\" +\r\n \" const [_, ptr] = message.match(/ @\\\\+(\\\\d+)\\\\s*$/);\" + \"\\n\" +\r\n \" console.error(message + \\\": \\\" + [...new TextEncoder().encode(str.slice(+ptr - 40, +ptr + 40))].map((byte, i) => (i === 40 ? \\\"[\\\" : \\\"\\\") + byte.toString(16).padStart(2, \\\"0\\\") + (i === 40 ? \\\"]\\\" : \\\"\\\")).join(\\\" \\\"));\" + \"\\n\" +\r\n \" });\" + \"\\n\" +\r\n \"}\" + \"\\n\" +\r\n \"\" + \"\\n\" +\r\n \"export default init;\" + \"\\n\"\r\n );\r\n },\r\n\r\n async transform(code: string, id: string) {\r\n const emitWasm = options.emitWasm ?? (\"environment\" in this && this.environment.mode === \"build\");\r\n\r\n if (!emitWasm || !JS_FILE_EXT_REG.test(id)) return null;\r\n\r\n const initWasmFuncName = \"__\" + crypto.randomBytes(4).toString(\"hex\");\r\n const generateInitWasmFunc =\r\n `const ${initWasmFuncName} = (path, imports) => {` + \"\\n\" +\r\n (targets.includes(\"node\") ?\r\n \" if (typeof process !== \\\"undefined\\\" && \\\"versions\\\" in process && \\\"node\\\" in process.versions) return WebAssembly.instantiate(require(\\\"fs\\\").readFileSync(path), imports);\" + \"\\n\" :\r\n \"\") +\r\n (targets.includes(\"browser\") ?\r\n ` if (typeof window !== \"undefined\" && typeof document !== \"undefined\") return WebAssembly.instantiateStreaming(fetch(path), imports);` + \"\\n\" :\r\n \"\") +\r\n \"\" + \"\\n\" +\r\n \" throw new Error(\\\"This JavaScript runtime is not supported by this module. If this is a mistake, adjust your target to fit your specific runtime.\\\");\" + \"\\n\" +\r\n \"};\" + \"\\n\";\r\n\r\n const generateInitModuleFunc = (path: string): string => `async (imports) => ${initWasmFuncName}(\"${path}\", imports).then(({ instance: { exports } }) => exports)`;\r\n\r\n const originalCode = code;\r\n\r\n code = await transformImports(this as any, code, id, IMPORT_DEFAULT_REG, (path, name) => `const ${name} = ${generateInitModuleFunc(path)};`);\r\n code = await transformImports(this as any, code, id, IMPORT_STAR_REG , (path, name) => `const ${name} = { default: ${generateInitModuleFunc(path)} };`);\r\n\r\n if (code !== originalCode) code = generateInitWasmFunc + code;\r\n return code;\r\n },\r\n\r\n buildEnd() {\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\n\r\nexport default watCompilerPlugin;\r\nexport type { Wat2WasmOptions, WasmParserOptions, WasmGeneratorOptions, WasmTarget };\r\n"],"mappings":"gFAUA,MAAM,EAAqB,8EACrB,EAAqB,wFAErB,EAAkB,qBAElB,EAAO,MAAM,GAAU,CAUvB,EAAe,CAAC,UAAW,OAAO,CAgKxC,IAAA,GAvI2B,EAA2B,EAAE,GAAa,CACjE,GAAM,CACF,OAAQ,EAAgB,MAExB,OAAQ,EAAgB,EAAE,CAC1B,UAAW,EAAmB,EAAE,EAChC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M,eACN,QAAS,OAET,MAAM,KAAK,EAAY,CAGnB,IAFiB,EAAQ,WAAa,gBAAiB,MAAQ,KAAK,YAAY,OAAS,WAEzE,CAAC,EAAG,SAAS,OAAO,CAAE,OAAO,KAE7C,IAAM,EAAM,EAAW,EAAG,CAG1B,MACI,qBAHQ,KAAK,OAAO,aAAa,GAAG,EAAI,CAAC,CAGhB;;;;;;;;;;GAajC,MAAM,UAAU,EAAc,EAAY,CAGtC,GAAI,EAFa,EAAQ,WAAa,gBAAiB,MAAQ,KAAK,YAAY,OAAS,WAExE,CAAC,EAAgB,KAAK,EAAG,CAAE,OAAO,KAEnD,IAAM,EAAmB,KAAO,EAAO,YAAY,EAAE,CAAC,SAAS,MAAM,CAC/D,EACF,SAAS,EAAiB;GACzB,EAAQ,SAAS,OAAO,CACzB;EACA,KACC,EAAQ,SAAS,UAAU,CAC5B;EACA,IACK;;;EAIH,EAA0B,GAAyB,sBAAsB,EAAiB,IAAIA,EAAK,0DAEnG,EAAe,EAMrB,MAJA,GAAO,MAAM,EAAiB,KAAa,EAAM,EAAI,GAAqB,EAAM,IAAS,SAAS,EAAK,KAAK,EAAuBA,EAAK,CAAC,GAAG,CAC5I,EAAO,MAAM,EAAiB,KAAa,EAAM,EAAI,GAAqB,EAAM,IAAS,SAAS,EAAK,gBAAgB,EAAuBA,EAAK,CAAC,KAAK,CAErJ,IAAS,IAAc,EAAO,EAAuB,GAClD,GAGX,UAAW,CACP,IAAK,GAAM,CAAC,EAAU,KAAQ,EAC1B,KAAK,SAAS,CACV,KAAM,QAEN,SAAU,EACV,OAAQ,EACX,CAAC,EAGb"}
|
|
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\n/** See @see {@link https://github.com/AssemblyScript/wabt.js/blob/main/README.md|`wabt.WasmFeatures`} for more info. @see WasmParserOptions */\r\ntype WasmParserOptions = Parameters<WabtParserFunc>[2];\r\n\r\n/** See @see {@link https://github.com/AssemblyScript/wabt.js/blob/main/README.md|`wabt.ToBinaryOptions`} for more info. @see WasmGeneratorOptions */\r\ntype WasmGeneratorOptions = Parameters<ReturnType<WabtParserFunc>[\"toBinary\"]>[0];\r\n\r\nconst WASM_TARGETS = [\"browser\", \"node\"] as const;\r\n\r\n/** The available targets that is supported by `vite-plugin-wat2wasm`. @see WasmTarget */\r\ntype WasmTarget = typeof WASM_TARGETS[number];\r\n\r\n/** The configuration settings for `vite-plugin-wat2wasm`. @see Wat2WasmOptions */\r\ninterface Wat2WasmOptions {\r\n /** Determines whether `.wasm` files will be outputted after compiling `.wat` files during build. Useful if you want other bundlers/compilers to take over generation of `.wasm` files. @default true */\r\n emitWasm?: boolean;\r\n\r\n /** Selects the targets that can use the `.wat` modules. \"all\" means that all targets available in @see {@link WasmTarget|`WasmTarget`} can use said modules. @default \"all\" */\r\n target?: \"all\" | WasmTarget | WasmTarget[];\r\n\r\n /** Configures `.wasm` features you wish to enable for `vite-plugin-wat2wasm`. @default {} @see {@link WasmParserOptions|`WasmParserOptions`} */\r\n parser?: WasmParserOptions;\r\n\r\n /** Configures how `vite-plugin-wat2wasm` to generate `.wasm` files. @default {} @see {@link WasmGeneratorOptions|`WasmGeneratorOptions`} */\r\n generator?: WasmGeneratorOptions;\r\n}\r\n\r\n/** Enables compilation of `.wat` files and generation of `.wasm`, with modifiable settings.\r\n *\r\n * @param options - the configuration options for `vite-plugin-wat2wasm`. @see {@link Wat2WasmOptions|`Wat2WasmOptions`}\r\n * @returns a Vite plugin object that allows for compilation of `.wat` files. @see {@link https://vite.dev/guide/api-plugin|`Plugin`}\r\n */\r\nconst watCompilerPlugin = (options: Wat2WasmOptions = {}): Plugin => {\r\n const {\r\n target: optionsTarget = \"all\",\r\n\r\n parser: parserOptions = {},\r\n generator: generatorOptions = {}\r\n } = options;\r\n\r\n const targets =\r\n optionsTarget === \"all\"\r\n ? WASM_TARGETS as unknown as WasmTarget[] :\r\n typeof optionsTarget === \"string\"\r\n ? [optionsTarget] :\r\n optionsTarget.length === 0\r\n ? WASM_TARGETS as unknown as WasmTarget[]\r\n : optionsTarget;\r\n\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.replaceAll(\"\\\\\", \"/\") ?? null;\r\n if (watAbsPath === null) return code;\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 rootPath = \"environment\" in ctx ? ctx.environment.config.root : process.cwd(); // some contexts do not provide an environment, so compute it separately.\r\n\r\n let distRelPath = path.posix.relative(rootPath, watAbsPath);\r\n if (distRelPath.startsWith(\".\")) distRelPath = path.win32.relative(rootPath, watAbsPath).replaceAll(\"\\\\\", \"/\"); // if posix relative function resolves the paths incorrectly, use the windows function instead.\r\n\r\n const watName = path.basename(distRelPath, \".wat\") + \"-\" + hash;\r\n const watParent = path.dirname(distRelPath);\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 async load(id: string) {\r\n const emitWasm = options.emitWasm ?? (\"environment\" in this && this.environment.mode === \"build\");\r\n\r\n if (emitWasm || !id.endsWith(\".wat\")) return null;\r\n\r\n const bfr = compileWat(id);\r\n const str = btoa(String.fromCharCode(...bfr));\r\n\r\n return (\r\n `const str = atob(\"${str}\");` + \"\\n\" +\r\n \"\" + \"\\n\" +\r\n \"const init = async (imports = {}) => {\" + \"\\n\" +\r\n \" return WebAssembly.instantiate(new Uint8Array(str.length).fill(0x00).map((_, i) => str.charCodeAt(i)).buffer, imports).then(({ instance: { exports } }) => exports).catch(({ message }) => {\" + \"\\n\" +\r\n \" const [_, ptr] = message.match(/ @\\\\+(\\\\d+)\\\\s*$/);\" + \"\\n\" +\r\n \" console.error(message + \\\": \\\" + [...new TextEncoder().encode(str.slice(+ptr - 40, +ptr + 40))].map((byte, i) => (i === 40 ? \\\"[\\\" : \\\"\\\") + byte.toString(16).padStart(2, \\\"0\\\") + (i === 40 ? \\\"]\\\" : \\\"\\\")).join(\\\" \\\"));\" + \"\\n\" +\r\n \" });\" + \"\\n\" +\r\n \"}\" + \"\\n\" +\r\n \"\" + \"\\n\" +\r\n \"export default init;\" + \"\\n\"\r\n );\r\n },\r\n\r\n async transform(code: string, id: string) {\r\n const emitWasm = options.emitWasm ?? (\"environment\" in this && this.environment.mode === \"build\");\r\n\r\n if (!emitWasm || !JS_FILE_EXT_REG.test(id)) return null;\r\n\r\n const initWasmFuncName = \"__\" + crypto.randomBytes(4).toString(\"hex\");\r\n const generateInitWasmFunc =\r\n `const ${initWasmFuncName} = (path, imports) => {` + \"\\n\" +\r\n (targets.includes(\"node\") ?\r\n \" if (typeof process !== \\\"undefined\\\" && \\\"versions\\\" in process && \\\"node\\\" in process.versions) return WebAssembly.instantiate(require(\\\"fs\\\").readFileSync(path), imports);\" + \"\\n\" :\r\n \"\") +\r\n (targets.includes(\"browser\") ?\r\n ` if (typeof window !== \"undefined\" && typeof document !== \"undefined\") return WebAssembly.instantiateStreaming(fetch(path), imports);` + \"\\n\" :\r\n \"\") +\r\n \"\" + \"\\n\" +\r\n \" throw new Error(\\\"This JavaScript runtime is not supported by this module. If this is a mistake, adjust your target to fit your specific runtime.\\\");\" + \"\\n\" +\r\n \"};\" + \"\\n\";\r\n\r\n const generateInitModuleFunc = (path: string): string => `async (imports) => ${initWasmFuncName}(\"${path}\", imports).then(({ instance: { exports } }) => exports)`;\r\n\r\n const originalCode = code;\r\n\r\n code = await transformImports(this as any, code, id, IMPORT_DEFAULT_REG, (path, name) => `const ${name} = ${generateInitModuleFunc(path)};`);\r\n code = await transformImports(this as any, code, id, IMPORT_STAR_REG , (path, name) => `const ${name} = { default: ${generateInitModuleFunc(path)} };`);\r\n\r\n if (code !== originalCode) code = generateInitWasmFunc + code;\r\n return code;\r\n },\r\n\r\n buildEnd() {\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\n\r\nexport default watCompilerPlugin;\r\nexport type { Wat2WasmOptions, WasmParserOptions, WasmGeneratorOptions, WasmTarget };\r\n"],"mappings":"gFAUA,MAAM,EAAqB,8EACrB,EAAqB,wFAErB,EAAkB,qBAElB,EAAO,MAAM,GAAU,CAUvB,EAAe,CAAC,UAAW,OAAO,CAmKxC,IAAA,GA1I2B,EAA2B,EAAE,GAAa,CACjE,GAAM,CACF,OAAQ,EAAgB,MAExB,OAAQ,EAAgB,EAAE,CAC1B,UAAW,EAAmB,EAAE,EAChC,EAEE,EACF,IAAkB,MACZ,EACN,OAAO,GAAkB,SACnB,CAAC,EAAc,CACrB,EAAc,SAAW,EACnB,EACA,EAEJ,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,GAAG,WAAW,KAAM,IAAI,EAAI,KAC1F,GAAI,IAAe,KAAM,OAAO,EAEhC,IAAM,EAAM,EAAW,EAAW,CAE5B,EAAS,EAAO,WAAW,UAAU,CAC3C,EAAO,OAAO,EAAI,CAElB,IAAM,EAAO,EAAO,OAAO,YAAY,CAAC,MAAM,EAAG,EAAE,CAE7C,EAAW,gBAAiB,EAAM,EAAI,YAAY,OAAO,KAAO,QAAQ,KAAK,CAE/E,EAAc,EAAK,MAAM,SAAS,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S,SAAS,EAAK,KAAK,EAAuBA,EAAK,CAAC,GAAG,CAC5I,EAAO,MAAM,EAAiB,KAAa,EAAM,EAAI,GAAqB,EAAM,IAAS,SAAS,EAAK,gBAAgB,EAAuBA,EAAK,CAAC,KAAK,CAErJ,IAAS,IAAc,EAAO,EAAuB,GAClD,GAGX,UAAW,CACP,IAAK,GAAM,CAAC,EAAU,KAAQ,EAC1B,KAAK,SAAS,CACV,KAAM,QAEN,SAAU,EACV,OAAQ,EACX,CAAC,EAGb"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-plugin-wat2wasm",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.2.
|
|
4
|
+
"version": "1.2.2",
|
|
5
5
|
"description": "Enable .wat compilation and integrate generated WebAssembly modules into your codebase with type support",
|
|
6
6
|
|
|
7
7
|
"author": "osoclos",
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
|
|
43
43
|
"dependencies": { "wabt": "^1.0.39" },
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"tsdown": "^0.18.
|
|
46
|
-
"rolldown": "^1.0.0-
|
|
45
|
+
"tsdown": "^0.18.4",
|
|
46
|
+
"rolldown": "^1.0.0-rc.9",
|
|
47
47
|
|
|
48
48
|
"vite": "^8.0.0",
|
|
49
49
|
"vitest": "^4.0.18",
|