@powerhousedao/shared 6.2.3-dev.23 → 6.2.3-dev.25

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 (264) hide show
  1. package/dist/analytics/index.d.ts +4 -4
  2. package/dist/analytics/index.d.ts.map +1 -1
  3. package/dist/analytics/index.js +25 -24
  4. package/dist/analytics/index.js.map +1 -1
  5. package/dist/clis/args/{access-token-Bf1K1Fpc.mjs → access-token-3Hqv_U8I.mjs} +2 -2
  6. package/dist/clis/args/{access-token-Bf1K1Fpc.mjs.map → access-token-3Hqv_U8I.mjs.map} +1 -1
  7. package/dist/clis/args/access-token-C5sKsH2O.d.mts +16 -0
  8. package/dist/clis/args/access-token-C5sKsH2O.d.mts.map +1 -0
  9. package/dist/clis/args/access-token.d.mts +3 -2
  10. package/dist/clis/args/access-token.mjs +1 -1
  11. package/dist/clis/args/{common-BpnFLR-_.mjs → common-BXabdhiO.mjs} +10 -2
  12. package/dist/clis/args/{common-BpnFLR-_.mjs.map → common-BXabdhiO.mjs.map} +1 -1
  13. package/dist/clis/args/common-Bnm859xU.d.mts +186 -0
  14. package/dist/clis/args/common-Bnm859xU.d.mts.map +1 -0
  15. package/dist/clis/args/common.d.mts +3 -2
  16. package/dist/clis/args/common.mjs +1 -1
  17. package/dist/clis/args/{connect-ByiLv365.mjs → connect-B6xK4YI_.mjs} +2 -2
  18. package/dist/clis/args/{connect-ByiLv365.mjs.map → connect-B6xK4YI_.mjs.map} +1 -1
  19. package/dist/clis/args/connect-DjeiqXus.d.mts +450 -0
  20. package/dist/clis/args/connect-DjeiqXus.d.mts.map +1 -0
  21. package/dist/clis/args/connect.d.mts +3 -2
  22. package/dist/clis/args/connect.mjs +1 -1
  23. package/dist/clis/args/{generate-C51i00At.mjs → generate-10dooJ-D.mjs} +2 -2
  24. package/dist/clis/args/{generate-C51i00At.mjs.map → generate-10dooJ-D.mjs.map} +1 -1
  25. package/dist/clis/args/generate-DmgiCzuf.d.mts +106 -0
  26. package/dist/clis/args/generate-DmgiCzuf.d.mts.map +1 -0
  27. package/dist/clis/args/generate.d.mts +3 -2
  28. package/dist/clis/args/generate.mjs +1 -1
  29. package/dist/clis/args/help-DVPTARGn.d.mts +190 -0
  30. package/dist/clis/args/help-DVPTARGn.d.mts.map +1 -0
  31. package/dist/clis/args/{help-D2SeQC09.mjs → help-yRmplJjW.mjs} +15 -15
  32. package/dist/clis/args/{help-D2SeQC09.mjs.map → help-yRmplJjW.mjs.map} +1 -1
  33. package/dist/clis/args/help.d.mts +3 -2
  34. package/dist/clis/args/help.mjs +1 -1
  35. package/dist/clis/args/index.d.mts +20 -19
  36. package/dist/clis/args/index.mjs +18 -18
  37. package/dist/clis/args/init-CFeTq4Cq.d.mts +52 -0
  38. package/dist/clis/args/init-CFeTq4Cq.d.mts.map +1 -0
  39. package/dist/clis/args/{init-DBYYsV0Y.mjs → init-Dvb42Y87.mjs} +2 -2
  40. package/dist/clis/args/{init-DBYYsV0Y.mjs.map → init-Dvb42Y87.mjs.map} +1 -1
  41. package/dist/clis/args/init.d.mts +3 -2
  42. package/dist/clis/args/init.mjs +1 -1
  43. package/dist/clis/args/inspect-BjRmtB86.d.mts +13 -0
  44. package/dist/clis/args/inspect-BjRmtB86.d.mts.map +1 -0
  45. package/dist/clis/args/{inspect-BzBsZ0UO.mjs → inspect-UNQgtuR0.mjs} +2 -2
  46. package/dist/clis/args/{inspect-BzBsZ0UO.mjs.map → inspect-UNQgtuR0.mjs.map} +1 -1
  47. package/dist/clis/args/inspect.d.mts +3 -2
  48. package/dist/clis/args/inspect.mjs +1 -1
  49. package/dist/clis/args/install-B0tMyUMw.d.mts +37 -0
  50. package/dist/clis/args/install-B0tMyUMw.d.mts.map +1 -0
  51. package/dist/clis/args/{install-D0jaysiP.mjs → install-F-27kF6m.mjs} +2 -2
  52. package/dist/clis/args/{install-D0jaysiP.mjs.map → install-F-27kF6m.mjs.map} +1 -1
  53. package/dist/clis/args/install.d.mts +3 -2
  54. package/dist/clis/args/install.mjs +1 -1
  55. package/dist/clis/args/{list-BaO47Btz.mjs → list-Bkfn8Yuo.mjs} +2 -2
  56. package/dist/clis/args/{list-BaO47Btz.mjs.map → list-Bkfn8Yuo.mjs.map} +1 -1
  57. package/dist/clis/args/list-DrbxA7JJ.d.mts +10 -0
  58. package/dist/clis/args/list-DrbxA7JJ.d.mts.map +1 -0
  59. package/dist/clis/args/list.d.mts +3 -2
  60. package/dist/clis/args/list.mjs +1 -1
  61. package/dist/clis/args/{login-DM-qhiYI.mjs → login-CIFkQExi.mjs} +2 -2
  62. package/dist/clis/args/{login-DM-qhiYI.mjs.map → login-CIFkQExi.mjs.map} +1 -1
  63. package/dist/clis/args/login-CXRJXg71.d.mts +25 -0
  64. package/dist/clis/args/login-CXRJXg71.d.mts.map +1 -0
  65. package/dist/clis/args/login.d.mts +3 -2
  66. package/dist/clis/args/login.mjs +1 -1
  67. package/dist/clis/args/{magic-string.es-h_0HDQBQ.mjs → magic-string.es-CB2hOw9v.mjs} +14 -13
  68. package/dist/clis/args/{magic-string.es-h_0HDQBQ.mjs.map → magic-string.es-CB2hOw9v.mjs.map} +1 -1
  69. package/dist/clis/args/migrate-DkCQRL2D.d.mts +19 -0
  70. package/dist/clis/args/migrate-DkCQRL2D.d.mts.map +1 -0
  71. package/dist/clis/args/{migrate-EitaI7jq.mjs → migrate-DwJGhc2d.mjs} +2 -2
  72. package/dist/clis/args/{migrate-EitaI7jq.mjs.map → migrate-DwJGhc2d.mjs.map} +1 -1
  73. package/dist/clis/args/migrate.d.mts +3 -2
  74. package/dist/clis/args/migrate.mjs +1 -1
  75. package/dist/clis/args/publish-CeW4bOrl.d.mts +16 -0
  76. package/dist/clis/args/publish-CeW4bOrl.d.mts.map +1 -0
  77. package/dist/clis/args/{publish-DfMF3Nmc.mjs → publish-DHqlGWmL.mjs} +2 -2
  78. package/dist/clis/args/{publish-DfMF3Nmc.mjs.map → publish-DHqlGWmL.mjs.map} +1 -1
  79. package/dist/clis/args/publish.d.mts +3 -2
  80. package/dist/clis/args/publish.mjs +1 -1
  81. package/dist/clis/args/{registry-Di1tZqbn.mjs → registry-DIwES3l2.mjs} +2 -2
  82. package/dist/clis/args/{registry-Di1tZqbn.mjs.map → registry-DIwES3l2.mjs.map} +1 -1
  83. package/dist/clis/args/registry-DNH8xuaE.d.mts +17 -0
  84. package/dist/clis/args/registry-DNH8xuaE.d.mts.map +1 -0
  85. package/dist/clis/args/registry.d.mts +3 -2
  86. package/dist/clis/args/registry.mjs +1 -1
  87. package/dist/clis/args/service-BBx5GDTc.d.mts +27 -0
  88. package/dist/clis/args/service-BBx5GDTc.d.mts.map +1 -0
  89. package/dist/clis/args/{service-jRX2qPul.mjs → service-Cpjlyeu5.mjs} +2 -2
  90. package/dist/clis/args/{service-jRX2qPul.mjs.map → service-Cpjlyeu5.mjs.map} +1 -1
  91. package/dist/clis/args/service.d.mts +3 -2
  92. package/dist/clis/args/service.mjs +1 -1
  93. package/dist/clis/args/{switchboard-BhR-ZwGV.mjs → switchboard-CCaAtU56.mjs} +2 -2
  94. package/dist/clis/args/{switchboard-BhR-ZwGV.mjs.map → switchboard-CCaAtU56.mjs.map} +1 -1
  95. package/dist/clis/args/switchboard-RrNb1fUH.d.mts +70 -0
  96. package/dist/clis/args/switchboard-RrNb1fUH.d.mts.map +1 -0
  97. package/dist/clis/args/switchboard.d.mts +3 -2
  98. package/dist/clis/args/switchboard.mjs +1 -1
  99. package/dist/clis/args/{uninstall-diefi70g.mjs → uninstall-3U0B8g5c.mjs} +2 -2
  100. package/dist/clis/args/{uninstall-diefi70g.mjs.map → uninstall-3U0B8g5c.mjs.map} +1 -1
  101. package/dist/clis/args/uninstall-CDx7lwxn.d.mts +28 -0
  102. package/dist/clis/args/uninstall-CDx7lwxn.d.mts.map +1 -0
  103. package/dist/clis/args/uninstall.d.mts +3 -2
  104. package/dist/clis/args/uninstall.mjs +1 -1
  105. package/dist/clis/args/unpublish-CEDsk6uv.d.mts +22 -0
  106. package/dist/clis/args/unpublish-CEDsk6uv.d.mts.map +1 -0
  107. package/dist/clis/args/{unpublish-C6eNRzsU.mjs → unpublish-s9zUh6Gw.mjs} +2 -2
  108. package/dist/clis/args/{unpublish-C6eNRzsU.mjs.map → unpublish-s9zUh6Gw.mjs.map} +1 -1
  109. package/dist/clis/args/unpublish.d.mts +3 -2
  110. package/dist/clis/args/unpublish.mjs +1 -1
  111. package/dist/clis/args/{vetra-DV0zQzba.mjs → vetra-BUNlAAPp.mjs} +2 -2
  112. package/dist/clis/args/{vetra-DV0zQzba.mjs.map → vetra-BUNlAAPp.mjs.map} +1 -1
  113. package/dist/clis/args/vetra-DkDaWFPi.d.mts +111 -0
  114. package/dist/clis/args/vetra-DkDaWFPi.d.mts.map +1 -0
  115. package/dist/clis/args/vetra-ports.test.d.mts +2 -1
  116. package/dist/clis/args/vetra-ports.test.mjs +281 -176
  117. package/dist/clis/args/vetra-ports.test.mjs.map +1 -1
  118. package/dist/clis/args/vetra.d.mts +3 -2
  119. package/dist/clis/args/vetra.mjs +1 -1
  120. package/dist/clis/{build-config-BkfXtfV8.mjs → build-config-CmdMi_wu.mjs} +3 -3
  121. package/dist/clis/{build-config-BkfXtfV8.mjs.map → build-config-CmdMi_wu.mjs.map} +1 -1
  122. package/dist/clis/build-config.d.mts +20 -17
  123. package/dist/clis/build-config.d.mts.map +1 -1
  124. package/dist/clis/build-config.mjs +1 -1
  125. package/dist/clis/build-pieces.d.mts +43 -37
  126. package/dist/clis/build-pieces.d.mts.map +1 -1
  127. package/dist/clis/build-pieces.mjs +3 -2
  128. package/dist/clis/build-pieces.mjs.map +1 -1
  129. package/dist/clis/command-names.d.mts +2 -2
  130. package/dist/clis/command-names.d.mts.map +1 -1
  131. package/dist/clis/command-names.mjs.map +1 -1
  132. package/dist/clis/constants.d.mts +3 -2
  133. package/dist/clis/constants.mjs +3 -3
  134. package/dist/clis/constants.mjs.map +1 -1
  135. package/dist/clis/{index-CyAv0ucZ.d.mts → index-DpixpHXl.d.mts} +1800 -1265
  136. package/dist/clis/index-DpixpHXl.d.mts.map +1 -0
  137. package/dist/clis/index.d.mts +1295 -1254
  138. package/dist/clis/index.d.mts.map +1 -1
  139. package/dist/clis/index.mjs +92 -55
  140. package/dist/clis/index.mjs.map +1 -1
  141. package/dist/clis/project-env.d.mts +4 -4
  142. package/dist/clis/project-env.d.mts.map +1 -1
  143. package/dist/clis/project-env.mjs.map +1 -1
  144. package/dist/clis/project-ports.d.mts +5 -5
  145. package/dist/clis/project-ports.d.mts.map +1 -1
  146. package/dist/clis/project-ports.mjs +1 -1
  147. package/dist/clis/project-ports.mjs.map +1 -1
  148. package/dist/clis/services/telemetry.d.mts +7 -7
  149. package/dist/clis/services/telemetry.d.mts.map +1 -1
  150. package/dist/clis/services/telemetry.mjs.map +1 -1
  151. package/dist/clis/{types-DXhVHupa.d.mts → types-CMFHKrgv.d.mts} +67 -29
  152. package/dist/clis/types-CMFHKrgv.d.mts.map +1 -0
  153. package/dist/clis/utils.d.mts +4 -4
  154. package/dist/clis/utils.d.mts.map +1 -1
  155. package/dist/clis/utils.mjs.map +1 -1
  156. package/dist/{config-loader-e4-qdVVI.js → config-loader-SYDWHtqk.js} +12 -7
  157. package/dist/config-loader-SYDWHtqk.js.map +1 -0
  158. package/dist/connect/config-loader.d.ts +7 -8
  159. package/dist/connect/config-loader.d.ts.map +1 -1
  160. package/dist/connect/config-loader.js +1 -1
  161. package/dist/connect/index.d.ts +75 -68
  162. package/dist/connect/index.d.ts.map +1 -1
  163. package/dist/connect/index.js +88 -30
  164. package/dist/connect/index.js.map +1 -1
  165. package/dist/connect/json-adapter.d.ts +3 -4
  166. package/dist/connect/json-adapter.d.ts.map +1 -1
  167. package/dist/connect/json-adapter.js.map +1 -1
  168. package/dist/{constants-BP_gjn8g.d.ts → constants-DO4IYxuR.d.ts} +2 -1
  169. package/dist/constants-DO4IYxuR.d.ts.map +1 -0
  170. package/dist/constants.d.ts +3 -2
  171. package/dist/constants.js.map +1 -1
  172. package/dist/document-drive/index.d.ts +104 -101
  173. package/dist/document-drive/index.d.ts.map +1 -1
  174. package/dist/document-drive/index.js +15 -4
  175. package/dist/document-drive/index.js.map +1 -1
  176. package/dist/document-model/index.d.ts +5 -4
  177. package/dist/document-model/index.js +440 -226
  178. package/dist/document-model/index.js.map +1 -1
  179. package/dist/document-model/mock.d.ts +2 -3
  180. package/dist/document-model/mock.d.ts.map +1 -1
  181. package/dist/document-model/mock.js +2 -1
  182. package/dist/document-model/mock.js.map +1 -1
  183. package/dist/document-model/utils.d.ts +3 -2
  184. package/dist/document-model/utils.js +1 -1
  185. package/dist/{index-CAs0TFVQ.d.ts → index-CDDyUSHE.d.ts} +40 -28
  186. package/dist/index-CDDyUSHE.d.ts.map +1 -0
  187. package/dist/index-D0JljlgO.d.ts +36 -0
  188. package/dist/index-D0JljlgO.d.ts.map +1 -0
  189. package/dist/index.d.ts +7 -6
  190. package/dist/index.js.map +1 -1
  191. package/dist/processors/index.d.ts +3 -2
  192. package/dist/processors/index.js +5 -1
  193. package/dist/processors/index.js.map +1 -1
  194. package/dist/registry/index.d.ts +15 -15
  195. package/dist/registry/index.d.ts.map +1 -1
  196. package/dist/registry/index.js +2 -1
  197. package/dist/registry/index.js.map +1 -1
  198. package/dist/registry/manifest-slim.d.ts +4 -3
  199. package/dist/registry/manifest-slim.d.ts.map +1 -1
  200. package/dist/registry/manifest-slim.js.map +1 -1
  201. package/dist/registry/updates.d.ts +3 -3
  202. package/dist/registry/updates.d.ts.map +1 -1
  203. package/dist/registry/updates.js.map +1 -1
  204. package/dist/registry/urls.d.ts +2 -2
  205. package/dist/registry/urls.d.ts.map +1 -1
  206. package/dist/registry/urls.js.map +1 -1
  207. package/dist/{types-C1in4fl3.d.ts → types-Bsp8VL2y.d.ts} +2 -2
  208. package/dist/types-Bsp8VL2y.d.ts.map +1 -0
  209. package/dist/{types-ooGknils.d.ts → types-VDHUeQnm.d.ts} +17 -35
  210. package/dist/types-VDHUeQnm.d.ts.map +1 -0
  211. package/dist/{types-glwGlTGx.d.ts → types-xLPOHE23.d.ts} +532 -433
  212. package/dist/types-xLPOHE23.d.ts.map +1 -0
  213. package/dist/{utils-DP122OSS.d.ts → utils-BrKxCmKx.d.ts} +2 -2
  214. package/dist/utils-BrKxCmKx.d.ts.map +1 -0
  215. package/dist/{utils-aaTmfxFW.js → utils-XotexSsQ.js} +3 -2
  216. package/dist/{utils-aaTmfxFW.js.map → utils-XotexSsQ.js.map} +1 -1
  217. package/package.json +5 -4
  218. package/dist/clis/args/access-token--9H57y8J.d.mts +0 -18
  219. package/dist/clis/args/access-token--9H57y8J.d.mts.map +0 -1
  220. package/dist/clis/args/common-yKU4B741.d.mts +0 -186
  221. package/dist/clis/args/common-yKU4B741.d.mts.map +0 -1
  222. package/dist/clis/args/connect-BD-C5BkE.d.mts +0 -452
  223. package/dist/clis/args/connect-BD-C5BkE.d.mts.map +0 -1
  224. package/dist/clis/args/generate-rd5SAYho.d.mts +0 -108
  225. package/dist/clis/args/generate-rd5SAYho.d.mts.map +0 -1
  226. package/dist/clis/args/help-CjAsudUn.d.mts +0 -193
  227. package/dist/clis/args/help-CjAsudUn.d.mts.map +0 -1
  228. package/dist/clis/args/init-CUXyfquF.d.mts +0 -55
  229. package/dist/clis/args/init-CUXyfquF.d.mts.map +0 -1
  230. package/dist/clis/args/inspect-DtZeoA5c.d.mts +0 -15
  231. package/dist/clis/args/inspect-DtZeoA5c.d.mts.map +0 -1
  232. package/dist/clis/args/install-CkP8zcHb.d.mts +0 -40
  233. package/dist/clis/args/install-CkP8zcHb.d.mts.map +0 -1
  234. package/dist/clis/args/list-BGf8s_gj.d.mts +0 -12
  235. package/dist/clis/args/list-BGf8s_gj.d.mts.map +0 -1
  236. package/dist/clis/args/login-DNsHwvqk.d.mts +0 -27
  237. package/dist/clis/args/login-DNsHwvqk.d.mts.map +0 -1
  238. package/dist/clis/args/migrate-sixkWhxm.d.mts +0 -21
  239. package/dist/clis/args/migrate-sixkWhxm.d.mts.map +0 -1
  240. package/dist/clis/args/publish-Dqe5DUst.d.mts +0 -18
  241. package/dist/clis/args/publish-Dqe5DUst.d.mts.map +0 -1
  242. package/dist/clis/args/registry-C_RfTsKB.d.mts +0 -19
  243. package/dist/clis/args/registry-C_RfTsKB.d.mts.map +0 -1
  244. package/dist/clis/args/service-Cou6l7l8.d.mts +0 -22
  245. package/dist/clis/args/service-Cou6l7l8.d.mts.map +0 -1
  246. package/dist/clis/args/switchboard-BlPaq2at.d.mts +0 -72
  247. package/dist/clis/args/switchboard-BlPaq2at.d.mts.map +0 -1
  248. package/dist/clis/args/uninstall-BpA3YYbw.d.mts +0 -31
  249. package/dist/clis/args/uninstall-BpA3YYbw.d.mts.map +0 -1
  250. package/dist/clis/args/unpublish-CvwaIimG.d.mts +0 -24
  251. package/dist/clis/args/unpublish-CvwaIimG.d.mts.map +0 -1
  252. package/dist/clis/args/vetra-CoMvTJK7.d.mts +0 -113
  253. package/dist/clis/args/vetra-CoMvTJK7.d.mts.map +0 -1
  254. package/dist/clis/index-CyAv0ucZ.d.mts.map +0 -1
  255. package/dist/clis/types-DXhVHupa.d.mts.map +0 -1
  256. package/dist/config-loader-e4-qdVVI.js.map +0 -1
  257. package/dist/constants-BP_gjn8g.d.ts.map +0 -1
  258. package/dist/index-CAs0TFVQ.d.ts.map +0 -1
  259. package/dist/index-C_iVZe7f.d.ts +0 -7
  260. package/dist/index-C_iVZe7f.d.ts.map +0 -1
  261. package/dist/types-C1in4fl3.d.ts.map +0 -1
  262. package/dist/types-glwGlTGx.d.ts.map +0 -1
  263. package/dist/types-ooGknils.d.ts.map +0 -1
  264. package/dist/utils-DP122OSS.d.ts.map +0 -1
