@fgv/ts-web-extras 5.0.2 → 5.1.0-0

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.
Files changed (208) hide show
  1. package/.rush/temp/81e0881271ff236956b2f52e8ca99da6574c6e1e.tar.log +223 -0
  2. package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +35 -25
  3. package/.rush/temp/operation/build/all.log +35 -25
  4. package/.rush/temp/operation/build/log-chunks.jsonl +35 -25
  5. package/.rush/temp/operation/build/state.json +1 -1
  6. package/.rush/temp/shrinkwrap-deps.json +175 -163
  7. package/config/jest.config.json +4 -1
  8. package/config/typedoc.json +6 -0
  9. package/dist/index.js +2 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/packlets/crypto-utils/browserCryptoProvider.js +254 -0
  12. package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -0
  13. package/dist/packlets/crypto-utils/browserHashProvider.js.map +1 -0
  14. package/dist/packlets/{crypto → crypto-utils}/index.js +1 -0
  15. package/dist/packlets/crypto-utils/index.js.map +1 -0
  16. package/dist/packlets/file-api-types/index.js +27 -3
  17. package/dist/packlets/file-api-types/index.js.map +1 -1
  18. package/dist/packlets/file-tree/directoryHandleStore.js +124 -0
  19. package/dist/packlets/file-tree/directoryHandleStore.js.map +1 -0
  20. package/dist/packlets/file-tree/fileApiTreeAccessors.js +76 -0
  21. package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  22. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js +345 -0
  23. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -0
  24. package/dist/packlets/file-tree/index.js +3 -0
  25. package/dist/packlets/file-tree/index.js.map +1 -1
  26. package/dist/packlets/file-tree/localStorageTreeAccessors.js +308 -0
  27. package/dist/packlets/file-tree/localStorageTreeAccessors.js.map +1 -0
  28. package/dist/test/mocks/idb-keyval.js +6 -0
  29. package/dist/test/mocks/idb-keyval.js.map +1 -0
  30. package/dist/test/unit/browserHashProvider.test.js +1 -1
  31. package/dist/test/unit/browserHashProvider.test.js.map +1 -1
  32. package/dist/test/unit/directoryHandleStore.test.js +190 -0
  33. package/dist/test/unit/directoryHandleStore.test.js.map +1 -0
  34. package/dist/test/unit/fileApiTypes.test.js +30 -0
  35. package/dist/test/unit/fileApiTypes.test.js.map +1 -1
  36. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js +517 -0
  37. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -0
  38. package/dist/test/unit/localStorageTreeAccessors.test.js +595 -0
  39. package/dist/test/unit/localStorageTreeAccessors.test.js.map +1 -0
  40. package/dist/test/utils/fileSystemAccessMocks.js +271 -0
  41. package/dist/test/utils/fileSystemAccessMocks.js.map +1 -0
  42. package/dist/ts-web-extras.d.ts +460 -1
  43. package/dist/tsdoc-metadata.json +1 -1
  44. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider._constructor_.md +50 -0
  45. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.decrypt.md +104 -0
  46. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.derivekey.md +88 -0
  47. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.encrypt.md +72 -0
  48. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.frombase64.md +56 -0
  49. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.generatekey.md +19 -0
  50. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.generaterandombytes.md +56 -0
  51. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.md +169 -0
  52. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.tobase64.md +56 -0
  53. package/docs/{ts-web-extras.browserhashprovider.hashparts.md → ts-web-extras.cryptoutils.browserhashprovider.hashparts.md} +2 -2
  54. package/docs/{ts-web-extras.browserhashprovider.hashstring.md → ts-web-extras.cryptoutils.browserhashprovider.hashstring.md} +2 -2
  55. package/docs/{ts-web-extras.browserhashprovider.md → ts-web-extras.cryptoutils.browserhashprovider.md} +4 -4
  56. package/docs/ts-web-extras.cryptoutils.createbrowsercryptoprovider.md +19 -0
  57. package/docs/ts-web-extras.cryptoutils.md +71 -0
  58. package/docs/ts-web-extras.fileapitreeaccessors.createfromlocalstorage.md +74 -0
  59. package/docs/ts-web-extras.fileapitreeaccessors.createpersistent.md +76 -0
  60. package/docs/ts-web-extras.fileapitreeaccessors.md +32 -0
  61. package/docs/ts-web-extras.filesystemaccesstreeaccessors._constructor_.md +114 -0
  62. package/docs/ts-web-extras.filesystemaccesstreeaccessors.fileismutable.md +52 -0
  63. package/docs/ts-web-extras.filesystemaccesstreeaccessors.fromdirectoryhandle.md +72 -0
  64. package/docs/ts-web-extras.filesystemaccesstreeaccessors.getdirtypaths.md +17 -0
  65. package/docs/ts-web-extras.filesystemaccesstreeaccessors.isdirty.md +17 -0
  66. package/docs/ts-web-extras.filesystemaccesstreeaccessors.md +159 -0
  67. package/docs/ts-web-extras.filesystemaccesstreeaccessors.savefilecontents.md +66 -0
  68. package/docs/ts-web-extras.filesystemaccesstreeaccessors.synctodisk.md +17 -0
  69. package/docs/ts-web-extras.ifilesystemaccesstreeparams.autosync.md +13 -0
  70. package/docs/ts-web-extras.ifilesystemaccesstreeparams.md +78 -0
  71. package/docs/ts-web-extras.ifilesystemaccesstreeparams.requirewritepermission.md +13 -0
  72. package/docs/ts-web-extras.ilocalstoragetreeparams.autosync.md +13 -0
  73. package/docs/ts-web-extras.ilocalstoragetreeparams.md +97 -0
  74. package/docs/ts-web-extras.ilocalstoragetreeparams.pathtokeymap.md +13 -0
  75. package/docs/ts-web-extras.ilocalstoragetreeparams.storage.md +13 -0
  76. package/docs/ts-web-extras.localstoragetreeaccessors.fileismutable.md +56 -0
  77. package/docs/ts-web-extras.localstoragetreeaccessors.fromstorage.md +56 -0
  78. package/docs/ts-web-extras.localstoragetreeaccessors.getdirtypaths.md +19 -0
  79. package/docs/ts-web-extras.localstoragetreeaccessors.isdirty.md +19 -0
  80. package/docs/ts-web-extras.localstoragetreeaccessors.md +131 -0
  81. package/docs/ts-web-extras.localstoragetreeaccessors.savefilecontents.md +72 -0
  82. package/docs/ts-web-extras.localstoragetreeaccessors.synctodisk.md +19 -0
  83. package/docs/ts-web-extras.md +50 -4
  84. package/etc/ts-web-extras.api.md +91 -1
  85. package/lib/index.d.ts +2 -1
  86. package/lib/index.d.ts.map +1 -1
  87. package/lib/index.js +25 -2
  88. package/lib/index.js.map +1 -1
  89. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +77 -0
  90. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -0
  91. package/lib/packlets/crypto-utils/browserCryptoProvider.js +259 -0
  92. package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -0
  93. package/lib/packlets/crypto-utils/browserHashProvider.d.ts.map +1 -0
  94. package/lib/packlets/crypto-utils/browserHashProvider.js.map +1 -0
  95. package/lib/packlets/{crypto → crypto-utils}/index.d.ts +1 -0
  96. package/lib/packlets/crypto-utils/index.d.ts.map +1 -0
  97. package/lib/packlets/{crypto → crypto-utils}/index.js +1 -0
  98. package/lib/packlets/crypto-utils/index.js.map +1 -0
  99. package/lib/packlets/file-api-types/index.d.ts.map +1 -1
  100. package/lib/packlets/file-api-types/index.js +27 -3
  101. package/lib/packlets/file-api-types/index.js.map +1 -1
  102. package/lib/packlets/file-tree/directoryHandleStore.d.ts +59 -0
  103. package/lib/packlets/file-tree/directoryHandleStore.d.ts.map +1 -0
  104. package/lib/packlets/file-tree/directoryHandleStore.js +128 -0
  105. package/lib/packlets/file-tree/directoryHandleStore.js.map +1 -0
  106. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +57 -0
  107. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts.map +1 -1
  108. package/lib/packlets/file-tree/fileApiTreeAccessors.js +76 -0
  109. package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  110. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts +136 -0
  111. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts.map +1 -0
  112. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js +349 -0
  113. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -0
  114. package/lib/packlets/file-tree/index.d.ts +3 -0
  115. package/lib/packlets/file-tree/index.d.ts.map +1 -1
  116. package/lib/packlets/file-tree/index.js +3 -0
  117. package/lib/packlets/file-tree/index.js.map +1 -1
  118. package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts +129 -0
  119. package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts.map +1 -0
  120. package/lib/packlets/file-tree/localStorageTreeAccessors.js +312 -0
  121. package/lib/packlets/file-tree/localStorageTreeAccessors.js.map +1 -0
  122. package/lib/test/mocks/idb-keyval.d.ts +6 -0
  123. package/lib/test/mocks/idb-keyval.d.ts.map +1 -0
  124. package/lib/test/mocks/idb-keyval.js +9 -0
  125. package/lib/test/mocks/idb-keyval.js.map +1 -0
  126. package/lib/test/unit/browserHashProvider.test.js +21 -21
  127. package/lib/test/unit/browserHashProvider.test.js.map +1 -1
  128. package/lib/test/unit/directoryHandleStore.test.d.ts +2 -0
  129. package/lib/test/unit/directoryHandleStore.test.d.ts.map +1 -0
  130. package/lib/test/unit/directoryHandleStore.test.js +192 -0
  131. package/lib/test/unit/directoryHandleStore.test.js.map +1 -0
  132. package/lib/test/unit/fileApiTypes.test.js +30 -0
  133. package/lib/test/unit/fileApiTypes.test.js.map +1 -1
  134. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts +2 -0
  135. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts.map +1 -0
  136. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js +519 -0
  137. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -0
  138. package/lib/test/unit/localStorageTreeAccessors.test.d.ts +2 -0
  139. package/lib/test/unit/localStorageTreeAccessors.test.d.ts.map +1 -0
  140. package/lib/test/unit/localStorageTreeAccessors.test.js +597 -0
  141. package/lib/test/unit/localStorageTreeAccessors.test.js.map +1 -0
  142. package/lib/test/utils/fileSystemAccessMocks.d.ts +53 -0
  143. package/lib/test/utils/fileSystemAccessMocks.d.ts.map +1 -0
  144. package/lib/test/utils/fileSystemAccessMocks.js +277 -0
  145. package/lib/test/utils/fileSystemAccessMocks.js.map +1 -0
  146. package/package.json +27 -20
  147. package/rush-logs/ts-web-extras.build.cache.log +3 -1
  148. package/rush-logs/ts-web-extras.build.log +35 -25
  149. package/src/index.ts +2 -2
  150. package/src/packlets/crypto-utils/browserCryptoProvider.ts +311 -0
  151. package/src/packlets/{crypto → crypto-utils}/index.ts +1 -0
  152. package/src/packlets/file-api-types/index.ts +24 -3
  153. package/src/packlets/file-tree/directoryHandleStore.ts +136 -0
  154. package/src/packlets/file-tree/fileApiTreeAccessors.ts +90 -0
  155. package/src/packlets/file-tree/fileSystemAccessTreeAccessors.ts +427 -0
  156. package/src/packlets/file-tree/index.ts +3 -0
  157. package/src/packlets/file-tree/localStorageTreeAccessors.ts +377 -0
  158. package/src/test/mocks/idb-keyval.ts +5 -0
  159. package/src/test/unit/browserHashProvider.test.ts +1 -1
  160. package/src/test/unit/directoryHandleStore.test.ts +251 -0
  161. package/src/test/unit/fileApiTypes.test.ts +36 -0
  162. package/src/test/unit/fileSystemAccessTreeAccessors.test.ts +732 -0
  163. package/src/test/unit/localStorageTreeAccessors.test.ts +746 -0
  164. package/src/test/utils/fileSystemAccessMocks.ts +353 -0
  165. package/temp/build/typescript/ts_8nwakTlr.json +1 -0
  166. package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +1018 -0
  167. package/temp/coverage/{crypto → crypto-utils}/browserHashProvider.ts.html +3 -3
  168. package/temp/coverage/{lcov-report/crypto → crypto-utils}/index.html +21 -6
  169. package/temp/coverage/file-tree/directoryHandleStore.ts.html +493 -0
  170. package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +276 -6
  171. package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +1366 -0
  172. package/temp/coverage/file-tree/index.html +55 -10
  173. package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +1216 -0
  174. package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
  175. package/temp/coverage/helpers/index.html +1 -1
  176. package/temp/coverage/index.html +15 -15
  177. package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +1018 -0
  178. package/temp/coverage/lcov-report/{crypto → crypto-utils}/browserHashProvider.ts.html +3 -3
  179. package/temp/coverage/{crypto → lcov-report/crypto-utils}/index.html +21 -6
  180. package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +493 -0
  181. package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +276 -6
  182. package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +1366 -0
  183. package/temp/coverage/lcov-report/file-tree/index.html +55 -10
  184. package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +1216 -0
  185. package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
  186. package/temp/coverage/lcov-report/helpers/index.html +1 -1
  187. package/temp/coverage/lcov-report/index.html +15 -15
  188. package/temp/coverage/lcov-report/url-utils/index.html +1 -1
  189. package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
  190. package/temp/coverage/lcov.info +2128 -451
  191. package/temp/coverage/url-utils/index.html +1 -1
  192. package/temp/coverage/url-utils/urlParams.ts.html +1 -1
  193. package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
  194. package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +1 -1
  195. package/temp/ts-web-extras.api.json +3236 -385
  196. package/temp/ts-web-extras.api.md +91 -1
  197. package/dist/packlets/crypto/browserHashProvider.js.map +0 -1
  198. package/dist/packlets/crypto/index.js.map +0 -1
  199. package/lib/packlets/crypto/browserHashProvider.d.ts.map +0 -1
  200. package/lib/packlets/crypto/browserHashProvider.js.map +0 -1
  201. package/lib/packlets/crypto/index.d.ts.map +0 -1
  202. package/lib/packlets/crypto/index.js.map +0 -1
  203. package/temp/build/typescript/ts_vnCx6LlY.json +0 -1
  204. /package/dist/packlets/{crypto → crypto-utils}/browserHashProvider.js +0 -0
  205. /package/lib/packlets/{crypto → crypto-utils}/browserHashProvider.d.ts +0 -0
  206. /package/lib/packlets/{crypto → crypto-utils}/browserHashProvider.js +0 -0
  207. /package/src/packlets/{crypto → crypto-utils}/browserHashProvider.ts +0 -0
  208. /package/temp/test/jest/jest-transform-cache-7492f1b44480e0cdd1f220078fb3afd8-79ef2876fae7ca75eedb2aa53dc48338/{0e/package_0eb6535f5987849d93ea51ef33a14cf6 → 8d/package_8dcbedef69e4299f0f51fcda8f4f1c8e} +0 -0
