UNPKG

wasmrs-js

Version:

A JavaScript implementation of the RSocket protocol over WebAssembly.

1,087 lines (992 loc) 58.5 kB
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var browser = {exports: {}}; /** * Helpers. */ var ms; var hasRequiredMs; function requireMs () { if (hasRequiredMs) return ms; hasRequiredMs = 1; var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ ms = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } return ms; } /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = requireMs(); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } var common = setup; /* eslint-env browser */ (function (module, exports) { /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = common(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; } (browser, browser.exports)); var browserExports = browser.exports; var DEBUG = /*@__PURE__*/getDefaultExportFromCjs(browserExports); const debug$2 = DEBUG('wasmrs'); class TestableError extends Error { matcher() { return new RegExp(this.toString().replace(/^Error: /, '')); } } class HostCallNotImplementedError extends TestableError { constructor(binding, namespace, operation) { super(`Host call not implemented. Guest called host with binding = '${binding}', namespace = '${namespace}', & operation = '${operation}'`); } } var HostProtocolMethods; (function (HostProtocolMethods) { HostProtocolMethods["OP_LIST"] = "__op_list"; HostProtocolMethods["INIT_BUFFERS"] = "__init_buffers"; HostProtocolMethods["CONSOLE_LOG"] = "__console_log"; HostProtocolMethods["SEND"] = "__send"; })(HostProtocolMethods || (HostProtocolMethods = {})); var GuestProtocolMethods; (function (GuestProtocolMethods) { GuestProtocolMethods["START"] = "_start"; GuestProtocolMethods["OP_LIST_REQUEST"] = "__wasmrs_op_list_request"; GuestProtocolMethods["INIT"] = "__wasmrs_init"; GuestProtocolMethods["SEND"] = "__wasmrs_send"; })(GuestProtocolMethods || (GuestProtocolMethods = {})); function fromU32Bytes(bytes) { return (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]; } function toU32Bytes(num) { const result = new Uint8Array(4); result[0] = (num >> 24) % 256; result[1] = (num >> 16) % 256; result[2] = (num >> 8) % 256; result[3] = num % 256; return result; } function toU24Bytes(num) { const result = new Uint8Array(3); result[0] = (num >> 8) >> 8 % 256; result[1] = num >> 8 % 256; result[2] = num % 256; return result; } function fromU24Bytes(bytes) { return (bytes[0] << 16) | (bytes[1] << 8) | bytes[2]; } function fromU16Bytes(bytes) { return (bytes[0] << 8) | bytes[1]; } class ModuleState { guestRequest; guestResponse; hostResponse; guestError; hostError; hostCallback; writer; constructor(hostCall, writer) { this.hostCallback = hostCall || ((binding, namespace, operation) => { throw new HostCallNotImplementedError(binding, namespace, operation); }); this.writer = writer || (() => undefined); } } let WASI$2 = undefined; class WasmRsModule { module; constructor(module) { this.module = module; } // eslint-disable-next-line @typescript-eslint/no-explicit-any static from(any) { if (any instanceof WasmRsModule) { return any; } if (any instanceof WebAssembly.Module) { return new WasmRsModule(any); } if ('module' in any && any.module instanceof WebAssembly.Module) { return new WasmRsModule(any.module); } throw new Error(`cannot convert ${any} to WasmRsModule`); } static async compile(source) { const mod = WebAssembly.compile(source); return new WasmRsModule(await mod); } static async compileStreaming(source) { if (!WebAssembly.compileStreaming) { console.warn('WebAssembly.compileStreaming is not supported on this browser, wasm execution will be impacted.'); const bytes = new Uint8Array(await (await source).arrayBuffer()); return WasmRsModule.compile(bytes); } const mod = WebAssembly.compileStreaming(source); return new WasmRsModule(await mod); } async instantiate(options = {}) { const host = new WasmRsInstance(options); let wasi = undefined; if (options.wasi) { if (!WASI$2) { throw new Error('Wasi options provided but no WASI implementation found'); } wasi = await WASI$2.create(options.wasi); } const imports = linkImports(host, wasi); debug$2('instantiating wasm module'); const instance = await WebAssembly.instantiate(this.module, imports); if (wasi) { wasi.initialize(instance); } await host.initialize(instance); return host; } customSection(name) { return WebAssembly.Module.customSections(this.module, name); } } class WasmRsInstance extends EventTarget { guestBufferStart = 0; hostBufferStart = 0; state; guestSend; guestOpListRequest; textEncoder; textDecoder; instance; operations = new OperationList([], []); constructor(options = {}) { super(); this.state = new ModuleState(options.hostCall, options.writer); this.textEncoder = new TextEncoder(); this.textDecoder = new TextDecoder('utf-8'); this.guestSend = () => undefined; this.guestOpListRequest = () => undefined; } static setWasi(wasi) { WASI$2 = wasi; } initialize(instance) { this.instance = instance; const start = this.instance.exports[GuestProtocolMethods.START]; if (start != null) { debug$2(`>>>`, `${GuestProtocolMethods.START}()`); start([]); } const init = this.getProtocolExport(GuestProtocolMethods.INIT); const size = 512 * 1024; debug$2(`>>>`, `${GuestProtocolMethods.INIT}(${size},${size},${size})`); init(size, size, size); const opList = this.getProtocolExport(GuestProtocolMethods.OP_LIST_REQUEST); if (opList != null) { debug$2(`>>>`, `${GuestProtocolMethods.OP_LIST_REQUEST}()`); opList(); } this.guestSend = this.getProtocolExport(GuestProtocolMethods.SEND); this.guestOpListRequest = this.getProtocolExport(GuestProtocolMethods.OP_LIST_REQUEST); debug$2('initialized wasm module'); } getProtocolExport(name) { const fn = this.instance.exports[name]; if (fn == null) { throw new Error(`WebAssembly module does not export ${name}`); } return fn; } send(payload) { const memory = this.getCallerMemory(); const buffer = new Uint8Array(memory.buffer); debug$2(`writing ${payload.length} bytes to guest memory buffer`, payload, this.guestBufferStart); buffer.set(toU24Bytes(payload.length), this.guestBufferStart); buffer.set(payload, this.guestBufferStart + 3); debug$2(`>>>`, ` ${GuestProtocolMethods.SEND}(${payload.length})`); this.guestSend(payload.length); } getCallerMemory() { return this.instance.exports.memory; } close() { // } } function linkImports(instance, wasi) { if (wasi) { debug$2('enabling wasi'); // This looks like a broken types issue in the wasi module. // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return { wasi_snapshot_preview1: wasi.getImports(), wasmrs: linkHostExports(instance), }; } else { debug$2('disabling wasi'); return { wasmrs: linkHostExports(instance), }; } } class FrameEvent extends Event { payload; constructor(type, payload) { super(type); this.payload = payload; } } function linkHostExports(instance) { return { [HostProtocolMethods.CONSOLE_LOG](ptr, len) { debug$2('<<< __console_log %o bytes @ %o', len, ptr); const buffer = new Uint8Array(instance.getCallerMemory().buffer); const bytes = buffer.slice(ptr, ptr + len); console.log(instance.textDecoder.decode(bytes)); }, [HostProtocolMethods.INIT_BUFFERS](guestBufferPtr, hostBufferPtr) { debug$2('<<< __init_buffers(%o, %o)', guestBufferPtr, hostBufferPtr); instance.guestBufferStart = guestBufferPtr; instance.hostBufferStart = hostBufferPtr; }, [HostProtocolMethods.SEND](length) { debug$2('<<< __send(%o)', length); const buffer = new Uint8Array(instance.getCallerMemory().buffer); const bytes = buffer.slice(instance.hostBufferStart, instance.hostBufferStart + length); debug$2(`'frame' event: ${bytes.length} bytes`, Array.from(bytes) .map((n) => { if (n > 16 && n < 127) { return String.fromCharCode(n); } else { return `\\x${n.toString(16)}`; } }) .join('')); let done = false; let index = 0; while (!done) { const len = fromU24Bytes(bytes.slice(index, 3)); const frame = bytes.slice(index + 3, index + 3 + len); instance.dispatchEvent(new FrameEvent('frame', frame)); index += 3 + len; done = index >= bytes.length; } }, [HostProtocolMethods.OP_LIST](ptr, length) { debug$2('<<< __op_list(%o,%o)', ptr, length); const buffer = new Uint8Array(instance.getCallerMemory().buffer); const bytes = buffer.slice(ptr, ptr + length); if (length === 0) { return; } if (bytes.slice(0, 4).toString() !== OP_MAGIC_BYTES.toString()) { throw new Error('invalid op_list magic bytes'); } const version = fromU16Bytes(bytes.slice(4, 6)); debug$2(`op_list bytes: %o`, bytes); if (version == 1) { const ops = decodeV1Operations(bytes.slice(6), instance.textDecoder); debug$2('module operations: %o', ops); instance.operations = ops; } }, }; } function decodeV1Operations(buffer, decoder) { const imports = []; const exports = []; let numOps = fromU32Bytes(buffer.slice(0, 4)); debug$2(`decoding %o operations`, numOps); let index = 4; while (numOps > 0) { const kind = buffer[index++]; const dir = buffer[index++]; const opIndex = fromU32Bytes(buffer.slice(index, index + 4)); index += 4; const nsLen = fromU16Bytes(buffer.slice(index, index + 2)); index += 2; const namespace = decoder.decode(buffer.slice(index, index + nsLen)); index += nsLen; const opLen = fromU16Bytes(buffer.slice(index, index + 2)); index += 2; const operation = decoder.decode(buffer.slice(index, index + opLen)); index += opLen; const reservedLen = fromU16Bytes(buffer.slice(index, index + 2)); index += 2 + reservedLen; const op = new Operation(opIndex, kind, namespace, operation); if (dir === 1) { exports.push(op); } else { imports.push(op); } numOps--; } return new OperationList(imports, exports); } class OperationList { imports; exports; constructor(imports, exports) { this.imports = imports; this.exports = exports; } getExport(namespace, operation) { const op = this.exports.find((op) => op.namespace === namespace && op.operation === operation); if (!op) { throw new Error(`operation ${namespace}::${operation} not found in exports`); } return op; } getImport(namespace, operation) { const op = this.imports.find((op) => op.namespace === namespace && op.operation === operation); if (!op) { throw new Error(`operation ${namespace}::${operation} not found in imports`); } return op; } } class Operation { index; kind; namespace; operation; constructor(index, kind, namespace, operation) { this.index = index; this.kind = kind; this.namespace = namespace; this.operation = operation; } asEncoded() { const index = toU32Bytes(this.index); const encoded = new Uint8Array(index.length + 4); encoded.set(index); encoded.set(toU32Bytes(0), index.length); return encoded; } } var OperationType; (function (OperationType) { OperationType[OperationType["RR"] = 0] = "RR"; OperationType[OperationType["FNF"] = 1] = "FNF"; OperationType[OperationType["RS"] = 2] = "RS"; OperationType[OperationType["RC"] = 3] = "RC"; })(OperationType || (OperationType = {})); const OP_MAGIC_BYTES = Uint8Array.from([0x00, 0x77, 0x72, 0x73]); const CLOCKID_REALTIME=0;const CLOCKID_MONOTONIC=1;const ERRNO_SUCCESS=0;const ERRNO_BADF=8;const ERRNO_EXIST=20;const ERRNO_INVAL=28;const ERRNO_ISDIR=31;const ERRNO_NOENT=44;const ERRNO_PERM=63;const RIGHTS_FD_READ=1<<1;const RIGHTS_FD_WRITE=1<<6;class Iovec{static read_bytes(view,ptr){const iovec=new Iovec;iovec.buf=view.getUint32(ptr,true);iovec.buf_len=view.getUint32(ptr+4,true);return iovec}static read_bytes_array(view,ptr,len){const iovecs=[];for(let i=0;i<len;i++){iovecs.push(Iovec.read_bytes(view,ptr+8*i));}return iovecs}}class Ciovec{static read_bytes(view,ptr){const iovec=new Ciovec;iovec.buf=view.getUint32(ptr,true);iovec.buf_len=view.getUint32(ptr+4,true);return iovec}static read_bytes_array(view,ptr,len){const iovecs=[];for(let i=0;i<len;i++){iovecs.push(Ciovec.read_bytes(view,ptr+8*i));}return iovecs}}const WHENCE_SET=0;const WHENCE_CUR=1;const WHENCE_END=2;const FILETYPE_DIRECTORY=3;const FILETYPE_REGULAR_FILE=4;class Dirent{head_length(){return 24}name_length(){return this.dir_name.byteLength}write_head_bytes(view,ptr){view.setBigUint64(ptr,this.d_next,true);view.setBigUint64(ptr+8,this.d_ino,true);view.setUint32(ptr+16,this.dir_name.length,true);view.setUint8(ptr+20,this.d_type);}write_name_bytes(view8,ptr,buf_len){view8.set(this.dir_name.slice(0,Math.min(this.dir_name.byteLength,buf_len)),ptr);}constructor(next_cookie,name,type){this.d_ino=1n;const encoded_name=new TextEncoder().encode(name);this.d_next=next_cookie;this.d_namlen=encoded_name.byteLength;this.d_type=type;this.dir_name=encoded_name;}}const FDFLAGS_APPEND=1<<0;class Fdstat{write_bytes(view,ptr){view.setUint8(ptr,this.fs_filetype);view.setUint16(ptr+2,this.fs_flags,true);view.setBigUint64(ptr+8,this.fs_rights_base,true);view.setBigUint64(ptr+16,this.fs_rights_inherited,true);}constructor(filetype,flags,fs_rights_base=0n){this.fs_rights_base=0n;this.fs_rights_inherited=0n;this.fs_filetype=filetype;this.fs_flags=flags;this.fs_rights_base=fs_rights_base;}}const OFLAGS_CREAT=1<<0;const OFLAGS_DIRECTORY=1<<1;const OFLAGS_EXCL=1<<2;const OFLAGS_TRUNC=1<<3;class Filestat{write_bytes(view,ptr){view.setBigUint64(ptr,this.dev,true);view.setBigUint64(ptr+8,this.ino,true);view.setUint8(ptr+16,this.filetype);view.setBigUint64(ptr+24,this.nlink,true);view.setBigUint64(ptr+32,this.size,true);view.setBigUint64(ptr+38,this.atim,true);view.setBigUint64(ptr+46,this.mtim,true);view.setBigUint64(ptr+52,this.ctim,true);}constructor(filetype,size){this.dev=0n;this.ino=0n;this.nlink=0n;this.atim=0n;this.mtim=0n;this.ctim=0n;this.filetype=filetype;this.size=size;}}const PREOPENTYPE_DIR=0;class PrestatDir{write_bytes(view,ptr){view.setUint32(ptr,this.pr_name_len,true);}constructor(name_len){this.pr_name_len=name_len;}}class Prestat{static dir(name_len){const prestat=new Prestat;prestat.tag=PREOPENTYPE_DIR;prestat.inner=new PrestatDir(name_len);return prestat}write_bytes(view,ptr){view.setUint32(ptr,this.tag,true);this.inner.write_bytes(view,ptr+4);}} let Debug=class Debug{enable(enabled){this.log=createLogger(enabled===undefined?true:enabled,this.prefix);}get enabled(){return this.isEnabled}constructor(isEnabled){this.isEnabled=isEnabled;this.prefix="wasi:";this.enable(isEnabled);}};function createLogger(enabled,prefix){if(enabled){const a=console.log.bind(console,"%c%s","color: #265BA0",prefix);return a}else {return ()=>{}}}const debug$1=new Debug(false); let WASI$1=class WASI{start(instance){this.inst=instance;debug$1.log("calling _start");instance.exports._start();}initialize(instance){this.inst=instance;if(instance.exports._initialize){debug$1.log("calling _initialize");instance.exports._initialize();}else {debug$1.log("no _initialize found");}}constructor(args=[],env=[],fds=[],options={}){this.args=[];this.env=[];this.fds=[];debug$1.enable(options.debug);debug$1.log("initializing wasi",{args,env,fds});this.args=args;this.env=env;this.fds=fds;const self=this;this.wasiImport={args_sizes_get(argc,argv_buf_size){const buffer=new DataView(self.inst.exports.memory.buffer);buffer.setUint32(argc,self.args.length,true);let buf_size=0;for(const arg of self.args){buf_size+=arg.length+1;}buffer.setUint32(argv_buf_size,buf_size,true);debug$1.log(buffer.getUint32(argc,true),buffer.getUint32(argv_buf_size,true));return 0},args_get(argv,argv_buf){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);const orig_argv_buf=argv_buf;for(let i=0;i<self.args.length;i++){buffer.setUint32(argv,argv_buf,true);argv+=4;const arg=new TextEncoder().encode(self.args[i]);buffer8.set(arg,argv_buf);buffer.setUint8(argv_buf+arg.length,0);argv_buf+=arg.length+1;}if(debug$1.enabled){debug$1.log(new TextDecoder("utf-8").decode(buffer8.slice(orig_argv_buf,argv_buf)));}return 0},environ_sizes_get(environ_count,environ_size){const buffer=new DataView(self.inst.exports.memory.buffer);buffer.setUint32(environ_count,self.env.length,true);let buf_size=0;for(const environ of self.env){buf_size+=environ.length+1;}buffer.setUint32(environ_size,buf_size,true);debug$1.log(buffer.getUint32(environ_count,true),buffer.getUint32(environ_size,true));return 0},environ_get(environ,environ_buf){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);const orig_environ_buf=environ_buf;for(let i=0;i<self.env.length;i++){buffer.setUint32(environ,environ_buf,true);environ+=4;const e=new TextEncoder().encode(self.env[i]);buffer8.set(e,environ_buf);buffer.setUint8(environ_buf+e.length,0);environ_buf+=e.length+1;}if(debug$1.enabled){debug$1.log(new TextDecoder("utf-8").decode(buffer8.slice(orig_environ_buf,environ_buf)));}return 0},clock_res_get(id,res_ptr){throw "unimplemented"},clock_time_get(id,precision,time){const buffer=new DataView(self.inst.exports.memory.buffer);if(id===CLOCKID_REALTIME){buffer.setBigUint64(time,BigInt(new Date().getTime())*1000000n,true);}else if(id==CLOCKID_MONOTONIC){let monotonic_time;try{monotonic_time=BigInt(Math.round(performance.now()*1e6));}catch(e){monotonic_time=0n;}buffer.setBigUint64(time,monotonic_time,true);}else {buffer.setBigUint64(time,0n,true);}return 0},fd_advise(fd,offset,len,advice){if(self.fds[fd]!=undefined){return self.fds[fd].fd_advise(offset,len,advice)}else {return ERRNO_BADF}},fd_allocate(fd,offset,len){if(self.fds[fd]!=undefined){return self.fds[fd].fd_allocate(offset,len)}else {return ERRNO_BADF}},fd_close(fd){if(self.fds[fd]!=undefined){const ret=self.fds[fd].fd_close();self.fds[fd]=undefined;return ret}else {return ERRNO_BADF}},fd_datasync(fd){if(self.fds[fd]!=undefined){return self.fds[fd].fd_datasync()}else {return ERRNO_BADF}},fd_fdstat_get(fd,fdstat_ptr){if(self.fds[fd]!=undefined){const{ret,fdstat}=self.fds[fd].fd_fdstat_get();if(fdstat!=null){fdstat.write_bytes(new DataView(self.inst.exports.memory.buffer),fdstat_ptr);}return ret}else {return ERRNO_BADF}},fd_fdstat_set_flags(fd,flags){if(self.fds[fd]!=undefined){return self.fds[fd].fd_fdstat_set_flags(flags)}else {return ERRNO_BADF}},fd_fdstat_set_rights(fd,fs_rights_base,fs_rights_inheriting){if(self.fds[fd]!=undefined){return self.fds[fd].fd_fdstat_set_rights(fs_rights_base,fs_rights_inheriting)}else {return ERRNO_BADF}},fd_filestat_get(fd,filestat_ptr){if(self.fds[fd]!=undefined){const{ret,filestat}=self.fds[fd].fd_filestat_get();if(filestat!=null){filestat.write_bytes(new DataView(self.inst.exports.memory.buffer),filestat_ptr);}return ret}else {return ERRNO_BADF}},fd_filestat_set_size(fd,size){if(self.fds[fd]!=undefined){return self.fds[fd].fd_filestat_set_size(size)}else {return ERRNO_BADF}},fd_filestat_set_times(fd,atim,mtim,fst_flags){if(self.fds[fd]!=undefined){return self.fds[fd].fd_filestat_set_times(atim,mtim,fst_flags)}else {return ERRNO_BADF}},fd_pread(fd,iovs_ptr,iovs_len,offset,nread_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=Iovec.read_bytes_array(buffer,iovs_ptr,iovs_len);const{ret,nread}=self.fds[fd].fd_pread(buffer8,iovecs,offset);buffer.setUint32(nread_ptr,nread,true);return ret}else {return ERRNO_BADF}},fd_prestat_get(fd,buf_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const{ret,prestat}=self.fds[fd].fd_prestat_get();if(prestat!=null){prestat.write_bytes(buffer,buf_ptr);}return ret}else {return ERRNO_BADF}},fd_prestat_dir_name(fd,path_ptr,path_len){if(self.fds[fd]!=undefined){const{ret,prestat_dir_name}=self.fds[fd].fd_prestat_dir_name();if(prestat_dir_name!=null){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);buffer8.set(prestat_dir_name,path_ptr);}return ret}else {return ERRNO_BADF}},fd_pwrite(fd,iovs_ptr,iovs_len,offset,nwritten_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=Ciovec.read_bytes_array(buffer,iovs_ptr,iovs_len);const{ret,nwritten}=self.fds[fd].fd_pwrite(buffer8,iovecs,offset);buffer.setUint32(nwritten_ptr,nwritten,true);return ret}else {return ERRNO_BADF}},fd_read(fd,iovs_ptr,iovs_len,nread_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=Iovec.read_bytes_array(buffer,iovs_ptr,iovs_len);const{ret,nread}=self.fds[fd].fd_read(buffer8,iovecs);buffer.setUint32(nread_ptr,nread,true);return ret}else {return ERRNO_BADF}},fd_readdir(fd,buf,buf_len,cookie,bufused_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){let bufused=0;while(true){const{ret,dirent}=self.fds[fd].fd_readdir_single(cookie);if(ret!=0){buffer.setUint32(bufused_ptr,bufused,true);return ret}if(dirent==null){break}if(buf_len-bufused<dirent.head_length()){bufused=buf_len;break}const head_bytes=new ArrayBuffer(dirent.head_length());dirent.write_head_bytes(new DataView(head_bytes),0);buffer8.set(new Uint8Array(head_bytes).slice(0,Math.min(head_bytes.byteLength,buf_len-bufused)),buf);buf+=dirent.head_length();bufused+=dirent.head_length();if(buf_len-bufused<dirent.name_length()){bufused=buf_len;break}dirent.write_name_bytes(buffer8,buf,buf_len-bufused);buf+=dirent.name_length();bufused+=dirent.name_length();cookie=dirent.d_next;}buffer.setUint32(bufused_ptr,bufused,true);return 0}else {return ERRNO_BADF}},fd_renumber(fd,to){if(self.fds[fd]!=undefined&&self.fds[to]!=undefined){const ret=self.fds[to].fd_close();if(ret!=0){return ret}self.fds[to]=self.fds[fd];self.fds[fd]=undefined;return 0}else {return ERRNO_BADF}},fd_seek(fd,offset,whence,offset_out_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const{ret,offset:offset_out}=self.fds[fd].fd_seek(offset,whence);buffer.setBigInt64(offset_out_ptr,offset_out,true);return ret}else {return ERRNO_BADF}},fd_sync(fd){if(self.fds[fd]!=undefined){return self.fds[fd].fd_sync()}else {return ERRNO_BADF}},fd_tell(fd,offset_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const{ret,offset}=self.fds[fd].fd_tell();buffer.setBigUint64(offset_ptr,offset,true);return ret}else {return ERRNO_BADF}},fd_write(fd,iovs_ptr,iovs_len,nwritten_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=Ciovec.read_bytes_array(buffer,iovs_ptr,iovs_len);const{ret,nwritten}=self.fds[fd].fd_write(buffer8,iovecs);buffer.setUint32(nwritten_ptr,nwritten,true);return ret}else {return ERRNO_BADF}},path_create_directory(fd,path_ptr,path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_create_directory(path)}else {return ERRNO_BADF}},path_filestat_get(fd,flags,path_ptr,path_len,filestat_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));const{ret,filestat}=self.fds[fd].path_filestat_get(flags,path);if(filestat!=null){filestat.write_bytes(buffer,filestat_ptr);}return ret}else {return ERRNO_BADF}},path_filestat_set_times(fd,flags,path_ptr,path_len,atim,mtim,fst_flags){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_filestat_set_times(flags,path,atim,mtim,fst_flags)}else {return ERRNO_BADF}},path_link(old_fd,old_flags,old_path_ptr,old_path_len,new_fd,new_path_ptr,new_path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[old_fd]!=undefined&&self.fds[new_fd]!=undefined){const old_path=new TextDecoder("utf-8").decode(buffer8.slice(old_path_ptr,old_path_ptr+old_path_len));const new_path=new TextDecoder("utf-8").decode(buffer8.slice(new_path_ptr,new_path_ptr+new_path_len));return self.fds[new_fd].path_link(old_fd,old_flags,old_path,new_path)}else {return ERRNO_BADF}},path_open(fd,dirflags,path_ptr,path_len,oflags,fs_rights_base,fs_rights_inheriting,fd_flags,opened_fd_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));debug$1.log({path});const{ret,fd_obj}=self.fds[fd].path_open(dirflags,path,oflags,fs_rights_base,fs_rights_inheriting,fd_flags);if(ret!=0){return ret}self.fds.push(fd_obj);const opened_fd=self.fds.length-1;buffer.setUint32(opened_fd_ptr,opened_fd,true);return 0}else {return ERRNO_BADF}},path_readlink(fd,path_ptr,path_len,buf_ptr,buf_len,nread_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));debug$1.log({path});const{ret,data}=self.fds[fd].path_readlink(path);if(data!=null){if(data.length>buf_len){buffer.setUint32(nread_ptr,0,true);return ERRNO_BADF}buffer8.set(data,buf_ptr);buffer.setUint32(nread_ptr,data.length,true);}return ret}else {return ERRNO_BADF}},path_remove_directory(fd,path_ptr,path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_remove_directory(path)}else {return ERRNO_BADF}},path_rename(fd,old_path_ptr,old_path_len,new_fd,new_path_ptr,new_path_len){throw "FIXME what is the best abstraction for this?"},path_symlink(old_path_ptr,old_path_len,fd,new_path_ptr,new_path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const old_path=new TextDecoder("utf-8").decode(buffer8.slice(old_path_ptr,old_path_ptr+old_path_len));const new_path=new TextDecoder("utf-8").decode(buffer8.slice(new_path_ptr,new_path_ptr+new_path_len));return self.fds[fd].path_symlink(old_path,new_path)}else {return ERRNO_BADF}},path_unlink_file(fd,path_ptr,path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_unlink_file(path)}else {return ERRNO_BADF}},poll_oneoff(in_,out,nsubscriptions){throw "async io not supported"},proc_exit(exit_code){throw "exit with exit code "+exit_code},proc_raise(sig){throw "raised signal "+sig},sched_yield(){},random_get(buf,buf_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);for(let i=0;i<buf_len;i++){buffer8[buf+i]=Math.random()*256|0;}},sock_recv(fd,ri_data,ri_flags){throw "sockets not supported"},sock_send(fd,si_data,si_flags){throw "sockets not supported"},sock_shutdown(fd,how){throw "sockets not supported"},sock_accept(fd,flags){throw "sockets not supported"}};}}; class Fd{fd_advise(offset,len,advice){return -1}fd_allocate(offset,len){return -1}fd_close(){return 0}fd_datasync(){return -1}fd_fdstat_get(){return {ret:-1,fdstat:null}}fd_fdstat_set_flags(flags){return -1}fd_fdstat_set_rights(fs_rights_base,fs_rights_inheriting){return -1}fd_filestat_get(){return {ret:-1,filestat:null}}fd_filestat_set_size(size){return -1}fd_filestat_set_times(atim,mtim,fst_flags){return -1}fd_pread(view8,iovs,offset){return {ret:-1,nread:0}}fd_prestat_get(){return {ret:-1,prestat:null}}fd_prestat_dir_name(){return {ret:-1,prestat_dir_name:null}}fd_pwrite(view8,iovs,offset){return {ret:-1,nwritten:0}}fd_read(view8,iovs){return {ret:-1,nread:0}}fd_readdir_single(cookie){return {ret:-1,dirent:null}}fd_seek(offset,whence){return {ret:-1,offset:0n}}fd_sync(){return 0}fd_tell(){return {ret:-1,offset:0n}}fd_write(view8,iovs){return {ret:-1,nwritten:0}}path_create_directory(path){return -1}path_filestat_get(flags,path){return {ret:-1,filestat:null}}path_filestat_set_times(flags,path,atim,mtim,fst_flags){return -1}path_link(old_fd,old_flags,old_path,new_path){return -1}path_open(dirflags,path,oflags,fs_rights_base,fs_rights_inheriting,fd_flags){return {ret:-1,fd_obj:null}}path_readlink(path){return {ret:-1,data:null}}path_remove_directory(path){return -1}path_rename(old_path,new_fd,new_path){return -1}path_symlink(old_path,new_path){return -1}path_unlink_file(path){return -1}} class OpenFile extends Fd{fd_fdstat_get(){return {ret:0,fdstat:new Fdstat(FILETYPE_REGULAR_FILE,0,this.fs_rights_base)}}fd_read(view8,iovs){if((Number(this.fs_rights_base)&RIGHTS_FD_READ)!==RIGHTS_FD_READ){return {ret:ERRNO_BADF,nread:0}}let nread=0;for(const iovec of iovs){if(this.file_pos<this.file.data.byteLength){const slice=this.file.data.slice(Number(this.file_pos),Number(this.file_pos+BigInt(iovec.buf_len)));view8.set(slice,iovec.buf);this.file_pos+=BigInt(slice.length);nread+=slice.length;}else {break}}return {ret:0,nread}}fd_seek(offset,whence){let calculated_offset;switch(whence){case WHENCE_SET:calculated_offset=offset;break;case WHENCE_CUR:calculated_offset=this.file_pos+offset;break;case WHENCE_END:calculated_offset=BigInt(this.file.data.byteLength)+offset;break;default:return {ret:ERRNO_INVAL,offset:0n}}if(calculated_offset<0){return {ret:ERRNO_INVAL,offset:0n}}this.file_pos=calculated_offset;return {ret:0,offset:this.file_pos}}fd_write(view8,iovs){let nwritten=0;if(this.file.readonly||(Number(this.fs_rights_base)&RIGHTS_FD_WRITE)===0)return {ret:ERRNO_BADF,nwritten};for(const iovec of iovs){const buffer=view8.slice(iovec.buf,iovec.buf+iovec.buf_len);if(this.file_pos+BigInt(buffer.byteLength)>this.file.size){const old=this.file.data;this.file.data=new Uint8Array(Number(this.file_pos+BigInt(buffer.byteLength)));this.file.data.set(old);}this.file.data.set(buffer.slice(0,Number(this.file.size-this.file_pos)),Number(this.file_pos));this.file_pos+=BigInt(buffer.byteLength);nwritten+=iovec.buf_len;}return {ret:0,nwritten}}fd_filestat_get(){return {ret:0,filestat:this.file.stat()}}constructor(file,fs_rights_base=0n){super();this.file_pos=0n;this.fs_rights_base=0n;this.file=file;this.fs_rights_base=fs_rights_base;}}class OpenSyncOPFSFile extends Fd{fd_fdstat_get(){return {ret:0,fdstat:new Fdstat(FILETYPE_REGULAR_FILE,0)}}fd_filestat_get(){return {ret:0,filestat:new Filestat(FILETYPE_REGULAR_FILE,BigInt(this.file.handle.getSize()))}}fd_read(view8,iovs){if((Number(this.fs_rights_base)&RIGHTS_FD_READ)!==RIGHTS_FD_READ){return {ret:ERRNO_BADF,nread:0}}let nread=0;for(const iovec of iovs){if(this.position<this.file.handle.getSize()){const buf=new Uint8Array(view8.buffer,iovec.buf,iovec.buf_len);const n=this.file.handle.read(buf,{at:Number(this.position)});this.position+=BigInt(n);nread+=n;}else {break}}return {ret:0,nread}}fd_seek(offset,whence){let calculated_offset;switch(whence){case WHENCE_SET:calculated_offset=BigInt(offset);break;case WHENCE_CUR:calculated_offset=this.position+BigInt(offset);break;case WHENCE_END:calculated_offset=BigInt(this.file.handle.getSize())+BigInt(offset);break;default:return {ret:ERRNO_INVAL,offset:0n}}if(calculated_offset<0){return {ret:ERRNO_INVAL,offset:0n}}this.position=calculated_offset;return {ret:ERRNO_SUCCESS,offset:this.position}}fd_write(view8,iovs){let nwritten=0;if(this.file.readonly||(Number(this.fs_rights_base)&RIGHTS_FD_WRITE)===0)return {ret:ERRNO_BADF,nwritten};for(const iovec of iovs){const buf=new Uint8Array(view8.buffer,iovec.buf,iovec.buf_len);const n=this.file.handle.write(buf,{at:Number(this.position)});this.position+=BigInt(n);nwritten+=n;}return {ret:ERRNO_SUCCESS,nwritten}}fd_datasync(){this.file.handle.flush();return ERRNO_SUCCESS}fd_sync(){return this.fd_datasync()}fd_close(){return ERRNO_SUCCESS}constructor(file,fs_rights_base=0n){super();this.position=0n;this.fs_rights_base=0n;this.file=file;this.fs_rights_base=fs_rights_base;}}class OpenDirectory extends Fd{fd_fdstat_get(){return {ret:0,fdstat:new Fdstat(FILETYPE_DIRECTORY,0)}}fd_readdir_single(cookie){if(debug$1.enabled){debug$1.log("readdir_single",cookie);debug$1.log(cookie,Object.keys(this.dir.contents));}debug$1.log(cookie,Object.keys(this.dir.contents).slice(Number(cookie)));if(cookie>=BigInt(Object.keys(this.dir.contents).length)){return {ret:0,dirent:null}}const name=Obje