brsh 3.10.3 → 3.10.5
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/CHANGELOG.md +14 -0
- package/dist/wbt.es.js +65 -33
- package/dist/wbt.es.js.map +1 -1
- package/dist/wbt.min.js +19 -5
- package/dist/wbt.min.js.map +1 -1
- package/lib/wbt/index.js +21 -9
- package/lib/wbt/packages/wllama.js +13 -14
- package/lib/wbt/registry.js +18 -1
- package/package.json +1 -1
- package/test/wbt.test.js +99 -4
package/dist/wbt.min.js
CHANGED
|
@@ -10,12 +10,26 @@
|
|
|
10
10
|
`)},logf:e=>{H(1,String(e)+`
|
|
11
11
|
`)},trace:(e,t,...n)=>{let r=t>0?` `+n.slice(0,t).join(`, `):``;H(1,`trace: ${fe(e)}${r}\n`)},seed:()=>Date.now()*Math.random(),abort:(e,t,n,r)=>{let i=fe(e),a=fe(t);throw(i||a)&&H(2,`abort: ${i||`aborted`} at ${a||this.script}:${n||0}:${r||0}\n`),this.exitCode=134,{_wasmExit:!0,code:134}}},{get(e,t){return t in e?e[t]:()=>0}})};try{let t=await WebAssembly.compile(e);for(let e of WebAssembly.Module.imports(t))if(e.kind===`memory`){let t=new WebAssembly.Memory({initial:1,maximum:256});E=t,$[e.module]||($[e.module]={}),$[e.module][e.name]=t}if(D=await WebAssembly.instantiate(t,$),D.exports.memory&&(E=D.exports.memory),this._getTermiosLflag=typeof D.exports.get_termios_lflag==`function`?D.exports.get_termios_lflag:null,O=!!(D.exports.asyncify_start_unwind&&D.exports.asyncify_stop_unwind),O&&E){try{k=E.grow(1)*65536}catch{k=16}let e=k+8,t=k+65536-8;new Int32Array(E.buffer,k,2).set([e,t])}typeof D.exports.set_terminal_size==`function`&&V(),B&&(this._enterAltScreen(),this._syncRawMode());let n=this.stdout&&this.stdout.columns||this.stdinStream&&this.stdinStream.columns||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`COLUMNS`),10)||80,r=this.stdout&&this.stdout.rows||this.stdinStream&&this.stdinStream.rows||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`LINES`),10)||24;if(typeof D.exports.set_terminal_size==`function`)try{D.exports.set_terminal_size(n,r)}catch{}let i=n,a=r,o=(e,t)=>{if(!(!e||!t)){if(this.stdout&&(this.stdout.columns!==e||this.stdout.rows!==t)&&(this.stdout.columns=e,this.stdout.rows=t),this.stdinStream&&(this.stdinStream.columns!==e||this.stdinStream.rows!==t)&&(this.stdinStream.columns=e,this.stdinStream.rows=t),this.context&&typeof this.context.setVar==`function`)try{this.context.setVar(`COLUMNS`,String(e)),this.context.setVar(`LINES`,String(t))}catch{}if(!(e===i&&t===a)){if(i=e,a=t,typeof D?.exports?.set_terminal_size==`function`)try{D.exports.set_terminal_size(e,t)}catch{}if(M){let e=M;M=null,e()}}}};R=()=>{o(this.stdout&&this.stdout.columns||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`COLUMNS`),10)||80,this.stdout&&this.stdout.rows||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`LINES`),10)||24)},ee=()=>{o(this.stdinStream&&this.stdinStream.columns||this.stdout&&this.stdout.columns||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`COLUMNS`),10)||80,this.stdinStream&&this.stdinStream.rows||this.stdout&&this.stdout.rows||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`LINES`),10)||24)},this.stdout&&typeof this.stdout.on==`function`&&this.stdout.on(`resize`,R),this.stdinStream&&this.stdinStream!==this.stdout&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`resize`,ee);let s=D.exports._start||D.exports.__wasi_command||D.exports.main||D.exports.run;if(s)try{let e=s();for(e&&typeof e.then==`function`&&(e=await e);O&&typeof D.exports.asyncify_get_state==`function`&&D.exports.asyncify_get_state()===1;){if(this._killed){this.exitCode=130;break}if(D.exports.asyncify_stop_unwind(),A){try{await A}catch{if(this._killed){this.exitCode=130;break}}A=null}if(this._killed){this.exitCode=130;break}D.exports.asyncify_start_rewind(k),e=s(),e&&typeof e.then==`function`&&(e=await e)}}catch(e){this._killed?this.exitCode=130:(!e||!e._wasmExit)&&(this.stdErr=`${this.script}: runtime error: ${e?.message||String(e)}`,this.exitCode=1)}else{let e=Object.entries(D.exports).filter(([,e])=>typeof e==`function`).map(([e])=>e),t=e.length>0?` (module is a library exporting: ${e.join(`, `)})`:``;this.stdErr=`${this.script}: no CLI entry point found (expected _start, main, or run)${t}`,this.exitCode=1}}catch(e){this._killed?this.exitCode=130:(!e||!e._wasmExit)&&(this.stdErr=`${this.script}: ${e?.message||String(e)}`,this.exitCode=1)}finally{B&&this._exitAltScreen(),te&&(this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`data`,te),this.stdin&&typeof this.stdin.off==`function`&&this.stdin.off(`data`,te)),re&&this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,this._onStdinStreamData),R&&this.stdout&&typeof this.stdout.off==`function`&&this.stdout.off(`resize`,R),ee&&this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`resize`,ee),this._externalKeyHandler=null,this._getTermiosLflag=null;for(let e of X.values())se(e)}U();let pe=this.arguments||[];if(!(this.result&&this.result.getStdOutput&&this.result.getStdOutput().length>0)&&(this.exitCode===0||this.exitCode===void 0)){let t=this._ensurePkgMeta(),n=t&&t.bin||(this.script||`wasm`).split(`/`).pop(),r=Object.assign({name:t&&t.name||n,version:t&&t.version||`wasi`,description:`WebAssembly WASI binary (${this.script})`},t||{});if(pe.includes(`--help`)||pe.includes(`-h`)){let t=N(e);for(let e of P(n,r,t))this.stdOut=e}else (pe.includes(`--version`)||pe.includes(`-V`)||pe.includes(`-v`))&&(this.stdOut=`${n} (${r.name} ${r.version} wasm)`)}}},O=new Map;function k(e,t){if(!e||!e.exists(t))return null;if(e.isRealFilesystem)try{let n=Y();return new Uint8Array(n.readFileSync(e.absolutePath(t)))}catch{}let n=e.getFileByPath(t);if(n==null)return null;if(n instanceof Uint8Array||v!==void 0&&v.isBuffer(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(n instanceof ArrayBuffer)return new Uint8Array(n);if(typeof n==`string`){if(n.startsWith(`data:`)){let e=n.indexOf(`,`);if(e!==-1){let t=n.slice(e+1);if(v!==void 0)return new Uint8Array(v.from(t,`base64`));let r=atob(t),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}}let e=new Uint8Array(n.length);for(let t=0;t<n.length;t++)e[t]=n.charCodeAt(t)&255;return e}return null}function A(e,t,n,i=`application/octet-stream`){let a=n instanceof Uint8Array?n:new Uint8Array(n);if(e&&e.isRealFilesystem){e.setFileByPath(t,a,!0);return}let o=new Uint8Array(a.byteLength);o.set(a);let s=new r(o.buffer,i);if(typeof e._setFileRaw==`function`&&t.startsWith(`/var/lib/wbt/`)){e._setFileRaw(t,s,!0);return}e.setFileByPath(t,s,!0)}async function j(e,t,n=null){if(typeof n==`function`){let r=await n(e,t);if(r)return r}try{let t=await import(e);if(t)return t}catch{}if(t)try{return await import(t)}catch(n){if(!/^https?:\/\/esm\.sh\//i.test(t))try{return await import(`https://esm.sh/${e}`)}catch{}throw Error(`Failed to load WASM package '${e}' from ${t}: ${n.message||n}`)}throw Error(`Package '${e}' could not be loaded`)}function M(e,t=!1){let n={usage:null,options:[]};if(!e||typeof e!=`string`)return n;let r=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),i=new Set,a=t?r.findIndex(e=>/^usage:\s*(.+)/i.test(e)):-1,o=a>=0?a:0;for(let e=o;e<r.length;e++){let a=r[e];!n.usage&&/^usage:\s*(.+)/i.test(a)?n.usage=a.replace(/^usage:\s*/i,``).trim():/^(?:-[a-zA-Z0-9?]|--[a-zA-Z0-9][-a-zA-Z0-9]*)(?:\s|,|=|<|\[|$)/.test(a)&&a.length<=120&&!/^(?:-[hHvV],\s*)?--(?:help|version)\b/i.test(a)&&(!t||/^(?:-[a-zA-Z?]|--[a-zA-Z][a-zA-Z0-9-]*)(?:,\s*--?[a-zA-Z0-9-]+)?(?:\s+[<\[a-zA-Z0-9_.->\]]+)*(?:\s+[A-Za-z`'"(][A-Za-z0-9 ,.;:()'"`/<>\[\]=+$\t_-]*|)$/.test(a))&&(i.has(a)||(i.add(a),n.options.push(a)))}if(t&&n.options.length===0){let t=e.match(/--[a-z][a-z0-9-]{1,24}/g)||[];for(let e of Array.from(new Set(t)).slice(0,12))e!==`--help`&&e!==`--version`&&n.options.push(e)}return n}function N(e){let t={usage:null,options:[],exports:[],wasiImports:[],hasAsyncify:!1,isInteractive:!1};if(!(e instanceof Uint8Array)||e.length<8)return t;try{if(typeof WebAssembly<`u`&&WebAssembly.Module){let n=new WebAssembly.Module(e);t.exports=WebAssembly.Module.exports(n).filter(e=>e.kind===`function`).map(e=>e.name),t.wasiImports=WebAssembly.Module.imports(n).filter(e=>e.module.startsWith(`wasi_`)).map(e=>e.name),t.hasAsyncify=t.exports.includes(`asyncify_start_unwind`)&&t.exports.includes(`asyncify_stop_unwind`),t.exports.includes(`set_terminal_size`)&&(t.isInteractive=!0)}}catch{}try{let n=[],r=``;for(let t=0;t<e.length;t++){let i=e[t];i>=32&&i<=126||i===9||i===10?r+=String.fromCharCode(i):(r.length>=4&&n.push(r),r=``)}r.length>=4&&n.push(r);let i=n.join(`
|
|
12
12
|
`);t.isInteractive||(i.includes(`/dev/tty`)||i.includes(`\x1B[?1049h`)||i.includes(`smcup`)||i.includes(`xterm`))&&(t.isInteractive=!0);let a=M(i,!0);t.usage=a.usage,t.options=a.options}catch{}return t}function P(e,t={},n=null){let r=t.name||e,i=t.version||`wasm`,a=t.description||`WebAssembly binary`,o=t&&typeof t.repl==`object`?t.repl:t.repl?{}:null,s=n&&n.usage||t.usage,c=s?s.replace(/%s/g,e):null,l=o?`${e} [options] ${o.evalFlag?`[${o.evalFlag} <code>] `:``}[file] [args...]`:`${e} [options] [args...]`,u=[`${e} (${r} ${i} wasm) — ${a}`,`Usage: ${c||l}`];t.details&&u.push(``,t.details),u.push(``,`Options:`);let d=n&&n.options&&n.options.length>0?n.options:Array.isArray(t.options)?t.options:[];if(d.length>0)for(let e of d)u.push(` ${e}`);else o&&(o.evalFlag&&u.push(` ${o.evalFlag.padEnd(20)}Evaluate inline code and print result`),u.push(` (no arguments) Start interactive ${e} REPL shell`));return u.push(` -h, --help Show this help message and exit`),u.push(` -V, --version Show WebAssembly binary version and exit`),n&&n.exports&&n.exports.length>0&&u.push(``,`WASM Exports: ${n.exports.join(`, `)}`),Array.isArray(t.aliases)&&t.aliases.length>0&&u.push(``,`Aliases: ${t.aliases.join(`, `)}`),(t.homepage||t.cdnUrl||t.wasmUrl)&&u.push(`Source: ${t.homepage||t.cdnUrl||t.wasmUrl}`),u}function F(e,t={},n=null){let r=U(),i=(n||e.bin||e.name).toLowerCase();class a extends r{static get name(){return i}get name(){return i}get requiresFilesystem(){return!0}get interactive(){return this._subCommand?this._subCommand.interactive:this._isInteractive===void 0?!!(e&&(e.interactive||e.wasm?.interactive)||this._inspectedWasm&&this._inspectedWasm.isInteractive):!!this._isInteractive}get captureInput(){return this._subCommand?!!this._subCommand.captureInput:this.interactive}get isRaw(){return this._subCommand?!!(this._subCommand.isRaw||this._subCommand.stdinStream&&this._subCommand.stdinStream.isRaw):!!(this.stdinStream&&this.stdinStream.isRaw)}get _inAltScreen(){return!!(this.__inAltScreen||this._subCommand&&this._subCommand._inAltScreen)}set _inAltScreen(e){this.__inAltScreen=!!e}kill(e=`SIGINT`){this._subCommand&&typeof this._subCommand.kill==`function`&&this._subCommand.kill(e),super.kill(e)}onInput(e){this._subCommand&&typeof this._subCommand.onInput==`function`&&this._subCommand.onInput(e)}async run(){let n=[...this.arguments||[]],r=n.includes(`--help`)||n.includes(`-h`),a=!r&&(n.includes(`--version`)||n.includes(`-V`)||n.includes(`-v`)),o=this.fs||this.context&&this.context.fs;this._inspectedWasm=null,this._persistedWasmBytes=e.wasmPath?k(o,e.wasmPath):null,r&&this._persistedWasmBytes&&this._persistedWasmBytes.byteLength>0&&(this._inspectedWasm=N(this._persistedWasmBytes));try{if((e.type===`wasm`||e.type===`custom-wasm`)&&(this._persistedWasmBytes||e.wasmUrl)){let i=this._persistedWasmBytes;if(!i&&t.moduleLoader)try{let n=await t.moduleLoader(e.name,e.cdnUrl);n instanceof Uint8Array||n instanceof ArrayBuffer?i=n instanceof Uint8Array?n:new Uint8Array(n):n&&(n.wasmBytes||n.wasm||n.wasmBinary)&&(i=n.wasmBytes||n.wasm||n.wasmBinary)}catch{}if(!i&&e.wasmUrl&&(i=await this._fetchWasmBytes(e.wasmUrl)),i){r&&(this._inspectedWasm=N(i)),await this._runRawWasmBytes(i,n);return}}else{let o=e.cdnUrl||e.wasmUrl||`https://esm.sh/${e.name}`,s=typeof globalThis.fetch==`function`?globalThis.fetch:null;if(s&&this._persistedWasmBytes&&this._persistedWasmBytes.byteLength>0&&typeof Response<`u`){let t=this._persistedWasmBytes,n=e.wasmUrl||``;globalThis.fetch=async(e,r)=>{let i=typeof e==`string`?e:e&&e.url?e.url:``;return i&&(i===n||!/^https?:\/\//i.test(i)&&/\.wasm(\?.*)?$/i.test(i))?new Response(t,{status:200,headers:{"Content-Type":`application/wasm`}}):s(e,r)}}let c,l;try{c=await j(e.name,o,t.moduleLoader),l=c&&c.default!==void 0?c.default:c,l&&typeof l.then==`function`&&(l=await l)}finally{s&&(globalThis.fetch=s)}if(l instanceof Uint8Array||l instanceof ArrayBuffer){let e=l instanceof Uint8Array?l:new Uint8Array(l);r&&(this._inspectedWasm=N(e)),await this._runRawWasmBytes(e,n)}else if(l&&(l.wasmBytes instanceof Uint8Array||l.wasm instanceof Uint8Array)){let e=l.wasmBytes||l.wasm;r&&(this._inspectedWasm=N(e)),await this._runRawWasmBytes(e,n)}else if(typeof l==`function`)await this._runFunctionOrEmscripten(l,n,r,a);else if(l&&typeof l==`object`){l.ready&&await l.ready,r&&(l.HEAPU8 instanceof Uint8Array||l.wasmBinary instanceof Uint8Array)&&(this._inspectedWasm=N(l.wasmBinary||l.HEAPU8));let t=l.main||l.run||l.callMain||l.exec;if(typeof t==`function`)await this._invokeCliFunction(t.bind(l),n);else if(l.promised||typeof l.raw==`function`||typeof l.json==`function`){let e=l.promised?await l.promised:l,t=n.filter(e=>e.startsWith(`-`)),i=n.filter(e=>!e.startsWith(`-`)),o=i.shift()||`.`,s=this._createIoBridge(n,[],[]),c=i.length>0?s.readFile(i[0])||``:s.stdin||(r||a?`{}`:``),u=typeof e.raw==`function`?e.raw(c,o,t):!r&&!a?JSON.stringify(e.json(JSON.parse(c||`null`),o)):null;u!=null&&String(u).replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>{this.stdOut=e})}else if(!r&&!a){this.stdErr=`${i}: unsupported WASM module format for '${e.name}'`,this.exitCode=1;return}}else if(!r&&!a){this.stdErr=`${i}: unsupported WASM module format for '${e.name}'`,this.exitCode=1;return}}}catch(e){if(!r&&!a){if(e&&typeof e.status==`number`){this.exitCode=e.status;return}this.stdErr=`${i}: ${e.message||e}`,this.exitCode=1;return}}if(r||a){let t=this.result&&this.result.getStdOutput?this.result.getStdOutput():[],n=t.map(e=>e.string).join(`
|
|
13
|
-
`),o=r?M(n):null,s=r&&!!(o&&(o.usage||o.options.length>0)||t.some(e=>/\b(usage|options):/i.test(e.string))),c=t.filter(e=>e.type===`out`).map(e=>e.string),l=a&&c.length>0&&(this.exitCode===0||this.exitCode===void 0);if(r)if(s){let e=t.map(e=>e.string);this.result&&Array.isArray(this.result.std)&&(this.result.std.length=0),this.exitCode=0;for(let t of e)this.stdOut=t}else{this.result&&Array.isArray(this.result.std)&&(this.result.std.length=0),this.exitCode=0;for(let t of P(i,e,this._inspectedWasm))this.stdOut=t}else a&&!l?(this.result&&Array.isArray(this.result.std)&&(this.result.std.length=0),this.exitCode=0,this.stdOut=`${i} (${e.name} ${e.version||`wasm`} wasm)`):this.exitCode=0}}async _fetchWasmBytes(e){if(O.has(e))return O.get(e);let n=t.fetch||(typeof fetch==`function`?fetch:null);if(!n)throw Error(`fetch is not available in this environment`);let r=await n(e);if(!r||!r.ok)throw Error(`HTTP ${r?r.status:`error`} fetching ${e}`);let i=new Uint8Array(await r.arrayBuffer());return O.set(e,i),i}async _runRawWasmBytes(t,n){let r=new D(i,n,this.context);r.script=i,r.arguments=n,r.context=this.context,r.fs=this.fs,r._pkgMeta=e,r.stdinStream=this.stdinStream,r.stdout=this.stdout,r.stderr=this.stderr,r.stdin=this.stdin&&!this.stdin.isTTY?this.stdin:this.stdinStream,this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`data`,this._onStdinStreamData);let a=()=>{this.emit(`interactive`),this.context&&typeof this.context.emit==`function`&&this.context.emit(`interactive`)};r.on(`interactive`,a),this._subCommand=r;try{await r._runWasm(t)}finally{r.removeListener(`interactive`,a),r._inAltScreen&&r._exitAltScreen(),this._subCommand=null,this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,this._onStdinStreamData)}for(let e of r.result.getStdOutput())e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.exitCode=r.result.getExitCode()}_createIoBridge(t,n,r){let a=e=>({write(t){(t instanceof Uint8Array?new TextDecoder().decode(t):String(t??``)).replace(/\r?\n$/,``).split(/\r?\n/).forEach(t=>e.push(t))}});return{binName:i,args:t,stdin:this.stdin!==void 0&&this.stdin!==null?String(this.stdin):``,fs:this.fs,context:this.context,wasmPath:e.wasmPath||null,wasmBytes:this._persistedWasmBytes||null,stdout:Object.assign(e=>n.push(String(e)),a(n)),stderr:Object.assign(e=>r.push(String(e)),a(r)),readFile:(e,t)=>{if(!this.fs)return null;let n=t&&t!==`.`&&!e.startsWith(`/`)?`${t.replace(/\/+$/,``)}/${e}`:e,r=this.fs.getFileByPath(n)??this.fs.getFileByPath(e);return r==null?null:typeof r==`string`?r:new TextDecoder().decode(r)},readBytes:e=>k(this.fs,e),writeFile:(e,t,n)=>{if(!this.fs)return;let r=n&&n!==`.`&&!e.startsWith(`/`)?`${n.replace(/\/+$/,``)}/${e}`:e;if(t instanceof Uint8Array||ArrayBuffer.isView(t)){let e=r.endsWith(`.wasm`)?`application/wasm`:`application/octet-stream`;A(this.fs,r,t,e)}else this.fs.setFileByPath(r,String(t),!0);if(r.endsWith(`.wasm`)||r.endsWith(`.wat`))try{this.fs.setMode(r,493)}catch{}},listFiles:(e,t)=>{if(!this.fs)return[];let n=t&&t!==`.`&&!e.startsWith(`/`)?`${t.replace(/\/+$/,``)}/${e}`:e,r=this.fs.getFileByPath(n);return r&&typeof r==`object`&&!(r instanceof Uint8Array)?Object.keys(r):[]}}}async _runFunctionOrEmscripten(t,n,r=!1,i=!1){let a=[],o=[],s=new TextEncoder().encode(this.stdin||``),c=0,l=new Set,u={arguments:n,noInitialRun:!0,...this._persistedWasmBytes&&this._persistedWasmBytes.byteLength>0?{wasmBinary:this._persistedWasmBytes}:{},...e.wasmUrl?{locateFile:t=>t.endsWith(`.wasm`)?e.wasmUrl:t}:{},print:e=>{a.push(String(e))},printErr:e=>{o.push(String(e))},stdin:()=>c<s.length?s[c++]:null,preRun:[e=>{e&&e.FS&&(l=this._syncBrshToEmscriptenFs(e.FS,n))}]},d=this._createIoBridge(n,a,o),f;try{f=t.prototype&&t.prototype.constructor===t&&Object.getOwnPropertyNames(t.prototype).length>1?new t(u,d):await t(u,d)}catch(e){if(e&&typeof e.status==`number`)this.exitCode=e.status;else throw e}if(f&&typeof f==`object`)if(r&&(f.wasmBinary instanceof Uint8Array||f.HEAPU8 instanceof Uint8Array)&&(this._inspectedWasm=N(f.wasmBinary||f.HEAPU8)),typeof f.callMain==`function`){f.FS&&l.size===0&&(l=this._syncBrshToEmscriptenFs(f.FS,n));try{let e=await f.callMain(n);typeof e==`number`&&e!==0&&(this.exitCode=e)}catch(e){e&&typeof e.status==`number`?this.exitCode=e.status:(o.push(e.message||String(e)),this.exitCode=1)}f.FS&&this._syncEmscriptenFsToBrsh(f.FS,n,l)}else if(typeof f.exec==`function`&&typeof f.writeFile==`function`)await this._runVirtualFsInstance(f,n,a,o);else if(typeof f.main==`function`||typeof f.run==`function`){let e=(f.main||f.run).bind(f);await this._invokeCliFunction(e,n,a,o)}else !r&&!i&&typeof f.Database==`function`?this._runSqlJsDatabase(f,n,d,a):(typeof f.stdout==`string`&&f.stdout&&f.stdout.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>a.push(e)),typeof f.stderr==`string`&&f.stderr&&f.stderr.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>o.push(e)),f.error&&o.length===0&&(o.push(f.error.message||String(f.error)),this.exitCode=1),typeof f.exitCode==`number`&&(this.exitCode=f.exitCode));else typeof f==`string`?f.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>a.push(e)):typeof f==`number`&&(this.exitCode=f);a.forEach(e=>{this.stdOut=e}),o.forEach(e=>{this.stdErr=e})}_runSqlJsDatabase(e,t,n,r){let i=`list`,a=`:memory:`,o=null,s=[];for(let e=0;e<t.length;e++){let n=t[e];n===`-table`||n===`--table`||n===`-box`?i=`table`:n===`-csv`||n===`--csv`?i=`csv`:n===`-cmd`&&e+1<t.length?o=t[++e]:n.startsWith(`-`)||s.push(n)}if(s.length===1?/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|PRAGMA|WITH|BEGIN|EXPLAIN|\.)\b/i.test(s[0])?o=s[0]:a=s[0]:s.length>=2&&(a=s[0],o=s.slice(1).join(` `)),!o&&n.stdin&&n.stdin.trim()&&(o=n.stdin.trim()),!o)return;let c=a===`:memory:`?null:n.readBytes(a),l=c&&c.byteLength>0?new e.Database(c):new e.Database;try{if(o.trim()===`.tables`){let e=l.exec(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`),t=e[0]&&e[0].values?e[0].values.map(e=>e[0]):[];t.length>0&&r.push(t.join(` `))}else{let e=l.exec(o);for(let t of e){let e=(t.columns||[]).map(String),n=t.values||[];if(i===`table`&&e.length>0){let t=e.map(e=>e.length),i=n.map(n=>e.map((e,r)=>{let i=n[r]==null?`NULL`:String(n[r]);return i.length>t[r]&&(t[r]=i.length),i}));r.push(e.map((e,n)=>` `+e.padEnd(t[n])+` `).join(`|`)),r.push(t.map(e=>`-`.repeat(e+2)).join(`+`)),i.forEach(e=>r.push(e.map((e,n)=>` `+e.padEnd(t[n])+` `).join(`|`)))}else if(i===`csv`){let t=e=>{let t=e==null?``:String(e);return/[",\r\n]/.test(t)?`"`+t.replace(/"/g,`""`)+`"`:t};e.length>0&&r.push(e.map(t).join(`,`)),n.forEach(n=>r.push(e.map((e,r)=>t(n[r])).join(`,`)))}else n.forEach(t=>r.push(e.map((e,n)=>t[n]==null?``:String(t[n])).join(`|`)))}}a!==`:memory:`&&n.writeFile(a,l.export())}finally{l.close()}}async _runVirtualFsInstance(t,n,r,i){typeof t.on==`function`&&t.on(`log`,({message:e})=>{e&&r.push(e)}),!t.loaded&&typeof t.load==`function`&&await t.load(e.coreUrl?{coreURL:e.coreUrl}:void 0);let a=new Set,o=[];for(let e of n)if(!e.startsWith(`-`)&&(o.push(e),this.fs.exists(e))){let n=k(this.fs,e);n&&(await t.writeFile(e,n),a.add(e))}let s=await t.exec(n);for(let e of o)if(!a.has(e))try{if(typeof t.readFile==`function`){let n=await t.readFile(e);n&&A(this.fs,e,n)}}catch{}typeof s==`number`&&s!==0&&(this.exitCode=s,i.length===0&&r.length>0&&i.push(...r.splice(0,r.length)))}async _invokeCliFunction(e,t,n=null,r=null){let i=n||[],a=r||[],o=await e(t,this._createIoBridge(t,i,a));typeof o==`string`?o.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>i.push(e)):typeof o==`number`?this.exitCode=o:o&&typeof o==`object`&&(typeof o.stdout==`string`&&o.stdout&&o.stdout.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>i.push(e)),typeof o.stderr==`string`&&o.stderr&&o.stderr.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>a.push(e)),o.error?(a.length===0&&a.push(o.error.message||String(o.error)),this.exitCode=typeof o.exitCode==`number`?o.exitCode:1):typeof o.exitCode==`number`&&(this.exitCode=o.exitCode)),n||(i.forEach(e=>{this.stdOut=e}),a.forEach(e=>{this.stdErr=e}))}_syncBrshToEmscriptenFs(e,t){let n=new Set;if(!this.fs||!e||typeof e.writeFile!=`function`)return n;for(let r of t)if(!r.startsWith(`-`)&&this.fs.exists(r)){let t=k(this.fs,r);if(t)try{e.writeFile(r,t),n.add(r)}catch{}}return n}_syncEmscriptenFsToBrsh(e,t,n){if(!(!this.fs||!e||typeof e.readFile!=`function`)){for(let r of t)if(!(r.startsWith(`-`)||n.has(r)))try{let t=e.readFile(r);if(t){let e=r.endsWith(`.wasm`)?`application/wasm`:`application/octet-stream`;if(A(this.fs,r,t,e),r.endsWith(`.wasm`)||r.endsWith(`.wat`))try{this.fs.setMode(r,493)}catch{}}}catch{}}}}return a}function I(e,t){return e&&(e.endsWith(`.wasm`)||e.endsWith(`.wat`))?!0:t instanceof Uint8Array?t.length>=4&&t[0]===0&&t[1]===97&&t[2]===115&&t[3]===109:typeof t==`string`?t.charCodeAt(0)===0&&t.slice(1,4)===`asm`?!0:t.trimStart().startsWith(`(module`):!1}function L(e,t){if(!e||!t||typeof e.exists!=`function`||typeof e.getFileByPath!=`function`)return null;try{let n=t.split(`/`).filter(Boolean);n.pop();let r=(n.length?`/`+n.join(`/`):``)+`/package.json`;if(e.exists(r)){let t=e.getFileByPath(r);if(typeof t==`string`)return JSON.parse(t)}}catch{}return null}D.isWasmFile=I,D.readSiblingPkgMeta=L,D.readBytesFromFs=k,D.writeBytesToFs=A,D.loadModule=j,D.extractHelpFromText=M,D.inspectWasmBytes=N,D.formatWasmHelp=P,D.createGenericWasmCommand=F,D.createCommand=F,t.exports=D})),ae=t(((e,t)=>{var n={sqlite3:{name:`sqlite3`,bin:`sqlite3`,aliases:[`sqlite`],version:`1.13.0`,description:`SQLite compiled to WebAssembly (via sql.js) with filesystem persistence`,details:`SQLite3 WASM allows creating, querying, and modifying SQLite database files directly in the brsh filesystem. Supports interactive SQL shell, piped SQL input, and one-shot queries.`,homepage:`https://sql.js.org`,cdnUrl:`https://esm.sh/sql.js@1.13.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/sql.js@1.13.0/dist/sql-wasm.wasm`,type:`generic-runtime`,repl:{prompt:`sqlite> `,sessionArg:!0},size:`680 KB`},assemblyscript:{name:`assemblyscript`,bin:`asc`,aliases:[`asrun`,`asnode`,`assemblyscript`],version:`0.27.31`,description:`AssemblyScript compiler (asc) and JIT/AOT runtime runner (asrun / asnode)`,details:"AssemblyScript compiles a strict variant of TypeScript to WebAssembly. Includes `asc` (ahead-of-time compiler to .wasm/.wat) and `asrun` / `asnode`.",homepage:`https://www.assemblyscript.org`,cdnUrl:`https://esm.sh/assemblyscript@0.27.31/asc`,wasmUrl:`https://cdn.jsdelivr.net/npm/binaryen@119.0.0/index.wasm`,type:`generic-runtime`,repl:{prompt:`as> `,evalFlag:`-e`},size:`1.4 MB`},jq:{name:`jq`,bin:`jq`,aliases:[],version:`0.6.2`,description:`Command-line JSON processor compiled to WebAssembly (jq-web)`,details:`jq is like sed for JSON data — you can use it to slice, filter, map, and transform structured JSON data from files or piped standard input.`,homepage:`https://jqlang.github.io/jq/`,cdnUrl:`https://esm.sh/jq-web@0.6.2`,wasmUrl:`https://cdn.jsdelivr.net/npm/jq-web@0.6.2/jq.wasm`,type:`generic-runtime`,size:`620 KB`},python3:{name:`python3`,bin:`python3`,aliases:[`python`,`py`],version:`3.12.1`,description:`CPython 3.12 compiled to WebAssembly (via Pyodide)`,details:"Full Python 3.12 runtime in WebAssembly powered by Pyodide. Supports interactive Python REPL (`>>>`), running `.py` scripts from the brsh filesystem, `-c` inline code evaluation, and piped standard input.",homepage:`https://pyodide.org`,cdnUrl:`https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.mjs`,wasmUrl:`https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.asm.wasm`,indexURL:`https://cdn.jsdelivr.net/pyodide/v0.26.4/full/`,type:`generic-runtime`,repl:{prompt:`>>> `,evalFlag:`-c`},size:`6.4 MB`},duckdb:{name:`duckdb`,bin:`duckdb`,aliases:[],version:`1.29.0`,description:`In-process analytical SQL OLAP database compiled to WebAssembly`,details:`DuckDB-WASM executes analytical SQL queries directly in WebAssembly, including querying CSV and JSON files stored in the brsh filesystem, interactive SQL shell, and one-shot / piped queries.`,homepage:`https://duckdb.org`,cdnUrl:`https://esm.sh/@duckdb/duckdb-wasm@1.29.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/dist/duckdb-mvp.wasm`,type:`generic-runtime`,repl:{prompt:`D `,continuePrompt:` > `,evalFlag:`-c`},size:`4.2 MB`},graphviz:{name:`graphviz`,bin:`dot`,aliases:[`graphviz`],version:`1.13.0`,description:"Graphviz graph visualization compiler (`dot`) compiled to WebAssembly",details:"Powered by @hpcc-js/wasm-graphviz. Compiles DOT language graph descriptions (`.dot` / `.gv`) into SVG, DOT, canon, or JSON formats (`dot -Tsvg input.dot -o output.svg`).",homepage:`https://graphviz.org`,cdnUrl:`https://esm.sh/@hpcc-js/wasm-graphviz@1.13.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/@hpcc-js/wasm-graphviz@1.13.0/dist/graphvizlib.wasm`,type:`generic-runtime`,size:`1.1 MB`},ffmpeg:{name:`ffmpeg`,bin:`ffmpeg`,aliases:[],version:`0.12.10`,description:`FFmpeg multimedia framework compiled to WebAssembly (@ffmpeg/ffmpeg)`,details:"Record, convert, transcode, and inspect audio, video, and image files directly inside the brsh filesystem using WebAssembly (`ffmpeg -i input.mp4 output.webm`).",homepage:`https://ffmpegwasm.netlify.app`,cdnUrl:`https://esm.sh/@ffmpeg/ffmpeg@0.12.10`,coreUrl:`https://unpkg.com/@ffmpeg/core@0.12.6/dist/esm/ffmpeg-core.js`,wasmUrl:`https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.6/dist/esm/ffmpeg-core.wasm`,type:`generic-runtime`,size:`8.5 MB`},wabt:{name:`wabt`,bin:`wat2wasm`,aliases:[`wasm2wat`],version:`1.0.36`,description:`WebAssembly Binary Toolkit (wat2wasm & wasm2wat)`,details:`WABT provides tools for translating between WebAssembly Text Format (.wat) and the WebAssembly binary format (.wasm), as well as inspecting WASM modules.`,homepage:`https://github.com/WebAssembly/wabt`,cdnUrl:`https://esm.sh/wabt@1.0.36`,wasmUrl:`https://cdn.jsdelivr.net/npm/wabt@1.0.36/libwabt.wasm`,type:`generic-runtime`,size:`540 KB`},quickjs:{name:`quickjs`,bin:`qjs`,aliases:[`quickjs`],version:`0.31.0`,description:`Sandboxed QuickJS JavaScript engine compiled to WebAssembly`,details:`QuickJS is a small and embeddable Javascript engine supporting ES2023. Runs JS code and files inside an isolated WebAssembly sandbox.`,homepage:`https://bellard.org/quickjs/`,cdnUrl:`https://esm.sh/quickjs-emscripten@0.31.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/@jitl/quickjs-wasmfile-release-sync@0.31.0/dist/emscripten-module.wasm`,type:`generic-runtime`,repl:{prompt:`qjs > `,evalFlag:`-e`},size:`820 KB`},lua:{name:`lua`,bin:`lua`,aliases:[],version:`5.4.6`,description:`Lua 5.4 interpreter compiled to WebAssembly (via wasmoon)`,details:"Full Lua 5.4 virtual machine compiled to WebAssembly. Supports interactive REPL, script execution from the brsh filesystem, and `-e` one-liners.",homepage:`https://www.lua.org`,cdnUrl:`https://esm.sh/wasmoon@1.16.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/wasmoon@1.16.0/dist/glue.wasm`,type:`generic-runtime`,repl:{prompt:`lua> `,evalFlag:`-e`},size:`410 KB`},wllama:{name:`wllama`,bin:`wllama`,aliases:[`llama`,`llama-cli`],version:`3.8.1`,description:`WebAssembly & WebGPU LLM inference engine powered by llama.cpp (@wllama/wllama)`,details:`Wllama v3 runs GGUF large language models in WebAssembly with automatic WebGPU hardware acceleration. Supports one-shot chat/text completions, interactive chat REPL, model inspection, embeddings, benchmarks, and Hugging Face & local filesystem GGUF loading.`,homepage:`https://github.com/ngxson/wllama`,cdnUrl:`https://cdn.jsdelivr.net/npm/@wllama/wllama@3.8.1/esm/index.js`,wasmUrl:`https://cdn.jsdelivr.net/npm/@wllama/wllama@3.8.1/src/wasm/wllama.wasm`,type:`builtin-adapter`,adapter:`wllama`,size:`8.8 MB`},nano:{name:`nano`,bin:`nano`,aliases:[`nano-wasm`],version:`8.0.1`,description:`GNU nano 8.0 text editor compiled to WebAssembly (wasm32-wasip1) with ncurses`,details:`GNU nano is a small, user-friendly command-line text editor compiled to WebAssembly with wide-character ncurses 6.5, built-in terminfo fallbacks (xterm-256color, vt100, etc.), dynamic terminal dimensions (TIOCGWINSZ / LINES & COLUMNS), and zero custom imports (standard wasi_snapshot_preview1).`,homepage:`https://github.com/eliotstocker/nano-wasm`,cdnUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/nano-wasm@main/dist/nano.wasm`,wasmUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/nano-wasm@main/dist/nano.wasm`,type:`custom-wasm`,interactive:!0,size:`680 KB`},doom:{name:`doom`,bin:`doom`,aliases:[`doom-wasm`,`doom-ascii`],scripts:{freedoom:`https://cdn.jsdelivr.net/gh/eliotstocker/doom-wasm@main/bin/freedoom`},version:`1.0.0`,description:`Classic Doom (1993) compiled to WebAssembly with 24-bit ANSI rendering`,details:"Classic Doom engine compiled to WebAssembly (wasm32-wasip1) with 24-bit TrueColor ANSI terminal graphics, wasi-termios-brsh terminal shim, and Asyncify real-time frame loop. Includes the `freedoom` launcher script which automatically downloads and caches Freedoom Phase 1/2 WADs into /usr/share/games/doom/.",homepage:`https://github.com/eliotstocker/doom-wasm`,cdnUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/doom-wasm@main/dist/doom.wasm`,wasmUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/doom-wasm@main/dist/doom.wasm`,type:`custom-wasm`,interactive:!0,size:`1.0 MB`}},r={sqlite:`sqlite3`,"sqlite-wasm":`sqlite3`,asc:`assemblyscript`,asrun:`assemblyscript`,asnode:`assemblyscript`,python:`python3`,py:`python3`,pyodide:`python3`,dot:`graphviz`,wat2wasm:`wabt`,wasm2wat:`wabt`,qjs:`quickjs`,llama:`wllama`,"llama-cli":`wllama`,"llama.cpp":`wllama`,"@wllama/wllama":`wllama`,"nano-wasm":`nano`,"doom-wasm":`doom`,"doom-ascii":`doom`,freedoom:`doom`};function i(e){if(!e)return null;let t=e.toLowerCase().replace(/^(npm|esm):/i,``).replace(/@[\d.^~><=*]+$/,``);return r[t]||t}t.exports={DEFAULT_REGISTRY:n,PACKAGE_ALIASES:r,resolvePackageName:i}})),oe=t(((e,t)=>{function n(e,t,n={}){let{showRowCount:r=!0}=n;if(!e||e.length===0)return[];let i=e.map(e=>String(e)),a=i.map(e=>e.length),o=(t||[]).map(e=>i.map((t,n)=>{let r=Array.isArray(e)?e[n]:e[t],i=r==null?`NULL`:String(r);return i.length>a[n]&&(a[n]=i.length),i})),s=[],c=i.map((e,t)=>` `+e.padEnd(a[t])+` `).join(`|`),l=a.map(e=>`-`.repeat(e+2)).join(`+`);s.push(c),s.push(l);for(let e of o)s.push(e.map((e,t)=>` `+e.padEnd(a[t])+` `).join(`|`));return r&&s.push(`(${o.length} row${o.length===1?``:`s`})`),s}function r(e,t,n=!1){let r=[],i=(e||[]).map(e=>String(e));n&&i.length>0&&r.push(i.join(`|`));for(let e of t||[]){let t=i.map((t,n)=>{let r=Array.isArray(e)?e[n]:e[t];return r==null?``:String(r)});r.push(t.join(`|`))}return r}function i(e,t,n=!0){let r=e=>{let t=e==null?``:String(e);return/[",\r\n]/.test(t)?`"`+t.replace(/"/g,`""`)+`"`:t},i=[],a=(e||[]).map(e=>String(e));n&&a.length>0&&i.push(a.map(r).join(`,`));for(let e of t||[]){let t=a.map((t,n)=>r(Array.isArray(e)?e[n]:e[t]));i.push(t.join(`,`))}return i}var{readBytesFromFs:a,writeBytesToFs:o,loadModule:s,extractHelpFromText:c,inspectWasmBytes:l,formatWasmHelp:u}=X();t.exports={formatTable:n,formatPipeList:r,formatCsv:i,readBytesFromFs:a,writeBytesToFs:o,loadModule:s,extractHelpFromText:c,inspectWasmBytes:l,formatWasmHelp:u}})),Z=t(((e,t)=>{U();var n=G(),{readBytesFromFs:r,writeBytesToFs:i,loadModule:a}=oe(),o={smol:`https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q4_K_M.gguf`,smollm:`https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q4_K_M.gguf`,smollm2:`https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q4_K_M.gguf`,"smol-135m":`https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q4_K_M.gguf`,"smol-360m":`https://huggingface.co/bartowski/SmolLM2-360M-Instruct-GGUF/resolve/main/SmolLM2-360M-Instruct-Q4_K_M.gguf`,"smollm-360m":`https://huggingface.co/bartowski/SmolLM2-360M-Instruct-GGUF/resolve/main/SmolLM2-360M-Instruct-Q4_K_M.gguf`,"smollm2-360m":`https://huggingface.co/bartowski/SmolLM2-360M-Instruct-GGUF/resolve/main/SmolLM2-360M-Instruct-Q4_K_M.gguf`,"smol-1.7b":`https://huggingface.co/bartowski/SmolLM2-1.7B-Instruct-GGUF/resolve/main/SmolLM2-1.7B-Instruct-Q4_K_M.gguf`,qwen:`https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf`,"qwen2.5":`https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf`,"qwen-0.5b":`https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf`,"qwen2.5-0.5b":`https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf`,"qwen-1.5b":`https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf`,"qwen2.5-1.5b":`https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf`,stories:`https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K.gguf`,stories15m:`https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories15M.gguf`},s=o.smol,c=`https://cdn.jsdelivr.net/npm/@wllama/wllama@3.8.1/src/wasm/wllama.wasm`,l=`/var/cache/wllama`,u=new Map;function d(e){if(!e)return`${l}/model.gguf`;if(e.kind===`fs`)return e.path;if(e.kind===`hf-quant`)return`${l}/${(e.repo||`model`).split(`/`).pop().replace(/[^a-zA-Z0-9._-]/g,`_`)}-${(e.quant||`Q4_K_M`).replace(/[^a-zA-Z0-9._-]/g,`_`)}.gguf`;let t=(e.file||e.url||s).split(`/`).pop().split(`?`)[0]||`model.gguf`;return/\.gguf$/i.test(t)||(t+=`.gguf`),`${l}/${t}`}function f(e){return!e||e<=0?`0 B`:e>=1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)} GB`:e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}function p(e,t,n,r=20){let i=(e||`model.gguf`).split(`/`).pop().split(`?`)[0]||e;if(n>0){let e=Math.max(0,Math.min(1,t/n)),a=Math.round(e*100),o=Math.round(e*r);return`\rPulling ${i}: [${`█`.repeat(o)+`░`.repeat(Math.max(0,r-o))}] ${String(a).padStart(3)}% (${f(t)} / ${f(n)})`}return`\rPulling ${i}: ${f(t)} downloaded...`}var m=class{constructor({onRender:e=null,width:t=20,intervalMs:n=80,enabled:r=!0}={}){this.onRender=e,this.width=t,this.intervalMs=n,this.enabled=r,this.label=``,this.total=0,this.loaded=0,this.hint=``,this.startTime=0,this.step=0,this.timer=null,this.active=!1,this.isDeterminate=!1}start(e,{total:t=0,loaded:n=0,hint:r=``,determinate:i=null}={}){this.enabled&&(this.stopTimer(),this.label=e||`Loading`,this.total=t||0,this.loaded=n||0,this.hint=r||``,this.startTime=Date.now(),this.step=0,this.active=!0,this.isDeterminate=i===null?this.total>0&&this.loaded>0:i,this.render(),this.timer=setInterval(()=>{this.step++,this.render()},this.intervalMs))}update({loaded:e,total:t,hint:n}={}){!this.enabled||!this.active||(typeof t==`number`&&t>0&&(this.total=t,this.isDeterminate=!0),typeof e==`number`&&e>=0&&(this.loaded=e,this.total>0&&(this.isDeterminate=!0)),typeof n==`string`&&(this.hint=n),this.render())}formatLine(){let e=((Date.now()-this.startTime)/1e3).toFixed(1)+`s`;if(this.isDeterminate&&this.total>0){let t=Math.max(0,Math.min(1,this.loaded/this.total)),n=Math.round(t*100),r=Math.round(t*this.width),i=`█`.repeat(r)+`░`.repeat(Math.max(0,this.width-r)),a=`${f(this.loaded)} / ${f(this.total)}`,o=this.hint?` (${this.hint})`:``;return`${this.label}: [${i}] ${String(n).padStart(3)}% (${a}, ${e})${o}`}let t=Math.max(1,this.width-5),n=t*2,r=this.step%n,i=r<t?r:n-r,a=`[${`░`.repeat(i)}${`█`.repeat(5)}${`░`.repeat(Math.max(0,this.width-i-5))}]`,o=this.hint?` (${this.hint})`:``;return`${this.label}: ${a} ${e}${o}`}render(){!this.enabled||!this.active||typeof this.onRender!=`function`||this.onRender(this.formatLine())}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null)}finish(e=`Done`){if(!this.enabled||!this.active)return;this.stopTimer();let t=((Date.now()-this.startTime)/1e3).toFixed(1)+`s`,n=`█`.repeat(this.width),r=this.total>0?`, ${f(this.total)}`:``,i=`${this.label}: [${n}] 100% (${t}${r}) — ${e}`;typeof this.onRender==`function`&&this.onRender(i),this.active=!1}clear(){this.stopTimer(),this.active=!1,this.enabled&&typeof this.onRender==`function`&&this.onRender(``)}};function h(e,t=null,n=null,r=null){if(t){if(n){let e=t.replace(/^hf:/i,``).replace(/^\/+|\/+$/g,``),r=n.replace(/^\/+/,``);return{kind:`hf-file`,key:`hf:${e}/${r}`,repo:e,file:r,url:`https://huggingface.co/${e}/resolve/main/${r}`}}return{kind:`hf-quant`,key:`hf:${t}:${r||`Q4_K_M`}`,repo:t.replace(/^hf:/i,``),quant:r||`Q4_K_M`}}let i=(e||``).trim();if(!i)return{kind:`url`,key:s,url:s};let a=i.toLowerCase();if(o[a]&&(i=o[a]),/^hf:\/\//i.test(i)||/^hf:/i.test(i)){let e=i.replace(/^hf:(\/\/)?/i,``),t=e.match(/^([^/]+\/[^/:]+):([^/]+)$/);if(t)return{kind:`hf-quant`,key:`hf:${t[1]}:${t[2]}`,repo:t[1],quant:t[2]};let n=e.split(`/`);if(n.length>=3){let e=`${n[0]}/${n[1]}`,t=n.slice(2).join(`/`);return{kind:`hf-file`,key:`hf:${e}/${t}`,repo:e,file:t,url:`https://huggingface.co/${e}/resolve/main/${t}`}}return{kind:`hf-quant`,key:`hf:${e}:Q4_K_M`,repo:e,quant:`Q4_K_M`}}return/^https?:\/\//i.test(i)?{kind:`url`,key:i,url:i}:{kind:`fs`,key:i,path:i}}async function g(e,t){let n=await fetch(e);if(!n.ok)throw Error(`Failed to fetch model from ${e}: HTTP ${n.status}`);let r=Number(n.headers.get(`content-length`)||0);if(!n.body||typeof n.body.getReader!=`function`){let r=await n.arrayBuffer();typeof t==`function`&&t({loaded:r.byteLength,total:r.byteLength});let i=new Blob([r],{type:`application/octet-stream`});return i.name=e.split(`/`).pop().split(`?`)[0]||`model.gguf`,i}let i=n.body.getReader(),a=[],o=0;for(;;){let{done:e,value:n}=await i.read();if(e)break;a.push(n),o+=n.byteLength,typeof t==`function`&&t({loaded:o,total:r})}let s=new Blob(a,{type:`application/octet-stream`});return s.name=e.split(`/`).pop().split(`?`)[0]||`model.gguf`,s}async function _({wllama:e,mod:t,modelSpec:n,downloadedBlob:r=null,targetPersistPath:a,fs:o,progressCallback:c}){if(!o||!a)return null;let l=null;if(r&&typeof r.arrayBuffer==`function`)l=new Uint8Array(await r.arrayBuffer());else if(e&&typeof e.getLoadedBlob==`function`){let t=await e.getLoadedBlob();t instanceof Uint8Array?l=t:t&&typeof t.arrayBuffer==`function`&&(l=new Uint8Array(await t.arrayBuffer()))}else if(e&&e.modelManager&&typeof e.modelManager.getModels==`function`)try{let t=(await e.modelManager.getModels()).find(e=>e&&typeof e.open==`function`);if(t){let e=await t.open();Array.isArray(e)&&e.length>0&&typeof e[0].arrayBuffer==`function`&&(l=new Uint8Array(await e[0].arrayBuffer()))}}catch{}if(!l){let e=n.url||(n.kind===`url`?s:null);if(!e&&n.kind===`hf-quant`&&t&&typeof t.getHFModelSource==`function`)try{let r=await t.getHFModelSource({repo:n.repo,quant:n.quant});e=r.url||r}catch{}if(e&&typeof fetch==`function`)try{let t=await g(e,c);l=new Uint8Array(await t.arrayBuffer())}catch{}}return l||=new Uint8Array([71,71,85,70,3,0,0,0]),i(o,a,l,`application/octet-stream`),{path:a,size:l.byteLength}}async function v(e={}){let{modelSpec:t,mmprojSpec:n=null,loadParams:o={},fs:l,pkgMeta:f={},wbtConfig:p={},loadModel:m=!0,persist:h=!1,persistPath:v=null,tracker:y=null,shortLabel:b=`model.gguf`,isPullCommand:x=!1,onStatus:S=null}=e;typeof S==`function`&&S(`Initializing WASM runtime...`);let C=await a(`@wllama/wllama`,f.cdnUrl,p.moduleLoader),w=C.Wllama||C.default||C,T=C.LoggerWithoutDebug||void 0,E=f.wasmUrl||c;if(f.wasmPath&&l&&typeof URL<`u`&&typeof URL.createObjectURL==`function`){let e=r(l,f.wasmPath);e&&e.byteLength>0&&(E=URL.createObjectURL(new Blob([e],{type:`application/wasm`})))}let D={default:E,"single-thread/wllama.wasm":E,"multi-thread/wllama.wasm":E},O=()=>{try{return new w(D,{suppressNativeLog:!0,logger:T})}catch{return new w(D,{suppressNativeLog:!0,logger:T,cacheManager:{isSupported:()=>!0,getNameFromURL:async e=>e,list:async()=>[],clear:async()=>{},delete:async()=>{}}})}};if(!m)return{wllama:O(),mod:C,Wllama:w,modelKey:null,isCached:!1,persisted:null};let k=v||(h&&t.kind!==`fs`?d(t):null),A=t.kind===`fs`?null:d(t),j=t.kind===`fs`&&l&&typeof l.absolutePath==`function`?`fs:${l.absolutePath(t.path)}:gpu=${o.n_gpu_layers??`auto`}:emb=${!!o.embeddings}`:`${t.key}:gpu=${o.n_gpu_layers??`auto`}:emb=${!!o.embeddings}`;if(u.has(j)){let e=u.get(j);if(typeof e.isModelLoaded!=`function`||e.isModelLoaded()){typeof S==`function`&&S(`Loaded model from cache.`),y&&y.finish(`Loaded model from cache`);let n=null;if((h||v)&&l&&k)if(l.exists(k)){let e=r(l,k);n={path:k,size:e?e.byteLength:0}}else n=await _({wllama:e,mod:C,modelSpec:t,targetPersistPath:k,fs:l,progressCallback:o.progressCallback});return{wllama:e,mod:C,Wllama:w,modelKey:j,isCached:!0,persisted:n}}}let M=O(),N=null,P=null,F=(e=`loading tensors`)=>({...o,progressCallback:({loaded:t,total:n})=>{y&&y.update({loaded:t,total:n,hint:e}),typeof o.progressCallback==`function`&&o.progressCallback({loaded:t,total:n})}});if(t.kind!==`fs`&&l){let e=k&&l.exists(k)?k:A&&l.exists(A)?A:null;if(e){let t=r(l,e);if(t&&t.byteLength>0){typeof S==`function`&&S(`Loading model from ${e}...`),y&&y.start(`Loading model (${b}) weights`,{total:t.byteLength,hint:`parsing tensors & compiling WebGPU shaders`});let n=new Blob([t],{type:`application/octet-stream`});n.name=e.split(`/`).pop()||`model.gguf`,await M.loadModel([n],F()),P={path:e,bytes:t},y&&y.finish(`Model weights loaded`)}}}if(P)k&&k!==P.path&&i(l,k,P.bytes,`application/octet-stream`);else if(t.kind===`fs`){typeof S==`function`&&S(`Loading model from ${t.path}...`),y&&y.start(`Loading model (${b}) weights`,{hint:`reading file`});let e=r(l,t.path);if(!e)throw Error(`${t.path}: No such file or directory`);let a=new Blob([e],{type:`application/octet-stream`});a.name=t.path.split(`/`).pop()||`model.gguf`;let o=[a];if(n){let e=r(l,n);if(!e)throw Error(`${n}: No such file or directory`);let t=new Blob([e],{type:`application/octet-stream`});t.name=n.split(`/`).pop()||`mmproj.gguf`,o.push(t)}typeof S==`function`&&S(`Loading model ${a.name} into memory...`),y&&y.start(`Loading model (${b}) weights`,{total:e.byteLength,loaded:e.byteLength,hint:`parsing tensors & compiling WebGPU shaders`}),await M.loadModel(o,F()),y&&y.finish(`Model weights loaded`),k&&k!==t.path&&i(l,k,e,`application/octet-stream`)}else if(t.kind===`hf-quant`&&typeof M.loadModelFromHF==`function`){typeof S==`function`&&S(`Pulling model ${t.repo} (${t.quant})...`),y&&y.start(`Pulling ${b}`,{hint:`connecting to Hugging Face`});try{await M.loadModelFromHF({repo:t.repo,quant:t.quant},F(`downloading`)),y&&y.finish(`Model weights loaded`)}catch(e){if(typeof C.getHFModelSource==`function`){let e=await C.getHFModelSource({repo:t.repo,quant:t.quant});typeof S==`function`&&S(`Pulling model ${t.repo} (${t.quant})...`),y&&y.start(`Pulling ${b}`,{hint:`downloading`}),N=await g(e.url||e,e=>{y&&y.update({loaded:e.loaded,total:e.total,hint:`downloading`}),typeof o.progressCallback==`function`&&o.progressCallback(e)}),typeof S==`function`&&S(`Loading model into memory...`),y&&y.start(`Loading model (${b}) weights`,{total:N.size,hint:`parsing tensors & compiling WebGPU shaders`}),await M.loadModel([N],F()),y&&y.finish(`Model weights loaded`)}else throw e}}else if(t.kind===`hf-file`&&typeof M.loadModelFromHF==`function`){typeof S==`function`&&S(`Pulling model ${t.repo}/${t.file}...`),y&&y.start(`Pulling ${b}`,{hint:`connecting to Hugging Face`});try{await M.loadModelFromHF({repo:t.repo,file:t.file},F(`downloading`)),y&&y.finish(`Model weights loaded`)}catch{y&&y.start(`Pulling ${b}`,{hint:`downloading`}),N=await g(t.url,e=>{y&&y.update({loaded:e.loaded,total:e.total,hint:`downloading`}),typeof o.progressCallback==`function`&&o.progressCallback(e)}),typeof S==`function`&&S(`Loading model into memory...`),y&&y.start(`Loading model (${b}) weights`,{total:N.size,hint:`parsing tensors & compiling WebGPU shaders`}),await M.loadModel([N],F()),y&&y.finish(`Model weights loaded`)}}else{let e=t.url||s;typeof S==`function`&&S(`Pulling model from ${e.split(`/`).pop().split(`?`)[0]||e}...`),y&&y.start(`Pulling ${b}`,{hint:`downloading`});try{n&&/^https?:\/\//i.test(n)?await M.loadModelFromUrl({url:e,mmprojUrl:n},F(`downloading`)):await M.loadModelFromUrl(e,F(`downloading`)),y&&y.finish(`Model weights loaded`)}catch{N=await g(e,e=>{y&&y.update({loaded:e.loaded,total:e.total,hint:`downloading`}),typeof o.progressCallback==`function`&&o.progressCallback(e)}),typeof S==`function`&&S(`Loading model into memory...`),y&&y.start(`Loading model (${b}) weights`,{total:N.size,hint:`parsing tensors & compiling WebGPU shaders`}),await M.loadModel([N],F()),y&&y.finish(`Model weights loaded`)}}typeof S==`function`&&S(`Model loaded.`);let I=null;return P?I={path:k||P.path,size:P.bytes.byteLength}:(h||v)&&l&&k&&t.kind!==`fs`&&(I=await _({wllama:M,mod:C,modelSpec:t,downloadedBlob:N,targetPersistPath:k,fs:l,progressCallback:o.progressCallback})),u.set(j,M),{wllama:M,mod:C,Wllama:w,modelKey:j,isCached:!1,persisted:I}}function y(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return``;if(Array.isArray(e.choices)&&e.choices.length>0){let t=e.choices[0];if(t.message&&typeof t.message.content==`string`)return t.message.content;if(typeof t.text==`string`)return t.text;if(t.delta&&typeof t.delta.content==`string`)return t.delta.content}return typeof e.content==`string`?e.content:typeof e.text==`string`?e.text:``}function b(e={},t={},i=`wllama`){class a extends n{static get name(){return i}get name(){return i}constructor(e,t){super(e,t),this._parsed=this._parseArgs(e||[]),this._wllama=null,this._WllamaClass=null,this._persisted=null,this._messages=[],this._parsed.systemPrompt&&this._messages.push({role:`system`,content:this._parsed.systemPrompt})}_parseArgs(e){let t=null,n=null,r=null,i=null,a=null,s=null,c=null,l=null,u=256,d=.7,f,p,m=4096,g,_,v,y=!1,b=!1,x=!1,S=!0,C=!0,w=!1,T=null,E=!0,D=!1,O=!1,k=null,A=[],j=[];for(let o=0;o<e.length;o++){let h=e[o];if(h===`--help`||h===`-h`&&o+1>=e.length||h===`-?`)D=!0;else if(h===`--version`||h===`-V`||h===`-v`)O=!0;else if(h===`--serve`||h===`--daemon`)k=`serve`;else if(h===`-q`||h===`--quiet`||h===`--no-progress`)E=!1;else if(h===`--progress`)E=!0;else if(h===`--persist`||h===`--save`){w=!0;let n=e[o+1];n&&!n.startsWith(`-`)&&!/^https?:\/\//i.test(n)&&!/^hf:/i.test(n)&&(n.startsWith(`/`)||n.startsWith(`./`)||n.startsWith(`../`)||/\.gguf$/i.test(n))&&(t!==null||r!==null||o+2<e.length||k===`pull`)&&(t!==null||r!==null)&&(T=e[++o])}else h.startsWith(`--persist=`)?(w=!0,T=h.slice(10)||null):h.startsWith(`--save=`)?(w=!0,T=h.slice(7)||null):(h===`-o`||h===`--output`)&&o+1<e.length?(w=!0,T=e[++o]):h.startsWith(`--output=`)?(w=!0,T=h.slice(9)||null):(h===`-m`||h===`--model`||h===`--url`)&&o+1<e.length?t=e[++o]:h.startsWith(`--model=`)?t=h.slice(8):h===`--mmproj`&&o+1<e.length?n=e[++o]:(h===`--hf`||h===`-hf`||h===`--hf-repo`)&&o+1<e.length?r=e[++o]:h===`--hf-file`&&o+1<e.length?i=e[++o]:(h===`--quant`||h===`--hf-quant`)&&o+1<e.length?a=e[++o]:(h===`-p`||h===`--prompt`)&&o+1<e.length?s=e[++o]:h.startsWith(`--prompt=`)?s=h.slice(9):(h===`-f`||h===`--file`)&&o+1<e.length?c=e[++o]:(h===`-s`||h===`--system`||h===`--system-prompt`)&&o+1<e.length?l=e[++o]:(h===`-n`||h===`--n-predict`||h===`--max-tokens`)&&o+1<e.length?u=Number(e[++o])||256:(h===`--temp`||h===`--temperature`)&&o+1<e.length?d=Number(e[++o]):(h===`--top-k`||h===`--top_k`)&&o+1<e.length?f=Number(e[++o]):(h===`--top-p`||h===`--top_p`)&&o+1<e.length?p=Number(e[++o]):(h===`-c`||h===`--ctx-size`||h===`--n-ctx`)&&o+1<e.length?m=Number(e[++o])||4096:(h===`-b`||h===`--batch-size`)&&o+1<e.length?g=Number(e[++o]):(h===`-t`||h===`--threads`)&&o+1<e.length?_=Number(e[++o]):(h===`-ngl`||h===`--n-gpu-layers`||h===`--gpu-layers`)&&o+1<e.length?v=Number(e[++o]):h===`--no-gpu`||h===`--cpu`?v=0:h===`--webgpu`||h===`--gpu`?(v===void 0||v===0)&&(v=99):h===`--embeddings`||h===`--embedding`||h===`--embed`?(y=!0,k||=`embed`):h===`--raw`||h===`--completion`?b=!0:h===`--stream`?S=!0:h===`--no-stream`?S=!1:h===`--json`?x=!0:h===`--no-jinja`?C=!1:h.startsWith(`-`)?A.push(h):j.push(h)}if(j.length>0){let e=j[0].toLowerCase();if([`info`,`models`,`list`,`embed`,`embeddings`,`bench`,`test-ops`,`run`,`chat`,`completion`,`pull`,`download`].includes(e)){let e=j.shift().toLowerCase();e===`list`?k=`models`:e===`embeddings`?(k=`embed`,y=!0):e===`test-ops`?k=`bench`:e===`completion`?(k=`run`,b=!0):e===`download`||e===`pull`?(k=`pull`,w=!0):k=e}}if(j.length>0&&(!t&&!r&&(k===`pull`||o[j[0].toLowerCase()]||/\.gguf(\?.*)?$/i.test(j[0])||/^hf:/i.test(j[0])||/^https?:\/\//i.test(j[0]))&&(t=j.shift()),k===`pull`&&j.length>0&&!T?T=j.shift():j.length>0&&s===null&&(s=j.join(` `))),!t&&!r&&this.context&&typeof this.context.getVar==`function`){let e=this.context.getVar(`WLLAMA_MODEL`);e&&(t=e)}let M=h(t,r,i,a),N={n_ctx:m,jinja:C};return v!==void 0&&(N.n_gpu_layers=v),g!==void 0&&(N.n_batch=g),_!==void 0&&(N.n_threads=_),y&&(N.embeddings=!0),{model:t,mmproj:n,modelSpec:M,loadParams:N,prompt:s,file:c,systemPrompt:l,maxTokens:u,temperature:d,topK:f,topP:p,nCtx:m,nGpuLayers:v,embeddings:y,rawCompletion:b,jsonOutput:x,stream:S,persist:w,persistPath:T,showProgress:E,help:D,version:O,subcommand:k,host:`127.0.0.1`,port:8080,extraArgs:A}}shouldBeInteractive(){return!(this._parsed.help||this._parsed.version||this._parsed.subcommand&&this._parsed.subcommand!==`chat`||this._parsed.prompt!==null||this._parsed.file!==null||this.stdin!==void 0&&this.stdin!==null&&String(this.stdin).trim().length>0)}getReplTitle(){let t=this._parsed.model||this._parsed.modelSpec.key,n=this._parsed.nGpuLayers===0?`CPU`:`WebGPU`;return`Wllama ${e.version||`3.8.1`} (llama.cpp ${n}) — ${t}`}getReplPrompt(){return`llama> `}getReplWelcome(){let t=(this._wllama&&typeof this._wllama.isSupportWebGPU==`function`?this._wllama.isSupportWebGPU():typeof navigator<`u`&&navigator.gpu)&&this._parsed.nGpuLayers!==0?`WebGPU (hardware accelerated)`:`WASM CPU (SIMD)`,n=[`wllama (${e.version}, llama.cpp WebAssembly + WebGPU runtime)`,`Model: ${this._parsed.model||this._parsed.modelSpec.key}`,`Backend: ${t}`];return this._persisted&&this._persisted.path&&n.push(`Saved: ${this._persisted.path}`),n.push(`Type a message to chat, "/help" for commands, or ".exit" / Ctrl+D to quit.`),n}_renderStatus(e){!this._parsed.showProgress||this._parsed.jsonOutput||(this.emit(`wllama:status`,e),this.stderr&&typeof this.stderr.write==`function`&&this.stderr.write(`\r\x1b[K${e}`))}_clearStatus(){!this._parsed.showProgress||this._parsed.jsonOutput||this.stderr&&typeof this.stderr.write==`function`&&this.stderr.write(`\r\x1B[K`)}_createTracker(e=`Loading`){return new m({enabled:!!(this._parsed.showProgress&&!this._parsed.jsonOutput),width:20,intervalMs:80,onRender:e=>{this.interactive?(this._replStatus=e,this._renderRepl()):e?this._renderStatus(e):this._clearStatus()}})}_attachProgressCallback(){if(!this._parsed.showProgress||this._parsed.modelSpec.kind===`fs`)return;let e=this._parsed.model||this._parsed.modelSpec.file||this._parsed.modelSpec.repo||this._parsed.modelSpec.url||`model.gguf`,t=0;this._parsed.loadParams.progressCallback=({loaded:n,total:r})=>{let i=Date.now();if(t===0||r>0&&n>=r||i-t>=40){t=i;let a=p(e,n,r);this.interactive?(this._replStatus=a.replace(/^\r/,``),this._renderRepl()):this._parsed.subcommand===`pull`?(this.stdOut=a,this.flush()):this._renderStatus(a.replace(/^\r/,``))}}}async _initWllama(n=!0){n&&this._attachProgressCallback();let r=this._parsed.model||this._parsed.modelSpec.file||this._parsed.modelSpec.repo||this._parsed.modelSpec.url||`model.gguf`,i=r.split(`/`).pop().split(`?`)[0]||r,a=this._createTracker(),o=e=>{this.interactive?(this._replStatus=e,this._renderRepl()):this._renderStatus(e)};try{let{wllama:r,Wllama:s,persisted:c}=await v({modelSpec:this._parsed.modelSpec,mmprojSpec:this._parsed.mmproj,loadParams:this._parsed.loadParams,fs:this.fs,pkgMeta:e,wbtConfig:t,loadModel:n,persist:this._parsed.persist,persistPath:this._parsed.persistPath,tracker:a,shortLabel:i,isPullCommand:this._parsed.subcommand===`pull`,onStatus:o});this._wllama=r,this._WllamaClass=s,this._persisted=c}finally{a&&a.clear(),this.interactive||this._clearStatus()}}async initRepl(){await this._initWllama(!0)}async evaluateReplLine(e){let t=e.trim();if(!t)return{output:[]};if(t.startsWith(`/`)){let e=t.split(/\s+/),n=e[0].toLowerCase();if(n===`/help`||n===`/?`)return{output:[`REPL Commands:`,` /help Show this help message`,` /info Display loaded model metadata & WebGPU status`,` /system <PROMPT> Set system prompt and reset chat context`,` /temp <FLOAT> Set sampling temperature (current: `+this._parsed.temperature+`)`,` /reset Clear conversation history`,` .exit Exit interactive shell`]};if(n===`/reset`)return this._messages=this._parsed.systemPrompt?[{role:`system`,content:this._parsed.systemPrompt}]:[],{output:[`Conversation history cleared.`]};if(n===`/system`){let t=e.slice(1).join(` `);return this._parsed.systemPrompt=t,this._messages=t?[{role:`system`,content:t}]:[],{output:[`System prompt updated: "${t}"`]}}if(n===`/temp`){let t=Number(e[1]);return Number.isNaN(t)?{error:`Usage: /temp <number>`}:(this._parsed.temperature=t,{output:[`Temperature set to ${t}`]})}return n===`/info`||n===`/model`?{output:this._formatModelInfo()}:{error:`Unknown command ${n}. Type /help for available commands.`}}try{this._messages.push({role:`user`,content:t});let e=!1,n=await this._runChatTurn(this._messages,t=>{e=!0,typeof this.streamReplChunk==`function`&&this.streamReplChunk(t)});return this._messages.push({role:`assistant`,content:n}),e?{streamed:!0}:{output:n.split(/\r?\n/)}}catch(e){return{error:`wllama: ${e.message||e}`}}}async _runChatTurn(e,t=null){let n=!!(this._parsed.stream&&!this._parsed.jsonOutput),r={messages:e,max_tokens:this._parsed.maxTokens,temperature:this._parsed.temperature,stream:n};this._parsed.topK!==void 0&&(r.top_k=this._parsed.topK),this._parsed.topP!==void 0&&(r.top_p=this._parsed.topP);let i=this._createTracker();i.start(`Running inference`,{hint:`evaluating prompt & preparing KV cache`});try{if(typeof this._wllama.createChatCompletion==`function`){let e=await this._wllama.createChatCompletion(r);if(e&&typeof e[Symbol.asyncIterator]==`function`){let n=``,r=!1;for await(let a of e){let e=a?.choices?.[0]?.delta?.content??a?.choices?.[0]?.text??``;e&&(r||(r=!0,i.clear(),this.interactive?(this._replStatus=`Streaming tokens...`,this._renderRepl()):this._clearStatus()),n+=e,typeof t==`function`&&t(e))}return i.clear(),this.interactive||this._clearStatus(),n}if(i.clear(),this.interactive||this._clearStatus(),this._parsed.jsonOutput)return JSON.stringify(e);let n=y(e);return typeof t==`function`&&n&&t(n),n}let a={prompt:e[e.length-1]?.content||``,max_tokens:this._parsed.maxTokens,temperature:this._parsed.temperature,stream:n};this._parsed.topK!==void 0&&(a.top_k=this._parsed.topK),this._parsed.topP!==void 0&&(a.top_p=this._parsed.topP);let o=await this._wllama.createCompletion(a);if(o&&typeof o[Symbol.asyncIterator]==`function`){let e=``,n=!1;for await(let r of o){let a=r?.choices?.[0]?.text??r?.choices?.[0]?.delta?.content??``;a&&(n||(n=!0,i.clear(),this.interactive?(this._replStatus=`Streaming tokens...`,this._renderRepl()):this._clearStatus()),e+=a,typeof t==`function`&&t(a))}return i.clear(),this.interactive||this._clearStatus(),e}if(i.clear(),this.interactive||this._clearStatus(),this._parsed.jsonOutput)return JSON.stringify(o);let s=y(o);return typeof t==`function`&&s&&t(s),s}finally{i.clear(),this.interactive||this._clearStatus()}}_formatModelInfo(){let t=this._wllama&&typeof this._wllama.isSupportWebGPU==`function`?this._wllama.isSupportWebGPU():!!(typeof navigator<`u`&&navigator.gpu),n=this._wllama&&typeof this._wllama.isMultithread==`function`?this._wllama.isMultithread():!1,r=this._wllama&&typeof this._wllama.getNumThreads==`function`?this._wllama.getNumThreads():1,i=this._WllamaClass&&typeof this._WllamaClass.getLibllamaVersion==`function`?this._WllamaClass.getLibllamaVersion():`b6327`,a=this._wllama&&typeof this._wllama.getModelMetadata==`function`?this._wllama.getModelMetadata():null,o=[`Engine: wllama ${e.version} (libllama ${i})`,`Model: ${this._parsed.model||this._parsed.modelSpec.key}`,`WebGPU: ${t?this._parsed.nGpuLayers===0?`supported (disabled via --no-gpu)`:`enabled`:`not available (using WASM SIMD CPU)`}`,`Multithread: ${n?`yes (${r} threads)`:`no (${r} thread)`}`,`Context Size: ${this._parsed.nCtx}`];return this._persisted&&this._persisted.path&&o.push(`Persisted: ${this._persisted.path}`),a&&a.hparams&&o.push(`Architecture: layers=${a.hparams.nLayer}, embd=${a.hparams.nEmbd}, vocab=${a.hparams.nVocab}, ctx_train=${a.hparams.nCtxTrain}`),o}async _handleSubcommand(){let e=this._parsed.subcommand;if(this._parsed.port,e===`pull`){try{await this._initWllama(!0);let e=this._persisted&&this._persisted.path||this._parsed.persistPath||d(this._parsed.modelSpec),t=this._persisted&&this._persisted.size||0,n=t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${t} B`;this.stdOut=`Persisted model ${this._parsed.model||this._parsed.modelSpec.key} -> ${e} (${n})`}catch(e){this.stdErr=`wllama: could not pull model: ${e.message||e}`,this.exitCode=1}return}if(e===`info`){await this._initWllama(!0);for(let e of this._formatModelInfo())this.stdOut=e;return}if(e===`models`){await this._initWllama(!1);let e=[];this._wllama&&this._wllama.modelManager&&typeof this._wllama.modelManager.getModels==`function`&&(e=await this._wllama.modelManager.getModels());let t=[];if(this.fs&&typeof this.fs.exists==`function`&&this.fs.exists(l)){let e=typeof this.fs.getFileByPath==`function`?this.fs.getFileByPath(l):null;if(e&&typeof e==`object`)for(let n of Object.keys(e)){let e=`${l}/${n}`,i=r(this.fs,e);t.push({path:e,size:i?i.byteLength:0})}}if(e.length===0&&u.size===0&&t.length===0){this.stdOut=`No cached models found.`;return}this.stdOut=`MODEL SIZE STATUS`;for(let[e]of u.entries())this.stdOut=`${e.split(`:gpu=`)[0].padEnd(54)} in-memory loaded`;for(let e of t){let t=e.size>=1024*1024?`${(e.size/(1024*1024)).toFixed(1)} MB`:`${e.size} B`;this.stdOut=`${e.path.padEnd(54)} ${t.padEnd(11)} persisted (fs)`}for(let t of e){let e=(t.url||t.name||`model.gguf`).padEnd(54),n=t.size?`${(t.size/(1024*1024)).toFixed(1)} MB`.padEnd(11):`cached `;this.stdOut=`${e} ${n} cached`}return}if(e===`bench`){if(await this._initWllama(!1),typeof this._wllama.testBackendOps==`function`){let e=await this._wllama.testBackendOps(this._parsed.extraArgs);this.stdOut=`ggml backend ops test: ${e&&e.success?`PASSED`:`FAILED`} (retcode=${e?e.retcode:0})`,e&&!e.success&&(this.exitCode=e.retcode||1)}else this.stdOut=`ggml backend ops test: PASSED (retcode=0)`;return}}async runNonInteractive(){if(this._parsed.help){[`${i} (${e.name} ${e.version} wasm) — ${e.description}`,`Usage: ${i} [OPTIONS] [-m MODEL.gguf] [-p PROMPT]`,` wllama pull <URL_OR_HF> [-o PATH] Download & persist model into brsh filesystem`,` wllama models List loaded, persisted (fs), and cached models`,` wllama info [-m MODEL] Show model metadata & WebGPU status`,` wllama embed [-m MODEL] -p TEXT Compute embedding vector for text`,` wllama bench Run ggml WebGPU/CPU backend ops test`,``,`Options:`,` -m, --model=MODEL Path in brsh fs, URL, HF spec, or alias (default: smol [SmolLM2-135M]; also: qwen)`,` --hf=REPO Hugging Face model repository (e.g. Qwen/Qwen2.5-0.5B-Instruct-GGUF)`,` --quant=QUANT Hugging Face GGUF quantization (default: Q4_K_M)`,` --persist[=PATH] Persist pulled remote model into brsh filesystem (default: /var/cache/wllama/)`,` -o, --output=PATH Save pulled remote model to a specific path in the brsh filesystem`,` -q, --no-progress Suppress live download progress bar when pulling remote models`,` --mmproj=PATH_OR_URL Multimodal vision/audio projector GGUF file or URL`,` -p, --prompt=TEXT Prompt text to generate completion for`,` -f, --file=FILENAME Read prompt from a file in the brsh filesystem`,` -s, --system=TEXT System prompt for chat completion`,` -n, --max-tokens=N Maximum tokens to generate (default: 256)`,` --temp, --temperature=F Sampling temperature (default: 0.7)`,` --top-k=N Top-K sampling parameter`,` --top-p=F Top-P nucleus sampling parameter`,` -c, --ctx-size=N Context window size n_ctx (default: 4096)`,` -ngl, --n-gpu-layers=N Number of layers offloaded to WebGPU (default: all)`,` --no-gpu, --cpu Disable WebGPU and run on WASM SIMD CPU only`,` --raw, --completion Use raw text completion instead of chat completion`,` --stream Stream tokens as they are generated (default: enabled)`,` --no-stream Disable token streaming and wait for full response`,` --embed, --embeddings Generate embeddings instead of text completion`,` --json Output raw JSON response`,` -h, --help Show this help message and exit`,` -V, --version Show WebAssembly binary version and exit`,``,`Aliases: wllama, llama, llama-cli`,`Source: ${e.homepage||e.cdnUrl}`].forEach(e=>{this.stdOut=e});return}if(this._parsed.version){this.stdOut=`${i} (${e.name} ${e.version} wasm)`;return}if(this._parsed.subcommand&&![`run`,`embed`].includes(this._parsed.subcommand)){await this._handleSubcommand();return}try{await this._initWllama(!0);let e=``;if(this._parsed.file){let t=this.fs.getFileByPath(this._parsed.file);if(t==null){this.stdErr=`${i}: error: ${this._parsed.file}: No such file or directory`,this.exitCode=1;return}e=String(t)}else this._parsed.prompt===null?this.stdin!==void 0&&this.stdin!==null&&String(this.stdin).trim().length>0&&(e=String(this.stdin).trim()):e=this._parsed.prompt;if(this._parsed.embeddings||this._parsed.subcommand===`embed`){let t=this._createTracker();t.start(`Computing embeddings`,{hint:`evaluating prompt`});let n;try{n=await this._wllama.createEmbedding({input:e})}finally{t.clear(),this._clearStatus()}if(this._parsed.jsonOutput)this.stdOut=JSON.stringify(n);else{let e=n?.data?.[0]?.embedding||n?.embedding||[];this.stdOut=JSON.stringify(e)}return}if(this._parsed.rawCompletion){let t=!!(this._parsed.stream&&!this._parsed.jsonOutput),n={prompt:e,max_tokens:this._parsed.maxTokens,temperature:this._parsed.temperature,stream:t};this._parsed.topK!==void 0&&(n.top_k=this._parsed.topK),this._parsed.topP!==void 0&&(n.top_p=this._parsed.topP);let r=this._createTracker();r.start(`Running inference`,{hint:`evaluating prompt & preparing KV cache`});try{let e=await this._wllama.createCompletion(n),t=``;if(e&&typeof e[Symbol.asyncIterator]==`function`){let n=!1;for await(let i of e){let e=i?.choices?.[0]?.text??i?.choices?.[0]?.delta?.content??``;e&&(n||(n=!0,this._streamedStdout=!0,r.clear(),this._clearStatus()),t+=e,this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(e),this.emit(`token`,e))}r.clear(),this._clearStatus(),n&&t.length>0&&!t.endsWith(`
|
|
13
|
+
`),o=r?M(n):null,s=r&&!!(o&&(o.usage||o.options.length>0)||t.some(e=>/\b(usage|options):/i.test(e.string))),c=t.filter(e=>e.type===`out`).map(e=>e.string),l=a&&c.length>0&&(this.exitCode===0||this.exitCode===void 0);if(r)if(s){let e=t.map(e=>e.string);this.result&&Array.isArray(this.result.std)&&(this.result.std.length=0),this.exitCode=0;for(let t of e)this.stdOut=t}else{this.result&&Array.isArray(this.result.std)&&(this.result.std.length=0),this.exitCode=0;for(let t of P(i,e,this._inspectedWasm))this.stdOut=t}else a&&!l?(this.result&&Array.isArray(this.result.std)&&(this.result.std.length=0),this.exitCode=0,this.stdOut=`${i} (${e.name} ${e.version||`wasm`} wasm)`):this.exitCode=0}}async _fetchWasmBytes(e){if(O.has(e))return O.get(e);let n=t.fetch||(typeof fetch==`function`?fetch:null);if(!n)throw Error(`fetch is not available in this environment`);let r=await n(e);if(!r||!r.ok)throw Error(`HTTP ${r?r.status:`error`} fetching ${e}`);let i=new Uint8Array(await r.arrayBuffer());return O.set(e,i),i}async _runRawWasmBytes(t,n){let r=new D(i,n,this.context);r.script=i,r.arguments=n,r.context=this.context,r.fs=this.fs,r._pkgMeta=e,r.stdinStream=this.stdinStream,r.stdout=this.stdout,r.stderr=this.stderr,r.stdin=this.stdin&&!this.stdin.isTTY?this.stdin:this.stdinStream,this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`data`,this._onStdinStreamData);let a=()=>{this.emit(`interactive`),this.context&&typeof this.context.emit==`function`&&this.context.emit(`interactive`)};r.on(`interactive`,a),this._subCommand=r;try{await r._runWasm(t)}finally{r.removeListener(`interactive`,a),r._inAltScreen&&r._exitAltScreen(),this._subCommand=null,this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,this._onStdinStreamData)}for(let e of r.result.getStdOutput())e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.exitCode=r.result.getExitCode()}_createIoBridge(t,n,r){let a=e=>({write(t){(t instanceof Uint8Array?new TextDecoder().decode(t):String(t??``)).replace(/\r?\n$/,``).split(/\r?\n/).forEach(t=>e.push(t))}});return{binName:i,args:t,stdin:this.stdin!==void 0&&this.stdin!==null?String(this.stdin):``,fs:this.fs,context:this.context,wasmPath:e.wasmPath||null,wasmBytes:this._persistedWasmBytes||null,stdout:Object.assign(e=>n.push(String(e)),a(n)),stderr:Object.assign(e=>r.push(String(e)),a(r)),readFile:(e,t)=>{if(!this.fs)return null;let n=t&&t!==`.`&&!e.startsWith(`/`)?`${t.replace(/\/+$/,``)}/${e}`:e,r=this.fs.getFileByPath(n)??this.fs.getFileByPath(e);return r==null?null:typeof r==`string`?r:new TextDecoder().decode(r)},readBytes:e=>k(this.fs,e),writeFile:(e,t,n)=>{if(!this.fs)return;let r=n&&n!==`.`&&!e.startsWith(`/`)?`${n.replace(/\/+$/,``)}/${e}`:e;if(t instanceof Uint8Array||ArrayBuffer.isView(t)){let e=r.endsWith(`.wasm`)?`application/wasm`:`application/octet-stream`;A(this.fs,r,t,e)}else this.fs.setFileByPath(r,String(t),!0);if(r.endsWith(`.wasm`)||r.endsWith(`.wat`))try{this.fs.setMode(r,493)}catch{}},listFiles:(e,t)=>{if(!this.fs)return[];let n=t&&t!==`.`&&!e.startsWith(`/`)?`${t.replace(/\/+$/,``)}/${e}`:e,r=this.fs.getFileByPath(n);return r&&typeof r==`object`&&!(r instanceof Uint8Array)?Object.keys(r):[]}}}async _runFunctionOrEmscripten(t,n,r=!1,i=!1){let a=[],o=[],s=new TextEncoder().encode(this.stdin||``),c=0,l=new Set,u={arguments:n,noInitialRun:!0,...this._persistedWasmBytes&&this._persistedWasmBytes.byteLength>0?{wasmBinary:this._persistedWasmBytes}:{},...e.wasmUrl?{locateFile:t=>t.endsWith(`.wasm`)?e.wasmUrl:t}:{},print:e=>{a.push(String(e))},printErr:e=>{o.push(String(e))},stdin:()=>c<s.length?s[c++]:null,preRun:[e=>{e&&e.FS&&(l=this._syncBrshToEmscriptenFs(e.FS,n))}]},d=this._createIoBridge(n,a,o),f;try{f=t.prototype&&t.prototype.constructor===t&&Object.getOwnPropertyNames(t.prototype).length>1?new t(u,d):await t(u,d)}catch(e){if(e&&typeof e.status==`number`)this.exitCode=e.status;else throw e}if(f&&typeof f==`object`)if(r&&(f.wasmBinary instanceof Uint8Array||f.HEAPU8 instanceof Uint8Array)&&(this._inspectedWasm=N(f.wasmBinary||f.HEAPU8)),typeof f.callMain==`function`){f.FS&&l.size===0&&(l=this._syncBrshToEmscriptenFs(f.FS,n));try{let e=await f.callMain(n);typeof e==`number`&&e!==0&&(this.exitCode=e)}catch(e){e&&typeof e.status==`number`?this.exitCode=e.status:(o.push(e.message||String(e)),this.exitCode=1)}f.FS&&this._syncEmscriptenFsToBrsh(f.FS,n,l)}else if(typeof f.exec==`function`&&typeof f.writeFile==`function`)await this._runVirtualFsInstance(f,n,a,o);else if(typeof f.main==`function`||typeof f.run==`function`){let e=(f.main||f.run).bind(f);await this._invokeCliFunction(e,n,a,o)}else !r&&!i&&typeof f.Database==`function`?this._runSqlJsDatabase(f,n,d,a):(typeof f.stdout==`string`&&f.stdout&&f.stdout.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>a.push(e)),typeof f.stderr==`string`&&f.stderr&&f.stderr.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>o.push(e)),f.error&&o.length===0&&(o.push(f.error.message||String(f.error)),this.exitCode=1),typeof f.exitCode==`number`&&(this.exitCode=f.exitCode));else typeof f==`string`?f.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>a.push(e)):typeof f==`number`&&(this.exitCode=f);a.forEach(e=>{this.stdOut=e}),o.forEach(e=>{this.stdErr=e})}_runSqlJsDatabase(e,t,n,r){let i=`list`,a=`:memory:`,o=null,s=[];for(let e=0;e<t.length;e++){let n=t[e];n===`-table`||n===`--table`||n===`-box`?i=`table`:n===`-csv`||n===`--csv`?i=`csv`:n===`-cmd`&&e+1<t.length?o=t[++e]:n.startsWith(`-`)||s.push(n)}if(s.length===1?/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|PRAGMA|WITH|BEGIN|EXPLAIN|\.)\b/i.test(s[0])?o=s[0]:a=s[0]:s.length>=2&&(a=s[0],o=s.slice(1).join(` `)),!o&&n.stdin&&n.stdin.trim()&&(o=n.stdin.trim()),!o)return;let c=a===`:memory:`?null:n.readBytes(a),l=c&&c.byteLength>0?new e.Database(c):new e.Database;try{if(o.trim()===`.tables`){let e=l.exec(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`),t=e[0]&&e[0].values?e[0].values.map(e=>e[0]):[];t.length>0&&r.push(t.join(` `))}else{let e=l.exec(o);for(let t of e){let e=(t.columns||[]).map(String),n=t.values||[];if(i===`table`&&e.length>0){let t=e.map(e=>e.length),i=n.map(n=>e.map((e,r)=>{let i=n[r]==null?`NULL`:String(n[r]);return i.length>t[r]&&(t[r]=i.length),i}));r.push(e.map((e,n)=>` `+e.padEnd(t[n])+` `).join(`|`)),r.push(t.map(e=>`-`.repeat(e+2)).join(`+`)),i.forEach(e=>r.push(e.map((e,n)=>` `+e.padEnd(t[n])+` `).join(`|`)))}else if(i===`csv`){let t=e=>{let t=e==null?``:String(e);return/[",\r\n]/.test(t)?`"`+t.replace(/"/g,`""`)+`"`:t};e.length>0&&r.push(e.map(t).join(`,`)),n.forEach(n=>r.push(e.map((e,r)=>t(n[r])).join(`,`)))}else n.forEach(t=>r.push(e.map((e,n)=>t[n]==null?``:String(t[n])).join(`|`)))}}a!==`:memory:`&&n.writeFile(a,l.export())}finally{l.close()}}async _runVirtualFsInstance(t,n,r,i){typeof t.on==`function`&&t.on(`log`,({message:e})=>{e&&r.push(e)}),!t.loaded&&typeof t.load==`function`&&await t.load(e.coreUrl?{coreURL:e.coreUrl}:void 0);let a=new Set,o=[];for(let e of n)if(!e.startsWith(`-`)&&(o.push(e),this.fs.exists(e))){let n=k(this.fs,e);n&&(await t.writeFile(e,n),a.add(e))}let s=await t.exec(n);for(let e of o)if(!a.has(e))try{if(typeof t.readFile==`function`){let n=await t.readFile(e);n&&A(this.fs,e,n)}}catch{}typeof s==`number`&&s!==0&&(this.exitCode=s,i.length===0&&r.length>0&&i.push(...r.splice(0,r.length)))}async _invokeCliFunction(e,t,n=null,r=null){let i=n||[],a=r||[],o=await e(t,this._createIoBridge(t,i,a));typeof o==`string`?o.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>i.push(e)):typeof o==`number`?this.exitCode=o:o&&typeof o==`object`&&(typeof o.stdout==`string`&&o.stdout&&o.stdout.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>i.push(e)),typeof o.stderr==`string`&&o.stderr&&o.stderr.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>a.push(e)),o.error?(a.length===0&&a.push(o.error.message||String(o.error)),this.exitCode=typeof o.exitCode==`number`?o.exitCode:1):typeof o.exitCode==`number`&&(this.exitCode=o.exitCode)),n||(i.forEach(e=>{this.stdOut=e}),a.forEach(e=>{this.stdErr=e}))}_syncBrshToEmscriptenFs(e,t){let n=new Set;if(!this.fs||!e||typeof e.writeFile!=`function`)return n;for(let r of t)if(!r.startsWith(`-`)&&this.fs.exists(r)){let t=k(this.fs,r);if(t)try{e.writeFile(r,t),n.add(r)}catch{}}return n}_syncEmscriptenFsToBrsh(e,t,n){if(!(!this.fs||!e||typeof e.readFile!=`function`)){for(let r of t)if(!(r.startsWith(`-`)||n.has(r)))try{let t=e.readFile(r);if(t){let e=r.endsWith(`.wasm`)?`application/wasm`:`application/octet-stream`;if(A(this.fs,r,t,e),r.endsWith(`.wasm`)||r.endsWith(`.wat`))try{this.fs.setMode(r,493)}catch{}}}catch{}}}}return a}function I(e,t){return e&&(e.endsWith(`.wasm`)||e.endsWith(`.wat`))?!0:t instanceof Uint8Array?t.length>=4&&t[0]===0&&t[1]===97&&t[2]===115&&t[3]===109:typeof t==`string`?t.charCodeAt(0)===0&&t.slice(1,4)===`asm`?!0:t.trimStart().startsWith(`(module`):!1}function L(e,t){if(!e||!t||typeof e.exists!=`function`||typeof e.getFileByPath!=`function`)return null;try{let n=t.split(`/`).filter(Boolean);n.pop();let r=(n.length?`/`+n.join(`/`):``)+`/package.json`;if(e.exists(r)){let t=e.getFileByPath(r);if(typeof t==`string`)return JSON.parse(t)}}catch{}return null}D.isWasmFile=I,D.readSiblingPkgMeta=L,D.readBytesFromFs=k,D.writeBytesToFs=A,D.loadModule=j,D.extractHelpFromText=M,D.inspectWasmBytes=N,D.formatWasmHelp=P,D.createGenericWasmCommand=F,D.createCommand=F,t.exports=D})),ae=t(((e,t)=>{var n={sqlite3:{name:`sqlite3`,bin:`sqlite3`,aliases:[`sqlite`],version:`1.13.0`,description:`SQLite compiled to WebAssembly (via sql.js) with filesystem persistence`,details:`SQLite3 WASM allows creating, querying, and modifying SQLite database files directly in the brsh filesystem. Supports interactive SQL shell, piped SQL input, and one-shot queries.`,homepage:`https://sql.js.org`,cdnUrl:`https://esm.sh/sql.js@1.13.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/sql.js@1.13.0/dist/sql-wasm.wasm`,type:`generic-runtime`,repl:{prompt:`sqlite> `,sessionArg:!0},size:`680 KB`},assemblyscript:{name:`assemblyscript`,bin:`asc`,aliases:[`asrun`,`asnode`,`assemblyscript`],version:`0.27.31`,description:`AssemblyScript compiler (asc) and JIT/AOT runtime runner (asrun / asnode)`,details:"AssemblyScript compiles a strict variant of TypeScript to WebAssembly. Includes `asc` (ahead-of-time compiler to .wasm/.wat) and `asrun` / `asnode`.",homepage:`https://www.assemblyscript.org`,cdnUrl:`https://esm.sh/assemblyscript@0.27.31/asc`,wasmUrl:`https://cdn.jsdelivr.net/npm/binaryen@119.0.0/index.wasm`,type:`generic-runtime`,repl:{prompt:`as> `,evalFlag:`-e`},size:`1.4 MB`},jq:{name:`jq`,bin:`jq`,aliases:[],version:`0.6.2`,description:`Command-line JSON processor compiled to WebAssembly (jq-web)`,details:`jq is like sed for JSON data — you can use it to slice, filter, map, and transform structured JSON data from files or piped standard input.`,homepage:`https://jqlang.github.io/jq/`,cdnUrl:`https://esm.sh/jq-web@0.6.2`,wasmUrl:`https://cdn.jsdelivr.net/npm/jq-web@0.6.2/jq.wasm`,type:`generic-runtime`,size:`620 KB`},python3:{name:`python3`,bin:`python3`,aliases:[`python`,`py`],version:`3.12.1`,description:`CPython 3.12 compiled to WebAssembly (via Pyodide)`,details:"Full Python 3.12 runtime in WebAssembly powered by Pyodide. Supports interactive Python REPL (`>>>`), running `.py` scripts from the brsh filesystem, `-c` inline code evaluation, and piped standard input.",homepage:`https://pyodide.org`,cdnUrl:`https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.mjs`,wasmUrl:`https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.asm.wasm`,indexURL:`https://cdn.jsdelivr.net/pyodide/v0.26.4/full/`,type:`generic-runtime`,repl:{prompt:`>>> `,evalFlag:`-c`},size:`6.4 MB`},duckdb:{name:`duckdb`,bin:`duckdb`,aliases:[],version:`1.29.0`,description:`In-process analytical SQL OLAP database compiled to WebAssembly`,details:`DuckDB-WASM executes analytical SQL queries directly in WebAssembly, including querying CSV and JSON files stored in the brsh filesystem, interactive SQL shell, and one-shot / piped queries.`,homepage:`https://duckdb.org`,cdnUrl:`https://esm.sh/@duckdb/duckdb-wasm@1.29.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/dist/duckdb-mvp.wasm`,type:`generic-runtime`,repl:{prompt:`D `,continuePrompt:` > `,evalFlag:`-c`},size:`4.2 MB`},graphviz:{name:`graphviz`,bin:`dot`,aliases:[`graphviz`],version:`1.13.0`,description:"Graphviz graph visualization compiler (`dot`) compiled to WebAssembly",details:"Powered by @hpcc-js/wasm-graphviz. Compiles DOT language graph descriptions (`.dot` / `.gv`) into SVG, DOT, canon, or JSON formats (`dot -Tsvg input.dot -o output.svg`).",homepage:`https://graphviz.org`,cdnUrl:`https://esm.sh/@hpcc-js/wasm-graphviz@1.13.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/@hpcc-js/wasm-graphviz@1.13.0/dist/graphvizlib.wasm`,type:`generic-runtime`,size:`1.1 MB`},ffmpeg:{name:`ffmpeg`,bin:`ffmpeg`,aliases:[],version:`0.12.10`,description:`FFmpeg multimedia framework compiled to WebAssembly (@ffmpeg/ffmpeg)`,details:"Record, convert, transcode, and inspect audio, video, and image files directly inside the brsh filesystem using WebAssembly (`ffmpeg -i input.mp4 output.webm`).",homepage:`https://ffmpegwasm.netlify.app`,cdnUrl:`https://esm.sh/@ffmpeg/ffmpeg@0.12.10`,coreUrl:`https://unpkg.com/@ffmpeg/core@0.12.6/dist/esm/ffmpeg-core.js`,wasmUrl:`https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.6/dist/esm/ffmpeg-core.wasm`,type:`generic-runtime`,size:`8.5 MB`},wabt:{name:`wabt`,bin:`wat2wasm`,aliases:[`wasm2wat`],version:`1.0.36`,description:`WebAssembly Binary Toolkit (wat2wasm & wasm2wat)`,details:`WABT provides tools for translating between WebAssembly Text Format (.wat) and the WebAssembly binary format (.wasm), as well as inspecting WASM modules.`,homepage:`https://github.com/WebAssembly/wabt`,cdnUrl:`https://esm.sh/wabt@1.0.36`,wasmUrl:`https://cdn.jsdelivr.net/npm/wabt@1.0.36/libwabt.wasm`,type:`generic-runtime`,size:`540 KB`},quickjs:{name:`quickjs`,bin:`qjs`,aliases:[`quickjs`],version:`0.31.0`,description:`Sandboxed QuickJS JavaScript engine compiled to WebAssembly`,details:`QuickJS is a small and embeddable Javascript engine supporting ES2023. Runs JS code and files inside an isolated WebAssembly sandbox.`,homepage:`https://bellard.org/quickjs/`,cdnUrl:`https://esm.sh/quickjs-emscripten@0.31.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/@jitl/quickjs-wasmfile-release-sync@0.31.0/dist/emscripten-module.wasm`,type:`generic-runtime`,repl:{prompt:`qjs > `,evalFlag:`-e`},size:`820 KB`},lua:{name:`lua`,bin:`lua`,aliases:[],version:`5.4.6`,description:`Lua 5.4 interpreter compiled to WebAssembly (via wasmoon)`,details:"Full Lua 5.4 virtual machine compiled to WebAssembly. Supports interactive REPL, script execution from the brsh filesystem, and `-e` one-liners.",homepage:`https://www.lua.org`,cdnUrl:`https://esm.sh/wasmoon@1.16.0`,wasmUrl:`https://cdn.jsdelivr.net/npm/wasmoon@1.16.0/dist/glue.wasm`,type:`generic-runtime`,repl:{prompt:`lua> `,evalFlag:`-e`},size:`410 KB`},wllama:{name:`wllama`,bin:`wllama`,aliases:[`llama`,`llama-cli`],version:`3.8.1`,description:`WebAssembly & WebGPU LLM inference engine powered by llama.cpp (@wllama/wllama)`,details:`Wllama v3 runs GGUF large language models in WebAssembly with automatic WebGPU hardware acceleration. Supports one-shot chat/text completions, interactive chat REPL, model inspection, embeddings, benchmarks, and Hugging Face & local filesystem GGUF loading.`,homepage:`https://github.com/ngxson/wllama`,cdnUrl:`https://cdn.jsdelivr.net/npm/@wllama/wllama@3.8.1/esm/index.js`,wasmUrl:`https://cdn.jsdelivr.net/npm/@wllama/wllama@3.8.1/src/wasm/wllama.wasm`,type:`builtin-adapter`,adapter:`wllama`,size:`8.8 MB`},nano:{name:`nano`,bin:`nano`,aliases:[`nano-wasm`,`pico`],version:`8.0.1`,description:`GNU nano 8.0 text editor compiled to WebAssembly (wasm32-wasip1) with ncurses`,details:`GNU nano is a small, user-friendly command-line text editor compiled to WebAssembly with wide-character ncurses 6.5, built-in terminfo fallbacks (xterm-256color, vt100, etc.), dynamic terminal dimensions (TIOCGWINSZ / LINES & COLUMNS), and zero custom imports (standard wasi_snapshot_preview1).`,homepage:`https://github.com/eliotstocker/nano-wasm`,cdnUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/nano-wasm@main/dist/nano.wasm`,wasmUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/nano-wasm@main/dist/nano.wasm`,type:`custom-wasm`,interactive:!0,size:`680 KB`},vim:{name:`vim`,bin:`vim`,aliases:[`vi`,`vim-wasm`],version:`9.1.0700`,description:`Vim 9.1 text editor compiled to WebAssembly (wasm32-wasip1) with ncurses`,details:`Vim 9.1 (9.1.0700) compiled to WebAssembly (wasm32-wasip1) with static ncursesw 6.5, built-in terminfo fallbacks (xterm-256color, vt100, etc.), Asyncify interactive I/O, built-in defaults.vim fallback, and zero custom imports (standard wasi_snapshot_preview1).`,homepage:`https://github.com/eliotstocker/vim-wasm`,cdnUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/vim-wasm@main/dist/vim.wasm`,wasmUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/vim-wasm@main/dist/vim.wasm`,type:`custom-wasm`,interactive:!0,size:`4.5 MB`},doom:{name:`doom`,bin:`doom`,aliases:[`doom-wasm`,`doom-ascii`],scripts:{freedoom:`https://cdn.jsdelivr.net/gh/eliotstocker/doom-wasm@main/bin/freedoom`},version:`1.0.0`,description:`Classic Doom (1993) compiled to WebAssembly with 24-bit ANSI rendering`,details:"Classic Doom engine compiled to WebAssembly (wasm32-wasip1) with 24-bit TrueColor ANSI terminal graphics, wasi-termios-brsh terminal shim, and Asyncify real-time frame loop. Includes the `freedoom` launcher script which automatically downloads and caches Freedoom Phase 1/2 WADs into /usr/share/games/doom/.",homepage:`https://github.com/eliotstocker/doom-wasm`,cdnUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/doom-wasm@main/dist/doom.wasm`,wasmUrl:`https://cdn.jsdelivr.net/gh/eliotstocker/doom-wasm@main/dist/doom.wasm`,type:`custom-wasm`,interactive:!0,size:`1.0 MB`}},r={sqlite:`sqlite3`,"sqlite-wasm":`sqlite3`,asc:`assemblyscript`,asrun:`assemblyscript`,asnode:`assemblyscript`,python:`python3`,py:`python3`,pyodide:`python3`,dot:`graphviz`,wat2wasm:`wabt`,wasm2wat:`wabt`,qjs:`quickjs`,llama:`wllama`,"llama-cli":`wllama`,"llama.cpp":`wllama`,"@wllama/wllama":`wllama`,"nano-wasm":`nano`,pico:`nano`,vi:`vim`,"vim-wasm":`vim`,"doom-wasm":`doom`,"doom-ascii":`doom`,freedoom:`doom`};function i(e){if(!e)return null;let t=e.toLowerCase().replace(/^(npm|esm):/i,``).replace(/@[\d.^~><=*]+$/,``);return r[t]||t}t.exports={DEFAULT_REGISTRY:n,PACKAGE_ALIASES:r,resolvePackageName:i}})),oe=t(((e,t)=>{function n(e,t,n={}){let{showRowCount:r=!0}=n;if(!e||e.length===0)return[];let i=e.map(e=>String(e)),a=i.map(e=>e.length),o=(t||[]).map(e=>i.map((t,n)=>{let r=Array.isArray(e)?e[n]:e[t],i=r==null?`NULL`:String(r);return i.length>a[n]&&(a[n]=i.length),i})),s=[],c=i.map((e,t)=>` `+e.padEnd(a[t])+` `).join(`|`),l=a.map(e=>`-`.repeat(e+2)).join(`+`);s.push(c),s.push(l);for(let e of o)s.push(e.map((e,t)=>` `+e.padEnd(a[t])+` `).join(`|`));return r&&s.push(`(${o.length} row${o.length===1?``:`s`})`),s}function r(e,t,n=!1){let r=[],i=(e||[]).map(e=>String(e));n&&i.length>0&&r.push(i.join(`|`));for(let e of t||[]){let t=i.map((t,n)=>{let r=Array.isArray(e)?e[n]:e[t];return r==null?``:String(r)});r.push(t.join(`|`))}return r}function i(e,t,n=!0){let r=e=>{let t=e==null?``:String(e);return/[",\r\n]/.test(t)?`"`+t.replace(/"/g,`""`)+`"`:t},i=[],a=(e||[]).map(e=>String(e));n&&a.length>0&&i.push(a.map(r).join(`,`));for(let e of t||[]){let t=a.map((t,n)=>r(Array.isArray(e)?e[n]:e[t]));i.push(t.join(`,`))}return i}var{readBytesFromFs:a,writeBytesToFs:o,loadModule:s,extractHelpFromText:c,inspectWasmBytes:l,formatWasmHelp:u}=X();t.exports={formatTable:n,formatPipeList:r,formatCsv:i,readBytesFromFs:a,writeBytesToFs:o,loadModule:s,extractHelpFromText:c,inspectWasmBytes:l,formatWasmHelp:u}})),Z=t(((e,t)=>{U();var n=G(),{readBytesFromFs:r,writeBytesToFs:i,loadModule:a}=oe(),o={smol:`https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q4_K_M.gguf`,smollm:`https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q4_K_M.gguf`,smollm2:`https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q4_K_M.gguf`,"smol-135m":`https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q4_K_M.gguf`,"smol-360m":`https://huggingface.co/bartowski/SmolLM2-360M-Instruct-GGUF/resolve/main/SmolLM2-360M-Instruct-Q4_K_M.gguf`,"smollm-360m":`https://huggingface.co/bartowski/SmolLM2-360M-Instruct-GGUF/resolve/main/SmolLM2-360M-Instruct-Q4_K_M.gguf`,"smollm2-360m":`https://huggingface.co/bartowski/SmolLM2-360M-Instruct-GGUF/resolve/main/SmolLM2-360M-Instruct-Q4_K_M.gguf`,"smol-1.7b":`https://huggingface.co/bartowski/SmolLM2-1.7B-Instruct-GGUF/resolve/main/SmolLM2-1.7B-Instruct-Q4_K_M.gguf`,qwen:`https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf`,"qwen2.5":`https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf`,"qwen-0.5b":`https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf`,"qwen2.5-0.5b":`https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf`,"qwen-1.5b":`https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf`,"qwen2.5-1.5b":`https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf`,stories:`https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K.gguf`,stories15m:`https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories15M.gguf`},s=o.smol,c=`https://cdn.jsdelivr.net/npm/@wllama/wllama@3.8.1/src/wasm/wllama.wasm`,l=`/var/cache/wllama`,u=new Map;function d(e){if(!e)return`${l}/model.gguf`;if(e.kind===`fs`)return e.path;if(e.kind===`hf-quant`)return`${l}/${(e.repo||`model`).split(`/`).pop().replace(/[^a-zA-Z0-9._-]/g,`_`)}-${(e.quant||`Q4_K_M`).replace(/[^a-zA-Z0-9._-]/g,`_`)}.gguf`;let t=(e.file||e.url||s).split(`/`).pop().split(`?`)[0]||`model.gguf`;return/\.gguf$/i.test(t)||(t+=`.gguf`),`${l}/${t}`}function f(e){return!e||e<=0?`0 B`:e>=1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)} GB`:e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}function p(e,t,n,r=20){let i=(e||`model.gguf`).split(`/`).pop().split(`?`)[0]||e;if(n>0){let e=Math.max(0,Math.min(1,t/n)),a=Math.round(e*100),o=Math.round(e*r);return`\rPulling ${i}: [${`█`.repeat(o)+`░`.repeat(Math.max(0,r-o))}] ${String(a).padStart(3)}% (${f(t)} / ${f(n)})`}return`\rPulling ${i}: ${f(t)} downloaded...`}var m=class{constructor({onRender:e=null,width:t=20,intervalMs:n=80,enabled:r=!0}={}){this.onRender=e,this.width=t,this.intervalMs=n,this.enabled=r,this.label=``,this.total=0,this.loaded=0,this.hint=``,this.startTime=0,this.step=0,this.timer=null,this.active=!1,this.isDeterminate=!1}start(e,{total:t=0,loaded:n=0,hint:r=``,determinate:i=null}={}){this.enabled&&(this.stopTimer(),this.label=e||`Loading`,this.total=t||0,this.loaded=n||0,this.hint=r||``,this.startTime=Date.now(),this.step=0,this.active=!0,this.isDeterminate=i===null?this.total>0&&this.loaded>0:i,this.render(),this.timer=setInterval(()=>{this.step++,this.render()},this.intervalMs))}update({loaded:e,total:t,hint:n}={}){!this.enabled||!this.active||(typeof t==`number`&&t>0&&(this.total=t,this.isDeterminate=!0),typeof e==`number`&&e>=0&&(this.loaded=e,this.total>0&&(this.isDeterminate=!0)),typeof n==`string`&&(this.hint=n),this.render())}formatLine(){let e=((Date.now()-this.startTime)/1e3).toFixed(1)+`s`;if(this.isDeterminate&&this.total>0){let t=Math.max(0,Math.min(1,this.loaded/this.total)),n=Math.round(t*100),r=Math.round(t*this.width),i=`█`.repeat(r)+`░`.repeat(Math.max(0,this.width-r)),a=`${f(this.loaded)} / ${f(this.total)}`,o=this.hint?` (${this.hint})`:``;return`${this.label}: [${i}] ${String(n).padStart(3)}% (${a}, ${e})${o}`}let t=Math.max(1,this.width-5),n=t*2,r=this.step%n,i=r<t?r:n-r,a=`[${`░`.repeat(i)}${`█`.repeat(5)}${`░`.repeat(Math.max(0,this.width-i-5))}]`,o=this.hint?` (${this.hint})`:``;return`${this.label}: ${a} ${e}${o}`}render(){!this.enabled||!this.active||typeof this.onRender!=`function`||this.onRender(this.formatLine())}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null)}finish(e=`Done`){if(!this.enabled||!this.active)return;this.stopTimer();let t=((Date.now()-this.startTime)/1e3).toFixed(1)+`s`,n=`█`.repeat(this.width),r=this.total>0?`, ${f(this.total)}`:``,i=`${this.label}: [${n}] 100% (${t}${r}) — ${e}`;typeof this.onRender==`function`&&this.onRender(i),this.active=!1}clear(){let e=this.active;this.stopTimer(),this.active=!1,e&&this.enabled&&typeof this.onRender==`function`&&this.onRender(``)}};function h(e,t=null,n=null,r=null){if(t){if(n){let e=t.replace(/^hf:/i,``).replace(/^\/+|\/+$/g,``),r=n.replace(/^\/+/,``);return{kind:`hf-file`,key:`hf:${e}/${r}`,repo:e,file:r,url:`https://huggingface.co/${e}/resolve/main/${r}`}}return{kind:`hf-quant`,key:`hf:${t}:${r||`Q4_K_M`}`,repo:t.replace(/^hf:/i,``),quant:r||`Q4_K_M`}}let i=(e||``).trim();if(!i)return{kind:`url`,key:s,url:s};let a=i.toLowerCase();if(o[a]&&(i=o[a]),/^hf:\/\//i.test(i)||/^hf:/i.test(i)){let e=i.replace(/^hf:(\/\/)?/i,``),t=e.match(/^([^/]+\/[^/:]+):([^/]+)$/);if(t)return{kind:`hf-quant`,key:`hf:${t[1]}:${t[2]}`,repo:t[1],quant:t[2]};let n=e.split(`/`);if(n.length>=3){let e=`${n[0]}/${n[1]}`,t=n.slice(2).join(`/`);return{kind:`hf-file`,key:`hf:${e}/${t}`,repo:e,file:t,url:`https://huggingface.co/${e}/resolve/main/${t}`}}return{kind:`hf-quant`,key:`hf:${e}:Q4_K_M`,repo:e,quant:`Q4_K_M`}}return/^https?:\/\//i.test(i)?{kind:`url`,key:i,url:i}:{kind:`fs`,key:i,path:i}}async function g(e,t){let n=await fetch(e);if(!n.ok)throw Error(`Failed to fetch model from ${e}: HTTP ${n.status}`);let r=Number(n.headers.get(`content-length`)||0);if(!n.body||typeof n.body.getReader!=`function`){let r=await n.arrayBuffer();typeof t==`function`&&t({loaded:r.byteLength,total:r.byteLength});let i=new Blob([r],{type:`application/octet-stream`});return i.name=e.split(`/`).pop().split(`?`)[0]||`model.gguf`,i}let i=n.body.getReader(),a=[],o=0;for(;;){let{done:e,value:n}=await i.read();if(e)break;a.push(n),o+=n.byteLength,typeof t==`function`&&t({loaded:o,total:r})}let s=new Blob(a,{type:`application/octet-stream`});return s.name=e.split(`/`).pop().split(`?`)[0]||`model.gguf`,s}async function _({wllama:e,mod:t,modelSpec:n,downloadedBlob:r=null,targetPersistPath:a,fs:o,progressCallback:c}){if(!o||!a)return null;let l=null;if(r&&typeof r.arrayBuffer==`function`)l=new Uint8Array(await r.arrayBuffer());else if(e&&typeof e.getLoadedBlob==`function`){let t=await e.getLoadedBlob();t instanceof Uint8Array?l=t:t&&typeof t.arrayBuffer==`function`&&(l=new Uint8Array(await t.arrayBuffer()))}else if(e&&e.modelManager&&typeof e.modelManager.getModels==`function`)try{let t=(await e.modelManager.getModels()).find(e=>e&&typeof e.open==`function`);if(t){let e=await t.open();Array.isArray(e)&&e.length>0&&typeof e[0].arrayBuffer==`function`&&(l=new Uint8Array(await e[0].arrayBuffer()))}}catch{}if(!l){let e=n.url||(n.kind===`url`?s:null);if(!e&&n.kind===`hf-quant`&&t&&typeof t.getHFModelSource==`function`)try{let r=await t.getHFModelSource({repo:n.repo,quant:n.quant});e=r.url||r}catch{}if(e&&typeof fetch==`function`)try{let t=await g(e,c);l=new Uint8Array(await t.arrayBuffer())}catch{}}return l||=new Uint8Array([71,71,85,70,3,0,0,0]),i(o,a,l,`application/octet-stream`),{path:a,size:l.byteLength}}async function v(e={}){let{modelSpec:t,mmprojSpec:n=null,loadParams:o={},fs:l,pkgMeta:f={},wbtConfig:p={},loadModel:m=!0,persist:h=!1,persistPath:v=null,tracker:y=null,shortLabel:b=`model.gguf`,isPullCommand:x=!1,onStatus:S=null}=e;typeof S==`function`&&S(`Initializing WASM runtime...`);let C=await a(`@wllama/wllama`,f.cdnUrl,p.moduleLoader),w=C.Wllama||C.default||C,T=C.LoggerWithoutDebug||void 0,E=f.wasmUrl||c;if(f.wasmPath&&l&&typeof URL<`u`&&typeof URL.createObjectURL==`function`){let e=r(l,f.wasmPath);e&&e.byteLength>0&&(E=URL.createObjectURL(new Blob([e],{type:`application/wasm`})))}let D={default:E,"single-thread/wllama.wasm":E,"multi-thread/wllama.wasm":E},O=()=>{try{return new w(D,{suppressNativeLog:!0,logger:T})}catch{return new w(D,{suppressNativeLog:!0,logger:T,cacheManager:{isSupported:()=>!0,getNameFromURL:async e=>e,list:async()=>[],clear:async()=>{},delete:async()=>{}}})}};if(!m)return{wllama:O(),mod:C,Wllama:w,modelKey:null,isCached:!1,persisted:null};let k=v||(h&&t.kind!==`fs`?d(t):null),A=t.kind===`fs`?null:d(t),j=t.kind===`fs`&&l&&typeof l.absolutePath==`function`?`fs:${l.absolutePath(t.path)}:gpu=${o.n_gpu_layers??`auto`}:emb=${!!o.embeddings}`:`${t.key}:gpu=${o.n_gpu_layers??`auto`}:emb=${!!o.embeddings}`;if(u.has(j)){let e=u.get(j);if(typeof e.isModelLoaded!=`function`||e.isModelLoaded()){typeof S==`function`&&S(`Loaded model from cache.`),y&&y.finish(`Loaded model from cache`);let n=null;if((h||v)&&l&&k)if(l.exists(k)){let e=r(l,k);n={path:k,size:e?e.byteLength:0}}else n=await _({wllama:e,mod:C,modelSpec:t,targetPersistPath:k,fs:l,progressCallback:o.progressCallback});return{wllama:e,mod:C,Wllama:w,modelKey:j,isCached:!0,persisted:n}}}let M=O(),N=null,P=null,F=(e=`loading tensors`)=>({...o,progressCallback:({loaded:t,total:n})=>{y&&y.update({loaded:t,total:n,hint:e}),typeof o.progressCallback==`function`&&o.progressCallback({loaded:t,total:n})}});if(t.kind!==`fs`&&l){let e=k&&l.exists(k)?k:A&&l.exists(A)?A:null;if(e){let t=r(l,e);if(t&&t.byteLength>0){typeof S==`function`&&S(`Loading model from ${e}...`),y&&y.start(`Loading model (${b}) weights`,{total:t.byteLength,hint:`parsing tensors & compiling WebGPU shaders`});let n=new Blob([t],{type:`application/octet-stream`});n.name=e.split(`/`).pop()||`model.gguf`,await M.loadModel([n],F()),P={path:e,bytes:t},y&&y.finish(`Model weights loaded`)}}}if(P)k&&k!==P.path&&i(l,k,P.bytes,`application/octet-stream`);else if(t.kind===`fs`){typeof S==`function`&&S(`Loading model from ${t.path}...`),y&&y.start(`Loading model (${b}) weights`,{hint:`reading file`});let e=r(l,t.path);if(!e)throw Error(`${t.path}: No such file or directory`);let a=new Blob([e],{type:`application/octet-stream`});a.name=t.path.split(`/`).pop()||`model.gguf`;let o=[a];if(n){let e=r(l,n);if(!e)throw Error(`${n}: No such file or directory`);let t=new Blob([e],{type:`application/octet-stream`});t.name=n.split(`/`).pop()||`mmproj.gguf`,o.push(t)}typeof S==`function`&&S(`Loading model ${a.name} into memory...`),y&&y.start(`Loading model (${b}) weights`,{total:e.byteLength,loaded:e.byteLength,hint:`parsing tensors & compiling WebGPU shaders`}),await M.loadModel(o,F()),y&&y.finish(`Model weights loaded`),k&&k!==t.path&&i(l,k,e,`application/octet-stream`)}else if(t.kind===`hf-quant`&&typeof M.loadModelFromHF==`function`){typeof S==`function`&&S(`Pulling model ${t.repo} (${t.quant})...`),y&&y.start(`Pulling ${b}`,{hint:`connecting to Hugging Face`});try{await M.loadModelFromHF({repo:t.repo,quant:t.quant},F(`downloading`)),y&&y.finish(`Model weights loaded`)}catch(e){if(typeof C.getHFModelSource==`function`){let e=await C.getHFModelSource({repo:t.repo,quant:t.quant});typeof S==`function`&&S(`Pulling model ${t.repo} (${t.quant})...`),y&&y.start(`Pulling ${b}`,{hint:`downloading`}),N=await g(e.url||e,e=>{y&&y.update({loaded:e.loaded,total:e.total,hint:`downloading`}),typeof o.progressCallback==`function`&&o.progressCallback(e)}),typeof S==`function`&&S(`Loading model into memory...`),y&&y.start(`Loading model (${b}) weights`,{total:N.size,hint:`parsing tensors & compiling WebGPU shaders`}),await M.loadModel([N],F()),y&&y.finish(`Model weights loaded`)}else throw e}}else if(t.kind===`hf-file`&&typeof M.loadModelFromHF==`function`){typeof S==`function`&&S(`Pulling model ${t.repo}/${t.file}...`),y&&y.start(`Pulling ${b}`,{hint:`connecting to Hugging Face`});try{await M.loadModelFromHF({repo:t.repo,file:t.file},F(`downloading`)),y&&y.finish(`Model weights loaded`)}catch{y&&y.start(`Pulling ${b}`,{hint:`downloading`}),N=await g(t.url,e=>{y&&y.update({loaded:e.loaded,total:e.total,hint:`downloading`}),typeof o.progressCallback==`function`&&o.progressCallback(e)}),typeof S==`function`&&S(`Loading model into memory...`),y&&y.start(`Loading model (${b}) weights`,{total:N.size,hint:`parsing tensors & compiling WebGPU shaders`}),await M.loadModel([N],F()),y&&y.finish(`Model weights loaded`)}}else{let e=t.url||s;typeof S==`function`&&S(`Pulling model from ${e.split(`/`).pop().split(`?`)[0]||e}...`),y&&y.start(`Pulling ${b}`,{hint:`downloading`});try{n&&/^https?:\/\//i.test(n)?await M.loadModelFromUrl({url:e,mmprojUrl:n},F(`downloading`)):await M.loadModelFromUrl(e,F(`downloading`)),y&&y.finish(`Model weights loaded`)}catch{N=await g(e,e=>{y&&y.update({loaded:e.loaded,total:e.total,hint:`downloading`}),typeof o.progressCallback==`function`&&o.progressCallback(e)}),typeof S==`function`&&S(`Loading model into memory...`),y&&y.start(`Loading model (${b}) weights`,{total:N.size,hint:`parsing tensors & compiling WebGPU shaders`}),await M.loadModel([N],F()),y&&y.finish(`Model weights loaded`)}}typeof S==`function`&&S(`Model loaded.`);let I=null;return P?I={path:k||P.path,size:P.bytes.byteLength}:(h||v)&&l&&k&&t.kind!==`fs`&&(I=await _({wllama:M,mod:C,modelSpec:t,downloadedBlob:N,targetPersistPath:k,fs:l,progressCallback:o.progressCallback})),u.set(j,M),{wllama:M,mod:C,Wllama:w,modelKey:j,isCached:!1,persisted:I}}function y(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return``;if(Array.isArray(e.choices)&&e.choices.length>0){let t=e.choices[0];if(t.message&&typeof t.message.content==`string`)return t.message.content;if(typeof t.text==`string`)return t.text;if(t.delta&&typeof t.delta.content==`string`)return t.delta.content}return typeof e.content==`string`?e.content:typeof e.text==`string`?e.text:``}function b(e={},t={},i=`wllama`){class a extends n{static get name(){return i}get name(){return i}constructor(e,t){super(e,t),this._parsed=this._parseArgs(e||[]),this._wllama=null,this._WllamaClass=null,this._persisted=null,this._messages=[],this._parsed.systemPrompt&&this._messages.push({role:`system`,content:this._parsed.systemPrompt})}_parseArgs(e){let t=null,n=null,r=null,i=null,a=null,s=null,c=null,l=null,u=256,d=.7,f,p,m=4096,g,_,v,y=!1,b=!1,x=!1,S=!0,C=!0,w=!1,T=null,E=!0,D=!1,O=!1,k=null,A=[],j=[];for(let o=0;o<e.length;o++){let h=e[o];if(h===`--help`||h===`-h`&&o+1>=e.length||h===`-?`)D=!0;else if(h===`--version`||h===`-V`||h===`-v`)O=!0;else if(h===`--serve`||h===`--daemon`)k=`serve`;else if(h===`-q`||h===`--quiet`||h===`--no-progress`)E=!1;else if(h===`--progress`)E=!0;else if(h===`--persist`||h===`--save`){w=!0;let n=e[o+1];n&&!n.startsWith(`-`)&&!/^https?:\/\//i.test(n)&&!/^hf:/i.test(n)&&(n.startsWith(`/`)||n.startsWith(`./`)||n.startsWith(`../`)||/\.gguf$/i.test(n))&&(t!==null||r!==null||o+2<e.length||k===`pull`)&&(t!==null||r!==null)&&(T=e[++o])}else h.startsWith(`--persist=`)?(w=!0,T=h.slice(10)||null):h.startsWith(`--save=`)?(w=!0,T=h.slice(7)||null):(h===`-o`||h===`--output`)&&o+1<e.length?(w=!0,T=e[++o]):h.startsWith(`--output=`)?(w=!0,T=h.slice(9)||null):(h===`-m`||h===`--model`||h===`--url`)&&o+1<e.length?t=e[++o]:h.startsWith(`--model=`)?t=h.slice(8):h===`--mmproj`&&o+1<e.length?n=e[++o]:(h===`--hf`||h===`-hf`||h===`--hf-repo`)&&o+1<e.length?r=e[++o]:h===`--hf-file`&&o+1<e.length?i=e[++o]:(h===`--quant`||h===`--hf-quant`)&&o+1<e.length?a=e[++o]:(h===`-p`||h===`--prompt`)&&o+1<e.length?s=e[++o]:h.startsWith(`--prompt=`)?s=h.slice(9):(h===`-f`||h===`--file`)&&o+1<e.length?c=e[++o]:(h===`-s`||h===`--system`||h===`--system-prompt`)&&o+1<e.length?l=e[++o]:(h===`-n`||h===`--n-predict`||h===`--max-tokens`)&&o+1<e.length?u=Number(e[++o])||256:(h===`--temp`||h===`--temperature`)&&o+1<e.length?d=Number(e[++o]):(h===`--top-k`||h===`--top_k`)&&o+1<e.length?f=Number(e[++o]):(h===`--top-p`||h===`--top_p`)&&o+1<e.length?p=Number(e[++o]):(h===`-c`||h===`--ctx-size`||h===`--n-ctx`)&&o+1<e.length?m=Number(e[++o])||4096:(h===`-b`||h===`--batch-size`)&&o+1<e.length?g=Number(e[++o]):(h===`-t`||h===`--threads`)&&o+1<e.length?_=Number(e[++o]):(h===`-ngl`||h===`--n-gpu-layers`||h===`--gpu-layers`)&&o+1<e.length?v=Number(e[++o]):h===`--no-gpu`||h===`--cpu`?v=0:h===`--webgpu`||h===`--gpu`?(v===void 0||v===0)&&(v=99):h===`--embeddings`||h===`--embedding`||h===`--embed`?(y=!0,k||=`embed`):h===`--raw`||h===`--completion`?b=!0:h===`--stream`?S=!0:h===`--no-stream`?S=!1:h===`--json`?x=!0:h===`--no-jinja`?C=!1:h.startsWith(`-`)?A.push(h):j.push(h)}if(j.length>0){let e=j[0].toLowerCase();if([`info`,`models`,`list`,`embed`,`embeddings`,`bench`,`test-ops`,`run`,`chat`,`completion`,`pull`,`download`].includes(e)){let e=j.shift().toLowerCase();e===`list`?k=`models`:e===`embeddings`?(k=`embed`,y=!0):e===`test-ops`?k=`bench`:e===`completion`?(k=`run`,b=!0):e===`download`||e===`pull`?(k=`pull`,w=!0):k=e}}if(j.length>0&&(!t&&!r&&(k===`pull`||o[j[0].toLowerCase()]||/\.gguf(\?.*)?$/i.test(j[0])||/^hf:/i.test(j[0])||/^https?:\/\//i.test(j[0]))&&(t=j.shift()),k===`pull`&&j.length>0&&!T?T=j.shift():j.length>0&&s===null&&(s=j.join(` `))),!t&&!r&&this.context&&typeof this.context.getVar==`function`){let e=this.context.getVar(`WLLAMA_MODEL`);e&&(t=e)}let M=h(t,r,i,a),N={n_ctx:m,jinja:C};return v!==void 0&&(N.n_gpu_layers=v),g!==void 0&&(N.n_batch=g),_!==void 0&&(N.n_threads=_),y&&(N.embeddings=!0),{model:t,mmproj:n,modelSpec:M,loadParams:N,prompt:s,file:c,systemPrompt:l,maxTokens:u,temperature:d,topK:f,topP:p,nCtx:m,nGpuLayers:v,embeddings:y,rawCompletion:b,jsonOutput:x,stream:S,persist:w,persistPath:T,showProgress:E,help:D,version:O,subcommand:k,host:`127.0.0.1`,port:8080,extraArgs:A}}shouldBeInteractive(){return!(this._parsed.help||this._parsed.version||this._parsed.subcommand&&this._parsed.subcommand!==`chat`||this._parsed.prompt!==null||this._parsed.file!==null||this.stdin!==void 0&&this.stdin!==null&&String(this.stdin).trim().length>0)}getReplTitle(){let t=this._parsed.model||this._parsed.modelSpec.key,n=this._parsed.nGpuLayers===0?`CPU`:`WebGPU`;return`Wllama ${e.version||`3.8.1`} (llama.cpp ${n}) — ${t}`}getReplPrompt(){return`llama> `}getReplWelcome(){let t=(this._wllama&&typeof this._wllama.isSupportWebGPU==`function`?this._wllama.isSupportWebGPU():typeof navigator<`u`&&navigator.gpu)&&this._parsed.nGpuLayers!==0?`WebGPU (hardware accelerated)`:`WASM CPU (SIMD)`,n=[`wllama (${e.version}, llama.cpp WebAssembly + WebGPU runtime)`,`Model: ${this._parsed.model||this._parsed.modelSpec.key}`,`Backend: ${t}`];return this._persisted&&this._persisted.path&&n.push(`Saved: ${this._persisted.path}`),n.push(`Type a message to chat, "/help" for commands, or ".exit" / Ctrl+D to quit.`),n}_renderStatus(e){!this._parsed.showProgress||this._parsed.jsonOutput||(this.emit(`wllama:status`,e),this.stderr&&typeof this.stderr.write==`function`&&this.stderr.write(`\r\x1b[K${e}`))}_clearStatus(){!this._parsed.showProgress||this._parsed.jsonOutput||this.stderr&&typeof this.stderr.write==`function`&&this.stderr.write(`\r\x1B[K`)}_createTracker(e=`Loading`){return new m({enabled:!!(this._parsed.showProgress&&!this._parsed.jsonOutput),width:20,intervalMs:80,onRender:e=>{this.interactive?(this._replStatus=e,this._renderRepl()):e?this._renderStatus(e):this._clearStatus()}})}_attachProgressCallback(){if(!this._parsed.showProgress||this._parsed.modelSpec.kind===`fs`)return;let e=this._parsed.model||this._parsed.modelSpec.file||this._parsed.modelSpec.repo||this._parsed.modelSpec.url||`model.gguf`,t=0;this._parsed.loadParams.progressCallback=({loaded:n,total:r})=>{let i=Date.now();if(t===0||r>0&&n>=r||i-t>=40){t=i;let a=p(e,n,r);this.interactive?(this._replStatus=a.replace(/^\r/,``),this._renderRepl()):this._parsed.subcommand===`pull`?(this.stdOut=a,this.flush()):this._renderStatus(a.replace(/^\r/,``))}}}async _initWllama(n=!0){n&&this._attachProgressCallback();let r=this._parsed.model||this._parsed.modelSpec.file||this._parsed.modelSpec.repo||this._parsed.modelSpec.url||`model.gguf`,i=r.split(`/`).pop().split(`?`)[0]||r,a=this._createTracker(),o=e=>{this.interactive?(this._replStatus=e,this._renderRepl()):this._renderStatus(e)};try{let{wllama:r,Wllama:s,persisted:c}=await v({modelSpec:this._parsed.modelSpec,mmprojSpec:this._parsed.mmproj,loadParams:this._parsed.loadParams,fs:this.fs,pkgMeta:e,wbtConfig:t,loadModel:n,persist:this._parsed.persist,persistPath:this._parsed.persistPath,tracker:a,shortLabel:i,isPullCommand:this._parsed.subcommand===`pull`,onStatus:o});this._wllama=r,this._WllamaClass=s,this._persisted=c}finally{a&&a.clear(),this.interactive||this._clearStatus()}}async initRepl(){await this._initWllama(!0)}async evaluateReplLine(e){let t=e.trim();if(!t)return{output:[]};if(t.startsWith(`/`)){let e=t.split(/\s+/),n=e[0].toLowerCase();if(n===`/help`||n===`/?`)return{output:[`REPL Commands:`,` /help Show this help message`,` /info Display loaded model metadata & WebGPU status`,` /system <PROMPT> Set system prompt and reset chat context`,` /temp <FLOAT> Set sampling temperature (current: `+this._parsed.temperature+`)`,` /reset Clear conversation history`,` .exit Exit interactive shell`]};if(n===`/reset`)return this._messages=this._parsed.systemPrompt?[{role:`system`,content:this._parsed.systemPrompt}]:[],{output:[`Conversation history cleared.`]};if(n===`/system`){let t=e.slice(1).join(` `);return this._parsed.systemPrompt=t,this._messages=t?[{role:`system`,content:t}]:[],{output:[`System prompt updated: "${t}"`]}}if(n===`/temp`){let t=Number(e[1]);return Number.isNaN(t)?{error:`Usage: /temp <number>`}:(this._parsed.temperature=t,{output:[`Temperature set to ${t}`]})}return n===`/info`||n===`/model`?{output:this._formatModelInfo()}:{error:`Unknown command ${n}. Type /help for available commands.`}}try{this._messages.push({role:`user`,content:t});let e=!1,n=await this._runChatTurn(this._messages,t=>{e=!0,typeof this.streamReplChunk==`function`&&this.streamReplChunk(t)});return this._messages.push({role:`assistant`,content:n}),e?{streamed:!0}:{output:n.split(/\r?\n/)}}catch(e){return{error:`wllama: ${e.message||e}`}}}async _runChatTurn(e,t=null){let n=!!(this._parsed.stream&&!this._parsed.jsonOutput),r={messages:e,max_tokens:this._parsed.maxTokens,temperature:this._parsed.temperature,stream:n};this._parsed.topK!==void 0&&(r.top_k=this._parsed.topK),this._parsed.topP!==void 0&&(r.top_p=this._parsed.topP);let i=this._createTracker();i.start(`Running inference`,{hint:`evaluating prompt & preparing KV cache`});let a=!1;try{if(typeof this._wllama.createChatCompletion==`function`){let e=await this._wllama.createChatCompletion(r);if(e&&typeof e[Symbol.asyncIterator]==`function`){let n=``;for await(let r of e){let e=r?.choices?.[0]?.delta?.content??r?.choices?.[0]?.text??``;e&&(a||(a=!0,i.clear(),this.interactive&&(this._replStatus=`Streaming tokens...`,this._renderRepl())),n+=e,typeof t==`function`&&t(e))}return i.clear(),!this.interactive&&!a&&this._clearStatus(),n}if(i.clear(),this.interactive||this._clearStatus(),this._parsed.jsonOutput)return JSON.stringify(e);let n=y(e);return typeof t==`function`&&n&&t(n),n}let o={prompt:e[e.length-1]?.content||``,max_tokens:this._parsed.maxTokens,temperature:this._parsed.temperature,stream:n};this._parsed.topK!==void 0&&(o.top_k=this._parsed.topK),this._parsed.topP!==void 0&&(o.top_p=this._parsed.topP);let s=await this._wllama.createCompletion(o);if(s&&typeof s[Symbol.asyncIterator]==`function`){let e=``;for await(let n of s){let r=n?.choices?.[0]?.text??n?.choices?.[0]?.delta?.content??``;r&&(a||(a=!0,i.clear(),this.interactive&&(this._replStatus=`Streaming tokens...`,this._renderRepl())),e+=r,typeof t==`function`&&t(r))}return i.clear(),!this.interactive&&!a&&this._clearStatus(),e}if(i.clear(),this.interactive||this._clearStatus(),this._parsed.jsonOutput)return JSON.stringify(s);let c=y(s);return typeof t==`function`&&c&&t(c),c}finally{i.clear(),!this.interactive&&!a&&this._clearStatus()}}_formatModelInfo(){let t=this._wllama&&typeof this._wllama.isSupportWebGPU==`function`?this._wllama.isSupportWebGPU():!!(typeof navigator<`u`&&navigator.gpu),n=this._wllama&&typeof this._wllama.isMultithread==`function`?this._wllama.isMultithread():!1,r=this._wllama&&typeof this._wllama.getNumThreads==`function`?this._wllama.getNumThreads():1,i=this._WllamaClass&&typeof this._WllamaClass.getLibllamaVersion==`function`?this._WllamaClass.getLibllamaVersion():`b6327`,a=this._wllama&&typeof this._wllama.getModelMetadata==`function`?this._wllama.getModelMetadata():null,o=[`Engine: wllama ${e.version} (libllama ${i})`,`Model: ${this._parsed.model||this._parsed.modelSpec.key}`,`WebGPU: ${t?this._parsed.nGpuLayers===0?`supported (disabled via --no-gpu)`:`enabled`:`not available (using WASM SIMD CPU)`}`,`Multithread: ${n?`yes (${r} threads)`:`no (${r} thread)`}`,`Context Size: ${this._parsed.nCtx}`];return this._persisted&&this._persisted.path&&o.push(`Persisted: ${this._persisted.path}`),a&&a.hparams&&o.push(`Architecture: layers=${a.hparams.nLayer}, embd=${a.hparams.nEmbd}, vocab=${a.hparams.nVocab}, ctx_train=${a.hparams.nCtxTrain}`),o}async _handleSubcommand(){let e=this._parsed.subcommand;if(this._parsed.port,e===`pull`){try{await this._initWllama(!0);let e=this._persisted&&this._persisted.path||this._parsed.persistPath||d(this._parsed.modelSpec),t=this._persisted&&this._persisted.size||0,n=t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${t} B`;this.stdOut=`Persisted model ${this._parsed.model||this._parsed.modelSpec.key} -> ${e} (${n})`}catch(e){this.stdErr=`wllama: could not pull model: ${e.message||e}`,this.exitCode=1}return}if(e===`info`){await this._initWllama(!0);for(let e of this._formatModelInfo())this.stdOut=e;return}if(e===`models`){await this._initWllama(!1);let e=[];this._wllama&&this._wllama.modelManager&&typeof this._wllama.modelManager.getModels==`function`&&(e=await this._wllama.modelManager.getModels());let t=[];if(this.fs&&typeof this.fs.exists==`function`&&this.fs.exists(l)){let e=typeof this.fs.getFileByPath==`function`?this.fs.getFileByPath(l):null;if(e&&typeof e==`object`)for(let n of Object.keys(e)){let e=`${l}/${n}`,i=r(this.fs,e);t.push({path:e,size:i?i.byteLength:0})}}if(e.length===0&&u.size===0&&t.length===0){this.stdOut=`No cached models found.`;return}this.stdOut=`MODEL SIZE STATUS`;for(let[e]of u.entries())this.stdOut=`${e.split(`:gpu=`)[0].padEnd(54)} in-memory loaded`;for(let e of t){let t=e.size>=1024*1024?`${(e.size/(1024*1024)).toFixed(1)} MB`:`${e.size} B`;this.stdOut=`${e.path.padEnd(54)} ${t.padEnd(11)} persisted (fs)`}for(let t of e){let e=(t.url||t.name||`model.gguf`).padEnd(54),n=t.size?`${(t.size/(1024*1024)).toFixed(1)} MB`.padEnd(11):`cached `;this.stdOut=`${e} ${n} cached`}return}if(e===`bench`){if(await this._initWllama(!1),typeof this._wllama.testBackendOps==`function`){let e=await this._wllama.testBackendOps(this._parsed.extraArgs);this.stdOut=`ggml backend ops test: ${e&&e.success?`PASSED`:`FAILED`} (retcode=${e?e.retcode:0})`,e&&!e.success&&(this.exitCode=e.retcode||1)}else this.stdOut=`ggml backend ops test: PASSED (retcode=0)`;return}}async runNonInteractive(){if(this._parsed.help){[`${i} (${e.name} ${e.version} wasm) — ${e.description}`,`Usage: ${i} [OPTIONS] [-m MODEL.gguf] [-p PROMPT]`,` wllama pull <URL_OR_HF> [-o PATH] Download & persist model into brsh filesystem`,` wllama models List loaded, persisted (fs), and cached models`,` wllama info [-m MODEL] Show model metadata & WebGPU status`,` wllama embed [-m MODEL] -p TEXT Compute embedding vector for text`,` wllama bench Run ggml WebGPU/CPU backend ops test`,``,`Options:`,` -m, --model=MODEL Path in brsh fs, URL, HF spec, or alias (default: smol [SmolLM2-135M]; also: qwen)`,` --hf=REPO Hugging Face model repository (e.g. Qwen/Qwen2.5-0.5B-Instruct-GGUF)`,` --quant=QUANT Hugging Face GGUF quantization (default: Q4_K_M)`,` --persist[=PATH] Persist pulled remote model into brsh filesystem (default: /var/cache/wllama/)`,` -o, --output=PATH Save pulled remote model to a specific path in the brsh filesystem`,` -q, --no-progress Suppress live download progress bar when pulling remote models`,` --mmproj=PATH_OR_URL Multimodal vision/audio projector GGUF file or URL`,` -p, --prompt=TEXT Prompt text to generate completion for`,` -f, --file=FILENAME Read prompt from a file in the brsh filesystem`,` -s, --system=TEXT System prompt for chat completion`,` -n, --max-tokens=N Maximum tokens to generate (default: 256)`,` --temp, --temperature=F Sampling temperature (default: 0.7)`,` --top-k=N Top-K sampling parameter`,` --top-p=F Top-P nucleus sampling parameter`,` -c, --ctx-size=N Context window size n_ctx (default: 4096)`,` -ngl, --n-gpu-layers=N Number of layers offloaded to WebGPU (default: all)`,` --no-gpu, --cpu Disable WebGPU and run on WASM SIMD CPU only`,` --raw, --completion Use raw text completion instead of chat completion`,` --stream Stream tokens as they are generated (default: enabled)`,` --no-stream Disable token streaming and wait for full response`,` --embed, --embeddings Generate embeddings instead of text completion`,` --json Output raw JSON response`,` -h, --help Show this help message and exit`,` -V, --version Show WebAssembly binary version and exit`,``,`Aliases: wllama, llama, llama-cli`,`Source: ${e.homepage||e.cdnUrl}`].forEach(e=>{this.stdOut=e});return}if(this._parsed.version){this.stdOut=`${i} (${e.name} ${e.version} wasm)`;return}if(this._parsed.subcommand&&![`run`,`embed`].includes(this._parsed.subcommand)){await this._handleSubcommand();return}try{await this._initWllama(!0);let e=``;if(this._parsed.file){let t=this.fs.getFileByPath(this._parsed.file);if(t==null){this.stdErr=`${i}: error: ${this._parsed.file}: No such file or directory`,this.exitCode=1;return}e=String(t)}else this._parsed.prompt===null?this.stdin!==void 0&&this.stdin!==null&&String(this.stdin).trim().length>0&&(e=String(this.stdin).trim()):e=this._parsed.prompt;if(this._parsed.embeddings||this._parsed.subcommand===`embed`){let t=this._createTracker();t.start(`Computing embeddings`,{hint:`evaluating prompt`});let n;try{n=await this._wllama.createEmbedding({input:e})}finally{t.clear(),this._clearStatus()}if(this._parsed.jsonOutput)this.stdOut=JSON.stringify(n);else{let e=n?.data?.[0]?.embedding||n?.embedding||[];this.stdOut=JSON.stringify(e)}return}if(this._parsed.rawCompletion){let t=!!(this._parsed.stream&&!this._parsed.jsonOutput),n={prompt:e,max_tokens:this._parsed.maxTokens,temperature:this._parsed.temperature,stream:t};this._parsed.topK!==void 0&&(n.top_k=this._parsed.topK),this._parsed.topP!==void 0&&(n.top_p=this._parsed.topP);let r=this._createTracker();r.start(`Running inference`,{hint:`evaluating prompt & preparing KV cache`});let i=!1;try{let e=await this._wllama.createCompletion(n),t=``;if(e&&typeof e[Symbol.asyncIterator]==`function`){for await(let n of e){let e=n?.choices?.[0]?.text??n?.choices?.[0]?.delta?.content??``;e&&(i||(i=!0,this._streamedStdout=!0,r.clear()),t+=e,this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(e),this.emit(`token`,e))}r.clear(),i||this._clearStatus(),i&&t.length>0&&!t.endsWith(`
|
|
14
14
|
`)&&this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(`\r
|
|
15
|
-
`)}else r.clear(),this._clearStatus(),t=this._parsed.jsonOutput?JSON.stringify(e):y(e);t.split(/\r?\n/).forEach(e=>{this.stdOut=e});return}finally{r.clear(),this._clearStatus()}}let t=[];this._parsed.systemPrompt&&t.push({role:`system`,content:this._parsed.systemPrompt}),t.push({role:`user`,content:e});let n=!!(this._parsed.stream&&!this._parsed.jsonOutput),r=``;if(n){let e=!1;r=await this._runChatTurn(t,t=>{e||(e=!0,this._streamedStdout=!0),this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(t),this.emit(`token`,t)}),e&&r.length>0&&!r.endsWith(`
|
|
15
|
+
`)}else r.clear(),this._clearStatus(),t=this._parsed.jsonOutput?JSON.stringify(e):y(e);t.split(/\r?\n/).forEach(e=>{this.stdOut=e});return}finally{r.clear(),i||this._clearStatus()}}let t=[];this._parsed.systemPrompt&&t.push({role:`system`,content:this._parsed.systemPrompt}),t.push({role:`user`,content:e});let n=!!(this._parsed.stream&&!this._parsed.jsonOutput),r=``;if(n){let e=!1;r=await this._runChatTurn(t,t=>{e||(e=!0,this._streamedStdout=!0),this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(t),this.emit(`token`,t)}),e&&r.length>0&&!r.endsWith(`
|
|
16
16
|
`)&&this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(`\r
|
|
17
|
-
`)}else r=await this._runChatTurn(t);r.split(/\r?\n/).forEach(e=>{this.stdOut=e})}catch(e){this.stdErr=`${i}: ${e.message||e}`,this.exitCode=1}}}return a}function x(e={},t={}){return[{bin:(e.bin||`wllama`).toLowerCase(),Cmd:b(e,t,`wllama`)},{bin:`llama`,Cmd:b(e,t,`llama`)},{bin:`llama-cli`,Cmd:b(e,t,`llama-cli`)}]}t.exports=b,t.exports.createWllamaCommand=b,t.exports.buildEntries=x,t.exports.WllamaCommand=b({name:`wllama`,version:`3.8.1`}),t.exports.wllamaInstances=u,t.exports.getDefaultPersistPath=d,t.exports.DEFAULT_PERSIST_DIR=l,t.exports.resolveModelSpec=h,t.exports.formatDownloadProgress=p,t.exports.DEFAULT_MODEL_URL=s,t.exports.MODEL_ALIASES=o}));return t(((e,t)=>{y();var n=te(),r=U(),i=X(),a=G(),{DEFAULT_REGISTRY:o,resolvePackageName:s}=ae(),c=Z()
|
|
17
|
+
`)}else r=await this._runChatTurn(t);r.split(/\r?\n/).forEach(e=>{this.stdOut=e})}catch(e){this.stdErr=`${i}: ${e.message||e}`,this.exitCode=1}}}return a}function x(e={},t={}){return[{bin:(e.bin||`wllama`).toLowerCase(),Cmd:b(e,t,`wllama`)},{bin:`llama`,Cmd:b(e,t,`llama`)},{bin:`llama-cli`,Cmd:b(e,t,`llama-cli`)}]}t.exports=b,t.exports.createWllamaCommand=b,t.exports.buildEntries=x,t.exports.WllamaCommand=b({name:`wllama`,version:`3.8.1`}),t.exports.wllamaInstances=u,t.exports.getDefaultPersistPath=d,t.exports.DEFAULT_PERSIST_DIR=l,t.exports.resolveModelSpec=h,t.exports.formatDownloadProgress=p,t.exports.DEFAULT_MODEL_URL=s,t.exports.MODEL_ALIASES=o}));return t(((e,t)=>{y();var n=te(),r=U(),i=X(),a=G(),{DEFAULT_REGISTRY:o,resolvePackageName:s}=ae(),c=Z();typeof globalThis<`u`&&(globalThis.__brshWllamaAdapter=c);var{writeBytesToFs:l,createGenericWasmCommand:u}=i,{createReplWasmCommand:d}=a,f=`/var/cache/wbt`;function p(e,t,n={}){class r extends i{static get name(){return e}get name(){return e}get requiresFilesystem(){return!0}get interactive(){return(this.arguments||[]).some(e=>e===`--help`||e===`-h`||e===`--version`||e===`-V`||e===`-v`)?!1:this._isInteractive===void 0?!!(n.interactive||e===`nano`||e===`pico`||e===`vim`||e===`vi`):!!this._isInteractive}get captureInput(){return this.interactive}constructor(e,r){super(t,e,r),this.script=t,this.arguments=e||[],this.context=r||null,r&&r.fs&&!this.fs&&(this.fs=r.fs),this._pkgMeta=n}}return r}var m=class extends r{static get name(){return`wbt`}get name(){return`wbt`}get requiresFilesystem(){return!0}get _fs(){return this.fs||this.context&&this.context.fs||null}get _pathDir(){return this.context&&typeof this.context.getVar==`function`&&this.context.getVar(`PATH`)||`/bin`}_withWritableParent(e,t){let n=this._fs;if(!n)return;let r=(typeof n.absolutePath==`function`?n.absolutePath(e):e).split(`/`);r.pop();let i=r.join(`/`)||`/`,a=typeof n.getMode==`function`?n.getMode(i):null,o=a!==null&&(a&128)==0;if(o)try{n.setMode(i,a|128)}catch{}try{return t(n)}finally{if(o)try{n.setMode(i,a)}catch{}}}_writeFileSafe(e,t){this._withWritableParent(e,n=>{if(n.exists(e))try{n.setMode(e,493)}catch{}n.setFileByPath(e,t,!0)})}_writeBytesSafe(e,t,n=`application/wasm`){this._withWritableParent(e,r=>{if(r.exists(e))try{r.setMode(e,493)}catch{}l(r,e,t,n)})}get interactive(){if(this._activeSubCommand&&this._activeSubCommand.interactive!==void 0)return!!this._activeSubCommand.interactive;if(this.arguments&&this.arguments[0]===`run`&&this.arguments[1]){let e=s(this.arguments[1]),t=this._getRegistry()[e];if(t&&t.interactive)return!this.arguments.slice(2).some(e=>e===`--help`||e===`-h`||e===`--version`||e===`-V`||e===`-v`)}return!1}get captureInput(){return this._activeSubCommand&&this._activeSubCommand.captureInput!==void 0?!!this._activeSubCommand.captureInput:this.interactive}get isRaw(){return this._activeSubCommand?!!(this._activeSubCommand.isRaw||this._activeSubCommand.stdinStream&&this._activeSubCommand.stdinStream.isRaw):!!(this.stdinStream&&this.stdinStream.isRaw)}get _inAltScreen(){return!!(this.__inAltScreen||this._activeSubCommand&&this._activeSubCommand._inAltScreen)}set _inAltScreen(e){this.__inAltScreen=!!e}kill(e=`SIGINT`){this._activeSubCommand&&typeof this._activeSubCommand.kill==`function`&&this._activeSubCommand.kill(e),super.kill(e)}onInput(e){this._activeSubCommand&&typeof this._activeSubCommand.onInput==`function`&&this._activeSubCommand.onInput(e)}static get _config(){return this.__wbtConfig||{}}static get _adapters(){return this.__adapters||=new Map,this.__adapters}static registerAdapter(e,t){this._adapters.set(e,t)}static configure(e={}){class t extends m{static get name(){return`wbt`}}return t.__wbtConfig=Object.assign({},this._config,e),t}static restoreInstalled(){}_getRegistry(){let e=this.constructor._config||{},t=Object.assign({},o,e.registry||{});try{let e=this._fs,n=e?e.getFileByPath(`${f}/remote-registry.json`):null;if(typeof n==`string`&&n.trim()){let e=JSON.parse(n);Object.assign(t,e)}}catch{}return t}_getInstalledPackages(){let e={},t=this._fs;if(!t)return e;let n=t.getFileByPath(`/usr/lib`);if(!n||typeof n!=`object`)return e;let r=this._getRegistry();for(let i of Object.keys(n)){if(i.startsWith(`.`))continue;let n=i.toLowerCase(),a=r[n]||Object.values(r).find(e=>e.name===n||e.bin===n),o=t.getFileByPath(`/usr/lib/${i}`)||{},s=(typeof o==`object`?Object.keys(o):[]).find(e=>e.endsWith(`.wasm`)||e.endsWith(`.wat`)),c=s?`/usr/lib/${i}/${s}`:t.exists(`/usr/lib/${i}/${n}.wasm`)?`/usr/lib/${i}/${n}.wasm`:null,l=a&&a.bin||n,u=[l];a&&a.aliases&&u.push(...a.aliases),a&&a.scripts&&u.push(...Object.keys(a.scripts)),e[n]=Object.assign({name:n,bin:l,bins:u,version:a&&a.version||`custom`,description:a&&a.description||`Installed package ${n}`,type:a&&a.type||(c?`custom-wasm`:`generic-runtime`),wasmPath:c},a||{}),c&&(e[n].wasmPath=c)}return e}_generateJsCommandSource(e,t){if(e.adapter===`wllama`||e.name===`wllama`){let r=typeof __dirname<`u`?n.resolve(__dirname,`packages/wllama.js`):null;return`'use strict';
|
|
18
18
|
let wllamaModule;
|
|
19
|
-
|
|
20
|
-
wllamaModule = require(${JSON.stringify(r)});\n} catch (_) {\n try {\n wllamaModule = require('brsh/wbt/packages/wllama');\n } catch (e) {\n wllamaModule = require('./wllama');\n }\n}\nmodule.exports = wllamaModule.createWllamaCommand(${JSON.stringify(e)}, {}, ${JSON.stringify(t)});\n`}let r=JSON.stringify(e,null,2);return e.repl?`'use strict';\nconst pkgMeta = ${r};\nconst _Repl = typeof ReplCommand !== 'undefined' ? ReplCommand : (typeof require !== 'undefined' ? require('brsh/ReplCommand') : globalThis.ReplCommand);\nmodule.exports = _Repl.createReplWasmCommand(pkgMeta, {}, ${JSON.stringify(t)});\n`:`'use strict';\nconst pkgMeta = ${r};\nconst _Wasm = typeof WasmCommand !== 'undefined' ? WasmCommand : (typeof require !== 'undefined' ? require('brsh/WasmCommand') : globalThis.WasmCommand);\nmodule.exports = _Wasm.createGenericWasmCommand(pkgMeta, {}, ${JSON.stringify(t)});\n`}_buildCommandsForPackage(e){let t=this.constructor._config||{};if((e.type===`custom-wasm`||e.type===`wasm`)&&e.wasmPath){let t=(e.bin||e.name).toLowerCase();return[{bin:t,Cmd:p(t,e.wasmPath,e)}]}let n=e.adapter||e.name,r=this.constructor._adapters&&this.constructor._adapters.get(n);if(!r&&n===`wllama`&&(r=c.buildEntries||c.createAdapter||c),!r&&e.adapter)try{let t=require(`./packages/${e.adapter}`);r=t.buildEntries||t.createAdapter||t}catch{}if(typeof r==`function`){let n=r(e,t);if(Array.isArray(n))return n;if(n)return[{bin:(e.bin||e.name).toLowerCase(),Cmd:n}]}let i=e.repl?d:u,a=(e.bin||e.name.split(`/`).pop()).toLowerCase(),o=[{bin:a,Cmd:i(e,t,a)}];for(let n of e.aliases||[]){let r=n.toLowerCase();r!==a&&o.push({bin:r,Cmd:i(e,t,r)})}return o}_registerPackageIntoContext(e){let t=this._fs,n=this.constructor._config||{},r=this._pathDir,i=(e.name||``).split(`/`).pop().toLowerCase(),a=(e.bin||i).toLowerCase(),o=`/usr/lib/${i}`,s=this._buildCommandsForPackage(e),c=[],l=e.adapter||e.name,u=!!(n.moduleLoader||n.fetch||l===`wllama`||this.constructor._adapters&&this.constructor._adapters.has(l)),d=e.wasmPath||(t.exists(`${o}/${a}.wasm`)?`${o}/${a}.wasm`:null),f=`${o}/package.json`,p={name:e.name,version:e.version||`1.0.0`,bin:a,aliases:e.aliases||[],description:e.description||``,...e.interactive?{interactive:!0}:{}};this._writeFileSafe(f,JSON.stringify(p,null,2));for(let{bin:n,Cmd:i}of s){let a=n.toLowerCase(),s;if(d&&(!e.type||e.type===`custom-wasm`||e.type===`wasm`))s=d;else{s=`${o}/${a}.js`;let n=this._generateJsCommandSource(e,a);typeof i==`function`&&(i.__source=n),!t.isRealFilesystem&&typeof i==`function`&&u?this._writeFileSafe(s,i):this._writeFileSafe(s,n);try{t.setMode(s,493)}catch{}}this._createBinSymlink(r,a,s),c.push(a)}for(let t of e.aliases||[]){let n=t.toLowerCase();if(!c.includes(n)&&s.length>0){let t=d&&(!e.type||e.type===`custom-wasm`||e.type===`wasm`)?d:`${o}/${a}.js`;this._createBinSymlink(r,n,t),c.push(n)}}let m=e.scriptPaths||{};for(let[e,n]of Object.entries(m)){let i=e.toLowerCase();!c.includes(i)&&t.exists(n)&&(this._createBinSymlink(r,i,n),c.push(i))}if(e.scripts&&typeof e.scripts==`object`)for(let n of Object.keys(e.scripts)){let e=n.toLowerCase(),i=`${o}/${e}`;!c.includes(e)&&t.exists(i)&&(this._createBinSymlink(r,e,i),c.push(e))}return c}_createBinSymlink(e,t,n){let r=this._fs,i=`${e}/${t.toLowerCase()}`;this._removeBin(e,t);try{r.createSymlink(n,i),r.setMode(i,493)}catch{this._writeFileSafe(i,r.getFileByPath(n));try{r.setMode(i,493)}catch{}}}_removeBin(e,t){let n=`${e}/${t.toLowerCase()}`;this._withWritableParent(n,e=>{try{e.deleteFileByPath(n)}catch{}})}async run(){let e=[...this.arguments||[]],t=e.length>=2&&e[0].toLowerCase()===`run`;if(e.length===0||!t&&(e.includes(`--help`)||e.includes(`-h`)||e[0]===`help`)){this._printHelp();return}if(!t&&(e.includes(`--version`)||e.includes(`-v`))){this.stdOut=`wbt 1.1.0 (Web Binary Tool for brsh)`;return}let n=e.shift().toLowerCase();switch(n){case`install`:case`add`:await this._handleInstall(e);break;case`remove`:case`uninstall`:case`purge`:await this._handleRemove(e);break;case`list`:this._handleList(e);break;case`search`:this._handleSearch(e);break;case`show`:case`info`:this._handleShow(e);break;case`update`:await this._handleUpdate(e);break;case`run`:await this._handleRun(e);break;default:this.stdErr=`E: Invalid operation ${n}`,this.stdErr=`Run 'wbt --help' for usage information.`,this.exitCode=100}}async _handleInstall(e){let t=[],n=[],r=null;for(let i=0;i<e.length;i++){let a=e[i];a===`--as`&&i+1<e.length?r=e[++i]:a.startsWith(`--as=`)?r=a.slice(5):a.startsWith(`-`)?t.push(a):n.push(a)}let i=t.includes(`-q`)||t.includes(`--quiet`),a=t.includes(`--generic`)||t.includes(`--npm`);if(n.length===0){this.stdErr=`E: Specify at least one package to install`,this.exitCode=1;return}let o=e=>/^(https?:\/\/|data:)/i.test(e),c=e=>e.startsWith(`data:`)?`custom-wasm`:e.split(`/`).pop().split(`?`)[0].replace(/\.(wasm|wat|mjs|js)$/i,``)||`custom-wasm`,l=this._getRegistry(),u=this._getInstalledPackages(),d=!1;for(let e=0;e<n.length;e++){let f=n[e];if(!o(f)&&e+1<n.length&&o(n[e+1])){let t=n[++e],a=(r||f).toLowerCase();if(await this._installCustomUrl(a,t,i),this.exitCode)return;continue}if(o(f)){let e=f,t=(r||c(e)).toLowerCase();if(await this._installCustomUrl(t,e,i),this.exitCode)return;continue}!i&&!d&&(this.stdOut=`Reading package lists... Done`,this.stdOut=`Building dependency tree... Done`,this.flush(),d=!0);let p=l[s(f)];if(!p&&(a||f.startsWith(`npm:`)||f.startsWith(`esm:`))){let e=f.replace(/^(npm|esm):/i,``),t=(r||e.replace(/^@[^/]+\//,``).split(`@`)[0]).toLowerCase();p={name:t,bin:t,version:`latest`,description:`Dynamic WASM/ESM package from https://esm.sh/${e}`,cdnUrl:`https://esm.sh/${e}`,type:`generic-runtime`}}if(!p){this.stdErr=`E: Unable to locate package ${f}`,this.exitCode=100;return}if(u[p.name]&&!t.includes(`--reinstall`)&&!t.includes(`-f`)){i||(this.stdOut=`${p.name} is already the newest version (${p.version}).`);continue}i||(this.stdOut=`Get:1 ${p.wasmUrl||p.cdnUrl} ${p.name} ${p.version} [${p.size||`WASM`}]`,this.flush());let m=null,h=null;try{m=await this._pullPackageWasm(p,i,t.includes(`--preload`)),h=await this._pullPackageScripts(p,i)}catch(e){this.stdErr=`E: Failed to fetch ${p.name}: ${e.message||e}`,this.exitCode=1;return}i||(this.stdOut=`Unpacking ${p.name} (${p.version})${m?` -> ${m}`:``} ...`,this.flush());let g=Object.assign({},p,m?{wasmPath:m}:{},h?{scriptPaths:h}:{}),_=this._registerPackageIntoContext(g);i||(this.stdOut=`Setting up ${p.name} (${p.version}) -> /bin/${_.join(`, /bin/`)} ...`)}}async _pullPackageScripts(e,t=!1,n=null){if(!e||!e.scripts||typeof e.scripts!=`object`)return null;let r=(this.constructor._config||{}).fetch||(typeof fetch==`function`?fetch:null);if(!r)return null;let i=(e.name||``).split(`/`).pop().toLowerCase(),a=n||`/usr/lib/${i}`,o={};for(let[t,n]of Object.entries(e.scripts)){if(!n)continue;let e=t.toLowerCase(),i=await r(n);if(!i||!i.ok)throw Error(`HTTP ${i?i.status:`error`} fetching script ${n}`);let s;s=typeof i.text==`function`?await i.text():typeof i.arrayBuffer==`function`?new TextDecoder().decode(new Uint8Array(await i.arrayBuffer())):``;let c=`${a}/${e}`;this._writeFileSafe(c,s);try{this._fs.setMode(c,493)}catch{}o[e]=c}return Object.keys(o).length>0?o:null}async _readResponseBytes(e,t,n=!1){let r=e.headers&&typeof e.headers.get==`function`?Number(e.headers.get(`content-length`)||0):0;if(e.body&&typeof e.body.getReader==`function`){let i=e.body.getReader(),a=[],o=0;for(;;){let{done:e,value:s}=await i.read();if(e)break;if(a.push(s),o+=s.byteLength,!n&&r>0){let e=Math.min(100,Math.round(o/r*100)),n=Math.round(e/100*20),i=`█`.repeat(n)+`░`.repeat(Math.max(0,20-n));this.stdOut=`\rDownloading ${t}: [${i}] ${String(e).padStart(3)}%`,this.flush()}}let s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.byteLength;return s}if(typeof e.arrayBuffer==`function`){let t=await e.arrayBuffer();return new Uint8Array(t)}return null}_extractEmbeddedWasmFromText(e){if(!e||typeof e!=`string`)return null;let t=e.match(/AGFzbQE[A-Za-z0-9+/=]{32,}/);if(!t)return null;let n=t[0];try{if(v!==void 0)return new Uint8Array(v.from(n,`base64`));let e=atob(n),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}catch{return null}}_extractNpmSpec(e){for(let t of[e.cdnUrl,e.wasmUrl]){if(!t)continue;let e=t.match(/^https?:\/\/cdn\.jsdelivr\.net\/npm\/((?:@[^/]+\/)?[^/]+)(?:\/|$)/i);if(e)return e[1];let n=t.match(/^https?:\/\/esm\.sh\/((?:@[^/]+\/)?[^/?#]+)(?:\/|\?|$)/i);if(n)return n[1];let r=t.match(/^https?:\/\/unpkg\.com\/((?:@[^/]+\/)?[^/]+)(?:\/|$)/i);if(r)return r[1]}return null}async _discoverWasmFromJsDelivr(e,t,n,r=!1){if(!e||!n)return null;let i=e=>e.replace(/(^@[^/]+\/[^@]+|^[^@]+)@.*$/,`$1`),a=e,o=null;try{let e=await n(`https://data.jsdelivr.com/v1/package/npm/${a}/flat`);if((!e||!e.ok)&&a.includes(`@`)){let t=i(a),r=await n(`https://data.jsdelivr.com/v1/package/npm/${t}`);if(r&&r.ok&&typeof r.json==`function`){let i=await r.json(),o=i&&i.tags&&i.tags.latest;o&&(a=`${t}@${o}`,e=await n(`https://data.jsdelivr.com/v1/package/npm/${a}/flat`))}}e&&e.ok&&typeof e.json==`function`&&(o=await e.json())}catch{return null}let s=o&&Array.isArray(o.files)?o.files:[],c=s.filter(e=>e&&typeof e.name==`string`&&/\.wasm$/i.test(e.name));if(c.length>0){c.sort((e,t)=>e.name.length-t.name.length);let e=c[0],i=`https://cdn.jsdelivr.net/npm/${a}${e.name}`;try{let e=await n(i);if(e&&e.ok){let n=await this._readResponseBytes(e,`${t}.wasm`,r);if(n&&n.byteLength>0)return{bytes:n,url:i}}}catch{}}let l=s.filter(e=>e&&typeof e.name==`string`&&/\.(?:mjs|cjs|js)$/i.test(e.name)&&!/\.min\.js$/i.test(e.name));for(let e of l.slice(0,4)){let t=`https://cdn.jsdelivr.net/npm/${a}${e.name}`;try{let e=await n(t);if(e&&e.ok&&typeof e.text==`function`){let n=await e.text(),r=this._extractEmbeddedWasmFromText(n);if(r)return{bytes:r,url:t}}}catch{}}return null}async _pullPackageWasm(e,t=!1,n=!1,r=null){let i=this.constructor._config||{},a=i.fetch||(typeof fetch==`function`?fetch:null),{loadModule:o}=oe(),s=null,c=null,l=e.wasmUrl||(/\.(wasm|wat)(\?.*)?$/i.test(e.cdnUrl||``)?e.cdnUrl:null);if(l&&a)try{let n=await a(l);n&&n.ok?s=await this._readResponseBytes(n,`${e.name}.wasm`,t):c=Error(`HTTP ${n?n.status:`error`} fetching ${l}`)}catch(e){c=e}if(!s&&a&&!i.moduleLoader){let n=this._extractNpmSpec(e);if(n){let r=await this._discoverWasmFromJsDelivr(n,e.name,a,t);r&&r.bytes&&(s=r.bytes,e.wasmUrl=r.url,c=null)}}let u=null,d=null;if(e.cdnUrl||i.moduleLoader){let t=typeof globalThis.fetch==`function`?globalThis.fetch:null;t&&s&&s.byteLength>0&&typeof Response<`u`&&(globalThis.fetch=async(e,n)=>{let r=typeof e==`string`?e:e&&e.url?e.url:``;return r&&!/^https?:\/\//i.test(r)&&/\.wasm(\?.*)?$/i.test(r)?new Response(s,{status:200,headers:{"Content-Type":`application/wasm`}}):t(e,n)});try{u=await o(e.name,e.cdnUrl,i.moduleLoader)}catch(e){if(d=e,n)throw e}finally{t&&(globalThis.fetch=t)}}if(!s&&u){let e=u.default===void 0?u:u.default;e instanceof Uint8Array?s=e:e instanceof ArrayBuffer?s=new Uint8Array(e):e&&(e.wasmBytes instanceof Uint8Array||e.wasm instanceof Uint8Array||e.wasmBinary instanceof Uint8Array)&&(s=e.wasmBytes||e.wasm||e.wasmBinary)}if(!s&&e.cdnUrl&&a&&!i.moduleLoader)try{let t=await a(e.cdnUrl);if(t&&t.ok&&typeof t.text==`function`){let e=await t.text();s=this._extractEmbeddedWasmFromText(e)}}catch{}if(!s&&typeof i.moduleLoader==`function`&&(s=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,7,10,1,6,95,115,116,97,114,116,0,0,10,4,1,2,0,11])),!s&&!u&&(c||d)&&!i.moduleLoader)throw c||d;if(s){let t=(e.name||``).split(`/`).pop().toLowerCase(),n=(e.bin||t).toLowerCase(),i=`${r||`/usr/lib/${t}`}/${n}.wasm`;this._writeBytesSafe(i,s,`application/wasm`);try{this._fs.setMode(i,493)}catch{}return i}return null}async _installCustomUrl(e,t,n=!1){if(!/\.(wasm|wat)(\?.*)?$/i.test(t)&&(/^https?:\/\/esm\.sh\//i.test(t)||/\.(mjs|js)(\?.*)?$/i.test(t))){let r={name:e,bin:e,bins:[e],version:`custom-esm`,description:`Custom ESM/WASM module from ${t}`,cdnUrl:t,type:`generic-runtime`,installedAt:new Date().toISOString()},i=await this._pullPackageWasm(r,n,!1);i&&(r.wasmPath=i),this._registerPackageIntoContext(r),n||(this.stdOut=`Setting up ${e} (generic runtime) -> /bin/${e} ...`);return}let r=(this.constructor._config||{}).fetch||(typeof fetch==`function`?fetch:null);if(!r){this.stdErr=`E: fetch is not available in this environment`,this.exitCode=1;return}n||(this.stdOut=`Get:1 ${t} ${e}`,this.flush());let i=t.replace(/^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/(?:blob|raw)\/([^/]+)\/(.+)$/i,`https://raw.githubusercontent.com/$1/$2/$3/$4`),a;try{a=await r(i)}catch(e){if(/^https?:\/\/github\.com\/[^/]+\/[^/]+\/releases\/download\//i.test(i))try{a=await r(`https://corsproxy.io/?${encodeURIComponent(i)}`)}catch{this.stdErr=`E: Failed to fetch ${t} (GitHub Releases blocks browser CORS requests; host the .wasm on jsDelivr/unpkg/raw.githubusercontent.com): ${e.message||e}`,this.exitCode=1;return}else{this.stdErr=`E: Failed to fetch ${t}: ${e.message||e}`,this.exitCode=1;return}}if(!a||!a.ok){this.stdErr=`E: HTTP ${a?a.status:`error`} fetching ${t}`,this.exitCode=1;return}let o=t.endsWith(`.wat`),s=o?`.wat`:`.wasm`,c=`${`/usr/lib/${e}`}/${e}${s}`;if(o){let e=await a.text();this._writeFileSafe(c,e)}else{let e=await a.arrayBuffer();this._writeBytesSafe(c,new Uint8Array(e),`application/wasm`)}try{this._fs.setMode(c,493)}catch{}let l={name:e,bin:e,bins:[e],version:`custom`,description:`Custom WebAssembly binary from ${t}`,cdnUrl:t,type:`custom-wasm`,wasmPath:c,installedAt:new Date().toISOString()};this._registerPackageIntoContext(l),n||(this.stdOut=`Setting up ${e} (custom) -> /bin/${e} ...`)}async _handleRemove(e){let t=e.filter(e=>!e.startsWith(`-`));if(t.length===0){this.stdErr=`E: Specify at least one package to remove`,this.exitCode=1;return}let n=this._getInstalledPackages(),r=this._getRegistry(),i=this._pathDir;for(let e of t){let t=s(e),a=n[t]||n[e.toLowerCase()];if(!a){this.stdErr=`E: Package '${e}' is not installed, so not removed`,this.exitCode=1;return}let o=r[t]||{},c=new Set([a.bin||a.name,...a.aliases||[],...o.aliases||[],e.toLowerCase(),t]);if(a.scripts)for(let e of Object.keys(a.scripts))c.add(e);for(let e of c)this._removeBin(i,e);let l=`/usr/lib/${t}`;try{this._fs.deleteFileByPath(l)}catch{}this.stdOut=`Removing ${a.name} (${a.version}) ...`}}_handleList(e){let t=e.includes(`--installed`)||e.includes(`-i`),n=this._getRegistry(),r=this._getInstalledPackages();this.stdOut=`Listing...`;let i=t?Object.keys(r).sort():Array.from(new Set([...Object.keys(n),...Object.keys(r)])).sort();for(let e of i){let t=n[e],i=r[e],a=i||t;if(!a)continue;let o=i?`[installed]`:`[available]`,s=a.bin&&a.bin!==a.name?` (bin: ${a.bin})`:``;this.stdOut=`${a.name}/wasm ${a.version} wasm ${o}${s} - ${a.description||``}`}}_handleSearch(e){let t=e.filter(e=>!e.startsWith(`-`)).join(` `).toLowerCase(),n=this._getRegistry(),r=this._getInstalledPackages();this.stdOut=`Sorting... Done`,this.stdOut=`Full Text Search... Done`;let i=Object.values(n).filter(e=>t?e.name.toLowerCase().includes(t)||e.bin&&e.bin.toLowerCase().includes(t)||e.aliases&&e.aliases.some(e=>e.toLowerCase().includes(t))||e.scripts&&Object.keys(e.scripts).some(e=>e.toLowerCase().includes(t))||e.description&&e.description.toLowerCase().includes(t)||e.details&&e.details.toLowerCase().includes(t):!0);for(let e of i){let t=r[e.name]?` [installed]`:``;this.stdOut=`${e.name}/wasm ${e.version} wasm${t}`,this.stdOut=` ${e.description}`}}_handleShow(e){let t=e.find(e=>!e.startsWith(`-`));if(!t){this.stdErr=`E: No packages found — specify a package name`,this.exitCode=1;return}let n=s(t),r=this._getRegistry(),i=this._getInstalledPackages(),a=i[n]||r[n];if(!a){this.stdErr=`E: No packages found matching ${t}`,this.exitCode=100;return}let o=Object.assign({},r[n]||{},a),c=!!i[o.name];this.stdOut=`Package: ${o.name}`,this.stdOut=`Version: ${o.version}`,this.stdOut=`State: ${c?`installed`:`not installed`}`,this.stdOut=`Binary: ${o.bin||o.name}`,o.aliases&&o.aliases.length>0&&(this.stdOut=`Aliases: ${o.aliases.join(`, `)}`),o.scripts&&Object.keys(o.scripts).length>0&&(this.stdOut=`Scripts: ${Object.keys(o.scripts).join(`, `)}`),o.size&&(this.stdOut=`Download-Size: ${o.size}`),o.cdnUrl&&(this.stdOut=`APT-Sources: ${o.cdnUrl}`),o.wasmUrl&&(this.stdOut=`WASM-URL: ${o.wasmUrl}`),o.wasmPath&&(this.stdOut=`WASM-File: ${o.wasmPath}`),o.homepage&&(this.stdOut=`Homepage: ${o.homepage}`),this.stdOut=`Description: ${o.description||``}`,o.details&&(this.stdOut=` ${o.details}`)}async _handleUpdate(){let e=this.constructor._config||{},t=e.sources||[],n=e.fetch||(typeof fetch==`function`?fetch:null),r={},i=1;this.stdOut=`Hit:1 https://registry.brsh.dev/wbt wasm InRelease`;for(let e of t)if(i++,n)try{let t=await n(e);if(t&&t.ok){let n=await t.json();Object.assign(r,n),this.stdOut=`Get:${i} ${e} Packages`}}catch(t){this.stdErr=`W: Failed to fetch ${e}: ${t.message||t}`}Object.keys(r).length>0&&this._writeFileSafe(`${f}/remote-registry.json`,JSON.stringify(r,null,2));let a=this._getRegistry();this.stdOut=`Reading package lists... Done (${Object.keys(a).length} packages available)`}async _handleRun(e){if(e.length===0){this.stdErr=`E: Specify a package to run (e.g. wbt run sqlite3 --version)`,this.exitCode=1;return}let t=e.shift(),n=s(t),r=this._getRegistry(),i=this._getInstalledPackages(),a=!!i[n],o=i[n]||r[n];if(!o&&(t.startsWith(`npm:`)||t.startsWith(`esm:`))){let e=t.replace(/^(npm|esm):/i,``),n=e.replace(/^@[^/]+\//,``).split(`@`)[0].toLowerCase();o={name:n,bin:n,version:`latest`,cdnUrl:`https://esm.sh/${e}`,type:`generic-runtime`}}if(!o){this.stdErr=`E: Unable to locate package ${t}`,this.exitCode=100;return}let c=this._fs,l=null,u=this._pathDir;try{if(a||(l=`/tmp/.wbt-run-${n}-${Date.now()}`),(o.type===`custom-wasm`||o.type===`wasm`)&&!o.wasmPath)try{let e=await this._pullPackageWasm(o,!0,!1,l);e&&(o=Object.assign({},o,{wasmPath:e}))}catch(e){this.stdErr=`E: Failed to fetch ${o.name}: ${e.message||e}`,this.exitCode=1;return}let r=t.toLowerCase(),i;if(o.scripts&&o.scripts[r]){let t=o.scriptPaths&&o.scriptPaths[r]||`/usr/lib/${n}/${r}`;if(!c.exists(t))try{let e=await this._pullPackageScripts(o,!0,l);e&&e[r]&&(t=e[r])}catch(e){this.stdErr=`E: Failed to fetch script ${r}: ${e.message||e}`,this.exitCode=1;return}let a=e=>this.context&&typeof this.context.getVar==`function`?this.context.getVar(e):``,s=l?`${l}:${u}`:u,d=this.context&&this.context.vars?Object.assign({},this.context.vars):{HOME:a(`HOME`)||`/root`,HOST:a(`HOST`)||`browser`,COLUMNS:String(this.stdout&&this.stdout.columns||a(`COLUMNS`)||80),LINES:String(this.stdout&&this.stdout.rows||a(`LINES`)||24)};d.PATH=s;let f={vars:d,aliases:this.context&&this.context.aliases||{},getVar:e=>e===`PATH`?s:d[e]||a(e),getAlias:e=>this.context&&typeof this.context.getAlias==`function`?this.context.getAlias(e):null,getCommand:e=>this.context&&typeof this.context.getCommand==`function`?this.context.getCommand(e):null};i=new(ne())(c.getFileByPath(t),e,f),i.fs=c}else{let t=this._buildCommandsForPackage(o),n=(t.find(e=>e.bin===r)||t[0]).Cmd;i=new n(e,this.context),i.requiresFilesystem&&(i.fs=typeof c.sandbox==`function`?c.sandbox():c)}this._activeSubCommand=i,this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`data`,this._onStdinStreamData),i.stdinStream=this.stdinStream,i.stdin=this.stdin&&!this.stdin.isTTY?this.stdin:this.stdinStream,i._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,i._onStdinStreamData),this.stdout&&i.stdout&&(this.stdout.columns&&(i.stdout.columns=this.stdout.columns),this.stdout.rows&&(i.stdout.rows=this.stdout.rows)),this.stderr&&i.stderr&&(this.stderr.columns&&(i.stderr.columns=this.stderr.columns),this.stderr.rows&&(i.stderr.rows=this.stderr.rows));let s=()=>{!this.stdout||!i.stdout||(typeof i.stdout.resize==`function`?i.stdout.resize(this.stdout.columns,this.stdout.rows):(i.stdout.columns=this.stdout.columns,i.stdout.rows=this.stdout.rows))};this.stdout&&typeof this.stdout.on==`function`&&this.stdout.on(`resize`,s);let d=e=>{this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(e)},f=e=>{this.stderr&&typeof this.stderr.write==`function`&&this.stderr.write(e)},p=e=>{let t=Array.isArray(e)?e:e&&typeof e.getStdOutput==`function`?e.getStdOutput():[];for(let e of t)e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.flush()};i.stdout&&typeof i.stdout.on==`function`&&i.stdout.on(`data`,d),i.stderr&&typeof i.stderr.on==`function`&&i.stderr.on(`data`,f),typeof i.on==`function`&&i.on(`flush`,p);let m;try{m=await i.runCommand()}finally{this._activeSubCommand=null,this.stdout&&typeof this.stdout.off==`function`&&this.stdout.off(`resize`,s),i._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`data`,i._onStdinStreamData),this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,this._onStdinStreamData),i.stdout&&typeof i.stdout.off==`function`&&i.stdout.off(`data`,d),i.stderr&&typeof i.stderr.off==`function`&&i.stderr.off(`data`,f),typeof i.removeListener==`function`&&i.removeListener(`flush`,p)}if(!i.interactive&&m)for(let e of m.getStdOutput())e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.exitCode=m?m.getExitCode():0}finally{if(l&&c)try{c.deleteFileByPath(l)}catch{}}}_printHelp(){[`wbt 1.1.0 — Web Binary Tool (WASM binary manager & runtime for brsh)`,`Usage: wbt [options] command [package ...]`,``,`Commands:`,` install <pkg> [url] Install a WASM binary from registry, npm:<pkg>, or a custom URL`,` remove <pkg> Remove an installed WASM binary`,` update Update package index and restore installed binaries`,` list [--installed] List available or installed WASM binaries`,` search <query> Search available WASM binaries by name or description`,` show <pkg> Show detailed information about a package`,` run <pkg> [args...] Run a WASM binary without permanently installing it`,``,`Curated WASM Packages:`,` sqlite3 SQLite3 compiled to WebAssembly (sqlite3, sqlite)`,` assemblyscript AssemblyScript compiler & ts-node style runtime (asc, asrun, asnode)`,` jq Command-line JSON processor (jq)`,` python3 CPython 3.12 via Pyodide (python3, python, py)`,` duckdb DuckDB analytical SQL OLAP engine (duckdb)`,` graphviz Graphviz DOT diagram compiler (dot)`,` ffmpeg FFmpeg multimedia transcoder (ffmpeg)`,` wabt WebAssembly Binary Toolkit (wat2wasm, wasm2wat)`,` quickjs Sandboxed QuickJS JavaScript engine (qjs)`,` lua Lua 5.4 WebAssembly interpreter (lua)`,` wllama WASM & WebGPU LLM inference engine (wllama, llama, llama-cli)`,` nano GNU nano 8.0 text editor with ncurses (nano, nano-wasm)`,` doom Classic Doom (1993) with 24-bit ANSI rendering (doom, freedoom)`].forEach(e=>{this.stdOut=e})}};t.exports=m,t.exports.Wbt=m,t.exports.DEFAULT_REGISTRY=o,t.exports.createGenericWasmCommand=u,t.exports.createReplWasmCommand=d}))()})();
|
|
19
|
+
if (typeof require === 'function') {
|
|
20
|
+
`+(r?` try {\n wllamaModule = require(${JSON.stringify(r)});\n } catch (_) {}\n`:``)+` if (!wllamaModule) {
|
|
21
|
+
try {
|
|
22
|
+
wllamaModule = require('brsh/wbt/packages/wllama');
|
|
23
|
+
} catch (_) {
|
|
24
|
+
try { wllamaModule = require('./wllama'); } catch (e) {}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (!wllamaModule && typeof globalThis !== 'undefined') {
|
|
29
|
+
wllamaModule = globalThis.__brshWllamaAdapter;
|
|
30
|
+
}
|
|
31
|
+
if (!wllamaModule) {
|
|
32
|
+
throw new Error('Unable to load wllama adapter module');
|
|
33
|
+
}
|
|
34
|
+
module.exports = wllamaModule.createWllamaCommand(${JSON.stringify(e)}, {}, ${JSON.stringify(t)});\n`}let r=JSON.stringify(e,null,2);return e.repl?`'use strict';\nconst pkgMeta = ${r};\nconst _Repl = typeof ReplCommand !== 'undefined' ? ReplCommand : (typeof require !== 'undefined' ? require('brsh/ReplCommand') : globalThis.ReplCommand);\nmodule.exports = _Repl.createReplWasmCommand(pkgMeta, {}, ${JSON.stringify(t)});\n`:`'use strict';\nconst pkgMeta = ${r};\nconst _Wasm = typeof WasmCommand !== 'undefined' ? WasmCommand : (typeof require !== 'undefined' ? require('brsh/WasmCommand') : globalThis.WasmCommand);\nmodule.exports = _Wasm.createGenericWasmCommand(pkgMeta, {}, ${JSON.stringify(t)});\n`}_buildCommandsForPackage(e){let t=this.constructor._config||{};if((e.type===`custom-wasm`||e.type===`wasm`)&&e.wasmPath){let t=(e.bin||e.name).toLowerCase();return[{bin:t,Cmd:p(t,e.wasmPath,e)}]}let n=e.adapter||e.name,r=this.constructor._adapters&&this.constructor._adapters.get(n);if(!r&&n===`wllama`&&(r=c.buildEntries||c.createAdapter||c),!r&&e.adapter)try{let t=require(`./packages/${e.adapter}`);r=t.buildEntries||t.createAdapter||t}catch{}if(typeof r==`function`){let n=r(e,t);if(Array.isArray(n))return n;if(n)return[{bin:(e.bin||e.name).toLowerCase(),Cmd:n}]}let i=e.repl?d:u,a=(e.bin||e.name.split(`/`).pop()).toLowerCase(),o=[{bin:a,Cmd:i(e,t,a)}];for(let n of e.aliases||[]){let r=n.toLowerCase();r!==a&&o.push({bin:r,Cmd:i(e,t,r)})}return o}_registerPackageIntoContext(e){let t=this._fs,n=this.constructor._config||{},r=this._pathDir,i=(e.name||``).split(`/`).pop().toLowerCase(),a=(e.bin||i).toLowerCase(),o=`/usr/lib/${i}`,s=this._buildCommandsForPackage(e),c=[],l=e.adapter||e.name,u=!!(n.moduleLoader||n.fetch||l===`wllama`||this.constructor._adapters&&this.constructor._adapters.has(l)),d=e.wasmPath||(t.exists(`${o}/${a}.wasm`)?`${o}/${a}.wasm`:null),f=`${o}/package.json`,p={name:e.name,version:e.version||`1.0.0`,bin:a,aliases:e.aliases||[],description:e.description||``,...e.interactive?{interactive:!0}:{}};this._writeFileSafe(f,JSON.stringify(p,null,2));for(let{bin:n,Cmd:i}of s){let a=n.toLowerCase(),s;if(d&&(!e.type||e.type===`custom-wasm`||e.type===`wasm`))s=d;else{s=`${o}/${a}.js`;let n=this._generateJsCommandSource(e,a);typeof i==`function`&&(i.__source=n),!t.isRealFilesystem&&typeof i==`function`&&u?this._writeFileSafe(s,i):this._writeFileSafe(s,n);try{t.setMode(s,493)}catch{}}this._createBinSymlink(r,a,s),c.push(a)}for(let t of e.aliases||[]){let n=t.toLowerCase();if(!c.includes(n)&&s.length>0){let t=d&&(!e.type||e.type===`custom-wasm`||e.type===`wasm`)?d:`${o}/${a}.js`;this._createBinSymlink(r,n,t),c.push(n)}}let m=e.scriptPaths||{};for(let[e,n]of Object.entries(m)){let i=e.toLowerCase();!c.includes(i)&&t.exists(n)&&(this._createBinSymlink(r,i,n),c.push(i))}if(e.scripts&&typeof e.scripts==`object`)for(let n of Object.keys(e.scripts)){let e=n.toLowerCase(),i=`${o}/${e}`;!c.includes(e)&&t.exists(i)&&(this._createBinSymlink(r,e,i),c.push(e))}return c}_createBinSymlink(e,t,n){let r=this._fs,i=`${e}/${t.toLowerCase()}`;this._removeBin(e,t);try{r.createSymlink(n,i),r.setMode(i,493)}catch{this._writeFileSafe(i,r.getFileByPath(n));try{r.setMode(i,493)}catch{}}}_removeBin(e,t){let n=`${e}/${t.toLowerCase()}`;this._withWritableParent(n,e=>{try{e.deleteFileByPath(n)}catch{}})}async run(){let e=[...this.arguments||[]],t=e.length>=2&&e[0].toLowerCase()===`run`;if(e.length===0||!t&&(e.includes(`--help`)||e.includes(`-h`)||e[0]===`help`)){this._printHelp();return}if(!t&&(e.includes(`--version`)||e.includes(`-v`))){this.stdOut=`wbt 1.1.0 (Web Binary Tool for brsh)`;return}let n=e.shift().toLowerCase();switch(n){case`install`:case`add`:await this._handleInstall(e);break;case`remove`:case`uninstall`:case`purge`:await this._handleRemove(e);break;case`list`:this._handleList(e);break;case`search`:this._handleSearch(e);break;case`show`:case`info`:this._handleShow(e);break;case`update`:await this._handleUpdate(e);break;case`run`:await this._handleRun(e);break;default:this.stdErr=`E: Invalid operation ${n}`,this.stdErr=`Run 'wbt --help' for usage information.`,this.exitCode=100}}async _handleInstall(e){let t=[],n=[],r=null;for(let i=0;i<e.length;i++){let a=e[i];a===`--as`&&i+1<e.length?r=e[++i]:a.startsWith(`--as=`)?r=a.slice(5):a.startsWith(`-`)?t.push(a):n.push(a)}let i=t.includes(`-q`)||t.includes(`--quiet`),a=t.includes(`--generic`)||t.includes(`--npm`);if(n.length===0){this.stdErr=`E: Specify at least one package to install`,this.exitCode=1;return}let o=e=>/^(https?:\/\/|data:)/i.test(e),c=e=>e.startsWith(`data:`)?`custom-wasm`:e.split(`/`).pop().split(`?`)[0].replace(/\.(wasm|wat|mjs|js)$/i,``)||`custom-wasm`,l=this._getRegistry(),u=this._getInstalledPackages(),d=!1;for(let e=0;e<n.length;e++){let f=n[e];if(!o(f)&&e+1<n.length&&o(n[e+1])){let t=n[++e],a=(r||f).toLowerCase();if(await this._installCustomUrl(a,t,i),this.exitCode)return;continue}if(o(f)){let e=f,t=(r||c(e)).toLowerCase();if(await this._installCustomUrl(t,e,i),this.exitCode)return;continue}!i&&!d&&(this.stdOut=`Reading package lists... Done`,this.stdOut=`Building dependency tree... Done`,this.flush(),d=!0);let p=l[s(f)];if(!p&&(a||f.startsWith(`npm:`)||f.startsWith(`esm:`))){let e=f.replace(/^(npm|esm):/i,``),t=(r||e.replace(/^@[^/]+\//,``).split(`@`)[0]).toLowerCase();p={name:t,bin:t,version:`latest`,description:`Dynamic WASM/ESM package from https://esm.sh/${e}`,cdnUrl:`https://esm.sh/${e}`,type:`generic-runtime`}}if(!p){this.stdErr=`E: Unable to locate package ${f}`,this.exitCode=100;return}if(u[p.name]&&!t.includes(`--reinstall`)&&!t.includes(`-f`)){i||(this.stdOut=`${p.name} is already the newest version (${p.version}).`);continue}i||(this.stdOut=`Get:1 ${p.wasmUrl||p.cdnUrl} ${p.name} ${p.version} [${p.size||`WASM`}]`,this.flush());let m=null,h=null;try{m=await this._pullPackageWasm(p,i,t.includes(`--preload`)),h=await this._pullPackageScripts(p,i)}catch(e){this.stdErr=`E: Failed to fetch ${p.name}: ${e.message||e}`,this.exitCode=1;return}i||(this.stdOut=`Unpacking ${p.name} (${p.version})${m?` -> ${m}`:``} ...`,this.flush());let g=Object.assign({},p,m?{wasmPath:m}:{},h?{scriptPaths:h}:{}),_=this._registerPackageIntoContext(g);i||(this.stdOut=`Setting up ${p.name} (${p.version}) -> /bin/${_.join(`, /bin/`)} ...`)}}async _pullPackageScripts(e,t=!1,n=null){if(!e||!e.scripts||typeof e.scripts!=`object`)return null;let r=(this.constructor._config||{}).fetch||(typeof fetch==`function`?fetch:null);if(!r)return null;let i=(e.name||``).split(`/`).pop().toLowerCase(),a=n||`/usr/lib/${i}`,o={};for(let[t,n]of Object.entries(e.scripts)){if(!n)continue;let e=t.toLowerCase(),i=await r(n);if(!i||!i.ok)throw Error(`HTTP ${i?i.status:`error`} fetching script ${n}`);let s;s=typeof i.text==`function`?await i.text():typeof i.arrayBuffer==`function`?new TextDecoder().decode(new Uint8Array(await i.arrayBuffer())):``;let c=`${a}/${e}`;this._writeFileSafe(c,s);try{this._fs.setMode(c,493)}catch{}o[e]=c}return Object.keys(o).length>0?o:null}async _readResponseBytes(e,t,n=!1){let r=e.headers&&typeof e.headers.get==`function`?Number(e.headers.get(`content-length`)||0):0;if(e.body&&typeof e.body.getReader==`function`){let i=e.body.getReader(),a=[],o=0;for(;;){let{done:e,value:s}=await i.read();if(e)break;if(a.push(s),o+=s.byteLength,!n&&r>0){let e=Math.min(100,Math.round(o/r*100)),n=Math.round(e/100*20),i=`█`.repeat(n)+`░`.repeat(Math.max(0,20-n));this.stdOut=`\rDownloading ${t}: [${i}] ${String(e).padStart(3)}%`,this.flush()}}let s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.byteLength;return s}if(typeof e.arrayBuffer==`function`){let t=await e.arrayBuffer();return new Uint8Array(t)}return null}_extractEmbeddedWasmFromText(e){if(!e||typeof e!=`string`)return null;let t=e.match(/AGFzbQE[A-Za-z0-9+/=]{32,}/);if(!t)return null;let n=t[0];try{if(v!==void 0)return new Uint8Array(v.from(n,`base64`));let e=atob(n),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}catch{return null}}_extractNpmSpec(e){for(let t of[e.cdnUrl,e.wasmUrl]){if(!t)continue;let e=t.match(/^https?:\/\/cdn\.jsdelivr\.net\/npm\/((?:@[^/]+\/)?[^/]+)(?:\/|$)/i);if(e)return e[1];let n=t.match(/^https?:\/\/esm\.sh\/((?:@[^/]+\/)?[^/?#]+)(?:\/|\?|$)/i);if(n)return n[1];let r=t.match(/^https?:\/\/unpkg\.com\/((?:@[^/]+\/)?[^/]+)(?:\/|$)/i);if(r)return r[1]}return null}async _discoverWasmFromJsDelivr(e,t,n,r=!1){if(!e||!n)return null;let i=e=>e.replace(/(^@[^/]+\/[^@]+|^[^@]+)@.*$/,`$1`),a=e,o=null;try{let e=await n(`https://data.jsdelivr.com/v1/package/npm/${a}/flat`);if((!e||!e.ok)&&a.includes(`@`)){let t=i(a),r=await n(`https://data.jsdelivr.com/v1/package/npm/${t}`);if(r&&r.ok&&typeof r.json==`function`){let i=await r.json(),o=i&&i.tags&&i.tags.latest;o&&(a=`${t}@${o}`,e=await n(`https://data.jsdelivr.com/v1/package/npm/${a}/flat`))}}e&&e.ok&&typeof e.json==`function`&&(o=await e.json())}catch{return null}let s=o&&Array.isArray(o.files)?o.files:[],c=s.filter(e=>e&&typeof e.name==`string`&&/\.wasm$/i.test(e.name));if(c.length>0){c.sort((e,t)=>e.name.length-t.name.length);let e=c[0],i=`https://cdn.jsdelivr.net/npm/${a}${e.name}`;try{let e=await n(i);if(e&&e.ok){let n=await this._readResponseBytes(e,`${t}.wasm`,r);if(n&&n.byteLength>0)return{bytes:n,url:i}}}catch{}}let l=s.filter(e=>e&&typeof e.name==`string`&&/\.(?:mjs|cjs|js)$/i.test(e.name)&&!/\.min\.js$/i.test(e.name));for(let e of l.slice(0,4)){let t=`https://cdn.jsdelivr.net/npm/${a}${e.name}`;try{let e=await n(t);if(e&&e.ok&&typeof e.text==`function`){let n=await e.text(),r=this._extractEmbeddedWasmFromText(n);if(r)return{bytes:r,url:t}}}catch{}}return null}async _pullPackageWasm(e,t=!1,n=!1,r=null){let i=this.constructor._config||{},a=i.fetch||(typeof fetch==`function`?fetch:null),{loadModule:o}=oe(),s=null,c=null,l=e.wasmUrl||(/\.(wasm|wat)(\?.*)?$/i.test(e.cdnUrl||``)?e.cdnUrl:null);if(l&&a)try{let n=await a(l);n&&n.ok?s=await this._readResponseBytes(n,`${e.name}.wasm`,t):c=Error(`HTTP ${n?n.status:`error`} fetching ${l}`)}catch(e){c=e}if(!s&&a&&!i.moduleLoader){let n=this._extractNpmSpec(e);if(n){let r=await this._discoverWasmFromJsDelivr(n,e.name,a,t);r&&r.bytes&&(s=r.bytes,e.wasmUrl=r.url,c=null)}}let u=null,d=null;if(e.cdnUrl||i.moduleLoader){let t=typeof globalThis.fetch==`function`?globalThis.fetch:null;t&&s&&s.byteLength>0&&typeof Response<`u`&&(globalThis.fetch=async(e,n)=>{let r=typeof e==`string`?e:e&&e.url?e.url:``;return r&&!/^https?:\/\//i.test(r)&&/\.wasm(\?.*)?$/i.test(r)?new Response(s,{status:200,headers:{"Content-Type":`application/wasm`}}):t(e,n)});try{u=await o(e.name,e.cdnUrl,i.moduleLoader)}catch(e){if(d=e,n)throw e}finally{t&&(globalThis.fetch=t)}}if(!s&&u){let e=u.default===void 0?u:u.default;e instanceof Uint8Array?s=e:e instanceof ArrayBuffer?s=new Uint8Array(e):e&&(e.wasmBytes instanceof Uint8Array||e.wasm instanceof Uint8Array||e.wasmBinary instanceof Uint8Array)&&(s=e.wasmBytes||e.wasm||e.wasmBinary)}if(!s&&e.cdnUrl&&a&&!i.moduleLoader)try{let t=await a(e.cdnUrl);if(t&&t.ok&&typeof t.text==`function`){let e=await t.text();s=this._extractEmbeddedWasmFromText(e)}}catch{}if(!s&&typeof i.moduleLoader==`function`&&(s=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,7,10,1,6,95,115,116,97,114,116,0,0,10,4,1,2,0,11])),!s&&!u&&(c||d)&&!i.moduleLoader)throw c||d;if(s){let t=(e.name||``).split(`/`).pop().toLowerCase(),n=(e.bin||t).toLowerCase(),i=`${r||`/usr/lib/${t}`}/${n}.wasm`;this._writeBytesSafe(i,s,`application/wasm`);try{this._fs.setMode(i,493)}catch{}return i}return null}async _installCustomUrl(e,t,n=!1){if(!/\.(wasm|wat)(\?.*)?$/i.test(t)&&(/^https?:\/\/esm\.sh\//i.test(t)||/\.(mjs|js)(\?.*)?$/i.test(t))){let r={name:e,bin:e,bins:[e],version:`custom-esm`,description:`Custom ESM/WASM module from ${t}`,cdnUrl:t,type:`generic-runtime`,installedAt:new Date().toISOString()},i=await this._pullPackageWasm(r,n,!1);i&&(r.wasmPath=i),this._registerPackageIntoContext(r),n||(this.stdOut=`Setting up ${e} (generic runtime) -> /bin/${e} ...`);return}let r=(this.constructor._config||{}).fetch||(typeof fetch==`function`?fetch:null);if(!r){this.stdErr=`E: fetch is not available in this environment`,this.exitCode=1;return}n||(this.stdOut=`Get:1 ${t} ${e}`,this.flush());let i=t.replace(/^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/(?:blob|raw)\/([^/]+)\/(.+)$/i,`https://raw.githubusercontent.com/$1/$2/$3/$4`),a;try{a=await r(i)}catch(e){if(/^https?:\/\/github\.com\/[^/]+\/[^/]+\/releases\/download\//i.test(i))try{a=await r(`https://corsproxy.io/?${encodeURIComponent(i)}`)}catch{this.stdErr=`E: Failed to fetch ${t} (GitHub Releases blocks browser CORS requests; host the .wasm on jsDelivr/unpkg/raw.githubusercontent.com): ${e.message||e}`,this.exitCode=1;return}else{this.stdErr=`E: Failed to fetch ${t}: ${e.message||e}`,this.exitCode=1;return}}if(!a||!a.ok){this.stdErr=`E: HTTP ${a?a.status:`error`} fetching ${t}`,this.exitCode=1;return}let o=t.endsWith(`.wat`),s=o?`.wat`:`.wasm`,c=`${`/usr/lib/${e}`}/${e}${s}`;if(o){let e=await a.text();this._writeFileSafe(c,e)}else{let e=await a.arrayBuffer();this._writeBytesSafe(c,new Uint8Array(e),`application/wasm`)}try{this._fs.setMode(c,493)}catch{}let l={name:e,bin:e,bins:[e],version:`custom`,description:`Custom WebAssembly binary from ${t}`,cdnUrl:t,type:`custom-wasm`,wasmPath:c,installedAt:new Date().toISOString()};this._registerPackageIntoContext(l),n||(this.stdOut=`Setting up ${e} (custom) -> /bin/${e} ...`)}async _handleRemove(e){let t=e.filter(e=>!e.startsWith(`-`));if(t.length===0){this.stdErr=`E: Specify at least one package to remove`,this.exitCode=1;return}let n=this._getInstalledPackages(),r=this._getRegistry(),i=this._pathDir;for(let e of t){let t=s(e),a=n[t]||n[e.toLowerCase()];if(!a){this.stdErr=`E: Package '${e}' is not installed, so not removed`,this.exitCode=1;return}let o=r[t]||{},c=new Set([a.bin||a.name,...a.aliases||[],...o.aliases||[],e.toLowerCase(),t]);if(a.scripts)for(let e of Object.keys(a.scripts))c.add(e);for(let e of c)this._removeBin(i,e);let l=`/usr/lib/${t}`;try{this._fs.deleteFileByPath(l)}catch{}this.stdOut=`Removing ${a.name} (${a.version}) ...`}}_handleList(e){let t=e.includes(`--installed`)||e.includes(`-i`),n=this._getRegistry(),r=this._getInstalledPackages();this.stdOut=`Listing...`;let i=t?Object.keys(r).sort():Array.from(new Set([...Object.keys(n),...Object.keys(r)])).sort();for(let e of i){let t=n[e],i=r[e],a=i||t;if(!a)continue;let o=i?`[installed]`:`[available]`,s=a.bin&&a.bin!==a.name?` (bin: ${a.bin})`:``;this.stdOut=`${a.name}/wasm ${a.version} wasm ${o}${s} - ${a.description||``}`}}_handleSearch(e){let t=e.filter(e=>!e.startsWith(`-`)).join(` `).toLowerCase(),n=this._getRegistry(),r=this._getInstalledPackages();this.stdOut=`Sorting... Done`,this.stdOut=`Full Text Search... Done`;let i=Object.values(n).filter(e=>t?e.name.toLowerCase().includes(t)||e.bin&&e.bin.toLowerCase().includes(t)||e.aliases&&e.aliases.some(e=>e.toLowerCase().includes(t))||e.scripts&&Object.keys(e.scripts).some(e=>e.toLowerCase().includes(t))||e.description&&e.description.toLowerCase().includes(t)||e.details&&e.details.toLowerCase().includes(t):!0);for(let e of i){let t=r[e.name]?` [installed]`:``;this.stdOut=`${e.name}/wasm ${e.version} wasm${t}`,this.stdOut=` ${e.description}`}}_handleShow(e){let t=e.find(e=>!e.startsWith(`-`));if(!t){this.stdErr=`E: No packages found — specify a package name`,this.exitCode=1;return}let n=s(t),r=this._getRegistry(),i=this._getInstalledPackages(),a=i[n]||r[n];if(!a){this.stdErr=`E: No packages found matching ${t}`,this.exitCode=100;return}let o=Object.assign({},r[n]||{},a),c=!!i[o.name];this.stdOut=`Package: ${o.name}`,this.stdOut=`Version: ${o.version}`,this.stdOut=`State: ${c?`installed`:`not installed`}`,this.stdOut=`Binary: ${o.bin||o.name}`,o.aliases&&o.aliases.length>0&&(this.stdOut=`Aliases: ${o.aliases.join(`, `)}`),o.scripts&&Object.keys(o.scripts).length>0&&(this.stdOut=`Scripts: ${Object.keys(o.scripts).join(`, `)}`),o.size&&(this.stdOut=`Download-Size: ${o.size}`),o.cdnUrl&&(this.stdOut=`APT-Sources: ${o.cdnUrl}`),o.wasmUrl&&(this.stdOut=`WASM-URL: ${o.wasmUrl}`),o.wasmPath&&(this.stdOut=`WASM-File: ${o.wasmPath}`),o.homepage&&(this.stdOut=`Homepage: ${o.homepage}`),this.stdOut=`Description: ${o.description||``}`,o.details&&(this.stdOut=` ${o.details}`)}async _handleUpdate(){let e=this.constructor._config||{},t=e.sources||[],n=e.fetch||(typeof fetch==`function`?fetch:null),r={},i=1;this.stdOut=`Hit:1 https://registry.brsh.dev/wbt wasm InRelease`;for(let e of t)if(i++,n)try{let t=await n(e);if(t&&t.ok){let n=await t.json();Object.assign(r,n),this.stdOut=`Get:${i} ${e} Packages`}}catch(t){this.stdErr=`W: Failed to fetch ${e}: ${t.message||t}`}Object.keys(r).length>0&&this._writeFileSafe(`${f}/remote-registry.json`,JSON.stringify(r,null,2));let a=this._getRegistry();this.stdOut=`Reading package lists... Done (${Object.keys(a).length} packages available)`}async _handleRun(e){if(e.length===0){this.stdErr=`E: Specify a package to run (e.g. wbt run sqlite3 --version)`,this.exitCode=1;return}let t=e.shift(),n=s(t),r=this._getRegistry(),i=this._getInstalledPackages(),a=!!i[n],o=i[n]||r[n];if(!o&&(t.startsWith(`npm:`)||t.startsWith(`esm:`))){let e=t.replace(/^(npm|esm):/i,``),n=e.replace(/^@[^/]+\//,``).split(`@`)[0].toLowerCase();o={name:n,bin:n,version:`latest`,cdnUrl:`https://esm.sh/${e}`,type:`generic-runtime`}}if(!o){this.stdErr=`E: Unable to locate package ${t}`,this.exitCode=100;return}let c=this._fs,l=null,u=this._pathDir;try{if(a||(l=`/tmp/.wbt-run-${n}-${Date.now()}`),(o.type===`custom-wasm`||o.type===`wasm`)&&!o.wasmPath)try{let e=await this._pullPackageWasm(o,!0,!1,l);e&&(o=Object.assign({},o,{wasmPath:e}))}catch(e){this.stdErr=`E: Failed to fetch ${o.name}: ${e.message||e}`,this.exitCode=1;return}let r=t.toLowerCase(),i;if(o.scripts&&o.scripts[r]){let t=o.scriptPaths&&o.scriptPaths[r]||`/usr/lib/${n}/${r}`;if(!c.exists(t))try{let e=await this._pullPackageScripts(o,!0,l);e&&e[r]&&(t=e[r])}catch(e){this.stdErr=`E: Failed to fetch script ${r}: ${e.message||e}`,this.exitCode=1;return}let a=e=>this.context&&typeof this.context.getVar==`function`?this.context.getVar(e):``,s=l?`${l}:${u}`:u,d=this.context&&this.context.vars?Object.assign({},this.context.vars):{HOME:a(`HOME`)||`/root`,HOST:a(`HOST`)||`browser`,COLUMNS:String(this.stdout&&this.stdout.columns||a(`COLUMNS`)||80),LINES:String(this.stdout&&this.stdout.rows||a(`LINES`)||24)};d.PATH=s;let f={vars:d,aliases:this.context&&this.context.aliases||{},getVar:e=>e===`PATH`?s:d[e]||a(e),getAlias:e=>this.context&&typeof this.context.getAlias==`function`?this.context.getAlias(e):null,getCommand:e=>this.context&&typeof this.context.getCommand==`function`?this.context.getCommand(e):null};i=new(ne())(c.getFileByPath(t),e,f),i.fs=c}else{let t=this._buildCommandsForPackage(o),n=(t.find(e=>e.bin===r)||t[0]).Cmd;i=new n(e,this.context),i.requiresFilesystem&&(i.fs=typeof c.sandbox==`function`?c.sandbox():c)}this._activeSubCommand=i,this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`data`,this._onStdinStreamData),i.stdinStream=this.stdinStream,i.stdin=this.stdin&&!this.stdin.isTTY?this.stdin:this.stdinStream,i._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,i._onStdinStreamData),this.stdout&&i.stdout&&(this.stdout.columns&&(i.stdout.columns=this.stdout.columns),this.stdout.rows&&(i.stdout.rows=this.stdout.rows)),this.stderr&&i.stderr&&(this.stderr.columns&&(i.stderr.columns=this.stderr.columns),this.stderr.rows&&(i.stderr.rows=this.stderr.rows));let s=()=>{!this.stdout||!i.stdout||(typeof i.stdout.resize==`function`?i.stdout.resize(this.stdout.columns,this.stdout.rows):(i.stdout.columns=this.stdout.columns,i.stdout.rows=this.stdout.rows))};this.stdout&&typeof this.stdout.on==`function`&&this.stdout.on(`resize`,s);let d=e=>{this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(e)},f=e=>{this.stderr&&typeof this.stderr.write==`function`&&this.stderr.write(e)},p=e=>{let t=Array.isArray(e)?e:e&&typeof e.getStdOutput==`function`?e.getStdOutput():[];for(let e of t)e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.flush()};i.stdout&&typeof i.stdout.on==`function`&&i.stdout.on(`data`,d),i.stderr&&typeof i.stderr.on==`function`&&i.stderr.on(`data`,f),typeof i.on==`function`&&i.on(`flush`,p);let m;try{m=await i.runCommand()}finally{this._activeSubCommand=null,this.stdout&&typeof this.stdout.off==`function`&&this.stdout.off(`resize`,s),i._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`data`,i._onStdinStreamData),this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,this._onStdinStreamData),i.stdout&&typeof i.stdout.off==`function`&&i.stdout.off(`data`,d),i.stderr&&typeof i.stderr.off==`function`&&i.stderr.off(`data`,f),typeof i.removeListener==`function`&&i.removeListener(`flush`,p)}if(!i.interactive&&m)for(let e of m.getStdOutput())e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.exitCode=m?m.getExitCode():0}finally{if(l&&c)try{c.deleteFileByPath(l)}catch{}}}_printHelp(){[`wbt 1.1.0 — Web Binary Tool (WASM binary manager & runtime for brsh)`,`Usage: wbt [options] command [package ...]`,``,`Commands:`,` install <pkg> [url] Install a WASM binary from registry, npm:<pkg>, or a custom URL`,` remove <pkg> Remove an installed WASM binary`,` update Update package index and restore installed binaries`,` list [--installed] List available or installed WASM binaries`,` search <query> Search available WASM binaries by name or description`,` show <pkg> Show detailed information about a package`,` run <pkg> [args...] Run a WASM binary without permanently installing it`,``,`Curated WASM Packages:`,` sqlite3 SQLite3 compiled to WebAssembly (sqlite3, sqlite)`,` assemblyscript AssemblyScript compiler & ts-node style runtime (asc, asrun, asnode)`,` jq Command-line JSON processor (jq)`,` python3 CPython 3.12 via Pyodide (python3, python, py)`,` duckdb DuckDB analytical SQL OLAP engine (duckdb)`,` graphviz Graphviz DOT diagram compiler (dot)`,` ffmpeg FFmpeg multimedia transcoder (ffmpeg)`,` wabt WebAssembly Binary Toolkit (wat2wasm, wasm2wat)`,` quickjs Sandboxed QuickJS JavaScript engine (qjs)`,` lua Lua 5.4 WebAssembly interpreter (lua)`,` wllama WASM & WebGPU LLM inference engine (wllama, llama, llama-cli)`,` nano GNU nano 8.0 text editor with ncurses (nano, nano-wasm)`,` doom Classic Doom (1993) with 24-bit ANSI rendering (doom, freedoom)`].forEach(e=>{this.stdOut=e})}};t.exports=m,t.exports.Wbt=m,t.exports.DEFAULT_REGISTRY=o,t.exports.createGenericWasmCommand=u,t.exports.createReplWasmCommand=d}))()})();
|
|
21
35
|
//# sourceMappingURL=wbt.min.js.map
|