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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (383) hide show
  1. package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +58 -25
  2. package/.rush/temp/chunked-rush-logs/ts-web-extras.test.chunks.jsonl +70 -0
  3. package/.rush/temp/operation/build/all.log +58 -25
  4. package/.rush/temp/operation/build/error.log +18 -0
  5. package/.rush/temp/operation/build/log-chunks.jsonl +58 -25
  6. package/.rush/temp/operation/build/state.json +1 -1
  7. package/.rush/temp/operation/test/all.log +70 -0
  8. package/.rush/temp/operation/test/error.log +16 -0
  9. package/.rush/temp/operation/test/log-chunks.jsonl +70 -0
  10. package/.rush/temp/operation/test/state.json +3 -0
  11. package/.rush/temp/shrinkwrap-deps.json +175 -163
  12. package/config/jest.config.json +4 -1
  13. package/config/typedoc.json +6 -0
  14. package/dist/index.js +2 -2
  15. package/dist/index.js.map +1 -1
  16. package/dist/packlets/crypto-utils/browserCryptoProvider.js +254 -0
  17. package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -0
  18. package/dist/packlets/crypto-utils/browserHashProvider.js.map +1 -0
  19. package/dist/packlets/{crypto → crypto-utils}/index.js +1 -0
  20. package/dist/packlets/crypto-utils/index.js.map +1 -0
  21. package/dist/packlets/file-api-types/index.js +27 -3
  22. package/dist/packlets/file-api-types/index.js.map +1 -1
  23. package/dist/packlets/file-tree/directoryHandleStore.js +124 -0
  24. package/dist/packlets/file-tree/directoryHandleStore.js.map +1 -0
  25. package/dist/packlets/file-tree/fileApiTreeAccessors.js +91 -0
  26. package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  27. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js +414 -0
  28. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -0
  29. package/dist/packlets/file-tree/httpTreeAccessors.js +279 -0
  30. package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -0
  31. package/dist/packlets/file-tree/index.js +4 -0
  32. package/dist/packlets/file-tree/index.js.map +1 -1
  33. package/dist/packlets/file-tree/localStorageTreeAccessors.js +359 -0
  34. package/dist/packlets/file-tree/localStorageTreeAccessors.js.map +1 -0
  35. package/dist/test/mocks/idb-keyval.js +6 -0
  36. package/dist/test/mocks/idb-keyval.js.map +1 -0
  37. package/dist/test/unit/browserHashProvider.test.js +1 -1
  38. package/dist/test/unit/browserHashProvider.test.js.map +1 -1
  39. package/dist/test/unit/directoryHandleStore.test.js +190 -0
  40. package/dist/test/unit/directoryHandleStore.test.js.map +1 -0
  41. package/dist/test/unit/fileApiTreeAccessors.test.js +51 -0
  42. package/dist/test/unit/fileApiTreeAccessors.test.js.map +1 -1
  43. package/dist/test/unit/fileApiTypes.test.js +30 -0
  44. package/dist/test/unit/fileApiTypes.test.js.map +1 -1
  45. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js +622 -0
  46. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -0
  47. package/dist/test/unit/httpTreeAccessors.test.js +1000 -0
  48. package/dist/test/unit/httpTreeAccessors.test.js.map +1 -0
  49. package/dist/test/unit/localStorageTreeAccessors.test.js +812 -0
  50. package/dist/test/unit/localStorageTreeAccessors.test.js.map +1 -0
  51. package/dist/test/utils/fileSystemAccessMocks.js +271 -0
  52. package/dist/test/utils/fileSystemAccessMocks.js.map +1 -0
  53. package/dist/ts-web-extras.d.ts +584 -1
  54. package/dist/tsdoc-metadata.json +1 -1
  55. package/docs/@fgv/namespaces/CryptoUtils/README.md +18 -0
  56. package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserCryptoProvider.md +203 -0
  57. package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserHashProvider.md +63 -0
  58. package/docs/@fgv/namespaces/CryptoUtils/functions/createBrowserCryptoProvider.md +18 -0
  59. package/docs/@fgv/namespaces/FileTreeHelpers/README.md +19 -0
  60. package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileListMetadata.md +23 -0
  61. package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileMetadata.md +23 -0
  62. package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromDirectoryUpload.md +33 -0
  63. package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromFileList.md +33 -0
  64. package/docs/@fgv/namespaces/FileTreeHelpers/functions/getOriginalFile.md +25 -0
  65. package/docs/@fgv/namespaces/FileTreeHelpers/variables/defaultFileApiTreeInitParams.md +11 -0
  66. package/docs/README.md +78 -0
  67. package/docs/classes/DirectoryHandleStore.md +116 -0
  68. package/docs/classes/FileApiTreeAccessors.md +286 -0
  69. package/docs/classes/FileSystemAccessTreeAccessors.md +557 -0
  70. package/docs/classes/HttpTreeAccessors.md +508 -0
  71. package/docs/classes/LocalStorageTreeAccessors.md +520 -0
  72. package/docs/functions/exportAsJson.md +23 -0
  73. package/docs/functions/exportUsingFileSystemAPI.md +26 -0
  74. package/docs/functions/extractDirectoryPath.md +23 -0
  75. package/docs/functions/isDirectoryHandle.md +23 -0
  76. package/docs/functions/isFileHandle.md +23 -0
  77. package/docs/functions/isFilePath.md +21 -0
  78. package/docs/functions/parseContextFilter.md +22 -0
  79. package/docs/functions/parseQualifierDefaults.md +22 -0
  80. package/docs/functions/parseResourceTypes.md +22 -0
  81. package/docs/functions/parseUrlParameters.md +15 -0
  82. package/docs/functions/safeShowDirectoryPicker.md +24 -0
  83. package/docs/functions/safeShowOpenFilePicker.md +24 -0
  84. package/docs/functions/safeShowSaveFilePicker.md +24 -0
  85. package/docs/functions/supportsFileSystemAccess.md +23 -0
  86. package/docs/interfaces/FilePickerAcceptType.md +16 -0
  87. package/docs/interfaces/FileSystemCreateWritableOptions.md +15 -0
  88. package/docs/interfaces/FileSystemDirectoryHandle.md +187 -0
  89. package/docs/interfaces/FileSystemFileHandle.md +106 -0
  90. package/docs/interfaces/FileSystemGetDirectoryOptions.md +15 -0
  91. package/docs/interfaces/FileSystemGetFileOptions.md +15 -0
  92. package/docs/interfaces/FileSystemHandle.md +69 -0
  93. package/docs/interfaces/FileSystemHandlePermissionDescriptor.md +15 -0
  94. package/docs/interfaces/FileSystemRemoveOptions.md +15 -0
  95. package/docs/interfaces/FileSystemWritableFileStream.md +127 -0
  96. package/docs/interfaces/IDirectoryHandleTreeInitializer.md +17 -0
  97. package/docs/interfaces/IFileHandleTreeInitializer.md +16 -0
  98. package/docs/interfaces/IFileListTreeInitializer.md +15 -0
  99. package/docs/interfaces/IFileMetadata.md +19 -0
  100. package/docs/interfaces/IFileSystemAccessTreeParams.md +30 -0
  101. package/docs/interfaces/IFsAccessApis.md +57 -0
  102. package/docs/interfaces/IHttpTreeParams.md +32 -0
  103. package/docs/interfaces/ILocalStorageTreeParams.md +30 -0
  104. package/docs/interfaces/IUrlConfigOptions.md +27 -0
  105. package/docs/interfaces/ShowDirectoryPickerOptions.md +17 -0
  106. package/docs/interfaces/ShowOpenFilePickerOptions.md +19 -0
  107. package/docs/interfaces/ShowSaveFilePickerOptions.md +19 -0
  108. package/docs/type-aliases/TreeInitializer.md +11 -0
  109. package/docs/type-aliases/WellKnownDirectory.md +11 -0
  110. package/docs/type-aliases/WindowWithFsAccess.md +11 -0
  111. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_DB.md +11 -0
  112. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_STORE.md +11 -0
  113. package/etc/ts-web-extras.api.md +124 -1
  114. package/lib/index.d.ts +2 -1
  115. package/lib/index.d.ts.map +1 -1
  116. package/lib/index.js +25 -2
  117. package/lib/index.js.map +1 -1
  118. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +77 -0
  119. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -0
  120. package/lib/packlets/crypto-utils/browserCryptoProvider.js +259 -0
  121. package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -0
  122. package/lib/packlets/crypto-utils/browserHashProvider.d.ts.map +1 -0
  123. package/lib/packlets/crypto-utils/browserHashProvider.js.map +1 -0
  124. package/lib/packlets/{crypto → crypto-utils}/index.d.ts +1 -0
  125. package/lib/packlets/crypto-utils/index.d.ts.map +1 -0
  126. package/lib/packlets/{crypto → crypto-utils}/index.js +1 -0
  127. package/lib/packlets/crypto-utils/index.js.map +1 -0
  128. package/lib/packlets/file-api-types/index.d.ts.map +1 -1
  129. package/lib/packlets/file-api-types/index.js +27 -3
  130. package/lib/packlets/file-api-types/index.js.map +1 -1
  131. package/lib/packlets/file-tree/directoryHandleStore.d.ts +59 -0
  132. package/lib/packlets/file-tree/directoryHandleStore.d.ts.map +1 -0
  133. package/lib/packlets/file-tree/directoryHandleStore.js +128 -0
  134. package/lib/packlets/file-tree/directoryHandleStore.js.map +1 -0
  135. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +66 -0
  136. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts.map +1 -1
  137. package/lib/packlets/file-tree/fileApiTreeAccessors.js +91 -0
  138. package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  139. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts +152 -0
  140. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts.map +1 -0
  141. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js +418 -0
  142. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -0
  143. package/lib/packlets/file-tree/httpTreeAccessors.d.ts +88 -0
  144. package/lib/packlets/file-tree/httpTreeAccessors.d.ts.map +1 -0
  145. package/lib/packlets/file-tree/httpTreeAccessors.js +283 -0
  146. package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -0
  147. package/lib/packlets/file-tree/index.d.ts +4 -0
  148. package/lib/packlets/file-tree/index.d.ts.map +1 -1
  149. package/lib/packlets/file-tree/index.js +4 -0
  150. package/lib/packlets/file-tree/index.js.map +1 -1
  151. package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts +141 -0
  152. package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts.map +1 -0
  153. package/lib/packlets/file-tree/localStorageTreeAccessors.js +363 -0
  154. package/lib/packlets/file-tree/localStorageTreeAccessors.js.map +1 -0
  155. package/lib/test/mocks/idb-keyval.d.ts +6 -0
  156. package/lib/test/mocks/idb-keyval.d.ts.map +1 -0
  157. package/lib/test/mocks/idb-keyval.js +9 -0
  158. package/lib/test/mocks/idb-keyval.js.map +1 -0
  159. package/lib/test/unit/browserHashProvider.test.js +21 -21
  160. package/lib/test/unit/browserHashProvider.test.js.map +1 -1
  161. package/lib/test/unit/directoryHandleStore.test.d.ts +2 -0
  162. package/lib/test/unit/directoryHandleStore.test.d.ts.map +1 -0
  163. package/lib/test/unit/directoryHandleStore.test.js +192 -0
  164. package/lib/test/unit/directoryHandleStore.test.js.map +1 -0
  165. package/lib/test/unit/fileApiTreeAccessors.test.js +51 -0
  166. package/lib/test/unit/fileApiTreeAccessors.test.js.map +1 -1
  167. package/lib/test/unit/fileApiTypes.test.js +30 -0
  168. package/lib/test/unit/fileApiTypes.test.js.map +1 -1
  169. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts +2 -0
  170. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts.map +1 -0
  171. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js +624 -0
  172. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -0
  173. package/lib/test/unit/httpTreeAccessors.test.d.ts +2 -0
  174. package/lib/test/unit/httpTreeAccessors.test.d.ts.map +1 -0
  175. package/lib/test/unit/httpTreeAccessors.test.js +1002 -0
  176. package/lib/test/unit/httpTreeAccessors.test.js.map +1 -0
  177. package/lib/test/unit/localStorageTreeAccessors.test.d.ts +2 -0
  178. package/lib/test/unit/localStorageTreeAccessors.test.d.ts.map +1 -0
  179. package/lib/test/unit/localStorageTreeAccessors.test.js +814 -0
  180. package/lib/test/unit/localStorageTreeAccessors.test.js.map +1 -0
  181. package/lib/test/utils/fileSystemAccessMocks.d.ts +53 -0
  182. package/lib/test/utils/fileSystemAccessMocks.d.ts.map +1 -0
  183. package/lib/test/utils/fileSystemAccessMocks.js +277 -0
  184. package/lib/test/utils/fileSystemAccessMocks.js.map +1 -0
  185. package/package.json +41 -34
  186. package/rush-logs/ts-web-extras.build.cache.log +0 -1
  187. package/rush-logs/ts-web-extras.build.error.log +18 -0
  188. package/rush-logs/ts-web-extras.build.log +58 -25
  189. package/rush-logs/ts-web-extras.test.cache.log +1 -0
  190. package/rush-logs/ts-web-extras.test.error.log +16 -0
  191. package/rush-logs/ts-web-extras.test.log +70 -0
  192. package/src/index.ts +2 -2
  193. package/src/packlets/crypto-utils/browserCryptoProvider.ts +311 -0
  194. package/src/packlets/{crypto → crypto-utils}/index.ts +1 -0
  195. package/src/packlets/file-api-types/index.ts +24 -3
  196. package/src/packlets/file-tree/directoryHandleStore.ts +136 -0
  197. package/src/packlets/file-tree/fileApiTreeAccessors.ts +108 -0
  198. package/src/packlets/file-tree/fileSystemAccessTreeAccessors.ts +519 -0
  199. package/src/packlets/file-tree/httpTreeAccessors.ts +381 -0
  200. package/src/packlets/file-tree/index.ts +4 -0
  201. package/src/packlets/file-tree/localStorageTreeAccessors.ts +430 -0
  202. package/src/test/mocks/idb-keyval.ts +5 -0
  203. package/src/test/unit/browserHashProvider.test.ts +1 -1
  204. package/src/test/unit/directoryHandleStore.test.ts +251 -0
  205. package/src/test/unit/fileApiTreeAccessors.test.ts +69 -0
  206. package/src/test/unit/fileApiTypes.test.ts +36 -0
  207. package/src/test/unit/fileSystemAccessTreeAccessors.test.ts +885 -0
  208. package/src/test/unit/httpTreeAccessors.test.ts +1278 -0
  209. package/src/test/unit/localStorageTreeAccessors.test.ts +1014 -0
  210. package/src/test/utils/fileSystemAccessMocks.ts +353 -0
  211. package/temp/build/typescript/ts_8nwakTlr.json +1 -0
  212. package/temp/coverage/crypto/browserHashProvider.ts.html +1 -1
  213. package/temp/coverage/crypto/index.html +1 -1
  214. package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +1018 -0
  215. package/temp/coverage/crypto-utils/browserHashProvider.ts.html +304 -0
  216. package/temp/coverage/crypto-utils/index.html +131 -0
  217. package/temp/coverage/file-tree/directoryHandleStore.ts.html +493 -0
  218. package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +330 -6
  219. package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +1642 -0
  220. package/temp/coverage/file-tree/httpTreeAccessors.ts.html +1228 -0
  221. package/temp/coverage/file-tree/index.html +69 -9
  222. package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +1375 -0
  223. package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
  224. package/temp/coverage/helpers/index.html +1 -1
  225. package/temp/coverage/index.html +13 -13
  226. package/temp/coverage/lcov-report/crypto/browserHashProvider.ts.html +1 -1
  227. package/temp/coverage/lcov-report/crypto/index.html +1 -1
  228. package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +1018 -0
  229. package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +304 -0
  230. package/temp/coverage/lcov-report/crypto-utils/index.html +131 -0
  231. package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +493 -0
  232. package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +330 -6
  233. package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +1642 -0
  234. package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +1228 -0
  235. package/temp/coverage/lcov-report/file-tree/index.html +69 -9
  236. package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +1375 -0
  237. package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
  238. package/temp/coverage/lcov-report/helpers/index.html +1 -1
  239. package/temp/coverage/lcov-report/index.html +13 -13
  240. package/temp/coverage/lcov-report/url-utils/index.html +1 -1
  241. package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
  242. package/temp/coverage/lcov.info +2829 -428
  243. package/temp/coverage/url-utils/index.html +1 -1
  244. package/temp/coverage/url-utils/urlParams.ts.html +1 -1
  245. package/temp/test/jest/haste-map-b931e4e63102f86c5bd4949f7dced44f-9d713eb41149188b4e5c0ae3d86d0a57-2ad8e16b24e391b8cdbe50b55c137169 +0 -0
  246. package/temp/test/jest/perf-cache-b931e4e63102f86c5bd4949f7dced44f-da39a3ee5e6b4b0d3255bfef95601890 +1 -0
  247. package/temp/ts-web-extras.api.json +5282 -1472
  248. package/temp/ts-web-extras.api.md +124 -1
  249. package/dist/packlets/crypto/browserHashProvider.js.map +0 -1
  250. package/dist/packlets/crypto/index.js.map +0 -1
  251. package/docs/index.md +0 -34
  252. package/docs/ts-web-extras.browserhashprovider.hashparts.md +0 -88
  253. package/docs/ts-web-extras.browserhashprovider.hashstring.md +0 -72
  254. package/docs/ts-web-extras.browserhashprovider.md +0 -66
  255. package/docs/ts-web-extras.exportasjson.md +0 -70
  256. package/docs/ts-web-extras.exportusingfilesystemapi.md +0 -104
  257. package/docs/ts-web-extras.extractdirectorypath.md +0 -52
  258. package/docs/ts-web-extras.fileapitreeaccessors.create.md +0 -72
  259. package/docs/ts-web-extras.fileapitreeaccessors.extractfilemetadata.md +0 -54
  260. package/docs/ts-web-extras.fileapitreeaccessors.fromdirectoryupload.md +0 -72
  261. package/docs/ts-web-extras.fileapitreeaccessors.fromfilelist.md +0 -72
  262. package/docs/ts-web-extras.fileapitreeaccessors.getoriginalfile.md +0 -72
  263. package/docs/ts-web-extras.fileapitreeaccessors.md +0 -114
  264. package/docs/ts-web-extras.filepickeraccepttype.accept.md +0 -11
  265. package/docs/ts-web-extras.filepickeraccepttype.description.md +0 -11
  266. package/docs/ts-web-extras.filepickeraccepttype.md +0 -75
  267. package/docs/ts-web-extras.filesystemcreatewritableoptions_2.keepexistingdata.md +0 -11
  268. package/docs/ts-web-extras.filesystemcreatewritableoptions_2.md +0 -58
  269. package/docs/ts-web-extras.filesystemdirectoryhandle_2._symbol.asynciterator_.md +0 -15
  270. package/docs/ts-web-extras.filesystemdirectoryhandle_2.entries.md +0 -15
  271. package/docs/ts-web-extras.filesystemdirectoryhandle_2.getdirectoryhandle.md +0 -66
  272. package/docs/ts-web-extras.filesystemdirectoryhandle_2.getfilehandle.md +0 -66
  273. package/docs/ts-web-extras.filesystemdirectoryhandle_2.keys.md +0 -15
  274. package/docs/ts-web-extras.filesystemdirectoryhandle_2.kind.md +0 -11
  275. package/docs/ts-web-extras.filesystemdirectoryhandle_2.md +0 -146
  276. package/docs/ts-web-extras.filesystemdirectoryhandle_2.removeentry.md +0 -66
  277. package/docs/ts-web-extras.filesystemdirectoryhandle_2.resolve.md +0 -50
  278. package/docs/ts-web-extras.filesystemdirectoryhandle_2.values.md +0 -15
  279. package/docs/ts-web-extras.filesystemfilehandle_2.createwritable.md +0 -52
  280. package/docs/ts-web-extras.filesystemfilehandle_2.getfile.md +0 -15
  281. package/docs/ts-web-extras.filesystemfilehandle_2.kind.md +0 -11
  282. package/docs/ts-web-extras.filesystemfilehandle_2.md +0 -92
  283. package/docs/ts-web-extras.filesystemgetdirectoryoptions_2.create.md +0 -11
  284. package/docs/ts-web-extras.filesystemgetdirectoryoptions_2.md +0 -58
  285. package/docs/ts-web-extras.filesystemgetfileoptions_2.create.md +0 -11
  286. package/docs/ts-web-extras.filesystemgetfileoptions_2.md +0 -58
  287. package/docs/ts-web-extras.filesystemhandle_2.issameentry.md +0 -50
  288. package/docs/ts-web-extras.filesystemhandle_2.kind.md +0 -11
  289. package/docs/ts-web-extras.filesystemhandle_2.md +0 -119
  290. package/docs/ts-web-extras.filesystemhandle_2.name.md +0 -11
  291. package/docs/ts-web-extras.filesystemhandle_2.querypermission.md +0 -52
  292. package/docs/ts-web-extras.filesystemhandle_2.requestpermission.md +0 -52
  293. package/docs/ts-web-extras.filesystemhandlepermissiondescriptor.md +0 -58
  294. package/docs/ts-web-extras.filesystemhandlepermissiondescriptor.mode.md +0 -11
  295. package/docs/ts-web-extras.filesystemremoveoptions_2.md +0 -58
  296. package/docs/ts-web-extras.filesystemremoveoptions_2.recursive.md +0 -11
  297. package/docs/ts-web-extras.filesystemwritablefilestream_2.md +0 -57
  298. package/docs/ts-web-extras.filesystemwritablefilestream_2.seek.md +0 -50
  299. package/docs/ts-web-extras.filesystemwritablefilestream_2.truncate.md +0 -50
  300. package/docs/ts-web-extras.filesystemwritablefilestream_2.write.md +0 -50
  301. package/docs/ts-web-extras.filetreehelpers.defaultfileapitreeinitparams.md +0 -13
  302. package/docs/ts-web-extras.filetreehelpers.extractfilelistmetadata.md +0 -56
  303. package/docs/ts-web-extras.filetreehelpers.extractfilemetadata.md +0 -56
  304. package/docs/ts-web-extras.filetreehelpers.fromdirectoryupload.md +0 -76
  305. package/docs/ts-web-extras.filetreehelpers.fromfilelist.md +0 -76
  306. package/docs/ts-web-extras.filetreehelpers.getoriginalfile.md +0 -72
  307. package/docs/ts-web-extras.filetreehelpers.md +0 -102
  308. package/docs/ts-web-extras.idirectoryhandletreeinitializer.dirhandles.md +0 -11
  309. package/docs/ts-web-extras.idirectoryhandletreeinitializer.md +0 -100
  310. package/docs/ts-web-extras.idirectoryhandletreeinitializer.nonrecursive.md +0 -11
  311. package/docs/ts-web-extras.idirectoryhandletreeinitializer.prefix.md +0 -11
  312. package/docs/ts-web-extras.ifilehandletreeinitializer.filehandles.md +0 -11
  313. package/docs/ts-web-extras.ifilehandletreeinitializer.md +0 -79
  314. package/docs/ts-web-extras.ifilehandletreeinitializer.prefix.md +0 -11
  315. package/docs/ts-web-extras.ifilelisttreeinitializer.filelist.md +0 -11
  316. package/docs/ts-web-extras.ifilelisttreeinitializer.md +0 -58
  317. package/docs/ts-web-extras.ifilemetadata.lastmodified.md +0 -11
  318. package/docs/ts-web-extras.ifilemetadata.md +0 -124
  319. package/docs/ts-web-extras.ifilemetadata.name.md +0 -11
  320. package/docs/ts-web-extras.ifilemetadata.path.md +0 -11
  321. package/docs/ts-web-extras.ifilemetadata.size.md +0 -11
  322. package/docs/ts-web-extras.ifilemetadata.type.md +0 -11
  323. package/docs/ts-web-extras.ifsaccessapis.md +0 -56
  324. package/docs/ts-web-extras.ifsaccessapis.showdirectorypicker.md +0 -52
  325. package/docs/ts-web-extras.ifsaccessapis.showopenfilepicker.md +0 -52
  326. package/docs/ts-web-extras.ifsaccessapis.showsavefilepicker.md +0 -52
  327. package/docs/ts-web-extras.isdirectoryhandle.md +0 -56
  328. package/docs/ts-web-extras.isfilehandle.md +0 -56
  329. package/docs/ts-web-extras.isfilepath.md +0 -52
  330. package/docs/ts-web-extras.iurlconfigoptions.config.md +0 -13
  331. package/docs/ts-web-extras.iurlconfigoptions.configstartdir.md +0 -13
  332. package/docs/ts-web-extras.iurlconfigoptions.contextfilter.md +0 -13
  333. package/docs/ts-web-extras.iurlconfigoptions.input.md +0 -13
  334. package/docs/ts-web-extras.iurlconfigoptions.inputstartdir.md +0 -13
  335. package/docs/ts-web-extras.iurlconfigoptions.interactive.md +0 -13
  336. package/docs/ts-web-extras.iurlconfigoptions.loadzip.md +0 -13
  337. package/docs/ts-web-extras.iurlconfigoptions.maxdistance.md +0 -13
  338. package/docs/ts-web-extras.iurlconfigoptions.md +0 -286
  339. package/docs/ts-web-extras.iurlconfigoptions.qualifierdefaults.md +0 -13
  340. package/docs/ts-web-extras.iurlconfigoptions.reducequalifiers.md +0 -13
  341. package/docs/ts-web-extras.iurlconfigoptions.resourcetypes.md +0 -13
  342. package/docs/ts-web-extras.iurlconfigoptions.zipfile.md +0 -13
  343. package/docs/ts-web-extras.iurlconfigoptions.zippath.md +0 -13
  344. package/docs/ts-web-extras.md +0 -512
  345. package/docs/ts-web-extras.parsecontextfilter.md +0 -52
  346. package/docs/ts-web-extras.parsequalifierdefaults.md +0 -52
  347. package/docs/ts-web-extras.parseresourcetypes.md +0 -52
  348. package/docs/ts-web-extras.parseurlparameters.md +0 -17
  349. package/docs/ts-web-extras.safeshowdirectorypicker.md +0 -72
  350. package/docs/ts-web-extras.safeshowopenfilepicker.md +0 -72
  351. package/docs/ts-web-extras.safeshowsavefilepicker.md +0 -72
  352. package/docs/ts-web-extras.showdirectorypickeroptions.id.md +0 -11
  353. package/docs/ts-web-extras.showdirectorypickeroptions.md +0 -96
  354. package/docs/ts-web-extras.showdirectorypickeroptions.mode.md +0 -11
  355. package/docs/ts-web-extras.showdirectorypickeroptions.startin.md +0 -11
  356. package/docs/ts-web-extras.showopenfilepickeroptions.excludeacceptalloption.md +0 -11
  357. package/docs/ts-web-extras.showopenfilepickeroptions.id.md +0 -11
  358. package/docs/ts-web-extras.showopenfilepickeroptions.md +0 -134
  359. package/docs/ts-web-extras.showopenfilepickeroptions.multiple.md +0 -11
  360. package/docs/ts-web-extras.showopenfilepickeroptions.startin.md +0 -11
  361. package/docs/ts-web-extras.showopenfilepickeroptions.types.md +0 -11
  362. package/docs/ts-web-extras.showsavefilepickeroptions.excludeacceptalloption.md +0 -11
  363. package/docs/ts-web-extras.showsavefilepickeroptions.id.md +0 -11
  364. package/docs/ts-web-extras.showsavefilepickeroptions.md +0 -134
  365. package/docs/ts-web-extras.showsavefilepickeroptions.startin.md +0 -11
  366. package/docs/ts-web-extras.showsavefilepickeroptions.suggestedname.md +0 -11
  367. package/docs/ts-web-extras.showsavefilepickeroptions.types.md +0 -11
  368. package/docs/ts-web-extras.supportsfilesystemaccess.md +0 -56
  369. package/docs/ts-web-extras.treeinitializer.md +0 -15
  370. package/docs/ts-web-extras.wellknowndirectory.md +0 -13
  371. package/docs/ts-web-extras.windowwithfsaccess.md +0 -15
  372. package/lib/packlets/crypto/browserHashProvider.d.ts.map +0 -1
  373. package/lib/packlets/crypto/browserHashProvider.js.map +0 -1
  374. package/lib/packlets/crypto/index.d.ts.map +0 -1
  375. package/lib/packlets/crypto/index.js.map +0 -1
  376. package/temp/build/typescript/ts_vnCx6LlY.json +0 -1
  377. package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
  378. package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +0 -1
  379. /package/dist/packlets/{crypto → crypto-utils}/browserHashProvider.js +0 -0
  380. /package/lib/packlets/{crypto → crypto-utils}/browserHashProvider.d.ts +0 -0
  381. /package/lib/packlets/{crypto → crypto-utils}/browserHashProvider.js +0 -0
  382. /package/src/packlets/{crypto → crypto-utils}/browserHashProvider.ts +0 -0
  383. /package/temp/test/jest/{jest-transform-cache-7492f1b44480e0cdd1f220078fb3afd8-79ef2876fae7ca75eedb2aa53dc48338/0e/package_0eb6535f5987849d93ea51ef33a14cf6 → jest-transform-cache-b931e4e63102f86c5bd4949f7dced44f-79ef2876fae7ca75eedb2aa53dc48338/b5/package_b5f57afc9ec2c011239b1608ee5bdfa5} +0 -0