@@ -1,9 +1,176 @@
1
- import { a as base58Decode, c as buildOperationSignatureParams, d as hex2ab, i as ab2hex, l as getUnixTimestamp, n as generateId, o as base64UrlToBytes, r as generateMock, s as buildOperationSignatureMessage, t as deriveOperationId, u as hashBrowser } from "../utils-aaTmfxFW.js";
1
+ import { a as base58Decode, c as buildOperationSignatureParams, d as hex2ab, i as ab2hex, l as getUnixTimestamp, n as generateId, o as base64UrlToBytes, r as generateMock, s as buildOperationSignatureMessage, t as deriveOperationId, u as hashBrowser } from "../utils-XotexSsQ.js";
2
2
  import { ZodError, z } from "zod";
3
3
  import { stringify } from "safe-stable-stringify";
4
+ import { sha256 } from "@noble/hashes/sha2.js";
4
5
  import { strFromU8, strToU8, unzip, zip } from "fflate";
5
- import { castDraft, create, unsafe } from "mutative";
6
+ import { castDraft, create, isDraft, original, unsafe } from "mutative";
6
7
  import { constantCase, pascalCase } from "change-case";
8
+ //#region document-model/action-signature.ts
9
+ const ACTION_SIGNATURE_V2_PREFIX = "v2:";
10
+ const V2_HASH = /^v2:[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
11
+ const V2_TIMESTAMP = /^[0-9]+$/;
12
+ const V2_SIGNATURE = /^0x[0-9a-f]{128}$/;
13
+ const LONE_SURROGATE = /\p{Cs}/u;
14
+ const PREIMAGE_FIELDS = [
15
+ "version",
16
+ "documentId",
17
+ "branch",
18
+ "scope",
19
+ "type",
20
+ "id",
21
+ "timestampUtcMs",
22
+ "input",
23
+ "signer.user.address",
24
+ "signer.user.networkId",
25
+ "signer.user.chainId",
26
+ "signer.app.key"
27
+ ];
28
+ /** A value that would not survive a JSON store round trip unchanged. */
29
+ var CanonicalJsonError = class extends Error {
30
+ constructor(path, detail) {
31
+ super(`Cannot canonicalize ${path}: ${detail}`);
32
+ this.name = "CanonicalJsonError";
33
+ }
34
+ };
35
+ /** Sorted-key JSON, as the state hash encodes; drops `undefined` properties. */
36
+ function canonicalJson(value, label = "value") {
37
+ assertCanonical(value, label, /* @__PURE__ */ new Set());
38
+ return stringify(value);
39
+ }
40
+ /** Actions the reactor reduces itself, onto the document scope. */
41
+ const DOCUMENT_SCOPE_ACTION_TYPES = /* @__PURE__ */ new Set([
42
+ "CREATE_DOCUMENT",
43
+ "DELETE_DOCUMENT",
44
+ "UPGRADE_DOCUMENT",
45
+ "ADD_RELATIONSHIP",
46
+ "REMOVE_RELATIONSHIP",
47
+ "UPDATE_RELATIONSHIP"
48
+ ]);
49
+ /** Where a document-scope action writes: `sourceId` or `documentId`. */
50
+ function targetDocumentId(action, fallback) {
51
+ const input = action.input;
52
+ if (action.type === "ADD_RELATIONSHIP" || action.type === "REMOVE_RELATIONSHIP" || action.type === "UPDATE_RELATIONSHIP") return typeof input?.sourceId === "string" && input.sourceId.length > 0 ? input.sourceId : fallback;
53
+ return typeof input?.documentId === "string" && input.documentId.length > 0 ? input.documentId : fallback;
54
+ }
55
+ /** The log an action submitted to a job on `documentId` is stored in. */
56
+ function actionSigningTarget(action, documentId, branch) {
57
+ return {
58
+ documentId: DOCUMENT_SCOPE_ACTION_TYPES.has(action.type) ? targetDocumentId(action, documentId) : documentId,
59
+ branch
60
+ };
61
+ }
62
+ /** The identity a signer writes into `context.signer`, and signs over. */
63
+ function actionSignerIdentity(signer) {
64
+ return {
65
+ user: {
66
+ address: signer.user?.address ?? "",
67
+ networkId: signer.user?.networkId ?? "",
68
+ chainId: signer.user?.chainId ?? 0
69
+ },
70
+ app: {
71
+ name: signer.app?.name ?? "",
72
+ key: signer.app?.key ?? ""
73
+ }
74
+ };
75
+ }
76
+ /** The v2 preimage; throws `CanonicalJsonError` on an unsignable action. */
77
+ function actionPreimageV2(action, target, signer) {
78
+ if (!target.documentId) throw new CanonicalJsonError("documentId", "must not be empty");
79
+ if (!target.branch) throw new CanonicalJsonError("branch", "must not be empty");
80
+ if (action.input === void 0) throw new CanonicalJsonError("input", `action ${action.id} (${action.type}) has no input`);
81
+ const fields = [
82
+ "v2",
83
+ target.documentId,
84
+ target.branch,
85
+ action.scope,
86
+ action.type,
87
+ action.id,
88
+ action.timestampUtcMs,
89
+ action.input,
90
+ signer.user.address,
91
+ signer.user.networkId,
92
+ signer.user.chainId,
93
+ signer.app.key
94
+ ];
95
+ fields.forEach((field, i) => {
96
+ assertCanonical(field, PREIMAGE_FIELDS[i], /* @__PURE__ */ new Set());
97
+ });
98
+ return stringify(fields);
99
+ }
100
+ /** `"v2:" + base64url(sha256(preimage))`, unpadded. */
101
+ async function hashActionV2(action, target, signer) {
102
+ const preimage = actionPreimageV2(action, target, signer);
103
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(preimage));
104
+ return "v2:" + bytesToBase64Url$1(new Uint8Array(digest));
105
+ }
106
+ /** Signs `action` as a v2 tuple; the message layout is the legacy one. */
107
+ async function signActionV2(params) {
108
+ const { action, target, signer, sign } = params;
109
+ const previousStateHash = params.previousStateHash ?? "";
110
+ if (previousStateHash.includes(", ")) throw new Error(`Cannot sign action ${action.id}: the previous state hash contains ", "`);
111
+ const tuple = [
112
+ (Date.now() / 1e3).toFixed(0),
113
+ signer.app.key,
114
+ await hashActionV2(action, target, signer),
115
+ previousStateHash
116
+ ];
117
+ const signature = await sign(buildOperationSignatureMessage(tuple));
118
+ if (signature.length !== 64) throw new Error(`Cannot sign action ${action.id}: expected a 64-byte P-256 signature, got ${signature.length} bytes`);
119
+ return [...tuple, `0x${bytesToHex(signature)}`];
120
+ }
121
+ /** Element [2] carries the v2 prefix, whether or not it is well formed. */
122
+ function isV2ActionHash(hash) {
123
+ return hash.startsWith("v2:");
124
+ }
125
+ /** The strict shape of a v2 tuple, apart from what its hash covers. */
126
+ function v2TupleProblem(tuple) {
127
+ if (!V2_TIMESTAMP.test(tuple[0])) return "signing time is not decimal seconds";
128
+ if (!V2_HASH.test(tuple[2])) return "hash is not v2: and 43 base64url characters";
129
+ if (!V2_SIGNATURE.test(tuple[4])) return "signature is not 0x and 128 lowercase hex digits";
130
+ }
131
+ function assertCanonical(value, path, ancestors) {
132
+ switch (typeof value) {
133
+ case "string":
134
+ if (LONE_SURROGATE.test(value)) throw new CanonicalJsonError(path, "string holds a lone surrogate");
135
+ return;
136
+ case "boolean": return;
137
+ case "number":
138
+ if (!Number.isFinite(value)) throw new CanonicalJsonError(path, `${value} is not a JSON number`);
139
+ return;
140
+ case "undefined": throw new CanonicalJsonError(path, "undefined is not a JSON value");
141
+ case "bigint": throw new CanonicalJsonError(path, "BigInt is not a JSON value");
142
+ case "function":
143
+ case "symbol": throw new CanonicalJsonError(path, `${typeof value} is not a JSON value`);
144
+ }
145
+ if (value === null) return;
146
+ const object = value;
147
+ if (ancestors.has(object)) throw new CanonicalJsonError(path, "value is circular");
148
+ const toJSON = object.toJSON;
149
+ if (typeof toJSON === "function") {
150
+ assertCanonical(toJSON.call(object), path, new Set(ancestors).add(object));
151
+ return;
152
+ }
153
+ ancestors.add(object);
154
+ if (Array.isArray(object)) for (let i = 0; i < object.length; i++) {
155
+ if (!(i in object)) throw new CanonicalJsonError(`${path}[${i}]`, "array is sparse");
156
+ assertCanonical(object[i], `${path}[${i}]`, ancestors);
157
+ }
158
+ else for (const [key, child] of Object.entries(object)) {
159
+ if (LONE_SURROGATE.test(key)) throw new CanonicalJsonError(path, "key holds a lone surrogate");
160
+ if (child === void 0) continue;
161
+ assertCanonical(child, `${path}.${key}`, ancestors);
162
+ }
163
+ ancestors.delete(object);
164
+ }
165
+ function bytesToBase64Url$1(bytes) {
166
+ let binary = "";
167
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
168
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
169
+ }
170
+ function bytesToHex(bytes) {
171
+ return Array.from(bytes).map((byte) => byte.toString(16).padStart(2, "0")).join("");
172
+ }
173
+ //#endregion
7
174
  //#region document-model/signatures.ts
