brsh 3.7.0 → 3.8.1
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/Readme.md +128 -0
- package/dist/shell.es.js +633 -458
- package/dist/shell.es.js.map +1 -1
- package/dist/shell.min.js +18 -18
- package/dist/shell.min.js.map +1 -1
- package/dist/wbt.es.js +626 -451
- package/dist/wbt.es.js.map +1 -1
- package/dist/wbt.min.js +12 -12
- package/dist/wbt.min.js.map +1 -1
- package/lib/Command.js +3 -2
- package/lib/Readme.md +23 -1
- package/lib/TtyStream.js +12 -2
- package/lib/WasmCommand.js +380 -37
- package/package.json +1 -1
- package/test/wasm-cli.test.js +64 -0
- package/test/wbt.test.js +43 -4
package/dist/wbt.min.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";var Wbt=(function(){var e=(e,t)=>()=>(e&&(t=e(e=0)),t),t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);function n(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function r(e){var t=n(e),r=t[0],i=t[1];return(r+i)*3/4-i}function i(e,t,n){return(t+n)*3/4-n}function a(e){var t,r=n(e),a=r[0],o=r[1],s=new p(i(e,a,o)),c=0,l=o>0?a-4:a,u;for(u=0;u<l;u+=4)t=f[e.charCodeAt(u)]<<18|f[e.charCodeAt(u+1)]<<12|f[e.charCodeAt(u+2)]<<6|f[e.charCodeAt(u+3)],s[c++]=t>>16&255,s[c++]=t>>8&255,s[c++]=t&255;return o===2&&(t=f[e.charCodeAt(u)]<<2|f[e.charCodeAt(u+1)]>>4,s[c++]=t&255),o===1&&(t=f[e.charCodeAt(u)]<<10|f[e.charCodeAt(u+1)]<<4|f[e.charCodeAt(u+2)]>>2,s[c++]=t>>8&255,s[c++]=t&255),s}function o(e){return d[e>>18&63]+d[e>>12&63]+d[e>>6&63]+d[e&63]}function s(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(o(r));return i.join(``)}function c(e){for(var t,n=e.length,r=n%3,i=[],a=16383,o=0,c=n-r;o<c;o+=a)i.push(s(e,o,o+a>c?c:o+a));return r===1?(t=e[n-1],i.push(d[t>>2]+d[t<<4&63]+`==`)):r===2&&(t=(e[n-2]<<8)+e[n-1],i.push(d[t>>10]+d[t>>4&63]+d[t<<2&63]+`=`)),i.join(``)}var l,u,d,f,p,m,h,g,_,v,y=e((()=>{for(l={},u={},u.byteLength=r,u.toByteArray=a,u.fromByteArray=c,d=[],f=[],p=typeof Uint8Array<`u`?Uint8Array:Array,m=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,h=0,g=m.length;h<g;++h)d[h]=m[h],f[m.charCodeAt(h)]=h;f[45]=62,f[95]=63,_={},_.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},_.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128},(function(e){let t=u,n=_,r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=d,e.SlowBuffer=C,e.INSPECT_MAX_BYTES=50;let i=2147483647;e.kMaxLength=i;let{Uint8Array:a,ArrayBuffer:o,SharedArrayBuffer:s}=globalThis;d.TYPED_ARRAY_SUPPORT=c(),!d.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function c(){try{let e=new a(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,a.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(d.prototype,"parent",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.buffer}}),Object.defineProperty(d.prototype,"offset",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.byteOffset}});function l(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);let t=new a(e);return Object.setPrototypeOf(t,d.prototype),t}function d(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return h(e)}return f(e,t,n)}d.poolSize=8192;function f(e,t,n){if(typeof e==`string`)return g(e,t);if(o.isView(e))return y(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(Q(e,o)||e&&Q(e.buffer,o)||s!==void 0&&(Q(e,s)||e&&Q(e.buffer,s)))return b(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);let r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return d.from(r,t,n);let i=x(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return d.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}d.from=function(e,t,n){return f(e,t,n)},Object.setPrototypeOf(d.prototype,a.prototype),Object.setPrototypeOf(d,a);function p(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function m(e,t,n){return p(e),e<=0||t===void 0?l(e):typeof n==`string`?l(e).fill(t,n):l(e).fill(t)}d.alloc=function(e,t,n){return m(e,t,n)};function h(e){return p(e),l(e<0?0:S(e)|0)}d.allocUnsafe=function(e){return h(e)},d.allocUnsafeSlow=function(e){return h(e)};function g(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!d.isEncoding(t))throw TypeError(`Unknown encoding: `+t);let n=w(e,t)|0,r=l(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function v(e){let t=e.length<0?0:S(e.length)|0,n=l(t);for(let r=0;r<t;r+=1)n[r]=e[r]&255;return n}function y(e){if(Q(e,a)){let t=new a(e);return b(t.buffer,t.byteOffset,t.byteLength)}return v(e)}function b(e,t,n){if(t<0||e.byteLength<t)throw RangeError(`"offset" is outside of buffer bounds`);if(e.byteLength<t+(n||0))throw RangeError(`"length" is outside of buffer bounds`);let r;return r=t===void 0&&n===void 0?new a(e):n===void 0?new a(e,t):new a(e,t,n),Object.setPrototypeOf(r,d.prototype),r}function x(e){if(d.isBuffer(e)){let t=S(e.length)|0,n=l(t);return n.length===0||e.copy(n,0,0,t),n}if(e.length!==void 0)return typeof e.length!=`number`||de(e.length)?l(0):v(e);if(e.type===`Buffer`&&Array.isArray(e.data))return v(e.data)}function S(e){if(e>=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function C(e){return+e!=e&&(e=0),d.alloc(+e)}d.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==d.prototype},d.compare=function(e,t){if(Q(e,a)&&(e=d.from(e,e.offset,e.byteLength)),Q(t,a)&&(t=d.from(t,t.offset,t.byteLength)),!d.isBuffer(e)||!d.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},d.isEncoding=function(e){switch(String(e).toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`latin1`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return!0;default:return!1}},d.concat=function(e,t){if(!Array.isArray(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return d.alloc(0);let n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;let r=d.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){let t=e[n];if(Q(t,a))i+t.length>r.length?(d.isBuffer(t)||(t=d.from(t)),t.copy(r,i)):a.prototype.set.call(r,t,i);else if(d.isBuffer(t))t.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=t.length}return r};function w(e,t){if(d.isBuffer(e))return e.length;if(o.isView(e)||Q(e,o))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);let n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let i=!1;for(;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return oe(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return le(e).length;default:if(i)return r?-1:oe(e).length;t=(``+t).toLowerCase(),i=!0}}d.byteLength=w;function T(e,t,n){let r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return z(this,t,n);case`utf8`:case`utf-8`:return F(this,t,n);case`ascii`:return L(this,t,n);case`latin1`:case`binary`:return R(this,t,n);case`base64`:return P(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return B(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}d.prototype._isBuffer=!0;function E(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}d.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;t<e;t+=2)E(this,t,t+1);return this},d.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let t=0;t<e;t+=4)E(this,t,t+3),E(this,t+1,t+2);return this},d.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let t=0;t<e;t+=8)E(this,t,t+7),E(this,t+1,t+6),E(this,t+2,t+5),E(this,t+3,t+4);return this},d.prototype.toString=function(){let e=this.length;return e===0?``:arguments.length===0?F(this,0,e):T.apply(this,arguments)},d.prototype.toLocaleString=d.prototype.toString,d.prototype.equals=function(e){if(!d.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e?!0:d.compare(this,e)===0},d.prototype.inspect=function(){let t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(d.prototype[r]=d.prototype.inspect),d.prototype.compare=function(e,t,n,r,i){if(Q(e,a)&&(e=d.from(e,e.offset,e.byteLength)),!d.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;let o=i-r,s=n-t,c=Math.min(o,s),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){o=l[e],s=u[e];break}return o<s?-1:+(s<o)};function D(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,de(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0)if(i)n=0;else return-1;if(typeof t==`string`&&(t=d.from(t,r)),d.isBuffer(t))return t.length===0?-1:O(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof a.prototype.indexOf==`function`?i?a.prototype.indexOf.call(e,t,n):a.prototype.lastIndexOf.call(e,t,n):O(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function O(e,t,n,r,i){let a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}let l;if(i){let r=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,r===-1?0:l-r)){if(r===-1&&(r=l),l-r+1===s)return r*a}else r!==-1&&(l-=l-r),r=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){let n=!0;for(let r=0;r<s;r++)if(c(e,l+r)!==c(t,r)){n=!1;break}if(n)return l}return-1}d.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},d.prototype.indexOf=function(e,t,n){return D(this,e,t,n,!0)},d.prototype.lastIndexOf=function(e,t,n){return D(this,e,t,n,!1)};function k(e,t,n,r){n=Number(n)||0;let i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;let a=t.length;r>a/2&&(r=a/2);let o;for(o=0;o<r;++o){let r=parseInt(t.substr(o*2,2),16);if(de(r))return o;e[n+o]=r}return o}function A(e,t,n,r){return ue(oe(t,e.length-n),e,n,r)}function j(e,t,n,r){return ue(se(t),e,n,r)}function M(e,t,n,r){return ue(le(t),e,n,r)}function N(e,t,n,r){return ue(ce(t,e.length-n),e,n,r)}d.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);let i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;let a=!1;for(;;)switch(r){case`hex`:return k(this,e,t,n);case`utf8`:case`utf-8`:return A(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return j(this,e,t,n);case`base64`:return M(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return N(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},d.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function P(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function F(e,t,n){n=Math.min(e.length,n);let r=[],i=t;for(;i<n;){let t=e[i],a=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[i+1],(n&192)==128&&(c=(t&31)<<6|n&63,c>127&&(a=c));break;case 3:n=e[i+1],r=e[i+2],(n&192)==128&&(r&192)==128&&(c=(t&15)<<12|(n&63)<<6|r&63,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[i+1],r=e[i+2],s=e[i+3],(n&192)==128&&(r&192)==128&&(s&192)==128&&(c=(t&15)<<18|(n&63)<<12|(r&63)<<6|s&63,c>65535&&c<1114112&&(a=c))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a),i+=o}return ee(r)}let I=4096;function ee(e){let t=e.length;if(t<=I)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=I));return n}function L(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function R(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function z(e,t,n){let r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i=``;for(let r=t;r<n;++r)i+=fe[e[r]];return i}function B(e,t,n){let r=e.slice(t,n),i=``;for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+r[e+1]*256);return i}d.prototype.slice=function(e,t){let n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);let r=this.subarray(e,t);return Object.setPrototypeOf(r,d.prototype),r};function V(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}d.prototype.readUintLE=d.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||V(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return r},d.prototype.readUintBE=d.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||V(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},d.prototype.readUint8=d.prototype.readUInt8=function(e,t){return e>>>=0,t||V(e,1,this.length),this[e]},d.prototype.readUint16LE=d.prototype.readUInt16LE=function(e,t){return e>>>=0,t||V(e,2,this.length),this[e]|this[e+1]<<8},d.prototype.readUint16BE=d.prototype.readUInt16BE=function(e,t){return e>>>=0,t||V(e,2,this.length),this[e]<<8|this[e+1]},d.prototype.readUint32LE=d.prototype.readUInt32LE=function(e,t){return e>>>=0,t||V(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},d.prototype.readUint32BE=d.prototype.readUInt32BE=function(e,t){return e>>>=0,t||V(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},d.prototype.readBigUInt64LE=$(function(e){e>>>=0,Z(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&re(e,this.length-8);let r=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),d.prototype.readBigUInt64BE=$(function(e){e>>>=0,Z(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&re(e,this.length-8);let r=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),d.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||V(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},d.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||V(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},d.prototype.readInt8=function(e,t){return e>>>=0,t||V(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},d.prototype.readInt16LE=function(e,t){e>>>=0,t||V(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},d.prototype.readInt16BE=function(e,t){e>>>=0,t||V(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},d.prototype.readInt32LE=function(e,t){return e>>>=0,t||V(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},d.prototype.readInt32BE=function(e,t){return e>>>=0,t||V(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},d.prototype.readBigInt64LE=$(function(e){e>>>=0,Z(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&re(e,this.length-8);let r=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)}),d.prototype.readBigInt64BE=$(function(e){e>>>=0,Z(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&re(e,this.length-8);let r=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n)}),d.prototype.readFloatLE=function(e,t){return e>>>=0,t||V(e,4,this.length),n.read(this,e,!0,23,4)},d.prototype.readFloatBE=function(e,t){return e>>>=0,t||V(e,4,this.length),n.read(this,e,!1,23,4)},d.prototype.readDoubleLE=function(e,t){return e>>>=0,t||V(e,8,this.length),n.read(this,e,!0,52,8)},d.prototype.readDoubleBE=function(e,t){return e>>>=0,t||V(e,8,this.length),n.read(this,e,!1,52,8)};function H(e,t,n,r,i,a){if(!d.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}d.prototype.writeUintLE=d.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;H(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a<n&&(i*=256);)this[t+a]=e/i&255;return t+n},d.prototype.writeUintBE=d.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;H(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},d.prototype.writeUint8=d.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,1,255,0),this[t]=e&255,t+1},d.prototype.writeUint16LE=d.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},d.prototype.writeUint16BE=d.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},d.prototype.writeUint32LE=d.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},d.prototype.writeUint32BE=d.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function U(e,t,n,r,i){X(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function W(e,t,n,r,i){X(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}d.prototype.writeBigUInt64LE=$(function(e,t=0){return U(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),d.prototype.writeBigUInt64BE=$(function(e,t=0){return W(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),d.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);H(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i<n&&(a*=256);)e<0&&o===0&&this[t+i-1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},d.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);H(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},d.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},d.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},d.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},d.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},d.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||H(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},d.prototype.writeBigInt64LE=$(function(e,t=0){return U(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),d.prototype.writeBigInt64BE=$(function(e,t=0){return W(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function G(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function K(e,t,r,i,a){return t=+t,r>>>=0,a||G(e,t,r,4),n.write(e,t,r,i,23,4),r+4}d.prototype.writeFloatLE=function(e,t,n){return K(this,e,t,!0,n)},d.prototype.writeFloatBE=function(e,t,n){return K(this,e,t,!1,n)};function te(e,t,r,i,a){return t=+t,r>>>=0,a||G(e,t,r,8),n.write(e,t,r,i,52,8),r+8}d.prototype.writeDoubleLE=function(e,t,n){return te(this,e,t,!0,n)},d.prototype.writeDoubleBE=function(e,t,n){return te(this,e,t,!1,n)},d.prototype.copy=function(e,t,n,r){if(!d.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);let i=r-n;return this===e&&typeof a.prototype.copyWithin==`function`?this.copyWithin(t,n,r):a.prototype.set.call(e,this.subarray(n,r),t),i},d.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!d.isEncoding(r))throw TypeError(`Unknown encoding: `+r);if(e.length===1){let t=e.charCodeAt(0);(r===`utf8`&&t<128||r===`latin1`)&&(e=t)}}else typeof e==`number`?e&=255:typeof e==`boolean`&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;let i;if(typeof e==`number`)for(i=t;i<n;++i)this[i]=e;else{let a=d.isBuffer(e)?e:d.from(e,r),o=a.length;if(o===0)throw TypeError(`The value "`+e+`" is invalid for argument "value"`);for(i=0;i<n-t;++i)this[i+t]=a[i%o]}return this};let q={};function J(e,t,n){q[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}J(`ERR_BUFFER_OUT_OF_BOUNDS`,function(e){return e?`${e} is outside of buffer bounds`:`Attempt to access memory outside buffer bounds`},RangeError),J(`ERR_INVALID_ARG_TYPE`,function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),J(`ERR_OUT_OF_RANGE`,function(e,t,n){let r=`The value of "${e}" is out of range.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=Y(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=Y(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function Y(e){let t=``,n=e.length,r=+(e[0]===`-`);for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function ne(e,t,n){Z(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&re(t,e.length-(n+1))}function X(e,t,n,r,i,a){if(e>n||e<t){let r=typeof t==`bigint`?`n`:``,i;throw i=a>3?t===0||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${(a+1)*8}${r}`:`>= -(2${r} ** ${(a+1)*8-1}${r}) and < 2 ** ${(a+1)*8-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new q.ERR_OUT_OF_RANGE(`value`,i,e)}ne(r,i,a)}function Z(e,t){if(typeof e!=`number`)throw new q.ERR_INVALID_ARG_TYPE(t,`number`,e)}function re(e,t,n){throw Math.floor(e)===e?t<0?new q.ERR_BUFFER_OUT_OF_BOUNDS:new q.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(Z(e,n),new q.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}let ie=/[^+/0-9A-Za-z-_]/g;function ae(e){if(e=e.split(`=`)[0],e=e.trim().replace(ie,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function oe(e,t){t||=1/0;let n,r=e.length,i=null,a=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}else if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function se(e){let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function ce(e,t){let n,r,i,a=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function le(e){return t.toByteArray(ae(e))}function ue(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function Q(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function de(e){return e!==e}let fe=(function(){let e=`0123456789abcdef`,t=Array(256);for(let n=0;n<16;++n){let r=n*16;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t})();function $(e){return typeof BigInt>`u`?pe:e}function pe(){throw Error(`BigInt not supported`)}})(l),v=l.Buffer,l.Blob,l.BlobOptions,l.Buffer,l.File,l.FileOptions,l.INSPECT_MAX_BYTES,l.SlowBuffer,l.TranscodeEncoding,l.atob,l.btoa,l.constants,l.isAscii,l.isUtf8,l.kMaxLength,l.kStringMaxLength,l.resolveObjectURL,l.transcode})),b=t(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function d(e,t,n,r){var i,o,s;if(l(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=u(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function v(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function y(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}x(e,t,a,{once:!0}),t!==`error`&&b(e,i,{once:!0})})}function b(e,t,n){typeof e.on==`function`&&x(e,`error`,t,n)}function x(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),x=t(((e,t)=>{var n=[`out`,`err`];t.exports=class{constructor(e,t){if(!n.includes(e))throw Error(`incorrect std output type`);this.type=e,this.string=t}}})),S=t(((e,t)=>{var n=x();t.exports=class{constructor(e=[],t=0){if(typeof t!=`number`)throw Error(`Command Result ExitCode must be a number`);if(!Array.isArray(e))throw Error(`Command Result be array`);this.std=e,this.exitCode=t}addStdOutLine(e){this.std.push(new n(`out`,e))}addStdErrLine(e){this.std.push(new n(`err`,e))}getStdOutput(){return this.std}getExitCode(){return this.exitCode}flush(){let e=this.std;return this.std=[],e}}})),C=t(((e,t)=>{y();var n=b(),r=n.EventEmitter||n.default||n;function i(e){if(!e)return[];let t=typeof e==`string`?e:e instanceof Uint8Array||v!==void 0&&v.isBuffer(e)?new TextDecoder().decode(e):String(e),n=[],r=0;for(;r<t.length;){let e=t[r],i=t.charCodeAt(r);if(i===27){if(t.charCodeAt(r+1)===127||t.charCodeAt(r+1)===8){n.push(`^W`),r+=2;continue}if(t[r+1]===`[`||t[r+1]===`O`){let e=r+2;for(;e<t.length&&t.charCodeAt(e)>=32&&t.charCodeAt(e)<=63;)e++;if(e<t.length){let i=t.slice(r+2,e+1),a={A:`ArrowUp`,B:`ArrowDown`,C:`ArrowRight`,D:`ArrowLeft`,H:`Home`,F:`End`,"1~":`Home`,"3~":`Delete`,"4~":`End`,"5~":`PageUp`,"6~":`PageDown`,"7~":`Home`,"8~":`End`};a[i]&&n.push(a[i]),r=e+1;continue}}n.push(`Escape`),r++;continue}if(i===13||i===10){n.push(`Enter`),i===13&&t[r+1]===`
|
|
2
|
-
`&&r++,r++;continue}if(i===127||i===8){n.push(`Backspace`),r++;continue}if(i===9){n.push(`Tab`),r++;continue}if(i>=1&&i<=26){n.push(`^`+String.fromCharCode(i+64)),r++;continue}n.push(e),r++}return n}t.exports={TtyStream:class extends r{constructor(e={}){super(),this.isTTY=e.isTTY!==!1,this.readable=!0,this.writable=!0,this.columns=e.columns||80,this.rows=e.rows||24,this.isRaw=!1,this._encoding=null,this._onWrite=e.onWrite||null}write(e,t,n){
|
|
3
|
-
`):e===`Backspace`?this.stdout.write(`\b \b`):e.length===1&&this.stdout.write(e)),this.onInput(e)})}get name(){return`unnamed`}run(){return Promise.reject(`Command not implemented...`)}runCommand(){return Promise.resolve().then(()=>this.run()).then(e=>(e&&e.split(/\r?\n/).forEach(e=>this.stdOut=e),this.result)).catch(e=>{if(e&&e.__type)throw e;return e&&(this.stdErr=e.message||e),this.exitCode=127,this.result})}onInput(e){}set exitCode(e){this.result.exitCode=e}set stdOut(e){this.result.addStdOutLine(e)}set stdErr(e){this.result.addStdErrLine(e)}flush(){this.emit(`flush`,this.result.flush())}}})),T=t(((e,t)=>{var n=w();t.exports=class extends n{constructor(e,t){super(e,t)}}})),E=t(((e,t)=>{var n=T();function r(e){return/^#!\/(sh\.js|bin\/(sh|brsh))/.test(e)}t.exports=class extends n{constructor(e,t,n,r=!1){super(t,n),this.script=e,this.source=r}get captureInput(){return!!(this.sandbox&&this.sandbox.runningCommand&&this.sandbox.runningCommand.captureInput)}onInput(e){this.sandbox&&this.sandbox.onInput(e)}run(){let e=this.context&&this.context.fs||this.fs,t=e&&e.isRealFilesystem?{useRealFilesystem:!0}:{filesystem:e&&e.getRaw()||{},permissions:e&&e.getRawPermissions()||{}};this.sandbox=new globalThis.shell({cwd:e&&e.cwd||`/`,...t,subshell:!0}),this.sandbox.context.source(this.context),Array.isArray(this.arguments)&&(this.arguments.forEach((e,t)=>this.sandbox.context.setVar(String(t+1),e)),this.sandbox.context.setVar(`#`,String(this.arguments.length)),this.sandbox.context.setVar(`@`,this.arguments.join(` `)),this.sandbox.context.setVar(`*`,this.arguments.join(` `))),this.sandbox.on(`stdOut`,e=>{this.stdOut=e,this.flush()}),this.sandbox.on(`stdErr`,e=>{this.stdErr=e,this.flush()}),this._scriptFunctions={};let n=this.script.split(/\r?\n/);if(!r(n[0])){let e=n[0].startsWith(`#!`)?n[0].slice(2).split(/\s/)[0]:n[0];return Promise.reject(`${e}: bad interpreter: No such file or directory`)}let i=this._parseLines(n.slice(1));return this._executeNodes(i).catch(e=>{if(e&&e.__type===`return`)this.sandbox.lastCode=e.code;else if(e&&e.__type===`errexit`)this.sandbox.lastCode=e.code;else if(e&&(e.__type===`break`||e.__type===`continue`))this.stdErr=`${e.__type}: only meaningful in a for or while loop`,this.sandbox.lastCode=1;else return Promise.reject(e)}).then(()=>{this.exitCode=this.sandbox.lastCode,this.source&&this.context.source(this.sandbox.context)})}_accumulateLines(e){let t=[],n=null,r=!1,i=!1,a=!1;for(let o=0;o<e.length;o++){let s=e[o];n===null?n=s:a?n+=s:r||i?n+=`
|
|
4
|
-
`+s:n+=s;let c=0,l=!1,u=!1;for(;c<s.length;){let e=s[c];if(r)e===`'`&&(r=!1),c++;else if(i)e===`\\`&&c+1<s.length?c+=2:e===`\\`&&c+1===s.length?(l=!0,c++):(e===`"`&&(i=!1),c++);else{if(e===`#`&&(c===0||/\s/.test(s[c-1]))){u=!0;break}e===`\\`&&c+1<s.length?c+=2:e===`\\`&&c+1===s.length?(l=!0,c++):e===`'`?(r=!0,c++):(e===`"`&&(i=!0),c++)}}if(!r&&!l&&!u){let e=s.match(/(\\+)\s*$/);e&&e[1].length%2==1&&(l=!0)}a=l,l&&(n=n.replace(/\\\s*$/,``)),!r&&!i&&!l&&(t.push(n),n=null,a=!1)}return n!==null&&t.push(n),t}_parseLines(e){e=this._accumulateLines(e);let t=[],n=0;for(;n<e.length;){let r=e[n].trim();if(!r||r.startsWith(`#`)){n++;continue}if(r.startsWith(`if `)||r===`if`){let r=this._parseIf(e,n);t.push(r.node),n+=r.consumed;continue}if(r.startsWith(`while `)){let r=this._parseWhile(e,n);t.push(r.node),n+=r.consumed;continue}if(r.startsWith(`for `)){let r=this._parseFor(e,n);t.push(r.node),n+=r.consumed;continue}if(r.startsWith(`case `)||r===`case`){let r=this._parseCase(e,n);t.push(r.node),n+=r.consumed;continue}if(/^(?:function\s+[\w\d_]+|[\w\d_]+\s*\(\s*\))\s*(?:\{.*)?$/.test(r)){let r=this._parseFunction(e,n);t.push(r.node),n+=r.consumed;continue}t.push({type:`command`,line:r}),n++}return t}_parseIf(e,t){let n=e=>e.replace(/^(?:if|elif)\s+/,``).replace(/\s*;\s*then\s*$/,``).replace(/\s+then\s*$/,``).trim(),r=[{condition:n(e[t].trim()),bodyLines:[]}],i=[],a=r[0],o=!1,s=1,c=t+1;for(c<e.length&&e[c].trim()===`then`&&c++;c<e.length;){let t=e[c].trim();if((t.startsWith(`if `)||t===`if`)&&s++,t===`fi`&&(s--,s===0)){c++;break}if(s===1&&t.startsWith(`elif `)){let i={condition:n(t),bodyLines:[]};r.push(i),a=i,c++,c<e.length&&e[c].trim()===`then`&&c++;continue}if(s===1&&t===`else`){o=!0,c++;continue}o?i.push(e[c]):a.bodyLines.push(e[c]),c++}return{node:{type:`if`,clauses:r,elseLines:i},consumed:c-t}}_parseWhile(e,t){let n=e[t].trim().replace(/^while\s+/,``).replace(/\s*;\s*do\s*$/,``).replace(/\s+do\s*$/,``).trim(),r=t+1;r<e.length&&e[r].trim()===`do`&&r++;let i=[],a=1;for(;r<e.length;){let t=e[r].trim();if((t.startsWith(`while `)||t.startsWith(`for `))&&a++,t===`done`&&(a--,a===0)){r++;break}i.push(e[r]),r++}return{node:{type:`while`,condition:n,bodyLines:i},consumed:r-t}}_parseFor(e,t){let n=e[t].trim().replace(/\s*;\s*do\s*$/,``).replace(/\s+do\s*$/,``).match(/^for\s+(\w+)\s+in\s+(.+)$/),r=n?n[1]:``,i=n?n[2].trim():``,a=t+1;a<e.length&&e[a].trim()===`do`&&a++;let o=[],s=1;for(;a<e.length;){let t=e[a].trim();if((t.startsWith(`while `)||t.startsWith(`for `))&&s++,t===`done`&&(s--,s===0)){a++;break}o.push(e[a]),a++}return{node:{type:`for`,variable:r,list:i,bodyLines:o},consumed:a-t}}async _executeNodes(e){for(let t of e)await this._executeNode(t)}_executeNode(e){if(e.type===`function`){let t=e.name,n=e.bodyLines,r=this,i=T(),a=class extends i{static get name(){return t}run(){let e=this.arguments.map((e,t)=>({key:String(t+1),prev:r.sandbox.context.getVar(String(t+1))}));this.arguments.forEach((e,t)=>r.sandbox.context.setVar(String(t+1),e));let t=()=>e.forEach(({key:e,prev:t})=>t?r.sandbox.context.setVar(e,t):r.sandbox.context.unsetVar(e));return r._executeFunctionBody(n).then(()=>{t()}).catch(e=>{if(t(),e&&e.__type===`return`){this.exitCode=e.code;return}return Promise.reject(e)})}};return this.sandbox.context.setCommand(a),Promise.resolve()}if(e.type===`command`){if(/^return(\s+\d+)?\s*$/.test(e.line.trim())){let t=e.line.trim().match(/^return\s+(\d+)/),n=t?parseInt(t[1],10):0;return Promise.reject({__type:`return`,code:n})}if(/^break(\s+\d+)?\s*$/.test(e.line.trim())){let t=e.line.trim().match(/^break\s+(\d+)/),n=t?parseInt(t[1],10):1;return Promise.reject({__type:`break`,count:n})}if(/^continue(\s+\d+)?\s*$/.test(e.line.trim())){let t=e.line.trim().match(/^continue\s+(\d+)/),n=t?parseInt(t[1],10):1;return Promise.reject({__type:`continue`,count:n})}return(this.sandbox.context.getVar(`-`)||``).includes(`x`)&&(this.stdErr=`+ ${e.line.trim()}`,this.flush()),this.sandbox.onCommand(e.line,!1).then(()=>{if((this.sandbox.context.getVar(`-`)||``).includes(`e`)&&this.sandbox.lastCode!==0)return Promise.reject({__type:`errexit`,code:this.sandbox.lastCode})})}return e.type===`if`?this._executeIf(e):e.type===`while`?this._executeWhile(e):e.type===`for`?this._executeFor(e):e.type===`case`?this._executeCase(e):Promise.resolve()}async _executeIf(e){for(let t of e.clauses)if(await this.sandbox.onCommand(t.condition,!1),this.sandbox.lastCode===0)return this._executeNodes(this._parseLines(t.bodyLines));if(e.elseLines.length>0)return this._executeNodes(this._parseLines(e.elseLines))}async _executeWhile(e){for(;await this.sandbox.onCommand(e.condition,!1),this.sandbox.lastCode===0;)try{await this._executeNodes(this._parseLines(e.bodyLines))}catch(e){if(e&&e.__type===`break`){if(e.count<=1)break;throw{__type:`break`,count:e.count-1}}if(e&&e.__type===`continue`){if(e.count<=1)continue;throw{__type:`continue`,count:e.count-1}}throw e}}async _executeFor(e){let t=e.list.replace(/\${?([\w\d]+)}?/g,(e,t)=>this.sandbox.context.getVar(t)||``).split(/\s+/).filter(Boolean);for(let n of t){this.sandbox.context.setVar(e.variable,n);try{await this._executeNodes(this._parseLines(e.bodyLines))}catch(e){if(e&&e.__type===`break`){if(e.count<=1)break;throw{__type:`break`,count:e.count-1}}if(e&&e.__type===`continue`){if(e.count<=1)continue;throw{__type:`continue`,count:e.count-1}}throw e}}}_parseFunction(e,t){let n=e[t].trim(),r=n.match(/^function\s+([\w\d_]+)/)||n.match(/^([\w\d_]+)\s*\(/),i=r?r[1]:``,a=t+1;if(!n.includes(`{`)){for(;a<e.length&&!e[a].includes(`{`);)a++;a++}let o=[],s=1;for(;a<e.length;){if(e[a].trim()===`}`){a++;break}let t=(e[a].match(/\{/g)||[]).length,n=(e[a].match(/\}/g)||[]).length;if(s+=t-n,s<=0){a++;break}o.push(e[a]),a++}return{node:{type:`function`,name:i,bodyLines:o},consumed:a-t}}_parseCase(e,t){let n=e[t].trim().match(/^case\s+(.+?)\s+in\s*$/),r=n?n[1]:``,i=t+1,a=[],o=null,s=[];for(;i<e.length;){let t=e[i],n=t.trim();if(i++,!(!n||n.startsWith(`#`))){if(n===`esac`)break;if(o===null){let e=n.match(/^(.+?)\)\s*(.*)$/);if(e){o=e[1].trim();let t=e[2].trim();if(t===`;;`)a.push({pattern:o,bodyLines:[]}),o=null;else if(t.endsWith(`;;`)){let e=t.slice(0,-2).trim();a.push({pattern:o,bodyLines:e?[e]:[]}),o=null}else s=t?[t]:[]}}else n===`;;`?(a.push({pattern:o,bodyLines:s}),o=null,s=[]):n.endsWith(`;;`)?(s.push(n.slice(0,-2).trim()),a.push({pattern:o,bodyLines:s}),o=null,s=[]):s.push(t)}}return o!==null&&a.push({pattern:o,bodyLines:s}),{node:{type:`case`,word:r,clauses:a},consumed:i-t}}_executeFunctionBody(e){return this._executeNodes(this._parseLines(e))}async _executeCase(e){let t=await this.sandbox._replaceVariables(e.word),n=t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t;for(let t of e.clauses)if(this._matchPattern(t.pattern,n))return this._executeNodes(this._parseLines(t.bodyLines))}_matchPattern(e,t){let n=``,r=0;for(;r<e.length;){let t=e[r];if(t===`[`){let t=e.indexOf(`]`,r+1);t===-1?(n+=`\\[`,r++):(n+=e.slice(r,t+1),r=t+1)}else t===`*`?(n+=`.*`,r++):t===`?`?(n+=`.`,r++):/[.+^${}()|\\]/.test(t)?(n+=`\\`+t,r++):(n+=t,r++)}try{return RegExp(`^`+n+`$`).test(t)}catch{return!1}}},t.exports.isKnownInterpreter=r})),D=t(((e,t)=>{y();var n=new Set([`cwd`,`getFileByPath`,`setFileByPath`,`deleteFileByPath`,`exists`,`stat`,`absolutePath`,`getMode`,`setMode`,`isReadable`,`isWritable`,`isExecutable`,`getSize`,`autoComplete`,`isRealFilesystem`,`isSymlink`,`readSymlink`,`createSymlink`]),r=class{isReadable(e){let t=this.getMode(e);return t===null?!1:(t&256)!=0}isWritable(e){let t=this.getMode(e);return t===null?!1:(t&128)!=0}isExecutable(e){let t=this.getMode(e);return t===null?!1:(t&64)!=0}sandbox(){let e=this;return new Proxy(Object.create(null),{get(t,r){if(!n.has(r))return;let i=e[r];return typeof i==`function`?i.bind(e):i},set(){return!1},has(e,t){return n.has(t)}})}_triggerChange(){!this._onChange||this._changeScheduled||(this._changeScheduled=!0,Promise.resolve().then(()=>{this._changeScheduled=!1,typeof this._onChange==`function`&&this._onChange(this.getRaw(),this.getRawPermissions())}))}},i=class extends Uint8Array{constructor(e,t){super(e),Object.defineProperty(this,"mimeType",{value:t,enumerable:!1,configurable:!1,writable:!1})}toString(){if(v!==void 0)return`data:${this.mimeType};base64,${v.from(this).toString(`base64`)}`;let e=``,t=8192;for(let n=0;n<this.length;n+=t)e+=String.fromCharCode(...this.subarray(n,n+t));return`data:${this.mimeType};base64,${btoa(e)}`}},a=class{constructor(e){this.target=e}};t.exports=r,t.exports.BinaryFile=i,t.exports.SymlinkRef=a}));function O(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}function k(){throw Error(`setTimeout has not been defined`)}function A(){throw Error(`clearTimeout has not been defined`)}function j(e){if(R===setTimeout)return setTimeout(e,0);if((R===k||!R)&&setTimeout)return R=setTimeout,setTimeout(e,0);try{return R(e,0)}catch{try{return R.call(null,e,0)}catch{return R.call(this,e,0)}}}function M(e){if(z===clearTimeout)return clearTimeout(e);if((z===A||!z)&&clearTimeout)return z=clearTimeout,clearTimeout(e);try{return z(e)}catch{try{return z.call(null,e)}catch{return z.call(this,e)}}}function N(){!V||!H||(V=!1,H.length?B=H.concat(B):U=-1,B.length&&P())}function P(){if(!V){var e=j(N);V=!0;for(var t=B.length;t;){for(H=B,B=[];++U<t;)H&&H[U].run();U=-1,t=B.length}H=null,V=!1,M(e)}}function F(e,t){this.fun=e,this.array=t}function I(){}var ee,L,R,z,B,V,H,U,W,G,K=e((()=>{ee={exports:{}},L=ee.exports={},(function(){try{R=typeof setTimeout==`function`?setTimeout:k}catch{R=k}try{z=typeof clearTimeout==`function`?clearTimeout:A}catch{z=A}})(),B=[],V=!1,U=-1,L.nextTick=function(e){var t=Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];B.push(new F(e,t)),B.length===1&&!V&&j(P)},F.prototype.run=function(){this.fun.apply(null,this.array)},L.title=`browser`,L.browser=!0,L.env={},L.argv=[],L.version=``,L.versions={},L.on=I,L.addListener=I,L.once=I,L.off=I,L.removeListener=I,L.removeAllListeners=I,L.emit=I,L.prependListener=I,L.prependOnceListener=I,L.listeners=function(e){return[]},L.binding=function(e){throw Error(`process.binding is not supported`)},L.cwd=function(){return`/`},L.chdir=function(e){throw Error(`process.chdir is not supported`)},L.umask=function(){return 0},W=ee.exports,G=O(W)})),te=t(((e,t)=>{var n=w();t.exports=class extends n{get captureInput(){return!0}get interactive(){return!0}get terminalSize(){return this.stdout&&this.stdout.columns&&this.stdout.rows?{cols:parseInt(this.context&&this.context.getVar&&this.context.getVar(`COLUMNS`),10)||this.stdout.columns||80,rows:parseInt(this.context&&this.context.getVar&&this.context.getVar(`LINES`),10)||this.stdout.rows||24}:{cols:parseInt(this.context.getVar(`COLUMNS`),10)||80,rows:parseInt(this.context.getVar(`LINES`),10)||24}}_enterAltScreen(){this._inAltScreen||(this._inAltScreen=!0,this.stdinStream&&this.stdinStream.setRawMode(!0),this.stdout&&this.stdout.write(`\x1B[?1049h\x1B[2J\x1B[H`))}_exitAltScreen(){this._inAltScreen&&(this._inAltScreen=!1,this.stdinStream&&this.stdinStream.setRawMode(!1),this.stdout&&this.stdout.write(`\x1B[?1049l\x1B[?25h`))}runCommand(){return this.interactive&&this._enterAltScreen(),super.runCommand().finally(()=>{this._exitAltScreen()})}}})),q=t(((e,t)=>{y(),K();var{BinaryFile:n,SymlinkRef:r}=D(),i=new Uint8Array([66,82,70,83]),a=2;function o(e){if(!e)return!1;let t=e instanceof Uint8Array?e:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?new Uint8Array(e.buffer||e,e.byteOffset||0,e.byteLength):null;return!t||t.length<12?!1:t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]}function s(e={},t={},n={}){let o=new TextEncoder,s=[],c=0,l=e=>{let t=e instanceof Uint8Array?e:new Uint8Array(e),n=c;return s.push(t),c+=t.byteLength,[n,t.byteLength]},u={},d=(e,t)=>{if(e==null)return null;if(e instanceof r)return{$l:e.target};if(e instanceof Uint8Array||v!==void 0&&v.isBuffer(e)){let n=e instanceof Uint8Array?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=e.mimeType||(t.endsWith(`.wasm`)?`application/wasm`:`application/octet-stream`),[i,a]=l(n);return{$b:[i,a,r]}}if(typeof e==`function`)return n.commandsBundle||(u[t]=e.toString()),{$c:t};if(typeof e==`string`){if(e.startsWith(`data:`)){let t=e.indexOf(`;`),n=e.indexOf(`,`,t);if(t!==-1&&n!==-1&&e.slice(t+1,n)===`base64`){let r=e.slice(5,t),i=e.slice(n+1),a;if(v!==void 0)a=new Uint8Array(v.from(i,`base64`));else{let e=atob(i);a=new Uint8Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t)}let[o,s]=l(a);return{$b:[o,s,r]}}}let[t,n]=l(o.encode(e));return{$t:[t,n]}}if(typeof e==`object`){let n={};for(let r of Object.keys(e)){let i=`${t}/${r}`,a=d(e[r],i);a!==null&&(n[r]=a)}return{$d:n}}return null},f=d(e,``)||{$d:{}},p=null;n.commandsBundle&&typeof n.commandsBundle==`string`&&(p=l(o.encode(n.commandsBundle)));let m={v:a,tree:f,permissions:Object.assign({},t)};p&&(m.commandsSlice=p),Object.keys(u).length>0&&(m.inlineCommands=u);let h=o.encode(JSON.stringify(m)),g=12+h.byteLength+c,_=new Uint8Array(g);_.set(i,0);let y=new DataView(_.buffer,_.byteOffset,_.byteLength);y.setUint32(4,a,!0),y.setUint32(8,h.byteLength,!0),_.set(h,12);let b=12+h.byteLength;for(let e of s)_.set(e,b),b+=e.byteLength;return _}function c(e,t={}){let i=e instanceof Uint8Array?e:new Uint8Array(e.buffer||e,e.byteOffset||0,e.byteLength);if(!o(i))throw Error(`Invalid BRFS binary container (missing BRFS magic header)`);let s=new DataView(i.buffer,i.byteOffset,i.byteLength),c=s.getUint32(4,!0);if(c>a)throw Error(`Unsupported BRFS container version: ${c}`);let l=12+s.getUint32(8,!0);if(l>i.byteLength)throw Error(`Corrupt BRFS binary container (header length exceeds buffer)`);let u=new TextDecoder,d=u.decode(i.subarray(12,l)),f=JSON.parse(d),p=i.subarray(l),m=Object.assign({},t);if(Array.isArray(f.commandsSlice)){let[e,t]=f.commandsSlice,n=u.decode(p.subarray(e,e+t));try{let e=Function(n)();e&&typeof e==`object`&&Object.assign(m,e)}catch{}}let h=e=>{if(!e||typeof e!=`object`)return e;if(`$t`in e){let[t,n]=e.$t;return u.decode(p.subarray(t,t+n))}if(`$b`in e){let[t,r,i]=e.$b;return new n(p.slice(t,t+r).buffer,i||`application/octet-stream`)}if(`$l`in e)return new r(e.$l);if(`$c`in e){let t=e.$c;if(m[t])return m[t];if(f.inlineCommands&&f.inlineCommands[t])try{let e=w(),n=te();return Function(`Command`,`InteractiveCommand`,`return (${f.inlineCommands[t]});`)(e,n)}catch{return null}return null}if(`$d`in e){let t={};for(let[n,r]of Object.entries(e.$d)){let e=h(r);e!==null&&(t[n]=e)}return t}return e};return{filesystem:h(f.tree)||{},permissions:Object.assign({},f.permissions||{})}}function l(e){if(!e)return!1;let t=e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null;return!!(t&&t.byteLength>=2&&t[0]===31&&t[1]===139)}async function u(e){if(typeof DecompressionStream<`u`&&typeof Response<`u`){let t=new DecompressionStream(`gzip`),n=new Blob([e]).stream().pipeThrough(t),r=await new Response(n).arrayBuffer();return new Uint8Array(r)}if(G!==void 0&&typeof G.getBuiltinModule==`function`){let t=G.getBuiltinModule(`zlib`);if(t)return new Uint8Array(t.gunzipSync(v.from(e.buffer,e.byteOffset,e.byteLength)))}throw Error(`Gzip decompression is not supported in this environment`)}function d(e){return e?!!(typeof e==`string`||typeof e.then==`function`||typeof e.arrayBuffer==`function`||l(e)):!1}async function f(e,t={}){if(!e)return{filesystem:{},permissions:t};if(typeof e.then==`function`)return f(await e,t);if(typeof e.arrayBuffer==`function`){let n=await e.arrayBuffer();return f(new Uint8Array(n),t)}if(typeof e==`string`){if(!/^https?:\/\//i.test(e)&&G!==void 0&&typeof G.getBuiltinModule==`function`&&typeof window>`u`)try{let n=G.getBuiltinModule(`fs`);if(n&&n.existsSync(e)){let r=await n.promises.readFile(e);return f(new Uint8Array(r.buffer,r.byteOffset,r.byteLength),t)}}catch{}let n=await fetch(e);if(!n.ok)throw Error(`Failed to load filesystem from ${e}: HTTP ${n.status}`);let r=await n.arrayBuffer();return f(new Uint8Array(r),t)}if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let n=e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(l(n)&&(n=await u(n)),o(n)){let e=c(n);return{filesystem:e.filesystem,permissions:Object.assign({},e.permissions,t)}}let r=new TextDecoder(`utf-8`).decode(n);try{let e=JSON.parse(r);return e&&typeof e==`object`&&e.filesystem&&typeof e.permissions==`object`?{filesystem:e.filesystem,permissions:Object.assign({},e.permissions,t)}:{filesystem:e,permissions:t}}catch{let e=Function(`return `+r)();return e&&typeof e==`object`&&e.filesystem&&typeof e.permissions==`object`?{filesystem:e.filesystem,permissions:Object.assign({},e.permissions,t)}:{filesystem:e||{},permissions:t}}}return typeof e==`object`&&e.filesystem&&typeof e.permissions==`object`?d(e.filesystem)||o(e.filesystem)?f(e.filesystem,Object.assign({},e.permissions,t)):{filesystem:e.filesystem,permissions:Object.assign({},e.permissions,t)}:{filesystem:e,permissions:t}}t.exports={MAGIC:i,FORMAT_VERSION:a,isBinaryContainer:o,isGzipBytes:l,isAsyncFilesystemSource:d,resolveFilesystemSource:f,serializeBinaryFilesystem:s,deserializeBinaryFilesystem:c,FilesystemStorage:class{static async save(e,t=`brsh-rootfs`){let n=e.context?e.context.fs:e,r=s(n.getRaw(),n.getRawPermissions());return typeof indexedDB<`u`&&await this._idbPut(t,r),r}static async load(e=`brsh-rootfs`){if(e instanceof Uint8Array||e instanceof ArrayBuffer||typeof e==`string`&&(/^https?:\/\//i.test(e)||e.endsWith(`.brfs`)))return f(e);if(typeof indexedDB<`u`&&typeof e==`string`){let t=await this._idbGet(e);if(t&&o(t))return c(t)}return null}static async loadOrFetch(e=`brsh-rootfs`,t={}){return await this.load(e)||f(t)}static createAutoSave(e=`brsh-rootfs`,t=null){return(n,r)=>{let i=s(n,r);typeof indexedDB<`u`&&this._idbPut(e,i).catch(()=>{}),typeof t==`function`&&t(i,n,r)}}static _openIdb(){return new Promise((e,t)=>{let n=indexedDB.open(`brsh_fs_storage`,1);n.onupgradeneeded=()=>{n.result.createObjectStore(`snapshots`)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}static async _idbPut(e,t){let n=await this._openIdb();return new Promise((r,i)=>{let a=n.transaction(`snapshots`,`readwrite`);a.objectStore(`snapshots`).put(t,e),a.oncomplete=()=>{n.close(),r()},a.onerror=()=>{n.close(),i(a.error)}})}static async _idbGet(e){let t=await this._openIdb();return new Promise((n,r)=>{let i=t.transaction(`snapshots`,`readonly`).objectStore(`snapshots`).get(e);i.onsuccess=()=>{t.close(),n(i.result||null)},i.onerror=()=>{t.close(),r(i.error)}})}}}})),J=t(((e,t)=>{y();var n=D(),{BinaryFile:r,SymlinkRef:i}=n;function a(e){for(let t of Object.keys(e)){let n=e[t];if(typeof n==`object`&&n&&!(n instanceof Uint8Array)&&!(n instanceof i))a(n);else if(typeof n==`string`&&n.startsWith(`data:`)){let i=n.indexOf(`;`),a=n.indexOf(`,`,i);if(i!==-1&&a!==-1&&n.slice(i+1,a)===`base64`){let o=n.slice(5,i),s=n.slice(a+1),c;if(v!==void 0)c=new Uint8Array(v.from(s,`base64`));else{let e=atob(s);c=new Uint8Array(e.length);for(let t=0;t<e.length;t++)c[t]=e.charCodeAt(t)}e[t]=new r(c.buffer,o)}}}}t.exports=class extends n{constructor(e=`/`,t={},n={},r=null){if(super(),t instanceof Uint8Array||t instanceof ArrayBuffer){let{deserializeBinaryFilesystem:e}=q(),r=e(t);t=r.filesystem,n=Object.assign({},r.permissions,n)}else if(t&&typeof t==`object`&&t.filesystem&&(t.filesystem instanceof Uint8Array||typeof t.filesystem==`object`)&&(n=Object.assign({},t.permissions||{},n),t=t.filesystem,t instanceof Uint8Array||t instanceof ArrayBuffer)){let{deserializeBinaryFilesystem:e}=q(),r=e(t);t=r.filesystem,n=Object.assign({},r.permissions,n)}a(t),this.fileSystem=t,this.permissions=Object.assign({},n),this.cwd=e.endsWith(`/`)?e:e+`/`,this._onChange=r,this._changeScheduled=!1}toBinaryContainer(e={}){let{serializeBinaryFilesystem:t}=q();return t(this.fileSystem,this.permissions,e)}static fromBinaryContainer(e,t={}){let{deserializeBinaryFilesystem:n}=q();return n(e,t)}getFileByPath(e){let t=this._resolveByAbsolutePath(this._pathToAbsolute(e),!0);return t==null||!this.isReadable(e)?null:t}_getFileRaw(e){return this._getFileByAbsolutePath(this._pathToAbsolute(e))}exists(e){return this._resolveByAbsolutePath(this._pathToAbsolute(e),!0)!=null}isSymlink(e){return this._resolveByAbsolutePath(this._pathToAbsolute(e),!1)instanceof i}readSymlink(e){let t=this._resolveByAbsolutePath(this._pathToAbsolute(e),!1);return t instanceof i?t.target:null}createSymlink(e,t){this._setFileRaw(t,new i(e))}stat(e){let t=this._resolveByAbsolutePath(this._pathToAbsolute(e),!1);return t==null?null:t instanceof i?{isDirectory:!1,isFile:!1,isCommand:!1,isBinary:!1,isSymlink:!0}:{isDirectory:t.constructor===Object,isFile:typeof t==`string`||t instanceof Uint8Array,isCommand:typeof t==`function`,isBinary:t instanceof Uint8Array,isSymlink:!1}}_pathToAbsolute(e){return e.startsWith(`./`)&&(e=e.substring(2)),e.startsWith(`/`)||(e=(this.cwd&&this.cwd.endsWith(`/`)?this.cwd:this.cwd?this.cwd+`/`:`/`)+e),this._traverseComplexAbsolutePath(e)}_traverseComplexAbsolutePath(e){let t=e.split(`/`);for(;t.includes(`..`);){let e=t.indexOf(`..`)-1;t.splice(e,2)}return t.join(`/`)}absolutePath(e){return this._pathToAbsolute(e)}setFileByPath(e,t,n=!1){let r=this._pathToAbsolute(e);if(this._getFileByAbsolutePath(r)!=null){if(!this.isWritable(e))throw Error(`Permission denied`)}else{let e=r.split(`/`);e.pop();let t=e.join(`/`)||`/`,n=this.getMode(t);if(n!==null&&!(n&128))throw Error(`Permission denied`)}this._setFileByAbsolutePath(r,t,n),this._triggerChange()}_setFileRaw(e,t,n=!1){let r=this._pathToAbsolute(e);this._setFileByAbsolutePath(r,t,n),this._triggerChange()}_setFileByAbsolutePath(e,t,n=!0){let r=e.split(`/`);r.shift();let a=r.pop(),o=this.fileSystem,s=[];for(let e of r){if(s.push(e),!Object.prototype.hasOwnProperty.call(o,e)){if(!n)throw Error(`${e}: No such file or directory`);o[e]={}}let t=o[e];if(t instanceof i){let n=`/`+s.slice(0,-1).join(`/`),r=t.target.startsWith(`/`)?this._traverseComplexAbsolutePath(t.target):this._traverseComplexAbsolutePath(n+`/`+t.target);if(t=this._resolveByAbsolutePath(r,!0),typeof t!=`object`||!t||t instanceof i)throw Error(`${e}: Not a directory`)}o=t}o[a]=t}_resolveByAbsolutePath(e,t=!0,n=0){if(n>10)return null;let r=e.split(`/`);r.shift(),r.length>0&&r[r.length-1].length<1&&r.pop();let a=this.fileSystem,o=[];for(let e=0;e<r.length;e++){let s=r[e],c=e===r.length-1;if(typeof a!=`object`||!a||a instanceof i||!Object.prototype.hasOwnProperty.call(a,s))return null;if(a=a[s],o.push(s),a instanceof i&&(!c||t)){let e=`/`+o.slice(0,-1).join(`/`),t=a.target.startsWith(`/`)?this._traverseComplexAbsolutePath(a.target):this._traverseComplexAbsolutePath(e+`/`+a.target);if(a=this._resolveByAbsolutePath(t,!0,n+1),a==null)return null}}return a}_getFileByAbsolutePath(e){let t=e.split(`/`);return t.shift(),t[t.length-1].length<1&&t.pop(),t.reduce((e,t)=>typeof e!=`object`||!e||!Object.prototype.hasOwnProperty.call(e,t)?null:e[t],this.fileSystem)}deleteFileByPath(e){let t=this._pathToAbsolute(e),n=t.split(`/`);n.pop();let r=n.join(`/`)||`/`,i=this.getMode(r);if(i!==null&&!(i&128))throw Error(`${e}: Permission denied`);this._deleteByAbsolutePath(t);let a=t+`/`;Object.keys(this.permissions).forEach(e=>{(e===t||e.startsWith(a))&&delete this.permissions[e]}),this._triggerChange()}_deleteByAbsolutePath(e){let t=e.split(`/`);t.shift(),t[t.length-1]===``&&t.pop();let n=t.pop();if(!n)return;let r=this.fileSystem,a=[];for(let e of t){if(a.push(e),!Object.prototype.hasOwnProperty.call(r,e))return;let t=r[e];if(t instanceof i){let e=`/`+a.slice(0,-1).join(`/`),n=t.target.startsWith(`/`)?this._traverseComplexAbsolutePath(t.target):this._traverseComplexAbsolutePath(e+`/`+t.target);if(t=this._resolveByAbsolutePath(n,!0),typeof t!=`object`||!t||t instanceof i)return}r=t}r&&n in r&&delete r[n]}getMode(e){let t=this._pathToAbsolute(e);if(this.permissions[t]!==void 0)return this.permissions[t];let n=this._resolveByAbsolutePath(t,!0);return n==null?null:n.constructor===Object?493:typeof n==`function`?365:420}setMode(e,t){let n=this._pathToAbsolute(e);this.permissions[n]=t,this._triggerChange()}getSize(e){let t=this._pathToAbsolute(e),n=this._resolveByAbsolutePath(t,!0);return n==null?0:n.constructor===Object?JSON.stringify(n).length:n instanceof Uint8Array?n.length:n.toString().length}getRawPermissions(){return Object.assign({},this.permissions)}setCwd(e){this.cwd=this._pathToAbsolute(e.endsWith(`/`)?e:e+`/`)}getRaw(){return this.fileSystem}addFiles(e){Object.entries(e).forEach(([e,t])=>{this._setFileRaw(e,t,!0)})}autoComplete(e,t){let n=this._pathToAbsolute(e).split(`/`),r=n.pop(),i=this._getFileRaw(n.length>1?n.join(`/`):`/`),a=this._getFileRaw(t);if(i&&i.constructor===Object){let t=Object.keys(i).filter(e=>e.startsWith(r));r.length<1&&(t=t.filter(e=>!e.startsWith(`.`)));let n=e.split(`/`);n.pop();let o=i;if(t.length<1&&n.length<1&&a&&(t=Object.keys(a).filter(e=>e.startsWith(r)),o=a),t.length)return{path:n.length?n.join(`/`):null,options:t.map(e=>o[e]&&o[e].constructor===Object?e.concat(`/`):e)}}return null}},t.exports.BinaryFile=r,t.exports.SymlinkRef=i})),Y=t(((e,t)=>{t.exports=null})),ne=t(((e,t)=>{K();function n(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received `+JSON.stringify(e))}function r(e,t){for(var n=``,r=0,i=-1,a=0,o,s=0;s<=e.length;++s){if(s<e.length)o=e.charCodeAt(s);else if(o===47)break;else o=47;if(o===47){if(!(i===s-1||a===1))if(i!==s-1&&a===2){if(n.length<2||r!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var c=n.lastIndexOf(`/`);if(c!==n.length-1){c===-1?(n=``,r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf(`/`)),i=s,a=0;continue}}else if(n.length===2||n.length===1){n=``,r=0,i=s,a=0;continue}}t&&(n.length>0?n+=`/..`:n=`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,s):n=e.slice(i+1,s),r=s-i-1;i=s,a=0}else o===46&&a!==-1?++a:a=-1}return n}function i(e,t){var n=t.dir||t.root,r=t.base||(t.name||``)+(t.ext||``);return n?n===t.root?n+r:n+e+r:r}var a={resolve:function(){for(var e=``,t=!1,i,a=arguments.length-1;a>=-1&&!t;a--){var o;a>=0?o=arguments[a]:(i===void 0&&(i=G.cwd()),o=i),n(o),o.length!==0&&(e=o+`/`+e,t=o.charCodeAt(0)===47)}return e=r(e,!t),t?e.length>0?`/`+e:`/`:e.length>0?e:`.`},normalize:function(e){if(n(e),e.length===0)return`.`;var t=e.charCodeAt(0)===47,i=e.charCodeAt(e.length-1)===47;return e=r(e,!t),e.length===0&&!t&&(e=`.`),e.length>0&&i&&(e+=`/`),t?`/`+e:e},isAbsolute:function(e){return n(e),e.length>0&&e.charCodeAt(0)===47},join:function(){if(arguments.length===0)return`.`;for(var e,t=0;t<arguments.length;++t){var r=arguments[t];n(r),r.length>0&&(e===void 0?e=r:e+=`/`+r)}return e===void 0?`.`:a.normalize(e)},relative:function(e,t){if(n(e),n(t),e===t||(e=a.resolve(e),t=a.resolve(t),e===t))return``;for(var r=1;r<e.length&&e.charCodeAt(r)===47;++r);for(var i=e.length,o=i-r,s=1;s<t.length&&t.charCodeAt(s)===47;++s);for(var c=t.length-s,l=o<c?o:c,u=-1,d=0;d<=l;++d){if(d===l){if(c>l){if(t.charCodeAt(s+d)===47)return t.slice(s+d+1);if(d===0)return t.slice(s+d)}else o>l&&(e.charCodeAt(r+d)===47?u=d:d===0&&(u=0));break}var f=e.charCodeAt(r+d);if(f!==t.charCodeAt(s+d))break;f===47&&(u=d)}var p=``;for(d=r+u+1;d<=i;++d)(d===i||e.charCodeAt(d)===47)&&(p.length===0?p+=`..`:p+=`/..`);return p.length>0?p+t.slice(s+u):(s+=u,t.charCodeAt(s)===47&&++s,t.slice(s))},_makeLong:function(e){return e},dirname:function(e){if(n(e),e.length===0)return`.`;for(var t=e.charCodeAt(0),r=t===47,i=-1,a=!0,o=e.length-1;o>=1;--o)if(t=e.charCodeAt(o),t===47){if(!a){i=o;break}}else a=!1;return i===-1?r?`/`:`.`:r&&i===1?`//`:e.slice(0,i)},basename:function(e,t){if(t!==void 0&&typeof t!=`string`)throw TypeError(`"ext" argument must be a string`);n(e);var r=0,i=-1,a=!0,o;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return``;var s=t.length-1,c=-1;for(o=e.length-1;o>=0;--o){var l=e.charCodeAt(o);if(l===47){if(!a){r=o+1;break}}else c===-1&&(a=!1,c=o+1),s>=0&&(l===t.charCodeAt(s)?--s===-1&&(i=o):(s=-1,i=c))}return r===i?i=c:i===-1&&(i=e.length),e.slice(r,i)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!a){r=o+1;break}}else i===-1&&(a=!1,i=o+1);return i===-1?``:e.slice(r,i)}},extname:function(e){n(e);for(var t=-1,r=0,i=-1,a=!0,o=0,s=e.length-1;s>=0;--s){var c=e.charCodeAt(s);if(c===47){if(!a){r=s+1;break}continue}i===-1&&(a=!1,i=s+1),c===46?t===-1?t=s:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||i===-1||o===0||o===1&&t===i-1&&t===r+1?``:e.slice(t,i)},format:function(e){if(typeof e!=`object`||!e)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof e);return i(`/`,e)},parse:function(e){n(e);var t={root:``,dir:``,base:``,ext:``,name:``};if(e.length===0)return t;var r=e.charCodeAt(0),i=r===47,a;i?(t.root=`/`,a=1):a=0;for(var o=-1,s=0,c=-1,l=!0,u=e.length-1,d=0;u>=a;--u){if(r=e.charCodeAt(u),r===47){if(!l){s=u+1;break}continue}c===-1&&(l=!1,c=u+1),r===46?o===-1?o=u:d!==1&&(d=1):o!==-1&&(d=-1)}return o===-1||c===-1||d===0||d===1&&o===c-1&&o===s+1?c!==-1&&(s===0&&i?t.base=t.name=e.slice(1,c):t.base=t.name=e.slice(s,c)):(s===0&&i?(t.name=e.slice(1,o),t.base=e.slice(1,c)):(t.name=e.slice(s,o),t.base=e.slice(s,c)),t.ext=e.slice(o,c)),s>0?t.dir=e.slice(0,s-1):i&&(t.dir=`/`),t},sep:`/`,delimiter:`:`,win32:null,posix:null};a.posix=a,t.exports=a})),X=t(((e,t)=>{y();var n=E(),{BinaryFile:r}=J(),i=0,a=8,o=20,s=28,c=31,l=44,u=54,d=70,f=0,p=2,m=3,h=4,g=1,_=2,b=4,x=8,S=1,C=class extends n{get name(){return`wasm`}get requiresFilesystem(){return!0}get interactive(){if((this.arguments||[]).some(e=>e===`--help`||e===`-h`||e===`--version`||e===`-V`||e===`-v`))return!1;if(this._isInteractive!==void 0)return!!this._isInteractive;if(this._pkgMeta&&this._pkgMeta.interactive!==void 0)return!!this._pkgMeta.interactive;let e=(this.script||this.name||``).toLowerCase();return e===`nano`||e.endsWith(`/nano`)||e.endsWith(`nano.wasm`)}get captureInput(){return this.interactive}_enterAltScreen(){this._inAltScreen||(this._inAltScreen=!0,this.stdinStream&&typeof this.stdinStream.setRawMode==`function`&&this.stdinStream.setRawMode(!0),this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(`\x1B[?1049h\x1B[2J\x1B[H`))}_exitAltScreen(){this._inAltScreen&&(this._inAltScreen=!1,this.stdinStream&&typeof this.stdinStream.setRawMode==`function`&&this.stdinStream.setRawMode(!1),this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(`\x1B[?1049l\x1B[?25h`))}_keyToBytes(e){if(!e)return null;if(typeof e!=`string`)return e instanceof Uint8Array?e:new Uint8Array([Number(e)&255]);let t=e.match(/^\^([A-Za-z@\[\\\]^_?])$/);if(t){let e=t[1].toUpperCase();return e===`?`?new Uint8Array([127]):new Uint8Array([e.charCodeAt(0)-64])}let n={Enter:`\r`,Return:`\r`,Backspace:``,Tab:` `,Escape:`\x1B`,ArrowUp:`\x1B[A`,ArrowDown:`\x1B[B`,ArrowRight:`\x1B[C`,ArrowLeft:`\x1B[D`,Home:`\x1B[H`,End:`\x1B[F`,PageUp:`\x1B[5~`,PageDown:`\x1B[6~`,Delete:`\x1B[3~`,Insert:`\x1B[2~`};return n[e]?new TextEncoder().encode(n[e]):new TextEncoder().encode(e)}onInput(e){if(!this._handlingStreamData){if(typeof this._externalKeyHandler==`function`){this._externalKeyHandler(e);return}this.stdinStream&&this.stdinStream.isRaw}}runCommand(){return super.runCommand().finally(()=>{this._inAltScreen&&this._exitAltScreen()})}run(){let e=this.script,t=(()=>{try{return Y()}catch{return null}})();return this._loadBytes(e,t).then(({bytes:e,isWat:t})=>t?this._runWat(e):this._runWasm(e)).catch(e=>{this.stdErr=e.message||String(e),this.exitCode=1})}_loadBytes(e,t){let n=this.context&&this.context.fs||this.fs;if(!n)return Promise.reject(Error(`${e}: Filesystem is not available`));if(n.isRealFilesystem&&t)try{let r=t.readFileSync(n.absolutePath(e)),i=new Uint8Array(r);return Promise.resolve({bytes:i,isWat:this._isWat(e,i)})}catch(t){return Promise.reject(Error(`${e}: ${t.message}`))}let r=n.getFileByPath(e);if(r==null)return Promise.reject(Error(`${e}: No such file or directory`));let i=this._contentToBytes(r);return Promise.resolve({bytes:i,isWat:this._isWat(e,i)})}_isWat(e,t){return e.endsWith(`.wat`)?!0:t.length>0&&t[0]===40}_contentToBytes(e){if(e instanceof Uint8Array)return e;if(v!==void 0&&v.isBuffer(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}async _runWat(e){let t=new TextDecoder().decode(e),n,r;try{r=await import(`wabt`)}catch{this.stdErr=`${this.script}: WAT execution requires the 'wabt' package\nInstall it with: npm install wabt`,this.exitCode=1;return}try{let e=r.default??r,{buffer:i}=(typeof e==`function`?await e():e).parseWat(this.script,t,{mutable_globals:!0}).toBinary({});n=new Uint8Array(i)}catch(e){this.stdErr=`${this.script}: WAT compilation error: ${e.message}`,this.exitCode=1;return}return this._runWasm(n)}async _runWasm(e){if(typeof WebAssembly>`u`){this.stdErr=`${this.script}: WebAssembly is not available in this environment`,this.exitCode=1;return}let t={1:``,2:``},n=new TextDecoder,y=new TextEncoder,C=null,w=null,T=!1,E=0,D=null,O=null,k=null,A=null,N=!!(this.interactive&&(this.stdin===void 0||this.stdin===null||this.stdin===this.stdinStream||this.stdin&&this.stdin.isTTY)),P=(e,n)=>{if(N&&(e===1||e===2)){if(e===1&&this.stdout){this.stdout.write(n);return}if(e===2&&this.stderr){this.stderr.write(n);return}}t[e]=(t[e]||``)+n;let r=t[e].split(`
|
|
5
|
-
`);t[e]=r.pop();for(let t of r)e===1?this.stdOut=t:this.stdErr=t},F=()=>{t[1]&&=(N&&this.stdout?this.stdout.write(t[1]):this.stdOut=t[1],``),t[2]&&=(N&&this.stderr?this.stderr.write(t[2]):this.stdErr=t[2],``)},I=[],ee=e=>{if(!(!e||e.length===0)){for(let t=0;t<e.length;t++)I.push(e[t]);if(O){let e=O;O=null,e()}}};A=e=>{this._handlingStreamData=!0;try{ee(typeof e==`string`?y.encode(e):e instanceof Uint8Array?e:v!==void 0&&v.isBuffer(e)?new Uint8Array(e):y.encode(String(e??``)))}finally{this._handlingStreamData=!1}},this._externalKeyHandler=e=>{if(this._handlingStreamData)return;let t=this._keyToBytes(e);t&&ee(t)},N&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,A),N&&this.stdin&&this.stdin!==this.stdinStream&&typeof this.stdin.on==`function`&&this.stdin.on(`data`,A);let L=!N&&typeof this.stdin==`string`?y.encode(this.stdin):!N&&this.stdin instanceof Uint8Array?this.stdin:!N&&v!==void 0&&v.isBuffer(this.stdin)?new Uint8Array(this.stdin):new Uint8Array,R=0,z=this.context&&this.context.fs?this.context.fs:this.fs,B=this.context&&this.context.fs&&this.context.fs.cwd||this.fs&&this.fs.cwd||this.context&&typeof this.context.getVar==`function`&&this.context.getVar(`PWD`)||z&&z.cwd||`/`,V=B.length>1&&B.endsWith(`/`)?B.slice(0,-1):B,H=5,U=new Map([[3,{type:`preopen`,path:`/`,guestName:`/`}],[4,{type:`preopen`,path:V,guestName:`.`}]]),W=e=>{let t=e.split(`/`).filter(Boolean);return t.pop(),`/`+t.join(`/`)},G=(e,t)=>{let n=U.get(e);if(!n||n.type!==`preopen`&&n.type!==`dir`)return null;if(t.startsWith(`/`))return z.absolutePath(t);if(!t||t===`.`)return z.absolutePath(n.path);let r=n.path.endsWith(`/`)?n.path:n.path+`/`,i=z.absolutePath(r+t),a=z.absolutePath(`/`+t);if(n.path!==`/`){if(z.exists(i))return i;if(z.exists(a))return a;let e=z.exists(W(i));return z.exists(W(a))&&!e?a:i}if(z.exists(i))return i;let o=z.absolutePath(t);return z.exists(o)?o:i},K=e=>{if(!(!e||e.type!==`file`||!e.dirty||!z))try{let t=!0;for(let n=0;n<e.bytes.length;n++)if(e.bytes[n]===0){t=!1;break}if(t){let t=n.decode(e.bytes);z.setFileByPath(e.path,t,!0)}else{let t=new Uint8Array(e.bytes.length);t.set(e.bytes),z.setFileByPath(e.path,new r(t.buffer,`application/octet-stream`),!0)}e.dirty=!1}catch{}},te={TERM:`xterm-256color`,COLORTERM:`truecolor`,COLUMNS:String(this.stdout&&this.stdout.columns||this.context&&typeof this.context.getVar==`function`&&this.context.getVar(`COLUMNS`)||80),LINES:String(this.stdout&&this.stdout.rows||this.context&&typeof this.context.getVar==`function`&&this.context.getVar(`LINES`)||24),...this.context&&this.context.vars||{}},q=Object.entries(te).map(([e,t])=>`${e}=${t}`),J=new Proxy({fd_write:(e,t,r,o)=>{if(!C)return a;let s=new DataView(C.buffer);if(e===1||e===2){let a=0;for(let i=0;i<r;i++){let r=s.getUint32(t+i*8,!0),o=s.getUint32(t+i*8+4,!0);o>0&&P(e,n.decode(new Uint8Array(C.buffer,r,o))),a+=o}return s.setUint32(o,a,!0),i}let c=U.get(e);if(!c||c.type!==`file`)return a;let l=0;for(let e=0;e<r;e++){let n=s.getUint32(t+e*8,!0),r=s.getUint32(t+e*8+4,!0);if(r>0){let e=new Uint8Array(C.buffer,n,r),t=c.append?c.bytes.length:c.pos,i=t+r;if(i>c.bytes.length){let e=new Uint8Array(i);e.set(c.bytes),c.bytes=e}c.bytes.set(e,t),c.pos=t+r,c.dirty=!0,l+=r}}return s.setUint32(o,l,!0),i},fd_read:(e,t,n,r)=>{if(!C)return a;let o=new DataView(C.buffer);if(e===0){if(N&&T){if((typeof w?.exports?.asyncify_get_state==`function`?w.exports.asyncify_get_state():0)===2){w.exports.asyncify_stop_rewind();let e=0;for(let r=0;r<n&&I.length>0;r++){let n=o.getUint32(t+r*8,!0),i=o.getUint32(t+r*8+4,!0),a=Math.min(i,I.length),s=I.splice(0,a);new Uint8Array(C.buffer).set(s,n),e+=a}return o.setUint32(r,e,!0),i}if(I.length>0){let e=0;for(let r=0;r<n&&I.length>0;r++){let n=o.getUint32(t+r*8,!0),i=o.getUint32(t+r*8+4,!0),a=Math.min(i,I.length),s=I.splice(0,a);new Uint8Array(C.buffer).set(s,n),e+=a}return o.setUint32(r,e,!0),i}return w.exports.asyncify_start_unwind(E),D=new Promise(e=>{O=e}),o.setUint32(r,0,!0),i}let e=0;for(let r=0;r<n&&R<L.length;r++){let n=o.getUint32(t+r*8,!0),i=o.getUint32(t+r*8+4,!0),a=Math.min(i,L.length-R);new Uint8Array(C.buffer).set(L.slice(R,R+a),n),R+=a,e+=a}return o.setUint32(r,e,!0),i}let s=U.get(e);if(!s||s.type!==`file`)return a;let c=0;for(let e=0;e<n&&s.pos<s.bytes.length;e++){let n=o.getUint32(t+e*8,!0),r=o.getUint32(t+e*8+4,!0),i=Math.min(r,s.bytes.length-s.pos);new Uint8Array(C.buffer).set(s.bytes.subarray(s.pos,s.pos+i),n),s.pos+=i,c+=i}return o.setUint32(r,c,!0),i},fd_seek:(e,t,n,r,o)=>{if(!C)return a;if(e<=2)return d;let c=U.get(e);if(!c||c.type!==`file`)return a;let l,u,f;typeof t==`bigint`?(l=Number(t),u=n,f=r):(l=t,u=r,f=o);let p=c.pos;if(u===0)p=l;else if(u===1)p=c.pos+l;else if(u===2)p=c.bytes.length+l;else return s;return p<0?s:(c.pos=p,f&&new DataView(C.buffer).setBigUint64(f,BigInt(c.pos),!0),i)},fd_tell:(e,t)=>{if(!C)return a;let n=U.get(e);return!n||n.type!==`file`?a:(new DataView(C.buffer).setBigUint64(t,BigInt(n.pos),!0),i)},fd_close:e=>{if(e<=2)return i;let t=U.get(e);return t?(K(t),U.delete(e),i):a},fd_sync:e=>{let t=U.get(e);return t&&K(t),i},fd_datasync:e=>{let t=U.get(e);return t&&K(t),i},fd_prestat_get:(e,t)=>{if(!C)return a;let n=U.get(e);if(!n||n.type!==`preopen`)return a;let r=new DataView(C.buffer),o=y.encode(n.guestName);return r.setUint8(t,0),r.setUint32(t+4,o.length,!0),i},fd_prestat_dir_name:(e,t,n)=>{if(!C)return a;let r=U.get(e);if(!r||r.type!==`preopen`)return a;let o=y.encode(r.guestName);return new Uint8Array(C.buffer,t,Math.min(n,o.length)).set(o.subarray(0,n)),i},fd_fdstat_get:(e,t)=>{if(!C)return a;let n=new DataView(C.buffer),r=f;if(e<=2)r=p;else{let t=U.get(e);if(!t)return a;r=t.type===`preopen`||t.type===`dir`?m:h}for(let e=0;e<24;e++)n.setUint8(t+e,0);return n.setUint8(t,r),n.setBigUint64(t+8,18446744073709551615n,!0),n.setBigUint64(t+16,18446744073709551615n,!0),i},fd_fdstat_set_flags:()=>i,fd_filestat_get:(e,t)=>{if(!C)return a;let n=new DataView(C.buffer);for(let e=0;e<64;e++)n.setUint8(t+e,0);if(e<=2)return n.setUint8(t+16,p),i;let r=U.get(e);if(!r)return a;let o=r.type===`preopen`||r.type===`dir`;return n.setUint8(t+16,o?m:h),n.setBigUint64(t+24,1n,!0),n.setBigUint64(t+32,BigInt(r.bytes?r.bytes.length:0),!0),i},path_open:(e,t,r,s,d,f,p,m,h)=>{if(!C||!z)return a;let v=G(e,n.decode(new Uint8Array(C.buffer,r,s)));if(!v)return a;let w=z.stat(v),T=w!==null;if(d&b&&d&g&&T)return o;if(d&_){if(!T)return l;if(!w.isDirectory)return u;let e=H++;return U.set(e,{type:`dir`,path:v}),new DataView(C.buffer).setUint32(h,e,!0),i}if(T&&w.isDirectory)return c;if(!T&&!(d&g))return l;let E=new Uint8Array,D=!1;if(T&&!(d&x)){let e=z.getFileByPath(v);e!=null&&(E=typeof e==`string`?y.encode(e):new Uint8Array(this._contentToBytes(e)))}else D=!0;let O=H++;return U.set(O,{type:`file`,path:v,bytes:E,pos:m&S?E.length:0,append:!!(m&S),dirty:D}),new DataView(C.buffer).setUint32(h,O,!0),i},path_filestat_get:(e,t,r,o,s)=>{if(!C||!z)return a;let c=G(e,n.decode(new Uint8Array(C.buffer,r,o)));if(!c)return a;let u=z.stat(c);if(!u)return l;let d=new DataView(C.buffer);for(let e=0;e<64;e++)d.setUint8(s+e,0);return d.setUint8(s+16,u.isDirectory?m:h),d.setBigUint64(s+24,1n,!0),d.setBigUint64(s+32,BigInt(z.getSize(c)||0),!0),i},path_create_directory:(e,t,r)=>{if(!C||!z)return a;let o=G(e,n.decode(new Uint8Array(C.buffer,t,r)));if(!o)return a;try{return z.setFileByPath(o,{},!0),i}catch{return s}},path_unlink_file:(e,t,r)=>{if(!C||!z)return a;let o=G(e,n.decode(new Uint8Array(C.buffer,t,r)));if(!o||!z.exists(o))return l;try{return z.deleteFileByPath(o),i}catch{return s}},path_remove_directory:(e,t,r)=>{if(!C||!z)return a;let o=G(e,n.decode(new Uint8Array(C.buffer,t,r)));if(!o||!z.exists(o))return l;try{return z.deleteFileByPath(o),i}catch{return s}},path_rename:(e,t,r,o,c,u)=>{if(!C||!z)return a;let d=n.decode(new Uint8Array(C.buffer,t,r)),f=n.decode(new Uint8Array(C.buffer,c,u)),p=G(e,d),m=G(o,f);if(!p||!m)return a;if(!z.exists(p))return l;for(let e of U.values())e.path===p&&(K(e),e.path=m);try{let e=z.getFileByPath(p);return z.setFileByPath(m,e,!0),z.deleteFileByPath(p),i}catch{return s}},proc_exit:e=>{throw e!==0&&(this.exitCode=e),{_wasmExit:!0,code:e}},args_sizes_get:(e,t)=>{if(!C)return s;let n=[this.script,...this.arguments||[]],r=new DataView(C.buffer);return r.setUint32(e,n.length,!0),r.setUint32(t,n.reduce((e,t)=>e+y.encode(t).length+1,0),!0),i},args_get:(e,t)=>{if(!C)return s;let n=[this.script,...this.arguments||[]],r=new DataView(C.buffer),a=t;for(let t=0;t<n.length;t++){r.setUint32(e+t*4,a,!0);let i=y.encode(n[t]+`\0`);new Uint8Array(C.buffer).set(i,a),a+=i.length}return i},environ_sizes_get:(e,t)=>{if(!C)return s;let n=new DataView(C.buffer);n.setUint32(e,q.length,!0);let r=q.reduce((e,t)=>e+y.encode(t).length+1,0);return n.setUint32(t,r,!0),i},environ_get:(e,t)=>{if(!C)return s;let n=new DataView(C.buffer),r=t;for(let t=0;t<q.length;t++){n.setUint32(e+t*4,r,!0);let i=y.encode(q[t]+`\0`);new Uint8Array(C.buffer).set(i,r),r+=i.length}return i},clock_time_get:(e,t,n)=>{if(C){let e=BigInt(Date.now())*1000000n;new DataView(C.buffer).setBigUint64(n,e,!0)}return i},random_get:(e,t)=>{if(C){let n=new Uint8Array(C.buffer,e,t);for(let e=0;e<t;e++)n[e]=Math.random()*256|0}return i}},{get(e,t){return t in e?e[t]:()=>0}}),Y=e=>{if(!C||!e)return``;try{let t=new DataView(C.buffer).getUint32(e-4,!0),n=new Uint16Array(C.buffer,e,t>>>1);return String.fromCharCode(...n)}catch{return``}},ne={wasi_snapshot_preview1:J,wasi_unstable:J,env:new Proxy({print:(e,t)=>{C&&P(1,n.decode(new Uint8Array(C.buffer,e,t)))},eprint:(e,t)=>{C&&P(2,n.decode(new Uint8Array(C.buffer,e,t)))},log:e=>{P(1,Y(e)+`
|
|
6
|
-
`)},logi:e=>{
|
|
7
|
-
`)},logf:e=>{
|
|
8
|
-
`)},trace:(e,t,...n)=>{let r=t>0?` `+n.slice(0,t).join(`, `):``;
|
|
9
|
-
`),!0);t.usage=i.usage,t.options=i.options}catch{}return t}function
|
|
10
|
-
`),o=r?A(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 M(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(w.has(e))return w.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 w.set(e,i),i}async _runRawWasmBytes(t,n){let r=new C(i,n,this.context);r.script=i,r.arguments=n,r.context=this.context,r.fs=this.fs,r._pkgMeta=e,this.stdin!==void 0&&(r.stdin=this.stdin),await r._runWasm(t);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=>D(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`;O(this.fs,r,t,e)}else this.fs.setFileByPath(r,String(t),!0);if(r.endsWith(`.wasm`)||r.endsWith(`.wat`))try{this.context&&this.context.fs?this.context.fs.setMode(r,493):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){let i=[],a=[],o=new TextEncoder().encode(this.stdin||``),s=0,c=new Set,l={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=>{i.push(String(e))},printErr:e=>{a.push(String(e))},stdin:()=>s<o.length?o[s++]:null,preRun:[e=>{e&&e.FS&&(c=this._syncBrshToEmscriptenFs(e.FS,n))}]},u=this._createIoBridge(n,i,a),d;try{d=t.prototype&&t.prototype.constructor===t&&Object.getOwnPropertyNames(t.prototype).length>1?new t(l,u):await t(l,u)}catch(e){if(e&&typeof e.status==`number`)this.exitCode=e.status;else throw e}if(d&&typeof d==`object`)if(r&&(d.wasmBinary instanceof Uint8Array||d.HEAPU8 instanceof Uint8Array)&&(this._inspectedWasm=j(d.wasmBinary||d.HEAPU8)),typeof d.callMain==`function`){d.FS&&c.size===0&&(c=this._syncBrshToEmscriptenFs(d.FS,n));try{let e=await d.callMain(n);typeof e==`number`&&e!==0&&(this.exitCode=e)}catch(e){e&&typeof e.status==`number`?this.exitCode=e.status:(a.push(e.message||String(e)),this.exitCode=1)}d.FS&&this._syncEmscriptenFsToBrsh(d.FS,n,c)}else if(typeof d.exec==`function`&&typeof d.writeFile==`function`)await this._runVirtualFsInstance(d,n,i,a);else if(typeof d.main==`function`||typeof d.run==`function`){let e=(d.main||d.run).bind(d);await this._invokeCliFunction(e,n,i,a)}else !r&&!isVersion&&typeof d.Database==`function`?this._runSqlJsDatabase(d,n,u,i):(typeof d.stdout==`string`&&d.stdout&&d.stdout.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>i.push(e)),typeof d.stderr==`string`&&d.stderr&&d.stderr.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>a.push(e)),d.error&&a.length===0&&(a.push(d.error.message||String(d.error)),this.exitCode=1),typeof d.exitCode==`number`&&(this.exitCode=d.exitCode));else typeof d==`string`?d.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>i.push(e)):typeof d==`number`&&(this.exitCode=d);i.forEach(e=>{this.stdOut=e}),a.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=D(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&&O(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=D(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(O(this.fs,r,t,e),r.endsWith(`.wasm`)||r.endsWith(`.wat`))try{this.context&&this.context.fs?this.context.fs.setMode(r,493):this.fs.setMode(r,493)}catch{}}}catch{}}}}return a}C.readBytesFromFs=D,C.writeBytesToFs=O,C.loadModule=k,C.extractHelpFromText=A,C.inspectWasmBytes=j,C.formatWasmHelp=M,C.createGenericWasmCommand=N,C.createCommand=N,t.exports=C})),Z=t(((e,t)=>{var n=te(),{createGenericWasmCommand:r}=X(),i=`\x1B[2J\x1B[H`,a=`\x1B[0m`,o=`\x1B[7m`,s=`\x1B[1m`,c=`\x1B[2m`,l=`\x1B[36m`,u=`\x1B[31m`,d=`\x1B[32m`,f=class extends n{get requiresFilesystem(){return!0}get interactive(){return this.shouldBeInteractive()}get captureInput(){return this.shouldBeInteractive()}shouldBeInteractive(){return!!this._dynamicReplActive}getReplTitle(){return this._dynamicReplOpts&&this._dynamicReplOpts.title||`${this.name} interactive shell`}getReplPrompt(){return this._dynamicReplMultiline&&this._dynamicReplOpts&&this._dynamicReplOpts.continuePrompt?this._dynamicReplOpts.continuePrompt:this._dynamicReplOpts&&this._dynamicReplOpts.prompt||`${this.name}> `}getReplWelcome(){return this._dynamicReplOpts&&this._dynamicReplOpts.banner||[`Welcome to ${this.name}. Type .exit or Ctrl+D to quit.`]}async initRepl(){}async evaluateReplLine(e){if(this._dynamicReplOpts&&typeof this._dynamicReplOpts.onEvaluate==`function`){let t=await this._dynamicReplOpts.onEvaluate(e);return{output:Array.isArray(t)?t:t==null?[]:[String(t)]}}return{output:[]}}async cleanupRepl(){this._dynamicReplOpts&&typeof this._dynamicReplOpts.onClose==`function`&&await this._dynamicReplOpts.onClose()}async runNonInteractive(){}startRepl(e={}){return this._dynamicReplActive=!0,this._dynamicReplOpts=e,this._dynamicReplBuffer=``,this._dynamicReplMultiline=!1,typeof this._enterAltScreen==`function`&&this._enterAltScreen(),this._launchInteractiveReplLoop()}run(){return this.shouldBeInteractive()?this._launchInteractiveReplLoop():Promise.resolve(this.runNonInteractive())}_launchInteractiveReplLoop(){return this._replHistory=[],this._replHistoryIdx=null,this._replInput=``,this._replCursor=0,this._replLog=[],this._replBusy=!0,this._replStatus=`Initializing WASM runtime...`,this._scrollOffset=0,this._renderRepl(),new Promise(e=>{this._replResolve=e,Promise.resolve().then(()=>this.initRepl()).then(()=>{this._replBusy=!1,this._replStatus=`^D / .exit: Quit | ^L: Clear | Up/Down: History`;for(let e of this.getReplWelcome())this._appendReplLog(e,`info`);this._renderRepl()}).catch(e=>{this._replBusy=!1,this.stdErr=e.message||String(e),this.exitCode=1,this._exitRepl()})})}_appendReplLog(e,t=`out`){let n=String(e??``).split(/\r?\n/);for(let e of n)this._replLog.push({text:e,type:t});this._scrollOffset=0}streamReplChunk(e,t=`out`){if(!e)return;(this._replLog.length===0||this._replLog[this._replLog.length-1].type!==t||!this._replStreamingActive)&&(this._replLog.push({text:``,type:t}),this._replStreamingActive=!0);let n=this._replLog[this._replLog.length-1],r=(n.text+e).split(/\r?\n/);n.text=r[0];for(let e=1;e<r.length;e++)this._replLog.push({text:r[e],type:t});this._scrollOffset=0,this._renderRepl()}onInput(e){if(this.shouldBeInteractive()){if(e===`^D`||e===`^X`){this._exitRepl();return}if(e===`^C`){this._replInput.length>0||this._dynamicReplBuffer?(this._appendReplLog(`${this.getReplPrompt()}${this._replInput}^C`,`prompt`),this._replInput=``,this._replCursor=0,this._dynamicReplBuffer=``,this._dynamicReplMultiline=!1,this._renderRepl()):this._exitRepl();return}if(!this._replBusy){if(e===`^L`){this._replLog=[],this._scrollOffset=0,this._renderRepl();return}if(e===`Enter`){let e=this._replInput;this._replInput=``,this._replCursor=0,this._replHistoryIdx=null,e.trim()&&this._replHistory.push(e),this._appendReplLog(`${this.getReplPrompt()}${e}`,`prompt`);let t=e.trim();if(this._dynamicReplOpts&&typeof this._dynamicReplOpts.isExitCommand==`function`&&this._dynamicReplOpts.isExitCommand(t)||t===`.exit`||t===`.quit`||t===`\\q`||t===`exit`||t===`quit`||t===`exit()`||t===`quit()`){this._exitRepl();return}if(t===`.clear`||t===`\\! clear`){this._replLog=[],this._renderRepl();return}if(this._dynamicReplOpts&&typeof this._dynamicReplOpts.needsMoreInput==`function`&&(this._dynamicReplBuffer=this._dynamicReplBuffer?`${this._dynamicReplBuffer}\n${e}`:e,this._dynamicReplOpts.needsMoreInput(this._dynamicReplBuffer))){this._dynamicReplMultiline=!0,this._renderRepl();return}let n=this._dynamicReplBuffer||e;this._dynamicReplBuffer=``,this._dynamicReplMultiline=!1,this._replBusy=!0,this._replStatus=`Running...`,this._renderRepl(),Promise.resolve().then(()=>this.evaluateReplLine(n)).then(e=>{if(this._replBusy=!1,this._replStreamingActive=!1,this._replStatus=`^D / .exit: Quit | ^L: Clear | Up/Down: History`,e){if(e.clear&&(this._replLog=[]),!e.streamed)if(Array.isArray(e.output))for(let t of e.output)this._appendReplLog(t,`out`);else typeof e.output==`string`&&e.output.length>0&&this._appendReplLog(e.output,`out`);if(e.error&&this._appendReplLog(e.error,`err`),e.exit){this._exitRepl();return}}this._renderRepl()}).catch(e=>{this._replBusy=!1,this._replStatus=`^D / .exit: Quit | ^L: Clear | Up/Down: History`,this._appendReplLog(`Error: ${e.message||e}`,`err`),this._renderRepl()});return}if(e===`Backspace`){this._replCursor>0&&(this._replInput=this._replInput.slice(0,this._replCursor-1)+this._replInput.slice(this._replCursor),this._replCursor--,this._renderRepl());return}if(e===`^W`){let e=this._replCursor;for(;e>0&&this._replInput[e-1]===` `;)e--;for(;e>0&&this._replInput[e-1]!==` `;)e--;this._replInput=this._replInput.slice(0,e)+this._replInput.slice(this._replCursor),this._replCursor=e,this._renderRepl();return}if(e===`Delete`){this._replCursor<this._replInput.length&&(this._replInput=this._replInput.slice(0,this._replCursor)+this._replInput.slice(this._replCursor+1),this._renderRepl());return}if(e===`ArrowLeft`){this._replCursor>0&&(this._replCursor--,this._renderRepl());return}if(e===`ArrowRight`){this._replCursor<this._replInput.length&&(this._replCursor++,this._renderRepl());return}if(e===`Home`||e===`^A`){this._replCursor=0,this._renderRepl();return}if(e===`End`||e===`^E`){this._replCursor=this._replInput.length,this._renderRepl();return}if(e===`ArrowUp`){if(this._replHistory.length===0)return;this._replHistoryIdx===null?this._replHistoryIdx=this._replHistory.length-1:this._replHistoryIdx>0&&this._replHistoryIdx--,this._replInput=this._replHistory[this._replHistoryIdx],this._replCursor=this._replInput.length,this._renderRepl();return}if(e===`ArrowDown`){if(this._replHistoryIdx===null)return;this._replHistoryIdx<this._replHistory.length-1?(this._replHistoryIdx++,this._replInput=this._replHistory[this._replHistoryIdx]):(this._replHistoryIdx=null,this._replInput=``),this._replCursor=this._replInput.length,this._renderRepl();return}if(e===`PageUp`){let e=Math.max(0,this._replLog.length-5);this._scrollOffset=Math.min(e,this._scrollOffset+5),this._renderRepl();return}if(e===`PageDown`){this._scrollOffset=Math.max(0,this._scrollOffset-5),this._renderRepl();return}e.length===1&&!e.startsWith(`^`)&&(this._replInput=this._replInput.slice(0,this._replCursor)+e+this._replInput.slice(this._replCursor),this._replCursor++,this._renderRepl())}}}_renderRepl(){let{cols:e,rows:t}=this.terminalSize,n=Math.max(3,t-3),r=`${o}${s}${` ${this.getReplTitle()} `.padEnd(e).slice(0,e)}${a}`,f=this._replLog.length,p=Math.max(0,f-this._scrollOffset),m=Math.max(0,p-n),h=this._replLog.slice(m,p),g=[];for(let e=0;e<n;e++){let t=h[e];if(!t){g.push(``);continue}t.type===`prompt`?g.push(`${l}${t.text}${a}`):t.type===`err`?g.push(`${u}${t.text}${a}`):t.type===`info`?g.push(`${c}${t.text}${a}`):g.push(t.text)}let _=this.getReplPrompt(),v=this._replInput.slice(0,this._replCursor),y=this._replCursor<this._replInput.length?this._replInput[this._replCursor]:` `,b=this._replCursor<this._replInput.length?this._replInput.slice(this._replCursor+1):``,x=this._replBusy?`${c}${this._replStatus}${a}`:`${d}${s}${_}${a}${v}${o}${y}${a}${b}`,S=`${o}${` ${this._replStatus} `.padEnd(e).slice(0,e)}${a}`,C=[i+r,...g,x,S].join(`
|
|
1
|
+
"use strict";var Wbt=(function(){var e=(e,t)=>()=>(e&&(t=e(e=0)),t),t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);function n(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function r(e){var t=n(e),r=t[0],i=t[1];return(r+i)*3/4-i}function i(e,t,n){return(t+n)*3/4-n}function a(e){var t,r=n(e),a=r[0],o=r[1],s=new p(i(e,a,o)),c=0,l=o>0?a-4:a,u;for(u=0;u<l;u+=4)t=f[e.charCodeAt(u)]<<18|f[e.charCodeAt(u+1)]<<12|f[e.charCodeAt(u+2)]<<6|f[e.charCodeAt(u+3)],s[c++]=t>>16&255,s[c++]=t>>8&255,s[c++]=t&255;return o===2&&(t=f[e.charCodeAt(u)]<<2|f[e.charCodeAt(u+1)]>>4,s[c++]=t&255),o===1&&(t=f[e.charCodeAt(u)]<<10|f[e.charCodeAt(u+1)]<<4|f[e.charCodeAt(u+2)]>>2,s[c++]=t>>8&255,s[c++]=t&255),s}function o(e){return d[e>>18&63]+d[e>>12&63]+d[e>>6&63]+d[e&63]}function s(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(o(r));return i.join(``)}function c(e){for(var t,n=e.length,r=n%3,i=[],a=16383,o=0,c=n-r;o<c;o+=a)i.push(s(e,o,o+a>c?c:o+a));return r===1?(t=e[n-1],i.push(d[t>>2]+d[t<<4&63]+`==`)):r===2&&(t=(e[n-2]<<8)+e[n-1],i.push(d[t>>10]+d[t>>4&63]+d[t<<2&63]+`=`)),i.join(``)}var l,u,d,f,p,m,h,g,_,v,y=e((()=>{for(l={},u={},u.byteLength=r,u.toByteArray=a,u.fromByteArray=c,d=[],f=[],p=typeof Uint8Array<`u`?Uint8Array:Array,m=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,h=0,g=m.length;h<g;++h)d[h]=m[h],f[m.charCodeAt(h)]=h;f[45]=62,f[95]=63,_={},_.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},_.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128},(function(e){let t=u,n=_,r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=d,e.SlowBuffer=C,e.INSPECT_MAX_BYTES=50;let i=2147483647;e.kMaxLength=i;let{Uint8Array:a,ArrayBuffer:o,SharedArrayBuffer:s}=globalThis;d.TYPED_ARRAY_SUPPORT=c(),!d.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function c(){try{let e=new a(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,a.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(d.prototype,"parent",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.buffer}}),Object.defineProperty(d.prototype,"offset",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.byteOffset}});function l(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);let t=new a(e);return Object.setPrototypeOf(t,d.prototype),t}function d(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return h(e)}return f(e,t,n)}d.poolSize=8192;function f(e,t,n){if(typeof e==`string`)return g(e,t);if(o.isView(e))return y(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if($(e,o)||e&&$(e.buffer,o)||s!==void 0&&($(e,s)||e&&$(e.buffer,s)))return b(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);let r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return d.from(r,t,n);let i=x(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return d.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}d.from=function(e,t,n){return f(e,t,n)},Object.setPrototypeOf(d.prototype,a.prototype),Object.setPrototypeOf(d,a);function p(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function m(e,t,n){return p(e),e<=0||t===void 0?l(e):typeof n==`string`?l(e).fill(t,n):l(e).fill(t)}d.alloc=function(e,t,n){return m(e,t,n)};function h(e){return p(e),l(e<0?0:S(e)|0)}d.allocUnsafe=function(e){return h(e)},d.allocUnsafeSlow=function(e){return h(e)};function g(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!d.isEncoding(t))throw TypeError(`Unknown encoding: `+t);let n=w(e,t)|0,r=l(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function v(e){let t=e.length<0?0:S(e.length)|0,n=l(t);for(let r=0;r<t;r+=1)n[r]=e[r]&255;return n}function y(e){if($(e,a)){let t=new a(e);return b(t.buffer,t.byteOffset,t.byteLength)}return v(e)}function b(e,t,n){if(t<0||e.byteLength<t)throw RangeError(`"offset" is outside of buffer bounds`);if(e.byteLength<t+(n||0))throw RangeError(`"length" is outside of buffer bounds`);let r;return r=t===void 0&&n===void 0?new a(e):n===void 0?new a(e,t):new a(e,t,n),Object.setPrototypeOf(r,d.prototype),r}function x(e){if(d.isBuffer(e)){let t=S(e.length)|0,n=l(t);return n.length===0||e.copy(n,0,0,t),n}if(e.length!==void 0)return typeof e.length!=`number`||ue(e.length)?l(0):v(e);if(e.type===`Buffer`&&Array.isArray(e.data))return v(e.data)}function S(e){if(e>=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function C(e){return+e!=e&&(e=0),d.alloc(+e)}d.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==d.prototype},d.compare=function(e,t){if($(e,a)&&(e=d.from(e,e.offset,e.byteLength)),$(t,a)&&(t=d.from(t,t.offset,t.byteLength)),!d.isBuffer(e)||!d.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},d.isEncoding=function(e){switch(String(e).toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`latin1`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return!0;default:return!1}},d.concat=function(e,t){if(!Array.isArray(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return d.alloc(0);let n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;let r=d.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){let t=e[n];if($(t,a))i+t.length>r.length?(d.isBuffer(t)||(t=d.from(t)),t.copy(r,i)):a.prototype.set.call(r,t,i);else if(d.isBuffer(t))t.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=t.length}return r};function w(e,t){if(d.isBuffer(e))return e.length;if(o.isView(e)||$(e,o))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);let n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let i=!1;for(;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return ae(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return ce(e).length;default:if(i)return r?-1:ae(e).length;t=(``+t).toLowerCase(),i=!0}}d.byteLength=w;function T(e,t,n){let r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return B(this,t,n);case`utf8`:case`utf-8`:return F(this,t,n);case`ascii`:return R(this,t,n);case`latin1`:case`binary`:return z(this,t,n);case`base64`:return P(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return V(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}d.prototype._isBuffer=!0;function E(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}d.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;t<e;t+=2)E(this,t,t+1);return this},d.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let t=0;t<e;t+=4)E(this,t,t+3),E(this,t+1,t+2);return this},d.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let t=0;t<e;t+=8)E(this,t,t+7),E(this,t+1,t+6),E(this,t+2,t+5),E(this,t+3,t+4);return this},d.prototype.toString=function(){let e=this.length;return e===0?``:arguments.length===0?F(this,0,e):T.apply(this,arguments)},d.prototype.toLocaleString=d.prototype.toString,d.prototype.equals=function(e){if(!d.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e?!0:d.compare(this,e)===0},d.prototype.inspect=function(){let t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(d.prototype[r]=d.prototype.inspect),d.prototype.compare=function(e,t,n,r,i){if($(e,a)&&(e=d.from(e,e.offset,e.byteLength)),!d.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;let o=i-r,s=n-t,c=Math.min(o,s),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){o=l[e],s=u[e];break}return o<s?-1:+(s<o)};function D(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,ue(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0)if(i)n=0;else return-1;if(typeof t==`string`&&(t=d.from(t,r)),d.isBuffer(t))return t.length===0?-1:O(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof a.prototype.indexOf==`function`?i?a.prototype.indexOf.call(e,t,n):a.prototype.lastIndexOf.call(e,t,n):O(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function O(e,t,n,r,i){let a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}let l;if(i){let r=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,r===-1?0:l-r)){if(r===-1&&(r=l),l-r+1===s)return r*a}else r!==-1&&(l-=l-r),r=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){let n=!0;for(let r=0;r<s;r++)if(c(e,l+r)!==c(t,r)){n=!1;break}if(n)return l}return-1}d.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},d.prototype.indexOf=function(e,t,n){return D(this,e,t,n,!0)},d.prototype.lastIndexOf=function(e,t,n){return D(this,e,t,n,!1)};function k(e,t,n,r){n=Number(n)||0;let i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;let a=t.length;r>a/2&&(r=a/2);let o;for(o=0;o<r;++o){let r=parseInt(t.substr(o*2,2),16);if(ue(r))return o;e[n+o]=r}return o}function A(e,t,n,r){return le(ae(t,e.length-n),e,n,r)}function j(e,t,n,r){return le(oe(t),e,n,r)}function M(e,t,n,r){return le(ce(t),e,n,r)}function N(e,t,n,r){return le(se(t,e.length-n),e,n,r)}d.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);let i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;let a=!1;for(;;)switch(r){case`hex`:return k(this,e,t,n);case`utf8`:case`utf-8`:return A(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return j(this,e,t,n);case`base64`:return M(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return N(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},d.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function P(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function F(e,t,n){n=Math.min(e.length,n);let r=[],i=t;for(;i<n;){let t=e[i],a=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[i+1],(n&192)==128&&(c=(t&31)<<6|n&63,c>127&&(a=c));break;case 3:n=e[i+1],r=e[i+2],(n&192)==128&&(r&192)==128&&(c=(t&15)<<12|(n&63)<<6|r&63,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[i+1],r=e[i+2],s=e[i+3],(n&192)==128&&(r&192)==128&&(s&192)==128&&(c=(t&15)<<18|(n&63)<<12|(r&63)<<6|s&63,c>65535&&c<1114112&&(a=c))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a),i+=o}return L(r)}let I=4096;function L(e){let t=e.length;if(t<=I)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=I));return n}function R(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function z(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function B(e,t,n){let r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i=``;for(let r=t;r<n;++r)i+=de[e[r]];return i}function V(e,t,n){let r=e.slice(t,n),i=``;for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+r[e+1]*256);return i}d.prototype.slice=function(e,t){let n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);let r=this.subarray(e,t);return Object.setPrototypeOf(r,d.prototype),r};function H(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}d.prototype.readUintLE=d.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||H(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return r},d.prototype.readUintBE=d.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||H(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},d.prototype.readUint8=d.prototype.readUInt8=function(e,t){return e>>>=0,t||H(e,1,this.length),this[e]},d.prototype.readUint16LE=d.prototype.readUInt16LE=function(e,t){return e>>>=0,t||H(e,2,this.length),this[e]|this[e+1]<<8},d.prototype.readUint16BE=d.prototype.readUInt16BE=function(e,t){return e>>>=0,t||H(e,2,this.length),this[e]<<8|this[e+1]},d.prototype.readUint32LE=d.prototype.readUInt32LE=function(e,t){return e>>>=0,t||H(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},d.prototype.readUint32BE=d.prototype.readUInt32BE=function(e,t){return e>>>=0,t||H(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},d.prototype.readBigUInt64LE=fe(function(e){e>>>=0,Z(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&Q(e,this.length-8);let r=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),d.prototype.readBigUInt64BE=fe(function(e){e>>>=0,Z(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&Q(e,this.length-8);let r=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),d.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||H(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},d.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||H(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},d.prototype.readInt8=function(e,t){return e>>>=0,t||H(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},d.prototype.readInt16LE=function(e,t){e>>>=0,t||H(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},d.prototype.readInt16BE=function(e,t){e>>>=0,t||H(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},d.prototype.readInt32LE=function(e,t){return e>>>=0,t||H(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},d.prototype.readInt32BE=function(e,t){return e>>>=0,t||H(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},d.prototype.readBigInt64LE=fe(function(e){e>>>=0,Z(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&Q(e,this.length-8);let r=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)}),d.prototype.readBigInt64BE=fe(function(e){e>>>=0,Z(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&Q(e,this.length-8);let r=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n)}),d.prototype.readFloatLE=function(e,t){return e>>>=0,t||H(e,4,this.length),n.read(this,e,!0,23,4)},d.prototype.readFloatBE=function(e,t){return e>>>=0,t||H(e,4,this.length),n.read(this,e,!1,23,4)},d.prototype.readDoubleLE=function(e,t){return e>>>=0,t||H(e,8,this.length),n.read(this,e,!0,52,8)},d.prototype.readDoubleBE=function(e,t){return e>>>=0,t||H(e,8,this.length),n.read(this,e,!1,52,8)};function U(e,t,n,r,i,a){if(!d.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}d.prototype.writeUintLE=d.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;U(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a<n&&(i*=256);)this[t+a]=e/i&255;return t+n},d.prototype.writeUintBE=d.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;U(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},d.prototype.writeUint8=d.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,1,255,0),this[t]=e&255,t+1},d.prototype.writeUint16LE=d.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},d.prototype.writeUint16BE=d.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},d.prototype.writeUint32LE=d.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},d.prototype.writeUint32BE=d.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function W(e,t,n,r,i){ne(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function G(e,t,n,r,i){ne(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}d.prototype.writeBigUInt64LE=fe(function(e,t=0){return W(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),d.prototype.writeBigUInt64BE=fe(function(e,t=0){return G(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),d.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);U(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i<n&&(a*=256);)e<0&&o===0&&this[t+i-1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},d.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);U(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},d.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},d.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},d.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},d.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},d.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||U(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},d.prototype.writeBigInt64LE=fe(function(e,t=0){return W(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),d.prototype.writeBigInt64BE=fe(function(e,t=0){return G(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function K(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function q(e,t,r,i,a){return t=+t,r>>>=0,a||K(e,t,r,4),n.write(e,t,r,i,23,4),r+4}d.prototype.writeFloatLE=function(e,t,n){return q(this,e,t,!0,n)},d.prototype.writeFloatBE=function(e,t,n){return q(this,e,t,!1,n)};function J(e,t,r,i,a){return t=+t,r>>>=0,a||K(e,t,r,8),n.write(e,t,r,i,52,8),r+8}d.prototype.writeDoubleLE=function(e,t,n){return J(this,e,t,!0,n)},d.prototype.writeDoubleBE=function(e,t,n){return J(this,e,t,!1,n)},d.prototype.copy=function(e,t,n,r){if(!d.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);let i=r-n;return this===e&&typeof a.prototype.copyWithin==`function`?this.copyWithin(t,n,r):a.prototype.set.call(e,this.subarray(n,r),t),i},d.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!d.isEncoding(r))throw TypeError(`Unknown encoding: `+r);if(e.length===1){let t=e.charCodeAt(0);(r===`utf8`&&t<128||r===`latin1`)&&(e=t)}}else typeof e==`number`?e&=255:typeof e==`boolean`&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;let i;if(typeof e==`number`)for(i=t;i<n;++i)this[i]=e;else{let a=d.isBuffer(e)?e:d.from(e,r),o=a.length;if(o===0)throw TypeError(`The value "`+e+`" is invalid for argument "value"`);for(i=0;i<n-t;++i)this[i+t]=a[i%o]}return this};let Y={};function ee(e,t,n){Y[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}ee(`ERR_BUFFER_OUT_OF_BOUNDS`,function(e){return e?`${e} is outside of buffer bounds`:`Attempt to access memory outside buffer bounds`},RangeError),ee(`ERR_INVALID_ARG_TYPE`,function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),ee(`ERR_OUT_OF_RANGE`,function(e,t,n){let r=`The value of "${e}" is out of range.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=X(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=X(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function X(e){let t=``,n=e.length,r=+(e[0]===`-`);for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function te(e,t,n){Z(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&Q(t,e.length-(n+1))}function ne(e,t,n,r,i,a){if(e>n||e<t){let r=typeof t==`bigint`?`n`:``,i;throw i=a>3?t===0||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${(a+1)*8}${r}`:`>= -(2${r} ** ${(a+1)*8-1}${r}) and < 2 ** ${(a+1)*8-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new Y.ERR_OUT_OF_RANGE(`value`,i,e)}te(r,i,a)}function Z(e,t){if(typeof e!=`number`)throw new Y.ERR_INVALID_ARG_TYPE(t,`number`,e)}function Q(e,t,n){throw Math.floor(e)===e?t<0?new Y.ERR_BUFFER_OUT_OF_BOUNDS:new Y.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(Z(e,n),new Y.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}let re=/[^+/0-9A-Za-z-_]/g;function ie(e){if(e=e.split(`=`)[0],e=e.trim().replace(re,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function ae(e,t){t||=1/0;let n,r=e.length,i=null,a=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}else if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function oe(e){let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function se(e,t){let n,r,i,a=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function ce(e){return t.toByteArray(ie(e))}function le(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function $(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function ue(e){return e!==e}let de=(function(){let e=`0123456789abcdef`,t=Array(256);for(let n=0;n<16;++n){let r=n*16;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t})();function fe(e){return typeof BigInt>`u`?pe:e}function pe(){throw Error(`BigInt not supported`)}})(l),v=l.Buffer,l.Blob,l.BlobOptions,l.Buffer,l.File,l.FileOptions,l.INSPECT_MAX_BYTES,l.SlowBuffer,l.TranscodeEncoding,l.atob,l.btoa,l.constants,l.isAscii,l.isUtf8,l.kMaxLength,l.kStringMaxLength,l.resolveObjectURL,l.transcode})),b=t(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function d(e,t,n,r){var i,o,s;if(l(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=u(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function v(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function y(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}x(e,t,a,{once:!0}),t!==`error`&&b(e,i,{once:!0})})}function b(e,t,n){typeof e.on==`function`&&x(e,`error`,t,n)}function x(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),x=t(((e,t)=>{var n=[`out`,`err`];t.exports=class{constructor(e,t){if(!n.includes(e))throw Error(`incorrect std output type`);this.type=e,this.string=t}}})),S=t(((e,t)=>{var n=x();t.exports=class{constructor(e=[],t=0){if(typeof t!=`number`)throw Error(`Command Result ExitCode must be a number`);if(!Array.isArray(e))throw Error(`Command Result be array`);this.std=e,this.exitCode=t}addStdOutLine(e){this.std.push(new n(`out`,e))}addStdErrLine(e){this.std.push(new n(`err`,e))}getStdOutput(){return this.std}getExitCode(){return this.exitCode}flush(){let e=this.std;return this.std=[],e}}})),C=t(((e,t)=>{y();var n=b(),r=n.EventEmitter||n.default||n;function i(e){if(!e)return[];let t=typeof e==`string`?e:e instanceof Uint8Array||v!==void 0&&v.isBuffer(e)?new TextDecoder().decode(e):String(e),n=[],r=0;for(;r<t.length;){let e=t[r],i=t.charCodeAt(r);if(i===27){if(t.charCodeAt(r+1)===127||t.charCodeAt(r+1)===8){n.push(`^W`),r+=2;continue}if(t[r+1]===`[`||t[r+1]===`O`){let e=r+2;for(;e<t.length&&t.charCodeAt(e)>=32&&t.charCodeAt(e)<=63;)e++;if(e<t.length){let i=t.slice(r+2,e+1),a={A:`ArrowUp`,B:`ArrowDown`,C:`ArrowRight`,D:`ArrowLeft`,H:`Home`,F:`End`,"1~":`Home`,"3~":`Delete`,"4~":`End`,"5~":`PageUp`,"6~":`PageDown`,"7~":`Home`,"8~":`End`};a[i]&&n.push(a[i]),r=e+1;continue}}n.push(`Escape`),r++;continue}if(i===13||i===10){n.push(`Enter`),i===13&&t[r+1]===`
|
|
2
|
+
`&&r++,r++;continue}if(i===127||i===8){n.push(`Backspace`),r++;continue}if(i===9){n.push(`Tab`),r++;continue}if(i>=1&&i<=26){n.push(`^`+String.fromCharCode(i+64)),r++;continue}n.push(e),r++}return n}t.exports={TtyStream:class extends r{constructor(e={}){super(),this.isTTY=e.isTTY!==!1,this.readable=!0,this.writable=!0,this.columns=e.columns||80,this.rows=e.rows||24,this.isRaw=!1,this._encoding=null,this._onWrite=e.onWrite||null}write(e,t,n){if(e==null)return!0;typeof this._onWrite==`function`&&this._onWrite(e),this._isPushing=!0;try{this.emit(`data`,this._formatChunk(e))}finally{this._isPushing=!1}return typeof t==`function`?t():typeof n==`function`&&n(),!0}pushData(e){if(e!=null){this._isPushing=!0;try{this.emit(`data`,this._formatChunk(e))}finally{this._isPushing=!1}}}_formatChunk(e){return this._encoding?typeof e==`string`?e:e instanceof Uint8Array||v!==void 0&&v.isBuffer(e)?new TextDecoder().decode(e):String(e):e}setRawMode(e){return this.isRaw=!!e,this}setEncoding(e){return this._encoding=e,this}getWindowSize(){return[this.columns,this.rows]}resize(e,t){this.columns=e,this.rows=t,this.emit(`resize`)}resume(){return this}pause(){return this}pipe(e){return this.on(`data`,t=>e.write(t)),e}unpipe(){return this}end(e,t,n){return e!=null&&this.write(e,typeof t==`string`?t:void 0),this.emit(`end`),typeof t==`function`?t():typeof n==`function`&&n(),this}destroy(){this.removeAllListeners()}toString(){return``}valueOf(){return``}},parseVtKeys:i}})),w=t(((e,t)=>{var n=b(),r=S(),{TtyStream:i,parseVtKeys:a}=C(),o=n.EventEmitter||n.default||n;t.exports=class extends o{constructor(e,t){super(),this.arguments=e,this.result=new r,this.context=t||null;let n=this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`COLUMNS`),10)||80,o=this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`LINES`),10)||24;this.stdinStream=new i({columns:n,rows:o}),this.stdin=this.stdinStream,this.stdout=new i({columns:n,rows:o,onWrite:e=>this.emit(`stdout`,e)}),this.stderr=new i({columns:n,rows:o,onWrite:e=>this.emit(`stderr`,e)}),this._onStdinStreamData=e=>{if(!this.captureInput)return;let t=a(e);for(let e of t)!this.interactive&&!this.stdinStream.isRaw&&(e===`Enter`?this.stdout.write(`\r
|
|
3
|
+
`):e===`Backspace`?this.stdout.write(`\b \b`):e.length===1&&this.stdout.write(e)),this.onInput(e)},this.stdinStream.on(`data`,this._onStdinStreamData)}get name(){return`unnamed`}run(){return Promise.reject(`Command not implemented...`)}runCommand(){return Promise.resolve().then(()=>this.run()).then(e=>(e&&e.split(/\r?\n/).forEach(e=>this.stdOut=e),this.result)).catch(e=>{if(e&&e.__type)throw e;return e&&(this.stdErr=e.message||e),this.exitCode=127,this.result})}onInput(e){}set exitCode(e){this.result.exitCode=e}set stdOut(e){this.result.addStdOutLine(e)}set stdErr(e){this.result.addStdErrLine(e)}flush(){this.emit(`flush`,this.result.flush())}}})),T=t(((e,t)=>{var n=w();t.exports=class extends n{constructor(e,t){super(e,t)}}})),E=t(((e,t)=>{var n=T();function r(e){return/^#!\/(sh\.js|bin\/(sh|brsh))/.test(e)}t.exports=class extends n{constructor(e,t,n,r=!1){super(t,n),this.script=e,this.source=r}get captureInput(){return!!(this.sandbox&&this.sandbox.runningCommand&&this.sandbox.runningCommand.captureInput)}onInput(e){this.sandbox&&this.sandbox.onInput(e)}run(){let e=this.context&&this.context.fs||this.fs,t=e&&e.isRealFilesystem?{useRealFilesystem:!0}:{filesystem:e&&e.getRaw()||{},permissions:e&&e.getRawPermissions()||{}};this.sandbox=new globalThis.shell({cwd:e&&e.cwd||`/`,...t,subshell:!0}),this.sandbox.context.source(this.context),Array.isArray(this.arguments)&&(this.arguments.forEach((e,t)=>this.sandbox.context.setVar(String(t+1),e)),this.sandbox.context.setVar(`#`,String(this.arguments.length)),this.sandbox.context.setVar(`@`,this.arguments.join(` `)),this.sandbox.context.setVar(`*`,this.arguments.join(` `))),this.sandbox.on(`stdOut`,e=>{this.stdOut=e,this.flush()}),this.sandbox.on(`stdErr`,e=>{this.stdErr=e,this.flush()}),this._scriptFunctions={};let n=this.script.split(/\r?\n/);if(!r(n[0])){let e=n[0].startsWith(`#!`)?n[0].slice(2).split(/\s/)[0]:n[0];return Promise.reject(`${e}: bad interpreter: No such file or directory`)}let i=this._parseLines(n.slice(1));return this._executeNodes(i).catch(e=>{if(e&&e.__type===`return`)this.sandbox.lastCode=e.code;else if(e&&e.__type===`errexit`)this.sandbox.lastCode=e.code;else if(e&&(e.__type===`break`||e.__type===`continue`))this.stdErr=`${e.__type}: only meaningful in a for or while loop`,this.sandbox.lastCode=1;else return Promise.reject(e)}).then(()=>{this.exitCode=this.sandbox.lastCode,this.source&&this.context.source(this.sandbox.context)})}_accumulateLines(e){let t=[],n=null,r=!1,i=!1,a=!1;for(let o=0;o<e.length;o++){let s=e[o];n===null?n=s:a?n+=s:r||i?n+=`
|
|
4
|
+
`+s:n+=s;let c=0,l=!1,u=!1;for(;c<s.length;){let e=s[c];if(r)e===`'`&&(r=!1),c++;else if(i)e===`\\`&&c+1<s.length?c+=2:e===`\\`&&c+1===s.length?(l=!0,c++):(e===`"`&&(i=!1),c++);else{if(e===`#`&&(c===0||/\s/.test(s[c-1]))){u=!0;break}e===`\\`&&c+1<s.length?c+=2:e===`\\`&&c+1===s.length?(l=!0,c++):e===`'`?(r=!0,c++):(e===`"`&&(i=!0),c++)}}if(!r&&!l&&!u){let e=s.match(/(\\+)\s*$/);e&&e[1].length%2==1&&(l=!0)}a=l,l&&(n=n.replace(/\\\s*$/,``)),!r&&!i&&!l&&(t.push(n),n=null,a=!1)}return n!==null&&t.push(n),t}_parseLines(e){e=this._accumulateLines(e);let t=[],n=0;for(;n<e.length;){let r=e[n].trim();if(!r||r.startsWith(`#`)){n++;continue}if(r.startsWith(`if `)||r===`if`){let r=this._parseIf(e,n);t.push(r.node),n+=r.consumed;continue}if(r.startsWith(`while `)){let r=this._parseWhile(e,n);t.push(r.node),n+=r.consumed;continue}if(r.startsWith(`for `)){let r=this._parseFor(e,n);t.push(r.node),n+=r.consumed;continue}if(r.startsWith(`case `)||r===`case`){let r=this._parseCase(e,n);t.push(r.node),n+=r.consumed;continue}if(/^(?:function\s+[\w\d_]+|[\w\d_]+\s*\(\s*\))\s*(?:\{.*)?$/.test(r)){let r=this._parseFunction(e,n);t.push(r.node),n+=r.consumed;continue}t.push({type:`command`,line:r}),n++}return t}_parseIf(e,t){let n=e=>e.replace(/^(?:if|elif)\s+/,``).replace(/\s*;\s*then\s*$/,``).replace(/\s+then\s*$/,``).trim(),r=[{condition:n(e[t].trim()),bodyLines:[]}],i=[],a=r[0],o=!1,s=1,c=t+1;for(c<e.length&&e[c].trim()===`then`&&c++;c<e.length;){let t=e[c].trim();if((t.startsWith(`if `)||t===`if`)&&s++,t===`fi`&&(s--,s===0)){c++;break}if(s===1&&t.startsWith(`elif `)){let i={condition:n(t),bodyLines:[]};r.push(i),a=i,c++,c<e.length&&e[c].trim()===`then`&&c++;continue}if(s===1&&t===`else`){o=!0,c++;continue}o?i.push(e[c]):a.bodyLines.push(e[c]),c++}return{node:{type:`if`,clauses:r,elseLines:i},consumed:c-t}}_parseWhile(e,t){let n=e[t].trim().replace(/^while\s+/,``).replace(/\s*;\s*do\s*$/,``).replace(/\s+do\s*$/,``).trim(),r=t+1;r<e.length&&e[r].trim()===`do`&&r++;let i=[],a=1;for(;r<e.length;){let t=e[r].trim();if((t.startsWith(`while `)||t.startsWith(`for `))&&a++,t===`done`&&(a--,a===0)){r++;break}i.push(e[r]),r++}return{node:{type:`while`,condition:n,bodyLines:i},consumed:r-t}}_parseFor(e,t){let n=e[t].trim().replace(/\s*;\s*do\s*$/,``).replace(/\s+do\s*$/,``).match(/^for\s+(\w+)\s+in\s+(.+)$/),r=n?n[1]:``,i=n?n[2].trim():``,a=t+1;a<e.length&&e[a].trim()===`do`&&a++;let o=[],s=1;for(;a<e.length;){let t=e[a].trim();if((t.startsWith(`while `)||t.startsWith(`for `))&&s++,t===`done`&&(s--,s===0)){a++;break}o.push(e[a]),a++}return{node:{type:`for`,variable:r,list:i,bodyLines:o},consumed:a-t}}async _executeNodes(e){for(let t of e)await this._executeNode(t)}_executeNode(e){if(e.type===`function`){let t=e.name,n=e.bodyLines,r=this,i=T(),a=class extends i{static get name(){return t}run(){let e=this.arguments.map((e,t)=>({key:String(t+1),prev:r.sandbox.context.getVar(String(t+1))}));this.arguments.forEach((e,t)=>r.sandbox.context.setVar(String(t+1),e));let t=()=>e.forEach(({key:e,prev:t})=>t?r.sandbox.context.setVar(e,t):r.sandbox.context.unsetVar(e));return r._executeFunctionBody(n).then(()=>{t()}).catch(e=>{if(t(),e&&e.__type===`return`){this.exitCode=e.code;return}return Promise.reject(e)})}};return this.sandbox.context.setCommand(a),Promise.resolve()}if(e.type===`command`){if(/^return(\s+\d+)?\s*$/.test(e.line.trim())){let t=e.line.trim().match(/^return\s+(\d+)/),n=t?parseInt(t[1],10):0;return Promise.reject({__type:`return`,code:n})}if(/^break(\s+\d+)?\s*$/.test(e.line.trim())){let t=e.line.trim().match(/^break\s+(\d+)/),n=t?parseInt(t[1],10):1;return Promise.reject({__type:`break`,count:n})}if(/^continue(\s+\d+)?\s*$/.test(e.line.trim())){let t=e.line.trim().match(/^continue\s+(\d+)/),n=t?parseInt(t[1],10):1;return Promise.reject({__type:`continue`,count:n})}return(this.sandbox.context.getVar(`-`)||``).includes(`x`)&&(this.stdErr=`+ ${e.line.trim()}`,this.flush()),this.sandbox.onCommand(e.line,!1).then(()=>{if((this.sandbox.context.getVar(`-`)||``).includes(`e`)&&this.sandbox.lastCode!==0)return Promise.reject({__type:`errexit`,code:this.sandbox.lastCode})})}return e.type===`if`?this._executeIf(e):e.type===`while`?this._executeWhile(e):e.type===`for`?this._executeFor(e):e.type===`case`?this._executeCase(e):Promise.resolve()}async _executeIf(e){for(let t of e.clauses)if(await this.sandbox.onCommand(t.condition,!1),this.sandbox.lastCode===0)return this._executeNodes(this._parseLines(t.bodyLines));if(e.elseLines.length>0)return this._executeNodes(this._parseLines(e.elseLines))}async _executeWhile(e){for(;await this.sandbox.onCommand(e.condition,!1),this.sandbox.lastCode===0;)try{await this._executeNodes(this._parseLines(e.bodyLines))}catch(e){if(e&&e.__type===`break`){if(e.count<=1)break;throw{__type:`break`,count:e.count-1}}if(e&&e.__type===`continue`){if(e.count<=1)continue;throw{__type:`continue`,count:e.count-1}}throw e}}async _executeFor(e){let t=e.list.replace(/\${?([\w\d]+)}?/g,(e,t)=>this.sandbox.context.getVar(t)||``).split(/\s+/).filter(Boolean);for(let n of t){this.sandbox.context.setVar(e.variable,n);try{await this._executeNodes(this._parseLines(e.bodyLines))}catch(e){if(e&&e.__type===`break`){if(e.count<=1)break;throw{__type:`break`,count:e.count-1}}if(e&&e.__type===`continue`){if(e.count<=1)continue;throw{__type:`continue`,count:e.count-1}}throw e}}}_parseFunction(e,t){let n=e[t].trim(),r=n.match(/^function\s+([\w\d_]+)/)||n.match(/^([\w\d_]+)\s*\(/),i=r?r[1]:``,a=t+1;if(!n.includes(`{`)){for(;a<e.length&&!e[a].includes(`{`);)a++;a++}let o=[],s=1;for(;a<e.length;){if(e[a].trim()===`}`){a++;break}let t=(e[a].match(/\{/g)||[]).length,n=(e[a].match(/\}/g)||[]).length;if(s+=t-n,s<=0){a++;break}o.push(e[a]),a++}return{node:{type:`function`,name:i,bodyLines:o},consumed:a-t}}_parseCase(e,t){let n=e[t].trim().match(/^case\s+(.+?)\s+in\s*$/),r=n?n[1]:``,i=t+1,a=[],o=null,s=[];for(;i<e.length;){let t=e[i],n=t.trim();if(i++,!(!n||n.startsWith(`#`))){if(n===`esac`)break;if(o===null){let e=n.match(/^(.+?)\)\s*(.*)$/);if(e){o=e[1].trim();let t=e[2].trim();if(t===`;;`)a.push({pattern:o,bodyLines:[]}),o=null;else if(t.endsWith(`;;`)){let e=t.slice(0,-2).trim();a.push({pattern:o,bodyLines:e?[e]:[]}),o=null}else s=t?[t]:[]}}else n===`;;`?(a.push({pattern:o,bodyLines:s}),o=null,s=[]):n.endsWith(`;;`)?(s.push(n.slice(0,-2).trim()),a.push({pattern:o,bodyLines:s}),o=null,s=[]):s.push(t)}}return o!==null&&a.push({pattern:o,bodyLines:s}),{node:{type:`case`,word:r,clauses:a},consumed:i-t}}_executeFunctionBody(e){return this._executeNodes(this._parseLines(e))}async _executeCase(e){let t=await this.sandbox._replaceVariables(e.word),n=t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t;for(let t of e.clauses)if(this._matchPattern(t.pattern,n))return this._executeNodes(this._parseLines(t.bodyLines))}_matchPattern(e,t){let n=``,r=0;for(;r<e.length;){let t=e[r];if(t===`[`){let t=e.indexOf(`]`,r+1);t===-1?(n+=`\\[`,r++):(n+=e.slice(r,t+1),r=t+1)}else t===`*`?(n+=`.*`,r++):t===`?`?(n+=`.`,r++):/[.+^${}()|\\]/.test(t)?(n+=`\\`+t,r++):(n+=t,r++)}try{return RegExp(`^`+n+`$`).test(t)}catch{return!1}}},t.exports.isKnownInterpreter=r})),D=t(((e,t)=>{y();var n=new Set([`cwd`,`getFileByPath`,`setFileByPath`,`deleteFileByPath`,`exists`,`stat`,`absolutePath`,`getMode`,`setMode`,`isReadable`,`isWritable`,`isExecutable`,`getSize`,`autoComplete`,`isRealFilesystem`,`isSymlink`,`readSymlink`,`createSymlink`]),r=class{isReadable(e){let t=this.getMode(e);return t===null?!1:(t&256)!=0}isWritable(e){let t=this.getMode(e);return t===null?!1:(t&128)!=0}isExecutable(e){let t=this.getMode(e);return t===null?!1:(t&64)!=0}sandbox(){let e=this;return new Proxy(Object.create(null),{get(t,r){if(!n.has(r))return;let i=e[r];return typeof i==`function`?i.bind(e):i},set(){return!1},has(e,t){return n.has(t)}})}_triggerChange(){!this._onChange||this._changeScheduled||(this._changeScheduled=!0,Promise.resolve().then(()=>{this._changeScheduled=!1,typeof this._onChange==`function`&&this._onChange(this.getRaw(),this.getRawPermissions())}))}},i=class extends Uint8Array{constructor(e,t){super(e),Object.defineProperty(this,"mimeType",{value:t,enumerable:!1,configurable:!1,writable:!1})}toString(){if(v!==void 0)return`data:${this.mimeType};base64,${v.from(this).toString(`base64`)}`;let e=``,t=8192;for(let n=0;n<this.length;n+=t)e+=String.fromCharCode(...this.subarray(n,n+t));return`data:${this.mimeType};base64,${btoa(e)}`}},a=class{constructor(e){this.target=e}};t.exports=r,t.exports.BinaryFile=i,t.exports.SymlinkRef=a}));function O(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}function k(){throw Error(`setTimeout has not been defined`)}function A(){throw Error(`clearTimeout has not been defined`)}function j(e){if(z===setTimeout)return setTimeout(e,0);if((z===k||!z)&&setTimeout)return z=setTimeout,setTimeout(e,0);try{return z(e,0)}catch{try{return z.call(null,e,0)}catch{return z.call(this,e,0)}}}function M(e){if(B===clearTimeout)return clearTimeout(e);if((B===A||!B)&&clearTimeout)return B=clearTimeout,clearTimeout(e);try{return B(e)}catch{try{return B.call(null,e)}catch{return B.call(this,e)}}}function N(){!H||!U||(H=!1,U.length?V=U.concat(V):W=-1,V.length&&P())}function P(){if(!H){var e=j(N);H=!0;for(var t=V.length;t;){for(U=V,V=[];++W<t;)U&&U[W].run();W=-1,t=V.length}U=null,H=!1,M(e)}}function F(e,t){this.fun=e,this.array=t}function I(){}var L,R,z,B,V,H,U,W,G,K,q=e((()=>{L={exports:{}},R=L.exports={},(function(){try{z=typeof setTimeout==`function`?setTimeout:k}catch{z=k}try{B=typeof clearTimeout==`function`?clearTimeout:A}catch{B=A}})(),V=[],H=!1,W=-1,R.nextTick=function(e){var t=Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];V.push(new F(e,t)),V.length===1&&!H&&j(P)},F.prototype.run=function(){this.fun.apply(null,this.array)},R.title=`browser`,R.browser=!0,R.env={},R.argv=[],R.version=``,R.versions={},R.on=I,R.addListener=I,R.once=I,R.off=I,R.removeListener=I,R.removeAllListeners=I,R.emit=I,R.prependListener=I,R.prependOnceListener=I,R.listeners=function(e){return[]},R.binding=function(e){throw Error(`process.binding is not supported`)},R.cwd=function(){return`/`},R.chdir=function(e){throw Error(`process.chdir is not supported`)},R.umask=function(){return 0},G=L.exports,K=O(G)})),J=t(((e,t)=>{var n=w();t.exports=class extends n{get captureInput(){return!0}get interactive(){return!0}get terminalSize(){return this.stdout&&this.stdout.columns&&this.stdout.rows?{cols:parseInt(this.context&&this.context.getVar&&this.context.getVar(`COLUMNS`),10)||this.stdout.columns||80,rows:parseInt(this.context&&this.context.getVar&&this.context.getVar(`LINES`),10)||this.stdout.rows||24}:{cols:parseInt(this.context.getVar(`COLUMNS`),10)||80,rows:parseInt(this.context.getVar(`LINES`),10)||24}}_enterAltScreen(){this._inAltScreen||(this._inAltScreen=!0,this.stdinStream&&this.stdinStream.setRawMode(!0),this.stdout&&this.stdout.write(`\x1B[?1049h\x1B[2J\x1B[H`))}_exitAltScreen(){this._inAltScreen&&(this._inAltScreen=!1,this.stdinStream&&this.stdinStream.setRawMode(!1),this.stdout&&this.stdout.write(`\x1B[?1049l\x1B[?25h`))}runCommand(){return this.interactive&&this._enterAltScreen(),super.runCommand().finally(()=>{this._exitAltScreen()})}}})),Y=t(((e,t)=>{y(),q();var{BinaryFile:n,SymlinkRef:r}=D(),i=new Uint8Array([66,82,70,83]),a=2;function o(e){if(!e)return!1;let t=e instanceof Uint8Array?e:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?new Uint8Array(e.buffer||e,e.byteOffset||0,e.byteLength):null;return!t||t.length<12?!1:t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]}function s(e={},t={},n={}){let o=new TextEncoder,s=[],c=0,l=e=>{let t=e instanceof Uint8Array?e:new Uint8Array(e),n=c;return s.push(t),c+=t.byteLength,[n,t.byteLength]},u={},d=(e,t)=>{if(e==null)return null;if(e instanceof r)return{$l:e.target};if(e instanceof Uint8Array||v!==void 0&&v.isBuffer(e)){let n=e instanceof Uint8Array?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=e.mimeType||(t.endsWith(`.wasm`)?`application/wasm`:`application/octet-stream`),[i,a]=l(n);return{$b:[i,a,r]}}if(typeof e==`function`)return n.commandsBundle||(u[t]=e.toString()),{$c:t};if(typeof e==`string`){if(e.startsWith(`data:`)){let t=e.indexOf(`;`),n=e.indexOf(`,`,t);if(t!==-1&&n!==-1&&e.slice(t+1,n)===`base64`){let r=e.slice(5,t),i=e.slice(n+1),a;if(v!==void 0)a=new Uint8Array(v.from(i,`base64`));else{let e=atob(i);a=new Uint8Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t)}let[o,s]=l(a);return{$b:[o,s,r]}}}let[t,n]=l(o.encode(e));return{$t:[t,n]}}if(typeof e==`object`){let n={};for(let r of Object.keys(e)){let i=`${t}/${r}`,a=d(e[r],i);a!==null&&(n[r]=a)}return{$d:n}}return null},f=d(e,``)||{$d:{}},p=null;n.commandsBundle&&typeof n.commandsBundle==`string`&&(p=l(o.encode(n.commandsBundle)));let m={v:a,tree:f,permissions:Object.assign({},t)};p&&(m.commandsSlice=p),Object.keys(u).length>0&&(m.inlineCommands=u);let h=o.encode(JSON.stringify(m)),g=12+h.byteLength+c,_=new Uint8Array(g);_.set(i,0);let y=new DataView(_.buffer,_.byteOffset,_.byteLength);y.setUint32(4,a,!0),y.setUint32(8,h.byteLength,!0),_.set(h,12);let b=12+h.byteLength;for(let e of s)_.set(e,b),b+=e.byteLength;return _}function c(e,t={}){let i=e instanceof Uint8Array?e:new Uint8Array(e.buffer||e,e.byteOffset||0,e.byteLength);if(!o(i))throw Error(`Invalid BRFS binary container (missing BRFS magic header)`);let s=new DataView(i.buffer,i.byteOffset,i.byteLength),c=s.getUint32(4,!0);if(c>a)throw Error(`Unsupported BRFS container version: ${c}`);let l=12+s.getUint32(8,!0);if(l>i.byteLength)throw Error(`Corrupt BRFS binary container (header length exceeds buffer)`);let u=new TextDecoder,d=u.decode(i.subarray(12,l)),f=JSON.parse(d),p=i.subarray(l),m=Object.assign({},t);if(Array.isArray(f.commandsSlice)){let[e,t]=f.commandsSlice,n=u.decode(p.subarray(e,e+t));try{let e=Function(n)();e&&typeof e==`object`&&Object.assign(m,e)}catch{}}let h=e=>{if(!e||typeof e!=`object`)return e;if(`$t`in e){let[t,n]=e.$t;return u.decode(p.subarray(t,t+n))}if(`$b`in e){let[t,r,i]=e.$b;return new n(p.slice(t,t+r).buffer,i||`application/octet-stream`)}if(`$l`in e)return new r(e.$l);if(`$c`in e){let t=e.$c;if(m[t])return m[t];if(f.inlineCommands&&f.inlineCommands[t])try{let e=w(),n=J();return Function(`Command`,`InteractiveCommand`,`return (${f.inlineCommands[t]});`)(e,n)}catch{return null}return null}if(`$d`in e){let t={};for(let[n,r]of Object.entries(e.$d)){let e=h(r);e!==null&&(t[n]=e)}return t}return e};return{filesystem:h(f.tree)||{},permissions:Object.assign({},f.permissions||{})}}function l(e){if(!e)return!1;let t=e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null;return!!(t&&t.byteLength>=2&&t[0]===31&&t[1]===139)}async function u(e){if(typeof DecompressionStream<`u`&&typeof Response<`u`){let t=new DecompressionStream(`gzip`),n=new Blob([e]).stream().pipeThrough(t),r=await new Response(n).arrayBuffer();return new Uint8Array(r)}if(K!==void 0&&typeof K.getBuiltinModule==`function`){let t=K.getBuiltinModule(`zlib`);if(t)return new Uint8Array(t.gunzipSync(v.from(e.buffer,e.byteOffset,e.byteLength)))}throw Error(`Gzip decompression is not supported in this environment`)}function d(e){return e?!!(typeof e==`string`||typeof e.then==`function`||typeof e.arrayBuffer==`function`||l(e)):!1}async function f(e,t={}){if(!e)return{filesystem:{},permissions:t};if(typeof e.then==`function`)return f(await e,t);if(typeof e.arrayBuffer==`function`){let n=await e.arrayBuffer();return f(new Uint8Array(n),t)}if(typeof e==`string`){if(!/^https?:\/\//i.test(e)&&K!==void 0&&typeof K.getBuiltinModule==`function`&&typeof window>`u`)try{let n=K.getBuiltinModule(`fs`);if(n&&n.existsSync(e)){let r=await n.promises.readFile(e);return f(new Uint8Array(r.buffer,r.byteOffset,r.byteLength),t)}}catch{}let n=await fetch(e);if(!n.ok)throw Error(`Failed to load filesystem from ${e}: HTTP ${n.status}`);let r=await n.arrayBuffer();return f(new Uint8Array(r),t)}if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let n=e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(l(n)&&(n=await u(n)),o(n)){let e=c(n);return{filesystem:e.filesystem,permissions:Object.assign({},e.permissions,t)}}let r=new TextDecoder(`utf-8`).decode(n);try{let e=JSON.parse(r);return e&&typeof e==`object`&&e.filesystem&&typeof e.permissions==`object`?{filesystem:e.filesystem,permissions:Object.assign({},e.permissions,t)}:{filesystem:e,permissions:t}}catch{let e=Function(`return `+r)();return e&&typeof e==`object`&&e.filesystem&&typeof e.permissions==`object`?{filesystem:e.filesystem,permissions:Object.assign({},e.permissions,t)}:{filesystem:e||{},permissions:t}}}return typeof e==`object`&&e.filesystem&&typeof e.permissions==`object`?d(e.filesystem)||o(e.filesystem)?f(e.filesystem,Object.assign({},e.permissions,t)):{filesystem:e.filesystem,permissions:Object.assign({},e.permissions,t)}:{filesystem:e,permissions:t}}t.exports={MAGIC:i,FORMAT_VERSION:a,isBinaryContainer:o,isGzipBytes:l,isAsyncFilesystemSource:d,resolveFilesystemSource:f,serializeBinaryFilesystem:s,deserializeBinaryFilesystem:c,FilesystemStorage:class{static async save(e,t=`brsh-rootfs`){let n=e.context?e.context.fs:e,r=s(n.getRaw(),n.getRawPermissions());return typeof indexedDB<`u`&&await this._idbPut(t,r),r}static async load(e=`brsh-rootfs`){if(e instanceof Uint8Array||e instanceof ArrayBuffer||typeof e==`string`&&(/^https?:\/\//i.test(e)||e.endsWith(`.brfs`)))return f(e);if(typeof indexedDB<`u`&&typeof e==`string`){let t=await this._idbGet(e);if(t&&o(t))return c(t)}return null}static async loadOrFetch(e=`brsh-rootfs`,t={}){return await this.load(e)||f(t)}static createAutoSave(e=`brsh-rootfs`,t=null){return(n,r)=>{let i=s(n,r);typeof indexedDB<`u`&&this._idbPut(e,i).catch(()=>{}),typeof t==`function`&&t(i,n,r)}}static _openIdb(){return new Promise((e,t)=>{let n=indexedDB.open(`brsh_fs_storage`,1);n.onupgradeneeded=()=>{n.result.createObjectStore(`snapshots`)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}static async _idbPut(e,t){let n=await this._openIdb();return new Promise((r,i)=>{let a=n.transaction(`snapshots`,`readwrite`);a.objectStore(`snapshots`).put(t,e),a.oncomplete=()=>{n.close(),r()},a.onerror=()=>{n.close(),i(a.error)}})}static async _idbGet(e){let t=await this._openIdb();return new Promise((n,r)=>{let i=t.transaction(`snapshots`,`readonly`).objectStore(`snapshots`).get(e);i.onsuccess=()=>{t.close(),n(i.result||null)},i.onerror=()=>{t.close(),r(i.error)}})}}}})),ee=t(((e,t)=>{y();var n=D(),{BinaryFile:r,SymlinkRef:i}=n;function a(e){for(let t of Object.keys(e)){let n=e[t];if(typeof n==`object`&&n&&!(n instanceof Uint8Array)&&!(n instanceof i))a(n);else if(typeof n==`string`&&n.startsWith(`data:`)){let i=n.indexOf(`;`),a=n.indexOf(`,`,i);if(i!==-1&&a!==-1&&n.slice(i+1,a)===`base64`){let o=n.slice(5,i),s=n.slice(a+1),c;if(v!==void 0)c=new Uint8Array(v.from(s,`base64`));else{let e=atob(s);c=new Uint8Array(e.length);for(let t=0;t<e.length;t++)c[t]=e.charCodeAt(t)}e[t]=new r(c.buffer,o)}}}}t.exports=class extends n{constructor(e=`/`,t={},n={},r=null){if(super(),t instanceof Uint8Array||t instanceof ArrayBuffer){let{deserializeBinaryFilesystem:e}=Y(),r=e(t);t=r.filesystem,n=Object.assign({},r.permissions,n)}else if(t&&typeof t==`object`&&t.filesystem&&(t.filesystem instanceof Uint8Array||typeof t.filesystem==`object`)&&(n=Object.assign({},t.permissions||{},n),t=t.filesystem,t instanceof Uint8Array||t instanceof ArrayBuffer)){let{deserializeBinaryFilesystem:e}=Y(),r=e(t);t=r.filesystem,n=Object.assign({},r.permissions,n)}a(t),this.fileSystem=t,this.permissions=Object.assign({},n),this.cwd=e.endsWith(`/`)?e:e+`/`,this._onChange=r,this._changeScheduled=!1}toBinaryContainer(e={}){let{serializeBinaryFilesystem:t}=Y();return t(this.fileSystem,this.permissions,e)}static fromBinaryContainer(e,t={}){let{deserializeBinaryFilesystem:n}=Y();return n(e,t)}getFileByPath(e){let t=this._resolveByAbsolutePath(this._pathToAbsolute(e),!0);return t==null||!this.isReadable(e)?null:t}_getFileRaw(e){return this._getFileByAbsolutePath(this._pathToAbsolute(e))}exists(e){return this._resolveByAbsolutePath(this._pathToAbsolute(e),!0)!=null}isSymlink(e){return this._resolveByAbsolutePath(this._pathToAbsolute(e),!1)instanceof i}readSymlink(e){let t=this._resolveByAbsolutePath(this._pathToAbsolute(e),!1);return t instanceof i?t.target:null}createSymlink(e,t){this._setFileRaw(t,new i(e))}stat(e){let t=this._resolveByAbsolutePath(this._pathToAbsolute(e),!1);return t==null?null:t instanceof i?{isDirectory:!1,isFile:!1,isCommand:!1,isBinary:!1,isSymlink:!0}:{isDirectory:t.constructor===Object,isFile:typeof t==`string`||t instanceof Uint8Array,isCommand:typeof t==`function`,isBinary:t instanceof Uint8Array,isSymlink:!1}}_pathToAbsolute(e){return e.startsWith(`./`)&&(e=e.substring(2)),e.startsWith(`/`)||(e=(this.cwd&&this.cwd.endsWith(`/`)?this.cwd:this.cwd?this.cwd+`/`:`/`)+e),this._traverseComplexAbsolutePath(e)}_traverseComplexAbsolutePath(e){let t=e.split(`/`);for(;t.includes(`..`);){let e=t.indexOf(`..`)-1;t.splice(e,2)}return t.join(`/`)}absolutePath(e){return this._pathToAbsolute(e)}setFileByPath(e,t,n=!1){let r=this._pathToAbsolute(e);if(this._getFileByAbsolutePath(r)!=null){if(!this.isWritable(e))throw Error(`Permission denied`)}else{let e=r.split(`/`);e.pop();let t=e.join(`/`)||`/`,n=this.getMode(t);if(n!==null&&!(n&128))throw Error(`Permission denied`)}this._setFileByAbsolutePath(r,t,n),this._triggerChange()}_setFileRaw(e,t,n=!1){let r=this._pathToAbsolute(e);this._setFileByAbsolutePath(r,t,n),this._triggerChange()}_setFileByAbsolutePath(e,t,n=!0){let r=e.split(`/`);r.shift();let a=r.pop(),o=this.fileSystem,s=[];for(let e of r){if(s.push(e),!Object.prototype.hasOwnProperty.call(o,e)){if(!n)throw Error(`${e}: No such file or directory`);o[e]={}}let t=o[e];if(t instanceof i){let n=`/`+s.slice(0,-1).join(`/`),r=t.target.startsWith(`/`)?this._traverseComplexAbsolutePath(t.target):this._traverseComplexAbsolutePath(n+`/`+t.target);if(t=this._resolveByAbsolutePath(r,!0),typeof t!=`object`||!t||t instanceof i)throw Error(`${e}: Not a directory`)}o=t}o[a]=t}_resolveByAbsolutePath(e,t=!0,n=0){if(n>10)return null;let r=e.split(`/`);r.shift(),r.length>0&&r[r.length-1].length<1&&r.pop();let a=this.fileSystem,o=[];for(let e=0;e<r.length;e++){let s=r[e],c=e===r.length-1;if(typeof a!=`object`||!a||a instanceof i||!Object.prototype.hasOwnProperty.call(a,s))return null;if(a=a[s],o.push(s),a instanceof i&&(!c||t)){let e=`/`+o.slice(0,-1).join(`/`),t=a.target.startsWith(`/`)?this._traverseComplexAbsolutePath(a.target):this._traverseComplexAbsolutePath(e+`/`+a.target);if(a=this._resolveByAbsolutePath(t,!0,n+1),a==null)return null}}return a}_getFileByAbsolutePath(e){let t=e.split(`/`);return t.shift(),t[t.length-1].length<1&&t.pop(),t.reduce((e,t)=>typeof e!=`object`||!e||!Object.prototype.hasOwnProperty.call(e,t)?null:e[t],this.fileSystem)}deleteFileByPath(e){let t=this._pathToAbsolute(e),n=t.split(`/`);n.pop();let r=n.join(`/`)||`/`,i=this.getMode(r);if(i!==null&&!(i&128))throw Error(`${e}: Permission denied`);this._deleteByAbsolutePath(t);let a=t+`/`;Object.keys(this.permissions).forEach(e=>{(e===t||e.startsWith(a))&&delete this.permissions[e]}),this._triggerChange()}_deleteByAbsolutePath(e){let t=e.split(`/`);t.shift(),t[t.length-1]===``&&t.pop();let n=t.pop();if(!n)return;let r=this.fileSystem,a=[];for(let e of t){if(a.push(e),!Object.prototype.hasOwnProperty.call(r,e))return;let t=r[e];if(t instanceof i){let e=`/`+a.slice(0,-1).join(`/`),n=t.target.startsWith(`/`)?this._traverseComplexAbsolutePath(t.target):this._traverseComplexAbsolutePath(e+`/`+t.target);if(t=this._resolveByAbsolutePath(n,!0),typeof t!=`object`||!t||t instanceof i)return}r=t}r&&n in r&&delete r[n]}getMode(e){let t=this._pathToAbsolute(e);if(this.permissions[t]!==void 0)return this.permissions[t];let n=this._resolveByAbsolutePath(t,!0);return n==null?null:n.constructor===Object?493:typeof n==`function`?365:420}setMode(e,t){let n=this._pathToAbsolute(e);this.permissions[n]=t,this._triggerChange()}getSize(e){let t=this._pathToAbsolute(e),n=this._resolveByAbsolutePath(t,!0);return n==null?0:n.constructor===Object?JSON.stringify(n).length:n instanceof Uint8Array?n.length:n.toString().length}getRawPermissions(){return Object.assign({},this.permissions)}setCwd(e){this.cwd=this._pathToAbsolute(e.endsWith(`/`)?e:e+`/`)}getRaw(){return this.fileSystem}addFiles(e){Object.entries(e).forEach(([e,t])=>{this._setFileRaw(e,t,!0)})}autoComplete(e,t){let n=this._pathToAbsolute(e).split(`/`),r=n.pop(),i=this._getFileRaw(n.length>1?n.join(`/`):`/`),a=this._getFileRaw(t);if(i&&i.constructor===Object){let t=Object.keys(i).filter(e=>e.startsWith(r));r.length<1&&(t=t.filter(e=>!e.startsWith(`.`)));let n=e.split(`/`);n.pop();let o=i;if(t.length<1&&n.length<1&&a&&(t=Object.keys(a).filter(e=>e.startsWith(r)),o=a),t.length)return{path:n.length?n.join(`/`):null,options:t.map(e=>o[e]&&o[e].constructor===Object?e.concat(`/`):e)}}return null}},t.exports.BinaryFile=r,t.exports.SymlinkRef=i})),X=t(((e,t)=>{t.exports=null})),te=t(((e,t)=>{q();function n(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received `+JSON.stringify(e))}function r(e,t){for(var n=``,r=0,i=-1,a=0,o,s=0;s<=e.length;++s){if(s<e.length)o=e.charCodeAt(s);else if(o===47)break;else o=47;if(o===47){if(!(i===s-1||a===1))if(i!==s-1&&a===2){if(n.length<2||r!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var c=n.lastIndexOf(`/`);if(c!==n.length-1){c===-1?(n=``,r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf(`/`)),i=s,a=0;continue}}else if(n.length===2||n.length===1){n=``,r=0,i=s,a=0;continue}}t&&(n.length>0?n+=`/..`:n=`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,s):n=e.slice(i+1,s),r=s-i-1;i=s,a=0}else o===46&&a!==-1?++a:a=-1}return n}function i(e,t){var n=t.dir||t.root,r=t.base||(t.name||``)+(t.ext||``);return n?n===t.root?n+r:n+e+r:r}var a={resolve:function(){for(var e=``,t=!1,i,a=arguments.length-1;a>=-1&&!t;a--){var o;a>=0?o=arguments[a]:(i===void 0&&(i=K.cwd()),o=i),n(o),o.length!==0&&(e=o+`/`+e,t=o.charCodeAt(0)===47)}return e=r(e,!t),t?e.length>0?`/`+e:`/`:e.length>0?e:`.`},normalize:function(e){if(n(e),e.length===0)return`.`;var t=e.charCodeAt(0)===47,i=e.charCodeAt(e.length-1)===47;return e=r(e,!t),e.length===0&&!t&&(e=`.`),e.length>0&&i&&(e+=`/`),t?`/`+e:e},isAbsolute:function(e){return n(e),e.length>0&&e.charCodeAt(0)===47},join:function(){if(arguments.length===0)return`.`;for(var e,t=0;t<arguments.length;++t){var r=arguments[t];n(r),r.length>0&&(e===void 0?e=r:e+=`/`+r)}return e===void 0?`.`:a.normalize(e)},relative:function(e,t){if(n(e),n(t),e===t||(e=a.resolve(e),t=a.resolve(t),e===t))return``;for(var r=1;r<e.length&&e.charCodeAt(r)===47;++r);for(var i=e.length,o=i-r,s=1;s<t.length&&t.charCodeAt(s)===47;++s);for(var c=t.length-s,l=o<c?o:c,u=-1,d=0;d<=l;++d){if(d===l){if(c>l){if(t.charCodeAt(s+d)===47)return t.slice(s+d+1);if(d===0)return t.slice(s+d)}else o>l&&(e.charCodeAt(r+d)===47?u=d:d===0&&(u=0));break}var f=e.charCodeAt(r+d);if(f!==t.charCodeAt(s+d))break;f===47&&(u=d)}var p=``;for(d=r+u+1;d<=i;++d)(d===i||e.charCodeAt(d)===47)&&(p.length===0?p+=`..`:p+=`/..`);return p.length>0?p+t.slice(s+u):(s+=u,t.charCodeAt(s)===47&&++s,t.slice(s))},_makeLong:function(e){return e},dirname:function(e){if(n(e),e.length===0)return`.`;for(var t=e.charCodeAt(0),r=t===47,i=-1,a=!0,o=e.length-1;o>=1;--o)if(t=e.charCodeAt(o),t===47){if(!a){i=o;break}}else a=!1;return i===-1?r?`/`:`.`:r&&i===1?`//`:e.slice(0,i)},basename:function(e,t){if(t!==void 0&&typeof t!=`string`)throw TypeError(`"ext" argument must be a string`);n(e);var r=0,i=-1,a=!0,o;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return``;var s=t.length-1,c=-1;for(o=e.length-1;o>=0;--o){var l=e.charCodeAt(o);if(l===47){if(!a){r=o+1;break}}else c===-1&&(a=!1,c=o+1),s>=0&&(l===t.charCodeAt(s)?--s===-1&&(i=o):(s=-1,i=c))}return r===i?i=c:i===-1&&(i=e.length),e.slice(r,i)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!a){r=o+1;break}}else i===-1&&(a=!1,i=o+1);return i===-1?``:e.slice(r,i)}},extname:function(e){n(e);for(var t=-1,r=0,i=-1,a=!0,o=0,s=e.length-1;s>=0;--s){var c=e.charCodeAt(s);if(c===47){if(!a){r=s+1;break}continue}i===-1&&(a=!1,i=s+1),c===46?t===-1?t=s:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||i===-1||o===0||o===1&&t===i-1&&t===r+1?``:e.slice(t,i)},format:function(e){if(typeof e!=`object`||!e)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof e);return i(`/`,e)},parse:function(e){n(e);var t={root:``,dir:``,base:``,ext:``,name:``};if(e.length===0)return t;var r=e.charCodeAt(0),i=r===47,a;i?(t.root=`/`,a=1):a=0;for(var o=-1,s=0,c=-1,l=!0,u=e.length-1,d=0;u>=a;--u){if(r=e.charCodeAt(u),r===47){if(!l){s=u+1;break}continue}c===-1&&(l=!1,c=u+1),r===46?o===-1?o=u:d!==1&&(d=1):o!==-1&&(d=-1)}return o===-1||c===-1||d===0||d===1&&o===c-1&&o===s+1?c!==-1&&(s===0&&i?t.base=t.name=e.slice(1,c):t.base=t.name=e.slice(s,c)):(s===0&&i?(t.name=e.slice(1,o),t.base=e.slice(1,c)):(t.name=e.slice(s,o),t.base=e.slice(s,c)),t.ext=e.slice(o,c)),s>0?t.dir=e.slice(0,s-1):i&&(t.dir=`/`),t},sep:`/`,delimiter:`:`,win32:null,posix:null};a.posix=a,t.exports=a})),ne=t(((e,t)=>{y();var n=E(),{BinaryFile:r}=ee(),i=0,a=6,o=8,s=20,c=28,l=31,u=44,d=54,f=70,p=0,m=2,h=3,g=4,_=1,b=2,x=4,S=8,C=1,w=4,D=class extends n{get name(){return`wasm`}get requiresFilesystem(){return!0}get interactive(){if((this.arguments||[]).some(e=>e===`--help`||e===`-h`||e===`--version`||e===`-V`||e===`-v`))return!1;if(this._isInteractive!==void 0)return!!this._isInteractive;if(this._pkgMeta&&this._pkgMeta.interactive!==void 0)return!!this._pkgMeta.interactive;let e=(this.script||this.name||``).toLowerCase();return e===`nano`||e.endsWith(`/nano`)||e.endsWith(`nano.wasm`)}get captureInput(){return this.interactive}_enterAltScreen(){this._inAltScreen||(this._inAltScreen=!0,this.stdinStream&&typeof this.stdinStream.setRawMode==`function`&&this.stdinStream.setRawMode(!0),this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(`\x1B[?1049h\x1B[2J\x1B[H`))}_exitAltScreen(){this._inAltScreen&&(this._inAltScreen=!1,this.stdinStream&&typeof this.stdinStream.setRawMode==`function`&&this.stdinStream.setRawMode(!1),this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(`\x1B[?1049l\x1B[?25h`))}_keyToBytes(e){if(!e)return null;if(typeof e!=`string`)return e instanceof Uint8Array?e:new Uint8Array([Number(e)&255]);let t=e.match(/^\^([A-Za-z@\[\\\]^_?])$/);if(t){let e=t[1].toUpperCase();return e===`?`?new Uint8Array([127]):new Uint8Array([e.charCodeAt(0)-64])}let n={Enter:`\r`,Return:`\r`,Backspace:``,Tab:` `,Escape:`\x1B`,ArrowUp:`\x1B[A`,ArrowDown:`\x1B[B`,ArrowRight:`\x1B[C`,ArrowLeft:`\x1B[D`,Home:`\x1B[H`,End:`\x1B[F`,PageUp:`\x1B[5~`,PageDown:`\x1B[6~`,Delete:`\x1B[3~`,Insert:`\x1B[2~`};return n[e]?new TextEncoder().encode(n[e]):new TextEncoder().encode(e)}onInput(e){if(!this._handlingStreamData&&!(this.stdinStream&&this.stdinStream._isPushing)){if(typeof this._externalKeyHandler==`function`){this._externalKeyHandler(e);return}this.stdinStream&&this.stdinStream.isRaw}}runCommand(){return super.runCommand().finally(()=>{this._inAltScreen&&this._exitAltScreen()})}run(){let e=this.script,t=(()=>{try{return X()}catch{return null}})();return this._loadBytes(e,t).then(({bytes:e,isWat:t})=>t?this._runWat(e):this._runWasm(e)).catch(e=>{this.stdErr=e.message||String(e),this.exitCode=1})}_loadBytes(e,t){let n=this.context&&this.context.fs||this.fs;if(!n)return Promise.reject(Error(`${e}: Filesystem is not available`));if(n.isRealFilesystem&&t)try{let r=t.readFileSync(n.absolutePath(e)),i=new Uint8Array(r);return Promise.resolve({bytes:i,isWat:this._isWat(e,i)})}catch(t){return Promise.reject(Error(`${e}: ${t.message}`))}let r=n.getFileByPath(e);if(r==null)return Promise.reject(Error(`${e}: No such file or directory`));let i=this._contentToBytes(r);return Promise.resolve({bytes:i,isWat:this._isWat(e,i)})}_isWat(e,t){return e.endsWith(`.wat`)?!0:t.length>0&&t[0]===40}_contentToBytes(e){if(e instanceof Uint8Array)return e;if(v!==void 0&&v.isBuffer(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}async _runWat(e){let t=new TextDecoder().decode(e),n,r;try{r=await import(`wabt`)}catch{this.stdErr=`${this.script}: WAT execution requires the 'wabt' package\nInstall it with: npm install wabt`,this.exitCode=1;return}try{let e=r.default??r,{buffer:i}=(typeof e==`function`?await e():e).parseWat(this.script,t,{mutable_globals:!0}).toBinary({});n=new Uint8Array(i)}catch(e){this.stdErr=`${this.script}: WAT compilation error: ${e.message}`,this.exitCode=1;return}return this._runWasm(n)}async _runWasm(e){if(typeof WebAssembly>`u`){this.stdErr=`${this.script}: WebAssembly is not available in this environment`,this.exitCode=1;return}let t={1:``,2:``},n=new TextDecoder,y=new TextEncoder,T=null,E=null,D=!1,O=0,k=null,A=null,j=null,M=null,F=this.stdin===void 0||this.stdin===null||this.stdin===this.stdinStream||this.stdin&&this.stdin.isTTY,I=!!(this.interactive&&F),L=()=>{I||!F||(I=!0,this._isInteractive=!0,t[1]&&=(this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(t[1]),``),t[2]&&=(this.stderr&&typeof this.stderr.write==`function`&&this.stderr.write(t[2]),``),this.stdinStream&&typeof this.stdinStream.setRawMode==`function`&&this.stdinStream.setRawMode(!0))},R=(e,n)=>{if(I&&(e===1||e===2)){if(e===1&&this.stdout){this.stdout.write(n);return}if(e===2&&this.stderr){this.stderr.write(n);return}}t[e]=(t[e]||``)+n;let r=t[e].split(`
|
|
5
|
+
`);t[e]=r.pop();for(let t of r)e===1?this.stdOut=t:this.stdErr=t},z=()=>{t[1]&&=(I&&this.stdout?this.stdout.write(t[1]):this.stdOut=t[1],``),t[2]&&=(I&&this.stderr?this.stderr.write(t[2]):this.stdErr=t[2],``)},B=[],V=e=>{if(!(!e||e.length===0)){for(let t=0;t<e.length;t++)B.push(e[t]);if(A){let e=A;A=null,e()}}};M=e=>{this._handlingStreamData=!0;try{V(typeof e==`string`?y.encode(e):e instanceof Uint8Array?e:v!==void 0&&v.isBuffer(e)?new Uint8Array(e):y.encode(String(e??``)))}finally{this._handlingStreamData=!1}},this._externalKeyHandler=e=>{if(this._handlingStreamData)return;let t=this._keyToBytes(e);t&&V(t)},this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`data`,this._onStdinStreamData),F&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,M),F&&this.stdin&&this.stdin!==this.stdinStream&&typeof this.stdin.on==`function`&&this.stdin.on(`data`,M);let H=!F&&typeof this.stdin==`string`?y.encode(this.stdin):!F&&this.stdin instanceof Uint8Array?this.stdin:!F&&v!==void 0&&v.isBuffer(this.stdin)?new Uint8Array(this.stdin):new Uint8Array,U=0,W=this.context&&this.context.fs?this.context.fs:this.fs,G=this.context&&this.context.fs&&this.context.fs.cwd||this.fs&&this.fs.cwd||this.context&&typeof this.context.getVar==`function`&&this.context.getVar(`PWD`)||W&&W.cwd||`/`,K=G.length>1&&G.endsWith(`/`)?G.slice(0,-1):G,q=5,J=new Map([[3,{type:`preopen`,path:`/`,guestName:`/`}],[4,{type:`preopen`,path:K,guestName:`.`}]]),Y=new Map([[0,0],[1,0],[2,0]]),ee=e=>{let t=e.split(`/`).filter(Boolean);return t.pop(),`/`+t.join(`/`)},X=(e,t)=>{let n=J.get(e);if(!n||n.type!==`preopen`&&n.type!==`dir`)return null;if(t.startsWith(`/`))return W.absolutePath(t);if(!t||t===`.`)return W.absolutePath(n.path);let r=n.path.endsWith(`/`)?n.path:n.path+`/`,i=W.absolutePath(r+t),a=W.absolutePath(`/`+t);if(n.path!==`/`){if(W.exists(i))return i;if(W.exists(a))return a;let e=W.exists(ee(i));return W.exists(ee(a))&&!e?a:i}if(W.exists(i))return i;let o=W.absolutePath(t);return W.exists(o)?o:i},te=e=>{if(!(!e||e.type!==`file`||!e.dirty||!W))try{let t=!0;for(let n=0;n<e.bytes.length;n++)if(e.bytes[n]===0){t=!1;break}if(t){let t=n.decode(e.bytes);W.setFileByPath(e.path,t,!0)}else{let t=new Uint8Array(e.bytes.length);t.set(e.bytes),W.setFileByPath(e.path,new r(t.buffer,`application/octet-stream`),!0)}e.dirty=!1}catch{}},ne={TERM:`xterm-256color`,COLORTERM:`truecolor`,COLUMNS:String(this.stdout&&this.stdout.columns||this.context&&typeof this.context.getVar==`function`&&this.context.getVar(`COLUMNS`)||80),LINES:String(this.stdout&&this.stdout.rows||this.context&&typeof this.context.getVar==`function`&&this.context.getVar(`LINES`)||24),...this.context&&this.context.vars||{}},Z=Object.entries(ne).map(([e,t])=>`${e}=${t}`),Q=new Proxy({fd_write:(e,t,r,a)=>{if(!T)return o;let s=new DataView(T.buffer);if(e===1||e===2){let o=0;for(let i=0;i<r;i++){let r=s.getUint32(t+i*8,!0),a=s.getUint32(t+i*8+4,!0);a>0&&R(e,n.decode(new Uint8Array(T.buffer,r,a))),o+=a}return s.setUint32(a,o,!0),i}let c=J.get(e);if(!c)return o;if(c.type===`dev_null`||c.type===`dev_zero`){let e=0;for(let n=0;n<r;n++)e+=s.getUint32(t+n*8+4,!0);return s.setUint32(a,e,!0),i}if(c.type===`dev_tty`){let e=0;for(let i=0;i<r;i++){let r=s.getUint32(t+i*8,!0),a=s.getUint32(t+i*8+4,!0);a>0&&R(1,n.decode(new Uint8Array(T.buffer,r,a))),e+=a}return s.setUint32(a,e,!0),i}if(c.type!==`file`)return o;let l=0;for(let e=0;e<r;e++){let n=s.getUint32(t+e*8,!0),r=s.getUint32(t+e*8+4,!0);if(r>0){let e=new Uint8Array(T.buffer,n,r),t=c.append?c.bytes.length:c.pos,i=t+r;if(i>c.bytes.length){let e=new Uint8Array(i);e.set(c.bytes),c.bytes=e}c.bytes.set(e,t),c.pos=t+r,c.dirty=!0,l+=r}}return s.setUint32(a,l,!0),i},fd_read:(e,t,n,r)=>{if(!T)return o;let s=new DataView(T.buffer),c=J.get(e),l=!!(c&&c.type===`dev_tty`);if(e===0||I&&e===2||l){(l||e===2)&&L();let o=!!((Y.get(e)||0)&w);if(D){if((typeof E?.exports?.asyncify_get_state==`function`?E.exports.asyncify_get_state():0)===2){E.exports.asyncify_stop_rewind();let e=0;for(let r=0;r<n&&B.length>0;r++){let n=s.getUint32(t+r*8,!0),i=s.getUint32(t+r*8+4,!0),a=Math.min(i,B.length),o=B.splice(0,a);new Uint8Array(T.buffer).set(o,n),e+=a}return s.setUint32(r,e,!0),i}if(B.length>0){let e=0;for(let r=0;r<n&&B.length>0;r++){let n=s.getUint32(t+r*8,!0),i=s.getUint32(t+r*8+4,!0),a=Math.min(i,B.length),o=B.splice(0,a);new Uint8Array(T.buffer).set(o,n),e+=a}return s.setUint32(r,e,!0),i}return o?(s.setUint32(r,0,!0),a):(E.exports.asyncify_start_unwind(O),k=new Promise(e=>{A=e}),s.setUint32(r,0,!0),i)}if(B.length>0){let e=0;for(let r=0;r<n&&B.length>0;r++){let n=s.getUint32(t+r*8,!0),i=s.getUint32(t+r*8+4,!0),a=Math.min(i,B.length),o=B.splice(0,a);new Uint8Array(T.buffer).set(o,n),e+=a}return s.setUint32(r,e,!0),i}let c=0;for(let e=0;e<n&&U<H.length;e++){let n=s.getUint32(t+e*8,!0),r=s.getUint32(t+e*8+4,!0),i=Math.min(r,H.length-U);new Uint8Array(T.buffer).set(H.slice(U,U+i),n),U+=i,c+=i}return c===0&&o&&U>=H.length?(s.setUint32(r,0,!0),a):(s.setUint32(r,c,!0),i)}if(!c)return o;if(c.type===`dev_null`)return s.setUint32(r,0,!0),i;if(c.type===`dev_zero`){let e=0;for(let r=0;r<n;r++){let n=s.getUint32(t+r*8,!0),i=s.getUint32(t+r*8+4,!0);new Uint8Array(T.buffer,n,i).fill(0),e+=i}return s.setUint32(r,e,!0),i}if(c.type===`dev_urandom`){let e=0;for(let r=0;r<n;r++){let n=s.getUint32(t+r*8,!0),i=s.getUint32(t+r*8+4,!0),a=new Uint8Array(T.buffer,n,i);if(typeof crypto<`u`&&crypto.getRandomValues)crypto.getRandomValues(a);else for(let e=0;e<i;e++)a[e]=Math.floor(Math.random()*256);e+=i}return s.setUint32(r,e,!0),i}if(c.type!==`file`)return o;let u=0;for(let e=0;e<n&&c.pos<c.bytes.length;e++){let n=s.getUint32(t+e*8,!0),r=s.getUint32(t+e*8+4,!0),i=Math.min(r,c.bytes.length-c.pos);new Uint8Array(T.buffer).set(c.bytes.subarray(c.pos,c.pos+i),n),c.pos+=i,u+=i}return s.setUint32(r,u,!0),i},fd_seek:(e,t,n,r,a)=>{if(!T)return o;if(e<=2)return f;let s=J.get(e);if(!s)return o;if(s.type===`dev_tty`||s.type===`dev_null`||s.type===`dev_zero`||s.type===`dev_urandom`)return f;if(s.type!==`file`)return o;let l,u,d;typeof t==`bigint`?(l=Number(t),u=n,d=r):(l=t,u=r,d=a);let p=s.pos;if(u===0)p=l;else if(u===1)p=s.pos+l;else if(u===2)p=s.bytes.length+l;else return c;return p<0?c:(s.pos=p,d&&new DataView(T.buffer).setBigUint64(d,BigInt(s.pos),!0),i)},fd_tell:(e,t)=>{if(!T)return o;let n=J.get(e);return!n||n.type!==`file`?o:(new DataView(T.buffer).setBigUint64(t,BigInt(n.pos),!0),i)},fd_close:e=>{if(e<=2)return i;let t=J.get(e);return t?(t.type===`file`&&te(t),J.delete(e),Y.delete(e),i):o},fd_sync:e=>{let t=J.get(e);return t&&te(t),i},fd_datasync:e=>{let t=J.get(e);return t&&te(t),i},fd_prestat_get:(e,t)=>{if(!T)return o;let n=J.get(e);if(!n||n.type!==`preopen`)return o;let r=new DataView(T.buffer),a=y.encode(n.guestName);return r.setUint8(t,0),r.setUint32(t+4,a.length,!0),i},fd_prestat_dir_name:(e,t,n)=>{if(!T)return o;let r=J.get(e);if(!r||r.type!==`preopen`)return o;let a=y.encode(r.guestName);return new Uint8Array(T.buffer,t,Math.min(n,a.length)).set(a.subarray(0,n)),i},fd_fdstat_get:(e,t)=>{if(!T)return o;let n=new DataView(T.buffer),r=p;if(e<=2)r=m;else{let t=J.get(e);if(!t)return o;r=t.type===`dev_null`||t.type===`dev_zero`||t.type===`dev_urandom`||t.type===`dev_tty`?m:t.type===`preopen`||t.type===`dir`?h:g}for(let e=0;e<24;e++)n.setUint8(t+e,0);n.setUint8(t,r);let a=Y.get(e)||(J.get(e)?.append?C:0);return n.setUint16(t+2,a,!0),n.setBigUint64(t+8,18446744073709551615n,!0),n.setBigUint64(t+16,18446744073709551615n,!0),i},fd_fdstat_set_flags:(e,t)=>{if(!T||e>2&&!J.has(e))return o;Y.set(e,t);let n=J.get(e);return n&&(n.append=!!(t&C)),(e===0||e===2||n&&n.type===`dev_tty`)&&t&w&&L(),i},fd_filestat_get:(e,t)=>{if(!T)return o;let n=new DataView(T.buffer);for(let e=0;e<64;e++)n.setUint8(t+e,0);if(e<=2)return n.setUint8(t+16,m),i;let r=J.get(e);if(!r)return o;if(r.type===`dev_null`||r.type===`dev_zero`||r.type===`dev_urandom`||r.type===`dev_tty`)return n.setUint8(t+16,m),n.setBigUint64(t+24,1n,!0),i;let a=r.type===`preopen`||r.type===`dir`;return n.setUint8(t+16,a?h:g),n.setBigUint64(t+24,1n,!0),n.setBigUint64(t+32,BigInt(r.bytes?r.bytes.length:0),!0),i},path_open:(e,t,r,a,c,f,p,m,h)=>{if(!T||!W)return o;let g=X(e,n.decode(new Uint8Array(T.buffer,r,a)));if(!g)return o;let v=g.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`;if(v===`/dev/null`){let e=q++;return J.set(e,{type:`dev_null`,path:`/dev/null`}),new DataView(T.buffer).setUint32(h,e,!0),i}if(v===`/dev/zero`){let e=q++;return J.set(e,{type:`dev_zero`,path:`/dev/zero`}),new DataView(T.buffer).setUint32(h,e,!0),i}if(v===`/dev/urandom`||v===`/dev/random`){let e=q++;return J.set(e,{type:`dev_urandom`,path:v}),new DataView(T.buffer).setUint32(h,e,!0),i}if(v===`/dev/tty`){L();let e=q++;return J.set(e,{type:`dev_tty`,path:`/dev/tty`}),new DataView(T.buffer).setUint32(h,e,!0),i}let w=W.stat(g),E=w!==null;if(c&x&&c&_&&E)return s;if(c&b){if(!E)return u;if(!w.isDirectory)return d;let e=q++;return J.set(e,{type:`dir`,path:g}),new DataView(T.buffer).setUint32(h,e,!0),i}if(E&&w.isDirectory)return l;if(!E&&!(c&_))return u;let D=new Uint8Array,O=!1;if(E&&!(c&S)){let e=W.getFileByPath(g);e!=null&&(D=typeof e==`string`?y.encode(e):new Uint8Array(this._contentToBytes(e)))}else O=!0;let k=q++;return J.set(k,{type:`file`,path:g,bytes:D,pos:m&C?D.length:0,append:!!(m&C),dirty:O}),new DataView(T.buffer).setUint32(h,k,!0),i},path_filestat_get:(e,t,r,a,s)=>{if(!T||!W)return o;let c=X(e,n.decode(new Uint8Array(T.buffer,r,a)));if(!c)return o;let l=c.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`;if(l===`/dev/null`||l===`/dev/zero`||l===`/dev/urandom`||l===`/dev/random`||l===`/dev/tty`){let e=new DataView(T.buffer);for(let t=0;t<64;t++)e.setUint8(s+t,0);return e.setUint8(s+16,m),e.setBigUint64(s+24,1n,!0),i}let d=W.stat(c);if(!d)return u;let f=new DataView(T.buffer);for(let e=0;e<64;e++)f.setUint8(s+e,0);return f.setUint8(s+16,d.isDirectory?h:g),f.setBigUint64(s+24,1n,!0),f.setBigUint64(s+32,BigInt(W.getSize(c)||0),!0),i},path_create_directory:(e,t,r)=>{if(!T||!W)return o;let a=X(e,n.decode(new Uint8Array(T.buffer,t,r)));if(!a)return o;try{return W.setFileByPath(a,{},!0),i}catch{return c}},path_unlink_file:(e,t,r)=>{if(!T||!W)return o;let a=X(e,n.decode(new Uint8Array(T.buffer,t,r)));if(!a||!W.exists(a))return u;try{return W.deleteFileByPath(a),i}catch{return c}},path_remove_directory:(e,t,r)=>{if(!T||!W)return o;let a=X(e,n.decode(new Uint8Array(T.buffer,t,r)));if(!a||!W.exists(a))return u;try{return W.deleteFileByPath(a),i}catch{return c}},path_rename:(e,t,r,a,s,l)=>{if(!T||!W)return o;let d=n.decode(new Uint8Array(T.buffer,t,r)),f=n.decode(new Uint8Array(T.buffer,s,l)),p=X(e,d),m=X(a,f);if(!p||!m)return o;if(!W.exists(p))return u;for(let e of J.values())e.path===p&&(te(e),e.path=m);try{let e=W.getFileByPath(p);return W.setFileByPath(m,e,!0),W.deleteFileByPath(p),i}catch{return c}},proc_exit:e=>{throw e!==0&&(this.exitCode=e),{_wasmExit:!0,code:e}},args_sizes_get:(e,t)=>{if(!T)return c;let n=[this.script,...this.arguments||[]],r=new DataView(T.buffer);return r.setUint32(e,n.length,!0),r.setUint32(t,n.reduce((e,t)=>e+y.encode(t).length+1,0),!0),i},args_get:(e,t)=>{if(!T)return c;let n=[this.script,...this.arguments||[]],r=new DataView(T.buffer),a=t;for(let t=0;t<n.length;t++){r.setUint32(e+t*4,a,!0);let i=y.encode(n[t]+`\0`);new Uint8Array(T.buffer).set(i,a),a+=i.length}return i},environ_sizes_get:(e,t)=>{if(!T)return c;let n=new DataView(T.buffer);n.setUint32(e,Z.length,!0);let r=Z.reduce((e,t)=>e+y.encode(t).length+1,0);return n.setUint32(t,r,!0),i},environ_get:(e,t)=>{if(!T)return c;let n=new DataView(T.buffer),r=t;for(let t=0;t<Z.length;t++){n.setUint32(e+t*4,r,!0);let i=y.encode(Z[t]+`\0`);new Uint8Array(T.buffer).set(i,r),r+=i.length}return i},clock_time_get:(e,t,n)=>{if(T){let e=BigInt(Date.now())*1000000n;new DataView(T.buffer).setBigUint64(n,e,!0)}return i},random_get:(e,t)=>{if(T){let n=new Uint8Array(T.buffer,e,t);for(let e=0;e<t;e++)n[e]=Math.random()*256|0}return i},clock_nanosleep:(e,t,n,r,a)=>{if(!T)return o;let s=new DataView(T.buffer).getBigUint64(n,!0),c=0;if(t&1){let e=BigInt(Date.now())*1000000n;c=s>e?Number((s-e)/1000000n):0}else c=Number(s/1000000n);return D&&c>0?(typeof E?.exports?.asyncify_get_state==`function`?E.exports.asyncify_get_state():0)===2?(E.exports.asyncify_stop_rewind(),i):(E.exports.asyncify_start_unwind(O),k=new Promise(e=>setTimeout(e,Math.max(1,c))),i):i},poll_oneoff:(e,t,n,r)=>{if(!T)return o;let a=new DataView(T.buffer);if(D){if((typeof E?.exports?.asyncify_get_state==`function`?E.exports.asyncify_get_state():0)===2){E.exports.asyncify_stop_rewind();let o=0;for(let r=0;r<n;r++){let n=e+r*48,s=a.getBigUint64(n,!0),c=a.getUint8(n+8),l=t+o*32;a.setBigUint64(l,s,!0),a.setUint16(l+8,i,!0),a.setUint8(l+10,c);for(let e=11;e<32;e++)a.setUint8(l+e,0);c===1&&a.setBigUint64(l+16,BigInt(B.length),!0),o++}return a.setUint32(r,o,!0),i}let o=0,s=1/0;for(let t=0;t<n;t++){let n=e+t*48,r=a.getUint8(n+8);if(r===0){let e=a.getBigUint64(n+24,!0),t=a.getUint16(n+40,!0),r=0;if(t&1){let t=BigInt(Date.now())*1000000n;r=e>t?Number((e-t)/1000000n):0}else r=Number(e/1000000n);r<s&&(s=r)}else if(r===1){let e=a.getUint32(n+16,!0),t=J.get(e),r=!!(t&&t.type===`dev_tty`);(e===0||e===2||r)&&L(),(e===0||I&&e===2||r)&&B.length>0&&o++}else r===2&&o++}if(o>0||s===0){let o=0;for(let r=0;r<n;r++){let n=e+r*48,c=a.getBigUint64(n,!0),l=a.getUint8(n+8),u=!1;if(l===0&&s===0)u=!0;else if(l===1){let e=a.getUint32(n+16,!0),t=J.get(e),r=!!(t&&t.type===`dev_tty`);(e===0||I&&e===2||r)&&B.length>0&&(u=!0)}else l===2&&(u=!0);if(u){let e=t+o*32;a.setBigUint64(e,c,!0),a.setUint16(e+8,i,!0),a.setUint8(e+10,l);for(let t=11;t<32;t++)a.setUint8(e+t,0);l===1&&a.setBigUint64(e+16,BigInt(B.length),!0),o++}}return a.setUint32(r,o,!0),i}return E.exports.asyncify_start_unwind(O),k=new Promise(e=>{let t=null;A=()=>{t&&clearTimeout(t),A=null,e()},s!==1/0&&(t=setTimeout(()=>{A=null,e()},Math.max(1,s)))}),a.setUint32(r,0,!0),i}return a.setUint32(r,0,!0),i}},{get(e,t){return t in e?e[t]:()=>0}}),re=e=>{if(!T||!e)return``;try{let t=new DataView(T.buffer).getUint32(e-4,!0),n=new Uint16Array(T.buffer,e,t>>>1);return String.fromCharCode(...n)}catch{return``}},ie={wasi_snapshot_preview1:Q,wasi_unstable:Q,env:new Proxy({print:(e,t)=>{T&&R(1,n.decode(new Uint8Array(T.buffer,e,t)))},eprint:(e,t)=>{T&&R(2,n.decode(new Uint8Array(T.buffer,e,t)))},log:e=>{R(1,re(e)+`
|
|
6
|
+
`)},logi:e=>{R(1,String(e)+`
|
|
7
|
+
`)},logf:e=>{R(1,String(e)+`
|
|
8
|
+
`)},trace:(e,t,...n)=>{let r=t>0?` `+n.slice(0,t).join(`, `):``;R(1,`trace: ${re(e)}${r}\n`)},seed:()=>Date.now()*Math.random(),abort:(e,t,n,r)=>{let i=re(e),a=re(t);throw(i||a)&&R(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});T=t,ie[e.module]||(ie[e.module]={}),ie[e.module][e.name]=t}if(E=await WebAssembly.instantiate(t,ie),E.exports.memory&&(T=E.exports.memory),D=!!(E.exports.asyncify_start_unwind&&E.exports.asyncify_stop_unwind),D&&T){try{O=T.grow(1)*65536}catch{O=16}let e=O+8,t=O+65536-8;new Int32Array(T.buffer,O,2).set([e,t])}typeof E.exports.set_terminal_size==`function`&&L(),I&&this._enterAltScreen();let n=this.stdout&&this.stdout.columns||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`COLUMNS`),10)||80,r=this.stdout&&this.stdout.rows||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`LINES`),10)||24;if(typeof E.exports.set_terminal_size==`function`)try{E.exports.set_terminal_size(n,r)}catch{}j=()=>{let e=this.stdout&&this.stdout.columns||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`COLUMNS`),10)||80,t=this.stdout&&this.stdout.rows||this.context&&typeof this.context.getVar==`function`&&parseInt(this.context.getVar(`LINES`),10)||24;if(typeof E?.exports?.set_terminal_size==`function`)try{E.exports.set_terminal_size(e,t)}catch{}},this.stdout&&typeof this.stdout.on==`function`&&this.stdout.on(`resize`,j),this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`resize`,j);let i=E.exports._start||E.exports.__wasi_command||E.exports.main||E.exports.run;if(i)try{let e=i();for(e&&typeof e.then==`function`&&(e=await e);D&&typeof E.exports.asyncify_get_state==`function`&&E.exports.asyncify_get_state()===1;)E.exports.asyncify_stop_unwind(),k&&=(await k,null),E.exports.asyncify_start_rewind(O),e=i(),e&&typeof e.then==`function`&&(e=await e)}catch(e){(!e||!e._wasmExit)&&(this.stdErr=`${this.script}: runtime error: ${e?.message||String(e)}`,this.exitCode=1)}else{let e=Object.entries(E.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){(!e||!e._wasmExit)&&(this.stdErr=`${this.script}: ${e?.message||String(e)}`,this.exitCode=1)}finally{I&&this._exitAltScreen(),M&&(this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`data`,M),this.stdin&&typeof this.stdin.off==`function`&&this.stdin.off(`data`,M)),this._onStdinStreamData&&this.stdinStream&&typeof this.stdinStream.on==`function`&&this.stdinStream.on(`data`,this._onStdinStreamData),j&&(this.stdout&&typeof this.stdout.off==`function`&&this.stdout.off(`resize`,j),this.stdinStream&&typeof this.stdinStream.off==`function`&&this.stdinStream.off(`resize`,j)),this._externalKeyHandler=null;for(let e of J.values())te(e)}z();let ae=this.arguments||[];if(!(this.result&&this.result.getStdOutput&&this.result.getStdOutput().length>0)&&(this.exitCode===0||this.exitCode===void 0)){let t=(this.script||`wasm`).split(`/`).pop(),n=Object.assign({name:t,version:`wasi`,description:`WebAssembly WASI binary (${this.script})`},this._pkgMeta||{});if(ae.includes(`--help`)||ae.includes(`-h`)){let r=N(e);for(let e of P(t,n,r))this.stdOut=e}else (ae.includes(`--version`)||ae.includes(`-V`)||ae.includes(`-v`))&&(this.stdOut=`${t} (${n.name} ${n.version} wasm)`)}}},O=new Map;function k(e,t){if(!e||!e.exists(t))return null;if(e.isRealFilesystem)try{let n=X();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),o=new Uint8Array(a.byteLength);o.set(a);let s=new r(o.buffer,i);if(e.isRealFilesystem)try{let n=X(),r=te(),i=e.absolutePath(t);n.mkdirSync(r.dirname(i),{recursive:!0}),n.writeFileSync(i,v.from(a.buffer,a.byteOffset,a.byteLength));return}catch{if(typeof e._setFileRaw==`function`){e._setFileRaw(t,s,!0);return}}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:[]};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)}}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=M(n.join(`
|
|
9
|
+
`),!0);t.usage=i.usage,t.options=i.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=T(),i=(n||e.bin||e.name).toLowerCase();class a extends r{static get name(){return i}get name(){return i}get requiresFilesystem(){return!0}async run(){let n=[...this.arguments||[]],r=n.includes(`--help`)||n.includes(`-h`),a=!r&&(n.includes(`--version`)||n.includes(`-V`)||n.includes(`-v`));this._inspectedWasm=null,this._persistedWasmBytes=e.wasmPath?k(this.context&&this.context.fs||this.fs,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);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(`
|
|
10
|
+
`),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,this.stdin!==void 0&&(r.stdin=this.stdin),await r._runWasm(t);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.context&&this.context.fs?this.context.fs.setMode(r,493):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){let i=[],a=[],o=new TextEncoder().encode(this.stdin||``),s=0,c=new Set,l={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=>{i.push(String(e))},printErr:e=>{a.push(String(e))},stdin:()=>s<o.length?o[s++]:null,preRun:[e=>{e&&e.FS&&(c=this._syncBrshToEmscriptenFs(e.FS,n))}]},u=this._createIoBridge(n,i,a),d;try{d=t.prototype&&t.prototype.constructor===t&&Object.getOwnPropertyNames(t.prototype).length>1?new t(l,u):await t(l,u)}catch(e){if(e&&typeof e.status==`number`)this.exitCode=e.status;else throw e}if(d&&typeof d==`object`)if(r&&(d.wasmBinary instanceof Uint8Array||d.HEAPU8 instanceof Uint8Array)&&(this._inspectedWasm=N(d.wasmBinary||d.HEAPU8)),typeof d.callMain==`function`){d.FS&&c.size===0&&(c=this._syncBrshToEmscriptenFs(d.FS,n));try{let e=await d.callMain(n);typeof e==`number`&&e!==0&&(this.exitCode=e)}catch(e){e&&typeof e.status==`number`?this.exitCode=e.status:(a.push(e.message||String(e)),this.exitCode=1)}d.FS&&this._syncEmscriptenFsToBrsh(d.FS,n,c)}else if(typeof d.exec==`function`&&typeof d.writeFile==`function`)await this._runVirtualFsInstance(d,n,i,a);else if(typeof d.main==`function`||typeof d.run==`function`){let e=(d.main||d.run).bind(d);await this._invokeCliFunction(e,n,i,a)}else !r&&!isVersion&&typeof d.Database==`function`?this._runSqlJsDatabase(d,n,u,i):(typeof d.stdout==`string`&&d.stdout&&d.stdout.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>i.push(e)),typeof d.stderr==`string`&&d.stderr&&d.stderr.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>a.push(e)),d.error&&a.length===0&&(a.push(d.error.message||String(d.error)),this.exitCode=1),typeof d.exitCode==`number`&&(this.exitCode=d.exitCode));else typeof d==`string`?d.replace(/\r?\n$/,``).split(/\r?\n/).forEach(e=>i.push(e)):typeof d==`number`&&(this.exitCode=d);i.forEach(e=>{this.stdOut=e}),a.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.context&&this.context.fs?this.context.fs.setMode(r,493):this.fs.setMode(r,493)}catch{}}}catch{}}}}return a}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})),Z=t(((e,t)=>{var n=J(),{createGenericWasmCommand:r}=ne(),i=`\x1B[2J\x1B[H`,a=`\x1B[0m`,o=`\x1B[7m`,s=`\x1B[1m`,c=`\x1B[2m`,l=`\x1B[36m`,u=`\x1B[31m`,d=`\x1B[32m`,f=class extends n{get requiresFilesystem(){return!0}get interactive(){return this.shouldBeInteractive()}get captureInput(){return this.shouldBeInteractive()}shouldBeInteractive(){return!!this._dynamicReplActive}getReplTitle(){return this._dynamicReplOpts&&this._dynamicReplOpts.title||`${this.name} interactive shell`}getReplPrompt(){return this._dynamicReplMultiline&&this._dynamicReplOpts&&this._dynamicReplOpts.continuePrompt?this._dynamicReplOpts.continuePrompt:this._dynamicReplOpts&&this._dynamicReplOpts.prompt||`${this.name}> `}getReplWelcome(){return this._dynamicReplOpts&&this._dynamicReplOpts.banner||[`Welcome to ${this.name}. Type .exit or Ctrl+D to quit.`]}async initRepl(){}async evaluateReplLine(e){if(this._dynamicReplOpts&&typeof this._dynamicReplOpts.onEvaluate==`function`){let t=await this._dynamicReplOpts.onEvaluate(e);return{output:Array.isArray(t)?t:t==null?[]:[String(t)]}}return{output:[]}}async cleanupRepl(){this._dynamicReplOpts&&typeof this._dynamicReplOpts.onClose==`function`&&await this._dynamicReplOpts.onClose()}async runNonInteractive(){}startRepl(e={}){return this._dynamicReplActive=!0,this._dynamicReplOpts=e,this._dynamicReplBuffer=``,this._dynamicReplMultiline=!1,typeof this._enterAltScreen==`function`&&this._enterAltScreen(),this._launchInteractiveReplLoop()}run(){return this.shouldBeInteractive()?this._launchInteractiveReplLoop():Promise.resolve(this.runNonInteractive())}_launchInteractiveReplLoop(){return this._replHistory=[],this._replHistoryIdx=null,this._replInput=``,this._replCursor=0,this._replLog=[],this._replBusy=!0,this._replStatus=`Initializing WASM runtime...`,this._scrollOffset=0,this._renderRepl(),new Promise(e=>{this._replResolve=e,Promise.resolve().then(()=>this.initRepl()).then(()=>{this._replBusy=!1,this._replStatus=`^D / .exit: Quit | ^L: Clear | Up/Down: History`;for(let e of this.getReplWelcome())this._appendReplLog(e,`info`);this._renderRepl()}).catch(e=>{this._replBusy=!1,this.stdErr=e.message||String(e),this.exitCode=1,this._exitRepl()})})}_appendReplLog(e,t=`out`){let n=String(e??``).split(/\r?\n/);for(let e of n)this._replLog.push({text:e,type:t});this._scrollOffset=0}streamReplChunk(e,t=`out`){if(!e)return;(this._replLog.length===0||this._replLog[this._replLog.length-1].type!==t||!this._replStreamingActive)&&(this._replLog.push({text:``,type:t}),this._replStreamingActive=!0);let n=this._replLog[this._replLog.length-1],r=(n.text+e).split(/\r?\n/);n.text=r[0];for(let e=1;e<r.length;e++)this._replLog.push({text:r[e],type:t});this._scrollOffset=0,this._renderRepl()}onInput(e){if(this.shouldBeInteractive()){if(e===`^D`||e===`^X`){this._exitRepl();return}if(e===`^C`){this._replInput.length>0||this._dynamicReplBuffer?(this._appendReplLog(`${this.getReplPrompt()}${this._replInput}^C`,`prompt`),this._replInput=``,this._replCursor=0,this._dynamicReplBuffer=``,this._dynamicReplMultiline=!1,this._renderRepl()):this._exitRepl();return}if(!this._replBusy){if(e===`^L`){this._replLog=[],this._scrollOffset=0,this._renderRepl();return}if(e===`Enter`){let e=this._replInput;this._replInput=``,this._replCursor=0,this._replHistoryIdx=null,e.trim()&&this._replHistory.push(e),this._appendReplLog(`${this.getReplPrompt()}${e}`,`prompt`);let t=e.trim();if(this._dynamicReplOpts&&typeof this._dynamicReplOpts.isExitCommand==`function`&&this._dynamicReplOpts.isExitCommand(t)||t===`.exit`||t===`.quit`||t===`\\q`||t===`exit`||t===`quit`||t===`exit()`||t===`quit()`){this._exitRepl();return}if(t===`.clear`||t===`\\! clear`){this._replLog=[],this._renderRepl();return}if(this._dynamicReplOpts&&typeof this._dynamicReplOpts.needsMoreInput==`function`&&(this._dynamicReplBuffer=this._dynamicReplBuffer?`${this._dynamicReplBuffer}\n${e}`:e,this._dynamicReplOpts.needsMoreInput(this._dynamicReplBuffer))){this._dynamicReplMultiline=!0,this._renderRepl();return}let n=this._dynamicReplBuffer||e;this._dynamicReplBuffer=``,this._dynamicReplMultiline=!1,this._replBusy=!0,this._replStatus=`Running...`,this._renderRepl(),Promise.resolve().then(()=>this.evaluateReplLine(n)).then(e=>{if(this._replBusy=!1,this._replStreamingActive=!1,this._replStatus=`^D / .exit: Quit | ^L: Clear | Up/Down: History`,e){if(e.clear&&(this._replLog=[]),!e.streamed)if(Array.isArray(e.output))for(let t of e.output)this._appendReplLog(t,`out`);else typeof e.output==`string`&&e.output.length>0&&this._appendReplLog(e.output,`out`);if(e.error&&this._appendReplLog(e.error,`err`),e.exit){this._exitRepl();return}}this._renderRepl()}).catch(e=>{this._replBusy=!1,this._replStatus=`^D / .exit: Quit | ^L: Clear | Up/Down: History`,this._appendReplLog(`Error: ${e.message||e}`,`err`),this._renderRepl()});return}if(e===`Backspace`){this._replCursor>0&&(this._replInput=this._replInput.slice(0,this._replCursor-1)+this._replInput.slice(this._replCursor),this._replCursor--,this._renderRepl());return}if(e===`^W`){let e=this._replCursor;for(;e>0&&this._replInput[e-1]===` `;)e--;for(;e>0&&this._replInput[e-1]!==` `;)e--;this._replInput=this._replInput.slice(0,e)+this._replInput.slice(this._replCursor),this._replCursor=e,this._renderRepl();return}if(e===`Delete`){this._replCursor<this._replInput.length&&(this._replInput=this._replInput.slice(0,this._replCursor)+this._replInput.slice(this._replCursor+1),this._renderRepl());return}if(e===`ArrowLeft`){this._replCursor>0&&(this._replCursor--,this._renderRepl());return}if(e===`ArrowRight`){this._replCursor<this._replInput.length&&(this._replCursor++,this._renderRepl());return}if(e===`Home`||e===`^A`){this._replCursor=0,this._renderRepl();return}if(e===`End`||e===`^E`){this._replCursor=this._replInput.length,this._renderRepl();return}if(e===`ArrowUp`){if(this._replHistory.length===0)return;this._replHistoryIdx===null?this._replHistoryIdx=this._replHistory.length-1:this._replHistoryIdx>0&&this._replHistoryIdx--,this._replInput=this._replHistory[this._replHistoryIdx],this._replCursor=this._replInput.length,this._renderRepl();return}if(e===`ArrowDown`){if(this._replHistoryIdx===null)return;this._replHistoryIdx<this._replHistory.length-1?(this._replHistoryIdx++,this._replInput=this._replHistory[this._replHistoryIdx]):(this._replHistoryIdx=null,this._replInput=``),this._replCursor=this._replInput.length,this._renderRepl();return}if(e===`PageUp`){let e=Math.max(0,this._replLog.length-5);this._scrollOffset=Math.min(e,this._scrollOffset+5),this._renderRepl();return}if(e===`PageDown`){this._scrollOffset=Math.max(0,this._scrollOffset-5),this._renderRepl();return}e.length===1&&!e.startsWith(`^`)&&(this._replInput=this._replInput.slice(0,this._replCursor)+e+this._replInput.slice(this._replCursor),this._replCursor++,this._renderRepl())}}}_renderRepl(){let{cols:e,rows:t}=this.terminalSize,n=Math.max(3,t-3),r=`${o}${s}${` ${this.getReplTitle()} `.padEnd(e).slice(0,e)}${a}`,f=this._replLog.length,p=Math.max(0,f-this._scrollOffset),m=Math.max(0,p-n),h=this._replLog.slice(m,p),g=[];for(let e=0;e<n;e++){let t=h[e];if(!t){g.push(``);continue}t.type===`prompt`?g.push(`${l}${t.text}${a}`):t.type===`err`?g.push(`${u}${t.text}${a}`):t.type===`info`?g.push(`${c}${t.text}${a}`):g.push(t.text)}let _=this.getReplPrompt(),v=this._replInput.slice(0,this._replCursor),y=this._replCursor<this._replInput.length?this._replInput[this._replCursor]:` `,b=this._replCursor<this._replInput.length?this._replInput.slice(this._replCursor+1):``,x=this._replBusy?`${c}${this._replStatus}${a}`:`${d}${s}${_}${a}${v}${o}${y}${a}${b}`,S=`${o}${` ${this._replStatus} `.padEnd(e).slice(0,e)}${a}`,C=[i+r,...g,x,S].join(`
|
|
11
11
|
`);this.stdOut=C,this.flush()}_exitRepl(){Promise.resolve().then(()=>this.cleanupRepl()).catch(()=>{}).finally(()=>{if(this._replResolve){let e=this._replResolve;this._replResolve=null,e()}})}};function p(e,t={},n=null){let i=(n||e.bin||e.name).toLowerCase(),a=r(e,t,i),o=e&&typeof e.repl==`object`?e.repl:{};class s extends f{static get name(){return i}get name(){return i}constructor(e,t){super(e,t),this._sessionArgs=[],this._isInteractiveMode=this._detectInteractiveMode(e||[])}_detectInteractiveMode(e){if(e.includes(`--help`)||e.includes(`-h`)||e.includes(`--version`)||e.includes(`-V`)||e.includes(`-v`))return!1;if(e.length===0)return!0;if(o.sessionArg&&e.length===1&&!e[0].startsWith(`-`)){let t=e[0].trim();if(!/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|PRAGMA|WITH|BEGIN|EXPLAIN|\.)\b/i.test(t))return this._sessionArgs=[e[0]],!0}return!1}shouldBeInteractive(){return this._dynamicReplActive?!0:this.stdin!==void 0&&this.stdin!==null&&String(this.stdin).trim().length>0?!1:this._isInteractiveMode}getReplTitle(){let t=this._sessionArgs.length>0?` — ${this._sessionArgs.join(` `)}`:``;return o.title||`${i} (${e.name} ${e.version||`wasm`})${t}`}getReplPrompt(){return this._dynamicReplMultiline&&o.continuePrompt?o.continuePrompt:o.prompt||`${i}> `}getReplWelcome(){return o.banner||[`${e.name} (${e.version||`wasm`}) interactive shell`,`Type ".exit" or Ctrl+D to quit.`]}async evaluateReplLine(e){let t=o.evalFlag,n=t?[...this._sessionArgs,t,e]:[...this._sessionArgs,e],r=t?void 0:e,{out:i,err:a}=await this._captureBaseWasmOutput(n,r);return{output:i,error:a.length>0?a.join(`
|
|
12
|
-
`):void 0}}async runNonInteractive(){await this._delegateToBaseWasm([...this.arguments||[]])}async _delegateToBaseWasm(e){let t=new a(e,this.context);t.fs=this.fs,this.stdin!==void 0&&(t.stdin=this.stdin),await t.run();for(let e of t.result.getStdOutput())e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.exitCode=t.exitCode||t.result.getExitCode()}async _captureBaseWasmOutput(e,t){let n=new a(e,this.context);n.fs=this.fs,t!==void 0&&(n.stdin=t),await n.run();let r=[],i=[];for(let e of n.result.getStdOutput())e.type===`err`?i.push(e.string):r.push(e.string);return{out:r,err:i}}}return s}f.createReplWasmCommand=p,f.createCommand=p,t.exports=f})),re=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`}},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`};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}})),ie=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}})),ae=t(((e,t)=>{w();var n=Z(),{readBytesFromFs:r,writeBytesToFs:i,loadModule:a}=ie(),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(`
|
|
12
|
+
`):void 0}}async runNonInteractive(){await this._delegateToBaseWasm([...this.arguments||[]])}async _delegateToBaseWasm(e){let t=new a(e,this.context);t.fs=this.fs,this.stdin!==void 0&&(t.stdin=this.stdin),await t.run();for(let e of t.result.getStdOutput())e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.exitCode=t.exitCode||t.result.getExitCode()}async _captureBaseWasmOutput(e,t){let n=new a(e,this.context);n.fs=this.fs,t!==void 0&&(n.stdin=t),await n.run();let r=[],i=[];for(let e of n.result.getStdOutput())e.type===`err`?i.push(e.string):r.push(e.string);return{out:r,err:i}}}return s}f.createReplWasmCommand=p,f.createCommand=p,t.exports=f})),Q=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`}},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`};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}})),re=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}=ne();t.exports={formatTable:n,formatPipeList:r,formatCsv:i,readBytesFromFs:a,writeBytesToFs:o,loadModule:s,extractHelpFromText:c,inspectWasmBytes:l,formatWasmHelp:u}})),ie=t(((e,t)=>{w();var n=Z(),{readBytesFromFs:r,writeBytesToFs:i,loadModule:a}=re(),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
13
|
`)&&this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(`\r
|
|
14
14
|
`)}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
15
|
`)&&this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(`\r
|
|
16
|
-
`)}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=T(),r=X(),i=Z(),{DEFAULT_REGISTRY:a,resolvePackageName:o}=re(),s=ae(),{writeBytesToFs:c,createGenericWasmCommand:l}=r,{createReplWasmCommand:u}=i,d=`/var/lib/wbt/installed.json`,f=`/var/cache/wbt`;function p(e,t,n={}){class i extends r{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`):!!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 i}var m=class extends n{static get name(){return`wbt`}get name(){return`wbt`}get requiresFilesystem(){return!0}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=this.arguments[1].toLowerCase(),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}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(e,t={}){let n=e.context||e;if(!n||!n.fs)return;let r=new(this.configure(t))([],n);r.fs=n.fs.sandbox(),r._restoreCommands()}_getRegistry(){let e=this.constructor._config||{},t=Object.assign({},a,e.registry||{});try{let e=this.context.fs._getFileRaw(`${f}/remote-registry.json`);if(typeof e==`string`&&e.trim()){let n=JSON.parse(e);Object.assign(t,n)}}catch{}return t}_readState(){try{let e=this.context.fs._getFileRaw(d);if(typeof e==`string`&&e.trim()){let t=JSON.parse(e);if(t&&typeof t==`object`&&t.packages)return t}}catch{}return{packages:{}}}_writeState(e){this.context.fs._setFileRaw(d,JSON.stringify(e,null,2),!0)}_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=s.buildEntries||s.createAdapter||s),!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?u:l,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.context.getVar(`PATH`)||`/bin`,n=this._buildCommandsForPackage(e),r=[];for(let{bin:e,Cmd:i}of n){let n=e.toLowerCase();this._installBin(t,n,i),r.push(n)}for(let i of e.aliases||[]){let e=i.toLowerCase();if(!r.includes(e)&&n.length>0){let i=n[0].Cmd;class a extends i{static get name(){return e}get name(){return e}}this._installBin(t,e,a),r.push(e)}}return r}_installBin(e,t,n){let r=`${e}/${t}`;this.context.fs.addFiles({[r]:n}),this.context.fs.setMode(r,365)}_removeBin(e,t){let n=`${e}/${t.toLowerCase()}`;if(this.context.fs._deleteByAbsolutePath)this.context.fs._deleteByAbsolutePath(n),this.context.fs._triggerChange();else try{this.context.fs.deleteFileByPath(n)}catch{}}_restoreCommands(){let e=this._readState(),t=this._getRegistry();for(let[n,r]of Object.entries(e.packages)){let e=t[n]||r;if(e)try{this._registerPackageIntoContext(e)}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 s=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._readState(),d=!1;for(let e=0;e<n.length;e++){let f=n[e];if(!s(f)&&e+1<n.length&&s(n[e+1])){let t=n[++e],a=(r||f).toLowerCase();if(await this._installCustomUrl(a,t,i,u),this.exitCode)return;continue}if(s(f)){let e=f,t=(r||c(e)).toLowerCase();if(await this._installCustomUrl(t,e,i,u),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[o(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.packages[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;try{m=await this._pullPackageWasm(p,i,t.includes(`--preload`))}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 h=Object.assign({},p,m?{wasmPath:m}:{}),g=this._registerPackageIntoContext(h);u.packages[p.name]={name:p.name,bin:p.bin,bins:g,aliases:p.aliases||[],version:p.version,description:p.description,cdnUrl:p.cdnUrl,wasmUrl:p.wasmUrl,wasmPath:m||p.wasmPath,type:p.type,adapter:p.adapter,repl:p.repl,installedAt:new Date().toISOString()},i||(this.stdOut=`Setting up ${p.name} (${p.version}) -> /bin/${g.join(`, /bin/`)} ...`)}this._writeState(u)}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){let r=this.constructor._config||{},i=r.fetch||(typeof fetch==`function`?fetch:null),{loadModule:a}=ie(),o=null,s=null,l=e.wasmUrl||(/\.(wasm|wat)(\?.*)?$/i.test(e.cdnUrl||``)?e.cdnUrl:null);if(l&&i)try{let n=await i(l);n&&n.ok?o=await this._readResponseBytes(n,`${e.name}.wasm`,t):s=Error(`HTTP ${n?n.status:`error`} fetching ${l}`)}catch(e){s=e}if(!o&&i&&!r.moduleLoader){let n=this._extractNpmSpec(e);if(n){let r=await this._discoverWasmFromJsDelivr(n,e.name,i,t);r&&r.bytes&&(o=r.bytes,e.wasmUrl=r.url,s=null)}}let u=null,d=null;if(e.cdnUrl||r.moduleLoader){let t=typeof globalThis.fetch==`function`?globalThis.fetch:null;t&&o&&o.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(o,{status:200,headers:{"Content-Type":`application/wasm`}}):t(e,n)});try{u=await a(e.name,e.cdnUrl,r.moduleLoader)}catch(e){if(d=e,n)throw e}finally{t&&(globalThis.fetch=t)}}if(!o&&u){let e=u.default===void 0?u:u.default;e instanceof Uint8Array?o=e:e instanceof ArrayBuffer?o=new Uint8Array(e):e&&(e.wasmBytes instanceof Uint8Array||e.wasm instanceof Uint8Array||e.wasmBinary instanceof Uint8Array)&&(o=e.wasmBytes||e.wasm||e.wasmBinary)}if(!o&&e.cdnUrl&&i&&!r.moduleLoader)try{let t=await i(e.cdnUrl);if(t&&t.ok&&typeof t.text==`function`){let e=await t.text();o=this._extractEmbeddedWasmFromText(e)}}catch{}if(!o&&typeof r.moduleLoader==`function`&&(o=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])),!o&&!u&&(s||d)&&!r.moduleLoader)throw s||d;if(o){let t=`/var/lib/wbt/wasm/${e.name}.wasm`;c(this.context.fs,t,o,`application/wasm`);try{this.context.fs.setMode(t,493)}catch{}return t}return null}async _installCustomUrl(e,t,n=!1,r=null){if(!/\.(wasm|wat)(\?.*)?$/i.test(t)&&(/^https?:\/\/esm\.sh\//i.test(t)||/\.(mjs|js)(\?.*)?$/i.test(t))){let i={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()},a=await this._pullPackageWasm(i,n,!1);a&&(i.wasmPath=a),this._registerPackageIntoContext(i);let o=r||this._readState();o.packages[e]=i,this._writeState(o),n||(this.stdOut=`Setting up ${e} (generic runtime) -> /bin/${e} ...`);return}let i=(this.constructor._config||{}).fetch||(typeof fetch==`function`?fetch:null);if(!i){this.stdErr=`E: fetch is not available in this environment`,this.exitCode=1;return}n||(this.stdOut=`Get:1 ${t} ${e}`,this.flush());let a=t.replace(/^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/(?:blob|raw)\/([^/]+)\/(.+)$/i,`https://raw.githubusercontent.com/$1/$2/$3/$4`),o;try{o=await i(a)}catch(e){if(/^https?:\/\/github\.com\/[^/]+\/[^/]+\/releases\/download\//i.test(a))try{o=await i(`https://corsproxy.io/?${encodeURIComponent(a)}`)}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(!o||!o.ok){this.stdErr=`E: HTTP ${o?o.status:`error`} fetching ${t}`,this.exitCode=1;return}let s=t.endsWith(`.wat`),l=`/var/lib/wbt/wasm/${e}${s?`.wat`:`.wasm`}`;if(s){let e=await o.text();this.context.fs._setFileRaw(l,e,!0)}else{let e=await o.arrayBuffer();c(this.fs,l,new Uint8Array(e),`application/wasm`)}this.context.fs.setMode(l,493);let u={name:e,bin:e,bins:[e],version:`custom`,description:`Custom WebAssembly binary from ${t}`,cdnUrl:t,type:`custom-wasm`,wasmPath:l,installedAt:new Date().toISOString()};this._registerPackageIntoContext(u);let d=r||this._readState();d.packages[e]=u,this._writeState(d),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._readState(),r=this.context.getVar(`PATH`)||`/bin`;for(let e of t){let t=o(e),i=n.packages[t]||n.packages[e.toLowerCase()];if(!i){this.stdErr=`E: Package '${e}' is not installed, so not removed`,this.exitCode=1;return}let a=i.bins||[i.bin||i.name,...i.aliases||[]];for(let e of a)this._removeBin(r,e);if(i.wasmPath)try{this.context.fs.deleteFileByPath(i.wasmPath)}catch{}delete n.packages[i.name],this.stdOut=`Removing ${i.name} (${i.version}) ...`}this._writeState(n)}_handleList(e){let t=e.includes(`--installed`)||e.includes(`-i`),n=this._getRegistry(),r=this._readState();this.stdOut=`Listing...`;let i=t?Object.keys(r.packages).sort():Array.from(new Set([...Object.keys(n),...Object.keys(r.packages)])).sort();for(let e of i){let t=n[e],i=r.packages[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._readState();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.description&&e.description.toLowerCase().includes(t)||e.details&&e.details.toLowerCase().includes(t):!0);for(let e of i){let t=r.packages[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=o(t),r=this._getRegistry(),i=this._readState(),a=i.packages[n]||r[n];if(!a){this.stdErr=`E: No packages found matching ${t}`,this.exitCode=100;return}let s=Object.assign({},r[n]||{},a),c=!!i.packages[s.name];this.stdOut=`Package: ${s.name}`,this.stdOut=`Version: ${s.version}`,this.stdOut=`State: ${c?`installed`:`not installed`}`,this.stdOut=`Binary: ${s.bin||s.name}`,s.aliases&&s.aliases.length>0&&(this.stdOut=`Aliases: ${s.aliases.join(`, `)}`),s.size&&(this.stdOut=`Download-Size: ${s.size}`),s.cdnUrl&&(this.stdOut=`APT-Sources: ${s.cdnUrl}`),s.wasmUrl&&(this.stdOut=`WASM-URL: ${s.wasmUrl}`),s.wasmPath&&(this.stdOut=`WASM-File: ${s.wasmPath}`),s.homepage&&(this.stdOut=`Homepage: ${s.homepage}`),this.stdOut=`Description: ${s.description||``}`,s.details&&(this.stdOut=` ${s.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.context.fs._setFileRaw(`${f}/remote-registry.json`,JSON.stringify(r,null,2),!0),this._restoreCommands();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=o(t),r=this._getRegistry(),i=this._readState().packages[n]||r[n];if(!i&&(t.startsWith(`npm:`)||t.startsWith(`esm:`))){let e=t.replace(/^(npm|esm):/i,``),n=e.replace(/^@[^/]+\//,``).split(`@`)[0].toLowerCase();i={name:n,bin:n,version:`latest`,cdnUrl:`https://esm.sh/${e}`,type:`generic-runtime`}}if(!i){this.stdErr=`E: Unable to locate package ${t}`,this.exitCode=100;return}if((i.type===`custom-wasm`||i.type===`wasm`)&&!i.wasmPath)try{let e=await this._pullPackageWasm(i,!0);e&&(i=Object.assign({},i,{wasmPath:e}))}catch(e){this.stdErr=`E: Failed to fetch ${i.name}: ${e.message||e}`,this.exitCode=1;return}let a=this._buildCommandsForPackage(i),s=(a.find(e=>e.bin===t.toLowerCase())||a[0]).Cmd,c=new s(e,this.context);c.requiresFilesystem&&(c.fs=this.context.fs.sandbox()),this._activeSubCommand=c,c.stdinStream=this.stdinStream,c.stdin=this.stdin&&!this.stdin.isTTY?this.stdin:this.stdinStream;let l=e=>{this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(e)},u=e=>{this.stderr&&typeof this.stderr.write==`function`&&this.stderr.write(e)};c.stdout&&typeof c.stdout.on==`function`&&c.stdout.on(`data`,l),c.stderr&&typeof c.stderr.on==`function`&&c.stderr.on(`data`,u);let d;try{d=await c.runCommand()}finally{this._activeSubCommand=null,c.stdout&&typeof c.stdout.off==`function`&&c.stdout.off(`data`,l),c.stderr&&typeof c.stderr.off==`function`&&c.stderr.off(`data`,u)}if(!c.interactive&&d)for(let e of d.getStdOutput())e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.exitCode=d?d.getExitCode():0}_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)`].forEach(e=>{this.stdOut=e})}};t.exports=m,t.exports.Wbt=m,t.exports.DEFAULT_REGISTRY=a,t.exports.createGenericWasmCommand=l,t.exports.createReplWasmCommand=u}))()})();
|
|
16
|
+
`)}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=T(),r=ne(),i=Z(),{DEFAULT_REGISTRY:a,resolvePackageName:o}=Q(),s=ie(),{writeBytesToFs:c,createGenericWasmCommand:l}=r,{createReplWasmCommand:u}=i,d=`/var/lib/wbt/installed.json`,f=`/var/cache/wbt`;function p(e,t,n={}){class i extends r{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`):!!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 i}var m=class extends n{static get name(){return`wbt`}get name(){return`wbt`}get requiresFilesystem(){return!0}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=this.arguments[1].toLowerCase(),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}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(e,t={}){let n=e.context||e;if(!n||!n.fs)return;let r=new(this.configure(t))([],n);r.fs=n.fs.sandbox(),r._restoreCommands()}_getRegistry(){let e=this.constructor._config||{},t=Object.assign({},a,e.registry||{});try{let e=this.context.fs._getFileRaw(`${f}/remote-registry.json`);if(typeof e==`string`&&e.trim()){let n=JSON.parse(e);Object.assign(t,n)}}catch{}return t}_readState(){try{let e=this.context.fs._getFileRaw(d);if(typeof e==`string`&&e.trim()){let t=JSON.parse(e);if(t&&typeof t==`object`&&t.packages)return t}}catch{}return{packages:{}}}_writeState(e){this.context.fs._setFileRaw(d,JSON.stringify(e,null,2),!0)}_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=s.buildEntries||s.createAdapter||s),!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?u:l,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.context.getVar(`PATH`)||`/bin`,n=this._buildCommandsForPackage(e),r=[];for(let{bin:e,Cmd:i}of n){let n=e.toLowerCase();this._installBin(t,n,i),r.push(n)}for(let i of e.aliases||[]){let e=i.toLowerCase();if(!r.includes(e)&&n.length>0){let i=n[0].Cmd;class a extends i{static get name(){return e}get name(){return e}}this._installBin(t,e,a),r.push(e)}}return r}_installBin(e,t,n){let r=`${e}/${t}`;this.context.fs.addFiles({[r]:n}),this.context.fs.setMode(r,365)}_removeBin(e,t){let n=`${e}/${t.toLowerCase()}`;if(this.context.fs._deleteByAbsolutePath)this.context.fs._deleteByAbsolutePath(n),this.context.fs._triggerChange();else try{this.context.fs.deleteFileByPath(n)}catch{}}_restoreCommands(){let e=this._readState(),t=this._getRegistry();for(let[n,r]of Object.entries(e.packages)){let e=t[n]||r;if(e)try{this._registerPackageIntoContext(e)}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 s=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._readState(),d=!1;for(let e=0;e<n.length;e++){let f=n[e];if(!s(f)&&e+1<n.length&&s(n[e+1])){let t=n[++e],a=(r||f).toLowerCase();if(await this._installCustomUrl(a,t,i,u),this.exitCode)return;continue}if(s(f)){let e=f,t=(r||c(e)).toLowerCase();if(await this._installCustomUrl(t,e,i,u),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[o(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.packages[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;try{m=await this._pullPackageWasm(p,i,t.includes(`--preload`))}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 h=Object.assign({},p,m?{wasmPath:m}:{}),g=this._registerPackageIntoContext(h);u.packages[p.name]={name:p.name,bin:p.bin,bins:g,aliases:p.aliases||[],version:p.version,description:p.description,cdnUrl:p.cdnUrl,wasmUrl:p.wasmUrl,wasmPath:m||p.wasmPath,type:p.type,adapter:p.adapter,repl:p.repl,installedAt:new Date().toISOString()},i||(this.stdOut=`Setting up ${p.name} (${p.version}) -> /bin/${g.join(`, /bin/`)} ...`)}this._writeState(u)}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){let r=this.constructor._config||{},i=r.fetch||(typeof fetch==`function`?fetch:null),{loadModule:a}=re(),o=null,s=null,l=e.wasmUrl||(/\.(wasm|wat)(\?.*)?$/i.test(e.cdnUrl||``)?e.cdnUrl:null);if(l&&i)try{let n=await i(l);n&&n.ok?o=await this._readResponseBytes(n,`${e.name}.wasm`,t):s=Error(`HTTP ${n?n.status:`error`} fetching ${l}`)}catch(e){s=e}if(!o&&i&&!r.moduleLoader){let n=this._extractNpmSpec(e);if(n){let r=await this._discoverWasmFromJsDelivr(n,e.name,i,t);r&&r.bytes&&(o=r.bytes,e.wasmUrl=r.url,s=null)}}let u=null,d=null;if(e.cdnUrl||r.moduleLoader){let t=typeof globalThis.fetch==`function`?globalThis.fetch:null;t&&o&&o.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(o,{status:200,headers:{"Content-Type":`application/wasm`}}):t(e,n)});try{u=await a(e.name,e.cdnUrl,r.moduleLoader)}catch(e){if(d=e,n)throw e}finally{t&&(globalThis.fetch=t)}}if(!o&&u){let e=u.default===void 0?u:u.default;e instanceof Uint8Array?o=e:e instanceof ArrayBuffer?o=new Uint8Array(e):e&&(e.wasmBytes instanceof Uint8Array||e.wasm instanceof Uint8Array||e.wasmBinary instanceof Uint8Array)&&(o=e.wasmBytes||e.wasm||e.wasmBinary)}if(!o&&e.cdnUrl&&i&&!r.moduleLoader)try{let t=await i(e.cdnUrl);if(t&&t.ok&&typeof t.text==`function`){let e=await t.text();o=this._extractEmbeddedWasmFromText(e)}}catch{}if(!o&&typeof r.moduleLoader==`function`&&(o=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])),!o&&!u&&(s||d)&&!r.moduleLoader)throw s||d;if(o){let t=`/var/lib/wbt/wasm/${e.name}.wasm`;c(this.context.fs,t,o,`application/wasm`);try{this.context.fs.setMode(t,493)}catch{}return t}return null}async _installCustomUrl(e,t,n=!1,r=null){if(!/\.(wasm|wat)(\?.*)?$/i.test(t)&&(/^https?:\/\/esm\.sh\//i.test(t)||/\.(mjs|js)(\?.*)?$/i.test(t))){let i={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()},a=await this._pullPackageWasm(i,n,!1);a&&(i.wasmPath=a),this._registerPackageIntoContext(i);let o=r||this._readState();o.packages[e]=i,this._writeState(o),n||(this.stdOut=`Setting up ${e} (generic runtime) -> /bin/${e} ...`);return}let i=(this.constructor._config||{}).fetch||(typeof fetch==`function`?fetch:null);if(!i){this.stdErr=`E: fetch is not available in this environment`,this.exitCode=1;return}n||(this.stdOut=`Get:1 ${t} ${e}`,this.flush());let a=t.replace(/^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/(?:blob|raw)\/([^/]+)\/(.+)$/i,`https://raw.githubusercontent.com/$1/$2/$3/$4`),o;try{o=await i(a)}catch(e){if(/^https?:\/\/github\.com\/[^/]+\/[^/]+\/releases\/download\//i.test(a))try{o=await i(`https://corsproxy.io/?${encodeURIComponent(a)}`)}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(!o||!o.ok){this.stdErr=`E: HTTP ${o?o.status:`error`} fetching ${t}`,this.exitCode=1;return}let s=t.endsWith(`.wat`),l=`/var/lib/wbt/wasm/${e}${s?`.wat`:`.wasm`}`;if(s){let e=await o.text();this.context.fs._setFileRaw(l,e,!0)}else{let e=await o.arrayBuffer();c(this.fs,l,new Uint8Array(e),`application/wasm`)}this.context.fs.setMode(l,493);let u={name:e,bin:e,bins:[e],version:`custom`,description:`Custom WebAssembly binary from ${t}`,cdnUrl:t,type:`custom-wasm`,wasmPath:l,installedAt:new Date().toISOString()};this._registerPackageIntoContext(u);let d=r||this._readState();d.packages[e]=u,this._writeState(d),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._readState(),r=this.context.getVar(`PATH`)||`/bin`;for(let e of t){let t=o(e),i=n.packages[t]||n.packages[e.toLowerCase()];if(!i){this.stdErr=`E: Package '${e}' is not installed, so not removed`,this.exitCode=1;return}let a=i.bins||[i.bin||i.name,...i.aliases||[]];for(let e of a)this._removeBin(r,e);if(i.wasmPath)try{this.context.fs.deleteFileByPath(i.wasmPath)}catch{}delete n.packages[i.name],this.stdOut=`Removing ${i.name} (${i.version}) ...`}this._writeState(n)}_handleList(e){let t=e.includes(`--installed`)||e.includes(`-i`),n=this._getRegistry(),r=this._readState();this.stdOut=`Listing...`;let i=t?Object.keys(r.packages).sort():Array.from(new Set([...Object.keys(n),...Object.keys(r.packages)])).sort();for(let e of i){let t=n[e],i=r.packages[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._readState();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.description&&e.description.toLowerCase().includes(t)||e.details&&e.details.toLowerCase().includes(t):!0);for(let e of i){let t=r.packages[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=o(t),r=this._getRegistry(),i=this._readState(),a=i.packages[n]||r[n];if(!a){this.stdErr=`E: No packages found matching ${t}`,this.exitCode=100;return}let s=Object.assign({},r[n]||{},a),c=!!i.packages[s.name];this.stdOut=`Package: ${s.name}`,this.stdOut=`Version: ${s.version}`,this.stdOut=`State: ${c?`installed`:`not installed`}`,this.stdOut=`Binary: ${s.bin||s.name}`,s.aliases&&s.aliases.length>0&&(this.stdOut=`Aliases: ${s.aliases.join(`, `)}`),s.size&&(this.stdOut=`Download-Size: ${s.size}`),s.cdnUrl&&(this.stdOut=`APT-Sources: ${s.cdnUrl}`),s.wasmUrl&&(this.stdOut=`WASM-URL: ${s.wasmUrl}`),s.wasmPath&&(this.stdOut=`WASM-File: ${s.wasmPath}`),s.homepage&&(this.stdOut=`Homepage: ${s.homepage}`),this.stdOut=`Description: ${s.description||``}`,s.details&&(this.stdOut=` ${s.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.context.fs._setFileRaw(`${f}/remote-registry.json`,JSON.stringify(r,null,2),!0),this._restoreCommands();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=o(t),r=this._getRegistry(),i=this._readState().packages[n]||r[n];if(!i&&(t.startsWith(`npm:`)||t.startsWith(`esm:`))){let e=t.replace(/^(npm|esm):/i,``),n=e.replace(/^@[^/]+\//,``).split(`@`)[0].toLowerCase();i={name:n,bin:n,version:`latest`,cdnUrl:`https://esm.sh/${e}`,type:`generic-runtime`}}if(!i){this.stdErr=`E: Unable to locate package ${t}`,this.exitCode=100;return}if((i.type===`custom-wasm`||i.type===`wasm`)&&!i.wasmPath)try{let e=await this._pullPackageWasm(i,!0);e&&(i=Object.assign({},i,{wasmPath:e}))}catch(e){this.stdErr=`E: Failed to fetch ${i.name}: ${e.message||e}`,this.exitCode=1;return}let a=this._buildCommandsForPackage(i),s=(a.find(e=>e.bin===t.toLowerCase())||a[0]).Cmd,c=new s(e,this.context);c.requiresFilesystem&&(c.fs=this.context.fs.sandbox()),this._activeSubCommand=c,c.stdinStream=this.stdinStream,c.stdin=this.stdin&&!this.stdin.isTTY?this.stdin:this.stdinStream;let l=e=>{this.stdout&&typeof this.stdout.write==`function`&&this.stdout.write(e)},u=e=>{this.stderr&&typeof this.stderr.write==`function`&&this.stderr.write(e)};c.stdout&&typeof c.stdout.on==`function`&&c.stdout.on(`data`,l),c.stderr&&typeof c.stderr.on==`function`&&c.stderr.on(`data`,u);let d;try{d=await c.runCommand()}finally{this._activeSubCommand=null,c.stdout&&typeof c.stdout.off==`function`&&c.stdout.off(`data`,l),c.stderr&&typeof c.stderr.off==`function`&&c.stderr.off(`data`,u)}if(!c.interactive&&d)for(let e of d.getStdOutput())e.type===`out`?this.stdOut=e.string:e.type===`err`&&(this.stdErr=e.string);this.exitCode=d?d.getExitCode():0}_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)`].forEach(e=>{this.stdOut=e})}};t.exports=m,t.exports.Wbt=m,t.exports.DEFAULT_REGISTRY=a,t.exports.createGenericWasmCommand=l,t.exports.createReplWasmCommand=u}))()})();
|
|
17
17
|
//# sourceMappingURL=wbt.min.js.map
|