@fgv/ts-web-extras 5.1.0-4 → 5.1.0-41

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 (424) hide show
  1. package/dist/packlets/crypto-utils/browserCryptoProvider.js +413 -18
  2. package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
  3. package/dist/packlets/crypto-utils/idbPrivateKeyStorage.js +238 -0
  4. package/dist/packlets/crypto-utils/idbPrivateKeyStorage.js.map +1 -0
  5. package/dist/packlets/crypto-utils/index.js +13 -0
  6. package/dist/packlets/crypto-utils/index.js.map +1 -1
  7. package/dist/packlets/file-tree/directoryHandleStore.js.map +1 -1
  8. package/dist/packlets/file-tree/fileApiTreeAccessors.js +1 -1
  9. package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  10. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js +2 -2
  11. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
  12. package/dist/packlets/file-tree/httpTreeAccessors.js +74 -44
  13. package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -1
  14. package/dist/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
  15. package/dist/packlets/helpers/fileTreeHelpers.js +1 -1
  16. package/dist/packlets/helpers/fileTreeHelpers.js.map +1 -1
  17. package/dist/ts-web-extras.d.ts +259 -10
  18. package/dist/tsdoc-metadata.json +1 -1
  19. package/eslint.config.js +32 -0
  20. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +145 -6
  21. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -1
  22. package/lib/packlets/crypto-utils/browserCryptoProvider.js +412 -17
  23. package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
  24. package/lib/packlets/crypto-utils/idbPrivateKeyStorage.d.ts +87 -0
  25. package/lib/packlets/crypto-utils/idbPrivateKeyStorage.d.ts.map +1 -0
  26. package/lib/packlets/crypto-utils/idbPrivateKeyStorage.js +242 -0
  27. package/lib/packlets/crypto-utils/idbPrivateKeyStorage.js.map +1 -0
  28. package/lib/packlets/crypto-utils/index.d.ts +14 -0
  29. package/lib/packlets/crypto-utils/index.d.ts.map +1 -1
  30. package/lib/packlets/crypto-utils/index.js +14 -0
  31. package/lib/packlets/crypto-utils/index.js.map +1 -1
  32. package/lib/packlets/file-tree/directoryHandleStore.d.ts +2 -2
  33. package/lib/packlets/file-tree/directoryHandleStore.d.ts.map +1 -1
  34. package/lib/packlets/file-tree/directoryHandleStore.js.map +1 -1
  35. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +2 -2
  36. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts.map +1 -1
  37. package/lib/packlets/file-tree/fileApiTreeAccessors.js +1 -1
  38. package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  39. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts.map +1 -1
  40. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js +2 -2
  41. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
  42. package/lib/packlets/file-tree/httpTreeAccessors.d.ts +6 -0
  43. package/lib/packlets/file-tree/httpTreeAccessors.d.ts.map +1 -1
  44. package/lib/packlets/file-tree/httpTreeAccessors.js +74 -44
  45. package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -1
  46. package/lib/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
  47. package/lib/packlets/helpers/fileTreeHelpers.d.ts +1 -1
  48. package/lib/packlets/helpers/fileTreeHelpers.d.ts.map +1 -1
  49. package/lib/packlets/helpers/fileTreeHelpers.js +6 -6
  50. package/lib/packlets/helpers/fileTreeHelpers.js.map +1 -1
  51. package/package.json +15 -14
  52. package/.rush/temp/44b0369e8112f3c6f4248af466a3f35ad626d9d7.tar.log +0 -237
  53. package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +0 -55
  54. package/.rush/temp/operation/build/all.log +0 -55
  55. package/.rush/temp/operation/build/log-chunks.jsonl +0 -55
  56. package/.rush/temp/operation/build/state.json +0 -3
  57. package/.rush/temp/shrinkwrap-deps.json +0 -692
  58. package/CHANGELOG.md +0 -23
  59. package/config/api-extractor.json +0 -343
  60. package/config/jest.config.json +0 -19
  61. package/config/rig.json +0 -16
  62. package/config/typedoc.json +0 -7
  63. package/dist/test/mocks/idb-keyval.js +0 -6
  64. package/dist/test/mocks/idb-keyval.js.map +0 -1
  65. package/dist/test/setupTests.js +0 -74
  66. package/dist/test/setupTests.js.map +0 -1
  67. package/dist/test/unit/browserHashProvider.test.js +0 -140
  68. package/dist/test/unit/browserHashProvider.test.js.map +0 -1
  69. package/dist/test/unit/directoryHandleStore.test.js +0 -190
  70. package/dist/test/unit/directoryHandleStore.test.js.map +0 -1
  71. package/dist/test/unit/fileApiTreeAccessors.test.js +0 -1188
  72. package/dist/test/unit/fileApiTreeAccessors.test.js.map +0 -1
  73. package/dist/test/unit/fileApiTypes.test.js +0 -472
  74. package/dist/test/unit/fileApiTypes.test.js.map +0 -1
  75. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js +0 -622
  76. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js.map +0 -1
  77. package/dist/test/unit/fileTreeHelpers.test.js +0 -590
  78. package/dist/test/unit/fileTreeHelpers.test.js.map +0 -1
  79. package/dist/test/unit/httpTreeAccessors.test.js +0 -1229
  80. package/dist/test/unit/httpTreeAccessors.test.js.map +0 -1
  81. package/dist/test/unit/localStorageTreeAccessors.test.js +0 -812
  82. package/dist/test/unit/localStorageTreeAccessors.test.js.map +0 -1
  83. package/dist/test/unit/urlParams.test.js +0 -393
  84. package/dist/test/unit/urlParams.test.js.map +0 -1
  85. package/dist/test/utils/fileSystemAccessMocks.js +0 -271
  86. package/dist/test/utils/fileSystemAccessMocks.js.map +0 -1
  87. package/dist/test/utils/testHelpers.js +0 -124
  88. package/dist/test/utils/testHelpers.js.map +0 -1
  89. package/docs/CryptoUtils/README.md +0 -60
  90. package/docs/CryptoUtils/classes/BrowserCryptoProvider.decrypt.md +0 -27
  91. package/docs/CryptoUtils/classes/BrowserCryptoProvider.deriveKey.md +0 -26
  92. package/docs/CryptoUtils/classes/BrowserCryptoProvider.encrypt.md +0 -25
  93. package/docs/CryptoUtils/classes/BrowserCryptoProvider.fromBase64.md +0 -24
  94. package/docs/CryptoUtils/classes/BrowserCryptoProvider.generateKey.md +0 -17
  95. package/docs/CryptoUtils/classes/BrowserCryptoProvider.generateRandomBytes.md +0 -24
  96. package/docs/CryptoUtils/classes/BrowserCryptoProvider.md +0 -151
  97. package/docs/CryptoUtils/classes/BrowserCryptoProvider.toBase64.md +0 -24
  98. package/docs/CryptoUtils/classes/BrowserHashProvider.hashParts.md +0 -26
  99. package/docs/CryptoUtils/classes/BrowserHashProvider.hashString.md +0 -25
  100. package/docs/CryptoUtils/classes/BrowserHashProvider.md +0 -81
  101. package/docs/CryptoUtils/functions/createBrowserCryptoProvider.md +0 -12
  102. package/docs/FileTreeHelpers/README.md +0 -85
  103. package/docs/FileTreeHelpers/functions/extractFileListMetadata.md +0 -11
  104. package/docs/FileTreeHelpers/functions/extractFileMetadata.md +0 -11
  105. package/docs/FileTreeHelpers/functions/fromDirectoryUpload.md +0 -12
  106. package/docs/FileTreeHelpers/functions/fromFileList.md +0 -12
  107. package/docs/FileTreeHelpers/functions/getOriginalFile.md +0 -11
  108. package/docs/FileTreeHelpers/variables/defaultFileApiTreeInitParams.md +0 -9
  109. package/docs/README.md +0 -524
  110. package/docs/classes/BrowserCryptoProvider.decrypt.md +0 -27
  111. package/docs/classes/BrowserCryptoProvider.deriveKey.md +0 -26
  112. package/docs/classes/BrowserCryptoProvider.encrypt.md +0 -25
  113. package/docs/classes/BrowserCryptoProvider.fromBase64.md +0 -24
  114. package/docs/classes/BrowserCryptoProvider.generateKey.md +0 -17
  115. package/docs/classes/BrowserCryptoProvider.generateRandomBytes.md +0 -24
  116. package/docs/classes/BrowserCryptoProvider.md +0 -151
  117. package/docs/classes/BrowserCryptoProvider.toBase64.md +0 -24
  118. package/docs/classes/BrowserHashProvider.hashParts.md +0 -26
  119. package/docs/classes/BrowserHashProvider.hashString.md +0 -25
  120. package/docs/classes/BrowserHashProvider.md +0 -81
  121. package/docs/classes/DirectoryHandleStore.getAll.md +0 -17
  122. package/docs/classes/DirectoryHandleStore.getAllLabels.md +0 -17
  123. package/docs/classes/DirectoryHandleStore.load.md +0 -24
  124. package/docs/classes/DirectoryHandleStore.md +0 -120
  125. package/docs/classes/DirectoryHandleStore.remove.md +0 -24
  126. package/docs/classes/DirectoryHandleStore.save.md +0 -25
  127. package/docs/classes/FileApiTreeAccessors.create.md +0 -25
  128. package/docs/classes/FileApiTreeAccessors.createFromHttp.md +0 -24
  129. package/docs/classes/FileApiTreeAccessors.createFromLocalStorage.md +0 -25
  130. package/docs/classes/FileApiTreeAccessors.createPersistent.md +0 -26
  131. package/docs/classes/FileApiTreeAccessors.createPersistentFromFile.md +0 -27
  132. package/docs/classes/FileApiTreeAccessors.extractFileMetadata.md +0 -24
  133. package/docs/classes/FileApiTreeAccessors.fromDirectoryUpload.md +0 -25
  134. package/docs/classes/FileApiTreeAccessors.fromFileList.md +0 -25
  135. package/docs/classes/FileApiTreeAccessors.getOriginalFile.md +0 -27
  136. package/docs/classes/FileApiTreeAccessors.md +0 -172
  137. package/docs/classes/FileSystemAccessTreeAccessors.deleteFile.md +0 -22
  138. package/docs/classes/FileSystemAccessTreeAccessors.fileIsMutable.md +0 -22
  139. package/docs/classes/FileSystemAccessTreeAccessors.fromDirectoryHandle.md +0 -25
  140. package/docs/classes/FileSystemAccessTreeAccessors.fromFileHandle.md +0 -29
  141. package/docs/classes/FileSystemAccessTreeAccessors.getDirtyPaths.md +0 -15
  142. package/docs/classes/FileSystemAccessTreeAccessors.isDirty.md +0 -15
  143. package/docs/classes/FileSystemAccessTreeAccessors.md +0 -275
  144. package/docs/classes/FileSystemAccessTreeAccessors.saveFileContents.md +0 -23
  145. package/docs/classes/FileSystemAccessTreeAccessors.syncToDisk.md +0 -15
  146. package/docs/classes/HttpTreeAccessors.deleteFile.md +0 -22
  147. package/docs/classes/HttpTreeAccessors.fileIsMutable.md +0 -24
  148. package/docs/classes/HttpTreeAccessors.fromHttp.md +0 -24
  149. package/docs/classes/HttpTreeAccessors.getDirtyPaths.md +0 -17
  150. package/docs/classes/HttpTreeAccessors.isDirty.md +0 -17
  151. package/docs/classes/HttpTreeAccessors.md +0 -261
  152. package/docs/classes/HttpTreeAccessors.saveFileContents.md +0 -25
  153. package/docs/classes/HttpTreeAccessors.syncToDisk.md +0 -22
  154. package/docs/classes/LocalStorageTreeAccessors.deleteFile.md +0 -24
  155. package/docs/classes/LocalStorageTreeAccessors.fileIsMutable.md +0 -24
  156. package/docs/classes/LocalStorageTreeAccessors.fromStorage.md +0 -25
  157. package/docs/classes/LocalStorageTreeAccessors.getDirtyPaths.md +0 -17
  158. package/docs/classes/LocalStorageTreeAccessors.isDirty.md +0 -17
  159. package/docs/classes/LocalStorageTreeAccessors.md +0 -270
  160. package/docs/classes/LocalStorageTreeAccessors.saveFileContents.md +0 -25
  161. package/docs/classes/LocalStorageTreeAccessors.syncToDisk.md +0 -17
  162. package/docs/functions/createBrowserCryptoProvider.md +0 -12
  163. package/docs/functions/exportAsJson.md +0 -12
  164. package/docs/functions/exportUsingFileSystemAPI.md +0 -11
  165. package/docs/functions/extractDirectoryPath.md +0 -13
  166. package/docs/functions/extractFileListMetadata.md +0 -11
  167. package/docs/functions/extractFileMetadata.md +0 -11
  168. package/docs/functions/fromDirectoryUpload.md +0 -12
  169. package/docs/functions/fromFileList.md +0 -12
  170. package/docs/functions/getOriginalFile.md +0 -11
  171. package/docs/functions/isDirectoryHandle.md +0 -11
  172. package/docs/functions/isFileHandle.md +0 -11
  173. package/docs/functions/isFilePath.md +0 -11
  174. package/docs/functions/parseContextFilter.md +0 -12
  175. package/docs/functions/parseQualifierDefaults.md +0 -12
  176. package/docs/functions/parseResourceTypes.md +0 -12
  177. package/docs/functions/parseUrlParameters.md +0 -11
  178. package/docs/functions/safeShowDirectoryPicker.md +0 -11
  179. package/docs/functions/safeShowOpenFilePicker.md +0 -11
  180. package/docs/functions/safeShowSaveFilePicker.md +0 -11
  181. package/docs/functions/supportsFileSystemAccess.md +0 -11
  182. package/docs/interfaces/FilePickerAcceptType.accept.md +0 -9
  183. package/docs/interfaces/FilePickerAcceptType.description.md +0 -9
  184. package/docs/interfaces/FilePickerAcceptType.md +0 -61
  185. package/docs/interfaces/FileSystemCreateWritableOptions.keepExistingData.md +0 -9
  186. package/docs/interfaces/FileSystemCreateWritableOptions.md +0 -44
  187. package/docs/interfaces/FileSystemDirectoryHandle._asyncIterator_.md +0 -13
  188. package/docs/interfaces/FileSystemDirectoryHandle.entries.md +0 -13
  189. package/docs/interfaces/FileSystemDirectoryHandle.getDirectoryHandle.md +0 -21
  190. package/docs/interfaces/FileSystemDirectoryHandle.getFileHandle.md +0 -21
  191. package/docs/interfaces/FileSystemDirectoryHandle.keys.md +0 -13
  192. package/docs/interfaces/FileSystemDirectoryHandle.kind.md +0 -9
  193. package/docs/interfaces/FileSystemDirectoryHandle.md +0 -224
  194. package/docs/interfaces/FileSystemDirectoryHandle.removeEntry.md +0 -21
  195. package/docs/interfaces/FileSystemDirectoryHandle.resolve.md +0 -20
  196. package/docs/interfaces/FileSystemDirectoryHandle.values.md +0 -13
  197. package/docs/interfaces/FileSystemFileHandle.createWritable.md +0 -20
  198. package/docs/interfaces/FileSystemFileHandle.getFile.md +0 -13
  199. package/docs/interfaces/FileSystemFileHandle.kind.md +0 -9
  200. package/docs/interfaces/FileSystemFileHandle.md +0 -146
  201. package/docs/interfaces/FileSystemGetDirectoryOptions.create.md +0 -9
  202. package/docs/interfaces/FileSystemGetDirectoryOptions.md +0 -44
  203. package/docs/interfaces/FileSystemGetFileOptions.create.md +0 -9
  204. package/docs/interfaces/FileSystemGetFileOptions.md +0 -44
  205. package/docs/interfaces/FileSystemHandle.isSameEntry.md +0 -20
  206. package/docs/interfaces/FileSystemHandle.kind.md +0 -9
  207. package/docs/interfaces/FileSystemHandle.md +0 -118
  208. package/docs/interfaces/FileSystemHandle.name.md +0 -9
  209. package/docs/interfaces/FileSystemHandle.queryPermission.md +0 -20
  210. package/docs/interfaces/FileSystemHandle.requestPermission.md +0 -20
  211. package/docs/interfaces/FileSystemHandlePermissionDescriptor.md +0 -44
  212. package/docs/interfaces/FileSystemHandlePermissionDescriptor.mode.md +0 -9
  213. package/docs/interfaces/FileSystemRemoveOptions.md +0 -44
  214. package/docs/interfaces/FileSystemRemoveOptions.recursive.md +0 -9
  215. package/docs/interfaces/FileSystemWritableFileStream.md +0 -142
  216. package/docs/interfaces/FileSystemWritableFileStream.seek.md +0 -20
  217. package/docs/interfaces/FileSystemWritableFileStream.truncate.md +0 -20
  218. package/docs/interfaces/FileSystemWritableFileStream.write.md +0 -20
  219. package/docs/interfaces/IDirectoryHandleTreeInitializer.dirHandles.md +0 -9
  220. package/docs/interfaces/IDirectoryHandleTreeInitializer.md +0 -78
  221. package/docs/interfaces/IDirectoryHandleTreeInitializer.nonRecursive.md +0 -9
  222. package/docs/interfaces/IDirectoryHandleTreeInitializer.prefix.md +0 -9
  223. package/docs/interfaces/IFileHandleTreeInitializer.fileHandles.md +0 -9
  224. package/docs/interfaces/IFileHandleTreeInitializer.md +0 -61
  225. package/docs/interfaces/IFileHandleTreeInitializer.prefix.md +0 -9
  226. package/docs/interfaces/IFileListTreeInitializer.fileList.md +0 -9
  227. package/docs/interfaces/IFileListTreeInitializer.md +0 -44
  228. package/docs/interfaces/IFileMetadata.lastModified.md +0 -9
  229. package/docs/interfaces/IFileMetadata.md +0 -112
  230. package/docs/interfaces/IFileMetadata.name.md +0 -9
  231. package/docs/interfaces/IFileMetadata.path.md +0 -9
  232. package/docs/interfaces/IFileMetadata.size.md +0 -9
  233. package/docs/interfaces/IFileMetadata.type.md +0 -9
  234. package/docs/interfaces/IFileSystemAccessTreeParams.autoSync.md +0 -12
  235. package/docs/interfaces/IFileSystemAccessTreeParams.filePath.md +0 -13
  236. package/docs/interfaces/IFileSystemAccessTreeParams.logger.md +0 -11
  237. package/docs/interfaces/IFileSystemAccessTreeParams.md +0 -148
  238. package/docs/interfaces/IFileSystemAccessTreeParams.requireWritePermission.md +0 -13
  239. package/docs/interfaces/IFsAccessApis.md +0 -62
  240. package/docs/interfaces/IFsAccessApis.showDirectoryPicker.md +0 -20
  241. package/docs/interfaces/IFsAccessApis.showOpenFilePicker.md +0 -20
  242. package/docs/interfaces/IFsAccessApis.showSaveFilePicker.md +0 -20
  243. package/docs/interfaces/IHttpTreeParams.autoSync.md +0 -9
  244. package/docs/interfaces/IHttpTreeParams.baseUrl.md +0 -9
  245. package/docs/interfaces/IHttpTreeParams.fetchImpl.md +0 -9
  246. package/docs/interfaces/IHttpTreeParams.logger.md +0 -9
  247. package/docs/interfaces/IHttpTreeParams.md +0 -182
  248. package/docs/interfaces/IHttpTreeParams.namespace.md +0 -9
  249. package/docs/interfaces/IHttpTreeParams.userId.md +0 -9
  250. package/docs/interfaces/ILocalStorageTreeParams.autoSync.md +0 -12
  251. package/docs/interfaces/ILocalStorageTreeParams.md +0 -131
  252. package/docs/interfaces/ILocalStorageTreeParams.pathToKeyMap.md +0 -13
  253. package/docs/interfaces/ILocalStorageTreeParams.storage.md +0 -12
  254. package/docs/interfaces/IUrlConfigOptions.config.md +0 -11
  255. package/docs/interfaces/IUrlConfigOptions.configStartDir.md +0 -11
  256. package/docs/interfaces/IUrlConfigOptions.contextFilter.md +0 -11
  257. package/docs/interfaces/IUrlConfigOptions.input.md +0 -11
  258. package/docs/interfaces/IUrlConfigOptions.inputStartDir.md +0 -11
  259. package/docs/interfaces/IUrlConfigOptions.interactive.md +0 -11
  260. package/docs/interfaces/IUrlConfigOptions.loadZip.md +0 -11
  261. package/docs/interfaces/IUrlConfigOptions.maxDistance.md +0 -11
  262. package/docs/interfaces/IUrlConfigOptions.md +0 -248
  263. package/docs/interfaces/IUrlConfigOptions.qualifierDefaults.md +0 -11
  264. package/docs/interfaces/IUrlConfigOptions.reduceQualifiers.md +0 -11
  265. package/docs/interfaces/IUrlConfigOptions.resourceTypes.md +0 -11
  266. package/docs/interfaces/IUrlConfigOptions.zipFile.md +0 -11
  267. package/docs/interfaces/IUrlConfigOptions.zipPath.md +0 -11
  268. package/docs/interfaces/ShowDirectoryPickerOptions.id.md +0 -9
  269. package/docs/interfaces/ShowDirectoryPickerOptions.md +0 -78
  270. package/docs/interfaces/ShowDirectoryPickerOptions.mode.md +0 -9
  271. package/docs/interfaces/ShowDirectoryPickerOptions.startIn.md +0 -9
  272. package/docs/interfaces/ShowOpenFilePickerOptions.excludeAcceptAllOption.md +0 -9
  273. package/docs/interfaces/ShowOpenFilePickerOptions.id.md +0 -9
  274. package/docs/interfaces/ShowOpenFilePickerOptions.md +0 -112
  275. package/docs/interfaces/ShowOpenFilePickerOptions.multiple.md +0 -9
  276. package/docs/interfaces/ShowOpenFilePickerOptions.startIn.md +0 -9
  277. package/docs/interfaces/ShowOpenFilePickerOptions.types.md +0 -9
  278. package/docs/interfaces/ShowSaveFilePickerOptions.excludeAcceptAllOption.md +0 -9
  279. package/docs/interfaces/ShowSaveFilePickerOptions.id.md +0 -9
  280. package/docs/interfaces/ShowSaveFilePickerOptions.md +0 -112
  281. package/docs/interfaces/ShowSaveFilePickerOptions.startIn.md +0 -9
  282. package/docs/interfaces/ShowSaveFilePickerOptions.suggestedName.md +0 -9
  283. package/docs/interfaces/ShowSaveFilePickerOptions.types.md +0 -9
  284. package/docs/type-aliases/TreeInitializer.md +0 -11
  285. package/docs/type-aliases/WellKnownDirectory.md +0 -11
  286. package/docs/type-aliases/WindowWithFsAccess.md +0 -11
  287. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_DB.md +0 -9
  288. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_STORE.md +0 -9
  289. package/docs/variables/defaultFileApiTreeInitParams.md +0 -9
  290. package/etc/ts-web-extras.api.md +0 -433
  291. package/lib/test/mocks/idb-keyval.d.ts +0 -6
  292. package/lib/test/mocks/idb-keyval.d.ts.map +0 -1
  293. package/lib/test/mocks/idb-keyval.js +0 -9
  294. package/lib/test/mocks/idb-keyval.js.map +0 -1
  295. package/lib/test/setupTests.d.ts +0 -2
  296. package/lib/test/setupTests.d.ts.map +0 -1
  297. package/lib/test/setupTests.js +0 -76
  298. package/lib/test/setupTests.js.map +0 -1
  299. package/lib/test/unit/browserHashProvider.test.d.ts +0 -2
  300. package/lib/test/unit/browserHashProvider.test.d.ts.map +0 -1
  301. package/lib/test/unit/browserHashProvider.test.js +0 -142
  302. package/lib/test/unit/browserHashProvider.test.js.map +0 -1
  303. package/lib/test/unit/directoryHandleStore.test.d.ts +0 -2
  304. package/lib/test/unit/directoryHandleStore.test.d.ts.map +0 -1
  305. package/lib/test/unit/directoryHandleStore.test.js +0 -192
  306. package/lib/test/unit/directoryHandleStore.test.js.map +0 -1
  307. package/lib/test/unit/fileApiTreeAccessors.test.d.ts +0 -2
  308. package/lib/test/unit/fileApiTreeAccessors.test.d.ts.map +0 -1
  309. package/lib/test/unit/fileApiTreeAccessors.test.js +0 -1190
  310. package/lib/test/unit/fileApiTreeAccessors.test.js.map +0 -1
  311. package/lib/test/unit/fileApiTypes.test.d.ts +0 -2
  312. package/lib/test/unit/fileApiTypes.test.d.ts.map +0 -1
  313. package/lib/test/unit/fileApiTypes.test.js +0 -474
  314. package/lib/test/unit/fileApiTypes.test.js.map +0 -1
  315. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts +0 -2
  316. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts.map +0 -1
  317. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js +0 -624
  318. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js.map +0 -1
  319. package/lib/test/unit/fileTreeHelpers.test.d.ts +0 -2
  320. package/lib/test/unit/fileTreeHelpers.test.d.ts.map +0 -1
  321. package/lib/test/unit/fileTreeHelpers.test.js +0 -592
  322. package/lib/test/unit/fileTreeHelpers.test.js.map +0 -1
  323. package/lib/test/unit/httpTreeAccessors.test.d.ts +0 -2
  324. package/lib/test/unit/httpTreeAccessors.test.d.ts.map +0 -1
  325. package/lib/test/unit/httpTreeAccessors.test.js +0 -1231
  326. package/lib/test/unit/httpTreeAccessors.test.js.map +0 -1
  327. package/lib/test/unit/localStorageTreeAccessors.test.d.ts +0 -2
  328. package/lib/test/unit/localStorageTreeAccessors.test.d.ts.map +0 -1
  329. package/lib/test/unit/localStorageTreeAccessors.test.js +0 -814
  330. package/lib/test/unit/localStorageTreeAccessors.test.js.map +0 -1
  331. package/lib/test/unit/urlParams.test.d.ts +0 -2
  332. package/lib/test/unit/urlParams.test.d.ts.map +0 -1
  333. package/lib/test/unit/urlParams.test.js +0 -395
  334. package/lib/test/unit/urlParams.test.js.map +0 -1
  335. package/lib/test/utils/fileSystemAccessMocks.d.ts +0 -53
  336. package/lib/test/utils/fileSystemAccessMocks.d.ts.map +0 -1
  337. package/lib/test/utils/fileSystemAccessMocks.js +0 -277
  338. package/lib/test/utils/fileSystemAccessMocks.js.map +0 -1
  339. package/lib/test/utils/testHelpers.d.ts +0 -51
  340. package/lib/test/utils/testHelpers.d.ts.map +0 -1
  341. package/lib/test/utils/testHelpers.js +0 -133
  342. package/lib/test/utils/testHelpers.js.map +0 -1
  343. package/rush-logs/ts-web-extras.build.cache.log +0 -3
  344. package/rush-logs/ts-web-extras.build.log +0 -55
  345. package/src/index.browser.ts +0 -24
  346. package/src/index.ts +0 -47
  347. package/src/packlets/crypto-utils/browserCryptoProvider.ts +0 -311
  348. package/src/packlets/crypto-utils/browserHashProvider.ts +0 -73
  349. package/src/packlets/crypto-utils/index.ts +0 -29
  350. package/src/packlets/file-api-types/index.ts +0 -366
  351. package/src/packlets/file-tree/directoryHandleStore.ts +0 -136
  352. package/src/packlets/file-tree/fileApiTreeAccessors.ts +0 -528
  353. package/src/packlets/file-tree/fileSystemAccessTreeAccessors.ts +0 -519
  354. package/src/packlets/file-tree/httpTreeAccessors.ts +0 -448
  355. package/src/packlets/file-tree/index.ts +0 -32
  356. package/src/packlets/file-tree/localStorageTreeAccessors.ts +0 -430
  357. package/src/packlets/helpers/fileTreeHelpers.ts +0 -107
  358. package/src/packlets/helpers/index.ts +0 -28
  359. package/src/packlets/url-utils/index.ts +0 -28
  360. package/src/packlets/url-utils/urlParams.ts +0 -245
  361. package/src/test/mocks/idb-keyval.ts +0 -5
  362. package/src/test/setupTests.ts +0 -87
  363. package/src/test/unit/browserHashProvider.test.ts +0 -155
  364. package/src/test/unit/browserHashProvider.test.ts.bak +0 -376
  365. package/src/test/unit/directoryHandleStore.test.ts +0 -251
  366. package/src/test/unit/fileApiTreeAccessors.test.ts +0 -1387
  367. package/src/test/unit/fileApiTypes.test.ts +0 -587
  368. package/src/test/unit/fileSystemAccessTreeAccessors.test.ts +0 -885
  369. package/src/test/unit/fileTreeHelpers.test.ts +0 -694
  370. package/src/test/unit/httpTreeAccessors.test.ts +0 -1571
  371. package/src/test/unit/localStorageTreeAccessors.test.ts +0 -1014
  372. package/src/test/unit/urlParams.test.ts +0 -464
  373. package/src/test/utils/fileSystemAccessMocks.ts +0 -353
  374. package/src/test/utils/testHelpers.ts +0 -155
  375. package/temp/build/typescript/ts_8nwakTlr.json +0 -1
  376. package/temp/coverage/base.css +0 -224
  377. package/temp/coverage/block-navigation.js +0 -87
  378. package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +0 -1018
  379. package/temp/coverage/crypto-utils/browserHashProvider.ts.html +0 -304
  380. package/temp/coverage/crypto-utils/index.html +0 -131
  381. package/temp/coverage/favicon.png +0 -0
  382. package/temp/coverage/file-tree/directoryHandleStore.ts.html +0 -493
  383. package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +0 -1669
  384. package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +0 -1642
  385. package/temp/coverage/file-tree/httpTreeAccessors.ts.html +0 -1429
  386. package/temp/coverage/file-tree/index.html +0 -176
  387. package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +0 -1375
  388. package/temp/coverage/helpers/fileTreeHelpers.ts.html +0 -406
  389. package/temp/coverage/helpers/index.html +0 -116
  390. package/temp/coverage/index.html +0 -161
  391. package/temp/coverage/lcov-report/base.css +0 -224
  392. package/temp/coverage/lcov-report/block-navigation.js +0 -87
  393. package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +0 -1018
  394. package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +0 -304
  395. package/temp/coverage/lcov-report/crypto-utils/index.html +0 -131
  396. package/temp/coverage/lcov-report/favicon.png +0 -0
  397. package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +0 -493
  398. package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +0 -1669
  399. package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +0 -1642
  400. package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +0 -1429
  401. package/temp/coverage/lcov-report/file-tree/index.html +0 -176
  402. package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +0 -1375
  403. package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +0 -406
  404. package/temp/coverage/lcov-report/helpers/index.html +0 -116
  405. package/temp/coverage/lcov-report/index.html +0 -161
  406. package/temp/coverage/lcov-report/prettify.css +0 -1
  407. package/temp/coverage/lcov-report/prettify.js +0 -2
  408. package/temp/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  409. package/temp/coverage/lcov-report/sorter.js +0 -210
  410. package/temp/coverage/lcov-report/url-utils/index.html +0 -116
  411. package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +0 -820
  412. package/temp/coverage/lcov.info +0 -3597
  413. package/temp/coverage/prettify.css +0 -1
  414. package/temp/coverage/prettify.js +0 -2
  415. package/temp/coverage/sort-arrow-sprite.png +0 -0
  416. package/temp/coverage/sorter.js +0 -210
  417. package/temp/coverage/url-utils/index.html +0 -116
  418. package/temp/coverage/url-utils/urlParams.ts.html +0 -820
  419. package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
  420. package/temp/test/jest/jest-transform-cache-7492f1b44480e0cdd1f220078fb3afd8-79ef2876fae7ca75eedb2aa53dc48338/7c/package_7c16afc8299e635d80273763175c7a50 +0 -53
  421. package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +0 -1
  422. package/temp/ts-web-extras.api.json +0 -8850
  423. package/temp/ts-web-extras.api.md +0 -433
  424. package/tsconfig.json +0 -7
