@narumitw/pi-sync 0.59.0 → 0.60.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 (321) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +19 -10
  3. package/dist/chunks/{chunk-AMJRUXFT.ts → chunk-2JNFEZ3V.ts} +2 -6
  4. package/dist/chunks/{chunk-AMJRUXFT.ts.map → chunk-2JNFEZ3V.ts.map} +1 -1
  5. package/dist/chunks/{chunk-NGW4JMBF.ts → chunk-4RNCZZY7.ts} +33 -27
  6. package/dist/chunks/{chunk-NGW4JMBF.ts.map → chunk-4RNCZZY7.ts.map} +3 -3
  7. package/dist/chunks/{config-J5VZUY4J.ts → chunk-7AC2RX4M.ts} +6 -13
  8. package/dist/chunks/chunk-7AC2RX4M.ts.map +7 -0
  9. package/dist/chunks/{chunk-76HID27T.ts → chunk-BGGKHHO4.ts} +18 -14
  10. package/dist/chunks/{chunk-76HID27T.ts.map → chunk-BGGKHHO4.ts.map} +1 -1
  11. package/dist/chunks/chunk-BWWTOQOW.ts +737 -0
  12. package/dist/chunks/chunk-BWWTOQOW.ts.map +7 -0
  13. package/dist/chunks/chunk-CEMFCWIU.ts +20 -0
  14. package/dist/chunks/chunk-CEMFCWIU.ts.map +7 -0
  15. package/dist/chunks/chunk-CZNBKIM5.ts +20 -0
  16. package/dist/chunks/chunk-CZNBKIM5.ts.map +7 -0
  17. package/dist/chunks/{chunk-YIPK23JW.ts → chunk-ENFHHB5O.ts} +1 -16
  18. package/dist/chunks/{chunk-YIPK23JW.ts.map → chunk-ENFHHB5O.ts.map} +1 -1
  19. package/dist/chunks/{chunk-KHBPED6W.ts → chunk-GSQGBVKG.ts} +2 -2
  20. package/dist/chunks/chunk-HNKLBM3U.ts +18 -0
  21. package/dist/chunks/chunk-HNKLBM3U.ts.map +7 -0
  22. package/dist/chunks/{chunk-QPC5HT3A.ts → chunk-J5COV5TY.ts} +21 -2
  23. package/dist/chunks/chunk-J5COV5TY.ts.map +7 -0
  24. package/dist/chunks/chunk-JKBUYCPC.ts +52 -0
  25. package/dist/chunks/chunk-JKBUYCPC.ts.map +7 -0
  26. package/dist/chunks/chunk-JZKCOM62.ts +26 -0
  27. package/dist/chunks/chunk-JZKCOM62.ts.map +7 -0
  28. package/dist/chunks/chunk-M7RHV3H6.ts +33 -0
  29. package/dist/chunks/chunk-M7RHV3H6.ts.map +7 -0
  30. package/dist/chunks/{chunk-2ZZJXITS.ts → chunk-MIXZVHFR.ts} +24 -10
  31. package/dist/chunks/chunk-MIXZVHFR.ts.map +7 -0
  32. package/dist/chunks/chunk-NPT2G4FU.ts +15 -0
  33. package/dist/chunks/chunk-NPT2G4FU.ts.map +7 -0
  34. package/dist/chunks/chunk-PDBTD2K6.ts +11 -0
  35. package/dist/chunks/chunk-PDBTD2K6.ts.map +7 -0
  36. package/dist/chunks/chunk-UBE6XWOM.ts +29 -0
  37. package/dist/chunks/chunk-UBE6XWOM.ts.map +7 -0
  38. package/dist/chunks/{chunk-PQ75RPUP.ts → chunk-UZUUUY7C.ts} +8 -8
  39. package/dist/chunks/chunk-VZCWYXRS.ts +23 -0
  40. package/dist/chunks/chunk-VZCWYXRS.ts.map +7 -0
  41. package/dist/chunks/{chunk-DTPELCPW.ts → chunk-YWEYRRQI.ts} +45 -37
  42. package/dist/chunks/chunk-YWEYRRQI.ts.map +7 -0
  43. package/dist/chunks/{chunk-ECYCNZOE.ts → chunk-ZMNVNECV.ts} +5 -1
  44. package/dist/chunks/chunk-ZMNVNECV.ts.map +7 -0
  45. package/dist/chunks/{command-handler-SDGKIQH2.ts → command-handler-3O76V7Q5.ts} +80 -86
  46. package/dist/chunks/command-handler-3O76V7Q5.ts.map +7 -0
  47. package/dist/chunks/conflict-review-XBSME2ER.ts +18 -0
  48. package/dist/chunks/conflict-review-XBSME2ER.ts.map +7 -0
  49. package/dist/chunks/{continuous-record-OM64J27R.ts → continuous-record-ZHUXVO4E.ts} +5 -13
  50. package/dist/chunks/continuous-record-ZHUXVO4E.ts.map +7 -0
  51. package/dist/chunks/{file-selection-7HEVPO4T.ts → file-selection-S6CNNNQI.ts} +11 -14
  52. package/dist/chunks/{file-selection-7HEVPO4T.ts.map → file-selection-S6CNNNQI.ts.map} +1 -1
  53. package/dist/chunks/manager-result-dispatcher-I2AMCCE7.ts +18 -0
  54. package/dist/chunks/{manager-ui-65ZETN6F.ts → manager-ui-SJOBTJLY.ts} +80 -123
  55. package/dist/chunks/manager-ui-SJOBTJLY.ts.map +7 -0
  56. package/dist/chunks/merge-review-SGDLMVS4.ts +10 -0
  57. package/dist/chunks/remote-selection-ui-GZHPDQ4L.ts +17 -0
  58. package/dist/chunks/{setup-switch-AB27ADDI.ts → setup-switch-M3BAFGJM.ts} +9 -13
  59. package/dist/chunks/{setup-wizard-5FILKFLQ.ts → setup-wizard-NFAWP4KF.ts} +18 -21
  60. package/dist/chunks/{setup-wizard-5FILKFLQ.ts.map → setup-wizard-NFAWP4KF.ts.map} +1 -1
  61. package/dist/chunks/{snapshot-G3W2GOGB.ts → snapshot-D4SFDP5J.ts} +8 -13
  62. package/dist/chunks/snapshot-D4SFDP5J.ts.map +7 -0
  63. package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts +13 -0
  64. package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts.map +7 -0
  65. package/dist/chunks/state-directory-JZSZVVPX.ts +17 -0
  66. package/dist/chunks/sync-inspection-BJ4KPPNO.ts +23 -0
  67. package/dist/chunks/sync-inspection-BJ4KPPNO.ts.map +7 -0
  68. package/dist/chunks/sync-operations-TLWER2TT.ts +45 -0
  69. package/dist/chunks/sync-operations-TLWER2TT.ts.map +7 -0
  70. package/dist/chunks/{sync-state-H4TFZZ7S.ts → sync-state-FVCJJ7MY.ts} +5 -11
  71. package/dist/chunks/sync-state-FVCJJ7MY.ts.map +7 -0
  72. package/dist/index.ts +269 -313
  73. package/dist/index.ts.map +4 -4
  74. package/docs/daemon-migration.md +93 -0
  75. package/package.json +3 -6
  76. package/skills/configure-pi-sync/SKILL.md +1 -1
  77. package/skills/configure-pi-sync/references/configuration.md +19 -6
  78. package/src/backends/backend-factory.ts +2 -23
  79. package/src/backends/backend-identity.ts +5 -40
  80. package/src/backends/backend-types.ts +1 -81
  81. package/src/backends/git/git-backend.ts +6 -784
  82. package/src/backends/git/git-config.ts +8 -130
  83. package/src/backends/git/git-runner.ts +7 -255
  84. package/src/backends/git/git-storage.ts +14 -293
  85. package/src/backends/s3/s3-backend.ts +11 -523
  86. package/src/backends/s3/s3-client.ts +2 -399
  87. package/src/backends/s3/s3-conditions.ts +2 -67
  88. package/src/backends/snapshot-pointer.ts +2 -27
  89. package/src/backends/sync-backend.ts +6 -101
  90. package/src/backends/webdav/webdav-backend.ts +10 -622
  91. package/src/backends/webdav/webdav-client.ts +6 -370
  92. package/src/backends/webdav/webdav-config.ts +8 -82
  93. package/src/commands/command-execution.ts +40 -36
  94. package/src/commands/command.ts +23 -1
  95. package/src/daemon/apply-gate.ts +146 -0
  96. package/src/daemon/pi-client.ts +591 -0
  97. package/src/daemon/recovery.ts +103 -0
  98. package/src/paths.ts +12 -83
  99. package/src/settings/config-errors.ts +2 -6
  100. package/src/settings/config-file.ts +19 -693
  101. package/src/settings/config.ts +16 -263
  102. package/src/settings/settings-management.ts +11 -254
  103. package/src/settings/settings-store.ts +10 -48
  104. package/src/settings/settings-types.ts +1 -157
  105. package/src/settings/settings-validation.ts +17 -435
  106. package/src/snapshot/session-paths.ts +11 -111
  107. package/src/snapshot/snapshot-apply.ts +9 -322
  108. package/src/snapshot/snapshot-case-replacement.ts +6 -80
  109. package/src/snapshot/snapshot-codec.ts +2 -59
  110. package/src/snapshot/snapshot-exclude-safety.ts +2 -44
  111. package/src/snapshot/snapshot-mutation-queues.ts +6 -142
  112. package/src/snapshot/snapshot-paths.ts +2 -11
  113. package/src/snapshot/snapshot-root-transition.ts +6 -154
  114. package/src/snapshot/snapshot-transaction-directory.ts +5 -16
  115. package/src/snapshot/snapshot-transaction-plan.ts +2 -72
  116. package/src/snapshot/snapshot-transaction.ts +6 -946
  117. package/src/snapshot/snapshot-types.ts +1 -43
  118. package/src/snapshot/snapshot.ts +19 -447
  119. package/src/state/json-file.ts +2 -47
  120. package/src/state/lock-policy.ts +2 -2
  121. package/src/state/lock.ts +10 -292
  122. package/src/state/lockfile-fs.ts +2 -25
  123. package/src/state/merge-baseline-store.ts +8 -208
  124. package/src/state/mutation-directory-sync.ts +2 -34
  125. package/src/state/operation-availability.ts +7 -59
  126. package/src/state/state-directory.ts +8 -243
  127. package/src/state/state-types.ts +1 -25
  128. package/src/state/sync-state-store.ts +11 -75
  129. package/src/sync/agent-candidate.ts +7 -256
  130. package/src/sync/agent-plan.ts +2 -107
  131. package/src/sync/agent-policy.ts +10 -13
  132. package/src/sync/agent-refusal-retry.ts +2 -54
  133. package/src/sync/agent-request.ts +2 -19
  134. package/src/sync/agent-runner.ts +2 -191
  135. package/src/sync/agent-store.ts +7 -182
  136. package/src/sync/agent-sync.ts +2 -141
  137. package/src/sync/apply-review.ts +2 -63
  138. package/src/sync/automatic-sync.ts +55 -111
  139. package/src/sync/conflict-artifact-ownership.ts +2 -63
  140. package/src/sync/conflict-artifacts.ts +8 -195
  141. package/src/sync/conflict-groups.ts +2 -68
  142. package/src/sync/conflict-preview.ts +2 -56
  143. package/src/sync/conflict-resolution.ts +2 -93
  144. package/src/sync/conflict-retention.ts +2 -72
  145. package/src/sync/conflict-review.ts +3 -92
  146. package/src/sync/content-conflicts.ts +2 -73
  147. package/src/sync/continuous-errors.ts +7 -85
  148. package/src/sync/continuous-lease.ts +2 -216
  149. package/src/sync/continuous-record.ts +10 -261
  150. package/src/sync/continuous-storage.ts +12 -64
  151. package/src/sync/continuous-sync.ts +2 -563
  152. package/src/sync/continuous-watch.ts +2 -61
  153. package/src/sync/exclude-policy.ts +6 -84
  154. package/src/sync/field-migration.ts +2 -39
  155. package/src/sync/file-merge-planner.ts +2 -143
  156. package/src/sync/json-document.ts +7 -184
  157. package/src/sync/local-field-policy.ts +2 -29
  158. package/src/sync/local-fields.ts +9 -119
  159. package/src/sync/merge-apply.ts +2 -439
  160. package/src/sync/merge-journal.ts +10 -228
  161. package/src/sync/merge-transfer-error.ts +2 -72
  162. package/src/sync/merged-sync.ts +2 -919
  163. package/src/sync/mutation-owner.ts +2 -22
  164. package/src/sync/package-merge.ts +2 -87
  165. package/src/sync/partial-progress.ts +2 -55
  166. package/src/sync/remote-snapshot.ts +7 -79
  167. package/src/sync/session-merge.ts +2 -194
  168. package/src/sync/settings-conflicts.ts +2 -64
  169. package/src/sync/settings-merge.ts +6 -121
  170. package/src/sync/signals.ts +2 -8
  171. package/src/sync/startup-check.ts +15 -31
  172. package/src/sync/startup-timings.ts +2 -94
  173. package/src/sync/sync-decision.ts +3 -111
  174. package/src/sync/sync-error-guidance.ts +2 -46
  175. package/src/sync/sync-errors.ts +7 -23
  176. package/src/sync/sync-inspection.ts +10 -59
  177. package/src/sync/sync-local.ts +2 -44
  178. package/src/sync/sync-mutations.ts +10 -788
  179. package/src/sync/sync-operations.ts +32 -11
  180. package/src/sync/sync-policy.ts +34 -474
  181. package/src/sync/sync-queries.ts +2 -247
  182. package/src/sync/sync-state.ts +18 -157
  183. package/src/sync/text-merge.ts +10 -133
  184. package/src/sync-extension.ts +192 -142
  185. package/dist/chunks/agent-candidate-ZHN7FTZT.ts +0 -30
  186. package/dist/chunks/agent-plan-ILFEUJ2E.ts +0 -124
  187. package/dist/chunks/agent-plan-ILFEUJ2E.ts.map +0 -7
  188. package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts +0 -73
  189. package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts.map +0 -7
  190. package/dist/chunks/agent-runner-FCRV2Z75.ts +0 -185
  191. package/dist/chunks/agent-runner-FCRV2Z75.ts.map +0 -7
  192. package/dist/chunks/agent-store-CCKN4DPR.ts +0 -175
  193. package/dist/chunks/agent-store-CCKN4DPR.ts.map +0 -7
  194. package/dist/chunks/agent-sync-EGA2I5W7.ts +0 -22
  195. package/dist/chunks/chunk-25QCU3LY.ts +0 -220
  196. package/dist/chunks/chunk-25QCU3LY.ts.map +0 -7
  197. package/dist/chunks/chunk-2JZFHNLM.ts +0 -113
  198. package/dist/chunks/chunk-2JZFHNLM.ts.map +0 -7
  199. package/dist/chunks/chunk-2UKUKIBI.ts +0 -25
  200. package/dist/chunks/chunk-2UKUKIBI.ts.map +0 -7
  201. package/dist/chunks/chunk-2ZZJXITS.ts.map +0 -7
  202. package/dist/chunks/chunk-3JTZF7Z5.ts +0 -77
  203. package/dist/chunks/chunk-3JTZF7Z5.ts.map +0 -7
  204. package/dist/chunks/chunk-3ST7RSYN.ts +0 -21
  205. package/dist/chunks/chunk-3ST7RSYN.ts.map +0 -7
  206. package/dist/chunks/chunk-4NVHHDN2.ts +0 -61
  207. package/dist/chunks/chunk-4NVHHDN2.ts.map +0 -7
  208. package/dist/chunks/chunk-5SFMBY5P.ts +0 -26
  209. package/dist/chunks/chunk-5SFMBY5P.ts.map +0 -7
  210. package/dist/chunks/chunk-6OFMB6KK.ts +0 -215
  211. package/dist/chunks/chunk-6OFMB6KK.ts.map +0 -7
  212. package/dist/chunks/chunk-6XU5HZAN.ts +0 -205
  213. package/dist/chunks/chunk-6XU5HZAN.ts.map +0 -7
  214. package/dist/chunks/chunk-6YGRZSCN.ts +0 -128
  215. package/dist/chunks/chunk-6YGRZSCN.ts.map +0 -7
  216. package/dist/chunks/chunk-7D5SF7P3.ts +0 -29
  217. package/dist/chunks/chunk-7D5SF7P3.ts.map +0 -7
  218. package/dist/chunks/chunk-7WYF2KUO.ts +0 -1161
  219. package/dist/chunks/chunk-7WYF2KUO.ts.map +0 -7
  220. package/dist/chunks/chunk-APDNHB2T.ts +0 -2037
  221. package/dist/chunks/chunk-APDNHB2T.ts.map +0 -7
  222. package/dist/chunks/chunk-AR2DGDUI.ts +0 -55
  223. package/dist/chunks/chunk-AR2DGDUI.ts.map +0 -7
  224. package/dist/chunks/chunk-DT7M4VQS.ts +0 -69
  225. package/dist/chunks/chunk-DT7M4VQS.ts.map +0 -7
  226. package/dist/chunks/chunk-DTPELCPW.ts.map +0 -7
  227. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  228. package/dist/chunks/chunk-FHE2DCA2.ts +0 -61
  229. package/dist/chunks/chunk-FHE2DCA2.ts.map +0 -7
  230. package/dist/chunks/chunk-G4RUXRWZ.ts +0 -48
  231. package/dist/chunks/chunk-G4RUXRWZ.ts.map +0 -7
  232. package/dist/chunks/chunk-ILXMZ2HU.ts +0 -58
  233. package/dist/chunks/chunk-ILXMZ2HU.ts.map +0 -7
  234. package/dist/chunks/chunk-LA3HQMFG.ts +0 -115
  235. package/dist/chunks/chunk-LA3HQMFG.ts.map +0 -7
  236. package/dist/chunks/chunk-M6VQJIOU.ts +0 -54
  237. package/dist/chunks/chunk-M6VQJIOU.ts.map +0 -7
  238. package/dist/chunks/chunk-MKC3PXCN.ts +0 -369
  239. package/dist/chunks/chunk-MKC3PXCN.ts.map +0 -7
  240. package/dist/chunks/chunk-OQBE2OMB.ts +0 -88
  241. package/dist/chunks/chunk-OQBE2OMB.ts.map +0 -7
  242. package/dist/chunks/chunk-P3YD4ONV.ts +0 -123
  243. package/dist/chunks/chunk-P3YD4ONV.ts.map +0 -7
  244. package/dist/chunks/chunk-PRUEIIK7.ts +0 -24
  245. package/dist/chunks/chunk-PRUEIIK7.ts.map +0 -7
  246. package/dist/chunks/chunk-PWMWOJP4.ts +0 -17
  247. package/dist/chunks/chunk-PWMWOJP4.ts.map +0 -7
  248. package/dist/chunks/chunk-QPC5HT3A.ts.map +0 -7
  249. package/dist/chunks/chunk-QQVK2XFC.ts +0 -64
  250. package/dist/chunks/chunk-QQVK2XFC.ts.map +0 -7
  251. package/dist/chunks/chunk-RDOX3VH5.ts +0 -140
  252. package/dist/chunks/chunk-RDOX3VH5.ts.map +0 -7
  253. package/dist/chunks/chunk-S7D6XWHI.ts +0 -258
  254. package/dist/chunks/chunk-S7D6XWHI.ts.map +0 -7
  255. package/dist/chunks/chunk-SHPNS7FM.ts +0 -64
  256. package/dist/chunks/chunk-SHPNS7FM.ts.map +0 -7
  257. package/dist/chunks/chunk-SWRVXVFD.ts +0 -248
  258. package/dist/chunks/chunk-SWRVXVFD.ts.map +0 -7
  259. package/dist/chunks/chunk-T2SJD3N7.ts +0 -99
  260. package/dist/chunks/chunk-T2SJD3N7.ts.map +0 -7
  261. package/dist/chunks/chunk-T2TYBLXK.ts +0 -27
  262. package/dist/chunks/chunk-T2TYBLXK.ts.map +0 -7
  263. package/dist/chunks/chunk-UZSDS4HF.ts +0 -403
  264. package/dist/chunks/chunk-UZSDS4HF.ts.map +0 -7
  265. package/dist/chunks/chunk-VPODHKOX.ts +0 -229
  266. package/dist/chunks/chunk-VPODHKOX.ts.map +0 -7
  267. package/dist/chunks/chunk-WEKGW7HV.ts +0 -162
  268. package/dist/chunks/chunk-WEKGW7HV.ts.map +0 -7
  269. package/dist/chunks/chunk-WUHRVSWI.ts +0 -369
  270. package/dist/chunks/chunk-WUHRVSWI.ts.map +0 -7
  271. package/dist/chunks/chunk-X7R6DCVF.ts +0 -28
  272. package/dist/chunks/chunk-X7R6DCVF.ts.map +0 -7
  273. package/dist/chunks/chunk-XJHQPB3E.ts +0 -107
  274. package/dist/chunks/chunk-XJHQPB3E.ts.map +0 -7
  275. package/dist/chunks/chunk-XZ3ZTHKR.ts +0 -1184
  276. package/dist/chunks/chunk-XZ3ZTHKR.ts.map +0 -7
  277. package/dist/chunks/chunk-YDVQYUHE.ts +0 -34
  278. package/dist/chunks/chunk-YDVQYUHE.ts.map +0 -7
  279. package/dist/chunks/chunk-YEULK7MK.ts +0 -415
  280. package/dist/chunks/chunk-YEULK7MK.ts.map +0 -7
  281. package/dist/chunks/chunk-YHT4YTYG.ts +0 -31
  282. package/dist/chunks/chunk-YHT4YTYG.ts.map +0 -7
  283. package/dist/chunks/chunk-ZW5ZLGBI.ts +0 -154
  284. package/dist/chunks/chunk-ZW5ZLGBI.ts.map +0 -7
  285. package/dist/chunks/command-handler-SDGKIQH2.ts.map +0 -7
  286. package/dist/chunks/conflict-artifacts-MYSH3L2J.ts +0 -33
  287. package/dist/chunks/conflict-review-J6ZSPNWL.ts +0 -190
  288. package/dist/chunks/conflict-review-J6ZSPNWL.ts.map +0 -7
  289. package/dist/chunks/continuous-sync-BH5SWIRV.ts +0 -590
  290. package/dist/chunks/continuous-sync-BH5SWIRV.ts.map +0 -7
  291. package/dist/chunks/git-backend-6CKI6CUG.ts +0 -1074
  292. package/dist/chunks/git-backend-6CKI6CUG.ts.map +0 -7
  293. package/dist/chunks/local-fields-SR7PH66U.ts +0 -27
  294. package/dist/chunks/local-fields-SR7PH66U.ts.map +0 -7
  295. package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts +0 -33
  296. package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts.map +0 -7
  297. package/dist/chunks/manager-ui-65ZETN6F.ts.map +0 -7
  298. package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts +0 -26
  299. package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts.map +0 -7
  300. package/dist/chunks/remote-selection-ui-W55BQDJQ.ts +0 -32
  301. package/dist/chunks/remote-selection-ui-W55BQDJQ.ts.map +0 -7
  302. package/dist/chunks/s3-backend-FDK7JSDQ.ts +0 -845
  303. package/dist/chunks/s3-backend-FDK7JSDQ.ts.map +0 -7
  304. package/dist/chunks/setup-switch-AB27ADDI.ts.map +0 -7
  305. package/dist/chunks/snapshot-G3W2GOGB.ts.map +0 -7
  306. package/dist/chunks/snapshot-transaction-SGRUWT73.ts +0 -25
  307. package/dist/chunks/snapshot-transaction-SGRUWT73.ts.map +0 -7
  308. package/dist/chunks/sync-inspection-MDYHZHT7.ts +0 -26
  309. package/dist/chunks/sync-inspection-MDYHZHT7.ts.map +0 -7
  310. package/dist/chunks/sync-operations-ZAUP65FH.ts +0 -1032
  311. package/dist/chunks/sync-operations-ZAUP65FH.ts.map +0 -7
  312. package/dist/chunks/sync-state-H4TFZZ7S.ts.map +0 -7
  313. package/dist/chunks/webdav-backend-UNMIAXM5.ts +0 -852
  314. package/dist/chunks/webdav-backend-UNMIAXM5.ts.map +0 -7
  315. /package/dist/chunks/{chunk-KHBPED6W.ts.map → chunk-GSQGBVKG.ts.map} +0 -0
  316. /package/dist/chunks/{chunk-PQ75RPUP.ts.map → chunk-UZUUUY7C.ts.map} +0 -0
  317. /package/dist/chunks/{agent-candidate-ZHN7FTZT.ts.map → manager-result-dispatcher-I2AMCCE7.ts.map} +0 -0
  318. /package/dist/chunks/{agent-sync-EGA2I5W7.ts.map → merge-review-SGDLMVS4.ts.map} +0 -0
  319. /package/dist/chunks/{config-J5VZUY4J.ts.map → remote-selection-ui-GZHPDQ4L.ts.map} +0 -0
  320. /package/dist/chunks/{conflict-artifacts-MYSH3L2J.ts.map → setup-switch-M3BAFGJM.ts.map} +0 -0
  321. /package/dist/chunks/{continuous-record-OM64J27R.ts.map → state-directory-JZSZVVPX.ts.map} +0 -0
