@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
@@ -12,5 +12,8 @@
12
12
  }
13
13
  },
14
14
  "collectCoverage": true,
15
- "coverageReporters": ["text", "lcov", "html"]
15
+ "coverageReporters": ["text", "lcov", "html"],
16
+ "moduleNameMapper": {
17
+ "^idb-keyval$": "<rootDir>/lib/test/mocks/idb-keyval.js"
18
+ }
16
19
  }
@@ -0,0 +1,6 @@
1
+ {
2
+ "$schema": "https://typedoc.org/schema.json",
3
+ "extends": ["@fgv/heft-dual-rig/profiles/default/config/typedoc.base.json"],
4
+ "entryPoints": ["../src/index.ts"],
5
+ "out": "../docs"
6
+ }
package/dist/index.js CHANGED
@@ -29,8 +29,8 @@
29
29
  *
30
30
  * @packageDocumentation
31
31
  */
32
- // Export crypto functionality
33
- export * from './packlets/crypto';
32
+ import * as CryptoUtils from './packlets/crypto-utils';
33
+ export { CryptoUtils };
34
34
  // Export file tree functionality
35
35
  export * from './packlets/file-tree';
36
36
  // Export helper functions
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;;;;;;GASG;AAEH,8BAA8B;AAC9B,cAAc,mBAAmB,CAAC;AAElC,iCAAiC;AACjC,cAAc,sBAAsB,CAAC;AAErC,0BAA0B;AAC1B,cAAc,oBAAoB,CAAC;AAEnC,sCAAsC;AACtC,cAAc,2BAA2B,CAAC;AAE1C,uBAAuB;AACvB,cAAc,sBAAsB,CAAC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Browser-compatible utilities and FileTree implementations.\n *\n * This library provides browser-compatible alternatives to Node.js-specific functionality,\n * including Web Crypto API-based hashing, File API-based file tree implementations,\n * and URL parameter parsing utilities.\n * All exports are designed to be tree-shakeable for optimal bundle size.\n *\n * @packageDocumentation\n */\n\n// Export crypto functionality\nexport * from './packlets/crypto';\n\n// Export file tree functionality\nexport * from './packlets/file-tree';\n\n// Export helper functions\nexport * from './packlets/helpers';\n\n// Export File System Access API types\nexport * from './packlets/file-api-types';\n\n// Export URL utilities\nexport * from './packlets/url-utils';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;;;;;;GASG;AAEH,OAAO,KAAK,WAAW,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,CAAC;AAEvB,iCAAiC;AACjC,cAAc,sBAAsB,CAAC;AAErC,0BAA0B;AAC1B,cAAc,oBAAoB,CAAC;AAEnC,sCAAsC;AACtC,cAAc,2BAA2B,CAAC;AAE1C,uBAAuB;AACvB,cAAc,sBAAsB,CAAC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Browser-compatible utilities and FileTree implementations.\n *\n * This library provides browser-compatible alternatives to Node.js-specific functionality,\n * including Web Crypto API-based hashing, File API-based file tree implementations,\n * and URL parameter parsing utilities.\n * All exports are designed to be tree-shakeable for optimal bundle size.\n *\n * @packageDocumentation\n */\n\nimport * as CryptoUtils from './packlets/crypto-utils';\nexport { CryptoUtils };\n\n// Export file tree functionality\nexport * from './packlets/file-tree';\n\n// Export helper functions\nexport * from './packlets/helpers';\n\n// Export File System Access API types\nexport * from './packlets/file-api-types';\n\n// Export URL utilities\nexport * from './packlets/url-utils';\n"]}
@@ -0,0 +1,254 @@
1
+ // Copyright (c) 2024 Erik Fortune
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ // of this software and associated documentation files (the "Software"), to deal
5
+ // in the Software without restriction, including without limitation the rights
6
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ // copies of the Software, and to permit persons to whom the Software is
8
+ // furnished to do so, subject to the following conditions:
9
+ //
10
+ // The above copyright notice and this permission notice shall be included in all
11
+ // copies or substantial portions of the Software.
12
+ //
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ // SOFTWARE.
20
+ /* c8 ignore start - Browser-only implementation cannot be tested in Node.js environment */
21
+ import { captureResult, Failure, Success } from '@fgv/ts-utils';
22
+ import { CryptoUtils } from '@fgv/ts-extras';
23
+ const CryptoConstants = CryptoUtils.Constants;
24
+ /**
25
+ * Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.
26
+ * @param arr - The Uint8Array to extract from
27
+ * @returns An `ArrayBuffer` containing a copy of the data.
28
+ */
29
+ function toArrayBuffer(arr) {
30
+ // Create a new ArrayBuffer and copy the data - this handles both ArrayBuffer and SharedArrayBuffer
31
+ const buffer = new ArrayBuffer(arr.byteLength);
32
+ new Uint8Array(buffer).set(arr);
33
+ return buffer;
34
+ }
35
+ /**
36
+ * Browser implementation of `ICryptoProvider` using the Web Crypto API.
37
+ * Uses AES-256-GCM for authenticated encryption.
38
+ *
39
+ * Note: This provider requires a browser environment with Web Crypto API support.
40
+ * In Node.js 15+, Web Crypto is available via globalThis.crypto or require('crypto').webcrypto.
41
+ *
42
+ * @public
43
+ */
44
+ export class BrowserCryptoProvider {
45
+ /**
46
+ * Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.
47
+ * @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)
48
+ */
49
+ constructor(cryptoApi) {
50
+ if (cryptoApi) {
51
+ this._crypto = cryptoApi;
52
+ }
53
+ else if (typeof globalThis !== 'undefined' && globalThis.crypto) {
54
+ this._crypto = globalThis.crypto;
55
+ }
56
+ else if (typeof window !== 'undefined' && window.crypto) {
57
+ this._crypto = window.crypto;
58
+ }
59
+ else {
60
+ throw new Error('Web Crypto API not available');
61
+ }
62
+ }
63
+ /**
64
+ * Encrypts plaintext using AES-256-GCM.
65
+ * @param plaintext - UTF-8 string to encrypt
66
+ * @param key - 32-byte encryption key
67
+ * @returns `Success` with encryption result, or `Failure` with an error.
68
+ */
69
+ async encrypt(plaintext, key) {
70
+ if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {
71
+ return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
72
+ }
73
+ try {
74
+ // Generate random IV
75
+ const iv = this._crypto.getRandomValues(new Uint8Array(CryptoConstants.GCM_IV_SIZE));
76
+ // Import the key
77
+ const cryptoKey = await this._crypto.subtle.importKey('raw', toArrayBuffer(key), { name: 'AES-GCM' }, false, ['encrypt']);
78
+ // Encode plaintext to bytes
79
+ const encoder = new TextEncoder();
80
+ const plaintextBytes = encoder.encode(plaintext);
81
+ // Encrypt (Web Crypto appends auth tag to ciphertext)
82
+ const encryptedWithTag = await this._crypto.subtle.encrypt({
83
+ name: 'AES-GCM',
84
+ iv: iv,
85
+ tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits
86
+ }, cryptoKey, plaintextBytes);
87
+ // Split ciphertext and auth tag (auth tag is last 16 bytes)
88
+ const encryptedArray = new Uint8Array(encryptedWithTag);
89
+ const encryptedData = encryptedArray.slice(0, encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE);
90
+ const authTag = encryptedArray.slice(encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE);
91
+ return Success.with({
92
+ iv,
93
+ authTag,
94
+ encryptedData
95
+ });
96
+ }
97
+ catch (e) {
98
+ const message = e instanceof Error ? e.message : String(e);
99
+ return Failure.with(`Encryption failed: ${message}`);
100
+ }
101
+ }
102
+ /**
103
+ * Decrypts ciphertext using AES-256-GCM.
104
+ * @param encryptedData - Encrypted bytes
105
+ * @param key - 32-byte decryption key
106
+ * @param iv - Initialization vector (12 bytes)
107
+ * @param authTag - GCM authentication tag (16 bytes)
108
+ * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.
109
+ */
110
+ async decrypt(encryptedData, key, iv, authTag) {
111
+ if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {
112
+ return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
113
+ }
114
+ if (iv.length !== CryptoConstants.GCM_IV_SIZE) {
115
+ return Failure.with(`IV must be ${CryptoConstants.GCM_IV_SIZE} bytes, got ${iv.length}`);
116
+ }
117
+ if (authTag.length !== CryptoConstants.GCM_AUTH_TAG_SIZE) {
118
+ return Failure.with(`Auth tag must be ${CryptoConstants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);
119
+ }
120
+ try {
121
+ // Import the key
122
+ const cryptoKey = await this._crypto.subtle.importKey('raw', toArrayBuffer(key), { name: 'AES-GCM' }, false, ['decrypt']);
123
+ // Web Crypto expects ciphertext + auth tag concatenated
124
+ const encryptedWithTag = new Uint8Array(encryptedData.length + authTag.length);
125
+ encryptedWithTag.set(encryptedData);
126
+ encryptedWithTag.set(authTag, encryptedData.length);
127
+ // Decrypt
128
+ const decrypted = await this._crypto.subtle.decrypt({
129
+ name: 'AES-GCM',
130
+ iv: toArrayBuffer(iv),
131
+ tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits
132
+ }, cryptoKey, encryptedWithTag);
133
+ // Decode to string
134
+ const decoder = new TextDecoder();
135
+ return Success.with(decoder.decode(decrypted));
136
+ }
137
+ catch (e) {
138
+ const message = e instanceof Error ? e.message : String(e);
139
+ return Failure.with(`Decryption failed: ${message}`);
140
+ }
141
+ }
142
+ /**
143
+ * Generates a random 32-byte key suitable for AES-256.
144
+ * @returns Success with generated key, or Failure with error
145
+ */
146
+ async generateKey() {
147
+ try {
148
+ return Success.with(this._crypto.getRandomValues(new Uint8Array(CryptoConstants.AES_256_KEY_SIZE)));
149
+ }
150
+ catch (e) {
151
+ const message = e instanceof Error ? e.message : String(e);
152
+ return Failure.with(`Key generation failed: ${message}`);
153
+ }
154
+ }
155
+ /**
156
+ * Derives a key from a password using PBKDF2.
157
+ * @param password - Password string
158
+ * @param salt - Salt bytes (should be at least 16 bytes)
159
+ * @param iterations - Number of iterations (recommend 100000+)
160
+ * @returns Success with derived 32-byte key, or Failure with error
161
+ */
162
+ async deriveKey(password, salt, iterations) {
163
+ if (iterations < 1) {
164
+ return Failure.with('Iterations must be at least 1');
165
+ }
166
+ if (salt.length < 8) {
167
+ return Failure.with('Salt should be at least 8 bytes');
168
+ }
169
+ try {
170
+ // Encode password
171
+ const encoder = new TextEncoder();
172
+ const passwordBytes = encoder.encode(password);
173
+ // Import password as key material
174
+ const keyMaterial = await this._crypto.subtle.importKey('raw', passwordBytes, 'PBKDF2', false, [
175
+ 'deriveBits'
176
+ ]);
177
+ // Derive key bits
178
+ const derivedBits = await this._crypto.subtle.deriveBits({
179
+ name: 'PBKDF2',
180
+ salt: toArrayBuffer(salt),
181
+ iterations: iterations,
182
+ hash: 'SHA-256'
183
+ }, keyMaterial, CryptoConstants.AES_256_KEY_SIZE * 8 // bits
184
+ );
185
+ return Success.with(new Uint8Array(derivedBits));
186
+ }
187
+ catch (e) {
188
+ const message = e instanceof Error ? e.message : String(e);
189
+ return Failure.with(`Key derivation failed: ${message}`);
190
+ }
191
+ }
192
+ // ============================================================================
193
+ // Platform Utility Methods
194
+ // ============================================================================
195
+ /**
196
+ * Generates cryptographically secure random bytes.
197
+ * @param length - Number of bytes to generate
198
+ * @returns Success with random bytes, or Failure with error
199
+ */
200
+ generateRandomBytes(length) {
201
+ if (length < 1) {
202
+ return Failure.with('Length must be at least 1');
203
+ }
204
+ try {
205
+ return Success.with(this._crypto.getRandomValues(new Uint8Array(length)));
206
+ }
207
+ catch (e) {
208
+ const message = e instanceof Error ? e.message : String(e);
209
+ return Failure.with(`Random bytes generation failed: ${message}`);
210
+ }
211
+ }
212
+ /**
213
+ * Encodes binary data to base64 string.
214
+ * @param data - Binary data to encode
215
+ * @returns Base64-encoded string
216
+ */
217
+ toBase64(data) {
218
+ // Convert Uint8Array to binary string, then to base64
219
+ let binary = '';
220
+ for (let i = 0; i < data.length; i++) {
221
+ binary += String.fromCharCode(data[i]);
222
+ }
223
+ return btoa(binary);
224
+ }
225
+ /**
226
+ * Decodes base64 string to binary data.
227
+ * @param base64 - Base64-encoded string
228
+ * @returns Success with decoded bytes, or Failure if invalid base64
229
+ */
230
+ fromBase64(base64) {
231
+ try {
232
+ const binary = atob(base64);
233
+ const bytes = new Uint8Array(binary.length);
234
+ for (let i = 0; i < binary.length; i++) {
235
+ bytes[i] = binary.charCodeAt(i);
236
+ }
237
+ return Success.with(bytes);
238
+ }
239
+ catch (e) {
240
+ return Failure.with('Invalid base64 string');
241
+ }
242
+ }
243
+ }
244
+ /**
245
+ * Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web
246
+ * Crypto API is available.
247
+ * @returns `Success` with provider, or `Failure` if not available
248
+ * @public
249
+ */
250
+ export function createBrowserCryptoProvider() {
251
+ return captureResult(() => new BrowserCryptoProvider());
252
+ }
253
+ /* c8 ignore stop */
254
+ //# sourceMappingURL=browserCryptoProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/browserCryptoProvider.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ,2FAA2F;AAC3F,OAAO,EAAE,aAAa,EAAE,OAAO,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAI7C,MAAM,eAAe,GAAG,WAAW,CAAC,SAAS,CAAC;AAE9C;;;;GAIG;AACH,SAAS,aAAa,CAAC,GAAe;IACpC,mGAAmG;IACnG,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC/C,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChC,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,OAAO,qBAAqB;IAGhC;;;OAGG;IACH,YAAmB,SAAkB;QACnC,IAAI,SAAS,EAAE,CAAC;YACd,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;QAC3B,CAAC;aAAM,IAAI,OAAO,UA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CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACrC,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACzC,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACI,UAAU,CAAC,MAAc;QAC9B,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YAC5B,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC5C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACvC,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAClC,CAAC;YACD,OAAO,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC7B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,OAAO,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B;IACzC,OAAO,aAAa,CAAC,GAAG,EAAE,CAAC,IAAI,qBAAqB,EAAE,CAAC,CAAC;AAC1D,CAAC;AACD,oBAAoB","sourcesContent":["// Copyright (c) 2024 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/* c8 ignore start - Browser-only implementation cannot be tested in Node.js environment */\nimport { captureResult, Failure, Result, Success } from '@fgv/ts-utils';\nimport { CryptoUtils } from '@fgv/ts-extras';\n\ntype ICryptoProvider = CryptoUtils.ICryptoProvider;\ntype IEncryptionResult = CryptoUtils.IEncryptionResult;\nconst CryptoConstants = CryptoUtils.Constants;\n\n/**\n * Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.\n * @param arr - The Uint8Array to extract from\n * @returns An `ArrayBuffer` containing a copy of the data.\n */\nfunction toArrayBuffer(arr: Uint8Array): ArrayBuffer {\n // Create a new ArrayBuffer and copy the data - this handles both ArrayBuffer and SharedArrayBuffer\n const buffer = new ArrayBuffer(arr.byteLength);\n new Uint8Array(buffer).set(arr);\n return buffer;\n}\n\n/**\n * Browser implementation of `ICryptoProvider` using the Web Crypto API.\n * Uses AES-256-GCM for authenticated encryption.\n *\n * Note: This provider requires a browser environment with Web Crypto API support.\n * In Node.js 15+, Web Crypto is available via globalThis.crypto or require('crypto').webcrypto.\n *\n * @public\n */\nexport class BrowserCryptoProvider implements ICryptoProvider {\n private readonly _crypto: Crypto;\n\n /**\n * Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.\n * @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)\n */\n public constructor(cryptoApi?: Crypto) {\n if (cryptoApi) {\n this._crypto = cryptoApi;\n } else if (typeof globalThis !== 'undefined' && globalThis.crypto) {\n this._crypto = globalThis.crypto;\n } else if (typeof window !== 'undefined' && window.crypto) {\n this._crypto = window.crypto;\n } else {\n throw new Error('Web Crypto API not available');\n }\n }\n\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns `Success` with encryption result, or `Failure` with an error.\n */\n public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>> {\n if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n try {\n // Generate random IV\n const iv = this._crypto.getRandomValues(new Uint8Array(CryptoConstants.GCM_IV_SIZE));\n\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['encrypt']\n );\n\n // Encode plaintext to bytes\n const encoder = new TextEncoder();\n const plaintextBytes = encoder.encode(plaintext);\n\n // Encrypt (Web Crypto appends auth tag to ciphertext)\n const encryptedWithTag = await this._crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv,\n tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n plaintextBytes\n );\n\n // Split ciphertext and auth tag (auth tag is last 16 bytes)\n const encryptedArray = new Uint8Array(encryptedWithTag);\n const encryptedData = encryptedArray.slice(\n 0,\n encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE\n );\n const authTag = encryptedArray.slice(encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE);\n return Success.with({\n iv,\n authTag,\n encryptedData\n });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Encryption failed: ${message}`);\n }\n }\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.\n */\n public async decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>> {\n if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== CryptoConstants.GCM_IV_SIZE) {\n return Failure.with(`IV must be ${CryptoConstants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== CryptoConstants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `Auth tag must be ${CryptoConstants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`\n );\n }\n\n try {\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['decrypt']\n );\n\n // Web Crypto expects ciphertext + auth tag concatenated\n const encryptedWithTag = new Uint8Array(encryptedData.length + authTag.length);\n encryptedWithTag.set(encryptedData);\n encryptedWithTag.set(authTag, encryptedData.length);\n\n // Decrypt\n const decrypted = await this._crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: toArrayBuffer(iv),\n tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n encryptedWithTag\n );\n\n // Decode to string\n const decoder = new TextDecoder();\n return Success.with(decoder.decode(decrypted));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Decryption failed: ${message}`);\n }\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns Success with generated key, or Failure with error\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n try {\n return Success.with(this._crypto.getRandomValues(new Uint8Array(CryptoConstants.AES_256_KEY_SIZE)));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key generation failed: ${message}`);\n }\n }\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns Success with derived 32-byte key, or Failure with error\n */\n public async deriveKey(\n password: string,\n salt: Uint8Array,\n iterations: number\n ): Promise<Result<Uint8Array>> {\n if (iterations < 1) {\n return Failure.with('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return Failure.with('Salt should be at least 8 bytes');\n }\n\n try {\n // Encode password\n const encoder = new TextEncoder();\n const passwordBytes = encoder.encode(password);\n\n // Import password as key material\n const keyMaterial = await this._crypto.subtle.importKey('raw', passwordBytes, 'PBKDF2', false, [\n 'deriveBits'\n ]);\n\n // Derive key bits\n const derivedBits = await this._crypto.subtle.deriveBits(\n {\n name: 'PBKDF2',\n salt: toArrayBuffer(salt),\n iterations: iterations,\n hash: 'SHA-256'\n },\n keyMaterial,\n CryptoConstants.AES_256_KEY_SIZE * 8 // bits\n );\n\n return Success.with(new Uint8Array(derivedBits));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key derivation failed: ${message}`);\n }\n }\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n public generateRandomBytes(length: number): Result<Uint8Array> {\n if (length < 1) {\n return Failure.with('Length must be at least 1');\n }\n try {\n return Success.with(this._crypto.getRandomValues(new Uint8Array(length)));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Random bytes generation failed: ${message}`);\n }\n }\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n public toBase64(data: Uint8Array): string {\n // Convert Uint8Array to binary string, then to base64\n let binary = '';\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]);\n }\n return btoa(binary);\n }\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n public fromBase64(base64: string): Result<Uint8Array> {\n try {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return Success.with(bytes);\n } catch (e) {\n return Failure.with('Invalid base64 string');\n }\n }\n}\n\n/**\n * Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web\n * Crypto API is available.\n * @returns `Success` with provider, or `Failure` if not available\n * @public\n */\nexport function createBrowserCryptoProvider(): Result<BrowserCryptoProvider> {\n return captureResult(() => new BrowserCryptoProvider());\n}\n/* c8 ignore stop */\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserHashProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/browserHashProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAU,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAEtD;;;;GAIG;AACH,MAAM,OAAO,mBAAmB;IAC9B;;;;;OAKG;IACI,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,IAAY,EAAE,YAAoB,SAAS;QACxE,IAAI,CAAC;YACH,yCAAyC;YACzC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;gBACnB,OAAO,IAAI,CAAC,kDAAkD,CAAC,CAAC;YAClE,CAAC;YAED,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;YAClC,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACxC,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;YACrE,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;YAC7C,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC;iBAClC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;iBAC3C,IAAI,CAAC,EAAE,CAAC,CAAC;YAEZ,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC;QAC1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,IAAI,CAAC,4BAA4B,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACpG,CAAC;IACH,CAAC;IAED;;;;;;OAMG;IACI,MAAM,CAAC,KAAK,CAAC,SAAS,CAC3B,KAAe,EACf,YAAoB,SAAS,EAC7B,YAAoB,GAAG;QAEvB,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACvC,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IAC9C,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, succeed, fail } from '@fgv/ts-utils';\n\n/**\n * Browser-compatible hash provider using the Web Crypto API.\n * Supports common hash algorithms available in browsers.\n * @public\n */\nexport class BrowserHashProvider {\n /**\n * Hash a string using the specified algorithm.\n * @param data - The string to hash\n * @param algorithm - The hash algorithm to use\n * @returns Promise resolving to the hex-encoded hash\n */\n public static async hashString(data: string, algorithm: string = 'SHA-256'): Promise<Result<string>> {\n try {\n /* c8 ignore next 3 - defense in depth */\n if (!crypto.subtle) {\n return fail('Web Crypto API not available in this environment');\n }\n\n const encoder = new TextEncoder();\n const dataBuffer = encoder.encode(data);\n const hashBuffer = await crypto.subtle.digest(algorithm, dataBuffer);\n const hashArray = new Uint8Array(hashBuffer);\n const hashHex = Array.from(hashArray)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n\n return succeed(hashHex);\n } catch (error) {\n return fail(`Hash computation failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Hash multiple strings concatenated with a separator.\n * @param parts - Array of strings to concatenate and hash\n * @param algorithm - The hash algorithm to use\n * @param separator - Separator to use between parts (default: '|')\n * @returns Promise resolving to the hex-encoded hash\n */\n public static async hashParts(\n parts: string[],\n algorithm: string = 'SHA-256',\n separator: string = '|'\n ): Promise<Result<string>> {\n const combined = parts.join(separator);\n return this.hashString(combined, algorithm);\n }\n}\n"]}
@@ -24,4 +24,5 @@
24
24
  * @packageDocumentation
25
25
  */
26
26
  export * from './browserHashProvider';
27
+ export * from './browserCryptoProvider';
27
28
  //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;GAGG;AAEH,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Browser-compatible cryptographic utilities using the Web Crypto API.\n * @packageDocumentation\n */\n\nexport * from './browserHashProvider';\nexport * from './browserCryptoProvider';\n"]}
@@ -55,7 +55,15 @@ export function isDirectoryHandle(handle) {
55
55
  */
56
56
  export async function safeShowOpenFilePicker(window, options) {
57
57
  if (supportsFileSystemAccess(window)) {
58
- return window.showOpenFilePicker(options);
58
+ try {
59
+ return await window.showOpenFilePicker(options);
60
+ }
61
+ catch (error) {
62
+ if (error instanceof DOMException && error.name === 'AbortError') {
63
+ return null;
64
+ }
65
+ throw error;
66
+ }
59
67
  }
60
68
  return null;
61
69
  }
@@ -68,7 +76,15 @@ export async function safeShowOpenFilePicker(window, options) {
68
76
  */
69
77
  export async function safeShowSaveFilePicker(window, options) {
70
78
  if (supportsFileSystemAccess(window)) {
71
- return window.showSaveFilePicker(options);
79
+ try {
80
+ return await window.showSaveFilePicker(options);
81
+ }
82
+ catch (error) {
83
+ if (error instanceof DOMException && error.name === 'AbortError') {
84
+ return null;
85
+ }
86
+ throw error;
87
+ }
72
88
  }
73
89
  return null;
74
90
  }
@@ -81,7 +97,15 @@ export async function safeShowSaveFilePicker(window, options) {
81
97
  */
82
98
  export async function safeShowDirectoryPicker(window, options) {
83
99
  if (supportsFileSystemAccess(window)) {
84
- return window.showDirectoryPicker(options);
100
+ try {
101
+ return await window.showDirectoryPicker(options);
102
+ }
103
+ catch (error) {
104
+ if (error instanceof DOMException && error.name === 'AbortError') {
105
+ return null;
106
+ }
107
+ throw error;
108
+ }
85
109
  }
86
110
  return null;
87
111
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/file-api-types/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAsKH;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CAAC,MAAc;IACrD,OAAO,oBAAoB,IAAI,MAAM,IAAI,oBAAoB,IAAI,MAAM,IAAI,qBAAqB,IAAI,MAAM,CAAC;AAC7G,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,MAAwB;IACnD,OAAO,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC;AAChC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAwB;IACxD,OAAO,MAAM,CAAC,IAAI,KAAK,WAAW,CAAC;AACrC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,MAAc,EACd,OAAmC;IAEnC,IAAI,wBAAwB,CAAC,MAAM,CAAC,EAAE,CAAC;QACrC,OAAO,MAAM,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;IAC5C,CAAC;IACD,OAAO,I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CAAC,KAAK,UAAU,wBAAwB,CAC5C,IAAa,EACb,aAAqB,EACrB,cAAsB,YAAY,EAClC,SAAiB,UAAU,CAAC,MAAM;IAElC,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,EAAE,CAAC;QACtC,4BAA4B;QAC5B,YAAY,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;QAClC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,CAAC;QACH,MAAM,UAAU,GAAG,MAAM,sBAAsB,CAAC,MAAM,EAAE;YACtD,aAAa;YACb,KAAK,EAAE;gBACL;oBACE,WAAW;oBACX,MAAM,EAAE;wBACN,kBAAkB,EAAE,CAAC,OAAO,CAAC;qBAC9B;iBACF;aACF;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,6CAA6C;YAC7C,YAAY,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;YAClC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QAC3C,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC,cAAc,EAAE,CAAC;QACnD,MAAM,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC3B,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;QAEvB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,iDAAiD;QACjD,IAAK,KAAe,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YAC3C,4BAA4B;YAC5B,YAAY,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;YAClC,OAAO,KAAK,CAAC;QACf,CAAC;QACD,0DAA0D;QAC1D,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * File System Access API type definitions and utilities for browser compatibility.\n * @packageDocumentation\n */\n\n// Local type definitions for File System Access API\n// Based on https://wicg.github.io/file-system-access/\n\n/**\n * File System Access API methods available on Window\n * @public\n */\nexport interface IFsAccessApis {\n showDirectoryPicker(options?: ShowDirectoryPickerOptions): Promise<FileSystemDirectoryHandle>;\n showOpenFilePicker(options?: ShowOpenFilePickerOptions): Promise<FileSystemFileHandle[]>;\n showSaveFilePicker(options?: ShowSaveFilePickerOptions): Promise<FileSystemFileHandle>;\n}\n\n/**\n * Window interface extended with File System Access API\n * @public\n */\nexport type WindowWithFsAccess = Window & IFsAccessApis;\n\n/**\n * Base interface for file system handles\n * @public\n */\nexport interface FileSystemHandle {\n readonly kind: 'file' | 'directory';\n readonly name: string;\n isSameEntry(other: FileSystemHandle): Promise<boolean>;\n queryPermission(descriptor?: FileSystemHandlePermissionDescriptor): Promise<PermissionState>;\n requestPermission(descriptor?: FileSystemHandlePermissionDescriptor): Promise<PermissionState>;\n}\n\n/**\n * File handle interface\n * @public\n */\nexport interface FileSystemFileHandle extends FileSystemHandle {\n readonly kind: 'file';\n getFile(): Promise<File>;\n createWritable(options?: FileSystemCreateWritableOptions): Promise<FileSystemWritableFileStream>;\n}\n\n/**\n * Directory handle interface\n * @public\n */\nexport interface FileSystemDirectoryHandle extends FileSystemHandle {\n readonly kind: 'directory';\n getDirectoryHandle(\n name: string,\n options?: FileSystemGetDirectoryOptions\n ): Promise<FileSystemDirectoryHandle>;\n getFileHandle(name: string, options?: FileSystemGetFileOptions): Promise<FileSystemFileHandle>;\n removeEntry(name: string, options?: FileSystemRemoveOptions): Promise<void>;\n resolve(possibleDescendant: FileSystemHandle): Promise<string[] | null>;\n keys(): AsyncIterableIterator<string>;\n values(): AsyncIterableIterator<FileSystemHandle>;\n entries(): AsyncIterableIterator<[string, FileSystemHandle]>;\n [Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;\n}\n\n/**\n * Permission descriptor for file system handles\n * @public\n */\nexport interface FileSystemHandlePermissionDescriptor {\n mode?: 'read' | 'readwrite';\n}\n\n/**\n * Options for creating writable file streams\n * @public\n */\nexport interface FileSystemCreateWritableOptions {\n keepExistingData?: boolean;\n}\n\n/**\n * Options for getting directory handles\n * @public\n */\nexport interface FileSystemGetDirectoryOptions {\n create?: boolean;\n}\n\n/**\n * Options for getting file handles\n * @public\n */\nexport interface FileSystemGetFileOptions {\n create?: boolean;\n}\n\n/**\n * Options for removing entries\n * @public\n */\nexport interface FileSystemRemoveOptions {\n recursive?: boolean;\n}\n\n/**\n * Writable file stream interface\n * @public\n */\nexport interface FileSystemWritableFileStream extends WritableStream {\n write(data: BufferSource | Blob | string): Promise<void>;\n seek(position: number): Promise<void>;\n truncate(size: number): Promise<void>;\n}\n\n/**\n * Directory picker options\n * @public\n */\nexport interface ShowDirectoryPickerOptions {\n id?: string;\n mode?: 'read' | 'readwrite';\n startIn?: FileSystemHandle | WellKnownDirectory;\n}\n\n/**\n * File picker options\n * @public\n */\nexport interface ShowOpenFilePickerOptions {\n multiple?: boolean;\n excludeAcceptAllOption?: boolean;\n id?: string;\n startIn?: FileSystemHandle | WellKnownDirectory;\n types?: FilePickerAcceptType[];\n}\n\n/**\n * Save file picker options\n * @public\n */\nexport interface ShowSaveFilePickerOptions {\n excludeAcceptAllOption?: boolean;\n id?: string;\n startIn?: FileSystemHandle | WellKnownDirectory;\n suggestedName?: string;\n types?: FilePickerAcceptType[];\n}\n\n/**\n * File picker accept type\n * @public\n */\nexport interface FilePickerAcceptType {\n description?: string;\n accept: Record<string, string | string[]>;\n}\n\n/**\n * Well-known directory type\n * @public\n */\nexport type WellKnownDirectory = 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos';\n\n/**\n * Type guard to check if the browser supports the File System Access API\n * @param window - The window object to check\n * @returns True if the window supports File System Access API\n * @public\n */\nexport function supportsFileSystemAccess(window: Window): window is WindowWithFsAccess {\n return 'showOpenFilePicker' in window && 'showSaveFilePicker' in window && 'showDirectoryPicker' in window;\n}\n\n/**\n * Type guard to check if a FileSystemHandle is a file handle\n * @param handle - The handle to check\n * @returns True if the handle is a FileSystemFileHandle\n * @public\n */\nexport function isFileHandle(handle: FileSystemHandle): handle is FileSystemFileHandle {\n return handle.kind === 'file';\n}\n\n/**\n * Type guard to check if a FileSystemHandle is a directory handle\n * @param handle - The handle to check\n * @returns True if the handle is a FileSystemDirectoryHandle\n * @public\n */\nexport function isDirectoryHandle(handle: FileSystemHandle): handle is FileSystemDirectoryHandle {\n return handle.kind === 'directory';\n}\n\n/**\n * Safely access showOpenFilePicker with proper type checking\n * @param window - The window object\n * @param options - Options for the file picker\n * @returns Promise with file handles or null if not supported\n * @public\n */\nexport async function safeShowOpenFilePicker(\n window: Window,\n options?: ShowOpenFilePickerOptions\n): Promise<FileSystemFileHandle[] | null> {\n if (supportsFileSystemAccess(window)) {\n return window.showOpenFilePicker(options);\n }\n return null;\n}\n\n/**\n * Safely access showSaveFilePicker with proper type checking\n * @param window - The window object\n * @param options - Options for the file picker\n * @returns Promise with file handle or null if not supported\n * @public\n */\nexport async function safeShowSaveFilePicker(\n window: Window,\n options?: ShowSaveFilePickerOptions\n): Promise<FileSystemFileHandle | null> {\n if (supportsFileSystemAccess(window)) {\n return window.showSaveFilePicker(options);\n }\n return null;\n}\n\n/**\n * Safely access showDirectoryPicker with proper type checking\n * @param window - The window object\n * @param options - Options for the directory picker\n * @returns Promise with directory handle or null if not supported\n * @public\n */\nexport async function safeShowDirectoryPicker(\n window: Window,\n options?: ShowDirectoryPickerOptions\n): Promise<FileSystemDirectoryHandle | null> {\n if (supportsFileSystemAccess(window)) {\n return window.showDirectoryPicker(options);\n }\n return null;\n}\n\n/**\n * Export data as JSON file using legacy blob download method.\n * Creates a temporary download link and triggers file download.\n * @param data - Data to export as JSON\n * @param filename - Name for the downloaded file\n * @public\n */\nexport function exportAsJson(data: unknown, filename: string): void {\n const json = JSON.stringify(data, null, 2);\n const blob = new Blob([json], { type: 'application/json' });\n const url = URL.createObjectURL(blob);\n\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n}\n\n/**\n * Export data using File System Access API with fallback to blob download.\n * @param data - Data to export as JSON\n * @param suggestedName - Suggested filename for the save dialog\n * @param description - Description for file type filter (default: 'JSON files')\n * @param window - Window object for API access (default: globalThis.window)\n * @returns Promise resolving to true if saved via File System Access API, false if fallback used\n * @public\n */\nexport async function exportUsingFileSystemAPI(\n data: unknown,\n suggestedName: string,\n description: string = 'JSON files',\n window: Window = globalThis.window\n): Promise<boolean> {\n if (!supportsFileSystemAccess(window)) {\n // Fallback to blob download\n exportAsJson(data, suggestedName);\n return false;\n }\n\n try {\n const fileHandle = await safeShowSaveFilePicker(window, {\n suggestedName,\n types: [\n {\n description,\n accept: {\n 'application/json': ['.json']\n }\n }\n ]\n });\n\n if (!fileHandle) {\n // User cancelled - fallback to blob download\n exportAsJson(data, suggestedName);\n return false;\n }\n\n const json = JSON.stringify(data, null, 2);\n const writable = await fileHandle.createWritable();\n await writable.write(json);\n await writable.close();\n\n return true;\n } catch (error) {\n // Handle errors by falling back to blob download\n if ((error as Error).name === 'AbortError') {\n // User cancelled - fallback\n exportAsJson(data, suggestedName);\n return false;\n }\n // Other errors - re-throw as they indicate a real problem\n throw error;\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/file-api-types/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAsKH;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CAAC,MAAc;IACrD,OAAO,oBAAoB,IAAI,MAAM,IAAI,oBAAoB,IAAI,MAAM,IAAI,qBAAqB,IAAI,MAAM,CAAC;AAC7G,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,MAAwB;IACnD,OAAO,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC;AAChC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAwB;IACxD,OAAO,MAAM,CAAC,IAAI,KAAK,WAAW,CAAC;AACrC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,MAAc,EACd,OAAmC;IAEnC,IAAI,wBAAwB,CAAC,MAAM,CAAC,EAAE,CAAC;QACrC,IAAI,CAAC;YACH,OAAO,MAAM,MAAM,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;QAClD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;gBACjE,OAAO,IAAI,CAAC;YACd,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,MAAc,EACd,OAAm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AE,CAAC;QACf,iDAAiD;QACjD,IAAK,KAAe,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YAC3C,4BAA4B;YAC5B,YAAY,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;YAClC,OAAO,KAAK,CAAC;QACf,CAAC;QACD,0DAA0D;QAC1D,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * File System Access API type definitions and utilities for browser compatibility.\n * @packageDocumentation\n */\n\n// Local type definitions for File System Access API\n// Based on https://wicg.github.io/file-system-access/\n\n/**\n * File System Access API methods available on Window\n * @public\n */\nexport interface IFsAccessApis {\n showDirectoryPicker(options?: ShowDirectoryPickerOptions): Promise<FileSystemDirectoryHandle>;\n showOpenFilePicker(options?: ShowOpenFilePickerOptions): Promise<FileSystemFileHandle[]>;\n showSaveFilePicker(options?: ShowSaveFilePickerOptions): Promise<FileSystemFileHandle>;\n}\n\n/**\n * Window interface extended with File System Access API\n * @public\n */\nexport type WindowWithFsAccess = Window & IFsAccessApis;\n\n/**\n * Base interface for file system handles\n * @public\n */\nexport interface FileSystemHandle {\n readonly kind: 'file' | 'directory';\n readonly name: string;\n isSameEntry(other: FileSystemHandle): Promise<boolean>;\n queryPermission(descriptor?: FileSystemHandlePermissionDescriptor): Promise<PermissionState>;\n requestPermission(descriptor?: FileSystemHandlePermissionDescriptor): Promise<PermissionState>;\n}\n\n/**\n * File handle interface\n * @public\n */\nexport interface FileSystemFileHandle extends FileSystemHandle {\n readonly kind: 'file';\n getFile(): Promise<File>;\n createWritable(options?: FileSystemCreateWritableOptions): Promise<FileSystemWritableFileStream>;\n}\n\n/**\n * Directory handle interface\n * @public\n */\nexport interface FileSystemDirectoryHandle extends FileSystemHandle {\n readonly kind: 'directory';\n getDirectoryHandle(\n name: string,\n options?: FileSystemGetDirectoryOptions\n ): Promise<FileSystemDirectoryHandle>;\n getFileHandle(name: string, options?: FileSystemGetFileOptions): Promise<FileSystemFileHandle>;\n removeEntry(name: string, options?: FileSystemRemoveOptions): Promise<void>;\n resolve(possibleDescendant: FileSystemHandle): Promise<string[] | null>;\n keys(): AsyncIterableIterator<string>;\n values(): AsyncIterableIterator<FileSystemHandle>;\n entries(): AsyncIterableIterator<[string, FileSystemHandle]>;\n [Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;\n}\n\n/**\n * Permission descriptor for file system handles\n * @public\n */\nexport interface FileSystemHandlePermissionDescriptor {\n mode?: 'read' | 'readwrite';\n}\n\n/**\n * Options for creating writable file streams\n * @public\n */\nexport interface FileSystemCreateWritableOptions {\n keepExistingData?: boolean;\n}\n\n/**\n * Options for getting directory handles\n * @public\n */\nexport interface FileSystemGetDirectoryOptions {\n create?: boolean;\n}\n\n/**\n * Options for getting file handles\n * @public\n */\nexport interface FileSystemGetFileOptions {\n create?: boolean;\n}\n\n/**\n * Options for removing entries\n * @public\n */\nexport interface FileSystemRemoveOptions {\n recursive?: boolean;\n}\n\n/**\n * Writable file stream interface\n * @public\n */\nexport interface FileSystemWritableFileStream extends WritableStream {\n write(data: BufferSource | Blob | string): Promise<void>;\n seek(position: number): Promise<void>;\n truncate(size: number): Promise<void>;\n}\n\n/**\n * Directory picker options\n * @public\n */\nexport interface ShowDirectoryPickerOptions {\n id?: string;\n mode?: 'read' | 'readwrite';\n startIn?: FileSystemHandle | WellKnownDirectory;\n}\n\n/**\n * File picker options\n * @public\n */\nexport interface ShowOpenFilePickerOptions {\n multiple?: boolean;\n excludeAcceptAllOption?: boolean;\n id?: string;\n startIn?: FileSystemHandle | WellKnownDirectory;\n types?: FilePickerAcceptType[];\n}\n\n/**\n * Save file picker options\n * @public\n */\nexport interface ShowSaveFilePickerOptions {\n excludeAcceptAllOption?: boolean;\n id?: string;\n startIn?: FileSystemHandle | WellKnownDirectory;\n suggestedName?: string;\n types?: FilePickerAcceptType[];\n}\n\n/**\n * File picker accept type\n * @public\n */\nexport interface FilePickerAcceptType {\n description?: string;\n accept: Record<string, string | string[]>;\n}\n\n/**\n * Well-known directory type\n * @public\n */\nexport type WellKnownDirectory = 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos';\n\n/**\n * Type guard to check if the browser supports the File System Access API\n * @param window - The window object to check\n * @returns True if the window supports File System Access API\n * @public\n */\nexport function supportsFileSystemAccess(window: Window): window is WindowWithFsAccess {\n return 'showOpenFilePicker' in window && 'showSaveFilePicker' in window && 'showDirectoryPicker' in window;\n}\n\n/**\n * Type guard to check if a FileSystemHandle is a file handle\n * @param handle - The handle to check\n * @returns True if the handle is a FileSystemFileHandle\n * @public\n */\nexport function isFileHandle(handle: FileSystemHandle): handle is FileSystemFileHandle {\n return handle.kind === 'file';\n}\n\n/**\n * Type guard to check if a FileSystemHandle is a directory handle\n * @param handle - The handle to check\n * @returns True if the handle is a FileSystemDirectoryHandle\n * @public\n */\nexport function isDirectoryHandle(handle: FileSystemHandle): handle is FileSystemDirectoryHandle {\n return handle.kind === 'directory';\n}\n\n/**\n * Safely access showOpenFilePicker with proper type checking\n * @param window - The window object\n * @param options - Options for the file picker\n * @returns Promise with file handles or null if not supported\n * @public\n */\nexport async function safeShowOpenFilePicker(\n window: Window,\n options?: ShowOpenFilePickerOptions\n): Promise<FileSystemFileHandle[] | null> {\n if (supportsFileSystemAccess(window)) {\n try {\n return await window.showOpenFilePicker(options);\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n return null;\n }\n throw error;\n }\n }\n return null;\n}\n\n/**\n * Safely access showSaveFilePicker with proper type checking\n * @param window - The window object\n * @param options - Options for the file picker\n * @returns Promise with file handle or null if not supported\n * @public\n */\nexport async function safeShowSaveFilePicker(\n window: Window,\n options?: ShowSaveFilePickerOptions\n): Promise<FileSystemFileHandle | null> {\n if (supportsFileSystemAccess(window)) {\n try {\n return await window.showSaveFilePicker(options);\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n return null;\n }\n throw error;\n }\n }\n return null;\n}\n\n/**\n * Safely access showDirectoryPicker with proper type checking\n * @param window - The window object\n * @param options - Options for the directory picker\n * @returns Promise with directory handle or null if not supported\n * @public\n */\nexport async function safeShowDirectoryPicker(\n window: Window,\n options?: ShowDirectoryPickerOptions\n): Promise<FileSystemDirectoryHandle | null> {\n if (supportsFileSystemAccess(window)) {\n try {\n return await window.showDirectoryPicker(options);\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n return null;\n }\n throw error;\n }\n }\n return null;\n}\n\n/**\n * Export data as JSON file using legacy blob download method.\n * Creates a temporary download link and triggers file download.\n * @param data - Data to export as JSON\n * @param filename - Name for the downloaded file\n * @public\n */\nexport function exportAsJson(data: unknown, filename: string): void {\n const json = JSON.stringify(data, null, 2);\n const blob = new Blob([json], { type: 'application/json' });\n const url = URL.createObjectURL(blob);\n\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n}\n\n/**\n * Export data using File System Access API with fallback to blob download.\n * @param data - Data to export as JSON\n * @param suggestedName - Suggested filename for the save dialog\n * @param description - Description for file type filter (default: 'JSON files')\n * @param window - Window object for API access (default: globalThis.window)\n * @returns Promise resolving to true if saved via File System Access API, false if fallback used\n * @public\n */\nexport async function exportUsingFileSystemAPI(\n data: unknown,\n suggestedName: string,\n description: string = 'JSON files',\n window: Window = globalThis.window\n): Promise<boolean> {\n if (!supportsFileSystemAccess(window)) {\n // Fallback to blob download\n exportAsJson(data, suggestedName);\n return false;\n }\n\n try {\n const fileHandle = await safeShowSaveFilePicker(window, {\n suggestedName,\n types: [\n {\n description,\n accept: {\n 'application/json': ['.json']\n }\n }\n ]\n });\n\n if (!fileHandle) {\n // User cancelled - fallback to blob download\n exportAsJson(data, suggestedName);\n return false;\n }\n\n const json = JSON.stringify(data, null, 2);\n const writable = await fileHandle.createWritable();\n await writable.write(json);\n await writable.close();\n\n return true;\n } catch (error) {\n // Handle errors by falling back to blob download\n if ((error as Error).name === 'AbortError') {\n // User cancelled - fallback\n exportAsJson(data, suggestedName);\n return false;\n }\n // Other errors - re-throw as they indicate a real problem\n throw error;\n }\n}\n"]}
@@ -0,0 +1,124 @@
1
+ // Copyright (c) 2026 Erik Fortune
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ // of this software and associated documentation files (the "Software"), to deal
5
+ // in the Software without restriction, including without limitation the rights
6
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ // copies of the Software, and to permit persons to whom the Software is
8
+ // furnished to do so, subject to the following conditions:
9
+ //
10
+ // The above copyright notice and this permission notice shall be included in all
11
+ // copies or substantial portions of the Software.
12
+ //
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ // SOFTWARE.
20
+ /**
21
+ * Persistent storage for FileSystemDirectoryHandle objects using IndexedDB.
22
+ * Allows directory handles to survive page reloads without re-prompting the user.
23
+ * @packageDocumentation
24
+ */
25
+ import { fail, succeed } from '@fgv/ts-utils';
26
+ import { createStore, del, get, keys, set } from 'idb-keyval';
27
+ /**
28
+ * Default IndexedDB database name for directory handles.
29
+ * @public
30
+ */
31
+ export const DEFAULT_DIRECTORY_HANDLE_DB = 'chocolate-lab-storage';
32
+ /**
33
+ * Default IndexedDB store name for directory handles.
34
+ * @public
35
+ */
36
+ export const DEFAULT_DIRECTORY_HANDLE_STORE = 'directory-handles';
37
+ /**
38
+ * Manages persistence of {@link FileSystemDirectoryHandle} objects in IndexedDB.
39
+ * Keyed by a label (typically the directory name).
40
+ * @public
41
+ */
42
+ export class DirectoryHandleStore {
43
+ constructor(dbName = DEFAULT_DIRECTORY_HANDLE_DB, storeName = DEFAULT_DIRECTORY_HANDLE_STORE) {
44
+ this._store = createStore(dbName, storeName);
45
+ }
46
+ /**
47
+ * Saves a directory handle to IndexedDB under the given label.
48
+ * @param label - Key to store the handle under (typically dirHandle.name)
49
+ * @param handle - The FileSystemDirectoryHandle to persist
50
+ * @returns Success or Failure
51
+ */
52
+ async save(label, handle) {
53
+ try {
54
+ await set(label, handle, this._store);
55
+ return succeed(undefined);
56
+ }
57
+ catch (e) {
58
+ return fail(`DirectoryHandleStore.save "${label}": ${String(e)}`);
59
+ }
60
+ }
61
+ /**
62
+ * Retrieves a directory handle by label.
63
+ * @param label - Key to look up
64
+ * @returns Success with handle (or undefined if not found), or Failure on error
65
+ */
66
+ async load(label) {
67
+ try {
68
+ const handle = await get(label, this._store);
69
+ return succeed(handle);
70
+ }
71
+ catch (e) {
72
+ return fail(`DirectoryHandleStore.load "${label}": ${String(e)}`);
73
+ }
74
+ }
75
+ /**
76
+ * Removes a directory handle from IndexedDB.
77
+ * @param label - Key to remove
78
+ * @returns Success or Failure
79
+ */
80
+ async remove(label) {
81
+ try {
82
+ await del(label, this._store);
83
+ return succeed(undefined);
84
+ }
85
+ catch (e) {
86
+ return fail(`DirectoryHandleStore.remove "${label}": ${String(e)}`);
87
+ }
88
+ }
89
+ /**
90
+ * Returns all stored labels (keys).
91
+ * @returns Success with array of labels, or Failure
92
+ */
93
+ async getAllLabels() {
94
+ try {
95
+ const allKeys = await keys(this._store);
96
+ return succeed(allKeys);
97
+ }
98
+ catch (e) {
99
+ return fail(`DirectoryHandleStore.getAllLabels: ${String(e)}`);
100
+ }
101
+ }
102
+ /**
103
+ * Returns all stored handles as label/handle pairs.
104
+ * @returns Success with array of entries, or Failure
105
+ */
106
+ async getAll() {
107
+ const labelsResult = await this.getAllLabels();
108
+ if (labelsResult.isFailure()) {
109
+ return fail(labelsResult.message);
110
+ }
111
+ const entries = [];
112
+ for (const label of labelsResult.value) {
113
+ const handleResult = await this.load(label);
114
+ if (handleResult.isFailure()) {
115
+ return fail(handleResult.message);
116
+ }
117
+ if (handleResult.value !== undefined) {
118
+ entries.push({ label, handle: handleResult.value });
119
+ }
120
+ }
121
+ return succeed(entries);
122
+ }
123
+ }
124
+ //# sourceMappingURL=directoryHandleStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directoryHandleStore.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/directoryHandleStore.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE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E,CAAC;gBACrC,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,CAAC,KAAK,EAAE,CAAC,CAAC;YACtD,CAAC;QACH,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1B,CAAC;CACF","sourcesContent":["// 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/**\n * Persistent storage for FileSystemDirectoryHandle objects using IndexedDB.\n * Allows directory handles to survive page reloads without re-prompting the user.\n * @packageDocumentation\n */\n\nimport { fail, Result, succeed } from '@fgv/ts-utils';\nimport { createStore, del, get, keys, set } from 'idb-keyval';\nimport { FileSystemDirectoryHandle } from '../file-api-types';\n\n/**\n * Default IndexedDB database name for directory handles.\n * @public\n */\nexport const DEFAULT_DIRECTORY_HANDLE_DB = 'chocolate-lab-storage';\n\n/**\n * Default IndexedDB store name for directory handles.\n * @public\n */\nexport const DEFAULT_DIRECTORY_HANDLE_STORE = 'directory-handles';\n\n/**\n * Manages persistence of {@link FileSystemDirectoryHandle} objects in IndexedDB.\n * Keyed by a label (typically the directory name).\n * @public\n */\nexport class DirectoryHandleStore {\n private readonly _store: ReturnType<typeof createStore>;\n\n public constructor(\n dbName: string = DEFAULT_DIRECTORY_HANDLE_DB,\n storeName: string = DEFAULT_DIRECTORY_HANDLE_STORE\n ) {\n this._store = createStore(dbName, storeName);\n }\n\n /**\n * Saves a directory handle to IndexedDB under the given label.\n * @param label - Key to store the handle under (typically dirHandle.name)\n * @param handle - The FileSystemDirectoryHandle to persist\n * @returns Success or Failure\n */\n public async save(label: string, handle: FileSystemDirectoryHandle): Promise<Result<void>> {\n try {\n await set(label, handle, this._store);\n return succeed(undefined);\n } catch (e) {\n return fail(`DirectoryHandleStore.save \"${label}\": ${String(e)}`);\n }\n }\n\n /**\n * Retrieves a directory handle by label.\n * @param label - Key to look up\n * @returns Success with handle (or undefined if not found), or Failure on error\n */\n public async load(label: string): Promise<Result<FileSystemDirectoryHandle | undefined>> {\n try {\n const handle = await get<FileSystemDirectoryHandle>(label, this._store);\n return succeed(handle);\n } catch (e) {\n return fail(`DirectoryHandleStore.load \"${label}\": ${String(e)}`);\n }\n }\n\n /**\n * Removes a directory handle from IndexedDB.\n * @param label - Key to remove\n * @returns Success or Failure\n */\n public async remove(label: string): Promise<Result<void>> {\n try {\n await del(label, this._store);\n return succeed(undefined);\n } catch (e) {\n return fail(`DirectoryHandleStore.remove \"${label}\": ${String(e)}`);\n }\n }\n\n /**\n * Returns all stored labels (keys).\n * @returns Success with array of labels, or Failure\n */\n public async getAllLabels(): Promise<Result<string[]>> {\n try {\n const allKeys = await keys<string>(this._store);\n return succeed(allKeys);\n } catch (e) {\n return fail(`DirectoryHandleStore.getAllLabels: ${String(e)}`);\n }\n }\n\n /**\n * Returns all stored handles as label/handle pairs.\n * @returns Success with array of entries, or Failure\n */\n public async getAll(): Promise<Result<Array<{ label: string; handle: FileSystemDirectoryHandle }>>> {\n const labelsResult = await this.getAllLabels();\n if (labelsResult.isFailure()) {\n return fail(labelsResult.message);\n }\n\n const entries: Array<{ label: string; handle: FileSystemDirectoryHandle }> = [];\n for (const label of labelsResult.value) {\n const handleResult = await this.load(label);\n if (handleResult.isFailure()) {\n return fail(handleResult.message);\n }\n if (handleResult.value !== undefined) {\n entries.push({ label, handle: handleResult.value });\n }\n }\n return succeed(entries);\n }\n}\n"]}