@@ -1 +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,O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AAC,CAAC;YAC3D,OAAO,OAAO,CAAC,IAAI,CAAC,mCAAmC,OAAO,EAAE,CAAC,CAAC;QACpE,CAAC;IACH,CAAC;IAED;;;;OAIG;IACI,QAAQ,CAAC,IAAgB;QAC9B,sDAAsD;QACtD,IAAI,MAAM,GAAG,EAAE,CAAC;QAChB,KAAK,IAAI,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"]}
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,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,IAAI,EACJ,OAAO,EAEP,OAAO,EACP,OAAO,EAER,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,sGAAsG;AACtG;;;;GA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6B,EAAE,KAAa;IACjF,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QAClC,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,uCAAuC,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,CAAC;IAC7F,CAAC;IACD,MAAM,UAAU,GAAI,GAAG,CAAC,SAA4B,CAAC,UAAU,CAAC;IAChE,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,mCAAmC,UAAU,IAAI,CAAC,CAAC;IACjF,CAAC;IACD,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACzB,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,cAAc,OAAO,oBAAoB,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;IACrF,CAAC;IACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAED,4FAA4F;AAC5F;;;;;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\nimport {\n captureAsyncResult,\n captureResult,\n fail,\n Failure,\n Result,\n succeed,\n Success,\n Uuid\n} from '@fgv/ts-utils';\nimport { CryptoUtils } from '@fgv/ts-extras';\n\n/* c8 ignore start - Used only by browser-only methods that cannot be tested in Node.js environment */\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/* c8 ignore stop */\n\n/**\n * Returns a fresh Uint8Array view over a non-shared ArrayBuffer copy of `arr`.\n * Used by {@link BrowserCryptoProvider.wrapBytes | wrapBytes} and\n * {@link BrowserCryptoProvider.unwrapBytes | unwrapBytes}: Node 20's\n * webcrypto.subtle rejects raw `ArrayBuffer` for several `BufferSource`\n * parameters with \"is not instance of ArrayBuffer, Buffer, TypedArray, or\n * DataView\" even though `ArrayBuffer` should be valid per the spec; a\n * TypedArray view is accepted on Node 20+ and on browsers, and the explicit\n * `Uint8Array<ArrayBuffer>` return type also satisfies TypeScript's `BufferSource`\n * (which excludes the `SharedArrayBuffer` branch of `Uint8Array`'s buffer type).\n */\nfunction toBufferView(arr: Uint8Array): Uint8Array<ArrayBuffer> {\n const buffer = new ArrayBuffer(arr.byteLength);\n const view = new Uint8Array(buffer);\n view.set(arr);\n return view;\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 CryptoUtils.ICryptoProvider {\n private readonly _crypto: Crypto;\n\n /* c8 ignore start - Existing browser-only methods cannot be tested in Node.js environment */\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<CryptoUtils.IEncryptionResult>> {\n if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n try {\n // Generate random IV\n const iv = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.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: CryptoUtils.Constants.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 - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE\n );\n const authTag = encryptedArray.slice(encryptedArray.length - CryptoUtils.Constants.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 !== CryptoUtils.Constants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== CryptoUtils.Constants.GCM_IV_SIZE) {\n return Failure.with(`IV must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `Auth tag must be ${CryptoUtils.Constants.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: CryptoUtils.Constants.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(\n this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.AES_256_KEY_SIZE))\n );\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 CryptoUtils.Constants.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 * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns `Success` with hex-encoded hash string, or `Failure` with an error.\n */\n public async sha256(data: string): Promise<Result<string>> {\n try {\n const encoder = new TextEncoder();\n const dataBuffer = encoder.encode(data);\n const hashBuffer = await this._crypto.subtle.digest('SHA-256', 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 return succeed(hashHex);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return fail(`SHA-256 hash 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 /* c8 ignore stop */\n\n /**\n * Generates a cryptographically random UUIDv4 using the injected\n * `Crypto` instance.\n * @returns `Success` with the generated UUID, or `Failure` if the underlying\n * `Crypto` instance does not expose `randomUUID`.\n */\n public generateUuid(): Result<Uuid> {\n /* c8 ignore next 3 - randomUUID is always available in supported runtimes (Node 22+, modern browsers) */\n if (typeof this._crypto.randomUUID !== 'function') {\n return Failure.with('Crypto instance does not expose randomUUID');\n }\n return captureResult(() => this._crypto.randomUUID() as Uuid);\n }\n\n /* c8 ignore start - browser-only methods continue */\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 // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair via Web Crypto.\n * @param algorithm - The algorithm to use.\n * @param extractable - Whether the resulting keys may be exported.\n * @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.\n */\n public async generateKeyPair(\n algorithm: CryptoUtils.KeyPairAlgorithm,\n extractable: boolean\n ): Promise<Result<CryptoKeyPair>> {\n const params = CryptoUtils.keyPairAlgorithmParams[algorithm];\n // Widening upcast to `AlgorithmIdentifier` steers TS to subtle.generateKey's\n // broad overload, which accepts the Ed25519 `{ name: 'Ed25519' }` shape and\n // returns `CryptoKey | CryptoKeyPair`. The narrowing back to `CryptoKeyPair`\n // is a runtime check via the `in` operator, not a type assertion.\n const result = await captureAsyncResult(async () => {\n const generated = await this._crypto.subtle.generateKey(\n params.generateKey as AlgorithmIdentifier,\n extractable,\n [...params.keyPairUsages]\n );\n if ('privateKey' in generated && 'publicKey' in generated) {\n return generated;\n }\n /* c8 ignore next - unreachable: every entry in keyPairAlgorithmParams produces a keypair */\n throw new Error(`${algorithm} unexpectedly produced a single CryptoKey`);\n });\n return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);\n }\n\n /**\n * Exports a public `CryptoKey` as a JSON Web Key.\n * @remarks\n * Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`\n * does not enforce public-vs-private; without this guard a caller that\n * passed an extractable private key would receive its private fields\n * (`d`, `p`, `q`, ...) as JWK, defeating the method's name.\n * @param publicKey - Extractable public key to export.\n * @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.\n */\n public async exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>> {\n if (publicKey.type !== 'public') {\n return Failure.with(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => this._crypto.subtle.exportKey('jwk', publicKey));\n return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);\n }\n\n /**\n * Imports a public-key JWK as a `CryptoKey` for the requested algorithm.\n * @param jwk - The JSON Web Key produced by a prior export.\n * @param algorithm - The algorithm the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.\n */\n public async importPublicKeyJwk(\n jwk: JsonWebKey,\n algorithm: CryptoUtils.KeyPairAlgorithm\n ): Promise<Result<CryptoKey>> {\n const params = CryptoUtils.keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n this._crypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages)\n );\n return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);\n }\n\n /**\n * Exports a public `CryptoKey` as a DER-encoded SPKI blob.\n * @param publicKey - The public `CryptoKey` to export.\n * @returns `Success` with the raw SPKI bytes, or `Failure` with error context.\n */\n public async exportPublicKeySpki(publicKey: CryptoKey): Promise<Result<Uint8Array>> {\n if (publicKey.type !== 'public') {\n return Failure.with(`exportPublicKeySpki requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => this._crypto.subtle.exportKey('spki', publicKey));\n return result\n .withErrorFormat((e) => `exportPublicKeySpki: failed to export key: ${e}`)\n .onSuccess((buf) => succeed(new Uint8Array(buf)));\n }\n\n /**\n * Imports a public key from a DER-encoded SPKI blob.\n * @param spkiBytes - The raw SPKI bytes.\n * @param algorithm - The algorithm the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with error context.\n */\n public async importPublicKeySpki(\n spkiBytes: Uint8Array,\n algorithm: CryptoUtils.KeyPairAlgorithm\n ): Promise<Result<CryptoKey>> {\n const params = CryptoUtils.keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n this._crypto.subtle.importKey(\n 'spki',\n toBufferView(spkiBytes),\n params.importPublicKey as AlgorithmIdentifier,\n true,\n [...params.publicKeyUsages]\n )\n );\n return result.withErrorFormat(\n (e) => `importPublicKeySpki: failed to import ${algorithm} public key from SPKI: ${e}`\n );\n }\n /* c8 ignore stop */\n\n /**\n * Signs `data` with `privateKey` using the algorithm inferred from the key.\n * @param privateKey - A signing `CryptoKey` (`'ecdsa-p256'` or `'ed25519'`).\n * @param data - The bytes to sign.\n * @returns `Success` with the raw signature bytes, or `Failure` with error context.\n */\n public async sign(privateKey: CryptoKey, data: Uint8Array): Promise<Result<Uint8Array>> {\n const algorithm = signAlgorithmFromKey(privateKey);\n const result = await captureAsyncResult(() =>\n this._crypto.subtle.sign(algorithm, privateKey, toBufferView(data))\n );\n return result\n .withErrorFormat((e) => `sign failed: ${e}`)\n .onSuccess((buf) => succeed(new Uint8Array(buf)));\n }\n\n /**\n * Verifies a signature produced by {@link BrowserCryptoProvider.sign}.\n * @param publicKey - A verify `CryptoKey` (`'ecdsa-p256'` or `'ed25519'`).\n * @param signature - The raw signature bytes.\n * @param data - The original data that was signed.\n * @returns `Success` with `true` if valid, `false` if not, or `Failure` with error context.\n */\n public async verify(\n publicKey: CryptoKey,\n signature: Uint8Array,\n data: Uint8Array\n ): Promise<Result<boolean>> {\n const algorithm = signAlgorithmFromKey(publicKey);\n const result = await captureAsyncResult(() =>\n this._crypto.subtle.verify(algorithm, publicKey, toBufferView(signature), toBufferView(data))\n );\n return result.withErrorFormat((e) => `verify failed: ${e}`);\n }\n\n /**\n * Compares two byte arrays in constant time.\n *\n * Accumulates XOR differences with bitwise-OR; no early-return is possible\n * once the length check passes, making timing independent of the byte\n * values. Returns `false` immediately on length mismatch (length is not\n * secret in normal use).\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` if lengths match and all bytes are equal, `false` otherwise.\n */\n public timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n // eslint-disable-next-line no-bitwise\n diff |= a[i] ^ b[i];\n }\n return diff === 0;\n }\n\n /**\n * Computes an HMAC-SHA256 MAC for `data` using `key`.\n * @param key - An HMAC `CryptoKey` with `'sign'` usage.\n * @param data - The bytes to authenticate.\n * @returns `Success` with the 32-byte MAC, or `Failure` with error context.\n */\n public async hmacSha256(key: CryptoKey, data: Uint8Array): Promise<Result<Uint8Array>> {\n const result = await captureAsyncResult(() =>\n this._crypto.subtle.sign({ name: 'HMAC' }, key, toBufferView(data))\n );\n return result\n .withErrorFormat((e) => `hmacSha256 failed: ${e}`)\n .onSuccess((buf) => succeed(new Uint8Array(buf)));\n }\n\n /**\n * Verifies an HMAC-SHA256 MAC in constant time.\n * @param key - An HMAC `CryptoKey` with `'sign'` usage.\n * @param signature - The MAC bytes to verify.\n * @param data - The original data that was authenticated.\n * @returns `Success` with `true` if valid, `false` if not, or `Failure` with error context.\n */\n public async verifyHmacSha256(\n key: CryptoKey,\n signature: Uint8Array,\n data: Uint8Array\n ): Promise<Result<boolean>> {\n return (await this.hmacSha256(key, data))\n .withErrorFormat((e) => `verifyHmacSha256 failed: ${e}`)\n .onSuccess((mac) => succeed(this.timingSafeEqual(mac, signature)));\n }\n\n /**\n * Encrypts raw bytes using AES-256-GCM with a caller-supplied nonce and\n * optional AAD. See {@link CryptoUtils.ICryptoProvider.encryptBytes | ICryptoProvider.encryptBytes}\n * — in particular the caller's responsibility to use a unique `nonce` per\n * message under a given `key`.\n *\n * Byte-identical to {@link CryptoUtils.NodeCryptoProvider.encryptBytes} for\n * identical `(key, nonce, plaintext, aad)`: Web Crypto appends the 16-byte tag\n * to the ciphertext, and this method splits it off so the returned\n * `ciphertext`/`authTag` match Node's separated-tag layout exactly.\n * @param key - 32-byte AES-256 key.\n * @param nonce - 12-byte GCM nonce (must be unique per message under `key`).\n * @param plaintext - The bytes to encrypt (empty permitted).\n * @param aad - Optional additional authenticated data bound into the tag.\n * @returns `Success` with the ciphertext and 16-byte auth tag, or `Failure` with an error.\n */\n public async encryptBytes(\n key: Uint8Array,\n nonce: Uint8Array,\n plaintext: Uint8Array,\n aad?: Uint8Array\n ): Promise<Result<CryptoUtils.IEncryptBytesResult>> {\n if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {\n return Failure.with(\n `encryptBytes: key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`\n );\n }\n if (nonce.length !== CryptoUtils.Constants.GCM_IV_SIZE) {\n return Failure.with(\n `encryptBytes: nonce must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes, got ${nonce.length}`\n );\n }\n const result = await captureAsyncResult(async () => {\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toBufferView(key),\n { name: 'AES-GCM' },\n false,\n ['encrypt']\n );\n const algorithm: AesGcmParams = {\n name: 'AES-GCM',\n iv: toBufferView(nonce),\n tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits\n };\n if (aad !== undefined) {\n algorithm.additionalData = toBufferView(aad);\n }\n const encryptedWithTag = new Uint8Array(\n await this._crypto.subtle.encrypt(algorithm, cryptoKey, toBufferView(plaintext))\n );\n const tagStart = encryptedWithTag.length - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE;\n return {\n ciphertext: encryptedWithTag.slice(0, tagStart),\n authTag: encryptedWithTag.slice(tagStart)\n };\n });\n return result.withErrorFormat((e) => `encryptBytes failed: ${e}`);\n }\n\n /**\n * Decrypts raw bytes produced by {@link BrowserCryptoProvider.encryptBytes}\n * using AES-256-GCM. See\n * {@link CryptoUtils.ICryptoProvider.decryptBytes | ICryptoProvider.decryptBytes}.\n * Fails (never throws) on any authentication failure, including a mismatched `aad`.\n * @param key - 32-byte AES-256 key.\n * @param nonce - 12-byte GCM nonce (the same one used to encrypt).\n * @param ciphertext - The ciphertext from the `encryptBytes` result.\n * @param authTag - The 16-byte GCM auth tag from the `encryptBytes` result.\n * @param aad - The identical AAD supplied at encrypt time (or absent).\n * @returns `Success` with the decrypted plaintext bytes, or `Failure` with an error.\n */\n public async decryptBytes(\n key: Uint8Array,\n nonce: Uint8Array,\n ciphertext: Uint8Array,\n authTag: Uint8Array,\n aad?: Uint8Array\n ): Promise<Result<Uint8Array>> {\n if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {\n return Failure.with(\n `decryptBytes: key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`\n );\n }\n if (nonce.length !== CryptoUtils.Constants.GCM_IV_SIZE) {\n return Failure.with(\n `decryptBytes: nonce must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes, got ${nonce.length}`\n );\n }\n if (authTag.length !== CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `decryptBytes: auth tag must be ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`\n );\n }\n const result = await captureAsyncResult(async () => {\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toBufferView(key),\n { name: 'AES-GCM' },\n false,\n ['decrypt']\n );\n // Web Crypto expects ciphertext + auth tag concatenated.\n const encryptedWithTag = new Uint8Array(ciphertext.length + authTag.length);\n encryptedWithTag.set(ciphertext);\n encryptedWithTag.set(authTag, ciphertext.length);\n const algorithm: AesGcmParams = {\n name: 'AES-GCM',\n iv: toBufferView(nonce),\n tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits\n };\n if (aad !== undefined) {\n algorithm.additionalData = toBufferView(aad);\n }\n const decrypted = await this._crypto.subtle.decrypt(algorithm, cryptoKey, encryptedWithTag);\n return new Uint8Array(decrypted);\n });\n return result.withErrorFormat((e) => `decryptBytes failed: ${e}`);\n }\n\n /**\n * Wraps `plaintext` for the holder of `recipientPublicKey` using\n * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.\n * @param plaintext - The bytes to wrap.\n * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.\n * @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.\n * @returns `Success` with the wrapped payload, or `Failure` with an error.\n */\n public async wrapBytes(\n plaintext: Uint8Array,\n recipientPublicKey: CryptoKey,\n options: CryptoUtils.IWrapBytesOptions\n ): Promise<Result<CryptoUtils.IWrappedBytes>> {\n const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');\n if (recipientCheck.isFailure()) {\n return Failure.with(`wrapBytes failed: ${recipientCheck.message}`);\n }\n const subtle = this._crypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveKey'\n ])) as CryptoKeyPair;\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: recipientPublicKey },\n ephemeral.privateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n const nonce = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));\n const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, toBufferView(plaintext));\n const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);\n return {\n ephemeralPublicKey,\n nonce: this.toBase64(nonce),\n ciphertext: this.toBase64(new Uint8Array(ctBuf))\n };\n });\n return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);\n }\n\n /**\n * Unwraps a payload produced by `wrapBytes` using the recipient's private\n * key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.\n * @param wrapped - The wrapped payload.\n * @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.\n * @param options - HKDF salt and info matching the wrap call.\n * @returns `Success` with the original `plaintext`, or `Failure` with an error.\n */\n public async unwrapBytes(\n wrapped: CryptoUtils.IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: CryptoUtils.IWrapBytesOptions\n ): Promise<Result<Uint8Array>> {\n const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');\n if (recipientCheck.isFailure()) {\n return Failure.with(`unwrapBytes failed: ${recipientCheck.message}`);\n }\n const nonceResult = this.fromBase64(wrapped.nonce);\n if (nonceResult.isFailure()) {\n return Failure.with(`unwrapBytes failed: nonce: ${nonceResult.message}`);\n }\n if (nonceResult.value.length !== CryptoUtils.Constants.GCM_IV_SIZE) {\n return Failure.with(\n `unwrapBytes failed: nonce must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`\n );\n }\n const ciphertextResult = this.fromBase64(wrapped.ciphertext);\n if (ciphertextResult.isFailure()) {\n return Failure.with(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);\n }\n if (ciphertextResult.value.length < CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `unwrapBytes failed: ciphertext must be at least ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`\n );\n }\n const subtle = this._crypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeralPub = await subtle.importKey(\n 'jwk',\n wrapped.ephemeralPublicKey,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: ephemeralPub },\n recipientPrivateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['decrypt']\n );\n const ptBuf = await subtle.decrypt(\n { name: 'AES-GCM', iv: toBufferView(nonceResult.value) },\n wrapKey,\n toBufferView(ciphertextResult.value)\n );\n return new Uint8Array(ptBuf);\n });\n return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);\n }\n}\n\n/**\n * Derives the algorithm identifier needed by `crypto.subtle.sign/verify`\n * from the key's embedded `algorithm` property. ECDSA requires an explicit\n * `hash` parameter that is not stored on the key object itself; all other\n * supported signing algorithms (`Ed25519`) use the key algorithm as-is.\n */\nfunction signAlgorithmFromKey(key: CryptoKey): AlgorithmIdentifier | EcdsaParams {\n if (key.algorithm.name === 'ECDSA') {\n return { name: 'ECDSA', hash: 'SHA-256' };\n }\n return key.algorithm as AlgorithmIdentifier;\n}\n\n/**\n * Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`\n * (public or private). Used by the wrap/unwrap methods to surface a clean\n * `Failure` instead of letting the WebCrypto deriveKey call throw a less\n * informative error later in the pipeline. Key usages are intentionally not\n * checked here: WebCrypto already produces a specific error if `deriveKey` is\n * not in `usages`, and `deriveBits` is an equally valid alternative usage that\n * an explicit check would have to track.\n * @param key - The CryptoKey to validate.\n * @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).\n * @param label - Human-readable role label included in the failure message.\n * @returns `Success` with the key (unchanged) when the algorithm, curve, and\n * type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.\n */\nfunction checkEcdhP256(key: CryptoKey, keyType: 'public' | 'private', label: string): Result<CryptoKey> {\n if (key.algorithm.name !== 'ECDH') {\n return Failure.with(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);\n }\n const namedCurve = (key.algorithm as EcKeyAlgorithm).namedCurve;\n if (namedCurve !== 'P-256') {\n return Failure.with(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);\n }\n if (key.type !== keyType) {\n return Failure.with(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);\n }\n return succeed(key);\n}\n\n/* c8 ignore start - Constructs a provider; only meaningful in a real browser environment */\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,238 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { captureAsyncResult, captureResult, fail, succeed } from '@fgv/ts-utils';
23
+ const DEFAULT_DATABASE_NAME = 'fgv-keystore-private-keys';
24
+ const DEFAULT_STORE_NAME = 'privateKeys';
25
+ /**
26
+ * {@link CryptoUtils.KeyStore.IPrivateKeyStorage | IPrivateKeyStorage}
27
+ * implementation backed by IndexedDB. Stores `CryptoKey` objects directly via
28
+ * IndexedDB's structured-clone serialization — no JWK round-trip — so it works
29
+ * with non-extractable keys.
30
+ *
31
+ * `supportsNonExtractable` is `true`: because the `CryptoKey` is stored by
32
+ * reference (structured clone) rather than exported, the keystore may generate
33
+ * `extractable: false` keys for maximum security on browsers that support it.
34
+ *
35
+ * The database is opened lazily on first use and cached. Each operation runs in
36
+ * its own transaction, relying on IndexedDB's default serialization. Multi-tab
37
+ * concurrency is a known limitation: two tabs writing the same id can race; this
38
+ * implementation targets single-tab use.
39
+ *
40
+ * @public
41
+ */
42
+ export class IdbPrivateKeyStorage {
43
+ constructor(factory, databaseName, storeName) {
44
+ /**
45
+ * `true` — IndexedDB stores `CryptoKey` objects directly, so non-extractable
46
+ * keys are supported.
47
+ */
48
+ this.supportsNonExtractable = true;
49
+ this._factory = factory;
50
+ this._databaseName = databaseName;
51
+ this._storeName = storeName;
52
+ }
53
+ /**
54
+ * Creates a new {@link CryptoUtils.IdbPrivateKeyStorage}.
55
+ * @param params - Optional {@link CryptoUtils.IIdbPrivateKeyStorageCreateParams}.
56
+ * @returns `Success` with the new instance, or `Failure` if no IndexedDB
57
+ * factory is available.
58
+ */
59
+ static create(params = {}) {
60
+ var _a, _b, _c;
61
+ const factory = (_a = params.indexedDB) !== null && _a !== void 0 ? _a : globalThis.indexedDB;
62
+ if (factory === undefined) {
63
+ return fail('IdbPrivateKeyStorage: no IndexedDB factory available (pass params.indexedDB)');
64
+ }
65
+ return succeed(new IdbPrivateKeyStorage(factory, (_b = params.databaseName) !== null && _b !== void 0 ? _b : DEFAULT_DATABASE_NAME, (_c = params.storeName) !== null && _c !== void 0 ? _c : DEFAULT_STORE_NAME));
66
+ }
67
+ /**
68
+ * Stores `key` under `id`.
69
+ * @param id - Storage handle to write under.
70
+ * @param key - The private `CryptoKey` to persist.
71
+ */
72
+ async store(id, key) {
73
+ if (key.type !== 'private') {
74
+ return fail(`failed to store private key '${id}': expected a private key, got '${key.type}'`);
75
+ }
76
+ return (await this._withStore('readwrite', (store) => this._request(store.put(key, id))))
77
+ .withErrorFormat((msg) => `failed to store private key '${id}': ${msg}`)
78
+ .onSuccess(() => succeed(id));
79
+ }
80
+ /**
81
+ * Loads the private key stored under `id`.
82
+ * @param id - Storage handle to look up.
83
+ */
84
+ async load(id) {
85
+ return (await this._getRaw(id))
86
+ .withErrorFormat((msg) => `failed to load private key '${id}': ${msg}`)
87
+ .onSuccess((key) => (key === undefined ? fail(`key not found: '${id}'`) : succeed(key)));
88
+ }
89
+ /**
90
+ * Deletes the entry stored under `id`. Missing ids fail, mirroring the
91
+ * encrypted-file backend. The existence check and the delete run in separate
92
+ * transactions (single-tab assumption).
93
+ * @param id - Storage handle to remove.
94
+ */
95
+ async delete(id) {
96
+ const existingResult = await this._getRaw(id);
97
+ /* c8 ignore next 3 - defensive: the existence-check read only fails on an IndexedDB environment error */
98
+ if (existingResult.isFailure()) {
99
+ return fail(`failed to delete private key '${id}': ${existingResult.message}`);
100
+ }
101
+ if (existingResult.value === undefined) {
102
+ return fail(`key not found: '${id}'`);
103
+ }
104
+ return (await this._withStore('readwrite', (store) => this._request(store.delete(id))))
105
+ .withErrorFormat((msg) => `failed to delete private key '${id}': ${msg}`)
106
+ .onSuccess(() => succeed(id));
107
+ }
108
+ /**
109
+ * Lists every stored id.
110
+ */
111
+ async list() {
112
+ return (await this._withStore('readonly', (store) => this._request(store.getAllKeys())))
113
+ .withErrorFormat((msg) => `failed to list private keys: ${msg}`)
114
+ .onSuccess((keys) => succeed(keys.map((key) => String(key))));
115
+ }
116
+ async _getRaw(id) {
117
+ return this._withStore('readonly', (store) => this._request(store.get(id)));
118
+ }
119
+ async _openDb() {
120
+ if (this._db !== undefined) {
121
+ return succeed(this._db);
122
+ }
123
+ const firstOpen = await this._open(undefined);
124
+ /* c8 ignore next 3 - defensive: database open only fails on a corrupted/blocked IndexedDB environment */
125
+ if (firstOpen.isFailure()) {
126
+ return firstOpen;
127
+ }
128
+ // The object store is created in `onupgradeneeded`, which only fires when
129
+ // the version changes. If a database at this name already existed at the
130
+ // current version but without our store (e.g. a different `storeName` than
131
+ // a prior instance used), the store is absent. Re-open at the next version
132
+ // to add it via a version-bump upgrade rather than failing later writes
133
+ // with NotFoundError.
134
+ let db = firstOpen.value;
135
+ if (!db.objectStoreNames.contains(this._storeName)) {
136
+ const nextVersion = db.version + 1;
137
+ db.close();
138
+ const reopen = await this._open(nextVersion);
139
+ /* c8 ignore next 3 - defensive: the version-bump re-open only fails on an IndexedDB environment fault */
140
+ if (reopen.isFailure()) {
141
+ return reopen;
142
+ }
143
+ db = reopen.value;
144
+ }
145
+ this._db = db;
146
+ return succeed(db);
147
+ }
148
+ async _open(version) {
149
+ return captureAsyncResult(() => new Promise((resolve, reject) => {
150
+ const request = version === undefined
151
+ ? this._factory.open(this._databaseName)
152
+ : this._factory.open(this._databaseName, version);
153
+ request.onupgradeneeded = () => {
154
+ // Create our object store if absent. This fires on initial creation
155
+ // and on the version bump used to add a store to an existing
156
+ // database; future schema migrations extend this hook additively.
157
+ if (!request.result.objectStoreNames.contains(this._storeName)) {
158
+ request.result.createObjectStore(this._storeName);
159
+ }
160
+ };
161
+ request.onsuccess = () => {
162
+ const db = request.result;
163
+ // If another connection (e.g. a sibling instance adding a store via
164
+ // version bump, or another tab) needs to upgrade, close this one so
165
+ // we don't block it. Clear the cached handle first so the next
166
+ // operation reopens rather than reusing the now-closed connection.
167
+ // Single-tab use is the documented assumption; this just prevents a
168
+ // deadlock when several instances share a db.
169
+ db.onversionchange = () => {
170
+ if (this._db === db) {
171
+ this._db = undefined;
172
+ }
173
+ db.close();
174
+ };
175
+ resolve(db);
176
+ };
177
+ /* c8 ignore next 2 - defensive: open errors require a corrupted/blocked IndexedDB environment */
178
+ request.onerror = () => { var _a; return reject((_a = request.error) !== null && _a !== void 0 ? _a : new Error('IndexedDB open failed')); };
179
+ }));
180
+ }
181
+ async _withStore(mode, op) {
182
+ const dbResult = await this._openDb();
183
+ /* c8 ignore next 3 - defensive: database open only fails on a corrupted/blocked IndexedDB environment */
184
+ if (dbResult.isFailure()) {
185
+ return fail(dbResult.message);
186
+ }
187
+ const txnResult = captureResult(() => dbResult.value.transaction(this._storeName, mode));
188
+ /* c8 ignore next 3 - transaction creation only throws if the store was deleted out from under us */
189
+ if (txnResult.isFailure()) {
190
+ return fail(txnResult.message);
191
+ }
192
+ const transaction = txnResult.value;
193
+ // For writes, a successful request is not durable until the transaction
194
+ // commits (oncomplete); it can still abort afterwards. Attach the completion
195
+ // listener BEFORE issuing the request so no event is missed, and wait for it
196
+ // before reporting success. Reads need no such wait.
197
+ const completion = mode === 'readwrite' ? this._awaitCompletion(transaction) : undefined;
198
+ // `op` builds and issues the IDB request synchronously (e.g. `store.put`),
199
+ // which can throw before any Promise is created — DataCloneError on a
200
+ // non-cloneable value, or a transaction-state DOMException. Run it inside a
201
+ // capture boundary so those surface as Failure rather than a rejection,
202
+ // preserving the Result contract.
203
+ const opOuter = await captureAsyncResult(() => op(transaction.objectStore(this._storeName)));
204
+ /* c8 ignore next 3 - defensive: synchronous IDB throws (e.g. DataCloneError) are unreachable for the typed public surface (private CryptoKeys clone; reads pass a string id), but the capture preserves the Result contract */
205
+ if (opOuter.isFailure()) {
206
+ return fail(opOuter.message);
207
+ }
208
+ const opResult = opOuter.value;
209
+ /* c8 ignore next 3 - defensive: the request itself only fails on an IndexedDB environment fault */
210
+ if (opResult.isFailure()) {
211
+ return opResult;
212
+ }
213
+ if (completion !== undefined) {
214
+ const commitResult = await completion;
215
+ /* c8 ignore next 3 - defensive: a transaction abort after a successful request requires an IndexedDB environment fault */
216
+ if (commitResult.isFailure()) {
217
+ return fail(commitResult.message);
218
+ }
219
+ }
220
+ return opResult;
221
+ }
222
+ async _request(request) {
223
+ return captureAsyncResult(() => new Promise((resolve, reject) => {
224
+ request.onsuccess = () => resolve(request.result);
225
+ /* c8 ignore next 2 - defensive: per-request errors require a corrupted IndexedDB environment */
226
+ request.onerror = () => { var _a; return reject((_a = request.error) !== null && _a !== void 0 ? _a : new Error('IndexedDB request failed')); };
227
+ }));
228
+ }
229
+ async _awaitCompletion(transaction) {
230
+ return captureAsyncResult(() => new Promise((resolve, reject) => {
231
+ transaction.oncomplete = () => resolve(true);
232
+ /* c8 ignore next 4 - defensive: abort/error after a successful write requires an IndexedDB environment fault */
233
+ transaction.onabort = () => { var _a; return reject((_a = transaction.error) !== null && _a !== void 0 ? _a : new Error('IndexedDB transaction aborted')); };
234
+ transaction.onerror = () => { var _a; return reject((_a = transaction.error) !== null && _a !== void 0 ? _a : new Error('IndexedDB transaction error')); };
235
+ }));
236
+ }
237
+ }
238
+ //# sourceMappingURL=idbPrivateKeyStorage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idbPrivateKeyStorage.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/idbPrivateKeyStorage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,IAAI,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AA0BzF,MAAM,qBAAqB,GAAW,2BAA2B,CAAC;AAClE,MAAM,kBAAkB,GAAW,aAAa,CAAC;AAEjD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,oBAAoB;IAY/B,YAAoB,OAAmB,EAAE,YAAoB,EAAE,SAAiB;QAXhF;;;WAGG;QACa,2BAAsB,GAAS,IAAI,CAAC;QAQlD,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,MAAM,CAAC,SAA4C,EAAE;;QACjE,MAAM,OAAO,GAA2B,MAAA,MAAM,CAAC,SAAS,mCAAI,UAAU,CAAC,SAAS,CAAC;QACjF,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC1B,OAAO,IAAI,C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;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { captureAsyncResult, captureResult, fail, Result, succeed } from '@fgv/ts-utils';\nimport { CryptoUtils } from '@fgv/ts-extras';\n\n/**\n * Parameters for {@link CryptoUtils.IdbPrivateKeyStorage.create}.\n * @public\n */\nexport interface IIdbPrivateKeyStorageCreateParams {\n /**\n * IndexedDB database name. Default: `'fgv-keystore-private-keys'`.\n */\n readonly databaseName?: string;\n\n /**\n * IndexedDB object-store name. Default: `'privateKeys'`.\n */\n readonly storeName?: string;\n\n /**\n * IndexedDB factory to use. Defaults to `globalThis.indexedDB`. Supplied\n * explicitly in tests (e.g. a `fake-indexeddb` factory) or to target a\n * non-default factory.\n */\n readonly indexedDB?: IDBFactory;\n}\n\nconst DEFAULT_DATABASE_NAME: string = 'fgv-keystore-private-keys';\nconst DEFAULT_STORE_NAME: string = 'privateKeys';\n\n/**\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage | IPrivateKeyStorage}\n * implementation backed by IndexedDB. Stores `CryptoKey` objects directly via\n * IndexedDB's structured-clone serialization — no JWK round-trip — so it works\n * with non-extractable keys.\n *\n * `supportsNonExtractable` is `true`: because the `CryptoKey` is stored by\n * reference (structured clone) rather than exported, the keystore may generate\n * `extractable: false` keys for maximum security on browsers that support it.\n *\n * The database is opened lazily on first use and cached. Each operation runs in\n * its own transaction, relying on IndexedDB's default serialization. Multi-tab\n * concurrency is a known limitation: two tabs writing the same id can race; this\n * implementation targets single-tab use.\n *\n * @public\n */\nexport class IdbPrivateKeyStorage implements CryptoUtils.KeyStore.IPrivateKeyStorage {\n /**\n * `true` — IndexedDB stores `CryptoKey` objects directly, so non-extractable\n * keys are supported.\n */\n public readonly supportsNonExtractable: true = true;\n\n private readonly _factory: IDBFactory;\n private readonly _databaseName: string;\n private readonly _storeName: string;\n private _db: IDBDatabase | undefined;\n\n private constructor(factory: IDBFactory, databaseName: string, storeName: string) {\n this._factory = factory;\n this._databaseName = databaseName;\n this._storeName = storeName;\n }\n\n /**\n * Creates a new {@link CryptoUtils.IdbPrivateKeyStorage}.\n * @param params - Optional {@link CryptoUtils.IIdbPrivateKeyStorageCreateParams}.\n * @returns `Success` with the new instance, or `Failure` if no IndexedDB\n * factory is available.\n */\n public static create(params: IIdbPrivateKeyStorageCreateParams = {}): Result<IdbPrivateKeyStorage> {\n const factory: IDBFactory | undefined = params.indexedDB ?? globalThis.indexedDB;\n if (factory === undefined) {\n return fail('IdbPrivateKeyStorage: no IndexedDB factory available (pass params.indexedDB)');\n }\n return succeed(\n new IdbPrivateKeyStorage(\n factory,\n params.databaseName ?? DEFAULT_DATABASE_NAME,\n params.storeName ?? DEFAULT_STORE_NAME\n )\n );\n }\n\n /**\n * Stores `key` under `id`.\n * @param id - Storage handle to write under.\n * @param key - The private `CryptoKey` to persist.\n */\n public async store(id: string, key: CryptoKey): Promise<Result<string>> {\n if (key.type !== 'private') {\n return fail(`failed to store private key '${id}': expected a private key, got '${key.type}'`);\n }\n return (await this._withStore('readwrite', (store) => this._request(store.put(key, id))))\n .withErrorFormat((msg) => `failed to store private key '${id}': ${msg}`)\n .onSuccess(() => succeed(id));\n }\n\n /**\n * Loads the private key stored under `id`.\n * @param id - Storage handle to look up.\n */\n public async load(id: string): Promise<Result<CryptoKey>> {\n return (await this._getRaw(id))\n .withErrorFormat((msg) => `failed to load private key '${id}': ${msg}`)\n .onSuccess((key) => (key === undefined ? fail(`key not found: '${id}'`) : succeed(key)));\n }\n\n /**\n * Deletes the entry stored under `id`. Missing ids fail, mirroring the\n * encrypted-file backend. The existence check and the delete run in separate\n * transactions (single-tab assumption).\n * @param id - Storage handle to remove.\n */\n public async delete(id: string): Promise<Result<string>> {\n const existingResult = await this._getRaw(id);\n /* c8 ignore next 3 - defensive: the existence-check read only fails on an IndexedDB environment error */\n if (existingResult.isFailure()) {\n return fail(`failed to delete private key '${id}': ${existingResult.message}`);\n }\n if (existingResult.value === undefined) {\n return fail(`key not found: '${id}'`);\n }\n return (await this._withStore('readwrite', (store) => this._request(store.delete(id))))\n .withErrorFormat((msg) => `failed to delete private key '${id}': ${msg}`)\n .onSuccess(() => succeed(id));\n }\n\n /**\n * Lists every stored id.\n */\n public async list(): Promise<Result<readonly string[]>> {\n return (await this._withStore('readonly', (store) => this._request<IDBValidKey[]>(store.getAllKeys())))\n .withErrorFormat((msg) => `failed to list private keys: ${msg}`)\n .onSuccess((keys) => succeed(keys.map((key) => String(key))));\n }\n\n private async _getRaw(id: string): Promise<Result<CryptoKey | undefined>> {\n return this._withStore('readonly', (store) => this._request<CryptoKey | undefined>(store.get(id)));\n }\n\n private async _openDb(): Promise<Result<IDBDatabase>> {\n if (this._db !== undefined) {\n return succeed(this._db);\n }\n const firstOpen = await this._open(undefined);\n /* c8 ignore next 3 - defensive: database open only fails on a corrupted/blocked IndexedDB environment */\n if (firstOpen.isFailure()) {\n return firstOpen;\n }\n // The object store is created in `onupgradeneeded`, which only fires when\n // the version changes. If a database at this name already existed at the\n // current version but without our store (e.g. a different `storeName` than\n // a prior instance used), the store is absent. Re-open at the next version\n // to add it via a version-bump upgrade rather than failing later writes\n // with NotFoundError.\n let db = firstOpen.value;\n if (!db.objectStoreNames.contains(this._storeName)) {\n const nextVersion = db.version + 1;\n db.close();\n const reopen = await this._open(nextVersion);\n /* c8 ignore next 3 - defensive: the version-bump re-open only fails on an IndexedDB environment fault */\n if (reopen.isFailure()) {\n return reopen;\n }\n db = reopen.value;\n }\n this._db = db;\n return succeed(db);\n }\n\n private async _open(version: number | undefined): Promise<Result<IDBDatabase>> {\n return captureAsyncResult<IDBDatabase>(\n () =>\n new Promise<IDBDatabase>((resolve, reject) => {\n const request =\n version === undefined\n ? this._factory.open(this._databaseName)\n : this._factory.open(this._databaseName, version);\n request.onupgradeneeded = (): void => {\n // Create our object store if absent. This fires on initial creation\n // and on the version bump used to add a store to an existing\n // database; future schema migrations extend this hook additively.\n if (!request.result.objectStoreNames.contains(this._storeName)) {\n request.result.createObjectStore(this._storeName);\n }\n };\n request.onsuccess = (): void => {\n const db = request.result;\n // If another connection (e.g. a sibling instance adding a store via\n // version bump, or another tab) needs to upgrade, close this one so\n // we don't block it. Clear the cached handle first so the next\n // operation reopens rather than reusing the now-closed connection.\n // Single-tab use is the documented assumption; this just prevents a\n // deadlock when several instances share a db.\n db.onversionchange = (): void => {\n if (this._db === db) {\n this._db = undefined;\n }\n db.close();\n };\n resolve(db);\n };\n /* c8 ignore next 2 - defensive: open errors require a corrupted/blocked IndexedDB environment */\n request.onerror = (): void => reject(request.error ?? new Error('IndexedDB open failed'));\n })\n );\n }\n\n private async _withStore<T>(\n mode: IDBTransactionMode,\n op: (store: IDBObjectStore) => Promise<Result<T>>\n ): Promise<Result<T>> {\n const dbResult = await this._openDb();\n /* c8 ignore next 3 - defensive: database open only fails on a corrupted/blocked IndexedDB environment */\n if (dbResult.isFailure()) {\n return fail(dbResult.message);\n }\n const txnResult = captureResult(() => dbResult.value.transaction(this._storeName, mode));\n /* c8 ignore next 3 - transaction creation only throws if the store was deleted out from under us */\n if (txnResult.isFailure()) {\n return fail(txnResult.message);\n }\n const transaction = txnResult.value;\n\n // For writes, a successful request is not durable until the transaction\n // commits (oncomplete); it can still abort afterwards. Attach the completion\n // listener BEFORE issuing the request so no event is missed, and wait for it\n // before reporting success. Reads need no such wait.\n const completion = mode === 'readwrite' ? this._awaitCompletion(transaction) : undefined;\n\n // `op` builds and issues the IDB request synchronously (e.g. `store.put`),\n // which can throw before any Promise is created — DataCloneError on a\n // non-cloneable value, or a transaction-state DOMException. Run it inside a\n // capture boundary so those surface as Failure rather than a rejection,\n // preserving the Result contract.\n const opOuter = await captureAsyncResult(() => op(transaction.objectStore(this._storeName)));\n /* c8 ignore next 3 - defensive: synchronous IDB throws (e.g. DataCloneError) are unreachable for the typed public surface (private CryptoKeys clone; reads pass a string id), but the capture preserves the Result contract */\n if (opOuter.isFailure()) {\n return fail(opOuter.message);\n }\n const opResult = opOuter.value;\n /* c8 ignore next 3 - defensive: the request itself only fails on an IndexedDB environment fault */\n if (opResult.isFailure()) {\n return opResult;\n }\n if (completion !== undefined) {\n const commitResult = await completion;\n /* c8 ignore next 3 - defensive: a transaction abort after a successful request requires an IndexedDB environment fault */\n if (commitResult.isFailure()) {\n return fail(commitResult.message);\n }\n }\n return opResult;\n }\n\n private async _request<T>(request: IDBRequest<T>): Promise<Result<T>> {\n return captureAsyncResult<T>(\n () =>\n new Promise<T>((resolve, reject) => {\n request.onsuccess = (): void => resolve(request.result);\n /* c8 ignore next 2 - defensive: per-request errors require a corrupted IndexedDB environment */\n request.onerror = (): void => reject(request.error ?? new Error('IndexedDB request failed'));\n })\n );\n }\n\n private async _awaitCompletion(transaction: IDBTransaction): Promise<Result<true>> {\n return captureAsyncResult<true>(\n () =>\n new Promise<true>((resolve, reject) => {\n transaction.oncomplete = (): void => resolve(true);\n /* c8 ignore next 4 - defensive: abort/error after a successful write requires an IndexedDB environment fault */\n transaction.onabort = (): void =>\n reject(transaction.error ?? new Error('IndexedDB transaction aborted'));\n transaction.onerror = (): void =>\n reject(transaction.error ?? new Error('IndexedDB transaction error'));\n })\n );\n }\n}\n"]}
@@ -25,4 +25,17 @@
25
25
  */
26
26
  export * from './browserHashProvider';
27
27
  export * from './browserCryptoProvider';
28
+ export * from './idbPrivateKeyStorage';
29
+ // HpkeProvider re-export: implementation lives in @fgv/ts-extras CryptoUtils packlet;
30
+ // re-exported here so browser callers can import from @fgv/ts-web-extras for this primitive.
31
+ // We import from the top-level namespace to avoid relying on package.json exports path
32
+ // resolution (which requires moduleResolution: node16 or bundler).
33
+ import { CryptoUtils } from '@fgv/ts-extras';
34
+ /**
35
+ * HPKE base mode (RFC 9180) — `DHKEM(X25519, HKDF-SHA256) + HKDF-SHA256 + AES-256-GCM`.
36
+ * Re-exported from `@fgv/ts-extras` for browser consumers.
37
+ * @see {@link CryptoUtils.HpkeProvider}
38
+ * @public
39
+ */
40
+ export const HpkeProvider = CryptoUtils.HpkeProvider;
28
41
  //# sourceMappingURL=index.js.map
@@ -1 +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"]}
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;AACxC,cAAc,wBAAwB,CAAC;AAEvC,sFAAsF;AACtF,6FAA6F;AAC7F,uFAAuF;AACvF,mEAAmE;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAoC,WAAW,CAAC,YAAY,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';\nexport * from './idbPrivateKeyStorage';\n\n// HpkeProvider re-export: implementation lives in @fgv/ts-extras CryptoUtils packlet;\n// re-exported here so browser callers can import from @fgv/ts-web-extras for this primitive.\n// We import from the top-level namespace to avoid relying on package.json exports path\n// resolution (which requires moduleResolution: node16 or bundler).\nimport { CryptoUtils } from '@fgv/ts-extras';\n\n/**\n * HPKE base mode (RFC 9180) — `DHKEM(X25519, HKDF-SHA256) + HKDF-SHA256 + AES-256-GCM`.\n * Re-exported from `@fgv/ts-extras` for browser consumers.\n * @see {@link CryptoUtils.HpkeProvider}\n * @public\n */\nexport const HpkeProvider: typeof CryptoUtils.HpkeProvider = CryptoUtils.HpkeProvider;\n\n/**\n * Output of `HpkeProvider.sealBase`. Re-exported from `@fgv/ts-extras`.\n * @public\n */\nexport type IHpkeSealResult = CryptoUtils.IHpkeSealResult;\n"]}
@@ -1 +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;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ;;;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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"]}
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;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ;;;;GAIG;AAEH,OAAO,EAAE,IAAI,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAG9D;;;GAGG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAW,uBAAuB,CAAC;AAE3E;;;GAGG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAW,mBAAmB,CAAC;AAE1E;;;;GAIG;AACH,MAAM,OAAO,oBAAoB;IAG/B,YACE,SAAiB,2BAA2B,EAC5C,YAAoB,8BAA8B;QAElD,IAAI,CAAC,MAAM,GAAG,WAAW,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IAC/C,CAAC;IAED;;;;;OAKG;IACI,KAAK,CAAC,IAAI,CAAC,KAAa,EAAE,MAAiC;QAChE,IAAI,CAAC;YACH,MAAM,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;YACtC,OAAO,OAAO,CAAC,SAAS,CAAC,CAAC;QAC5B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,I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AO,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACpC,CAAC;QAED,MAAM,OAAO,GAAgE,EAAE,CAAC;QAChF,KAAK,MAAM,KAAK,IAAI,YAAY,CAAC,KAAK,EAAE,CAAC;YACvC,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAC5C,IAAI,YAAY,CAAC,SAAS,EAAE,EAAE,CAAC;gBAC7B,OAAO,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;YACpC,CAAC;YACD,IAAI,YAAY,CAAC,KAAK,KAAK,SAAS,EAAE,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: string = 'chocolate-lab-storage';\n\n/**\n * Default IndexedDB store name for directory handles.\n * @public\n */\nexport const DEFAULT_DIRECTORY_HANDLE_STORE: string = '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"]}
@@ -236,7 +236,7 @@ export class FileApiTreeAccessors {
236
236
  }
237
237
  /**
238
238
  * Extract file metadata from a File.
239
- * @param fileList - The File to extract metadata from
239
+ * @param file - The File to extract metadata from
240
240
  * @returns The {@link IFileMetadata | file metadata}
241
241
  */
242
242
  static extractFileMetadata(file) {