@@ -1,845 +0,0 @@
1
- // @generated by scripts/build-runtime.mjs; do not edit.
2
- // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
- import {
4
- createLatestPointer,
5
- remoteHistoryEntry
6
- } from "./chunk-YHT4YTYG.ts";
7
- import {
8
- decodeSnapshot,
9
- encodeSnapshot
10
- } from "./chunk-QQVK2XFC.ts";
11
- import {
12
- syncErrorGuidance
13
- } from "./chunk-G4RUXRWZ.ts";
14
- import {
15
- validatePortableSnapshot
16
- } from "./chunk-P3YD4ONV.ts";
17
- import "./chunk-7D5SF7P3.ts";
18
- import {
19
- sessionTokenWarnings
20
- } from "./chunk-XZ3ZTHKR.ts";
21
- import "./chunk-X7R6DCVF.ts";
22
- import {
23
- throwIfAborted
24
- } from "./chunk-PWMWOJP4.ts";
25
- import "./chunk-ZW5ZLGBI.ts";
26
- import "./chunk-2JZFHNLM.ts";
27
- import "./chunk-T2SJD3N7.ts";
28
- import "./chunk-MKC3PXCN.ts";
29
- import {
30
- portableSnapshotSelection
31
- } from "./chunk-WUHRVSWI.ts";
32
- import "./chunk-LA3HQMFG.ts";
33
- import "./chunk-3JTZF7Z5.ts";
34
- import {
35
- encodeKey,
36
- posixJoin
37
- } from "./chunk-FHE2DCA2.ts";
38
- import {
39
- retryAfter
40
- } from "./chunk-DT7M4VQS.ts";
41
- import {
42
- SyncBackendConflictError,
43
- SyncBackendPublicationOutcomeUnknownError
44
- } from "./chunk-YDVQYUHE.ts";
45
-
46
- // src/backends/s3/s3-backend.ts
47
- import { createHash as createHash2 } from "node:crypto";
48
-
49
- // src/backends/s3/s3-client.ts
50
- import { createHash, createHmac } from "node:crypto";
51
- import { setTimeout as sleep } from "node:timers/promises";
52
- var MAX_JSON_RESPONSE_BYTES = 1024 * 1024;
53
- var MAX_SNAPSHOT_RESPONSE_BYTES = 256 * 1024 * 1024;
54
- var MAX_ERROR_RESPONSE_BYTES = 64 * 1024;
55
- var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
56
- function iso8601Basic(date) {
57
- return date.toISOString().replace(/[:-]|\.\d{3}/g, "");
58
- }
59
- function isCloudflareR2Endpoint(endpoint) {
60
- const value = endpoint?.trim();
61
- if (!value) return false;
62
- try {
63
- const hostname = new URL(value).hostname.toLowerCase();
64
- return hostname === "r2.cloudflarestorage.com" || hostname.endsWith(".r2.cloudflarestorage.com");
65
- } catch {
66
- return false;
67
- }
68
- }
69
- var S3ObjectAlreadyExistsError = class extends Error {
70
- constructor(key) {
71
- super(`S3 object already exists: ${key}`);
72
- this.key = key;
73
- this.name = "S3ObjectAlreadyExistsError";
74
- }
75
- key;
76
- };
77
- var S3HttpError = class extends Error {
78
- constructor(message, status, retryAfterMs) {
79
- super(message);
80
- this.status = status;
81
- this.retryAfterMs = retryAfterMs;
82
- this.name = "S3HttpError";
83
- }
84
- status;
85
- retryAfterMs;
86
- };
87
- var S3Client = class {
88
- config;
89
- endpoint;
90
- signal;
91
- requestTimeoutMs;
92
- omitSessionTokenAfterRejection = false;
93
- constructor(config, signal, requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
94
- this.config = config;
95
- this.endpoint = new URL(config.profile.endpoint);
96
- this.signal = signal;
97
- this.requestTimeoutMs = requestTimeoutMs;
98
- }
99
- /** Read-only access probe. A bare 404 cannot distinguish a missing key from a missing bucket. */
100
- async diagnoseRead(key) {
101
- this.signal?.throwIfAborted();
102
- const response = await this.request("GET", key);
103
- if (response.ok) {
104
- await response.body?.cancel();
105
- this.signal?.throwIfAborted();
106
- return "readable";
107
- }
108
- const detail = await this.readErrorText(response);
109
- this.signal?.throwIfAborted();
110
- if (response.status === 404) {
111
- const code = /<Code>\s*([A-Za-z]+)\s*<\/Code>/u.exec(detail)?.[1];
112
- if (code === "NoSuchBucket") return "missing-bucket";
113
- if (code === "NoSuchKey") return "missing-key";
114
- return "unknown-404";
115
- }
116
- throw new S3HttpError(`S3 remote read failed (HTTP ${response.status}).`, response.status);
117
- }
118
- async getJson(key) {
119
- const maxAttempts = 3;
120
- let lastError;
121
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
122
- const object = await this.request("GET", key);
123
- if (object.status === 404) return { missing: true };
124
- if (!object.ok) {
125
- throw new S3HttpError(
126
- `S3 GET failed (${object.status}): ${await this.readErrorText(object)}`,
127
- object.status,
128
- retryAfter(object)
129
- );
130
- }
131
- const body = await readBoundedText(object, MAX_JSON_RESPONSE_BYTES, "S3 JSON response");
132
- if (body.length > 0) {
133
- return {
134
- value: JSON.parse(body),
135
- etag: normalizeEtag(object.headers.get("etag")),
136
- missing: false
137
- };
138
- }
139
- lastError = new Error(`S3 GET returned an empty body for ${key}`);
140
- if (attempt < maxAttempts) {
141
- await sleep(250 * attempt, void 0, { signal: this.signal });
142
- }
143
- }
144
- throw lastError;
145
- }
146
- async getBuffer(key) {
147
- const maxAttempts = 3;
148
- let lastError;
149
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
150
- const object = await this.request("GET", key);
151
- if (object.status === 404) return { missing: true };
152
- if (!object.ok) {
153
- throw new S3HttpError(
154
- `S3 GET failed (${object.status}): ${await this.readErrorText(object)}`,
155
- object.status,
156
- retryAfter(object)
157
- );
158
- }
159
- const buffer = await readBoundedBuffer(object, MAX_SNAPSHOT_RESPONSE_BYTES, "S3 snapshot response");
160
- if (buffer.length > 0) {
161
- return { value: buffer, etag: normalizeEtag(object.headers.get("etag")), missing: false };
162
- }
163
- lastError = new Error(`S3 GET returned an empty body for ${key}`);
164
- if (attempt < maxAttempts) {
165
- await sleep(250 * attempt, void 0, { signal: this.signal });
166
- }
167
- }
168
- throw lastError;
169
- }
170
- async putJson(key, value, options = {}) {
171
- const body = Buffer.from(JSON.stringify(value, null, " "), "utf8");
172
- await this.putBuffer(key, body, "application/json", options);
173
- }
174
- async putBuffer(key, body, contentType, options = {}) {
175
- const headers = { "content-type": contentType };
176
- if (options.ifAbsent) headers["if-none-match"] = "*";
177
- if (options.ifMatch) headers["if-match"] = options.ifMatch;
178
- const response = await this.request("PUT", key, body, headers);
179
- if ((options.ifAbsent || options.ifMatch) && (response.status === 412 || response.status === 409)) {
180
- await response.body?.cancel();
181
- if (options.ifAbsent && response.status === 412) throw new S3ObjectAlreadyExistsError(key);
182
- if (options.ifAbsent || options.ifMatch) {
183
- throw new S3HttpError(`S3 conditional PUT rejected (${response.status}).`, response.status);
184
- }
185
- }
186
- if (!response.ok) {
187
- throw new S3HttpError(
188
- `S3 PUT failed (${response.status}): ${await this.readErrorText(response)}`,
189
- response.status,
190
- retryAfter(response)
191
- );
192
- }
193
- await response.body?.cancel();
194
- }
195
- async delete(key) {
196
- const response = await this.request("DELETE", key);
197
- if (!response.ok && response.status !== 404) {
198
- throw new S3HttpError(
199
- `S3 DELETE failed (${response.status}): ${await this.readErrorText(response)}`,
200
- response.status,
201
- retryAfter(response)
202
- );
203
- }
204
- await response.body?.cancel();
205
- }
206
- async request(method, key, body, extraHeaders = {}) {
207
- const url = new URL(this.endpoint.toString());
208
- const endpointPath = url.pathname.replace(/%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9._~/%-]/gu, encodeKey).replace(/%[0-9A-Fa-f]{2}/gu, (escaped) => escaped.toUpperCase());
209
- url.pathname = posixJoin(endpointPath, encodeKey(this.config.destination.bucket), encodeKey(key));
210
- const send = async (sessionToken2) => {
211
- const transportSignal = this.transportSignal();
212
- const headers = await signedHeaders({
213
- method,
214
- url,
215
- body,
216
- // Transfer compression can weaken an object's ETag (R2 JSON responses).
217
- // Read the original representation for exact checksums and strong If-Match tokens.
218
- extraHeaders: method === "GET" ? { ...extraHeaders, "accept-encoding": "identity" } : extraHeaders,
219
- accessKeyId: this.config.profile.accessKeyId,
220
- secretAccessKey: this.config.profile.secretAccessKey,
221
- sessionToken: sessionToken2,
222
- region: this.config.profile.region
223
- });
224
- try {
225
- return await fetch(url, {
226
- method,
227
- headers,
228
- body: body ? new Uint8Array(body) : void 0,
229
- // Never forward signed headers or snapshot bodies to an unreviewed URL.
230
- redirect: "error",
231
- signal: transportSignal
232
- });
233
- } catch (error) {
234
- if (error instanceof Error && error.name === "AbortError") throw error;
235
- if (error instanceof Error && error.name === "TimeoutError") {
236
- throw new Error("S3 request timed out.", { cause: error });
237
- }
238
- throw new Error(`S3 request failed: ${this.redact(errorMessage(error))}`, { cause: error });
239
- }
240
- };
241
- const sessionToken = this.omitSessionTokenAfterRejection ? void 0 : this.config.profile.sessionToken;
242
- const response = await send(sessionToken);
243
- try {
244
- if (!await this.shouldRetryWithoutSessionToken(response, sessionToken)) return response;
245
- } catch (error) {
246
- await response.body?.cancel().catch(() => void 0);
247
- throw error;
248
- }
249
- await response.body?.cancel();
250
- const retry = await send(void 0);
251
- if (retry.ok || retry.status === 404) this.omitSessionTokenAfterRejection = true;
252
- return retry;
253
- }
254
- transportSignal() {
255
- const timeout = AbortSignal.timeout(this.requestTimeoutMs);
256
- return this.signal ? AbortSignal.any([this.signal, timeout]) : timeout;
257
- }
258
- async shouldRetryWithoutSessionToken(response, sessionToken) {
259
- if (!sessionToken || !isCloudflareR2Endpoint(this.config.profile.endpoint) || response.ok || response.status !== 400) {
260
- return false;
261
- }
262
- return isSecurityTokenInvalidArgument(
263
- await readBoundedText(response.clone(), MAX_ERROR_RESPONSE_BYTES, "S3 error response")
264
- );
265
- }
266
- async readErrorText(response) {
267
- try {
268
- return this.redact(await readBoundedText(response, MAX_ERROR_RESPONSE_BYTES, "S3 error response"));
269
- } catch (error) {
270
- return this.redact(errorMessage(error));
271
- }
272
- }
273
- redact(value) {
274
- let redacted = value;
275
- let endpointUsername;
276
- let endpointPassword;
277
- let endpointQueryValues = [];
278
- try {
279
- const endpoint = new URL(this.config.profile.endpoint);
280
- endpointUsername = endpoint.username;
281
- endpointPassword = endpoint.password;
282
- endpointQueryValues = [...endpoint.searchParams.values()];
283
- } catch {
284
- }
285
- for (const secret of [
286
- this.config.profile.accessKeyId,
287
- this.config.profile.secretAccessKey,
288
- this.config.profile.sessionToken,
289
- endpointUsername,
290
- endpointPassword,
291
- ...endpointQueryValues
292
- ]) {
293
- if (secret) redacted = redacted.replaceAll(secret, "[REDACTED]");
294
- }
295
- return redacted;
296
- }
297
- };
298
- async function readBoundedText(response, limit, label) {
299
- return (await readBoundedBuffer(response, limit, label)).toString("utf8");
300
- }
301
- async function readBoundedBuffer(response, limit, label) {
302
- const contentLength = Number(response.headers.get("content-length"));
303
- if (Number.isFinite(contentLength) && contentLength > limit) {
304
- void response.body?.cancel().catch(() => void 0);
305
- throw new Error(`${label} exceeds the ${limit}-byte limit.`);
306
- }
307
- if (!response.body) return Buffer.alloc(0);
308
- const reader = response.body.getReader();
309
- const chunks = [];
310
- let total = 0;
311
- try {
312
- while (true) {
313
- const { done, value } = await reader.read();
314
- if (done) break;
315
- total += value.byteLength;
316
- if (total > limit) {
317
- void reader.cancel().catch(() => void 0);
318
- throw new Error(`${label} exceeds the ${limit}-byte limit.`);
319
- }
320
- chunks.push(Buffer.from(value));
321
- }
322
- } finally {
323
- reader.releaseLock();
324
- }
325
- return Buffer.concat(chunks, total);
326
- }
327
- function errorMessage(error) {
328
- return error instanceof Error ? error.message : String(error);
329
- }
330
- async function signedHeaders(input) {
331
- const now = /* @__PURE__ */ new Date();
332
- const amzDate = iso8601Basic(now);
333
- const dateStamp = amzDate.slice(0, 8);
334
- const payloadHash = sha256(input.body ?? Buffer.alloc(0));
335
- const headers = {
336
- ...lowercaseKeys(input.extraHeaders),
337
- host: input.url.host,
338
- "x-amz-content-sha256": payloadHash,
339
- "x-amz-date": amzDate
340
- };
341
- if (input.sessionToken) headers["x-amz-security-token"] = input.sessionToken;
342
- const signedHeaderNames = Object.keys(headers).sort();
343
- const canonicalHeaders = signedHeaderNames.map((name) => `${name}:${headers[name]?.trim()}
344
- `).join("");
345
- const canonicalRequest = [
346
- input.method,
347
- input.url.pathname,
348
- input.url.searchParams.toString(),
349
- canonicalHeaders,
350
- signedHeaderNames.join(";"),
351
- payloadHash
352
- ].join("\n");
353
- const scope = `${dateStamp}/${input.region}/s3/aws4_request`;
354
- const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, sha256(Buffer.from(canonicalRequest))].join("\n");
355
- const signingKey = hmac(
356
- hmac(hmac(hmac(Buffer.from(`AWS4${input.secretAccessKey}`), dateStamp), input.region), "s3"),
357
- "aws4_request"
358
- );
359
- const signature = createHmac("sha256", signingKey).update(stringToSign).digest("hex");
360
- return {
361
- ...headers,
362
- authorization: `AWS4-HMAC-SHA256 Credential=${input.accessKeyId}/${scope}, SignedHeaders=${signedHeaderNames.join(";")}, Signature=${signature}`
363
- };
364
- }
365
- function hmac(key, value) {
366
- return createHmac("sha256", key).update(value).digest();
367
- }
368
- function sha256(value) {
369
- return createHash("sha256").update(value).digest("hex");
370
- }
371
- function lowercaseKeys(value) {
372
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key.toLowerCase(), item]));
373
- }
374
- function normalizeEtag(value) {
375
- return value ?? void 0;
376
- }
377
- function isSecurityTokenInvalidArgument(text) {
378
- return text.includes("<Code>InvalidArgument</Code>") && text.includes("<Message>X-Amz-Security-Token</Message>");
379
- }
380
-
381
- // src/backends/s3/s3-conditions.ts
382
- import { randomUUID } from "node:crypto";
383
- function requireS3Etag(value) {
384
- if (!value || !/^"[^"\r\n]+"$/u.test(value)) throw new Error("S3 conditional publication requires a strong ETag.");
385
- return value;
386
- }
387
- async function verifyS3Conditions(config, signal) {
388
- const key = posixJoin(
389
- config.destination.prefix === "./" ? "" : config.destination.prefix,
390
- ".pi-sync-probes",
391
- randomUUID()
392
- );
393
- const client = new S3Client(config, signal);
394
- let failure;
395
- let attempted = false;
396
- try {
397
- signal?.throwIfAborted();
398
- attempted = true;
399
- await client.putBuffer(key, Buffer.from("first"), "text/plain", { ifAbsent: true });
400
- const first = await client.getBuffer(key);
401
- const etag = requireS3Etag(first.etag);
402
- if (!first.value?.equals(Buffer.from("first"))) throw new Error("S3 conditional probe read did not match.");
403
- await expectRejected(client.putBuffer(key, Buffer.from("ignored"), "text/plain", { ifAbsent: true }));
404
- await expectRejected(client.putBuffer(key, Buffer.from("ignored"), "text/plain", { ifMatch: '"pi-sync-stale"' }));
405
- const unchanged = await client.getBuffer(key);
406
- if (!unchanged.value?.equals(first.value) || unchanged.etag !== etag)
407
- throw new Error("S3 failed precondition changed the probe.");
408
- await client.putBuffer(key, Buffer.from("second"), "text/plain", { ifMatch: etag });
409
- const second = await client.getBuffer(key);
410
- if (!second.value?.equals(Buffer.from("second")) || requireS3Etag(second.etag) === etag) {
411
- throw new Error("S3 conditional write did not rotate the probe ETag.");
412
- }
413
- await expectRejected(client.putBuffer(key, Buffer.from("ignored"), "text/plain", { ifMatch: etag }));
414
- const final = await client.getBuffer(key);
415
- if (!final.value?.equals(second.value) || final.etag !== second.etag)
416
- throw new Error("S3 stale ETag changed the probe.");
417
- signal?.throwIfAborted();
418
- } catch (error) {
419
- failure = error;
420
- }
421
- if (attempted) {
422
- try {
423
- await new S3Client(config, AbortSignal.timeout(1e4)).delete(key);
424
- } catch (error) {
425
- throw new Error(`S3 probe cleanup failed; remove ${key}.`, { cause: failure ?? error });
426
- }
427
- }
428
- if (failure) throw failure;
429
- signal?.throwIfAborted();
430
- }
431
- async function expectRejected(operation) {
432
- try {
433
- await operation;
434
- } catch (error) {
435
- if (error instanceof S3ObjectAlreadyExistsError || error instanceof S3HttpError && error.status === 412) return;
436
- throw error;
437
- }
438
- throw new Error("S3 server ignored a write precondition; publication stopped for safety.");
439
- }
440
-
441
- // src/backends/s3/s3-backend.ts
442
- var VERSION = 1;
443
- var POST_COMMIT_TIMEOUT_MS = 3e4;
444
- var S3SyncBackend = class {
445
- constructor(config, postCommitTimeoutMs = POST_COMMIT_TIMEOUT_MS) {
446
- this.config = config;
447
- this.postCommitTimeoutMs = postCommitTimeoutMs;
448
- assertSafeDestination(config);
449
- this.identity = s3BackendIdentity(config);
450
- this.destination = s3Destination(config);
451
- }
452
- config;
453
- postCommitTimeoutMs;
454
- identity;
455
- destination;
456
- capability = "conditional-required";
457
- checksums = /* @__PURE__ */ new Map();
458
- recoveryHead;
459
- sameRevision(left, right) {
460
- return left === right;
461
- }
462
- matchesUncommittedRecoveryHead(current, recorded) {
463
- return this.sameRevision(current.revision, recorded.revision) || current.snapshotId === recorded.snapshotId && current.snapshotRef === recorded.snapshotRef && current.revision === this.recoveryHead?.current && recorded.revision === this.recoveryHead?.legacy;
464
- }
465
- async readHead(signal) {
466
- this.recoveryHead = void 0;
467
- const object = await new S3Client(this.config, signal).getJson(latestKey(this.config));
468
- throwIfAborted(signal);
469
- if (object.missing) return void 0;
470
- const pointer = requirePointer(
471
- object.value,
472
- "Remote latest pointer is malformed.",
473
- this.config.destination.namespace
474
- );
475
- this.registerChecksum(pointer.snapshot, pointer.sha256);
476
- const head = remoteHead(pointer, this.identity, object.etag);
477
- if (object.etag && /^"[^"\r\n]+"$/u.test(object.etag)) {
478
- this.recoveryHead = {
479
- current: head.revision,
480
- legacy: remoteHead(pointer, this.identity, `W/${object.etag}`).revision
481
- };
482
- }
483
- return head;
484
- }
485
- async readSnapshot(reference, signal) {
486
- const expectedChecksum = this.checksums.get(reference) ?? await this.resolveChecksum(reference, signal);
487
- const object = await new S3Client(this.config, signal).getBuffer(snapshotKey(this.config, reference));
488
- throwIfAborted(signal);
489
- if (!object.value) throw new Error(`Snapshot not found: ${reference}`);
490
- if (expectedChecksum && sha2562(object.value) !== expectedChecksum) {
491
- throw new Error("Remote snapshot checksum mismatch.");
492
- }
493
- const snapshot = await decodeSnapshot(object.value, { signal });
494
- if (snapshot.id !== reference || snapshot.profile !== this.config.destination.namespace) {
495
- throw new Error("Remote snapshot identity mismatch.");
496
- }
497
- validateSnapshotBundle(snapshot);
498
- return snapshot;
499
- }
500
- async publishSnapshot(snapshot, expected, options = {}) {
501
- throwIfAborted(options.signal);
502
- assertSnapshotIdentity(snapshot, this.config.destination.namespace);
503
- await verifyS3Conditions(this.config, options.signal);
504
- throwIfAborted(options.signal);
505
- const stagedKey = snapshotKey(this.config, snapshot.id);
506
- const encoded = await encodeSnapshot(snapshot);
507
- throwIfAborted(options.signal);
508
- const pointer = pointerFor(this.config, snapshot, sha2562(encoded));
509
- const cancellableClient = new S3Client(this.config, options.signal);
510
- try {
511
- await cancellableClient.putBuffer(stagedKey, encoded, "application/gzip", {
512
- ifAbsent: true
513
- });
514
- } catch (error) {
515
- if (!(error instanceof S3ObjectAlreadyExistsError)) throw error;
516
- const existing = await cancellableClient.getBuffer(stagedKey);
517
- if (!existing.value || sha2562(existing.value) !== pointer.sha256) {
518
- throw new SyncBackendConflictError(
519
- `Immutable snapshot id already exists with different content: ${snapshot.id}`
520
- );
521
- }
522
- }
523
- const currentObject = await cancellableClient.getJson(latestKey(this.config));
524
- throwIfAborted(options.signal);
525
- let current;
526
- if (!currentObject.missing) {
527
- const currentPointer = requirePointer(
528
- currentObject.value,
529
- "Remote latest pointer is malformed.",
530
- this.config.destination.namespace
531
- );
532
- this.registerChecksum(currentPointer.snapshot, currentPointer.sha256);
533
- current = remoteHead(currentPointer, this.identity, currentObject.etag);
534
- }
535
- if (!matchesExpected(current, expected)) {
536
- throw new SyncBackendConflictError("Remote changed while pushing. Run /sync pull first, then retry.", {
537
- currentHead: current
538
- });
539
- }
540
- const condition = currentObject.missing ? { ifAbsent: true } : { ifMatch: requireS3Etag(currentObject.etag) };
541
- throwIfAborted(options.signal);
542
- options.onCommit?.();
543
- const commitClient = new S3Client(this.config, AbortSignal.timeout(this.postCommitTimeoutMs));
544
- try {
545
- await commitClient.putJson(latestKey(this.config), pointer, condition);
546
- } catch (error) {
547
- if (error instanceof S3ObjectAlreadyExistsError || error instanceof S3HttpError && (error.status === 412 || error.status === 409)) {
548
- throw new SyncBackendConflictError("Remote conditional publication was rejected; reread and retry.", {
549
- cause: error
550
- });
551
- }
552
- throw new SyncBackendPublicationOutcomeUnknownError(
553
- `Remote publication outcome is unknown: ${errorMessage2(error)}`,
554
- { cause: error }
555
- );
556
- }
557
- let verifiedObject;
558
- try {
559
- verifiedObject = await commitClient.getJson(latestKey(this.config));
560
- } catch (error) {
561
- throw new SyncBackendPublicationOutcomeUnknownError(
562
- `Remote snapshot may be active, but publication could not be verified: ${errorMessage2(error)}`,
563
- { cause: error }
564
- );
565
- }
566
- let verifiedPointer;
567
- try {
568
- verifiedPointer = requirePointer(
569
- verifiedObject.value,
570
- "Remote latest pointer is malformed after publication.",
571
- this.config.destination.namespace
572
- );
573
- } catch (error) {
574
- throw new SyncBackendPublicationOutcomeUnknownError(
575
- `Remote snapshot may be active, but publication verification was malformed: ${errorMessage2(error)}`,
576
- { cause: error }
577
- );
578
- }
579
- if (!samePointer(verifiedPointer, pointer)) {
580
- throw new SyncBackendConflictError(
581
- "Remote latest changed immediately after push. Run /sync status before continuing.",
582
- {
583
- phase: "after-commit",
584
- currentHead: remoteHead(verifiedPointer, this.identity, verifiedObject.etag),
585
- candidateMayHaveBeenActive: true
586
- }
587
- );
588
- }
589
- this.registerChecksum(verifiedPointer.snapshot, verifiedPointer.sha256);
590
- const head = remoteHead(verifiedPointer, this.identity, verifiedObject.etag);
591
- const warning = await this.updateHistorySafely(commitClient, pointer);
592
- return { head, warnings: warning ? [warning] : [] };
593
- }
594
- async listHistory(signal) {
595
- const object = await new S3Client(this.config, signal).getJson(historyKey(this.config));
596
- throwIfAborted(signal);
597
- if (object.missing) return [];
598
- const pointers = requireHistory(object.value, this.config.destination.namespace);
599
- for (const pointer of pointers) {
600
- const known = this.checksums.get(pointer.snapshot);
601
- if (known && known !== pointer.sha256) {
602
- throw new Error("Remote history conflicts with an already observed snapshot checksum.");
603
- }
604
- }
605
- for (const pointer of pointers) this.registerChecksum(pointer.snapshot, pointer.sha256);
606
- return pointers.map(remoteHistoryEntry);
607
- }
608
- async diagnose(signal) {
609
- throwIfAborted(signal);
610
- const diagnostics = [
611
- {
612
- key: "s3-config",
613
- level: "info",
614
- message: `s3 config: ok (${this.config.destination.bucket}/${storageRoot(this.config)})`
615
- },
616
- ...sessionTokenWarnings(this.config.profile).map((message) => ({
617
- key: "s3-session-token",
618
- level: "warning",
619
- message
620
- }))
621
- ];
622
- const deadline = AbortSignal.timeout(1e4);
623
- const probeSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
624
- try {
625
- const result = await new S3Client(this.config, probeSignal).diagnoseRead(latestKey(this.config));
626
- throwIfAborted(probeSignal);
627
- const messages = {
628
- readable: "s3 remote read: HTTP success. Snapshot contents and write access are not tested.",
629
- "missing-key": "s3 remote read: no snapshot at this path (NoSuchKey). Write access is not tested; verify the bucket and path before first sync.",
630
- "missing-bucket": "s3 remote read: bucket not found (NoSuchBucket). Create the bucket with your provider or edit the setup's bucket name.",
631
- "unknown-404": "s3 remote read: HTTP 404; cannot confirm whether the bucket or snapshot is missing. Verify the endpoint, bucket, and path with your provider. Write access is not tested."
632
- };
633
- diagnostics.push({
634
- key: "s3-read",
635
- level: result === "readable" ? "info" : "warning",
636
- message: messages[result]
637
- });
638
- } catch (error) {
639
- throwIfAborted(signal);
640
- diagnostics.push({
641
- key: "s3-read",
642
- level: "warning",
643
- message: syncErrorGuidance(deadline.aborted ? new Error("S3 diagnostic request timed out.") : error)
644
- });
645
- }
646
- return diagnostics;
647
- }
648
- async resolveChecksum(reference, signal) {
649
- await this.readHead(signal);
650
- const headChecksum = this.checksums.get(reference);
651
- if (headChecksum) return headChecksum;
652
- await this.listHistory(signal);
653
- return this.checksums.get(reference);
654
- }
655
- registerChecksum(reference, checksum) {
656
- const known = this.checksums.get(reference);
657
- if (known && known !== checksum) {
658
- throw new Error("Remote snapshot reference was rebound to a different checksum.");
659
- }
660
- this.checksums.set(reference, checksum);
661
- }
662
- async updateHistorySafely(client, pointer) {
663
- try {
664
- await this.updateHistory(client, pointer);
665
- return void 0;
666
- } catch (error) {
667
- return `Remote snapshot is active, but history could not be updated: ${errorMessage2(error)}. Run /sync doctor before relying on history.`;
668
- }
669
- }
670
- async updateHistory(client, pointer) {
671
- const object = await client.getJson(historyKey(this.config));
672
- const snapshots = object.missing ? [] : requireHistory(object.value, this.config.destination.namespace);
673
- const existing = snapshots.find((snapshot) => snapshot.snapshot === pointer.snapshot);
674
- if (existing) {
675
- if (!samePointer(existing, pointer)) throw new Error("Remote history rebound an immutable snapshot reference.");
676
- return;
677
- }
678
- const next = [...snapshots, pointer].slice(-100);
679
- const condition = object.missing ? { ifAbsent: true } : { ifMatch: requireS3Etag(object.etag) };
680
- await client.putJson(historyKey(this.config), { version: VERSION, snapshots: next }, condition);
681
- }
682
- };
683
- function latestKey(config) {
684
- return posixJoin(storageRoot(config), "latest.json");
685
- }
686
- function historyKey(config) {
687
- return posixJoin(storageRoot(config), "history.json");
688
- }
689
- function snapshotKey(config, id) {
690
- requireSnapshotReference(id);
691
- return posixJoin(storageRoot(config), "snapshots", `${id}.json.gz`);
692
- }
693
- function storageRoot(config) {
694
- return config.destination.prefix === "./" ? "" : config.destination.prefix;
695
- }
696
- function pointerFor(config, snapshot, checksum) {
697
- return createLatestPointer(config.destination.namespace, snapshot, checksum);
698
- }
699
- function s3BackendIdentity(config) {
700
- const destination = JSON.stringify([
701
- secretFreeEndpoint(config.profile.endpoint),
702
- trimSlashes(config.destination.bucket),
703
- trimSlashes(config.destination.prefix)
704
- ]);
705
- return `s3:${sha2562(Buffer.from(destination))}`;
706
- }
707
- function s3Destination(config) {
708
- let host = secretFreeEndpoint(config.profile.endpoint);
709
- try {
710
- host = new URL(host).hostname;
711
- } catch {
712
- host = "invalid S3 endpoint";
713
- }
714
- return `${host} \xB7 ${config.destination.bucket}/${storageRoot(config)}`;
715
- }
716
- function secretFreeEndpoint(value) {
717
- const normalized = value.trim();
718
- try {
719
- const url = new URL(normalized);
720
- url.username = "";
721
- url.password = "";
722
- return url.toString();
723
- } catch {
724
- return normalized.replace(/\/\/[^/@\s]+@/u, "//");
725
- }
726
- }
727
- function trimSlashes(value) {
728
- return value.replace(/^\/+|\/+$/g, "");
729
- }
730
- function remoteHead(pointer, identity, etag) {
731
- return {
732
- snapshotRef: pointer.snapshot,
733
- snapshotId: pointer.snapshot,
734
- revision: `s3:${sha2562(Buffer.from(canonicalJson([identity, etag ?? null, pointer])))}`,
735
- createdAt: pointer.createdAt,
736
- machine: pointer.machine,
737
- syncSessions: pointer.syncSessions === true,
738
- ...pointer.selection === void 0 ? {} : { selection: pointer.selection }
739
- };
740
- }
741
- function samePointer(left, right) {
742
- return canonicalJson(left) === canonicalJson(right);
743
- }
744
- function canonicalJson(value) {
745
- return JSON.stringify(canonicalValue(value));
746
- }
747
- function canonicalValue(value) {
748
- if (Array.isArray(value)) return value.map(canonicalValue);
749
- if (!value || typeof value !== "object") return value;
750
- return Object.fromEntries(
751
- Object.keys(value).sort().map((key) => [key, canonicalValue(value[key])])
752
- );
753
- }
754
- function matchesExpected(head, expected) {
755
- if (expected.kind === "missing") return head === void 0;
756
- return head?.revision === expected.revision;
757
- }
758
- function requirePointer(value, message, expectedProfile) {
759
- if (!value || value.version !== VERSION || value.profile !== expectedProfile || typeof value.snapshot !== "string" || !isSafeSnapshotReference(value.snapshot) || typeof value.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(value.sha256) || typeof value.createdAt !== "string" || !isSafeMetadata(value.createdAt, 64) || typeof value.machine !== "string" || !isSafeMetadata(value.machine, 256) || value.syncSessions !== void 0 && typeof value.syncSessions !== "boolean") {
760
- throw new Error(message);
761
- }
762
- if (value.selection !== void 0) portableSnapshotSelection(value.selection);
763
- return value;
764
- }
765
- function requireHistory(value, expectedProfile) {
766
- if (!value || value.version !== VERSION || !Array.isArray(value.snapshots)) {
767
- throw new Error("Remote history is malformed.");
768
- }
769
- const pointers = value.snapshots.map(
770
- (pointer) => requirePointer(pointer, "Remote history entry is malformed.", expectedProfile)
771
- );
772
- const references = /* @__PURE__ */ new Set();
773
- for (const pointer of pointers) {
774
- if (references.has(pointer.snapshot)) {
775
- throw new Error("Remote history contains duplicate snapshot references.");
776
- }
777
- references.add(pointer.snapshot);
778
- }
779
- return pointers;
780
- }
781
- function assertSnapshotIdentity(snapshot, expectedProfile) {
782
- validatePortableSnapshot(snapshot);
783
- if (snapshot.profile !== expectedProfile || !isSafeSnapshotReference(snapshot.id) || !isSafeMetadata(snapshot.createdAt, 64) || !isSafeMetadata(snapshot.machine, 256) || !Array.isArray(snapshot.files)) {
784
- throw new Error("Invalid snapshot identity for S3 publication.");
785
- }
786
- }
787
- function validateSnapshotBundle(snapshot) {
788
- const paths = /* @__PURE__ */ new Set();
789
- for (const file of snapshot.files) {
790
- if (!file || typeof file.path !== "string" || typeof file.contentBase64 !== "string" || typeof file.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(file.sha256) || paths.has(file.path)) {
791
- throw new Error("Remote snapshot bundle is malformed.");
792
- }
793
- const content = Buffer.from(file.contentBase64, "base64");
794
- if (content.toString("base64") !== file.contentBase64 || sha2562(content) !== file.sha256) {
795
- throw new Error("Remote snapshot file checksum mismatch.");
796
- }
797
- paths.add(file.path);
798
- }
799
- }
800
- function assertSafeDestination(config) {
801
- for (const [label, value, allowEmpty] of [
802
- ["bucket", config.destination.bucket, false],
803
- ["prefix", config.destination.prefix, true],
804
- ["namespace", config.destination.namespace, false]
805
- ]) {
806
- if (label === "prefix" && value === "./") continue;
807
- if (!allowEmpty && value.length === 0 || value.includes("\\") || hasControlCharacter(value) || value.split("/").some((segment) => segment === "." || segment === "..")) {
808
- throw new Error(`Invalid S3 storage location ${label}.`);
809
- }
810
- }
811
- }
812
- function requireSnapshotReference(reference) {
813
- if (!isSafeSnapshotReference(reference)) {
814
- throw new Error("Invalid S3 snapshot reference.");
815
- }
816
- }
817
- function isSafeSnapshotReference(reference) {
818
- return reference.length > 0 && reference.length <= 512 && reference !== "." && reference !== ".." && !reference.includes("/") && !reference.includes("\\") && !hasControlCharacter(reference);
819
- }
820
- function isSafeMetadata(value, maxLength) {
821
- return value.length > 0 && value.length <= maxLength && !hasControlCharacter(value);
822
- }
823
- function hasControlCharacter(value) {
824
- return [...value].some((character) => {
825
- const code = character.codePointAt(0) ?? 0;
826
- return code < 32 || code === 127;
827
- });
828
- }
829
- function sha2562(value) {
830
- return createHash2("sha256").update(value).digest("hex");
831
- }
832
- function errorMessage2(error) {
833
- return error instanceof Error ? error.message : String(error);
834
- }
835
- export {
836
- S3SyncBackend,
837
- encodeKey,
838
- historyKey,
839
- latestKey,
840
- pointerFor,
841
- s3BackendIdentity,
842
- snapshotKey,
843
- storageRoot
844
- };
845
- //# sourceMappingURL=s3-backend-FDK7JSDQ.ts.map