@fgv/ts-web-extras 5.1.0-3 → 5.1.0-5

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 (270) hide show
  1. package/.rush/temp/{61c1d4a91d98f048b475a5bb3e6541c5d27819de.tar.log → 54f89319dd14b2acc47614d70128001f4227d01e.tar.log} +3 -3
  2. package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +18 -18
  3. package/.rush/temp/operation/build/all.log +18 -18
  4. package/.rush/temp/operation/build/log-chunks.jsonl +18 -18
  5. package/.rush/temp/operation/build/state.json +1 -1
  6. package/.rush/temp/shrinkwrap-deps.json +690 -633
  7. package/config/typedoc.json +2 -1
  8. package/dist/packlets/file-tree/httpTreeAccessors.js +72 -42
  9. package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -1
  10. package/dist/test/unit/httpTreeAccessors.test.js +135 -0
  11. package/dist/test/unit/httpTreeAccessors.test.js.map +1 -1
  12. package/dist/ts-web-extras.d.ts +6 -0
  13. package/dist/tsdoc-metadata.json +1 -1
  14. package/docs/CryptoUtils/README.md +60 -0
  15. package/docs/CryptoUtils/classes/BrowserCryptoProvider.decrypt.md +27 -0
  16. package/docs/CryptoUtils/classes/BrowserCryptoProvider.deriveKey.md +26 -0
  17. package/docs/CryptoUtils/classes/BrowserCryptoProvider.encrypt.md +25 -0
  18. package/docs/CryptoUtils/classes/BrowserCryptoProvider.fromBase64.md +24 -0
  19. package/docs/CryptoUtils/classes/BrowserCryptoProvider.generateKey.md +17 -0
  20. package/docs/CryptoUtils/classes/BrowserCryptoProvider.generateRandomBytes.md +24 -0
  21. package/docs/CryptoUtils/classes/BrowserCryptoProvider.md +151 -0
  22. package/docs/CryptoUtils/classes/BrowserCryptoProvider.toBase64.md +24 -0
  23. package/docs/CryptoUtils/classes/BrowserHashProvider.hashParts.md +26 -0
  24. package/docs/CryptoUtils/classes/BrowserHashProvider.hashString.md +25 -0
  25. package/docs/CryptoUtils/classes/BrowserHashProvider.md +81 -0
  26. package/docs/CryptoUtils/functions/createBrowserCryptoProvider.md +12 -0
  27. package/docs/FileTreeHelpers/README.md +85 -0
  28. package/docs/FileTreeHelpers/functions/extractFileListMetadata.md +11 -0
  29. package/docs/FileTreeHelpers/functions/extractFileMetadata.md +11 -0
  30. package/docs/FileTreeHelpers/functions/fromDirectoryUpload.md +12 -0
  31. package/docs/FileTreeHelpers/functions/fromFileList.md +12 -0
  32. package/docs/FileTreeHelpers/functions/getOriginalFile.md +11 -0
  33. package/docs/FileTreeHelpers/variables/defaultFileApiTreeInitParams.md +9 -0
  34. package/docs/README.md +499 -53
  35. package/docs/classes/BrowserCryptoProvider.decrypt.md +27 -0
  36. package/docs/classes/BrowserCryptoProvider.deriveKey.md +26 -0
  37. package/docs/classes/BrowserCryptoProvider.encrypt.md +25 -0
  38. package/docs/classes/BrowserCryptoProvider.fromBase64.md +24 -0
  39. package/docs/classes/BrowserCryptoProvider.generateKey.md +17 -0
  40. package/docs/classes/BrowserCryptoProvider.generateRandomBytes.md +24 -0
  41. package/docs/classes/BrowserCryptoProvider.md +151 -0
  42. package/docs/classes/BrowserCryptoProvider.toBase64.md +24 -0
  43. package/docs/classes/BrowserHashProvider.hashParts.md +26 -0
  44. package/docs/classes/BrowserHashProvider.hashString.md +25 -0
  45. package/docs/classes/BrowserHashProvider.md +81 -0
  46. package/docs/classes/DirectoryHandleStore.getAll.md +17 -0
  47. package/docs/classes/DirectoryHandleStore.getAllLabels.md +17 -0
  48. package/docs/classes/DirectoryHandleStore.load.md +24 -0
  49. package/docs/classes/DirectoryHandleStore.md +65 -61
  50. package/docs/classes/DirectoryHandleStore.remove.md +24 -0
  51. package/docs/classes/DirectoryHandleStore.save.md +25 -0
  52. package/docs/classes/FileApiTreeAccessors.create.md +25 -0
  53. package/docs/classes/FileApiTreeAccessors.createFromHttp.md +24 -0
  54. package/docs/classes/FileApiTreeAccessors.createFromLocalStorage.md +25 -0
  55. package/docs/classes/FileApiTreeAccessors.createPersistent.md +26 -0
  56. package/docs/classes/FileApiTreeAccessors.createPersistentFromFile.md +27 -0
  57. package/docs/classes/FileApiTreeAccessors.extractFileMetadata.md +24 -0
  58. package/docs/classes/FileApiTreeAccessors.fromDirectoryUpload.md +25 -0
  59. package/docs/classes/FileApiTreeAccessors.fromFileList.md +25 -0
  60. package/docs/classes/FileApiTreeAccessors.getOriginalFile.md +27 -0
  61. package/docs/classes/FileApiTreeAccessors.md +87 -201
  62. package/docs/classes/FileSystemAccessTreeAccessors.deleteFile.md +22 -0
  63. package/docs/classes/FileSystemAccessTreeAccessors.fileIsMutable.md +22 -0
  64. package/docs/classes/FileSystemAccessTreeAccessors.fromDirectoryHandle.md +25 -0
  65. package/docs/classes/FileSystemAccessTreeAccessors.fromFileHandle.md +29 -0
  66. package/docs/classes/FileSystemAccessTreeAccessors.getDirtyPaths.md +15 -0
  67. package/docs/classes/FileSystemAccessTreeAccessors.isDirty.md +15 -0
  68. package/docs/classes/FileSystemAccessTreeAccessors.md +128 -410
  69. package/docs/classes/FileSystemAccessTreeAccessors.saveFileContents.md +23 -0
  70. package/docs/classes/FileSystemAccessTreeAccessors.syncToDisk.md +15 -0
  71. package/docs/classes/HttpTreeAccessors.deleteFile.md +22 -0
  72. package/docs/classes/HttpTreeAccessors.fileIsMutable.md +24 -0
  73. package/docs/classes/HttpTreeAccessors.fromHttp.md +24 -0
  74. package/docs/classes/HttpTreeAccessors.getDirtyPaths.md +17 -0
  75. package/docs/classes/HttpTreeAccessors.isDirty.md +17 -0
  76. package/docs/classes/HttpTreeAccessors.md +121 -368
  77. package/docs/classes/HttpTreeAccessors.saveFileContents.md +25 -0
  78. package/docs/classes/HttpTreeAccessors.syncToDisk.md +22 -0
  79. package/docs/classes/LocalStorageTreeAccessors.deleteFile.md +24 -0
  80. package/docs/classes/LocalStorageTreeAccessors.fileIsMutable.md +24 -0
  81. package/docs/classes/LocalStorageTreeAccessors.fromStorage.md +25 -0
  82. package/docs/classes/LocalStorageTreeAccessors.getDirtyPaths.md +17 -0
  83. package/docs/classes/LocalStorageTreeAccessors.isDirty.md +17 -0
  84. package/docs/classes/LocalStorageTreeAccessors.md +121 -371
  85. package/docs/classes/LocalStorageTreeAccessors.saveFileContents.md +25 -0
  86. package/docs/classes/LocalStorageTreeAccessors.syncToDisk.md +17 -0
  87. package/docs/functions/createBrowserCryptoProvider.md +12 -0
  88. package/docs/functions/exportAsJson.md +6 -17
  89. package/docs/functions/exportUsingFileSystemAPI.md +6 -21
  90. package/docs/functions/extractDirectoryPath.md +6 -16
  91. package/docs/functions/extractFileListMetadata.md +11 -0
  92. package/docs/functions/extractFileMetadata.md +11 -0
  93. package/docs/functions/fromDirectoryUpload.md +12 -0
  94. package/docs/functions/fromFileList.md +12 -0
  95. package/docs/functions/getOriginalFile.md +11 -0
  96. package/docs/functions/isDirectoryHandle.md +6 -18
  97. package/docs/functions/isFileHandle.md +6 -18
  98. package/docs/functions/isFilePath.md +6 -16
  99. package/docs/functions/parseContextFilter.md +6 -16
  100. package/docs/functions/parseQualifierDefaults.md +6 -16
  101. package/docs/functions/parseResourceTypes.md +6 -16
  102. package/docs/functions/parseUrlParameters.md +6 -10
  103. package/docs/functions/safeShowDirectoryPicker.md +6 -19
  104. package/docs/functions/safeShowOpenFilePicker.md +6 -19
  105. package/docs/functions/safeShowSaveFilePicker.md +6 -19
  106. package/docs/functions/supportsFileSystemAccess.md +6 -18
  107. package/docs/interfaces/FilePickerAcceptType.accept.md +9 -0
  108. package/docs/interfaces/FilePickerAcceptType.description.md +9 -0
  109. package/docs/interfaces/FilePickerAcceptType.md +54 -9
  110. package/docs/interfaces/FileSystemCreateWritableOptions.keepExistingData.md +9 -0
  111. package/docs/interfaces/FileSystemCreateWritableOptions.md +37 -8
  112. package/docs/interfaces/FileSystemDirectoryHandle._asyncIterator_.md +13 -0
  113. package/docs/interfaces/FileSystemDirectoryHandle.entries.md +13 -0
  114. package/docs/interfaces/FileSystemDirectoryHandle.getDirectoryHandle.md +21 -0
  115. package/docs/interfaces/FileSystemDirectoryHandle.getFileHandle.md +21 -0
  116. package/docs/interfaces/FileSystemDirectoryHandle.keys.md +13 -0
  117. package/docs/interfaces/FileSystemDirectoryHandle.kind.md +9 -0
  118. package/docs/interfaces/FileSystemDirectoryHandle.md +140 -103
  119. package/docs/interfaces/FileSystemDirectoryHandle.removeEntry.md +21 -0
  120. package/docs/interfaces/FileSystemDirectoryHandle.resolve.md +20 -0
  121. package/docs/interfaces/FileSystemDirectoryHandle.values.md +13 -0
  122. package/docs/interfaces/FileSystemFileHandle.createWritable.md +20 -0
  123. package/docs/interfaces/FileSystemFileHandle.getFile.md +13 -0
  124. package/docs/interfaces/FileSystemFileHandle.kind.md +9 -0
  125. package/docs/interfaces/FileSystemFileHandle.md +98 -58
  126. package/docs/interfaces/FileSystemGetDirectoryOptions.create.md +9 -0
  127. package/docs/interfaces/FileSystemGetDirectoryOptions.md +37 -8
  128. package/docs/interfaces/FileSystemGetFileOptions.create.md +9 -0
  129. package/docs/interfaces/FileSystemGetFileOptions.md +37 -8
  130. package/docs/interfaces/FileSystemHandle.isSameEntry.md +20 -0
  131. package/docs/interfaces/FileSystemHandle.kind.md +9 -0
  132. package/docs/interfaces/FileSystemHandle.md +88 -39
  133. package/docs/interfaces/FileSystemHandle.name.md +9 -0
  134. package/docs/interfaces/FileSystemHandle.queryPermission.md +20 -0
  135. package/docs/interfaces/FileSystemHandle.requestPermission.md +20 -0
  136. package/docs/interfaces/FileSystemHandlePermissionDescriptor.md +37 -8
  137. package/docs/interfaces/FileSystemHandlePermissionDescriptor.mode.md +9 -0
  138. package/docs/interfaces/FileSystemRemoveOptions.md +37 -8
  139. package/docs/interfaces/FileSystemRemoveOptions.recursive.md +9 -0
  140. package/docs/interfaces/FileSystemWritableFileStream.md +83 -68
  141. package/docs/interfaces/FileSystemWritableFileStream.seek.md +20 -0
  142. package/docs/interfaces/FileSystemWritableFileStream.truncate.md +20 -0
  143. package/docs/interfaces/FileSystemWritableFileStream.write.md +20 -0
  144. package/docs/interfaces/IDirectoryHandleTreeInitializer.dirHandles.md +9 -0
  145. package/docs/interfaces/IDirectoryHandleTreeInitializer.md +71 -10
  146. package/docs/interfaces/IDirectoryHandleTreeInitializer.nonRecursive.md +9 -0
  147. package/docs/interfaces/IDirectoryHandleTreeInitializer.prefix.md +9 -0
  148. package/docs/interfaces/IFileHandleTreeInitializer.fileHandles.md +9 -0
  149. package/docs/interfaces/IFileHandleTreeInitializer.md +54 -9
  150. package/docs/interfaces/IFileHandleTreeInitializer.prefix.md +9 -0
  151. package/docs/interfaces/IFileListTreeInitializer.fileList.md +9 -0
  152. package/docs/interfaces/IFileListTreeInitializer.md +37 -8
  153. package/docs/interfaces/IFileMetadata.lastModified.md +9 -0
  154. package/docs/interfaces/IFileMetadata.md +105 -12
  155. package/docs/interfaces/IFileMetadata.name.md +9 -0
  156. package/docs/interfaces/IFileMetadata.path.md +9 -0
  157. package/docs/interfaces/IFileMetadata.size.md +9 -0
  158. package/docs/interfaces/IFileMetadata.type.md +9 -0
  159. package/docs/interfaces/IFileSystemAccessTreeParams.autoSync.md +12 -0
  160. package/docs/interfaces/IFileSystemAccessTreeParams.filePath.md +13 -0
  161. package/docs/interfaces/IFileSystemAccessTreeParams.logger.md +11 -0
  162. package/docs/interfaces/IFileSystemAccessTreeParams.md +138 -20
  163. package/docs/interfaces/IFileSystemAccessTreeParams.requireWritePermission.md +13 -0
  164. package/docs/interfaces/IFsAccessApis.md +36 -31
  165. package/docs/interfaces/IFsAccessApis.showDirectoryPicker.md +20 -0
  166. package/docs/interfaces/IFsAccessApis.showOpenFilePicker.md +20 -0
  167. package/docs/interfaces/IFsAccessApis.showSaveFilePicker.md +20 -0
  168. package/docs/interfaces/IHttpTreeParams.autoSync.md +9 -0
  169. package/docs/interfaces/IHttpTreeParams.baseUrl.md +9 -0
  170. package/docs/interfaces/IHttpTreeParams.fetchImpl.md +9 -0
  171. package/docs/interfaces/IHttpTreeParams.logger.md +9 -0
  172. package/docs/interfaces/IHttpTreeParams.md +172 -22
  173. package/docs/interfaces/IHttpTreeParams.namespace.md +9 -0
  174. package/docs/interfaces/IHttpTreeParams.userId.md +9 -0
  175. package/docs/interfaces/ILocalStorageTreeParams.autoSync.md +12 -0
  176. package/docs/interfaces/ILocalStorageTreeParams.md +121 -20
  177. package/docs/interfaces/ILocalStorageTreeParams.pathToKeyMap.md +13 -0
  178. package/docs/interfaces/ILocalStorageTreeParams.storage.md +12 -0
  179. package/docs/interfaces/IUrlConfigOptions.config.md +11 -0
  180. package/docs/interfaces/IUrlConfigOptions.configStartDir.md +11 -0
  181. package/docs/interfaces/IUrlConfigOptions.contextFilter.md +11 -0
  182. package/docs/interfaces/IUrlConfigOptions.input.md +11 -0
  183. package/docs/interfaces/IUrlConfigOptions.inputStartDir.md +11 -0
  184. package/docs/interfaces/IUrlConfigOptions.interactive.md +11 -0
  185. package/docs/interfaces/IUrlConfigOptions.loadZip.md +11 -0
  186. package/docs/interfaces/IUrlConfigOptions.maxDistance.md +11 -0
  187. package/docs/interfaces/IUrlConfigOptions.md +241 -20
  188. package/docs/interfaces/IUrlConfigOptions.qualifierDefaults.md +11 -0
  189. package/docs/interfaces/IUrlConfigOptions.reduceQualifiers.md +11 -0
  190. package/docs/interfaces/IUrlConfigOptions.resourceTypes.md +11 -0
  191. package/docs/interfaces/IUrlConfigOptions.zipFile.md +11 -0
  192. package/docs/interfaces/IUrlConfigOptions.zipPath.md +11 -0
  193. package/docs/interfaces/ShowDirectoryPickerOptions.id.md +9 -0
  194. package/docs/interfaces/ShowDirectoryPickerOptions.md +71 -10
  195. package/docs/interfaces/ShowDirectoryPickerOptions.mode.md +9 -0
  196. package/docs/interfaces/ShowDirectoryPickerOptions.startIn.md +9 -0
  197. package/docs/interfaces/ShowOpenFilePickerOptions.excludeAcceptAllOption.md +9 -0
  198. package/docs/interfaces/ShowOpenFilePickerOptions.id.md +9 -0
  199. package/docs/interfaces/ShowOpenFilePickerOptions.md +105 -12
  200. package/docs/interfaces/ShowOpenFilePickerOptions.multiple.md +9 -0
  201. package/docs/interfaces/ShowOpenFilePickerOptions.startIn.md +9 -0
  202. package/docs/interfaces/ShowOpenFilePickerOptions.types.md +9 -0
  203. package/docs/interfaces/ShowSaveFilePickerOptions.excludeAcceptAllOption.md +9 -0
  204. package/docs/interfaces/ShowSaveFilePickerOptions.id.md +9 -0
  205. package/docs/interfaces/ShowSaveFilePickerOptions.md +105 -12
  206. package/docs/interfaces/ShowSaveFilePickerOptions.startIn.md +9 -0
  207. package/docs/interfaces/ShowSaveFilePickerOptions.suggestedName.md +9 -0
  208. package/docs/interfaces/ShowSaveFilePickerOptions.types.md +9 -0
  209. package/docs/type-aliases/TreeInitializer.md +7 -7
  210. package/docs/type-aliases/WellKnownDirectory.md +7 -7
  211. package/docs/type-aliases/WindowWithFsAccess.md +7 -7
  212. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_DB.md +5 -7
  213. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_STORE.md +5 -7
  214. package/docs/variables/defaultFileApiTreeInitParams.md +9 -0
  215. package/lib/packlets/file-tree/httpTreeAccessors.d.ts +6 -0
  216. package/lib/packlets/file-tree/httpTreeAccessors.d.ts.map +1 -1
  217. package/lib/packlets/file-tree/httpTreeAccessors.js +72 -42
  218. package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -1
  219. package/lib/test/unit/httpTreeAccessors.test.js +135 -0
  220. package/lib/test/unit/httpTreeAccessors.test.js.map +1 -1
  221. package/package.json +12 -11
  222. package/rush-logs/ts-web-extras.build.cache.log +1 -1
  223. package/rush-logs/ts-web-extras.build.log +18 -18
  224. package/src/packlets/file-tree/httpTreeAccessors.ts +76 -46
  225. package/src/test/unit/httpTreeAccessors.test.ts +179 -0
  226. package/temp/build/typescript/ts_8nwakTlr.json +1 -1
  227. package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +1 -1
  228. package/temp/coverage/crypto-utils/browserHashProvider.ts.html +1 -1
  229. package/temp/coverage/crypto-utils/index.html +1 -1
  230. package/temp/coverage/file-tree/directoryHandleStore.ts.html +1 -1
  231. package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +1 -1
  232. package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
  233. package/temp/coverage/file-tree/httpTreeAccessors.ts.html +333 -243
  234. package/temp/coverage/file-tree/index.html +11 -11
  235. package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +1 -1
  236. package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
  237. package/temp/coverage/helpers/index.html +1 -1
  238. package/temp/coverage/index.html +10 -10
  239. package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +1 -1
  240. package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +1 -1
  241. package/temp/coverage/lcov-report/crypto-utils/index.html +1 -1
  242. package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +1 -1
  243. package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +1 -1
  244. package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
  245. package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +333 -243
  246. package/temp/coverage/lcov-report/file-tree/index.html +11 -11
  247. package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +1 -1
  248. package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
  249. package/temp/coverage/lcov-report/helpers/index.html +1 -1
  250. package/temp/coverage/lcov-report/index.html +10 -10
  251. package/temp/coverage/lcov-report/url-utils/index.html +1 -1
  252. package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
  253. package/temp/coverage/lcov.info +470 -437
  254. package/temp/coverage/url-utils/index.html +1 -1
  255. package/temp/coverage/url-utils/urlParams.ts.html +1 -1
  256. package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
  257. package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +1 -1
  258. package/temp/ts-web-extras.api.json +1 -1
  259. package/docs/@fgv/namespaces/CryptoUtils/README.md +0 -18
  260. package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserCryptoProvider.md +0 -203
  261. package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserHashProvider.md +0 -63
  262. package/docs/@fgv/namespaces/CryptoUtils/functions/createBrowserCryptoProvider.md +0 -18
  263. package/docs/@fgv/namespaces/FileTreeHelpers/README.md +0 -19
  264. package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileListMetadata.md +0 -23
  265. package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileMetadata.md +0 -23
  266. package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromDirectoryUpload.md +0 -33
  267. package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromFileList.md +0 -33
  268. package/docs/@fgv/namespaces/FileTreeHelpers/functions/getOriginalFile.md +0 -25
  269. package/docs/@fgv/namespaces/FileTreeHelpers/variables/defaultFileApiTreeInitParams.md +0 -11
  270. /package/temp/test/jest/jest-transform-cache-7492f1b44480e0cdd1f220078fb3afd8-79ef2876fae7ca75eedb2aa53dc48338/{d6/package_d6e3b0fa94752e16b0b2a2777739b973 → 7c/package_7c16afc8299e635d80273763175c7a50} +0 -0
