@backblaze-labs/b2-sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (701) hide show
  1. package/CHANGELOG.md +110 -5
  2. package/README.md +144 -33
  3. package/dist/_virtual/_b2-sdk-version-json.cjs +4 -0
  4. package/dist/_virtual/_b2-sdk-version-json.js +4 -0
  5. package/dist/auth/account-info.d.cts +32 -0
  6. package/dist/auth/account-info.d.cts.map +1 -1
  7. package/dist/auth/account-info.d.ts +32 -0
  8. package/dist/auth/account-info.d.ts.map +1 -1
  9. package/dist/auth/file.cjs +408 -207
  10. package/dist/auth/file.cjs.map +1 -1
  11. package/dist/auth/file.d.cts +77 -3
  12. package/dist/auth/file.d.cts.map +1 -1
  13. package/dist/auth/file.d.ts +77 -3
  14. package/dist/auth/file.d.ts.map +1 -1
  15. package/dist/auth/file.js +407 -207
  16. package/dist/auth/file.js.map +1 -1
  17. package/dist/auth/in-memory.cjs +212 -183
  18. package/dist/auth/in-memory.cjs.map +1 -1
  19. package/dist/auth/in-memory.d.cts +8 -0
  20. package/dist/auth/in-memory.d.cts.map +1 -1
  21. package/dist/auth/in-memory.d.ts +8 -0
  22. package/dist/auth/in-memory.d.ts.map +1 -1
  23. package/dist/auth/in-memory.js +211 -182
  24. package/dist/auth/in-memory.js.map +1 -1
  25. package/dist/auth/index.cjs +7 -9
  26. package/dist/auth/index.d.cts +3 -2
  27. package/dist/auth/index.d.cts.map +1 -1
  28. package/dist/auth/index.d.ts +3 -2
  29. package/dist/auth/index.d.ts.map +1 -1
  30. package/dist/auth/index.js +2 -8
  31. package/dist/auth/realms.cjs +80 -7
  32. package/dist/auth/realms.cjs.map +1 -1
  33. package/dist/auth/realms.d.cts +27 -4
  34. package/dist/auth/realms.d.cts.map +1 -1
  35. package/dist/auth/realms.d.ts +27 -4
  36. package/dist/auth/realms.d.ts.map +1 -1
  37. package/dist/auth/realms.js +80 -9
  38. package/dist/auth/realms.js.map +1 -1
  39. package/dist/auth/upload-url-pool.cjs +55 -51
  40. package/dist/auth/upload-url-pool.cjs.map +1 -1
  41. package/dist/auth/upload-url-pool.js +55 -51
  42. package/dist/auth/upload-url-pool.js.map +1 -1
  43. package/dist/bucket.cjs +785 -787
  44. package/dist/bucket.cjs.map +1 -1
  45. package/dist/bucket.d.cts +35 -47
  46. package/dist/bucket.d.cts.map +1 -1
  47. package/dist/bucket.d.ts +35 -47
  48. package/dist/bucket.d.ts.map +1 -1
  49. package/dist/bucket.js +780 -782
  50. package/dist/bucket.js.map +1 -1
  51. package/dist/client.cjs +246 -228
  52. package/dist/client.cjs.map +1 -1
  53. package/dist/client.d.cts +25 -17
  54. package/dist/client.d.cts.map +1 -1
  55. package/dist/client.d.ts +25 -17
  56. package/dist/client.d.ts.map +1 -1
  57. package/dist/client.js +243 -225
  58. package/dist/client.js.map +1 -1
  59. package/dist/copy/large.cjs +114 -71
  60. package/dist/copy/large.cjs.map +1 -1
  61. package/dist/copy/large.d.cts +6 -0
  62. package/dist/copy/large.d.cts.map +1 -1
  63. package/dist/copy/large.d.ts +6 -0
  64. package/dist/copy/large.d.ts.map +1 -1
  65. package/dist/copy/large.js +112 -69
  66. package/dist/copy/large.js.map +1 -1
  67. package/dist/download/checksum.cjs +89 -0
  68. package/dist/download/checksum.cjs.map +1 -0
  69. package/dist/download/checksum.d.cts +40 -0
  70. package/dist/download/checksum.d.cts.map +1 -0
  71. package/dist/download/checksum.d.ts +40 -0
  72. package/dist/download/checksum.d.ts.map +1 -0
  73. package/dist/download/checksum.js +87 -0
  74. package/dist/download/checksum.js.map +1 -0
  75. package/dist/download/parallel.cjs +214 -118
  76. package/dist/download/parallel.cjs.map +1 -1
  77. package/dist/download/parallel.d.cts +5 -1
  78. package/dist/download/parallel.d.cts.map +1 -1
  79. package/dist/download/parallel.d.ts +5 -1
  80. package/dist/download/parallel.d.ts.map +1 -1
  81. package/dist/download/parallel.js +212 -116
  82. package/dist/download/parallel.js.map +1 -1
  83. package/dist/download/single.cjs +188 -97
  84. package/dist/download/single.cjs.map +1 -1
  85. package/dist/download/single.d.cts +6 -1
  86. package/dist/download/single.d.cts.map +1 -1
  87. package/dist/download/single.d.ts +6 -1
  88. package/dist/download/single.d.ts.map +1 -1
  89. package/dist/download/single.js +186 -98
  90. package/dist/download/single.js.map +1 -1
  91. package/dist/errors/index.cjs +699 -243
  92. package/dist/errors/index.cjs.map +1 -1
  93. package/dist/errors/index.d.cts +285 -82
  94. package/dist/errors/index.d.cts.map +1 -1
  95. package/dist/errors/index.d.ts +285 -82
  96. package/dist/errors/index.d.ts.map +1 -1
  97. package/dist/errors/index.js +678 -261
  98. package/dist/errors/index.js.map +1 -1
  99. package/dist/http/retry.cjs +45 -28
  100. package/dist/http/retry.cjs.map +1 -1
  101. package/dist/http/retry.d.cts +15 -2
  102. package/dist/http/retry.d.cts.map +1 -1
  103. package/dist/http/retry.d.ts +15 -2
  104. package/dist/http/retry.d.ts.map +1 -1
  105. package/dist/http/retry.js +46 -31
  106. package/dist/http/retry.js.map +1 -1
  107. package/dist/http/transport.cjs +438 -140
  108. package/dist/http/transport.cjs.map +1 -1
  109. package/dist/http/transport.d.cts +21 -2
  110. package/dist/http/transport.d.cts.map +1 -1
  111. package/dist/http/transport.d.ts +21 -2
  112. package/dist/http/transport.d.ts.map +1 -1
  113. package/dist/http/transport.js +437 -140
  114. package/dist/http/transport.js.map +1 -1
  115. package/dist/http/url-guard.cjs +154 -89
  116. package/dist/http/url-guard.cjs.map +1 -1
  117. package/dist/http/url-guard.d.cts +25 -3
  118. package/dist/http/url-guard.d.cts.map +1 -1
  119. package/dist/http/url-guard.d.ts +25 -3
  120. package/dist/http/url-guard.d.ts.map +1 -1
  121. package/dist/http/url-guard.js +152 -90
  122. package/dist/http/url-guard.js.map +1 -1
  123. package/dist/http/user-agent.cjs +84 -44
  124. package/dist/http/user-agent.cjs.map +1 -1
  125. package/dist/http/user-agent.js +84 -46
  126. package/dist/http/user-agent.js.map +1 -1
  127. package/dist/index.cjs +101 -77
  128. package/dist/index.d.cts +27 -21
  129. package/dist/index.d.cts.map +1 -1
  130. package/dist/index.d.ts +27 -21
  131. package/dist/index.d.ts.map +1 -1
  132. package/dist/index.js +15 -71
  133. package/dist/internal/b2-naming.cjs +66 -0
  134. package/dist/internal/b2-naming.cjs.map +1 -0
  135. package/dist/internal/b2-naming.d.cts +43 -0
  136. package/dist/internal/b2-naming.d.cts.map +1 -0
  137. package/dist/internal/b2-naming.d.ts +43 -0
  138. package/dist/internal/b2-naming.d.ts.map +1 -0
  139. package/dist/internal/b2-naming.js +60 -0
  140. package/dist/internal/b2-naming.js.map +1 -0
  141. package/dist/internal/upload-retry-options.cjs +21 -0
  142. package/dist/internal/upload-retry-options.cjs.map +1 -0
  143. package/dist/internal/upload-retry-options.d.cts +12 -0
  144. package/dist/internal/upload-retry-options.d.cts.map +1 -0
  145. package/dist/internal/upload-retry-options.d.ts +12 -0
  146. package/dist/internal/upload-retry-options.d.ts.map +1 -0
  147. package/dist/internal/upload-retry-options.js +21 -0
  148. package/dist/internal/upload-retry-options.js.map +1 -0
  149. package/dist/internal/url-redaction.cjs +31 -0
  150. package/dist/internal/url-redaction.cjs.map +1 -0
  151. package/dist/internal/url-redaction.d.cts +17 -0
  152. package/dist/internal/url-redaction.d.cts.map +1 -0
  153. package/dist/internal/url-redaction.d.ts +17 -0
  154. package/dist/internal/url-redaction.d.ts.map +1 -0
  155. package/dist/internal/url-redaction.js +31 -0
  156. package/dist/internal/url-redaction.js.map +1 -0
  157. package/dist/notifications/index.cjs +4 -6
  158. package/dist/notifications/index.d.cts +1 -1
  159. package/dist/notifications/index.d.cts.map +1 -1
  160. package/dist/notifications/index.d.ts +1 -1
  161. package/dist/notifications/index.d.ts.map +1 -1
  162. package/dist/notifications/index.js +1 -6
  163. package/dist/notifications/webhook.cjs +195 -85
  164. package/dist/notifications/webhook.cjs.map +1 -1
  165. package/dist/notifications/webhook.d.cts.map +1 -1
  166. package/dist/notifications/webhook.d.ts.map +1 -1
  167. package/dist/notifications/webhook.js +195 -87
  168. package/dist/notifications/webhook.js.map +1 -1
  169. package/dist/object.cjs +253 -210
  170. package/dist/object.cjs.map +1 -1
  171. package/dist/object.d.cts +9 -55
  172. package/dist/object.d.cts.map +1 -1
  173. package/dist/object.d.ts +9 -55
  174. package/dist/object.d.ts.map +1 -1
  175. package/dist/object.js +249 -206
  176. package/dist/object.js.map +1 -1
  177. package/dist/raw/encoding.cjs +74 -35
  178. package/dist/raw/encoding.cjs.map +1 -1
  179. package/dist/raw/encoding.js +74 -38
  180. package/dist/raw/encoding.js.map +1 -1
  181. package/dist/raw/index.cjs +678 -587
  182. package/dist/raw/index.cjs.map +1 -1
  183. package/dist/raw/index.d.cts +121 -18
  184. package/dist/raw/index.d.cts.map +1 -1
  185. package/dist/raw/index.d.ts +121 -18
  186. package/dist/raw/index.d.ts.map +1 -1
  187. package/dist/raw/index.js +674 -589
  188. package/dist/raw/index.js.map +1 -1
  189. package/dist/s3/index.cjs +355 -18
  190. package/dist/s3/index.cjs.map +1 -1
  191. package/dist/s3/index.d.cts +233 -5
  192. package/dist/s3/index.d.cts.map +1 -1
  193. package/dist/s3/index.d.ts +233 -5
  194. package/dist/s3/index.d.ts.map +1 -1
  195. package/dist/s3/index.js +351 -22
  196. package/dist/s3/index.js.map +1 -1
  197. package/dist/s3/sigv4.cjs +149 -0
  198. package/dist/s3/sigv4.cjs.map +1 -0
  199. package/dist/s3/sigv4.d.cts +43 -0
  200. package/dist/s3/sigv4.d.cts.map +1 -0
  201. package/dist/s3/sigv4.d.ts +43 -0
  202. package/dist/s3/sigv4.d.ts.map +1 -0
  203. package/dist/s3/sigv4.js +148 -0
  204. package/dist/s3/sigv4.js.map +1 -0
  205. package/dist/s3/validation.cjs +69 -0
  206. package/dist/s3/validation.cjs.map +1 -0
  207. package/dist/s3/validation.d.cts +43 -0
  208. package/dist/s3/validation.d.cts.map +1 -0
  209. package/dist/s3/validation.d.ts +43 -0
  210. package/dist/s3/validation.d.ts.map +1 -0
  211. package/dist/s3/validation.js +66 -0
  212. package/dist/s3/validation.js.map +1 -0
  213. package/dist/simulator/capabilities.cjs +63 -48
  214. package/dist/simulator/capabilities.cjs.map +1 -1
  215. package/dist/simulator/capabilities.js +63 -49
  216. package/dist/simulator/capabilities.js.map +1 -1
  217. package/dist/simulator/index.cjs +2124 -1548
  218. package/dist/simulator/index.cjs.map +1 -1
  219. package/dist/simulator/index.d.cts +79 -11
  220. package/dist/simulator/index.d.cts.map +1 -1
  221. package/dist/simulator/index.d.ts +79 -11
  222. package/dist/simulator/index.d.ts.map +1 -1
  223. package/dist/simulator/index.js +2112 -1546
  224. package/dist/simulator/index.js.map +1 -1
  225. package/dist/simulator/validation.cjs +191 -153
  226. package/dist/simulator/validation.cjs.map +1 -1
  227. package/dist/simulator/validation.d.cts +3 -21
  228. package/dist/simulator/validation.d.cts.map +1 -1
  229. package/dist/simulator/validation.d.ts +3 -21
  230. package/dist/simulator/validation.d.ts.map +1 -1
  231. package/dist/simulator/validation.js +188 -162
  232. package/dist/simulator/validation.js.map +1 -1
  233. package/dist/streams/collect.cjs +74 -24
  234. package/dist/streams/collect.cjs.map +1 -1
  235. package/dist/streams/collect.d.cts +14 -1
  236. package/dist/streams/collect.d.cts.map +1 -1
  237. package/dist/streams/collect.d.ts +14 -1
  238. package/dist/streams/collect.d.ts.map +1 -1
  239. package/dist/streams/collect.js +74 -25
  240. package/dist/streams/collect.js.map +1 -1
  241. package/dist/streams/file-source.cjs +287 -0
  242. package/dist/streams/file-source.cjs.map +1 -0
  243. package/dist/streams/file-source.d.cts +96 -0
  244. package/dist/streams/file-source.d.cts.map +1 -0
  245. package/dist/streams/file-source.d.ts +96 -0
  246. package/dist/streams/file-source.d.ts.map +1 -0
  247. package/dist/streams/file-source.js +286 -0
  248. package/dist/streams/file-source.js.map +1 -0
  249. package/dist/streams/hash.cjs +207 -115
  250. package/dist/streams/hash.cjs.map +1 -1
  251. package/dist/streams/hash.d.cts +5 -4
  252. package/dist/streams/hash.d.cts.map +1 -1
  253. package/dist/streams/hash.d.ts +5 -4
  254. package/dist/streams/hash.d.ts.map +1 -1
  255. package/dist/streams/hash.js +208 -95
  256. package/dist/streams/hash.js.map +1 -1
  257. package/dist/streams/index.cjs +12 -12
  258. package/dist/streams/index.d.cts +3 -3
  259. package/dist/streams/index.d.cts.map +1 -1
  260. package/dist/streams/index.d.ts +3 -3
  261. package/dist/streams/index.d.ts.map +1 -1
  262. package/dist/streams/index.js +2 -10
  263. package/dist/streams/progress.cjs +60 -46
  264. package/dist/streams/progress.cjs.map +1 -1
  265. package/dist/streams/progress.js +60 -46
  266. package/dist/streams/progress.js.map +1 -1
  267. package/dist/streams/source.cjs +316 -146
  268. package/dist/streams/source.cjs.map +1 -1
  269. package/dist/streams/source.d.cts +56 -18
  270. package/dist/streams/source.d.cts.map +1 -1
  271. package/dist/streams/source.d.ts +56 -18
  272. package/dist/streams/source.d.ts.map +1 -1
  273. package/dist/streams/source.js +312 -149
  274. package/dist/streams/source.js.map +1 -1
  275. package/dist/sync/actions/index.cjs +236 -184
  276. package/dist/sync/actions/index.cjs.map +1 -1
  277. package/dist/sync/actions/index.d.cts +29 -21
  278. package/dist/sync/actions/index.d.cts.map +1 -1
  279. package/dist/sync/actions/index.d.ts +29 -21
  280. package/dist/sync/actions/index.d.ts.map +1 -1
  281. package/dist/sync/actions/index.js +236 -190
  282. package/dist/sync/actions/index.js.map +1 -1
  283. package/dist/sync/b2-sha1-reader.cjs +148 -0
  284. package/dist/sync/b2-sha1-reader.cjs.map +1 -0
  285. package/dist/sync/b2-sha1-reader.d.cts +58 -0
  286. package/dist/sync/b2-sha1-reader.d.cts.map +1 -0
  287. package/dist/sync/b2-sha1-reader.d.ts +58 -0
  288. package/dist/sync/b2-sha1-reader.d.ts.map +1 -0
  289. package/dist/sync/b2-sha1-reader.js +145 -0
  290. package/dist/sync/b2-sha1-reader.js.map +1 -0
  291. package/dist/sync/download-staging.cjs +265 -0
  292. package/dist/sync/download-staging.cjs.map +1 -0
  293. package/dist/sync/download-staging.d.cts +54 -0
  294. package/dist/sync/download-staging.d.cts.map +1 -0
  295. package/dist/sync/download-staging.d.ts +54 -0
  296. package/dist/sync/download-staging.d.ts.map +1 -0
  297. package/dist/sync/download-staging.js +259 -0
  298. package/dist/sync/download-staging.js.map +1 -0
  299. package/dist/sync/filesystem-errors.cjs +32 -0
  300. package/dist/sync/filesystem-errors.cjs.map +1 -0
  301. package/dist/sync/filesystem-errors.d.cts +8 -0
  302. package/dist/sync/filesystem-errors.d.cts.map +1 -0
  303. package/dist/sync/filesystem-errors.d.ts +8 -0
  304. package/dist/sync/filesystem-errors.d.ts.map +1 -0
  305. package/dist/sync/filesystem-errors.js +32 -0
  306. package/dist/sync/filesystem-errors.js.map +1 -0
  307. package/dist/sync/filters.cjs +217 -0
  308. package/dist/sync/filters.cjs.map +1 -0
  309. package/dist/sync/filters.d.cts +51 -0
  310. package/dist/sync/filters.d.cts.map +1 -0
  311. package/dist/sync/filters.d.ts +51 -0
  312. package/dist/sync/filters.d.ts.map +1 -0
  313. package/dist/sync/filters.js +213 -0
  314. package/dist/sync/filters.js.map +1 -0
  315. package/dist/sync/index.cjs +39 -22
  316. package/dist/sync/index.d.cts +14 -9
  317. package/dist/sync/index.d.cts.map +1 -1
  318. package/dist/sync/index.d.ts +14 -9
  319. package/dist/sync/index.d.ts.map +1 -1
  320. package/dist/sync/index.js +9 -20
  321. package/dist/sync/local-file-identity.cjs +61 -0
  322. package/dist/sync/local-file-identity.cjs.map +1 -0
  323. package/dist/sync/local-file-identity.d.cts +37 -0
  324. package/dist/sync/local-file-identity.d.cts.map +1 -0
  325. package/dist/sync/local-file-identity.d.ts +37 -0
  326. package/dist/sync/local-file-identity.d.ts.map +1 -0
  327. package/dist/sync/local-file-identity.js +60 -0
  328. package/dist/sync/local-file-identity.js.map +1 -0
  329. package/dist/sync/local-file-io.cjs +364 -0
  330. package/dist/sync/local-file-io.cjs.map +1 -0
  331. package/dist/sync/local-file-io.d.cts +75 -0
  332. package/dist/sync/local-file-io.d.cts.map +1 -0
  333. package/dist/sync/local-file-io.d.ts +75 -0
  334. package/dist/sync/local-file-io.d.ts.map +1 -0
  335. package/dist/sync/local-file-io.js +360 -0
  336. package/dist/sync/local-file-io.js.map +1 -0
  337. package/dist/sync/local-filesystem-root.cjs +27 -0
  338. package/dist/sync/local-filesystem-root.cjs.map +1 -0
  339. package/dist/sync/local-filesystem-root.d.cts +18 -0
  340. package/dist/sync/local-filesystem-root.d.cts.map +1 -0
  341. package/dist/sync/local-filesystem-root.d.ts +18 -0
  342. package/dist/sync/local-filesystem-root.d.ts.map +1 -0
  343. package/dist/sync/local-filesystem-root.js +26 -0
  344. package/dist/sync/local-filesystem-root.js.map +1 -0
  345. package/dist/sync/local-sha1.cjs +119 -0
  346. package/dist/sync/local-sha1.cjs.map +1 -0
  347. package/dist/sync/local-sha1.d.cts +39 -0
  348. package/dist/sync/local-sha1.d.cts.map +1 -0
  349. package/dist/sync/local-sha1.d.ts +39 -0
  350. package/dist/sync/local-sha1.d.ts.map +1 -0
  351. package/dist/sync/local-sha1.js +117 -0
  352. package/dist/sync/local-sha1.js.map +1 -0
  353. package/dist/sync/pairing.cjs +118 -29
  354. package/dist/sync/pairing.cjs.map +1 -1
  355. package/dist/sync/pairing.d.cts +7 -2
  356. package/dist/sync/pairing.d.cts.map +1 -1
  357. package/dist/sync/pairing.d.ts +7 -2
  358. package/dist/sync/pairing.d.ts.map +1 -1
  359. package/dist/sync/pairing.js +120 -31
  360. package/dist/sync/pairing.js.map +1 -1
  361. package/dist/sync/path-order.cjs +30 -0
  362. package/dist/sync/path-order.cjs.map +1 -0
  363. package/dist/sync/path-order.d.cts +28 -0
  364. package/dist/sync/path-order.d.cts.map +1 -0
  365. package/dist/sync/path-order.d.ts +28 -0
  366. package/dist/sync/path-order.d.ts.map +1 -0
  367. package/dist/sync/path-order.js +29 -0
  368. package/dist/sync/path-order.js.map +1 -0
  369. package/dist/sync/path-safety.cjs +111 -0
  370. package/dist/sync/path-safety.cjs.map +1 -0
  371. package/dist/sync/path-safety.d.cts +78 -0
  372. package/dist/sync/path-safety.d.cts.map +1 -0
  373. package/dist/sync/path-safety.d.ts +78 -0
  374. package/dist/sync/path-safety.d.ts.map +1 -0
  375. package/dist/sync/path-safety.js +105 -0
  376. package/dist/sync/path-safety.js.map +1 -0
  377. package/dist/sync/paths.d.cts +19 -0
  378. package/dist/sync/paths.d.cts.map +1 -0
  379. package/dist/sync/paths.d.ts +19 -0
  380. package/dist/sync/paths.d.ts.map +1 -0
  381. package/dist/sync/policies/compare.cjs +389 -11
  382. package/dist/sync/policies/compare.cjs.map +1 -1
  383. package/dist/sync/policies/compare.d.cts +100 -2
  384. package/dist/sync/policies/compare.d.cts.map +1 -1
  385. package/dist/sync/policies/compare.d.ts +100 -2
  386. package/dist/sync/policies/compare.d.ts.map +1 -1
  387. package/dist/sync/policies/compare.js +387 -13
  388. package/dist/sync/policies/compare.js.map +1 -1
  389. package/dist/sync/policies/index.cjs +76 -65
  390. package/dist/sync/policies/index.cjs.map +1 -1
  391. package/dist/sync/policies/index.d.cts +35 -6
  392. package/dist/sync/policies/index.d.cts.map +1 -1
  393. package/dist/sync/policies/index.d.ts +35 -6
  394. package/dist/sync/policies/index.d.ts.map +1 -1
  395. package/dist/sync/policies/index.js +76 -65
  396. package/dist/sync/policies/index.js.map +1 -1
  397. package/dist/sync/prefix.cjs +96 -0
  398. package/dist/sync/prefix.cjs.map +1 -0
  399. package/dist/sync/prefix.d.cts +55 -0
  400. package/dist/sync/prefix.d.cts.map +1 -0
  401. package/dist/sync/prefix.d.ts +55 -0
  402. package/dist/sync/prefix.d.ts.map +1 -0
  403. package/dist/sync/prefix.js +92 -0
  404. package/dist/sync/prefix.js.map +1 -0
  405. package/dist/sync/regexp-safety.cjs +192 -0
  406. package/dist/sync/regexp-safety.cjs.map +1 -0
  407. package/dist/sync/regexp-safety.d.cts +29 -0
  408. package/dist/sync/regexp-safety.d.cts.map +1 -0
  409. package/dist/sync/regexp-safety.d.ts +29 -0
  410. package/dist/sync/regexp-safety.d.ts.map +1 -0
  411. package/dist/sync/regexp-safety.js +190 -0
  412. package/dist/sync/regexp-safety.js.map +1 -0
  413. package/dist/sync/scan-events.cjs +33 -0
  414. package/dist/sync/scan-events.cjs.map +1 -0
  415. package/dist/sync/scan-events.d.cts +17 -0
  416. package/dist/sync/scan-events.d.cts.map +1 -0
  417. package/dist/sync/scan-events.d.ts +17 -0
  418. package/dist/sync/scan-events.d.ts.map +1 -0
  419. package/dist/sync/scan-events.js +32 -0
  420. package/dist/sync/scan-events.js.map +1 -0
  421. package/dist/sync/scan-limit.cjs +33 -0
  422. package/dist/sync/scan-limit.cjs.map +1 -0
  423. package/dist/sync/scan-limit.d.cts +21 -0
  424. package/dist/sync/scan-limit.d.cts.map +1 -0
  425. package/dist/sync/scan-limit.d.ts +21 -0
  426. package/dist/sync/scan-limit.d.ts.map +1 -0
  427. package/dist/sync/scan-limit.js +31 -0
  428. package/dist/sync/scan-limit.js.map +1 -0
  429. package/dist/sync/scanners/b2.cjs +239 -55
  430. package/dist/sync/scanners/b2.cjs.map +1 -1
  431. package/dist/sync/scanners/b2.d.cts +26 -7
  432. package/dist/sync/scanners/b2.d.cts.map +1 -1
  433. package/dist/sync/scanners/b2.d.ts +26 -7
  434. package/dist/sync/scanners/b2.d.ts.map +1 -1
  435. package/dist/sync/scanners/b2.js +239 -55
  436. package/dist/sync/scanners/b2.js.map +1 -1
  437. package/dist/sync/scanners/local.cjs +215 -56
  438. package/dist/sync/scanners/local.cjs.map +1 -1
  439. package/dist/sync/scanners/local.d.cts +22 -7
  440. package/dist/sync/scanners/local.d.cts.map +1 -1
  441. package/dist/sync/scanners/local.d.ts +22 -7
  442. package/dist/sync/scanners/local.d.ts.map +1 -1
  443. package/dist/sync/scanners/local.js +216 -57
  444. package/dist/sync/scanners/local.js.map +1 -1
  445. package/dist/sync/sha1-metadata.cjs +94 -0
  446. package/dist/sync/sha1-metadata.cjs.map +1 -0
  447. package/dist/sync/sha1-metadata.d.cts +82 -0
  448. package/dist/sync/sha1-metadata.d.cts.map +1 -0
  449. package/dist/sync/sha1-metadata.d.ts +82 -0
  450. package/dist/sync/sha1-metadata.d.ts.map +1 -0
  451. package/dist/sync/sha1-metadata.js +89 -0
  452. package/dist/sync/sha1-metadata.js.map +1 -0
  453. package/dist/sync/sha1-options.cjs +23 -0
  454. package/dist/sync/sha1-options.cjs.map +1 -0
  455. package/dist/sync/sha1-options.d.cts +14 -0
  456. package/dist/sync/sha1-options.d.cts.map +1 -0
  457. package/dist/sync/sha1-options.d.ts +14 -0
  458. package/dist/sync/sha1-options.d.ts.map +1 -0
  459. package/dist/sync/sha1-options.js +21 -0
  460. package/dist/sync/sha1-options.js.map +1 -0
  461. package/dist/sync/synchronizer.cjs +782 -197
  462. package/dist/sync/synchronizer.cjs.map +1 -1
  463. package/dist/sync/synchronizer.d.cts +47 -1
  464. package/dist/sync/synchronizer.d.cts.map +1 -1
  465. package/dist/sync/synchronizer.d.ts +47 -1
  466. package/dist/sync/synchronizer.d.ts.map +1 -1
  467. package/dist/sync/synchronizer.js +779 -173
  468. package/dist/sync/synchronizer.js.map +1 -1
  469. package/dist/sync/types.d.cts +208 -16
  470. package/dist/sync/types.d.cts.map +1 -1
  471. package/dist/sync/types.d.ts +208 -16
  472. package/dist/sync/types.d.ts.map +1 -1
  473. package/dist/types/auth.cjs +76 -56
  474. package/dist/types/auth.cjs.map +1 -1
  475. package/dist/types/auth.d.cts +67 -9
  476. package/dist/types/auth.d.cts.map +1 -1
  477. package/dist/types/auth.d.ts +67 -9
  478. package/dist/types/auth.d.ts.map +1 -1
  479. package/dist/types/auth.js +77 -57
  480. package/dist/types/auth.js.map +1 -1
  481. package/dist/types/bucket.cjs +74 -38
  482. package/dist/types/bucket.cjs.map +1 -1
  483. package/dist/types/bucket.js +75 -41
  484. package/dist/types/bucket.js.map +1 -1
  485. package/dist/types/encryption.cjs +364 -327
  486. package/dist/types/encryption.cjs.map +1 -1
  487. package/dist/types/encryption.d.cts +16 -0
  488. package/dist/types/encryption.d.cts.map +1 -1
  489. package/dist/types/encryption.d.ts +16 -0
  490. package/dist/types/encryption.d.ts.map +1 -1
  491. package/dist/types/encryption.js +364 -310
  492. package/dist/types/encryption.js.map +1 -1
  493. package/dist/types/errors.cjs +47 -0
  494. package/dist/types/errors.cjs.map +1 -0
  495. package/dist/types/errors.d.cts +13 -4
  496. package/dist/types/errors.d.cts.map +1 -1
  497. package/dist/types/errors.d.ts +13 -4
  498. package/dist/types/errors.d.ts.map +1 -1
  499. package/dist/types/errors.js +47 -0
  500. package/dist/types/errors.js.map +1 -0
  501. package/dist/types/file.cjs +36 -19
  502. package/dist/types/file.cjs.map +1 -1
  503. package/dist/types/file.d.cts +2 -2
  504. package/dist/types/file.d.cts.map +1 -1
  505. package/dist/types/file.d.ts +2 -2
  506. package/dist/types/file.d.ts.map +1 -1
  507. package/dist/types/file.js +37 -21
  508. package/dist/types/file.js.map +1 -1
  509. package/dist/types/ids.cjs +53 -9
  510. package/dist/types/ids.cjs.map +1 -1
  511. package/dist/types/ids.js +54 -15
  512. package/dist/types/ids.js.map +1 -1
  513. package/dist/types/index.d.cts +12 -11
  514. package/dist/types/index.d.cts.map +1 -1
  515. package/dist/types/index.d.ts +12 -11
  516. package/dist/types/index.d.ts.map +1 -1
  517. package/dist/types/key.d.cts +44 -8
  518. package/dist/types/key.d.cts.map +1 -1
  519. package/dist/types/key.d.ts +44 -8
  520. package/dist/types/key.d.ts.map +1 -1
  521. package/dist/types/lock.cjs +33 -13
  522. package/dist/types/lock.cjs.map +1 -1
  523. package/dist/types/lock.js +34 -15
  524. package/dist/types/lock.js.map +1 -1
  525. package/dist/types/notifications.cjs +44 -22
  526. package/dist/types/notifications.cjs.map +1 -1
  527. package/dist/types/notifications.js +45 -23
  528. package/dist/types/notifications.js.map +1 -1
  529. package/dist/types/upload.d.cts +39 -5
  530. package/dist/types/upload.d.cts.map +1 -1
  531. package/dist/types/upload.d.ts +39 -5
  532. package/dist/types/upload.d.ts.map +1 -1
  533. package/dist/upload/abort-scope.cjs +91 -0
  534. package/dist/upload/abort-scope.cjs.map +1 -0
  535. package/dist/upload/abort-scope.d.cts +48 -0
  536. package/dist/upload/abort-scope.d.cts.map +1 -0
  537. package/dist/upload/abort-scope.d.ts +48 -0
  538. package/dist/upload/abort-scope.d.ts.map +1 -0
  539. package/dist/upload/abort-scope.js +88 -0
  540. package/dist/upload/abort-scope.js.map +1 -0
  541. package/dist/upload/cancel.cjs +183 -8
  542. package/dist/upload/cancel.cjs.map +1 -1
  543. package/dist/upload/cancel.d.cts +110 -2
  544. package/dist/upload/cancel.d.cts.map +1 -1
  545. package/dist/upload/cancel.d.ts +110 -2
  546. package/dist/upload/cancel.d.ts.map +1 -1
  547. package/dist/upload/cancel.js +178 -9
  548. package/dist/upload/cancel.js.map +1 -1
  549. package/dist/upload/concurrency.cjs +79 -52
  550. package/dist/upload/concurrency.cjs.map +1 -1
  551. package/dist/upload/concurrency.js +79 -53
  552. package/dist/upload/concurrency.js.map +1 -1
  553. package/dist/upload/finish.cjs +59 -0
  554. package/dist/upload/finish.cjs.map +1 -0
  555. package/dist/upload/finish.d.cts +26 -0
  556. package/dist/upload/finish.d.cts.map +1 -0
  557. package/dist/upload/finish.d.ts +26 -0
  558. package/dist/upload/finish.d.ts.map +1 -0
  559. package/dist/upload/finish.js +59 -0
  560. package/dist/upload/finish.js.map +1 -0
  561. package/dist/upload/large.cjs +301 -218
  562. package/dist/upload/large.cjs.map +1 -1
  563. package/dist/upload/large.d.cts +76 -9
  564. package/dist/upload/large.d.cts.map +1 -1
  565. package/dist/upload/large.d.ts +76 -9
  566. package/dist/upload/large.d.ts.map +1 -1
  567. package/dist/upload/large.js +301 -218
  568. package/dist/upload/large.js.map +1 -1
  569. package/dist/upload/options.cjs +28 -0
  570. package/dist/upload/options.cjs.map +1 -0
  571. package/dist/upload/options.d.cts +104 -0
  572. package/dist/upload/options.d.cts.map +1 -0
  573. package/dist/upload/options.d.ts +104 -0
  574. package/dist/upload/options.d.ts.map +1 -0
  575. package/dist/upload/options.js +27 -0
  576. package/dist/upload/options.js.map +1 -0
  577. package/dist/upload/resume.cjs +333 -33
  578. package/dist/upload/resume.cjs.map +1 -1
  579. package/dist/upload/resume.d.cts +82 -12
  580. package/dist/upload/resume.d.cts.map +1 -1
  581. package/dist/upload/resume.d.ts +82 -12
  582. package/dist/upload/resume.d.ts.map +1 -1
  583. package/dist/upload/resume.js +330 -33
  584. package/dist/upload/resume.js.map +1 -1
  585. package/dist/upload/retry.cjs +186 -0
  586. package/dist/upload/retry.cjs.map +1 -0
  587. package/dist/upload/retry.d.cts +127 -0
  588. package/dist/upload/retry.d.cts.map +1 -0
  589. package/dist/upload/retry.d.ts +127 -0
  590. package/dist/upload/retry.d.ts.map +1 -0
  591. package/dist/upload/retry.js +182 -0
  592. package/dist/upload/retry.js.map +1 -0
  593. package/dist/upload/single.cjs +68 -44
  594. package/dist/upload/single.cjs.map +1 -1
  595. package/dist/upload/single.d.cts +2 -1
  596. package/dist/upload/single.d.cts.map +1 -1
  597. package/dist/upload/single.d.ts +2 -1
  598. package/dist/upload/single.d.ts.map +1 -1
  599. package/dist/upload/single.js +68 -44
  600. package/dist/upload/single.js.map +1 -1
  601. package/dist/upload/stream.cjs +317 -193
  602. package/dist/upload/stream.cjs.map +1 -1
  603. package/dist/upload/stream.d.cts +3 -1
  604. package/dist/upload/stream.d.cts.map +1 -1
  605. package/dist/upload/stream.d.ts +3 -1
  606. package/dist/upload/stream.d.ts.map +1 -1
  607. package/dist/upload/stream.js +316 -192
  608. package/dist/upload/stream.js.map +1 -1
  609. package/dist/util/best-effort.cjs +42 -8
  610. package/dist/util/best-effort.cjs.map +1 -1
  611. package/dist/util/best-effort.d.cts +2 -1
  612. package/dist/util/best-effort.d.cts.map +1 -1
  613. package/dist/util/best-effort.d.ts +2 -1
  614. package/dist/util/best-effort.d.ts.map +1 -1
  615. package/dist/util/best-effort.js +43 -9
  616. package/dist/util/best-effort.js.map +1 -1
  617. package/dist/util/bytes.cjs +23 -0
  618. package/dist/util/bytes.cjs.map +1 -0
  619. package/dist/util/bytes.d.cts +15 -0
  620. package/dist/util/bytes.d.cts.map +1 -0
  621. package/dist/util/bytes.d.ts +15 -0
  622. package/dist/util/bytes.d.ts.map +1 -0
  623. package/dist/util/bytes.js +23 -0
  624. package/dist/util/bytes.js.map +1 -0
  625. package/dist/util/crypto.cjs +68 -0
  626. package/dist/util/crypto.cjs.map +1 -0
  627. package/dist/util/crypto.d.cts +26 -0
  628. package/dist/util/crypto.d.cts.map +1 -0
  629. package/dist/util/crypto.d.ts +26 -0
  630. package/dist/util/crypto.d.ts.map +1 -0
  631. package/dist/util/crypto.js +66 -0
  632. package/dist/util/crypto.js.map +1 -0
  633. package/dist/util/defaults.cjs +25 -9
  634. package/dist/util/defaults.cjs.map +1 -1
  635. package/dist/util/defaults.js +26 -11
  636. package/dist/util/defaults.js.map +1 -1
  637. package/dist/util/error-reason.cjs +41 -0
  638. package/dist/util/error-reason.cjs.map +1 -0
  639. package/dist/util/error-reason.d.cts +9 -0
  640. package/dist/util/error-reason.d.cts.map +1 -0
  641. package/dist/util/error-reason.d.ts +9 -0
  642. package/dist/util/error-reason.d.ts.map +1 -0
  643. package/dist/util/error-reason.js +41 -0
  644. package/dist/util/error-reason.js.map +1 -0
  645. package/dist/util/http.cjs +23 -0
  646. package/dist/util/http.cjs.map +1 -0
  647. package/dist/util/http.d.cts +13 -0
  648. package/dist/util/http.d.cts.map +1 -0
  649. package/dist/util/http.d.ts +13 -0
  650. package/dist/util/http.d.ts.map +1 -0
  651. package/dist/util/http.js +23 -0
  652. package/dist/util/http.js.map +1 -0
  653. package/dist/util/normalize.cjs +66 -7
  654. package/dist/util/normalize.cjs.map +1 -1
  655. package/dist/util/normalize.js +67 -10
  656. package/dist/util/normalize.js.map +1 -1
  657. package/dist/util/paginator.cjs +63 -14
  658. package/dist/util/paginator.cjs.map +1 -1
  659. package/dist/util/paginator.js +64 -16
  660. package/dist/util/paginator.js.map +1 -1
  661. package/dist/util/plan-ranges.cjs +47 -22
  662. package/dist/util/plan-ranges.cjs.map +1 -1
  663. package/dist/util/plan-ranges.js +48 -24
  664. package/dist/util/plan-ranges.js.map +1 -1
  665. package/dist/util/sha1.cjs +27 -0
  666. package/dist/util/sha1.cjs.map +1 -0
  667. package/dist/util/sha1.d.cts +17 -0
  668. package/dist/util/sha1.d.cts.map +1 -0
  669. package/dist/util/sha1.d.ts +17 -0
  670. package/dist/util/sha1.d.ts.map +1 -0
  671. package/dist/util/sha1.js +26 -0
  672. package/dist/util/sha1.js.map +1 -0
  673. package/dist/util/text-codec.cjs +29 -5
  674. package/dist/util/text-codec.cjs.map +1 -1
  675. package/dist/util/text-codec.js +30 -7
  676. package/dist/util/text-codec.js.map +1 -1
  677. package/dist/util/to-error.cjs +18 -4
  678. package/dist/util/to-error.cjs.map +1 -1
  679. package/dist/util/to-error.js +19 -5
  680. package/dist/util/to-error.js.map +1 -1
  681. package/dist/version.cjs +17 -5
  682. package/dist/version.cjs.map +1 -1
  683. package/dist/version.d.cts +3 -3
  684. package/dist/version.d.ts +3 -3
  685. package/dist/version.js +19 -6
  686. package/dist/version.js.map +1 -1
  687. package/package.json +19 -16
  688. package/dist/auth/index.cjs.map +0 -1
  689. package/dist/auth/index.js.map +0 -1
  690. package/dist/index.cjs.map +0 -1
  691. package/dist/index.js.map +0 -1
  692. package/dist/notifications/index.cjs.map +0 -1
  693. package/dist/notifications/index.js.map +0 -1
  694. package/dist/package.json.cjs +0 -9
  695. package/dist/package.json.cjs.map +0 -1
  696. package/dist/package.json.js +0 -9
  697. package/dist/package.json.js.map +0 -1
  698. package/dist/streams/index.cjs.map +0 -1
  699. package/dist/streams/index.js.map +0 -1
  700. package/dist/sync/index.cjs.map +0 -1
  701. package/dist/sync/index.js.map +0 -1
