@seedprotocol/publish 0.4.31 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +64 -18
  3. package/dist/config-Q3y4Fab2.js +936 -0
  4. package/dist/config-Q3y4Fab2.js.map +1 -0
  5. package/dist/config-bUKEs4Uf.js +511 -0
  6. package/dist/config-bUKEs4Uf.js.map +1 -0
  7. package/dist/config.d.ts +42 -4
  8. package/dist/config.d.ts.map +1 -1
  9. package/dist/ensureManagedAccountEasConfigured-BXF7gQCi.js +1270 -0
  10. package/dist/ensureManagedAccountEasConfigured-BXF7gQCi.js.map +1 -0
  11. package/dist/ensureManagedAccountEasConfigured-BxdK_Vhf.js +1204 -0
  12. package/dist/ensureManagedAccountEasConfigured-BxdK_Vhf.js.map +1 -0
  13. package/dist/ensureManagedAccountEasConfigured-CZGguM7q.js +1177 -0
  14. package/dist/ensureManagedAccountEasConfigured-CZGguM7q.js.map +1 -0
  15. package/dist/ensureManagedAccountEasConfigured-CZS__-ha.js +1177 -0
  16. package/dist/ensureManagedAccountEasConfigured-CZS__-ha.js.map +1 -0
  17. package/dist/ensureManagedAccountEasConfigured-D2_Jjjxt.js +1192 -0
  18. package/dist/ensureManagedAccountEasConfigured-D2_Jjjxt.js.map +1 -0
  19. package/dist/ensureManagedAccountEasConfigured-DDFBEb-B.js +1192 -0
  20. package/dist/ensureManagedAccountEasConfigured-DDFBEb-B.js.map +1 -0
  21. package/dist/ensureManagedAccountEasConfigured-zcyqhWPe.js +1270 -0
  22. package/dist/ensureManagedAccountEasConfigured-zcyqhWPe.js.map +1 -0
  23. package/dist/ensureModularPublishBootstrap-2agkGdih.js +124 -0
  24. package/dist/ensureModularPublishBootstrap-2agkGdih.js.map +1 -0
  25. package/dist/ensureModularPublishBootstrap-B5i_dQrv.js +124 -0
  26. package/dist/ensureModularPublishBootstrap-B5i_dQrv.js.map +1 -0
  27. package/dist/ensureModularPublishBootstrap-BSXyZgld.js +124 -0
  28. package/dist/ensureModularPublishBootstrap-BSXyZgld.js.map +1 -0
  29. package/dist/ensureModularPublishBootstrap-C0gx7sbt.js +124 -0
  30. package/dist/ensureModularPublishBootstrap-C0gx7sbt.js.map +1 -0
  31. package/dist/ensureModularPublishBootstrap-DHNo4j6X.js +124 -0
  32. package/dist/ensureModularPublishBootstrap-DHNo4j6X.js.map +1 -0
  33. package/dist/ensureModularPublishBootstrap-DQ-oruO1.js +124 -0
  34. package/dist/ensureModularPublishBootstrap-DQ-oruO1.js.map +1 -0
  35. package/dist/ensureModularPublishBootstrap-QRGGgnkz.js +124 -0
  36. package/dist/ensureModularPublishBootstrap-QRGGgnkz.js.map +1 -0
  37. package/dist/ensureSmartWalletThenPublish-BmeIFGIX.js +47 -0
  38. package/dist/ensureSmartWalletThenPublish-BmeIFGIX.js.map +1 -0
  39. package/dist/ensureSmartWalletThenPublish-CR4N0M9S.js +47 -0
  40. package/dist/ensureSmartWalletThenPublish-CR4N0M9S.js.map +1 -0
  41. package/dist/ensureSmartWalletThenPublish-CRza0sML.js +47 -0
  42. package/dist/ensureSmartWalletThenPublish-CRza0sML.js.map +1 -0
  43. package/dist/ensureSmartWalletThenPublish-DzOnwM-9.js +47 -0
  44. package/dist/ensureSmartWalletThenPublish-DzOnwM-9.js.map +1 -0
  45. package/dist/ensureSmartWalletThenPublish-UFczP8th.js +47 -0
  46. package/dist/ensureSmartWalletThenPublish-UFczP8th.js.map +1 -0
  47. package/dist/ensureSmartWalletThenPublish-k085lqDO.js +47 -0
  48. package/dist/ensureSmartWalletThenPublish-k085lqDO.js.map +1 -0
  49. package/dist/ensureSmartWalletThenPublish-xcHGv06S.js +47 -0
  50. package/dist/ensureSmartWalletThenPublish-xcHGv06S.js.map +1 -0
  51. package/dist/helpers/abi/eas.d.ts +203 -0
  52. package/dist/helpers/abi/eas.d.ts.map +1 -0
  53. package/dist/helpers/abi/executor.d.ts +33 -0
  54. package/dist/helpers/abi/executor.d.ts.map +1 -0
  55. package/dist/helpers/abi/factory.d.ts +31 -0
  56. package/dist/helpers/abi/factory.d.ts.map +1 -0
  57. package/dist/helpers/abi/publisher.d.ts +199 -0
  58. package/dist/helpers/abi/publisher.d.ts.map +1 -0
  59. package/dist/helpers/abi/schemaRegistry.d.ts +45 -0
  60. package/dist/helpers/abi/schemaRegistry.d.ts.map +1 -0
  61. package/dist/helpers/adapters/eip1193.d.ts +17 -0
  62. package/dist/helpers/adapters/eip1193.d.ts.map +1 -0
  63. package/dist/helpers/adapters/permissionlessTxSender.d.ts +11 -0
  64. package/dist/helpers/adapters/permissionlessTxSender.d.ts.map +1 -0
  65. package/dist/helpers/adapters/thirdwebAccount.d.ts +13 -0
  66. package/dist/helpers/adapters/thirdwebAccount.d.ts.map +1 -0
  67. package/dist/helpers/arweave.d.ts +4 -4
  68. package/dist/helpers/arweave.d.ts.map +1 -1
  69. package/dist/helpers/chainClient.d.ts +15 -0
  70. package/dist/helpers/chainClient.d.ts.map +1 -0
  71. package/dist/helpers/chainConfig.d.ts +12 -0
  72. package/dist/helpers/chainConfig.d.ts.map +1 -0
  73. package/dist/helpers/constants.d.ts +1 -2
  74. package/dist/helpers/constants.d.ts.map +1 -1
  75. package/dist/helpers/contracts/index.d.ts +90 -0
  76. package/dist/helpers/contracts/index.d.ts.map +1 -0
  77. package/dist/helpers/defaultChain.d.ts +4 -0
  78. package/dist/helpers/defaultChain.d.ts.map +1 -0
  79. package/dist/helpers/easDirect.d.ts +7 -76
  80. package/dist/helpers/easDirect.d.ts.map +1 -1
  81. package/dist/helpers/ensureEip7702ModularAccountReady.d.ts +1 -4
  82. package/dist/helpers/ensureEip7702ModularAccountReady.d.ts.map +1 -1
  83. package/dist/helpers/ensureExecutorModule.d.ts +1 -9
  84. package/dist/helpers/ensureExecutorModule.d.ts.map +1 -1
  85. package/dist/helpers/ensureManagedAccountEasConfigured.d.ts +2 -5
  86. package/dist/helpers/ensureManagedAccountEasConfigured.d.ts.map +1 -1
  87. package/dist/helpers/ensureManagedAccountReady.d.ts.map +1 -1
  88. package/dist/helpers/ensureManagedSignerSessionKey.d.ts +1 -0
  89. package/dist/helpers/ensureManagedSignerSessionKey.d.ts.map +1 -1
  90. package/dist/helpers/ensureSmartWalletThenPublish.d.ts +3 -13
  91. package/dist/helpers/ensureSmartWalletThenPublish.d.ts.map +1 -1
  92. package/dist/helpers/ensureWalletThenPublish.d.ts +21 -0
  93. package/dist/helpers/ensureWalletThenPublish.d.ts.map +1 -0
  94. package/dist/helpers/nameSchemaAttestation.d.ts +7 -0
  95. package/dist/helpers/nameSchemaAttestation.d.ts.map +1 -0
  96. package/dist/helpers/publishWalletRegistry.d.ts +19 -0
  97. package/dist/helpers/publishWalletRegistry.d.ts.map +1 -0
  98. package/dist/helpers/resolvePublishWallet.d.ts +7 -0
  99. package/dist/helpers/resolvePublishWallet.d.ts.map +1 -0
  100. package/dist/helpers/schemaRegistry.d.ts +11 -0
  101. package/dist/helpers/schemaRegistry.d.ts.map +1 -0
  102. package/dist/helpers/seedSigner.d.ts +62 -0
  103. package/dist/helpers/seedSigner.d.ts.map +1 -0
  104. package/dist/helpers/thirdweb.d.ts +14 -2
  105. package/dist/helpers/thirdweb.d.ts.map +1 -1
  106. package/dist/index.d.ts +11 -11
  107. package/dist/index.d.ts.map +1 -1
  108. package/dist/index.js +283 -5171
  109. package/dist/index.js.map +1 -1
  110. package/dist/publishManager-1vLf1ZHv.js +3005 -0
  111. package/dist/publishManager-1vLf1ZHv.js.map +1 -0
  112. package/dist/publishManager-5hUL8Of5.js +3007 -0
  113. package/dist/publishManager-5hUL8Of5.js.map +1 -0
  114. package/dist/publishManager-BO4sSSvo.js +3007 -0
  115. package/dist/publishManager-BO4sSSvo.js.map +1 -0
  116. package/dist/publishManager-BOICv9Yl.js +3008 -0
  117. package/dist/publishManager-BOICv9Yl.js.map +1 -0
  118. package/dist/publishManager-CCXWxiT1.js +3008 -0
  119. package/dist/publishManager-CCXWxiT1.js.map +1 -0
  120. package/dist/publishManager-Ccot_poQ.js +3008 -0
  121. package/dist/publishManager-Ccot_poQ.js.map +1 -0
  122. package/dist/publishManager-De3uWE-p.js +3007 -0
  123. package/dist/publishManager-De3uWE-p.js.map +1 -0
  124. package/dist/react/ConnectButton.d.ts.map +1 -1
  125. package/dist/react/PublishConfigContext.d.ts +4 -0
  126. package/dist/react/PublishConfigContext.d.ts.map +1 -0
  127. package/dist/react/PublishProvider.d.ts +7 -1
  128. package/dist/react/PublishProvider.d.ts.map +1 -1
  129. package/dist/react/PublishProvider.thirdweb.d.ts +11 -0
  130. package/dist/react/PublishProvider.thirdweb.d.ts.map +1 -0
  131. package/dist/react/useSeedWallet.d.ts +17 -0
  132. package/dist/react/useSeedWallet.d.ts.map +1 -0
  133. package/dist/resolveRevokeAccount-BGVjf-kI.js +30 -0
  134. package/dist/resolveRevokeAccount-BGVjf-kI.js.map +1 -0
  135. package/dist/resolveRevokeAccount-BRwOBTJ4.js +30 -0
  136. package/dist/resolveRevokeAccount-BRwOBTJ4.js.map +1 -0
  137. package/dist/resolveRevokeAccount-C0ZWAcHX.js +30 -0
  138. package/dist/resolveRevokeAccount-C0ZWAcHX.js.map +1 -0
  139. package/dist/resolveRevokeAccount-CKcr55EY.js +30 -0
  140. package/dist/resolveRevokeAccount-CKcr55EY.js.map +1 -0
  141. package/dist/resolveRevokeAccount-DNvuOQ1c.js +30 -0
  142. package/dist/resolveRevokeAccount-DNvuOQ1c.js.map +1 -0
  143. package/dist/resolveRevokeAccount-DvEPXZKI.js +30 -0
  144. package/dist/resolveRevokeAccount-DvEPXZKI.js.map +1 -0
  145. package/dist/resolveRevokeAccount-rOof3dUA.js +30 -0
  146. package/dist/resolveRevokeAccount-rOof3dUA.js.map +1 -0
  147. package/dist/seedSigner-BvK5WjmV.js +66 -0
  148. package/dist/seedSigner-BvK5WjmV.js.map +1 -0
  149. package/dist/services/PublishManager/actions/createPublish.d.ts.map +1 -1
  150. package/dist/services/PublishManager/actions/retryAttestations.d.ts +3 -2
  151. package/dist/services/PublishManager/actions/retryAttestations.d.ts.map +1 -1
  152. package/dist/services/PublishManager/actors/restoreFromDb.d.ts.map +1 -1
  153. package/dist/services/PublishManager/index.d.ts +2 -2
  154. package/dist/services/PublishManager/index.d.ts.map +1 -1
  155. package/dist/services/publish/actors/checking.d.ts.map +1 -1
  156. package/dist/services/publish/actors/createArweaveDataItems.d.ts.map +1 -1
  157. package/dist/services/publish/actors/createAttestations.d.ts.map +1 -1
  158. package/dist/services/publish/actors/createAttestationsDirectToEas.d.ts.map +1 -1
  159. package/dist/services/publish/actors/seedUidHelpers.d.ts +1 -17
  160. package/dist/services/publish/actors/seedUidHelpers.d.ts.map +1 -1
  161. package/dist/services/publish/helpers/ensureEasSchemas.d.ts +2 -5
  162. package/dist/services/publish/helpers/ensureEasSchemas.d.ts.map +1 -1
  163. package/dist/services/publish/helpers/receiptAttestationMs.d.ts +1 -3
  164. package/dist/services/publish/helpers/receiptAttestationMs.d.ts.map +1 -1
  165. package/dist/services/publish/index.d.ts.map +1 -1
  166. package/dist/services/revoke/revokeAttestations.d.ts +1 -3
  167. package/dist/services/revoke/revokeAttestations.d.ts.map +1 -1
  168. package/dist/services/upload/uploadMachine.d.ts +1 -1
  169. package/dist/thirdweb.d.ts +17 -0
  170. package/dist/thirdweb.d.ts.map +1 -0
  171. package/dist/thirdweb.js +176 -0
  172. package/dist/thirdweb.js.map +1 -0
  173. package/dist/types.d.ts +9 -4
  174. package/dist/types.d.ts.map +1 -1
  175. package/dist/worker-B3R2zwxm.js +69 -0
  176. package/dist/worker-B3R2zwxm.js.map +1 -0
  177. package/dist/worker-BVc0OzNI.js +105 -0
  178. package/dist/worker-BVc0OzNI.js.map +1 -0
  179. package/dist/worker-BWERw2Le.js +69 -0
  180. package/dist/worker-BWERw2Le.js.map +1 -0
  181. package/dist/worker-Bb3a6nOf.js +69 -0
  182. package/dist/worker-Bb3a6nOf.js.map +1 -0
  183. package/dist/worker-BqeFFnN_.js +69 -0
  184. package/dist/worker-BqeFFnN_.js.map +1 -0
  185. package/dist/worker-CqCsdQeT.js +69 -0
  186. package/dist/worker-CqCsdQeT.js.map +1 -0
  187. package/dist/worker-QZN_HMAs.js +69 -0
  188. package/dist/worker-QZN_HMAs.js.map +1 -0
  189. package/dist/worker-VilzVQ8C.js +69 -0
  190. package/dist/worker-VilzVQ8C.js.map +1 -0
  191. package/dist/worker-j_9ajZZU.js +100 -0
  192. package/dist/worker-j_9ajZZU.js.map +1 -0
  193. package/package.json +20 -5
