@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
@@ -0,0 +1,377 @@
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 { DetailedResult, fail, Result, succeed, succeedWithDetail } from '@fgv/ts-utils';
24
+ import { FileTree } from '@fgv/ts-json-base';
25
+ import { isJsonObject, type JsonObject } from '@fgv/ts-json-base';
26
+
27
+ /**
28
+ * Configuration for LocalStorageTreeAccessors.
29
+ * @public
30
+ */
31
+ export interface ILocalStorageTreeParams<TCT extends string = string>
32
+ extends FileTree.IFileTreeInitParams<TCT> {
33
+ /**
34
+ * Map of directory path prefixes to localStorage keys.
35
+ * Files under each prefix are stored in the corresponding localStorage key.
36
+ * Example: \{ '/data/ingredients': 'myapp:ingredients:v1' \}
37
+ */
38
+ pathToKeyMap: Record<string, string>;
39
+
40
+ /**
41
+ * Storage instance to use. Defaults to window.localStorage.
42
+ * Can be overridden for testing with mock storage.
43
+ */
44
+ storage?: Storage;
45
+
46
+ /**
47
+ * If true, automatically sync changes to localStorage on every modification.
48
+ * If false (default), changes are only synced when syncToDisk() is called.
49
+ */
50
+ autoSync?: boolean;
51
+ }
52
+
53
+ /**
54
+ * Browser localStorage-backed file tree accessors with persistence support.
55
+ *
56
+ * Maps filesystem-like directory paths to localStorage keys, where each key stores
57
+ * multiple collections as a JSON object. This provides a general-purpose implementation
58
+ * for browser-based file tree persistence without requiring File System Access API.
59
+ *
60
+ * Storage format per key: `{ "collection-id": "<raw file content>" }`
61
+ * File paths map as: `/data/ingredients/collection-id.yaml` → stored in key for `/data/ingredients`
62
+ *
63
+ * Legacy format (v1): `{ "collection-id": { ...parsedJsonObject } }` is auto-migrated on load.
64
+ *
65
+ * @public
66
+ */
67
+ export class LocalStorageTreeAccessors<TCT extends string = string>
68
+ extends FileTree.InMemoryTreeAccessors<TCT>
69
+ implements FileTree.IPersistentFileTreeAccessors<TCT>
70
+ {
71
+ private readonly _storage: Storage;
72
+ private readonly _pathToKeyMap: Map<string, string>;
73
+ private readonly _keyToPathMap: Map<string, string>;
74
+ private readonly _dirtyFiles: Set<string>;
75
+ private readonly _autoSync: boolean;
76
+
77
+ /**
78
+ * Private constructor. Use fromStorage() factory method instead.
79
+ * @internal
80
+ */
81
+ private constructor(
82
+ files: FileTree.IInMemoryFile<TCT>[],
83
+ storage: Storage,
84
+ pathToKeyMap: Map<string, string>,
85
+ params?: ILocalStorageTreeParams<TCT>
86
+ ) {
87
+ super(files, params);
88
+ this._storage = storage;
89
+ this._pathToKeyMap = pathToKeyMap;
90
+ this._keyToPathMap = new Map(Array.from(pathToKeyMap.entries()).map(([k, v]) => [v, k]));
91
+ this._dirtyFiles = new Set();
92
+ this._autoSync = params?.autoSync ?? false;
93
+ }
94
+
95
+ /**
96
+ * Create LocalStorageTreeAccessors from browser localStorage.
97
+ * Loads all collections from the configured storage keys.
98
+ *
99
+ * @param params - Configuration including path-to-key mappings
100
+ * @returns Result containing the accessors or an error
101
+ * @public
102
+ */
103
+ public static fromStorage<TCT extends string = string>(
104
+ params: ILocalStorageTreeParams<TCT>
105
+ ): Result<LocalStorageTreeAccessors<TCT>> {
106
+ try {
107
+ const storage = params.storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);
108
+ if (!storage) {
109
+ return fail('localStorage is not available');
110
+ }
111
+
112
+ const pathToKeyMap = new Map(Object.entries(params.pathToKeyMap));
113
+ const files = this._loadFromStorage<TCT>(storage, pathToKeyMap, params);
114
+
115
+ return succeed(new LocalStorageTreeAccessors<TCT>(files, storage, pathToKeyMap, params));
116
+ /* c8 ignore next 4 - defensive: outer catch for unexpected errors */
117
+ } catch (error) {
118
+ const message = error instanceof Error ? error.message : String(error);
119
+ return fail(`Failed to create LocalStorageTreeAccessors: ${message}`);
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Load all files from localStorage based on path-to-key mappings.
125
+ * @internal
126
+ */
127
+ private static _loadFromStorage<TCT extends string = string>(
128
+ storage: Storage,
129
+ pathToKeyMap: Map<string, string>,
130
+ params?: ILocalStorageTreeParams<TCT>
131
+ ): FileTree.IInMemoryFile<TCT>[] {
132
+ const files: FileTree.IInMemoryFile<TCT>[] = [];
133
+
134
+ for (const [dataPath, storageKey] of pathToKeyMap.entries()) {
135
+ const rawJson = storage.getItem(storageKey);
136
+ if (!rawJson) {
137
+ continue;
138
+ }
139
+
140
+ try {
141
+ const parsed: unknown = JSON.parse(rawJson);
142
+ if (!isJsonObject(parsed)) {
143
+ continue;
144
+ }
145
+
146
+ for (const [collectionId, contents] of Object.entries(parsed)) {
147
+ // Support both new format (string values) and legacy format (JsonObject values)
148
+ let rawContent: string;
149
+ let extension: string;
150
+ if (typeof contents === 'string') {
151
+ rawContent = contents;
152
+ // Infer extension: if content looks like JSON, use .json; otherwise .yaml
153
+ extension = this._looksLikeJson(contents) ? '.json' : '.yaml';
154
+ } else if (isJsonObject(contents)) {
155
+ // Legacy format: migrate by stringifying
156
+ rawContent = JSON.stringify(contents);
157
+ extension = '.json';
158
+ } else {
159
+ continue;
160
+ }
161
+
162
+ const filePath = this._joinPath(dataPath, `${collectionId}${extension}`);
163
+ const contentType = params?.inferContentType
164
+ ? params.inferContentType(filePath, undefined).orDefault()
165
+ : undefined;
166
+
167
+ files.push({
168
+ path: filePath,
169
+ contents: rawContent,
170
+ contentType
171
+ });
172
+ }
173
+ } catch {
174
+ // Skip corrupted data
175
+ continue;
176
+ }
177
+ }
178
+
179
+ return files;
180
+ }
181
+
182
+ /**
183
+ * Heuristic check: does the content look like JSON?
184
+ * @internal
185
+ */
186
+ private static _looksLikeJson(content: string): boolean {
187
+ const trimmed = content.trimStart();
188
+ return trimmed.startsWith('{') || trimmed.startsWith('[');
189
+ }
190
+
191
+ /**
192
+ * Join path components, handling leading/trailing slashes.
193
+ * @internal
194
+ */
195
+ private static _joinPath(base: string, name: string): string {
196
+ const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;
197
+ const cleanName = name.startsWith('/') ? name.slice(1) : name;
198
+ return `${cleanBase}/${cleanName}`;
199
+ }
200
+
201
+ /**
202
+ * Get the storage key for a given file path.
203
+ * @internal
204
+ */
205
+ private _getStorageKeyForPath(path: string): string | undefined {
206
+ // Find the longest matching prefix
207
+ let bestMatch: { prefix: string; key: string } | undefined;
208
+ for (const [prefix, key] of this._pathToKeyMap.entries()) {
209
+ if (path.startsWith(prefix)) {
210
+ if (!bestMatch || prefix.length > bestMatch.prefix.length) {
211
+ bestMatch = { prefix, key };
212
+ }
213
+ }
214
+ }
215
+ return bestMatch?.key;
216
+ }
217
+
218
+ /**
219
+ * Get the data path prefix for a given file path.
220
+ * @internal
221
+ */
222
+ private _getDataPathForPath(path: string): string | undefined {
223
+ for (const prefix of this._pathToKeyMap.keys()) {
224
+ if (path.startsWith(prefix)) {
225
+ return prefix;
226
+ }
227
+ }
228
+ /* c8 ignore next 2 - coverage intermittently missed in full suite */
229
+ return undefined;
230
+ }
231
+
232
+ /**
233
+ * Extract collection ID from a file path.
234
+ * Example: '/data/ingredients/my-collection.yaml' → 'my-collection'
235
+ * @internal
236
+ */
237
+ private _getCollectionIdFromPath(path: string): string {
238
+ const dataPath = this._getDataPathForPath(path);
239
+ /* c8 ignore next 3 - coverage intermittently missed in full suite */
240
+ if (!dataPath) {
241
+ return path;
242
+ }
243
+
244
+ const relativePath = path.slice(dataPath.length);
245
+ const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath;
246
+
247
+ // Remove any file extension
248
+ const dotIndex = cleanPath.lastIndexOf('.');
249
+ return dotIndex > 0 ? cleanPath.slice(0, dotIndex) : cleanPath;
250
+ }
251
+
252
+ /**
253
+ * Sync a single dirty file to localStorage.
254
+ * @internal
255
+ */
256
+ private _syncFile(path: string): Result<void> {
257
+ const storageKey = this._getStorageKeyForPath(path);
258
+ if (!storageKey) {
259
+ return fail(`No storage key configured for path: ${path}`);
260
+ }
261
+
262
+ const collectionId = this._getCollectionIdFromPath(path);
263
+ const contentsResult = this.getFileContents(path);
264
+ if (contentsResult.isFailure()) {
265
+ return fail(`Failed to get file contents for ${path}: ${contentsResult.message}`);
266
+ }
267
+
268
+ try {
269
+ const contents = contentsResult.value;
270
+
271
+ // Load existing data from storage
272
+ const existingJson = this._storage.getItem(storageKey);
273
+ let existing: Record<string, unknown> = {};
274
+ if (existingJson) {
275
+ try {
276
+ const parsed = JSON.parse(existingJson);
277
+ if (isJsonObject(parsed)) {
278
+ existing = parsed as Record<string, unknown>;
279
+ }
280
+ } catch {
281
+ // Start fresh if corrupted
282
+ }
283
+ }
284
+
285
+ // Store raw content string (content-agnostic: JSON, YAML, etc.)
286
+ existing[collectionId] = contents;
287
+ this._storage.setItem(storageKey, JSON.stringify(existing));
288
+
289
+ return succeed(undefined);
290
+ /* c8 ignore next 4 - defensive: only triggers on storage quota or similar runtime errors */
291
+ } catch (error) {
292
+ const message = error instanceof Error ? error.message : String(error);
293
+ return fail(`Failed to sync file ${path}: ${message}`);
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Sync all dirty files to localStorage.
299
+ * @returns Result indicating success or failure
300
+ * @public
301
+ */
302
+ public async syncToDisk(): Promise<Result<void>> {
303
+ if (this._dirtyFiles.size === 0) {
304
+ return succeed(undefined);
305
+ }
306
+
307
+ const errors: string[] = [];
308
+ for (const path of this._dirtyFiles) {
309
+ const result = this._syncFile(path);
310
+ if (result.isFailure()) {
311
+ errors.push(result.message);
312
+ }
313
+ }
314
+
315
+ if (errors.length > 0) {
316
+ return fail(`Failed to sync ${errors.length} file(s): ${errors.join('; ')}`);
317
+ }
318
+
319
+ this._dirtyFiles.clear();
320
+ return succeed(undefined);
321
+ }
322
+
323
+ /**
324
+ * Check if there are unsaved changes.
325
+ * @returns True if there are dirty files
326
+ * @public
327
+ */
328
+ public isDirty(): boolean {
329
+ return this._dirtyFiles.size > 0;
330
+ }
331
+
332
+ /**
333
+ * Get list of file paths with unsaved changes.
334
+ * @returns Array of dirty file paths
335
+ * @public
336
+ */
337
+ public getDirtyPaths(): string[] {
338
+ return Array.from(this._dirtyFiles);
339
+ }
340
+
341
+ /**
342
+ * Save file contents. Marks file as dirty and optionally auto-syncs.
343
+ * @param path - File path
344
+ * @param contents - New file contents
345
+ * @returns Result with the saved contents or error
346
+ * @public
347
+ */
348
+ public saveFileContents(path: string, contents: string): Result<string> {
349
+ const result = super.saveFileContents(path, contents);
350
+ if (result.isSuccess()) {
351
+ this._dirtyFiles.add(path);
352
+ if (this._autoSync) {
353
+ const syncResult = this._syncFile(path);
354
+ if (syncResult.isSuccess()) {
355
+ this._dirtyFiles.delete(path);
356
+ } else {
357
+ return fail(syncResult.message);
358
+ }
359
+ }
360
+ }
361
+ return result;
362
+ }
363
+
364
+ /**
365
+ * Check if a file is mutable and return persistence detail.
366
+ * @param path - File path to check
367
+ * @returns DetailedResult with mutability status and 'persistent' detail if mutable
368
+ * @public
369
+ */
370
+ public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {
371
+ const baseResult = super.fileIsMutable(path);
372
+ if (baseResult.isSuccess() && baseResult.value === true) {
373
+ return succeedWithDetail(true, 'persistent');
374
+ }
375
+ return baseResult;
376
+ }
377
+ }
@@ -0,0 +1,5 @@
1
+ export const createStore = jest.fn(() => ({}));
2
+ export const get = jest.fn();
3
+ export const set = jest.fn();
4
+ export const del = jest.fn();
5
+ export const keys = jest.fn();
@@ -21,7 +21,7 @@
21
21
  */
22
22
 
23
23
  import '@fgv/ts-utils-jest';
24
- import { BrowserHashProvider } from '../../packlets/crypto';
24
+ import { BrowserHashProvider } from '../../packlets/crypto-utils';
25
25
 
26
26
  describe('BrowserHashProvider', () => {
27
27
  describe('hashString', () => {
@@ -0,0 +1,251 @@
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 '@fgv/ts-utils-jest';
24
+ import {
25
+ DirectoryHandleStore,
26
+ DEFAULT_DIRECTORY_HANDLE_DB,
27
+ DEFAULT_DIRECTORY_HANDLE_STORE
28
+ } from '../../packlets/file-tree/directoryHandleStore';
29
+ import type { FileSystemDirectoryHandle } from '../../packlets/file-api-types';
30
+
31
+ import { get, set, del, keys, createStore } from 'idb-keyval';
32
+
33
+ const mockGet = jest.mocked(get);
34
+ const mockSet = jest.mocked(set);
35
+ const mockDel = jest.mocked(del);
36
+ const mockKeys = jest.mocked(keys);
37
+ const mockCreateStore = jest.mocked(createStore);
38
+
39
+ function makeMockHandle(name: string): FileSystemDirectoryHandle {
40
+ return {
41
+ kind: 'directory',
42
+ name,
43
+ isSameEntry: jest.fn(),
44
+ queryPermission: jest.fn(),
45
+ requestPermission: jest.fn(),
46
+ getDirectoryHandle: jest.fn(),
47
+ getFileHandle: jest.fn(),
48
+ removeEntry: jest.fn(),
49
+ resolve: jest.fn(),
50
+ keys: jest.fn(),
51
+ values: jest.fn(),
52
+ entries: jest.fn(),
53
+ [Symbol.asyncIterator]: jest.fn()
54
+ } as FileSystemDirectoryHandle;
55
+ }
56
+
57
+ describe('DirectoryHandleStore', () => {
58
+ beforeEach(() => {
59
+ jest.clearAllMocks();
60
+ });
61
+
62
+ describe('constants', () => {
63
+ test('DEFAULT_DIRECTORY_HANDLE_DB has expected value', () => {
64
+ expect(DEFAULT_DIRECTORY_HANDLE_DB).toBe('chocolate-lab-storage');
65
+ });
66
+
67
+ test('DEFAULT_DIRECTORY_HANDLE_STORE has expected value', () => {
68
+ expect(DEFAULT_DIRECTORY_HANDLE_STORE).toBe('directory-handles');
69
+ });
70
+ });
71
+
72
+ describe('constructor', () => {
73
+ test('uses default db and store names', () => {
74
+ new DirectoryHandleStore();
75
+ expect(mockCreateStore).toHaveBeenCalledWith(
76
+ DEFAULT_DIRECTORY_HANDLE_DB,
77
+ DEFAULT_DIRECTORY_HANDLE_STORE
78
+ );
79
+ });
80
+
81
+ test('uses custom db and store names', () => {
82
+ new DirectoryHandleStore('custom-db', 'custom-store');
83
+ expect(mockCreateStore).toHaveBeenCalledWith('custom-db', 'custom-store');
84
+ });
85
+ });
86
+
87
+ describe('save', () => {
88
+ test('saves a handle successfully', async () => {
89
+ mockSet.mockResolvedValue(undefined);
90
+ const store = new DirectoryHandleStore();
91
+ const handle = makeMockHandle('my-dir');
92
+
93
+ const result = await store.save('my-dir', handle);
94
+
95
+ expect(result).toSucceed();
96
+ expect(mockSet).toHaveBeenCalledWith('my-dir', handle, expect.anything());
97
+ });
98
+
99
+ test('returns failure when set throws', async () => {
100
+ mockSet.mockRejectedValue(new Error('IndexedDB unavailable'));
101
+ const store = new DirectoryHandleStore();
102
+ const handle = makeMockHandle('my-dir');
103
+
104
+ const result = await store.save('my-dir', handle);
105
+
106
+ expect(result).toFailWith(/IndexedDB unavailable/);
107
+ });
108
+ });
109
+
110
+ describe('load', () => {
111
+ test('returns the handle when found', async () => {
112
+ const handle = makeMockHandle('my-dir');
113
+ mockGet.mockResolvedValue(handle);
114
+ const store = new DirectoryHandleStore();
115
+
116
+ const result = await store.load('my-dir');
117
+
118
+ expect(result).toSucceedWith(handle);
119
+ expect(mockGet).toHaveBeenCalledWith('my-dir', expect.anything());
120
+ });
121
+
122
+ test('returns undefined when not found', async () => {
123
+ mockGet.mockResolvedValue(undefined);
124
+ const store = new DirectoryHandleStore();
125
+
126
+ const result = await store.load('missing');
127
+
128
+ expect(result).toSucceedWith(undefined);
129
+ });
130
+
131
+ test('returns failure when get throws', async () => {
132
+ mockGet.mockRejectedValue(new Error('read error'));
133
+ const store = new DirectoryHandleStore();
134
+
135
+ const result = await store.load('my-dir');
136
+
137
+ expect(result).toFailWith(/read error/);
138
+ });
139
+ });
140
+
141
+ describe('remove', () => {
142
+ test('removes a handle successfully', async () => {
143
+ mockDel.mockResolvedValue(undefined);
144
+ const store = new DirectoryHandleStore();
145
+
146
+ const result = await store.remove('my-dir');
147
+
148
+ expect(result).toSucceed();
149
+ expect(mockDel).toHaveBeenCalledWith('my-dir', expect.anything());
150
+ });
151
+
152
+ test('returns failure when del throws', async () => {
153
+ mockDel.mockRejectedValue(new Error('delete error'));
154
+ const store = new DirectoryHandleStore();
155
+
156
+ const result = await store.remove('my-dir');
157
+
158
+ expect(result).toFailWith(/delete error/);
159
+ });
160
+ });
161
+
162
+ describe('getAllLabels', () => {
163
+ test('returns all keys', async () => {
164
+ mockKeys.mockResolvedValue(['dir-a', 'dir-b']);
165
+ const store = new DirectoryHandleStore();
166
+
167
+ const result = await store.getAllLabels();
168
+
169
+ expect(result).toSucceedWith(['dir-a', 'dir-b']);
170
+ expect(mockKeys).toHaveBeenCalledWith(expect.anything());
171
+ });
172
+
173
+ test('returns empty array when no keys', async () => {
174
+ mockKeys.mockResolvedValue([]);
175
+ const store = new DirectoryHandleStore();
176
+
177
+ const result = await store.getAllLabels();
178
+
179
+ expect(result).toSucceedWith([]);
180
+ });
181
+
182
+ test('returns failure when keys throws', async () => {
183
+ mockKeys.mockRejectedValue(new Error('keys error'));
184
+ const store = new DirectoryHandleStore();
185
+
186
+ const result = await store.getAllLabels();
187
+
188
+ expect(result).toFailWith(/keys error/);
189
+ });
190
+ });
191
+
192
+ describe('getAll', () => {
193
+ test('returns all label/handle pairs', async () => {
194
+ const handleA = makeMockHandle('dir-a');
195
+ const handleB = makeMockHandle('dir-b');
196
+ mockKeys.mockResolvedValue(['dir-a', 'dir-b']);
197
+ mockGet.mockResolvedValueOnce(handleA).mockResolvedValueOnce(handleB);
198
+ const store = new DirectoryHandleStore();
199
+
200
+ const result = await store.getAll();
201
+
202
+ expect(result).toSucceedAndSatisfy((entries) => {
203
+ expect(entries).toHaveLength(2);
204
+ expect(entries[0]).toEqual({ label: 'dir-a', handle: handleA });
205
+ expect(entries[1]).toEqual({ label: 'dir-b', handle: handleB });
206
+ });
207
+ });
208
+
209
+ test('returns empty array when no handles stored', async () => {
210
+ mockKeys.mockResolvedValue([]);
211
+ const store = new DirectoryHandleStore();
212
+
213
+ const result = await store.getAll();
214
+
215
+ expect(result).toSucceedWith([]);
216
+ });
217
+
218
+ test('skips entries where handle is undefined', async () => {
219
+ const handleA = makeMockHandle('dir-a');
220
+ mockKeys.mockResolvedValue(['dir-a', 'dir-b']);
221
+ mockGet.mockResolvedValueOnce(handleA).mockResolvedValueOnce(undefined);
222
+ const store = new DirectoryHandleStore();
223
+
224
+ const result = await store.getAll();
225
+
226
+ expect(result).toSucceedAndSatisfy((entries) => {
227
+ expect(entries).toHaveLength(1);
228
+ expect(entries[0]).toEqual({ label: 'dir-a', handle: handleA });
229
+ });
230
+ });
231
+
232
+ test('returns failure when getAllLabels fails', async () => {
233
+ mockKeys.mockRejectedValue(new Error('keys error'));
234
+ const store = new DirectoryHandleStore();
235
+
236
+ const result = await store.getAll();
237
+
238
+ expect(result).toFailWith(/keys error/);
239
+ });
240
+
241
+ test('returns failure when load fails for a key', async () => {
242
+ mockKeys.mockResolvedValue(['dir-a']);
243
+ mockGet.mockRejectedValue(new Error('load error'));
244
+ const store = new DirectoryHandleStore();
245
+
246
+ const result = await store.getAll();
247
+
248
+ expect(result).toFailWith(/load error/);
249
+ });
250
+ });
251
+ });
@@ -279,6 +279,18 @@ describe('File API Types', () => {
279
279
 
280
280
  await expect(safeShowOpenFilePicker(mockWindow)).rejects.toThrow('User cancelled file picker');
281
281
  });
282
+
283
+ test('returns null when user cancels (AbortError)', async () => {
284
+ const abortError = new DOMException('The user aborted a request.', 'AbortError');
285
+ const mockWindow = {
286
+ showOpenFilePicker: jest.fn().mockRejectedValue(abortError),
287
+ showSaveFilePicker: jest.fn(),
288
+ showDirectoryPicker: jest.fn()
289
+ } as unknown as WindowWithFsAccess;
290
+
291
+ const result = await safeShowOpenFilePicker(mockWindow);
292
+ expect(result).toBeNull();
293
+ });
282
294
  });
283
295
 
284
296
  describe('safeShowSaveFilePicker', () => {
@@ -357,6 +369,18 @@ describe('File API Types', () => {
357
369
 
358
370
  await expect(safeShowSaveFilePicker(mockWindow)).rejects.toThrow('Save operation failed');
359
371
  });
372
+
373
+ test('returns null when user cancels (AbortError)', async () => {
374
+ const abortError = new DOMException('The user aborted a request.', 'AbortError');
375
+ const mockWindow = {
376
+ showOpenFilePicker: jest.fn(),
377
+ showSaveFilePicker: jest.fn().mockRejectedValue(abortError),
378
+ showDirectoryPicker: jest.fn()
379
+ } as unknown as WindowWithFsAccess;
380
+
381
+ const result = await safeShowSaveFilePicker(mockWindow);
382
+ expect(result).toBeNull();
383
+ });
360
384
  });
361
385
 
362
386
  describe('safeShowDirectoryPicker', () => {
@@ -441,6 +465,18 @@ describe('File API Types', () => {
441
465
 
442
466
  await expect(safeShowDirectoryPicker(mockWindow)).rejects.toThrow('Directory access denied');
443
467
  });
468
+
469
+ test('returns null when user cancels (AbortError)', async () => {
470
+ const abortError = new DOMException('The user aborted a request.', 'AbortError');
471
+ const mockWindow = {
472
+ showOpenFilePicker: jest.fn(),
473
+ showSaveFilePicker: jest.fn(),
474
+ showDirectoryPicker: jest.fn().mockRejectedValue(abortError)
475
+ } as unknown as WindowWithFsAccess;
476
+
477
+ const result = await safeShowDirectoryPicker(mockWindow);
478
+ expect(result).toBeNull();
479
+ });
444
480
  });
445
481
 
446
482
  describe('integration tests', () => {