@fgv/ts-web-extras 5.1.0-0 → 5.1.0-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +56 -33
- package/.rush/temp/chunked-rush-logs/ts-web-extras.test.chunks.jsonl +70 -0
- package/.rush/temp/operation/build/all.log +56 -33
- package/.rush/temp/operation/build/error.log +18 -0
- package/.rush/temp/operation/build/log-chunks.jsonl +56 -33
- package/.rush/temp/operation/build/state.json +1 -1
- package/.rush/temp/operation/test/all.log +70 -0
- package/.rush/temp/operation/test/error.log +16 -0
- package/.rush/temp/operation/test/log-chunks.jsonl +70 -0
- package/.rush/temp/operation/test/state.json +3 -0
- package/dist/packlets/file-tree/fileApiTreeAccessors.js +15 -0
- package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
- package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js +79 -10
- package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
- package/dist/packlets/file-tree/httpTreeAccessors.js +279 -0
- package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -0
- package/dist/packlets/file-tree/index.js +1 -0
- package/dist/packlets/file-tree/index.js.map +1 -1
- package/dist/packlets/file-tree/localStorageTreeAccessors.js +51 -0
- package/dist/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
- package/dist/test/unit/fileApiTreeAccessors.test.js +51 -0
- package/dist/test/unit/fileApiTreeAccessors.test.js.map +1 -1
- package/dist/test/unit/fileSystemAccessTreeAccessors.test.js +265 -160
- package/dist/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -1
- package/dist/test/unit/httpTreeAccessors.test.js +1000 -0
- package/dist/test/unit/httpTreeAccessors.test.js.map +1 -0
- package/dist/test/unit/localStorageTreeAccessors.test.js +218 -1
- package/dist/test/unit/localStorageTreeAccessors.test.js.map +1 -1
- package/dist/ts-web-extras.d.ts +124 -0
- package/docs/@fgv/namespaces/CryptoUtils/README.md +18 -0
- package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserCryptoProvider.md +203 -0
- package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserHashProvider.md +63 -0
- package/docs/@fgv/namespaces/CryptoUtils/functions/createBrowserCryptoProvider.md +18 -0
- package/docs/@fgv/namespaces/FileTreeHelpers/README.md +19 -0
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileListMetadata.md +23 -0
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileMetadata.md +23 -0
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromDirectoryUpload.md +33 -0
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromFileList.md +33 -0
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/getOriginalFile.md +25 -0
- package/docs/@fgv/namespaces/FileTreeHelpers/variables/defaultFileApiTreeInitParams.md +11 -0
- package/docs/README.md +78 -0
- package/docs/classes/DirectoryHandleStore.md +116 -0
- package/docs/classes/FileApiTreeAccessors.md +286 -0
- package/docs/classes/FileSystemAccessTreeAccessors.md +557 -0
- package/docs/classes/HttpTreeAccessors.md +508 -0
- package/docs/classes/LocalStorageTreeAccessors.md +520 -0
- package/docs/functions/exportAsJson.md +23 -0
- package/docs/functions/exportUsingFileSystemAPI.md +26 -0
- package/docs/functions/extractDirectoryPath.md +23 -0
- package/docs/functions/isDirectoryHandle.md +23 -0
- package/docs/functions/isFileHandle.md +23 -0
- package/docs/functions/isFilePath.md +21 -0
- package/docs/functions/parseContextFilter.md +22 -0
- package/docs/functions/parseQualifierDefaults.md +22 -0
- package/docs/functions/parseResourceTypes.md +22 -0
- package/docs/functions/parseUrlParameters.md +15 -0
- package/docs/functions/safeShowDirectoryPicker.md +24 -0
- package/docs/functions/safeShowOpenFilePicker.md +24 -0
- package/docs/functions/safeShowSaveFilePicker.md +24 -0
- package/docs/functions/supportsFileSystemAccess.md +23 -0
- package/docs/interfaces/FilePickerAcceptType.md +16 -0
- package/docs/interfaces/FileSystemCreateWritableOptions.md +15 -0
- package/docs/interfaces/FileSystemDirectoryHandle.md +187 -0
- package/docs/interfaces/FileSystemFileHandle.md +106 -0
- package/docs/interfaces/FileSystemGetDirectoryOptions.md +15 -0
- package/docs/interfaces/FileSystemGetFileOptions.md +15 -0
- package/docs/interfaces/FileSystemHandle.md +69 -0
- package/docs/interfaces/FileSystemHandlePermissionDescriptor.md +15 -0
- package/docs/interfaces/FileSystemRemoveOptions.md +15 -0
- package/docs/interfaces/FileSystemWritableFileStream.md +127 -0
- package/docs/interfaces/IDirectoryHandleTreeInitializer.md +17 -0
- package/docs/interfaces/IFileHandleTreeInitializer.md +16 -0
- package/docs/interfaces/IFileListTreeInitializer.md +15 -0
- package/docs/interfaces/IFileMetadata.md +19 -0
- package/docs/interfaces/IFileSystemAccessTreeParams.md +30 -0
- package/docs/interfaces/IFsAccessApis.md +57 -0
- package/docs/interfaces/IHttpTreeParams.md +32 -0
- package/docs/interfaces/ILocalStorageTreeParams.md +30 -0
- package/docs/interfaces/IUrlConfigOptions.md +27 -0
- package/docs/interfaces/ShowDirectoryPickerOptions.md +17 -0
- package/docs/interfaces/ShowOpenFilePickerOptions.md +19 -0
- package/docs/interfaces/ShowSaveFilePickerOptions.md +19 -0
- package/docs/type-aliases/TreeInitializer.md +11 -0
- package/docs/type-aliases/WellKnownDirectory.md +11 -0
- package/docs/type-aliases/WindowWithFsAccess.md +11 -0
- package/docs/variables/DEFAULT_DIRECTORY_HANDLE_DB.md +11 -0
- package/docs/variables/DEFAULT_DIRECTORY_HANDLE_STORE.md +11 -0
- package/etc/ts-web-extras.api.md +33 -0
- package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +9 -0
- package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.js +15 -0
- package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts +17 -1
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js +78 -9
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
- package/lib/packlets/file-tree/httpTreeAccessors.d.ts +88 -0
- package/lib/packlets/file-tree/httpTreeAccessors.d.ts.map +1 -0
- package/lib/packlets/file-tree/httpTreeAccessors.js +283 -0
- package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -0
- package/lib/packlets/file-tree/index.d.ts +1 -0
- package/lib/packlets/file-tree/index.d.ts.map +1 -1
- package/lib/packlets/file-tree/index.js +1 -0
- package/lib/packlets/file-tree/index.js.map +1 -1
- package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts +12 -0
- package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/file-tree/localStorageTreeAccessors.js +51 -0
- package/lib/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
- package/lib/test/unit/fileApiTreeAccessors.test.js +51 -0
- package/lib/test/unit/fileApiTreeAccessors.test.js.map +1 -1
- package/lib/test/unit/fileSystemAccessTreeAccessors.test.js +265 -160
- package/lib/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -1
- package/lib/test/unit/httpTreeAccessors.test.d.ts +2 -0
- package/lib/test/unit/httpTreeAccessors.test.d.ts.map +1 -0
- package/lib/test/unit/httpTreeAccessors.test.js +1002 -0
- package/lib/test/unit/httpTreeAccessors.test.js.map +1 -0
- package/lib/test/unit/localStorageTreeAccessors.test.js +218 -1
- package/lib/test/unit/localStorageTreeAccessors.test.js.map +1 -1
- package/package.json +25 -25
- package/rush-logs/ts-web-extras.build.cache.log +0 -3
- package/rush-logs/ts-web-extras.build.error.log +18 -0
- package/rush-logs/ts-web-extras.build.log +56 -33
- package/rush-logs/ts-web-extras.test.cache.log +1 -0
- package/rush-logs/ts-web-extras.test.error.log +16 -0
- package/rush-logs/ts-web-extras.test.log +70 -0
- package/src/packlets/file-tree/fileApiTreeAccessors.ts +18 -0
- package/src/packlets/file-tree/fileSystemAccessTreeAccessors.ts +100 -8
- package/src/packlets/file-tree/httpTreeAccessors.ts +381 -0
- package/src/packlets/file-tree/index.ts +1 -0
- package/src/packlets/file-tree/localStorageTreeAccessors.ts +53 -0
- package/src/test/unit/fileApiTreeAccessors.test.ts +69 -0
- package/src/test/unit/fileSystemAccessTreeAccessors.test.ts +341 -188
- package/src/test/unit/httpTreeAccessors.test.ts +1278 -0
- package/src/test/unit/localStorageTreeAccessors.test.ts +269 -1
- package/temp/build/typescript/ts_8nwakTlr.json +1 -1
- package/temp/coverage/crypto/browserHashProvider.ts.html +304 -0
- package/temp/coverage/crypto/index.html +116 -0
- package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +1 -1
- package/temp/coverage/crypto-utils/browserHashProvider.ts.html +1 -1
- package/temp/coverage/crypto-utils/index.html +1 -1
- package/temp/coverage/file-tree/directoryHandleStore.ts.html +1 -1
- package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +60 -6
- package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +410 -134
- package/temp/coverage/file-tree/httpTreeAccessors.ts.html +1228 -0
- package/temp/coverage/file-tree/index.html +35 -20
- package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +318 -159
- package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/helpers/index.html +1 -1
- package/temp/coverage/index.html +11 -11
- package/temp/coverage/lcov-report/crypto/browserHashProvider.ts.html +304 -0
- package/temp/coverage/lcov-report/crypto/index.html +116 -0
- package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +1 -1
- package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +1 -1
- package/temp/coverage/lcov-report/crypto-utils/index.html +1 -1
- package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +60 -6
- package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +410 -134
- package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +1228 -0
- package/temp/coverage/lcov-report/file-tree/index.html +35 -20
- package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +318 -159
- package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/lcov-report/helpers/index.html +1 -1
- package/temp/coverage/lcov-report/index.html +11 -11
- package/temp/coverage/lcov-report/url-utils/index.html +1 -1
- package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
- package/temp/coverage/lcov.info +1920 -1196
- package/temp/coverage/url-utils/index.html +1 -1
- package/temp/coverage/url-utils/urlParams.ts.html +1 -1
- package/temp/test/jest/haste-map-b931e4e63102f86c5bd4949f7dced44f-9d713eb41149188b4e5c0ae3d86d0a57-2ad8e16b24e391b8cdbe50b55c137169 +0 -0
- package/temp/test/jest/perf-cache-b931e4e63102f86c5bd4949f7dced44f-da39a3ee5e6b4b0d3255bfef95601890 +1 -0
- package/temp/ts-web-extras.api.json +1313 -354
- package/temp/ts-web-extras.api.md +33 -0
- package/.rush/temp/81e0881271ff236956b2f52e8ca99da6574c6e1e.tar.log +0 -223
- package/docs/index.md +0 -34
- package/docs/ts-web-extras.cryptoutils.browsercryptoprovider._constructor_.md +0 -50
- package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.decrypt.md +0 -104
- package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.derivekey.md +0 -88
- package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.encrypt.md +0 -72
- package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.frombase64.md +0 -56
- package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.generatekey.md +0 -19
- package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.generaterandombytes.md +0 -56
- package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.md +0 -169
- package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.tobase64.md +0 -56
- package/docs/ts-web-extras.cryptoutils.browserhashprovider.hashparts.md +0 -88
- package/docs/ts-web-extras.cryptoutils.browserhashprovider.hashstring.md +0 -72
- package/docs/ts-web-extras.cryptoutils.browserhashprovider.md +0 -66
- package/docs/ts-web-extras.cryptoutils.createbrowsercryptoprovider.md +0 -19
- package/docs/ts-web-extras.cryptoutils.md +0 -71
- package/docs/ts-web-extras.exportasjson.md +0 -70
- package/docs/ts-web-extras.exportusingfilesystemapi.md +0 -104
- package/docs/ts-web-extras.extractdirectorypath.md +0 -52
- package/docs/ts-web-extras.fileapitreeaccessors.create.md +0 -72
- package/docs/ts-web-extras.fileapitreeaccessors.createfromlocalstorage.md +0 -74
- package/docs/ts-web-extras.fileapitreeaccessors.createpersistent.md +0 -76
- package/docs/ts-web-extras.fileapitreeaccessors.extractfilemetadata.md +0 -54
- package/docs/ts-web-extras.fileapitreeaccessors.fromdirectoryupload.md +0 -72
- package/docs/ts-web-extras.fileapitreeaccessors.fromfilelist.md +0 -72
- package/docs/ts-web-extras.fileapitreeaccessors.getoriginalfile.md +0 -72
- package/docs/ts-web-extras.fileapitreeaccessors.md +0 -146
- package/docs/ts-web-extras.filepickeraccepttype.accept.md +0 -11
- package/docs/ts-web-extras.filepickeraccepttype.description.md +0 -11
- package/docs/ts-web-extras.filepickeraccepttype.md +0 -75
- package/docs/ts-web-extras.filesystemaccesstreeaccessors._constructor_.md +0 -114
- package/docs/ts-web-extras.filesystemaccesstreeaccessors.fileismutable.md +0 -52
- package/docs/ts-web-extras.filesystemaccesstreeaccessors.fromdirectoryhandle.md +0 -72
- package/docs/ts-web-extras.filesystemaccesstreeaccessors.getdirtypaths.md +0 -17
- package/docs/ts-web-extras.filesystemaccesstreeaccessors.isdirty.md +0 -17
- package/docs/ts-web-extras.filesystemaccesstreeaccessors.md +0 -159
- package/docs/ts-web-extras.filesystemaccesstreeaccessors.savefilecontents.md +0 -66
- package/docs/ts-web-extras.filesystemaccesstreeaccessors.synctodisk.md +0 -17
- package/docs/ts-web-extras.filesystemcreatewritableoptions_2.keepexistingdata.md +0 -11
- package/docs/ts-web-extras.filesystemcreatewritableoptions_2.md +0 -58
- package/docs/ts-web-extras.filesystemdirectoryhandle_2._symbol.asynciterator_.md +0 -15
- package/docs/ts-web-extras.filesystemdirectoryhandle_2.entries.md +0 -15
- package/docs/ts-web-extras.filesystemdirectoryhandle_2.getdirectoryhandle.md +0 -66
- package/docs/ts-web-extras.filesystemdirectoryhandle_2.getfilehandle.md +0 -66
- package/docs/ts-web-extras.filesystemdirectoryhandle_2.keys.md +0 -15
- package/docs/ts-web-extras.filesystemdirectoryhandle_2.kind.md +0 -11
- package/docs/ts-web-extras.filesystemdirectoryhandle_2.md +0 -146
- package/docs/ts-web-extras.filesystemdirectoryhandle_2.removeentry.md +0 -66
- package/docs/ts-web-extras.filesystemdirectoryhandle_2.resolve.md +0 -50
- package/docs/ts-web-extras.filesystemdirectoryhandle_2.values.md +0 -15
- package/docs/ts-web-extras.filesystemfilehandle_2.createwritable.md +0 -52
- package/docs/ts-web-extras.filesystemfilehandle_2.getfile.md +0 -15
- package/docs/ts-web-extras.filesystemfilehandle_2.kind.md +0 -11
- package/docs/ts-web-extras.filesystemfilehandle_2.md +0 -92
- package/docs/ts-web-extras.filesystemgetdirectoryoptions_2.create.md +0 -11
- package/docs/ts-web-extras.filesystemgetdirectoryoptions_2.md +0 -58
- package/docs/ts-web-extras.filesystemgetfileoptions_2.create.md +0 -11
- package/docs/ts-web-extras.filesystemgetfileoptions_2.md +0 -58
- package/docs/ts-web-extras.filesystemhandle_2.issameentry.md +0 -50
- package/docs/ts-web-extras.filesystemhandle_2.kind.md +0 -11
- package/docs/ts-web-extras.filesystemhandle_2.md +0 -119
- package/docs/ts-web-extras.filesystemhandle_2.name.md +0 -11
- package/docs/ts-web-extras.filesystemhandle_2.querypermission.md +0 -52
- package/docs/ts-web-extras.filesystemhandle_2.requestpermission.md +0 -52
- package/docs/ts-web-extras.filesystemhandlepermissiondescriptor.md +0 -58
- package/docs/ts-web-extras.filesystemhandlepermissiondescriptor.mode.md +0 -11
- package/docs/ts-web-extras.filesystemremoveoptions_2.md +0 -58
- package/docs/ts-web-extras.filesystemremoveoptions_2.recursive.md +0 -11
- package/docs/ts-web-extras.filesystemwritablefilestream_2.md +0 -57
- package/docs/ts-web-extras.filesystemwritablefilestream_2.seek.md +0 -50
- package/docs/ts-web-extras.filesystemwritablefilestream_2.truncate.md +0 -50
- package/docs/ts-web-extras.filesystemwritablefilestream_2.write.md +0 -50
- package/docs/ts-web-extras.filetreehelpers.defaultfileapitreeinitparams.md +0 -13
- package/docs/ts-web-extras.filetreehelpers.extractfilelistmetadata.md +0 -56
- package/docs/ts-web-extras.filetreehelpers.extractfilemetadata.md +0 -56
- package/docs/ts-web-extras.filetreehelpers.fromdirectoryupload.md +0 -76
- package/docs/ts-web-extras.filetreehelpers.fromfilelist.md +0 -76
- package/docs/ts-web-extras.filetreehelpers.getoriginalfile.md +0 -72
- package/docs/ts-web-extras.filetreehelpers.md +0 -102
- package/docs/ts-web-extras.idirectoryhandletreeinitializer.dirhandles.md +0 -11
- package/docs/ts-web-extras.idirectoryhandletreeinitializer.md +0 -100
- package/docs/ts-web-extras.idirectoryhandletreeinitializer.nonrecursive.md +0 -11
- package/docs/ts-web-extras.idirectoryhandletreeinitializer.prefix.md +0 -11
- package/docs/ts-web-extras.ifilehandletreeinitializer.filehandles.md +0 -11
- package/docs/ts-web-extras.ifilehandletreeinitializer.md +0 -79
- package/docs/ts-web-extras.ifilehandletreeinitializer.prefix.md +0 -11
- package/docs/ts-web-extras.ifilelisttreeinitializer.filelist.md +0 -11
- package/docs/ts-web-extras.ifilelisttreeinitializer.md +0 -58
- package/docs/ts-web-extras.ifilemetadata.lastmodified.md +0 -11
- package/docs/ts-web-extras.ifilemetadata.md +0 -124
- package/docs/ts-web-extras.ifilemetadata.name.md +0 -11
- package/docs/ts-web-extras.ifilemetadata.path.md +0 -11
- package/docs/ts-web-extras.ifilemetadata.size.md +0 -11
- package/docs/ts-web-extras.ifilemetadata.type.md +0 -11
- package/docs/ts-web-extras.ifilesystemaccesstreeparams.autosync.md +0 -13
- package/docs/ts-web-extras.ifilesystemaccesstreeparams.md +0 -78
- package/docs/ts-web-extras.ifilesystemaccesstreeparams.requirewritepermission.md +0 -13
- package/docs/ts-web-extras.ifsaccessapis.md +0 -56
- package/docs/ts-web-extras.ifsaccessapis.showdirectorypicker.md +0 -52
- package/docs/ts-web-extras.ifsaccessapis.showopenfilepicker.md +0 -52
- package/docs/ts-web-extras.ifsaccessapis.showsavefilepicker.md +0 -52
- package/docs/ts-web-extras.ilocalstoragetreeparams.autosync.md +0 -13
- package/docs/ts-web-extras.ilocalstoragetreeparams.md +0 -97
- package/docs/ts-web-extras.ilocalstoragetreeparams.pathtokeymap.md +0 -13
- package/docs/ts-web-extras.ilocalstoragetreeparams.storage.md +0 -13
- package/docs/ts-web-extras.isdirectoryhandle.md +0 -56
- package/docs/ts-web-extras.isfilehandle.md +0 -56
- package/docs/ts-web-extras.isfilepath.md +0 -52
- package/docs/ts-web-extras.iurlconfigoptions.config.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.configstartdir.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.contextfilter.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.input.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.inputstartdir.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.interactive.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.loadzip.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.maxdistance.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.md +0 -286
- package/docs/ts-web-extras.iurlconfigoptions.qualifierdefaults.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.reducequalifiers.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.resourcetypes.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.zipfile.md +0 -13
- package/docs/ts-web-extras.iurlconfigoptions.zippath.md +0 -13
- package/docs/ts-web-extras.localstoragetreeaccessors.fileismutable.md +0 -56
- package/docs/ts-web-extras.localstoragetreeaccessors.fromstorage.md +0 -56
- package/docs/ts-web-extras.localstoragetreeaccessors.getdirtypaths.md +0 -19
- package/docs/ts-web-extras.localstoragetreeaccessors.isdirty.md +0 -19
- package/docs/ts-web-extras.localstoragetreeaccessors.md +0 -131
- package/docs/ts-web-extras.localstoragetreeaccessors.savefilecontents.md +0 -72
- package/docs/ts-web-extras.localstoragetreeaccessors.synctodisk.md +0 -19
- package/docs/ts-web-extras.md +0 -558
- package/docs/ts-web-extras.parsecontextfilter.md +0 -52
- package/docs/ts-web-extras.parsequalifierdefaults.md +0 -52
- package/docs/ts-web-extras.parseresourcetypes.md +0 -52
- package/docs/ts-web-extras.parseurlparameters.md +0 -17
- package/docs/ts-web-extras.safeshowdirectorypicker.md +0 -72
- package/docs/ts-web-extras.safeshowopenfilepicker.md +0 -72
- package/docs/ts-web-extras.safeshowsavefilepicker.md +0 -72
- package/docs/ts-web-extras.showdirectorypickeroptions.id.md +0 -11
- package/docs/ts-web-extras.showdirectorypickeroptions.md +0 -96
- package/docs/ts-web-extras.showdirectorypickeroptions.mode.md +0 -11
- package/docs/ts-web-extras.showdirectorypickeroptions.startin.md +0 -11
- package/docs/ts-web-extras.showopenfilepickeroptions.excludeacceptalloption.md +0 -11
- package/docs/ts-web-extras.showopenfilepickeroptions.id.md +0 -11
- package/docs/ts-web-extras.showopenfilepickeroptions.md +0 -134
- package/docs/ts-web-extras.showopenfilepickeroptions.multiple.md +0 -11
- package/docs/ts-web-extras.showopenfilepickeroptions.startin.md +0 -11
- package/docs/ts-web-extras.showopenfilepickeroptions.types.md +0 -11
- package/docs/ts-web-extras.showsavefilepickeroptions.excludeacceptalloption.md +0 -11
- package/docs/ts-web-extras.showsavefilepickeroptions.id.md +0 -11
- package/docs/ts-web-extras.showsavefilepickeroptions.md +0 -134
- package/docs/ts-web-extras.showsavefilepickeroptions.startin.md +0 -11
- package/docs/ts-web-extras.showsavefilepickeroptions.suggestedname.md +0 -11
- package/docs/ts-web-extras.showsavefilepickeroptions.types.md +0 -11
- package/docs/ts-web-extras.supportsfilesystemaccess.md +0 -56
- package/docs/ts-web-extras.treeinitializer.md +0 -15
- package/docs/ts-web-extras.wellknowndirectory.md +0 -13
- package/docs/ts-web-extras.windowwithfsaccess.md +0 -15
- package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
- package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +0 -1
- /package/temp/test/jest/{jest-transform-cache-7492f1b44480e0cdd1f220078fb3afd8-79ef2876fae7ca75eedb2aa53dc48338/8d/package_8dcbedef69e4299f0f51fcda8f4f1c8e → jest-transform-cache-b931e4e63102f86c5bd4949f7dced44f-79ef2876fae7ca75eedb2aa53dc48338/b5/package_b5f57afc9ec2c011239b1608ee5bdfa5} +0 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* Copyright (c) 2026 Erik Fortune
|
|
4
|
+
*
|
|
5
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
* in the Software without restriction, including without limitation the rights
|
|
8
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
* furnished to do so, subject to the following conditions:
|
|
11
|
+
*
|
|
12
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
* copies or substantial portions of the Software.
|
|
14
|
+
*
|
|
15
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
* SOFTWARE.
|
|
22
|
+
*/
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.HttpTreeAccessors = void 0;
|
|
25
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
26
|
+
const ts_json_base_1 = require("@fgv/ts-json-base");
|
|
27
|
+
function normalizeFetch(fetchImpl) {
|
|
28
|
+
const resolved = fetchImpl !== null && fetchImpl !== void 0 ? fetchImpl : globalThis.fetch;
|
|
29
|
+
return resolved.bind(globalThis);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* HTTP-backed file tree accessors that cache data in memory and persist via REST API.
|
|
33
|
+
* @public
|
|
34
|
+
*/
|
|
35
|
+
class HttpTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAccessors {
|
|
36
|
+
constructor(files, params) {
|
|
37
|
+
var _a, _b;
|
|
38
|
+
super(files, params);
|
|
39
|
+
this._dirtyFiles = new Set();
|
|
40
|
+
this._pendingDeletions = new Set();
|
|
41
|
+
this._baseUrl = params.baseUrl.replace(/\/$/, '');
|
|
42
|
+
this._namespace = params.namespace;
|
|
43
|
+
this._fetchImpl = normalizeFetch(params.fetchImpl);
|
|
44
|
+
this._autoSync = (_a = params.autoSync) !== null && _a !== void 0 ? _a : false;
|
|
45
|
+
this._userId = params.userId;
|
|
46
|
+
this._logger = (_b = params.logger) !== null && _b !== void 0 ? _b : new ts_utils_1.Logging.LogReporter();
|
|
47
|
+
}
|
|
48
|
+
async _runAutoSyncTask(path) {
|
|
49
|
+
try {
|
|
50
|
+
const result = await this.syncToDisk();
|
|
51
|
+
if (result.isFailure()) {
|
|
52
|
+
this._logger.error(`Auto-sync failed for ${path}: ${result.message}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
this._logger.error(`Auto-sync threw for ${path}: ${String(err)}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Creates a new HttpTreeAccessors instance from an HTTP backend.
|
|
61
|
+
* @param params - Configuration parameters for the HTTP tree accessors.
|
|
62
|
+
* @returns A promise that resolves to a result containing the new HttpTreeAccessors instance or an error message.
|
|
63
|
+
*/
|
|
64
|
+
static async fromHttp(params) {
|
|
65
|
+
const filesResult = await this._loadFiles(params, '/');
|
|
66
|
+
if (filesResult.isFailure()) {
|
|
67
|
+
return (0, ts_utils_1.fail)(filesResult.message);
|
|
68
|
+
}
|
|
69
|
+
return (0, ts_utils_1.succeed)(new HttpTreeAccessors(filesResult.value, params));
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Synchronizes all dirty files to the HTTP backend.
|
|
73
|
+
* @returns A promise that resolves to a result indicating success or failure.
|
|
74
|
+
*/
|
|
75
|
+
async syncToDisk() {
|
|
76
|
+
if (this._dirtyFiles.size === 0 && this._pendingDeletions.size === 0) {
|
|
77
|
+
return (0, ts_utils_1.succeed)(undefined);
|
|
78
|
+
}
|
|
79
|
+
for (const path of this._pendingDeletions) {
|
|
80
|
+
const query = new URLSearchParams();
|
|
81
|
+
query.set('path', path);
|
|
82
|
+
if (this._namespace) {
|
|
83
|
+
query.set('namespace', this._namespace);
|
|
84
|
+
}
|
|
85
|
+
const deleteResult = await this._request(`/file?${query.toString()}`, {
|
|
86
|
+
method: 'DELETE'
|
|
87
|
+
});
|
|
88
|
+
if (deleteResult.isFailure()) {
|
|
89
|
+
return (0, ts_utils_1.fail)(`delete ${path}: ${deleteResult.message}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const path of this._dirtyFiles) {
|
|
93
|
+
const contentsResult = this.getFileContents(path);
|
|
94
|
+
if (contentsResult.isFailure()) {
|
|
95
|
+
return (0, ts_utils_1.fail)(`${path}: ${contentsResult.message}`);
|
|
96
|
+
}
|
|
97
|
+
const body = {
|
|
98
|
+
path,
|
|
99
|
+
contents: contentsResult.value
|
|
100
|
+
};
|
|
101
|
+
if (this._namespace) {
|
|
102
|
+
body.namespace = this._namespace;
|
|
103
|
+
}
|
|
104
|
+
const saveResult = await this._request('/file', {
|
|
105
|
+
method: 'PUT',
|
|
106
|
+
body: JSON.stringify(body)
|
|
107
|
+
});
|
|
108
|
+
if (saveResult.isFailure()) {
|
|
109
|
+
return (0, ts_utils_1.fail)(`sync ${path}: ${saveResult.message}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
this._pendingDeletions.clear();
|
|
113
|
+
this._dirtyFiles.clear();
|
|
114
|
+
const syncBody = {};
|
|
115
|
+
if (this._namespace) {
|
|
116
|
+
syncBody.namespace = this._namespace;
|
|
117
|
+
}
|
|
118
|
+
const syncResult = await this._request('/sync', {
|
|
119
|
+
method: 'POST',
|
|
120
|
+
body: JSON.stringify(syncBody)
|
|
121
|
+
});
|
|
122
|
+
return syncResult.isFailure() ? (0, ts_utils_1.fail)(syncResult.message) : (0, ts_utils_1.succeed)(undefined);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Checks if there are any dirty files that need synchronization.
|
|
126
|
+
* @returns True if there are dirty files, false otherwise.
|
|
127
|
+
*/
|
|
128
|
+
isDirty() {
|
|
129
|
+
return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Gets the list of paths for all dirty files.
|
|
133
|
+
* @returns An array of file paths that have been modified but not yet synchronized.
|
|
134
|
+
*/
|
|
135
|
+
getDirtyPaths() {
|
|
136
|
+
return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];
|
|
137
|
+
}
|
|
138
|
+
deleteFile(path) {
|
|
139
|
+
const result = super.deleteFile(path);
|
|
140
|
+
if (result.isFailure()) {
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
this._dirtyFiles.delete(path);
|
|
144
|
+
this._pendingDeletions.add(path);
|
|
145
|
+
if (!this._autoSync) {
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
void this._runAutoSyncTask(path);
|
|
149
|
+
return result;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Saves file contents and marks the file as dirty for synchronization.
|
|
153
|
+
* @param path - The path to the file.
|
|
154
|
+
* @param contents - The new contents of the file.
|
|
155
|
+
* @returns A result indicating success or failure.
|
|
156
|
+
*/
|
|
157
|
+
saveFileContents(path, contents) {
|
|
158
|
+
const result = super.saveFileContents(path, contents);
|
|
159
|
+
if (result.isFailure()) {
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
this._dirtyFiles.add(path);
|
|
163
|
+
if (!this._autoSync) {
|
|
164
|
+
return result;
|
|
165
|
+
}
|
|
166
|
+
// fire-and-log-on-failure automatic sync for immediate persistence workflow
|
|
167
|
+
void this._runAutoSyncTask(path);
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Checks if a file is mutable (can be modified).
|
|
172
|
+
* @param path - The path to the file.
|
|
173
|
+
* @returns A detailed result indicating if the file is mutable and the reason.
|
|
174
|
+
*/
|
|
175
|
+
fileIsMutable(path) {
|
|
176
|
+
const result = super.fileIsMutable(path);
|
|
177
|
+
if (result.isSuccess() && result.value === true) {
|
|
178
|
+
return (0, ts_utils_1.succeedWithDetail)(true, 'persistent');
|
|
179
|
+
}
|
|
180
|
+
return result;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Makes an HTTP request to the specified resource path.
|
|
184
|
+
* @param resourcePath - The path to the resource.
|
|
185
|
+
* @param init - Optional request initialization options.
|
|
186
|
+
* @returns A promise that resolves to a result containing the response data or an error message.
|
|
187
|
+
*/
|
|
188
|
+
async _request(resourcePath, init) {
|
|
189
|
+
var _a;
|
|
190
|
+
const response = await this._fetchImpl(`${this._baseUrl}${resourcePath}`, Object.assign({ headers: Object.assign(Object.assign({ 'Content-Type': 'application/json' }, (this._userId ? { 'X-User-Id': this._userId } : {})), ((_a = init === null || init === void 0 ? void 0 : init.headers) !== null && _a !== void 0 ? _a : {})) }, init)).catch((err) => ({ err }));
|
|
191
|
+
if ('err' in response) {
|
|
192
|
+
const message = response.err instanceof Error ? response.err.message : String(response.err);
|
|
193
|
+
return (0, ts_utils_1.fail)(message);
|
|
194
|
+
}
|
|
195
|
+
if (!response.ok) {
|
|
196
|
+
const message = await response.text().catch(() => `HTTP ${response.status}`);
|
|
197
|
+
return (0, ts_utils_1.fail)(message);
|
|
198
|
+
}
|
|
199
|
+
const json = await response.json().catch(() => undefined);
|
|
200
|
+
if (json === undefined) {
|
|
201
|
+
return (0, ts_utils_1.fail)('invalid JSON response');
|
|
202
|
+
}
|
|
203
|
+
return (0, ts_utils_1.succeed)(json);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Loads files from the HTTP backend for the specified directory path.
|
|
207
|
+
* @param params - Configuration parameters for the HTTP tree accessors.
|
|
208
|
+
* @param directoryPath - The path to the directory to load files from.
|
|
209
|
+
* @returns A promise that resolves to a result containing the loaded files or an error message.
|
|
210
|
+
*/
|
|
211
|
+
static async _loadFiles(params, directoryPath) {
|
|
212
|
+
var _a;
|
|
213
|
+
const childrenResult = await this._requestWithParams(params, '/tree/children', {
|
|
214
|
+
path: directoryPath,
|
|
215
|
+
namespace: params.namespace
|
|
216
|
+
});
|
|
217
|
+
if (childrenResult.isFailure()) {
|
|
218
|
+
return (0, ts_utils_1.fail)(childrenResult.message);
|
|
219
|
+
}
|
|
220
|
+
const allFiles = [];
|
|
221
|
+
for (const item of childrenResult.value.children) {
|
|
222
|
+
if (item.type === 'directory') {
|
|
223
|
+
const nestedResult = await this._loadFiles(params, item.path);
|
|
224
|
+
if (nestedResult.isFailure()) {
|
|
225
|
+
return (0, ts_utils_1.fail)(nestedResult.message);
|
|
226
|
+
}
|
|
227
|
+
allFiles.push(...nestedResult.value);
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
const fileResult = await this._requestWithParams(params, '/file', {
|
|
231
|
+
path: item.path,
|
|
232
|
+
namespace: params.namespace
|
|
233
|
+
});
|
|
234
|
+
if (fileResult.isFailure()) {
|
|
235
|
+
return (0, ts_utils_1.fail)(fileResult.message);
|
|
236
|
+
}
|
|
237
|
+
const contentType = (_a = params.inferContentType) === null || _a === void 0 ? void 0 : _a.call(params, item.path, fileResult.value.contentType).orDefault();
|
|
238
|
+
allFiles.push({
|
|
239
|
+
path: item.path,
|
|
240
|
+
contents: fileResult.value.contents,
|
|
241
|
+
contentType
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return (0, ts_utils_1.succeed)(allFiles);
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Makes an HTTP request with query parameters to the specified resource path.
|
|
249
|
+
* @param params - Configuration parameters for the HTTP tree accessors.
|
|
250
|
+
* @param resourcePath - The path to the resource.
|
|
251
|
+
* @param query - Query parameters to include in the request.
|
|
252
|
+
* @returns A promise that resolves to a result containing the response data or an error message.
|
|
253
|
+
*/
|
|
254
|
+
static async _requestWithParams(params, resourcePath, query) {
|
|
255
|
+
const search = new URLSearchParams();
|
|
256
|
+
for (const [key, value] of Object.entries(query)) {
|
|
257
|
+
if (value !== undefined) {
|
|
258
|
+
search.set(key, value);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const fetchImpl = normalizeFetch(params.fetchImpl);
|
|
262
|
+
/* c8 ignore next 3 - userId header in static _requestWithParams; covered by userId tests via fromHttp */
|
|
263
|
+
const userIdHeaders = params.userId
|
|
264
|
+
? { headers: { 'X-User-Id': params.userId } }
|
|
265
|
+
: undefined;
|
|
266
|
+
const response = await fetchImpl(`${params.baseUrl.replace(/\/$/, '')}${resourcePath}?${search.toString()}`, userIdHeaders).catch((err) => ({ err }));
|
|
267
|
+
if ('err' in response) {
|
|
268
|
+
const message = response.err instanceof Error ? response.err.message : String(response.err);
|
|
269
|
+
return (0, ts_utils_1.fail)(message);
|
|
270
|
+
}
|
|
271
|
+
if (!response.ok) {
|
|
272
|
+
const message = await response.text().catch(() => `HTTP ${response.status}`);
|
|
273
|
+
return (0, ts_utils_1.fail)(message);
|
|
274
|
+
}
|
|
275
|
+
const json = await response.json().catch(() => undefined);
|
|
276
|
+
if (json === undefined) {
|
|
277
|
+
return (0, ts_utils_1.fail)('invalid JSON response');
|
|
278
|
+
}
|
|
279
|
+
return (0, ts_utils_1.succeed)(json);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
exports.HttpTreeAccessors = HttpTreeAccessors;
|
|
283
|
+
//# sourceMappingURL=httpTreeAccessors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"httpTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/httpTreeAccessors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAuG;AACvG,oDAA6C;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,MAAa,iBACX,SAAQ,uBAAQ,CAAC,qBAA0B;IAY3C,YAAoB,KAAoC,EAAE,MAA4B;;QACpF,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;Q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C9B,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,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,IAAA,eAAI,EAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;YAC7E,OAAO,IAAA,eAAI,EAAC,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,IAAA,eAAI,EAAC,uBAAuB,CAAC,CAAC;QACvC,CAAC;QAED,OAAO,IAAA,kBAAO,EAAC,IAAS,CAAC,CAAC;IAC5B,CAAC;CACF;AAxTD,8CAwTC","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 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 * @returns A promise that resolves to a result indicating success or failure.\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._dirtyFiles.size === 0 && this._pendingDeletions.size === 0) {\n return succeed(undefined);\n }\n\n for (const path of this._pendingDeletions) {\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._request<{ deleted: boolean }>(`/file?${query.toString()}`, {\n method: 'DELETE'\n });\n if (deleteResult.isFailure()) {\n return fail(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of this._dirtyFiles) {\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\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._request<IHttpStorageFileResponse>('/file', {\n method: 'PUT',\n body: JSON.stringify(body)\n });\n if (saveResult.isFailure()) {\n return fail(`sync ${path}: ${saveResult.message}`);\n }\n }\n\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n\n const syncBody: Record<string, unknown> = {};\n if (this._namespace) {\n syncBody.namespace = this._namespace;\n }\n\n const syncResult = await this._request<IHttpStorageSyncResponse>('/sync', {\n method: 'POST',\n body: JSON.stringify(syncBody)\n });\n\n return syncResult.isFailure() ? fail(syncResult.message) : succeed(undefined);\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 message = await response.text().catch(() => `HTTP ${response.status}`);\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 * 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 /* c8 ignore next 3 - userId header in static _requestWithParams; covered by userId tests via fromHttp */\n const userIdHeaders: RequestInit | undefined = 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 message = await response.text().catch(() => `HTTP ${response.status}`);\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":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/file-tree/index.ts"],"names":[],"mappings":"AAsBA;;;GAGG;AAEH,cAAc,wBAAwB,CAAC;AACvC,cAAc,wBAAwB,CAAC;AACvC,cAAc,iCAAiC,CAAC;AAChD,cAAc,6BAA6B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/file-tree/index.ts"],"names":[],"mappings":"AAsBA;;;GAGG;AAEH,cAAc,wBAAwB,CAAC;AACvC,cAAc,wBAAwB,CAAC;AACvC,cAAc,iCAAiC,CAAC;AAChD,cAAc,qBAAqB,CAAC;AACpC,cAAc,6BAA6B,CAAC"}
|
|
@@ -42,5 +42,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
42
42
|
__exportStar(require("./directoryHandleStore"), exports);
|
|
43
43
|
__exportStar(require("./fileApiTreeAccessors"), exports);
|
|
44
44
|
__exportStar(require("./fileSystemAccessTreeAccessors"), exports);
|
|
45
|
+
__exportStar(require("./httpTreeAccessors"), exports);
|
|
45
46
|
__exportStar(require("./localStorageTreeAccessors"), exports);
|
|
46
47
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;AAEH;;;GAGG;AAEH,yDAAuC;AACvC,yDAAuC;AACvC,kEAAgD;AAChD,8DAA4C","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\n/**\n * Browser-compatible FileTree implementations using the File API.\n * @packageDocumentation\n */\n\nexport * from './directoryHandleStore';\nexport * from './fileApiTreeAccessors';\nexport * from './fileSystemAccessTreeAccessors';\nexport * from './localStorageTreeAccessors';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;AAEH;;;GAGG;AAEH,yDAAuC;AACvC,yDAAuC;AACvC,kEAAgD;AAChD,sDAAoC;AACpC,8DAA4C","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\n/**\n * Browser-compatible FileTree implementations using the File API.\n * @packageDocumentation\n */\n\nexport * from './directoryHandleStore';\nexport * from './fileApiTreeAccessors';\nexport * from './fileSystemAccessTreeAccessors';\nexport * from './httpTreeAccessors';\nexport * from './localStorageTreeAccessors';\n"]}
|
|
@@ -87,6 +87,11 @@ export declare class LocalStorageTreeAccessors<TCT extends string = string> exte
|
|
|
87
87
|
* @internal
|
|
88
88
|
*/
|
|
89
89
|
private _getCollectionIdFromPath;
|
|
90
|
+
/**
|
|
91
|
+
* Remove a file's entry from its localStorage key.
|
|
92
|
+
* @internal
|
|
93
|
+
*/
|
|
94
|
+
private _deleteFileFromStorage;
|
|
90
95
|
/**
|
|
91
96
|
* Sync a single dirty file to localStorage.
|
|
92
97
|
* @internal
|
|
@@ -110,6 +115,13 @@ export declare class LocalStorageTreeAccessors<TCT extends string = string> exte
|
|
|
110
115
|
* @public
|
|
111
116
|
*/
|
|
112
117
|
getDirtyPaths(): string[];
|
|
118
|
+
/**
|
|
119
|
+
* Delete a file and remove it from localStorage.
|
|
120
|
+
* @param path - File path to delete
|
|
121
|
+
* @returns Result with true if deleted, or error
|
|
122
|
+
* @public
|
|
123
|
+
*/
|
|
124
|
+
deleteFile(path: string): Result<boolean>;
|
|
113
125
|
/**
|
|
114
126
|
* Save file contents. Marks file as dirty and optionally auto-syncs.
|
|
115
127
|
* @param path - File path
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localStorageTreeAccessors.d.ts","sourceRoot":"","sources":["../../../src/packlets/file-tree/localStorageTreeAccessors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OAAO,IAAI,OAAO;IAIzB;;;;OAIG;IACI,aAAa,IAAI,MAAM,EAAE;IAIhC;;;;;OAKG;IACI,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC;IAShD;;;;;;OAMG;IACI,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;IAgBvE;;;;;OAKG;IACI,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,UAAU,CAAC;CAOjF"}
|
|
@@ -51,6 +51,7 @@ class LocalStorageTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAcce
|
|
|
51
51
|
this._pathToKeyMap = pathToKeyMap;
|
|
52
52
|
this._keyToPathMap = new Map(Array.from(pathToKeyMap.entries()).map(([k, v]) => [v, k]));
|
|
53
53
|
this._dirtyFiles = new Set();
|
|
54
|
+
/* c8 ignore next 1 - intermittent branch coverage: ?? false branch when params is undefined */
|
|
54
55
|
this._autoSync = (_a = params === null || params === void 0 ? void 0 : params.autoSync) !== null && _a !== void 0 ? _a : false;
|
|
55
56
|
}
|
|
56
57
|
/**
|
|
@@ -64,6 +65,7 @@ class LocalStorageTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAcce
|
|
|
64
65
|
static fromStorage(params) {
|
|
65
66
|
var _a;
|
|
66
67
|
try {
|
|
68
|
+
/* c8 ignore next 1 - intermittent branch coverage: window.localStorage branch when params.storage is undefined */
|
|
67
69
|
const storage = (_a = params.storage) !== null && _a !== void 0 ? _a : (typeof window !== 'undefined' ? window.localStorage : undefined);
|
|
68
70
|
if (!storage) {
|
|
69
71
|
return (0, ts_utils_1.fail)('localStorage is not available');
|
|
@@ -112,6 +114,7 @@ class LocalStorageTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAcce
|
|
|
112
114
|
continue;
|
|
113
115
|
}
|
|
114
116
|
const filePath = this._joinPath(dataPath, `${collectionId}${extension}`);
|
|
117
|
+
/* c8 ignore next 3 - intermittent branch coverage: ternary branches in tight loop */
|
|
115
118
|
const contentType = (params === null || params === void 0 ? void 0 : params.inferContentType)
|
|
116
119
|
? params.inferContentType(filePath, undefined).orDefault()
|
|
117
120
|
: undefined;
|
|
@@ -142,6 +145,7 @@ class LocalStorageTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAcce
|
|
|
142
145
|
* @internal
|
|
143
146
|
*/
|
|
144
147
|
static _joinPath(base, name) {
|
|
148
|
+
/* c8 ignore next 2 - intermittent branch coverage: slash-trimming edge cases */
|
|
145
149
|
const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;
|
|
146
150
|
const cleanName = name.startsWith('/') ? name.slice(1) : name;
|
|
147
151
|
return `${cleanBase}/${cleanName}`;
|
|
@@ -155,6 +159,7 @@ class LocalStorageTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAcce
|
|
|
155
159
|
let bestMatch;
|
|
156
160
|
for (const [prefix, key] of this._pathToKeyMap.entries()) {
|
|
157
161
|
if (path.startsWith(prefix)) {
|
|
162
|
+
/* c8 ignore next 1 - intermittent: overlapping-prefix branch requires two matching prefixes in iteration order */
|
|
158
163
|
if (!bestMatch || prefix.length > bestMatch.prefix.length) {
|
|
159
164
|
bestMatch = { prefix, key };
|
|
160
165
|
}
|
|
@@ -187,11 +192,43 @@ class LocalStorageTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAcce
|
|
|
187
192
|
return path;
|
|
188
193
|
}
|
|
189
194
|
const relativePath = path.slice(dataPath.length);
|
|
195
|
+
/* c8 ignore next 1 - defensive: relativePath always starts with / when paths are absolute */
|
|
190
196
|
const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath;
|
|
191
197
|
// Remove any file extension
|
|
192
198
|
const dotIndex = cleanPath.lastIndexOf('.');
|
|
193
199
|
return dotIndex > 0 ? cleanPath.slice(0, dotIndex) : cleanPath;
|
|
194
200
|
}
|
|
201
|
+
/**
|
|
202
|
+
* Remove a file's entry from its localStorage key.
|
|
203
|
+
* @internal
|
|
204
|
+
*/
|
|
205
|
+
_deleteFileFromStorage(path) {
|
|
206
|
+
const storageKey = this._getStorageKeyForPath(path);
|
|
207
|
+
if (!storageKey) {
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
const collectionId = this._getCollectionIdFromPath(path);
|
|
211
|
+
const existingJson = this._storage.getItem(storageKey);
|
|
212
|
+
if (!existingJson) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
const parsed = JSON.parse(existingJson);
|
|
217
|
+
if ((0, ts_json_base_2.isJsonObject)(parsed)) {
|
|
218
|
+
const existing = parsed;
|
|
219
|
+
delete existing[collectionId];
|
|
220
|
+
if (Object.keys(existing).length > 0) {
|
|
221
|
+
this._storage.setItem(storageKey, JSON.stringify(existing));
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
this._storage.removeItem(storageKey);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
catch (_a) {
|
|
229
|
+
// Storage is corrupted — nothing to clean up
|
|
230
|
+
}
|
|
231
|
+
}
|
|
195
232
|
/**
|
|
196
233
|
* Sync a single dirty file to localStorage.
|
|
197
234
|
* @internal
|
|
@@ -271,6 +308,20 @@ class LocalStorageTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAcce
|
|
|
271
308
|
getDirtyPaths() {
|
|
272
309
|
return Array.from(this._dirtyFiles);
|
|
273
310
|
}
|
|
311
|
+
/**
|
|
312
|
+
* Delete a file and remove it from localStorage.
|
|
313
|
+
* @param path - File path to delete
|
|
314
|
+
* @returns Result with true if deleted, or error
|
|
315
|
+
* @public
|
|
316
|
+
*/
|
|
317
|
+
deleteFile(path) {
|
|
318
|
+
const result = super.deleteFile(path);
|
|
319
|
+
if (result.isSuccess()) {
|
|
320
|
+
this._dirtyFiles.delete(path);
|
|
321
|
+
this._deleteFileFromStorage(path);
|
|
322
|
+
}
|
|
323
|
+
return result;
|
|
324
|
+
}
|
|
274
325
|
/**
|
|
275
326
|
* Save file contents. Marks file as dirty and optionally auto-syncs.
|
|
276
327
|
* @param path - File path
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localStorageTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/localStorageTreeAccessors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAyF;AACzF,oDAA6C;AAC7C,oDAAkE;AA4BlE;;;;;;;;;;;;;GAaG;AACH,MAAa,yBACX,SAAQ,uBAAQ,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,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACzF,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QAC7B,IAAI,CAAC,SAAS,GAAG,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,mCAAI,KAAK,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACI,MAAM,CAAC,WAAW,CACvB,MAAoC;;QAEpC,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAA,MAAM,CAAC,OAAO,mCAAI,CAAC,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,C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eAAI,EAAC,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,IAAA,4BAAiB,EAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;CACF;AAtTD,8DAsTC","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 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 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 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 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 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 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 * 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 * 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,4CAAyF;AACzF,oDAA6C;AAC7C,oDAAkE;AA4BlE;;;;;;;;;;;;;GAaG;AACH,MAAa,yBACX,SAAQ,uBAAQ,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,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACzF,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QAC7B,+FAA+F;QAC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M,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,IAAA,eAAI,EAAC,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,IAAA,4BAAiB,EAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;CACF;AA3WD,8DA2WC","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"]}
|