@@ -0,0 +1,1278 @@
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 { fail, Logging } from '@fgv/ts-utils';
25
+ import { HttpTreeAccessors } from '../../packlets/file-tree';
26
+
27
+ // ---- Mock fetch helpers ----
28
+
29
+ interface IMockResponse {
30
+ ok: boolean;
31
+ status?: number;
32
+ jsonValue?: unknown;
33
+ textValue?: string;
34
+ throwOnJson?: boolean;
35
+ throwOnText?: boolean;
36
+ }
37
+
38
+ function makeMockResponse(options: IMockResponse): Response {
39
+ const { ok, status = ok ? 200 : 400, jsonValue, textValue, throwOnJson, throwOnText } = options;
40
+ return {
41
+ ok,
42
+ status,
43
+ json: throwOnJson
44
+ ? () => Promise.reject(new Error('JSON parse error'))
45
+ : () => Promise.resolve(jsonValue),
46
+ text: throwOnText
47
+ ? () => Promise.reject(new Error('text error'))
48
+ : () => Promise.resolve(textValue ?? `HTTP ${status}`)
49
+ } as unknown as Response;
50
+ }
51
+
52
+ type FetchCall = { url: string; init?: RequestInit };
53
+
54
+ /**
55
+ * Creates a mock fetch function that returns responses for each call in order.
56
+ * Each entry maps to one fetch() invocation in call order.
57
+ */
58
+ function makeMockFetch(responses: IMockResponse[]): { fetchImpl: typeof fetch; calls: FetchCall[] } {
59
+ const calls: FetchCall[] = [];
60
+ let callIndex = 0;
61
+
62
+ const fetchImpl = (url: string | URL | Request, init?: RequestInit): Promise<Response> => {
63
+ calls.push({ url: url.toString(), init });
64
+ const response = responses[callIndex++];
65
+ if (response === undefined) {
66
+ return Promise.reject(new Error(`Unexpected fetch call #${callIndex} to ${url.toString()}`));
67
+ }
68
+ return Promise.resolve(makeMockResponse(response));
69
+ };
70
+
71
+ return { fetchImpl: fetchImpl as typeof fetch, calls };
72
+ }
73
+
74
+ /**
75
+ * Creates a mock fetch function that throws a network error on every call.
76
+ */
77
+ function makeThrowingFetch(message: string): typeof fetch {
78
+ return (_url: string | URL | Request, _init?: RequestInit): Promise<Response> => {
79
+ return Promise.reject(new Error(message));
80
+ };
81
+ }
82
+
83
+ // ---- Shared test data builders ----
84
+
85
+ /** Minimal tree-children response for a single file at root. */
86
+ function rootWithOneFile(fileName = 'data.json'): unknown {
87
+ return {
88
+ path: '/',
89
+ children: [{ path: `/${fileName}`, name: fileName, type: 'file' }]
90
+ };
91
+ }
92
+
93
+ /** File response for a JSON file. */
94
+ function fileResponse(path: string, contents: string, contentType?: string): unknown {
95
+ const response: Record<string, unknown> = { path, contents };
96
+ if (contentType !== undefined) {
97
+ response.contentType = contentType;
98
+ }
99
+ return response;
100
+ }
101
+
102
+ /** Root children response containing a subdirectory and a file. */
103
+ function rootWithDirAndFile(): unknown {
104
+ return {
105
+ path: '/',
106
+ children: [
107
+ { path: '/subdir', name: 'subdir', type: 'directory' },
108
+ { path: '/root.json', name: 'root.json', type: 'file' }
109
+ ]
110
+ };
111
+ }
112
+
113
+ /** Children response for /subdir containing one file. */
114
+ function subdirWithOneFile(): unknown {
115
+ return {
116
+ path: '/subdir',
117
+ children: [{ path: '/subdir/nested.json', name: 'nested.json', type: 'file' }]
118
+ };
119
+ }
120
+
121
+ // ---- Tests ----
122
+
123
+ describe('HttpTreeAccessors', () => {
124
+ describe('fromHttp()', () => {
125
+ test('succeeds with an empty directory (no children)', async () => {
126
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
127
+
128
+ const result = await HttpTreeAccessors.fromHttp({
129
+ baseUrl: 'http://localhost:3000',
130
+ fetchImpl
131
+ });
132
+
133
+ expect(result).toSucceedAndSatisfy((accessors) => {
134
+ expect(accessors).toBeInstanceOf(HttpTreeAccessors);
135
+ expect(accessors.isDirty()).toBe(false);
136
+ });
137
+ });
138
+
139
+ test('succeeds and loads a single file at root', async () => {
140
+ const { fetchImpl } = makeMockFetch([
141
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
142
+ { ok: true, jsonValue: fileResponse('/data.json', '{"items":{}}') }
143
+ ]);
144
+
145
+ const result = await HttpTreeAccessors.fromHttp({
146
+ baseUrl: 'http://localhost:3000',
147
+ fetchImpl,
148
+ mutable: true
149
+ });
150
+
151
+ expect(result).toSucceedAndSatisfy((accessors) => {
152
+ expect(accessors.getFileContents('/data.json')).toSucceedWith('{"items":{}}');
153
+ });
154
+ });
155
+
156
+ test('succeeds with multiple files at root', async () => {
157
+ const { fetchImpl } = makeMockFetch([
158
+ {
159
+ ok: true,
160
+ jsonValue: {
161
+ path: '/',
162
+ children: [
163
+ { path: '/alpha.json', name: 'alpha.json', type: 'file' },
164
+ { path: '/beta.json', name: 'beta.json', type: 'file' }
165
+ ]
166
+ }
167
+ },
168
+ { ok: true, jsonValue: fileResponse('/alpha.json', '"alpha"') },
169
+ { ok: true, jsonValue: fileResponse('/beta.json', '"beta"') }
170
+ ]);
171
+
172
+ const result = await HttpTreeAccessors.fromHttp({
173
+ baseUrl: 'http://localhost:3000',
174
+ fetchImpl,
175
+ mutable: true
176
+ });
177
+
178
+ expect(result).toSucceedAndSatisfy((accessors) => {
179
+ expect(accessors.getFileContents('/alpha.json')).toSucceedWith('"alpha"');
180
+ expect(accessors.getFileContents('/beta.json')).toSucceedWith('"beta"');
181
+ });
182
+ });
183
+
184
+ test('succeeds and recursively loads files in subdirectories', async () => {
185
+ const { fetchImpl } = makeMockFetch([
186
+ { ok: true, jsonValue: rootWithDirAndFile() },
187
+ { ok: true, jsonValue: subdirWithOneFile() },
188
+ { ok: true, jsonValue: fileResponse('/subdir/nested.json', '"nested"') },
189
+ { ok: true, jsonValue: fileResponse('/root.json', '"root"') }
190
+ ]);
191
+
192
+ const result = await HttpTreeAccessors.fromHttp({
193
+ baseUrl: 'http://localhost:3000',
194
+ fetchImpl,
195
+ mutable: true
196
+ });
197
+
198
+ expect(result).toSucceedAndSatisfy((accessors) => {
199
+ expect(accessors.getFileContents('/subdir/nested.json')).toSucceedWith('"nested"');
200
+ expect(accessors.getFileContents('/root.json')).toSucceedWith('"root"');
201
+ });
202
+ });
203
+
204
+ test('strips trailing slash from baseUrl', async () => {
205
+ const { fetchImpl, calls } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
206
+
207
+ await HttpTreeAccessors.fromHttp({
208
+ baseUrl: 'http://localhost:3000/',
209
+ fetchImpl
210
+ });
211
+
212
+ // The URL should start with the base URL without a trailing slash, then /tree/children
213
+ expect(calls[0].url).toMatch(/^http:\/\/localhost:3000\/tree\/children/);
214
+ // There should be no double slash in the path portion (after the protocol)
215
+ const urlPath = calls[0].url.replace('http://', '');
216
+ expect(urlPath).not.toContain('//');
217
+ });
218
+
219
+ test('includes namespace in query parameters when provided', async () => {
220
+ const { fetchImpl, calls } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
221
+
222
+ await HttpTreeAccessors.fromHttp({
223
+ baseUrl: 'http://localhost:3000',
224
+ namespace: 'my-namespace',
225
+ fetchImpl
226
+ });
227
+
228
+ expect(calls[0].url).toContain('namespace=my-namespace');
229
+ });
230
+
231
+ test('omits namespace from query parameters when not provided', async () => {
232
+ const { fetchImpl, calls } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
233
+
234
+ await HttpTreeAccessors.fromHttp({
235
+ baseUrl: 'http://localhost:3000',
236
+ fetchImpl
237
+ });
238
+
239
+ expect(calls[0].url).not.toContain('namespace');
240
+ });
241
+
242
+ test('applies prefix parameter to loaded file paths', async () => {
243
+ const { fetchImpl } = makeMockFetch([
244
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
245
+ { ok: true, jsonValue: fileResponse('/data.json', '{"items":{}}') }
246
+ ]);
247
+
248
+ const result = await HttpTreeAccessors.fromHttp({
249
+ baseUrl: 'http://localhost:3000',
250
+ prefix: '/app',
251
+ fetchImpl,
252
+ mutable: true
253
+ });
254
+
255
+ expect(result).toSucceedAndSatisfy((accessors) => {
256
+ expect(accessors.getFileContents('/app/data.json')).toSucceedWith('{"items":{}}');
257
+ });
258
+ });
259
+
260
+ test('fails when the initial children fetch fails with a network error', async () => {
261
+ const result = await HttpTreeAccessors.fromHttp({
262
+ baseUrl: 'http://localhost:3000',
263
+ fetchImpl: makeThrowingFetch('Network unreachable')
264
+ });
265
+
266
+ expect(result).toFailWith(/network unreachable/i);
267
+ });
268
+
269
+ test('fails when the children response is not ok', async () => {
270
+ const { fetchImpl } = makeMockFetch([{ ok: false, status: 404, textValue: 'Not Found' }]);
271
+
272
+ const result = await HttpTreeAccessors.fromHttp({
273
+ baseUrl: 'http://localhost:3000',
274
+ fetchImpl
275
+ });
276
+
277
+ expect(result).toFailWith(/not found/i);
278
+ });
279
+
280
+ test('fails when the children response contains invalid JSON', async () => {
281
+ const { fetchImpl } = makeMockFetch([{ ok: true, throwOnJson: true }]);
282
+
283
+ const result = await HttpTreeAccessors.fromHttp({
284
+ baseUrl: 'http://localhost:3000',
285
+ fetchImpl
286
+ });
287
+
288
+ expect(result).toFailWith(/invalid json/i);
289
+ });
290
+
291
+ test('fails when a file fetch fails with a network error', async () => {
292
+ let callCount = 0;
293
+ const fetchImpl: typeof fetch = (_url, _init) => {
294
+ callCount++;
295
+ if (callCount === 1) {
296
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
297
+ }
298
+ return Promise.reject(new Error('File fetch failed'));
299
+ };
300
+
301
+ const result = await HttpTreeAccessors.fromHttp({
302
+ baseUrl: 'http://localhost:3000',
303
+ fetchImpl
304
+ });
305
+
306
+ expect(result).toFailWith(/file fetch failed/i);
307
+ });
308
+
309
+ test('fails when a file response is not ok', async () => {
310
+ const { fetchImpl } = makeMockFetch([
311
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
312
+ { ok: false, status: 403, textValue: 'Forbidden' }
313
+ ]);
314
+
315
+ const result = await HttpTreeAccessors.fromHttp({
316
+ baseUrl: 'http://localhost:3000',
317
+ fetchImpl
318
+ });
319
+
320
+ expect(result).toFailWith(/forbidden/i);
321
+ });
322
+
323
+ test('fails when a file response contains invalid JSON', async () => {
324
+ const { fetchImpl } = makeMockFetch([
325
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
326
+ { ok: true, throwOnJson: true }
327
+ ]);
328
+
329
+ const result = await HttpTreeAccessors.fromHttp({
330
+ baseUrl: 'http://localhost:3000',
331
+ fetchImpl
332
+ });
333
+
334
+ expect(result).toFailWith(/invalid json/i);
335
+ });
336
+
337
+ test('fails when a nested directory fetch fails', async () => {
338
+ const { fetchImpl } = makeMockFetch([
339
+ { ok: true, jsonValue: rootWithDirAndFile() },
340
+ { ok: false, status: 500, textValue: 'Internal Server Error' }
341
+ ]);
342
+
343
+ const result = await HttpTreeAccessors.fromHttp({
344
+ baseUrl: 'http://localhost:3000',
345
+ fetchImpl
346
+ });
347
+
348
+ expect(result).toFailWith(/internal server error/i);
349
+ });
350
+ });
351
+
352
+ describe('isDirty() and getDirtyPaths()', () => {
353
+ test('starts not dirty after loading', async () => {
354
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
355
+
356
+ const accessors = (
357
+ await HttpTreeAccessors.fromHttp({ baseUrl: 'http://localhost:3000', fetchImpl })
358
+ ).orThrow();
359
+
360
+ expect(accessors.isDirty()).toBe(false);
361
+ expect(accessors.getDirtyPaths()).toEqual([]);
362
+ });
363
+
364
+ test('becomes dirty after saveFileContents', async () => {
365
+ const { fetchImpl } = makeMockFetch([
366
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
367
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
368
+ ]);
369
+
370
+ const accessors = (
371
+ await HttpTreeAccessors.fromHttp({
372
+ baseUrl: 'http://localhost:3000',
373
+ fetchImpl,
374
+ mutable: true
375
+ })
376
+ ).orThrow();
377
+
378
+ accessors.saveFileContents('/data.json', '{"modified":true}').orThrow();
379
+
380
+ expect(accessors.isDirty()).toBe(true);
381
+ expect(accessors.getDirtyPaths()).toContain('/data.json');
382
+ });
383
+
384
+ test('tracks multiple dirty files', async () => {
385
+ const { fetchImpl } = makeMockFetch([
386
+ {
387
+ ok: true,
388
+ jsonValue: {
389
+ path: '/',
390
+ children: [
391
+ { path: '/a.json', name: 'a.json', type: 'file' },
392
+ { path: '/b.json', name: 'b.json', type: 'file' }
393
+ ]
394
+ }
395
+ },
396
+ { ok: true, jsonValue: fileResponse('/a.json', '{}') },
397
+ { ok: true, jsonValue: fileResponse('/b.json', '{}') }
398
+ ]);
399
+
400
+ const accessors = (
401
+ await HttpTreeAccessors.fromHttp({
402
+ baseUrl: 'http://localhost:3000',
403
+ fetchImpl,
404
+ mutable: true
405
+ })
406
+ ).orThrow();
407
+
408
+ accessors.saveFileContents('/a.json', '"a"').orThrow();
409
+ accessors.saveFileContents('/b.json', '"b"').orThrow();
410
+
411
+ expect(accessors.getDirtyPaths()).toHaveLength(2);
412
+ expect(accessors.getDirtyPaths()).toContain('/a.json');
413
+ expect(accessors.getDirtyPaths()).toContain('/b.json');
414
+ });
415
+
416
+ test('tracks deleted files as pending dirty paths', async () => {
417
+ const { fetchImpl } = makeMockFetch([
418
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
419
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
420
+ ]);
421
+
422
+ const accessors = (
423
+ await HttpTreeAccessors.fromHttp({
424
+ baseUrl: 'http://localhost:3000',
425
+ fetchImpl,
426
+ mutable: true
427
+ })
428
+ ).orThrow();
429
+
430
+ accessors.deleteFile('/data.json').orThrow();
431
+
432
+ expect(accessors.isDirty()).toBe(true);
433
+ expect(accessors.getDirtyPaths()).toContain('/data.json');
434
+ });
435
+ });
436
+
437
+ describe('saveFileContents()', () => {
438
+ test('fails when the file is not found (immutable tree has no matching path)', async () => {
439
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
440
+
441
+ const accessors = (
442
+ await HttpTreeAccessors.fromHttp({ baseUrl: 'http://localhost:3000', fetchImpl })
443
+ ).orThrow();
444
+
445
+ // With mutable: false (default), saveFileContents should fail
446
+ const result = accessors.saveFileContents('/missing.json', '{}');
447
+ expect(result).toFail();
448
+ });
449
+
450
+ test('marks the file as dirty without autoSync', async () => {
451
+ const { fetchImpl } = makeMockFetch([
452
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
453
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
454
+ ]);
455
+
456
+ const accessors = (
457
+ await HttpTreeAccessors.fromHttp({
458
+ baseUrl: 'http://localhost:3000',
459
+ fetchImpl,
460
+ mutable: true
461
+ })
462
+ ).orThrow();
463
+
464
+ const result = accessors.saveFileContents('/data.json', '{"updated":true}');
465
+ expect(result).toSucceedWith('{"updated":true}');
466
+ expect(accessors.isDirty()).toBe(true);
467
+ // No additional fetch calls should have occurred (no autoSync)
468
+ });
469
+
470
+ test('triggers fire-and-forget autoSync when autoSync is enabled', async () => {
471
+ const syncResponses: IMockResponse[] = [
472
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
473
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
474
+ // PUT /file response for sync
475
+ { ok: true, jsonValue: { path: '/data.json', contents: '{"auto":true}' } },
476
+ // POST /sync response
477
+ { ok: true, jsonValue: { synced: 1 } }
478
+ ];
479
+ const { fetchImpl, calls } = makeMockFetch(syncResponses);
480
+
481
+ const accessors = (
482
+ await HttpTreeAccessors.fromHttp({
483
+ baseUrl: 'http://localhost:3000',
484
+ fetchImpl,
485
+ mutable: true,
486
+ autoSync: true
487
+ })
488
+ ).orThrow();
489
+
490
+ const result = accessors.saveFileContents('/data.json', '{"auto":true}');
491
+ expect(result).toSucceedWith('{"auto":true}');
492
+
493
+ // autoSync fires-and-forgets; wait for microtasks to drain
494
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
495
+
496
+ // Verify that PUT + POST /sync were called
497
+ const methodCalls = calls.slice(2).map((c) => c.init?.method);
498
+ expect(methodCalls).toContain('PUT');
499
+ expect(methodCalls).toContain('POST');
500
+ });
501
+
502
+ test('logs when autoSync returns a failure Result', async () => {
503
+ const logger = {
504
+ detail: jest.fn(),
505
+ info: jest.fn(),
506
+ warn: jest.fn(),
507
+ error: jest.fn()
508
+ } as unknown as Logging.LogReporter<unknown>;
509
+
510
+ const { fetchImpl } = makeMockFetch([
511
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
512
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
513
+ ]);
514
+
515
+ const accessors = (
516
+ await HttpTreeAccessors.fromHttp({
517
+ baseUrl: 'http://localhost:3000',
518
+ fetchImpl,
519
+ mutable: true,
520
+ autoSync: true,
521
+ logger
522
+ })
523
+ ).orThrow();
524
+
525
+ (accessors as unknown as { syncToDisk: () => Promise<ReturnType<typeof fail<void>>> }).syncToDisk =
526
+ async () => fail<void>('simulated sync failure');
527
+
528
+ accessors.saveFileContents('/data.json', '{"auto":true}').orThrow();
529
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
530
+
531
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('simulated sync failure'));
532
+ });
533
+
534
+ test('logs when autoSync throws unexpectedly', async () => {
535
+ const logger = {
536
+ detail: jest.fn(),
537
+ info: jest.fn(),
538
+ warn: jest.fn(),
539
+ error: jest.fn()
540
+ } as unknown as Logging.LogReporter<unknown>;
541
+
542
+ const { fetchImpl } = makeMockFetch([
543
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
544
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
545
+ ]);
546
+
547
+ const accessors = (
548
+ await HttpTreeAccessors.fromHttp({
549
+ baseUrl: 'http://localhost:3000',
550
+ fetchImpl,
551
+ mutable: true,
552
+ autoSync: true,
553
+ logger
554
+ })
555
+ ).orThrow();
556
+
557
+ (accessors as unknown as { syncToDisk: () => Promise<unknown> }).syncToDisk = async () => {
558
+ throw new Error('simulated throw');
559
+ };
560
+
561
+ accessors.saveFileContents('/data.json', '{"auto":true}').orThrow();
562
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
563
+
564
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('simulated throw'));
565
+ });
566
+ });
567
+
568
+ describe('fileIsMutable()', () => {
569
+ test('returns persistent detail when file exists and mutable is true', async () => {
570
+ const { fetchImpl } = makeMockFetch([
571
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
572
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
573
+ ]);
574
+
575
+ const accessors = (
576
+ await HttpTreeAccessors.fromHttp({
577
+ baseUrl: 'http://localhost:3000',
578
+ fetchImpl,
579
+ mutable: true
580
+ })
581
+ ).orThrow();
582
+
583
+ const result = accessors.fileIsMutable('/data.json');
584
+ expect(result.isSuccess()).toBe(true);
585
+ if (result.isSuccess()) {
586
+ expect(result.value).toBe(true);
587
+ expect(result.detail).toBe('persistent');
588
+ }
589
+ });
590
+
591
+ test('returns not-mutable detail when mutable is false', async () => {
592
+ const { fetchImpl } = makeMockFetch([
593
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
594
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
595
+ ]);
596
+
597
+ const accessors = (
598
+ await HttpTreeAccessors.fromHttp({
599
+ baseUrl: 'http://localhost:3000',
600
+ fetchImpl,
601
+ mutable: false
602
+ })
603
+ ).orThrow();
604
+
605
+ const result = accessors.fileIsMutable('/data.json');
606
+ expect(result.isFailure()).toBe(true);
607
+ if (result.isFailure()) {
608
+ expect(result.detail).toBe('not-mutable');
609
+ }
610
+ });
611
+
612
+ test('returns persistent detail for any path when mutable is true (no path existence check)', async () => {
613
+ // InMemoryTreeAccessors checks the mutable config, not path existence.
614
+ // HttpTreeAccessors layers "persistent" on top of a successful mutable check.
615
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
616
+
617
+ const accessors = (
618
+ await HttpTreeAccessors.fromHttp({
619
+ baseUrl: 'http://localhost:3000',
620
+ fetchImpl,
621
+ mutable: true
622
+ })
623
+ ).orThrow();
624
+
625
+ // Any path succeeds as "persistent" when mutable: true
626
+ const result = accessors.fileIsMutable('/nonexistent.json');
627
+ expect(result.isSuccess()).toBe(true);
628
+ if (result.isSuccess()) {
629
+ expect(result.value).toBe(true);
630
+ expect(result.detail).toBe('persistent');
631
+ }
632
+ });
633
+ });
634
+
635
+ describe('syncToDisk()', () => {
636
+ test('succeeds immediately with no dirty files', async () => {
637
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
638
+
639
+ const accessors = (
640
+ await HttpTreeAccessors.fromHttp({ baseUrl: 'http://localhost:3000', fetchImpl })
641
+ ).orThrow();
642
+
643
+ const result = await accessors.syncToDisk();
644
+ expect(result).toSucceed();
645
+ });
646
+
647
+ test('PUTs each dirty file then POSTs /sync', async () => {
648
+ const { fetchImpl, calls } = makeMockFetch([
649
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
650
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
651
+ { ok: true, jsonValue: fileResponse('/data.json', '{"new":1}') },
652
+ { ok: true, jsonValue: { synced: 1 } }
653
+ ]);
654
+
655
+ const accessors = (
656
+ await HttpTreeAccessors.fromHttp({
657
+ baseUrl: 'http://localhost:3000',
658
+ fetchImpl,
659
+ mutable: true
660
+ })
661
+ ).orThrow();
662
+
663
+ accessors.saveFileContents('/data.json', '{"new":1}').orThrow();
664
+ const result = await accessors.syncToDisk();
665
+
666
+ expect(result).toSucceed();
667
+ const syncCalls = calls.slice(2);
668
+ expect(syncCalls[0].url).toContain('/file');
669
+ expect(syncCalls[0].init?.method).toBe('PUT');
670
+ expect(syncCalls[1].url).toContain('/sync');
671
+ expect(syncCalls[1].init?.method).toBe('POST');
672
+ });
673
+
674
+ test('clears dirty state after successful sync', async () => {
675
+ const { fetchImpl } = makeMockFetch([
676
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
677
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
678
+ { ok: true, jsonValue: fileResponse('/data.json', '"updated"') },
679
+ { ok: true, jsonValue: { synced: 1 } }
680
+ ]);
681
+
682
+ const accessors = (
683
+ await HttpTreeAccessors.fromHttp({
684
+ baseUrl: 'http://localhost:3000',
685
+ fetchImpl,
686
+ mutable: true
687
+ })
688
+ ).orThrow();
689
+
690
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
691
+ expect(accessors.isDirty()).toBe(true);
692
+
693
+ await accessors.syncToDisk();
694
+ expect(accessors.isDirty()).toBe(false);
695
+ expect(accessors.getDirtyPaths()).toEqual([]);
696
+ });
697
+
698
+ test('includes namespace in PUT body and POST /sync body when provided', async () => {
699
+ const { fetchImpl, calls } = makeMockFetch([
700
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
701
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
702
+ { ok: true, jsonValue: fileResponse('/data.json', '"v2"') },
703
+ { ok: true, jsonValue: { synced: 1 } }
704
+ ]);
705
+
706
+ const accessors = (
707
+ await HttpTreeAccessors.fromHttp({
708
+ baseUrl: 'http://localhost:3000',
709
+ namespace: 'myns',
710
+ fetchImpl,
711
+ mutable: true
712
+ })
713
+ ).orThrow();
714
+
715
+ accessors.saveFileContents('/data.json', '"v2"').orThrow();
716
+ await accessors.syncToDisk();
717
+
718
+ const putBody = JSON.parse(calls[2].init?.body as string) as Record<string, unknown>;
719
+ expect(putBody.namespace).toBe('myns');
720
+
721
+ const syncBody = JSON.parse(calls[3].init?.body as string) as Record<string, unknown>;
722
+ expect(syncBody.namespace).toBe('myns');
723
+ });
724
+
725
+ test('omits namespace from PUT body and POST /sync body when not provided', async () => {
726
+ const { fetchImpl, calls } = makeMockFetch([
727
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
728
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
729
+ { ok: true, jsonValue: fileResponse('/data.json', '"v2"') },
730
+ { ok: true, jsonValue: { synced: 1 } }
731
+ ]);
732
+
733
+ const accessors = (
734
+ await HttpTreeAccessors.fromHttp({
735
+ baseUrl: 'http://localhost:3000',
736
+ fetchImpl,
737
+ mutable: true
738
+ })
739
+ ).orThrow();
740
+
741
+ accessors.saveFileContents('/data.json', '"v2"').orThrow();
742
+ await accessors.syncToDisk();
743
+
744
+ const putBody = JSON.parse(calls[2].init?.body as string) as Record<string, unknown>;
745
+ expect(putBody.namespace).toBeUndefined();
746
+
747
+ const syncBody = JSON.parse(calls[3].init?.body as string) as Record<string, unknown>;
748
+ expect(syncBody.namespace).toBeUndefined();
749
+ });
750
+
751
+ test('fails when PUT for a dirty file returns a non-ok response', async () => {
752
+ const { fetchImpl } = makeMockFetch([
753
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
754
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
755
+ { ok: false, status: 500, textValue: 'Server Error' }
756
+ ]);
757
+
758
+ const accessors = (
759
+ await HttpTreeAccessors.fromHttp({
760
+ baseUrl: 'http://localhost:3000',
761
+ fetchImpl,
762
+ mutable: true
763
+ })
764
+ ).orThrow();
765
+
766
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
767
+ const result = await accessors.syncToDisk();
768
+
769
+ expect(result).toFailWith(/sync.*data\.json.*server error/i);
770
+ });
771
+
772
+ test('fails when PUT for a dirty file encounters a network error', async () => {
773
+ let callCount = 0;
774
+ const fetchImpl: typeof fetch = (_url, _init) => {
775
+ callCount++;
776
+ if (callCount === 1) {
777
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
778
+ }
779
+ if (callCount === 2) {
780
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') }));
781
+ }
782
+ return Promise.reject(new Error('PUT network error'));
783
+ };
784
+
785
+ const accessors = (
786
+ await HttpTreeAccessors.fromHttp({
787
+ baseUrl: 'http://localhost:3000',
788
+ fetchImpl,
789
+ mutable: true
790
+ })
791
+ ).orThrow();
792
+
793
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
794
+ const result = await accessors.syncToDisk();
795
+
796
+ expect(result).toFailWith(/put network error/i);
797
+ });
798
+
799
+ test('fails when POST /sync returns a non-ok response', async () => {
800
+ const { fetchImpl } = makeMockFetch([
801
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
802
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
803
+ { ok: true, jsonValue: fileResponse('/data.json', '"v2"') },
804
+ { ok: false, status: 503, textValue: 'Service Unavailable' }
805
+ ]);
806
+
807
+ const accessors = (
808
+ await HttpTreeAccessors.fromHttp({
809
+ baseUrl: 'http://localhost:3000',
810
+ fetchImpl,
811
+ mutable: true
812
+ })
813
+ ).orThrow();
814
+
815
+ accessors.saveFileContents('/data.json', '"v2"').orThrow();
816
+ const result = await accessors.syncToDisk();
817
+
818
+ expect(result).toFailWith(/service unavailable/i);
819
+ });
820
+
821
+ test('fails when POST /sync encounters a network error', async () => {
822
+ let callCount = 0;
823
+ const fetchImpl: typeof fetch = (_url, _init) => {
824
+ callCount++;
825
+ if (callCount === 1) {
826
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
827
+ }
828
+ if (callCount === 2) {
829
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') }));
830
+ }
831
+ if (callCount === 3) {
832
+ return Promise.resolve(
833
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '"v2"') })
834
+ );
835
+ }
836
+ return Promise.reject(new Error('POST network error'));
837
+ };
838
+
839
+ const accessors = (
840
+ await HttpTreeAccessors.fromHttp({
841
+ baseUrl: 'http://localhost:3000',
842
+ fetchImpl,
843
+ mutable: true
844
+ })
845
+ ).orThrow();
846
+
847
+ accessors.saveFileContents('/data.json', '"v2"').orThrow();
848
+ const result = await accessors.syncToDisk();
849
+
850
+ expect(result).toFailWith(/post network error/i);
851
+ });
852
+
853
+ test('syncs multiple dirty files in order', async () => {
854
+ const { fetchImpl, calls } = makeMockFetch([
855
+ {
856
+ ok: true,
857
+ jsonValue: {
858
+ path: '/',
859
+ children: [
860
+ { path: '/a.json', name: 'a.json', type: 'file' },
861
+ { path: '/b.json', name: 'b.json', type: 'file' }
862
+ ]
863
+ }
864
+ },
865
+ { ok: true, jsonValue: fileResponse('/a.json', '{}') },
866
+ { ok: true, jsonValue: fileResponse('/b.json', '{}') },
867
+ { ok: true, jsonValue: fileResponse('/a.json', '"a-updated"') },
868
+ { ok: true, jsonValue: fileResponse('/b.json', '"b-updated"') },
869
+ { ok: true, jsonValue: { synced: 2 } }
870
+ ]);
871
+
872
+ const accessors = (
873
+ await HttpTreeAccessors.fromHttp({
874
+ baseUrl: 'http://localhost:3000',
875
+ fetchImpl,
876
+ mutable: true
877
+ })
878
+ ).orThrow();
879
+
880
+ accessors.saveFileContents('/a.json', '"a-updated"').orThrow();
881
+ accessors.saveFileContents('/b.json', '"b-updated"').orThrow();
882
+
883
+ const result = await accessors.syncToDisk();
884
+ expect(result).toSucceed();
885
+
886
+ // Verify 2 PUTs + 1 POST
887
+ const syncCalls = calls.slice(3);
888
+ const methods = syncCalls.map((c) => c.init?.method);
889
+ expect(methods.filter((m) => m === 'PUT')).toHaveLength(2);
890
+ expect(methods.filter((m) => m === 'POST')).toHaveLength(1);
891
+ });
892
+
893
+ test('DELETEs pending deletions before POST /sync', async () => {
894
+ const { fetchImpl, calls } = makeMockFetch([
895
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
896
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
897
+ { ok: true, jsonValue: { deleted: true } },
898
+ { ok: true, jsonValue: { synced: 0 } }
899
+ ]);
900
+
901
+ const accessors = (
902
+ await HttpTreeAccessors.fromHttp({
903
+ baseUrl: 'http://localhost:3000',
904
+ fetchImpl,
905
+ mutable: true
906
+ })
907
+ ).orThrow();
908
+
909
+ accessors.deleteFile('/data.json').orThrow();
910
+ const result = await accessors.syncToDisk();
911
+
912
+ expect(result).toSucceed();
913
+ const syncCalls = calls.slice(2);
914
+ expect(syncCalls[0].init?.method).toBe('DELETE');
915
+ expect(syncCalls[0].url).toContain('/file?');
916
+ expect(syncCalls[1].init?.method).toBe('POST');
917
+ expect(accessors.isDirty()).toBe(false);
918
+ });
919
+
920
+ test('fails when DELETE for pending deletion returns non-ok response', async () => {
921
+ const { fetchImpl } = makeMockFetch([
922
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
923
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
924
+ { ok: false, status: 500, textValue: 'Delete failed' }
925
+ ]);
926
+
927
+ const accessors = (
928
+ await HttpTreeAccessors.fromHttp({
929
+ baseUrl: 'http://localhost:3000',
930
+ fetchImpl,
931
+ mutable: true
932
+ })
933
+ ).orThrow();
934
+
935
+ accessors.deleteFile('/data.json').orThrow();
936
+ const result = await accessors.syncToDisk();
937
+
938
+ expect(result).toFailWith(/delete.*data\.json.*delete failed/i);
939
+ });
940
+ });
941
+
942
+ describe('syncToDisk() - getFileContents failure', () => {
943
+ test('fails when getFileContents returns failure for a dirty file during sync', async () => {
944
+ // This covers lines 112-113: the contentsResult.isFailure() branch in syncToDisk.
945
+ // We load a file, mark it dirty, then sabotage getFileContents to fail.
946
+ const { fetchImpl } = makeMockFetch([
947
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
948
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
949
+ ]);
950
+
951
+ const accessors = (
952
+ await HttpTreeAccessors.fromHttp({
953
+ baseUrl: 'http://localhost:3000',
954
+ fetchImpl,
955
+ mutable: true
956
+ })
957
+ ).orThrow();
958
+
959
+ accessors.saveFileContents('/data.json', '{"new":1}').orThrow();
960
+
961
+ // Sabotage the base getFileContents to simulate a failure
962
+ const originalGet = accessors.getFileContents.bind(accessors);
963
+ accessors.getFileContents = (path: string) => {
964
+ if (path === '/data.json') {
965
+ // eslint-disable-next-line import/no-internal-modules
966
+ const { fail: failResult } = require('@fgv/ts-utils') as typeof import('@fgv/ts-utils');
967
+ return failResult('simulated get failure');
968
+ }
969
+ return originalGet(path);
970
+ };
971
+
972
+ const result = await accessors.syncToDisk();
973
+ expect(result).toFailWith(/simulated get failure/i);
974
+ });
975
+ });
976
+
977
+ describe('_request() invalid JSON during sync', () => {
978
+ test('fails when PUT /file returns invalid JSON', async () => {
979
+ // Covers lines 225-226: _request() returns fail('invalid JSON response')
980
+ // when response.json() throws during a sync PUT.
981
+ const { fetchImpl } = makeMockFetch([
982
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
983
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
984
+ // PUT response with ok=true but throwOnJson simulates invalid JSON body
985
+ { ok: true, throwOnJson: true }
986
+ ]);
987
+
988
+ const accessors = (
989
+ await HttpTreeAccessors.fromHttp({
990
+ baseUrl: 'http://localhost:3000',
991
+ fetchImpl,
992
+ mutable: true
993
+ })
994
+ ).orThrow();
995
+
996
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
997
+ const result = await accessors.syncToDisk();
998
+
999
+ expect(result).toFailWith(/invalid json/i);
1000
+ });
1001
+ });
1002
+
1003
+ describe('fromHttp() with inferContentType', () => {
1004
+ test('calls inferContentType when provided and uses the result', async () => {
1005
+ // Covers line 270: params.inferContentType?.(...).orDefault()
1006
+ const { fetchImpl } = makeMockFetch([
1007
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1008
+ { ok: true, jsonValue: fileResponse('/data.json', '{}', 'application/json') }
1009
+ ]);
1010
+
1011
+ const result = await HttpTreeAccessors.fromHttp({
1012
+ baseUrl: 'http://localhost:3000',
1013
+ fetchImpl,
1014
+ inferContentType: (path, provided) => {
1015
+ if (provided === 'application/json') {
1016
+ const { succeed: s } = require('@fgv/ts-utils') as typeof import('@fgv/ts-utils');
1017
+ return s('json' as string);
1018
+ }
1019
+ const { succeed: s } = require('@fgv/ts-utils') as typeof import('@fgv/ts-utils');
1020
+ return s(undefined);
1021
+ }
1022
+ });
1023
+
1024
+ expect(result).toSucceed();
1025
+ });
1026
+ });
1027
+
1028
+ describe('_request() error handling', () => {
1029
+ test('returns failure with error message for network error (Error instance throw) during sync', async () => {
1030
+ // Covers line 214 true branch: response.err instanceof Error -> uses .message
1031
+ let callCount = 0;
1032
+ const fetchImpl: typeof fetch = (_url, _init) => {
1033
+ callCount++;
1034
+ if (callCount === 1) {
1035
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1036
+ }
1037
+ if (callCount === 2) {
1038
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') }));
1039
+ }
1040
+ // PUT request throws an Error instance
1041
+ return Promise.reject(new Error('real Error instance'));
1042
+ };
1043
+
1044
+ const accessors = (
1045
+ await HttpTreeAccessors.fromHttp({
1046
+ baseUrl: 'http://localhost:3000',
1047
+ fetchImpl,
1048
+ mutable: true
1049
+ })
1050
+ ).orThrow();
1051
+
1052
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1053
+ const result = await accessors.syncToDisk();
1054
+
1055
+ expect(result).toFailWith(/real error instance/i);
1056
+ });
1057
+
1058
+ test('returns failure with error message for non-Error throw during sync PUT', async () => {
1059
+ // Covers line 214 false branch: thrown value is not an Error instance -> uses String(response.err)
1060
+ // Must be triggered via syncToDisk() which uses the instance _request() method.
1061
+ let callCount = 0;
1062
+ const fetchImpl: typeof fetch = (_url, _init) => {
1063
+ callCount++;
1064
+ if (callCount === 1) {
1065
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1066
+ }
1067
+ if (callCount === 2) {
1068
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') }));
1069
+ }
1070
+ // Non-Error throw (e.g., a plain string)
1071
+ return Promise.reject('non-error string rejection');
1072
+ };
1073
+
1074
+ const accessors = (
1075
+ await HttpTreeAccessors.fromHttp({
1076
+ baseUrl: 'http://localhost:3000',
1077
+ fetchImpl,
1078
+ mutable: true
1079
+ })
1080
+ ).orThrow();
1081
+
1082
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1083
+ const result = await accessors.syncToDisk();
1084
+
1085
+ expect(result).toFailWith(/non-error string rejection/i);
1086
+ });
1087
+
1088
+ test('returns failure with HTTP status fallback when response.text() throws during sync', async () => {
1089
+ // Covers the text() catch branch in _request(): uses `HTTP ${status}` fallback
1090
+ let callCount = 0;
1091
+ const fetchImpl: typeof fetch = (_url, _init) => {
1092
+ callCount++;
1093
+ if (callCount === 1) {
1094
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1095
+ }
1096
+ if (callCount === 2) {
1097
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') }));
1098
+ }
1099
+ return Promise.resolve(makeMockResponse({ ok: false, status: 502, throwOnText: true }));
1100
+ };
1101
+
1102
+ const accessors = (
1103
+ await HttpTreeAccessors.fromHttp({
1104
+ baseUrl: 'http://localhost:3000',
1105
+ fetchImpl,
1106
+ mutable: true
1107
+ })
1108
+ ).orThrow();
1109
+
1110
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1111
+ const result = await accessors.syncToDisk();
1112
+
1113
+ expect(result).toFailWith(/http 502/i);
1114
+ });
1115
+ });
1116
+
1117
+ describe('_requestWithParams() error handling', () => {
1118
+ test('returns failure with error message for non-Error network throw during init', async () => {
1119
+ // _requestWithParams is used for GET requests during fromHttp(); test non-Error throw branch
1120
+ const fetchImpl: typeof fetch = (_url, _init) => {
1121
+ return Promise.reject(42);
1122
+ };
1123
+
1124
+ const result = await HttpTreeAccessors.fromHttp({
1125
+ baseUrl: 'http://localhost:3000',
1126
+ fetchImpl
1127
+ });
1128
+
1129
+ expect(result).toFailWith(/42/);
1130
+ });
1131
+
1132
+ test('returns failure with HTTP status fallback when response.text() throws during init', async () => {
1133
+ const fetchImpl: typeof fetch = (_url, _init) => {
1134
+ return Promise.resolve(makeMockResponse({ ok: false, status: 504, throwOnText: true }));
1135
+ };
1136
+
1137
+ const result = await HttpTreeAccessors.fromHttp({
1138
+ baseUrl: 'http://localhost:3000',
1139
+ fetchImpl
1140
+ });
1141
+
1142
+ expect(result).toFailWith(/http 504/i);
1143
+ });
1144
+
1145
+ test('uses globalThis.fetch when no fetchImpl provided', async () => {
1146
+ // Covers line 48: the `fetchImpl ?? globalThis.fetch` right-side branch.
1147
+ // We temporarily replace globalThis.fetch with a mock that returns an empty tree.
1148
+ const originalFetch = globalThis.fetch;
1149
+ let fetchCallCount = 0;
1150
+
1151
+ globalThis.fetch = (_url: string | URL | Request, _init?: RequestInit) => {
1152
+ fetchCallCount++;
1153
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: { path: '/', children: [] } }));
1154
+ };
1155
+
1156
+ try {
1157
+ const result = await HttpTreeAccessors.fromHttp({
1158
+ baseUrl: 'http://localhost:3000'
1159
+ // No fetchImpl - should fall back to globalThis.fetch
1160
+ });
1161
+
1162
+ expect(result).toSucceed();
1163
+ expect(fetchCallCount).toBeGreaterThan(0);
1164
+ } finally {
1165
+ globalThis.fetch = originalFetch;
1166
+ }
1167
+ });
1168
+ });
1169
+
1170
+ describe('userId header in _request()', () => {
1171
+ test('includes X-User-Id header in PUT /file and POST /sync requests when userId is set', async () => {
1172
+ // Covers line 259: the this._userId branch in _request()
1173
+ const { fetchImpl, calls } = makeMockFetch([
1174
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1175
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1176
+ { ok: true, jsonValue: fileResponse('/data.json', '"updated"') },
1177
+ { ok: true, jsonValue: { synced: 1 } }
1178
+ ]);
1179
+
1180
+ const accessors = (
1181
+ await HttpTreeAccessors.fromHttp({
1182
+ baseUrl: 'http://localhost:3000',
1183
+ fetchImpl,
1184
+ mutable: true,
1185
+ userId: 'test-user-123'
1186
+ })
1187
+ ).orThrow();
1188
+
1189
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1190
+ const result = await accessors.syncToDisk();
1191
+ expect(result).toSucceed();
1192
+
1193
+ // The PUT and POST requests should include the X-User-Id header
1194
+ const syncCalls = calls.slice(2);
1195
+ for (const call of syncCalls) {
1196
+ const headers = call.init?.headers as Record<string, string> | undefined;
1197
+ expect(headers?.['X-User-Id']).toBe('test-user-123');
1198
+ }
1199
+ });
1200
+ });
1201
+
1202
+ describe('deleteFile()', () => {
1203
+ test('fails when the underlying InMemoryTreeAccessors deleteFile fails (file not found)', async () => {
1204
+ // Covers lines 200-201: result.isFailure() branch in deleteFile
1205
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
1206
+
1207
+ const accessors = (
1208
+ await HttpTreeAccessors.fromHttp({ baseUrl: 'http://localhost:3000', fetchImpl, mutable: true })
1209
+ ).orThrow();
1210
+
1211
+ // Delete a file that does not exist — super.deleteFile should fail
1212
+ const result = accessors.deleteFile('/nonexistent.json');
1213
+ expect(result).toFail();
1214
+ });
1215
+
1216
+ test('includes namespace in DELETE query params when namespace is configured', async () => {
1217
+ // Covers lines 131-132: the namespace branch in syncToDisk's pending-deletion loop
1218
+ const { fetchImpl, calls } = makeMockFetch([
1219
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1220
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1221
+ { ok: true, jsonValue: { deleted: true } },
1222
+ { ok: true, jsonValue: { synced: 0 } }
1223
+ ]);
1224
+
1225
+ const accessors = (
1226
+ await HttpTreeAccessors.fromHttp({
1227
+ baseUrl: 'http://localhost:3000',
1228
+ namespace: 'my-namespace',
1229
+ fetchImpl,
1230
+ mutable: true
1231
+ })
1232
+ ).orThrow();
1233
+
1234
+ accessors.deleteFile('/data.json').orThrow();
1235
+ const result = await accessors.syncToDisk();
1236
+
1237
+ expect(result).toSucceed();
1238
+
1239
+ // The DELETE request URL should include namespace as a query parameter
1240
+ const deleteCalls = calls.filter((c) => c.init?.method === 'DELETE');
1241
+ expect(deleteCalls).toHaveLength(1);
1242
+ expect(deleteCalls[0].url).toContain('namespace=my-namespace');
1243
+ });
1244
+
1245
+ test('triggers fire-and-forget autoSync after successful delete when autoSync is enabled', async () => {
1246
+ // Covers lines 209-212: the autoSync branch in deleteFile
1247
+ const syncResponses: IMockResponse[] = [
1248
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1249
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1250
+ // DELETE /file response for pending deletion
1251
+ { ok: true, jsonValue: { deleted: true } },
1252
+ // POST /sync response
1253
+ { ok: true, jsonValue: { synced: 0 } }
1254
+ ];
1255
+ const { fetchImpl, calls } = makeMockFetch(syncResponses);
1256
+
1257
+ const accessors = (
1258
+ await HttpTreeAccessors.fromHttp({
1259
+ baseUrl: 'http://localhost:3000',
1260
+ fetchImpl,
1261
+ mutable: true,
1262
+ autoSync: true
1263
+ })
1264
+ ).orThrow();
1265
+
1266
+ const result = accessors.deleteFile('/data.json');
1267
+ expect(result).toSucceedWith(true);
1268
+
1269
+ // autoSync fires-and-forgets; wait for microtasks to drain
1270
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
1271
+
1272
+ // Verify that DELETE + POST /sync were called
1273
+ const methodCalls = calls.slice(2).map((c) => c.init?.method);
1274
+ expect(methodCalls).toContain('DELETE');
1275
+ expect(methodCalls).toContain('POST');
1276
+ });
1277
+ });
1278
+ });