8
175
  /**
9
176
  * What separates a signature's params when it travels as one string.
@@ -198,7 +365,7 @@ var GrantNotFoundError = class extends Error {
198
365
  }
199
366
  };
200
367
  /**
201
- * Thrown when a disallowed action (UNDO, REDO, PRUNE) targets the auth scope.
368
+ * Thrown when a disallowed action (UNDO, REDO) targets the auth scope.
202
369
  */
203
370
  var AuthActionNotAllowedError = class extends Error {
204
371
  actionType;
@@ -257,8 +424,6 @@ var UnsupportedDocumentModelVersionError = class extends Error {
257
424
  //#region document-model/schemas.ts
258
425
  const isDefinedNonNullAny = (v) => v !== void 0 && v !== null;
259
426
  const definedNonNullAnySchema = z.any().refine((v) => isDefinedNonNullAny(v));
260
- const Load_StateSchema = z.enum(["LOAD_STATE"]);
261
- const PruneSchema = z.enum(["PRUNE"]);
262
427
  const RedoSchema = z.enum(["REDO"]);
263
428
  const Set_NameSchema = z.enum(["SET_NAME"]);
264
429
  const Set_PreferredEditorSchema = z.enum(["SET_PREFERRED_EDITOR"]);
@@ -268,50 +433,12 @@ function OperationScopeSchema() {
268
433
  }
269
434
  function DocumentActionSchema() {
270
435
  return z.union([
271
- LoadStateActionSchema(),
272
- PruneActionSchema(),
273
436
  RedoActionSchema(),
274
437
  SetNameActionSchema(),
275
438
  SetPreferredEditorActionSchema(),
276
439
  UndoActionSchema()
277
440
  ]);
278
441
  }
279
- function LoadStateActionSchema() {
280
- return z.object({
281
- id: z.string(),
282
- timestampUtcMs: z.string(),
283
- input: z.lazy(() => LoadStateActionInputSchema()),
284
- type: Load_StateSchema,
285
- scope: OperationScopeSchema()
286
- });
287
- }
288
- function LoadStateActionInputSchema() {
289
- return z.object({
290
- operations: z.number(),
291
- state: z.lazy(() => LoadStateActionStateInputSchema())
292
- });
293
- }
294
- function LoadStateActionStateInputSchema() {
295
- return z.object({
296
- data: z.unknown().nullish(),
297
- name: z.string()
298
- });
299
- }
300
- function PruneActionSchema() {
301
- return z.object({
302
- id: z.string(),
303
- timestampUtcMs: z.string(),
304
- input: z.lazy(() => PruneActionInputSchema()),
305
- type: PruneSchema,
306
- scope: OperationScopeSchema()
307
- });
308
- }
309
- function PruneActionInputSchema() {
310
- return z.object({
311
- end: z.number().nullish(),
312
- start: z.number().nullish()
313
- });
314
- }
315
442
  function RedoActionInputSchema() {
316
443
  return z.object({ count: z.number() });
317
444
  }
@@ -862,35 +989,6 @@ const undo = (count = 1, scope = "global") => createAction("UNDO", { count }, vo
862
989
  * @category Actions
863
990
  */
864
991
  const redo = (count = 1, scope = "global") => createAction("REDO", { count }, void 0, RedoActionInputSchema, scope);
865
- /**
866
- * Joins multiple operations into a single {@link loadState | LOAD_STATE} operation.
867
- *
868
- * @remarks
869
- * Useful to keep operations history smaller. Operations to prune are selected by index,
870
- * similar to the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | slice} method in Arrays.
871
- *
872
- * @param start - Index of the first operation to prune
873
- * @param end - Index of the last operation to prune
874
- * @category Actions
875
- */
876
- const prune = (start, end, scope = "global") => createAction("PRUNE", {
877
- start,
878
- end
879
- }, void 0, PruneActionInputSchema, scope);
880
- /**
881
- * Replaces the state of the document.
882
- *
883
- * @remarks
884
- * This action shouldn't be used directly. It is dispatched by the {@link prune} action.
885
- *
886
- * @param state - State to be set in the document.
887
- * @param operations - Number of operations that were removed from the previous state.
888
- * @category Actions
889
- */
890
- const loadState = (state, operations) => createAction("LOAD_STATE", {
891
- state,
892
- operations
893
- }, void 0, LoadStateActionInputSchema);
894
992
  const noop = (scope = "global") => createAction("NOOP", {}, void 0, void 0, scope);
895
993
  /**
896
994
  * Helper function to be used by action creators.
@@ -988,6 +1086,7 @@ async function buildOperationSignature(context, signMethod) {
988
1086
  const signature = await signMethod(buildOperationSignatureMessage(params));
989
1087
  return [...params, `0x${ab2hex(signature)}`];
990
1088
  }
1089
+ /** @deprecated Emits a legacy SHA-1 tuple; sign through `ISigner.signAction`. */
991
1090
  async function buildSignedAction(action, reducer, document, signer, signHandler) {
992
1091
  const scopeOperations = reducer(document, action, void 0, { reuseOperationResultingState: true }).operations[action.scope];
993
1092
  if (!scopeOperations) throw new Error(`No operations found for scope: ${action.scope}`);
@@ -1000,8 +1099,10 @@ async function buildSignedAction(action, reducer, document, signer, signHandler)
1000
1099
  action,
1001
1100
  previousStateHash
1002
1101
  }, signHandler);
1003
- return operationWithContext(operation, { signer: actionSigner(signer.user, signer.app, [...signer.signatures, signature]) });
1102
+ const actionContext = { signer: actionSigner(signer.user, signer.app, [...signer.signatures, signature]) };
1103
+ return operationWithContext(operation, actionContext);
1004
1104
  }
1105
+ /** @deprecated Use `verifyActionSignature` from `@powerhousedao/reactor`. */
1005
1106
  async function verifyOperationSignature(signature, signer, verifyHandler) {
1006
1107
  const publicKey = signer.app.key;
1007
1108
  const params = signature.slice(0, 4);
@@ -1076,8 +1177,6 @@ const baseActions = {
1076
1177
  setPreferredEditor,
1077
1178
  undo,
1078
1179
  redo,
1079
- prune,
1080
- loadState,
1081
1180
  noop
1082
1181
  };
1083
1182
  const documentModelActions = {
@@ -1195,7 +1294,7 @@ var AuthAdministrationMissingError = class extends Error {
1195
1294
  this.name = "AuthAdministrationMissingError";
1196
1295
  }
1197
1296
  };
1198
- const GRANT_KEYS = new Set([
1297
+ const GRANT_KEYS = /* @__PURE__ */ new Set([
1199
1298
  "id",
1200
1299
  "description",
1201
1300
  "effect",
@@ -1203,13 +1302,13 @@ const GRANT_KEYS = new Set([
1203
1302
  "capability",
1204
1303
  "where"
1205
1304
  ]);
1206
- const PRINCIPAL_KINDS = new Set([
1305
+ const PRINCIPAL_KINDS = /* @__PURE__ */ new Set([
1207
1306
  "anyone",
1208
1307
  "address",
1209
1308
  "group",
1210
1309
  "match"
1211
1310
  ]);
1212
- const COMPARISON_CONDITION_KINDS = new Set([
1311
+ const COMPARISON_CONDITION_KINDS = /* @__PURE__ */ new Set([
1213
1312
  "eq",
1214
1313
  "ne",
1215
1314
  "lt",
@@ -2538,12 +2637,12 @@ function assertAuthPreservedOnDuplicate(documentId, source, duplicated) {
2538
2637
  * The auth scope a state snapshot may install, given the policy already there.
2539
2638
  *
2540
2639
  * `applyAuthAction` is the validated door onto `state.auth`, but a whole-state
2541
- * snapshot (UPGRADE_DOCUMENT's `initialState`, LOAD_STATE's `data`) replaces the
2542
- * scope wholesale and is authorized as a `document`-scope write. Without this,
2543
- * a subject holding `execute` on `document` and no auth grant at all can install
2544
- * a policy of its choosing, name itself `creator` (which exempts the policy from
2545
- * the retention rule for good), or wipe an existing policy by carrying the
2546
- * default uninitialized one.
2640
+ * snapshot (UPGRADE_DOCUMENT's `initialState`) replaces the scope wholesale and
2641
+ * is authorized as a `document`-scope write. Without this, a subject holding
2642
+ * `execute` on `document` and no auth grant at all can install a policy of its
2643
+ * choosing, name itself `creator` (which exempts the policy from the retention
2644
+ * rule for good), or wipe an existing policy by carrying the default
2645
+ * uninitialized one.
2547
2646
  *
2548
2647
  * Three cases:
2549
2648
  *
@@ -2570,13 +2669,9 @@ function resolveSnapshotAuth(documentId, documentType, current, incoming) {
2570
2669
  assertValidInitialGrants(incoming.grants, documentType, incoming.creator);
2571
2670
  return incoming;
2572
2671
  }
2573
- /** UNDO, REDO and PRUNE are rejected on the auth scope. */
2672
+ /** UNDO and REDO are rejected on the auth scope. */
2574
2673
  function assertAuthScopeActionAllowed(action) {
2575
- if (action.scope === "auth" && [
2576
- "UNDO",
2577
- "REDO",
2578
- "PRUNE"
2579
- ].includes(action.type)) throw new AuthActionNotAllowedError(action.type);
2674
+ if (action.scope === "auth" && ["UNDO", "REDO"].includes(action.type)) throw new AuthActionNotAllowedError(action.type);
2580
2675
  }
2581
2676
  /**
2582
2677
  * Evaluates the auth policy for a single request and reports why it refused.
@@ -2682,6 +2777,68 @@ function assertIsDocumentModelDocument(document) {
2682
2777
  DocumentModelSchema.parse(document);
2683
2778
  }
2684
2779
  //#endregion
2780
+ //#region document-model/signature-policy.ts
2781
+ /** The `protocolVersions` key that fixes a document's signature requirement. */
2782
+ const SIGNATURE_PROTOCOL = "signature";
2783
+ /** `protocolVersions.signature` of a document that requires v2 tuples. */
2784
+ const SIGNATURE_PROTOCOL_V2 = 2;
2785
+ /** What a new document is created as unless the caller or host says otherwise. */
2786
+ const DEFAULT_SIGNATURE_POLICY = "v2-required";
2787
+ function isSignaturePolicy(value) {
2788
+ return value === "legacy" || value === "v2-required";
2789
+ }
2790
+ const DERIVED_ID = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
2791
+ /** Read from a header, a CREATE_DOCUMENT input or a bare map. */
2792
+ function signaturePolicyOf(source) {
2793
+ const version = (source && "protocolVersions" in source ? source.protocolVersions : source)?.[SIGNATURE_PROTOCOL];
2794
+ return typeof version === "number" && version >= 2 ? "v2-required" : "legacy";
2795
+ }
2796
+ /** `protocolVersions` for a new v2-required document. */
2797
+ function v2RequiredProtocolVersions(base = {}) {
2798
+ return {
2799
+ "base-reducer": 2,
2800
+ ...base,
2801
+ [SIGNATURE_PROTOCOL]: 2
2802
+ };
2803
+ }
2804
+ /**
2805
+ * The policy a create call asks for: `signaturePolicy`, else the `signature`
2806
+ * key of its `protocolVersions`, else `fallback`, the host's default.
2807
+ */
2808
+ function requestedSignaturePolicy(request, fallback) {
2809
+ if (request?.signaturePolicy) return request.signaturePolicy;
2810
+ if (request?.protocolVersions?.["signature"] !== void 0) return signaturePolicyOf(request.protocolVersions);
2811
+ return fallback;
2812
+ }
2813
+ /** `protocolVersions` for a new document under `policy`, over `base`. */
2814
+ function protocolVersionsFor(policy, base = {}) {
2815
+ if (policy === "v2-required") return v2RequiredProtocolVersions(base);
2816
+ const { [SIGNATURE_PROTOCOL]: _signature, ...rest } = base;
2817
+ return {
2818
+ "base-reducer": 2,
2819
+ ...rest
2820
+ };
2821
+ }
2822
+ /** `base64url(sha256(canonicalJson(params)))`, unpadded. */
2823
+ function deriveDocumentId(params) {
2824
+ const preimage = canonicalJson({
2825
+ documentType: params.documentType,
2826
+ createdAtUtcIso: params.createdAtUtcIso,
2827
+ nonce: params.nonce,
2828
+ protocolVersions: params.protocolVersions
2829
+ }, "document id");
2830
+ return bytesToBase64Url(sha256(new TextEncoder().encode(preimage)));
2831
+ }
2832
+ /** Whether `id` has the shape `deriveDocumentId` produces. */
2833
+ function isDerivedDocumentId(id) {
2834
+ return DERIVED_ID.test(id);
2835
+ }
2836
+ function bytesToBase64Url(bytes) {
2837
+ let binary = "";
2838
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
2839
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2840
+ }
2841
+ //#endregion
2685
2842
  //#region document-model/header.ts
2686
2843
  /**
2687
2844
  * Generates a deterministic payload from signing parameters
@@ -2701,11 +2858,11 @@ async function createVerificationSigner(pubKey) {
2701
2858
  }, true, ["verify"]);
2702
2859
  return {
2703
2860
  publicKey: cryptoKey,
2704
- async sign(_data) {
2705
- throw new Error("verification-only signer cannot sign data");
2861
+ sign(_data) {
2862
+ return Promise.reject(/* @__PURE__ */ new Error("verification-only signer cannot sign data"));
2706
2863
  },
2707
- async signAction(_action, _abortSignal) {
2708
- throw new Error("verification-only signer cannot sign actions");
2864
+ signAction(_action, _target, _abortSignal) {
2865
+ return Promise.reject(/* @__PURE__ */ new Error("verification-only signer cannot sign actions"));
2709
2866
  },
2710
2867
  async verify(data, signature) {
2711
2868
  let isValid;
@@ -2775,26 +2932,68 @@ const validateHeader = async (header) => {
2775
2932
  * Creates a header that has yet to be signed. This header is not valid, but
2776
2933
  * can be input into {@link createSignedHeader} to create a signed header.
2777
2934
  *
2935
+ * With `protocolVersions` requiring v2 signatures the header takes a random
2936
+ * nonce and the id {@link deriveDocumentId} gives, so `id` must be omitted.
2937
+ *
2778
2938
  * @returns An unsigned header for a document.
2779
2939
  */
2780
- const createPresignedHeader = (id = generateId(), documentType = "") => {
2781
- return {
2782
- id,
2940
+ const createPresignedHeader = (id, documentType = "", protocolVersions) => {
2941
+ const createdAtUtcIso = (/* @__PURE__ */ new Date()).toISOString();
2942
+ const header = {
2943
+ id: id ?? generateId(),
2783
2944
  sig: {
2784
2945
  publicKey: {},
2785
2946
  nonce: ""
2786
2947
  },
2787
2948
  documentType,
2788
- createdAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),
2949
+ createdAtUtcIso,
2789
2950
  slug: "",
2790
2951
  name: "",
2791
2952
  branch: "main",
2792
2953
  revision: { document: 0 },
2793
- lastModifiedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),
2954
+ lastModifiedAtUtcIso: createdAtUtcIso,
2794
2955
  meta: {}
2795
2956
  };
2957
+ if (protocolVersions === void 0) return header;
2958
+ header.protocolVersions = { ...protocolVersions };
2959
+ if (signaturePolicyOf(header) === "legacy") return header;
2960
+ if (id !== void 0) throw new Error(`A v2-required document's id is derived from its header; cannot use ${id}`);
2961
+ header.sig.nonce = generateId();
2962
+ header.id = deriveDocumentId({
2963
+ documentType,
2964
+ createdAtUtcIso,
2965
+ nonce: header.sig.nonce,
2966
+ protocolVersions: header.protocolVersions
2967
+ });
2968
+ return header;
2796
2969
  };
2797
2970
  /**
2971
+ * A header for a copy of a document headed `source`. A copy is v2-required
2972
+ * when its source is or when `policy` asks for it, and then takes a derived id;
2973
+ * otherwise it takes `id`. It keeps the source's other protocol versions.
2974
+ */
2975
+ function createCopyHeader(source, id, policy = DEFAULT_SIGNATURE_POLICY) {
2976
+ const base = source.protocolVersions ?? {};
2977
+ if (signaturePolicyOf(source) === "v2-required" || policy === "v2-required") return createPresignedHeader(void 0, source.documentType, protocolVersionsFor("v2-required", base));
2978
+ const header = createPresignedHeader(id, source.documentType);
2979
+ if (source.protocolVersions) header.protocolVersions = { ...source.protocolVersions };
2980
+ return header;
2981
+ }
2982
+ /** Whether a v2-required `header` carries the id its params derive. */
2983
+ function hasDerivedDocumentId(header) {
2984
+ if (signaturePolicyOf(header) === "legacy" || !header.protocolVersions) return false;
2985
+ try {
2986
+ return deriveDocumentId({
2987
+ documentType: header.documentType,
2988
+ createdAtUtcIso: header.createdAtUtcIso,
2989
+ nonce: header.sig.nonce,
2990
+ protocolVersions: header.protocolVersions
2991
+ }) === header.id;
2992
+ } catch {
2993
+ return false;
2994
+ }
2995
+ }
2996
+ /**
2798
2997
  * Creates a new, signed header for a document. This will replace the id of the
2799
2998
  * document.
2800
2999
  *
@@ -2837,7 +3036,8 @@ const createSignedHeader = async (unsignedHeader, documentType, signer) => {
2837
3036
  * some are not. See the PHDocumentHeader type for more information.
2838
3037
  */
2839
3038
  const createSignedHeaderForSigner = async (documentType, signer) => {
2840
- return await createSignedHeader(createPresignedHeader(), documentType, signer);
3039
+ const unsignedHeader = createPresignedHeader();
3040
+ return await createSignedHeader(unsignedHeader, documentType, signer);
2841
3041
  };
2842
3042
  //#endregion
2843
3043
  //#region document-model/documents.ts
@@ -2855,9 +3055,7 @@ function isDocumentAction(action) {
2855
3055
  "SET_NAME",
2856
3056
  "SET_PREFERRED_EDITOR",
2857
3057
  "UNDO",
2858
- "REDO",
2859
- "PRUNE",
2860
- "LOAD_STATE"
3058
+ "REDO"
2861
3059
  ].includes(action.type);
2862
3060
  }
2863
3061
  /**
@@ -2913,12 +3111,16 @@ function createDocumentScopeOperations(header, state) {
2913
3111
  }
2914
3112
  /**
2915
3113
  * Creates a new document. When `documentType` is given the header is stamped
2916
- * with it and the document-scope operations are seeded.
3114
+ * with it and the document-scope operations are seeded. Without
3115
+ * `protocolVersions` the document is v2-required and takes a derived id; with
3116
+ * them it is v2-required only if they say so (see {@link protocolVersionsFor}).
2917
3117
  */
2918
- function baseCreateDocument(createState, initialState, documentType = "") {
3118
+ function baseCreateDocument(createState, initialState, documentType = "", protocolVersions) {
2919
3119
  const state = createState(initialState);
2920
- const header = createPresignedHeader(generateId(), documentType);
2921
- header.protocolVersions = { "base-reducer": 2 };
3120
+ const header = createPresignedHeader(void 0, documentType, protocolVersions === void 0 ? protocolVersionsFor("v2-required") : {
3121
+ "base-reducer": 2,
3122
+ ...protocolVersions
3123
+ });
2922
3124
  return {
2923
3125
  header,
2924
3126
  state,
@@ -2934,8 +3136,39 @@ function baseCreateDocument(createState, initialState, documentType = "") {
2934
3136
  clipboard: []
2935
3137
  };
2936
3138
  }
3139
+ /**
3140
+ * `document`, not yet created, under a fresh header for `policy`. A legacy
3141
+ * header takes `id` when given; a v2-required one ignores `id` and derives its
3142
+ * own, so a caller that needs a fixed id must ask for legacy.
3143
+ * `protocolVersions` are merged over the document's. Name, slug, branch and
3144
+ * meta carry over. A document already under `policy` is returned as is unless
3145
+ * a legacy `id` or `protocolVersions` are given.
3146
+ */
3147
+ function withSignaturePolicy(document, policy, options = {}) {
3148
+ const id = policy === "legacy" ? options.id : void 0;
3149
+ if (id === void 0 && options.protocolVersions === void 0 && signaturePolicyOf(document.header) === policy) return document;
3150
+ const source = document.header;
3151
+ const header = createPresignedHeader(id, source.documentType, protocolVersionsFor(policy, {
3152
+ ...source.protocolVersions,
3153
+ ...options.protocolVersions
3154
+ }));
3155
+ header.name = source.name;
3156
+ header.slug = source.slug;
3157
+ header.branch = source.branch;
3158
+ header.meta = source.meta;
3159
+ const operations = document.operations.document ? {
3160
+ ...document.operations,
3161
+ document: createDocumentScopeOperations(header, document.state)
3162
+ } : document.operations;
3163
+ return {
3164
+ ...document,
3165
+ header,
3166
+ operations
3167
+ };
3168
+ }
2937
3169
  function hashDocumentStateForScope(document, scope = "global") {
2938
- return hashBrowser(stringify(document.state[scope] || ""));
3170
+ const stateString = stringify(document.state[scope] || "");
3171
+ return hashBrowser(stateString);
2939
3172
  }
2940
3173
  function readOnly(value) {
2941
3174
  return Object.freeze(value);
@@ -3066,7 +3299,7 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
3066
3299
  const backfilledInitialState = backfillAuthState(initialState);
3067
3300
  let documentState = backfilledInitialState;
3068
3301
  const operationsToReplay = [];
3069
- const allScopes = new Set([
3302
+ const allScopes = /* @__PURE__ */ new Set([
3070
3303
  ...Object.keys(operations),
3071
3304
  "global",
3072
3305
  "local"
@@ -3124,7 +3357,7 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
3124
3357
  if (operation.hash !== hashDocumentStateForScope(result, scope)) throw new HashMismatchError(scope, result, operation);
3125
3358
  else break;
3126
3359
  }
3127
- const allResultScopes = new Set([
3360
+ const allResultScopes = /* @__PURE__ */ new Set([
3128
3361
  ...Object.keys(result.operations),
3129
3362
  ...Object.keys(operations),
3130
3363
  "global",
@@ -3187,8 +3420,8 @@ function checkCleanedOperationsIntegrity(sortedOperations) {
3187
3420
  index: nextOperation.index,
3188
3421
  skip: nextOperation.skip
3189
3422
  },
3190
- issue: IntegrityIssueType.UNEXPECTED_INDEX,
3191
- category: nextIndex > currentIndex + 1 ? IntegrityIssueSubType.MISSING_INDEX : IntegrityIssueSubType.DUPLICATED_INDEX,
3423
+ issue: "UNEXPECTED_INDEX",
3424
+ category: nextIndex > currentIndex + 1 ? "MISSING_INDEX" : "DUPLICATED_INDEX",
3192
3425
  message: `Expected index ${currentIndex + 1} with skip 0 or equivalent, got index ${nextOperation.index} with skip ${nextOperation.skip}`
3193
3426
  });
3194
3427
  currentIndex = nextOperation.index;
@@ -3298,12 +3531,14 @@ function attachBranch(trunk, newBranch) {
3298
3531
  nextTrunkOperation = trunkCopy.shift();
3299
3532
  }
3300
3533
  if (!nextTrunkOperation) enteredBranch = true;
3301
- else if (!enteredBranch) if (operationsAreEqual(nextTrunkOperation, newOperationCandidate)) {
3302
- newOperations.shift();
3303
- result.push(nextTrunkOperation);
3304
- } else {
3305
- trunkCopy.unshift(nextTrunkOperation);
3306
- enteredBranch = true;
3534
+ else if (!enteredBranch) {
3535
+ if (operationsAreEqual(nextTrunkOperation, newOperationCandidate)) {
3536
+ newOperations.shift();
3537
+ result.push(nextTrunkOperation);
3538
+ } else {
3539
+ trunkCopy.unshift(nextTrunkOperation);
3540
+ enteredBranch = true;
3541
+ }
3307
3542
  }
3308
3543
  if (enteredBranch) {
3309
3544
  let nextAppend = newOperations.shift();
@@ -3334,13 +3569,14 @@ function split(sortedTargetOperations, sortedMergeOperations) {
3334
3569
  for (let i = 0; i < maxLength; i++) {
3335
3570
  const targetOperation = sortedTargetOperations[i];
3336
3571
  const mergeOperation = sortedMergeOperations[i];
3337
- if (targetOperation && mergeOperation) if (!splitHappened && operationsAreEqual(targetOperation, mergeOperation)) commonOperations.push(targetOperation);
3338
- else {
3339
- splitHappened = true;
3340
- targetDiffOperations.push(targetOperation);
3341
- mergeDiffOperations.push(mergeOperation);
3342
- }
3343
- else if (targetOperation) targetDiffOperations.push(targetOperation);
3572
+ if (targetOperation && mergeOperation) {
3573
+ if (!splitHappened && operationsAreEqual(targetOperation, mergeOperation)) commonOperations.push(targetOperation);
3574
+ else {
3575
+ splitHappened = true;
3576
+ targetDiffOperations.push(targetOperation);
3577
+ mergeDiffOperations.push(mergeOperation);
3578
+ }
3579
+ } else if (targetOperation) targetDiffOperations.push(targetOperation);
3344
3580
  else if (mergeOperation) mergeDiffOperations.push(mergeOperation);
3345
3581
  }
3346
3582
  return [
@@ -3392,14 +3628,14 @@ function prepareOperations(operationsHistory, newOperations) {
3392
3628
  const sortedOperationsHistory = sortOperations(operationsHistory);
3393
3629
  const sortedOperations = sortOperations(newOperations);
3394
3630
  const integrityErrors = checkCleanedOperationsIntegrity([...sortedOperationsHistory, ...sortedOperations]);
3395
- const firstMissingIndexOperation = [...integrityErrors.filter((integrityIssue) => integrityIssue.category === IntegrityIssueSubType.MISSING_INDEX)].sort((a, b) => b.operation.index - a.operation.index).pop()?.operation;
3631
+ const firstMissingIndexOperation = [...integrityErrors.filter((integrityIssue) => integrityIssue.category === "MISSING_INDEX")].sort((a, b) => b.operation.index - a.operation.index).pop()?.operation;
3396
3632
  for (const newOperation of sortedOperations) {
3397
3633
  if (firstMissingIndexOperation && newOperation.index >= firstMissingIndexOperation.index) {
3398
3634
  result.invalidOperations.push(newOperation);
3399
3635
  continue;
3400
3636
  }
3401
3637
  if (integrityErrors.some((integrityError) => {
3402
- return integrityError.operation.index === newOperation.index && integrityError.operation.skip === newOperation.skip && integrityError.category === IntegrityIssueSubType.DUPLICATED_INDEX;
3638
+ return integrityError.operation.index === newOperation.index && integrityError.operation.skip === newOperation.skip && integrityError.category === "DUPLICATED_INDEX";
3403
3639
  })) {
3404
3640
  result.duplicatedOperations.push(newOperation);
3405
3641
  continue;
@@ -3628,18 +3864,6 @@ function redoOperation(document, action, skip) {
3628
3864
  });
3629
3865
  });
3630
3866
  }
3631
- function loadStateOperation(document, action) {
3632
- const loaded = backfillAuthState(action.state.data);
3633
- loaded.auth = resolveSnapshotAuth(document.header.id, document.header.documentType, backfillAuthState({ ...document.state }).auth, loaded.auth);
3634
- return {
3635
- ...document,
3636
- header: {
3637
- ...document.header,
3638
- name: action.state.name
3639
- },
3640
- state: loaded
3641
- };
3642
- }
3643
3867
  /**
3644
3868
  * Reads an operation's outcome. A denial takes precedence over a reducer
3645
3869
  * error, since a denied operation never reaches its reducer.
@@ -3672,15 +3896,12 @@ function replayOperations(initialState, clearedOperations, stateReducer, header,
3672
3896
  * @returns The updated document state.
3673
3897
  */
3674
3898
  function updateOperationsForAction(document, action, reuseLastOperationIndex, skip, context) {
3675
- if ([
3676
- "UNDO",
3677
- "REDO",
3678
- "PRUNE"
3679
- ].includes(action.type)) return document;
3899
+ if (["UNDO", "REDO"].includes(action.type)) return document;
3680
3900
  const scope = action.scope;
3681
3901
  const existing = document.operations[scope];
3682
3902
  const lastOperationIndex = existing?.at(-1)?.index ?? -1;
3683
- const newOperation = operationFromAction(action, reuseLastOperationIndex ? lastOperationIndex : lastOperationIndex + 1, skip, context);
3903
+ const index = reuseLastOperationIndex ? lastOperationIndex : lastOperationIndex + 1;
3904
+ const newOperation = operationFromAction(action, index, skip, context);
3684
3905
  const operations = [...existing ?? [], newOperation];
3685
3906
  return {
3686
3907
  ...document,
@@ -3724,20 +3945,17 @@ function updateDocument(document, action, reuseLastOperationIndex, skip, context
3724
3945
  return newDocument;
3725
3946
  }
3726
3947
  /**
3727
- * The base document reducer function that wraps a custom reducer function.
3948
+ * The base document reducer function.
3728
3949
  *
3729
3950
  * @param state The current state of the document.
3730
3951
  * @param action The action being applied to the document.
3731
- * @param wrappedReducer The custom reducer function being wrapped by the base reducer.
3732
3952
  * @returns The updated document state.
3733
3953
  */
3734
- function _baseReducer(document, action, wrappedReducer) {
3954
+ function _baseReducer(document, action) {
3735
3955
  const parsedAction = DocumentActionSchema().parse(action);
3736
3956
  switch (parsedAction.type) {
3737
3957
  case "SET_NAME": return setNameOperation(document, parsedAction.input);
3738
3958
  case "SET_PREFERRED_EDITOR": return setPreferredEditorOperation(document, parsedAction.input);
3739
- case "PRUNE": return pruneOperation(document, parsedAction.input, wrappedReducer);
3740
- case "LOAD_STATE": return loadStateOperation(document, parsedAction.input);
3741
3959
  default: return document;
3742
3960
  }
3743
3961
  }
@@ -3815,7 +4033,7 @@ function processUndoOperation(document, scope, customReducer, reuseOperationResu
3815
4033
  }
3816
4034
  /**
3817
4035
  * Base document reducer that wraps a custom document reducer and handles
3818
- * document-level actions such as undo, redo, prune, and set name.
4036
+ * document-level actions such as undo, redo, and set name.
3819
4037
  *
3820
4038
  * @template TGlobalState - The type of the state of the custom reducer.
3821
4039
  * @template TAction - The type of the actions of the custom reducer.
@@ -3843,7 +4061,7 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
3843
4061
  ...newDocument,
3844
4062
  clipboard: []
3845
4063
  };
3846
- if (isDocumentAction(_action)) newDocument = _baseReducer(newDocument, _action, customReducer);
4064
+ if (isDocumentAction(_action)) newDocument = _baseReducer(newDocument, _action);
3847
4065
  const operationContext = {
3848
4066
  documentId: document.header.id,
3849
4067
  scope: _action.scope,
@@ -3906,11 +4124,7 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
3906
4124
  }
3907
4125
  }
3908
4126
  });
3909
- if ([
3910
- "UNDO",
3911
- "REDO",
3912
- "PRUNE"
3913
- ].includes(_action.type)) return newDocument;
4127
+ if (["UNDO", "REDO"].includes(_action.type)) return newDocument;
3914
4128
  const scope = _action.scope || "global";
3915
4129
  const replayHash = options.replayOptions?.operation.hash;
3916
4130
  const hash = replayHash ? replayHash : hashDocumentStateForScope(newDocument, scope);
@@ -3930,7 +4144,6 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
3930
4144
  * - `SET_NAME`
3931
4145
  * - `UNDO`
3932
4146
  * - `REDO`
3933
- * - `PRUNE`
3934
4147
  *
3935
4148
  * It also updates the document-related attributes on every operation.
3936
4149
  *
@@ -3945,46 +4158,6 @@ function createReducer(stateReducer, documentReducer = baseReducer) {
3945
4158
  };
3946
4159
  return reducer;
3947
4160
  }
3948
- function pruneOperation(document, input, wrappedReducer) {
3949
- const operations = document.operations.global;
3950
- if (!operations) throw new Error("No global operations found");
3951
- let { start, end } = input;
3952
- start = start || 0;
3953
- end = end || operations.length;
3954
- const actionsToPrune = operations.slice(start, end);
3955
- const actionsToKeepStart = operations.slice(0, start);
3956
- const actionsToKeepEnd = operations.slice(end);
3957
- const newDocument = replayOperations(document.initialState, {
3958
- ...document.operations,
3959
- global: actionsToKeepStart.concat(actionsToPrune)
3960
- }, wrappedReducer, document.header);
3961
- const newState = newDocument.state;
3962
- const name = newDocument.header.name;
3963
- const loadStateIndex = actionsToKeepStart.length;
3964
- const loadStateTimestamp = actionsToKeepStart.length ? actionsToKeepStart[actionsToKeepStart.length - 1].timestampUtcMs : actionsToKeepEnd.length ? actionsToKeepEnd[0].timestampUtcMs : (/* @__PURE__ */ new Date()).toISOString();
3965
- const action = loadState({
3966
- name,
3967
- ...newState
3968
- }, actionsToPrune.length);
3969
- return replayOperations(document.initialState, {
3970
- ...document.operations,
3971
- global: [
3972
- ...actionsToKeepStart,
3973
- {
3974
- skip: 0,
3975
- ...action,
3976
- action,
3977
- timestampUtcMs: loadStateTimestamp,
3978
- index: loadStateIndex,
3979
- hash: hashDocumentStateForScope({ state: newState }, "global")
3980
- },
3981
- ...actionsToKeepEnd.map((action, index) => ({
3982
- ...action,
3983
- index: loadStateIndex + index + 1
3984
- }))
3985
- ]
3986
- }, wrappedReducer, document.header);
3987
- }
3988
4161
  //#endregion
3989
4162
  //#region document-model/validation.ts
3990
4163
  /**
@@ -3994,8 +4167,6 @@ function pruneOperation(document, input, wrappedReducer) {
3994
4167
  const RESERVED_OPERATION_NAMES = [
3995
4168
  "UNDO",
3996
4169
  "REDO",
3997
- "PRUNE",
3998
- "LOAD_STATE",
3999
4170
  "SET_NAME",
4000
4171
  "SET_PREFERRED_EDITOR",
4001
4172
  "NOOP"
@@ -4234,6 +4405,15 @@ function orderBy(items, order) {
4234
4405
  return (rank.get(a.item.id) ?? Number.MAX_SAFE_INTEGER) - (rank.get(b.item.id) ?? Number.MAX_SAFE_INTEGER) || a.index - b.index;
4235
4406
  }).map(({ item }) => item);
4236
4407
  }
4408
+ /**
4409
+ * The untouched base of a mutative draft, or the value itself when it is not a
4410
+ * draft. Build replacement lists from it and freeze them before assigning, as
4411
+ * the drive node reducer does, so finalize skips the walk over the assigned
4412
+ * list. Read before writing: the base does not see this action's mutations.
4413
+ */
4414
+ function readBase(value) {
4415
+ return isDraft(value) ? original(value) : value;
4416
+ }
4237
4417
  const documentModelHeaderReducer = {
4238
4418
  setModelNameOperation(state, action) {
4239
4419
  state.name = action.input.name;
@@ -4283,7 +4463,8 @@ const documentModelModuleReducer = {
4283
4463
  deleteModuleOperation(state, action) {
4284
4464
  findModuleOrThrow(state, action.input.id);
4285
4465
  const latestSpec = state.specifications[state.specifications.length - 1];
4286
- latestSpec.modules = latestSpec.modules.filter((m) => m.id != action.input.id);
4466
+ const modules = readBase(latestSpec).modules.filter((m) => m.id != action.input.id);
4467
+ latestSpec.modules = Object.freeze(modules);
4287
4468
  },
4288
4469
  reorderModulesOperation(state, action) {
4289
4470
  const latestSpec = state.specifications[state.specifications.length - 1];
@@ -4401,14 +4582,20 @@ const documentModelOperationReducer = {
4401
4582
  const matches = latestSpec.modules.flatMap((mod) => mod.operations.filter((op) => op.id === action.input.operationId));
4402
4583
  if (matches.length === 0) throw new Error(`Operation "${action.input.operationId}" not found in the latest specification`);
4403
4584
  if (matches.length > 1) throw new Error(`Operation "${action.input.operationId}" is duplicated in the latest specification`);
4404
- const moved = matches[0];
4405
- for (const mod of latestSpec.modules) mod.operations = mod.operations.filter((op) => op.id !== action.input.operationId);
4406
- targetModule.operations.push(moved);
4585
+ const moved = readBase(matches[0]);
4586
+ for (const mod of latestSpec.modules) {
4587
+ const operations = readBase(mod).operations.filter((op) => op.id !== action.input.operationId);
4588
+ if (mod === targetModule) operations.push(moved);
4589
+ mod.operations = Object.freeze(operations);
4590
+ }
4407
4591
  },
4408
4592
  deleteOperationOperation(state, action) {
4409
4593
  findOperationOrThrow(state, action.input.id);
4410
4594
  const latestSpec = state.specifications[state.specifications.length - 1];
4411
- for (const mod of latestSpec.modules) mod.operations = mod.operations.filter((operation) => operation.id != action.input.id);
4595
+ for (const mod of latestSpec.modules) {
4596
+ const operations = readBase(mod).operations.filter((operation) => operation.id != action.input.id);
4597
+ mod.operations = Object.freeze(operations);
4598
+ }
4412
4599
  },
4413
4600
  reorderModuleOperationsOperation(state, action) {
4414
4601
  const targetModule = findModuleOrThrow(state, action.input.moduleId);
@@ -4446,7 +4633,8 @@ const documentModelStateSchemaReducer = {
4446
4633
  if (!Object.keys(latestSpec.state).includes(action.input.scope)) throw new Error(`Invalid scope: ${action.input.scope}`);
4447
4634
  const scopeState = latestSpec.state[action.input.scope];
4448
4635
  if (!scopeState.examples.some((e) => e.id == action.input.id)) throw new Error(`State example "${action.input.id}" not found in scope "${action.input.scope}"`);
4449
- scopeState.examples = scopeState.examples.filter((e) => e.id != action.input.id);
4636
+ const examples = readBase(scopeState).examples.filter((e) => e.id != action.input.id);
4637
+ scopeState.examples = Object.freeze(examples);
4450
4638
  },
4451
4639
  reorderStateExamplesOperation(state, action) {
4452
4640
  const latestSpec = state.specifications[state.specifications.length - 1];
@@ -4716,7 +4904,11 @@ function applyUpgradeDocumentAction(document, action, upgradePath) {
4716
4904
  const toVersion = action.input.toVersion;
4717
4905
  if (fromVersion === toVersion && fromVersion > 0) return document;
4718
4906
  if (fromVersion > toVersion) throw new DowngradeNotSupportedError(document.header.documentType, fromVersion, toVersion);
4719
- if (upgradePath) for (const transition of upgradePath) document = transition.upgradeReducer(document, action);
4907
+ if (upgradePath) {
4908
+ const protocolVersions = document.header.protocolVersions;
4909
+ for (const transition of upgradePath) document = transition.upgradeReducer(document, action);
4910
+ document = withProtocolVersions(document, protocolVersions);
4911
+ }
4720
4912
  applyInitialState(document, action);
4721
4913
  document.state.document = {
4722
4914
  ...document.state.document,
@@ -4724,6 +4916,16 @@ function applyUpgradeDocumentAction(document, action, upgradePath) {
4724
4916
  };
4725
4917
  return document;
4726
4918
  }
4919
+ /** CREATE_DOCUMENT fixes `protocolVersions`; this puts them back after a reducer. */
4920
+ function withProtocolVersions(document, protocolVersions) {
4921
+ const header = { ...document.header };
4922
+ if (protocolVersions === void 0) delete header.protocolVersions;
4923
+ else header.protocolVersions = { ...protocolVersions };
4924
+ return {
4925
+ ...document,
4926
+ header
4927
+ };
4928
+ }
4727
4929
  /**
4728
4930
  * Applies a DELETE_DOCUMENT action to a document.
4729
4931
  * Marks the document as deleted in the document scope state.
@@ -4849,7 +5051,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
4849
5051
  const curr = boundaries[i]?.[s] ?? 0;
4850
5052
  if (boundaries[i]) boundaries[i][s] = Math.max(prev, curr);
4851
5053
  }
4852
- const allScopes = new Set([
5054
+ const allScopes = /* @__PURE__ */ new Set([
4853
5055
  ...Object.keys(operations),
4854
5056
  "global",
4855
5057
  "local"
@@ -4936,7 +5138,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
4936
5138
  }
4937
5139
  }
4938
5140
  }
4939
- const allResultScopes = new Set([
5141
+ const allResultScopes = /* @__PURE__ */ new Set([
4940
5142
  ...Object.keys(document.operations),
4941
5143
  ...Object.keys(operations),
4942
5144
  "global",
@@ -5020,22 +5222,21 @@ async function createZip(document) {
5020
5222
  */
5021
5223
  async function createMinimalZip(data) {
5022
5224
  const now = (/* @__PURE__ */ new Date()).toISOString();
5023
- const header = {
5024
- id: data.documentId,
5025
- sig: {
5026
- publicKey: {},
5027
- nonce: ""
5028
- },
5029
- documentType: data.documentType,
5030
- createdAtUtcIso: now,
5031
- slug: data.name,
5032
- name: data.name,
5033
- branch: data.branch,
5034
- revision: {},
5035
- lastModifiedAtUtcIso: now
5036
- };
5037
5225
  return zipAsync({
5038
- "header.json": jsonEntry(header),
5226
+ "header.json": jsonEntry({
5227
+ id: data.documentId,
5228
+ sig: {
5229
+ publicKey: {},
5230
+ nonce: ""
5231
+ },
5232
+ documentType: data.documentType,
5233
+ createdAtUtcIso: now,
5234
+ slug: data.name,
5235
+ name: data.name,
5236
+ branch: data.branch,
5237
+ revision: {},
5238
+ lastModifiedAtUtcIso: now
5239
+ }),
5039
5240
  "state.json": jsonEntry(data.state),
5040
5241
  "current-state.json": jsonEntry(data.state),
5041
5242
  "operations.json": jsonEntry({})
@@ -5059,7 +5260,9 @@ async function parseZipData(data) {
5059
5260
  if (!files["header.json"]) throw new Error("Document header not found - file format may be outdated");
5060
5261
  const header = JSON.parse(readEntry(files, "header.json"));
5061
5262
  if (!files["operations.json"]) throw new Error("Operations history not found");
5062
- const clearedOperations = garbageCollectDocumentOperations(JSON.parse(readEntry(files, "operations.json")));
5263
+ const operations = JSON.parse(readEntry(files, "operations.json"));
5264
+ const clearedOperations = garbageCollectDocumentOperations(operations);
5265
+ pinProtocolVersionsToCreate(header, operations);
5063
5266
  const operationsError = validateOperations(clearedOperations);
5064
5267
  if (operationsError.length) {
5065
5268
  const errorMessages = operationsError.map((err) => err.message);
@@ -5071,6 +5274,17 @@ async function parseZipData(data) {
5071
5274
  clearedOperations
5072
5275
  };
5073
5276
  }
5277
+ /** header.json is a snapshot; the stored CREATE_DOCUMENT input wins. */
5278
+ function pinProtocolVersionsToCreate(header, operations) {
5279
+ const create = operations.document?.find((operation) => operation.action.type === "CREATE_DOCUMENT");
5280
+ if (!create) return;
5281
+ const input = create.action.input;
5282
+ if (input?.protocolVersions) header.protocolVersions = { ...input.protocolVersions };
5283
+ else if (header.protocolVersions) {
5284
+ const { [SIGNATURE_PROTOCOL]: _dropped, ...rest } = header.protocolVersions;
5285
+ header.protocolVersions = rest;
5286
+ }
5287
+ }
5074
5288
  async function loadFromZipData(data, reducer, options) {
5075
5289
  const { initialState, header, clearedOperations } = await parseZipData(data);
5076
5290
  return {
@@ -5146,6 +5360,6 @@ const getFileBrowser = (file) => {
5146
5360
  return Promise.resolve().then(() => readFileBrowser(file));
5147
5361
  };
5148
5362
  //#endregion
5149
- export { AUTH_ACTION_TYPES, AUTH_DENIED_BY_GRANT_REASON, AUTH_NO_GRANT_REASON, AUTH_VERSION_UNSUPPORTED_REASON, AddChangeLogItemInputSchema, AddModuleInputSchema, AddOperationErrorInputSchema, AddOperationExampleInputSchema, AddOperationInputSchema, AddStateExampleInputSchema, AuthActionNotAllowedError, AuthAdministrationLockoutError, AuthAdministrationMissingError, AuthAlreadyInitializedError, AuthInitializerNotCreatorError, AuthPolicyNotPreservedError, AuthorSchema, BaseDocumentHeaderSchema, BaseDocumentStateSchema, CodeExampleSchema, ConfigEntrySchema, ConfigEntryTypeSchema, DOCUMENT_DELETED_REASON, DeleteChangeLogItemInputSchema, DeleteModuleInputSchema, DeleteOperationErrorInputSchema, DeleteOperationExampleInputSchema, DeleteOperationInputSchema, DeleteStateExampleInputSchema, DocumentActionSchema, DocumentModelGlobalStateSchema, DocumentModelHeaderSchema, DocumentModelInputSchema, DocumentModelPHStateSchema, DocumentModelSchema, DocumentSpecificationSchema, DowngradeNotSupportedError, FileSystemError, GrantNotFoundError, GrantSchema, GroupPrincipalNotAllowedError, HASH_ALGORITHM_SHA1, HASH_ALGORITHM_SHA256, HASH_ALGORITHM_SHA512, HASH_ENCODING_BASE64, HASH_ENCODING_HEX, HashMismatchError, InitializeAuthActionInputSchema, IntegrityIssueSubType, IntegrityIssueType, InvalidActionInputError, InvalidActionInputZodError, InvalidAuthVersionError, InvalidGrantError, LoadStateActionInputSchema, LoadStateActionSchema, LoadStateActionStateInputSchema, Load_StateSchema, MAX_AUTH_GRANTS, MAX_CAPABILITY_OPERATIONS, MAX_CONDITION_DEPTH, MAX_CONDITION_NODES, MAX_SUPPORTED_AUTH_VERSION, ManifestSchema, ModuleSchema, MoveGrantActionInputSchema, MoveOperationInputSchema, OPERATION_NAME_PATTERN, OperationErrorSchema, OperationScopeSchema, OperationSpecificationSchema, PieceModuleSchema, PieceModulesSchema, PowerhouseModuleSchema, PowerhouseModulesSchema, PruneActionInputSchema, PruneActionSchema, PruneSchema, PublisherSchema, PwaConfigSchema, RESERVED_OPERATION_NAMES, RedoActionInputSchema, RedoActionSchema, RedoSchema, RemoveGrantActionInputSchema, ReorderChangeLogItemsInputSchema, ReorderModuleOperationsInputSchema, ReorderModulesInputSchema, ReorderOperationErrorsInputSchema, ReorderOperationExamplesInputSchema, ReorderStateExamplesInputSchema, ScopeStateSchema, SetAuthorNameInputSchema, SetAuthorWebsiteInputSchema, SetGrantActionInputSchema, SetInitialStateInputSchema, SetModelDescriptionInputSchema, SetModelExtensionInputSchema, SetModelIdInputSchema, SetModelNameInputSchema, SetModuleDescriptionInputSchema, SetModuleNameInputSchema, SetNameActionInputSchema, SetNameActionSchema, SetOperationDescriptionInputSchema, SetOperationErrorCodeInputSchema, SetOperationErrorDescriptionInputSchema, SetOperationErrorNameInputSchema, SetOperationErrorTemplateInputSchema, SetOperationNameInputSchema, SetOperationReducerInputSchema, SetOperationSchemaInputSchema, SetOperationScopeInputSchema, SetOperationTemplateInputSchema, SetPreferredEditorActionInputSchema, SetPreferredEditorActionSchema, SetStateSchemaInputSchema, Set_NameSchema, Set_PreferredEditorSchema, StateSchema, UndoActionInputSchema, UndoActionSchema, UndoSchema, UnsupportedDocumentModelVersionError, UpdateChangeLogItemInputSchema, UpdateOperationExampleInputSchema, UpdateStateExampleInputSchema, ab2hex, actionContext, actionFromAction, actionSigner, actions, addChangeLogItem, addModule, addOperation, addOperationError, addOperationExample, addStateExample, addUndo, appendWithoutApplying, applyAuthAction, applyDeleteDocumentAction, applyInitializeAuthAction, applyMoveGrantAction, applyRemoveGrantAction, applySetGrantAction, applyUpgradeDocumentAction, assertAuthAdministrationRetained, assertAuthPreservedOnDuplicate, assertAuthScopeActionAllowed, assertIsDocumentModelDocument, assertIsDocumentModelState, assertModuleIdUnique, assertOperationErrorIdUnique, assertOperationExampleIdUnique, assertOperationIdUnique, assertValidGrant, assertValidGrantUpsert, assertValidInitialGrants, attachBranch, backfillAuthState, base58Decode, base64UrlToBytes, baseActions, baseCreateDocument, baseLoadFromInput, baseLoadFromInputVersioned, baseReducer, baseReducerVersion, baseSaveToFileHandle, buildOperationSignature, buildOperationSignatureMessage, buildOperationSignatureParams, buildSignedAction, checkCleanedOperationsIntegrity, checkOperationsIntegrity, computeUpgradeTransitions, createAction, createAuthState, createBaseState, createDocumentState, createGlobalState, createLocalState, createMinimalZip, createPresignedHeader, createReducer, createSignedHeader, createSignedHeaderForSigner, createState, createVerificationSigner, createZip, decide, defaultAuthState, defaultBaseState, defaultDocumentState, defaultGlobalState, defaultLocalState, defaultPHState, definedNonNullAnySchema, deleteChangeLogItem, deleteModule, deleteOperation, deleteOperationError, deleteOperationExample, deleteStateExample, deriveOperationId, deserializeSignature, diffOperations, documentModelActions, documentModelDocumentType, documentModelFileExtension, documentModelGlobalState, documentModelHeaderReducer, documentModelInitialGlobalState, documentModelInitialLocalState, documentModelLoadFromInput, documentModelModuleReducer, documentModelOperationErrorReducer, documentModelOperationExampleReducer, documentModelOperationReducer, documentModelReducer, documentModelSaveToFileHandle, documentModelStateReducer, documentModelStateSchemaReducer, documentModelVersioningReducer, evaluate, evaluateCondition, evaluateGrantStack, evaluateGrants, fetchFileBrowser, filterDocumentOperationsResultingState, filterDuplicatedOperations, findModuleOrThrow, findOperationErrorOrThrow, findOperationExampleOrThrow, findOperationOrThrow, garbageCollect, garbageCollectDocumentOperations, garbageCollectV2, generateId, generateMock, getAllOperationNames, getDocumentLastModified, getFileBrowser, getUnixTimestamp, grantProblem, groupDocumentType, groupMembershipActionTypes, groupOperationsByScope, hashBrowser, hashDocumentStateForScope, hex2ab, initializeAuth, isAuthAction, isDefinedNonNullAny, isDenied, isDocumentAction, isDocumentCreator, isDocumentModelDocument, isDocumentModelState, isDocumentZip, isNoopOperation, isPlainValue, isReservedOperationName, isUndo, isUndoRedo, isValidOperationNameFormat, loadState, loadStateOperation, mapSkippedOperations, mapSkippedOperationsV2, mentionedGroupIds, merge, moveGrant, moveOperation, nextSkipNumber, noop, normalizeDocumentModelVersion, operationExampleCreators, operationFromAction, operationFromOperation, operationOutcome, operationWithContext, operationsAreEqual, parseBulkArchive, parseResultingState, precedes, prepareOperations, processUndoRedo, prune, pruneOperation, readFileBrowser, readOnly, redo, redoOperation, referencedGroupIds, releaseNewVersion, removeExistingOperations, removeGrant, reorderChangeLogItems, reorderModuleOperations, reorderModules, reorderOperationErrors, reorderOperationExamples, reorderStateExamples, replayDocument, replayDocumentVersioned, replayOperations, reshuffleByTimestamp, reshuffleByTimestampAndIndex, resolveSnapshotAuth, serializeSignature, setAuthorName, setAuthorWebsite, setGrant, setInitialState, setModelDescription, setModelExtension, setModelId, setModelName, setModuleDescription, setModuleName, setName, setNameOperation, setOperationDescription, setOperationErrorCode, setOperationErrorDescription, setOperationErrorName, setOperationErrorTemplate, setOperationName, setOperationReducer, setOperationSchema, setOperationScope, setOperationTemplate, setPreferredEditor, setPreferredEditorOperation, setStateSchema, sign, skipHeaderOperations, sortMappedOperations, sortOperations, split, toTransportAction, undo, undoOperation, undoOperationV2, updateChangeLogItem, updateDocument, updateHeaderRevision, updateOperationExample, updateStateExample, validateHeader, validateInitialState, validateModule, validateModuleOperation, validateModules, validateOperationName, validateOperations, validateStateSchemaName, verify, verifyOperationSignature, writeFileBrowser, zipEntries };
5363
+ export { ACTION_SIGNATURE_V2_PREFIX, AUTH_ACTION_TYPES, AUTH_DENIED_BY_GRANT_REASON, AUTH_NO_GRANT_REASON, AUTH_VERSION_UNSUPPORTED_REASON, AddChangeLogItemInputSchema, AddModuleInputSchema, AddOperationErrorInputSchema, AddOperationExampleInputSchema, AddOperationInputSchema, AddStateExampleInputSchema, AuthActionNotAllowedError, AuthAdministrationLockoutError, AuthAdministrationMissingError, AuthAlreadyInitializedError, AuthInitializerNotCreatorError, AuthPolicyNotPreservedError, AuthorSchema, BaseDocumentHeaderSchema, BaseDocumentStateSchema, CanonicalJsonError, CodeExampleSchema, ConfigEntrySchema, ConfigEntryTypeSchema, DEFAULT_SIGNATURE_POLICY, DOCUMENT_DELETED_REASON, DOCUMENT_SCOPE_ACTION_TYPES, DeleteChangeLogItemInputSchema, DeleteModuleInputSchema, DeleteOperationErrorInputSchema, DeleteOperationExampleInputSchema, DeleteOperationInputSchema, DeleteStateExampleInputSchema, DocumentActionSchema, DocumentModelGlobalStateSchema, DocumentModelHeaderSchema, DocumentModelInputSchema, DocumentModelPHStateSchema, DocumentModelSchema, DocumentSpecificationSchema, DowngradeNotSupportedError, FileSystemError, GrantNotFoundError, GrantSchema, GroupPrincipalNotAllowedError, HASH_ALGORITHM_SHA1, HASH_ALGORITHM_SHA256, HASH_ALGORITHM_SHA512, HASH_ENCODING_BASE64, HASH_ENCODING_HEX, HashMismatchError, InitializeAuthActionInputSchema, IntegrityIssueSubType, IntegrityIssueType, InvalidActionInputError, InvalidActionInputZodError, InvalidAuthVersionError, InvalidGrantError, MAX_AUTH_GRANTS, MAX_CAPABILITY_OPERATIONS, MAX_CONDITION_DEPTH, MAX_CONDITION_NODES, MAX_SUPPORTED_AUTH_VERSION, ManifestSchema, ModuleSchema, MoveGrantActionInputSchema, MoveOperationInputSchema, OPERATION_NAME_PATTERN, OperationErrorSchema, OperationScopeSchema, OperationSpecificationSchema, PieceModuleSchema, PieceModulesSchema, PowerhouseModuleSchema, PowerhouseModulesSchema, PublisherSchema, PwaConfigSchema, RESERVED_OPERATION_NAMES, RedoActionInputSchema, RedoActionSchema, RedoSchema, RemoveGrantActionInputSchema, ReorderChangeLogItemsInputSchema, ReorderModuleOperationsInputSchema, ReorderModulesInputSchema, ReorderOperationErrorsInputSchema, ReorderOperationExamplesInputSchema, ReorderStateExamplesInputSchema, SIGNATURE_PROTOCOL, SIGNATURE_PROTOCOL_V2, ScopeStateSchema, SetAuthorNameInputSchema, SetAuthorWebsiteInputSchema, SetGrantActionInputSchema, SetInitialStateInputSchema, SetModelDescriptionInputSchema, SetModelExtensionInputSchema, SetModelIdInputSchema, SetModelNameInputSchema, SetModuleDescriptionInputSchema, SetModuleNameInputSchema, SetNameActionInputSchema, SetNameActionSchema, SetOperationDescriptionInputSchema, SetOperationErrorCodeInputSchema, SetOperationErrorDescriptionInputSchema, SetOperationErrorNameInputSchema, SetOperationErrorTemplateInputSchema, SetOperationNameInputSchema, SetOperationReducerInputSchema, SetOperationSchemaInputSchema, SetOperationScopeInputSchema, SetOperationTemplateInputSchema, SetPreferredEditorActionInputSchema, SetPreferredEditorActionSchema, SetStateSchemaInputSchema, Set_NameSchema, Set_PreferredEditorSchema, StateSchema, UndoActionInputSchema, UndoActionSchema, UndoSchema, UnsupportedDocumentModelVersionError, UpdateChangeLogItemInputSchema, UpdateOperationExampleInputSchema, UpdateStateExampleInputSchema, ab2hex, actionContext, actionFromAction, actionPreimageV2, actionSigner, actionSignerIdentity, actionSigningTarget, actions, addChangeLogItem, addModule, addOperation, addOperationError, addOperationExample, addStateExample, addUndo, appendWithoutApplying, applyAuthAction, applyDeleteDocumentAction, applyInitializeAuthAction, applyMoveGrantAction, applyRemoveGrantAction, applySetGrantAction, applyUpgradeDocumentAction, assertAuthAdministrationRetained, assertAuthPreservedOnDuplicate, assertAuthScopeActionAllowed, assertIsDocumentModelDocument, assertIsDocumentModelState, assertModuleIdUnique, assertOperationErrorIdUnique, assertOperationExampleIdUnique, assertOperationIdUnique, assertValidGrant, assertValidGrantUpsert, assertValidInitialGrants, attachBranch, backfillAuthState, base58Decode, base64UrlToBytes, baseActions, baseCreateDocument, baseLoadFromInput, baseLoadFromInputVersioned, baseReducer, baseReducerVersion, baseSaveToFileHandle, buildOperationSignature, buildOperationSignatureMessage, buildOperationSignatureParams, buildSignedAction, canonicalJson, checkCleanedOperationsIntegrity, checkOperationsIntegrity, computeUpgradeTransitions, createAction, createAuthState, createBaseState, createCopyHeader, createDocumentState, createGlobalState, createLocalState, createMinimalZip, createPresignedHeader, createReducer, createSignedHeader, createSignedHeaderForSigner, createState, createVerificationSigner, createZip, decide, defaultAuthState, defaultBaseState, defaultDocumentState, defaultGlobalState, defaultLocalState, defaultPHState, definedNonNullAnySchema, deleteChangeLogItem, deleteModule, deleteOperation, deleteOperationError, deleteOperationExample, deleteStateExample, deriveDocumentId, deriveOperationId, deserializeSignature, diffOperations, documentModelActions, documentModelDocumentType, documentModelFileExtension, documentModelGlobalState, documentModelHeaderReducer, documentModelInitialGlobalState, documentModelInitialLocalState, documentModelLoadFromInput, documentModelModuleReducer, documentModelOperationErrorReducer, documentModelOperationExampleReducer, documentModelOperationReducer, documentModelReducer, documentModelSaveToFileHandle, documentModelStateReducer, documentModelStateSchemaReducer, documentModelVersioningReducer, evaluate, evaluateCondition, evaluateGrantStack, evaluateGrants, fetchFileBrowser, filterDocumentOperationsResultingState, filterDuplicatedOperations, findModuleOrThrow, findOperationErrorOrThrow, findOperationExampleOrThrow, findOperationOrThrow, garbageCollect, garbageCollectDocumentOperations, garbageCollectV2, generateId, generateMock, getAllOperationNames, getDocumentLastModified, getFileBrowser, getUnixTimestamp, grantProblem, groupDocumentType, groupMembershipActionTypes, groupOperationsByScope, hasDerivedDocumentId, hashActionV2, hashBrowser, hashDocumentStateForScope, hex2ab, initializeAuth, isAuthAction, isDefinedNonNullAny, isDenied, isDerivedDocumentId, isDocumentAction, isDocumentCreator, isDocumentModelDocument, isDocumentModelState, isDocumentZip, isNoopOperation, isPlainValue, isReservedOperationName, isSignaturePolicy, isUndo, isUndoRedo, isV2ActionHash, isValidOperationNameFormat, mapSkippedOperations, mapSkippedOperationsV2, mentionedGroupIds, merge, moveGrant, moveOperation, nextSkipNumber, noop, normalizeDocumentModelVersion, operationExampleCreators, operationFromAction, operationFromOperation, operationOutcome, operationWithContext, operationsAreEqual, parseBulkArchive, parseResultingState, precedes, prepareOperations, processUndoRedo, protocolVersionsFor, readFileBrowser, readOnly, redo, redoOperation, referencedGroupIds, releaseNewVersion, removeExistingOperations, removeGrant, reorderChangeLogItems, reorderModuleOperations, reorderModules, reorderOperationErrors, reorderOperationExamples, reorderStateExamples, replayDocument, replayDocumentVersioned, replayOperations, requestedSignaturePolicy, reshuffleByTimestamp, reshuffleByTimestampAndIndex, resolveSnapshotAuth, serializeSignature, setAuthorName, setAuthorWebsite, setGrant, setInitialState, setModelDescription, setModelExtension, setModelId, setModelName, setModuleDescription, setModuleName, setName, setNameOperation, setOperationDescription, setOperationErrorCode, setOperationErrorDescription, setOperationErrorName, setOperationErrorTemplate, setOperationName, setOperationReducer, setOperationSchema, setOperationScope, setOperationTemplate, setPreferredEditor, setPreferredEditorOperation, setStateSchema, sign, signActionV2, signaturePolicyOf, skipHeaderOperations, sortMappedOperations, sortOperations, split, targetDocumentId, toTransportAction, undo, undoOperation, undoOperationV2, updateChangeLogItem, updateDocument, updateHeaderRevision, updateOperationExample, updateStateExample, v2RequiredProtocolVersions, v2TupleProblem, validateHeader, validateInitialState, validateModule, validateModuleOperation, validateModules, validateOperationName, validateOperations, validateStateSchemaName, verify, verifyOperationSignature, withProtocolVersions, withSignaturePolicy, writeFileBrowser, zipEntries };
5150
5364
 
5151
5365
  //# sourceMappingURL=index.js.map