@@ -80,6 +80,8 @@ class HttpTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAccessors {
80
80
  */
81
81
  async syncToDisk() {
82
82
  if (this._syncPromise) {
83
+ // Wait for the in-flight sync — it drains the queue in a loop,
84
+ // so any items added before it finishes will be included.
83
85
  return this._syncPromise;
84
86
  }
85
87
  this._syncPromise = this._doSync().finally(() => {
@@ -88,57 +90,85 @@ class HttpTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAccessors {
88
90
  return this._syncPromise;
89
91
  }
90
92
  async _doSync() {
91
- if (this._dirtyFiles.size === 0 && this._pendingDeletions.size === 0) {
92
- return (0, ts_utils_1.succeed)(undefined);
93
- }
94
- // Snapshot and clear dirty sets so that changes arriving during
95
- // the async sync are not dropped when we finish.
96
- const deletions = new Set(this._pendingDeletions);
97
- const dirty = new Set(this._dirtyFiles);
98
- this._pendingDeletions.clear();
99
- this._dirtyFiles.clear();
100
- for (const path of deletions) {
101
- const query = new URLSearchParams();
102
- query.set('path', path);
103
- if (this._namespace) {
104
- query.set('namespace', this._namespace);
93
+ // Drain loop: keep processing as long as new items arrive.
94
+ // This is critical for bulk operations (e.g. reset) where many
95
+ // deleteFile/saveFileContents calls happen synchronously — only
96
+ // the first may be in the set when we snapshot, but the rest
97
+ // arrive during the async gaps and must be picked up before
98
+ // we return.
99
+ let didWork = false;
100
+ while (this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0) {
101
+ didWork = true;
102
+ // Snapshot and clear so that changes arriving during the async
103
+ // requests land in the live sets for the next iteration.
104
+ const deletions = new Set(this._pendingDeletions);
105
+ const dirty = new Set(this._dirtyFiles);
106
+ this._pendingDeletions.clear();
107
+ this._dirtyFiles.clear();
108
+ for (const path of deletions) {
109
+ const query = new URLSearchParams();
110
+ query.set('path', path);
111
+ if (this._namespace) {
112
+ query.set('namespace', this._namespace);
113
+ }
114
+ const deleteResult = await this._requestWithRetry(`/file?${query.toString()}`, {
115
+ method: 'DELETE'
116
+ });
117
+ if (deleteResult.isFailure()) {
118
+ this._restoreUnsynced(deletions, dirty);
119
+ return (0, ts_utils_1.fail)(`delete ${path}: ${deleteResult.message}`);
120
+ }
105
121
  }
106
- const deleteResult = await this._requestWithRetry(`/file?${query.toString()}`, {
107
- method: 'DELETE'
108
- });
109
- if (deleteResult.isFailure()) {
110
- return (0, ts_utils_1.fail)(`delete ${path}: ${deleteResult.message}`);
122
+ for (const path of dirty) {
123
+ const contentsResult = this.getFileContents(path);
124
+ if (contentsResult.isFailure()) {
125
+ this._restoreUnsynced(deletions, dirty);
126
+ return (0, ts_utils_1.fail)(`${path}: ${contentsResult.message}`);
127
+ }
128
+ const body = {
129
+ path,
130
+ contents: contentsResult.value
131
+ };
132
+ if (this._namespace) {
133
+ body.namespace = this._namespace;
134
+ }
135
+ const saveResult = await this._requestWithRetry('/file', {
136
+ method: 'PUT',
137
+ body: JSON.stringify(body)
138
+ });
139
+ if (saveResult.isFailure()) {
140
+ this._restoreUnsynced(deletions, dirty);
141
+ return (0, ts_utils_1.fail)(`sync ${path}: ${saveResult.message}`);
142
+ }
111
143
  }
112
144
  }
113
- for (const path of dirty) {
114
- const contentsResult = this.getFileContents(path);
115
- if (contentsResult.isFailure()) {
116
- return (0, ts_utils_1.fail)(`${path}: ${contentsResult.message}`);
117
- }
118
- const body = {
119
- path,
120
- contents: contentsResult.value
121
- };
145
+ if (didWork) {
146
+ const syncBody = {};
122
147
  if (this._namespace) {
123
- body.namespace = this._namespace;
148
+ syncBody.namespace = this._namespace;
124
149
  }
125
- const saveResult = await this._requestWithRetry('/file', {
126
- method: 'PUT',
127
- body: JSON.stringify(body)
150
+ const syncResult = await this._requestWithRetry('/sync', {
151
+ method: 'POST',
152
+ body: JSON.stringify(syncBody)
128
153
  });
129
- if (saveResult.isFailure()) {
130
- return (0, ts_utils_1.fail)(`sync ${path}: ${saveResult.message}`);
154
+ if (syncResult.isFailure()) {
155
+ return (0, ts_utils_1.fail)(syncResult.message);
131
156
  }
132
157
  }
133
- const syncBody = {};
134
- if (this._namespace) {
135
- syncBody.namespace = this._namespace;
158
+ return (0, ts_utils_1.succeed)(undefined);
159
+ }
160
+ /**
161
+ * Restores snapshotted items back into the live dirty sets so they
162
+ * are retried on the next sync attempt. Items that were added to
163
+ * the live sets while the sync was in flight are preserved.
164
+ */
165
+ _restoreUnsynced(deletions, dirty) {
166
+ for (const path of deletions) {
167
+ this._pendingDeletions.add(path);
168
+ }
169
+ for (const path of dirty) {
170
+ this._dirtyFiles.add(path);
136
171
  }
137
- const syncResult = await this._requestWithRetry('/sync', {
138
- method: 'POST',
139
- body: JSON.stringify(syncBody)
140
- });
141
- return syncResult.isFailure() ? (0, ts_utils_1.fail)(syncResult.message) : (0, ts_utils_1.succeed)(undefined);
142
172
  }
143
173
  /**
144
174
  * Checks if there are any dirty files that need synchronization.
@@ -1 +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;IAe3C,YAAoB,KAAoC,EAAE,MAA4B;;QACpF,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAVN,gBAAW,GAAgB,IAAI,GAAG,EAAE,CAAC;QACrC,sBAAiB,GAAgB,IAAI,GAAG,EAAE,CAAC;QAU1D,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,cAAc,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,CAAC,SAAS,GAAG,MAAA,MAAM,CAAC,QAAQ,mCAAI,KAAK,CAAC;QAC1C,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,MAAA,MAAM,CAAC,MAAM,mCAAI,IAAI,kBAAO,CAAC,WAAW,EAAW,CAAC;IACrE,CAAC;IAE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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;AA3XD,8CA2XC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, type Result, succeed, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\n\ninterface IHttpStorageTreeItem {\n readonly path: string;\n readonly name: string;\n readonly type: 'file' | 'directory';\n}\n\ninterface IHttpStorageTreeChildrenResponse {\n readonly path: string;\n readonly children: ReadonlyArray<IHttpStorageTreeItem>;\n}\n\ninterface IHttpStorageFileResponse {\n readonly path: string;\n readonly contents: string;\n readonly contentType?: string;\n}\n\ninterface IHttpStorageSyncResponse {\n readonly synced: number;\n}\n\nfunction normalizeFetch(fetchImpl?: typeof fetch): typeof fetch {\n const resolved = fetchImpl ?? globalThis.fetch;\n return resolved.bind(globalThis) as typeof fetch;\n}\n\n/**\n * Configuration for creating HTTP-backed tree accessors.\n * @public\n */\nexport interface IHttpTreeParams<TCT extends string = string> extends FileTree.IFileTreeInitParams<TCT> {\n readonly baseUrl: string;\n readonly namespace?: string;\n readonly autoSync?: boolean;\n readonly fetchImpl?: typeof fetch;\n readonly userId?: string;\n readonly logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * HTTP-backed file tree accessors that cache data in memory and persist via REST API.\n * @public\n */\nexport class HttpTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _baseUrl: string;\n private readonly _namespace: string | undefined;\n private readonly _fetchImpl: typeof fetch;\n private readonly _dirtyFiles: Set<string> = new Set();\n private readonly _pendingDeletions: Set<string> = new Set();\n private readonly _autoSync: boolean;\n private readonly _userId: string | undefined;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /** Guards against concurrent syncToDisk calls (thundering herd from autoSync). */\n private _syncPromise: Promise<Result<void>> | undefined;\n\n private constructor(files: FileTree.IInMemoryFile<TCT>[], params: IHttpTreeParams<TCT>) {\n super(files, params);\n this._baseUrl = params.baseUrl.replace(/\\/$/, '');\n this._namespace = params.namespace;\n this._fetchImpl = normalizeFetch(params.fetchImpl);\n this._autoSync = params.autoSync ?? false;\n this._userId = params.userId;\n this._logger = params.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(path: string): Promise<void> {\n try {\n const result = await this.syncToDisk();\n if (result.isFailure()) {\n this._logger.error(`Auto-sync failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-sync threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new HttpTreeAccessors instance from an HTTP backend.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @returns A promise that resolves to a result containing the new HttpTreeAccessors instance or an error message.\n */\n public static async fromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<HttpTreeAccessors<TCT>>> {\n const filesResult = await this._loadFiles<TCT>(params, '/');\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n return succeed(new HttpTreeAccessors<TCT>(filesResult.value, params));\n }\n\n /**\n * Synchronizes all dirty files to the HTTP backend.\n *\n * Uses a concurrency guard: if a sync is already in progress, callers\n * await the existing operation rather than starting a parallel one.\n * This prevents the thundering herd that occurs when autoSync fires\n * for every file written during a bulk operation (e.g. restore).\n *\n * @returns A promise that resolves to a result indicating success or failure.\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._syncPromise) {\n return this._syncPromise;\n }\n\n this._syncPromise = this._doSync().finally(() => {\n this._syncPromise = undefined;\n });\n return this._syncPromise;\n }\n\n private async _doSync(): Promise<Result<void>> {\n if (this._dirtyFiles.size === 0 && this._pendingDeletions.size === 0) {\n return succeed(undefined);\n }\n\n // Snapshot and clear dirty sets so that changes arriving during\n // the async sync are not dropped when we finish.\n const deletions = new Set(this._pendingDeletions);\n const dirty = new Set(this._dirtyFiles);\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n\n for (const path of deletions) {\n const query = new URLSearchParams();\n query.set('path', path);\n if (this._namespace) {\n query.set('namespace', this._namespace);\n }\n\n const deleteResult = await this._requestWithRetry<{ deleted: boolean }>(`/file?${query.toString()}`, {\n method: 'DELETE'\n });\n if (deleteResult.isFailure()) {\n return fail(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of dirty) {\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n return fail(`${path}: ${contentsResult.message}`);\n }\n\n const body: Record<string, unknown> = {\n path,\n contents: contentsResult.value\n };\n if (this._namespace) {\n body.namespace = this._namespace;\n }\n\n const saveResult = await this._requestWithRetry<IHttpStorageFileResponse>('/file', {\n method: 'PUT',\n body: JSON.stringify(body)\n });\n if (saveResult.isFailure()) {\n return fail(`sync ${path}: ${saveResult.message}`);\n }\n }\n\n const syncBody: Record<string, unknown> = {};\n if (this._namespace) {\n syncBody.namespace = this._namespace;\n }\n\n const syncResult = await this._requestWithRetry<IHttpStorageSyncResponse>('/sync', {\n method: 'POST',\n body: JSON.stringify(syncBody)\n });\n\n 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 body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n return succeed(json as T);\n }\n\n /**\n * Wraps `_request` with retry logic for transient failures\n * (network errors, 503 service unavailable, etc.).\n */\n private async _requestWithRetry<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const maxAttempts = 3;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const result = await this._request<T>(resourcePath, init);\n if (result.isSuccess() || attempt === maxAttempts) {\n return result;\n }\n // Retry on transient-looking errors\n const msg = result.message;\n const lowerMsg = msg.toLowerCase();\n const isTransient =\n msg.includes('503') ||\n msg.includes('502') ||\n msg.includes('429') ||\n lowerMsg.includes('disconnect') ||\n lowerMsg.includes('econnreset') ||\n lowerMsg.includes('failed to fetch') ||\n lowerMsg.includes('network');\n if (!isTransient) {\n return result;\n }\n // Exponential backoff: 500ms, 1000ms\n const delayMs = 500 * Math.pow(2, attempt - 1);\n this._logger.detail(\n `Retrying ${\n init?.method ?? 'GET'\n } ${resourcePath} after ${delayMs}ms (attempt ${attempt}/${maxAttempts})`\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n /* c8 ignore next 1 - defensive coding: loop always returns */\n return fail('retry loop exited unexpectedly');\n }\n\n /**\n * Loads files from the HTTP backend for the specified directory path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param directoryPath - The path to the directory to load files from.\n * @returns A promise that resolves to a result containing the loaded files or an error message.\n */\n private static async _loadFiles<TCT extends string = string>(\n params: IHttpTreeParams<TCT>,\n directoryPath: string\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const childrenResult = await this._requestWithParams<IHttpStorageTreeChildrenResponse>(\n params,\n '/tree/children',\n {\n path: directoryPath,\n namespace: params.namespace\n }\n );\n if (childrenResult.isFailure()) {\n return fail(childrenResult.message);\n }\n\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const item of childrenResult.value.children) {\n if (item.type === 'directory') {\n const nestedResult = await this._loadFiles(params, item.path);\n if (nestedResult.isFailure()) {\n return fail(nestedResult.message);\n }\n allFiles.push(...nestedResult.value);\n } else {\n const fileResult = await this._requestWithParams<IHttpStorageFileResponse>(params, '/file', {\n path: item.path,\n namespace: params.namespace\n });\n if (fileResult.isFailure()) {\n return fail(fileResult.message);\n }\n\n const contentType = params.inferContentType?.(item.path, fileResult.value.contentType).orDefault();\n allFiles.push({\n path: item.path,\n contents: fileResult.value.contents,\n contentType\n });\n }\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Makes an HTTP request with query parameters to the specified resource path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param resourcePath - The path to the resource.\n * @param query - Query parameters to include in the request.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private static async _requestWithParams<T>(\n params: IHttpTreeParams,\n resourcePath: string,\n query: Record<string, string | undefined>\n ): Promise<Result<T>> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n search.set(key, value);\n }\n }\n\n const fetchImpl = normalizeFetch(params.fetchImpl);\n const userIdHeaders: RequestInit | undefined = /* c8 ignore next */ params.userId\n ? { headers: { 'X-User-Id': params.userId } }\n : undefined;\n const response = await fetchImpl(\n `${params.baseUrl.replace(/\\/$/, '')}${resourcePath}?${search.toString()}`,\n userIdHeaders\n ).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n\n return succeed(json as T);\n }\n}\n"]}
1
+ {"version":3,"file":"httpTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/httpTreeAccessors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,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;IAe3C,YAAoB,KAAoC,EAAE,MAA4B;;QACpF,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAVN,gBAAW,GAAgB,IAAI,GAAG,EAAE,CAAC;QACrC,sBAAiB,GAAgB,IAAI,GAAG,EAAE,CAAC;QAU1D,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,cAAc,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,CAAC,SAAS,GAAG,MAAA,MAAM,CAAC,QAAQ,mCAAI,KAAK,CAAC;Q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M,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,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YACnD,MAAM,OAAO,GAAG,IAAI;gBAClB,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,KAAK,IAAI,EAAE;gBACpC,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;YACrD,OAAO,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;AAzZD,8CAyZC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, type Result, succeed, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\n\ninterface IHttpStorageTreeItem {\n readonly path: string;\n readonly name: string;\n readonly type: 'file' | 'directory';\n}\n\ninterface IHttpStorageTreeChildrenResponse {\n readonly path: string;\n readonly children: ReadonlyArray<IHttpStorageTreeItem>;\n}\n\ninterface IHttpStorageFileResponse {\n readonly path: string;\n readonly contents: string;\n readonly contentType?: string;\n}\n\ninterface IHttpStorageSyncResponse {\n readonly synced: number;\n}\n\nfunction normalizeFetch(fetchImpl?: typeof fetch): typeof fetch {\n const resolved = fetchImpl ?? globalThis.fetch;\n return resolved.bind(globalThis) as typeof fetch;\n}\n\n/**\n * Configuration for creating HTTP-backed tree accessors.\n * @public\n */\nexport interface IHttpTreeParams<TCT extends string = string> extends FileTree.IFileTreeInitParams<TCT> {\n readonly baseUrl: string;\n readonly namespace?: string;\n readonly autoSync?: boolean;\n readonly fetchImpl?: typeof fetch;\n readonly userId?: string;\n readonly logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * HTTP-backed file tree accessors that cache data in memory and persist via REST API.\n * @public\n */\nexport class HttpTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _baseUrl: string;\n private readonly _namespace: string | undefined;\n private readonly _fetchImpl: typeof fetch;\n private readonly _dirtyFiles: Set<string> = new Set();\n private readonly _pendingDeletions: Set<string> = new Set();\n private readonly _autoSync: boolean;\n private readonly _userId: string | undefined;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /** Guards against concurrent syncToDisk calls (thundering herd from autoSync). */\n private _syncPromise: Promise<Result<void>> | undefined;\n\n private constructor(files: FileTree.IInMemoryFile<TCT>[], params: IHttpTreeParams<TCT>) {\n super(files, params);\n this._baseUrl = params.baseUrl.replace(/\\/$/, '');\n this._namespace = params.namespace;\n this._fetchImpl = normalizeFetch(params.fetchImpl);\n this._autoSync = params.autoSync ?? false;\n this._userId = params.userId;\n this._logger = params.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(path: string): Promise<void> {\n try {\n const result = await this.syncToDisk();\n if (result.isFailure()) {\n this._logger.error(`Auto-sync failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-sync threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new HttpTreeAccessors instance from an HTTP backend.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @returns A promise that resolves to a result containing the new HttpTreeAccessors instance or an error message.\n */\n public static async fromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<HttpTreeAccessors<TCT>>> {\n const filesResult = await this._loadFiles<TCT>(params, '/');\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n return succeed(new HttpTreeAccessors<TCT>(filesResult.value, params));\n }\n\n /**\n * Synchronizes all dirty files to the HTTP backend.\n *\n * Uses a concurrency guard: if a sync is already in progress, callers\n * await the existing operation rather than starting a parallel one.\n * This prevents the thundering herd that occurs when autoSync fires\n * for every file written during a bulk operation (e.g. restore).\n *\n * @returns A promise that resolves to a result indicating success or failure.\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._syncPromise) {\n // Wait for the in-flight sync — it drains the queue in a loop,\n // so any items added before it finishes will be included.\n return this._syncPromise;\n }\n\n this._syncPromise = this._doSync().finally(() => {\n this._syncPromise = undefined;\n });\n return this._syncPromise;\n }\n\n private async _doSync(): Promise<Result<void>> {\n // Drain loop: keep processing as long as new items arrive.\n // This is critical for bulk operations (e.g. reset) where many\n // deleteFile/saveFileContents calls happen synchronously — only\n // the first may be in the set when we snapshot, but the rest\n // arrive during the async gaps and must be picked up before\n // we return.\n let didWork = false;\n while (this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0) {\n didWork = true;\n // Snapshot and clear so that changes arriving during the async\n // requests land in the live sets for the next iteration.\n const deletions = new Set(this._pendingDeletions);\n const dirty = new Set(this._dirtyFiles);\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n\n for (const path of deletions) {\n const query = new URLSearchParams();\n query.set('path', path);\n if (this._namespace) {\n query.set('namespace', this._namespace);\n }\n\n const deleteResult = await this._requestWithRetry<{ deleted: boolean }>(`/file?${query.toString()}`, {\n method: 'DELETE'\n });\n if (deleteResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of dirty) {\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`${path}: ${contentsResult.message}`);\n }\n\n const body: Record<string, unknown> = {\n path,\n contents: contentsResult.value\n };\n if (this._namespace) {\n body.namespace = this._namespace;\n }\n\n const saveResult = await this._requestWithRetry<IHttpStorageFileResponse>('/file', {\n method: 'PUT',\n body: JSON.stringify(body)\n });\n if (saveResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`sync ${path}: ${saveResult.message}`);\n }\n }\n }\n\n if (didWork) {\n const syncBody: Record<string, unknown> = {};\n if (this._namespace) {\n syncBody.namespace = this._namespace;\n }\n\n const syncResult = await this._requestWithRetry<IHttpStorageSyncResponse>('/sync', {\n method: 'POST',\n body: JSON.stringify(syncBody)\n });\n\n if (syncResult.isFailure()) {\n return fail(syncResult.message);\n }\n }\n return succeed(undefined);\n }\n\n /**\n * Restores snapshotted items back into the live dirty sets so they\n * are retried on the next sync attempt. Items that were added to\n * the live sets while the sync was in flight are preserved.\n */\n private _restoreUnsynced(deletions: Set<string>, dirty: Set<string>): void {\n for (const path of deletions) {\n this._pendingDeletions.add(path);\n }\n for (const path of dirty) {\n this._dirtyFiles.add(path);\n }\n }\n\n /**\n * Checks if there are any dirty files that need synchronization.\n * @returns True if there are dirty files, false otherwise.\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Gets the list of paths for all dirty files.\n * @returns An array of file paths that have been modified but not yet synchronized.\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.delete(path);\n this._pendingDeletions.add(path);\n\n if (!this._autoSync) {\n return result;\n }\n\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Saves file contents and marks the file as dirty for synchronization.\n * @param path - The path to the file.\n * @param contents - The new contents of the file.\n * @returns A result indicating success or failure.\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.add(path);\n if (!this._autoSync) {\n return result;\n }\n\n // fire-and-log-on-failure automatic sync for immediate persistence workflow\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Checks if a file is mutable (can be modified).\n * @param path - The path to the file.\n * @returns A detailed result indicating if the file is mutable and the reason.\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const result = super.fileIsMutable(path);\n if (result.isSuccess() && result.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return result;\n }\n\n /**\n * Makes an HTTP request to the specified resource path.\n * @param resourcePath - The path to the resource.\n * @param init - Optional request initialization options.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private async _request<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const response = await this._fetchImpl(`${this._baseUrl}${resourcePath}`, {\n headers: {\n 'Content-Type': 'application/json',\n ...(this._userId ? { 'X-User-Id': this._userId } : {}),\n /* c8 ignore next 1 - defensive coding: init.headers is never set by current callers */\n ...(init?.headers ?? {})\n },\n ...init\n }).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n return succeed(json as T);\n }\n\n /**\n * Wraps `_request` with retry logic for transient failures\n * (network errors, 503 service unavailable, etc.).\n */\n private async _requestWithRetry<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const maxAttempts = 3;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const result = await this._request<T>(resourcePath, init);\n if (result.isSuccess() || attempt === maxAttempts) {\n return result;\n }\n // Retry on transient-looking errors\n const msg = result.message;\n const lowerMsg = msg.toLowerCase();\n const isTransient =\n msg.includes('503') ||\n msg.includes('502') ||\n msg.includes('429') ||\n lowerMsg.includes('disconnect') ||\n lowerMsg.includes('econnreset') ||\n lowerMsg.includes('failed to fetch') ||\n lowerMsg.includes('network');\n if (!isTransient) {\n return result;\n }\n // Exponential backoff: 500ms, 1000ms\n const delayMs = 500 * Math.pow(2, attempt - 1);\n this._logger.detail(\n `Retrying ${\n init?.method ?? 'GET'\n } ${resourcePath} after ${delayMs}ms (attempt ${attempt}/${maxAttempts})`\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n /* c8 ignore next 1 - defensive coding: loop always returns */\n return fail('retry loop exited unexpectedly');\n }\n\n /**\n * Loads files from the HTTP backend for the specified directory path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param directoryPath - The path to the directory to load files from.\n * @returns A promise that resolves to a result containing the loaded files or an error message.\n */\n private static async _loadFiles<TCT extends string = string>(\n params: IHttpTreeParams<TCT>,\n directoryPath: string\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const childrenResult = await this._requestWithParams<IHttpStorageTreeChildrenResponse>(\n params,\n '/tree/children',\n {\n path: directoryPath,\n namespace: params.namespace\n }\n );\n if (childrenResult.isFailure()) {\n return fail(childrenResult.message);\n }\n\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const item of childrenResult.value.children) {\n if (item.type === 'directory') {\n const nestedResult = await this._loadFiles(params, item.path);\n if (nestedResult.isFailure()) {\n return fail(nestedResult.message);\n }\n allFiles.push(...nestedResult.value);\n } else {\n const fileResult = await this._requestWithParams<IHttpStorageFileResponse>(params, '/file', {\n path: item.path,\n namespace: params.namespace\n });\n if (fileResult.isFailure()) {\n return fail(fileResult.message);\n }\n\n const contentType = params.inferContentType?.(item.path, fileResult.value.contentType).orDefault();\n allFiles.push({\n path: item.path,\n contents: fileResult.value.contents,\n contentType\n });\n }\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Makes an HTTP request with query parameters to the specified resource path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param resourcePath - The path to the resource.\n * @param query - Query parameters to include in the request.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private static async _requestWithParams<T>(\n params: IHttpTreeParams,\n resourcePath: string,\n query: Record<string, string | undefined>\n ): Promise<Result<T>> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n search.set(key, value);\n }\n }\n\n const fetchImpl = normalizeFetch(params.fetchImpl);\n const userIdHeaders: RequestInit | undefined = /* c8 ignore next */ params.userId\n ? { headers: { 'X-User-Id': params.userId } }\n : undefined;\n const response = await fetchImpl(\n `${params.baseUrl.replace(/\\/$/, '')}${resourcePath}?${search.toString()}`,\n userIdHeaders\n ).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n\n return succeed(json as T);\n }\n}\n"]}
@@ -1226,6 +1226,141 @@ describe('HttpTreeAccessors', () => {
1226
1226
  expect(putCalls).toHaveLength(1);
1227
1227
  expect(postCalls).toHaveLength(1);
1228
1228
  });
1229
+ test('drains items written during an in-flight sync within the same _doSync call', async () => {
1230
+ // This tests the drain loop fix for the race where:
1231
+ // 1. sync starts, snapshots dirty set {a.json}
1232
+ // 2. during the PUT for a.json, a new write arrives adding a.json back
1233
+ // 3. _doSync loops back, snapshots the new item, and syncs it too
1234
+ // 4. Only one POST /sync is sent at the end, after all items are drained
1235
+ let callCount = 0;
1236
+ let saveHook;
1237
+ const fetchImpl = (url, init) => {
1238
+ callCount++;
1239
+ const urlStr = url.toString();
1240
+ // Calls 1-2: fromHttp load
1241
+ if (callCount <= 2) {
1242
+ if (callCount === 1) {
1243
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('a.json') }));
1244
+ }
1245
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/a.json', '"orig"') }));
1246
+ }
1247
+ // Call 3: first PUT /file for a.json — trigger a write mid-sync
1248
+ if (callCount === 3 && (init === null || init === void 0 ? void 0 : init.method) === 'PUT') {
1249
+ saveHook === null || saveHook === void 0 ? void 0 : saveHook();
1250
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/a.json', '"v1"') }));
1251
+ }
1252
+ // Call 4: second PUT /file for a.json (drain loop iteration)
1253
+ if (callCount === 4 && (init === null || init === void 0 ? void 0 : init.method) === 'PUT') {
1254
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/a.json', '"v2"') }));
1255
+ }
1256
+ // Call 5: single POST /sync after drain loop exits
1257
+ if (callCount === 5 && urlStr.includes('/sync')) {
1258
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: { synced: 1 } }));
1259
+ }
1260
+ return Promise.reject(new Error(`Unexpected call #${callCount} to ${urlStr}`));
1261
+ };
1262
+ const accessors = (await file_tree_1.HttpTreeAccessors.fromHttp({
1263
+ baseUrl: 'http://localhost:3000',
1264
+ fetchImpl: fetchImpl,
1265
+ mutable: true
1266
+ })).orThrow();
1267
+ // Write a.json
1268
+ accessors.saveFileContents('/a.json', '"v1"').orThrow();
1269
+ // Set up the hook BEFORE starting sync — the mock fetch for the PUT
1270
+ // runs synchronously within syncToDisk(), so the hook must be in place.
1271
+ saveHook = () => {
1272
+ accessors.saveFileContents('/a.json', '"v2"').orThrow();
1273
+ };
1274
+ // Start sync — during the first PUT, saveHook fires and writes v2.
1275
+ // The drain loop in _doSync picks this up and PUTs again before
1276
+ // sending the final POST /sync.
1277
+ const result = await accessors.syncToDisk();
1278
+ expect(result).toSucceed();
1279
+ expect(accessors.isDirty()).toBe(false);
1280
+ // 5 calls: 2 load + 2 PUTs (v1, v2) + 1 POST /sync
1281
+ expect(callCount).toBe(5);
1282
+ });
1283
+ });
1284
+ describe('syncToDisk() error recovery', () => {
1285
+ test('restores dirty files when PUT fails so they can be retried', async () => {
1286
+ const { fetchImpl } = makeMockFetch([
1287
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1288
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1289
+ // PUT /file fails with non-transient error
1290
+ { ok: false, status: 500, textValue: 'Server Error' }
1291
+ ]);
1292
+ const accessors = (await file_tree_1.HttpTreeAccessors.fromHttp({
1293
+ baseUrl: 'http://localhost:3000',
1294
+ fetchImpl,
1295
+ mutable: true
1296
+ })).orThrow();
1297
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1298
+ expect(accessors.isDirty()).toBe(true);
1299
+ const result = await accessors.syncToDisk();
1300
+ expect(result).toFailWith(/sync.*data\.json.*server error/i);
1301
+ // The file should still be dirty so a retry is possible
1302
+ expect(accessors.isDirty()).toBe(true);
1303
+ expect(accessors.getDirtyPaths()).toContain('/data.json');
1304
+ });
1305
+ test('restores pending deletions when DELETE fails so they can be retried', async () => {
1306
+ const { fetchImpl } = makeMockFetch([
1307
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1308
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1309
+ // DELETE fails with non-transient error
1310
+ { ok: false, status: 500, textValue: 'Server Error' }
1311
+ ]);
1312
+ const accessors = (await file_tree_1.HttpTreeAccessors.fromHttp({
1313
+ baseUrl: 'http://localhost:3000',
1314
+ fetchImpl,
1315
+ mutable: true
1316
+ })).orThrow();
1317
+ accessors.deleteFile('/data.json').orThrow();
1318
+ expect(accessors.isDirty()).toBe(true);
1319
+ const result = await accessors.syncToDisk();
1320
+ expect(result).toFailWith(/delete.*data\.json.*server error/i);
1321
+ // The deletion should still be pending so a retry is possible
1322
+ expect(accessors.isDirty()).toBe(true);
1323
+ expect(accessors.getDirtyPaths()).toContain('/data.json');
1324
+ });
1325
+ test('restores dirty files when POST /sync fails so they can be retried', async () => {
1326
+ jest.useFakeTimers();
1327
+ try {
1328
+ let callCount = 0;
1329
+ const fetchImpl = (_url, _init) => {
1330
+ callCount++;
1331
+ if (callCount === 1) {
1332
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1333
+ }
1334
+ if (callCount === 2) {
1335
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') }));
1336
+ }
1337
+ if (callCount === 3) {
1338
+ // PUT succeeds
1339
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '"v2"') }));
1340
+ }
1341
+ // All /sync attempts: persistent 503
1342
+ return Promise.resolve(makeMockResponse({ ok: false, status: 503, textValue: 'Service Unavailable' }));
1343
+ };
1344
+ const accessors = (await file_tree_1.HttpTreeAccessors.fromHttp({
1345
+ baseUrl: 'http://localhost:3000',
1346
+ fetchImpl,
1347
+ mutable: true
1348
+ })).orThrow();
1349
+ accessors.saveFileContents('/data.json', '"v2"').orThrow();
1350
+ const syncPromise = accessors.syncToDisk();
1351
+ await jest.advanceTimersByTimeAsync(1500);
1352
+ const result = await syncPromise;
1353
+ expect(result).toFailWith(/service unavailable/i);
1354
+ // The PUT succeeded — data is on the server — so the file is no
1355
+ // longer dirty. Only the server-side /sync acknowledgement failed,
1356
+ // which is not something the client can meaningfully retry via
1357
+ // re-sending the file contents.
1358
+ expect(accessors.isDirty()).toBe(false);
1359
+ }
1360
+ finally {
1361
+ jest.useRealTimers();
1362
+ }
1363
+ });
1229
1364
  });
1230
1365
  });
1231
1366
  //# sourceMappingURL=httpTreeAccessors.test.js.map