/** * File Host — provides extern "env" file I/O functions for WASM. * * Maps to `extern "env" fn js_file_*` declarations in * src/files/filesystem.zig (WASM backend). * * Storage model: * - Upload files: registered as browser File objects (lazy, no upfront copy) * - Small files / WASM-created files: stored as Uint8Array in memory * - Download files: accumulated in memory, retrieved via getFileBlob() * - All files identified by virtual paths (string keys) * * For large uploads, the File object is kept as-is and sliced on demand. * WASM extern "env" reads (js_file_read) work from in-memory data only, * so files must be materialized before WASM can access them. For the * JS-level transfer, we stream directly from the File object. */ export class FileHost { /** @type {Map} */ #files = new Map(); /** @type {number} */ #nextId = 1; /** @type {Map} virtual path -> materialized file data */ #registered = new Map(); /** @type {Map} virtual path -> browser File object (lazy, not loaded) */ #browserFiles = new Map(); /** @type {Set} virtual directory paths */ #directories = new Set(); /** @type {() => WebAssembly.Memory} */ #getMemory; /** * @param {() => WebAssembly.Memory} getMemory - Returns the WASM memory instance */ constructor(getMemory) { this.#getMemory = getMemory; } /** * Register in-memory data for virtual file access (small files, WASM downloads). * @param {string} virtualPath * @param {Uint8Array} data */ registerFile(virtualPath, data) { this.#registered.set(virtualPath, data); } /** * Register a browser File object for streaming access. * Does NOT read the file into memory — stores the File handle for * on-demand slice reads via readFileChunk(). * @param {File} file * @returns {string} virtual path */ registerBrowserFile(file) { const virtualPath = file.name; this.#browserFiles.set(virtualPath, file); return virtualPath; } /** * Materialize a browser File into memory so WASM extern "env" can access it. * Only needed if WASM-side code needs to read the file (hashing, etc.). * For JS-level transfers, use readFileChunk() instead. * @param {string} virtualPath * @param {(loaded: number, total: number) => void} [onProgress] * @returns {Promise} */ async materializeFile(virtualPath, onProgress) { const file = this.#browserFiles.get(virtualPath); if (!file) return; if (this.#registered.has(virtualPath)) return; // already materialized const total = file.size; const data = new Uint8Array(total); const chunkSize = 4 * 1024 * 1024; // 4MB chunks let offset = 0; while (offset < total) { const end = Math.min(offset + chunkSize, total); const slice = file.slice(offset, end); const buf = await slice.arrayBuffer(); data.set(new Uint8Array(buf), offset); offset = end; if (onProgress) onProgress(offset, total); } this.#registered.set(virtualPath, data); } /** * Read a chunk from a browser File without loading the whole file. * Returns a Uint8Array of the requested range. * @param {string} virtualPath * @param {number} offset * @param {number} length * @returns {Promise} */ async readFileChunk(virtualPath, offset, length) { // Prefer in-memory data if available const data = this.#registered.get(virtualPath); if (data) { const end = Math.min(offset + length, data.length); return data.subarray(offset, end); } // Stream from File object const file = this.#browserFiles.get(virtualPath); if (!file) throw new Error(`File not found: ${virtualPath}`); const end = Math.min(offset + length, file.size); const slice = file.slice(offset, end); const buf = await slice.arrayBuffer(); return new Uint8Array(buf); } /** * Get file size without loading into memory. * @param {string} virtualPath * @returns {number | null} */ getFileSize(virtualPath) { const data = this.#registered.get(virtualPath); if (data) return data.length; const file = this.#browserFiles.get(virtualPath); if (file) return file.size; return null; } /** * Get a completed download as a Blob. * @param {string} virtualPath * @returns {Blob | null} */ getFileBlob(virtualPath) { const data = this.#registered.get(virtualPath); if (data) return new Blob([data]); const file = this.#browserFiles.get(virtualPath); if (file) return file; // File is already a Blob return null; } /** * Check if a file is registered (either in-memory or as File handle). * @param {string} virtualPath * @returns {boolean} */ hasFile(virtualPath) { return this.#registered.has(virtualPath) || this.#browserFiles.has(virtualPath); } /** * Get all registered file paths. * @returns {string[]} */ listFiles() { return [...new Set([...this.#registered.keys(), ...this.#browserFiles.keys()])]; } // ============================================================ // extern "env" implementations (work with in-memory data only) // ============================================================ #readString(ptr, len) { const bytes = new Uint8Array(this.#getMemory().buffer, ptr, len); return new TextDecoder().decode(bytes); } /** * Open an existing file. Returns file_id >= 0 or -1 on error. * Only works with materialized (in-memory) files. */ js_file_open(pathPtr, pathLen, readOnly) { const path = this.#readString(pathPtr, pathLen); const data = this.#registered.get(path); if (!data) return -1; const fileId = this.#nextId++; this.#files.set(fileId, { data: readOnly ? data : new Uint8Array(data), // copy for writable pos: 0, name: path, readOnly: readOnly === 1, }); return fileId; } /** * Create a new file. Returns file_id >= 0 or -1 on error. */ js_file_create(pathPtr, pathLen) { const path = this.#readString(pathPtr, pathLen); const fileId = this.#nextId++; const data = new Uint8Array(0); this.#registered.set(path, data); this.#files.set(fileId, { data, pos: 0, name: path, readOnly: false, }); return fileId; } /** * Read from file at offset. Returns bytes read or -1 on error. */ js_file_read(fileId, bufPtr, bufLen, offset) { const file = this.#files.get(fileId); if (!file) return -1; // Use BigInt-safe conversion (offset comes as i64 from WASM) const off = Number(offset); const available = Math.max(0, file.data.length - off); const toRead = Math.min(bufLen, available); if (toRead <= 0) return 0; const dest = new Uint8Array(this.#getMemory().buffer, bufPtr, toRead); dest.set(file.data.subarray(off, off + toRead)); return toRead; } /** * Write to file at offset. Returns bytes written or -1 on error. */ js_file_write(fileId, dataPtr, dataLen, offset) { const file = this.#files.get(fileId); if (!file || file.readOnly) return -1; const off = Number(offset); const src = new Uint8Array(this.#getMemory().buffer, dataPtr, dataLen); // Grow file if needed const needed = off + dataLen; if (needed > file.data.length) { const newData = new Uint8Array(needed); newData.set(file.data); file.data = newData; // Update registered copy this.#registered.set(file.name, file.data); } file.data.set(src, off); return dataLen; } /** * Get file size. Returns size >= 0 or -1 on error. */ js_file_get_size(fileId) { const file = this.#files.get(fileId); if (!file) return -1n; // BigInt for i64 return return BigInt(file.data.length); } /** * Close a file handle. */ js_file_close(fileId) { this.#files.delete(fileId); } /** * Check if a file exists. Returns 1 if exists, 0 if not. */ js_file_exists(pathPtr, pathLen) { const path = this.#readString(pathPtr, pathLen); return this.#registered.has(path) || this.#browserFiles.has(path) || this.#directories.has(path) ? 1 : 0; } /** * Delete a file. Returns 1 on success, 0 on failure. */ js_file_delete(pathPtr, pathLen) { const path = this.#readString(pathPtr, pathLen); const a = this.#registered.delete(path); const b = this.#browserFiles.delete(path); return (a || b) ? 1 : 0; } /** * Rename a file. Returns 1 on success, 0 on failure. */ js_file_rename(oldPtr, oldLen, newPtr, newLen) { const oldPath = this.#readString(oldPtr, oldLen); const newPath = this.#readString(newPtr, newLen); const data = this.#registered.get(oldPath); if (data) { this.#registered.delete(oldPath); this.#registered.set(newPath, data); return 1; } const file = this.#browserFiles.get(oldPath); if (file) { this.#browserFiles.delete(oldPath); this.#browserFiles.set(newPath, file); return 1; } return 0; } /** * Create a directory (no-op in memory model, just track it). * Returns 1 on success. */ js_file_mkdir(pathPtr, pathLen) { const path = this.#readString(pathPtr, pathLen); this.#directories.add(path); return 1; } /** * Get the env bindings to merge into the WASM import object. * @returns {Record} */ getEnvBindings() { return { js_file_open: (p, l, r) => this.js_file_open(p, l, r), js_file_create: (p, l) => this.js_file_create(p, l), js_file_read: (f, b, l, o) => this.js_file_read(f, b, l, o), js_file_write: (f, d, l, o) => this.js_file_write(f, d, l, o), js_file_get_size: (f) => this.js_file_get_size(f), js_file_close: (f) => this.js_file_close(f), js_file_exists: (p, l) => this.js_file_exists(p, l), js_file_delete: (p, l) => this.js_file_delete(p, l), js_file_rename: (op, ol, np, nl) => this.js_file_rename(op, ol, np, nl), js_file_mkdir: (p, l) => this.js_file_mkdir(p, l), }; } }