@@ -29,6 +29,8 @@ import {
29
29
  FileSystemFileHandle,
30
30
  FileSystemDirectoryHandle
31
31
  } from '../file-api-types';
32
+ import { FileSystemAccessTreeAccessors, IFileSystemAccessTreeParams } from './fileSystemAccessTreeAccessors';
33
+ import { LocalStorageTreeAccessors, ILocalStorageTreeParams } from './localStorageTreeAccessors';
32
34
 
33
35
  /**
34
36
  * Interface for File objects that may have the webkitRelativePath property.
@@ -101,6 +103,94 @@ export interface IFileMetadata {
101
103
  * @public
102
104
  */
103
105
  export class FileApiTreeAccessors<TCT extends string = string> {
106
+ /**
107
+ * Create a persistent FileTree from a File System Access API directory handle.
108
+ * Changes to files can be synced back to disk.
109
+ *
110
+ * @param dirHandle - FileSystemDirectoryHandle to load files from
111
+ * @param params - Optional parameters including autoSync and permission settings
112
+ * @returns Promise resolving to a FileTree with persistence capability
113
+ *
114
+ * @remarks
115
+ * - Only works in browsers supporting File System Access API (Chrome, Edge, Opera)
116
+ * - Requires 'readwrite' permission on the directory handle
117
+ * - Falls back to read-only mode if permissions unavailable (unless requireWritePermission is true)
118
+ *
119
+ * @public
120
+ */
121
+ public static async createPersistent<TCT extends string = string>(
122
+ dirHandle: FileSystemDirectoryHandle,
123
+ params?: IFileSystemAccessTreeParams<TCT>
124
+ ): Promise<Result<FileTree.FileTree<TCT>>> {
125
+ const accessorsResult = await FileSystemAccessTreeAccessors.fromDirectoryHandle<TCT>(dirHandle, params);
126
+ if (accessorsResult.isFailure()) {
127
+ return fail(accessorsResult.message);
128
+ }
129
+
130
+ return FileTree.FileTree.create<TCT>(accessorsResult.value);
131
+ }
132
+
133
+ /**
134
+ * Create a persistent FileTree from a single File System Access API file handle.
135
+ * The tree contains exactly one file at `/<filename>`.
136
+ * Changes can be synced back to the original file via `syncToDisk()`.
137
+ *
138
+ * @param fileHandle - FileSystemFileHandle to load
139
+ * @param params - Optional parameters including autoSync and permission settings
140
+ * @returns Promise resolving to a FileTree with persistence capability
141
+ * @public
142
+ */
143
+ public static async createPersistentFromFile<TCT extends string = string>(
144
+ fileHandle: FileSystemFileHandle,
145
+ params?: IFileSystemAccessTreeParams<TCT>
146
+ ): Promise<Result<FileTree.FileTree<TCT>>> {
147
+ const accessorsResult = await FileSystemAccessTreeAccessors.fromFileHandle<TCT>(fileHandle, params);
148
+ if (accessorsResult.isFailure()) {
149
+ return fail(accessorsResult.message);
150
+ }
151
+
152
+ return FileTree.FileTree.create<TCT>(accessorsResult.value);
153
+ }
154
+
155
+ /**
156
+ * Create a persistent FileTree from browser localStorage.
157
+ * Changes to files can be synced back to localStorage.
158
+ *
159
+ * @param params - Configuration including path-to-key mappings and optional autoSync
160
+ * @returns Result containing a FileTree with persistence capability
161
+ *
162
+ * @remarks
163
+ * - Works in all browsers with localStorage support
164
+ * - Maps directory paths to localStorage keys
165
+ * - Each key stores multiple collections as JSON
166
+ * - Files are automatically discovered from storage
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * const tree = FileApiTreeAccessors.createFromLocalStorage({
171
+ * pathToKeyMap: {
172
+ * '/data/ingredients': 'myapp:ingredients:v1',
173
+ * '/data/fillings': 'myapp:fillings:v1'
174
+ * },
175
+ * mutable: true,
176
+ * autoSync: false
177
+ * });
178
+ * ```
179
+ *
180
+ * @public
181
+ */
182
+ public static createFromLocalStorage<TCT extends string = string>(
183
+ params: ILocalStorageTreeParams<TCT>
184
+ ): Result<FileTree.FileTree<TCT>> {
185
+ const accessorsResult = LocalStorageTreeAccessors.fromStorage<TCT>(params);
186
+ /* c8 ignore next 3 - coverage intermittently missed in full suite */
187
+ if (accessorsResult.isFailure()) {
188
+ return fail(accessorsResult.message);
189
+ }
190
+
191
+ return FileTree.FileTree.create<TCT>(accessorsResult.value);
192
+ }
193
+
104
194
  /**
105
195
  * Create FileTree from various file sources using TreeInitializer array.
106
196
  * @param initializers - Array of TreeInitializer objects specifying file sources
@@ -0,0 +1,427 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import { Result, succeed, fail, captureResult, DetailedResult, succeedWithDetail } from '@fgv/ts-utils';
24
+ import { FileTree } from '@fgv/ts-json-base';
25
+ import { FileSystemDirectoryHandle, FileSystemFileHandle } from '../file-api-types';
26
+
27
+ /**
28
+ * Options for creating persistent file trees.
29
+ * @public
30
+ */
31
+ export interface IFileSystemAccessTreeParams<TCT extends string = string>
32
+ extends FileTree.IFileTreeInitParams<TCT> {
33
+ /**
34
+ * Automatically sync changes to disk immediately after each save.
35
+ * If false, changes are batched and written on explicit syncToDisk() call.
36
+ * @defaultValue false
37
+ */
38
+ autoSync?: boolean;
39
+
40
+ /**
41
+ * Require write permission on the directory handle.
42
+ * If true, fails if write permission cannot be obtained.
43
+ * If false, falls back to read-only mode.
44
+ * @defaultValue true
45
+ */
46
+ requireWritePermission?: boolean;
47
+
48
+ /**
49
+ * Override the path at which the file is stored in the tree (for fromFileHandle).
50
+ * Must be an absolute path (e.g., '/data/confections/common.yaml').
51
+ * If omitted, defaults to `/<filename>`.
52
+ */
53
+ filePath?: string;
54
+ }
55
+
56
+ /**
57
+ * Implementation of `FileTree.IPersistentFileTreeAccessors` that uses the File System Access API
58
+ * to provide persistent file editing in browsers.
59
+ * @public
60
+ */
61
+ export class FileSystemAccessTreeAccessors<TCT extends string = string>
62
+ extends FileTree.InMemoryTreeAccessors<TCT>
63
+ implements FileTree.IPersistentFileTreeAccessors<TCT>
64
+ {
65
+ private readonly _handles: Map<string, FileSystemFileHandle>;
66
+ private readonly _rootDir: FileSystemDirectoryHandle;
67
+ private readonly _dirtyFiles: Set<string>;
68
+ private readonly _autoSync: boolean;
69
+ private readonly _hasWritePermission: boolean;
70
+
71
+ /**
72
+ * Protected constructor for FileSystemAccessTreeAccessors.
73
+ * @param files - An array of in-memory files to include in the tree.
74
+ * @param rootDir - The root directory handle.
75
+ * @param handles - Map of file paths to their handles.
76
+ * @param params - Optional params for the tree.
77
+ * @param hasWritePermission - Whether write permission was granted.
78
+ */
79
+ protected constructor(
80
+ files: FileTree.IInMemoryFile<TCT>[],
81
+ rootDir: FileSystemDirectoryHandle,
82
+ handles: Map<string, FileSystemFileHandle>,
83
+ params: IFileSystemAccessTreeParams<TCT> | undefined,
84
+ hasWritePermission: boolean
85
+ ) {
86
+ super(files, params);
87
+ this._rootDir = rootDir;
88
+ this._handles = handles;
89
+ this._dirtyFiles = new Set();
90
+ this._autoSync = params?.autoSync ?? false;
91
+ this._hasWritePermission = hasWritePermission;
92
+ }
93
+
94
+ /**
95
+ * Creates a new FileSystemAccessTreeAccessors instance from a directory handle.
96
+ * @param dirHandle - The FileSystemDirectoryHandle to load files from.
97
+ * @param params - Optional parameters including autoSync and permission settings.
98
+ * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.
99
+ * @public
100
+ */
101
+ public static async fromDirectoryHandle<TCT extends string = string>(
102
+ dirHandle: FileSystemDirectoryHandle,
103
+ params?: IFileSystemAccessTreeParams<TCT>
104
+ ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {
105
+ try {
106
+ // Check write permission
107
+ const hasWritePermission = await this._checkWritePermission(dirHandle);
108
+
109
+ /* c8 ignore next 3 - coverage intermittently missed in full suite */
110
+ if (!hasWritePermission && (params?.requireWritePermission ?? true)) {
111
+ return fail('Write permission required but not granted');
112
+ }
113
+
114
+ // Load all files from the directory (always use '/' as base, prefix is handled by parent)
115
+ const { files, handles } = await this._loadDirectory<TCT>(dirHandle, '/', params);
116
+
117
+ // Enable tree mutability when write permission is granted and caller didn't explicitly set mutable
118
+ const effectiveParams: IFileSystemAccessTreeParams<TCT> = {
119
+ ...params,
120
+ mutable: params?.mutable ?? (hasWritePermission ? true : false)
121
+ };
122
+
123
+ return succeed(
124
+ new FileSystemAccessTreeAccessors<TCT>(files, dirHandle, handles, effectiveParams, hasWritePermission)
125
+ );
126
+ /* c8 ignore next 4 - defensive: outer catch for unexpected errors */
127
+ } catch (error) {
128
+ const message = error instanceof Error ? error.message : String(error);
129
+ return fail(`Failed to create FileSystemAccessTreeAccessors: ${message}`);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Creates a new FileSystemAccessTreeAccessors instance from a single file handle.
135
+ *
136
+ * The resulting tree contains exactly one file at `/<filename>`.
137
+ * `syncToDisk()` writes changes back to the original file via the File System Access API.
138
+ * New file creation is not supported on this tree (no parent directory handle).
139
+ *
140
+ * @param fileHandle - The FileSystemFileHandle to load.
141
+ * @param params - Optional parameters including autoSync and permission settings.
142
+ * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.
143
+ * @public
144
+ */
145
+ public static async fromFileHandle<TCT extends string = string>(
146
+ fileHandle: FileSystemFileHandle,
147
+ params?: IFileSystemAccessTreeParams<TCT>
148
+ ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {
149
+ try {
150
+ const hasWritePermission = await this._checkFileWritePermission(fileHandle);
151
+
152
+ if (!hasWritePermission && (params?.requireWritePermission ?? true)) {
153
+ return fail('Write permission required but not granted');
154
+ }
155
+
156
+ const file = await fileHandle.getFile();
157
+ const contents = await file.text();
158
+ const path = params?.filePath ?? `/${fileHandle.name}`;
159
+ const contentType = params?.inferContentType
160
+ ? params.inferContentType(path, file.type).orDefault()
161
+ : undefined;
162
+
163
+ const files: FileTree.IInMemoryFile<TCT>[] = [{ path, contents, contentType }];
164
+ const handles = new Map<string, FileSystemFileHandle>([[path, fileHandle]]);
165
+
166
+ const dummyRoot = {} as FileSystemDirectoryHandle;
167
+ const effectiveParams: IFileSystemAccessTreeParams<TCT> = {
168
+ ...params,
169
+ mutable: hasWritePermission ? true : params?.mutable ?? false
170
+ };
171
+
172
+ return succeed(
173
+ new FileSystemAccessTreeAccessors<TCT>(files, dummyRoot, handles, effectiveParams, hasWritePermission)
174
+ );
175
+ } catch (error) {
176
+ const message = error instanceof Error ? error.message : String(error);
177
+ return fail(`Failed to create FileSystemAccessTreeAccessors from file: ${message}`);
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Check if the directory handle has write permission.
183
+ * @param handle - The directory handle to check.
184
+ * @returns Promise resolving to true if write permission is granted.
185
+ * @internal
186
+ */
187
+ private static async _checkWritePermission(handle: FileSystemDirectoryHandle): Promise<boolean> {
188
+ try {
189
+ const permission = await handle.queryPermission({ mode: 'readwrite' });
190
+
191
+ if (permission === 'granted') {
192
+ return true;
193
+ }
194
+
195
+ if (permission === 'prompt') {
196
+ const requested = await handle.requestPermission({ mode: 'readwrite' });
197
+ return requested === 'granted';
198
+ }
199
+
200
+ return false;
201
+ } catch (error) {
202
+ // Permission API might not be available or might throw
203
+ return false;
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Check if the file handle has write permission.
209
+ * @param handle - The file handle to check.
210
+ * @returns Promise resolving to true if write permission is granted.
211
+ * @internal
212
+ */
213
+ private static async _checkFileWritePermission(handle: FileSystemFileHandle): Promise<boolean> {
214
+ try {
215
+ const permission = await handle.queryPermission({ mode: 'readwrite' });
216
+
217
+ if (permission === 'granted') {
218
+ return true;
219
+ }
220
+
221
+ if (permission === 'prompt') {
222
+ const requested = await handle.requestPermission({ mode: 'readwrite' });
223
+ return requested === 'granted';
224
+ }
225
+
226
+ return false;
227
+ } catch (error) {
228
+ return false;
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Load all files from a directory handle recursively.
234
+ * @param dirHandle - The directory handle to load from.
235
+ * @param basePath - The base path for files.
236
+ * @param params - Optional parameters.
237
+ * @returns Promise resolving to files and handles.
238
+ * @internal
239
+ */
240
+ private static async _loadDirectory<TCT extends string = string>(
241
+ dirHandle: FileSystemDirectoryHandle,
242
+ basePath: string,
243
+ params?: IFileSystemAccessTreeParams<TCT>
244
+ ): Promise<{ files: FileTree.IInMemoryFile<TCT>[]; handles: Map<string, FileSystemFileHandle> }> {
245
+ const files: FileTree.IInMemoryFile<TCT>[] = [];
246
+ const handles = new Map<string, FileSystemFileHandle>();
247
+
248
+ for await (const [name, handle] of dirHandle.entries()) {
249
+ if (handle.kind === 'file') {
250
+ const fileHandle = handle as FileSystemFileHandle;
251
+ const file = await fileHandle.getFile();
252
+ const contents = await file.text();
253
+ const path = this._joinPath(basePath, name);
254
+ /* c8 ignore next 2 - coverage intermittently missed in full suite */
255
+ const contentType = params?.inferContentType
256
+ ? params.inferContentType(path, file.type).orDefault()
257
+ : undefined;
258
+
259
+ files.push({ path, contents, contentType });
260
+ handles.set(path, fileHandle);
261
+ } else if (handle.kind === 'directory') {
262
+ const subDirHandle = handle as FileSystemDirectoryHandle;
263
+ const subPath = this._joinPath(basePath, name);
264
+ const subResult = await this._loadDirectory<TCT>(subDirHandle, subPath, params);
265
+ files.push(...subResult.files);
266
+ for (const [path, fileHandle] of subResult.handles) {
267
+ handles.set(path, fileHandle);
268
+ }
269
+ }
270
+ }
271
+
272
+ return { files, handles };
273
+ }
274
+
275
+ /**
276
+ * Join path segments.
277
+ * @param base - The base path.
278
+ * @param name - The name to append.
279
+ * @returns The joined path.
280
+ * @internal
281
+ */
282
+ private static _joinPath(base: string, name: string): string {
283
+ const normalized = base.endsWith('/') ? base.slice(0, -1) : base;
284
+ return `${normalized}/${name}`;
285
+ }
286
+
287
+ /**
288
+ * Implements `FileTree.IPersistentFileTreeAccessors.syncToDisk`
289
+ */
290
+ public async syncToDisk(): Promise<Result<void>> {
291
+ if (!this._hasWritePermission) {
292
+ return fail('Write permission not granted - cannot sync to disk');
293
+ }
294
+
295
+ const errors: string[] = [];
296
+
297
+ for (const path of this._dirtyFiles) {
298
+ const syncResult = await this._syncFile(path);
299
+ if (syncResult.isFailure()) {
300
+ errors.push(`${path}: ${syncResult.message}`);
301
+ }
302
+ }
303
+
304
+ if (errors.length > 0) {
305
+ return fail(`Failed to sync ${errors.length} file(s):\n${errors.join('\n')}`);
306
+ }
307
+
308
+ this._dirtyFiles.clear();
309
+ return succeed(undefined);
310
+ }
311
+
312
+ /**
313
+ * Implements `FileTree.IPersistentFileTreeAccessors.isDirty`
314
+ */
315
+ public isDirty(): boolean {
316
+ return this._dirtyFiles.size > 0;
317
+ }
318
+
319
+ /**
320
+ * Implements `FileTree.IPersistentFileTreeAccessors.getDirtyPaths`
321
+ */
322
+ public getDirtyPaths(): string[] {
323
+ return Array.from(this._dirtyFiles);
324
+ }
325
+
326
+ /**
327
+ * Implements `FileTree.IMutableFileTreeAccessors.saveFileContents`
328
+ */
329
+ public saveFileContents(path: string, contents: string): Result<string> {
330
+ // Call parent to update in-memory state
331
+ const result = super.saveFileContents(path, contents);
332
+
333
+ if (result.isSuccess() && this._hasWritePermission) {
334
+ this._dirtyFiles.add(path);
335
+
336
+ // Auto-sync if enabled
337
+ if (this._autoSync) {
338
+ // Fire and forget - errors logged but don't block
339
+ this._syncFile(path).catch((err) => {
340
+ /* c8 ignore next 1 - defensive: async auto-sync error logging */
341
+ console.error(`Auto-sync failed for ${path}:`, err);
342
+ });
343
+ }
344
+ }
345
+
346
+ return result;
347
+ }
348
+
349
+ /**
350
+ * Implements `FileTree.IMutableFileTreeAccessors.fileIsMutable`
351
+ */
352
+ public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {
353
+ const baseResult = super.fileIsMutable(path);
354
+
355
+ if (baseResult.isSuccess() && baseResult.detail === 'transient' && this._hasWritePermission) {
356
+ // Upgrade to 'persistent' if we have write permission
357
+ return succeedWithDetail(true, 'persistent');
358
+ }
359
+
360
+ return baseResult;
361
+ }
362
+
363
+ /**
364
+ * Sync a single file to disk.
365
+ * @param path - The path of the file to sync.
366
+ * @returns Promise resolving to success or failure.
367
+ * @internal
368
+ */
369
+ private async _syncFile(path: string): Promise<Result<void>> {
370
+ const handle = this._handles.get(path);
371
+ if (!handle) {
372
+ return this._createAndWriteFile(path);
373
+ }
374
+
375
+ const contents = this.getFileContents(path);
376
+ if (contents.isFailure()) {
377
+ return fail(contents.message);
378
+ }
379
+
380
+ try {
381
+ const writable = await handle.createWritable();
382
+ await writable.write(contents.value);
383
+ await writable.close();
384
+ return succeed(undefined);
385
+ /* c8 ignore next 4 - coverage intermittently missed in full suite */
386
+ } catch (error) {
387
+ const message = error instanceof Error ? error.message : String(error);
388
+ return fail(`Failed to write file: ${message}`);
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Create a new file and write its contents.
394
+ * @param path - The path of the file to create.
395
+ * @returns Promise resolving to success or failure.
396
+ * @internal
397
+ */
398
+ private async _createAndWriteFile(path: string): Promise<Result<void>> {
399
+ try {
400
+ // Parse path to get directory and filename
401
+ const absolutePath = this.resolveAbsolutePath(path);
402
+ const parts = absolutePath.split('/').filter((p) => p.length > 0);
403
+ const filename = parts.pop();
404
+
405
+ /* c8 ignore next 3 - coverage intermittently missed in full suite */
406
+ if (!filename) {
407
+ return fail(`Invalid file path: ${path}`);
408
+ }
409
+
410
+ // Navigate/create directory structure
411
+ let currentDir = this._rootDir;
412
+ for (const part of parts) {
413
+ currentDir = await currentDir.getDirectoryHandle(part, { create: true });
414
+ }
415
+
416
+ // Create file and write contents
417
+ const fileHandle = await currentDir.getFileHandle(filename, { create: true });
418
+ this._handles.set(path, fileHandle);
419
+
420
+ return this._syncFile(path);
421
+ /* c8 ignore next 4 - coverage intermittently missed in full suite */
422
+ } catch (error) {
423
+ const message = error instanceof Error ? error.message : String(error);
424
+ return fail(`Failed to create file ${path}: ${message}`);
425
+ }
426
+ }
427
+ }
@@ -25,4 +25,7 @@
25
25
  * @packageDocumentation
26
26
  */
27
27
 
28
+ export * from './directoryHandleStore';
28
29
  export * from './fileApiTreeAccessors';
30
+ export * from './fileSystemAccessTreeAccessors';
31
+ export * from './localStorageTreeAccessors';