@@ -1,1560 +1,2126 @@
1
- import { sha1Hex } from "../streams/hash.js";
2
- import { Capability } from "../types/auth.js";
3
- import { BucketRetentionMode } from "../types/bucket.js";
4
- import { EncryptionMode } from "../types/encryption.js";
5
1
  import { FileAction } from "../types/file.js";
6
2
  import { accountId, bucketId, fileId } from "../types/ids.js";
7
- import { utf8Encoder, utf8Decoder } from "../util/text-codec.js";
3
+ import { utf8Decoder, utf8Encoder } from "../util/text-codec.js";
4
+ import { encodeFileName } from "../raw/encoding.js";
5
+ import { hmacSha256 } from "../util/crypto.js";
6
+ import { sha1Hex } from "../streams/hash.js";
7
+ import { BucketRetentionMode } from "../types/bucket.js";
8
+ import { EncryptionAlgorithm, EncryptionMode } from "../types/encryption.js";
8
9
  import { toError } from "../util/to-error.js";
10
+ import { Capability } from "../types/auth.js";
9
11
  import { missingCapabilitiesFor } from "./capabilities.js";
10
- import { validateFileName, validateFileInfo, validateBucketName, validateBucketInfo, validateMaxCount } from "./validation.js";
11
- import { BUCKET_INFO_MAX_KEYS, BUCKET_INFO_VALUE_MAX, BUCKET_NAME_MAX, BUCKET_NAME_MIN, FILE_INFO_TOTAL_MAX, FILE_INFO_VALUE_MAX, FILE_NAME_MAX_BYTES, LIST_ENDPOINT_CAPS } from "./validation.js";
12
+ import { BUCKET_NAME_MAX, BUCKET_NAME_MIN, FILE_NAME_MAX_BYTES } from "../internal/b2-naming.js";
13
+ import { BUCKET_INFO_MAX_KEYS, BUCKET_INFO_VALUE_MAX, FILE_INFO_TOTAL_MAX, FILE_INFO_VALUE_MAX, LIST_ENDPOINT_CAPS, validateBucketInfo, validateBucketName, validateFileInfo, validateFileName, validateMaxCount } from "./validation.js";
14
+ //#region src/simulator/index.ts
15
+ var UPLOAD_TOKEN_SIGNING_KEY = "b2-sdk-typescript-simulator-upload-token-v1";
16
+ function base64UrlEncode(bytes) {
17
+ let binary = "";
18
+ for (const byte of bytes) binary += String.fromCharCode(byte);
19
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
20
+ }
21
+ function base64UrlDecode(encoded) {
22
+ const base64 = encoded.replaceAll("-", "+").replaceAll("_", "/");
23
+ const padding = (4 - base64.length % 4) % 4;
24
+ try {
25
+ const binary = atob(base64.padEnd(base64.length + padding, "="));
26
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+ function timingSafeStringEqual(left, right) {
32
+ const max = Math.max(left.length, right.length);
33
+ let mismatch = left.length === right.length ? 0 : 1;
34
+ for (let i = 0; i < max; i++) mismatch |= (left.charCodeAt(i) || 0) ^ (right.charCodeAt(i) || 0);
35
+ return mismatch === 0;
36
+ }
37
+ /**
38
+ * Parse an RFC 7233 `Range` header value into inclusive start/end byte
39
+ * offsets clamped to the file size. Supports closed (`bytes=0-999`),
40
+ * open-ended (`bytes=1000-`), and suffix (`bytes=-500`) forms.
41
+ *
42
+ * @param header - The raw header value (e.g. `'bytes=0-999'`).
43
+ * @param totalSize - The full file size in bytes (for clamping + suffix).
44
+ *
45
+ * @returns A {@link RangeParseResult} tagged with how the simulator
46
+ * should respond: serve the range, send 416, or ignore the header.
47
+ *
48
+ * @see https://www.rfc-editor.org/rfc/rfc7233#section-2.1
49
+ */
12
50
  function parseRangeHeader(header, totalSize) {
13
- const m = header.match(/^bytes=(\d*)-(\d*)$/);
14
- if (!m) return { kind: "malformed" };
15
- const [, startStr, endStr] = m;
16
- const hasStart = startStr !== "";
17
- const hasEnd = endStr !== "";
18
- if (!hasStart && !hasEnd) return { kind: "malformed" };
19
- if (totalSize === 0) return { kind: "unsatisfiable" };
20
- let start;
21
- let end;
22
- if (!hasStart) {
23
- const suffixLen = Number.parseInt(endStr ?? "0", 10);
24
- if (!Number.isFinite(suffixLen) || suffixLen <= 0) return { kind: "malformed" };
25
- start = Math.max(0, totalSize - suffixLen);
26
- end = totalSize - 1;
27
- } else if (!hasEnd) {
28
- start = Number.parseInt(startStr ?? "0", 10);
29
- end = totalSize - 1;
30
- } else {
31
- start = Number.parseInt(startStr ?? "0", 10);
32
- end = Number.parseInt(endStr ?? "0", 10);
33
- }
34
- if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || start > end) {
35
- return { kind: "malformed" };
36
- }
37
- if (start >= totalSize) return { kind: "unsatisfiable" };
38
- end = Math.min(end, totalSize - 1);
39
- return { kind: "ok", start, end };
51
+ const m = header.match(/^bytes=(\d*)-(\d*)$/);
52
+ if (!m) return { kind: "malformed" };
53
+ const [, startStr, endStr] = m;
54
+ const hasStart = startStr !== "";
55
+ const hasEnd = endStr !== "";
56
+ if (!hasStart && !hasEnd) return { kind: "malformed" };
57
+ if (totalSize === 0) return { kind: "unsatisfiable" };
58
+ let start;
59
+ let end;
60
+ if (!hasStart) {
61
+ const suffixLen = Number.parseInt(endStr ?? "0", 10);
62
+ if (!Number.isFinite(suffixLen) || suffixLen <= 0) return { kind: "malformed" };
63
+ start = Math.max(0, totalSize - suffixLen);
64
+ end = totalSize - 1;
65
+ } else if (!hasEnd) {
66
+ start = Number.parseInt(startStr ?? "0", 10);
67
+ end = totalSize - 1;
68
+ } else {
69
+ start = Number.parseInt(startStr ?? "0", 10);
70
+ end = Number.parseInt(endStr ?? "0", 10);
71
+ }
72
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || start > end) return { kind: "malformed" };
73
+ if (start >= totalSize) return { kind: "unsatisfiable" };
74
+ end = Math.min(end, totalSize - 1);
75
+ return {
76
+ kind: "ok",
77
+ start,
78
+ end
79
+ };
40
80
  }
81
+ /**
82
+ * Parse `X-Bz-Info-*` headers (lowercased Map keys) into a plain
83
+ * fileInfo record. Mirrors the SDK's `parseFileInfoHeaders` in
84
+ * `raw/encoding.ts` but operates on a `Record<string, string>` rather
85
+ * than a `Headers` object so the simulator can reuse the same
86
+ * extraction logic without converting back to `Headers`.
87
+ *
88
+ * @param headers - Lowercased header map.
89
+ *
90
+ * @returns Plain `Record<string, string>` of `fileInfo` keys/values.
91
+ */
41
92
  function parseFileInfoHeaders(headers) {
42
- const info = {};
43
- const prefix = "x-bz-info-";
44
- for (const [key, value] of Object.entries(headers)) {
45
- if (!key.startsWith(prefix)) continue;
46
- const fileInfoKey = decodeURIComponent(key.slice(prefix.length));
47
- info[fileInfoKey] = decodeURIComponent(value);
48
- }
49
- return info;
93
+ const info = {};
94
+ const prefix = "x-bz-info-";
95
+ for (const [key, value] of Object.entries(headers)) {
96
+ if (!key.startsWith(prefix)) continue;
97
+ const fileInfoKey = decodeURIComponent(key.slice(10));
98
+ info[fileInfoKey] = decodeURIComponent(value);
99
+ }
100
+ return info;
101
+ }
102
+ function decodeHeaderValue(value) {
103
+ try {
104
+ return decodeURIComponent(value);
105
+ } catch {
106
+ return value;
107
+ }
108
+ }
109
+ /**
110
+ * Compares B2 file names with deterministic JS string order, not locale collation.
111
+ *
112
+ * @param a - First file name.
113
+ * @param b - Second file name.
114
+ *
115
+ * @returns `-1` when `a` sorts first, `1` when `b` sorts first, otherwise `0`.
116
+ */
117
+ function compareB2FileNames(a, b) {
118
+ if (a < b) return -1;
119
+ if (a > b) return 1;
120
+ return 0;
121
+ }
122
+ function normalizeKeyBucketIds(req) {
123
+ return req.bucketIds === void 0 || req.bucketIds === null ? null : Object.freeze([...req.bucketIds]);
50
124
  }
