@fgv/ts-web-extras 5.1.0-27 → 5.1.0-28
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/dist/packlets/crypto-utils/browserCryptoProvider.js +82 -0
- package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/dist/packlets/crypto-utils/index.js +12 -0
- package/dist/packlets/crypto-utils/index.js.map +1 -1
- package/dist/packlets/file-tree/directoryHandleStore.js.map +1 -1
- package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
- package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js +2 -2
- package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
- package/dist/packlets/file-tree/httpTreeAccessors.js +2 -2
- package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -1
- package/dist/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
- package/dist/packlets/helpers/fileTreeHelpers.js +1 -1
- package/dist/packlets/helpers/fileTreeHelpers.js.map +1 -1
- package/dist/ts-web-extras.d.ts +61 -3
- package/dist/tsdoc-metadata.json +1 -1
- package/eslint.config.js +32 -0
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +42 -0
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/browserCryptoProvider.js +82 -0
- package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/lib/packlets/crypto-utils/index.d.ts +13 -0
- package/lib/packlets/crypto-utils/index.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/index.js +13 -0
- package/lib/packlets/crypto-utils/index.js.map +1 -1
- package/lib/packlets/file-tree/directoryHandleStore.d.ts +2 -2
- package/lib/packlets/file-tree/directoryHandleStore.d.ts.map +1 -1
- package/lib/packlets/file-tree/directoryHandleStore.js.map +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js +2 -2
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
- package/lib/packlets/file-tree/httpTreeAccessors.js +2 -2
- package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -1
- package/lib/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
- package/lib/packlets/helpers/fileTreeHelpers.d.ts +1 -1
- package/lib/packlets/helpers/fileTreeHelpers.d.ts.map +1 -1
- package/lib/packlets/helpers/fileTreeHelpers.js +6 -6
- package/lib/packlets/helpers/fileTreeHelpers.js.map +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileSystemAccessTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/fileSystemAccessTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;AAEH,OAAO,EAEL,OAAO,EACP,IAAI,EAGJ,iBAAiB,EACjB,OAAO,EACR,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAmC7C;;;;GAIG;AACH,MAAM,OAAO,6BACX,SAAQ,QAAQ,CAAC,qBAA0B;IAW3C;;;;;;;OAOG;IACH,YACE,KAAoC,EACpC,OAAkC,EAClC,OAA0C,EAC1C,MAAoD,EACpD,kBAA2B;;QAE3B,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QAC7B,IAAI,CAAC,iBAAiB,GAAG,IAAI,GAAG,EAAE,CAAC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AQ,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YAEpC,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;YAC5B,qEAAqE;QACvE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,OAAO,IAAI,CAAC,yBAAyB,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n Result,\n succeed,\n fail,\n captureResult,\n DetailedResult,\n succeedWithDetail,\n Logging\n} from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport { FileSystemDirectoryHandle, FileSystemFileHandle } from '../file-api-types';\n\n/**\n * Options for creating persistent file trees.\n * @public\n */\nexport interface IFileSystemAccessTreeParams<TCT extends string = string>\n extends FileTree.IFileTreeInitParams<TCT> {\n /**\n * Automatically sync changes to disk immediately after each save.\n * If false, changes are batched and written on explicit syncToDisk() call.\n * @defaultValue false\n */\n autoSync?: boolean;\n\n /**\n * Require write permission on the directory handle.\n * If true, fails if write permission cannot be obtained.\n * If false, falls back to read-only mode.\n * @defaultValue true\n */\n requireWritePermission?: boolean;\n\n /**\n * Override the path at which the file is stored in the tree (for fromFileHandle).\n * Must be an absolute path (e.g., '/data/confections/common.yaml').\n * If omitted, defaults to `/<filename>`.\n */\n filePath?: string;\n\n /** Optional logger for auto-sync and persistence failures. */\n logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * Implementation of `FileTree.IPersistentFileTreeAccessors` that uses the File System Access API\n * to provide persistent file editing in browsers.\n * @public\n */\nexport class FileSystemAccessTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _handles: Map<string, FileSystemFileHandle>;\n private readonly _rootDir: FileSystemDirectoryHandle;\n private readonly _dirtyFiles: Set<string>;\n private readonly _pendingDeletions: Set<string>;\n private readonly _autoSync: boolean;\n private readonly _hasWritePermission: boolean;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /**\n * Protected constructor for FileSystemAccessTreeAccessors.\n * @param files - An array of in-memory files to include in the tree.\n * @param rootDir - The root directory handle.\n * @param handles - Map of file paths to their handles.\n * @param params - Optional params for the tree.\n * @param hasWritePermission - Whether write permission was granted.\n */\n protected constructor(\n files: FileTree.IInMemoryFile<TCT>[],\n rootDir: FileSystemDirectoryHandle,\n handles: Map<string, FileSystemFileHandle>,\n params: IFileSystemAccessTreeParams<TCT> | undefined,\n hasWritePermission: boolean\n ) {\n super(files, params);\n this._rootDir = rootDir;\n this._handles = handles;\n this._dirtyFiles = new Set();\n this._pendingDeletions = new Set();\n /* c8 ignore next 3 - intermittent branch coverage: ?? fallback branches in constructor */\n this._autoSync = params?.autoSync ?? false;\n this._hasWritePermission = hasWritePermission;\n this._logger = params?.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(\n path: string,\n operation: 'save' | 'delete',\n action: () => Promise<Result<void>>\n ): Promise<void> {\n try {\n const result = await action();\n if (result.isFailure()) {\n this._logger.error(`Auto-${operation} failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-${operation} threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new FileSystemAccessTreeAccessors instance from a directory handle.\n * @param dirHandle - The FileSystemDirectoryHandle to load files from.\n * @param params - Optional parameters including autoSync and permission settings.\n * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.\n * @public\n */\n public static async fromDirectoryHandle<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {\n try {\n // Check write permission\n const hasWritePermission = await this._checkWritePermission(dirHandle);\n\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!hasWritePermission && (params?.requireWritePermission ?? true)) {\n return fail('Write permission required but not granted');\n }\n\n // Load all files from the directory (always use '/' as base, prefix is handled by parent)\n const { files, handles } = await this._loadDirectory<TCT>(dirHandle, '/', params);\n\n // Enable tree mutability when write permission is granted and caller didn't explicitly set mutable\n const effectiveParams: IFileSystemAccessTreeParams<TCT> = {\n ...params,\n mutable: params?.mutable ?? (hasWritePermission ? true : false)\n };\n\n return succeed(\n new FileSystemAccessTreeAccessors<TCT>(files, dirHandle, handles, effectiveParams, hasWritePermission)\n );\n /* c8 ignore next 4 - defensive: outer catch for unexpected errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create FileSystemAccessTreeAccessors: ${message}`);\n }\n }\n\n /**\n * Creates a new FileSystemAccessTreeAccessors instance from a single file handle.\n *\n * The resulting tree contains exactly one file at `/<filename>`.\n * `syncToDisk()` writes changes back to the original file via the File System Access API.\n * New file creation is not supported on this tree (no parent directory handle).\n *\n * @param fileHandle - The FileSystemFileHandle to load.\n * @param params - Optional parameters including autoSync and permission settings.\n * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.\n * @public\n */\n public static async fromFileHandle<TCT extends string = string>(\n fileHandle: FileSystemFileHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {\n try {\n const hasWritePermission = await this._checkFileWritePermission(fileHandle);\n\n /* c8 ignore next 1 - intermittent branch coverage: ?? true fallback */\n if (!hasWritePermission && (params?.requireWritePermission ?? true)) {\n return fail('Write permission required but not granted');\n }\n\n const file = await fileHandle.getFile();\n const contents = await file.text();\n const path = params?.filePath ?? `/${fileHandle.name}`;\n /* c8 ignore next 3 - intermittent branch coverage: ternary for inferContentType */\n const contentType = params?.inferContentType\n ? params.inferContentType(path, file.type).orDefault()\n : undefined;\n\n const files: FileTree.IInMemoryFile<TCT>[] = [{ path, contents, contentType }];\n const handles = new Map<string, FileSystemFileHandle>([[path, fileHandle]]);\n\n const dummyRoot = {} as FileSystemDirectoryHandle;\n const effectiveParams: IFileSystemAccessTreeParams<TCT> = {\n ...params,\n /* c8 ignore next 1 - intermittent branch coverage: ?? false fallback */\n mutable: hasWritePermission ? true : params?.mutable ?? false\n };\n\n return succeed(\n new FileSystemAccessTreeAccessors<TCT>(files, dummyRoot, handles, effectiveParams, hasWritePermission)\n );\n } catch (error) {\n /* c8 ignore next 1 - intermittent branch coverage: error instanceof Error false branch */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create FileSystemAccessTreeAccessors from file: ${message}`);\n }\n }\n\n /**\n * Check if the directory handle has write permission.\n * @param handle - The directory handle to check.\n * @returns Promise resolving to true if write permission is granted.\n * @internal\n */\n private static async _checkWritePermission(handle: FileSystemDirectoryHandle): Promise<boolean> {\n try {\n const permission = await handle.queryPermission({ mode: 'readwrite' });\n\n if (permission === 'granted') {\n return true;\n }\n\n if (permission === 'prompt') {\n const requested = await handle.requestPermission({ mode: 'readwrite' });\n return requested === 'granted';\n }\n\n return false;\n } catch (error) {\n // Permission API might not be available or might throw\n return false;\n }\n }\n\n /**\n * Check if the file handle has write permission.\n * @param handle - The file handle to check.\n * @returns Promise resolving to true if write permission is granted.\n * @internal\n */\n private static async _checkFileWritePermission(handle: FileSystemFileHandle): Promise<boolean> {\n try {\n const permission = await handle.queryPermission({ mode: 'readwrite' });\n\n if (permission === 'granted') {\n return true;\n }\n\n if (permission === 'prompt') {\n const requested = await handle.requestPermission({ mode: 'readwrite' });\n return requested === 'granted';\n }\n\n return false;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Load all files from a directory handle recursively.\n * @param dirHandle - The directory handle to load from.\n * @param basePath - The base path for files.\n * @param params - Optional parameters.\n * @returns Promise resolving to files and handles.\n * @internal\n */\n private static async _loadDirectory<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n basePath: string,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<{ files: FileTree.IInMemoryFile<TCT>[]; handles: Map<string, FileSystemFileHandle> }> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n const handles = new Map<string, FileSystemFileHandle>();\n\n for await (const [name, handle] of dirHandle.entries()) {\n if (handle.kind === 'file') {\n const fileHandle = handle as FileSystemFileHandle;\n const file = await fileHandle.getFile();\n const contents = await file.text();\n const path = this._joinPath(basePath, name);\n /* c8 ignore next 2 - coverage intermittently missed in full suite */\n const contentType = params?.inferContentType\n ? params.inferContentType(path, file.type).orDefault()\n : undefined;\n\n files.push({ path, contents, contentType });\n handles.set(path, fileHandle);\n } else if (handle.kind === 'directory') {\n const subDirHandle = handle as FileSystemDirectoryHandle;\n const subPath = this._joinPath(basePath, name);\n const subResult = await this._loadDirectory<TCT>(subDirHandle, subPath, params);\n files.push(...subResult.files);\n for (const [path, fileHandle] of subResult.handles) {\n handles.set(path, fileHandle);\n }\n }\n }\n\n return { files, handles };\n }\n\n /**\n * Join path segments.\n * @param base - The base path.\n * @param name - The name to append.\n * @returns The joined path.\n * @internal\n */\n private static _joinPath(base: string, name: string): string {\n const normalized = base.endsWith('/') ? base.slice(0, -1) : base;\n return `${normalized}/${name}`;\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.syncToDisk`\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (!this._hasWritePermission) {\n return fail('Write permission not granted - cannot sync to disk');\n }\n\n const errors: string[] = [];\n\n // Process pending deletions from disk\n for (const path of this._pendingDeletions) {\n const deleteResult = await this._deleteFileFromDisk(path);\n if (deleteResult.isFailure()) {\n errors.push(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of this._dirtyFiles) {\n const syncResult = await this._syncFile(path);\n if (syncResult.isFailure()) {\n errors.push(`${path}: ${syncResult.message}`);\n }\n }\n\n if (errors.length > 0) {\n return fail(`Failed to sync ${errors.length} file(s):\\n${errors.join('\\n')}`);\n }\n\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n return succeed(undefined);\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.isDirty`\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.getDirtyPaths`\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n /**\n * Override deleteFile to track pending deletions for syncToDisk.\n */\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isSuccess()) {\n this._dirtyFiles.delete(path);\n this._handles.delete(path);\n\n if (this._hasWritePermission) {\n this._pendingDeletions.add(path);\n\n if (this._autoSync) {\n void this._runAutoSyncTask(path, 'delete', () => this._deleteFileFromDisk(path));\n }\n }\n }\n return result;\n }\n\n /**\n * Implements `FileTree.IMutableFileTreeAccessors.saveFileContents`\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n // Call parent to update in-memory state\n const result = super.saveFileContents(path, contents);\n\n if (result.isSuccess() && this._hasWritePermission) {\n this._dirtyFiles.add(path);\n\n // Auto-sync if enabled\n if (this._autoSync) {\n // Fire and log-on-failure; don't block the save path.\n void this._runAutoSyncTask(path, 'save', () => this._syncFile(path));\n }\n }\n\n return result;\n }\n\n /**\n * Implements `FileTree.IMutableFileTreeAccessors.fileIsMutable`\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const baseResult = super.fileIsMutable(path);\n\n if (baseResult.isSuccess() && baseResult.detail === 'transient' && this._hasWritePermission) {\n // Upgrade to 'persistent' if we have write permission\n return succeedWithDetail(true, 'persistent');\n }\n\n return baseResult;\n }\n\n /**\n * Sync a single file to disk.\n * @param path - The path of the file to sync.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _syncFile(path: string): Promise<Result<void>> {\n const handle = this._handles.get(path);\n if (!handle) {\n return this._createAndWriteFile(path);\n }\n\n const contents = this.getFileContents(path);\n if (contents.isFailure()) {\n return fail(contents.message);\n }\n\n try {\n const writable = await handle.createWritable();\n await writable.write(contents.value);\n await writable.close();\n return succeed(undefined);\n /* c8 ignore next 4 - coverage intermittently missed in full suite */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to write file: ${message}`);\n }\n }\n\n /**\n * Delete a file from disk using the File System Access API.\n * @param path - The path of the file to delete.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _deleteFileFromDisk(path: string): Promise<Result<void>> {\n try {\n const absolutePath = this.resolveAbsolutePath(path);\n const parts = absolutePath.split('/').filter((p) => p.length > 0);\n const filename = parts.pop();\n\n /* c8 ignore next 3 - defensive: invalid path */\n if (!filename) {\n return fail(`Invalid file path: ${path}`);\n }\n\n // Navigate to the parent directory\n let currentDir = this._rootDir;\n for (const part of parts) {\n currentDir = await currentDir.getDirectoryHandle(part);\n }\n\n await currentDir.removeEntry(filename);\n return succeed(undefined);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to delete file ${path}: ${message}`);\n }\n }\n\n /**\n * Create a new file and write its contents.\n * @param path - The path of the file to create.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _createAndWriteFile(path: string): Promise<Result<void>> {\n try {\n // Parse path to get directory and filename\n const absolutePath = this.resolveAbsolutePath(path);\n const parts = absolutePath.split('/').filter((p) => p.length > 0);\n const filename = parts.pop();\n\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!filename) {\n return fail(`Invalid file path: ${path}`);\n }\n\n // Navigate/create directory structure\n let currentDir = this._rootDir;\n for (const part of parts) {\n currentDir = await currentDir.getDirectoryHandle(part, { create: true });\n }\n\n // Create file and write contents\n const fileHandle = await currentDir.getFileHandle(filename, { create: true });\n this._handles.set(path, fileHandle);\n\n return this._syncFile(path);\n /* c8 ignore next 4 - coverage intermittently missed in full suite */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create file ${path}: ${message}`);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fileSystemAccessTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/fileSystemAccessTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;AAEH,OAAO,EAAU,OAAO,EAAE,IAAI,EAAkB,iBAAiB,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAClG,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAmC7C;;;;GAIG;AACH,MAAM,OAAO,6BACX,SAAQ,QAAQ,CAAC,qBAA0B;IAW3C;;;;;;;OAOG;IACH,YACE,KAAoC,EACpC,OAAkC,EAClC,OAA0C,EAC1C,MAAoD,EACpD,kBAA2B;;QAE3B,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,I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AAC,kBAAkB,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;YAC3E,CAAC;YAED,iCAAiC;YACjC,MAAM,UAAU,GAAG,MAAM,UAAU,CAAC,aAAa,CAAC,QAAQ,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;YAC9E,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YAEpC,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;YAC5B,qEAAqE;QACvE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,OAAO,IAAI,CAAC,yBAAyB,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, succeed, fail, DetailedResult, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport { FileSystemDirectoryHandle, FileSystemFileHandle } from '../file-api-types';\n\n/**\n * Options for creating persistent file trees.\n * @public\n */\nexport interface IFileSystemAccessTreeParams<TCT extends string = string>\n extends FileTree.IFileTreeInitParams<TCT> {\n /**\n * Automatically sync changes to disk immediately after each save.\n * If false, changes are batched and written on explicit syncToDisk() call.\n * @defaultValue false\n */\n autoSync?: boolean;\n\n /**\n * Require write permission on the directory handle.\n * If true, fails if write permission cannot be obtained.\n * If false, falls back to read-only mode.\n * @defaultValue true\n */\n requireWritePermission?: boolean;\n\n /**\n * Override the path at which the file is stored in the tree (for fromFileHandle).\n * Must be an absolute path (e.g., '/data/confections/common.yaml').\n * If omitted, defaults to `/<filename>`.\n */\n filePath?: string;\n\n /** Optional logger for auto-sync and persistence failures. */\n logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * Implementation of `FileTree.IPersistentFileTreeAccessors` that uses the File System Access API\n * to provide persistent file editing in browsers.\n * @public\n */\nexport class FileSystemAccessTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _handles: Map<string, FileSystemFileHandle>;\n private readonly _rootDir: FileSystemDirectoryHandle;\n private readonly _dirtyFiles: Set<string>;\n private readonly _pendingDeletions: Set<string>;\n private readonly _autoSync: boolean;\n private readonly _hasWritePermission: boolean;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /**\n * Protected constructor for FileSystemAccessTreeAccessors.\n * @param files - An array of in-memory files to include in the tree.\n * @param rootDir - The root directory handle.\n * @param handles - Map of file paths to their handles.\n * @param params - Optional params for the tree.\n * @param hasWritePermission - Whether write permission was granted.\n */\n protected constructor(\n files: FileTree.IInMemoryFile<TCT>[],\n rootDir: FileSystemDirectoryHandle,\n handles: Map<string, FileSystemFileHandle>,\n params: IFileSystemAccessTreeParams<TCT> | undefined,\n hasWritePermission: boolean\n ) {\n super(files, params);\n this._rootDir = rootDir;\n this._handles = handles;\n this._dirtyFiles = new Set();\n this._pendingDeletions = new Set();\n /* c8 ignore next 3 - intermittent branch coverage: ?? fallback branches in constructor */\n this._autoSync = params?.autoSync ?? false;\n this._hasWritePermission = hasWritePermission;\n this._logger = params?.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(\n path: string,\n operation: 'save' | 'delete',\n action: () => Promise<Result<void>>\n ): Promise<void> {\n try {\n const result = await action();\n if (result.isFailure()) {\n this._logger.error(`Auto-${operation} failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-${operation} threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new FileSystemAccessTreeAccessors instance from a directory handle.\n * @param dirHandle - The FileSystemDirectoryHandle to load files from.\n * @param params - Optional parameters including autoSync and permission settings.\n * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.\n * @public\n */\n public static async fromDirectoryHandle<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {\n try {\n // Check write permission\n const hasWritePermission = await this._checkWritePermission(dirHandle);\n\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!hasWritePermission && (params?.requireWritePermission ?? true)) {\n return fail('Write permission required but not granted');\n }\n\n // Load all files from the directory (always use '/' as base, prefix is handled by parent)\n const { files, handles } = await this._loadDirectory<TCT>(dirHandle, '/', params);\n\n // Enable tree mutability when write permission is granted and caller didn't explicitly set mutable\n const effectiveParams: IFileSystemAccessTreeParams<TCT> = {\n ...params,\n mutable: params?.mutable ?? (hasWritePermission ? true : false)\n };\n\n return succeed(\n new FileSystemAccessTreeAccessors<TCT>(files, dirHandle, handles, effectiveParams, hasWritePermission)\n );\n /* c8 ignore next 4 - defensive: outer catch for unexpected errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create FileSystemAccessTreeAccessors: ${message}`);\n }\n }\n\n /**\n * Creates a new FileSystemAccessTreeAccessors instance from a single file handle.\n *\n * The resulting tree contains exactly one file at `/<filename>`.\n * `syncToDisk()` writes changes back to the original file via the File System Access API.\n * New file creation is not supported on this tree (no parent directory handle).\n *\n * @param fileHandle - The FileSystemFileHandle to load.\n * @param params - Optional parameters including autoSync and permission settings.\n * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.\n * @public\n */\n public static async fromFileHandle<TCT extends string = string>(\n fileHandle: FileSystemFileHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {\n try {\n const hasWritePermission = await this._checkFileWritePermission(fileHandle);\n\n /* c8 ignore next 1 - intermittent branch coverage: ?? true fallback */\n if (!hasWritePermission && (params?.requireWritePermission ?? true)) {\n return fail('Write permission required but not granted');\n }\n\n const file = await fileHandle.getFile();\n const contents = await file.text();\n const path = params?.filePath ?? `/${fileHandle.name}`;\n /* c8 ignore next 3 - intermittent branch coverage: ternary for inferContentType */\n const contentType = params?.inferContentType\n ? params.inferContentType(path, file.type).orDefault()\n : undefined;\n\n const files: FileTree.IInMemoryFile<TCT>[] = [{ path, contents, contentType }];\n const handles = new Map<string, FileSystemFileHandle>([[path, fileHandle]]);\n\n const dummyRoot = {} as FileSystemDirectoryHandle;\n const effectiveParams: IFileSystemAccessTreeParams<TCT> = {\n ...params,\n /* c8 ignore next 1 - intermittent branch coverage: ?? false fallback */\n mutable: hasWritePermission ? true : params?.mutable ?? false\n };\n\n return succeed(\n new FileSystemAccessTreeAccessors<TCT>(files, dummyRoot, handles, effectiveParams, hasWritePermission)\n );\n } catch (error) {\n /* c8 ignore next 1 - intermittent branch coverage: error instanceof Error false branch */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create FileSystemAccessTreeAccessors from file: ${message}`);\n }\n }\n\n /**\n * Check if the directory handle has write permission.\n * @param handle - The directory handle to check.\n * @returns Promise resolving to true if write permission is granted.\n * @internal\n */\n private static async _checkWritePermission(handle: FileSystemDirectoryHandle): Promise<boolean> {\n try {\n const permission = await handle.queryPermission({ mode: 'readwrite' });\n\n if (permission === 'granted') {\n return true;\n }\n\n if (permission === 'prompt') {\n const requested = await handle.requestPermission({ mode: 'readwrite' });\n return requested === 'granted';\n }\n\n return false;\n } catch (error) {\n // Permission API might not be available or might throw\n return false;\n }\n }\n\n /**\n * Check if the file handle has write permission.\n * @param handle - The file handle to check.\n * @returns Promise resolving to true if write permission is granted.\n * @internal\n */\n private static async _checkFileWritePermission(handle: FileSystemFileHandle): Promise<boolean> {\n try {\n const permission = await handle.queryPermission({ mode: 'readwrite' });\n\n if (permission === 'granted') {\n return true;\n }\n\n if (permission === 'prompt') {\n const requested = await handle.requestPermission({ mode: 'readwrite' });\n return requested === 'granted';\n }\n\n return false;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Load all files from a directory handle recursively.\n * @param dirHandle - The directory handle to load from.\n * @param basePath - The base path for files.\n * @param params - Optional parameters.\n * @returns Promise resolving to files and handles.\n * @internal\n */\n private static async _loadDirectory<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n basePath: string,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<{ files: FileTree.IInMemoryFile<TCT>[]; handles: Map<string, FileSystemFileHandle> }> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n const handles = new Map<string, FileSystemFileHandle>();\n\n for await (const [name, handle] of dirHandle.entries()) {\n if (handle.kind === 'file') {\n const fileHandle = handle as FileSystemFileHandle;\n const file = await fileHandle.getFile();\n const contents = await file.text();\n const path = this._joinPath(basePath, name);\n /* c8 ignore next 2 - coverage intermittently missed in full suite */\n const contentType = params?.inferContentType\n ? params.inferContentType(path, file.type).orDefault()\n : undefined;\n\n files.push({ path, contents, contentType });\n handles.set(path, fileHandle);\n } else if (handle.kind === 'directory') {\n const subDirHandle = handle as FileSystemDirectoryHandle;\n const subPath = this._joinPath(basePath, name);\n const subResult = await this._loadDirectory<TCT>(subDirHandle, subPath, params);\n files.push(...subResult.files);\n for (const [path, fileHandle] of subResult.handles) {\n handles.set(path, fileHandle);\n }\n }\n }\n\n return { files, handles };\n }\n\n /**\n * Join path segments.\n * @param base - The base path.\n * @param name - The name to append.\n * @returns The joined path.\n * @internal\n */\n private static _joinPath(base: string, name: string): string {\n const normalized = base.endsWith('/') ? base.slice(0, -1) : base;\n return `${normalized}/${name}`;\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.syncToDisk`\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (!this._hasWritePermission) {\n return fail('Write permission not granted - cannot sync to disk');\n }\n\n const errors: string[] = [];\n\n // Process pending deletions from disk\n for (const path of this._pendingDeletions) {\n const deleteResult = await this._deleteFileFromDisk(path);\n if (deleteResult.isFailure()) {\n errors.push(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of this._dirtyFiles) {\n const syncResult = await this._syncFile(path);\n if (syncResult.isFailure()) {\n errors.push(`${path}: ${syncResult.message}`);\n }\n }\n\n if (errors.length > 0) {\n return fail(`Failed to sync ${errors.length} file(s):\\n${errors.join('\\n')}`);\n }\n\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n return succeed(undefined);\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.isDirty`\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.getDirtyPaths`\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n /**\n * Override deleteFile to track pending deletions for syncToDisk.\n */\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isSuccess()) {\n this._dirtyFiles.delete(path);\n this._handles.delete(path);\n\n if (this._hasWritePermission) {\n this._pendingDeletions.add(path);\n\n if (this._autoSync) {\n this._runAutoSyncTask(path, 'delete', () => this._deleteFileFromDisk(path)).catch(() => undefined);\n }\n }\n }\n return result;\n }\n\n /**\n * Implements `FileTree.IMutableFileTreeAccessors.saveFileContents`\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n // Call parent to update in-memory state\n const result = super.saveFileContents(path, contents);\n\n if (result.isSuccess() && this._hasWritePermission) {\n this._dirtyFiles.add(path);\n\n // Auto-sync if enabled\n if (this._autoSync) {\n // Fire and log-on-failure; don't block the save path.\n this._runAutoSyncTask(path, 'save', () => this._syncFile(path)).catch(() => undefined);\n }\n }\n\n return result;\n }\n\n /**\n * Implements `FileTree.IMutableFileTreeAccessors.fileIsMutable`\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const baseResult = super.fileIsMutable(path);\n\n if (baseResult.isSuccess() && baseResult.detail === 'transient' && this._hasWritePermission) {\n // Upgrade to 'persistent' if we have write permission\n return succeedWithDetail(true, 'persistent');\n }\n\n return baseResult;\n }\n\n /**\n * Sync a single file to disk.\n * @param path - The path of the file to sync.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _syncFile(path: string): Promise<Result<void>> {\n const handle = this._handles.get(path);\n if (!handle) {\n return this._createAndWriteFile(path);\n }\n\n const contents = this.getFileContents(path);\n if (contents.isFailure()) {\n return fail(contents.message);\n }\n\n try {\n const writable = await handle.createWritable();\n await writable.write(contents.value);\n await writable.close();\n return succeed(undefined);\n /* c8 ignore next 4 - coverage intermittently missed in full suite */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to write file: ${message}`);\n }\n }\n\n /**\n * Delete a file from disk using the File System Access API.\n * @param path - The path of the file to delete.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _deleteFileFromDisk(path: string): Promise<Result<void>> {\n try {\n const absolutePath = this.resolveAbsolutePath(path);\n const parts = absolutePath.split('/').filter((p) => p.length > 0);\n const filename = parts.pop();\n\n /* c8 ignore next 3 - defensive: invalid path */\n if (!filename) {\n return fail(`Invalid file path: ${path}`);\n }\n\n // Navigate to the parent directory\n let currentDir = this._rootDir;\n for (const part of parts) {\n currentDir = await currentDir.getDirectoryHandle(part);\n }\n\n await currentDir.removeEntry(filename);\n return succeed(undefined);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to delete file ${path}: ${message}`);\n }\n }\n\n /**\n * Create a new file and write its contents.\n * @param path - The path of the file to create.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _createAndWriteFile(path: string): Promise<Result<void>> {\n try {\n // Parse path to get directory and filename\n const absolutePath = this.resolveAbsolutePath(path);\n const parts = absolutePath.split('/').filter((p) => p.length > 0);\n const filename = parts.pop();\n\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!filename) {\n return fail(`Invalid file path: ${path}`);\n }\n\n // Navigate/create directory structure\n let currentDir = this._rootDir;\n for (const part of parts) {\n currentDir = await currentDir.getDirectoryHandle(part, { create: true });\n }\n\n // Create file and write contents\n const fileHandle = await currentDir.getFileHandle(filename, { create: true });\n this._handles.set(path, fileHandle);\n\n return this._syncFile(path);\n /* c8 ignore next 4 - coverage intermittently missed in full suite */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create file ${path}: ${message}`);\n }\n }\n}\n"]}
|
|
@@ -191,7 +191,7 @@ export class HttpTreeAccessors extends FileTree.InMemoryTreeAccessors {
|
|
|
191
191
|
if (!this._autoSync) {
|
|
192
192
|
return result;
|
|
193
193
|
}
|
|
194
|
-
|
|
194
|
+
this._runAutoSyncTask(path).catch(() => undefined);
|
|
195
195
|
return result;
|
|
196
196
|
}
|
|
197
197
|
/**
|
|
@@ -210,7 +210,7 @@ export class HttpTreeAccessors extends FileTree.InMemoryTreeAccessors {
|
|
|
210
210
|
return result;
|
|
211
211
|
}
|
|
212
212
|
// fire-and-log-on-failure automatic sync for immediate persistence workflow
|
|
213
|
-
|
|
213
|
+
this._runAutoSyncTask(path).catch(() => undefined);
|
|
214
214
|
return result;
|
|
215
215
|
}
|
|
216
216
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/httpTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAkB,IAAI,EAAe,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACvG,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAuB7C,SAAS,cAAc,CAAC,SAAwB;IAC9C,MAAM,QAAQ,GAAG,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,UAAU,CAAC,KAAK,CAAC;IAC/C,OAAO,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAiB,CAAC;AACnD,CAAC;AAeD;;;GAGG;AACH,MAAM,OAAO,iBACX,SAAQ,QAAQ,CAAC,qBAA0B;IAe3C,YAAoB,KAAoC,EAAE,MAA4B;;QACpF,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAVN,gBAAW,GAAgB,IAAI,GAAG,EAAE,CAAC;QACrC,sBAAiB,GAAgB,IAAI,GAAG,EAAE,CAAC;QAU1D,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,cAAc,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,CAAC,SAAS,GAAG,MAAA,MAAM,CAAC,QAAQ,mCAAI,KAAK,CAAC;QAC1C,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;QAC7B,IAAI,CAA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;YACtB,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC5F,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YACnD,MAAM,OAAO,GAAG,IAAI;gBAClB,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,KAAK,IAAI,EAAE;gBACpC,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;YACrD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC1D,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,IAAI,CAAC,uBAAuB,CAAC,CAAC;QACvC,CAAC;QAED,OAAO,OAAO,CAAC,IAAS,CAAC,CAAC;IAC5B,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, type Result, succeed, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\n\ninterface IHttpStorageTreeItem {\n readonly path: string;\n readonly name: string;\n readonly type: 'file' | 'directory';\n}\n\ninterface IHttpStorageTreeChildrenResponse {\n readonly path: string;\n readonly children: ReadonlyArray<IHttpStorageTreeItem>;\n}\n\ninterface IHttpStorageFileResponse {\n readonly path: string;\n readonly contents: string;\n readonly contentType?: string;\n}\n\ninterface IHttpStorageSyncResponse {\n readonly synced: number;\n}\n\nfunction normalizeFetch(fetchImpl?: typeof fetch): typeof fetch {\n const resolved = fetchImpl ?? globalThis.fetch;\n return resolved.bind(globalThis) as typeof fetch;\n}\n\n/**\n * Configuration for creating HTTP-backed tree accessors.\n * @public\n */\nexport interface IHttpTreeParams<TCT extends string = string> extends FileTree.IFileTreeInitParams<TCT> {\n readonly baseUrl: string;\n readonly namespace?: string;\n readonly autoSync?: boolean;\n readonly fetchImpl?: typeof fetch;\n readonly userId?: string;\n readonly logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * HTTP-backed file tree accessors that cache data in memory and persist via REST API.\n * @public\n */\nexport class HttpTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _baseUrl: string;\n private readonly _namespace: string | undefined;\n private readonly _fetchImpl: typeof fetch;\n private readonly _dirtyFiles: Set<string> = new Set();\n private readonly _pendingDeletions: Set<string> = new Set();\n private readonly _autoSync: boolean;\n private readonly _userId: string | undefined;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /** Guards against concurrent syncToDisk calls (thundering herd from autoSync). */\n private _syncPromise: Promise<Result<void>> | undefined;\n\n private constructor(files: FileTree.IInMemoryFile<TCT>[], params: IHttpTreeParams<TCT>) {\n super(files, params);\n this._baseUrl = params.baseUrl.replace(/\\/$/, '');\n this._namespace = params.namespace;\n this._fetchImpl = normalizeFetch(params.fetchImpl);\n this._autoSync = params.autoSync ?? false;\n this._userId = params.userId;\n this._logger = params.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(path: string): Promise<void> {\n try {\n const result = await this.syncToDisk();\n if (result.isFailure()) {\n this._logger.error(`Auto-sync failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-sync threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new HttpTreeAccessors instance from an HTTP backend.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @returns A promise that resolves to a result containing the new HttpTreeAccessors instance or an error message.\n */\n public static async fromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<HttpTreeAccessors<TCT>>> {\n const filesResult = await this._loadFiles<TCT>(params, '/');\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n return succeed(new HttpTreeAccessors<TCT>(filesResult.value, params));\n }\n\n /**\n * Synchronizes all dirty files to the HTTP backend.\n *\n * Uses a concurrency guard: if a sync is already in progress, callers\n * await the existing operation rather than starting a parallel one.\n * This prevents the thundering herd that occurs when autoSync fires\n * for every file written during a bulk operation (e.g. restore).\n *\n * @returns A promise that resolves to a result indicating success or failure.\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._syncPromise) {\n // Wait for the in-flight sync — it drains the queue in a loop,\n // so any items added before it finishes will be included.\n return this._syncPromise;\n }\n\n this._syncPromise = this._doSync().finally(() => {\n this._syncPromise = undefined;\n });\n return this._syncPromise;\n }\n\n private async _doSync(): Promise<Result<void>> {\n // Drain loop: keep processing as long as new items arrive.\n // This is critical for bulk operations (e.g. reset) where many\n // deleteFile/saveFileContents calls happen synchronously — only\n // the first may be in the set when we snapshot, but the rest\n // arrive during the async gaps and must be picked up before\n // we return.\n let didWork = false;\n while (this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0) {\n didWork = true;\n // Snapshot and clear so that changes arriving during the async\n // requests land in the live sets for the next iteration.\n const deletions = new Set(this._pendingDeletions);\n const dirty = new Set(this._dirtyFiles);\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n\n for (const path of deletions) {\n const query = new URLSearchParams();\n query.set('path', path);\n if (this._namespace) {\n query.set('namespace', this._namespace);\n }\n\n const deleteResult = await this._requestWithRetry<{ deleted: boolean }>(`/file?${query.toString()}`, {\n method: 'DELETE'\n });\n if (deleteResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of dirty) {\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`${path}: ${contentsResult.message}`);\n }\n\n const body: Record<string, unknown> = {\n path,\n contents: contentsResult.value\n };\n if (this._namespace) {\n body.namespace = this._namespace;\n }\n\n const saveResult = await this._requestWithRetry<IHttpStorageFileResponse>('/file', {\n method: 'PUT',\n body: JSON.stringify(body)\n });\n if (saveResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`sync ${path}: ${saveResult.message}`);\n }\n }\n }\n\n if (didWork) {\n const syncBody: Record<string, unknown> = {};\n if (this._namespace) {\n syncBody.namespace = this._namespace;\n }\n\n const syncResult = await this._requestWithRetry<IHttpStorageSyncResponse>('/sync', {\n method: 'POST',\n body: JSON.stringify(syncBody)\n });\n\n if (syncResult.isFailure()) {\n return fail(syncResult.message);\n }\n }\n return succeed(undefined);\n }\n\n /**\n * Restores snapshotted items back into the live dirty sets so they\n * are retried on the next sync attempt. Items that were added to\n * the live sets while the sync was in flight are preserved.\n */\n private _restoreUnsynced(deletions: Set<string>, dirty: Set<string>): void {\n for (const path of deletions) {\n this._pendingDeletions.add(path);\n }\n for (const path of dirty) {\n this._dirtyFiles.add(path);\n }\n }\n\n /**\n * Checks if there are any dirty files that need synchronization.\n * @returns True if there are dirty files, false otherwise.\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Gets the list of paths for all dirty files.\n * @returns An array of file paths that have been modified but not yet synchronized.\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.delete(path);\n this._pendingDeletions.add(path);\n\n if (!this._autoSync) {\n return result;\n }\n\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Saves file contents and marks the file as dirty for synchronization.\n * @param path - The path to the file.\n * @param contents - The new contents of the file.\n * @returns A result indicating success or failure.\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.add(path);\n if (!this._autoSync) {\n return result;\n }\n\n // fire-and-log-on-failure automatic sync for immediate persistence workflow\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Checks if a file is mutable (can be modified).\n * @param path - The path to the file.\n * @returns A detailed result indicating if the file is mutable and the reason.\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const result = super.fileIsMutable(path);\n if (result.isSuccess() && result.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return result;\n }\n\n /**\n * Makes an HTTP request to the specified resource path.\n * @param resourcePath - The path to the resource.\n * @param init - Optional request initialization options.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private async _request<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const response = await this._fetchImpl(`${this._baseUrl}${resourcePath}`, {\n headers: {\n 'Content-Type': 'application/json',\n ...(this._userId ? { 'X-User-Id': this._userId } : {}),\n /* c8 ignore next 1 - defensive coding: init.headers is never set by current callers */\n ...(init?.headers ?? {})\n },\n ...init\n }).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n return succeed(json as T);\n }\n\n /**\n * Wraps `_request` with retry logic for transient failures\n * (network errors, 503 service unavailable, etc.).\n */\n private async _requestWithRetry<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const maxAttempts = 3;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const result = await this._request<T>(resourcePath, init);\n if (result.isSuccess() || attempt === maxAttempts) {\n return result;\n }\n // Retry on transient-looking errors\n const msg = result.message;\n const lowerMsg = msg.toLowerCase();\n const isTransient =\n msg.includes('503') ||\n msg.includes('502') ||\n msg.includes('429') ||\n lowerMsg.includes('disconnect') ||\n lowerMsg.includes('econnreset') ||\n lowerMsg.includes('failed to fetch') ||\n lowerMsg.includes('network');\n if (!isTransient) {\n return result;\n }\n // Exponential backoff: 500ms, 1000ms\n const delayMs = 500 * Math.pow(2, attempt - 1);\n this._logger.detail(\n `Retrying ${\n init?.method ?? 'GET'\n } ${resourcePath} after ${delayMs}ms (attempt ${attempt}/${maxAttempts})`\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n /* c8 ignore next 1 - defensive coding: loop always returns */\n return fail('retry loop exited unexpectedly');\n }\n\n /**\n * Loads files from the HTTP backend for the specified directory path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param directoryPath - The path to the directory to load files from.\n * @returns A promise that resolves to a result containing the loaded files or an error message.\n */\n private static async _loadFiles<TCT extends string = string>(\n params: IHttpTreeParams<TCT>,\n directoryPath: string\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const childrenResult = await this._requestWithParams<IHttpStorageTreeChildrenResponse>(\n params,\n '/tree/children',\n {\n path: directoryPath,\n namespace: params.namespace\n }\n );\n if (childrenResult.isFailure()) {\n return fail(childrenResult.message);\n }\n\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const item of childrenResult.value.children) {\n if (item.type === 'directory') {\n const nestedResult = await this._loadFiles(params, item.path);\n if (nestedResult.isFailure()) {\n return fail(nestedResult.message);\n }\n allFiles.push(...nestedResult.value);\n } else {\n const fileResult = await this._requestWithParams<IHttpStorageFileResponse>(params, '/file', {\n path: item.path,\n namespace: params.namespace\n });\n if (fileResult.isFailure()) {\n return fail(fileResult.message);\n }\n\n const contentType = params.inferContentType?.(item.path, fileResult.value.contentType).orDefault();\n allFiles.push({\n path: item.path,\n contents: fileResult.value.contents,\n contentType\n });\n }\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Makes an HTTP request with query parameters to the specified resource path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param resourcePath - The path to the resource.\n * @param query - Query parameters to include in the request.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private static async _requestWithParams<T>(\n params: IHttpTreeParams,\n resourcePath: string,\n query: Record<string, string | undefined>\n ): Promise<Result<T>> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n search.set(key, value);\n }\n }\n\n const fetchImpl = normalizeFetch(params.fetchImpl);\n const userIdHeaders: RequestInit | undefined = /* c8 ignore next */ params.userId\n ? { headers: { 'X-User-Id': params.userId } }\n : undefined;\n const response = await fetchImpl(\n `${params.baseUrl.replace(/\\/$/, '')}${resourcePath}?${search.toString()}`,\n userIdHeaders\n ).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n\n return succeed(json as T);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"httpTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/httpTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAkB,IAAI,EAAe,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACvG,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAuB7C,SAAS,cAAc,CAAC,SAAwB;IAC9C,MAAM,QAAQ,GAAG,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,UAAU,CAAC,KAAK,CAAC;IAC/C,OAAO,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAiB,CAAC;AACnD,CAAC;AAeD;;;GAGG;AACH,MAAM,OAAO,iBACX,SAAQ,QAAQ,CAAC,qBAA0B;IAe3C,YAAoB,KAAoC,EAAE,MAA4B;;QACpF,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAVN,gBAAW,GAAgB,IAAI,GAAG,EAAE,CAAC;QACrC,sBAAiB,GAAgB,IAAI,GAAG,EAAE,CAAC;QAU1D,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,cAAc,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,C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AAE,EAAE,CAAC,GAAG,YAAY,IAAI,MAAM,CAAC,QAAQ,EAAE,EAAE,EAC1E,aAAa,CACd,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAY,CAAA,CAAC,CAAC;QAE9C,IAAI,KAAK,IAAI,QAAQ,EAAE,CAAC;YACtB,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC5F,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YACnD,MAAM,OAAO,GAAG,IAAI;gBAClB,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,KAAK,IAAI,EAAE;gBACpC,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;YACrD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC1D,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,IAAI,CAAC,uBAAuB,CAAC,CAAC;QACvC,CAAC;QAED,OAAO,OAAO,CAAC,IAAS,CAAC,CAAC;IAC5B,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, type Result, succeed, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\n\ninterface IHttpStorageTreeItem {\n readonly path: string;\n readonly name: string;\n readonly type: 'file' | 'directory';\n}\n\ninterface IHttpStorageTreeChildrenResponse {\n readonly path: string;\n readonly children: ReadonlyArray<IHttpStorageTreeItem>;\n}\n\ninterface IHttpStorageFileResponse {\n readonly path: string;\n readonly contents: string;\n readonly contentType?: string;\n}\n\ninterface IHttpStorageSyncResponse {\n readonly synced: number;\n}\n\nfunction normalizeFetch(fetchImpl?: typeof fetch): typeof fetch {\n const resolved = fetchImpl ?? globalThis.fetch;\n return resolved.bind(globalThis) as typeof fetch;\n}\n\n/**\n * Configuration for creating HTTP-backed tree accessors.\n * @public\n */\nexport interface IHttpTreeParams<TCT extends string = string> extends FileTree.IFileTreeInitParams<TCT> {\n readonly baseUrl: string;\n readonly namespace?: string;\n readonly autoSync?: boolean;\n readonly fetchImpl?: typeof fetch;\n readonly userId?: string;\n readonly logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * HTTP-backed file tree accessors that cache data in memory and persist via REST API.\n * @public\n */\nexport class HttpTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _baseUrl: string;\n private readonly _namespace: string | undefined;\n private readonly _fetchImpl: typeof fetch;\n private readonly _dirtyFiles: Set<string> = new Set();\n private readonly _pendingDeletions: Set<string> = new Set();\n private readonly _autoSync: boolean;\n private readonly _userId: string | undefined;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /** Guards against concurrent syncToDisk calls (thundering herd from autoSync). */\n private _syncPromise: Promise<Result<void>> | undefined;\n\n private constructor(files: FileTree.IInMemoryFile<TCT>[], params: IHttpTreeParams<TCT>) {\n super(files, params);\n this._baseUrl = params.baseUrl.replace(/\\/$/, '');\n this._namespace = params.namespace;\n this._fetchImpl = normalizeFetch(params.fetchImpl);\n this._autoSync = params.autoSync ?? false;\n this._userId = params.userId;\n this._logger = params.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(path: string): Promise<void> {\n try {\n const result = await this.syncToDisk();\n if (result.isFailure()) {\n this._logger.error(`Auto-sync failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-sync threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new HttpTreeAccessors instance from an HTTP backend.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @returns A promise that resolves to a result containing the new HttpTreeAccessors instance or an error message.\n */\n public static async fromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<HttpTreeAccessors<TCT>>> {\n const filesResult = await this._loadFiles<TCT>(params, '/');\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n return succeed(new HttpTreeAccessors<TCT>(filesResult.value, params));\n }\n\n /**\n * Synchronizes all dirty files to the HTTP backend.\n *\n * Uses a concurrency guard: if a sync is already in progress, callers\n * await the existing operation rather than starting a parallel one.\n * This prevents the thundering herd that occurs when autoSync fires\n * for every file written during a bulk operation (e.g. restore).\n *\n * @returns A promise that resolves to a result indicating success or failure.\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._syncPromise) {\n // Wait for the in-flight sync — it drains the queue in a loop,\n // so any items added before it finishes will be included.\n return this._syncPromise;\n }\n\n this._syncPromise = this._doSync().finally(() => {\n this._syncPromise = undefined;\n });\n return this._syncPromise;\n }\n\n private async _doSync(): Promise<Result<void>> {\n // Drain loop: keep processing as long as new items arrive.\n // This is critical for bulk operations (e.g. reset) where many\n // deleteFile/saveFileContents calls happen synchronously — only\n // the first may be in the set when we snapshot, but the rest\n // arrive during the async gaps and must be picked up before\n // we return.\n let didWork = false;\n while (this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0) {\n didWork = true;\n // Snapshot and clear so that changes arriving during the async\n // requests land in the live sets for the next iteration.\n const deletions = new Set(this._pendingDeletions);\n const dirty = new Set(this._dirtyFiles);\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n\n for (const path of deletions) {\n const query = new URLSearchParams();\n query.set('path', path);\n if (this._namespace) {\n query.set('namespace', this._namespace);\n }\n\n const deleteResult = await this._requestWithRetry<{ deleted: boolean }>(`/file?${query.toString()}`, {\n method: 'DELETE'\n });\n if (deleteResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of dirty) {\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`${path}: ${contentsResult.message}`);\n }\n\n const body: Record<string, unknown> = {\n path,\n contents: contentsResult.value\n };\n if (this._namespace) {\n body.namespace = this._namespace;\n }\n\n const saveResult = await this._requestWithRetry<IHttpStorageFileResponse>('/file', {\n method: 'PUT',\n body: JSON.stringify(body)\n });\n if (saveResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`sync ${path}: ${saveResult.message}`);\n }\n }\n }\n\n if (didWork) {\n const syncBody: Record<string, unknown> = {};\n if (this._namespace) {\n syncBody.namespace = this._namespace;\n }\n\n const syncResult = await this._requestWithRetry<IHttpStorageSyncResponse>('/sync', {\n method: 'POST',\n body: JSON.stringify(syncBody)\n });\n\n if (syncResult.isFailure()) {\n return fail(syncResult.message);\n }\n }\n return succeed(undefined);\n }\n\n /**\n * Restores snapshotted items back into the live dirty sets so they\n * are retried on the next sync attempt. Items that were added to\n * the live sets while the sync was in flight are preserved.\n */\n private _restoreUnsynced(deletions: Set<string>, dirty: Set<string>): void {\n for (const path of deletions) {\n this._pendingDeletions.add(path);\n }\n for (const path of dirty) {\n this._dirtyFiles.add(path);\n }\n }\n\n /**\n * Checks if there are any dirty files that need synchronization.\n * @returns True if there are dirty files, false otherwise.\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Gets the list of paths for all dirty files.\n * @returns An array of file paths that have been modified but not yet synchronized.\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.delete(path);\n this._pendingDeletions.add(path);\n\n if (!this._autoSync) {\n return result;\n }\n\n this._runAutoSyncTask(path).catch(() => undefined);\n return result;\n }\n\n /**\n * Saves file contents and marks the file as dirty for synchronization.\n * @param path - The path to the file.\n * @param contents - The new contents of the file.\n * @returns A result indicating success or failure.\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.add(path);\n if (!this._autoSync) {\n return result;\n }\n\n // fire-and-log-on-failure automatic sync for immediate persistence workflow\n this._runAutoSyncTask(path).catch(() => undefined);\n return result;\n }\n\n /**\n * Checks if a file is mutable (can be modified).\n * @param path - The path to the file.\n * @returns A detailed result indicating if the file is mutable and the reason.\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const result = super.fileIsMutable(path);\n if (result.isSuccess() && result.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return result;\n }\n\n /**\n * Makes an HTTP request to the specified resource path.\n * @param resourcePath - The path to the resource.\n * @param init - Optional request initialization options.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private async _request<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const response = await this._fetchImpl(`${this._baseUrl}${resourcePath}`, {\n headers: {\n 'Content-Type': 'application/json',\n ...(this._userId ? { 'X-User-Id': this._userId } : {}),\n /* c8 ignore next 1 - defensive coding: init.headers is never set by current callers */\n ...(init?.headers ?? {})\n },\n ...init\n }).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n return succeed(json as T);\n }\n\n /**\n * Wraps `_request` with retry logic for transient failures\n * (network errors, 503 service unavailable, etc.).\n */\n private async _requestWithRetry<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const maxAttempts = 3;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const result = await this._request<T>(resourcePath, init);\n if (result.isSuccess() || attempt === maxAttempts) {\n return result;\n }\n // Retry on transient-looking errors\n const msg = result.message;\n const lowerMsg = msg.toLowerCase();\n const isTransient =\n msg.includes('503') ||\n msg.includes('502') ||\n msg.includes('429') ||\n lowerMsg.includes('disconnect') ||\n lowerMsg.includes('econnreset') ||\n lowerMsg.includes('failed to fetch') ||\n lowerMsg.includes('network');\n if (!isTransient) {\n return result;\n }\n // Exponential backoff: 500ms, 1000ms\n const delayMs = 500 * Math.pow(2, attempt - 1);\n this._logger.detail(\n `Retrying ${\n init?.method ?? 'GET'\n } ${resourcePath} after ${delayMs}ms (attempt ${attempt}/${maxAttempts})`\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n /* c8 ignore next 1 - defensive coding: loop always returns */\n return fail('retry loop exited unexpectedly');\n }\n\n /**\n * Loads files from the HTTP backend for the specified directory path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param directoryPath - The path to the directory to load files from.\n * @returns A promise that resolves to a result containing the loaded files or an error message.\n */\n private static async _loadFiles<TCT extends string = string>(\n params: IHttpTreeParams<TCT>,\n directoryPath: string\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const childrenResult = await this._requestWithParams<IHttpStorageTreeChildrenResponse>(\n params,\n '/tree/children',\n {\n path: directoryPath,\n namespace: params.namespace\n }\n );\n if (childrenResult.isFailure()) {\n return fail(childrenResult.message);\n }\n\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const item of childrenResult.value.children) {\n if (item.type === 'directory') {\n const nestedResult = await this._loadFiles(params, item.path);\n if (nestedResult.isFailure()) {\n return fail(nestedResult.message);\n }\n allFiles.push(...nestedResult.value);\n } else {\n const fileResult = await this._requestWithParams<IHttpStorageFileResponse>(params, '/file', {\n path: item.path,\n namespace: params.namespace\n });\n if (fileResult.isFailure()) {\n return fail(fileResult.message);\n }\n\n const contentType = params.inferContentType?.(item.path, fileResult.value.contentType).orDefault();\n allFiles.push({\n path: item.path,\n contents: fileResult.value.contents,\n contentType\n });\n }\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Makes an HTTP request with query parameters to the specified resource path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param resourcePath - The path to the resource.\n * @param query - Query parameters to include in the request.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private static async _requestWithParams<T>(\n params: IHttpTreeParams,\n resourcePath: string,\n query: Record<string, string | undefined>\n ): Promise<Result<T>> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n search.set(key, value);\n }\n }\n\n const fetchImpl = normalizeFetch(params.fetchImpl);\n const userIdHeaders: RequestInit | undefined = /* c8 ignore next */ params.userId\n ? { headers: { 'X-User-Id': params.userId } }\n : undefined;\n const response = await fetchImpl(\n `${params.baseUrl.replace(/\\/$/, '')}${resourcePath}?${search.toString()}`,\n userIdHeaders\n ).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n\n return succeed(json as T);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localStorageTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/localStorageTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAkB,IAAI,EAAU,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACzF,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAmB,MAAM,mBAAmB,CAAC;AA4BlE;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,yBACX,SAAQ,QAAQ,CAAC,qBAA0B;IAS3C;;;OAGG;IACH,YACE,KAAoC,EACpC,OAAgB,EAChB,YAAiC,EACjC,MAAqC;;QAErC,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAClC,IAAI,CAAC,aAAa,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,YAAY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,CAAC;QACpC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;;OAMG;IACI,gBAAgB,CAAC,IAAY,EAAE,QAAgB;QACpD,MAAM,MAAM,GAAG,KAAK,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACtD,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;YACvB,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YAC3B,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;gBACnB,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;gBACxC,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC;oBAC3B,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;gBAChC,CAAC;qBAAM,CAAC;oBACN,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;gBAClC,CAAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACI,aAAa,CAAC,IAAY;QAC/B,MAAM,UAAU,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,UAAU,CAAC,SAAS,EAAE,IAAI,UAAU,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YACxD,OAAO,iBAAiB,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, Result, succeed, succeedWithDetail } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport { isJsonObject, type JsonObject } from '@fgv/ts-json-base';\n\n/**\n * Configuration for LocalStorageTreeAccessors.\n * @public\n */\nexport interface ILocalStorageTreeParams<TCT extends string = string>\n extends FileTree.IFileTreeInitParams<TCT> {\n /**\n * Map of directory path prefixes to localStorage keys.\n * Files under each prefix are stored in the corresponding localStorage key.\n * Example: \\{ '/data/ingredients': 'myapp:ingredients:v1' \\}\n */\n pathToKeyMap: Record<string, string>;\n\n /**\n * Storage instance to use. Defaults to window.localStorage.\n * Can be overridden for testing with mock storage.\n */\n storage?: Storage;\n\n /**\n * If true, automatically sync changes to localStorage on every modification.\n * If false (default), changes are only synced when syncToDisk() is called.\n */\n autoSync?: boolean;\n}\n\n/**\n * Browser localStorage-backed file tree accessors with persistence support.\n *\n * Maps filesystem-like directory paths to localStorage keys, where each key stores\n * multiple collections as a JSON object. This provides a general-purpose implementation\n * for browser-based file tree persistence without requiring File System Access API.\n *\n * Storage format per key: `{ \"collection-id\": \"<raw file content>\" }`\n * File paths map as: `/data/ingredients/collection-id.yaml` → stored in key for `/data/ingredients`\n *\n * Legacy format (v1): `{ \"collection-id\": { ...parsedJsonObject } }` is auto-migrated on load.\n *\n * @public\n */\nexport class LocalStorageTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _storage: Storage;\n private readonly _pathToKeyMap: Map<string, string>;\n private readonly _keyToPathMap: Map<string, string>;\n private readonly _dirtyFiles: Set<string>;\n private readonly _autoSync: boolean;\n\n /**\n * Private constructor. Use fromStorage() factory method instead.\n * @internal\n */\n private constructor(\n files: FileTree.IInMemoryFile<TCT>[],\n storage: Storage,\n pathToKeyMap: Map<string, string>,\n params?: ILocalStorageTreeParams<TCT>\n ) {\n super(files, params);\n this._storage = storage;\n this._pathToKeyMap = pathToKeyMap;\n this._keyToPathMap = new Map(Array.from(pathToKeyMap.entries()).map(([k, v]) => [v, k]));\n this._dirtyFiles = new Set();\n /* c8 ignore next 1 - intermittent branch coverage: ?? false branch when params is undefined */\n this._autoSync = params?.autoSync ?? false;\n }\n\n /**\n * Create LocalStorageTreeAccessors from browser localStorage.\n * Loads all collections from the configured storage keys.\n *\n * @param params - Configuration including path-to-key mappings\n * @returns Result containing the accessors or an error\n * @public\n */\n public static fromStorage<TCT extends string = string>(\n params: ILocalStorageTreeParams<TCT>\n ): Result<LocalStorageTreeAccessors<TCT>> {\n try {\n /* c8 ignore next 1 - intermittent branch coverage: window.localStorage branch when params.storage is undefined */\n const storage = params.storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);\n if (!storage) {\n return fail('localStorage is not available');\n }\n\n const pathToKeyMap = new Map(Object.entries(params.pathToKeyMap));\n const files = this._loadFromStorage<TCT>(storage, pathToKeyMap, params);\n\n return succeed(new LocalStorageTreeAccessors<TCT>(files, storage, pathToKeyMap, params));\n /* c8 ignore next 4 - defensive: outer catch for unexpected errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create LocalStorageTreeAccessors: ${message}`);\n }\n }\n\n /**\n * Load all files from localStorage based on path-to-key mappings.\n * @internal\n */\n private static _loadFromStorage<TCT extends string = string>(\n storage: Storage,\n pathToKeyMap: Map<string, string>,\n params?: ILocalStorageTreeParams<TCT>\n ): FileTree.IInMemoryFile<TCT>[] {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const [dataPath, storageKey] of pathToKeyMap.entries()) {\n const rawJson = storage.getItem(storageKey);\n if (!rawJson) {\n continue;\n }\n\n try {\n const parsed: unknown = JSON.parse(rawJson);\n if (!isJsonObject(parsed)) {\n continue;\n }\n\n for (const [collectionId, contents] of Object.entries(parsed)) {\n // Support both new format (string values) and legacy format (JsonObject values)\n let rawContent: string;\n let extension: string;\n if (typeof contents === 'string') {\n rawContent = contents;\n // Infer extension: if content looks like JSON, use .json; otherwise .yaml\n extension = this._looksLikeJson(contents) ? '.json' : '.yaml';\n } else if (isJsonObject(contents)) {\n // Legacy format: migrate by stringifying\n rawContent = JSON.stringify(contents);\n extension = '.json';\n } else {\n continue;\n }\n\n const filePath = this._joinPath(dataPath, `${collectionId}${extension}`);\n /* c8 ignore next 3 - intermittent branch coverage: ternary branches in tight loop */\n const contentType = params?.inferContentType\n ? params.inferContentType(filePath, undefined).orDefault()\n : undefined;\n\n files.push({\n path: filePath,\n contents: rawContent,\n contentType\n });\n }\n } catch {\n // Skip corrupted data\n continue;\n }\n }\n\n return files;\n }\n\n /**\n * Heuristic check: does the content look like JSON?\n * @internal\n */\n private static _looksLikeJson(content: string): boolean {\n const trimmed = content.trimStart();\n return trimmed.startsWith('{') || trimmed.startsWith('[');\n }\n\n /**\n * Join path components, handling leading/trailing slashes.\n * @internal\n */\n private static _joinPath(base: string, name: string): string {\n /* c8 ignore next 2 - intermittent branch coverage: slash-trimming edge cases */\n const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;\n const cleanName = name.startsWith('/') ? name.slice(1) : name;\n return `${cleanBase}/${cleanName}`;\n }\n\n /**\n * Get the storage key for a given file path.\n * @internal\n */\n private _getStorageKeyForPath(path: string): string | undefined {\n // Find the longest matching prefix\n let bestMatch: { prefix: string; key: string } | undefined;\n for (const [prefix, key] of this._pathToKeyMap.entries()) {\n if (path.startsWith(prefix)) {\n /* c8 ignore next 1 - intermittent: overlapping-prefix branch requires two matching prefixes in iteration order */\n if (!bestMatch || prefix.length > bestMatch.prefix.length) {\n bestMatch = { prefix, key };\n }\n }\n }\n return bestMatch?.key;\n }\n\n /**\n * Get the data path prefix for a given file path.\n * @internal\n */\n private _getDataPathForPath(path: string): string | undefined {\n for (const prefix of this._pathToKeyMap.keys()) {\n if (path.startsWith(prefix)) {\n return prefix;\n }\n }\n /* c8 ignore next 2 - coverage intermittently missed in full suite */\n return undefined;\n }\n\n /**\n * Extract collection ID from a file path.\n * Example: '/data/ingredients/my-collection.yaml' → 'my-collection'\n * @internal\n */\n private _getCollectionIdFromPath(path: string): string {\n const dataPath = this._getDataPathForPath(path);\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!dataPath) {\n return path;\n }\n\n const relativePath = path.slice(dataPath.length);\n /* c8 ignore next 1 - defensive: relativePath always starts with / when paths are absolute */\n const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath;\n\n // Remove any file extension\n const dotIndex = cleanPath.lastIndexOf('.');\n return dotIndex > 0 ? cleanPath.slice(0, dotIndex) : cleanPath;\n }\n\n /**\n * Remove a file's entry from its localStorage key.\n * @internal\n */\n private _deleteFileFromStorage(path: string): void {\n const storageKey = this._getStorageKeyForPath(path);\n if (!storageKey) {\n return;\n }\n\n const collectionId = this._getCollectionIdFromPath(path);\n const existingJson = this._storage.getItem(storageKey);\n if (!existingJson) {\n return;\n }\n\n try {\n const parsed = JSON.parse(existingJson);\n if (isJsonObject(parsed)) {\n const existing = parsed as Record<string, unknown>;\n delete existing[collectionId];\n if (Object.keys(existing).length > 0) {\n this._storage.setItem(storageKey, JSON.stringify(existing));\n } else {\n this._storage.removeItem(storageKey);\n }\n }\n } catch {\n // Storage is corrupted — nothing to clean up\n }\n }\n\n /**\n * Sync a single dirty file to localStorage.\n * @internal\n */\n private _syncFile(path: string): Result<void> {\n const storageKey = this._getStorageKeyForPath(path);\n if (!storageKey) {\n return fail(`No storage key configured for path: ${path}`);\n }\n\n const collectionId = this._getCollectionIdFromPath(path);\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n return fail(`Failed to get file contents for ${path}: ${contentsResult.message}`);\n }\n\n try {\n const contents = contentsResult.value;\n\n // Load existing data from storage\n const existingJson = this._storage.getItem(storageKey);\n let existing: Record<string, unknown> = {};\n if (existingJson) {\n try {\n const parsed = JSON.parse(existingJson);\n if (isJsonObject(parsed)) {\n existing = parsed as Record<string, unknown>;\n }\n } catch {\n // Start fresh if corrupted\n }\n }\n\n // Store raw content string (content-agnostic: JSON, YAML, etc.)\n existing[collectionId] = contents;\n this._storage.setItem(storageKey, JSON.stringify(existing));\n\n return succeed(undefined);\n /* c8 ignore next 4 - defensive: only triggers on storage quota or similar runtime errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to sync file ${path}: ${message}`);\n }\n }\n\n /**\n * Sync all dirty files to localStorage.\n * @returns Result indicating success or failure\n * @public\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._dirtyFiles.size === 0) {\n return succeed(undefined);\n }\n\n const errors: string[] = [];\n for (const path of this._dirtyFiles) {\n const result = this._syncFile(path);\n if (result.isFailure()) {\n errors.push(result.message);\n }\n }\n\n if (errors.length > 0) {\n return fail(`Failed to sync ${errors.length} file(s): ${errors.join('; ')}`);\n }\n\n this._dirtyFiles.clear();\n return succeed(undefined);\n }\n\n /**\n * Check if there are unsaved changes.\n * @returns True if there are dirty files\n * @public\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0;\n }\n\n /**\n * Get list of file paths with unsaved changes.\n * @returns Array of dirty file paths\n * @public\n */\n public getDirtyPaths(): string[] {\n return Array.from(this._dirtyFiles);\n }\n\n /**\n * Delete a file and remove it from localStorage.\n * @param path - File path to delete\n * @returns Result with true if deleted, or error\n * @public\n */\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isSuccess()) {\n this._dirtyFiles.delete(path);\n this._deleteFileFromStorage(path);\n }\n return result;\n }\n\n /**\n * Save file contents. Marks file as dirty and optionally auto-syncs.\n * @param path - File path\n * @param contents - New file contents\n * @returns Result with the saved contents or error\n * @public\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isSuccess()) {\n this._dirtyFiles.add(path);\n if (this._autoSync) {\n const syncResult = this._syncFile(path);\n if (syncResult.isSuccess()) {\n this._dirtyFiles.delete(path);\n } else {\n return fail(syncResult.message);\n }\n }\n }\n return result;\n }\n\n /**\n * Check if a file is mutable and return persistence detail.\n * @param path - File path to check\n * @returns DetailedResult with mutability status and 'persistent' detail if mutable\n * @public\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const baseResult = super.fileIsMutable(path);\n if (baseResult.isSuccess() && baseResult.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return baseResult;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"localStorageTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/localStorageTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAkB,IAAI,EAAU,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACzF,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AA4BjD;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,yBACX,SAAQ,QAAQ,CAAC,qBAA0B;IAS3C;;;OAGG;IACH,YACE,KAAoC,EACpC,OAAgB,EAChB,YAAiC,EACjC,MAAqC;;QAErC,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CA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YACvB,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YAC9B,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,CAAC;QACpC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;;OAMG;IACI,gBAAgB,CAAC,IAAY,EAAE,QAAgB;QACpD,MAAM,MAAM,GAAG,KAAK,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACtD,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;YACvB,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YAC3B,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;gBACnB,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;gBACxC,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC;oBAC3B,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;gBAChC,CAAC;qBAAM,CAAC;oBACN,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;gBAClC,CAAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACI,aAAa,CAAC,IAAY;QAC/B,MAAM,UAAU,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,UAAU,CAAC,SAAS,EAAE,IAAI,UAAU,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YACxD,OAAO,iBAAiB,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, Result, succeed, succeedWithDetail } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport { isJsonObject } from '@fgv/ts-json-base';\n\n/**\n * Configuration for LocalStorageTreeAccessors.\n * @public\n */\nexport interface ILocalStorageTreeParams<TCT extends string = string>\n extends FileTree.IFileTreeInitParams<TCT> {\n /**\n * Map of directory path prefixes to localStorage keys.\n * Files under each prefix are stored in the corresponding localStorage key.\n * Example: \\{ '/data/ingredients': 'myapp:ingredients:v1' \\}\n */\n pathToKeyMap: Record<string, string>;\n\n /**\n * Storage instance to use. Defaults to window.localStorage.\n * Can be overridden for testing with mock storage.\n */\n storage?: Storage;\n\n /**\n * If true, automatically sync changes to localStorage on every modification.\n * If false (default), changes are only synced when syncToDisk() is called.\n */\n autoSync?: boolean;\n}\n\n/**\n * Browser localStorage-backed file tree accessors with persistence support.\n *\n * Maps filesystem-like directory paths to localStorage keys, where each key stores\n * multiple collections as a JSON object. This provides a general-purpose implementation\n * for browser-based file tree persistence without requiring File System Access API.\n *\n * Storage format per key: `{ \"collection-id\": \"<raw file content>\" }`\n * File paths map as: `/data/ingredients/collection-id.yaml` → stored in key for `/data/ingredients`\n *\n * Legacy format (v1): `{ \"collection-id\": { ...parsedJsonObject } }` is auto-migrated on load.\n *\n * @public\n */\nexport class LocalStorageTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _storage: Storage;\n private readonly _pathToKeyMap: Map<string, string>;\n private readonly _keyToPathMap: Map<string, string>;\n private readonly _dirtyFiles: Set<string>;\n private readonly _autoSync: boolean;\n\n /**\n * Private constructor. Use fromStorage() factory method instead.\n * @internal\n */\n private constructor(\n files: FileTree.IInMemoryFile<TCT>[],\n storage: Storage,\n pathToKeyMap: Map<string, string>,\n params?: ILocalStorageTreeParams<TCT>\n ) {\n super(files, params);\n this._storage = storage;\n this._pathToKeyMap = pathToKeyMap;\n this._keyToPathMap = new Map(Array.from(pathToKeyMap.entries()).map(([k, v]) => [v, k]));\n this._dirtyFiles = new Set();\n /* c8 ignore next 1 - intermittent branch coverage: ?? false branch when params is undefined */\n this._autoSync = params?.autoSync ?? false;\n }\n\n /**\n * Create LocalStorageTreeAccessors from browser localStorage.\n * Loads all collections from the configured storage keys.\n *\n * @param params - Configuration including path-to-key mappings\n * @returns Result containing the accessors or an error\n * @public\n */\n public static fromStorage<TCT extends string = string>(\n params: ILocalStorageTreeParams<TCT>\n ): Result<LocalStorageTreeAccessors<TCT>> {\n try {\n /* c8 ignore next 1 - intermittent branch coverage: window.localStorage branch when params.storage is undefined */\n const storage = params.storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);\n if (!storage) {\n return fail('localStorage is not available');\n }\n\n const pathToKeyMap = new Map(Object.entries(params.pathToKeyMap));\n const files = this._loadFromStorage<TCT>(storage, pathToKeyMap, params);\n\n return succeed(new LocalStorageTreeAccessors<TCT>(files, storage, pathToKeyMap, params));\n /* c8 ignore next 4 - defensive: outer catch for unexpected errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create LocalStorageTreeAccessors: ${message}`);\n }\n }\n\n /**\n * Load all files from localStorage based on path-to-key mappings.\n * @internal\n */\n private static _loadFromStorage<TCT extends string = string>(\n storage: Storage,\n pathToKeyMap: Map<string, string>,\n params?: ILocalStorageTreeParams<TCT>\n ): FileTree.IInMemoryFile<TCT>[] {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const [dataPath, storageKey] of pathToKeyMap.entries()) {\n const rawJson = storage.getItem(storageKey);\n if (!rawJson) {\n continue;\n }\n\n try {\n const parsed: unknown = JSON.parse(rawJson);\n if (!isJsonObject(parsed)) {\n continue;\n }\n\n for (const [collectionId, contents] of Object.entries(parsed)) {\n // Support both new format (string values) and legacy format (JsonObject values)\n let rawContent: string;\n let extension: string;\n if (typeof contents === 'string') {\n rawContent = contents;\n // Infer extension: if content looks like JSON, use .json; otherwise .yaml\n extension = this._looksLikeJson(contents) ? '.json' : '.yaml';\n } else if (isJsonObject(contents)) {\n // Legacy format: migrate by stringifying\n rawContent = JSON.stringify(contents);\n extension = '.json';\n } else {\n continue;\n }\n\n const filePath = this._joinPath(dataPath, `${collectionId}${extension}`);\n /* c8 ignore next 3 - intermittent branch coverage: ternary branches in tight loop */\n const contentType = params?.inferContentType\n ? params.inferContentType(filePath, undefined).orDefault()\n : undefined;\n\n files.push({\n path: filePath,\n contents: rawContent,\n contentType\n });\n }\n } catch {\n // Skip corrupted data\n continue;\n }\n }\n\n return files;\n }\n\n /**\n * Heuristic check: does the content look like JSON?\n * @internal\n */\n private static _looksLikeJson(content: string): boolean {\n const trimmed = content.trimStart();\n return trimmed.startsWith('{') || trimmed.startsWith('[');\n }\n\n /**\n * Join path components, handling leading/trailing slashes.\n * @internal\n */\n private static _joinPath(base: string, name: string): string {\n /* c8 ignore next 2 - intermittent branch coverage: slash-trimming edge cases */\n const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;\n const cleanName = name.startsWith('/') ? name.slice(1) : name;\n return `${cleanBase}/${cleanName}`;\n }\n\n /**\n * Get the storage key for a given file path.\n * @internal\n */\n private _getStorageKeyForPath(path: string): string | undefined {\n // Find the longest matching prefix\n let bestMatch: { prefix: string; key: string } | undefined;\n for (const [prefix, key] of this._pathToKeyMap.entries()) {\n if (path.startsWith(prefix)) {\n /* c8 ignore next 1 - intermittent: overlapping-prefix branch requires two matching prefixes in iteration order */\n if (!bestMatch || prefix.length > bestMatch.prefix.length) {\n bestMatch = { prefix, key };\n }\n }\n }\n return bestMatch?.key;\n }\n\n /**\n * Get the data path prefix for a given file path.\n * @internal\n */\n private _getDataPathForPath(path: string): string | undefined {\n for (const prefix of this._pathToKeyMap.keys()) {\n if (path.startsWith(prefix)) {\n return prefix;\n }\n }\n /* c8 ignore next 2 - coverage intermittently missed in full suite */\n return undefined;\n }\n\n /**\n * Extract collection ID from a file path.\n * Example: '/data/ingredients/my-collection.yaml' → 'my-collection'\n * @internal\n */\n private _getCollectionIdFromPath(path: string): string {\n const dataPath = this._getDataPathForPath(path);\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!dataPath) {\n return path;\n }\n\n const relativePath = path.slice(dataPath.length);\n /* c8 ignore next 1 - defensive: relativePath always starts with / when paths are absolute */\n const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath;\n\n // Remove any file extension\n const dotIndex = cleanPath.lastIndexOf('.');\n return dotIndex > 0 ? cleanPath.slice(0, dotIndex) : cleanPath;\n }\n\n /**\n * Remove a file's entry from its localStorage key.\n * @internal\n */\n private _deleteFileFromStorage(path: string): void {\n const storageKey = this._getStorageKeyForPath(path);\n if (!storageKey) {\n return;\n }\n\n const collectionId = this._getCollectionIdFromPath(path);\n const existingJson = this._storage.getItem(storageKey);\n if (!existingJson) {\n return;\n }\n\n try {\n const parsed = JSON.parse(existingJson);\n if (isJsonObject(parsed)) {\n const existing = parsed as Record<string, unknown>;\n delete existing[collectionId];\n if (Object.keys(existing).length > 0) {\n this._storage.setItem(storageKey, JSON.stringify(existing));\n } else {\n this._storage.removeItem(storageKey);\n }\n }\n } catch {\n // Storage is corrupted — nothing to clean up\n }\n }\n\n /**\n * Sync a single dirty file to localStorage.\n * @internal\n */\n private _syncFile(path: string): Result<void> {\n const storageKey = this._getStorageKeyForPath(path);\n if (!storageKey) {\n return fail(`No storage key configured for path: ${path}`);\n }\n\n const collectionId = this._getCollectionIdFromPath(path);\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n return fail(`Failed to get file contents for ${path}: ${contentsResult.message}`);\n }\n\n try {\n const contents = contentsResult.value;\n\n // Load existing data from storage\n const existingJson = this._storage.getItem(storageKey);\n let existing: Record<string, unknown> = {};\n if (existingJson) {\n try {\n const parsed = JSON.parse(existingJson);\n if (isJsonObject(parsed)) {\n existing = parsed as Record<string, unknown>;\n }\n } catch {\n // Start fresh if corrupted\n }\n }\n\n // Store raw content string (content-agnostic: JSON, YAML, etc.)\n existing[collectionId] = contents;\n this._storage.setItem(storageKey, JSON.stringify(existing));\n\n return succeed(undefined);\n /* c8 ignore next 4 - defensive: only triggers on storage quota or similar runtime errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to sync file ${path}: ${message}`);\n }\n }\n\n /**\n * Sync all dirty files to localStorage.\n * @returns Result indicating success or failure\n * @public\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._dirtyFiles.size === 0) {\n return succeed(undefined);\n }\n\n const errors: string[] = [];\n for (const path of this._dirtyFiles) {\n const result = this._syncFile(path);\n if (result.isFailure()) {\n errors.push(result.message);\n }\n }\n\n if (errors.length > 0) {\n return fail(`Failed to sync ${errors.length} file(s): ${errors.join('; ')}`);\n }\n\n this._dirtyFiles.clear();\n return succeed(undefined);\n }\n\n /**\n * Check if there are unsaved changes.\n * @returns True if there are dirty files\n * @public\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0;\n }\n\n /**\n * Get list of file paths with unsaved changes.\n * @returns Array of dirty file paths\n * @public\n */\n public getDirtyPaths(): string[] {\n return Array.from(this._dirtyFiles);\n }\n\n /**\n * Delete a file and remove it from localStorage.\n * @param path - File path to delete\n * @returns Result with true if deleted, or error\n * @public\n */\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isSuccess()) {\n this._dirtyFiles.delete(path);\n this._deleteFileFromStorage(path);\n }\n return result;\n }\n\n /**\n * Save file contents. Marks file as dirty and optionally auto-syncs.\n * @param path - File path\n * @param contents - New file contents\n * @returns Result with the saved contents or error\n * @public\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isSuccess()) {\n this._dirtyFiles.add(path);\n if (this._autoSync) {\n const syncResult = this._syncFile(path);\n if (syncResult.isSuccess()) {\n this._dirtyFiles.delete(path);\n } else {\n return fail(syncResult.message);\n }\n }\n }\n return result;\n }\n\n /**\n * Check if a file is mutable and return persistence detail.\n * @param path - File path to check\n * @returns DetailedResult with mutability status and 'persistent' detail if mutable\n * @public\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const baseResult = super.fileIsMutable(path);\n if (baseResult.isSuccess() && baseResult.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return baseResult;\n }\n}\n"]}
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* SOFTWARE.
|
|
21
21
|
*/
|
|
22
22
|
import { FileTree } from '@fgv/ts-json-base';
|
|
23
|
-
import { FileApiTreeAccessors } from '../file-tree
|
|
23
|
+
import { FileApiTreeAccessors } from '../file-tree';
|
|
24
24
|
/**
|
|
25
25
|
* Default initialization parameters for a `FileTree` using {@link FileApiTreeAccessors}.
|
|
26
26
|
* @public
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileTreeHelpers.js","sourceRoot":"","sources":["../../../src/packlets/helpers/fileTreeHelpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C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,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC;AACtF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAU;IAC5C,OAAO,oBAAoB,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC;AACxD,CAAC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport { FileApiTreeAccessors, IFileMetadata } from '../file-tree';\n\n/**\n * Default initialization parameters for a `FileTree` using {@link FileApiTreeAccessors}.\n * @public\n */\nexport const defaultFileApiTreeInitParams: FileTree.IFileTreeInitParams<string> = {\n inferContentType: FileTree.FileItem.defaultAcceptContentType\n};\n\n/**\n * Helper function to create a new FileTree instance\n * from a browser FileList (e.g., from input[type=\"file\"]).\n * @param fileList - FileList from a file input element\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to a successful Result with the new FileTree instance\n * if successful, or a failed Result with an error message otherwise\n * @remarks The content type of the files is always `string` and the default\n * accept contentType function (`FileTree.FileItem.defaultAcceptContentType`) is\n * used, so content type is derived from the mime type of the file, when\n * available.\n * @public\n */\nexport function fromFileList(\n fileList: FileList,\n params?: FileTree.IFileTreeInitParams<string>\n): Promise<Result<FileTree.FileTree<string>>> {\n params = { ...defaultFileApiTreeInitParams, ...(params ?? {}) };\n return FileApiTreeAccessors.fromFileList(fileList, params);\n}\n\n/**\n * Helper function to create a new FileTree instance\n * from a directory upload with webkitRelativePath support.\n * @param fileList - FileList from a directory upload (input with webkitdirectory)\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to a successful Result with the new FileTree instance\n * if successful, or a failed Result with an error message otherwise\n * @remarks The content type of the files is always `string` and the default\n * accept contentType function (`FileTree.FileItem.defaultAcceptContentType`) is\n * is used, so content type is derived from the mime type of the file, when\n * available.\n * @public\n */\nexport function fromDirectoryUpload(\n fileList: FileList,\n params?: FileTree.IFileTreeInitParams<string>\n): Promise<Result<FileTree.FileTree<string>>> {\n params = { ...defaultFileApiTreeInitParams, ...(params ?? {}) };\n return FileApiTreeAccessors.fromDirectoryUpload(fileList, params);\n}\n\n/**\n * Helper function to get the original File object from a FileList by path.\n * @param fileList - The original FileList\n * @param path - The path to the file\n * @returns A successful Result with the File object if found,\n * or a failed Result with an error message otherwise\n * @public\n */\nexport function getOriginalFile(fileList: FileList, path: string): Result<File> {\n return FileApiTreeAccessors.getOriginalFile(fileList, path);\n}\n\n/**\n * Helper function to extract metadata from a `FileList`.\n * @param fileList - The `FileList` to extract metadata from\n * @returns Array of {@link IFileMetadata | file metadata} objects\n * @public\n */\nexport function extractFileListMetadata(fileList: FileList): Array<IFileMetadata> {\n return Array.from(fileList).map((f) => FileApiTreeAccessors.extractFileMetadata(f));\n}\n\n/**\n * Helper function to extract metadata from a `File`.\n * @param file - The File to extract metadata from\n * @returns {@link IFileMetadata | file metadata} object\n * @public\n */\nexport function extractFileMetadata(file: File): IFileMetadata {\n return FileApiTreeAccessors.extractFileMetadata(file);\n}\n"]}
|
package/dist/ts-web-extras.d.ts
CHANGED
|
@@ -130,6 +130,48 @@ declare class BrowserCryptoProvider implements CryptoUtils_2.ICryptoProvider {
|
|
|
130
130
|
* @returns `Success` with the imported public `CryptoKey`, or `Failure` with error context.
|
|
131
131
|
*/
|
|
132
132
|
importPublicKeySpki(spkiBytes: Uint8Array, algorithm: CryptoUtils_2.KeyPairAlgorithm): Promise<Result<CryptoKey>>;
|
|
133
|
+
/**
|
|
134
|
+
* Signs `data` with `privateKey` using the algorithm inferred from the key.
|
|
135
|
+
* @param privateKey - A signing `CryptoKey` (`'ecdsa-p256'` or `'ed25519'`).
|
|
136
|
+
* @param data - The bytes to sign.
|
|
137
|
+
* @returns `Success` with the raw signature bytes, or `Failure` with error context.
|
|
138
|
+
*/
|
|
139
|
+
sign(privateKey: CryptoKey, data: Uint8Array): Promise<Result<Uint8Array>>;
|
|
140
|
+
/**
|
|
141
|
+
* Verifies a signature produced by {@link BrowserCryptoProvider.sign}.
|
|
142
|
+
* @param publicKey - A verify `CryptoKey` (`'ecdsa-p256'` or `'ed25519'`).
|
|
143
|
+
* @param signature - The raw signature bytes.
|
|
144
|
+
* @param data - The original data that was signed.
|
|
145
|
+
* @returns `Success` with `true` if valid, `false` if not, or `Failure` with error context.
|
|
146
|
+
*/
|
|
147
|
+
verify(publicKey: CryptoKey, signature: Uint8Array, data: Uint8Array): Promise<Result<boolean>>;
|
|
148
|
+
/**
|
|
149
|
+
* Compares two byte arrays in constant time.
|
|
150
|
+
*
|
|
151
|
+
* Accumulates XOR differences with bitwise-OR; no early-return is possible
|
|
152
|
+
* once the length check passes, making timing independent of the byte
|
|
153
|
+
* values. Returns `false` immediately on length mismatch (length is not
|
|
154
|
+
* secret in normal use).
|
|
155
|
+
* @param a - First byte array.
|
|
156
|
+
* @param b - Second byte array.
|
|
157
|
+
* @returns `true` if lengths match and all bytes are equal, `false` otherwise.
|
|
158
|
+
*/
|
|
159
|
+
timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;
|
|
160
|
+
/**
|
|
161
|
+
* Computes an HMAC-SHA256 MAC for `data` using `key`.
|
|
162
|
+
* @param key - An HMAC `CryptoKey` with `'sign'` usage.
|
|
163
|
+
* @param data - The bytes to authenticate.
|
|
164
|
+
* @returns `Success` with the 32-byte MAC, or `Failure` with error context.
|
|
165
|
+
*/
|
|
166
|
+
hmacSha256(key: CryptoKey, data: Uint8Array): Promise<Result<Uint8Array>>;
|
|
167
|
+
/**
|
|
168
|
+
* Verifies an HMAC-SHA256 MAC in constant time.
|
|
169
|
+
* @param key - An HMAC `CryptoKey` with `'sign'` usage.
|
|
170
|
+
* @param signature - The MAC bytes to verify.
|
|
171
|
+
* @param data - The original data that was authenticated.
|
|
172
|
+
* @returns `Success` with `true` if valid, `false` if not, or `Failure` with error context.
|
|
173
|
+
*/
|
|
174
|
+
verifyHmacSha256(key: CryptoKey, signature: Uint8Array, data: Uint8Array): Promise<Result<boolean>>;
|
|
133
175
|
/**
|
|
134
176
|
* Wraps `plaintext` for the holder of `recipientPublicKey` using
|
|
135
177
|
* ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
|
|
@@ -184,6 +226,8 @@ declare function createBrowserCryptoProvider(): Result<BrowserCryptoProvider>;
|
|
|
184
226
|
|
|
185
227
|
declare namespace CryptoUtils {
|
|
186
228
|
export {
|
|
229
|
+
HpkeProvider,
|
|
230
|
+
IHpkeSealResult,
|
|
187
231
|
BrowserHashProvider,
|
|
188
232
|
createBrowserCryptoProvider,
|
|
189
233
|
BrowserCryptoProvider
|
|
@@ -195,13 +239,13 @@ export { CryptoUtils }
|
|
|
195
239
|
* Default IndexedDB database name for directory handles.
|
|
196
240
|
* @public
|
|
197
241
|
*/
|
|
198
|
-
export declare const DEFAULT_DIRECTORY_HANDLE_DB
|
|
242
|
+
export declare const DEFAULT_DIRECTORY_HANDLE_DB: string;
|
|
199
243
|
|
|
200
244
|
/**
|
|
201
245
|
* Default IndexedDB store name for directory handles.
|
|
202
246
|
* @public
|
|
203
247
|
*/
|
|
204
|
-
export declare const DEFAULT_DIRECTORY_HANDLE_STORE
|
|
248
|
+
export declare const DEFAULT_DIRECTORY_HANDLE_STORE: string;
|
|
205
249
|
|
|
206
250
|
/**
|
|
207
251
|
* Default initialization parameters for a `FileTree` using {@link FileApiTreeAccessors}.
|
|
@@ -300,7 +344,7 @@ declare function extractFileListMetadata(fileList: FileList): Array<IFileMetadat
|
|
|
300
344
|
* Supports File API (FileList) and File System Access API handles.
|
|
301
345
|
* @public
|
|
302
346
|
*/
|
|
303
|
-
export declare class FileApiTreeAccessors
|
|
347
|
+
export declare class FileApiTreeAccessors {
|
|
304
348
|
/**
|
|
305
349
|
* Create a persistent FileTree from a File System Access API directory handle.
|
|
306
350
|
* Changes to files can be synced back to disk.
|
|
@@ -722,6 +766,14 @@ declare function extractFileListMetadata(fileList: FileList): Array<IFileMetadat
|
|
|
722
766
|
*/
|
|
723
767
|
declare function getOriginalFile(fileList: FileList, path: string): Result<File>;
|
|
724
768
|
|
|
769
|
+
/**
|
|
770
|
+
* HPKE base mode (RFC 9180) — `DHKEM(X25519, HKDF-SHA256) + HKDF-SHA256 + AES-256-GCM`.
|
|
771
|
+
* Re-exported from `@fgv/ts-extras` for browser consumers.
|
|
772
|
+
* @see {@link CryptoUtils.HpkeProvider}
|
|
773
|
+
* @public
|
|
774
|
+
*/
|
|
775
|
+
declare const HpkeProvider: typeof CryptoUtils_2.HpkeProvider;
|
|
776
|
+
|
|
725
777
|
/**
|
|
726
778
|
* HTTP-backed file tree accessors that cache data in memory and persist via REST API.
|
|
727
779
|
* @public
|
|
@@ -893,6 +945,12 @@ declare function extractFileListMetadata(fileList: FileList): Array<IFileMetadat
|
|
|
893
945
|
showSaveFilePicker(options?: ShowSaveFilePickerOptions): Promise<FileSystemFileHandle_2>;
|
|
894
946
|
}
|
|
895
947
|
|
|
948
|
+
/**
|
|
949
|
+
* Output of `HpkeProvider.sealBase`. Re-exported from `@fgv/ts-extras`.
|
|
950
|
+
* @public
|
|
951
|
+
*/
|
|
952
|
+
declare type IHpkeSealResult = CryptoUtils_2.IHpkeSealResult;
|
|
953
|
+
|
|
896
954
|
/**
|
|
897
955
|
* Configuration for creating HTTP-backed tree accessors.
|
|
898
956
|
* @public
|