UNPKG

@firesystem/indexeddb

Version:

IndexedDB implementation of Virtual File System

1,080 lines (1,078 loc) 37.3 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { IndexedDBFileSystem: () => IndexedDBFileSystem }); module.exports = __toCommonJS(index_exports); // src/IndexedDBFileSystem.ts var import_core = require("@firesystem/core"); var IndexedDBFileSystem = class extends import_core.BaseFileSystem { constructor(config) { super(); this.db = null; this.watchers = []; this.isInitialized = false; this.events = new import_core.TypedEventEmitter(); this.broadcastChannel = null; this.fileSnapshots = /* @__PURE__ */ new Map(); this.pollingInterval = null; this.enableExternalSync = true; this.deepChangeDetection = false; // Capabilities do IndexedDB this.capabilities = { readonly: false, caseSensitive: true, atomicRename: false, // IndexedDB não tem rename atômico verdadeiro supportsWatch: true, supportsMetadata: true, maxFileSize: void 0, // Depende do browser e quota maxPathLength: 1024 }; this.config = { dbName: config.dbName, version: config.version || 1, storeName: config.storeName || "files", enableExternalSync: config.enableExternalSync ?? true, deepChangeDetection: config.deepChangeDetection ?? false }; this.enableExternalSync = config.enableExternalSync ?? true; this.deepChangeDetection = config.deepChangeDetection ?? false; if (this.enableExternalSync && typeof BroadcastChannel !== "undefined") { this.setupBroadcastChannel(); } } async ensureDB() { if (this.db && this.db.name === this.config.dbName) { return this.db; } return new Promise((resolve, reject) => { const request = indexedDB.open(this.config.dbName, this.config.version); request.onerror = () => { reject(new Error(`Failed to open IndexedDB: ${request.error}`)); }; request.onsuccess = async () => { this.db = request.result; this.isInitialized = true; this.db.onclose = () => { this.db = null; this.isInitialized = false; }; await this.ensureRootExists(); resolve(this.db); }; request.onupgradeneeded = (event) => { const db = event.target.result; if (!db.objectStoreNames.contains(this.config.storeName)) { const store = db.createObjectStore(this.config.storeName, { keyPath: "path" }); store.createIndex("type", "type", { unique: false }); store.createIndex("parent", "parent", { unique: false }); store.createIndex("modified", "modified", { unique: false }); const now = /* @__PURE__ */ new Date(); store.add({ path: "/", type: "directory", size: 0, created: now, modified: now, parent: "" }); } }; }); } async initialize() { const startTime = Date.now(); this.events.emit(import_core.FileSystemEvents.INITIALIZING, void 0); try { const db = await this.ensureDB(); const allFiles = await this.loadAllFiles(); const fileCount = allFiles.length; for (let i = 0; i < allFiles.length; i++) { const file = allFiles[i]; if (file.type === "file") { this.events.emit(import_core.FileSystemEvents.FILE_READ, { path: file.path, size: file.size }); } else { this.events.emit(import_core.FileSystemEvents.DIR_READ, { path: file.path, count: 0 // We'll count children later if needed }); } this.events.emit(import_core.FileSystemEvents.INIT_PROGRESS, { loaded: i + 1, total: fileCount, phase: "loading-files" }); } this.events.emit(import_core.FileSystemEvents.INITIALIZED, { duration: Date.now() - startTime }); } catch (error) { this.events.emit(import_core.FileSystemEvents.INIT_ERROR, { error }); throw error; } } async loadAllFiles() { const db = await this.ensureDB(); return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readonly"); const store = transaction.objectStore(this.config.storeName); const request = store.getAll(); request.onsuccess = () => { const files = request.result; const userFiles = files.filter((f) => f.path !== "/"); resolve(userFiles); }; request.onerror = () => { reject(new Error(`Failed to load files: ${request.error}`)); }; }); } async readFile(path) { const normalized = (0, import_core.normalizePath)(path); const db = await this.ensureDB(); return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readonly"); const store = transaction.objectStore(this.config.storeName); const request = store.get(normalized); request.onsuccess = () => { const file = request.result; if (!file) { reject( new Error(`ENOENT: no such file or directory, open '${path}'`) ); return; } if (file.type === "directory") { reject( new Error( `EISDIR: illegal operation on a directory, read '${path}'` ) ); return; } resolve({ path: file.path, name: (0, import_core.basename)(file.path), type: file.type, size: file.size, created: file.created, modified: file.modified, metadata: file.metadata, content: file.content }); }; request.onerror = () => { reject(new Error(`Failed to read file: ${request.error}`)); }; }); } async writeFile(path, content, metadata) { const normalized = (0, import_core.normalizePath)(path); const db = await this.ensureDB(); await this.ensureParentExists(normalized); const now = /* @__PURE__ */ new Date(); const size = this.calculateSize(content); return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readwrite"); const store = transaction.objectStore(this.config.storeName); const getRequest = store.get(normalized); getRequest.onsuccess = () => { const existing = getRequest.result; const isUpdate = !!existing; const storedFile = { path: normalized, type: "file", content, size, created: existing?.created || now, modified: now, metadata, parent: (0, import_core.dirname)(normalized) }; const putRequest = store.put(storedFile); putRequest.onsuccess = () => { const entry = { path: normalized, name: (0, import_core.basename)(normalized), type: "file", size, created: storedFile.created, modified: storedFile.modified, metadata, content }; const event = { type: isUpdate ? "updated" : "created", path: normalized, timestamp: now }; this.notifyWatchers(event); this.broadcastChange({ ...event, size, isDirectory: false, fileType: "file" }); resolve(entry); }; putRequest.onerror = () => { reject(new Error(`Failed to write file: ${putRequest.error}`)); }; }; getRequest.onerror = () => { reject(new Error(`Failed to check existing file: ${getRequest.error}`)); }; }); } async deleteFile(path) { const normalized = (0, import_core.normalizePath)(path); const db = await this.ensureDB(); const file = await this.stat(normalized).catch(() => null); if (!file) { throw new Error(`ENOENT: no such file or directory, unlink '${path}'`); } return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readwrite"); const store = transaction.objectStore(this.config.storeName); if (file.type === "directory") { const index = store.index("parent"); const request = index.count(normalized); request.onsuccess = () => { if (request.result > 0) { reject( new Error(`ENOTEMPTY: directory not empty, rmdir '${path}'`) ); return; } const deleteRequest = store.delete(normalized); deleteRequest.onsuccess = () => { const event = { type: "deleted", path: normalized, timestamp: /* @__PURE__ */ new Date() }; this.notifyWatchers(event); this.broadcastChange(event); resolve(); }; deleteRequest.onerror = () => { reject( new Error(`Failed to delete directory: ${deleteRequest.error}`) ); }; }; request.onerror = () => { reject( new Error(`Failed to check directory contents: ${request.error}`) ); }; } else { const request = store.delete(normalized); request.onsuccess = () => { const event = { type: "deleted", path: normalized, timestamp: /* @__PURE__ */ new Date() }; this.notifyWatchers(event); this.broadcastChange(event); resolve(); }; request.onerror = () => { reject(new Error(`Failed to delete file: ${request.error}`)); }; } }); } async exists(path) { const normalized = (0, import_core.normalizePath)(path); const db = await this.ensureDB(); return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readonly"); const store = transaction.objectStore(this.config.storeName); const request = store.count(normalized); request.onsuccess = () => { resolve(request.result > 0); }; request.onerror = () => { reject(new Error(`Failed to check existence: ${request.error}`)); }; }); } async readDir(path) { const normalized = (0, import_core.normalizePath)(path); const db = await this.ensureDB(); if (normalized !== "/" && !await this.exists(normalized)) { throw new Error(`ENOENT: no such file or directory, scandir '${path}'`); } return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readonly"); const store = transaction.objectStore(this.config.storeName); const index = store.index("parent"); const request = index.getAll(normalized); request.onsuccess = () => { const files = request.result; const entries = files.map((file) => ({ path: file.path, name: (0, import_core.basename)(file.path), type: file.type, size: file.size, created: file.created, modified: file.modified, metadata: file.metadata })); resolve(entries); }; request.onerror = () => { reject(new Error(`Failed to read directory: ${request.error}`)); }; }); } async mkdir(path, recursive = false) { const normalized = (0, import_core.normalizePath)(path); if (normalized === "/") { throw new Error(`EEXIST: file already exists, mkdir '${path}'`); } const db = await this.ensureDB(); if (await this.exists(normalized)) { throw new Error(`EEXIST: file already exists, mkdir '${path}'`); } const parent = (0, import_core.dirname)(normalized); if (!recursive && parent !== "/" && !await this.exists(parent)) { throw new Error(`ENOENT: no such file or directory, mkdir '${path}'`); } if (recursive && parent !== "/" && !await this.exists(parent)) { await this.mkdir(parent, true); } const now = /* @__PURE__ */ new Date(); return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readwrite"); const store = transaction.objectStore(this.config.storeName); const storedFile = { path: normalized, type: "directory", size: 0, created: now, modified: now, parent: (0, import_core.dirname)(normalized) }; const request = store.add(storedFile); request.onsuccess = () => { const entry = { path: normalized, name: (0, import_core.basename)(normalized), type: "directory", size: 0, created: now, modified: now }; const event = { type: "created", path: normalized, timestamp: now }; this.notifyWatchers(event); this.broadcastChange({ ...event, isDirectory: true, fileType: "directory" }); resolve(entry); }; request.onerror = () => { reject(new Error(`Failed to create directory: ${request.error}`)); }; }); } async rmdir(path, recursive = false) { const normalized = (0, import_core.normalizePath)(path); if (normalized === "/") { throw new Error(`EBUSY: resource busy or locked, rmdir '${path}'`); } const db = await this.ensureDB(); const stat = await this.stat(normalized).catch(() => null); if (!stat) { throw new Error(`ENOENT: no such file or directory, rmdir '${path}'`); } if (stat.type !== "directory") { throw new Error(`ENOTDIR: not a directory, rmdir '${path}'`); } if (recursive) { await this.deleteRecursive(normalized); } else { const contents = await this.readDir(normalized); if (contents.length > 0) { throw new Error(`ENOTEMPTY: directory not empty, rmdir '${path}'`); } } await this.deleteFile(normalized); } async rename(oldPath, newPath) { const oldNormalized = (0, import_core.normalizePath)(oldPath); const newNormalized = (0, import_core.normalizePath)(newPath); const db = await this.ensureDB(); const oldStat = await this.stat(oldNormalized); await this.ensureParentExists(newNormalized); if (await this.exists(newNormalized)) { throw new Error( `EEXIST: file already exists, rename '${oldPath}' -> '${newPath}'` ); } const now = /* @__PURE__ */ new Date(); return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readwrite"); const store = transaction.objectStore(this.config.storeName); if (oldStat.type === "directory") { const request = store.openCursor(); const updates = []; request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const file = cursor.value; if (file.path.startsWith(oldNormalized + "/") || file.path === oldNormalized) { const newFilePath = file.path.replace( oldNormalized, newNormalized ); updates.push({ ...file, path: newFilePath, parent: (0, import_core.dirname)(newFilePath), modified: file.path === oldNormalized ? now : file.modified }); } cursor.continue(); } else { let completed = 0; const total = updates.length; if (total === 0) { reject(new Error(`Directory not found: ${oldPath}`)); return; } updates.forEach((file) => { store.delete(file.path.replace(newNormalized, oldNormalized)); const addRequest = store.add(file); addRequest.onsuccess = () => { completed++; if (completed === total) { const entry = updates.find((f) => f.path === newNormalized); const event2 = { type: "renamed", path: newNormalized, oldPath: oldNormalized, timestamp: now }; this.notifyWatchers(event2); this.broadcastChange(event2); resolve({ path: entry.path, name: (0, import_core.basename)(entry.path), type: entry.type, size: entry.size, created: entry.created, modified: entry.modified, metadata: entry.metadata }); } }; addRequest.onerror = () => { reject( new Error(`Failed to rename directory: ${addRequest.error}`) ); }; }); } }; request.onerror = () => { reject(new Error(`Failed to read files: ${request.error}`)); }; } else { const getRequest = store.get(oldNormalized); getRequest.onsuccess = () => { const file = getRequest.result; if (!file) { reject(new Error(`File not found: ${oldPath}`)); return; } store.delete(oldNormalized); const newFile = { ...file, path: newNormalized, parent: (0, import_core.dirname)(newNormalized), modified: now }; const addRequest = store.add(newFile); addRequest.onsuccess = () => { const entry = { path: newNormalized, name: (0, import_core.basename)(newNormalized), type: file.type, size: file.size, created: file.created, modified: now, metadata: file.metadata, content: file.content }; const event = { type: "renamed", path: newNormalized, oldPath: oldNormalized, timestamp: now }; this.notifyWatchers(event); this.broadcastChange(event); resolve(entry); }; addRequest.onerror = () => { reject(new Error(`Failed to rename file: ${addRequest.error}`)); }; }; getRequest.onerror = () => { reject(new Error(`Failed to read file: ${getRequest.error}`)); }; } }); } async move(sourcePaths, targetPath) { const targetNormalized = (0, import_core.normalizePath)(targetPath); const targetStat = await this.stat(targetNormalized).catch(() => null); if (!targetStat || targetStat.type !== "directory") { throw new Error(`ENOTDIR: not a directory, move to '${targetPath}'`); } for (const sourcePath of sourcePaths) { const name = (0, import_core.basename)(sourcePath); const newPath = (0, import_core.join)(targetNormalized, name); await this.rename(sourcePath, newPath); } } async copy(sourcePath, targetPath) { const sourceNormalized = (0, import_core.normalizePath)(sourcePath); const targetNormalized = (0, import_core.normalizePath)(targetPath); const source = await this.readFile(sourceNormalized); return this.writeFile(targetNormalized, source.content, source.metadata); } watch(pattern, callback) { const id = this.generateWatcherId(); const listener = { id, pattern, callback }; this.watchers.push(listener); return { dispose: () => { const index = this.watchers.findIndex((w) => w.id === id); if (index !== -1) { this.watchers.splice(index, 1); } } }; } async stat(path) { const normalized = (0, import_core.normalizePath)(path); const db = await this.ensureDB(); return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readonly"); const store = transaction.objectStore(this.config.storeName); const request = store.get(normalized); request.onsuccess = () => { const file = request.result; if (!file) { reject( new Error(`ENOENT: no such file or directory, stat '${path}'`) ); return; } resolve({ path: file.path, size: file.size, type: file.type, created: file.created, modified: file.modified, readonly: false // Sempre false em IndexedDB }); }; request.onerror = () => { reject(new Error(`Failed to stat file: ${request.error}`)); }; }); } async glob(pattern) { const db = await this.ensureDB(); return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readonly"); const store = transaction.objectStore(this.config.storeName); const request = store.getAll(); request.onsuccess = () => { const files = request.result; const paths = files.map((file) => file.path).filter((path) => this.matchesPattern(path, pattern)).sort(); resolve(paths); }; request.onerror = () => { reject(new Error(`Failed to glob: ${request.error}`)); }; }); } async clear() { const startTime = Date.now(); const operationId = `clear-${startTime}`; this.events.emit(import_core.FileSystemEvents.OPERATION_START, { operation: "clear", id: operationId }); this.events.emit(import_core.FileSystemEvents.STORAGE_CLEARING, void 0); try { const db = await this.ensureDB(); await new Promise((resolve, reject) => { const transaction = db.transaction( [this.config.storeName], "readwrite" ); const store = transaction.objectStore(this.config.storeName); const request = store.clear(); request.onsuccess = () => { const rootTransaction = db.transaction( [this.config.storeName], "readwrite" ); const rootStore = rootTransaction.objectStore(this.config.storeName); const now = /* @__PURE__ */ new Date(); const rootDir = { path: "/", type: "directory", size: 0, created: now, modified: now, parent: "" }; const rootRequest = rootStore.add(rootDir); rootRequest.onsuccess = () => resolve(); rootRequest.onerror = () => reject(new Error(`Failed to recreate root: ${rootRequest.error}`)); }; request.onerror = () => { reject(new Error(`Failed to clear store: ${request.error}`)); }; }); const duration = Date.now() - startTime; this.events.emit(import_core.FileSystemEvents.STORAGE_CLEARED, { duration }); this.events.emit(import_core.FileSystemEvents.OPERATION_END, { operation: "clear", id: operationId, duration }); } catch (error) { this.events.emit(import_core.FileSystemEvents.OPERATION_ERROR, { operation: "clear", error }); throw error; } } async size() { const startTime = Date.now(); const operationId = `size-${startTime}`; this.events.emit(import_core.FileSystemEvents.OPERATION_START, { operation: "size", id: operationId }); try { const db = await this.ensureDB(); const totalSize = await new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readonly"); const store = transaction.objectStore(this.config.storeName); const request = store.getAll(); request.onsuccess = () => { const files = request.result; const size = files.reduce((sum, file) => sum + file.size, 0); resolve(size); }; request.onerror = () => { reject(new Error(`Failed to calculate size: ${request.error}`)); }; }); this.events.emit(import_core.FileSystemEvents.STORAGE_SIZE_CALCULATED, { size: totalSize }); this.events.emit(import_core.FileSystemEvents.OPERATION_END, { operation: "size", id: operationId, duration: Date.now() - startTime }); return totalSize; } catch (error) { this.events.emit(import_core.FileSystemEvents.OPERATION_ERROR, { operation: "size", error }); throw error; } } // Helper methods async calculateHash(data) { const str = typeof data === "string" ? data : JSON.stringify(data); let hash = 0; for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; } return hash.toString(36); } calculateSize(content) { if (content === null || content === void 0) { return 0; } if (typeof content === "string") { return new Blob([content]).size; } if (content instanceof ArrayBuffer) { return content.byteLength; } if (content instanceof Blob) { return content.size; } if (typeof content === "object") { return new Blob([JSON.stringify(content)]).size; } return 0; } async ensureParentExists(path) { const parent = (0, import_core.dirname)(path); if (parent === "/" || parent === path) return; if (!await this.exists(parent)) { throw new Error(`ENOENT: no such file or directory, open '${path}'`); } } async deleteRecursive(path) { const entries = await this.readDir(path); for (const entry of entries) { if (entry.type === "directory") { await this.deleteRecursive(entry.path); } await this.deleteFile(entry.path); } } matchesPattern(path, pattern) { if (pattern === "**" || pattern === "**/*") { return true; } if (pattern === "*") { return path.split("/").length === 2 && path !== "/"; } let regex = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "___GLOBSTAR___").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/___GLOBSTAR___\//g, "(.*/)?").replace(/\/___GLOBSTAR___/g, "(/.*)?").replace(/___GLOBSTAR___/g, ".*"); regex = "^" + regex + "$"; return new RegExp(regex).test(path); } notifyWatchers(event) { for (const watcher of this.watchers) { if (this.matchesPattern(event.path, watcher.pattern)) { try { watcher.callback(event); } catch (error) { console.error( `Error in watch callback for pattern "${watcher.pattern}":`, error ); } } } } generateWatcherId() { return `watch_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; } async ensureRootExists() { if (!this.db) return; const transaction = this.db.transaction( [this.config.storeName], "readonly" ); const store = transaction.objectStore(this.config.storeName); const request = store.get("/"); return new Promise((resolve) => { request.onsuccess = async () => { if (!request.result) { const writeTransaction = this.db.transaction( [this.config.storeName], "readwrite" ); const writeStore = writeTransaction.objectStore( this.config.storeName ); const now = /* @__PURE__ */ new Date(); await new Promise((res, rej) => { const addRequest = writeStore.add({ path: "/", type: "directory", size: 0, created: now, modified: now, parent: "" }); addRequest.onsuccess = () => res(); addRequest.onerror = () => rej(new Error("Failed to create root directory")); }); } resolve(); }; request.onerror = () => resolve(); }); } setupBroadcastChannel() { this.broadcastChannel = new BroadcastChannel(`vfs-${this.config.dbName}`); this.broadcastChannel.onmessage = (event) => { const { type, path, oldPath, timestamp } = event.data; this.notifyWatchers({ type, path, oldPath, timestamp: new Date(timestamp) }); switch (type) { case "created": if (event.data.isDirectory) { this.events.emit(import_core.FileSystemEvents.DIR_CREATED, { path }); } else { this.events.emit(import_core.FileSystemEvents.FILE_WRITTEN, { path, size: event.data.size || 0 }); } break; case "updated": this.events.emit(import_core.FileSystemEvents.FILE_WRITTEN, { path, size: event.data.size || 0 }); break; case "deleted": this.events.emit(import_core.FileSystemEvents.FILE_DELETED, { path }); break; case "renamed": if (oldPath) { this.events.emit(import_core.FileSystemEvents.FILE_DELETED, { path: oldPath }); } this.events.emit(import_core.FileSystemEvents.FILE_WRITTEN, { path, size: event.data.size || 0 }); break; } }; } broadcastChange(event) { if (this.broadcastChannel) { this.broadcastChannel.postMessage({ ...event, timestamp: event.timestamp.toISOString() }); } } async startWatching(pollingIntervalMs = 250) { if (!this.enableExternalSync) return; await this.updateFileSnapshots(); this.pollingInterval = setInterval(async () => { await this.checkForExternalChanges(); }, pollingIntervalMs); } async stopWatching() { if (this.pollingInterval) { clearInterval(this.pollingInterval); this.pollingInterval = null; } } async updateFileSnapshots() { const db = await this.ensureDB(); return new Promise((resolve, reject) => { const transaction = db.transaction([this.config.storeName], "readonly"); const store = transaction.objectStore(this.config.storeName); const request = store.getAll(); request.onsuccess = async () => { const files = request.result; this.fileSnapshots.clear(); for (const file of files) { if (file.path !== "/") { const snapshot = { path: file.path, type: file.type, modified: file.modified, size: file.size }; if (this.deepChangeDetection && file.type === "file") { snapshot.contentHash = await this.calculateHash(file.content); if (file.metadata) { snapshot.metadataHash = await this.calculateHash(file.metadata); } } this.fileSnapshots.set(file.path, snapshot); } } resolve(); }; request.onerror = () => { reject(new Error(`Failed to update snapshots: ${request.error}`)); }; }); } async checkForExternalChanges() { const db = await this.ensureDB(); const currentFiles = /* @__PURE__ */ new Map(); const filesToDeepCheck = []; return new Promise((resolve) => { const transaction = db.transaction([this.config.storeName], "readonly"); const store = transaction.objectStore(this.config.storeName); const request = store.getAll(); request.onsuccess = async () => { const files = request.result; files.forEach((file) => { if (file.path !== "/") { currentFiles.set(file.path, { path: file.path, type: file.type, modified: file.modified, size: file.size }); } }); currentFiles.forEach((current, path) => { const snapshot = this.fileSnapshots.get(path); if (!snapshot) { this.notifyWatchers({ type: "created", path, timestamp: /* @__PURE__ */ new Date() }); if (current.type === "directory") { this.events.emit(import_core.FileSystemEvents.DIR_CREATED, { path }); } else { this.events.emit(import_core.FileSystemEvents.FILE_WRITTEN, { path, size: current.size }); } } else if (current.modified.getTime() !== snapshot.modified.getTime() || current.size !== snapshot.size) { this.notifyWatchers({ type: "updated", path, timestamp: /* @__PURE__ */ new Date() }); if (current.type === "file") { this.events.emit(import_core.FileSystemEvents.FILE_WRITTEN, { path, size: current.size }); } } else if (this.deepChangeDetection && current.type === "file") { filesToDeepCheck.push(path); } }); this.fileSnapshots.forEach((snapshot, path) => { if (!currentFiles.has(path)) { this.notifyWatchers({ type: "deleted", path, timestamp: /* @__PURE__ */ new Date() }); if (snapshot.type === "directory") { this.events.emit(import_core.FileSystemEvents.DIR_DELETED, { path }); } else { this.events.emit(import_core.FileSystemEvents.FILE_DELETED, { path }); } } }); if (filesToDeepCheck.length > 0) { await this.performDeepContentCheck(filesToDeepCheck, files); } if (this.deepChangeDetection) { for (const file of files) { if (file.type === "file" && file.path !== "/") { const snapshot = currentFiles.get(file.path); if (snapshot) { snapshot.contentHash = await this.calculateHash(file.content); if (file.metadata) { snapshot.metadataHash = await this.calculateHash(file.metadata); } } } } } this.fileSnapshots = currentFiles; resolve(); }; request.onerror = () => resolve(); }); } async performDeepContentCheck(paths, allFiles) { for (const path of paths) { const file = allFiles.find((f) => f.path === path); const snapshot = this.fileSnapshots.get(path); if (file && snapshot) { const currentContentHash = await this.calculateHash(file.content); const currentMetadataHash = file.metadata ? await this.calculateHash(file.metadata) : void 0; const contentChanged = snapshot.contentHash && snapshot.contentHash !== currentContentHash; const metadataChanged = snapshot.metadataHash && currentMetadataHash && snapshot.metadataHash !== currentMetadataHash; if (contentChanged || metadataChanged) { this.notifyWatchers({ type: "updated", path, timestamp: /* @__PURE__ */ new Date() }); this.events.emit(import_core.FileSystemEvents.FILE_WRITTEN, { path, size: file.size }); } } } } dispose() { this.stopWatching(); if (this.broadcastChannel) { this.broadcastChannel.close(); this.broadcastChannel = null; } if (this.db) { this.db.close(); this.db = null; } this.watchers = []; this.fileSnapshots.clear(); } // Sobrescrever métodos de permissão (sempre permitido em IndexedDB) async canModify(path) { return true; } async canCreateIn(parentPath) { try { const stat = await this.stat(parentPath); return stat.type === "directory"; } catch { return (0, import_core.normalizePath)(parentPath) === "/"; } } // Não sobrescrever writeFileAtomic - usar implementação base // IndexedDB não tem rename verdadeiramente atômico }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { IndexedDBFileSystem }); //# sourceMappingURL=index.cjs.map