51
- class B2Simulator {
52
- buckets = /* @__PURE__ */ new Map();
53
- accountId = "sim_account_0001";
54
- largeFiles = /* @__PURE__ */ new Map();
55
- keys = /* @__PURE__ */ new Map();
56
- notificationRules = /* @__PURE__ */ new Map();
57
- minimumPartSize;
58
- recommendedPartSize;
59
- faults = [];
60
- nextFaultId = 1;
61
- onWebhookDeliver;
62
- onReplicate;
63
- onHookError;
64
- strictAuth;
65
- authTokenTtlMs;
66
- /**
67
- * Issued auth tokens with their associated grant scope + expiry. In
68
- * permissive mode (`strictAuth: false`) this is still populated by
69
- * `authorize` but never consulted on subsequent requests. In strict
70
- * mode each request looks up its `Authorization` header here.
71
- */
72
- issuedTokens = /* @__PURE__ */ new Map();
73
- /**
74
- * Virtual-clock offset applied to `Date.now()` for expiry checks.
75
- * Defaults to 0. Tests advance via {@link advanceTime} to fast-forward
76
- * past auth-token expiry without sleeping.
77
- */
78
- clockOffsetMs = 0;
79
- /**
80
- * Per-instance monotonic counter used to mint realistic-looking
81
- * IDs (`b2_bucket_<24-hex>`, `4_z<24-hex>`, etc.) and auth tokens.
82
- * Module-global previously, which leaked state across `B2Simulator`
83
- * instances in the same Vitest worker — concurrent tests could see
84
- * colliding tokens. Per-instance ensures determinism within a single
85
- * simulator's lifetime.
86
- */
87
- nextId = 1;
88
- /**
89
- * Last-issued upload timestamp. The simulator enforces strict
90
- * monotonicity so version ordering is deterministic for tests; if
91
- * two writes hit the same `Date.now()` millisecond, the second
92
- * receives `lastTimestamp + 1`.
93
- */
94
- lastTimestamp = 0;
95
- /**
96
- * Outstanding fire-and-forget hook invocations. Tracked so tests
97
- * (and future {@link flushHooks} callers) can wait for every
98
- * dispatched `onWebhookDeliver` / `onReplicate` callback to settle
99
- * before asserting against observable side effects. The microtask
100
- * dance in fidelity tests was previously brittle: positive cases
101
- * flushed twice, negative cases flushed once, and any addition to
102
- * the hook dispatch chain quietly broke the negative path.
103
- */
104
- pendingHooks = /* @__PURE__ */ new Set();
105
- /**
106
- * Constructs a new in-memory B2 simulator.
107
- * @param options - Optional simulator overrides. See {@link B2SimulatorOptions}.
108
- */
109
- constructor(options = {}) {
110
- this.minimumPartSize = options.minimumPartSize ?? 5e6;
111
- this.recommendedPartSize = options.recommendedPartSize ?? 1e8;
112
- if (options.onWebhookDeliver !== void 0) this.onWebhookDeliver = options.onWebhookDeliver;
113
- if (options.onReplicate !== void 0) this.onReplicate = options.onReplicate;
114
- if (options.onHookError !== void 0) this.onHookError = options.onHookError;
115
- this.strictAuth = options.strictAuth ?? false;
116
- this.authTokenTtlMs = options.authTokenTtlMs ?? 24 * 60 * 60 * 1e3;
117
- }
118
- /**
119
- * Advance the simulator's virtual clock by `ms` milliseconds. Used in
120
- * conjunction with `strictAuth: true` + a finite `authTokenTtlMs` to
121
- * force token expiry without `setTimeout`-based delays.
122
- *
123
- * @param ms - Milliseconds to advance. Negative values rewind (rarely useful).
124
- */
125
- advanceTime(ms) {
126
- this.clockOffsetMs += ms;
127
- }
128
- /**
129
- * Current simulator time. Equal to `Date.now() + clockOffsetMs`.
130
- *
131
- * @returns Unix milliseconds.
132
- */
133
- now() {
134
- return Date.now() + this.clockOffsetMs;
135
- }
136
- /**
137
- * Generate a deterministic-but-realistic-looking B2 identifier of the
138
- * shape `<prefix>_<24-hex-counter>`, which approximates the visual
139
- * width of real B2 wire IDs. The counter is monotonic per instance
140
- * so test fixtures are deterministic across runs of the same
141
- * simulator.
142
- *
143
- * @param prefix - B2-style prefix (`'b2_bucket'`, `'4_z'`, etc.).
144
- *
145
- * @returns A simulator-issued identifier that looks like a B2 wire ID.
146
- */
147
- genId(prefix) {
148
- const n = this.nextId++;
149
- return `${prefix}_${n.toString(16).padStart(24, "0")}`;
150
- }
151
- /**
152
- * Return a strictly-increasing upload timestamp, even when multiple
153
- * writes land in the same `Date.now()` millisecond. Tests rely on
154
- * `uploadTimestamp` ordering to discriminate file versions; ties from
155
- * coarse system-clock resolution would otherwise make version
156
- * selection nondeterministic.
157
- *
158
- * @returns Unix milliseconds.
159
- */
160
- monotonicTimestamp() {
161
- const now = Date.now();
162
- if (now <= this.lastTimestamp) {
163
- this.lastTimestamp += 1;
164
- } else {
165
- this.lastTimestamp = now;
166
- }
167
- return this.lastTimestamp;
168
- }
169
- /**
170
- * Wait for every fire-and-forget hook (`onWebhookDeliver`,
171
- * `onReplicate`) currently in flight to settle. Use in tests after
172
- * an upload/copy/finish-large-file call to deterministically observe
173
- * hook side effects without microtask-flush guesswork.
174
- *
175
- * @returns A promise that resolves once every pending hook callback
176
- * has either resolved or rejected.
177
- */
178
- async flushHooks() {
179
- while (this.pendingHooks.size > 0) {
180
- const snapshot = [...this.pendingHooks];
181
- await Promise.allSettled(snapshot);
182
- }
183
- }
184
- /**
185
- * Authorize a request against the strict-auth bookkeeping. Returns
186
- * a `SimulatorJsonResponse` error on failure or `null` on success.
187
- * Only consulted when `strictAuth: true`.
188
- *
189
- * @param authToken - The `Authorization` header value from the request.
190
- * @param endpoint - B2 endpoint name being invoked.
191
- * @param bucketId - Optional bucket ID the request operates on, for scope check.
192
- * @param fileName - Optional file name the request operates on, for prefix check.
193
- *
194
- * @returns `null` when the request is authorized, otherwise a 401/403 response.
195
- */
196
- authorizeRequest(authToken, endpoint, bucketId2, fileName) {
197
- const required = missingCapabilitiesFor(endpoint, []);
198
- const noCheckNeeded = required.length === 0 && endpoint === "b2_authorize_account";
199
- if (noCheckNeeded) return null;
200
- if (authToken === void 0 || authToken === "") {
201
- return this.error(401, "bad_auth_token", "missing Authorization header");
202
- }
203
- const token = this.issuedTokens.get(authToken);
204
- if (!token) {
205
- return this.error(401, "bad_auth_token", "unknown auth token");
206
- }
207
- if (this.now() > token.expiresAt) {
208
- return this.error(401, "expired_auth_token", "auth token has expired; reauthorize");
209
- }
210
- const missing = missingCapabilitiesFor(endpoint, token.capabilities);
211
- if (missing.length > 0) {
212
- return this.error(
213
- 403,
214
- "unauthorized",
215
- `application key lacks required capabilities: ${missing.join(", ")}`
216
- );
217
- }
218
- if (token.bucketId !== null && bucketId2 !== void 0 && bucketId2 !== token.bucketId) {
219
- return this.error(
220
- 403,
221
- "unauthorized",
222
- `application key is scoped to bucket ${token.bucketId}; cannot access ${bucketId2}`
223
- );
224
- }
225
- if (token.namePrefix !== null && fileName !== void 0 && !fileName.startsWith(token.namePrefix)) {
226
- return this.error(
227
- 403,
228
- "unauthorized",
229
- `application key is scoped to prefix "${token.namePrefix}"; "${fileName}" is outside scope`
230
- );
231
- }
232
- return null;
233
- }
234
- /**
235
- * Look up the application key matching the `Authorization` header on
236
- * an `authorize_account` request. The header is in the form
237
- * `Basic base64(applicationKeyId:applicationKey)`.
238
- *
239
- * Returns `null` for the implicit master credential (anything that
240
- * does not match a key minted via `b2_create_key`); in that case
241
- * `authorize` grants the full master capability set.
242
- *
243
- * @param authzHeader - Raw HTTP `Authorization` header value.
244
- *
245
- * @returns The matching key's grant scope, or `null` for the master.
246
- */
247
- findKeyForAuthHeader(authzHeader) {
248
- if (!authzHeader || !authzHeader.startsWith("Basic ")) return null;
249
- const decoded = (() => {
250
- try {
251
- return atob(authzHeader.slice(6));
252
- } catch {
253
- return null;
254
- }
255
- })();
256
- if (decoded === null) return null;
257
- const idx = decoded.indexOf(":");
258
- if (idx === -1) return null;
259
- const applicationKeyId = decoded.slice(0, idx);
260
- const applicationKey = decoded.slice(idx + 1);
261
- const stored = this.keys.get(applicationKeyId);
262
- if (!stored || stored.applicationKey !== applicationKey) return null;
263
- return {
264
- capabilities: stored.capabilities,
265
- bucketId: stored.bucketId,
266
- namePrefix: stored.namePrefix,
267
- applicationKeyId
268
- };
269
- }
270
- /**
271
- * Creates an {@link HttpTransport} that routes requests to this simulator.
272
- * @returns A transport instance backed by this in-memory simulator.
273
- */
274
- transport() {
275
- return new SimulatorTransport(this);
276
- }
277
- /**
278
- * Register a synthetic failure to inject on requests whose URL contains
279
- * `spec.on`. Use this to exercise retry / backoff / error-handling
280
- * paths in tests without hand-rolling a wrapping `HttpTransport`. The
281
- * fault is consumed in registration order on each matched request;
282
- * once its `count` budget is exhausted it auto-retires.
283
- *
284
- * Faults are checked BEFORE the simulator's real handlers run, so a
285
- * matched request never touches in-memory state — failed uploads
286
- * don't create partial parts, failed deletes don't remove anything.
287
- *
288
- * @param spec - The failure to inject. See {@link FaultSpec}.
289
- *
290
- * @returns A handle whose `clear()` method removes this specific
291
- * fault registration (other faults remain in effect).
292
- *
293
- * @example
294
- * ```ts
295
- * // Fail the next 2 b2_upload_part calls with 503, then succeed.
296
- * sim.injectFailure({ on: 'b2_upload_part', status: 503, count: 2 })
297
- *
298
- * // Fail every b2_authorize_account with 401 + Retry-After: 5.
299
- * const handle = sim.injectFailure({
300
- * on: 'b2_authorize_account',
301
- * status: 401,
302
- * code: 'expired_auth_token',
303
- * retryAfter: 5,
304
- * })
305
- * // ... later
306
- * handle.clear()
307
- * ```
308
- */
309
- injectFailure(spec) {
310
- const id = this.nextFaultId++;
311
- const fault = {
312
- id,
313
- spec,
314
- remainingSkip: spec.skip ?? 0,
315
- remainingCount: spec.count ?? Number.POSITIVE_INFINITY
316
- };
317
- this.faults.push(fault);
318
- return {
319
- clear: () => {
320
- const idx = this.faults.findIndex((f) => f.id === id);
321
- if (idx !== -1) this.faults.splice(idx, 1);
322
- }
323
- };
324
- }
325
- /**
326
- * Remove every registered fault. Equivalent to calling `.clear()` on
327
- * every handle returned by {@link injectFailure}, plus a defensive
328
- * reset for tests that re-use a simulator across cases.
329
- */
330
- clearFaults() {
331
- this.faults.length = 0;
332
- }
333
- /**
334
- * Internal: checks the registered faults for a match on the given URL
335
- * and consumes one if it should fire. Called from
336
- * {@link SimulatorTransport.send} before any real handler runs.
337
- *
338
- * @param url - The request URL to match against each fault's `on`
339
- * substring.
340
- *
341
- * @returns The fault to apply, or `null` if no fault should fire.
342
- *
343
- * @internal
344
- */
345
- consumeMatchingFault(url) {
346
- for (let i = 0; i < this.faults.length; i++) {
347
- const fault = this.faults[i];
348
- if (!url.includes(fault.spec.on)) continue;
349
- if (fault.remainingSkip > 0) {
350
- fault.remainingSkip -= 1;
351
- continue;
352
- }
353
- if (fault.remainingCount <= 0) continue;
354
- fault.remainingCount -= 1;
355
- if (fault.remainingCount <= 0) {
356
- this.faults.splice(i, 1);
357
- }
358
- return fault.spec;
359
- }
360
- return null;
361
- }
362
- /**
363
- * Dispatches a JSON API request to the appropriate handler.
364
- * @param _method - The HTTP method (unused).
365
- * @param path - The request URL path containing the B2 endpoint name.
366
- * @param headers - The HTTP request headers; consulted by the
367
- * strict-auth gate to look up the issued auth token.
368
- * @param body - The parsed JSON request body.
369
- *
370
- * @returns An object with HTTP status and JSON response body.
371
- */
372
- async handleRequest(_method, path, headers, body) {
373
- const endpoint = path.split("/").pop() ?? "";
374
- if (this.strictAuth) {
375
- const authError = this.authorizeRequest(headers["authorization"], endpoint);
376
- if (authError !== null) return authError;
377
- }
378
- switch (endpoint) {
379
- case "b2_authorize_account":
380
- return this.authorize(headers["authorization"]);
381
- case "b2_create_bucket":
382
- return this.createBucket(
383
- body
384
- );
385
- case "b2_list_buckets":
386
- return this.listBuckets();
387
- case "b2_delete_bucket":
388
- return this.deleteBucket(body);
389
- case "b2_update_bucket":
390
- return this.updateBucket(body);
391
- case "b2_get_upload_url":
392
- return this.getUploadUrl(body);
393
- case "b2_list_file_names":
394
- return this.listFileNames(
395
- body
396
- );
397
- case "b2_list_file_versions":
398
- return this.listFileVersions(
399
- body
400
- );
401
- case "b2_get_file_info":
402
- return this.getFileInfo(body);
403
- case "b2_hide_file":
404
- return this.hideFile(body);
405
- case "b2_delete_file_version":
406
- return this.deleteFileVersion(
407
- body
408
- );
409
- case "b2_copy_file":
410
- return this.copyFile(
411
- body
412
- );
413
- case "b2_start_large_file":
414
- return this.startLargeFile(
415
- body
416
- );
417
- case "b2_get_upload_part_url":
418
- return this.getUploadPartUrl(body);
419
- case "b2_finish_large_file":
420
- return this.finishLargeFile(body);
421
- case "b2_cancel_large_file":
422
- return this.cancelLargeFile(body);
423
- case "b2_list_unfinished_large_files":
424
- return this.listUnfinishedLargeFiles(
425
- body
426
- );
427
- case "b2_list_parts":
428
- return this.listParts(
429
- body
430
- );
431
- case "b2_copy_part":
432
- return await this.copyPart(
433
- body
434
- );
435
- case "b2_get_download_authorization":
436
- return this.getDownloadAuthorization(
437
- body
438
- );
439
- case "b2_create_key":
440
- return this.createKey(
441
- body
442
- );
443
- case "b2_list_keys":
444
- return this.listKeys(
445
- body
446
- );
447
- case "b2_delete_key":
448
- return this.deleteKey(body);
449
- case "b2_update_file_retention":
450
- return this.updateFileRetention(
451
- body
452
- );
453
- case "b2_update_file_legal_hold":
454
- return this.updateFileLegalHold(
455
- body
456
- );
457
- case "b2_get_bucket_notification_rules":
458
- return this.getBucketNotificationRules(body);
459
- case "b2_set_bucket_notification_rules":
460
- return this.setBucketNotificationRules(
461
- body
462
- );
463
- default:
464
- return {
465
- status: 400,
466
- body: { status: 400, code: "bad_request", message: `Unknown endpoint: ${endpoint}` }
467
- };
468
- }
469
- }
470
- /**
471
- * Handles file and part upload requests (`b2_upload_file`, `b2_upload_part`).
472
- * Dispatches to the appropriate internal handler based on the URL.
473
- * @param url - The upload endpoint URL used to determine the upload type.
474
- * @param headers - The HTTP headers containing file metadata and authorization.
475
- * @param data - The raw file or part content as bytes.
476
- *
477
- * @returns An object with HTTP status and JSON response body.
478
- */
479
- handleUpload(url, headers, data) {
480
- const isPart = url.includes("b2_upload_part");
481
- if (this.strictAuth) {
482
- const endpoint = isPart ? "b2_upload_part" : "b2_upload_file";
483
- const authError = this.authorizeRequest(headers["authorization"], endpoint);
484
- if (authError !== null) return authError;
485
- }
486
- if (isPart) {
487
- return this.handleUploadPart(url, headers, data);
488
- }
489
- return this.handleUploadFile(url, headers, data);
490
- }
491
- /**
492
- * Handles file download requests (`b2_download_file_by_id`, `/file/` by name).
493
- * Returns the file data along with B2 response headers.
494
- * @param path - The request URL path identifying the file to download.
495
- * @param headers - The HTTP request headers for range or authorization.
496
- * @param method - The HTTP method; `'HEAD'` suppresses the response body.
497
- *
498
- * @returns The download response containing file data and B2 headers.
499
- */
500
- handleDownload(path, headers, method = "GET") {
501
- if (path.includes("b2_download_file_by_id")) {
502
- if (this.strictAuth) {
503
- const authError = this.authorizeRequest(headers["authorization"], "b2_download_file_by_id");
504
- if (authError !== null) return this.errorAsDownload(authError);
505
- }
506
- const url = new URL(`http://localhost${path}`);
507
- const fileId2 = url.searchParams.get("fileId") ?? "";
508
- return this.finalizeDownload(this.downloadById(fileId2, headers["range"]), url, method);
509
- }
510
- const fileMatch = path.match(/^([^?]+)/)?.[1]?.match(/\/file\/([^/]+)\/(.+)/);
511
- if (fileMatch) {
512
- const bucketName = decodeURIComponent(fileMatch[1] ?? "");
513
- const fileName = decodeURIComponent(fileMatch[2] ?? "");
514
- if (this.strictAuth) {
515
- const authError = this.authorizeRequest(
516
- headers["authorization"],
517
- "b2_download_file_by_name",
518
- void 0,
519
- fileName
520
- );
521
- if (authError !== null) return this.errorAsDownload(authError);
522
- }
523
- const url = new URL(`http://localhost${path}`);
524
- return this.finalizeDownload(
525
- this.downloadByName(bucketName, fileName, headers["range"]),
526
- url,
527
- method
528
- );
529
- }
530
- return { status: 404, headers: {}, data: null };
531
- }
532
- /**
533
- * Convert a synthetic JSON error body into a `SimulatorDownloadResponse`
534
- * shape so the strict-auth gate on download paths can surface 401/403s
535
- * through the same transport plumbing as a regular failed download.
536
- *
537
- * @param json - The JSON error from {@link authorizeRequest}.
538
- *
539
- * @returns A download-shaped response with the error body bytes inline.
540
- */
541
- errorAsDownload(json) {
542
- return {
543
- status: json.status,
544
- headers: { "Content-Type": "application/json" },
545
- data: utf8Encoder.encode(JSON.stringify(json.body))
546
- };
547
- }
548
- /**
549
- * Applies HEAD-method body suppression and `b2Content*` response-header
550
- * overrides parsed from the download URL's query string. Mirrors what the
551
- * real B2 service does: any `b2Content*` query parameter is echoed back as
552
- * the corresponding response header.
553
- *
554
- * @param response - The download response produced by {@link downloadById} or {@link downloadByName}.
555
- * @param url - The parsed download URL (used to read `b2Content*` query params).
556
- * @param method - The HTTP method of the originating request.
557
- *
558
- * @returns The response with overrides applied.
559
- */
560
- finalizeDownload(response, url, method) {
561
- const overrideMap = {
562
- b2ContentDisposition: "Content-Disposition",
563
- b2ContentLanguage: "Content-Language",
564
- b2ContentEncoding: "Content-Encoding",
565
- b2ContentType: "Content-Type",
566
- b2CacheControl: "Cache-Control",
567
- b2Expires: "Expires"
568
- };
569
- const newHeaders = { ...response.headers };
570
- for (const [param, header] of Object.entries(overrideMap)) {
571
- const value = url.searchParams.get(param);
572
- if (value !== null) newHeaders[header] = value;
573
- }
574
- const data = method === "HEAD" ? null : response.data;
575
- return { status: response.status, headers: newHeaders, data };
576
- }
577
- handleUploadFile(url, headers, data) {
578
- const bucketId2 = new URL(url).searchParams.get("bucketId");
579
- if (!bucketId2) return this.error(400, "bad_request", "Missing bucketId");
580
- const bucket = this.buckets.get(bucketId2);
581
- if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
582
- const fileName = decodeURIComponent(headers["x-bz-file-name"] ?? "");
583
- const contentType = headers["content-type"] ?? "application/octet-stream";
584
- const sha1 = headers["x-bz-content-sha1"] ?? "none";
585
- const fileNameError = validateFileName(fileName);
586
- if (fileNameError) return this.error(400, fileNameError.code, fileNameError.message);
587
- const fileInfo = parseFileInfoHeaders(headers);
588
- const fileInfoError = validateFileInfo(fileInfo);
589
- if (fileInfoError) return this.error(400, fileInfoError.code, fileInfoError.message);
590
- const fileVersion = this.makeFileVersion({
591
- bucketId: bucketId2,
592
- fileName,
593
- contentType,
594
- contentLength: data.byteLength,
595
- contentSha1: sha1,
596
- action: FileAction.Upload
597
- });
598
- const stored = { fileVersion, data };
599
- const existing = bucket.files.get(fileName);
600
- if (existing) {
601
- existing.push(stored);
602
- } else {
603
- bucket.files.set(fileName, [stored]);
604
- }
605
- this.firePostUploadHooks(fileVersion, bucketId2, "b2:ObjectCreated:Upload");
606
- return { status: 200, body: fileVersion };
607
- }
608
- handleUploadPart(url, headers, data) {
609
- const fileId2 = new URL(url).searchParams.get("fileId");
610
- if (!fileId2) return this.error(400, "bad_request", "Missing fileId");
611
- const large = this.largeFiles.get(fileId2);
612
- if (!large) return this.error(400, "bad_request", "Large file not found");
613
- const partNumber = Number.parseInt(headers["x-bz-part-number"] ?? "0", 10);
614
- const sha1 = headers["x-bz-content-sha1"] ?? "none";
615
- large.parts.set(partNumber, { data, sha1 });
616
- return {
617
- status: 200,
618
- body: {
619
- fileId: large.fileId,
620
- partNumber,
621
- contentLength: data.byteLength,
622
- contentSha1: sha1,
623
- serverSideEncryption: { mode: EncryptionMode.None },
624
- uploadTimestamp: Date.now()
625
- }
626
- };
627
- }
628
- downloadById(fileId2, range) {
629
- const found = this.findFile(fileId2);
630
- if (found === null) return { status: 404, headers: {}, data: null };
631
- return this.serveFile(found.stored, range);
632
- }
633
- downloadByName(bucketName, fileName, range) {
634
- for (const bucket of this.buckets.values()) {
635
- if (bucket.info.bucketName !== bucketName) continue;
636
- const versions = bucket.files.get(fileName);
637
- if (!versions || versions.length === 0) break;
638
- const latest = versions[versions.length - 1];
639
- if (!latest || latest.fileVersion.action === FileAction.Hide) {
640
- return { status: 404, headers: {}, data: null };
641
- }
642
- return this.serveFile(latest, range);
643
- }
644
- return { status: 404, headers: {}, data: null };
645
- }
646
- serveFile(stored, range) {
647
- const fullData = stored.data;
648
- let data = fullData;
649
- let status = 200;
650
- let contentRange = null;
651
- if (range) {
652
- const parsed = parseRangeHeader(range, fullData.byteLength);
653
- if (parsed.kind === "ok") {
654
- data = fullData.subarray(parsed.start, parsed.end + 1);
655
- status = 206;
656
- contentRange = `bytes ${parsed.start}-${parsed.end}/${fullData.byteLength}`;
657
- } else if (parsed.kind === "unsatisfiable") {
658
- return {
659
- status: 416,
660
- headers: {
661
- "Content-Type": stored.fileVersion.contentType,
662
- "Content-Range": `bytes */${fullData.byteLength}`
663
- },
664
- data: new Uint8Array(0)
665
- };
666
- }
667
- }
668
- const fv = stored.fileVersion;
669
- const headers = {
670
- "Content-Type": fv.contentType,
671
- "Content-Length": String(data.byteLength),
672
- "X-Bz-File-Id": fv.fileId,
673
- "X-Bz-File-Name": encodeURIComponent(fv.fileName),
674
- "X-Bz-Content-Sha1": fv.contentSha1 ?? "none",
675
- "X-Bz-Upload-Timestamp": String(fv.uploadTimestamp),
676
- "X-Bz-Info-src_last_modified_millis": String(fv.uploadTimestamp)
677
- };
678
- if (contentRange !== null) {
679
- headers["Content-Range"] = contentRange;
680
- }
681
- return { status, headers, data };
682
- }
683
- // --- API handlers ---
684
- authorize(authzHeader) {
685
- const capabilities = [
686
- Capability.ListBuckets,
687
- Capability.ReadBuckets,
688
- Capability.WriteBuckets,
689
- Capability.DeleteBuckets,
690
- Capability.ListFiles,
691
- Capability.ReadFiles,
692
- Capability.WriteFiles,
693
- Capability.DeleteFiles,
694
- Capability.ListKeys,
695
- Capability.WriteKeys,
696
- Capability.DeleteKeys,
697
- Capability.ShareFiles,
698
- Capability.ReadBucketNotifications,
699
- Capability.WriteBucketNotifications
700
- ];
701
- const keyForAuth = this.findKeyForAuthHeader(authzHeader);
702
- const tokenStr = `sim_auth_token_${this.nextId++}`;
703
- this.issuedTokens.set(tokenStr, {
704
- capabilities: keyForAuth?.capabilities ?? capabilities,
705
- bucketId: keyForAuth?.bucketId ?? null,
706
- namePrefix: keyForAuth?.namePrefix ?? null,
707
- expiresAt: this.now() + this.authTokenTtlMs,
708
- applicationKeyId: keyForAuth?.applicationKeyId ?? null
709
- });
710
- return {
711
- status: 200,
712
- body: {
713
- accountId: accountId(this.accountId),
714
- // `AuthToken` has no public factory by design — auth tokens are
715
- // minted by B2, not constructed by user code. The simulator is
716
- // the only legitimate place that needs to forge one.
717
- authorizationToken: tokenStr,
718
- apiInfo: {
719
- storageApi: {
720
- absoluteMinimumPartSize: this.minimumPartSize,
721
- apiUrl: "http://localhost:0",
722
- bucketId: keyForAuth?.bucketId ?? null,
723
- bucketName: null,
724
- downloadUrl: "http://localhost:0",
725
- infoType: "storageApi",
726
- namePrefix: keyForAuth?.namePrefix ?? null,
727
- recommendedPartSize: this.recommendedPartSize,
728
- s3ApiUrl: "http://localhost:0",
729
- allowed: {
730
- capabilities: keyForAuth?.capabilities ?? capabilities,
731
- bucketId: keyForAuth?.bucketId ?? null,
732
- bucketName: null,
733
- namePrefix: keyForAuth?.namePrefix ?? null
734
- }
735
- }
736
- },
737
- applicationKeyExpirationTimestamp: null
738
- }
739
- };
740
- }
741
- createBucket(req) {
742
- const nameError = validateBucketName(req.bucketName);
743
- if (nameError) return this.error(400, nameError.code, nameError.message);
744
- if (req.bucketInfo !== void 0) {
745
- const infoError = validateBucketInfo(req.bucketInfo);
746
- if (infoError) return this.error(400, infoError.code, infoError.message);
747
- }
748
- for (const b of this.buckets.values()) {
749
- if (b.info.bucketName === req.bucketName) {
750
- return this.error(400, "duplicate_bucket_name", "Bucket name already in use");
751
- }
752
- }
753
- const bid = bucketId(this.genId("b2_bucket"));
754
- const defaultRetention = req.defaultRetention ?? {
755
- mode: BucketRetentionMode.None,
756
- period: null
757
- };
758
- const info = {
759
- accountId: accountId(req.accountId),
760
- bucketId: bid,
761
- bucketName: req.bucketName,
762
- bucketType: req.bucketType,
763
- bucketInfo: req.bucketInfo ?? {},
764
- corsRules: req.corsRules ?? [],
765
- defaultServerSideEncryption: req.defaultServerSideEncryption ?? { mode: EncryptionMode.None },
766
- fileLockConfiguration: {
767
- isClientAuthorizedToRead: true,
768
- value: {
769
- isFileLockEnabled: req.fileLockEnabled ?? false,
770
- defaultRetention
771
- }
772
- },
773
- lifecycleRules: req.lifecycleRules ?? [],
774
- options: [],
775
- revision: 1,
776
- defaultRetention,
777
- replicationConfiguration: req.replicationConfiguration ?? {
778
- asReplicationSource: null,
779
- asReplicationDestination: null
780
- }
781
- };
782
- this.buckets.set(bid, { info, files: /* @__PURE__ */ new Map() });
783
- return { status: 200, body: info };
784
- }
785
- listBuckets() {
786
- const buckets = [...this.buckets.values()].map((b) => b.info);
787
- return { status: 200, body: { buckets } };
788
- }
789
- deleteBucket(req) {
790
- const bucket = this.buckets.get(req.bucketId);
791
- if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
792
- this.buckets.delete(req.bucketId);
793
- return { status: 200, body: bucket.info };
794
- }
795
- updateBucket(req) {
796
- const bucket = this.buckets.get(req["bucketId"]);
797
- if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
798
- if (req["bucketInfo"] !== void 0) {
799
- const infoError = validateBucketInfo(req["bucketInfo"]);
800
- if (infoError) return this.error(400, infoError.code, infoError.message);
801
- }
802
- const updated = {
803
- ...bucket.info,
804
- ...req["bucketType"] !== void 0 ? { bucketType: req["bucketType"] } : {},
805
- ...req["bucketInfo"] !== void 0 ? { bucketInfo: req["bucketInfo"] } : {},
806
- ...req["lifecycleRules"] !== void 0 ? { lifecycleRules: req["lifecycleRules"] } : {},
807
- ...req["corsRules"] !== void 0 ? { corsRules: req["corsRules"] } : {},
808
- ...req["replicationConfiguration"] !== void 0 ? {
809
- replicationConfiguration: req["replicationConfiguration"]
810
- } : {},
811
- ...req["defaultRetention"] !== void 0 ? {
812
- defaultRetention: req["defaultRetention"],
813
- fileLockConfiguration: {
814
- isClientAuthorizedToRead: true,
815
- value: {
816
- isFileLockEnabled: bucket.info.fileLockConfiguration.value?.isFileLockEnabled ?? false,
817
- defaultRetention: req["defaultRetention"]
818
- }
819
- }
820
- } : {},
821
- ...req["defaultServerSideEncryption"] !== void 0 ? {
822
- defaultServerSideEncryption: req["defaultServerSideEncryption"]
823
- } : {},
824
- revision: bucket.info.revision + 1
825
- };
826
- this.buckets.set(req["bucketId"], { info: updated, files: bucket.files });
827
- return { status: 200, body: updated };
828
- }
829
- getUploadUrl(req) {
830
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
831
- return {
832
- status: 200,
833
- body: {
834
- bucketId: req.bucketId,
835
- uploadUrl: `http://localhost:0/b2api/v3/b2_upload_file?bucketId=${req.bucketId}`,
836
- authorizationToken: "sim_upload_token"
837
- }
838
- };
839
- }
840
- listFileNames(req) {
841
- const bucket = this.buckets.get(req.bucketId);
842
- if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
843
- const countError = validateMaxCount(req.maxFileCount, "b2_list_file_names");
844
- if (countError) return this.error(400, countError.code, countError.message);
845
- const max = req.maxFileCount ?? 1e3;
846
- const prefix = req.prefix ?? "";
847
- let allFiles = [...bucket.files.entries()].filter(([name]) => name.startsWith(prefix)).map(([_, versions]) => versions[versions.length - 1]).filter((v) => v !== void 0).map((v) => v.fileVersion).sort((a, b) => a.fileName.localeCompare(b.fileName));
848
- if (req.startFileName) {
849
- const start = req.startFileName;
850
- allFiles = allFiles.filter((f) => f.fileName >= start);
851
- }
852
- const files = allFiles.slice(0, max);
853
- const nextFileName = allFiles.length > max ? allFiles[max]?.fileName ?? null : null;
854
- return { status: 200, body: { files, nextFileName } };
855
- }
856
- listFileVersions(req) {
857
- const bucket = this.buckets.get(req.bucketId);
858
- if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
859
- const countError = validateMaxCount(req.maxFileCount, "b2_list_file_versions");
860
- if (countError) return this.error(400, countError.code, countError.message);
861
- const max = req.maxFileCount ?? 1e3;
862
- const prefix = req.prefix ?? "";
863
- const allVersions = [...bucket.files.entries()].filter(([name]) => name.startsWith(prefix)).flatMap(([_, versions]) => versions.map((v) => v.fileVersion)).sort((a, b) => {
864
- const nameCmp = a.fileName.localeCompare(b.fileName);
865
- if (nameCmp !== 0) return nameCmp;
866
- return b.uploadTimestamp - a.uploadTimestamp;
867
- });
868
- let startIdx = 0;
869
- if (req.startFileName !== void 0) {
870
- const startName = req.startFileName;
871
- const startId = req.startFileId;
872
- const nameIdx = allVersions.findIndex((f) => f.fileName >= startName);
873
- if (nameIdx === -1) {
874
- startIdx = allVersions.length;
875
- } else if (startId !== void 0) {
876
- const exactIdx = allVersions.findIndex((f, i) => i >= nameIdx && f.fileId === startId);
877
- startIdx = exactIdx !== -1 ? exactIdx : nameIdx;
878
- } else {
879
- startIdx = nameIdx;
880
- }
881
- }
882
- const sliced = allVersions.slice(startIdx, startIdx + max);
883
- const hasMore = startIdx + max < allVersions.length;
884
- const nextFileName = hasMore ? allVersions[startIdx + max]?.fileName ?? null : null;
885
- const nextFileId = hasMore ? allVersions[startIdx + max]?.fileId ?? null : null;
886
- return { status: 200, body: { files: sliced, nextFileName, nextFileId } };
887
- }
888
- getFileInfo(req) {
889
- const found = this.findFile(req.fileId);
890
- if (found === null) return this.error(404, "file_not_present", "File not found");
891
- return { status: 200, body: found.stored.fileVersion };
892
- }
893
- hideFile(req) {
894
- const bucket = this.buckets.get(req.bucketId);
895
- if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
896
- const nameError = validateFileName(req.fileName);
897
- if (nameError) return this.error(400, nameError.code, nameError.message);
898
- const fileVersion = this.makeFileVersion({
899
- bucketId: req.bucketId,
900
- fileName: req.fileName,
901
- contentType: "application/octet-stream",
902
- contentLength: 0,
903
- contentSha1: "none",
904
- action: FileAction.Hide
905
- });
906
- const existing = bucket.files.get(req.fileName);
907
- const stored = { fileVersion, data: new Uint8Array(0) };
908
- if (existing) {
909
- existing.push(stored);
910
- } else {
911
- bucket.files.set(req.fileName, [stored]);
912
- }
913
- return { status: 200, body: fileVersion };
914
- }
915
- deleteFileVersion(req) {
916
- const found = this.findFile(req.fileId);
917
- if (found === null || found.stored.fileVersion.fileName !== req.fileName) {
918
- return this.error(400, "file_not_present", "File version not found");
919
- }
920
- const fv = found.stored.fileVersion;
921
- const retention = fv.fileRetention?.value;
922
- const legalHold = fv.legalHold?.value;
923
- const now = Date.now();
924
- if (legalHold === "on") {
925
- return this.error(
926
- 400,
927
- "file_lock_legal_hold_protected",
928
- "File is on legal hold and cannot be deleted"
929
- );
930
- }
931
- if (retention?.mode === "compliance" && retention.retainUntilTimestamp !== null && retention.retainUntilTimestamp > now) {
932
- return this.error(
933
- 400,
934
- "file_lock_compliance_protected",
935
- `File is under compliance-mode retention and cannot be deleted until ${new Date(retention.retainUntilTimestamp).toISOString()}`
936
- );
937
- }
938
- if (retention?.mode === "governance" && retention.retainUntilTimestamp !== null && retention.retainUntilTimestamp > now && req.bypassGovernance !== true) {
939
- return this.error(
940
- 400,
941
- "file_lock_governance_protected",
942
- "File is under governance-mode retention; pass bypassGovernance: true to delete"
943
- );
944
- }
945
- found.versions.splice(found.index, 1);
946
- if (found.versions.length === 0) found.bucket.files.delete(req.fileName);
947
- return { status: 200, body: { fileId: req.fileId, fileName: req.fileName } };
948
- }
949
- copyFile(req) {
950
- const nameError = validateFileName(req.fileName);
951
- if (nameError) return this.error(400, nameError.code, nameError.message);
952
- const found = this.findFile(req.sourceFileId);
953
- if (found === null) return this.error(404, "file_not_present", "Source file not found");
954
- const sourceStored = found.stored;
955
- const destBucketId = req.destinationBucketId ?? found.bucketId;
956
- const destBucket = this.buckets.get(destBucketId);
957
- if (!destBucket) return this.error(400, "bad_bucket_id", "Destination bucket not found");
958
- const fileVersion = this.makeFileVersion({
959
- bucketId: destBucketId,
960
- fileName: req.fileName,
961
- contentType: sourceStored.fileVersion.contentType,
962
- contentLength: sourceStored.data.byteLength,
963
- contentSha1: sourceStored.fileVersion.contentSha1 ?? "none",
964
- action: FileAction.Copy
965
- });
966
- const copied = { fileVersion, data: new Uint8Array(sourceStored.data) };
967
- const existing = destBucket.files.get(req.fileName);
968
- if (existing) {
969
- existing.push(copied);
970
- } else {
971
- destBucket.files.set(req.fileName, [copied]);
972
- }
973
- this.firePostUploadHooks(fileVersion, destBucketId, "b2:ObjectCreated:Copy");
974
- return { status: 200, body: fileVersion };
975
- }
976
- startLargeFile(req) {
977
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
978
- const nameError = validateFileName(req.fileName);
979
- if (nameError) return this.error(400, nameError.code, nameError.message);
980
- if (req.fileInfo !== void 0) {
981
- const infoError = validateFileInfo(req.fileInfo);
982
- if (infoError) return this.error(400, infoError.code, infoError.message);
983
- }
984
- const fid = this.genId("4_z");
985
- const large = {
986
- fileId: fid,
987
- bucketId: req.bucketId,
988
- fileName: req.fileName,
989
- contentType: req.contentType,
990
- fileInfo: req.fileInfo ?? {},
991
- parts: /* @__PURE__ */ new Map()
992
- };
993
- this.largeFiles.set(fid, large);
994
- return {
995
- status: 200,
996
- body: {
997
- fileId: fid,
998
- fileName: req.fileName,
999
- accountId: this.accountId,
1000
- bucketId: req.bucketId,
1001
- contentType: req.contentType,
1002
- fileInfo: large.fileInfo
1003
- }
1004
- };
1005
- }
1006
- getUploadPartUrl(req) {
1007
- if (!this.largeFiles.has(req.fileId))
1008
- return this.error(400, "bad_request", "Large file not found");
1009
- return {
1010
- status: 200,
1011
- body: {
1012
- fileId: req.fileId,
1013
- uploadUrl: `http://localhost:0/b2api/v3/b2_upload_part?fileId=${req.fileId}`,
1014
- authorizationToken: "sim_part_token"
1015
- }
1016
- };
1017
- }
1018
- finishLargeFile(req) {
1019
- const large = this.largeFiles.get(req.fileId);
1020
- if (!large) return this.error(400, "bad_request", "Large file not found");
1021
- const bucket = this.buckets.get(large.bucketId);
1022
- if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
1023
- const sortedParts = [...large.parts.entries()].sort((a, b) => a[0] - b[0]);
1024
- if (sortedParts.length > 1e4) {
1025
- return this.error(
1026
- 400,
1027
- "bad_request",
1028
- `multipart upload has ${sortedParts.length} parts; B2 caps at 10000`
1029
- );
1030
- }
1031
- for (const [partNumber] of sortedParts) {
1032
- if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > 1e4) {
1033
- return this.error(
1034
- 400,
1035
- "bad_request",
1036
- `partNumber ${partNumber} is outside the [1, 10000] range B2 accepts`
1037
- );
1038
- }
1039
- }
1040
- if (req.partSha1Array.length !== sortedParts.length) {
1041
- return this.error(
1042
- 400,
1043
- "bad_request",
1044
- `partSha1Array has ${req.partSha1Array.length} entries but ${sortedParts.length} parts were uploaded`
1045
- );
1046
- }
1047
- for (let i = 0; i < sortedParts.length - 1; i++) {
1048
- const [partNumber, part] = sortedParts[i];
1049
- if (part.data.byteLength < this.minimumPartSize) {
1050
- return this.error(
1051
- 400,
1052
- "bad_request",
1053
- `part ${partNumber} (${part.data.byteLength} bytes) is smaller than the minimum part size of ${this.minimumPartSize}`
1054
- );
1055
- }
1056
- }
1057
- let totalSize = 0;
1058
- for (const [_, part] of sortedParts) totalSize += part.data.byteLength;
1059
- const combined = new Uint8Array(totalSize);
1060
- let offset = 0;
1061
- for (const [_, part] of sortedParts) {
1062
- combined.set(part.data, offset);
1063
- offset += part.data.byteLength;
1064
- }
1065
- const fileVersion = this.makeFileVersion({
1066
- bucketId: large.bucketId,
1067
- fileName: large.fileName,
1068
- contentType: large.contentType,
1069
- contentLength: totalSize,
1070
- contentSha1: "none",
1071
- action: FileAction.Upload
1072
- });
1073
- const stored = { fileVersion, data: combined };
1074
- const existing = bucket.files.get(large.fileName);
1075
- if (existing) {
1076
- existing.push(stored);
1077
- } else {
1078
- bucket.files.set(large.fileName, [stored]);
1079
- }
1080
- this.largeFiles.delete(req.fileId);
1081
- this.firePostUploadHooks(fileVersion, large.bucketId, "b2:ObjectCreated:Upload");
1082
- return { status: 200, body: fileVersion };
1083
- }
1084
- cancelLargeFile(req) {
1085
- const large = this.largeFiles.get(req.fileId);
1086
- if (!large) return this.error(400, "bad_request", "Large file not found");
1087
- this.largeFiles.delete(req.fileId);
1088
- return {
1089
- status: 200,
1090
- body: {
1091
- fileId: large.fileId,
1092
- accountId: this.accountId,
1093
- bucketId: large.bucketId,
1094
- fileName: large.fileName
1095
- }
1096
- };
1097
- }
1098
- listUnfinishedLargeFiles(req) {
1099
- const countError = validateMaxCount(req.maxFileCount, "b2_list_unfinished_large_files");
1100
- if (countError) return this.error(400, countError.code, countError.message);
1101
- const prefix = req.namePrefix ?? "";
1102
- const max = req.maxFileCount ?? 100;
1103
- const candidates = [...this.largeFiles.values()].filter((f) => f.bucketId === req.bucketId).filter((f) => f.fileName.startsWith(prefix)).sort((a, b) => a.fileName.localeCompare(b.fileName));
1104
- let startIndex = 0;
1105
- if (req.startFileId !== void 0) {
1106
- const found = candidates.findIndex((f) => f.fileId === req.startFileId);
1107
- startIndex = found >= 0 ? found : 0;
1108
- }
1109
- const slice = candidates.slice(startIndex, startIndex + max);
1110
- const files = slice.map((f) => ({
1111
- fileId: f.fileId,
1112
- fileName: f.fileName,
1113
- accountId: this.accountId,
1114
- bucketId: f.bucketId,
1115
- contentType: f.contentType,
1116
- fileInfo: f.fileInfo
1117
- }));
1118
- const hasMore = startIndex + max < candidates.length;
1119
- const nextFileId = hasMore ? candidates[startIndex + max]?.fileId ?? null : null;
1120
- return { status: 200, body: { files, nextFileId } };
1121
- }
1122
- listParts(req) {
1123
- const large = this.largeFiles.get(req.fileId);
1124
- if (!large) return this.error(400, "bad_request", "Large file not found");
1125
- const countError = validateMaxCount(req.maxPartCount, "b2_list_parts");
1126
- if (countError) return this.error(400, countError.code, countError.message);
1127
- const start = req.startPartNumber ?? 1;
1128
- const max = req.maxPartCount ?? 1e3;
1129
- const allParts = [...large.parts.entries()].filter(([n]) => n >= start).sort((a, b) => a[0] - b[0]).map(([partNumber, part]) => ({
1130
- fileId: req.fileId,
1131
- partNumber,
1132
- contentLength: part.data.byteLength,
1133
- contentSha1: part.sha1,
1134
- uploadTimestamp: Date.now()
1135
- }));
1136
- const parts = allParts.slice(0, max);
1137
- const nextPartNumber = allParts.length > max ? allParts[max]?.partNumber ?? null : null;
1138
- return { status: 200, body: { parts, nextPartNumber } };
1139
- }
1140
- async copyPart(req) {
1141
- const large = this.largeFiles.get(req.largeFileId);
1142
- if (!large) return this.error(400, "bad_request", "Large file not found");
1143
- const found = this.findFile(req.sourceFileId);
1144
- if (found === null) return this.error(404, "file_not_present", "Source file not found");
1145
- const sourceStored = found.stored;
1146
- let partData = sourceStored.data;
1147
- if (req.range) {
1148
- const match = req.range.match(/bytes=(\d+)-(\d+)?/);
1149
- if (match) {
1150
- const rs = Number.parseInt(match[1] ?? "0", 10);
1151
- const re = match[2] !== void 0 ? Number.parseInt(match[2], 10) : sourceStored.data.byteLength - 1;
1152
- partData = sourceStored.data.slice(rs, re + 1);
1153
- }
1154
- }
1155
- const sha1 = await sha1Hex(partData);
1156
- large.parts.set(req.partNumber, { data: new Uint8Array(partData), sha1 });
1157
- return {
1158
- status: 200,
1159
- body: {
1160
- fileId: req.largeFileId,
1161
- partNumber: req.partNumber,
1162
- contentLength: partData.byteLength,
1163
- contentSha1: sha1
1164
- }
1165
- };
1166
- }
1167
- getDownloadAuthorization(req) {
1168
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1169
- return {
1170
- status: 200,
1171
- body: {
1172
- bucketId: req.bucketId,
1173
- fileNamePrefix: req.fileNamePrefix,
1174
- authorizationToken: `sim_dl_auth_${this.genId("tok")}`
1175
- }
1176
- };
1177
- }
1178
- // --- Keys ---
1179
- createKey(req) {
1180
- const kid = this.genId("sim_key");
1181
- const appKey = this.genId("sim_secret");
1182
- const expiration = req.validDurationInSeconds !== void 0 ? Date.now() + req.validDurationInSeconds * 1e3 : null;
1183
- const stored = {
1184
- applicationKeyId: kid,
1185
- keyName: req.keyName,
1186
- capabilities: req.capabilities,
1187
- accountId: req.accountId,
1188
- applicationKey: appKey,
1189
- bucketId: req.bucketId ?? null,
1190
- namePrefix: req.namePrefix ?? null,
1191
- expirationTimestamp: expiration
1192
- };
1193
- this.keys.set(kid, stored);
1194
- return {
1195
- status: 200,
1196
- body: {
1197
- keyName: stored.keyName,
1198
- applicationKeyId: stored.applicationKeyId,
1199
- applicationKey: stored.applicationKey,
1200
- capabilities: stored.capabilities,
1201
- accountId: stored.accountId,
1202
- expirationTimestamp: stored.expirationTimestamp,
1203
- bucketId: stored.bucketId,
1204
- namePrefix: stored.namePrefix,
1205
- options: []
1206
- }
1207
- };
1208
- }
1209
- listKeys(req) {
1210
- const countError = validateMaxCount(req.maxKeyCount, "b2_list_keys");
1211
- if (countError) return this.error(400, countError.code, countError.message);
1212
- const max = req.maxKeyCount ?? 1e3;
1213
- let allKeys = [...this.keys.values()].sort(
1214
- (a, b) => a.applicationKeyId.localeCompare(b.applicationKeyId)
1215
- );
1216
- if (req.startApplicationKeyId) {
1217
- const start = req.startApplicationKeyId;
1218
- allKeys = allKeys.filter((k) => k.applicationKeyId >= start);
1219
- }
1220
- const keys = allKeys.slice(0, max).map((k) => ({
1221
- keyName: k.keyName,
1222
- applicationKeyId: k.applicationKeyId,
1223
- capabilities: k.capabilities,
1224
- accountId: k.accountId,
1225
- expirationTimestamp: k.expirationTimestamp,
1226
- bucketId: k.bucketId,
1227
- namePrefix: k.namePrefix,
1228
- options: []
1229
- }));
1230
- const nextId = allKeys.length > max ? allKeys[max]?.applicationKeyId ?? null : null;
1231
- return { status: 200, body: { keys, nextApplicationKeyId: nextId } };
1232
- }
1233
- deleteKey(req) {
1234
- const key = this.keys.get(req.applicationKeyId);
1235
- if (!key) return this.error(400, "bad_request", "Key not found");
1236
- this.keys.delete(req.applicationKeyId);
1237
- for (const [token, scope] of this.issuedTokens.entries()) {
1238
- if (scope.applicationKeyId === req.applicationKeyId) {
1239
- this.issuedTokens.delete(token);
1240
- }
1241
- }
1242
- return {
1243
- status: 200,
1244
- body: {
1245
- keyName: key.keyName,
1246
- applicationKeyId: key.applicationKeyId,
1247
- capabilities: key.capabilities,
1248
- accountId: key.accountId,
1249
- expirationTimestamp: key.expirationTimestamp,
1250
- bucketId: key.bucketId,
1251
- namePrefix: key.namePrefix,
1252
- options: []
1253
- }
1254
- };
1255
- }
1256
- // --- File lock ---
1257
- updateFileRetention(req) {
1258
- const found = this.findFile(req.fileId);
1259
- if (found === null || found.stored.fileVersion.fileName !== req.fileName) {
1260
- return this.error(404, "file_not_present", "File not found");
1261
- }
1262
- found.versions[found.index] = {
1263
- fileVersion: {
1264
- ...found.stored.fileVersion,
1265
- fileRetention: { isClientAuthorizedToRead: true, value: req.fileRetention }
1266
- },
1267
- data: found.stored.data
1268
- };
1269
- return {
1270
- status: 200,
1271
- body: {
1272
- fileName: req.fileName,
1273
- fileId: req.fileId,
1274
- fileRetention: req.fileRetention
1275
- }
1276
- };
1277
- }
1278
- updateFileLegalHold(req) {
1279
- const found = this.findFile(req.fileId);
1280
- if (found === null || found.stored.fileVersion.fileName !== req.fileName) {
1281
- return this.error(404, "file_not_present", "File not found");
1282
- }
1283
- found.versions[found.index] = {
1284
- fileVersion: {
1285
- ...found.stored.fileVersion,
1286
- legalHold: {
1287
- isClientAuthorizedToRead: true,
1288
- value: req.legalHold
1289
- }
1290
- },
1291
- data: found.stored.data
1292
- };
1293
- return {
1294
- status: 200,
1295
- body: {
1296
- fileName: req.fileName,
1297
- fileId: req.fileId,
1298
- legalHold: req.legalHold
1299
- }
1300
- };
1301
- }
1302
- // --- Notifications ---
1303
- getBucketNotificationRules(req) {
1304
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1305
- const rules = this.notificationRules.get(req.bucketId) ?? [];
1306
- return { status: 200, body: { bucketId: req.bucketId, eventNotificationRules: rules } };
1307
- }
1308
- setBucketNotificationRules(req) {
1309
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1310
- this.notificationRules.set(req.bucketId, req.eventNotificationRules);
1311
- return {
1312
- status: 200,
1313
- body: { bucketId: req.bucketId, eventNotificationRules: req.eventNotificationRules }
1314
- };
1315
- }
1316
- // --- Helpers ---
1317
- /**
1318
- * Locates a stored file version by its `fileId`, scanning every bucket.
1319
- *
1320
- * Returns enough context to support read-only inspection (`stored`,
1321
- * `bucketId`) AND in-place mutation (`versions`, `index`) so callers
1322
- * that need to splice the version out can do so without re-scanning.
1323
- *
1324
- * Real B2 fileIds embed the bucketId, so production lookups are O(1);
1325
- * the simulator's flat ID generator (`this.genId('4_z')`) doesn't, so this
1326
- * is O(buckets × files × versions). Acceptable for tests.
1327
- *
1328
- * @param fileId - The file version ID to locate.
1329
- *
1330
- * @returns The location of the matching version, or `null` if not found.
1331
- */
1332
- findFile(fileId2) {
1333
- for (const [bid, bucket] of this.buckets.entries()) {
1334
- for (const versions of bucket.files.values()) {
1335
- const idx = versions.findIndex((v) => v.fileVersion.fileId === fileId2);
1336
- if (idx !== -1) {
1337
- const stored = versions[idx];
1338
- return { stored, bucketId: bid, bucket, versions, index: idx };
1339
- }
1340
- }
1341
- }
1342
- return null;
1343
- }
1344
- makeFileVersion(params) {
1345
- return {
1346
- accountId: accountId(this.accountId),
1347
- action: params.action,
1348
- bucketId: bucketId(params.bucketId),
1349
- contentLength: params.contentLength,
1350
- contentMd5: null,
1351
- contentSha1: params.contentSha1,
1352
- contentType: params.contentType,
1353
- fileId: fileId(this.genId("4_z")),
1354
- fileInfo: {},
1355
- fileName: params.fileName,
1356
- fileRetention: { isClientAuthorizedToRead: true, value: null },
1357
- legalHold: { isClientAuthorizedToRead: true, value: null },
1358
- replicationStatus: null,
1359
- serverSideEncryption: { mode: EncryptionMode.None },
1360
- uploadTimestamp: this.monotonicTimestamp()
1361
- };
1362
- }
1363
- error(status, code, message) {
1364
- return { status, body: { status, code, message } };
1365
- }
1366
- /**
1367
- * Fire the pluggable post-upload hooks for a file that just landed in
1368
- * a bucket: matching event-notification rules → `onWebhookDeliver`,
1369
- * configured replication source rules → `onReplicate`. Errors thrown
1370
- * from user-supplied hooks are swallowed so a buggy listener never
1371
- * masks an otherwise-successful API response.
1372
- *
1373
- * Fired-and-forgotten (no await) by the handler so the synthetic
1374
- * response is returned to the caller as fast as production B2 would
1375
- * acknowledge the write.
1376
- *
1377
- * @param fileVersion - The freshly-stored file metadata.
1378
- * @param bucketId - The bucket the upload landed in.
1379
- * @param eventType - The B2 event-type tag (e.g. `'b2:ObjectCreated:Upload'`)
1380
- * used to match against `EventNotificationRule.eventTypes` globs.
1381
- */
1382
- firePostUploadHooks(fileVersion, bucketId2, eventType) {
1383
- const bucket = this.buckets.get(bucketId2);
1384
- if (!bucket) return;
1385
- if (this.onWebhookDeliver !== void 0) {
1386
- const rules = this.notificationRules.get(bucketId2) ?? [];
1387
- for (const rule of rules) {
1388
- if (!rule.isEnabled) continue;
1389
- const matches = rule.eventTypes.some((pattern) => eventTypeMatches(pattern, eventType));
1390
- if (!matches) continue;
1391
- const hook = this.onWebhookDeliver;
1392
- this.dispatchHook("webhook", () => hook({ rule, fileVersion, bucketId: bucketId2 }));
1393
- }
1394
- }
1395
- if (this.onReplicate !== void 0) {
1396
- const replConfig = bucket.info.replicationConfiguration;
1397
- const sourceRules = replConfig.asReplicationSource?.replicationRules ?? [];
1398
- for (const rule of sourceRules) {
1399
- if (!rule.isEnabled) continue;
1400
- if (rule.fileNamePrefix && !fileVersion.fileName.startsWith(rule.fileNamePrefix)) continue;
1401
- const hook = this.onReplicate;
1402
- this.dispatchHook(
1403
- "replication",
1404
- () => hook({
1405
- sourceFileVersion: fileVersion,
1406
- sourceBucketId: bucketId2,
1407
- destinationBucketId: rule.destinationBucketId
1408
- })
1409
- );
1410
- }
1411
- }
1412
- }
1413
- /**
1414
- * Schedule a user-supplied hook callback. Errors are routed to
1415
- * `onHookError` if configured, swallowed otherwise. The returned
1416
- * promise is tracked in {@link pendingHooks} so `flushHooks()` can
1417
- * wait for every dispatched hook to settle.
1418
- *
1419
- * @param kind - Which hook this is (`'webhook'` or `'replication'`).
1420
- * @param fn - Thunk that performs the hook invocation.
1421
- */
1422
- dispatchHook(kind, fn) {
1423
- const task = Promise.resolve().then(() => fn()).catch((err) => {
1424
- if (this.onHookError !== void 0) {
1425
- this.onHookError({ kind, error: toError(err) });
1426
- }
1427
- }).finally(() => {
1428
- this.pendingHooks.delete(task);
1429
- });
1430
- this.pendingHooks.add(task);
1431
- }
125
+ function singleBucketId(bucketIds) {
126
+ return bucketIds?.length === 1 ? bucketIds[0] ?? null : null;
1432
127
  }