@@ -0,0 +1,3007 @@
1
+ import { $ as e, C as t, D as n, G as r, J as i, K as a, M as o, O as s, Q as c, St as l, T as u, Tt as d, W as f, X as p, Z as m, a as h, at as ee, bt as g, c as _, d as v, dt as y, et as te, ft as b, g as ne, gt as x, h as re, i as ie, k as ae, l as oe, mt as se, nt as ce, o as le, st as ue, t as de, tt as fe, u as pe, wt as me, xt as he, yt as ge } from "./ensureManagedAccountEasConfigured-DDFBEb-B.js";
2
+ import { BaseArweaveClient as _e, BaseDb as S, BaseFileManager as C, INTERNAL_DATA_TYPES as ve, Item as w, ModelPropertyDataTypes as ye, applyPropertyAttestationUidsFromPublish as be, arweaveL1FinalizeJobs as xe, getCorrectId as Se, getEasSchemaForItemProperty as Ce, getItemPropertiesFromEas as we, getRelatedItemsForPublish as Te, getSegmentedItemProperties as Ee, getUploadPipelineTransactionStatus as De, htmlEmbeddedImageCoPublish as Oe, isItemOwned as ke, itemHasPublishUploadCandidates as Ae, prepareHtmlEmbeddedImagesForPublish as je, publishProcesses as T, resolvePublishPayloadValues as Me, rewriteHtmlEmbeddedImagesOnDisk as Ne, setSchemaUidForModel as Pe, setSchemaUidForSchemaDefinition as E, updateVersionUid as Fe, validateItemForPublish as Ie } from "@seedprotocol/sdk";
3
+ import { decodeAbiParameters as Le, encodeAbiParameters as Re, parseEventLogs as D } from "viem";
4
+ import { getContract as ze, sendTransaction as Be } from "thirdweb";
5
+ import { optimismSepolia as Ve } from "thirdweb/chains";
6
+ import { ethers as O } from "ethers";
7
+ import { NO_EXPIRATION as He, SchemaEncoder as Ue, SchemaRegistry as We, ZERO_ADDRESS as Ge, ZERO_BYTES32 as Ke } from "@ethereum-attestation-service/eas-sdk";
8
+ import { assign as k, createActor as qe, enqueueActions as Je, fromCallback as A, fromPromise as j, setup as Ye } from "xstate";
9
+ import Xe from "arweave";
10
+ import M from "debug";
11
+ import { and as Ze, desc as Qe, eq as N } from "drizzle-orm";
12
+ import { getInstalledModules as $e, installModule as et } from "thirdweb/modules";
13
+ //#region src/helpers/schemaRegistry.ts
14
+ async function tt(e) {
15
+ return y(e);
16
+ }
17
+ function nt(e) {
18
+ return ue(e);
19
+ }
20
+ //#endregion
21
+ //#region src/helpers/nameSchemaAttestation.ts
22
+ var rt = "0x0000000000000000000000000000000000000000";
23
+ function it(e) {
24
+ let t = new Ue("bytes32 schemaId,string name").encodeData([{
25
+ name: "schemaId",
26
+ value: e.schemaUid,
27
+ type: "bytes32"
28
+ }, {
29
+ name: "name",
30
+ value: e.schemaName,
31
+ type: "string"
32
+ }]);
33
+ return ce({
34
+ schema: he,
35
+ data: {
36
+ recipient: rt,
37
+ expirationTime: BigInt(He),
38
+ revocable: !0,
39
+ refUID: Ke,
40
+ data: t,
41
+ value: 0n
42
+ }
43
+ });
44
+ }
45
+ //#endregion
46
+ //#region src/services/publish/helpers/ensureEasSchemas.ts
47
+ var P = "0x0000000000000000000000000000000000000000", F = !0;
48
+ function at(e) {
49
+ return e.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
50
+ }
51
+ async function ot(e) {
52
+ let { itemRelationProperties: t, itemImageProperties: n, itemListProperties: r } = await Ee(e), i = /* @__PURE__ */ new Set();
53
+ e.modelName && i.add(e.modelName);
54
+ for (let e of t) {
55
+ let t = e.propertyDef?.ref;
56
+ t && i.add(t);
57
+ }
58
+ for (let e of n) {
59
+ let t = e.propertyDef?.dataType;
60
+ t === "File" ? i.add("File") : t === "Html" ? i.add("Html") : i.add("Image");
61
+ }
62
+ for (let e of r) {
63
+ let t = e.propertyDef?.ref;
64
+ t && i.add(t);
65
+ }
66
+ return i;
67
+ }
68
+ async function I(e, t) {
69
+ await x((await e.sendTransaction(t)).transactionHash);
70
+ }
71
+ async function L(e, t) {
72
+ let n = f(t) ? t.txSender : a(t) ? t : (() => {
73
+ throw Error("@seedprotocol/publish: ensureEasSchemasForItem requires a PublishWallet or SeedTxSender");
74
+ })(), { itemBasicProperties: r, itemRelationProperties: i, itemImageProperties: o, itemListProperties: s } = await Ee(e), c = [
75
+ ...r,
76
+ ...i,
77
+ ...o,
78
+ ...s
79
+ ], l = /* @__PURE__ */ new Set(), u = await ot(e), d = /* @__PURE__ */ new Set();
80
+ for (let e of u) {
81
+ let t = `bytes32 ${at(e)}`, r = We.getSchemaUID(t, P, F);
82
+ if (await tt(r)) {
83
+ Pe({
84
+ modelName: e,
85
+ schemaUid: r
86
+ });
87
+ continue;
88
+ }
89
+ if (d.has(r)) {
90
+ Pe({
91
+ modelName: e,
92
+ schemaUid: r
93
+ });
94
+ continue;
95
+ }
96
+ try {
97
+ await I(n, nt({
98
+ schema: t,
99
+ resolverAddress: P,
100
+ revocable: F
101
+ }));
102
+ } catch (t) {
103
+ throw Error(`Failed to register EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
104
+ }
105
+ try {
106
+ await I(n, it({
107
+ schemaUid: r,
108
+ schemaName: at(e)
109
+ }));
110
+ } catch (t) {
111
+ throw Error(`Failed to name EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
112
+ }
113
+ d.add(r), Pe({
114
+ modelName: e,
115
+ schemaUid: r
116
+ });
117
+ }
118
+ let p = "string storage_transaction_id", m = We.getSchemaUID(p, P, F);
119
+ if (await tt(m)) E({
120
+ text: p,
121
+ schemaUid: m
122
+ });
123
+ else if (!l.has(m) && (u.has("Image") || u.has("File") || u.has("Html"))) {
124
+ try {
125
+ await I(n, nt({
126
+ schema: p,
127
+ resolverAddress: P,
128
+ revocable: F
129
+ })), await I(n, it({
130
+ schemaUid: m,
131
+ schemaName: "storage_transaction_id"
132
+ }));
133
+ } catch (e) {
134
+ throw Error(`Failed to register EAS schema for storageTransactionId: ${e instanceof Error ? e.message : String(e)}`);
135
+ }
136
+ l.add(m), E({
137
+ text: p,
138
+ schemaUid: m
139
+ });
140
+ }
141
+ for (let e of c) {
142
+ if (!e.propertyDef) continue;
143
+ let t = ve[e.propertyDef.dataType]?.eas ?? "string", r = e, i = r.storagePropertyName && r.storagePropertyName.length > 0 ? r.storagePropertyName : e.propertyName, a = at(i), o = `${t} ${a}`, s = [
144
+ "string",
145
+ "address",
146
+ "bool",
147
+ "bytes",
148
+ "bytes32",
149
+ "uint8",
150
+ "uint16",
151
+ "uint32",
152
+ "uint64",
153
+ "uint128",
154
+ "uint256"
155
+ ].includes(t) ? t : void 0, c = await Ce({
156
+ schemaUid: e.schemaUid,
157
+ propertyName: i,
158
+ easDataType: s
159
+ });
160
+ if (c) {
161
+ let e = await tt(c.id);
162
+ if (e && e.schema === o) {
163
+ E({
164
+ text: o,
165
+ schemaUid: c.id
166
+ });
167
+ continue;
168
+ }
169
+ }
170
+ let u = We.getSchemaUID(o, P, F);
171
+ if (await tt(u)) {
172
+ E({
173
+ text: o,
174
+ schemaUid: u
175
+ });
176
+ continue;
177
+ }
178
+ if (l.has(u)) {
179
+ E({
180
+ text: o,
181
+ schemaUid: u
182
+ });
183
+ continue;
184
+ }
185
+ try {
186
+ await I(n, nt({
187
+ schema: o,
188
+ resolverAddress: P,
189
+ revocable: F
190
+ }));
191
+ } catch (t) {
192
+ throw Error(`Failed to register EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
193
+ }
194
+ try {
195
+ await I(n, it({
196
+ schemaUid: u,
197
+ schemaName: a
198
+ }));
199
+ } catch (t) {
200
+ throw Error(`Failed to name EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
201
+ }
202
+ l.add(u), E({
203
+ text: o,
204
+ schemaUid: u
205
+ });
206
+ }
207
+ let h = await Te(e);
208
+ for (let e of h) await L(e, n);
209
+ }
210
+ //#endregion
211
+ //#region src/helpers/blockchain.ts
212
+ var R = () => {
213
+ let e = _e.getHost(), t = Xe;
214
+ return Object.keys(t).includes("default") && t.default ? t.default.init({
215
+ host: e,
216
+ protocol: "https"
217
+ }) : t.init({
218
+ host: e,
219
+ protocol: "https"
220
+ });
221
+ }, z = "0x" + "0".repeat(64), B = async (e) => {
222
+ let t;
223
+ try {
224
+ t = await w.find({ seedLocalId: e });
225
+ } catch {}
226
+ return t || new Promise((t) => {
227
+ let n = setInterval(() => {
228
+ try {
229
+ w.find({ seedLocalId: e }).then((e) => {
230
+ e && (clearInterval(n), t(e));
231
+ });
232
+ } catch {}
233
+ }, 200);
234
+ });
235
+ };
236
+ function st(e) {
237
+ if (!e || typeof e != "object") return;
238
+ let t = e;
239
+ if (Array.isArray(t.data_root)) return {
240
+ data_root: new Uint8Array(t.data_root),
241
+ chunks: (t.chunks ?? []).map((e) => ({
242
+ ...e,
243
+ dataHash: new Uint8Array(e.dataHash ?? [])
244
+ })),
245
+ proofs: (t.proofs ?? []).map((e) => ({
246
+ ...e,
247
+ proof: new Uint8Array(e.proof ?? [])
248
+ }))
249
+ };
250
+ }
251
+ function ct(e) {
252
+ return {
253
+ data_root: Array.from(e.data_root),
254
+ chunks: e.chunks.map((e) => ({
255
+ ...e,
256
+ dataHash: Array.from(e.dataHash)
257
+ })),
258
+ proofs: e.proofs.map((e) => ({
259
+ ...e,
260
+ proof: Array.from(e.proof)
261
+ }))
262
+ };
263
+ }
264
+ //#endregion
265
+ //#region src/services/publish/actors/createArweaveTransactions.ts
266
+ var lt = j(async ({ input: { context: e } }) => {
267
+ let { item: t } = e;
268
+ t.getPublishUploads || (t = await B(t.seedLocalId));
269
+ let n = {};
270
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
271
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
272
+ r?.length && (n.deferHtmlStorageSeedLocalIds = r);
273
+ let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = o(), s = e.signArweaveTransactions ?? a.signArweaveTransactions, c = e.arweaveJwk ?? a.arweaveJwk, l = i.map((e) => ({
274
+ versionLocalId: e.versionLocalId,
275
+ itemPropertyName: e.itemPropertyName,
276
+ transactionJson: e.transactionToSign.toJSON()
277
+ })), u;
278
+ if (s) u = await s(l);
279
+ else if (c) {
280
+ let e = R(), t = c;
281
+ u = [];
282
+ for (let n of l) {
283
+ let r = e.transactions.fromRaw(n.transactionJson);
284
+ r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
285
+ let i = r.toJSON();
286
+ u.push({
287
+ transaction: {
288
+ ...i,
289
+ chunks: r.chunks ? ct(r.chunks) : void 0
290
+ },
291
+ versionId: n.versionLocalId,
292
+ modelName: n.itemPropertyName
293
+ });
294
+ }
295
+ } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
296
+ let d = R();
297
+ return {
298
+ arweaveTransactions: u.map((e) => {
299
+ let { chunks: t, ...n } = e.transaction, r = { ...n }, i = st(t);
300
+ return i && (r.chunks = i), {
301
+ transaction: d.transactions.fromRaw(r),
302
+ versionId: e.versionId,
303
+ modelName: e.modelName
304
+ };
305
+ }),
306
+ publishUploads: i
307
+ };
308
+ }), ut = j(async ({ input: { context: e } }) => {
309
+ let { item: t } = e;
310
+ t.getPublishUploads || (t = await B(t.seedLocalId));
311
+ let n = {};
312
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
313
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
314
+ r?.length && (n.onlyHtmlStorageSeedLocalIds = r, n.skipRelationRecursion = !0);
315
+ let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = o(), s = e.signArweaveTransactions ?? a.signArweaveTransactions, c = e.arweaveJwk ?? a.arweaveJwk, l = i.map((e) => ({
316
+ versionLocalId: e.versionLocalId,
317
+ itemPropertyName: e.itemPropertyName,
318
+ transactionJson: e.transactionToSign.toJSON()
319
+ })), u;
320
+ if (s) u = await s(l);
321
+ else if (c) {
322
+ let e = R(), t = c;
323
+ u = [];
324
+ for (let n of l) {
325
+ let r = e.transactions.fromRaw(n.transactionJson);
326
+ r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
327
+ let i = r.toJSON();
328
+ u.push({
329
+ transaction: {
330
+ ...i,
331
+ chunks: r.chunks ? ct(r.chunks) : void 0
332
+ },
333
+ versionId: n.versionLocalId,
334
+ modelName: n.itemPropertyName
335
+ });
336
+ }
337
+ } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
338
+ let d = R();
339
+ return {
340
+ arweaveTransactions: u.map((e) => {
341
+ let { chunks: t, ...n } = e.transaction, r = { ...n }, i = st(t);
342
+ return i && (r.chunks = i), {
343
+ transaction: d.transactions.fromRaw(r),
344
+ versionId: e.versionId,
345
+ modelName: e.modelName
346
+ };
347
+ }),
348
+ publishUploads: i
349
+ };
350
+ }), dt = j(async ({ input: { context: e } }) => {
351
+ let t = e.htmlEmbeddedDataUriPolicy ?? "materialize";
352
+ return { deferredHtmlSeedLocalIds: (await je(e.item, t)).deferredHtmlSeedLocalIds };
353
+ });
354
+ //#endregion
355
+ //#region src/services/publish/actors/rewritingHtmlEmbedded.ts
356
+ function ft(e, t) {
357
+ let n = [], r = Math.min(e?.length ?? 0, t?.length ?? 0);
358
+ for (let i = 0; i < r; i++) {
359
+ let r = e[i], a = t[i], o = r.transaction?.id;
360
+ typeof o == "string" && o.length > 0 && n.push({
361
+ txId: o,
362
+ seedLocalId: a.seedLocalId,
363
+ versionLocalId: a.versionLocalId
364
+ });
365
+ }
366
+ return n;
367
+ }
368
+ var pt = j(async ({ input: { context: e } }) => {
369
+ let t = ft(e.htmlEmbeddedPhase1ArweaveTransactions, e.htmlEmbeddedPhase1PublishUploads);
370
+ await Ne(e.item.seedLocalId, t);
371
+ }), mt = (e, t, n) => {
372
+ let r = [];
373
+ return e && r.push({
374
+ name: "Content-SHA-256",
375
+ value: e
376
+ }), t && r.push({
377
+ name: "Content-Type",
378
+ value: t
379
+ }), n?.length && r.push(...n), r;
380
+ }, ht = async (e) => {
381
+ let t = (e instanceof Uint8Array, new Uint8Array(e)), n = await crypto.subtle.digest("SHA-256", t);
382
+ return Array.from(new Uint8Array(n)).map((e) => e.toString(16).padStart(2, "0")).join("");
383
+ }, gt = {
384
+ png: "image/png",
385
+ jpg: "image/jpeg",
386
+ jpeg: "image/jpeg",
387
+ gif: "image/gif",
388
+ webp: "image/webp",
389
+ svg: "image/svg+xml",
390
+ html: "text/html",
391
+ htm: "text/html",
392
+ json: "application/json",
393
+ txt: "text/plain"
394
+ }, _t = (e) => {
395
+ let t = e.split(".").pop()?.toLowerCase();
396
+ return t ? gt[t] : void 0;
397
+ }, vt = async (e) => typeof Blob < "u" && e instanceof Blob ? new Uint8Array(await e.arrayBuffer()) : new Uint8Array(e), yt = (e) => {
398
+ switch (e) {
399
+ case "Image": return C.getFilesPath("images");
400
+ case "File": return C.getFilesPath("files");
401
+ case "Html": return C.getFilesPath("html");
402
+ case "Json": return C.getFilesPath("json");
403
+ default: return C.getFilesPath("images");
404
+ }
405
+ }, bt = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]*)$/i;
406
+ function xt(e) {
407
+ let t = bt.exec((e ?? "").trim());
408
+ if (!t) return null;
409
+ try {
410
+ let e = t[1].toLowerCase().trim(), n = t[2].replace(/\s/g, "");
411
+ return {
412
+ mimeType: e,
413
+ bytes: Uint8Array.from(atob(n), (e) => e.charCodeAt(0))
414
+ };
415
+ } catch {
416
+ return null;
417
+ }
418
+ }
419
+ var St = async (e, t, n, r) => {
420
+ let i = r?.arweaveUploadTags, a = e.itemProperty, o = [];
421
+ for (let t of e.childProperties) {
422
+ let e = t.localStoragePath;
423
+ !e || e.endsWith("undefined") || await C.pathExists(e) && o.push({
424
+ propertyName: t.propertyName,
425
+ localStoragePath: e
426
+ });
427
+ }
428
+ let s;
429
+ if ((!o || o.length === 0) && n?.localStoragePath) {
430
+ let e = n.localStoragePath;
431
+ if (e && !e.endsWith("undefined") && await C.pathExists(e)) try {
432
+ s = await vt(await C.readFileAsBuffer(e));
433
+ } catch {
434
+ s = await vt((await C.getFs()).readFileSync(e));
435
+ }
436
+ }
437
+ if (o.length > 0) {
438
+ let e = "===FILE_SEPARATOR===", t = "", n = await C.getFs();
439
+ for (let r of o) {
440
+ let i;
441
+ try {
442
+ i = await n.promises.readFile(r.localStoragePath);
443
+ } catch {
444
+ i = n.readFileSync(r.localStoragePath);
445
+ }
446
+ t += `${e}${r.propertyName}${e}${i}`;
447
+ }
448
+ s = typeof document < "u" ? new TextEncoder().encode(t) : new Uint8Array(Buffer.from(t));
449
+ }
450
+ if (!s) return t;
451
+ let c = new Uint8Array(s), l = await ht(c), u;
452
+ o.length === 0 && n?.localStoragePath ? u = _t(n.localStoragePath) : o.length > 0 && (u = "application/octet-stream");
453
+ let d = n ? n.localId : a.localId, f = n ? n.propertyName : a.propertyName;
454
+ return t.push({
455
+ data: c,
456
+ contentHash: l,
457
+ contentType: u,
458
+ tags: mt(l, u, i),
459
+ itemPropertyName: f,
460
+ itemPropertyLocalId: d,
461
+ seedLocalId: a.seedLocalId,
462
+ versionLocalId: a.versionLocalId
463
+ }), t;
464
+ }, Ct = async (e, t) => {
465
+ let n = [], r = t?.arweaveUploadTags;
466
+ for (let i of e) {
467
+ let e = i.getService().getSnapshot(), a = "context" in e ? e.context : null;
468
+ if (!a) continue;
469
+ let o = a.propertyValue, s = a.refResolvedValue;
470
+ if (!s) continue;
471
+ let { localId: c } = Se(o ?? "");
472
+ if (!c) continue;
473
+ let l = i.propertyDef?.refValueType ?? i.propertyDef?.dataType ?? "Image";
474
+ if (l === ye.Html) {
475
+ if (t?.deferHtmlStorageSeedLocalIds?.includes(c) || t?.onlyHtmlStorageSeedLocalIds?.length && !t.onlyHtmlStorageSeedLocalIds.includes(c)) continue;
476
+ } else if (t?.onlyHtmlStorageSeedLocalIds?.length) continue;
477
+ let u = `${yt(l)}/${s}`;
478
+ if (!await C.pathExists(u)) continue;
479
+ let d = await vt(await C.readFileAsBuffer(u)), f = await ht(d), p = _t(s);
480
+ n.push({
481
+ data: d,
482
+ contentHash: f,
483
+ contentType: p,
484
+ tags: mt(f, p, r),
485
+ itemPropertyName: i.propertyName,
486
+ itemPropertyLocalId: i.localId,
487
+ seedLocalId: c,
488
+ versionLocalId: i.versionLocalId
489
+ });
490
+ }
491
+ return n;
492
+ };
493
+ async function wt(e, t, n) {
494
+ let r = S.getAppDb();
495
+ if (!r || n?.onlyHtmlStorageSeedLocalIds?.length) return t;
496
+ let i = await r.select().from(Oe).where(N(Oe.parentSeedLocalId, e.seedLocalId)), a = new Set(t.map((e) => e.seedLocalId));
497
+ for (let e of i) {
498
+ if (a.has(e.imageSeedLocalId)) continue;
499
+ let r = await w.find({
500
+ seedLocalId: e.imageSeedLocalId,
501
+ modelName: "Image"
502
+ });
503
+ if (!r) continue;
504
+ let i = r.internalProperties.storageTransactionId ?? r.allProperties.storageTransactionId, o = i?.getService().getSnapshot(), s = o && "context" in o ? o.context : void 0, c = xt(typeof s?.propertyValue == "string" ? s.propertyValue ?? "" : ""), l = [];
505
+ if (c && i && i.localId && i.versionLocalId) {
506
+ let e = await ht(c.bytes);
507
+ l = [{
508
+ data: c.bytes,
509
+ contentHash: e,
510
+ contentType: c.mimeType,
511
+ tags: mt(e, c.mimeType, n?.arweaveUploadTags),
512
+ itemPropertyName: i.propertyName,
513
+ itemPropertyLocalId: i.localId,
514
+ seedLocalId: r.seedLocalId,
515
+ versionLocalId: i.versionLocalId
516
+ }];
517
+ }
518
+ for (let e of l) a.has(e.seedLocalId) || (t.push(e), a.add(e.seedLocalId));
519
+ }
520
+ return t;
521
+ }
522
+ var Tt = async (e, t = [], n, r) => {
523
+ let { itemUploadProperties: i, itemRelationProperties: a, itemImageProperties: o } = await Ee(e);
524
+ if (!n && r?.onlyHtmlStorageSeedLocalIds?.length) {
525
+ let e = await Ct(o, r);
526
+ return t.push(...e), t;
527
+ }
528
+ for (let e of i) t = await St(e, t, n, r);
529
+ let s = await Ct(o, r);
530
+ if (t.push(...s), !n && !r?.onlyHtmlStorageSeedLocalIds?.length && (t = await wt(e, t, r)), r?.skipRelationRecursion) return t;
531
+ for (let e of a) {
532
+ let n = e.getService().getSnapshot(), i = "context" in n ? n.context : null;
533
+ if (!i) continue;
534
+ let a = i.propertyValue;
535
+ if (!a || e.uid) continue;
536
+ let { localId: o, uid: s } = Se(a), c = await w.find({
537
+ seedLocalId: o,
538
+ seedUid: s
539
+ });
540
+ if (!c) throw Error(`No relatedItem found for ${e.propertyName}`);
541
+ t = await Tt(c, t, e, r);
542
+ }
543
+ return t;
544
+ }, Et = 3, Dt = new TextEncoder().encode("seed-recovery"), Ot = 32, kt = 18446744073709551615n;
545
+ function At(e, t, n) {
546
+ let r = O.solidityPackedKeccak256([
547
+ "uint256",
548
+ "address",
549
+ "uint64"
550
+ ], [
551
+ BigInt(t),
552
+ e,
553
+ n & kt
554
+ ]);
555
+ return O.getBytes(r);
556
+ }
557
+ function jt(e) {
558
+ if (e.length === 0) return new Uint8Array([0]);
559
+ if (e.length !== Ot) throw Error(`ANS-104 target/anchor must be empty or ${Ot} bytes, got ${e.length}`);
560
+ let t = new Uint8Array(33);
561
+ return t[0] = 1, t.set(e, 1), t;
562
+ }
563
+ function Mt(e) {
564
+ return typeof e == "object" && !!e && "privateKey" in e && typeof e.privateKey == "string";
565
+ }
566
+ function Nt(e, t, n) {
567
+ let r = e >= 0 ? e << 1 : ~e << 1 | 1, i = n;
568
+ do {
569
+ let e = r & 127;
570
+ r >>>= 7, t[i++] = r ? e | 128 : e;
571
+ } while (r);
572
+ return i - n;
573
+ }
574
+ var Pt = (e) => {
575
+ if (!e?.length) return new Uint8Array();
576
+ let t = new TextEncoder(), n = new Uint8Array(16), r = [], i = (e) => {
577
+ let t = Nt(e, n, 0);
578
+ r.push(n.slice(0, t));
579
+ };
580
+ i(e.length);
581
+ for (let n of e) {
582
+ let e = t.encode(n.name), a = t.encode(n.value);
583
+ i(e.length), r.push(e), i(a.length), r.push(a);
584
+ }
585
+ i(0);
586
+ let a = r.reduce((e, t) => e + t.length, 0), o = new Uint8Array(a), s = 0;
587
+ for (let e of r) o.set(e, s), s += e.length;
588
+ return o;
589
+ }, Ft = (e) => {
590
+ let t = new Uint8Array(8), n = new DataView(t.buffer);
591
+ return n.setUint32(0, e & 4294967295, !0), n.setUint32(4, Math.floor(e / 4294967296), !0), t;
592
+ };
593
+ async function V(e) {
594
+ return new Uint8Array(await crypto.subtle.digest("SHA-384", e));
595
+ }
596
+ function It(e, t) {
597
+ let n = new Uint8Array(e.length + t.length);
598
+ return n.set(e, 0), n.set(t, e.length), n;
599
+ }
600
+ async function Lt(e) {
601
+ let t = new TextEncoder();
602
+ if (Array.isArray(e)) {
603
+ let n = await V(It(t.encode("list"), t.encode(e.length.toString())));
604
+ for (let t of e) {
605
+ let e = await Lt(t);
606
+ n = await V(It(n, e));
607
+ }
608
+ return n;
609
+ }
610
+ return V(It(await V(It(t.encode("blob"), t.encode(e.byteLength.toString()))), await V(e)));
611
+ }
612
+ async function Rt(e, t, n, r, i) {
613
+ let a = new TextEncoder();
614
+ return Lt([
615
+ a.encode("dataitem"),
616
+ a.encode("1"),
617
+ a.encode(Et.toString()),
618
+ e,
619
+ t,
620
+ n,
621
+ r,
622
+ i
623
+ ]);
624
+ }
625
+ function zt(e, t, n, r, i) {
626
+ let a = Pt(t), o = Ft(t.length), s = Ft(a.length), c = [
627
+ e,
628
+ jt(r),
629
+ jt(i),
630
+ o,
631
+ s,
632
+ a,
633
+ n
634
+ ], l = c.reduce((e, t) => e + t.length, 0), u = new Uint8Array(l), d = 0;
635
+ for (let e of c) u.set(e, d), d += e.length;
636
+ return u;
637
+ }
638
+ async function Bt(e, t) {
639
+ let n = new Uint8Array(2);
640
+ new DataView(n.buffer).setUint16(0, Et, !0);
641
+ let r = 67 + t.length, i = new Uint8Array(r);
642
+ i.set(n, 0), i.set(e, 2), i.set(t, 67);
643
+ let a = await crypto.subtle.digest("SHA-256", new Uint8Array(e));
644
+ return {
645
+ id: Kt(new Uint8Array(a)),
646
+ raw: i
647
+ };
648
+ }
649
+ var Vt = async (e, t, n, r = new Uint8Array()) => {
650
+ let i = O.SigningKey.computePublicKey(t.privateKey, !1), a = O.getBytes(i), o = Pt(n), s = new Uint8Array(), c = await Rt(a, s, r, o, e);
651
+ return Bt(O.getBytes(await t.signMessage(c)), zt(a, n, e, s, r));
652
+ }, Ht = async (e, t, n, r = new Uint8Array()) => {
653
+ let i = O.hexlify(Dt), a = await t.signMessage({ message: { raw: i } }), o = O.hashMessage(Dt), s = O.SigningKey.recoverPublicKey(o, a), c = O.getBytes(s), l = Pt(n), u = new Uint8Array(), d = await Rt(c, u, r, l, e), f = O.hexlify(d), p = await t.signMessage({ message: { raw: f } });
654
+ return Bt(O.getBytes(p), zt(c, n, e, u, r));
655
+ };
656
+ function Ut(e) {
657
+ if (e.length < 133) return null;
658
+ let t = e[132];
659
+ if (t !== 0 && t !== 1) return null;
660
+ let n = t === 1;
661
+ if (n && e.length < 165) return null;
662
+ let r = 132 + (n ? 33 : 1);
663
+ if (e.length < r + 1) return null;
664
+ let i = e[r];
665
+ if (i !== 0 && i !== 1) return null;
666
+ let a = i === 1;
667
+ return a && e.length < r + 33 ? null : r + (a ? 33 : 1);
668
+ }
669
+ function Wt(e) {
670
+ let t = Ut(e);
671
+ if (t == null) return null;
672
+ let n = e[132] === 1, r = n ? e.slice(133, 165) : new Uint8Array(), i = 132 + (n ? 33 : 1);
673
+ return {
674
+ rawTarget: r,
675
+ rawAnchor: e[i] === 1 ? e.slice(i + 1, i + 33) : new Uint8Array(),
676
+ tagsStart: t
677
+ };
678
+ }
679
+ async function Gt(e) {
680
+ let t = Wt(e);
681
+ if (t == null) return !1;
682
+ let { rawTarget: n, rawAnchor: r, tagsStart: i } = t, a = i + 16;
683
+ if (e.length < a) return !1;
684
+ let o = new DataView(e.buffer, e.byteOffset, e.byteLength);
685
+ if (o.getUint16(0, !0) !== Et) return !1;
686
+ let s = e.slice(2, 67), c = e.slice(67, 132), l = Number(o.getUint32(i + 8, !0) + o.getUint32(i + 12, !0) * 4294967296), u = i + 16 + l;
687
+ if (e.length < u) return !1;
688
+ let d = e.slice(i + 16, u), f = e.slice(u);
689
+ try {
690
+ let e = await Rt(c, n, r, d, f), t = O.hashMessage(e), i = O.hexlify(s), a = O.SigningKey.recoverPublicKey(t, i), o = O.getBytes(a);
691
+ return o.length === c.length && o.every((e, t) => e === c[t]);
692
+ } catch {
693
+ return !1;
694
+ }
695
+ }
696
+ var Kt = (e) => {
697
+ let t = "";
698
+ for (let n of e) t += String.fromCharCode(n);
699
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
700
+ }, qt = M("seedProtocol:createArweaveDataItems");
701
+ async function Jt(e, t, n) {
702
+ let r, i;
703
+ if (t) r = (await t(e)).map((e) => ({
704
+ transaction: { id: e.transaction.id },
705
+ versionId: e.versionId,
706
+ modelName: e.modelName
707
+ }));
708
+ else if (n) {
709
+ let t = [], a = Date.now();
710
+ for (let r = 0; r < e.length; r++) {
711
+ let i = e[r], o = i.tags, s = new Uint8Array(8);
712
+ crypto.getRandomValues(s);
713
+ let c = (new DataView(s.buffer).getBigUint64(0, !1) ^ BigInt(r)) & 18446744073709551615n, l;
714
+ if (Mt(n)) {
715
+ let e = At(n.address, a, c);
716
+ l = await Vt(i.data, n, o, e);
717
+ } else {
718
+ let e = f(n) ? n.signer : n, t = At(e.address, a, c);
719
+ l = await Ht(i.data, e, o, t);
720
+ }
721
+ if (!await Gt(l.raw)) throw qt("DataItem verification failed: id=%s modelName=%s", l.id, i.itemPropertyName), Error(`DataItem signature verification failed for ${i.itemPropertyName}. The signing key may not match the owner, or the payload may have been modified.`);
722
+ t.push(l);
723
+ }
724
+ i = t, r = t.map((t, n) => ({
725
+ transaction: { id: t.id },
726
+ versionId: e[n]?.versionLocalId,
727
+ modelName: e[n]?.itemPropertyName
728
+ }));
729
+ } else throw Error("@seedprotocol/publish: useArweaveBundler requires signDataItems or dataItemSigner (pass at createPublish or in PublishProvider config)");
730
+ let a = e.map((e) => ({
731
+ itemPropertyName: e.itemPropertyName,
732
+ itemPropertyLocalId: e.itemPropertyLocalId,
733
+ seedLocalId: e.seedLocalId,
734
+ versionLocalId: e.versionLocalId,
735
+ transactionToSign: null
736
+ }));
737
+ return {
738
+ arweaveTransactions: r,
739
+ publishUploads: a,
740
+ signedDataItems: i
741
+ };
742
+ }
743
+ var Yt = j(async ({ input: { context: e } }) => {
744
+ let { item: t } = e;
745
+ t.getPublishUploads || (t = await B(t.seedLocalId));
746
+ let n = {};
747
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
748
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
749
+ r?.length && (n.deferHtmlStorageSeedLocalIds = r);
750
+ let i = await Tt(t, [], void 0, Object.keys(n).length ? n : void 0), a = o();
751
+ return Jt(i, e.signDataItems ?? a.signDataItems, e.dataItemSigner ?? a.dataItemSigner);
752
+ });
753
+ //#endregion
754
+ //#region src/services/publish/actors/createArweaveDataItemsPhase2.ts
755
+ async function Xt(e) {
756
+ let { item: t } = e;
757
+ t.getPublishUploads || (t = await B(t.seedLocalId));
758
+ let n = {};
759
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
760
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
761
+ r?.length && (n.onlyHtmlStorageSeedLocalIds = r, n.skipRelationRecursion = !0);
762
+ let i = await Tt(t, [], void 0, Object.keys(n).length ? n : void 0), a = o(), s = e.signDataItems ?? a.signDataItems, c = e.dataItemSigner ?? a.dataItemSigner;
763
+ return i.length === 0 ? {
764
+ arweaveTransactions: [],
765
+ publishUploads: [],
766
+ signedDataItems: void 0
767
+ } : Jt(i, s, c);
768
+ }
769
+ var Zt = j(async ({ input: { context: e } }) => Xt(e)), Qt = 8192;
770
+ function $t(e) {
771
+ let t = new Uint8Array(e), n = "";
772
+ for (let e = 0; e < t.length; e += Qt) {
773
+ let r = t.subarray(e, Math.min(e + Qt, t.length));
774
+ n += String.fromCharCode.apply(null, r);
775
+ }
776
+ return btoa(n);
777
+ }
778
+ async function en(e) {
779
+ let t = [];
780
+ for (let [n, r] of e.entries()) {
781
+ let e = r;
782
+ if (typeof e == "object" && e && "arrayBuffer" in e) {
783
+ let r = $t(await e.arrayBuffer()), i = e;
784
+ t.push({
785
+ name: n,
786
+ value: r,
787
+ encoding: "base64",
788
+ filename: i.name || void 0
789
+ });
790
+ } else t.push({
791
+ name: n,
792
+ value: String(r)
793
+ });
794
+ }
795
+ return t;
796
+ }
797
+ function tn(e, t, n) {
798
+ let r = ["Upload server returned ", String(e)], i = t && typeof t == "object" && "message" in t ? String(t.message) : t && typeof t == "object" && "error" in t ? String(t.error) : null;
799
+ return i ? r.push(`: ${i}`) : n && r.push(` (${n})`), r.join("");
800
+ }
801
+ function nn(e) {
802
+ if (!e) return "Upload server unavailable. Please try again or check your connection.";
803
+ let t = e.toLowerCase();
804
+ return /other side closed|econnreset|socket hang up|connection closed/i.test(t) ? "Upload server closed the connection. It may be busy or the request may be too large—try again." : /etimedout|timeout/i.test(t) ? "Upload request timed out. Please try again." : /enotfound|getaddrinfo|dns/i.test(t) ? "Upload server could not be reached. Check the upload URL and your network." : "Upload failed. Please try again or check the upload server.";
805
+ }
806
+ async function rn(e, t, n) {
807
+ let r = typeof window < "u" ? window.Main : void 0;
808
+ if (r?.uploadArweaveStart) {
809
+ let n = await en(t);
810
+ return r.uploadArweaveStart(e, n);
811
+ }
812
+ let i = await fetch(e, {
813
+ method: "POST",
814
+ body: t
815
+ }), a = await i.json().catch(() => ({}));
816
+ return {
817
+ status: i.status,
818
+ body: a
819
+ };
820
+ }
821
+ //#endregion
822
+ //#region src/services/publish/actors/sendReimbursementRequest.ts
823
+ var an = j(async ({ input: { context: e, event: t } }) => {
824
+ let { arweaveTransactions: n = [], transactionKeys: r, reimbursementTransactionId: i } = e;
825
+ if (i) return { transactionId: i };
826
+ let a = n.map(({ transaction: e }) => e), s = new FormData();
827
+ for (let e of a) {
828
+ let { data: t, chunks: n, ...r } = e, i = t instanceof Blob ? t : new Blob([t]);
829
+ s.append(`${e.id}-data`, i, `${e.id}-data`);
830
+ let a = new Blob([JSON.stringify(n)], { type: "application/json" });
831
+ s.append(`${e.id}-chunks`, a, `${e.id}-chunks`);
832
+ let o = new Blob([JSON.stringify(r)], { type: "application/json" });
833
+ s.append(`${e.id}-json`, o, `${e.id}-json`);
834
+ }
835
+ let { uploadApiBaseUrl: c } = o(), { status: l, body: u, message: d } = await rn(`${c}/api/upload/arweave/start`, s, c);
836
+ if (l >= 300 || l < 200) {
837
+ let e = l === 0 ? d : null;
838
+ e && console.error("[upload]", e);
839
+ let t = l === 0 ? nn(e) : tn(l, u, r);
840
+ throw Error(t);
841
+ }
842
+ return u;
843
+ }), on = j(async ({ input: { context: e, event: t } }) => {
844
+ let { requestResponse: n, reimbursementTransactionId: r } = e;
845
+ if (!n) throw Error("No request response");
846
+ if (!r) throw Error("No reimbursement transaction id");
847
+ let i = R();
848
+ await new Promise((e, t) => {
849
+ let n = setInterval(async () => {
850
+ let t;
851
+ try {
852
+ t = await i.transactions.getStatus(r);
853
+ } catch {
854
+ return;
855
+ }
856
+ t && t.confirmed && (clearInterval(n), e());
857
+ }, 5e3);
858
+ });
859
+ }), H = M("seedProtocol:services:publish:actors");
860
+ function sn(e) {
861
+ if (e instanceof Uint8Array) return e;
862
+ if (e instanceof ArrayBuffer) return new Uint8Array(e);
863
+ throw Error("Transaction data must be Uint8Array or ArrayBuffer for upload resume");
864
+ }
865
+ var cn = A(({ sendBack: e, input: t }) => {
866
+ let n = t.context, r = (n.arweaveTransactions ?? []).map(({ transaction: e }) => e), i = R(), a = n.uploaderState && typeof n.currentTransactionIndex == "number", o = a ? n.currentTransactionIndex : 0;
867
+ (async () => {
868
+ let t = r.length;
869
+ for (let s = o; s < t; s++) {
870
+ let c = r[s];
871
+ if (!c) continue;
872
+ let l = i.transactions.fromRaw(c);
873
+ if (!await i.transactions.verify(l)) throw Error("Transaction verification failed");
874
+ let u, d = n.uploaderState;
875
+ if (a && s === o && d) {
876
+ let e = l.data, t = e instanceof Uint8Array ? e : sn(e);
877
+ u = await i.transactions.getUploader(d, t);
878
+ } else u = await i.transactions.getUploader(l, l.data);
879
+ for (; !u.isComplete;) {
880
+ H("uploading chunk"), H(`uploader.pctComplete: ${u.pctComplete}`), H(`uploader.uploadedChunks: ${u.uploadedChunks}`), H(`uploader.totalChunks: ${u.totalChunks}`), H(u.lastResponseError), H(u.lastResponseStatus);
881
+ try {
882
+ await u.uploadChunk(), e({
883
+ type: "updatePercentage",
884
+ completionPercentage: Math.trunc((s + u.pctComplete / 100) / t * 100),
885
+ uploaderState: u.toJSON(),
886
+ currentTransactionIndex: s
887
+ }), H(`${u.pctComplete}% complete, ${u.uploadedChunks}/${u.totalChunks}`);
888
+ } catch (e) {
889
+ H(e);
890
+ }
891
+ }
892
+ }
893
+ return "done";
894
+ })().then((t) => {
895
+ e({
896
+ type: "uploadComplete",
897
+ result: t
898
+ });
899
+ }).catch((t) => {
900
+ e({
901
+ type: "uploadError",
902
+ error: t
903
+ });
904
+ });
905
+ }), ln = 12e4, un = Function("s", "return import(s)"), dn = null, fn = async () => {
906
+ if (dn) return dn;
907
+ if (typeof window < "u") return null;
908
+ try {
909
+ let e = await un(`node:${["fs", "promises"].join("/")}`);
910
+ return dn = {
911
+ readFile: e.readFile,
912
+ stat: e.stat
913
+ }, dn;
914
+ } catch {
915
+ return null;
916
+ }
917
+ }, pn = A(({ sendBack: e, input: { context: t } }) => {
918
+ let { signedDataItems: n } = t, { uploadApiBaseUrl: r, useArweaveBundler: i } = o();
919
+ if (!i || !r) {
920
+ e({
921
+ type: "uploadError",
922
+ error: /* @__PURE__ */ Error("Arweave bundler not configured. Set useArweaveBundler and uploadApiBaseUrl.")
923
+ });
924
+ return;
925
+ }
926
+ let a = `${r.replace(/\/$/, "")}/api/upload/arweave/batch`;
927
+ if (!n || n.length === 0) {
928
+ e({
929
+ type: "uploadComplete",
930
+ result: "done"
931
+ });
932
+ return;
933
+ }
934
+ (async () => {
935
+ let e = n, t = e.length, r = Array(t).fill(null), i = async (e, t) => {
936
+ let n = e;
937
+ if (n.raw != null && (n.raw instanceof Uint8Array || Buffer.isBuffer(n.raw))) return n.raw.byteLength;
938
+ if (typeof n.getRaw == "function") {
939
+ let e = n.getRaw(), i = e instanceof Promise ? await e : e, a = Buffer.isBuffer(i) ? i : Buffer.from(i);
940
+ return r[t] = a, a.length;
941
+ }
942
+ if (n.filename != null) {
943
+ let e = await fn();
944
+ if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
945
+ return (await e.stat(n.filename)).size;
946
+ }
947
+ throw Error("Cannot get raw bytes from DataItem");
948
+ }, o = 4, s = [];
949
+ for (let n = 0; n < t; n++) {
950
+ let t = await i(e[n], n);
951
+ s.push(t), o += 4 + t;
952
+ }
953
+ let c = Buffer.alloc(o), l = 0;
954
+ c.writeUInt32BE(t, l), l += 4;
955
+ for (let n = 0; n < t; n++) {
956
+ let t = s[n], i = r[n];
957
+ if (i) {
958
+ c.writeUInt32BE(t, l), l += 4, i.copy(c, l), l += t;
959
+ continue;
960
+ }
961
+ let a = e[n];
962
+ if (a.raw != null && (a.raw instanceof Uint8Array || Buffer.isBuffer(a.raw))) {
963
+ c.writeUInt32BE(t, l), l += 4, c.set(a.raw, l), l += t;
964
+ continue;
965
+ }
966
+ if (a.filename != null) {
967
+ let e = await fn();
968
+ if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
969
+ let t = await e.readFile(a.filename);
970
+ c.writeUInt32BE(t.length, l), l += 4, t.copy(c, l), l += t.length;
971
+ continue;
972
+ }
973
+ throw Error("Cannot get raw bytes from DataItem");
974
+ }
975
+ let u = new AbortController(), d = setTimeout(() => u.abort(), ln), f;
976
+ try {
977
+ f = await fetch(a, {
978
+ method: "POST",
979
+ headers: { "Content-Type": "application/octet-stream" },
980
+ body: c,
981
+ signal: u.signal
982
+ });
983
+ } catch (e) {
984
+ throw clearTimeout(d), e instanceof Error && e.name === "AbortError" ? Error(`Arweave batch upload timed out after ${ln / 1e3}s (upload API did not respond). Check uploadApiBaseUrl and network.`) : e;
985
+ }
986
+ if (clearTimeout(d), !f.ok) throw Error(`Batch upload failed: ${f.status}`);
987
+ let p = await f.json().catch(() => ({})), m = typeof p.failed == "number" ? p.failed : 0;
988
+ if (m > 0) {
989
+ let e = p.total ?? "?", t = p.succeeded ?? 0;
990
+ throw Error(`Arweave batch upload failed: ${m} of ${e} item(s) failed (${t} succeeded)`);
991
+ }
992
+ })().then(() => e({
993
+ type: "uploadComplete",
994
+ result: "done"
995
+ })).catch((t) => e({
996
+ type: "uploadError",
997
+ error: t
998
+ }));
999
+ }), mn = "The executor module could not be installed on your publishing account on Optimism Sepolia. Reconnect and try again, or contact support if this persists.";
1000
+ async function hn(e, t, n) {
1001
+ let { modularAccountModuleContract: r } = n;
1002
+ if (!r) return;
1003
+ let i = ze({
1004
+ client: le(),
1005
+ chain: Ve,
1006
+ address: e
1007
+ });
1008
+ if (await se(e)) try {
1009
+ let e = await $e({ contract: i }), n = r.toLowerCase();
1010
+ if (e.some((e) => e.implementation?.toLowerCase() === n)) return;
1011
+ await x((await Be({
1012
+ transaction: et({
1013
+ contract: i,
1014
+ moduleContract: r,
1015
+ data: Re([{ type: "address" }], [g])
1016
+ }),
1017
+ account: t
1018
+ })).transactionHash);
1019
+ } catch (t) {
1020
+ if (s(t)) return;
1021
+ throw new u(mn, "EXECUTOR_MODULE_NOT_INSTALLED", e, t);
1022
+ }
1023
+ }
1024
+ //#endregion
1025
+ //#region src/helpers/ensureManagedAccountReady.ts
1026
+ var gn = "Could not connect the managed publishing account on Optimism Sepolia. Reconnect with the same sign-in method and try again.", _n = "Your publishing smart account is not deployed on Optimism Sepolia yet. Complete wallet setup, enable autoDeployManagedAccount in config if appropriate, then try again.", vn = "The managed account could not be confirmed on Optimism Sepolia after deployment. Wait a moment and retry, or check your network connection.", yn = "Automatic deployment of the managed publishing account failed on Optimism Sepolia. Retry or deploy the account through your wallet provider.";
1027
+ async function bn() {
1028
+ let { useModularExecutor: e } = o();
1029
+ if (!e) return { kind: "skip" };
1030
+ let t;
1031
+ try {
1032
+ t = await _(Ve);
1033
+ } catch (e) {
1034
+ return {
1035
+ kind: "unavailable",
1036
+ cause: e
1037
+ };
1038
+ }
1039
+ return await re(t) ? {
1040
+ kind: "ready",
1041
+ managedAddress: t
1042
+ } : {
1043
+ kind: "not_deployed",
1044
+ managedAddress: t
1045
+ };
1046
+ }
1047
+ async function xn() {
1048
+ let e = pe();
1049
+ await e.autoConnect({
1050
+ client: le(),
1051
+ chain: Ve
1052
+ });
1053
+ let t = e.getAccount();
1054
+ if (!t) throw new u(gn, "MANAGED_ACCOUNT_UNAVAILABLE");
1055
+ return t;
1056
+ }
1057
+ var Sn = 9e4;
1058
+ async function Cn(e) {
1059
+ let t;
1060
+ try {
1061
+ await Promise.race([h(e), new Promise((e, n) => {
1062
+ t = setTimeout(() => n(/* @__PURE__ */ Error(`Managed account deploy timed out after ${Sn / 1e3}s`)), Sn);
1063
+ })]);
1064
+ } finally {
1065
+ t != null && clearTimeout(t);
1066
+ }
1067
+ }
1068
+ async function wn(e) {
1069
+ let t = o(), n = await xn(), { fromThirdwebAccount: r } = await import("./ensureManagedAccountEasConfigured-DDFBEb-B.js").then((e) => e.L), i = {
1070
+ managedAddress: e,
1071
+ managedSigningAccount: r(n)
1072
+ };
1073
+ try {
1074
+ if (t.deployManagedAccount) await t.deployManagedAccount(i);
1075
+ else {
1076
+ let e = await oe();
1077
+ if (e) {
1078
+ let t = v();
1079
+ await t.autoConnect({
1080
+ client: le(),
1081
+ chain: Ve
1082
+ }), await ie({
1083
+ adminAddress: t.getAdminAccount?.()?.address ?? e.address,
1084
+ signingAccount: e
1085
+ });
1086
+ } else await Cn(n);
1087
+ }
1088
+ } catch (t) {
1089
+ if (await ne(e, /UserOp|user operation/i.test(ae(t)) ? 15 : 5)) return;
1090
+ throw new u(yn, "MANAGED_ACCOUNT_NOT_DEPLOYED", e, t);
1091
+ }
1092
+ if (!await ne(e)) throw new u(vn, "MANAGED_ACCOUNT_NOT_DEPLOYED", e);
1093
+ }
1094
+ async function Tn() {
1095
+ let e = o();
1096
+ if (!e.useModularExecutor) throw Error("runModularExecutorPublishPrep: useModularExecutor is false");
1097
+ let t = await bn();
1098
+ if (t.kind === "unavailable") return {
1099
+ ok: !1,
1100
+ error: new u(gn, "MANAGED_ACCOUNT_UNAVAILABLE", void 0, t.cause)
1101
+ };
1102
+ if (t.kind === "not_deployed") if (e.autoDeployManagedAccount) {
1103
+ try {
1104
+ await wn(t.managedAddress);
1105
+ } catch (e) {
1106
+ return {
1107
+ ok: !1,
1108
+ error: n(e) ? e : new u(yn, "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress, e)
1109
+ };
1110
+ }
1111
+ if (t = await bn(), t.kind !== "ready") return {
1112
+ ok: !1,
1113
+ error: new u(vn, "MANAGED_ACCOUNT_NOT_DEPLOYED", t.kind === "not_deployed" ? t.managedAddress : void 0)
1114
+ };
1115
+ } else return {
1116
+ ok: !1,
1117
+ error: new u(_n, "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress)
1118
+ };
1119
+ if (t.kind === "ready") {
1120
+ if (e.modularAccountModuleContract) try {
1121
+ let n = await xn();
1122
+ await hn(t.managedAddress, n, e);
1123
+ } catch (e) {
1124
+ return n(e) ? {
1125
+ ok: !1,
1126
+ error: e
1127
+ } : {
1128
+ ok: !1,
1129
+ error: new u("Executor module setup failed on Optimism Sepolia.", "EXECUTOR_MODULE_NOT_INSTALLED", t.managedAddress, e)
1130
+ };
1131
+ }
1132
+ return {
1133
+ ok: !0,
1134
+ managedAddress: t.managedAddress
1135
+ };
1136
+ }
1137
+ throw Error("runModularExecutorPublishPrep: unexpected readiness state");
1138
+ }
1139
+ //#endregion
1140
+ //#region src/helpers/resolvePublishWallet.ts
1141
+ function En(e) {
1142
+ if (f(e.wallet)) return e.wallet;
1143
+ if (f(e.account)) return e.account;
1144
+ let t = i();
1145
+ if (t) return t;
1146
+ throw Error("@seedprotocol/publish: no PublishWallet available. Pass fromEthersWallet / fromEip1193Provider / fromThirdwebAccount, or call setPublishWallet / useSeedWallet.");
1147
+ }
1148
+ //#endregion
1149
+ //#region src/services/publish/actors/persistSeedUid.ts
1150
+ var Dn = M("seedProtocol:services:publish:actors:persistSeedUid"), On = "0x" + "0".repeat(64), kn = 15e3;
1151
+ function An(e, t) {
1152
+ let n = e.seedLocalId, r = n ? t.find((e) => e?.localId === n) : void 0, i = r?.seedUid && r.seedUid !== On ? r.seedUid : t[0]?.seedUid;
1153
+ i && i !== On && (e.seedUid = i);
1154
+ }
1155
+ async function jn(e, t, n) {
1156
+ let r = e.persistSeedUid;
1157
+ if (typeof r != "function") return;
1158
+ let i = new Promise((e, t) => setTimeout(() => t(/* @__PURE__ */ Error("persistSeedUid timed out")), kn));
1159
+ try {
1160
+ await Promise.race([r.call(e, t, n), i]);
1161
+ } catch (e) {
1162
+ Dn("persistSeedUid failed (attestations already on-chain):", e);
1163
+ }
1164
+ }
1165
+ //#endregion
1166
+ //#region src/services/publish/helpers/verifyArweaveTransactionsExist.ts
1167
+ async function Mn(e) {
1168
+ if (e.length === 0) return;
1169
+ let { arweaveUploadVerificationBaseUrl: t } = o(), n = await Promise.all(e.map((e) => De(t, e)));
1170
+ for (let t = 0; t < e.length; t++) {
1171
+ let r = e[t], i = n[t];
1172
+ if (i) {
1173
+ if (i.status === 404) throw Error(`Arweave transaction ${r} not found. Upload may have failed. Delete this publish record and try again.`);
1174
+ if (i.status !== 200) {
1175
+ let e = i.status === 504 ? "request timed out (upload service did not respond in time)" : `status: ${i.status}`;
1176
+ throw Error(`Arweave transaction ${r} is not yet available from the upload service (${e}). Wait and retry.`);
1177
+ }
1178
+ }
1179
+ }
1180
+ }
1181
+ //#endregion
1182
+ //#region src/helpers/abi/executor.ts
1183
+ var Nn = [{
1184
+ type: "event",
1185
+ name: "CreatedAttestation",
1186
+ inputs: [{
1187
+ name: "result",
1188
+ type: "tuple",
1189
+ indexed: !1,
1190
+ components: [{
1191
+ name: "schemaUid",
1192
+ type: "bytes32"
1193
+ }, {
1194
+ name: "attestationUid",
1195
+ type: "bytes32"
1196
+ }]
1197
+ }]
1198
+ }, {
1199
+ type: "event",
1200
+ name: "SeedPublished",
1201
+ inputs: [{
1202
+ name: "seedUid",
1203
+ type: "bytes32",
1204
+ indexed: !1
1205
+ }, {
1206
+ name: "versionUid",
1207
+ type: "bytes32",
1208
+ indexed: !1
1209
+ }]
1210
+ }];
1211
+ //#endregion
1212
+ //#region src/services/publish/actors/seedUidHelpers.ts
1213
+ function U(e) {
1214
+ return e == null || e === "" ? z : ("0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(64, "0").slice(-64)).toLowerCase();
1215
+ }
1216
+ function Pn(e, t, n) {
1217
+ if (!t || !e.logs?.length) return;
1218
+ let r = U(t);
1219
+ if (r === z) return;
1220
+ let i = n ? Nn : ge;
1221
+ try {
1222
+ let t = D({
1223
+ abi: i,
1224
+ eventName: "CreatedAttestation",
1225
+ logs: e.logs,
1226
+ strict: !1
1227
+ });
1228
+ for (let e of t) {
1229
+ let t = e.args?.result;
1230
+ if (t?.attestationUid && U(t.schemaUid) === r) {
1231
+ let e = t.attestationUid;
1232
+ return e && U(e) !== z ? e : void 0;
1233
+ }
1234
+ }
1235
+ } catch {}
1236
+ }
1237
+ function Fn(e, t, n, r) {
1238
+ let i = t.toLowerCase(), a = e.logs?.filter((e) => e.address && e.address.toLowerCase() === i);
1239
+ if (!a?.length) return {};
1240
+ try {
1241
+ if (r) {
1242
+ let e = D({
1243
+ abi: Nn,
1244
+ eventName: "SeedPublished",
1245
+ logs: a,
1246
+ strict: !1
1247
+ })[0];
1248
+ if (!e) return {};
1249
+ let t = e.args;
1250
+ return {
1251
+ seedUid: t?.seedUid && U(t.seedUid) !== z ? t.seedUid : void 0,
1252
+ versionUid: t?.versionUid && U(t.versionUid) !== z ? t.versionUid : void 0
1253
+ };
1254
+ }
1255
+ let e = D({
1256
+ abi: ge,
1257
+ eventName: "SeedPublished",
1258
+ logs: a,
1259
+ strict: !1
1260
+ })[0];
1261
+ if (!e) return {};
1262
+ let t = e.args?.returnedDataFromEAS;
1263
+ if (!t || t === "0x") return {};
1264
+ let i = Le([{ type: "bytes32[]" }], t)[0];
1265
+ if (!i?.length) return {};
1266
+ let o = n, s = i[o], c = i[o + 1];
1267
+ return {
1268
+ seedUid: s && s !== z ? s : i.length === 1 && i[0] && i[0] !== z ? i[0] : void 0,
1269
+ versionUid: c && c !== z ? c : void 0
1270
+ };
1271
+ } catch {
1272
+ return {};
1273
+ }
1274
+ }
1275
+ function In(e, t, n, r) {
1276
+ return Fn(e, t, n, r).seedUid;
1277
+ }
1278
+ function Ln(e, t, n) {
1279
+ if (!t || !e.logs?.length) return;
1280
+ let r = U(t);
1281
+ if (r === z) return;
1282
+ let i = n ? Nn : ge;
1283
+ try {
1284
+ let t = D({
1285
+ abi: i,
1286
+ eventName: "CreatedAttestation",
1287
+ logs: e.logs,
1288
+ strict: !1
1289
+ });
1290
+ for (let e of t) {
1291
+ let t = e.args?.result;
1292
+ if (t?.attestationUid && U(t.schemaUid) === r) {
1293
+ let e = t.attestationUid;
1294
+ return e && U(e) !== z ? e : void 0;
1295
+ }
1296
+ }
1297
+ } catch {}
1298
+ }
1299
+ function Rn(e, t) {
1300
+ if (!e.logs?.length) return [];
1301
+ let n = t ? Nn : ge;
1302
+ try {
1303
+ let t = D({
1304
+ abi: n,
1305
+ eventName: "CreatedAttestation",
1306
+ logs: e.logs,
1307
+ strict: !1
1308
+ }), r = [];
1309
+ for (let e of t) {
1310
+ let t = e.args?.result;
1311
+ if (!t?.attestationUid) continue;
1312
+ let n = t.attestationUid;
1313
+ if (!n || U(n) === z) continue;
1314
+ let i = t.schemaUid;
1315
+ i && r.push({
1316
+ schemaUid: i,
1317
+ attestationUid: n
1318
+ });
1319
+ }
1320
+ return r;
1321
+ } catch {
1322
+ return [];
1323
+ }
1324
+ }
1325
+ //#endregion
1326
+ //#region src/services/publish/helpers/receiptAttestationMs.ts
1327
+ async function W(e) {
1328
+ let t = e?.blockNumber;
1329
+ return t == null ? Date.now() : await b(t) ?? Date.now();
1330
+ }
1331
+ //#endregion
1332
+ //#region src/services/publish/actors/publishRequestNormalize.ts
1333
+ var zn = 64, G = (e) => {
1334
+ if (e == null) return "0x" + "0".repeat(zn);
1335
+ if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(zn, "0").slice(-64);
1336
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1337
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1338
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(zn, "0").slice(-64);
1339
+ }
1340
+ return "0x" + "0".repeat(zn);
1341
+ }, Bn = (e) => {
1342
+ if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
1343
+ if (typeof e == "string") {
1344
+ let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
1345
+ return "0x" + (t.length % 2 == 1 ? "0" + t : t);
1346
+ }
1347
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1348
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1349
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
1350
+ }
1351
+ return "0x";
1352
+ };
1353
+ function Vn(e) {
1354
+ let t = new Set(e.map((e) => e?.localId).filter((e) => !!e));
1355
+ return e.some((e) => (e?.listOfAttestations ?? []).some((e) => {
1356
+ let n = e;
1357
+ return n._unresolvedValue && t.has(n._unresolvedValue) ? !0 : Array.isArray(n._rawListIdsForResolve) ? n._rawListIdsForResolve.some((e) => e && t.has(String(e).trim())) : !1;
1358
+ }));
1359
+ }
1360
+ function Hn(e, t) {
1361
+ return (e ?? []).filter((e) => e.publishLocalId && t.has(e.publishLocalId));
1362
+ }
1363
+ var Un = {
1364
+ recipient: Ge,
1365
+ expirationTime: BigInt(0),
1366
+ revocable: !0,
1367
+ refUID: z,
1368
+ data: z,
1369
+ value: BigInt(0)
1370
+ };
1371
+ function Wn(e) {
1372
+ let t = (e?.listOfAttestations ?? []).map((e) => {
1373
+ let t = Array.isArray(e?.data) ? e.data : [];
1374
+ return {
1375
+ schema: G(e?.schema),
1376
+ data: t.map((e) => ({
1377
+ ...e,
1378
+ refUID: G(e?.refUID),
1379
+ data: Bn(e?.data),
1380
+ expirationTime: e?.expirationTime == null ? BigInt(0) : BigInt(e.expirationTime),
1381
+ value: e?.value == null ? BigInt(0) : BigInt(e.value)
1382
+ })),
1383
+ ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
1384
+ ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {}
1385
+ };
1386
+ }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
1387
+ ...e,
1388
+ propertySchemaUid: G(e?.propertySchemaUid)
1389
+ }));
1390
+ return {
1391
+ ...e,
1392
+ seedUid: G(e?.seedUid),
1393
+ seedSchemaUid: G(e?.seedSchemaUid),
1394
+ versionUid: G(e?.versionUid),
1395
+ versionSchemaUid: G(e?.versionSchemaUid),
1396
+ listOfAttestations: t,
1397
+ propertiesToUpdate: n
1398
+ };
1399
+ }
1400
+ function Gn(e, t) {
1401
+ for (let n of e) for (let e of n?.propertiesToUpdate ?? []) {
1402
+ let n = e?.publishLocalId, r = G(e?.propertySchemaUid);
1403
+ if (!n || !r) continue;
1404
+ let i = t.get(n);
1405
+ if (!i?.listOfAttestations) continue;
1406
+ let a = i.listOfAttestations.find((e) => G(e?.schema)?.toLowerCase() === r?.toLowerCase());
1407
+ a && (!Array.isArray(a.data) || a.data.length === 0) && (a.data = [{
1408
+ ...Un,
1409
+ refUID: z
1410
+ }]);
1411
+ }
1412
+ }
1413
+ //#endregion
1414
+ //#region src/services/arweaveL1Finalize/enqueue.ts
1415
+ var Kn = "pending_l1";
1416
+ async function qn(e) {
1417
+ let { useArweaveBundler: t } = o();
1418
+ if (!t) return;
1419
+ let n = e.arweaveTransactions ?? [], r = e.publishUploads ?? [];
1420
+ if (n.length === 0 || n.length !== r.length) return;
1421
+ let i = S.getAppDb();
1422
+ if (!i) return;
1423
+ let a = Date.now();
1424
+ for (let e = 0; e < n.length; e++) {
1425
+ let t = n[e], o = r[e];
1426
+ if (!o) continue;
1427
+ let s = t.transaction?.id;
1428
+ if (!(!s || typeof s != "string")) try {
1429
+ await i.insert(xe).values({
1430
+ seedLocalId: o.seedLocalId,
1431
+ dataItemId: s,
1432
+ versionLocalId: o.versionLocalId ?? null,
1433
+ itemPropertyName: o.itemPropertyName ?? null,
1434
+ phase: Kn,
1435
+ createdAt: a,
1436
+ updatedAt: a
1437
+ }).onConflictDoNothing();
1438
+ } catch {}
1439
+ }
1440
+ }
1441
+ //#endregion
1442
+ //#region src/services/publish/actors/createAttestations.ts
1443
+ var Jn = M("seedProtocol:services:publish:actors");
1444
+ function Yn(e) {
1445
+ let { useModularExecutor: t, publisherAddress: n, modularAccountModuleContract: r, managedAddress: i } = e;
1446
+ if (t) {
1447
+ if (!i) throw Error("resolvePublishRouting: managedAddress is required when useModularExecutor is true");
1448
+ return {
1449
+ txTargetAddress: i,
1450
+ contractAddressForEvents: r || i
1451
+ };
1452
+ }
1453
+ return {
1454
+ txTargetAddress: n,
1455
+ contractAddressForEvents: n
1456
+ };
1457
+ }
1458
+ async function Xn(e) {
1459
+ let { receipt: t, seedLocalId: n, versionSchemaUid: r, contractAddressForEvents: i, listOfAttestationsCount: a, useModularExecutor: o, publisherAddress: s } = e;
1460
+ if (!n) return;
1461
+ let c = Ln(t, r, o) ?? Fn(t, i, a, o).versionUid, l = c ? G(c) : void 0;
1462
+ !l || l === z || await Fe({
1463
+ seedLocalId: n,
1464
+ versionUid: l,
1465
+ publisher: s,
1466
+ attestationCreatedAt: await W(t)
1467
+ });
1468
+ }
1469
+ function Zn(e, t) {
1470
+ return !e || !t ? !1 : G(e).toLowerCase() === G(t).toLowerCase();
1471
+ }
1472
+ function Qn(e, t, n) {
1473
+ return !n || t >= e.length ? t : Zn(e[t]?.schemaUid, n) ? t + 1 : t;
1474
+ }
1475
+ async function $n(e) {
1476
+ let { receipt: t, normalizedRequests: n, useModularExecutor: r } = e, i = Rn(t, r);
1477
+ if (!i.length) return;
1478
+ let a = await W(t), o = 0;
1479
+ for (let e of n) {
1480
+ let n = e.listOfAttestations ?? [];
1481
+ if (!n.length) continue;
1482
+ (!e.seedUid || G(e.seedUid) === z) && (o = Qn(i, o, e.seedSchemaUid)), o = Qn(i, o, e.versionSchemaUid);
1483
+ let s = n.length, c = i.slice(o, o + s);
1484
+ if (o += s, !c.length) continue;
1485
+ let l = Math.min(c.length, s), u = e.versionUid && G(e.versionUid) !== z ? G(e.versionUid) : void 0;
1486
+ u ||= Ln(t, e.versionSchemaUid, r), await be({
1487
+ seedLocalId: e.localId,
1488
+ attestationCreatedAtMs: a ?? null,
1489
+ versionUid: u && G(u) !== z ? G(u) : null,
1490
+ pairs: c.slice(0, l).map((e, t) => ({
1491
+ schemaUid: e.schemaUid,
1492
+ attestationUid: e.attestationUid,
1493
+ propertyName: typeof n[t]?._propertyName == "string" && n[t]._propertyName !== "" ? n[t]._propertyName : void 0
1494
+ }))
1495
+ });
1496
+ }
1497
+ }
1498
+ var er = j(async ({ input: { context: e } }) => {
1499
+ let { address: t, account: n, wallet: r } = e, i = e.arweaveTransactions ?? [], a = e.publishUploads ?? [], { item: s } = e, { modularAccountModuleContract: c, useModularExecutor: l } = o();
1500
+ if (!t || typeof t != "string" || !t.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
1501
+ if (!r && !n) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
1502
+ if (!l && !await se(t)) throw Error("EOA publishing must use the direct EAS path (multiPublish requires a deployed publisher contract). If you see this, attestation routing is misconfigured.");
1503
+ if (!s?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
1504
+ if (typeof s.getPublishUploads != "function" && (s = await B(s.seedLocalId)), i.length !== a.length) throw Error("Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.");
1505
+ let u = Yn({
1506
+ useModularExecutor: !1,
1507
+ publisherAddress: t
1508
+ }), d = En(e);
1509
+ await L(s, d);
1510
+ let f = i.map((e, t) => {
1511
+ let n = e.transaction?.id;
1512
+ if (!n || typeof n != "string") throw Error("Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.");
1513
+ let r = a[t];
1514
+ if (!r) throw Error("Publish upload index mismatch");
1515
+ return {
1516
+ ...r,
1517
+ txId: n
1518
+ };
1519
+ });
1520
+ await Mn(f.map((e) => e.txId));
1521
+ let p = await s.getPublishPayload(f, { publishMode: e.publishMode ?? "patch" }), m = Array.isArray(p) ? p : [p];
1522
+ if (l) {
1523
+ let e = await Tn();
1524
+ if (!e.ok) throw e.error;
1525
+ u = Yn({
1526
+ useModularExecutor: l,
1527
+ publisherAddress: t,
1528
+ modularAccountModuleContract: c,
1529
+ managedAddress: e.managedAddress
1530
+ });
1531
+ let { ensureModularPublishBootstrap: n } = await import("./ensureModularPublishBootstrap-BSXyZgld.js").then((e) => e.n), { fromThirdwebAccount: r } = await import("./ensureManagedAccountEasConfigured-DDFBEb-B.js").then((e) => e.L);
1532
+ d = r(await n(e.managedAddress));
1533
+ } else await de(t, d);
1534
+ let h = m.length > 1 && Vn(m), g, _ = null;
1535
+ if (h) {
1536
+ let e = structuredClone(m), n = {};
1537
+ for (let r = 0; r < e.length; r++) {
1538
+ e = await Me(e, n);
1539
+ let i = e[r], a = new Set([i.localId]), o = Wn({
1540
+ ...i,
1541
+ propertiesToUpdate: Hn(i.propertiesToUpdate, a)
1542
+ }), s = new Map([[o.localId, o]]);
1543
+ Gn([o], s);
1544
+ let c = ee(u.txTargetAddress, [o], 5000000n), f = await x((await d.txSender.sendTransaction(c)).transactionHash);
1545
+ if (!f) throw Error("Failed to send transaction");
1546
+ _ = f;
1547
+ let p = o?.listOfAttestations?.length ?? 0;
1548
+ await Xn({
1549
+ receipt: f,
1550
+ seedLocalId: i.localId,
1551
+ versionSchemaUid: o.versionSchemaUid,
1552
+ contractAddressForEvents: u.contractAddressForEvents,
1553
+ listOfAttestationsCount: p,
1554
+ useModularExecutor: l,
1555
+ publisherAddress: t
1556
+ });
1557
+ let m = !o.seedUid || G(o.seedUid) === z, h = o?.seedSchemaUid;
1558
+ if (m) {
1559
+ let t = Pn(f, h, l) ?? In(f, u.contractAddressForEvents, p, l);
1560
+ t && (n[i.localId] = t, e[r] = {
1561
+ ...e[r],
1562
+ seedUid: t
1563
+ });
1564
+ }
1565
+ await $n({
1566
+ receipt: f,
1567
+ normalizedRequests: [o],
1568
+ useModularExecutor: l
1569
+ });
1570
+ }
1571
+ for (let t of e) {
1572
+ let e = t?.localId, r = t?.seedUid;
1573
+ e && r && G(r) !== z && (n[e] = G(r));
1574
+ }
1575
+ g = (await Me(structuredClone(m), n)).map((e) => Wn({
1576
+ ...e,
1577
+ seedUid: n[e.localId] ?? e.seedUid
1578
+ }));
1579
+ } else {
1580
+ let e = m.map((e) => Wn(e));
1581
+ Gn(e, new Map(e.map((e) => [e?.localId, e])));
1582
+ let n = Array.isArray(p) ? e : [e[0]], r = ee(u.txTargetAddress, n, 5000000n), i = await x((await d.txSender.sendTransaction(r)).transactionHash);
1583
+ if (!i) throw Error("Failed to send transaction");
1584
+ _ = i;
1585
+ let a = e.find((e) => e?.localId === s.seedLocalId) ?? e[0];
1586
+ await Xn({
1587
+ receipt: i,
1588
+ seedLocalId: a?.localId,
1589
+ versionSchemaUid: a?.versionSchemaUid,
1590
+ contractAddressForEvents: u.contractAddressForEvents,
1591
+ listOfAttestationsCount: a?.listOfAttestations?.length ?? 0,
1592
+ useModularExecutor: l,
1593
+ publisherAddress: t
1594
+ }), await $n({
1595
+ receipt: i,
1596
+ normalizedRequests: n,
1597
+ useModularExecutor: l
1598
+ });
1599
+ let o = e[0], c = o?.seedUid, f = c === z || !c, h = o?.listOfAttestations?.length ?? 0, v = o?.seedSchemaUid, y = f ? Pn(i, v, l) ?? In(i, u.contractAddressForEvents, h, l) : void 0;
1600
+ g = y && e.length > 0 ? [{
1601
+ ...e[0],
1602
+ seedUid: y
1603
+ }, ...e.slice(1)] : e;
1604
+ }
1605
+ An(s, g);
1606
+ let v = s, y = g.find((e) => e?.localId === s.seedLocalId)?.seedUid;
1607
+ y && y !== z && await jn(v, t, _ ? await W(_) : void 0), Jn("requestData", p), qn(e);
1608
+ try {
1609
+ let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk");
1610
+ await e(s.seedLocalId);
1611
+ } catch {}
1612
+ return { easPayload: p };
1613
+ }), tr = M("seedProtocol:services:publish:verifyAttestations"), nr = "0x" + "0".repeat(64), rr = 64, ir = (e) => e == null ? "0x" + "0".repeat(rr) : typeof e == "string" ? "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(rr, "0").slice(-64) : "0x" + "0".repeat(rr), ar = 5e3, or = 6;
1614
+ async function sr({ normalizedRequests: e, item: n }) {
1615
+ let r = n.seedLocalId;
1616
+ for (let n of e) {
1617
+ if (n.listOfAttestations.length === 0 || n.versionUid === nr) continue;
1618
+ let e = n.listOfAttestations.map((e) => ir(e.schema).toLowerCase()), i = [], a;
1619
+ for (let e = 1; e <= or; e++) try {
1620
+ e > 1 && await new Promise((e) => setTimeout(e, ar)), i = await we({ versionUids: [n.versionUid] });
1621
+ break;
1622
+ } catch (t) {
1623
+ if (a = t, tr("verifyAttestations attempt %d failed:", e, t), e === or) throw tr("verifyAttestations: giving up after %d attempts", or), a;
1624
+ }
1625
+ let o = i.map((e) => e.schemaId ? ir(e.schemaId).toLowerCase() : "").filter(Boolean), s = new Set(o);
1626
+ if (e.filter((e) => !s.has(e)).length > 0) throw new t(`Publish verification failed: Seed and Version attestations were created, but property/metadata attestations are missing or incomplete. Expected ${e.length} property attestations for schema(s) ${e.join(", ")}; found ${o.length}. Use PublishManager.retryAttestations('${r}') to retry.`, r, e, o, "METADATA_PROPERTIES_MISSING");
1627
+ }
1628
+ }
1629
+ //#endregion
1630
+ //#region src/services/publish/actors/createAttestationsDirectToEas.ts
1631
+ var K = M("seedProtocol:services:publish:createAttestationsDirectToEas"), cr = 64, q = (e) => {
1632
+ if (e == null) return "0x" + "0".repeat(cr);
1633
+ if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(cr, "0").slice(-64);
1634
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1635
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1636
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(cr, "0").slice(-64);
1637
+ }
1638
+ return "0x" + "0".repeat(cr);
1639
+ }, lr = (e) => {
1640
+ if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
1641
+ if (typeof e == "string") {
1642
+ let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
1643
+ return "0x" + (t.length % 2 == 1 ? "0" + t : t);
1644
+ }
1645
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1646
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1647
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
1648
+ }
1649
+ return "0x";
1650
+ }, ur = async (e) => {
1651
+ let t;
1652
+ try {
1653
+ t = await w.find({ seedLocalId: e });
1654
+ } catch {}
1655
+ return t || new Promise((t) => {
1656
+ let n = setInterval(() => {
1657
+ try {
1658
+ w.find({ seedLocalId: e }).then((e) => {
1659
+ e && (clearInterval(n), t(e));
1660
+ });
1661
+ } catch {}
1662
+ }, 200);
1663
+ });
1664
+ }, dr = j(async ({ input: { context: n, event: r } }) => {
1665
+ let { address: i, account: a, wallet: s } = n, l = n.arweaveTransactions ?? [], u = n.publishUploads ?? [], { item: d } = n;
1666
+ if (!i || typeof i != "string" || !i.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
1667
+ if (!s && !a) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
1668
+ if (!d?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
1669
+ if (typeof d.getPublishUploads != "function" && (d = await ur(d.seedLocalId)), l.length !== u.length) throw Error("Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.");
1670
+ let f = En(n), h = f.txSender;
1671
+ await L(d, f);
1672
+ let ee = l.map((e, t) => {
1673
+ let n = e.transaction?.id;
1674
+ if (!n || typeof n != "string") throw Error("Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.");
1675
+ let r = u[t];
1676
+ if (!r) throw Error("Publish upload index mismatch");
1677
+ return {
1678
+ ...r,
1679
+ txId: n
1680
+ };
1681
+ });
1682
+ await Mn(ee.map((e) => e.txId));
1683
+ let g = await d.getPublishPayload(ee, { publishMode: n.publishMode ?? "patch" }), _ = (Array.isArray(g) ? g : [g]).map((e) => {
1684
+ let t = (e?.listOfAttestations ?? []).map((e) => {
1685
+ let t = Array.isArray(e?.data) ? e.data : [];
1686
+ return {
1687
+ schema: q(e?.schema),
1688
+ data: t.map((e) => ({
1689
+ ...e,
1690
+ refUID: q(e?.refUID),
1691
+ data: lr(e?.data)
1692
+ })),
1693
+ ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
1694
+ ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {}
1695
+ };
1696
+ }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
1697
+ ...e,
1698
+ propertySchemaUid: q(e?.propertySchemaUid)
1699
+ }));
1700
+ return {
1701
+ ...e,
1702
+ seedUid: q(e?.seedUid),
1703
+ seedSchemaUid: q(e?.seedSchemaUid),
1704
+ versionUid: q(e?.versionUid),
1705
+ versionSchemaUid: q(e?.versionSchemaUid),
1706
+ listOfAttestations: t,
1707
+ propertiesToUpdate: n
1708
+ };
1709
+ }), v = new Map(_.map((e) => [e.localId, e])), y = {
1710
+ recipient: Ge,
1711
+ expirationTime: BigInt(0),
1712
+ revocable: !0,
1713
+ refUID: p,
1714
+ data: p,
1715
+ value: BigInt(0)
1716
+ };
1717
+ for (let e of _) for (let t of e.propertiesToUpdate ?? []) {
1718
+ let e = t.publishLocalId, n = q(t.propertySchemaUid);
1719
+ if (!e || !n) continue;
1720
+ let r = v.get(e);
1721
+ if (!r?.listOfAttestations) continue;
1722
+ let i = r.listOfAttestations.find((e) => q(e?.schema)?.toLowerCase() === n?.toLowerCase());
1723
+ i && (!Array.isArray(i.data) || i.data.length === 0) && (i.data = [{
1724
+ ...y,
1725
+ refUID: p
1726
+ }]);
1727
+ }
1728
+ let b = Date.now();
1729
+ for (let t = 0; t < _.length; t++) {
1730
+ let n = _[t], r = n.seedUid, a = n.versionUid;
1731
+ if (r === p) {
1732
+ let e = te({
1733
+ schema: n.seedSchemaUid,
1734
+ data: {
1735
+ refUID: p,
1736
+ data: m(n.seedSchemaUid),
1737
+ revocable: n.seedIsRevocable
1738
+ }
1739
+ }), t = await x((await h.sendTransaction(e)).transactionHash);
1740
+ if (!t) throw Error("Failed to create Seed attestation");
1741
+ b = await W(t);
1742
+ let { easContractAddress: i } = o(), a = c(t, i);
1743
+ if (!a || a === p) throw Error("Failed to get Seed UID from attestation receipt");
1744
+ r = a, n.seedUid = a, K("created Seed attestation", r);
1745
+ }
1746
+ if (r !== p && a === p) {
1747
+ let e = te({
1748
+ schema: n.versionSchemaUid,
1749
+ data: {
1750
+ refUID: r,
1751
+ data: m(n.versionSchemaUid),
1752
+ revocable: !0
1753
+ }
1754
+ }), t = await x((await h.sendTransaction(e)).transactionHash);
1755
+ if (!t) throw Error("Failed to create Version attestation");
1756
+ b = await W(t);
1757
+ let { easContractAddress: s } = o(), l = c(t, s);
1758
+ if (!l || l === p) throw Error("Failed to get Version UID from attestation receipt");
1759
+ a = l, n.versionUid = l, await Fe({
1760
+ seedLocalId: n.localId,
1761
+ versionUid: l,
1762
+ publisher: i,
1763
+ attestationCreatedAt: b
1764
+ }), K("created Version attestation", a);
1765
+ }
1766
+ for (let e of n.listOfAttestations) for (let t of e.data) t.refUID = a;
1767
+ for (let e of n.propertiesToUpdate ?? []) {
1768
+ let t = v.get(e.publishLocalId);
1769
+ if (!t?.listOfAttestations) continue;
1770
+ let n = q(e.propertySchemaUid), i = t.listOfAttestations.find((e) => q(e?.schema)?.toLowerCase() === n?.toLowerCase());
1771
+ i?.data?.[0] && (i.data[0].data = m(r));
1772
+ }
1773
+ let s = n.listOfAttestations.map((e) => ({
1774
+ schema: e.schema,
1775
+ data: e.data.map((e) => ({
1776
+ recipient: e.recipient ?? Ge,
1777
+ expirationTime: e.expirationTime ?? 0n,
1778
+ revocable: e.revocable ?? !0,
1779
+ refUID: e.refUID ?? p,
1780
+ data: e.data ?? "0x",
1781
+ value: e.value ?? 0n
1782
+ }))
1783
+ }));
1784
+ if (s.length > 0) {
1785
+ let r = fe(s), i = await x((await h.sendTransaction(r)).transactionHash);
1786
+ if (!i) throw Error("Failed to create property attestations");
1787
+ b = await W(i), K("created property attestations for request", t);
1788
+ let { easContractAddress: c } = o(), l = e(i, c), u = n.listOfAttestations, d = l.length === u.length;
1789
+ await be({
1790
+ seedLocalId: n.localId,
1791
+ attestationCreatedAtMs: b ?? null,
1792
+ versionUid: a === p ? null : a,
1793
+ pairs: l.map((e, t) => ({
1794
+ schemaUid: e.schemaUid,
1795
+ attestationUid: e.uid,
1796
+ propertyName: d && typeof u[t]?._propertyName == "string" && u[t]._propertyName !== "" ? u[t]._propertyName : void 0
1797
+ }))
1798
+ });
1799
+ }
1800
+ }
1801
+ An(d, _);
1802
+ let ne = d;
1803
+ _[0]?.seedUid && _[0].seedUid !== p && await jn(ne, i, b);
1804
+ try {
1805
+ await sr({
1806
+ normalizedRequests: _,
1807
+ item: d
1808
+ });
1809
+ } catch (e) {
1810
+ throw e instanceof t || K("verifyAttestations failed (non-verification error):", e), e;
1811
+ }
1812
+ K("direct EAS publish complete"), qn(n);
1813
+ try {
1814
+ let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk");
1815
+ await e(d.seedLocalId);
1816
+ } catch {}
1817
+ return { easPayload: g };
1818
+ }), fr = async (e) => {
1819
+ let t;
1820
+ try {
1821
+ t = await w.find({ seedLocalId: e });
1822
+ } catch {}
1823
+ return t || new Promise((t) => {
1824
+ let n = setInterval(() => {
1825
+ w.find({ seedLocalId: e }).then((e) => {
1826
+ e && (clearInterval(n), t(e));
1827
+ }).catch(() => {});
1828
+ }, 200);
1829
+ });
1830
+ };
1831
+ async function pr(e) {
1832
+ return await Ae(typeof e.getPublishUploads == "function" ? e : await fr(e.seedLocalId));
1833
+ }
1834
+ //#endregion
1835
+ //#region src/services/publish/actors/checking.ts
1836
+ var J = /* @__PURE__ */ new Set();
1837
+ async function mr(e) {
1838
+ let t = o();
1839
+ return t.useDirectEas ? "directEas" : t.useModularExecutor || await se(e) ? "multiPublish" : "directEas";
1840
+ }
1841
+ var hr = A(({ sendBack: e, input: { context: t } }) => {
1842
+ let { item: n, account: r, wallet: i, publishMode: a, address: s } = t;
1843
+ return (async () => {
1844
+ if (!await ke(n)) {
1845
+ e({ type: "notOwner" });
1846
+ return;
1847
+ }
1848
+ if (J.has(n.seedLocalId)) {
1849
+ e({ type: "redundantPublishProcess" });
1850
+ return;
1851
+ }
1852
+ J.add(n.seedLocalId);
1853
+ try {
1854
+ let t = i ?? r;
1855
+ t && await L(n, t);
1856
+ let c = await Ie(n, [], { publishMode: a ?? "patch" });
1857
+ if (!c.isValid) {
1858
+ J.delete(n.seedLocalId), e({
1859
+ type: "validationFailed",
1860
+ errors: c.errors
1861
+ });
1862
+ return;
1863
+ }
1864
+ if (!s || typeof s != "string" || !s.trim()) {
1865
+ J.delete(n.seedLocalId), e({
1866
+ type: "validationFailed",
1867
+ errors: [{ message: "No publisher address for publish. Connect a wallet and try again." }]
1868
+ });
1869
+ return;
1870
+ }
1871
+ let l;
1872
+ try {
1873
+ l = await mr(s.trim());
1874
+ } catch (t) {
1875
+ J.delete(n.seedLocalId), e({
1876
+ type: "checkingFailed",
1877
+ error: Error("Could not verify whether the publisher is a deployed contract on Optimism Sepolia. Check your RPC connection and retry.", { cause: t })
1878
+ });
1879
+ return;
1880
+ }
1881
+ let u = await pr(n), d = o().useArweaveBundler, f = { attestationStrategy: l };
1882
+ e(u ? d ? {
1883
+ type: "validPublishProcessBundler",
1884
+ ...f
1885
+ } : {
1886
+ type: "validPublishProcess",
1887
+ ...f
1888
+ } : {
1889
+ type: "skipArweave",
1890
+ ...f
1891
+ });
1892
+ } catch (t) {
1893
+ J.delete(n.seedLocalId), console.error("[checking] failed", t), e({
1894
+ type: "checkingFailed",
1895
+ error: t instanceof Error ? t : Error(String(t))
1896
+ });
1897
+ }
1898
+ })().catch((t) => {
1899
+ J.delete(n.seedLocalId), console.error("[checking] unhandled rejection", t), e({
1900
+ type: "checkingFailed",
1901
+ error: t instanceof Error ? t : Error(String(t))
1902
+ });
1903
+ }), () => {
1904
+ J.delete(n.seedLocalId);
1905
+ };
1906
+ }), { SUCCESS: gr, FAILURE: Y } = d;
1907
+ function _r(e) {
1908
+ let t = e.attestationStrategy;
1909
+ return t === "directEas" ? !0 : t === "multiPublish" ? !1 : o().useDirectEas;
1910
+ }
1911
+ function X(e) {
1912
+ let t = e.attestationStrategy;
1913
+ return t === "multiPublish" ? !0 : t === "directEas" ? !1 : !o().useDirectEas;
1914
+ }
1915
+ function Z(e) {
1916
+ let t = e;
1917
+ return t.error ?? t.data;
1918
+ }
1919
+ var vr = Ye({
1920
+ types: {
1921
+ context: {},
1922
+ input: {}
1923
+ },
1924
+ actors: {
1925
+ createArweaveTransactions: lt,
1926
+ createArweaveTransactionsPhase2: ut,
1927
+ createArweaveDataItems: Yt,
1928
+ createArweaveDataItemsPhase2: Zt,
1929
+ sendReimbursementRequest: an,
1930
+ pollForConfirmation: on,
1931
+ uploadData: cn,
1932
+ uploadViaBundler: pn,
1933
+ createAttestations: er,
1934
+ createAttestationsDirectToEas: dr,
1935
+ checking: hr,
1936
+ preparingHtmlEmbedded: dt,
1937
+ rewritingHtmlEmbedded: pt
1938
+ },
1939
+ actions: {
1940
+ handleError: ({ event: e }) => {
1941
+ let t = Z(e);
1942
+ t == null ? console.error("Unknown error (full event):", e) : console.error(t);
1943
+ },
1944
+ assignErrorCreatingArweaveTransactions: k({
1945
+ error: ({ event: e }) => Z(e),
1946
+ errorStep: () => "creatingArweaveTransactions"
1947
+ }),
1948
+ assignErrorCreatingArweaveDataItems: k({
1949
+ error: ({ event: e }) => Z(e),
1950
+ errorStep: () => "creatingArweaveDataItems"
1951
+ }),
1952
+ assignErrorSendingReimbursementRequest: k({
1953
+ error: ({ event: e }) => Z(e),
1954
+ errorStep: () => "sendingReimbursementRequest"
1955
+ }),
1956
+ assignErrorPollingForConfirmation: k({
1957
+ error: ({ event: e }) => Z(e),
1958
+ errorStep: () => "pollingForConfirmation"
1959
+ }),
1960
+ assignErrorUploadingData: k({
1961
+ error: ({ event: e }) => Z(e),
1962
+ errorStep: () => "uploadingData"
1963
+ }),
1964
+ assignErrorPreparingHtmlEmbedded: k({
1965
+ error: ({ event: e }) => Z(e),
1966
+ errorStep: () => "preparingHtmlEmbedded"
1967
+ }),
1968
+ assignErrorRewritingHtmlEmbedded: k({
1969
+ error: ({ event: e }) => Z(e),
1970
+ errorStep: () => "rewritingHtmlEmbedded"
1971
+ }),
1972
+ assignErrorCreatingArweaveTransactionsPhase2: k({
1973
+ error: ({ event: e }) => Z(e),
1974
+ errorStep: () => "creatingArweaveTransactionsPhase2"
1975
+ }),
1976
+ assignErrorUploadingDataPhase2: k({
1977
+ error: ({ event: e }) => Z(e),
1978
+ errorStep: () => "uploadingDataPhase2"
1979
+ }),
1980
+ assignErrorUploadingViaBundler: k({
1981
+ error: ({ event: e }) => Z(e),
1982
+ errorStep: () => "uploadingViaBundler"
1983
+ }),
1984
+ assignErrorCreatingArweaveDataItemsPhase2: k({
1985
+ error: ({ event: e }) => Z(e),
1986
+ errorStep: () => "creatingArweaveDataItemsPhase2"
1987
+ }),
1988
+ assignErrorUploadingViaBundlerPhase2: k({
1989
+ error: ({ event: e }) => Z(e),
1990
+ errorStep: () => "uploadingViaBundlerPhase2"
1991
+ }),
1992
+ assignErrorCreatingAttestations: k({
1993
+ error: ({ event: e }) => Z(e),
1994
+ errorStep: () => "creatingAttestations"
1995
+ }),
1996
+ assignErrorCreatingAttestationsDirectToEas: k({
1997
+ error: ({ event: e }) => Z(e),
1998
+ errorStep: () => "creatingAttestationsDirectToEas"
1999
+ }),
2000
+ assignAccountFromRetry: k({
2001
+ wallet: ({ event: e }) => {
2002
+ let t = e;
2003
+ return t.wallet ?? t.account;
2004
+ },
2005
+ account: ({ event: e }) => {
2006
+ let t = e;
2007
+ return t.wallet ?? t.account;
2008
+ }
2009
+ }),
2010
+ assignErrorNotOwner: k({
2011
+ error: () => /* @__PURE__ */ Error("Item is read-only: you do not own this item. Only the publisher can publish."),
2012
+ errorStep: () => "checking"
2013
+ }),
2014
+ assignErrorValidationFailed: k({
2015
+ error: ({ event: e }) => {
2016
+ let t = e.errors ?? [], n = t.length > 0 ? `Validation failed (${t.length} error${t.length === 1 ? "" : "s"}):\n${t.map((e) => e.message).join("\n")}` : "Validation failed", r = Error(n);
2017
+ return r.validationErrors = t, r;
2018
+ },
2019
+ errorStep: () => "checking"
2020
+ }),
2021
+ assignErrorCheckingFailed: k({
2022
+ error: ({ event: e }) => {
2023
+ let t = e.error;
2024
+ return t instanceof Error ? t : Error(String(t ?? "Publish check failed"));
2025
+ },
2026
+ errorStep: () => "checking"
2027
+ })
2028
+ }
2029
+ }).createMachine({
2030
+ id: "publish",
2031
+ initial: "checking",
2032
+ context: ({ input: e }) => e,
2033
+ states: {
2034
+ checking: {
2035
+ on: {
2036
+ notOwner: {
2037
+ target: Y,
2038
+ actions: ["assignErrorNotOwner", "handleError"]
2039
+ },
2040
+ validationFailed: {
2041
+ target: Y,
2042
+ actions: ["assignErrorValidationFailed", "handleError"]
2043
+ },
2044
+ redundantPublishProcess: { target: "stopping" },
2045
+ checkingFailed: {
2046
+ target: Y,
2047
+ actions: ["assignErrorCheckingFailed", "handleError"]
2048
+ },
2049
+ validPublishProcess: {
2050
+ target: "preparingHtmlEmbedded",
2051
+ actions: k({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2052
+ },
2053
+ validPublishProcessBundler: {
2054
+ target: "preparingHtmlEmbedded",
2055
+ actions: k({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2056
+ },
2057
+ skipArweave: [{
2058
+ guard: ({ context: e }) => _r(e),
2059
+ target: "creatingAttestationsDirectToEas",
2060
+ actions: k({
2061
+ arweaveTransactions: () => [],
2062
+ publishUploads: () => [],
2063
+ attestationStrategy: ({ event: e }) => e.attestationStrategy
2064
+ })
2065
+ }, {
2066
+ guard: ({ context: e }) => X(e),
2067
+ target: "creatingAttestations",
2068
+ actions: k({
2069
+ arweaveTransactions: () => [],
2070
+ publishUploads: () => [],
2071
+ attestationStrategy: ({ event: e }) => e.attestationStrategy
2072
+ })
2073
+ }]
2074
+ },
2075
+ invoke: {
2076
+ src: "checking",
2077
+ input: ({ context: e }) => ({ context: e })
2078
+ }
2079
+ },
2080
+ preparingHtmlEmbedded: { invoke: {
2081
+ src: "preparingHtmlEmbedded",
2082
+ input: ({ context: e }) => ({ context: e }),
2083
+ onDone: [{
2084
+ guard: () => o().useArweaveBundler,
2085
+ target: "creatingArweaveDataItems",
2086
+ actions: k({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2087
+ }, {
2088
+ target: "creatingArweaveTransactions",
2089
+ actions: k({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2090
+ }],
2091
+ onError: {
2092
+ target: Y,
2093
+ actions: ["assignErrorPreparingHtmlEmbedded", "handleError"]
2094
+ }
2095
+ } },
2096
+ creatingArweaveTransactions: { invoke: {
2097
+ src: "createArweaveTransactions",
2098
+ input: ({ context: e, event: t }) => ({
2099
+ context: e,
2100
+ event: t
2101
+ }),
2102
+ onDone: {
2103
+ target: "sendingReimbursementRequest",
2104
+ actions: k({
2105
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2106
+ publishUploads: ({ event: e }) => e.output.publishUploads
2107
+ })
2108
+ },
2109
+ onError: {
2110
+ target: "failure",
2111
+ actions: ["assignErrorCreatingArweaveTransactions", "handleError"]
2112
+ }
2113
+ } },
2114
+ creatingArweaveDataItems: { invoke: {
2115
+ src: "createArweaveDataItems",
2116
+ input: ({ context: e, event: t }) => ({
2117
+ context: e,
2118
+ event: t
2119
+ }),
2120
+ onDone: {
2121
+ target: "uploadingViaBundler",
2122
+ actions: k({
2123
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2124
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2125
+ signedDataItems: ({ event: e }) => e.output.signedDataItems
2126
+ })
2127
+ },
2128
+ onError: {
2129
+ target: "failure",
2130
+ actions: ["assignErrorCreatingArweaveDataItems", "handleError"]
2131
+ }
2132
+ } },
2133
+ sendingReimbursementRequest: { invoke: {
2134
+ src: "sendReimbursementRequest",
2135
+ input: ({ context: e, event: t }) => ({
2136
+ context: e,
2137
+ event: t
2138
+ }),
2139
+ onDone: {
2140
+ target: "pollingForConfirmation",
2141
+ actions: k({
2142
+ requestResponse: ({ event: e }) => e.output,
2143
+ reimbursementTransactionId: ({ event: e }) => e.output.transactionId
2144
+ })
2145
+ },
2146
+ onError: {
2147
+ target: "failure",
2148
+ actions: ["assignErrorSendingReimbursementRequest", "handleError"]
2149
+ }
2150
+ } },
2151
+ pollingForConfirmation: { invoke: {
2152
+ src: "pollForConfirmation",
2153
+ input: ({ context: e, event: t }) => ({
2154
+ context: e,
2155
+ event: t
2156
+ }),
2157
+ onDone: {
2158
+ target: "uploadingData",
2159
+ actions: k({ reimbursementConfirmed: !0 })
2160
+ },
2161
+ onError: {
2162
+ target: "failure",
2163
+ actions: ["assignErrorPollingForConfirmation", "handleError"]
2164
+ }
2165
+ } },
2166
+ uploadingViaBundler: {
2167
+ on: {
2168
+ uploadComplete: [
2169
+ {
2170
+ guard: ({ context: e }) => _r(e),
2171
+ target: "creatingAttestationsDirectToEas",
2172
+ actions: k({
2173
+ completionPercentage: 100,
2174
+ signedDataItems: () => void 0,
2175
+ arweaveUploadData: () => void 0
2176
+ })
2177
+ },
2178
+ {
2179
+ guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
2180
+ target: "rewritingHtmlEmbedded",
2181
+ actions: k({
2182
+ htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
2183
+ htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? [],
2184
+ signedDataItems: () => void 0,
2185
+ arweaveUploadData: () => void 0
2186
+ })
2187
+ },
2188
+ {
2189
+ guard: ({ context: e }) => X(e),
2190
+ target: "creatingAttestations",
2191
+ actions: k({
2192
+ completionPercentage: 100,
2193
+ signedDataItems: () => void 0,
2194
+ arweaveUploadData: () => void 0
2195
+ })
2196
+ }
2197
+ ],
2198
+ uploadError: {
2199
+ target: "failure",
2200
+ actions: ["assignErrorUploadingViaBundler", "handleError"]
2201
+ }
2202
+ },
2203
+ invoke: {
2204
+ src: "uploadViaBundler",
2205
+ input: ({ context: e }) => ({ context: e })
2206
+ }
2207
+ },
2208
+ creatingArweaveDataItemsPhase2: { invoke: {
2209
+ src: "createArweaveDataItemsPhase2",
2210
+ input: ({ context: e, event: t }) => ({
2211
+ context: e,
2212
+ event: t
2213
+ }),
2214
+ onDone: {
2215
+ target: "uploadingViaBundlerPhase2",
2216
+ actions: k({
2217
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2218
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2219
+ signedDataItems: ({ event: e }) => e.output.signedDataItems,
2220
+ uploaderState: () => void 0,
2221
+ currentTransactionIndex: () => void 0
2222
+ })
2223
+ },
2224
+ onError: {
2225
+ target: Y,
2226
+ actions: ["assignErrorCreatingArweaveDataItemsPhase2", "handleError"]
2227
+ }
2228
+ } },
2229
+ uploadingViaBundlerPhase2: {
2230
+ on: {
2231
+ uploadComplete: [{
2232
+ guard: ({ context: e }) => _r(e),
2233
+ target: "creatingAttestationsDirectToEas",
2234
+ actions: k({
2235
+ completionPercentage: 100,
2236
+ signedDataItems: () => void 0,
2237
+ arweaveUploadData: () => void 0
2238
+ })
2239
+ }, {
2240
+ guard: ({ context: e }) => X(e),
2241
+ target: "creatingAttestations",
2242
+ actions: k({
2243
+ completionPercentage: 100,
2244
+ signedDataItems: () => void 0,
2245
+ arweaveUploadData: () => void 0,
2246
+ publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
2247
+ arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
2248
+ })
2249
+ }],
2250
+ uploadError: {
2251
+ target: Y,
2252
+ actions: ["assignErrorUploadingViaBundlerPhase2", "handleError"]
2253
+ }
2254
+ },
2255
+ invoke: {
2256
+ src: "uploadViaBundler",
2257
+ input: ({ context: e }) => ({ context: e })
2258
+ }
2259
+ },
2260
+ uploadingData: {
2261
+ on: {
2262
+ updatePercentage: { actions: k({
2263
+ completionPercentage: ({ event: e }) => e.completionPercentage,
2264
+ uploaderState: ({ event: e }) => e.uploaderState,
2265
+ currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
2266
+ }) },
2267
+ uploadComplete: [
2268
+ {
2269
+ guard: ({ context: e }) => _r(e),
2270
+ target: "creatingAttestationsDirectToEas",
2271
+ actions: k({ completionPercentage: 100 })
2272
+ },
2273
+ {
2274
+ guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
2275
+ target: "rewritingHtmlEmbedded",
2276
+ actions: k({
2277
+ htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
2278
+ htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? []
2279
+ })
2280
+ },
2281
+ {
2282
+ guard: ({ context: e }) => X(e),
2283
+ target: "creatingAttestations",
2284
+ actions: k({ completionPercentage: 100 })
2285
+ }
2286
+ ],
2287
+ uploadError: {
2288
+ target: "failure",
2289
+ actions: ["assignErrorUploadingData", "handleError"]
2290
+ }
2291
+ },
2292
+ invoke: {
2293
+ src: "uploadData",
2294
+ input: ({ context: e }) => ({ context: e })
2295
+ }
2296
+ },
2297
+ rewritingHtmlEmbedded: { invoke: {
2298
+ src: "rewritingHtmlEmbedded",
2299
+ input: ({ context: e }) => ({ context: e }),
2300
+ onDone: [{
2301
+ guard: () => !o().useArweaveBundler,
2302
+ target: "creatingArweaveTransactionsPhase2"
2303
+ }, {
2304
+ guard: () => o().useArweaveBundler,
2305
+ target: "creatingArweaveDataItemsPhase2"
2306
+ }],
2307
+ onError: {
2308
+ target: Y,
2309
+ actions: ["assignErrorRewritingHtmlEmbedded", "handleError"]
2310
+ }
2311
+ } },
2312
+ creatingArweaveTransactionsPhase2: { invoke: {
2313
+ src: "createArweaveTransactionsPhase2",
2314
+ input: ({ context: e, event: t }) => ({
2315
+ context: e,
2316
+ event: t
2317
+ }),
2318
+ onDone: {
2319
+ target: "uploadingDataPhase2",
2320
+ actions: k({
2321
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2322
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2323
+ uploaderState: () => void 0,
2324
+ currentTransactionIndex: () => void 0
2325
+ })
2326
+ },
2327
+ onError: {
2328
+ target: Y,
2329
+ actions: ["assignErrorCreatingArweaveTransactionsPhase2", "handleError"]
2330
+ }
2331
+ } },
2332
+ uploadingDataPhase2: {
2333
+ on: {
2334
+ updatePercentage: { actions: k({
2335
+ completionPercentage: ({ event: e }) => e.completionPercentage,
2336
+ uploaderState: ({ event: e }) => e.uploaderState,
2337
+ currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
2338
+ }) },
2339
+ uploadComplete: [{
2340
+ guard: ({ context: e }) => _r(e),
2341
+ target: "creatingAttestationsDirectToEas",
2342
+ actions: k({ completionPercentage: 100 })
2343
+ }, {
2344
+ guard: ({ context: e }) => X(e),
2345
+ target: "creatingAttestations",
2346
+ actions: k({
2347
+ completionPercentage: 100,
2348
+ publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
2349
+ arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
2350
+ })
2351
+ }],
2352
+ uploadError: {
2353
+ target: Y,
2354
+ actions: ["assignErrorUploadingDataPhase2", "handleError"]
2355
+ }
2356
+ },
2357
+ invoke: {
2358
+ src: "uploadData",
2359
+ input: ({ context: e }) => ({ context: e })
2360
+ }
2361
+ },
2362
+ creatingAttestations: { invoke: {
2363
+ src: "createAttestations",
2364
+ input: ({ context: e, event: t }) => ({
2365
+ context: e,
2366
+ event: t
2367
+ }),
2368
+ onDone: {
2369
+ target: gr,
2370
+ actions: k({ easPayload: ({ event: e }) => e.output?.easPayload })
2371
+ },
2372
+ onError: {
2373
+ target: "attestationFailureRecoverable",
2374
+ actions: ["assignErrorCreatingAttestations", "handleError"]
2375
+ }
2376
+ } },
2377
+ attestationFailureRecoverable: { on: { retry: {
2378
+ target: "creatingAttestations",
2379
+ actions: ["assignAccountFromRetry"]
2380
+ } } },
2381
+ creatingAttestationsDirectToEas: { invoke: {
2382
+ src: "createAttestationsDirectToEas",
2383
+ input: ({ context: e, event: t }) => ({
2384
+ context: e,
2385
+ event: t
2386
+ }),
2387
+ onDone: {
2388
+ target: gr,
2389
+ actions: k({ easPayload: ({ event: e }) => e.output?.easPayload })
2390
+ },
2391
+ onError: {
2392
+ target: "attestationFailureRecoverableDirectToEas",
2393
+ actions: ["assignErrorCreatingAttestationsDirectToEas", "handleError"]
2394
+ }
2395
+ } },
2396
+ attestationFailureRecoverableDirectToEas: { on: { retry: {
2397
+ target: "creatingAttestationsDirectToEas",
2398
+ actions: ["assignAccountFromRetry"]
2399
+ } } },
2400
+ stopping: {
2401
+ entry: ({ context: e }) => {
2402
+ console.log(`Actor for ${e.item?.seedLocalId} stopped`);
2403
+ },
2404
+ type: "final"
2405
+ },
2406
+ [gr]: {
2407
+ entry: ({ context: e }) => {},
2408
+ type: "final"
2409
+ },
2410
+ [Y]: {
2411
+ entry: ({ context: e }) => {},
2412
+ type: "final"
2413
+ }
2414
+ }
2415
+ }), yr = k(({ context: e, event: t }) => {
2416
+ let n = t, r = n.publishProcesses ?? /* @__PURE__ */ new Map(), i = n.subscriptions ?? /* @__PURE__ */ new Map();
2417
+ return {
2418
+ publishProcesses: new Map(r),
2419
+ subscriptions: new Map(i)
2420
+ };
2421
+ }), br = null;
2422
+ function xr(e) {
2423
+ br = e;
2424
+ }
2425
+ function Sr() {
2426
+ return br;
2427
+ }
2428
+ //#endregion
2429
+ //#region src/services/publishManager/actors/subscribe.ts
2430
+ var Cr = M("seedProtocol:services:PublishManager:actors:subscribe");
2431
+ function wr(e) {
2432
+ let t = e.value;
2433
+ return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
2434
+ }
2435
+ function Tr(e) {
2436
+ return l.includes(e);
2437
+ }
2438
+ var Er = A(({ receive: e, input: { publishProcess: t, seedLocalId: n } }) => {
2439
+ let r = Sr(), i = null, a = () => {
2440
+ i != null && (clearInterval(i), i = null);
2441
+ }, o = (e) => {
2442
+ let o = wr(e);
2443
+ Tr(o) && i == null && r ? i = setInterval(() => {
2444
+ try {
2445
+ let e = t.getSnapshot();
2446
+ if (e.status === "done") {
2447
+ a();
2448
+ return;
2449
+ }
2450
+ if (!Tr(wr(e))) {
2451
+ a();
2452
+ return;
2453
+ }
2454
+ } catch {
2455
+ return;
2456
+ }
2457
+ r?.savePublish(n, t);
2458
+ }, me) : Tr(o) || a();
2459
+ }, s = t.subscribe(async (e) => {
2460
+ Cr("Publish state:", e.value), r && (e.status === "done" ? (a(), r.savePublish(n, t, { triggerPublishDone: !0 })) : (r.savePublish(n, t), o(e)));
2461
+ });
2462
+ e(({ type: e }) => {
2463
+ e === "UNSUBSCRIBE" && (Cr("Received UNSUBSCRIBE event"), a(), s.unsubscribe(), r?.removeSubscription(n));
2464
+ });
2465
+ });
2466
+ //#endregion
2467
+ //#region src/services/publishManager/actions/createPublish.ts
2468
+ function Dr(e) {
2469
+ if (e) {
2470
+ if (f(e)) return e;
2471
+ if (r(e)) {
2472
+ let t = i();
2473
+ if (t && t.signer.address.toLowerCase() === e.address.toLowerCase()) return t;
2474
+ throw Error("@seedprotocol/publish: createPublish requires a PublishWallet (signer + txSender). Use fromEthersWallet, fromEip1193Provider, or fromThirdwebAccount.");
2475
+ }
2476
+ throw Error("@seedprotocol/publish: createPublish account must be a PublishWallet. Thirdweb Account must be wrapped with fromThirdwebAccount from @seedprotocol/publish/thirdweb.");
2477
+ }
2478
+ }
2479
+ function Or(e) {
2480
+ if (e) {
2481
+ if (e instanceof O.Wallet) return e;
2482
+ if (f(e)) return e.signer;
2483
+ if (r(e)) return e;
2484
+ }
2485
+ }
2486
+ var kr = Je(({ event: e, enqueue: t }) => {
2487
+ let { item: n, address: r, account: a, options: s } = e;
2488
+ if (!(r != null && typeof r == "string" && r.trim().length > 0)) {
2489
+ console.warn("[createPublish] No valid wallet address; skipping spawn.");
2490
+ return;
2491
+ }
2492
+ t.assign(({ context: e, spawn: t }) => {
2493
+ let { publishProcesses: c } = e;
2494
+ if (c && c.has(n.seedLocalId)) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" already exists.`), e;
2495
+ let l = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `run_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`, u = o(), d = [...u.arweaveUploadTags ?? [], ...s?.arweaveUploadTags ?? []], f = Dr(a) ?? i() ?? void 0, p = t(vr, { input: {
2496
+ item: n,
2497
+ address: r,
2498
+ wallet: f,
2499
+ account: f,
2500
+ modelName: n.modelName,
2501
+ schemaId: n.schemaUid,
2502
+ signDataItems: s?.signDataItems,
2503
+ dataItemSigner: Or(s?.dataItemSigner),
2504
+ signArweaveTransactions: s?.signArweaveTransactions,
2505
+ arweaveJwk: s?.arweaveJwk,
2506
+ publishMode: s?.publishMode ?? "patch",
2507
+ publishRunId: l,
2508
+ arweaveUploadTags: d.length ? d : void 0,
2509
+ htmlEmbeddedDataUriPolicy: s?.htmlEmbeddedDataUriPolicy ?? u.htmlEmbeddedDataUriPolicy ?? "materialize"
2510
+ } });
2511
+ return c.set(n.seedLocalId, p), {
2512
+ ...e,
2513
+ publishProcesses: c
2514
+ };
2515
+ }), t.assign(({ context: e, spawn: t }) => {
2516
+ let { subscriptions: r, publishProcesses: i } = e, a = i.get(n.seedLocalId);
2517
+ if (!a) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" does not exist.`), e;
2518
+ if (r.has(n.seedLocalId)) return console.warn(`Subscription with seedLocalId "${n.seedLocalId}" already exists.`), e;
2519
+ let o = t(Er, { input: {
2520
+ publishProcess: a,
2521
+ seedLocalId: n.seedLocalId
2522
+ } });
2523
+ return r.set(n.seedLocalId, o), {
2524
+ ...e,
2525
+ subscriptions: new Map(r)
2526
+ };
2527
+ });
2528
+ }), Ar = ({ context: e, event: t }) => {
2529
+ let { seedLocalId: n, account: r } = t, a = e.publishProcesses.get(n);
2530
+ if (!a) {
2531
+ console.warn(`Publish process with seedLocalId "${n}" does not exist.`);
2532
+ return;
2533
+ }
2534
+ let o = r == null ? i() ?? void 0 : f(r) ? r : void 0;
2535
+ r != null && !o && console.warn("[retryAttestations] account must be a PublishWallet. Use fromThirdwebAccount / fromEip1193Provider / fromEthersWallet."), a.send({
2536
+ type: "retry",
2537
+ account: o,
2538
+ wallet: o
2539
+ });
2540
+ };
2541
+ //#endregion
2542
+ //#region src/services/publishManager/actions/stopScopedOrStandaloneChild.ts
2543
+ function jr(e, t, n) {
2544
+ t._parent === e ? n.stopChild(t) : t.stop();
2545
+ }
2546
+ //#endregion
2547
+ //#region src/services/publishManager/actors/savePublish.ts
2548
+ var Q = M("seedProtocol:services:PublishManager:actors:savePublish"), Mr = /* @__PURE__ */ new Map();
2549
+ function Nr(e, t) {
2550
+ let n = (Mr.get(e) ?? Promise.resolve()).then(t);
2551
+ return Mr.set(e, n.catch(() => {})), n;
2552
+ }
2553
+ function Pr(e) {
2554
+ return e === "completed" || e === "failed" || e === "interrupted";
2555
+ }
2556
+ function Fr(e) {
2557
+ return e.status === "done" ? e.value === "success" ? "completed" : e.value === "failure" ? "failed" : "completed" : "in_progress";
2558
+ }
2559
+ var Ir = 500, Lr = 2e3;
2560
+ function Rr(e) {
2561
+ return JSON.stringify(e, (e, t) => typeof t == "bigint" ? t.toString() : t);
2562
+ }
2563
+ function zr(e) {
2564
+ if (typeof e != "object" || !e) return;
2565
+ let t = e, n = t.snapshot, r = (t.context ?? n?.context)?.publishRunId;
2566
+ return typeof r == "string" && r.length > 0 ? r : void 0;
2567
+ }
2568
+ function Br(e, t) {
2569
+ if (!e?.error || t !== "failed" && t !== "in_progress") return {};
2570
+ let n = e.error, r = n == null ? void 0 : (n instanceof Error ? n.message : String(n)).slice(0, Ir), i = e.errorStep, a;
2571
+ if (n instanceof Error && n.stack) a = n.stack.slice(0, Lr);
2572
+ else if (typeof n == "object" && n) try {
2573
+ a = JSON.stringify(n).slice(0, Lr);
2574
+ } catch {
2575
+ a = String(n).slice(0, Lr);
2576
+ }
2577
+ else n != null && (a = String(n).slice(0, Lr));
2578
+ return {
2579
+ errorMessage: r ?? void 0,
2580
+ errorStep: i,
2581
+ errorDetails: a
2582
+ };
2583
+ }
2584
+ function Vr(e) {
2585
+ return Nr(e, async () => {
2586
+ let t = S.getAppDb();
2587
+ if (!t) {
2588
+ Q("markInProgressPublishInterrupted: DB not ready, skipping");
2589
+ return;
2590
+ }
2591
+ let n = await t.select().from(T).where(Ze(N(T.seedLocalId, e), N(T.status, "in_progress"))).orderBy(Qe(T.updatedAt)).limit(1);
2592
+ if (n.length === 0) return;
2593
+ let r = Date.now();
2594
+ await t.update(T).set({
2595
+ status: "interrupted",
2596
+ completedAt: r,
2597
+ updatedAt: r,
2598
+ errorMessage: null,
2599
+ errorStep: null,
2600
+ errorDetails: null
2601
+ }).where(N(T.id, n[0].id));
2602
+ });
2603
+ }
2604
+ var Hr = A(({ sendBack: e, input: { persistedSnapshot: t, seedLocalId: n, triggerPublishDone: r } }) => {
2605
+ Q("savePublish seedLocalId", n);
2606
+ let i = t;
2607
+ Nr(n, async () => {
2608
+ let a = S.getAppDb();
2609
+ if (!a) {
2610
+ Q("savePublish: DB not ready, skipping"), e({
2611
+ type: "SAVE_PUBLISH_DONE",
2612
+ seedLocalId: n,
2613
+ triggerPublishDone: r
2614
+ });
2615
+ return;
2616
+ }
2617
+ let o = await a.select().from(T).where(Ze(N(T.seedLocalId, n), N(T.status, "in_progress"))).orderBy(Qe(T.updatedAt)).limit(1), s = typeof t == "string" ? t : Rr(t), c = Fr(i), l = Date.now(), u = Br(i.context, c);
2618
+ if (o.length > 0) {
2619
+ let e = o[0];
2620
+ await a.update(T).set({
2621
+ persistedSnapshot: s,
2622
+ status: c,
2623
+ updatedAt: l,
2624
+ ...i.status === "done" && c !== "in_progress" ? { completedAt: l } : {},
2625
+ ...u
2626
+ }).where(N(T.id, e.id));
2627
+ } else {
2628
+ let e = zr(i);
2629
+ if (e != null && c === "in_progress" && i.status !== "done") {
2630
+ let t = (await a.select().from(T).where(N(T.seedLocalId, n)).orderBy(Qe(T.startedAt)).limit(1))[0];
2631
+ if (t && Pr(t.status)) try {
2632
+ if (zr(JSON.parse(t.persistedSnapshot)) === e) {
2633
+ Q("savePublish: skip stale insert — same publishRunId as latest terminal row", n, e);
2634
+ return;
2635
+ }
2636
+ } catch {}
2637
+ }
2638
+ let t = i.context?.item, r = i.context?.modelName ?? t?.modelName ?? "", o = i.context?.schemaId ?? t?.schemaId;
2639
+ await a.insert(T).values({
2640
+ seedLocalId: n,
2641
+ modelName: r,
2642
+ schemaId: o ?? null,
2643
+ status: c,
2644
+ startedAt: l,
2645
+ persistedSnapshot: s,
2646
+ createdAt: l,
2647
+ updatedAt: l,
2648
+ ...u
2649
+ });
2650
+ }
2651
+ }).then(() => {
2652
+ e({
2653
+ type: "SAVE_PUBLISH_DONE",
2654
+ seedLocalId: n,
2655
+ triggerPublishDone: r
2656
+ });
2657
+ }).catch((t) => {
2658
+ Q("savePublish error", t), e({
2659
+ type: "SAVE_PUBLISH_DONE",
2660
+ seedLocalId: n,
2661
+ triggerPublishDone: r
2662
+ });
2663
+ });
2664
+ }), Ur = Je(({ context: e, event: t, enqueue: n, self: r }) => {
2665
+ let { publishProcesses: i, subscriptions: a } = e, { seedLocalId: o } = t;
2666
+ Vr(o).catch((e) => {
2667
+ console.warn(`[stopPublish] Failed to mark publish_processes row interrupted for "${o}":`, e);
2668
+ });
2669
+ let s = i.get(o);
2670
+ if (!s) {
2671
+ console.warn(`Publish process with seedLocalId "${o}" does not exist.`);
2672
+ return;
2673
+ }
2674
+ jr(r, s, n);
2675
+ let c = a.get(o);
2676
+ c && jr(r, c, n);
2677
+ let l = new Map(i);
2678
+ l.delete(o);
2679
+ let u = new Map(a);
2680
+ u.delete(o), n.assign({
2681
+ publishProcesses: l,
2682
+ subscriptions: u
2683
+ });
2684
+ }), Wr = M("seedProtocol:PublishManager:index"), Gr = Je(({ context: e, enqueue: t, self: n }) => {
2685
+ Wr("Stopping all actors..."), e.publishProcesses.forEach((e) => {
2686
+ jr(n, e, t);
2687
+ }), e.subscriptions.forEach((e) => {
2688
+ jr(n, e, t);
2689
+ }), t.assign({
2690
+ publishProcesses: /* @__PURE__ */ new Map(),
2691
+ subscriptions: /* @__PURE__ */ new Map()
2692
+ });
2693
+ }), Kr = Je(({ context: e, event: t, enqueue: n }) => {
2694
+ let { seedLocalId: r } = t, i = e.publishProcesses.get(r);
2695
+ if (!i) {
2696
+ console.warn(`Publish process with seedLocalId "${r}" does not exist.`);
2697
+ return;
2698
+ }
2699
+ n.stopChild(i);
2700
+ let a = e.subscriptions.get(r);
2701
+ a && n.stopChild(a);
2702
+ let o = new Map(e.publishProcesses);
2703
+ o.delete(r);
2704
+ let s = new Map(e.subscriptions);
2705
+ s.delete(r), n.assign({
2706
+ publishProcesses: o,
2707
+ subscriptions: s
2708
+ });
2709
+ }), qr = k(({ context: e, event: t }) => {
2710
+ let { subscriptions: n } = e, { seedLocalId: r, newSubscription: i } = t;
2711
+ return i && n.set(r, i), { subscriptions: new Map(n) };
2712
+ }), Jr = ["signedDataItems", "arweaveUploadData"];
2713
+ function Yr(e) {
2714
+ if (typeof e != "object" || !e) return e;
2715
+ let t = { ...e };
2716
+ for (let e of Jr) delete t[e];
2717
+ return t;
2718
+ }
2719
+ function Xr(e) {
2720
+ if (typeof e != "object" || !e) return e;
2721
+ let t = e, n = { ...t };
2722
+ t.context != null && typeof t.context == "object" && (n.context = Yr(t.context));
2723
+ let r = t.snapshot;
2724
+ if (typeof r == "object" && r) {
2725
+ let e = r, t = { ...e };
2726
+ e.context != null && typeof e.context == "object" && (t.context = Yr(e.context)), n.snapshot = t;
2727
+ }
2728
+ return n;
2729
+ }
2730
+ function Zr(e) {
2731
+ try {
2732
+ return Xr(e.getPersistedSnapshot?.() ?? e.getSnapshot());
2733
+ } catch {
2734
+ let t = e.getSnapshot(), n = t.context;
2735
+ if (!n?.item) return Xr(t);
2736
+ let r = n.item;
2737
+ return Xr({
2738
+ ...t,
2739
+ context: {
2740
+ ...n,
2741
+ item: {
2742
+ seedLocalId: r.seedLocalId,
2743
+ modelName: r.modelName,
2744
+ schemaId: r.schemaId
2745
+ }
2746
+ }
2747
+ });
2748
+ }
2749
+ }
2750
+ var Qr = k(({ context: e, event: t, spawn: n }) => {
2751
+ let { publishProcesses: r } = e, { seedLocalId: i, publishProcess: a, triggerPublishDone: o } = t;
2752
+ if (!a) return e;
2753
+ let s = new Map(r);
2754
+ s.set(i, a);
2755
+ let c = Zr(a);
2756
+ return n(Hr, {
2757
+ id: `savePublish_${i}_${Date.now()}`,
2758
+ input: {
2759
+ persistedSnapshot: c,
2760
+ seedLocalId: i,
2761
+ triggerPublishDone: o
2762
+ }
2763
+ }), { publishProcesses: s };
2764
+ }), $r = k(({ context: e, event: t }) => {
2765
+ let { publishProcesses: n, subscriptions: r } = e, i = t.seedLocalId, a = r.get(i);
2766
+ a && a.send({ type: "UNSUBSCRIBE" });
2767
+ let o = new Map(n);
2768
+ o.delete(i);
2769
+ let s = new Map(r);
2770
+ return s.delete(i), {
2771
+ publishProcesses: o,
2772
+ subscriptions: s
2773
+ };
2774
+ }), ei = k(({ context: e, event: t }) => {
2775
+ let { subscriptions: n } = e, r = t.seedLocalId, i = new Map(n);
2776
+ return i.delete(r), { subscriptions: i };
2777
+ }), ti = 6e4, ni = 2e3;
2778
+ async function ri(e) {
2779
+ let t = Date.now() + e;
2780
+ for (; Date.now() < t;) {
2781
+ try {
2782
+ if (S.isAppDbReady() && S.getAppDb()) return !0;
2783
+ } catch {}
2784
+ await new Promise((e) => setTimeout(e, ni));
2785
+ }
2786
+ return !1;
2787
+ }
2788
+ function ii(e) {
2789
+ let t = e.value;
2790
+ return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
2791
+ }
2792
+ function ai(e) {
2793
+ let t = ii(e);
2794
+ if (t === "pollingForConfirmation" && (!e.context?.reimbursementTransactionId || !e.context?.requestResponse)) return !1;
2795
+ if (t === "uploadingData") {
2796
+ let t = e.context?.arweaveTransactions, n = e.context?.publishUploads;
2797
+ if (!Array.isArray(t) || t.length === 0 || !Array.isArray(n)) return !1;
2798
+ }
2799
+ return !0;
2800
+ }
2801
+ function oi(e) {
2802
+ return typeof e == "object" && !!e && "xstate$$type" in e && e.xstate$$type === 1 && typeof e.id == "string";
2803
+ }
2804
+ function si(e, t, n) {
2805
+ e.context = e.context ?? {};
2806
+ let r = e.context.item;
2807
+ if (oi(r)) {
2808
+ e.context.item = {
2809
+ seedLocalId: t,
2810
+ modelName: e.context.modelName ?? n.modelName ?? "",
2811
+ schemaId: e.context.schemaId ?? n.schemaId ?? void 0
2812
+ };
2813
+ return;
2814
+ }
2815
+ e.context.item = {
2816
+ ...typeof r == "object" && r && !Array.isArray(r) ? r : {},
2817
+ seedLocalId: t,
2818
+ modelName: r?.modelName ?? e.context.modelName ?? n.modelName ?? "",
2819
+ schemaId: r?.schemaId ?? e.context.schemaId ?? n.schemaId ?? void 0
2820
+ };
2821
+ }
2822
+ var ci = A(({ sendBack: e, input: { context: t } }) => {
2823
+ (async () => {
2824
+ let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map();
2825
+ if (!await ri(ti)) return e({
2826
+ type: "RESTORE_FROM_DB_DONE",
2827
+ publishProcesses: t,
2828
+ subscriptions: n
2829
+ }), {
2830
+ newPublishProcesses: t,
2831
+ newSubscriptions: n
2832
+ };
2833
+ let r = S.getAppDb();
2834
+ if (!r) return e({
2835
+ type: "RESTORE_FROM_DB_DONE",
2836
+ publishProcesses: t,
2837
+ subscriptions: n
2838
+ }), {
2839
+ newPublishProcesses: t,
2840
+ newSubscriptions: n
2841
+ };
2842
+ let i = await r.select().from(T).where(N(T.status, "in_progress")), a = /* @__PURE__ */ new Map(), o = [...i].sort((e, t) => (t.updatedAt ?? t.createdAt ?? 0) - (e.updatedAt ?? e.createdAt ?? 0));
2843
+ for (let e of o) a.has(e.seedLocalId) || a.set(e.seedLocalId, e);
2844
+ let s = Array.from(a.values());
2845
+ for (let e of s) {
2846
+ let r;
2847
+ try {
2848
+ r = JSON.parse(e.persistedSnapshot);
2849
+ } catch {
2850
+ continue;
2851
+ }
2852
+ if (r.status === "done") continue;
2853
+ let i = r.context?.item?.seedLocalId ?? e.seedLocalId;
2854
+ if (!i || !ai(r)) continue;
2855
+ si(r, i, e);
2856
+ let a = qe(vr, {
2857
+ snapshot: r,
2858
+ input: void 0
2859
+ }), o = qe(Er, { input: {
2860
+ publishProcess: a,
2861
+ seedLocalId: i
2862
+ } });
2863
+ t.set(i, a), n.set(i, o), a.start(), o.start();
2864
+ }
2865
+ return {
2866
+ newPublishProcesses: t,
2867
+ newSubscriptions: n
2868
+ };
2869
+ })().then((t) => {
2870
+ if (!t) return;
2871
+ let { newPublishProcesses: n, newSubscriptions: r } = t;
2872
+ e({
2873
+ type: "RESTORE_FROM_DB_DONE",
2874
+ publishProcesses: n,
2875
+ subscriptions: r
2876
+ });
2877
+ });
2878
+ }), li = M("seedProtocol:PublishManager:index"), $ = qe(Ye({
2879
+ types: {
2880
+ context: {},
2881
+ input: {},
2882
+ events: {}
2883
+ },
2884
+ actors: { restoreFromDb: ci },
2885
+ actions: {
2886
+ assignRestoreFromDb: yr,
2887
+ createPublish: kr,
2888
+ addSubscription: qr,
2889
+ requestSavePublish: Qr,
2890
+ publishDone: $r,
2891
+ removeSubscription: ei,
2892
+ retryAttestations: Ar,
2893
+ stopPublish: Ur,
2894
+ stopAll: Gr,
2895
+ query: Kr
2896
+ }
2897
+ }).createMachine({
2898
+ id: "publishManager",
2899
+ initial: "restoreFromDb",
2900
+ context: {
2901
+ publishProcesses: /* @__PURE__ */ new Map(),
2902
+ subscriptions: /* @__PURE__ */ new Map()
2903
+ },
2904
+ states: {
2905
+ restoreFromDb: {
2906
+ on: { RESTORE_FROM_DB_DONE: {
2907
+ target: "active",
2908
+ actions: ["assignRestoreFromDb"]
2909
+ } },
2910
+ invoke: {
2911
+ src: "restoreFromDb",
2912
+ input: ({ context: e }) => ({ context: e })
2913
+ }
2914
+ },
2915
+ active: { on: {
2916
+ CREATE_PUBLISH: { actions: ["createPublish"] },
2917
+ ADD_SUBSCRIPTION: { actions: ["addSubscription"] },
2918
+ REQUEST_SAVE_PUBLISH: { actions: ["requestSavePublish"] },
2919
+ SAVE_PUBLISH_DONE: [{
2920
+ guard: ({ event: e }) => e.triggerPublishDone === !0,
2921
+ actions: ["publishDone"]
2922
+ }],
2923
+ PUBLISH_DONE: { actions: ["publishDone"] },
2924
+ REMOVE_SUBSCRIPTION: { actions: ["removeSubscription"] },
2925
+ RETRY_ATTESTATIONS: { actions: ["retryAttestations"] },
2926
+ STOP_PUBLISH: { actions: ["stopPublish"] },
2927
+ QUERY: { actions: ["query"] },
2928
+ STOP_ALL: { actions: ["stopAll"] }
2929
+ } }
2930
+ }
2931
+ }), { input: {
2932
+ publishProcesses: /* @__PURE__ */ new Map(),
2933
+ subscriptions: /* @__PURE__ */ new Map()
2934
+ } });
2935
+ xr({
2936
+ savePublish: (e, t, n) => {
2937
+ $.send({
2938
+ type: "REQUEST_SAVE_PUBLISH",
2939
+ seedLocalId: e,
2940
+ publishProcess: t,
2941
+ triggerPublishDone: n?.triggerPublishDone
2942
+ });
2943
+ },
2944
+ onPublishDone: (e) => {
2945
+ $.send({
2946
+ type: "PUBLISH_DONE",
2947
+ seedLocalId: e
2948
+ });
2949
+ },
2950
+ removeSubscription: (e) => {
2951
+ $.send({
2952
+ type: "REMOVE_SUBSCRIPTION",
2953
+ seedLocalId: e
2954
+ });
2955
+ }
2956
+ });
2957
+ var ui = $.subscribe((e) => {
2958
+ li("PublishManager snapshot:", e);
2959
+ });
2960
+ typeof document < "u" && ($.start(), window.addEventListener("load", () => {
2961
+ li("PublishManager started");
2962
+ }), window.addEventListener("beforeunload", () => {
2963
+ ui.unsubscribe(), $.stop();
2964
+ }));
2965
+ var di = {
2966
+ getService: () => $,
2967
+ createPublish: (e, t, n, r) => $.send({
2968
+ type: "CREATE_PUBLISH",
2969
+ item: e,
2970
+ address: t,
2971
+ account: n,
2972
+ options: r
2973
+ }),
2974
+ retryAttestations: (e, t) => $.send({
2975
+ type: "RETRY_ATTESTATIONS",
2976
+ seedLocalId: e,
2977
+ account: t
2978
+ }),
2979
+ stopPublish: (e) => $.send({
2980
+ type: "STOP_PUBLISH",
2981
+ seedLocalId: e
2982
+ }),
2983
+ query: (e) => $.send({
2984
+ type: "QUERY",
2985
+ seedLocalId: e
2986
+ }),
2987
+ stopAll: () => $.send({ type: "STOP_ALL" }),
2988
+ getPublish: (e) => $.getSnapshot().context.publishProcesses.get(e),
2989
+ savePublish: (e, t) => $.send({
2990
+ type: "REQUEST_SAVE_PUBLISH",
2991
+ seedLocalId: e,
2992
+ publishProcess: t
2993
+ }),
2994
+ addSubscription: (e, t) => $.send({
2995
+ type: "ADD_SUBSCRIPTION",
2996
+ seedLocalId: e,
2997
+ newSubscription: t
2998
+ }),
2999
+ removeSubscription: (e) => $.send({
3000
+ type: "REMOVE_SUBSCRIPTION",
3001
+ seedLocalId: e
3002
+ })
3003
+ };
3004
+ //#endregion
3005
+ export { wn as a, Gt as c, Tn as i, R as l, vr as n, hn as o, bn as r, At as s, di as t, L as u };
3006
+
3007
+ //# sourceMappingURL=publishManager-BO4sSSvo.js.map