1433
- const eventTypeRegexCache = /* @__PURE__ */ new Map();
128
+ function cloneBucketIds(bucketIds) {
129
+ return bucketIds === null ? null : [...bucketIds];
130
+ }
131
+ function hasOwnField(body, field) {
132
+ return typeof body === "object" && body !== null && Object.hasOwn(body, field);
133
+ }
134
+ function requestStringField(body, field) {
135
+ if (typeof body !== "object" || body === null) return void 0;
136
+ const value = body[field];
137
+ return typeof value === "string" ? value : void 0;
138
+ }
139
+ function fileNames(...names) {
140
+ const present = names.filter((name) => name !== void 0);
141
+ return present.length > 0 ? present : void 0;
142
+ }
143
+ function notificationRulePrefixes(body) {
144
+ if (typeof body !== "object" || body === null) return void 0;
145
+ const rules = body["eventNotificationRules"];
146
+ if (!Array.isArray(rules)) return void 0;
147
+ return rules.map((rule) => {
148
+ if (typeof rule !== "object" || rule === null) return "";
149
+ const objectNamePrefix = rule["objectNamePrefix"];
150
+ return typeof objectNamePrefix === "string" ? objectNamePrefix : "";
151
+ });
152
+ }
153
+ function storedNotificationRulePrefixes(rules) {
154
+ return (rules ?? []).map((rule) => typeof rule.objectNamePrefix === "string" ? rule.objectNamePrefix : "");
155
+ }
156
+ function hasKeyManagementCapability(capabilities) {
157
+ return capabilities.some((capability) => capability === Capability.ListKeys || capability === Capability.WriteKeys || capability === Capability.DeleteKeys);
158
+ }
159
+ function publicServerSideEncryption(encryption) {
160
+ if (encryption.mode === EncryptionMode.SseC) return {
161
+ mode: encryption.mode,
162
+ algorithm: encryption.algorithm
163
+ };
164
+ if (encryption.mode === EncryptionMode.None) return {
165
+ mode: null,
166
+ algorithm: null
167
+ };
168
+ return encryption;
169
+ }
170
+ function uploadServerSideEncryption(headers, fallback) {
171
+ if (headers["x-bz-server-side-encryption-customer-algorithm"] === EncryptionAlgorithm.Aes256) return {
172
+ mode: EncryptionMode.SseC,
173
+ algorithm: EncryptionAlgorithm.Aes256,
174
+ customerKey: headers["x-bz-server-side-encryption-customer-key"] ?? "",
175
+ customerKeyMd5: headers["x-bz-server-side-encryption-customer-key-md5"] ?? ""
176
+ };
177
+ if (headers["x-bz-server-side-encryption"] === EncryptionAlgorithm.Aes256) return {
178
+ mode: EncryptionMode.SseB2,
179
+ algorithm: EncryptionAlgorithm.Aes256
180
+ };
181
+ return fallback;
182
+ }
183
+ function defaultFileRetention(policy, uploadTimestamp) {
184
+ if (policy.mode === BucketRetentionMode.None || policy.period === null) return null;
185
+ const days = policy.period.unit === "days" ? policy.period.duration : policy.period.duration * 365;
186
+ return {
187
+ mode: policy.mode,
188
+ retainUntilTimestamp: uploadTimestamp + days * 24 * 60 * 60 * 1e3
189
+ };
190
+ }
191
+ /**
192
+ * In-memory B2 simulator for testing. Implements the B2 native API at the
193
+ * request/response level without any network I/O. Supports 25+ operations
194
+ * including buckets, files, large files, keys, and notifications.
195
+ *
196
+ * @example
197
+ * ```ts
198
+ * const sim = new B2Simulator()
199
+ * const client = new B2Client({
200
+ * applicationKeyId: 'test-key-id',
201
+ * applicationKey: 'test-key',
202
+ * transport: sim.transport(),
203
+ * })
204
+ * await client.authorize()
205
+ * ```
206
+ */
207
+ var B2Simulator = class {
208
+ buckets = /* @__PURE__ */ new Map();
209
+ accountId = "sim_account_0001";
210
+ largeFiles = /* @__PURE__ */ new Map();
211
+ keys = /* @__PURE__ */ new Map();
212
+ notificationRules = /* @__PURE__ */ new Map();
213
+ minimumPartSize;
214
+ recommendedPartSize;
215
+ faults = [];
216
+ nextFaultId = 1;
217
+ onWebhookDeliver;
218
+ onReplicate;
219
+ onHookError;
220
+ strictAuth;
221
+ authTokenTtlMs;
222
+ /**
223
+ * Issued auth tokens with their associated grant scope + expiry. In
224
+ * permissive mode (`strictAuth: false`) this is still populated by
225
+ * `authorize` but never consulted on subsequent requests. In strict
226
+ * mode each request looks up its `Authorization` header here.
227
+ */
228
+ issuedTokens = /* @__PURE__ */ new Map();
229
+ /**
230
+ * Mutable upload-token overrides for tokens minted by `b2_get_upload_url`
231
+ * and `b2_get_upload_part_url`. The token string is self-describing
232
+ * and signed so another simulator instance can validate issued-token
233
+ * state, while this map records local invalidation / forced-expiry
234
+ * state for tests.
235
+ */
236
+ uploadTokens = /* @__PURE__ */ new Map();
237
+ /**
238
+ * Virtual-clock offset applied to `Date.now()` for expiry checks.
239
+ * Defaults to 0. Tests advance via {@link advanceTime} to fast-forward
240
+ * past auth-token expiry without sleeping.
241
+ */
242
+ clockOffsetMs = 0;
243
+ /**
244
+ * Per-instance monotonic counter used to mint realistic-looking
245
+ * IDs (`b2_bucket_<24-hex>`, `4_z<24-hex>`, etc.) and auth tokens.
246
+ * Module-global previously, which leaked state across `B2Simulator`
247
+ * instances in the same Vitest worker — concurrent tests could see
248
+ * colliding tokens. Per-instance ensures determinism within a single
249
+ * simulator's lifetime.
250
+ */
251
+ nextId = 1;
252
+ /**
253
+ * Last-issued upload timestamp. The simulator enforces strict
254
+ * monotonicity so version ordering is deterministic for tests; if
255
+ * two writes hit the same `Date.now()` millisecond, the second
256
+ * receives `lastTimestamp + 1`.
257
+ */
258
+ lastTimestamp = 0;
259
+ /**
260
+ * Outstanding fire-and-forget hook invocations. Tracked so tests
261
+ * (and future {@link flushHooks} callers) can wait for every
262
+ * dispatched `onWebhookDeliver` / `onReplicate` callback to settle
263
+ * before asserting against observable side effects. The microtask
264
+ * dance in fidelity tests was previously brittle: positive cases
265
+ * flushed twice, negative cases flushed once, and any addition to
266
+ * the hook dispatch chain quietly broke the negative path.
267
+ */
268
+ pendingHooks = /* @__PURE__ */ new Set();
269
+ /**
270
+ * Constructs a new in-memory B2 simulator.
271
+ * @param options - Optional simulator overrides. See {@link B2SimulatorOptions}.
272
+ */
273
+ constructor(options = {}) {
274
+ this.minimumPartSize = options.minimumPartSize ?? 5e6;
275
+ this.recommendedPartSize = options.recommendedPartSize ?? 1e8;
276
+ if (options.onWebhookDeliver !== void 0) this.onWebhookDeliver = options.onWebhookDeliver;
277
+ if (options.onReplicate !== void 0) this.onReplicate = options.onReplicate;
278
+ if (options.onHookError !== void 0) this.onHookError = options.onHookError;
279
+ this.strictAuth = options.strictAuth ?? false;
280
+ this.authTokenTtlMs = options.authTokenTtlMs ?? 1440 * 60 * 1e3;
281
+ }
282
+ /**
283
+ * Advance the simulator's virtual clock by `ms` milliseconds. Used in
284
+ * conjunction with `strictAuth: true` + a finite `authTokenTtlMs` to
285
+ * force token expiry without `setTimeout`-based delays.
286
+ *
287
+ * @param ms - Milliseconds to advance. Negative values rewind (rarely useful).
288
+ */
289
+ advanceTime(ms) {
290
+ this.clockOffsetMs += ms;
291
+ }
292
+ /**
293
+ * Expire an upload authorization token previously returned by
294
+ * `b2_get_upload_url` or `b2_get_upload_part_url`. Tests can use this
295
+ * to simulate a stale upload URL and verify retry paths that fetch a
296
+ * fresh URL/token pair.
297
+ *
298
+ * @param authorizationToken - The upload authorization token to expire.
299
+ *
300
+ * @returns `true` when the token existed and was expired, otherwise `false`.
301
+ */
302
+ expireUploadToken(authorizationToken) {
303
+ const now = this.now();
304
+ const token = this.uploadTokens.get(authorizationToken);
305
+ if (token === void 0 || now >= token.cleanupAt) return false;
306
+ token.expiresAt = now - 1;
307
+ this.uploadTokens.set(authorizationToken, token);
308
+ return true;
309
+ }
310
+ /**
311
+ * Invalidate an upload authorization token previously returned by
312
+ * `b2_get_upload_url` or `b2_get_upload_part_url`.
313
+ *
314
+ * @param authorizationToken - The upload authorization token to invalidate.
315
+ *
316
+ * @returns `true` when the token existed and was invalidated, otherwise `false`.
317
+ */
318
+ invalidateUploadToken(authorizationToken) {
319
+ const now = this.now();
320
+ const token = this.uploadTokens.get(authorizationToken);
321
+ if (token === void 0 || now >= token.cleanupAt) {
322
+ this.pruneExpiredUploadTokens(now);
323
+ return false;
324
+ }
325
+ token.invalidated = true;
326
+ this.uploadTokens.set(authorizationToken, token);
327
+ this.pruneExpiredUploadTokens();
328
+ return true;
329
+ }
330
+ /**
331
+ * Current simulator time. Equal to `Date.now() + clockOffsetMs`.
332
+ *
333
+ * @returns Unix milliseconds.
334
+ */
335
+ now() {
336
+ return Date.now() + this.clockOffsetMs;
337
+ }
338
+ pruneExpiredUploadTokens(now = this.now()) {
339
+ for (const [authorizationToken, token] of this.uploadTokens.entries()) if (now >= token.cleanupAt) this.uploadTokens.delete(authorizationToken);
340
+ }
341
+ async uploadTokenState(authorizationToken) {
342
+ const stored = this.uploadTokens.get(authorizationToken);
343
+ if (stored !== void 0) return stored;
344
+ return await this.decodeUploadAuthorizationToken(authorizationToken);
345
+ }
346
+ async encodeUploadAuthorizationToken(token) {
347
+ const payload = {
348
+ v: 1,
349
+ kind: token.kind,
350
+ fileName: token.fileName,
351
+ uploadUrl: token.uploadUrl,
352
+ namePrefix: token.namePrefix,
353
+ applicationKeyId: token.applicationKeyId,
354
+ expiresAt: token.expiresAt
355
+ };
356
+ const encoded = base64UrlEncode(utf8Encoder.encode(JSON.stringify(payload)));
357
+ const signature = await this.signUploadTokenPayload(encoded);
358
+ return `${token.kind === "file" ? "sim_upload_auth" : "sim_part_auth"}_${encoded}.${signature}`;
359
+ }
360
+ async decodeUploadAuthorizationToken(authorizationToken) {
361
+ const expectedKind = authorizationToken.startsWith("sim_upload_auth_") ? "file" : authorizationToken.startsWith("sim_part_auth_") ? "part" : null;
362
+ if (expectedKind === null) return null;
363
+ const tokenParts = authorizationToken.slice(expectedKind === "file" ? 16 : 14).split(".");
364
+ if (tokenParts.length !== 2) return null;
365
+ const [payloadBytes, signature] = tokenParts;
366
+ if (!timingSafeStringEqual(signature, await this.signUploadTokenPayload(payloadBytes))) return null;
367
+ let parsed;
368
+ try {
369
+ const bytes = base64UrlDecode(payloadBytes);
370
+ if (bytes === null) return null;
371
+ parsed = JSON.parse(utf8Decoder.decode(bytes));
372
+ } catch {
373
+ return null;
374
+ }
375
+ if (typeof parsed !== "object" || parsed === null) return null;
376
+ const payload = parsed;
377
+ if (payload["v"] !== 1 || payload["kind"] !== expectedKind || typeof payload["uploadUrl"] !== "string" || typeof payload["expiresAt"] !== "number" || !Number.isFinite(payload["expiresAt"]) || !(payload["namePrefix"] === null || typeof payload["namePrefix"] === "string") || !(payload["applicationKeyId"] === null || typeof payload["applicationKeyId"] === "string")) return null;
378
+ let fileName;
379
+ if (expectedKind === "part") {
380
+ if (typeof payload["fileName"] !== "string") return null;
381
+ fileName = payload["fileName"];
382
+ } else {
383
+ if (payload["fileName"] !== null) return null;
384
+ fileName = null;
385
+ }
386
+ return {
387
+ kind: expectedKind,
388
+ fileName,
389
+ uploadUrl: payload["uploadUrl"],
390
+ namePrefix: payload["namePrefix"],
391
+ applicationKeyId: payload["applicationKeyId"],
392
+ expiresAt: payload["expiresAt"],
393
+ cleanupAt: payload["expiresAt"],
394
+ invalidated: false
395
+ };
396
+ }
397
+ async signUploadTokenPayload(encodedPayload) {
398
+ return base64UrlEncode(await hmacSha256(UPLOAD_TOKEN_SIGNING_KEY, encodedPayload));
399
+ }
400
+ /**
401
+ * Generate a deterministic-but-realistic-looking B2 identifier of the
402
+ * shape `<prefix>_<24-hex-counter>`, which approximates the visual
403
+ * width of real B2 wire IDs. The counter is monotonic per instance
404
+ * so test fixtures are deterministic across runs of the same
405
+ * simulator.
406
+ *
407
+ * @param prefix - B2-style prefix (`'b2_bucket'`, `'4_z'`, etc.).
408
+ *
409
+ * @returns A simulator-issued identifier that looks like a B2 wire ID.
410
+ */
411
+ genId(prefix) {
412
+ return `${prefix}_${(this.nextId++).toString(16).padStart(24, "0")}`;
413
+ }
414
+ /**
415
+ * Return a strictly-increasing upload timestamp, even when multiple
416
+ * writes land in the same `Date.now()` millisecond. Tests rely on
417
+ * `uploadTimestamp` ordering to discriminate file versions; ties from
418
+ * coarse system-clock resolution would otherwise make version
419
+ * selection nondeterministic.
420
+ *
421
+ * @returns Unix milliseconds.
422
+ */
423
+ monotonicTimestamp() {
424
+ const now = Date.now();
425
+ if (now <= this.lastTimestamp) this.lastTimestamp += 1;
426
+ else this.lastTimestamp = now;
427
+ return this.lastTimestamp;
428
+ }
429
+ /**
430
+ * Wait for every fire-and-forget hook (`onWebhookDeliver`,
431
+ * `onReplicate`) currently in flight to settle. Use in tests after
432
+ * an upload/copy/finish-large-file call to deterministically observe
433
+ * hook side effects without microtask-flush guesswork.
434
+ *
435
+ * @returns A promise that resolves once every pending hook callback
436
+ * has either resolved or rejected.
437
+ */
438
+ async flushHooks() {
439
+ while (this.pendingHooks.size > 0) {
440
+ const snapshot = [...this.pendingHooks];
441
+ await Promise.allSettled(snapshot);
442
+ }
443
+ }
444
+ /**
445
+ * Authorize a request against the strict-auth bookkeeping. Returns
446
+ * a `SimulatorJsonResponse` error on failure or `null` on success.
447
+ * Only consulted when `strictAuth: true`.
448
+ *
449
+ * @param authToken - The `Authorization` header value from the request.
450
+ * @param endpoint - B2 endpoint name being invoked.
451
+ * @param scope - Optional effective bucket and file-name scope derived from the request.
452
+ *
453
+ * @returns `null` when the request is authorized, otherwise a 401/403 response.
454
+ */
455
+ authorizeRequest(authToken, endpoint, scope) {
456
+ if (missingCapabilitiesFor(endpoint, []).length === 0 && endpoint === "b2_authorize_account") return null;
457
+ if (authToken === void 0 || authToken === "") return this.error(401, "bad_auth_token", "missing Authorization header");
458
+ const token = this.issuedTokens.get(authToken);
459
+ if (!token) return this.error(401, "bad_auth_token", "unknown auth token");
460
+ if (this.now() > token.expiresAt) return this.error(401, "expired_auth_token", "auth token has expired; reauthorize");
461
+ const missing = missingCapabilitiesFor(endpoint, token.capabilities);
462
+ if (missing.length > 0) return this.error(403, "unauthorized", `application key lacks required capabilities: ${missing.join(", ")}`);
463
+ if (token.bucketIds !== null) {
464
+ if ((scope?.bucketIds.length ?? 0) === 0 && scope?.requiresBucketScope === true) return this.error(403, "unauthorized", `application key is scoped to buckets ${token.bucketIds.join(", ")}; bucket scope is required`);
465
+ for (const bucketId of scope?.bucketIds ?? []) if (!token.bucketIds.includes(bucketId)) return this.error(403, "unauthorized", `application key is scoped to buckets ${token.bucketIds.join(", ")}; cannot access ${bucketId}`);
466
+ }
467
+ if (token.namePrefix !== null) for (const fileName of scope?.fileNames ?? []) {
468
+ if (fileName.startsWith(token.namePrefix)) continue;
469
+ return this.error(403, "unauthorized", `application key is scoped to prefix "${token.namePrefix}"; "${fileName}" is outside scope`);
470
+ }
471
+ return null;
472
+ }
473
+ requestScope(endpoint, body) {
474
+ const directBucketId = requestStringField(body, "bucketId");
475
+ const directFileName = requestStringField(body, "fileName");
476
+ switch (endpoint) {
477
+ case "b2_create_bucket": return {
478
+ bucketIds: [],
479
+ requiresBucketScope: true
480
+ };
481
+ case "b2_list_buckets": return this.listBucketsScope(body, directBucketId);
482
+ case "b2_list_file_names":
483
+ case "b2_list_file_versions": return {
484
+ bucketIds: directBucketId === void 0 ? [] : [directBucketId],
485
+ fileNames: [requestStringField(body, "prefix") ?? ""],
486
+ requiresBucketScope: true
487
+ };
488
+ case "b2_get_file_info": return this.fileIdScope(requestStringField(body, "fileId")) ?? {
489
+ bucketIds: [],
490
+ requiresBucketScope: true
491
+ };
492
+ case "b2_delete_file_version":
493
+ case "b2_update_file_retention":
494
+ case "b2_update_file_legal_hold": return this.fileVersionScope(body, directFileName);
495
+ case "b2_get_upload_part_url":
496
+ case "b2_finish_large_file":
497
+ case "b2_cancel_large_file":
498
+ case "b2_list_parts": return this.largeFileScope(requestStringField(body, "fileId")) ?? {
499
+ bucketIds: [],
500
+ requiresBucketScope: true
501
+ };
502
+ case "b2_copy_file": return this.copyFileScope(body, directFileName);
503
+ case "b2_copy_part": return this.copyPartScope(body);
504
+ case "b2_list_unfinished_large_files": return {
505
+ bucketIds: directBucketId === void 0 ? [] : [directBucketId],
506
+ fileNames: [requestStringField(body, "namePrefix") ?? ""],
507
+ requiresBucketScope: true
508
+ };
509
+ case "b2_get_download_authorization": return {
510
+ bucketIds: directBucketId === void 0 ? [] : [directBucketId],
511
+ fileNames: [requestStringField(body, "fileNamePrefix") ?? ""],
512
+ requiresBucketScope: true
513
+ };
514
+ case "b2_get_bucket_notification_rules": return this.notificationRulesScope(body, directBucketId, false);
515
+ case "b2_set_bucket_notification_rules": return this.notificationRulesScope(body, directBucketId, true);
516
+ default: return this.defaultRequestScope(directBucketId, directFileName);
517
+ }
518
+ }
519
+ listBucketsScope(body, directBucketId) {
520
+ if (directBucketId !== void 0) return {
521
+ bucketIds: [directBucketId],
522
+ requiresBucketScope: true
523
+ };
524
+ const bucketName = requestStringField(body, "bucketName");
525
+ if (bucketName !== void 0) {
526
+ const bucket = [...this.buckets.values()].find((b) => b.info.bucketName === bucketName);
527
+ return {
528
+ bucketIds: bucket === void 0 ? [] : [bucket.info.bucketId],
529
+ requiresBucketScope: true
530
+ };
531
+ }
532
+ return {
533
+ bucketIds: [],
534
+ requiresBucketScope: true
535
+ };
536
+ }
537
+ fileVersionScope(body, directFileName) {
538
+ const fileScope = this.fileIdScope(requestStringField(body, "fileId"));
539
+ if (fileScope !== void 0) return fileScope;
540
+ return {
541
+ bucketIds: [],
542
+ ...directFileName !== void 0 ? { fileNames: [directFileName] } : {},
543
+ requiresBucketScope: true
544
+ };
545
+ }
546
+ copyFileScope(body, directFileName) {
547
+ const sourceScope = this.fileIdScope(requestStringField(body, "sourceFileId"));
548
+ const destinationBucketId = requestStringField(body, "destinationBucketId");
549
+ const bucketIds = [...sourceScope?.bucketIds ?? [], ...destinationBucketId !== void 0 ? [destinationBucketId] : []];
550
+ const scopedFileNames = fileNames(...sourceScope?.fileNames ?? [], directFileName);
551
+ return {
552
+ bucketIds,
553
+ ...scopedFileNames !== void 0 ? { fileNames: scopedFileNames } : {},
554
+ requiresBucketScope: true
555
+ };
556
+ }
557
+ copyPartScope(body) {
558
+ const sourceScope = this.fileIdScope(requestStringField(body, "sourceFileId"));
559
+ const largeScope = this.largeFileScope(requestStringField(body, "largeFileId"));
560
+ const scopedFileNames = fileNames(...sourceScope?.fileNames ?? [], ...largeScope?.fileNames ?? []);
561
+ return {
562
+ bucketIds: [...sourceScope?.bucketIds ?? [], ...largeScope?.bucketIds ?? []],
563
+ ...scopedFileNames !== void 0 ? { fileNames: scopedFileNames } : {},
564
+ requiresBucketScope: true
565
+ };
566
+ }
567
+ notificationRulesScope(body, directBucketId, includeRequestRules) {
568
+ const existingPrefixes = directBucketId === void 0 ? [] : storedNotificationRulePrefixes(this.notificationRules.get(directBucketId));
569
+ const requestPrefixes = includeRequestRules ? notificationRulePrefixes(body) ?? [] : [];
570
+ const prefixes = [...existingPrefixes, ...requestPrefixes];
571
+ return {
572
+ bucketIds: directBucketId === void 0 ? [] : [directBucketId],
573
+ ...prefixes.length > 0 ? { fileNames: prefixes } : {},
574
+ requiresBucketScope: true
575
+ };
576
+ }
577
+ defaultRequestScope(directBucketId, directFileName) {
578
+ if (directBucketId !== void 0) return {
579
+ bucketIds: [directBucketId],
580
+ ...directFileName !== void 0 ? { fileNames: [directFileName] } : {},
581
+ requiresBucketScope: true
582
+ };
583
+ return directFileName !== void 0 ? {
584
+ bucketIds: [],
585
+ fileNames: [directFileName],
586
+ requiresBucketScope: false
587
+ } : void 0;
588
+ }
589
+ fileIdScope(fileId) {
590
+ if (fileId === void 0) return void 0;
591
+ const found = this.findFile(fileId);
592
+ if (found === null) return void 0;
593
+ return {
594
+ bucketIds: [found.bucketId],
595
+ fileNames: [found.stored.fileVersion.fileName],
596
+ requiresBucketScope: true
597
+ };
598
+ }
599
+ largeFileScope(fileId) {
600
+ if (fileId === void 0) return void 0;
601
+ const large = this.largeFiles.get(fileId);
602
+ if (large === void 0) return void 0;
603
+ return {
604
+ bucketIds: [large.bucketId],
605
+ fileNames: [large.fileName],
606
+ requiresBucketScope: true
607
+ };
608
+ }
609
+ async issueUploadAuthorization(options) {
610
+ const now = this.now();
611
+ this.pruneExpiredUploadTokens(now);
612
+ const endpoint = options.kind === "file" ? "b2_upload_file" : "b2_upload_part";
613
+ const idParam = options.kind === "file" ? "bucketId" : "fileId";
614
+ const scopedId = options.kind === "file" ? options.bucketId : options.fileId;
615
+ const uploadId = this.genId(options.kind === "file" ? "upload_file" : "upload_part");
616
+ const uploadUrl = new URL(`http://localhost:0/b2api/v3/${endpoint}`);
617
+ uploadUrl.searchParams.set(idParam, scopedId);
618
+ uploadUrl.searchParams.set("uploadId", uploadId);
619
+ const sourceToken = options.sourceAuthToken === void 0 ? void 0 : this.issuedTokens.get(options.sourceAuthToken);
620
+ const token = {
621
+ kind: options.kind,
622
+ fileName: options.kind === "part" ? options.fileName : null,
623
+ uploadUrl: uploadUrl.toString(),
624
+ namePrefix: this.strictAuth ? sourceToken?.namePrefix ?? null : null,
625
+ applicationKeyId: sourceToken?.applicationKeyId ?? null,
626
+ expiresAt: now + this.authTokenTtlMs,
627
+ cleanupAt: now + this.authTokenTtlMs,
628
+ invalidated: false
629
+ };
630
+ const authorizationToken = await this.encodeUploadAuthorizationToken(token);
631
+ this.uploadTokens.set(authorizationToken, token);
632
+ return {
633
+ uploadUrl: uploadUrl.toString(),
634
+ authorizationToken
635
+ };
636
+ }
637
+ async validateUploadAuthorization(kind, uploadUrl, authToken, fileName) {
638
+ if (authToken === void 0 || authToken === "") return this.error(401, "bad_auth_token", "missing upload Authorization header");
639
+ const token = await this.uploadTokenState(authToken);
640
+ if (token === null) {
641
+ this.pruneExpiredUploadTokens();
642
+ return this.error(401, "bad_auth_token", "unknown upload authorization token");
643
+ }
644
+ const now = this.now();
645
+ if (now >= token.expiresAt) {
646
+ if (now >= token.cleanupAt) this.uploadTokens.delete(authToken);
647
+ else this.uploadTokens.set(authToken, token);
648
+ this.pruneExpiredUploadTokens(now);
649
+ return this.error(401, "expired_auth_token", "upload authorization token has expired; get a new upload URL");
650
+ }
651
+ if (token.invalidated) {
652
+ this.uploadTokens.set(authToken, token);
653
+ this.pruneExpiredUploadTokens(now);
654
+ return this.error(401, "bad_auth_token", "upload authorization token has been invalidated");
655
+ }
656
+ if (token.kind !== kind) {
657
+ this.pruneExpiredUploadTokens(now);
658
+ return this.error(401, "bad_auth_token", "upload authorization token type mismatch");
659
+ }
660
+ this.pruneExpiredUploadTokens(now);
661
+ if (!this.uploadUrlMatches(token, uploadUrl)) return this.error(401, "bad_auth_token", "upload authorization token is not valid for this upload URL");
662
+ const scopedName = kind === "file" ? fileName : token.fileName ?? void 0;
663
+ if (token.namePrefix !== null && scopedName !== void 0) {
664
+ if (!scopedName.startsWith(token.namePrefix)) return this.error(403, "unauthorized", `application key is scoped to prefix "${token.namePrefix}"; "${scopedName}" is outside scope`);
665
+ }
666
+ return null;
667
+ }
668
+ uploadUrlMatches(token, uploadUrl) {
669
+ let expected;
670
+ let actual;
671
+ try {
672
+ expected = new URL(token.uploadUrl);
673
+ actual = new URL(uploadUrl);
674
+ } catch {
675
+ return false;
676
+ }
677
+ if (actual.origin !== expected.origin || actual.pathname !== expected.pathname) return false;
678
+ const scopeParam = token.kind === "file" ? "bucketId" : "fileId";
679
+ return actual.searchParams.get(scopeParam) === expected.searchParams.get(scopeParam) && actual.searchParams.get("uploadId") === expected.searchParams.get("uploadId");
680
+ }
681
+ allowedBuckets(bucketIds) {
682
+ if (bucketIds === void 0 || bucketIds === null) return null;
683
+ return bucketIds.map((id) => ({
684
+ id: bucketId(id),
685
+ name: this.buckets.get(id)?.info.bucketName ?? null
686
+ }));
687
+ }
688
+ /**
689
+ * Look up the application key matching the `Authorization` header on
690
+ * an `authorize_account` request. The header is in the form
691
+ * `Basic base64(applicationKeyId:applicationKey)`.
692
+ *
693
+ * Returns `null` for the implicit master credential (anything that
694
+ * does not match a key minted via `b2_create_key`); in that case
695
+ * `authorize` grants the full master capability set.
696
+ *
697
+ * @param authzHeader - Raw HTTP `Authorization` header value.
698
+ *
699
+ * @returns The matching key's grant scope, or `null` for the master.
700
+ */
701
+ findKeyForAuthHeader(authzHeader) {
702
+ if (!authzHeader?.startsWith("Basic ")) return null;
703
+ const decoded = (() => {
704
+ try {
705
+ return atob(authzHeader.slice(6));
706
+ } catch {
707
+ return null;
708
+ }
709
+ })();
710
+ if (decoded === null) return null;
711
+ const idx = decoded.indexOf(":");
712
+ if (idx === -1) return null;
713
+ const applicationKeyId = decoded.slice(0, idx);
714
+ const applicationKey = decoded.slice(idx + 1);
715
+ const stored = this.keys.get(applicationKeyId);
716
+ if (!stored || stored.applicationKey !== applicationKey) return null;
717
+ return {
718
+ capabilities: stored.capabilities,
719
+ bucketIds: stored.bucketIds,
720
+ namePrefix: stored.namePrefix,
721
+ applicationKeyId
722
+ };
723
+ }
724
+ /**
725
+ * Creates an {@link HttpTransport} that routes requests to this simulator.
726
+ * @returns A transport instance backed by this in-memory simulator.
727
+ */
728
+ transport() {
729
+ return new SimulatorTransport(this);
730
+ }
731
+ /**
732
+ * Register a synthetic failure to inject on requests whose URL contains
733
+ * `spec.on`. Use this to exercise retry / backoff / error-handling
734
+ * paths in tests without hand-rolling a wrapping `HttpTransport`. The
735
+ * fault is consumed in registration order on each matched request;
736
+ * once its `count` budget is exhausted it auto-retires.
737
+ *
738
+ * Faults are checked BEFORE the simulator's real handlers run, so a
739
+ * matched request never touches in-memory state — failed uploads
740
+ * don't create partial parts, failed deletes don't remove anything.
741
+ *
742
+ * @param spec - The failure to inject. See {@link FaultSpec}.
743
+ *
744
+ * @returns A handle whose `clear()` method removes this specific
745
+ * fault registration (other faults remain in effect).
746
+ *
747
+ * @example
748
+ * ```ts
749
+ * // Fail the next 2 b2_upload_part calls with 503, then succeed.
750
+ * sim.injectFailure({ on: 'b2_upload_part', status: 503, count: 2 })
751
+ *
752
+ * // Fail every b2_authorize_account with 401 + Retry-After: 5.
753
+ * const handle = sim.injectFailure({
754
+ * on: 'b2_authorize_account',
755
+ * status: 401,
756
+ * code: 'expired_auth_token',
757
+ * retryAfter: 5,
758
+ * })
759
+ * // ... later
760
+ * handle.clear()
761
+ * ```
762
+ */
763
+ injectFailure(spec) {
764
+ const id = this.nextFaultId++;
765
+ const fault = {
766
+ id,
767
+ spec,
768
+ remainingSkip: spec.skip ?? 0,
769
+ remainingCount: spec.count ?? Number.POSITIVE_INFINITY
770
+ };
771
+ this.faults.push(fault);
772
+ return { clear: () => {
773
+ const idx = this.faults.findIndex((f) => f.id === id);
774
+ if (idx !== -1) this.faults.splice(idx, 1);
775
+ } };
776
+ }
777
+ /**
778
+ * Remove every registered fault. Equivalent to calling `.clear()` on
779
+ * every handle returned by {@link injectFailure}, plus a defensive
780
+ * reset for tests that re-use a simulator across cases.
781
+ */
782
+ clearFaults() {
783
+ this.faults.length = 0;
784
+ }
785
+ /**
786
+ * Internal: checks the registered faults for a match on the given URL
787
+ * and consumes one if it should fire. Called from
788
+ * {@link SimulatorTransport.send} before any real handler runs.
789
+ *
790
+ * @param url - The request URL to match against each fault's `on`
791
+ * substring.
792
+ *
793
+ * @returns The fault to apply, or `null` if no fault should fire.
794
+ *
795
+ * @internal
796
+ */
797
+ consumeMatchingFault(url) {
798
+ for (let i = 0; i < this.faults.length; i++) {
799
+ const fault = this.faults[i];
800
+ if (!url.includes(fault.spec.on)) continue;
801
+ if (fault.remainingSkip > 0) {
802
+ fault.remainingSkip -= 1;
803
+ continue;
804
+ }
805
+ if (fault.remainingCount <= 0) continue;
806
+ fault.remainingCount -= 1;
807
+ if (fault.remainingCount <= 0) this.faults.splice(i, 1);
808
+ return fault.spec;
809
+ }
810
+ return null;
811
+ }
812
+ /**
813
+ * Dispatches a JSON API request to the appropriate handler.
814
+ * @param _method - The HTTP method (unused).
815
+ * @param origin - The request URL origin used for simulator-issued endpoints.
816
+ * @param path - The request URL path containing the B2 endpoint name.
817
+ * @param headers - The HTTP request headers; consulted by the
818
+ * strict-auth gate to look up the issued auth token.
819
+ * @param body - The parsed JSON request body.
820
+ *
821
+ * @returns An object with HTTP status and JSON response body.
822
+ */
823
+ async handleRequest(_method, origin, path, headers, body) {
824
+ const endpoint = path.split("/").pop() ?? "";
825
+ const apiVersion = path.match(/\/b2api\/(v\d+)\//)?.[1] ?? "v3";
826
+ if (this.strictAuth) {
827
+ const authError = this.authorizeRequest(headers["authorization"], endpoint, this.requestScope(endpoint, body));
828
+ if (authError !== null) return authError;
829
+ }
830
+ switch (endpoint) {
831
+ case "b2_authorize_account": return this.authorize(headers["authorization"], origin);
832
+ case "b2_create_bucket": return this.createBucket(body);
833
+ case "b2_list_buckets": return this.listBuckets(body);
834
+ case "b2_delete_bucket": return this.deleteBucket(body);
835
+ case "b2_update_bucket": return this.updateBucket(body);
836
+ case "b2_get_upload_url": return await this.getUploadUrl(body, headers["authorization"]);
837
+ case "b2_list_file_names": return this.listFileNames(body);
838
+ case "b2_list_file_versions": return this.listFileVersions(body);
839
+ case "b2_get_file_info": return this.getFileInfo(body);
840
+ case "b2_hide_file": return this.hideFile(body);
841
+ case "b2_delete_file_version": return this.deleteFileVersion(body);
842
+ case "b2_copy_file": return await this.copyFile(body);
843
+ case "b2_start_large_file": return this.startLargeFile(body);
844
+ case "b2_get_upload_part_url": return await this.getUploadPartUrl(body, headers["authorization"]);
845
+ case "b2_finish_large_file": return this.finishLargeFile(body);
846
+ case "b2_cancel_large_file": return this.cancelLargeFile(body);
847
+ case "b2_list_unfinished_large_files": return this.listUnfinishedLargeFiles(body);
848
+ case "b2_list_parts": return this.listParts(body);
849
+ case "b2_copy_part": return await this.copyPart(body);
850
+ case "b2_get_download_authorization": return this.getDownloadAuthorization(body);
851
+ case "b2_create_key": return this.createKey(body, apiVersion);
852
+ case "b2_list_keys": return this.listKeys(body);
853
+ case "b2_delete_key": return this.deleteKey(body);
854
+ case "b2_update_file_retention": return this.updateFileRetention(body);
855
+ case "b2_update_file_legal_hold": return this.updateFileLegalHold(body);
856
+ case "b2_get_bucket_notification_rules": return this.getBucketNotificationRules(body);
857
+ case "b2_set_bucket_notification_rules": return this.setBucketNotificationRules(body);
858
+ default: return {
859
+ status: 400,
860
+ body: {
861
+ status: 400,
862
+ code: "bad_request",
863
+ message: `Unknown endpoint: ${endpoint}`
864
+ }
865
+ };
866
+ }
867
+ }
868
+ /**
869
+ * Handles file and part upload requests (`b2_upload_file`, `b2_upload_part`).
870
+ * Dispatches to the appropriate internal handler based on the URL.
871
+ * @param url - The upload endpoint URL used to determine the upload type.
872
+ * @param headers - The HTTP headers containing file metadata and authorization.
873
+ * @param data - The raw file or part content as bytes.
874
+ *
875
+ * @returns A promise resolving to an object with HTTP status and JSON response body.
876
+ */
877
+ async handleUpload(url, headers, data) {
878
+ const endpoint = new URL(url).pathname.split("/").pop() ?? "";
879
+ const kind = endpoint === "b2_upload_file" ? "file" : endpoint === "b2_upload_part" ? "part" : null;
880
+ if (kind === null) return this.error(400, "bad_request", `Unknown upload endpoint: ${endpoint}`);
881
+ const fileName = kind === "part" || headers["x-bz-file-name"] === void 0 ? void 0 : decodeHeaderValue(headers["x-bz-file-name"]);
882
+ const authError = await this.validateUploadAuthorization(kind, url, headers["authorization"], fileName);
883
+ if (authError !== null) return authError;
884
+ if (kind === "part") return await this.handleUploadPart(url, headers, data);
885
+ return await this.handleUploadFile(url, headers, data);
886
+ }
887
+ /**
888
+ * Handles file download requests (`b2_download_file_by_id`, `/file/` by name).
889
+ * Returns the file data along with B2 response headers.
890
+ * @param path - The request URL path identifying the file to download.
891
+ * @param headers - The HTTP request headers for range or authorization.
892
+ * @param method - The HTTP method; `'HEAD'` suppresses the response body.
893
+ *
894
+ * @returns The download response containing file data and B2 headers.
895
+ */
896
+ handleDownload(path, headers, method = "GET") {
897
+ if (path.includes("b2_download_file_by_id")) {
898
+ if (this.strictAuth) {
899
+ const url = new URL(`http://localhost${path}`);
900
+ const authError = this.authorizeRequest(headers["authorization"], "b2_download_file_by_id", this.fileIdScope(url.searchParams.get("fileId") ?? void 0) ?? {
901
+ bucketIds: [],
902
+ requiresBucketScope: true
903
+ });
904
+ if (authError !== null) return this.errorAsDownload(authError);
905
+ }
906
+ const url = new URL(`http://localhost${path}`);
907
+ const fileId = url.searchParams.get("fileId") ?? "";
908
+ return this.finalizeDownload(this.downloadById(fileId, headers["range"]), url, method);
909
+ }
910
+ const fileMatch = path.match(/^([^?]+)/)?.[1]?.match(/\/file\/([^/]+)\/(.+)/);
911
+ if (fileMatch) {
912
+ const bucketName = decodeURIComponent(fileMatch[1] ?? "");
913
+ const fileName = decodeURIComponent(fileMatch[2] ?? "");
914
+ if (this.strictAuth) {
915
+ const bucket = [...this.buckets.values()].find((b) => b.info.bucketName === bucketName);
916
+ const authError = this.authorizeRequest(headers["authorization"], "b2_download_file_by_name", {
917
+ bucketIds: bucket === void 0 ? [] : [bucket.info.bucketId],
918
+ fileNames: [fileName],
919
+ requiresBucketScope: true
920
+ });
921
+ if (authError !== null) return this.errorAsDownload(authError);
922
+ }
923
+ const url = new URL(`http://localhost${path}`);
924
+ return this.finalizeDownload(this.downloadByName(bucketName, fileName, headers["range"]), url, method);
925
+ }
926
+ return {
927
+ status: 404,
928
+ headers: {},
929
+ data: null
930
+ };
931
+ }
932
+ /**
933
+ * Convert a synthetic JSON error body into a `SimulatorDownloadResponse`
934
+ * shape so the strict-auth gate on download paths can surface 401/403s
935
+ * through the same transport plumbing as a regular failed download.
936
+ *
937
+ * @param json - The JSON error from {@link authorizeRequest}.
938
+ *
939
+ * @returns A download-shaped response with the error body bytes inline.
940
+ */
941
+ errorAsDownload(json) {
942
+ return {
943
+ status: json.status,
944
+ headers: { "Content-Type": "application/json" },
945
+ data: utf8Encoder.encode(JSON.stringify(json.body))
946
+ };
947
+ }
948
+ /**
949
+ * Applies HEAD-method body suppression and `b2Content*` response-header
950
+ * overrides parsed from the download URL's query string. Mirrors what the
951
+ * real B2 service does: any `b2Content*` query parameter is echoed back as
952
+ * the corresponding response header.
953
+ *
954
+ * @param response - The download response produced by {@link downloadById} or {@link downloadByName}.
955
+ * @param url - The parsed download URL (used to read `b2Content*` query params).
956
+ * @param method - The HTTP method of the originating request.
957
+ *
958
+ * @returns The response with overrides applied.
959
+ */
960
+ finalizeDownload(response, url, method) {
961
+ const overrideMap = {
962
+ b2ContentDisposition: "Content-Disposition",
963
+ b2ContentLanguage: "Content-Language",
964
+ b2ContentEncoding: "Content-Encoding",
965
+ b2ContentType: "Content-Type",
966
+ b2CacheControl: "Cache-Control",
967
+ b2Expires: "Expires"
968
+ };
969
+ const newHeaders = { ...response.headers };
970
+ for (const [param, header] of Object.entries(overrideMap)) {
971
+ const value = url.searchParams.get(param);
972
+ if (value !== null) newHeaders[header] = value;
973
+ }
974
+ const data = method === "HEAD" ? null : response.data;
975
+ return {
976
+ status: response.status,
977
+ headers: newHeaders,
978
+ data
979
+ };
980
+ }
981
+ async handleUploadFile(url, headers, data) {
982
+ const bucketId = new URL(url).searchParams.get("bucketId");
983
+ if (!bucketId) return this.error(400, "bad_request", "Missing bucketId");
984
+ const bucket = this.buckets.get(bucketId);
985
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
986
+ const fileName = decodeHeaderValue(headers["x-bz-file-name"] ?? "");
987
+ const contentType = headers["content-type"] ?? "application/octet-stream";
988
+ const fileNameError = validateFileName(fileName);
989
+ if (fileNameError) return this.error(400, fileNameError.code, fileNameError.message);
990
+ const fileInfo = parseFileInfoHeaders(headers);
991
+ const fileInfoError = validateFileInfo(fileInfo);
992
+ if (fileInfoError) return this.error(400, fileInfoError.code, fileInfoError.message);
993
+ const resolved = await this.resolveUploadSha1(headers["x-bz-content-sha1"], data);
994
+ if ("status" in resolved) return resolved;
995
+ const { sha1: contentSha1, data: storedData } = resolved;
996
+ const fileVersion = this.makeFileVersion({
997
+ bucketId,
998
+ fileName,
999
+ contentType,
1000
+ contentLength: storedData.byteLength,
1001
+ contentSha1,
1002
+ fileInfo,
1003
+ action: FileAction.Upload,
1004
+ serverSideEncryption: uploadServerSideEncryption(headers, bucket.info.defaultServerSideEncryption)
1005
+ });
1006
+ const stored = {
1007
+ fileVersion,
1008
+ data: storedData
1009
+ };
1010
+ const existing = bucket.files.get(fileName);
1011
+ if (existing) existing.push(stored);
1012
+ else bucket.files.set(fileName, [stored]);
1013
+ this.firePostUploadHooks(fileVersion, bucketId, "b2:ObjectCreated:Upload");
1014
+ return {
1015
+ status: 200,
1016
+ body: fileVersion
1017
+ };
1018
+ }
1019
+ /**
1020
+ * Resolve the `X-Bz-Content-Sha1` header into the SHA-1 to store, verifying
1021
+ * it against the uploaded bytes where B2 would. Returns the SHA-1 string to
1022
+ * persist, or a `400 bad_request` response when a verifiable hash does not
1023
+ * match the data received.
1024
+ *
1025
+ * @param header - The raw `X-Bz-Content-Sha1` header value, if any.
1026
+ * @param data - The uploaded bytes.
1027
+ *
1028
+ * @returns The SHA-1 string to store, or an error response on mismatch.
1029
+ */
1030
+ async resolveUploadSha1(header, data) {
1031
+ const value = header ?? "none";
1032
+ if (value === "none" || value === "do_not_verify") return {
1033
+ sha1: "none",
1034
+ data
1035
+ };
1036
+ if (value.startsWith("unverified:")) return {
1037
+ sha1: value.slice(11).toLowerCase(),
1038
+ data
1039
+ };
1040
+ if (value === "hex_digits_at_end") {
1041
+ if (data.byteLength < 40) return this.error(400, "bad_request", "Sha1 did not match data received");
1042
+ const body = data.subarray(0, data.byteLength - 40);
1043
+ const trailer = utf8Decoder.decode(data.subarray(data.byteLength - 40)).toLowerCase();
1044
+ const actual = await sha1Hex(body);
1045
+ if (actual !== trailer) return this.error(400, "bad_request", "Sha1 did not match data received");
1046
+ return {
1047
+ sha1: actual,
1048
+ data: body
1049
+ };
1050
+ }
1051
+ const expected = value.toLowerCase();
1052
+ if (await sha1Hex(data) !== expected) return this.error(400, "bad_request", "Sha1 did not match data received");
1053
+ return {
1054
+ sha1: expected,
1055
+ data
1056
+ };
1057
+ }
1058
+ async handleUploadPart(url, headers, data) {
1059
+ const fileId = new URL(url).searchParams.get("fileId");
1060
+ if (!fileId) return this.error(400, "bad_request", "Missing fileId");
1061
+ const large = this.largeFiles.get(fileId);
1062
+ if (!large) return this.error(400, "bad_request", "Large file not found");
1063
+ const partNumber = Number.parseInt(headers["x-bz-part-number"] ?? "0", 10);
1064
+ const resolved = await this.resolveUploadSha1(headers["x-bz-content-sha1"], data);
1065
+ if ("status" in resolved) return resolved;
1066
+ const { sha1, data: partData } = resolved;
1067
+ large.parts.set(partNumber, {
1068
+ data: partData,
1069
+ sha1
1070
+ });
1071
+ return {
1072
+ status: 200,
1073
+ body: {
1074
+ fileId: large.fileId,
1075
+ partNumber,
1076
+ contentLength: partData.byteLength,
1077
+ contentSha1: sha1,
1078
+ serverSideEncryption: publicServerSideEncryption(large.serverSideEncryption),
1079
+ uploadTimestamp: Date.now()
1080
+ }
1081
+ };
1082
+ }
1083
+ downloadById(fileId, range) {
1084
+ const found = this.findFile(fileId);
1085
+ if (found === null) return {
1086
+ status: 404,
1087
+ headers: {},
1088
+ data: null
1089
+ };
1090
+ return this.serveFile(found.stored, range);
1091
+ }
1092
+ downloadByName(bucketName, fileName, range) {
1093
+ for (const bucket of this.buckets.values()) {
1094
+ if (bucket.info.bucketName !== bucketName) continue;
1095
+ const versions = bucket.files.get(fileName);
1096
+ if (!versions || versions.length === 0) break;
1097
+ const latest = versions[versions.length - 1];
1098
+ if (!latest || latest.fileVersion.action === FileAction.Hide) return {
1099
+ status: 404,
1100
+ headers: {},
1101
+ data: null
1102
+ };
1103
+ return this.serveFile(latest, range);
1104
+ }
1105
+ return {
1106
+ status: 404,
1107
+ headers: {},
1108
+ data: null
1109
+ };
1110
+ }
1111
+ serveFile(stored, range) {
1112
+ const fullData = stored.data;
1113
+ let data = fullData;
1114
+ let status = 200;
1115
+ let contentRange = null;
1116
+ if (range) {
1117
+ const parsed = parseRangeHeader(range, fullData.byteLength);
1118
+ if (parsed.kind === "ok") {
1119
+ data = fullData.subarray(parsed.start, parsed.end + 1);
1120
+ status = 206;
1121
+ contentRange = `bytes ${parsed.start}-${parsed.end}/${fullData.byteLength}`;
1122
+ } else if (parsed.kind === "unsatisfiable") return {
1123
+ status: 416,
1124
+ headers: {
1125
+ "Content-Type": stored.fileVersion.contentType,
1126
+ "Content-Range": `bytes */${fullData.byteLength}`
1127
+ },
1128
+ data: /* @__PURE__ */ new Uint8Array(0)
1129
+ };
1130
+ }
1131
+ const fv = stored.fileVersion;
1132
+ const headers = {
1133
+ "Content-Type": fv.contentType,
1134
+ "Content-Length": String(data.byteLength),
1135
+ "X-Bz-File-Id": fv.fileId,
1136
+ "X-Bz-File-Name": encodeFileName(fv.fileName),
1137
+ "X-Bz-Content-Sha1": fv.contentSha1 ?? "none",
1138
+ "X-Bz-Upload-Timestamp": String(fv.uploadTimestamp)
1139
+ };
1140
+ for (const [key, value] of Object.entries(fv.fileInfo)) headers[`X-Bz-Info-${encodeFileName(key)}`] = encodeFileName(value);
1141
+ if (!("src_last_modified_millis" in fv.fileInfo)) headers["X-Bz-Info-src_last_modified_millis"] = String(fv.uploadTimestamp);
1142
+ if (contentRange !== null) headers["Content-Range"] = contentRange;
1143
+ return {
1144
+ status,
1145
+ headers,
1146
+ data
1147
+ };
1148
+ }
1149
+ authorize(authzHeader, origin = "http://localhost:0") {
1150
+ const capabilities = [
1151
+ Capability.ListBuckets,
1152
+ Capability.ReadBuckets,
1153
+ Capability.WriteBuckets,
1154
+ Capability.DeleteBuckets,
1155
+ Capability.ListFiles,
1156
+ Capability.ReadFiles,
1157
+ Capability.WriteFiles,
1158
+ Capability.DeleteFiles,
1159
+ Capability.ListKeys,
1160
+ Capability.WriteKeys,
1161
+ Capability.DeleteKeys,
1162
+ Capability.ShareFiles,
1163
+ Capability.ReadBucketNotifications,
1164
+ Capability.WriteBucketNotifications
1165
+ ];
1166
+ const keyForAuth = this.findKeyForAuthHeader(authzHeader);
1167
+ const allowedBuckets = this.allowedBuckets(keyForAuth?.bucketIds);
1168
+ const legacyBucketId = singleBucketId(keyForAuth?.bucketIds);
1169
+ const legacyBucketName = legacyBucketId === null ? null : this.buckets.get(legacyBucketId)?.info.bucketName ?? null;
1170
+ const tokenStr = `sim_auth_token_${this.nextId++}`;
1171
+ this.issuedTokens.set(tokenStr, {
1172
+ capabilities: keyForAuth?.capabilities ?? capabilities,
1173
+ bucketIds: keyForAuth?.bucketIds ?? null,
1174
+ namePrefix: keyForAuth?.namePrefix ?? null,
1175
+ expiresAt: this.now() + this.authTokenTtlMs,
1176
+ applicationKeyId: keyForAuth?.applicationKeyId ?? null
1177
+ });
1178
+ return {
1179
+ status: 200,
1180
+ body: {
1181
+ accountId: accountId(this.accountId),
1182
+ authorizationToken: tokenStr,
1183
+ apiInfo: { storageApi: {
1184
+ absoluteMinimumPartSize: this.minimumPartSize,
1185
+ apiUrl: origin,
1186
+ bucketId: legacyBucketId === null ? null : bucketId(legacyBucketId),
1187
+ bucketName: legacyBucketName,
1188
+ downloadUrl: origin,
1189
+ infoType: "storageApi",
1190
+ namePrefix: keyForAuth?.namePrefix ?? null,
1191
+ recommendedPartSize: this.recommendedPartSize,
1192
+ s3ApiUrl: origin,
1193
+ allowed: {
1194
+ capabilities: keyForAuth?.capabilities ?? capabilities,
1195
+ buckets: allowedBuckets,
1196
+ bucketId: legacyBucketId === null ? null : bucketId(legacyBucketId),
1197
+ bucketName: legacyBucketName,
1198
+ namePrefix: keyForAuth?.namePrefix ?? null
1199
+ }
1200
+ } },
1201
+ applicationKeyExpirationTimestamp: null
1202
+ }
1203
+ };
1204
+ }
1205
+ createBucket(req) {
1206
+ const nameError = validateBucketName(req.bucketName);
1207
+ if (nameError) return this.error(400, nameError.code, nameError.message);
1208
+ if (req.bucketInfo !== void 0) {
1209
+ const infoError = validateBucketInfo(req.bucketInfo);
1210
+ if (infoError) return this.error(400, infoError.code, infoError.message);
1211
+ }
1212
+ for (const b of this.buckets.values()) if (b.info.bucketName === req.bucketName) return this.error(400, "duplicate_bucket_name", "Bucket name already in use");
1213
+ const bid = bucketId(this.genId("b2_bucket"));
1214
+ const defaultRetention = req.defaultRetention ?? {
1215
+ mode: BucketRetentionMode.None,
1216
+ period: null
1217
+ };
1218
+ const info = {
1219
+ accountId: accountId(req.accountId),
1220
+ bucketId: bid,
1221
+ bucketName: req.bucketName,
1222
+ bucketType: req.bucketType,
1223
+ bucketInfo: req.bucketInfo ?? {},
1224
+ corsRules: req.corsRules ?? [],
1225
+ defaultServerSideEncryption: req.defaultServerSideEncryption ?? { mode: EncryptionMode.None },
1226
+ fileLockConfiguration: {
1227
+ isClientAuthorizedToRead: true,
1228
+ value: {
1229
+ isFileLockEnabled: req.fileLockEnabled ?? false,
1230
+ defaultRetention
1231
+ }
1232
+ },
1233
+ lifecycleRules: req.lifecycleRules ?? [],
1234
+ options: [],
1235
+ revision: 1,
1236
+ defaultRetention,
1237
+ replicationConfiguration: req.replicationConfiguration ?? {
1238
+ asReplicationSource: null,
1239
+ asReplicationDestination: null
1240
+ }
1241
+ };
1242
+ this.buckets.set(bid, {
1243
+ info,
1244
+ files: /* @__PURE__ */ new Map()
1245
+ });
1246
+ return {
1247
+ status: 200,
1248
+ body: info
1249
+ };
1250
+ }
1251
+ listBuckets(req) {
1252
+ return {
1253
+ status: 200,
1254
+ body: { buckets: [...this.buckets.values()].map((b) => b.info).filter((bucket) => req.bucketId === void 0 || bucket.bucketId === req.bucketId).filter((bucket) => req.bucketName === void 0 || bucket.bucketName === req.bucketName).filter((bucket) => req.bucketTypes === void 0 || req.bucketTypes.includes(bucket.bucketType)) }
1255
+ };
1256
+ }
1257
+ deleteBucket(req) {
1258
+ const bucket = this.buckets.get(req.bucketId);
1259
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
1260
+ this.buckets.delete(req.bucketId);
1261
+ return {
1262
+ status: 200,
1263
+ body: bucket.info
1264
+ };
1265
+ }
1266
+ updateBucket(req) {
1267
+ const bucket = this.buckets.get(req["bucketId"]);
1268
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
1269
+ if (req["bucketInfo"] !== void 0) {
1270
+ const infoError = validateBucketInfo(req["bucketInfo"]);
1271
+ if (infoError) return this.error(400, infoError.code, infoError.message);
1272
+ }
1273
+ const updated = {
1274
+ ...bucket.info,
1275
+ ...req["bucketType"] !== void 0 ? { bucketType: req["bucketType"] } : {},
1276
+ ...req["bucketInfo"] !== void 0 ? { bucketInfo: req["bucketInfo"] } : {},
1277
+ ...req["lifecycleRules"] !== void 0 ? { lifecycleRules: req["lifecycleRules"] } : {},
1278
+ ...req["corsRules"] !== void 0 ? { corsRules: req["corsRules"] } : {},
1279
+ ...req["replicationConfiguration"] !== void 0 ? { replicationConfiguration: req["replicationConfiguration"] } : {},
1280
+ ...req["defaultRetention"] !== void 0 ? {
1281
+ defaultRetention: req["defaultRetention"],
1282
+ fileLockConfiguration: {
1283
+ isClientAuthorizedToRead: true,
1284
+ value: {
1285
+ isFileLockEnabled: bucket.info.fileLockConfiguration.value?.isFileLockEnabled ?? false,
1286
+ defaultRetention: req["defaultRetention"]
1287
+ }
1288
+ }
1289
+ } : {},
1290
+ ...req["defaultServerSideEncryption"] !== void 0 ? { defaultServerSideEncryption: req["defaultServerSideEncryption"] } : {},
1291
+ revision: bucket.info.revision + 1
1292
+ };
1293
+ this.buckets.set(req["bucketId"], {
1294
+ info: updated,
1295
+ files: bucket.files
1296
+ });
1297
+ return {
1298
+ status: 200,
1299
+ body: updated
1300
+ };
1301
+ }
1302
+ async getUploadUrl(req, authToken) {
1303
+ if (!this.buckets.get(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1304
+ const uploadAuth = await this.issueUploadAuthorization({
1305
+ kind: "file",
1306
+ sourceAuthToken: authToken,
1307
+ bucketId: req.bucketId
1308
+ });
1309
+ return {
1310
+ status: 200,
1311
+ body: {
1312
+ bucketId: req.bucketId,
1313
+ uploadUrl: uploadAuth.uploadUrl,
1314
+ authorizationToken: uploadAuth.authorizationToken
1315
+ }
1316
+ };
1317
+ }
1318
+ listFileNames(req) {
1319
+ const bucket = this.buckets.get(req.bucketId);
1320
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
1321
+ const countError = validateMaxCount(req.maxFileCount, "b2_list_file_names");
1322
+ if (countError) return this.error(400, countError.code, countError.message);
1323
+ const max = req.maxFileCount ?? 1e3;
1324
+ const prefix = req.prefix ?? "";
1325
+ let allFiles = [...bucket.files.entries()].filter(([name]) => name.startsWith(prefix)).map(([_, versions]) => versions[versions.length - 1]).filter((v) => v !== void 0).map((v) => v.fileVersion).sort((a, b) => compareB2FileNames(a.fileName, b.fileName));
1326
+ if (req.startFileName) {
1327
+ const start = req.startFileName;
1328
+ allFiles = allFiles.filter((f) => f.fileName >= start);
1329
+ }
1330
+ return {
1331
+ status: 200,
1332
+ body: {
1333
+ files: allFiles.slice(0, max),
1334
+ nextFileName: allFiles.length > max ? allFiles[max]?.fileName ?? null : null
1335
+ }
1336
+ };
1337
+ }
1338
+ listFileVersions(req) {
1339
+ const bucket = this.buckets.get(req.bucketId);
1340
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
1341
+ const countError = validateMaxCount(req.maxFileCount, "b2_list_file_versions");
1342
+ if (countError) return this.error(400, countError.code, countError.message);
1343
+ const max = req.maxFileCount ?? 1e3;
1344
+ const prefix = req.prefix ?? "";
1345
+ const allVersions = [...bucket.files.entries()].filter(([name]) => name.startsWith(prefix)).flatMap(([_, versions]) => versions.map((v) => v.fileVersion)).sort((a, b) => {
1346
+ const nameCmp = compareB2FileNames(a.fileName, b.fileName);
1347
+ if (nameCmp !== 0) return nameCmp;
1348
+ return b.uploadTimestamp - a.uploadTimestamp;
1349
+ });
1350
+ let startIdx = 0;
1351
+ if (req.startFileName !== void 0) {
1352
+ const startName = req.startFileName;
1353
+ const startId = req.startFileId;
1354
+ const nameIdx = allVersions.findIndex((f) => f.fileName >= startName);
1355
+ if (nameIdx === -1) startIdx = allVersions.length;
1356
+ else if (startId !== void 0) {
1357
+ const exactIdx = allVersions.findIndex((f, i) => i >= nameIdx && f.fileId === startId);
1358
+ startIdx = exactIdx !== -1 ? exactIdx : nameIdx;
1359
+ } else startIdx = nameIdx;
1360
+ }
1361
+ const sliced = allVersions.slice(startIdx, startIdx + max);
1362
+ const hasMore = startIdx + max < allVersions.length;
1363
+ return {
1364
+ status: 200,
1365
+ body: {
1366
+ files: sliced,
1367
+ nextFileName: hasMore ? allVersions[startIdx + max]?.fileName ?? null : null,
1368
+ nextFileId: hasMore ? allVersions[startIdx + max]?.fileId ?? null : null
1369
+ }
1370
+ };
1371
+ }
1372
+ getFileInfo(req) {
1373
+ const found = this.findFile(req.fileId);
1374
+ if (found === null) return this.error(404, "file_not_present", "File not found");
1375
+ return {
1376
+ status: 200,
1377
+ body: found.stored.fileVersion
1378
+ };
1379
+ }
1380
+ hideFile(req) {
1381
+ const bucket = this.buckets.get(req.bucketId);
1382
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
1383
+ const nameError = validateFileName(req.fileName);
1384
+ if (nameError) return this.error(400, nameError.code, nameError.message);
1385
+ const fileVersion = this.makeFileVersion({
1386
+ bucketId: req.bucketId,
1387
+ fileName: req.fileName,
1388
+ contentType: "application/octet-stream",
1389
+ contentLength: 0,
1390
+ contentSha1: "none",
1391
+ action: FileAction.Hide
1392
+ });
1393
+ const existing = bucket.files.get(req.fileName);
1394
+ const stored = {
1395
+ fileVersion,
1396
+ data: /* @__PURE__ */ new Uint8Array(0)
1397
+ };
1398
+ if (existing) existing.push(stored);
1399
+ else bucket.files.set(req.fileName, [stored]);
1400
+ return {
1401
+ status: 200,
1402
+ body: fileVersion
1403
+ };
1404
+ }
1405
+ deleteFileVersion(req) {
1406
+ const found = this.findFile(req.fileId);
1407
+ if (found === null || found.stored.fileVersion.fileName !== req.fileName) return this.error(400, "file_not_present", "File version not found");
1408
+ const fv = found.stored.fileVersion;
1409
+ const retention = fv.fileRetention?.value;
1410
+ const legalHold = fv.legalHold?.value;
1411
+ const now = Date.now();
1412
+ if (legalHold === "on") return this.error(400, "file_lock_legal_hold_protected", "File is on legal hold and cannot be deleted");
1413
+ if (retention?.mode === "compliance" && retention.retainUntilTimestamp !== null && retention.retainUntilTimestamp > now) return this.error(400, "file_lock_compliance_protected", `File is under compliance-mode retention and cannot be deleted until ${new Date(retention.retainUntilTimestamp).toISOString()}`);
1414
+ if (retention?.mode === "governance" && retention.retainUntilTimestamp !== null && retention.retainUntilTimestamp > now && req.bypassGovernance !== true) return this.error(400, "file_lock_governance_protected", "File is under governance-mode retention; pass bypassGovernance: true to delete");
1415
+ found.versions.splice(found.index, 1);
1416
+ if (found.versions.length === 0) found.bucket.files.delete(req.fileName);
1417
+ return {
1418
+ status: 200,
1419
+ body: {
1420
+ fileId: req.fileId,
1421
+ fileName: req.fileName
1422
+ }
1423
+ };
1424
+ }
1425
+ async copyFile(req) {
1426
+ const nameError = validateFileName(req.fileName);
1427
+ if (nameError) return this.error(400, nameError.code, nameError.message);
1428
+ const found = this.findFile(req.sourceFileId);
1429
+ if (found === null) return this.error(404, "file_not_present", "Source file not found");
1430
+ const sourceStored = found.stored;
1431
+ const destBucketId = req.destinationBucketId ?? found.bucketId;
1432
+ const destBucket = this.buckets.get(destBucketId);
1433
+ if (!destBucket) return this.error(400, "bad_bucket_id", "Destination bucket not found");
1434
+ let data = sourceStored.data;
1435
+ let contentSha1 = sourceStored.fileVersion.contentSha1 ?? "none";
1436
+ if (req.range !== void 0) {
1437
+ const parsed = parseRangeHeader(req.range, sourceStored.data.byteLength);
1438
+ if (parsed.kind === "malformed") return this.error(400, "bad_request", `Malformed copy range: ${req.range}`);
1439
+ if (parsed.kind === "unsatisfiable") return this.error(416, "range_not_satisfiable", `Unsatisfiable copy range: ${req.range}`);
1440
+ data = sourceStored.data.subarray(parsed.start, parsed.end + 1);
1441
+ contentSha1 = await sha1Hex(data);
1442
+ }
1443
+ const directive = req.metadataDirective;
1444
+ if (directive !== void 0 && directive !== "COPY" && directive !== "REPLACE") return this.error(400, "bad_request", `Invalid metadataDirective: ${directive}`);
1445
+ let contentType;
1446
+ let fileInfo;
1447
+ if (directive === "REPLACE") {
1448
+ if (req.contentType === void 0) return this.error(400, "bad_request", "contentType is required when metadataDirective is REPLACE");
1449
+ const replaceFileInfo = req.fileInfo ?? {};
1450
+ const fileInfoError = validateFileInfo(replaceFileInfo);
1451
+ if (fileInfoError) return this.error(400, fileInfoError.code, fileInfoError.message);
1452
+ contentType = req.contentType;
1453
+ fileInfo = replaceFileInfo;
1454
+ } else {
1455
+ if (req.contentType !== void 0 || req.fileInfo !== void 0) return this.error(400, "bad_request", "contentType and fileInfo may only be set when metadataDirective is REPLACE");
1456
+ contentType = sourceStored.fileVersion.contentType;
1457
+ fileInfo = sourceStored.fileVersion.fileInfo;
1458
+ }
1459
+ const fileVersion = this.makeFileVersion({
1460
+ bucketId: destBucketId,
1461
+ fileName: req.fileName,
1462
+ contentType,
1463
+ contentLength: data.byteLength,
1464
+ contentSha1,
1465
+ fileInfo,
1466
+ action: FileAction.Copy
1467
+ });
1468
+ const copied = {
1469
+ fileVersion,
1470
+ data: new Uint8Array(data)
1471
+ };
1472
+ const existing = destBucket.files.get(req.fileName);
1473
+ if (existing) existing.push(copied);
1474
+ else destBucket.files.set(req.fileName, [copied]);
1475
+ this.firePostUploadHooks(fileVersion, destBucketId, "b2:ObjectCreated:Copy");
1476
+ return {
1477
+ status: 200,
1478
+ body: fileVersion
1479
+ };
1480
+ }
1481
+ startLargeFile(req) {
1482
+ const bucket = this.buckets.get(req.bucketId);
1483
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
1484
+ const nameError = validateFileName(req.fileName);
1485
+ if (nameError) return this.error(400, nameError.code, nameError.message);
1486
+ if (req.fileInfo !== void 0) {
1487
+ const infoError = validateFileInfo(req.fileInfo);
1488
+ if (infoError) return this.error(400, infoError.code, infoError.message);
1489
+ }
1490
+ const fid = this.genId("4_z");
1491
+ const uploadTimestamp = this.monotonicTimestamp();
1492
+ const large = {
1493
+ fileId: fid,
1494
+ bucketId: req.bucketId,
1495
+ fileName: req.fileName,
1496
+ contentType: req.contentType,
1497
+ fileInfo: req.fileInfo ?? {},
1498
+ fileRetention: req.fileRetention ?? defaultFileRetention(bucket.info.defaultRetention, uploadTimestamp),
1499
+ legalHold: req.legalHold ?? null,
1500
+ serverSideEncryption: req.serverSideEncryption ?? bucket.info.defaultServerSideEncryption,
1501
+ uploadTimestamp,
1502
+ parts: /* @__PURE__ */ new Map()
1503
+ };
1504
+ this.largeFiles.set(fid, large);
1505
+ return {
1506
+ status: 200,
1507
+ body: {
1508
+ fileId: fid,
1509
+ fileName: req.fileName,
1510
+ accountId: this.accountId,
1511
+ bucketId: req.bucketId,
1512
+ contentType: req.contentType,
1513
+ fileInfo: large.fileInfo,
1514
+ action: FileAction.Start,
1515
+ contentLength: 0,
1516
+ contentSha1: "none",
1517
+ contentMd5: null,
1518
+ fileRetention: {
1519
+ isClientAuthorizedToRead: true,
1520
+ value: large.fileRetention
1521
+ },
1522
+ legalHold: {
1523
+ isClientAuthorizedToRead: true,
1524
+ value: large.legalHold
1525
+ },
1526
+ serverSideEncryption: publicServerSideEncryption(large.serverSideEncryption),
1527
+ uploadTimestamp: large.uploadTimestamp
1528
+ }
1529
+ };
1530
+ }
1531
+ async getUploadPartUrl(req, authToken) {
1532
+ const large = this.largeFiles.get(req.fileId);
1533
+ if (large === void 0) return this.error(400, "bad_request", "Large file not found");
1534
+ const uploadAuth = await this.issueUploadAuthorization({
1535
+ kind: "part",
1536
+ sourceAuthToken: authToken,
1537
+ fileId: req.fileId,
1538
+ fileName: large.fileName
1539
+ });
1540
+ return {
1541
+ status: 200,
1542
+ body: {
1543
+ fileId: req.fileId,
1544
+ uploadUrl: uploadAuth.uploadUrl,
1545
+ authorizationToken: uploadAuth.authorizationToken
1546
+ }
1547
+ };
1548
+ }
1549
+ finishLargeFile(req) {
1550
+ const large = this.largeFiles.get(req.fileId);
1551
+ if (!large) return this.error(400, "bad_request", "Large file not found");
1552
+ const bucket = this.buckets.get(large.bucketId);
1553
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
1554
+ const sortedParts = [...large.parts.entries()].sort((a, b) => a[0] - b[0]);
1555
+ if (sortedParts.length > 1e4) return this.error(400, "bad_request", `multipart upload has ${sortedParts.length} parts; B2 caps at 10000`);
1556
+ for (const [partNumber] of sortedParts) if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > 1e4) return this.error(400, "bad_request", `partNumber ${partNumber} is outside the [1, 10000] range B2 accepts`);
1557
+ if (req.partSha1Array.length !== sortedParts.length) return this.error(400, "bad_request", `partSha1Array has ${req.partSha1Array.length} entries but ${sortedParts.length} parts were uploaded`);
1558
+ for (let i = 0; i < sortedParts.length; i++) {
1559
+ const [partNumber, part] = sortedParts[i];
1560
+ if (req.partSha1Array[i]?.toLowerCase() !== part.sha1) return this.error(400, "bad_request", `part ${partNumber} SHA-1 does not match the uploaded part`);
1561
+ }
1562
+ for (let i = 0; i < sortedParts.length - 1; i++) {
1563
+ const [partNumber, part] = sortedParts[i];
1564
+ if (part.data.byteLength < this.minimumPartSize) return this.error(400, "bad_request", `part ${partNumber} (${part.data.byteLength} bytes) is smaller than the minimum part size of ${this.minimumPartSize}`);
1565
+ }
1566
+ let totalSize = 0;
1567
+ for (const [_, part] of sortedParts) totalSize += part.data.byteLength;
1568
+ const combined = new Uint8Array(totalSize);
1569
+ let offset = 0;
1570
+ for (const [_, part] of sortedParts) {
1571
+ combined.set(part.data, offset);
1572
+ offset += part.data.byteLength;
1573
+ }
1574
+ const fileVersion = this.makeFileVersion({
1575
+ bucketId: large.bucketId,
1576
+ fileName: large.fileName,
1577
+ contentType: large.contentType,
1578
+ contentLength: totalSize,
1579
+ contentSha1: "none",
1580
+ fileInfo: large.fileInfo,
1581
+ action: FileAction.Upload,
1582
+ fileRetention: large.fileRetention,
1583
+ legalHold: large.legalHold,
1584
+ serverSideEncryption: large.serverSideEncryption
1585
+ });
1586
+ const stored = {
1587
+ fileVersion,
1588
+ data: combined
1589
+ };
1590
+ const existing = bucket.files.get(large.fileName);
1591
+ if (existing) existing.push(stored);
1592
+ else bucket.files.set(large.fileName, [stored]);
1593
+ this.largeFiles.delete(req.fileId);
1594
+ this.firePostUploadHooks(fileVersion, large.bucketId, "b2:ObjectCreated:Upload");
1595
+ return {
1596
+ status: 200,
1597
+ body: fileVersion
1598
+ };
1599
+ }
1600
+ cancelLargeFile(req) {
1601
+ const large = this.largeFiles.get(req.fileId);
1602
+ if (!large) return this.error(400, "bad_request", "Large file not found");
1603
+ this.largeFiles.delete(req.fileId);
1604
+ return {
1605
+ status: 200,
1606
+ body: {
1607
+ fileId: large.fileId,
1608
+ accountId: this.accountId,
1609
+ bucketId: large.bucketId,
1610
+ fileName: large.fileName
1611
+ }
1612
+ };
1613
+ }
1614
+ listUnfinishedLargeFiles(req) {
1615
+ const countError = validateMaxCount(req.maxFileCount, "b2_list_unfinished_large_files");
1616
+ if (countError) return this.error(400, countError.code, countError.message);
1617
+ const prefix = req.namePrefix ?? "";
1618
+ const max = req.maxFileCount ?? 100;
1619
+ const candidates = [...this.largeFiles.values()].filter((f) => f.bucketId === req.bucketId).filter((f) => f.fileName.startsWith(prefix)).sort((a, b) => compareB2FileNames(a.fileName, b.fileName));
1620
+ let startIndex = 0;
1621
+ if (req.startFileId !== void 0) {
1622
+ const found = candidates.findIndex((f) => f.fileId === req.startFileId);
1623
+ startIndex = found >= 0 ? found : 0;
1624
+ }
1625
+ return {
1626
+ status: 200,
1627
+ body: {
1628
+ files: candidates.slice(startIndex, startIndex + max).map((f) => ({
1629
+ fileId: f.fileId,
1630
+ fileName: f.fileName,
1631
+ accountId: this.accountId,
1632
+ bucketId: f.bucketId,
1633
+ contentType: f.contentType,
1634
+ action: FileAction.Start,
1635
+ contentLength: 0,
1636
+ contentSha1: "none",
1637
+ contentMd5: null,
1638
+ fileInfo: f.fileInfo,
1639
+ fileRetention: {
1640
+ isClientAuthorizedToRead: true,
1641
+ value: f.fileRetention
1642
+ },
1643
+ legalHold: {
1644
+ isClientAuthorizedToRead: true,
1645
+ value: f.legalHold
1646
+ },
1647
+ serverSideEncryption: publicServerSideEncryption(f.serverSideEncryption),
1648
+ uploadTimestamp: f.uploadTimestamp
1649
+ })),
1650
+ nextFileId: startIndex + max < candidates.length ? candidates[startIndex + max]?.fileId ?? null : null
1651
+ }
1652
+ };
1653
+ }
1654
+ listParts(req) {
1655
+ const large = this.largeFiles.get(req.fileId);
1656
+ if (!large) return this.error(400, "bad_request", "Large file not found");
1657
+ const countError = validateMaxCount(req.maxPartCount, "b2_list_parts");
1658
+ if (countError) return this.error(400, countError.code, countError.message);
1659
+ const start = req.startPartNumber ?? 1;
1660
+ const max = req.maxPartCount ?? 1e3;
1661
+ const allParts = [...large.parts.entries()].filter(([n]) => n >= start).sort((a, b) => a[0] - b[0]).map(([partNumber, part]) => ({
1662
+ fileId: req.fileId,
1663
+ partNumber,
1664
+ contentLength: part.data.byteLength,
1665
+ contentSha1: part.sha1,
1666
+ uploadTimestamp: Date.now()
1667
+ }));
1668
+ return {
1669
+ status: 200,
1670
+ body: {
1671
+ parts: allParts.slice(0, max),
1672
+ nextPartNumber: allParts.length > max ? allParts[max]?.partNumber ?? null : null
1673
+ }
1674
+ };
1675
+ }
1676
+ async copyPart(req) {
1677
+ const large = this.largeFiles.get(req.largeFileId);
1678
+ if (!large) return this.error(400, "bad_request", "Large file not found");
1679
+ const found = this.findFile(req.sourceFileId);
1680
+ if (found === null) return this.error(404, "file_not_present", "Source file not found");
1681
+ const sourceStored = found.stored;
1682
+ let partData = sourceStored.data;
1683
+ if (req.range) {
1684
+ const match = req.range.match(/bytes=(\d+)-(\d+)?/);
1685
+ if (match) {
1686
+ const rs = Number.parseInt(match[1] ?? "0", 10);
1687
+ const re = match[2] !== void 0 ? Number.parseInt(match[2], 10) : sourceStored.data.byteLength - 1;
1688
+ partData = sourceStored.data.slice(rs, re + 1);
1689
+ }
1690
+ }
1691
+ const sha1 = await sha1Hex(partData);
1692
+ large.parts.set(req.partNumber, {
1693
+ data: new Uint8Array(partData),
1694
+ sha1
1695
+ });
1696
+ return {
1697
+ status: 200,
1698
+ body: {
1699
+ fileId: req.largeFileId,
1700
+ partNumber: req.partNumber,
1701
+ contentLength: partData.byteLength,
1702
+ contentSha1: sha1
1703
+ }
1704
+ };
1705
+ }
1706
+ getDownloadAuthorization(req) {
1707
+ if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1708
+ return {
1709
+ status: 200,
1710
+ body: {
1711
+ bucketId: req.bucketId,
1712
+ fileNamePrefix: req.fileNamePrefix,
1713
+ authorizationToken: `sim_dl_auth_${this.genId("tok")}`
1714
+ }
1715
+ };
1716
+ }
1717
+ createKey(req, apiVersion) {
1718
+ if (apiVersion === "v4" && hasOwnField(req, "bucketId")) return this.error(400, "bad_request", "bucketId is not accepted by v4 b2_create_key; use bucketIds");
1719
+ if (apiVersion !== "v4" && req.bucketId !== void 0 && req.bucketIds !== void 0) return this.error(400, "bad_request", "b2_create_key accepts either bucketIds or bucketId");
1720
+ const bucketIds = apiVersion !== "v4" && req.bucketId !== void 0 ? Object.freeze([req.bucketId]) : normalizeKeyBucketIds(req);
1721
+ const namePrefix = req.namePrefix === void 0 || req.namePrefix === "" ? null : req.namePrefix;
1722
+ if (hasKeyManagementCapability(req.capabilities) && (bucketIds !== null || namePrefix !== null)) return this.error(400, "bad_request", "key-management capabilities are account-level and cannot be bucket or name-prefix scoped");
1723
+ const kid = this.genId("sim_key");
1724
+ const appKey = this.genId("sim_secret");
1725
+ const expiration = req.validDurationInSeconds !== void 0 ? Date.now() + req.validDurationInSeconds * 1e3 : null;
1726
+ const stored = {
1727
+ applicationKeyId: kid,
1728
+ keyName: req.keyName,
1729
+ capabilities: req.capabilities,
1730
+ accountId: req.accountId,
1731
+ applicationKey: appKey,
1732
+ bucketIds,
1733
+ namePrefix,
1734
+ expirationTimestamp: expiration
1735
+ };
1736
+ this.keys.set(kid, stored);
1737
+ return {
1738
+ status: 200,
1739
+ body: {
1740
+ keyName: stored.keyName,
1741
+ applicationKeyId: stored.applicationKeyId,
1742
+ applicationKey: stored.applicationKey,
1743
+ capabilities: stored.capabilities,
1744
+ accountId: stored.accountId,
1745
+ expirationTimestamp: stored.expirationTimestamp,
1746
+ bucketIds: cloneBucketIds(stored.bucketIds),
1747
+ bucketId: singleBucketId(stored.bucketIds),
1748
+ namePrefix: stored.namePrefix,
1749
+ options: []
1750
+ }
1751
+ };
1752
+ }
1753
+ listKeys(req) {
1754
+ const countError = validateMaxCount(req.maxKeyCount, "b2_list_keys");
1755
+ if (countError) return this.error(400, countError.code, countError.message);
1756
+ const max = req.maxKeyCount ?? 1e3;
1757
+ let allKeys = [...this.keys.values()].sort((a, b) => a.applicationKeyId.localeCompare(b.applicationKeyId));
1758
+ if (req.startApplicationKeyId) {
1759
+ const start = req.startApplicationKeyId;
1760
+ allKeys = allKeys.filter((k) => k.applicationKeyId >= start);
1761
+ }
1762
+ return {
1763
+ status: 200,
1764
+ body: {
1765
+ keys: allKeys.slice(0, max).map((k) => ({
1766
+ keyName: k.keyName,
1767
+ applicationKeyId: k.applicationKeyId,
1768
+ capabilities: k.capabilities,
1769
+ accountId: k.accountId,
1770
+ expirationTimestamp: k.expirationTimestamp,
1771
+ bucketIds: cloneBucketIds(k.bucketIds),
1772
+ bucketId: singleBucketId(k.bucketIds),
1773
+ namePrefix: k.namePrefix,
1774
+ options: []
1775
+ })),
1776
+ nextApplicationKeyId: allKeys.length > max ? allKeys[max]?.applicationKeyId ?? null : null
1777
+ }
1778
+ };
1779
+ }
1780
+ deleteKey(req) {
1781
+ const key = this.keys.get(req.applicationKeyId);
1782
+ if (!key) return this.error(400, "bad_request", "Key not found");
1783
+ this.keys.delete(req.applicationKeyId);
1784
+ for (const [token, scope] of this.issuedTokens.entries()) if (scope.applicationKeyId === req.applicationKeyId) this.issuedTokens.delete(token);
1785
+ for (const [token, scope] of this.uploadTokens.entries()) if (scope.applicationKeyId === req.applicationKeyId) {
1786
+ scope.invalidated = true;
1787
+ this.uploadTokens.set(token, scope);
1788
+ }
1789
+ return {
1790
+ status: 200,
1791
+ body: {
1792
+ keyName: key.keyName,
1793
+ applicationKeyId: key.applicationKeyId,
1794
+ capabilities: key.capabilities,
1795
+ accountId: key.accountId,
1796
+ expirationTimestamp: key.expirationTimestamp,
1797
+ bucketIds: cloneBucketIds(key.bucketIds),
1798
+ bucketId: singleBucketId(key.bucketIds),
1799
+ namePrefix: key.namePrefix,
1800
+ options: []
1801
+ }
1802
+ };
1803
+ }
1804
+ updateFileRetention(req) {
1805
+ const found = this.findFile(req.fileId);
1806
+ if (found === null || found.stored.fileVersion.fileName !== req.fileName) return this.error(404, "file_not_present", "File not found");
1807
+ found.versions[found.index] = {
1808
+ fileVersion: {
1809
+ ...found.stored.fileVersion,
1810
+ fileRetention: {
1811
+ isClientAuthorizedToRead: true,
1812
+ value: req.fileRetention
1813
+ }
1814
+ },
1815
+ data: found.stored.data
1816
+ };
1817
+ return {
1818
+ status: 200,
1819
+ body: {
1820
+ fileName: req.fileName,
1821
+ fileId: req.fileId,
1822
+ fileRetention: req.fileRetention
1823
+ }
1824
+ };
1825
+ }
1826
+ updateFileLegalHold(req) {
1827
+ const found = this.findFile(req.fileId);
1828
+ if (found === null || found.stored.fileVersion.fileName !== req.fileName) return this.error(404, "file_not_present", "File not found");
1829
+ found.versions[found.index] = {
1830
+ fileVersion: {
1831
+ ...found.stored.fileVersion,
1832
+ legalHold: {
1833
+ isClientAuthorizedToRead: true,
1834
+ value: req.legalHold
1835
+ }
1836
+ },
1837
+ data: found.stored.data
1838
+ };
1839
+ return {
1840
+ status: 200,
1841
+ body: {
1842
+ fileName: req.fileName,
1843
+ fileId: req.fileId,
1844
+ legalHold: req.legalHold
1845
+ }
1846
+ };
1847
+ }
1848
+ getBucketNotificationRules(req) {
1849
+ if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1850
+ const rules = this.notificationRules.get(req.bucketId) ?? [];
1851
+ return {
1852
+ status: 200,
1853
+ body: {
1854
+ bucketId: req.bucketId,
1855
+ eventNotificationRules: rules
1856
+ }
1857
+ };
1858
+ }
1859
+ setBucketNotificationRules(req) {
1860
+ if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1861
+ this.notificationRules.set(req.bucketId, req.eventNotificationRules);
1862
+ return {
1863
+ status: 200,
1864
+ body: {
1865
+ bucketId: req.bucketId,
1866
+ eventNotificationRules: req.eventNotificationRules
1867
+ }
1868
+ };
1869
+ }
1870
+ /**
1871
+ * Locates a stored file version by its `fileId`, scanning every bucket.
1872
+ *
1873
+ * Returns enough context to support read-only inspection (`stored`,
1874
+ * `bucketId`) AND in-place mutation (`versions`, `index`) so callers
1875
+ * that need to splice the version out can do so without re-scanning.
1876
+ *
1877
+ * Real B2 fileIds embed the bucketId, so production lookups are O(1);
1878
+ * the simulator's flat ID generator (`this.genId('4_z')`) doesn't, so this
1879
+ * is O(buckets × files × versions). Acceptable for tests.
1880
+ *
1881
+ * @param fileId - The file version ID to locate.
1882
+ *
1883
+ * @returns The location of the matching version, or `null` if not found.
1884
+ */
1885
+ findFile(fileId) {
1886
+ for (const [bid, bucket] of this.buckets.entries()) for (const versions of bucket.files.values()) {
1887
+ const idx = versions.findIndex((v) => v.fileVersion.fileId === fileId);
1888
+ if (idx !== -1) return {
1889
+ stored: versions[idx],
1890
+ bucketId: bid,
1891
+ bucket,
1892
+ versions,
1893
+ index: idx
1894
+ };
1895
+ }
1896
+ return null;
1897
+ }
1898
+ makeFileVersion(params) {
1899
+ return {
1900
+ accountId: accountId(this.accountId),
1901
+ action: params.action,
1902
+ bucketId: bucketId(params.bucketId),
1903
+ contentLength: params.contentLength,
1904
+ contentMd5: null,
1905
+ contentSha1: params.contentSha1,
1906
+ contentType: params.contentType,
1907
+ fileId: fileId(this.genId("4_z")),
1908
+ fileInfo: params.fileInfo ?? {},
1909
+ fileName: params.fileName,
1910
+ fileRetention: {
1911
+ isClientAuthorizedToRead: true,
1912
+ value: params.fileRetention ?? null
1913
+ },
1914
+ legalHold: {
1915
+ isClientAuthorizedToRead: true,
1916
+ value: params.legalHold ?? null
1917
+ },
1918
+ replicationStatus: null,
1919
+ serverSideEncryption: publicServerSideEncryption(params.serverSideEncryption ?? { mode: EncryptionMode.None }),
1920
+ uploadTimestamp: this.monotonicTimestamp()
1921
+ };
1922
+ }
1923
+ error(status, code, message) {
1924
+ return {
1925
+ status,
1926
+ body: {
1927
+ status,
1928
+ code,
1929
+ message
1930
+ }
1931
+ };
1932
+ }
1933
+ /**
1934
+ * Fire the pluggable post-upload hooks for a file that just landed in
1935
+ * a bucket: matching event-notification rules → `onWebhookDeliver`,
1936
+ * configured replication source rules → `onReplicate`. Errors thrown
1937
+ * from user-supplied hooks are swallowed so a buggy listener never
1938
+ * masks an otherwise-successful API response.
1939
+ *
1940
+ * Fired-and-forgotten (no await) by the handler so the synthetic
1941
+ * response is returned to the caller as fast as production B2 would
1942
+ * acknowledge the write.
1943
+ *
1944
+ * @param fileVersion - The freshly-stored file metadata.
1945
+ * @param bucketId - The bucket the upload landed in.
1946
+ * @param eventType - The B2 event-type tag (e.g. `'b2:ObjectCreated:Upload'`)
1947
+ * used to match against `EventNotificationRule.eventTypes` globs.
1948
+ */
1949
+ firePostUploadHooks(fileVersion, bucketId, eventType) {
1950
+ const bucket = this.buckets.get(bucketId);
1951
+ if (!bucket) return;
1952
+ if (this.onWebhookDeliver !== void 0) {
1953
+ const rules = this.notificationRules.get(bucketId) ?? [];
1954
+ for (const rule of rules) {
1955
+ if (!rule.isEnabled) continue;
1956
+ if (!rule.eventTypes.some((pattern) => eventTypeMatches(pattern, eventType))) continue;
1957
+ const hook = this.onWebhookDeliver;
1958
+ this.dispatchHook("webhook", () => hook({
1959
+ rule,
1960
+ fileVersion,
1961
+ bucketId
1962
+ }));
1963
+ }
1964
+ }
1965
+ if (this.onReplicate !== void 0) {
1966
+ const sourceRules = bucket.info.replicationConfiguration.asReplicationSource?.replicationRules ?? [];
1967
+ for (const rule of sourceRules) {
1968
+ if (!rule.isEnabled) continue;
1969
+ if (rule.fileNamePrefix && !fileVersion.fileName.startsWith(rule.fileNamePrefix)) continue;
1970
+ const hook = this.onReplicate;
1971
+ this.dispatchHook("replication", () => hook({
1972
+ sourceFileVersion: fileVersion,
1973
+ sourceBucketId: bucketId,
1974
+ destinationBucketId: rule.destinationBucketId
1975
+ }));
1976
+ }
1977
+ }
1978
+ }
1979
+ /**
1980
+ * Schedule a user-supplied hook callback. Errors are routed to
1981
+ * `onHookError` if configured, swallowed otherwise. The returned
1982
+ * promise is tracked in {@link pendingHooks} so `flushHooks()` can
1983
+ * wait for every dispatched hook to settle.
1984
+ *
1985
+ * @param kind - Which hook this is (`'webhook'` or `'replication'`).
1986
+ * @param fn - Thunk that performs the hook invocation.
1987
+ */
1988
+ dispatchHook(kind, fn) {
1989
+ const task = Promise.resolve().then(() => fn()).catch((err) => {
1990
+ if (this.onHookError !== void 0) this.onHookError({
1991
+ kind,
1992
+ error: toError(err)
1993
+ });
1994
+ }).finally(() => {
1995
+ this.pendingHooks.delete(task);
1996
+ });
1997
+ this.pendingHooks.add(task);
1998
+ }
1999
+ };
2000
+ /**
2001
+ * Module-local cache of compiled glob regexes. Avoids recompiling the
2002
+ * same `eventTypes` pattern on every upload's hook dispatch — patterns
2003
+ * are stable for the lifetime of a `setBucketNotificationRules` call
2004
+ * and typically reused across thousands of uploads.
2005
+ */
2006
+ var eventTypeRegexCache = /* @__PURE__ */ new Map();
2007
+ /**
2008
+ * Wildcard match for B2 event-type globs. Supports the prefix-glob form
2009
+ * the B2 docs document: `b2:ObjectCreated:*` matches
2010
+ * `b2:ObjectCreated:Upload`, `b2:ObjectCreated:Copy`, etc. Exact
2011
+ * matches without `*` match literally.
2012
+ *
2013
+ * @param pattern - Glob from an `EventNotificationRule.eventTypes` entry.
2014
+ * @param eventType - Concrete event type produced by the simulator.
2015
+ *
2016
+ * @returns `true` when the pattern matches the event type.
2017
+ */
1434
2018
  function eventTypeMatches(pattern, eventType) {
1435
- if (!pattern.includes("*")) return pattern === eventType;
1436
- let compiled = eventTypeRegexCache.get(pattern);
1437
- if (compiled === void 0) {
1438
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
1439
- compiled = new RegExp(`^${escaped}$`);
1440
- eventTypeRegexCache.set(pattern, compiled);
1441
- }
1442
- return compiled.test(eventType);
2019
+ if (!pattern.includes("*")) return pattern === eventType;
2020
+ let compiled = eventTypeRegexCache.get(pattern);
2021
+ if (compiled === void 0) {
2022
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
2023
+ compiled = new RegExp(`^${escaped}$`);
2024
+ eventTypeRegexCache.set(pattern, compiled);
2025
+ }
2026
+ return compiled.test(eventType);
1443
2027
  }
2028
+ /**
2029
+ * Build a synthetic {@link HttpResponse} from a consumed {@link FaultSpec}.
2030
+ * Mirrors the shape of real B2 error responses so the SDK's
2031
+ * `RetryTransport` / `classifyError` paths see realistic input.
2032
+ *
2033
+ * @param fault - The fault spec to render.
2034
+ *
2035
+ * @returns An `HttpResponse` ready to return from `transport.send`.
2036
+ */
1444
2037
  function buildFaultResponse(fault) {
1445
- const status = fault.status ?? 503;
1446
- const code = fault.code ?? "service_unavailable";
1447
- const message = fault.message ?? "simulated failure";
1448
- const body = JSON.stringify({ status, code, message });
1449
- const headers = new Headers({ "Content-Type": "application/json" });
1450
- if (fault.retryAfter !== void 0) {
1451
- headers.set("Retry-After", String(fault.retryAfter));
1452
- }
1453
- return {
1454
- status,
1455
- headers,
1456
- body: new ReadableStream({
1457
- start(controller) {
1458
- controller.enqueue(utf8Encoder.encode(body));
1459
- controller.close();
1460
- }
1461
- }),
1462
- json: () => Promise.resolve(JSON.parse(body)),
1463
- text: () => Promise.resolve(body),
1464
- arrayBuffer: () => Promise.resolve(utf8Encoder.encode(body).buffer)
1465
- };
1466
- }
1467
- class SimulatorTransport {
1468
- constructor(sim) {
1469
- this.sim = sim;
1470
- }
1471
- async send(request) {
1472
- const url = request.url;
1473
- const fault = this.sim.consumeMatchingFault(url);
1474
- if (fault !== null) {
1475
- return buildFaultResponse(fault);
1476
- }
1477
- const headers = {};
1478
- if (request.headers) {
1479
- for (const [k, v] of Object.entries(request.headers)) {
1480
- headers[k.toLowerCase()] = v;
1481
- }
1482
- }
1483
- const isUpload = url.includes("b2_upload_file") || url.includes("b2_upload_part");
1484
- const parsedUrl = new URL(url);
1485
- const isDownload = parsedUrl.pathname.includes("b2_download_file_by_id") || parsedUrl.pathname.includes("/file/");
1486
- if (isDownload) {
1487
- const method = request.method === "HEAD" ? "HEAD" : "GET";
1488
- const result2 = this.sim.handleDownload(parsedUrl.pathname + parsedUrl.search, headers, method);
1489
- const data = result2.data ?? new Uint8Array(0);
1490
- const responseHeaders = new Headers(result2.headers);
1491
- responseHeaders.set(
1492
- "Content-Type",
1493
- result2.headers["Content-Type"] ?? "application/octet-stream"
1494
- );
1495
- const body = method === "HEAD" || result2.data === null ? null : new ReadableStream({
1496
- start(controller) {
1497
- controller.enqueue(data);
1498
- controller.close();
1499
- }
1500
- });
1501
- return {
1502
- status: result2.status,
1503
- headers: responseHeaders,
1504
- body,
1505
- json: () => Promise.reject(new Error("Download response is not JSON")),
1506
- text: () => Promise.resolve(utf8Decoder.decode(data)),
1507
- arrayBuffer: () => Promise.resolve(
1508
- data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
1509
- )
1510
- };
1511
- }
1512
- let result;
1513
- if (isUpload && request.body) {
1514
- const data = new Uint8Array(
1515
- request.body instanceof ArrayBuffer ? request.body : request.body instanceof Uint8Array ? request.body.buffer.slice(
1516
- request.body.byteOffset,
1517
- request.body.byteOffset + request.body.byteLength
1518
- ) : await new Response(request.body).arrayBuffer()
1519
- );
1520
- result = this.sim.handleUpload(url, headers, data);
1521
- } else {
1522
- let body = null;
1523
- if (request.body) {
1524
- const text = typeof request.body === "string" ? request.body : await new Response(request.body).text();
1525
- try {
1526
- body = JSON.parse(text);
1527
- } catch {
1528
- body = text;
1529
- }
1530
- }
1531
- result = await this.sim.handleRequest(request.method, parsedUrl.pathname, headers, body);
1532
- }
1533
- const responseBody = JSON.stringify(result.body);
1534
- return {
1535
- status: result.status,
1536
- headers: new Headers({ "Content-Type": "application/json" }),
1537
- body: new ReadableStream({
1538
- start(controller) {
1539
- controller.enqueue(utf8Encoder.encode(responseBody));
1540
- controller.close();
1541
- }
1542
- }),
1543
- json: () => Promise.resolve(result.body),
1544
- text: () => Promise.resolve(responseBody),
1545
- arrayBuffer: () => Promise.resolve(utf8Encoder.encode(responseBody).buffer)
1546
- };
1547
- }
2038
+ const status = fault.status ?? 503;
2039
+ const code = fault.code ?? "service_unavailable";
2040
+ const message = fault.message ?? "simulated failure";
2041
+ const body = JSON.stringify({
2042
+ status,
2043
+ code,
2044
+ message
2045
+ });
2046
+ const headers = new Headers({ "Content-Type": "application/json" });
2047
+ if (fault.retryAfter !== void 0) headers.set("Retry-After", String(fault.retryAfter));
2048
+ return {
2049
+ status,
2050
+ headers,
2051
+ body: new ReadableStream({ start(controller) {
2052
+ controller.enqueue(utf8Encoder.encode(body));
2053
+ controller.close();
2054
+ } }),
2055
+ json: () => Promise.resolve(JSON.parse(body)),
2056
+ text: () => Promise.resolve(body),
2057
+ arrayBuffer: () => Promise.resolve(utf8Encoder.encode(body).buffer)
2058
+ };
1548
2059
  }
1549
- export {
1550
- B2Simulator,
1551
- BUCKET_INFO_MAX_KEYS,
1552
- BUCKET_INFO_VALUE_MAX,
1553
- BUCKET_NAME_MAX,
1554
- BUCKET_NAME_MIN,
1555
- FILE_INFO_TOTAL_MAX,
1556
- FILE_INFO_VALUE_MAX,
1557
- FILE_NAME_MAX_BYTES,
1558
- LIST_ENDPOINT_CAPS
2060
+ var SimulatorTransport = class {
2061
+ sim;
2062
+ constructor(sim) {
2063
+ this.sim = sim;
2064
+ }
2065
+ async send(request) {
2066
+ const url = request.url;
2067
+ const fault = this.sim.consumeMatchingFault(url);
2068
+ if (fault !== null) return buildFaultResponse(fault);
2069
+ const headers = {};
2070
+ if (request.headers) for (const [k, v] of Object.entries(request.headers)) headers[k.toLowerCase()] = v;
2071
+ const parsedUrl = new URL(url);
2072
+ const endpoint = parsedUrl.pathname.split("/").pop() ?? "";
2073
+ const isUpload = endpoint === "b2_upload_file" || endpoint === "b2_upload_part";
2074
+ if (parsedUrl.pathname.includes("b2_download_file_by_id") || parsedUrl.pathname.includes("/file/")) {
2075
+ const method = request.method === "HEAD" ? "HEAD" : "GET";
2076
+ const result = this.sim.handleDownload(parsedUrl.pathname + parsedUrl.search, headers, method);
2077
+ const data = result.data ?? /* @__PURE__ */ new Uint8Array(0);
2078
+ const responseHeaders = new Headers(result.headers);
2079
+ responseHeaders.set("Content-Type", result.headers["Content-Type"] ?? "application/octet-stream");
2080
+ const body = method === "HEAD" || result.data === null ? null : new ReadableStream({ start(controller) {
2081
+ controller.enqueue(data);
2082
+ controller.close();
2083
+ } });
2084
+ return {
2085
+ status: result.status,
2086
+ headers: responseHeaders,
2087
+ body,
2088
+ json: () => Promise.reject(/* @__PURE__ */ new Error("Download response is not JSON")),
2089
+ text: () => Promise.resolve(utf8Decoder.decode(data)),
2090
+ arrayBuffer: () => Promise.resolve(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength))
2091
+ };
2092
+ }
2093
+ let result;
2094
+ if (isUpload && request.body) {
2095
+ const data = new Uint8Array(request.body instanceof ArrayBuffer ? request.body : request.body instanceof Uint8Array ? request.body.buffer.slice(request.body.byteOffset, request.body.byteOffset + request.body.byteLength) : await new Response(request.body).arrayBuffer());
2096
+ result = await this.sim.handleUpload(url, headers, data);
2097
+ } else {
2098
+ let body = null;
2099
+ if (request.body) {
2100
+ const text = typeof request.body === "string" ? request.body : await new Response(request.body).text();
2101
+ try {
2102
+ body = JSON.parse(text);
2103
+ } catch {
2104
+ body = text;
2105
+ }
2106
+ }
2107
+ result = await this.sim.handleRequest(request.method, parsedUrl.origin, parsedUrl.pathname, headers, body);
2108
+ }
2109
+ const responseBody = JSON.stringify(result.body);
2110
+ return {
2111
+ status: result.status,
2112
+ headers: new Headers({ "Content-Type": "application/json" }),
2113
+ body: new ReadableStream({ start(controller) {
2114
+ controller.enqueue(utf8Encoder.encode(responseBody));
2115
+ controller.close();
2116
+ } }),
2117
+ json: () => Promise.resolve(result.body),
2118
+ text: () => Promise.resolve(responseBody),
2119
+ arrayBuffer: () => Promise.resolve(utf8Encoder.encode(responseBody).buffer)
2120
+ };
2121
+ }
1559
2122
  };
1560
- //# sourceMappingURL=index.js.map
2123
+ //#endregion
2124
+ export { B2Simulator, BUCKET_INFO_MAX_KEYS, BUCKET_INFO_VALUE_MAX, BUCKET_NAME_MAX, BUCKET_NAME_MIN, FILE_INFO_TOTAL_MAX, FILE_INFO_VALUE_MAX, FILE_NAME_MAX_BYTES, LIST_ENDPOINT_CAPS };
2125
+
2126
+ //# sourceMappingURL=index.js.map