@seedprotocol/publish 0.6.10 → 0.7.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 (120) hide show
  1. package/README.md +1 -1
  2. package/dist/chainConfig-BDMRU4m8.js +1455 -0
  3. package/dist/chainConfig-BDMRU4m8.js.map +1 -0
  4. package/dist/chainConfig-BJ8C_RRz.js +1455 -0
  5. package/dist/chainConfig-BJ8C_RRz.js.map +1 -0
  6. package/dist/chainConfig-DWynbnb8.js +1455 -0
  7. package/dist/chainConfig-DWynbnb8.js.map +1 -0
  8. package/dist/chainConfig-DXCcqaAs.js +1455 -0
  9. package/dist/chainConfig-DXCcqaAs.js.map +1 -0
  10. package/dist/chainConfig-DmuPBs3D.js +1455 -0
  11. package/dist/chainConfig-DmuPBs3D.js.map +1 -0
  12. package/dist/collectBatchUids-CnIe9jUB.js.map +1 -1
  13. package/dist/config.d.ts.map +1 -1
  14. package/dist/ensureAutomationSessionKey-BVmh030S.js +84 -0
  15. package/dist/ensureAutomationSessionKey-BVmh030S.js.map +1 -0
  16. package/dist/ensureAutomationSessionKey-ClCkti9-.js +84 -0
  17. package/dist/ensureAutomationSessionKey-ClCkti9-.js.map +1 -0
  18. package/dist/ensureAutomationSessionKey-CxpJY_uH.js +84 -0
  19. package/dist/ensureAutomationSessionKey-CxpJY_uH.js.map +1 -0
  20. package/dist/ensureAutomationSessionKey-DwRm4YMJ.js +84 -0
  21. package/dist/ensureAutomationSessionKey-DwRm4YMJ.js.map +1 -0
  22. package/dist/ensureAutomationSessionKey-bw6knEyC.js +84 -0
  23. package/dist/ensureAutomationSessionKey-bw6knEyC.js.map +1 -0
  24. package/dist/ensureModularPublishBootstrap-CmxyX_EN.js +23 -0
  25. package/dist/ensureModularPublishBootstrap-CmxyX_EN.js.map +1 -0
  26. package/dist/ensureModularPublishBootstrap-DRFhp-O2.js +23 -0
  27. package/dist/ensureModularPublishBootstrap-DRFhp-O2.js.map +1 -0
  28. package/dist/ensureModularPublishBootstrap-DegJnYKL.js +23 -0
  29. package/dist/ensureModularPublishBootstrap-DegJnYKL.js.map +1 -0
  30. package/dist/ensureModularPublishBootstrap-E4l8no0p.js +23 -0
  31. package/dist/ensureModularPublishBootstrap-E4l8no0p.js.map +1 -0
  32. package/dist/ensureModularPublishBootstrap-Vc4Jz_B9.js +23 -0
  33. package/dist/ensureModularPublishBootstrap-Vc4Jz_B9.js.map +1 -0
  34. package/dist/ensureSmartWalletThenPublish-0nKg13WN.js +47 -0
  35. package/dist/ensureSmartWalletThenPublish-0nKg13WN.js.map +1 -0
  36. package/dist/ensureSmartWalletThenPublish-42iEhiHG.js +47 -0
  37. package/dist/ensureSmartWalletThenPublish-42iEhiHG.js.map +1 -0
  38. package/dist/ensureSmartWalletThenPublish-BdqeUL6t.js +47 -0
  39. package/dist/ensureSmartWalletThenPublish-BdqeUL6t.js.map +1 -0
  40. package/dist/ensureSmartWalletThenPublish-BfEndtFo.js +47 -0
  41. package/dist/ensureSmartWalletThenPublish-BfEndtFo.js.map +1 -0
  42. package/dist/ensureSmartWalletThenPublish-UklyVBu9.js +47 -0
  43. package/dist/ensureSmartWalletThenPublish-UklyVBu9.js.map +1 -0
  44. package/dist/index.js +6 -14
  45. package/dist/index.js.map +1 -1
  46. package/dist/managedAccountAdmin-B3DPMmhR.js +28 -0
  47. package/dist/managedAccountAdmin-B3DPMmhR.js.map +1 -0
  48. package/dist/managedAccountAdmin-ByEX_Eg2.js +28 -0
  49. package/dist/managedAccountAdmin-ByEX_Eg2.js.map +1 -0
  50. package/dist/managedAccountAdmin-C5UqbkQ0.js +28 -0
  51. package/dist/managedAccountAdmin-C5UqbkQ0.js.map +1 -0
  52. package/dist/managedAccountAdmin-DS6nniiu.js +28 -0
  53. package/dist/managedAccountAdmin-DS6nniiu.js.map +1 -0
  54. package/dist/managedAccountAdmin-DwFI-ZfE.js +28 -0
  55. package/dist/managedAccountAdmin-DwFI-ZfE.js.map +1 -0
  56. package/dist/publishAuthorization-C-XYb9Ef.js +4034 -0
  57. package/dist/publishAuthorization-C-XYb9Ef.js.map +1 -0
  58. package/dist/publishAuthorization-CAFF5jQ2.js +4023 -0
  59. package/dist/publishAuthorization-CAFF5jQ2.js.map +1 -0
  60. package/dist/publishAuthorization-CG23g8w2.js +3987 -0
  61. package/dist/publishAuthorization-CG23g8w2.js.map +1 -0
  62. package/dist/publishAuthorization-CvK_coYp.js +4011 -0
  63. package/dist/publishAuthorization-CvK_coYp.js.map +1 -0
  64. package/dist/publishAuthorization-S3ofoXPN.js +4059 -0
  65. package/dist/publishAuthorization-S3ofoXPN.js.map +1 -0
  66. package/dist/publishThirdwebClient-BFx_M2Uy.js +18 -0
  67. package/dist/publishThirdwebClient-BFx_M2Uy.js.map +1 -0
  68. package/dist/publishThirdwebClient-BQ_KnMi5.js +18 -0
  69. package/dist/publishThirdwebClient-BQ_KnMi5.js.map +1 -0
  70. package/dist/publishThirdwebClient-BmqsJCjp.js +18 -0
  71. package/dist/publishThirdwebClient-BmqsJCjp.js.map +1 -0
  72. package/dist/publishThirdwebClient-CPzAjnmf.js +18 -0
  73. package/dist/publishThirdwebClient-CPzAjnmf.js.map +1 -0
  74. package/dist/publishThirdwebClient-D-K2WEeM.js +18 -0
  75. package/dist/publishThirdwebClient-D-K2WEeM.js.map +1 -0
  76. package/dist/resolveRevokeAccount-9-OzXVdp.js +38 -0
  77. package/dist/resolveRevokeAccount-9-OzXVdp.js.map +1 -0
  78. package/dist/resolveRevokeAccount-CXTz4-wI.js +38 -0
  79. package/dist/resolveRevokeAccount-CXTz4-wI.js.map +1 -0
  80. package/dist/resolveRevokeAccount-CXa5XlOv.js +38 -0
  81. package/dist/resolveRevokeAccount-CXa5XlOv.js.map +1 -0
  82. package/dist/resolveRevokeAccount-CkbTpC27.js +38 -0
  83. package/dist/resolveRevokeAccount-CkbTpC27.js.map +1 -0
  84. package/dist/resolveRevokeAccount-QgZ6YZuS.js +38 -0
  85. package/dist/resolveRevokeAccount-QgZ6YZuS.js.map +1 -0
  86. package/dist/services/publish/actors/checking.d.ts.map +1 -1
  87. package/dist/services/publish/actors/createAttestations.d.ts.map +1 -1
  88. package/dist/services/publish/actors/createAttestationsDirectToEas.d.ts.map +1 -1
  89. package/dist/services/publish/actors/multiPublishReceipt.d.ts +58 -0
  90. package/dist/services/publish/actors/multiPublishReceipt.d.ts.map +1 -0
  91. package/dist/services/publish/actors/persistSeedUid.d.ts.map +1 -1
  92. package/dist/services/publish/actors/recordMultiPublishReceipt.d.ts +45 -0
  93. package/dist/services/publish/actors/recordMultiPublishReceipt.d.ts.map +1 -0
  94. package/dist/services/publish/actors/rewritingHtmlEmbedded.d.ts.map +1 -1
  95. package/dist/services/publish/helpers/getPublishUploadData.d.ts +5 -0
  96. package/dist/services/publish/helpers/getPublishUploadData.d.ts.map +1 -1
  97. package/dist/services/publishCost/types.d.ts +3 -1
  98. package/dist/services/publishCost/types.d.ts.map +1 -1
  99. package/dist/services/publishManager/actions/publishDone.d.ts.map +1 -1
  100. package/dist/services/publishManager/actions/stopAll.d.ts.map +1 -1
  101. package/dist/services/publishManager/actions/stopPublish.d.ts.map +1 -1
  102. package/dist/services/publishManager/actors/restoreFromDb.d.ts.map +1 -1
  103. package/dist/services/publishManager/index.d.ts +3 -3
  104. package/dist/services/publishManager/index.d.ts.map +1 -1
  105. package/dist/services/publishManager/publishLocks.d.ts +22 -0
  106. package/dist/services/publishManager/publishLocks.d.ts.map +1 -0
  107. package/dist/services/revoke/revokeAttestations.d.ts.map +1 -1
  108. package/dist/thirdweb.js +7 -9
  109. package/dist/thirdweb.js.map +1 -1
  110. package/dist/worker-BQN6N0W0.js +72 -0
  111. package/dist/worker-BQN6N0W0.js.map +1 -0
  112. package/dist/worker-CCQ7KBMm.js +72 -0
  113. package/dist/worker-CCQ7KBMm.js.map +1 -0
  114. package/dist/worker-CJRUAOAn.js +69 -0
  115. package/dist/worker-CJRUAOAn.js.map +1 -0
  116. package/dist/worker-FmHZbku5.js +72 -0
  117. package/dist/worker-FmHZbku5.js.map +1 -0
  118. package/dist/worker-qoGuo876.js +69 -0
  119. package/dist/worker-qoGuo876.js.map +1 -0
  120. package/package.json +8 -7
@@ -0,0 +1,4011 @@
1
+ import { t as e } from "./rolldown-runtime-Dy4uBu1J.js";
2
+ import { At as t, B as n, Ct as r, D as i, Dt as a, Et as o, F as s, G as c, H as l, I as u, J as d, K as f, L as p, O as m, Ot as h, P as g, Q as _, R as v, St as y, V as b, X as x, Y as ee, Z as te, _ as S, _t as ne, a as re, at as ie, b as ae, bt as oe, c as se, ct as ce, dt as C, et as le, f as ue, ft as de, h as fe, ht as pe, it as me, j as he, jt as ge, k as _e, lt as ve, mt as w, o as T, ot as ye, q as be, r as xe, rt as Se, st as Ce, t as E, u as we, ut as Te, v as D, wt as Ee, xt as De, y as O, yt as Oe, z as ke } from "./chainConfig-BJ8C_RRz.js";
3
+ import { t as k } from "./publishThirdwebClient-D-K2WEeM.js";
4
+ import { BaseArweaveClient as Ae, BaseDb as A, BaseFileManager as j, INTERNAL_DATA_TYPES as je, Item as M, ModelPropertyDataTypes as Me, applyPropertyAttestationUidsFromPublish as Ne, arweaveL1FinalizeJobs as Pe, assertLocalDbChain as Fe, getCorrectId as Ie, getEasSchemaForItemProperty as Le, getItemPropertiesFromEas as Re, getRelatedItemsForPublish as ze, getSegmentedItemProperties as Be, getUploadPipelineTransactionStatus as Ve, htmlEmbeddedImageCoPublish as He, isItemOwned as Ue, isPublishedSeedRef as We, itemHasPublishUploadCandidates as Ge, listRelationEasPropertyName as Ke, normalizeDataType as qe, normalizeRelationPropertyValue as Je, prepareHtmlEmbeddedImagesForPublish as Ye, publishProcesses as N, resolvePublishPayloadValues as Xe, resolveSeedIdsFromRefString as Ze, rewriteHtmlEmbeddedImagesOnDisk as Qe, setSchemaUidForModel as $e, setSchemaUidForSchemaDefinition as et, updateVersionUid as tt, validateItemForPublish as nt } from "@seedprotocol/sdk";
5
+ import { BaseError as rt, decodeAbiParameters as it, decodeErrorResult as at, isAddressEqual as ot, parseEther as st, parseEventLogs as P, toFunctionSelector as ct, zeroAddress as lt } from "viem";
6
+ import { deploySmartAccount as ut, getContract as dt } from "thirdweb";
7
+ import { ethers as F, keccak256 as ft, toUtf8Bytes as pt } from "ethers";
8
+ import { PUBLISH_AUTHORIZATION_DEFAULT_EXPIRATION_SECS as mt, PUBLISH_AUTHORIZATION_SCHEMA_DEF as ht, PUBLISH_AUTHORIZATION_SCHEMA_DEF as gt, PUBLISH_AUTHORIZATION_SCHEMA_NAME as _t, PUBLISH_AUTHORIZATION_SCHEMA_NAME as vt, PUBLISH_AUTHORIZATION_SCOPES as yt, PUBLISH_AUTHORIZATION_SCOPES as bt, assessPublishAuthorization as xt, decodePublishAuthorizationData as St, getPublishAuthorizationFromEas as Ct, isValidEasAttestationUid as wt, normalizeBytes32Hex as Tt } from "@seedprotocol/eas";
9
+ import { createContext as Et, useContext as Dt, useEffect as Ot, useRef as kt, useState as At } from "react";
10
+ import jt from "arweave";
11
+ import { NO_EXPIRATION as Mt, SchemaEncoder as Nt, SchemaRegistry as Pt, ZERO_ADDRESS as Ft, ZERO_BYTES32 as It } from "@ethereum-attestation-service/eas-sdk";
12
+ import { assign as I, createActor as Lt, enqueueActions as Rt, fromCallback as zt, fromPromise as L, setup as Bt } from "xstate";
13
+ import R from "debug";
14
+ import { and as Vt, desc as Ht, eq as z } from "drizzle-orm";
15
+ import { createWallet as Ut, inAppWallet as Wt } from "thirdweb/wallets";
16
+ import { useActiveAccount as Gt } from "thirdweb/react";
17
+ import { estimateUserOpGas as Kt, getPaymasterAndData as qt } from "thirdweb/wallets/smart";
18
+ //#region src/react/PublishConfigContext.tsx
19
+ var Jt = Et(null);
20
+ function Yt() {
21
+ let e = Dt(Jt);
22
+ if (!e) throw Error("usePublishConfig: PublishConfig is missing. Pass config to PublishProvider or call initPublish() before render.");
23
+ return e;
24
+ }
25
+ //#endregion
26
+ //#region src/helpers/describeRevert.ts
27
+ var Xt = [
28
+ {
29
+ type: "error",
30
+ name: "PublishIndexOutOfBounds",
31
+ inputs: [{
32
+ name: "targetIndex",
33
+ type: "uint256"
34
+ }, {
35
+ name: "length",
36
+ type: "uint256"
37
+ }]
38
+ },
39
+ {
40
+ type: "error",
41
+ name: "UnknownPublishLocalId",
42
+ inputs: [{
43
+ name: "publishLocalId",
44
+ type: "string"
45
+ }]
46
+ },
47
+ {
48
+ type: "error",
49
+ name: "PublishTargetAlreadyAttested",
50
+ inputs: [{
51
+ name: "requestIndex",
52
+ type: "uint256"
53
+ }, {
54
+ name: "targetIndex",
55
+ type: "uint256"
56
+ }]
57
+ },
58
+ {
59
+ type: "error",
60
+ name: "EmptyAttestationData",
61
+ inputs: [{
62
+ name: "targetIndex",
63
+ type: "uint256"
64
+ }, {
65
+ name: "propertySchemaUid",
66
+ type: "bytes32"
67
+ }]
68
+ },
69
+ {
70
+ type: "error",
71
+ name: "PropertyToUpdateNotFound",
72
+ inputs: [
73
+ {
74
+ name: "requestIndex",
75
+ type: "uint256"
76
+ },
77
+ {
78
+ name: "targetIndex",
79
+ type: "uint256"
80
+ },
81
+ {
82
+ name: "propertySchemaUid",
83
+ type: "bytes32"
84
+ }
85
+ ]
86
+ },
87
+ {
88
+ type: "error",
89
+ name: "AmbiguousPropertyToUpdate",
90
+ inputs: [{
91
+ name: "targetIndex",
92
+ type: "uint256"
93
+ }, {
94
+ name: "propertySchemaUid",
95
+ type: "bytes32"
96
+ }]
97
+ },
98
+ {
99
+ type: "error",
100
+ name: "InvalidEAS",
101
+ inputs: [{
102
+ name: "eas",
103
+ type: "address"
104
+ }]
105
+ },
106
+ {
107
+ type: "error",
108
+ name: "AttestationFailed",
109
+ inputs: [{
110
+ name: "schemaUid",
111
+ type: "bytes32"
112
+ }]
113
+ },
114
+ {
115
+ type: "error",
116
+ name: "Unauthorized",
117
+ inputs: [{
118
+ name: "caller",
119
+ type: "address"
120
+ }]
121
+ },
122
+ {
123
+ type: "error",
124
+ name: "InvalidAddress",
125
+ inputs: [{
126
+ name: "addr",
127
+ type: "address"
128
+ }]
129
+ },
130
+ {
131
+ type: "error",
132
+ name: "SeedExecutorAlreadyInstalled",
133
+ inputs: []
134
+ },
135
+ {
136
+ type: "error",
137
+ name: "SeedExecutorNotInstalled",
138
+ inputs: []
139
+ },
140
+ {
141
+ type: "error",
142
+ name: "NotSeedExecutor",
143
+ inputs: [{
144
+ name: "caller",
145
+ type: "address"
146
+ }]
147
+ },
148
+ {
149
+ type: "error",
150
+ name: "UnsupportedExecutionMode",
151
+ inputs: [{
152
+ name: "mode",
153
+ type: "bytes32"
154
+ }]
155
+ },
156
+ {
157
+ type: "error",
158
+ name: "TargetNotAllowed",
159
+ inputs: [{
160
+ name: "target",
161
+ type: "address"
162
+ }]
163
+ },
164
+ {
165
+ type: "error",
166
+ name: "SelectorNotAllowed",
167
+ inputs: [{
168
+ name: "selector",
169
+ type: "bytes4"
170
+ }]
171
+ },
172
+ {
173
+ type: "error",
174
+ name: "ValueMismatch",
175
+ inputs: [{
176
+ name: "encodedValue",
177
+ type: "uint256"
178
+ }, {
179
+ name: "sentValue",
180
+ type: "uint256"
181
+ }]
182
+ },
183
+ ...y,
184
+ ...Ee
185
+ ];
186
+ function Zt(e) {
187
+ if (e instanceof rt) return e.walk((e) => {
188
+ let t = e.data;
189
+ return typeof t == "string" && t.startsWith("0x") && t.length > 2;
190
+ })?.data;
191
+ }
192
+ function Qt(e) {
193
+ if (Zt(e)) return !0;
194
+ let t = e instanceof rt ? `${e.shortMessage} ${e.details}` : String(e);
195
+ return /revert/i.test(t);
196
+ }
197
+ var $t = "reverted with no data. The target likely has no matching function or the account cannot run executor calls";
198
+ function en(e, t = $t) {
199
+ if (!e || e === "0x") return t;
200
+ try {
201
+ let t = at({
202
+ abi: Xt,
203
+ data: e
204
+ }), n = t.args?.length ? `(${t.args.map(String).join(", ")})` : "";
205
+ return `reverted with ${t.errorName}${n}`;
206
+ } catch {
207
+ return `reverted with data ${e}`;
208
+ }
209
+ }
210
+ function tn(e, t) {
211
+ return t && t !== "0x" ? `The publish UserOp in transaction ${e} ${en(t)}.` : `The publish UserOp in transaction ${e} failed with no revert reason. That usually means it ran out of gas (the bundler's gas estimate was too low), not that the publish data is wrong. To confirm, run \`npx hardhat seed:explain-userop --network <network> --tx ${e}\` in seed-protocol.`;
212
+ }
213
+ function nn(e) {
214
+ let { txHash: t, revertData: n, sender: r, cause: i } = e, a = !!n && n !== "0x";
215
+ return new w(tn(t, n), a ? "USEROP_REVERTED" : "USEROP_FAILED_NO_REASON", r, i);
216
+ }
217
+ function rn(e) {
218
+ let t = [];
219
+ for (let n = e; n && t.length < 6; n = n.cause) t.push(n);
220
+ return t;
221
+ }
222
+ var an;
223
+ function on(e) {
224
+ return an ??= new Map(Xt.filter((e) => e.type === "error").map((e) => [ct(`${e.name}(${e.inputs.map((e) => e.type).join(",")})`), e.name])), an.get(e.toLowerCase());
225
+ }
226
+ function sn(e, t) {
227
+ for (let n of rn(e)) {
228
+ let r = String(n.message ?? "").match(/UserOp failed at txHash: (0x[0-9a-f]{64})/i);
229
+ if (r) return nn({
230
+ txHash: r[1],
231
+ sender: t,
232
+ cause: e
233
+ });
234
+ let i = n.signature;
235
+ if (n.name === "AbiErrorSignatureNotFoundError" && typeof i == "string") {
236
+ let n = on(i);
237
+ if (n) return new w(`The publish transaction reverted with ${n} (its arguments were not decoded).`, "USEROP_REVERTED", t, e);
238
+ }
239
+ }
240
+ return e;
241
+ }
242
+ //#endregion
243
+ //#region src/helpers/blockchain.ts
244
+ var B = () => {
245
+ let e = Ae.getArweaveJsApiConfig(), t = jt;
246
+ return Object.keys(t).includes("default") && t.default ? t.default.init(e) : t.init(e);
247
+ };
248
+ //#endregion
249
+ //#region src/helpers/schemaRegistry.ts
250
+ async function V(e) {
251
+ return Se(e);
252
+ }
253
+ function cn(e) {
254
+ return d(e);
255
+ }
256
+ //#endregion
257
+ //#region src/helpers/nameSchemaAttestation.ts
258
+ var ln = "0x0000000000000000000000000000000000000000";
259
+ function un(e) {
260
+ let t = new Nt("bytes32 schemaId,string name").encodeData([{
261
+ name: "schemaId",
262
+ value: e.schemaUid,
263
+ type: "bytes32"
264
+ }, {
265
+ name: "name",
266
+ value: e.schemaName,
267
+ type: "string"
268
+ }]);
269
+ return l({
270
+ schema: o,
271
+ data: {
272
+ recipient: ln,
273
+ expirationTime: BigInt(Mt),
274
+ revocable: !0,
275
+ refUID: It,
276
+ data: t,
277
+ value: 0n
278
+ }
279
+ });
280
+ }
281
+ //#endregion
282
+ //#region src/services/publish/helpers/ensureEasSchemas.ts
283
+ var H = "0x0000000000000000000000000000000000000000", U = !0, dn = "bytes32 schemaId,string name", fn = "bytes32 version", pn = /* @__PURE__ */ new Set();
284
+ function mn(e) {
285
+ return e.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
286
+ }
287
+ async function hn(e) {
288
+ let { itemRelationProperties: t, itemImageProperties: n, itemListProperties: r } = await Be(e), i = /* @__PURE__ */ new Set();
289
+ e.modelName && i.add(e.modelName);
290
+ for (let e of t) {
291
+ let t = e.propertyDef?.ref;
292
+ t && i.add(t);
293
+ }
294
+ for (let e of n) {
295
+ let t = qe(e.propertyDef?.dataType);
296
+ t === Me.File ? i.add("File") : t === Me.Html ? i.add("Html") : i.add("Image");
297
+ }
298
+ for (let e of r) {
299
+ let t = e.propertyDef?.ref;
300
+ t && i.add(t);
301
+ }
302
+ return i;
303
+ }
304
+ async function gn(e, t) {
305
+ let n = await e.sendTransaction(t);
306
+ await C(n.transactionHash);
307
+ }
308
+ function _n(e) {
309
+ let t = qe(e);
310
+ return je[t]?.eas ?? "string";
311
+ }
312
+ function vn(e, t) {
313
+ if (e) throw Error(`schema "${t}" is not registered; automation keys can't register schemas. Call ensureEasSchemasForItem with the owner wallet first.`);
314
+ }
315
+ async function yn() {
316
+ let e = xe().id;
317
+ if (pn.has(e)) return;
318
+ let t = Pt.getSchemaUID(fn, H, U), n = [[dn, o], [fn, t]], r = [];
319
+ for (let [e, t] of n) await V(t) || r.push(`"${e}" (${t})`);
320
+ if (r.length > 0) throw Error(`Seed base schema${r.length > 1 ? "s" : ""} ${r.join(" and ")} not registered on chain ${e}. The protocol registers base schemas for each supported chain (seed-protocol: bun run seed:ensure-schemas).`);
321
+ pn.add(e);
322
+ }
323
+ async function bn(e, t) {
324
+ if (typeof t?.blockSchemaRegistration == "boolean") return t.blockSchemaRegistration;
325
+ let n = t?.managedAddress?.trim();
326
+ if (!n || !i(e)) return !1;
327
+ let { isAutomationSessionActive: r } = await import("./ensureAutomationSessionKey-DwRm4YMJ.js").then((e) => e.n);
328
+ return r(n, e.signer.address);
329
+ }
330
+ async function xn(e, t, n) {
331
+ await Sn(e, t, n);
332
+ }
333
+ async function Sn(e, t, n) {
334
+ let r = await bn(t, n), a = i(t) ? t.txSender : _e(t) ? t : (() => {
335
+ throw Error("@seedprotocol/publish: ensureEasSchemasForItem requires a PublishWallet or SeedTxSender");
336
+ })();
337
+ await yn();
338
+ let { itemBasicProperties: o, itemRelationProperties: s, itemImageProperties: c, itemListProperties: l } = await Be(e), u = [
339
+ ...o,
340
+ ...s,
341
+ ...c,
342
+ ...l
343
+ ], d = /* @__PURE__ */ new Set(), f = await hn(e), p = /* @__PURE__ */ new Set();
344
+ for (let e of f) {
345
+ let t = `bytes32 ${mn(e)}`, n = Pt.getSchemaUID(t, H, U);
346
+ if (await V(n)) {
347
+ $e({
348
+ modelName: e,
349
+ schemaUid: n
350
+ });
351
+ continue;
352
+ }
353
+ if (p.has(n)) {
354
+ $e({
355
+ modelName: e,
356
+ schemaUid: n
357
+ });
358
+ continue;
359
+ }
360
+ vn(r, t);
361
+ try {
362
+ await gn(a, cn({
363
+ schema: t,
364
+ resolverAddress: H,
365
+ revocable: U
366
+ }));
367
+ } catch (t) {
368
+ throw Error(`Failed to register EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
369
+ }
370
+ try {
371
+ await gn(a, un({
372
+ schemaUid: n,
373
+ schemaName: mn(e)
374
+ }));
375
+ } catch (t) {
376
+ throw Error(`Failed to name EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
377
+ }
378
+ p.add(n), $e({
379
+ modelName: e,
380
+ schemaUid: n
381
+ });
382
+ }
383
+ let m = "string storage_transaction_id", h = Pt.getSchemaUID(m, H, U);
384
+ if (await V(h)) et({
385
+ text: m,
386
+ schemaUid: h
387
+ });
388
+ else if (!d.has(h) && (f.has("Image") || f.has("File") || f.has("Html"))) {
389
+ vn(r, m);
390
+ try {
391
+ await gn(a, cn({
392
+ schema: m,
393
+ resolverAddress: H,
394
+ revocable: U
395
+ })), await gn(a, un({
396
+ schemaUid: h,
397
+ schemaName: "storage_transaction_id"
398
+ }));
399
+ } catch (e) {
400
+ throw Error(`Failed to register EAS schema for storageTransactionId: ${e instanceof Error ? e.message : String(e)}`);
401
+ }
402
+ d.add(h), et({
403
+ text: m,
404
+ schemaUid: h
405
+ });
406
+ }
407
+ for (let e of u) {
408
+ if (!e.propertyDef) continue;
409
+ let t = _n(e.propertyDef.dataType), n = e, i = Ke(e.propertyName, e.propertyDef), o = i ?? (n.storagePropertyName && n.storagePropertyName.length > 0 ? n.storagePropertyName : e.propertyName), s = mn(o), c = `${t} ${s}`;
410
+ if (i && !s.endsWith("_ids")) throw Error(`Refusing to register "${c}" for list-relation property ${e.propertyName}: list relations attest as <singular>_<ref>_ids.`);
411
+ let l = [
412
+ "string",
413
+ "address",
414
+ "bool",
415
+ "bytes",
416
+ "bytes32",
417
+ "uint8",
418
+ "uint16",
419
+ "uint32",
420
+ "uint64",
421
+ "uint128",
422
+ "uint256"
423
+ ].includes(t) ? t : void 0, u = await Le({
424
+ schemaUid: i ? void 0 : e.schemaUid,
425
+ propertyName: o,
426
+ easDataType: l
427
+ });
428
+ if (u) {
429
+ let e = await V(u.id);
430
+ if (e && e.schema === c) {
431
+ et({
432
+ text: c,
433
+ schemaUid: u.id
434
+ });
435
+ continue;
436
+ }
437
+ }
438
+ let f = Pt.getSchemaUID(c, H, U);
439
+ if (await V(f)) {
440
+ et({
441
+ text: c,
442
+ schemaUid: f
443
+ });
444
+ continue;
445
+ }
446
+ if (d.has(f)) {
447
+ et({
448
+ text: c,
449
+ schemaUid: f
450
+ });
451
+ continue;
452
+ }
453
+ vn(r, c);
454
+ try {
455
+ await gn(a, cn({
456
+ schema: c,
457
+ resolverAddress: H,
458
+ revocable: U
459
+ }));
460
+ } catch (t) {
461
+ throw Error(`Failed to register EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
462
+ }
463
+ try {
464
+ await gn(a, un({
465
+ schemaUid: f,
466
+ schemaName: s
467
+ }));
468
+ } catch (t) {
469
+ throw Error(`Failed to name EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
470
+ }
471
+ d.add(f), et({
472
+ text: c,
473
+ schemaUid: f
474
+ });
475
+ }
476
+ let g = await ze(e);
477
+ for (let e of g) await Sn(e, t, {
478
+ managedAddress: n?.managedAddress,
479
+ blockSchemaRegistration: r
480
+ });
481
+ }
482
+ //#endregion
483
+ //#region src/services/publish/actors/utils.ts
484
+ var W = "0x" + "0".repeat(64), Cn = async (e) => {
485
+ let t;
486
+ try {
487
+ t = await M.find({ seedLocalId: e });
488
+ } catch {}
489
+ return t || new Promise((t) => {
490
+ let n = setInterval(() => {
491
+ try {
492
+ M.find({ seedLocalId: e }).then((e) => {
493
+ e && (clearInterval(n), t(e));
494
+ });
495
+ } catch {}
496
+ }, 200);
497
+ });
498
+ };
499
+ function wn(e) {
500
+ if (!e || typeof e != "object") return;
501
+ let t = e;
502
+ if (Array.isArray(t.data_root)) return {
503
+ data_root: new Uint8Array(t.data_root),
504
+ chunks: (t.chunks ?? []).map((e) => ({
505
+ ...e,
506
+ dataHash: new Uint8Array(e.dataHash ?? [])
507
+ })),
508
+ proofs: (t.proofs ?? []).map((e) => ({
509
+ ...e,
510
+ proof: new Uint8Array(e.proof ?? [])
511
+ }))
512
+ };
513
+ }
514
+ function Tn(e) {
515
+ return {
516
+ data_root: Array.from(e.data_root),
517
+ chunks: e.chunks.map((e) => ({
518
+ ...e,
519
+ dataHash: Array.from(e.dataHash)
520
+ })),
521
+ proofs: e.proofs.map((e) => ({
522
+ ...e,
523
+ proof: Array.from(e.proof)
524
+ }))
525
+ };
526
+ }
527
+ //#endregion
528
+ //#region src/services/publish/actors/createArweaveTransactions.ts
529
+ var En = L(async ({ input: { context: e } }) => {
530
+ let { item: t } = e;
531
+ t.getPublishUploads || (t = await Cn(t.seedLocalId));
532
+ let n = {};
533
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
534
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
535
+ r?.length && (n.deferHtmlStorageSeedLocalIds = r);
536
+ let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = T(), o = e.signArweaveTransactions ?? a.signArweaveTransactions, s = e.arweaveJwk ?? a.arweaveJwk, c = i.map((e) => ({
537
+ versionLocalId: e.versionLocalId,
538
+ itemPropertyName: e.itemPropertyName,
539
+ transactionJson: e.transactionToSign.toJSON()
540
+ })), l;
541
+ if (o) l = await o(c);
542
+ else if (s) {
543
+ let e = B(), t = s;
544
+ l = [];
545
+ for (let n of c) {
546
+ let r = e.transactions.fromRaw(n.transactionJson);
547
+ r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
548
+ let i = r.toJSON();
549
+ l.push({
550
+ transaction: {
551
+ ...i,
552
+ chunks: r.chunks ? Tn(r.chunks) : void 0
553
+ },
554
+ versionId: n.versionLocalId,
555
+ modelName: n.itemPropertyName
556
+ });
557
+ }
558
+ } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
559
+ let u = B();
560
+ return {
561
+ arweaveTransactions: l.map((e) => {
562
+ let { chunks: t, ...n } = e.transaction, r = { ...n }, i = wn(t);
563
+ return i && (r.chunks = i), {
564
+ transaction: u.transactions.fromRaw(r),
565
+ versionId: e.versionId,
566
+ modelName: e.modelName
567
+ };
568
+ }),
569
+ publishUploads: i
570
+ };
571
+ }), Dn = L(async ({ input: { context: e } }) => {
572
+ let { item: t } = e;
573
+ t.getPublishUploads || (t = await Cn(t.seedLocalId));
574
+ let n = {};
575
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
576
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
577
+ r?.length && (n.onlyHtmlStorageSeedLocalIds = r, n.skipRelationRecursion = !0);
578
+ let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = T(), o = e.signArweaveTransactions ?? a.signArweaveTransactions, s = e.arweaveJwk ?? a.arweaveJwk, c = i.map((e) => ({
579
+ versionLocalId: e.versionLocalId,
580
+ itemPropertyName: e.itemPropertyName,
581
+ transactionJson: e.transactionToSign.toJSON()
582
+ })), l;
583
+ if (o) l = await o(c);
584
+ else if (s) {
585
+ let e = B(), t = s;
586
+ l = [];
587
+ for (let n of c) {
588
+ let r = e.transactions.fromRaw(n.transactionJson);
589
+ r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
590
+ let i = r.toJSON();
591
+ l.push({
592
+ transaction: {
593
+ ...i,
594
+ chunks: r.chunks ? Tn(r.chunks) : void 0
595
+ },
596
+ versionId: n.versionLocalId,
597
+ modelName: n.itemPropertyName
598
+ });
599
+ }
600
+ } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
601
+ let u = B();
602
+ return {
603
+ arweaveTransactions: l.map((e) => {
604
+ let { chunks: t, ...n } = e.transaction, r = { ...n }, i = wn(t);
605
+ return i && (r.chunks = i), {
606
+ transaction: u.transactions.fromRaw(r),
607
+ versionId: e.versionId,
608
+ modelName: e.modelName
609
+ };
610
+ }),
611
+ publishUploads: i
612
+ };
613
+ }), On = L(async ({ input: { context: e } }) => {
614
+ let t = e.htmlEmbeddedDataUriPolicy ?? "materialize";
615
+ return { deferredHtmlSeedLocalIds: (await Ye(e.item, t)).deferredHtmlSeedLocalIds };
616
+ });
617
+ //#endregion
618
+ //#region src/services/publish/actors/rewritingHtmlEmbedded.ts
619
+ function kn(e, t) {
620
+ let n = [], r = Math.min(e?.length ?? 0, t?.length ?? 0);
621
+ for (let i = 0; i < r; i++) {
622
+ let r = e[i], a = t[i], o = r.transaction?.id;
623
+ typeof o == "string" && o.length > 0 && n.push({
624
+ txId: o,
625
+ seedLocalId: a.seedLocalId,
626
+ versionLocalId: a.versionLocalId
627
+ });
628
+ }
629
+ return n;
630
+ }
631
+ var An = L(async ({ input: { context: e } }) => {
632
+ let t = kn(e.htmlEmbeddedPhase1ArweaveTransactions, e.htmlEmbeddedPhase1PublishUploads);
633
+ await Qe(e.item.seedLocalId, t);
634
+ }), jn = (e, t, n) => {
635
+ let r = [];
636
+ return e && r.push({
637
+ name: "Content-SHA-256",
638
+ value: e
639
+ }), t && r.push({
640
+ name: "Content-Type",
641
+ value: t
642
+ }), n?.length && r.push(...n), r;
643
+ }, Mn = async (e) => {
644
+ let t = (e instanceof Uint8Array, new Uint8Array(e)), n = await crypto.subtle.digest("SHA-256", t);
645
+ return Array.from(new Uint8Array(n)).map((e) => e.toString(16).padStart(2, "0")).join("");
646
+ }, Nn = {
647
+ png: "image/png",
648
+ jpg: "image/jpeg",
649
+ jpeg: "image/jpeg",
650
+ gif: "image/gif",
651
+ webp: "image/webp",
652
+ svg: "image/svg+xml",
653
+ html: "text/html",
654
+ htm: "text/html",
655
+ json: "application/json",
656
+ txt: "text/plain"
657
+ }, Pn = (e) => {
658
+ let t = e.split(".").pop()?.toLowerCase();
659
+ return t ? Nn[t] : void 0;
660
+ }, Fn = async (e) => typeof Blob < "u" && e instanceof Blob ? new Uint8Array(await e.arrayBuffer()) : new Uint8Array(e), In = (e) => {
661
+ switch (e) {
662
+ case "Image": return j.getFilesPath("images");
663
+ case "File": return j.getFilesPath("files");
664
+ case "Html": return j.getFilesPath("html");
665
+ case "Json": return j.getFilesPath("json");
666
+ default: return j.getFilesPath("images");
667
+ }
668
+ }, Ln = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]*)$/i;
669
+ function Rn(e) {
670
+ let t = Ln.exec((e ?? "").trim());
671
+ if (!t) return null;
672
+ try {
673
+ let e = t[1].toLowerCase().trim(), n = t[2].replace(/\s/g, "");
674
+ return {
675
+ mimeType: e,
676
+ bytes: Uint8Array.from(atob(n), (e) => e.charCodeAt(0))
677
+ };
678
+ } catch {
679
+ return null;
680
+ }
681
+ }
682
+ var zn = async (e, t, n, r) => {
683
+ let i = r?.arweaveUploadTags, a = e.itemProperty, o = [];
684
+ for (let t of e.childProperties) {
685
+ let e = t.localStoragePath;
686
+ e && !e.endsWith("undefined") && await j.pathExists(e) && o.push({
687
+ propertyName: t.propertyName,
688
+ localStoragePath: e
689
+ });
690
+ }
691
+ let s;
692
+ if ((!o || o.length === 0) && n?.localStoragePath) {
693
+ let e = n.localStoragePath;
694
+ if (e && !e.endsWith("undefined") && await j.pathExists(e)) try {
695
+ s = await Fn(await j.readFileAsBuffer(e));
696
+ } catch {
697
+ s = await Fn((await j.getFs()).readFileSync(e));
698
+ }
699
+ }
700
+ if (o.length > 0) {
701
+ let e = "===FILE_SEPARATOR===", t = "", n = await j.getFs();
702
+ for (let r of o) {
703
+ let i;
704
+ try {
705
+ i = await n.promises.readFile(r.localStoragePath);
706
+ } catch {
707
+ i = n.readFileSync(r.localStoragePath);
708
+ }
709
+ t += `${e}${r.propertyName}${e}${i}`;
710
+ }
711
+ s = typeof document < "u" ? new TextEncoder().encode(t) : new Uint8Array(Buffer.from(t));
712
+ }
713
+ if (!s) return t;
714
+ let c = new Uint8Array(s), l = await Mn(c), u;
715
+ o.length === 0 && n?.localStoragePath ? u = Pn(n.localStoragePath) : o.length > 0 && (u = "application/octet-stream");
716
+ let d = n ? n.localId : a.localId, f = n ? n.propertyName : a.propertyName;
717
+ return t.push({
718
+ data: c,
719
+ contentHash: l,
720
+ contentType: u,
721
+ tags: jn(l, u, i),
722
+ itemPropertyName: f,
723
+ itemPropertyLocalId: d,
724
+ seedLocalId: a.seedLocalId,
725
+ versionLocalId: a.versionLocalId
726
+ }), t;
727
+ }, Bn = async (e, t) => {
728
+ let n = [], r = t?.arweaveUploadTags;
729
+ for (let i of e) {
730
+ let e = i.getService().getSnapshot(), a = "context" in e ? e.context : null;
731
+ if (!a) continue;
732
+ let o = a.propertyValue, s = a.refResolvedValue;
733
+ if (!s) continue;
734
+ let { localId: c } = Ie(o ?? "");
735
+ if (!c) continue;
736
+ let l = i.propertyDef?.refValueType ?? i.propertyDef?.dataType ?? "Image";
737
+ if (l === Me.Html) {
738
+ if (t?.deferHtmlStorageSeedLocalIds?.includes(c) || t?.onlyHtmlStorageSeedLocalIds?.length && !t.onlyHtmlStorageSeedLocalIds.includes(c)) continue;
739
+ } else if (t?.onlyHtmlStorageSeedLocalIds?.length) continue;
740
+ let u = `${In(l)}/${s}`;
741
+ if (!await j.pathExists(u)) continue;
742
+ let d = await Fn(await j.readFileAsBuffer(u)), f = await Mn(d), p = Pn(s);
743
+ n.push({
744
+ data: d,
745
+ contentHash: f,
746
+ contentType: p,
747
+ tags: jn(f, p, r),
748
+ itemPropertyName: i.propertyName,
749
+ itemPropertyLocalId: i.localId,
750
+ seedLocalId: c,
751
+ versionLocalId: i.versionLocalId
752
+ });
753
+ }
754
+ return n;
755
+ };
756
+ async function Vn(e, t, n) {
757
+ let r = A.getAppDb();
758
+ if (!r || n?.onlyHtmlStorageSeedLocalIds?.length) return t;
759
+ let i = await r.select().from(He).where(z(He.parentSeedLocalId, e.seedLocalId)), a = new Set(t.map((e) => e.seedLocalId));
760
+ for (let e of i) {
761
+ if (a.has(e.imageSeedLocalId)) continue;
762
+ let r = await M.find({
763
+ seedLocalId: e.imageSeedLocalId,
764
+ modelName: "Image"
765
+ });
766
+ if (!r) continue;
767
+ let i = r.internalProperties.storageTransactionId ?? r.allProperties.storageTransactionId, o = i?.getService().getSnapshot(), s = o && "context" in o ? o.context : void 0, c = Rn(typeof s?.propertyValue == "string" ? s.propertyValue ?? "" : ""), l = [];
768
+ if (c && i && i.localId && i.versionLocalId) {
769
+ let e = await Mn(c.bytes);
770
+ l = [{
771
+ data: c.bytes,
772
+ contentHash: e,
773
+ contentType: c.mimeType,
774
+ tags: jn(e, c.mimeType, n?.arweaveUploadTags),
775
+ itemPropertyName: i.propertyName,
776
+ itemPropertyLocalId: i.localId,
777
+ seedLocalId: r.seedLocalId,
778
+ versionLocalId: i.versionLocalId
779
+ }];
780
+ }
781
+ for (let e of l) a.has(e.seedLocalId) || (t.push(e), a.add(e.seedLocalId));
782
+ }
783
+ return t;
784
+ }
785
+ var Hn = async (e, t = [], n, r) => {
786
+ let { itemUploadProperties: i, itemRelationProperties: a, itemImageProperties: o } = await Be(e);
787
+ if (!n && r?.onlyHtmlStorageSeedLocalIds?.length) {
788
+ let e = await Bn(o, r);
789
+ return t.push(...e), t;
790
+ }
791
+ for (let e of i) t = await zn(e, t, n, r);
792
+ let s = await Bn(o, r);
793
+ if (t.push(...s), !n && !r?.onlyHtmlStorageSeedLocalIds?.length && (t = await Vn(e, t, r)), r?.skipRelationRecursion) return t;
794
+ for (let e of a) {
795
+ let n = e.getService().getSnapshot(), i = "context" in n ? n.context : null;
796
+ if (!i) continue;
797
+ let a = i.propertyValue;
798
+ if (!a || e.uid) continue;
799
+ let { seedLocalId: o, seedUid: s } = Ze(Je(a) ?? "");
800
+ if (!o && !s) throw Error(`Invalid relation value for ${e.propertyName}: expected local seed id or 0x uid`);
801
+ let c = await M.find({
802
+ seedLocalId: o,
803
+ seedUid: s
804
+ });
805
+ if (!c) {
806
+ if (We(a)) continue;
807
+ throw Error(`No relatedItem found for ${e.propertyName}`);
808
+ }
809
+ t = await Hn(c, t, e, r);
810
+ }
811
+ return t;
812
+ }, Un = 3, Wn = new TextEncoder().encode("seed-recovery"), Gn = 32, Kn = 18446744073709551615n;
813
+ function qn(e, t, n) {
814
+ let r = F.solidityPackedKeccak256([
815
+ "uint256",
816
+ "address",
817
+ "uint64"
818
+ ], [
819
+ BigInt(t),
820
+ e,
821
+ n & Kn
822
+ ]);
823
+ return F.getBytes(r);
824
+ }
825
+ function Jn(e) {
826
+ if (e.length === 0) return new Uint8Array([0]);
827
+ if (e.length !== Gn) throw Error(`ANS-104 target/anchor must be empty or ${Gn} bytes, got ${e.length}`);
828
+ let t = /* @__PURE__ */ new Uint8Array(33);
829
+ return t[0] = 1, t.set(e, 1), t;
830
+ }
831
+ function Yn(e) {
832
+ return typeof e == "object" && !!e && "privateKey" in e && typeof e.privateKey == "string";
833
+ }
834
+ function Xn(e, t, n) {
835
+ let r = e >= 0 ? e << 1 : ~e << 1 | 1, i = n;
836
+ do {
837
+ let e = r & 127;
838
+ r >>>= 7, t[i++] = r ? e | 128 : e;
839
+ } while (r);
840
+ return i - n;
841
+ }
842
+ var Zn = (e) => {
843
+ if (!e?.length) return /* @__PURE__ */ new Uint8Array();
844
+ let t = new TextEncoder(), n = /* @__PURE__ */ new Uint8Array(16), r = [], i = (e) => {
845
+ let t = Xn(e, n, 0);
846
+ r.push(n.slice(0, t));
847
+ };
848
+ i(e.length);
849
+ for (let n of e) {
850
+ let e = t.encode(n.name), a = t.encode(n.value);
851
+ i(e.length), r.push(e), i(a.length), r.push(a);
852
+ }
853
+ i(0);
854
+ let a = r.reduce((e, t) => e + t.length, 0), o = new Uint8Array(a), s = 0;
855
+ for (let e of r) o.set(e, s), s += e.length;
856
+ return o;
857
+ }, Qn = (e) => {
858
+ let t = /* @__PURE__ */ new Uint8Array(8), n = new DataView(t.buffer);
859
+ return n.setUint32(0, e & 4294967295, !0), n.setUint32(4, Math.floor(e / 4294967296), !0), t;
860
+ };
861
+ async function $n(e) {
862
+ return new Uint8Array(await crypto.subtle.digest("SHA-384", e));
863
+ }
864
+ function er(e, t) {
865
+ let n = new Uint8Array(e.length + t.length);
866
+ return n.set(e, 0), n.set(t, e.length), n;
867
+ }
868
+ async function tr(e) {
869
+ let t = new TextEncoder();
870
+ if (Array.isArray(e)) {
871
+ let n = await $n(er(t.encode("list"), t.encode(e.length.toString())));
872
+ for (let t of e) {
873
+ let e = await tr(t);
874
+ n = await $n(er(n, e));
875
+ }
876
+ return n;
877
+ }
878
+ return $n(er(await $n(er(t.encode("blob"), t.encode(e.byteLength.toString()))), await $n(e)));
879
+ }
880
+ async function nr(e, t, n, r, i) {
881
+ let a = new TextEncoder();
882
+ return tr([
883
+ a.encode("dataitem"),
884
+ a.encode("1"),
885
+ a.encode(Un.toString()),
886
+ e,
887
+ t,
888
+ n,
889
+ r,
890
+ i
891
+ ]);
892
+ }
893
+ function rr(e, t, n, r, i) {
894
+ let a = Zn(t), o = Qn(t.length), s = Qn(a.length), c = [
895
+ e,
896
+ Jn(r),
897
+ Jn(i),
898
+ o,
899
+ s,
900
+ a,
901
+ n
902
+ ], l = c.reduce((e, t) => e + t.length, 0), u = new Uint8Array(l), d = 0;
903
+ for (let e of c) u.set(e, d), d += e.length;
904
+ return u;
905
+ }
906
+ async function ir(e, t) {
907
+ let n = /* @__PURE__ */ new Uint8Array(2);
908
+ new DataView(n.buffer).setUint16(0, Un, !0);
909
+ let r = 67 + t.length, i = new Uint8Array(r);
910
+ i.set(n, 0), i.set(e, 2), i.set(t, 67);
911
+ let a = await crypto.subtle.digest("SHA-256", new Uint8Array(e));
912
+ return {
913
+ id: ur(new Uint8Array(a)),
914
+ raw: i
915
+ };
916
+ }
917
+ var ar = async (e, t, n, r = /* @__PURE__ */ new Uint8Array()) => {
918
+ let i = F.SigningKey.computePublicKey(t.privateKey, !1), a = F.getBytes(i), o = Zn(n), s = /* @__PURE__ */ new Uint8Array(), c = await nr(a, s, r, o, e);
919
+ return ir(F.getBytes(await t.signMessage(c)), rr(a, n, e, s, r));
920
+ }, or = async (e, t, n, r = /* @__PURE__ */ new Uint8Array()) => {
921
+ let i = F.hexlify(Wn), a = await t.signMessage({ message: { raw: i } }), o = F.hashMessage(Wn), s = F.SigningKey.recoverPublicKey(o, a), c = F.getBytes(s), l = Zn(n), u = /* @__PURE__ */ new Uint8Array(), d = await nr(c, u, r, l, e), f = F.hexlify(d), p = await t.signMessage({ message: { raw: f } });
922
+ return ir(F.getBytes(p), rr(c, n, e, u, r));
923
+ };
924
+ function sr(e) {
925
+ if (e.length < 133) return null;
926
+ let t = e[132];
927
+ if (t !== 0 && t !== 1) return null;
928
+ let n = t === 1;
929
+ if (n && e.length < 165) return null;
930
+ let r = 132 + (n ? 33 : 1);
931
+ if (e.length < r + 1) return null;
932
+ let i = e[r];
933
+ if (i !== 0 && i !== 1) return null;
934
+ let a = i === 1;
935
+ return a && e.length < r + 33 ? null : r + (a ? 33 : 1);
936
+ }
937
+ function cr(e) {
938
+ let t = sr(e);
939
+ if (t == null) return null;
940
+ let n = e[132] === 1, r = n ? e.slice(133, 165) : /* @__PURE__ */ new Uint8Array(), i = 132 + (n ? 33 : 1);
941
+ return {
942
+ rawTarget: r,
943
+ rawAnchor: e[i] === 1 ? e.slice(i + 1, i + 33) : /* @__PURE__ */ new Uint8Array(),
944
+ tagsStart: t
945
+ };
946
+ }
947
+ async function lr(e) {
948
+ let t = cr(e);
949
+ if (t == null) return !1;
950
+ let { rawTarget: n, rawAnchor: r, tagsStart: i } = t, a = i + 16;
951
+ if (e.length < a) return !1;
952
+ let o = new DataView(e.buffer, e.byteOffset, e.byteLength);
953
+ if (o.getUint16(0, !0) !== Un) return !1;
954
+ 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;
955
+ if (e.length < u) return !1;
956
+ let d = e.slice(i + 16, u), f = e.slice(u);
957
+ try {
958
+ let e = await nr(c, n, r, d, f), t = F.hashMessage(e), i = F.hexlify(s), a = F.SigningKey.recoverPublicKey(t, i), o = F.getBytes(a);
959
+ return o.length === c.length && o.every((e, t) => e === c[t]);
960
+ } catch {
961
+ return !1;
962
+ }
963
+ }
964
+ var ur = (e) => {
965
+ let t = "";
966
+ for (let n of e) t += String.fromCharCode(n);
967
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
968
+ }, dr = R("seedProtocol:createArweaveDataItems");
969
+ async function fr(e, t, n) {
970
+ let r, a;
971
+ if (t) r = (await t(e)).map((e) => ({
972
+ transaction: { id: e.transaction.id },
973
+ versionId: e.versionId,
974
+ modelName: e.modelName
975
+ }));
976
+ else if (n) {
977
+ let t = [], o = Date.now();
978
+ for (let r = 0; r < e.length; r++) {
979
+ let a = e[r], s = a.tags, c = /* @__PURE__ */ new Uint8Array(8);
980
+ crypto.getRandomValues(c);
981
+ let l = (new DataView(c.buffer).getBigUint64(0, !1) ^ BigInt(r)) & 18446744073709551615n, u;
982
+ if (Yn(n)) {
983
+ let e = qn(n.address, o, l);
984
+ u = await ar(a.data, n, s, e);
985
+ } else {
986
+ let e = i(n) ? n.signer : n, t = qn(e.address, o, l);
987
+ u = await or(a.data, e, s, t);
988
+ }
989
+ if (!await lr(u.raw)) throw dr("DataItem verification failed: id=%s modelName=%s", u.id, a.itemPropertyName), Error(`DataItem signature verification failed for ${a.itemPropertyName}. The signing key may not match the owner, or the payload may have been modified.`);
990
+ t.push(u);
991
+ }
992
+ a = t, r = t.map((t, n) => ({
993
+ transaction: { id: t.id },
994
+ versionId: e[n]?.versionLocalId,
995
+ modelName: e[n]?.itemPropertyName
996
+ }));
997
+ } else throw Error("@seedprotocol/publish: useArweaveBundler requires signDataItems or dataItemSigner (pass at createPublish or in PublishProvider config)");
998
+ let o = e.map((e) => ({
999
+ itemPropertyName: e.itemPropertyName,
1000
+ itemPropertyLocalId: e.itemPropertyLocalId,
1001
+ seedLocalId: e.seedLocalId,
1002
+ versionLocalId: e.versionLocalId,
1003
+ transactionToSign: null
1004
+ }));
1005
+ return {
1006
+ arweaveTransactions: r,
1007
+ publishUploads: o,
1008
+ signedDataItems: a
1009
+ };
1010
+ }
1011
+ var pr = L(async ({ input: { context: e } }) => {
1012
+ let { item: t } = e;
1013
+ t.getPublishUploads || (t = await Cn(t.seedLocalId));
1014
+ let n = {};
1015
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
1016
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
1017
+ r?.length && (n.deferHtmlStorageSeedLocalIds = r);
1018
+ let i = await Hn(t, [], void 0, Object.keys(n).length ? n : void 0), a = T();
1019
+ return fr(i, e.signDataItems ?? a.signDataItems, e.dataItemSigner ?? a.dataItemSigner);
1020
+ });
1021
+ //#endregion
1022
+ //#region src/services/publish/actors/createArweaveDataItemsPhase2.ts
1023
+ async function mr(e) {
1024
+ let { item: t } = e;
1025
+ t.getPublishUploads || (t = await Cn(t.seedLocalId));
1026
+ let n = {};
1027
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
1028
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
1029
+ r?.length && (n.onlyHtmlStorageSeedLocalIds = r, n.skipRelationRecursion = !0);
1030
+ let i = await Hn(t, [], void 0, Object.keys(n).length ? n : void 0), a = T(), o = e.signDataItems ?? a.signDataItems, s = e.dataItemSigner ?? a.dataItemSigner;
1031
+ return i.length === 0 ? {
1032
+ arweaveTransactions: [],
1033
+ publishUploads: [],
1034
+ signedDataItems: void 0
1035
+ } : fr(i, o, s);
1036
+ }
1037
+ var hr = L(async ({ input: { context: e } }) => mr(e)), gr = 8192;
1038
+ function _r(e) {
1039
+ let t = new Uint8Array(e), n = "";
1040
+ for (let e = 0; e < t.length; e += gr) {
1041
+ let r = t.subarray(e, Math.min(e + gr, t.length));
1042
+ n += String.fromCharCode.apply(null, r);
1043
+ }
1044
+ return btoa(n);
1045
+ }
1046
+ async function vr(e) {
1047
+ let t = [];
1048
+ for (let [n, r] of e.entries()) {
1049
+ let e = r;
1050
+ if (typeof e == "object" && e && "arrayBuffer" in e) {
1051
+ let r = _r(await e.arrayBuffer()), i = e;
1052
+ t.push({
1053
+ name: n,
1054
+ value: r,
1055
+ encoding: "base64",
1056
+ filename: i.name || void 0
1057
+ });
1058
+ } else t.push({
1059
+ name: n,
1060
+ value: String(r)
1061
+ });
1062
+ }
1063
+ return t;
1064
+ }
1065
+ function yr(e, t, n) {
1066
+ 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;
1067
+ return i ? r.push(`: ${i}`) : n && r.push(` (${n})`), r.join("");
1068
+ }
1069
+ function br(e) {
1070
+ if (!e) return "Upload server unavailable. Please try again or check your connection.";
1071
+ let t = e.toLowerCase();
1072
+ 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.";
1073
+ }
1074
+ async function xr(e, t, n) {
1075
+ let r = typeof window < "u" ? window.Main : void 0;
1076
+ if (r?.uploadArweaveStart) {
1077
+ let n = await vr(t);
1078
+ return r.uploadArweaveStart(e, n);
1079
+ }
1080
+ let i = await fetch(e, {
1081
+ method: "POST",
1082
+ body: t
1083
+ }), a = await i.json().catch(() => ({}));
1084
+ return {
1085
+ status: i.status,
1086
+ body: a
1087
+ };
1088
+ }
1089
+ //#endregion
1090
+ //#region src/services/publish/actors/sendReimbursementRequest.ts
1091
+ var Sr = L(async ({ input: { context: e, event: t } }) => {
1092
+ let { arweaveTransactions: n = [], transactionKeys: r, reimbursementTransactionId: i } = e;
1093
+ if (i) return { transactionId: i };
1094
+ let a = n.map(({ transaction: e }) => e), o = new FormData();
1095
+ for (let e of a) {
1096
+ let { data: t, chunks: n, ...r } = e, i = t instanceof Blob ? t : new Blob([t]);
1097
+ o.append(`${e.id}-data`, i, `${e.id}-data`);
1098
+ let a = new Blob([JSON.stringify(n)], { type: "application/json" });
1099
+ o.append(`${e.id}-chunks`, a, `${e.id}-chunks`);
1100
+ let s = new Blob([JSON.stringify(r)], { type: "application/json" });
1101
+ o.append(`${e.id}-json`, s, `${e.id}-json`);
1102
+ }
1103
+ let { uploadApiBaseUrl: s } = T(), { status: c, body: l, message: u } = await xr(`${s}/api/upload/arweave/start`, o, s);
1104
+ if (c >= 300 || c < 200) {
1105
+ let e = c === 0 ? u : null;
1106
+ e && console.error("[upload]", e);
1107
+ let t = c === 0 ? br(e) : yr(c, l, r);
1108
+ throw Error(t);
1109
+ }
1110
+ return l;
1111
+ }), Cr = L(async ({ input: { context: e, event: t } }) => {
1112
+ let { requestResponse: n, reimbursementTransactionId: r } = e;
1113
+ if (!n) throw Error("No request response");
1114
+ if (!r) throw Error("No reimbursement transaction id");
1115
+ let i = B();
1116
+ await new Promise((e, t) => {
1117
+ let n = setInterval(async () => {
1118
+ let t;
1119
+ try {
1120
+ t = await i.transactions.getStatus(r);
1121
+ } catch {
1122
+ return;
1123
+ }
1124
+ t && t.confirmed && (clearInterval(n), e());
1125
+ }, 5e3);
1126
+ });
1127
+ }), G = R("seedProtocol:services:publish:actors");
1128
+ function wr(e) {
1129
+ if (e instanceof Uint8Array) return e;
1130
+ if (e instanceof ArrayBuffer) return new Uint8Array(e);
1131
+ throw Error("Transaction data must be Uint8Array or ArrayBuffer for upload resume");
1132
+ }
1133
+ var Tr = zt(({ sendBack: e, input: t }) => {
1134
+ let n = t.context, r = (n.arweaveTransactions ?? []).map(({ transaction: e }) => e), i = B(), a = n.uploaderState && typeof n.currentTransactionIndex == "number", o = a ? n.currentTransactionIndex : 0;
1135
+ (async () => {
1136
+ let t = r.length;
1137
+ for (let s = o; s < t; s++) {
1138
+ let c = r[s];
1139
+ if (!c) continue;
1140
+ let l = i.transactions.fromRaw(c);
1141
+ if (!await i.transactions.verify(l)) throw Error("Transaction verification failed");
1142
+ let u, d = n.uploaderState;
1143
+ if (a && s === o && d) {
1144
+ let e = l.data, t = e instanceof Uint8Array ? e : wr(e);
1145
+ u = await i.transactions.getUploader(d, t);
1146
+ } else u = await i.transactions.getUploader(l, l.data);
1147
+ for (; !u.isComplete;) {
1148
+ G("uploading chunk"), G(`uploader.pctComplete: ${u.pctComplete}`), G(`uploader.uploadedChunks: ${u.uploadedChunks}`), G(`uploader.totalChunks: ${u.totalChunks}`), G(u.lastResponseError), G(u.lastResponseStatus);
1149
+ try {
1150
+ await u.uploadChunk(), e({
1151
+ type: "updatePercentage",
1152
+ completionPercentage: Math.trunc((s + u.pctComplete / 100) / t * 100),
1153
+ uploaderState: u.toJSON(),
1154
+ currentTransactionIndex: s
1155
+ }), G(`${u.pctComplete}% complete, ${u.uploadedChunks}/${u.totalChunks}`);
1156
+ } catch (e) {
1157
+ G(e);
1158
+ }
1159
+ }
1160
+ }
1161
+ return "done";
1162
+ })().then((t) => {
1163
+ e({
1164
+ type: "uploadComplete",
1165
+ result: t
1166
+ });
1167
+ }).catch((t) => {
1168
+ e({
1169
+ type: "uploadError",
1170
+ error: t
1171
+ });
1172
+ });
1173
+ }), Er = 12e4, Dr = Function("s", "return import(s)"), Or = null, kr = async () => {
1174
+ if (Or) return Or;
1175
+ if (typeof window < "u") return null;
1176
+ try {
1177
+ let e = await Dr(`node:${["fs", "promises"].join("/")}`);
1178
+ return Or = {
1179
+ readFile: e.readFile,
1180
+ stat: e.stat
1181
+ }, Or;
1182
+ } catch {
1183
+ return null;
1184
+ }
1185
+ }, Ar = zt(({ sendBack: e, input: { context: t } }) => {
1186
+ let { signedDataItems: n } = t, { uploadApiBaseUrl: r, useArweaveBundler: i } = T();
1187
+ if (!i || !r) {
1188
+ e({
1189
+ type: "uploadError",
1190
+ error: /* @__PURE__ */ Error("Arweave bundler not configured. Set useArweaveBundler and uploadApiBaseUrl.")
1191
+ });
1192
+ return;
1193
+ }
1194
+ let a = `${r.replace(/\/$/, "")}/api/upload/arweave/batch`;
1195
+ if (!n || n.length === 0) {
1196
+ e({
1197
+ type: "uploadComplete",
1198
+ result: "done"
1199
+ });
1200
+ return;
1201
+ }
1202
+ (async () => {
1203
+ let e = n, t = e.length, r = Array(t).fill(null), i = async (e, t) => {
1204
+ let n = e;
1205
+ if (n.raw != null && (n.raw instanceof Uint8Array || Buffer.isBuffer(n.raw))) return n.raw.byteLength;
1206
+ if (typeof n.getRaw == "function") {
1207
+ let e = n.getRaw(), i = e instanceof Promise ? await e : e, a = Buffer.isBuffer(i) ? i : Buffer.from(i);
1208
+ return r[t] = a, a.length;
1209
+ }
1210
+ if (n.filename != null) {
1211
+ let e = await kr();
1212
+ if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
1213
+ return (await e.stat(n.filename)).size;
1214
+ }
1215
+ throw Error("Cannot get raw bytes from DataItem");
1216
+ }, o = 4, s = [];
1217
+ for (let n = 0; n < t; n++) {
1218
+ let t = await i(e[n], n);
1219
+ s.push(t), o += 4 + t;
1220
+ }
1221
+ let c = Buffer.alloc(o), l = 0;
1222
+ c.writeUInt32BE(t, l), l += 4;
1223
+ for (let n = 0; n < t; n++) {
1224
+ let t = s[n], i = r[n];
1225
+ if (i) {
1226
+ c.writeUInt32BE(t, l), l += 4, i.copy(c, l), l += t;
1227
+ continue;
1228
+ }
1229
+ let a = e[n];
1230
+ if (a.raw != null && (a.raw instanceof Uint8Array || Buffer.isBuffer(a.raw))) {
1231
+ c.writeUInt32BE(t, l), l += 4, c.set(a.raw, l), l += t;
1232
+ continue;
1233
+ }
1234
+ if (a.filename != null) {
1235
+ let e = await kr();
1236
+ if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
1237
+ let t = await e.readFile(a.filename);
1238
+ c.writeUInt32BE(t.length, l), l += 4, t.copy(c, l), l += t.length;
1239
+ continue;
1240
+ }
1241
+ throw Error("Cannot get raw bytes from DataItem");
1242
+ }
1243
+ let u = new AbortController(), d = setTimeout(() => u.abort(), Er), f;
1244
+ try {
1245
+ f = await fetch(a, {
1246
+ method: "POST",
1247
+ headers: { "Content-Type": "application/octet-stream" },
1248
+ body: c,
1249
+ signal: u.signal
1250
+ });
1251
+ } catch (e) {
1252
+ throw clearTimeout(d), e instanceof Error && e.name === "AbortError" ? Error(`Arweave batch upload timed out after ${Er / 1e3}s (upload API did not respond). Check uploadApiBaseUrl and network.`) : e;
1253
+ }
1254
+ if (clearTimeout(d), !f.ok) throw Error(`Batch upload failed: ${f.status}`);
1255
+ let p = await f.json().catch(() => ({})), m = typeof p.failed == "number" ? p.failed : 0;
1256
+ if (m > 0) {
1257
+ let e = p.total ?? "?", t = p.succeeded ?? 0;
1258
+ throw Error(`Arweave batch upload failed: ${m} of ${e} item(s) failed (${t} succeeded)`);
1259
+ }
1260
+ })().then(() => e({
1261
+ type: "uploadComplete",
1262
+ result: "done"
1263
+ })).catch((t) => e({
1264
+ type: "uploadError",
1265
+ error: t
1266
+ }));
1267
+ }), jr = 12000n;
1268
+ function Mr(e) {
1269
+ return "paymasterAndData" in e && e.paymasterAndData ? e.paymasterAndData : "0x";
1270
+ }
1271
+ function Nr(e, t, n) {
1272
+ return async (r) => {
1273
+ if (D("paymaster hook called (userOp from thirdweb; callGasLimit is tx.gas or 0)", {
1274
+ sender: r.sender,
1275
+ chainId: t.id,
1276
+ bundlerUrl: n ?? "(thirdweb default)",
1277
+ entryPoint: "initCode" in r ? "v0.6" : "v0.7",
1278
+ ...S(r)
1279
+ }), !("initCode" in r)) throw Error("@seedprotocol/publish: the managed account sent an EntryPoint v0.7 UserOp; its sponsored gas handling only supports EntryPoint v0.6.");
1280
+ let i = typeof e == "function" ? e() : e, a = await qt({
1281
+ userOp: r,
1282
+ client: i,
1283
+ chain: t
1284
+ });
1285
+ D("1/3 paymaster sponsored (limits here are ignored)", S(a));
1286
+ let o = {
1287
+ ...r,
1288
+ paymasterAndData: Mr(a)
1289
+ }, s = await Kt({
1290
+ userOp: o,
1291
+ options: {
1292
+ client: i,
1293
+ chain: t,
1294
+ bundlerUrl: n
1295
+ }
1296
+ });
1297
+ D("2/3 bundler estimate (callGasLimit includes thirdweb's +50k)", S(s));
1298
+ let c = s.callGasLimit * jr / 10000n;
1299
+ o.callGasLimit = r.callGasLimit > c ? r.callGasLimit : c, o.verificationGasLimit = s.verificationGasLimit, o.preVerificationGas = s.preVerificationGas, D("raised limits sent to the paymaster for signing", {
1300
+ ...S(o),
1301
+ headroomBps: jr,
1302
+ raisedEstimate: c,
1303
+ txGas: r.callGasLimit
1304
+ });
1305
+ let l = await qt({
1306
+ userOp: o,
1307
+ client: i,
1308
+ chain: t
1309
+ });
1310
+ if (D("3/3 paymaster signed", S(l)), l.callGasLimit && l.verificationGasLimit && l.preVerificationGas) return D("returning to thirdweb: the PAYMASTER's own limits (its signature covers them)", {
1311
+ ...S(l),
1312
+ requestedCallGasLimit: o.callGasLimit
1313
+ }), l;
1314
+ let u = {
1315
+ paymasterAndData: Mr(l),
1316
+ callGasLimit: o.callGasLimit,
1317
+ verificationGasLimit: o.verificationGasLimit,
1318
+ preVerificationGas: o.preVerificationGas
1319
+ };
1320
+ return D("returning to thirdweb: our raised limits (thirdweb should send exactly these)", S(u)), u;
1321
+ };
1322
+ }
1323
+ //#endregion
1324
+ //#region src/helpers/thirdweb.ts
1325
+ var Pr = /* @__PURE__ */ e({
1326
+ ExternalWalletsForDeploy: () => Jr,
1327
+ appMetadata: () => Zr,
1328
+ deployManagedAccountViaFactory: () => Xr,
1329
+ deploySmartWalletContract: () => Yr,
1330
+ getConnectedAccount: () => $r,
1331
+ getConnectedManagedAccountAddress: () => Qr,
1332
+ getConnectedModularAccount: () => ei,
1333
+ getManagedAccountWallet: () => ii,
1334
+ getModularAccountWallet: () => oi,
1335
+ getSharedPublishInAppWalletStorage: () => Rr,
1336
+ getSmartWalletAddressForAdmin: () => Wr,
1337
+ getWalletsForConnectButton: () => si,
1338
+ isSmartWalletDeployed: () => Gr,
1339
+ pollSmartWalletDeployed: () => Kr,
1340
+ resolveSmartWalletForPublish: () => qr,
1341
+ syncPublishInAppAuthToken: () => zr,
1342
+ useActiveSmartWalletContract: () => Ur,
1343
+ useLocalWalletAccount: () => Hr,
1344
+ wallets: () => Vr
1345
+ }), Fr = R("permaPress:helpers:thirdweb"), Ir = "seedProtocol:inAppPublish:", Lr = null;
1346
+ function Rr() {
1347
+ return Lr ||= {
1348
+ getItem: async (e) => typeof window > "u" ? null : localStorage.getItem(Ir + e),
1349
+ setItem: async (e, t) => {
1350
+ typeof window > "u" || localStorage.setItem(Ir + e, t);
1351
+ },
1352
+ removeItem: async (e) => {
1353
+ typeof window > "u" || localStorage.removeItem(Ir + e);
1354
+ }
1355
+ }, Lr;
1356
+ }
1357
+ function zr() {
1358
+ if (typeof window > "u") return {
1359
+ syncedBareToPrefixed: !1,
1360
+ syncedPrefixedToBare: !1
1361
+ };
1362
+ let { thirdwebClientId: e } = T();
1363
+ if (!e) return {
1364
+ syncedBareToPrefixed: !1,
1365
+ syncedPrefixedToBare: !1
1366
+ };
1367
+ try {
1368
+ let t = `walletToken-${e}`, n = `${Ir}${t}`, r = localStorage.getItem(t), i = localStorage.getItem(n), a = !1, o = !1;
1369
+ return r && !i && (localStorage.setItem(n, r), a = !0), i && !r && (localStorage.setItem(t, i), o = !0), i && r && r !== i && (localStorage.setItem(t, i), o = !0), {
1370
+ syncedBareToPrefixed: a,
1371
+ syncedPrefixedToBare: o
1372
+ };
1373
+ } catch {
1374
+ return {
1375
+ syncedBareToPrefixed: !1,
1376
+ syncedPrefixedToBare: !1
1377
+ };
1378
+ }
1379
+ }
1380
+ async function Br(e = O()) {
1381
+ zr();
1382
+ let t = ii();
1383
+ return await t.autoConnect({
1384
+ client: k(),
1385
+ chain: e
1386
+ }), t;
1387
+ }
1388
+ var Vr = [Ut("io.metamask")], Hr = () => {
1389
+ let [e, t] = At(null);
1390
+ return Ut("io.metamask"), kt(!1), Ot(() => {}, []), e;
1391
+ }, Ur = () => {
1392
+ let e = Gt(), [t, n] = At(null);
1393
+ return Ot(() => {
1394
+ e && e.address && n(dt({
1395
+ client: k(),
1396
+ chain: O(),
1397
+ address: e.address
1398
+ }));
1399
+ }, [e]), t;
1400
+ };
1401
+ async function Wr(e, t = "0x") {
1402
+ return _(e, t);
1403
+ }
1404
+ async function Gr(e) {
1405
+ return ce(e);
1406
+ }
1407
+ async function Kr(e, t, n) {
1408
+ return ve(e, t, n);
1409
+ }
1410
+ async function qr(e) {
1411
+ if (!e) return { needsDeploy: !0 };
1412
+ if (await Gr(e.address)) return {
1413
+ address: e.address,
1414
+ account: e
1415
+ };
1416
+ let t = await Wr(e.address);
1417
+ return await Gr(t) ? {
1418
+ address: t,
1419
+ account: e
1420
+ } : { needsDeploy: !0 };
1421
+ }
1422
+ var Jr = [Ut("io.metamask"), Ut("me.rainbow")], Yr = async (e) => {
1423
+ let t = dt({
1424
+ client: k(),
1425
+ chain: O(),
1426
+ address: e.address
1427
+ }), n = await ut({
1428
+ smartAccount: e,
1429
+ chain: O(),
1430
+ client: k(),
1431
+ accountContract: t
1432
+ });
1433
+ return Fr("deploySmartAccount result:", n), n;
1434
+ };
1435
+ async function Xr(e) {
1436
+ let { asThirdwebPublishWallet: t } = await import("./chainConfig-BJ8C_RRz.js").then((e) => e.g), n = t(e.signingAccount), r = b(e.adminAddress, e.data ?? "0x");
1437
+ await n.txSender.sendTransaction(r);
1438
+ }
1439
+ var Zr = {
1440
+ name: "Seed Protocol",
1441
+ description: "Seed Protocol",
1442
+ url: "https://seedprotocol.io"
1443
+ };
1444
+ async function Qr(e = O()) {
1445
+ let t = (await Br(e)).getAccount();
1446
+ if (!t) throw Error("Failed to get managed account");
1447
+ return t.address;
1448
+ }
1449
+ async function $r() {
1450
+ try {
1451
+ let e = oi();
1452
+ return await e.autoConnect({
1453
+ client: k(),
1454
+ chain: O()
1455
+ }), e.getAccount() ?? null;
1456
+ } catch {
1457
+ return null;
1458
+ }
1459
+ }
1460
+ async function ei() {
1461
+ return $r();
1462
+ }
1463
+ function ti(e) {
1464
+ let t = O(e).id, n = e.managedAccountFactoryAddress ?? h[t];
1465
+ if (!n) throw Error(`@seedprotocol/publish: no ManagedAccount factory is known for chain ${t}. Pass managedAccountFactoryAddress in publish config, or use the EOA / direct EAS path.`);
1466
+ return n;
1467
+ }
1468
+ var ni = [
1469
+ "farcaster",
1470
+ "email",
1471
+ "passkey",
1472
+ "phone"
1473
+ ], ri = null, ii = (e) => {
1474
+ let t = e ?? re(), n = O(t ?? void 0), r = t ? ti(t) : se(), { bundlerUrl: i, sponsorGas: a } = we(t);
1475
+ if (!i && ae(n)) throw Error(`@seedprotocol/publish: chain ${n.id} is local, so Thirdweb's hosted bundler cannot reach it. Set PublishConfig.thirdweb.bundlerUrl to the chain's bundler (seedTwinConfig does this for the twin).`);
1476
+ let o = [
1477
+ n.id,
1478
+ n.rpc,
1479
+ r,
1480
+ i ?? "",
1481
+ a
1482
+ ].join("|").toLowerCase();
1483
+ return ri?.key !== o && (D("managed wallet built", {
1484
+ chainId: n.id,
1485
+ sponsorGas: a,
1486
+ bundlerUrl: i ?? "(thirdweb default)",
1487
+ paymasterHook: a ? "installed" : "none (thirdweb estimates callGasLimit itself)"
1488
+ }), ri = {
1489
+ key: o,
1490
+ wallet: Wt({
1491
+ storage: Rr(),
1492
+ auth: { options: [...ni] },
1493
+ executionMode: {
1494
+ mode: "EIP4337",
1495
+ smartAccount: {
1496
+ chain: n,
1497
+ factoryAddress: r,
1498
+ sponsorGas: a,
1499
+ ...i || a ? { overrides: {
1500
+ ...i ? { bundlerUrl: i } : {},
1501
+ ...a ? { paymaster: Nr(k, n, i) } : {}
1502
+ } } : {}
1503
+ }
1504
+ }
1505
+ })
1506
+ }), ri.wallet;
1507
+ }, ai = null, oi = (e) => {
1508
+ let t = e ?? re(), { modularWalletMode: n, sponsorGas: r } = we(t);
1509
+ if (n === "EIP7702") {
1510
+ let e = O(t ?? void 0);
1511
+ if (ae(e)) throw Error(`@seedprotocol/publish: chain ${e.id} is local, and Thirdweb's EIP-7702 mode needs its hosted bundler, which cannot reach it. Set PublishConfig.thirdweb.modularWalletMode to 'EOA' and fund the in-app EOA (seedTwinConfig does this for the twin).`);
1512
+ }
1513
+ let i = `${n}|${r}`;
1514
+ return ai?.key !== i && (ai = {
1515
+ key: i,
1516
+ wallet: Wt({
1517
+ storage: Rr(),
1518
+ auth: { options: [...ni] },
1519
+ executionMode: n === "EOA" ? { mode: "EOA" } : {
1520
+ mode: "EIP7702",
1521
+ sponsorGas: r
1522
+ }
1523
+ })
1524
+ }), ai.wallet;
1525
+ }, si = (e) => {
1526
+ let t = e ?? re() ?? void 0;
1527
+ return t?.useModularExecutor ? [oi(t)] : [ii(t)];
1528
+ }, ci = "This ManagedAccount predates the Seed executor router extension, so the Seed executor cannot act for it and publish automation is not available for this account.", li = "The Seed executor is not installed for this ManagedAccount, so automation session keys cannot publish through it. The account admin installs it (installSeedExecutor), which enrollPublishAutomation does.", ui = "The Seed executor module is configured with a different EAS contract for this ManagedAccount than publish config. Automation session keys cannot change it.", di = "Could not read the Seed executor module state for this ManagedAccount.";
1529
+ function fi() {
1530
+ let e = T().modularAccountModuleContract?.trim();
1531
+ if (!e || !/^0x[0-9a-fA-F]{40}$/.test(e)) throw Error("@seedprotocol/publish: publish automation requires PublishConfig.modularAccountModuleContract (executor module).");
1532
+ return e;
1533
+ }
1534
+ async function pi(e) {
1535
+ return await ie(e) === null;
1536
+ }
1537
+ async function mi(e, t = {}) {
1538
+ let n = fi(), r = e, i, a;
1539
+ if (t.installedEas) i = !0, a = t.installedEas;
1540
+ else try {
1541
+ i = await Te(() => te(n, r), Boolean, { attempts: t.readAttempts ?? 1 }), a = i ? await x(n, r) : lt;
1542
+ } catch (t) {
1543
+ throw new w(di, "AUTOMATION_UNSUPPORTED_ACCOUNT", e, t);
1544
+ }
1545
+ if (!i) {
1546
+ let t = await pi(r) ? ci : li;
1547
+ throw new w(t, "AUTOMATION_UNSUPPORTED_ACCOUNT", e);
1548
+ }
1549
+ let o = T().easContractAddress?.toLowerCase();
1550
+ if (o && a.toLowerCase() !== o) throw new w(ui, "AUTOMATION_UNSUPPORTED_ACCOUNT", e);
1551
+ }
1552
+ function hi(e) {
1553
+ let t = e instanceof rt ? `${e.shortMessage} ${e.details} ${e.message}` : String(e);
1554
+ return /insufficient funds|insufficient balance/i.test(t);
1555
+ }
1556
+ async function gi(e) {
1557
+ let { managedAddress: t, tx: n, action: r, code: i = "AUTOMATION_PREFLIGHT_FAILED", requireSimulation: a = !0 } = e, o = (e) => Ce().call({
1558
+ account: t,
1559
+ to: n.to,
1560
+ data: n.data,
1561
+ value: n.value,
1562
+ ...e ? { stateOverride: [{
1563
+ address: t,
1564
+ balance: st("1000")
1565
+ }] } : {}
1566
+ });
1567
+ try {
1568
+ try {
1569
+ await o(!1);
1570
+ } catch (e) {
1571
+ if (!hi(e)) throw e;
1572
+ await o(!0);
1573
+ }
1574
+ } catch (e) {
1575
+ let n = Qt(e);
1576
+ if (!n && !a) return;
1577
+ let o = n ? en(Zt(e)) : "could not be simulated";
1578
+ throw new w(`Simulated ${r} from ${t} ${o}; nothing was sent.`, i, t, e);
1579
+ }
1580
+ }
1581
+ //#endregion
1582
+ //#region src/helpers/ensureExecutorModule.ts
1583
+ var _i = () => `The executor module could not be installed on your publishing account on ${E()}. Reconnect and try again, or contact support if this persists.`;
1584
+ async function vi(e, t, n) {
1585
+ let { modularAccountModuleContract: r } = n;
1586
+ if (!r || !await ce(e)) return { status: "skipped" };
1587
+ let i = await ie(e);
1588
+ return i ? yi(e, i.executor, r) : { status: "skipped" };
1589
+ }
1590
+ async function yi(e, t, n) {
1591
+ if (t.toLowerCase() !== n.trim().toLowerCase()) throw new w(`Your publishing account's Seed executor is ${t}, but publish config sets modularAccountModuleContract to ${n}. Point modularAccountModuleContract at the account's executor.`, "EXECUTOR_MODULE_NOT_INSTALLED", e);
1592
+ let r = e, i, a, o;
1593
+ try {
1594
+ if (await me(r, t)) return { status: "already-installed" };
1595
+ let { getManagedAccountAdmin: n } = await import("./managedAccountAdmin-DS6nniiu.js").then((e) => e.n), s = fe(await n(e));
1596
+ i = s.txSender.address;
1597
+ let c = await s.txSender.sendTransaction(f(r));
1598
+ o = c.transactionHash;
1599
+ try {
1600
+ a = await C(c.transactionHash);
1601
+ } catch (e) {
1602
+ if (!(e instanceof pe)) throw e;
1603
+ }
1604
+ } catch (t) {
1605
+ throw t instanceof w ? t : new w(_i(), "EXECUTOR_MODULE_NOT_INSTALLED", e, t);
1606
+ }
1607
+ let s = a && bi(a, r, t);
1608
+ if (s) return {
1609
+ status: "installed",
1610
+ eas: s,
1611
+ transactionHash: o
1612
+ };
1613
+ let c = await xi(r, i);
1614
+ if (c === "already-installed") return { status: "already-installed" };
1615
+ throw new w(`installSeedExecutor in transaction ${o} did not install the Seed executor on ${e}${c ? `: ${c}` : ""}.`, "EXECUTOR_MODULE_NOT_INSTALLED", e);
1616
+ }
1617
+ function bi(e, t, n) {
1618
+ if (P({
1619
+ abi: oe,
1620
+ eventName: "SeedExecutorInstalled",
1621
+ logs: e.logs,
1622
+ strict: !1
1623
+ }).some((e) => ot(e.address, t) && e.args.executor && ot(e.args.executor, n))) return P({
1624
+ abi: y,
1625
+ eventName: "ModuleInitialized",
1626
+ logs: e.logs,
1627
+ strict: !1
1628
+ }).find((e) => ot(e.address, n) && e.args.account && ot(e.args.account, t))?.args.eas;
1629
+ }
1630
+ async function xi(e, t) {
1631
+ try {
1632
+ await gi({
1633
+ managedAddress: t,
1634
+ tx: f(e),
1635
+ action: "installSeedExecutor",
1636
+ requireSimulation: !1
1637
+ });
1638
+ return;
1639
+ } catch (e) {
1640
+ let t = en(Zt(e instanceof w ? e.underlyingCause : e));
1641
+ return t === "reverted with SeedExecutorAlreadyInstalled" ? "already-installed" : t;
1642
+ }
1643
+ }
1644
+ //#endregion
1645
+ //#region src/helpers/ensureManagedAccountReady.ts
1646
+ var Si = () => `Could not connect the managed publishing account on ${E()}. Reconnect with the same sign-in method and try again.`, Ci = () => `Your publishing smart account is not deployed on ${E()} yet. Complete wallet setup, enable autoDeployManagedAccount in config if appropriate, then try again.`, wi = () => `The managed account could not be confirmed on ${E()} after deployment. Wait a moment and retry, or check your network connection.`, Ti = () => `Automatic deployment of the managed publishing account failed on ${E()}. Retry or deploy the account through your wallet provider.`;
1647
+ async function Ei() {
1648
+ let { useModularExecutor: e } = T();
1649
+ if (!e) return { kind: "skip" };
1650
+ let t;
1651
+ try {
1652
+ t = await Qr(O());
1653
+ } catch (e) {
1654
+ return {
1655
+ kind: "unavailable",
1656
+ cause: e
1657
+ };
1658
+ }
1659
+ return await Gr(t) ? {
1660
+ kind: "ready",
1661
+ managedAddress: t
1662
+ } : {
1663
+ kind: "not_deployed",
1664
+ managedAddress: t
1665
+ };
1666
+ }
1667
+ async function Di() {
1668
+ zr();
1669
+ let e = ii();
1670
+ await e.autoConnect({
1671
+ client: k(),
1672
+ chain: O()
1673
+ });
1674
+ let t = e.getAccount();
1675
+ if (!t) throw new w(Si(), "MANAGED_ACCOUNT_UNAVAILABLE");
1676
+ return t;
1677
+ }
1678
+ var Oi = 9e4;
1679
+ async function ki(e) {
1680
+ let t;
1681
+ try {
1682
+ await Promise.race([Yr(e), new Promise((e, n) => {
1683
+ t = setTimeout(() => n(/* @__PURE__ */ Error(`Managed account deploy timed out after ${Oi / 1e3}s`)), Oi);
1684
+ })]);
1685
+ } finally {
1686
+ t != null && clearTimeout(t);
1687
+ }
1688
+ }
1689
+ async function Ai(e) {
1690
+ let t = T(), n = await Di(), { fromThirdwebAccount: r } = await import("./chainConfig-BJ8C_RRz.js").then((e) => e.g), i = {
1691
+ managedAddress: e,
1692
+ managedSigningAccount: r(n)
1693
+ };
1694
+ try {
1695
+ if (t.deployManagedAccount) await t.deployManagedAccount(i);
1696
+ else {
1697
+ let e = await ei();
1698
+ if (e) {
1699
+ let t = oi();
1700
+ await t.autoConnect({
1701
+ client: k(),
1702
+ chain: O()
1703
+ }), await Xr({
1704
+ adminAddress: t.getAdminAccount?.()?.address ?? e.address,
1705
+ signingAccount: e
1706
+ });
1707
+ } else await ki(n);
1708
+ }
1709
+ } catch (t) {
1710
+ if (await Kr(e, /UserOp|user operation/i.test(Oe(t)) ? 15 : 5)) return;
1711
+ throw new w(Ti(), "MANAGED_ACCOUNT_NOT_DEPLOYED", e, t);
1712
+ }
1713
+ if (!await Kr(e)) throw new w(wi(), "MANAGED_ACCOUNT_NOT_DEPLOYED", e);
1714
+ }
1715
+ async function ji() {
1716
+ let e = T();
1717
+ if (!e.useModularExecutor) throw Error("runModularExecutorPublishPrep: useModularExecutor is false");
1718
+ let t = await Ei();
1719
+ if (t.kind === "unavailable") return {
1720
+ ok: !1,
1721
+ error: new w(Si(), "MANAGED_ACCOUNT_UNAVAILABLE", void 0, t.cause)
1722
+ };
1723
+ if (t.kind === "not_deployed") {
1724
+ if (e.autoDeployManagedAccount) {
1725
+ try {
1726
+ await Ai(t.managedAddress);
1727
+ } catch (e) {
1728
+ return {
1729
+ ok: !1,
1730
+ error: ne(e) ? e : new w(Ti(), "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress, e)
1731
+ };
1732
+ }
1733
+ if (t = await Ei(), t.kind !== "ready") return {
1734
+ ok: !1,
1735
+ error: new w(wi(), "MANAGED_ACCOUNT_NOT_DEPLOYED", t.kind === "not_deployed" ? t.managedAddress : void 0)
1736
+ };
1737
+ } else return {
1738
+ ok: !1,
1739
+ error: new w(Ci(), "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress)
1740
+ };
1741
+ }
1742
+ if (t.kind === "ready") {
1743
+ if (e.modularAccountModuleContract) try {
1744
+ let n = await Di();
1745
+ await vi(t.managedAddress, n, e);
1746
+ } catch (e) {
1747
+ console.warn(`[@seedprotocol/publish] Executor module setup failed on ${E()}; publishing continues, but publish automation needs it.`, e);
1748
+ }
1749
+ return {
1750
+ ok: !0,
1751
+ managedAddress: t.managedAddress
1752
+ };
1753
+ }
1754
+ throw Error("runModularExecutorPublishPrep: unexpected readiness state");
1755
+ }
1756
+ //#endregion
1757
+ //#region src/helpers/resolvePublishWallet.ts
1758
+ function Mi(e) {
1759
+ if (i(e.wallet)) return e.wallet;
1760
+ if (i(e.account)) return e.account;
1761
+ let t = he();
1762
+ if (t) return t;
1763
+ throw Error("@seedprotocol/publish: no PublishWallet available. Pass fromEthersWallet / fromEip1193Provider / fromThirdwebAccount, or call setPublishWallet / useSeedWallet.");
1764
+ }
1765
+ //#endregion
1766
+ //#region src/services/publish/actors/persistSeedUid.ts
1767
+ var Ni = R("seedProtocol:services:publish:actors:persistSeedUid"), Pi = "0x" + "0".repeat(64), Fi = 15e3;
1768
+ function Ii(e, t) {
1769
+ let n = e.seedLocalId, r = n ? t.find((e) => e?.localId === n) : void 0, i = r?.seedUid && r.seedUid !== Pi ? r.seedUid : t[0]?.seedUid;
1770
+ i && i !== Pi && (e.seedUid = i);
1771
+ }
1772
+ async function Li(e, t, n) {
1773
+ let r = e.persistSeedUid;
1774
+ if (typeof r != "function") return;
1775
+ let i = new Promise((e, t) => setTimeout(() => t(/* @__PURE__ */ Error("persistSeedUid timed out")), Fi));
1776
+ try {
1777
+ await Promise.race([r.call(e, t, n), i]);
1778
+ } catch (e) {
1779
+ Ni("persistSeedUid failed (attestations already on-chain):", e);
1780
+ }
1781
+ }
1782
+ //#endregion
1783
+ //#region src/services/publish/helpers/verifyArweaveTransactionsExist.ts
1784
+ async function Ri(e) {
1785
+ if (e.length === 0) return;
1786
+ let { arweaveUploadVerificationBaseUrl: t } = T(), n = await Promise.all(e.map((e) => Ve(t, e)));
1787
+ for (let t = 0; t < e.length; t++) {
1788
+ let r = e[t], i = n[t];
1789
+ if (i) {
1790
+ if (i.status === 404) throw Error(`Arweave transaction ${r} not found. Upload may have failed. Delete this publish record and try again.`);
1791
+ if (i.status !== 200) {
1792
+ let e = i.status === 504 ? "request timed out (upload service did not respond in time)" : `status: ${i.status}`;
1793
+ throw Error(`Arweave transaction ${r} is not yet available from the upload service (${e}). Wait and retry.`);
1794
+ }
1795
+ }
1796
+ }
1797
+ }
1798
+ //#endregion
1799
+ //#region src/services/publish/actors/seedUidHelpers.ts
1800
+ function K(e) {
1801
+ return e == null || e === "" ? W : ("0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(64, "0").slice(-64)).toLowerCase();
1802
+ }
1803
+ function zi(e, t, n) {
1804
+ if (!t || !e.logs?.length) return;
1805
+ let i = K(t);
1806
+ if (i === W) return;
1807
+ let a = n ? De : r;
1808
+ try {
1809
+ let t = P({
1810
+ abi: a,
1811
+ eventName: "CreatedAttestation",
1812
+ logs: e.logs,
1813
+ strict: !1
1814
+ });
1815
+ for (let e of t) {
1816
+ let t = e.args?.result;
1817
+ if (t?.attestationUid && K(t.schemaUid) === i) {
1818
+ let e = t.attestationUid;
1819
+ return e && K(e) !== W ? e : void 0;
1820
+ }
1821
+ }
1822
+ } catch {}
1823
+ }
1824
+ function Bi(e, t, n, i) {
1825
+ let a = t.toLowerCase(), o = e.logs?.filter((e) => e.address && e.address.toLowerCase() === a);
1826
+ if (!o?.length) return {};
1827
+ try {
1828
+ if (i) {
1829
+ let e = P({
1830
+ abi: De,
1831
+ eventName: "SeedPublished",
1832
+ logs: o,
1833
+ strict: !1
1834
+ })[0];
1835
+ if (!e) return {};
1836
+ let t = e.args;
1837
+ return {
1838
+ seedUid: t?.seedUid && K(t.seedUid) !== W ? t.seedUid : void 0,
1839
+ versionUid: t?.versionUid && K(t.versionUid) !== W ? t.versionUid : void 0
1840
+ };
1841
+ }
1842
+ let e = P({
1843
+ abi: r,
1844
+ eventName: "SeedPublished",
1845
+ logs: o,
1846
+ strict: !1
1847
+ })[0];
1848
+ if (!e) return {};
1849
+ let t = e.args?.returnedDataFromEAS;
1850
+ if (!t || t === "0x") return {};
1851
+ let a = it([{ type: "bytes32[]" }], t)[0];
1852
+ if (!a?.length) return {};
1853
+ let s = n, c = a[s], l = a[s + 1];
1854
+ return {
1855
+ seedUid: c && c !== W ? c : a.length === 1 && a[0] && a[0] !== W ? a[0] : void 0,
1856
+ versionUid: l && l !== W ? l : void 0
1857
+ };
1858
+ } catch {
1859
+ return {};
1860
+ }
1861
+ }
1862
+ function Vi(e, t, n, r) {
1863
+ return Bi(e, t, n, r).seedUid;
1864
+ }
1865
+ function Hi(e, t, n) {
1866
+ if (!t || !e.logs?.length) return;
1867
+ let i = K(t);
1868
+ if (i === W) return;
1869
+ let a = n ? De : r;
1870
+ try {
1871
+ let t = P({
1872
+ abi: a,
1873
+ eventName: "CreatedAttestation",
1874
+ logs: e.logs,
1875
+ strict: !1
1876
+ });
1877
+ for (let e of t) {
1878
+ let t = e.args?.result;
1879
+ if (t?.attestationUid && K(t.schemaUid) === i) {
1880
+ let e = t.attestationUid;
1881
+ return e && K(e) !== W ? e : void 0;
1882
+ }
1883
+ }
1884
+ } catch {}
1885
+ }
1886
+ function Ui(e, t) {
1887
+ if (!e.logs?.length) return [];
1888
+ let n = t ? De : r;
1889
+ try {
1890
+ let t = P({
1891
+ abi: n,
1892
+ eventName: "CreatedAttestation",
1893
+ logs: e.logs,
1894
+ strict: !1
1895
+ }), r = [];
1896
+ for (let e of t) {
1897
+ let t = e.args?.result;
1898
+ if (!t?.attestationUid) continue;
1899
+ let n = t.attestationUid;
1900
+ if (!n || K(n) === W) continue;
1901
+ let i = t.schemaUid;
1902
+ i && r.push({
1903
+ schemaUid: i,
1904
+ attestationUid: n
1905
+ });
1906
+ }
1907
+ return r;
1908
+ } catch {
1909
+ return [];
1910
+ }
1911
+ }
1912
+ function Wi(e, t) {
1913
+ let n = t.toLowerCase(), i = e.logs?.filter((e) => e.address && e.address.toLowerCase() === n);
1914
+ if (!i?.length) return [];
1915
+ try {
1916
+ let e = P({
1917
+ abi: r,
1918
+ eventName: "SeedPublished",
1919
+ logs: i,
1920
+ strict: !1
1921
+ })[0];
1922
+ if (!e) return [];
1923
+ let t = e.args?.returnedDataFromEAS;
1924
+ return !t || t === "0x" ? [] : it([{ type: "bytes32[]" }], t)[0] ?? [];
1925
+ } catch {
1926
+ return [];
1927
+ }
1928
+ }
1929
+ function Gi(e, t, n) {
1930
+ if (!n.length) return [];
1931
+ let r = Wi(e, t), i = n.length;
1932
+ if (r.length < i) return [];
1933
+ let a = [];
1934
+ for (let e = 0; e < i; e++) {
1935
+ let t = r[e], i = n[e]?.schema;
1936
+ t && K(t) !== W && i && a.push({
1937
+ schemaUid: i,
1938
+ attestationUid: t
1939
+ });
1940
+ }
1941
+ return a;
1942
+ }
1943
+ function Ki(e) {
1944
+ let t = Ui(e.receipt, e.useModularExecutor);
1945
+ if (t.length) return t;
1946
+ let n = p(e.receipt, e.easContractAddress);
1947
+ return n.length ? n.map((e) => ({
1948
+ schemaUid: e.schemaUid,
1949
+ attestationUid: e.uid
1950
+ })) : e.useModularExecutor ? [] : Gi(e.receipt, e.contractAddressForEvents, e.listOfAttestations ?? []);
1951
+ }
1952
+ //#endregion
1953
+ //#region src/services/publish/helpers/receiptAttestationMs.ts
1954
+ async function q(e) {
1955
+ let t = e?.blockNumber;
1956
+ return t == null ? Date.now() : await ye(t) ?? Date.now();
1957
+ }
1958
+ //#endregion
1959
+ //#region src/services/publish/actors/publishRequestNormalize.ts
1960
+ var qi = 64, J = (e) => {
1961
+ if (e == null) return "0x" + "0".repeat(qi);
1962
+ if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(qi, "0").slice(-64);
1963
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1964
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1965
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(qi, "0").slice(-64);
1966
+ }
1967
+ return "0x" + "0".repeat(qi);
1968
+ }, Ji = (e) => {
1969
+ if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
1970
+ if (typeof e == "string") {
1971
+ let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
1972
+ return "0x" + (t.length % 2 == 1 ? "0" + t : t);
1973
+ }
1974
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1975
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1976
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
1977
+ }
1978
+ return "0x";
1979
+ };
1980
+ function Yi(e) {
1981
+ let t = new Set(e.map((e) => e?.localId).filter((e) => !!e));
1982
+ return e.some((e) => (e?.listOfAttestations ?? []).some((e) => {
1983
+ let n = e;
1984
+ return n._unresolvedValue && t.has(n._unresolvedValue) ? !0 : Array.isArray(n._rawListIdsForResolve) ? n._rawListIdsForResolve.some((e) => e && t.has(String(e).trim())) : !1;
1985
+ }));
1986
+ }
1987
+ function Xi(e, t) {
1988
+ return (e ?? []).filter((e) => e.publishLocalId && t.has(e.publishLocalId));
1989
+ }
1990
+ var Zi = {
1991
+ recipient: Ft,
1992
+ expirationTime: BigInt(0),
1993
+ revocable: !0,
1994
+ refUID: W,
1995
+ data: W,
1996
+ value: BigInt(0)
1997
+ };
1998
+ function Qi(e) {
1999
+ let t = (e?.listOfAttestations ?? []).map((e) => {
2000
+ let t = Array.isArray(e?.data) ? e.data : [];
2001
+ return {
2002
+ schema: J(e?.schema),
2003
+ data: t.map((e) => ({
2004
+ ...e,
2005
+ refUID: J(e?.refUID),
2006
+ data: Ji(e?.data),
2007
+ expirationTime: e?.expirationTime == null ? BigInt(0) : BigInt(e.expirationTime),
2008
+ value: e?.value == null ? BigInt(0) : BigInt(e.value)
2009
+ })),
2010
+ ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
2011
+ ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {}
2012
+ };
2013
+ }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
2014
+ ...e,
2015
+ propertySchemaUid: J(e?.propertySchemaUid)
2016
+ }));
2017
+ return {
2018
+ ...e,
2019
+ seedUid: J(e?.seedUid),
2020
+ seedSchemaUid: J(e?.seedSchemaUid),
2021
+ versionUid: J(e?.versionUid),
2022
+ versionSchemaUid: J(e?.versionSchemaUid),
2023
+ listOfAttestations: t,
2024
+ propertiesToUpdate: n
2025
+ };
2026
+ }
2027
+ function $i(e, t) {
2028
+ for (let n of e) for (let e of n?.propertiesToUpdate ?? []) {
2029
+ let n = e?.publishLocalId, r = J(e?.propertySchemaUid);
2030
+ if (!n || !r) continue;
2031
+ let i = t.get(n);
2032
+ if (!i?.listOfAttestations) continue;
2033
+ let a = i.listOfAttestations.find((e) => J(e?.schema)?.toLowerCase() === r?.toLowerCase());
2034
+ a && (!Array.isArray(a.data) || a.data.length === 0) && (a.data = [{
2035
+ ...Zi,
2036
+ refUID: W
2037
+ }]);
2038
+ }
2039
+ }
2040
+ //#endregion
2041
+ //#region src/services/arweaveL1Finalize/enqueue.ts
2042
+ var ea = "pending_l1";
2043
+ async function ta(e) {
2044
+ let { useArweaveBundler: t } = T();
2045
+ if (!t) return;
2046
+ let n = e.arweaveTransactions ?? [], r = e.publishUploads ?? [];
2047
+ if (n.length === 0 || n.length !== r.length) return;
2048
+ let i = A.getAppDb();
2049
+ if (!i) return;
2050
+ let a = Date.now();
2051
+ for (let e = 0; e < n.length; e++) {
2052
+ let t = n[e], o = r[e];
2053
+ if (!o) continue;
2054
+ let s = t.transaction?.id;
2055
+ if (s && typeof s == "string") try {
2056
+ await i.insert(Pe).values({
2057
+ seedLocalId: o.seedLocalId,
2058
+ dataItemId: s,
2059
+ versionLocalId: o.versionLocalId ?? null,
2060
+ itemPropertyName: o.itemPropertyName ?? null,
2061
+ phase: ea,
2062
+ createdAt: a,
2063
+ updatedAt: a
2064
+ }).onConflictDoNothing();
2065
+ } catch {}
2066
+ }
2067
+ }
2068
+ //#endregion
2069
+ //#region src/helpers/ensureManagedAccountEasConfigured.ts
2070
+ var na = () => `Could not verify or set the EAS contract address on your publishing account on ${E()}.`, ra = "ManagedAccount EAS pointer does not match publish config. Configure EAS with the user’s ManagedAccount wallet before automation publish (session keys cannot call setEas).", ia = (e) => `Your publishing account's Seed extension uses EAS ${e}, but publish config sets easContractAddress to a different contract. The extension's EAS is fixed at deployment; fix easContractAddress.`;
2071
+ function aa(e) {
2072
+ return e.toLowerCase();
2073
+ }
2074
+ function oa(e) {
2075
+ let { easContractAddress: t } = T(), n = aa(t);
2076
+ if (!n || n === aa(lt)) throw new w("Publish config is missing a valid easContractAddress.", "MANAGED_ACCOUNT_SET_EAS_FAILED", e);
2077
+ return n;
2078
+ }
2079
+ async function sa(e) {
2080
+ try {
2081
+ let t = await le(e);
2082
+ return aa(typeof t == "string" ? t : String(t));
2083
+ } catch (t) {
2084
+ throw new w(na(), "MANAGED_ACCOUNT_SET_EAS_FAILED", e, t);
2085
+ }
2086
+ }
2087
+ async function ca(e) {
2088
+ let t = oa(e);
2089
+ if (await sa(e) !== t) throw new w(ra, "MANAGED_ACCOUNT_SET_EAS_FAILED", e);
2090
+ }
2091
+ async function la(e, t) {
2092
+ let n = oa(e), r = await sa(e);
2093
+ if (r !== n) {
2094
+ if (r !== aa(lt)) throw new w(ia(r), "MANAGED_ACCOUNT_SET_EAS_FAILED", e);
2095
+ try {
2096
+ let n = typeof t == "function" ? await t() : t, r = i(n) ? n.txSender : _e(n) ? n : (() => {
2097
+ throw Error("@seedprotocol/publish: ensureManagedAccountEasConfigured requires PublishWallet or SeedTxSender");
2098
+ })(), { easContractAddress: a } = T(), o = ee(e, a), s = await r.sendTransaction(o);
2099
+ await C(s.transactionHash);
2100
+ } catch (t) {
2101
+ throw new w(na(), "MANAGED_ACCOUNT_SET_EAS_FAILED", e, t);
2102
+ }
2103
+ }
2104
+ }
2105
+ //#endregion
2106
+ //#region src/services/publish/actors/createAttestations.ts
2107
+ var ua = R("seedProtocol:services:publish:actors");
2108
+ function da(e) {
2109
+ return !!e && /^0x[0-9a-fA-F]{40}$/.test(e.trim());
2110
+ }
2111
+ function fa(e) {
2112
+ let { useModularExecutor: t, publisherAddress: n, modularAccountModuleContract: r, managedAddress: i, routeToExecutorModule: a } = e;
2113
+ if (t) {
2114
+ if (!i) throw Error("resolvePublishRouting: managedAddress is required when useModularExecutor is true");
2115
+ let e = r?.trim();
2116
+ if (a) {
2117
+ if (!da(e)) throw Error("resolvePublishRouting: modularAccountModuleContract is required when routeToExecutorModule is true");
2118
+ return {
2119
+ txTargetAddress: e,
2120
+ contractAddressForEvents: e
2121
+ };
2122
+ }
2123
+ return {
2124
+ txTargetAddress: i,
2125
+ contractAddressForEvents: e || i
2126
+ };
2127
+ }
2128
+ return {
2129
+ txTargetAddress: n,
2130
+ contractAddressForEvents: n
2131
+ };
2132
+ }
2133
+ async function pa(e) {
2134
+ let { receipt: t, seedLocalId: n, versionSchemaUid: r, contractAddressForEvents: i, listOfAttestationsCount: a, useModularExecutor: o, publisherAddress: s } = e;
2135
+ if (!n) return;
2136
+ let c = Hi(t, r, o) ?? Bi(t, i, a, o).versionUid, l = c ? J(c) : void 0;
2137
+ if (!l || l === W) return;
2138
+ let u = await q(t);
2139
+ await tt({
2140
+ seedLocalId: n,
2141
+ versionUid: l,
2142
+ publisher: s,
2143
+ attestationCreatedAt: u
2144
+ });
2145
+ }
2146
+ function ma(e, t) {
2147
+ return !e || !t ? !1 : J(e).toLowerCase() === J(t).toLowerCase();
2148
+ }
2149
+ function ha(e, t, n) {
2150
+ return !n || t >= e.length ? t : ma(e[t]?.schemaUid, n) ? t + 1 : t;
2151
+ }
2152
+ async function ga(e) {
2153
+ let { receipt: t, normalizedRequests: n, useModularExecutor: r, contractAddressForEvents: i } = e, { easContractAddress: a } = T(), o = Ki({
2154
+ receipt: t,
2155
+ useModularExecutor: r,
2156
+ easContractAddress: a,
2157
+ contractAddressForEvents: i,
2158
+ listOfAttestations: n.flatMap((e) => e.listOfAttestations ?? [])
2159
+ });
2160
+ if (!o.length) {
2161
+ ua("persistPropertyMetadataUidsFromContractReceipt: no property attestation pairs");
2162
+ return;
2163
+ }
2164
+ let s = await q(t), c = 0;
2165
+ for (let e of n) {
2166
+ let n = e.listOfAttestations ?? [];
2167
+ if ((!e.seedUid || J(e.seedUid) === W) && (c = ha(o, c, e.seedSchemaUid)), c = ha(o, c, e.versionSchemaUid), !n.length) continue;
2168
+ let a = n.length, l = o.slice(c, c + a);
2169
+ if (c += a, !l.length) continue;
2170
+ let u = Math.min(l.length, a), d = e.versionUid && J(e.versionUid) !== W ? J(e.versionUid) : void 0;
2171
+ d ||= Hi(t, e.versionSchemaUid, r) ?? Bi(t, i, a, r).versionUid, await Ne({
2172
+ seedLocalId: e.localId,
2173
+ attestationCreatedAtMs: s ?? null,
2174
+ versionUid: d && J(d) !== W ? J(d) : null,
2175
+ pairs: l.slice(0, u).map((e, t) => ({
2176
+ schemaUid: e.schemaUid,
2177
+ attestationUid: e.attestationUid,
2178
+ propertyName: typeof n[t]?._propertyName == "string" && n[t]._propertyName !== "" ? n[t]._propertyName : void 0
2179
+ }))
2180
+ });
2181
+ }
2182
+ }
2183
+ var _a = L(async ({ input: { context: e } }) => {
2184
+ let { address: t, account: n, wallet: r } = e, i = e.arweaveTransactions ?? [], a = e.publishUploads ?? [], { item: o } = e, { modularAccountModuleContract: s, useModularExecutor: l } = T();
2185
+ if (!t || typeof t != "string" || !t.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
2186
+ if (!r && !n) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
2187
+ if (!l && !await ce(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.");
2188
+ if (!o?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
2189
+ if (typeof o.getPublishUploads != "function" && (o = await Cn(o.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.");
2190
+ let u = fa({
2191
+ useModularExecutor: !1,
2192
+ publisherAddress: t
2193
+ }), d = Mi(e), f = !1;
2194
+ await xn(o, d, { managedAddress: t });
2195
+ let p = i.map((e, t) => {
2196
+ let n = e.transaction?.id;
2197
+ 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.");
2198
+ let r = a[t];
2199
+ if (!r) throw Error("Publish upload index mismatch");
2200
+ return {
2201
+ ...r,
2202
+ txId: n
2203
+ };
2204
+ });
2205
+ await Ri(p.map((e) => e.txId));
2206
+ let m = await o.getPublishPayload(p, { publishMode: e.publishMode ?? "patch" }), h = Array.isArray(m) ? m : [m];
2207
+ if (l) {
2208
+ let e = d?.signer?.address, n = !1;
2209
+ if (t && e) {
2210
+ let { isAutomationSessionActive: r } = await import("./ensureAutomationSessionKey-DwRm4YMJ.js").then((e) => e.n);
2211
+ n = await r(t, e);
2212
+ }
2213
+ if (n) {
2214
+ let e = s?.trim();
2215
+ if (!da(e)) throw Error("@seedprotocol/publish: automation publish requires PublishConfig.modularAccountModuleContract (executor module). Session keys are module-only and cannot call the ManagedAccount directly.");
2216
+ u = fa({
2217
+ useModularExecutor: l,
2218
+ publisherAddress: t,
2219
+ modularAccountModuleContract: e,
2220
+ managedAddress: t,
2221
+ routeToExecutorModule: !0
2222
+ }), f = !0, await mi(t);
2223
+ } else {
2224
+ let e = await ji();
2225
+ if (!e.ok) throw e.error;
2226
+ u = fa({
2227
+ useModularExecutor: l,
2228
+ publisherAddress: t,
2229
+ modularAccountModuleContract: s,
2230
+ managedAddress: e.managedAddress
2231
+ });
2232
+ let { ensureModularPublishBootstrap: n } = await import("./ensureModularPublishBootstrap-DRFhp-O2.js").then((e) => e.n), { fromThirdwebAccount: r } = await import("./chainConfig-BJ8C_RRz.js").then((e) => e.g);
2233
+ d = r(await n(e.managedAddress));
2234
+ }
2235
+ } else await la(t, d);
2236
+ let g = async (e) => {
2237
+ let n = u.txTargetAddress, r = f ? c(n, e, 5000000n) : be(n, e, 5000000n);
2238
+ await gi(f ? {
2239
+ managedAddress: t,
2240
+ tx: r,
2241
+ action: "multiPublish via the executor module"
2242
+ } : {
2243
+ managedAddress: d.txSender.address,
2244
+ tx: r,
2245
+ action: "multiPublish",
2246
+ code: "PUBLISH_PREFLIGHT_FAILED",
2247
+ requireSimulation: !1
2248
+ });
2249
+ try {
2250
+ return await d.txSender.sendTransaction(r);
2251
+ } catch (e) {
2252
+ throw sn(e, d.txSender.address);
2253
+ }
2254
+ }, _ = h.length > 1 && Yi(h), v, y = null, b = [];
2255
+ if (_) {
2256
+ let e = structuredClone(h), n = {};
2257
+ for (let r = 0; r < e.length; r++) {
2258
+ e = await Xe(e, n);
2259
+ let i = e[r], a = /* @__PURE__ */ new Set([i.localId]), o = Qi({
2260
+ ...i,
2261
+ propertiesToUpdate: Xi(i.propertiesToUpdate, a)
2262
+ }), s = /* @__PURE__ */ new Map([[o.localId, o]]);
2263
+ $i([o], s);
2264
+ let c = await g([o]), d = await C(c.transactionHash);
2265
+ if (!d) throw Error("Failed to send transaction");
2266
+ y = d;
2267
+ let f = o?.listOfAttestations?.length ?? 0;
2268
+ for (let e of Ui(d, l)) e.attestationUid && b.push(e.attestationUid);
2269
+ await pa({
2270
+ receipt: d,
2271
+ seedLocalId: i.localId,
2272
+ versionSchemaUid: o.versionSchemaUid,
2273
+ contractAddressForEvents: u.contractAddressForEvents,
2274
+ listOfAttestationsCount: f,
2275
+ useModularExecutor: l,
2276
+ publisherAddress: t
2277
+ });
2278
+ let p = !o.seedUid || J(o.seedUid) === W, m = o?.seedSchemaUid;
2279
+ if (p) {
2280
+ let t = zi(d, m, l) ?? Vi(d, u.contractAddressForEvents, f, l);
2281
+ t && (n[i.localId] = t, e[r] = {
2282
+ ...e[r],
2283
+ seedUid: t
2284
+ }, b.push(t));
2285
+ }
2286
+ await ga({
2287
+ receipt: d,
2288
+ normalizedRequests: [o],
2289
+ useModularExecutor: l,
2290
+ contractAddressForEvents: u.contractAddressForEvents
2291
+ });
2292
+ }
2293
+ for (let t of e) {
2294
+ let e = t?.localId, r = t?.seedUid;
2295
+ e && r && J(r) !== W && (n[e] = J(r));
2296
+ }
2297
+ v = (await Xe(structuredClone(h), n)).map((e) => Qi({
2298
+ ...e,
2299
+ seedUid: n[e.localId] ?? e.seedUid
2300
+ }));
2301
+ } else {
2302
+ let e = h.map((e) => Qi(e));
2303
+ $i(e, new Map(e.map((e) => [e?.localId, e])));
2304
+ let n = Array.isArray(m) ? e : [e[0]], r = await g(n), i = await C(r.transactionHash);
2305
+ if (!i) throw Error("Failed to send transaction");
2306
+ y = i;
2307
+ for (let e of Ui(i, l)) e.attestationUid && b.push(e.attestationUid);
2308
+ let a = e.find((e) => e?.localId === o.seedLocalId) ?? e[0];
2309
+ await pa({
2310
+ receipt: i,
2311
+ seedLocalId: a?.localId,
2312
+ versionSchemaUid: a?.versionSchemaUid,
2313
+ contractAddressForEvents: u.contractAddressForEvents,
2314
+ listOfAttestationsCount: a?.listOfAttestations?.length ?? 0,
2315
+ useModularExecutor: l,
2316
+ publisherAddress: t
2317
+ }), await ga({
2318
+ receipt: i,
2319
+ normalizedRequests: n,
2320
+ useModularExecutor: l,
2321
+ contractAddressForEvents: u.contractAddressForEvents
2322
+ });
2323
+ let s = e[0], c = s?.seedUid, d = c === W || !c, f = s?.listOfAttestations?.length ?? 0, p = s?.seedSchemaUid, _ = d ? zi(i, p, l) ?? Vi(i, u.contractAddressForEvents, f, l) : void 0;
2324
+ _ && b.push(_), v = _ && e.length > 0 ? [{
2325
+ ...e[0],
2326
+ seedUid: _
2327
+ }, ...e.slice(1)] : e;
2328
+ }
2329
+ Ii(o, v);
2330
+ let x = o, ee = v.find((e) => e?.localId === o.seedLocalId)?.seedUid;
2331
+ ee && ee !== W && await Li(x, t, y ? await q(y) : void 0), ua("requestData", m), ta(e);
2332
+ try {
2333
+ let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk");
2334
+ await e(o.seedLocalId);
2335
+ } catch {}
2336
+ let { collectPublishedBatch: te } = await import("./collectBatchUids-CnIe9jUB.js").then((e) => e.t), S = v.find((e) => e?.localId === o.seedLocalId) ?? v[0];
2337
+ for (let e of v) e?.seedUid && b.push(String(e.seedUid)), e?.versionUid && b.push(String(e.versionUid));
2338
+ return {
2339
+ easPayload: m,
2340
+ publishedBatch: S?.seedUid ? te({
2341
+ seedUid: String(S.seedUid),
2342
+ versionUid: S.versionUid ? String(S.versionUid) : void 0,
2343
+ extraUids: b
2344
+ }) : null
2345
+ };
2346
+ }), va = R("seedProtocol:services:publish:verifyAttestations"), ya = "0x" + "0".repeat(64), ba = 64, xa = (e) => e == null ? "0x" + "0".repeat(ba) : typeof e == "string" ? "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(ba, "0").slice(-64) : "0x" + "0".repeat(ba), Sa = 5e3, Ca = 6;
2347
+ async function wa({ normalizedRequests: e, item: t }) {
2348
+ let n = t.seedLocalId;
2349
+ for (let t of e) {
2350
+ if (t.listOfAttestations.length === 0 || t.versionUid === ya) continue;
2351
+ let e = t.listOfAttestations.map((e) => xa(e.schema).toLowerCase()), r = [], i;
2352
+ for (let e = 1; e <= Ca; e++) try {
2353
+ e > 1 && await new Promise((e) => setTimeout(e, Sa)), r = await Re({ versionUids: [t.versionUid] });
2354
+ break;
2355
+ } catch (t) {
2356
+ if (i = t, va("verifyAttestations attempt %d failed:", e, t), e === Ca) throw va("verifyAttestations: giving up after %d attempts", Ca), i;
2357
+ }
2358
+ let a = r.map((e) => e.schemaId ? xa(e.schemaId).toLowerCase() : "").filter(Boolean), o = new Set(a);
2359
+ if (e.filter((e) => !o.has(e)).length > 0) throw new de(`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 ${a.length}. Use PublishManager.retryAttestations('${n}') to retry.`, n, e, a, "METADATA_PROPERTIES_MISSING");
2360
+ }
2361
+ }
2362
+ //#endregion
2363
+ //#region src/services/publish/actors/createAttestationsDirectToEas.ts
2364
+ var Ta = R("seedProtocol:services:publish:createAttestationsDirectToEas"), Ea = 64, Y = (e) => {
2365
+ if (e == null) return "0x" + "0".repeat(Ea);
2366
+ if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(Ea, "0").slice(-64);
2367
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
2368
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
2369
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(Ea, "0").slice(-64);
2370
+ }
2371
+ return "0x" + "0".repeat(Ea);
2372
+ }, Da = (e) => {
2373
+ if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
2374
+ if (typeof e == "string") {
2375
+ let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
2376
+ return "0x" + (t.length % 2 == 1 ? "0" + t : t);
2377
+ }
2378
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
2379
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
2380
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
2381
+ }
2382
+ return "0x";
2383
+ }, Oa = async (e) => {
2384
+ let t;
2385
+ try {
2386
+ t = await M.find({ seedLocalId: e });
2387
+ } catch {}
2388
+ return t || new Promise((t) => {
2389
+ let n = setInterval(() => {
2390
+ try {
2391
+ M.find({ seedLocalId: e }).then((e) => {
2392
+ e && (clearInterval(n), t(e));
2393
+ });
2394
+ } catch {}
2395
+ }, 200);
2396
+ });
2397
+ }, ka = L(async ({ input: { context: e, event: t } }) => {
2398
+ let { address: n, account: r, wallet: i } = e, a = e.arweaveTransactions ?? [], o = e.publishUploads ?? [], { item: c } = e;
2399
+ if (!n || typeof n != "string" || !n.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
2400
+ if (!i && !r) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
2401
+ if (!c?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
2402
+ if (typeof c.getPublishUploads != "function" && (c = await Oa(c.seedLocalId)), a.length !== o.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.");
2403
+ let l = Mi(e), d = l.txSender;
2404
+ await xn(c, l, { managedAddress: n });
2405
+ let f = a.map((e, t) => {
2406
+ let n = e.transaction?.id;
2407
+ 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.");
2408
+ let r = o[t];
2409
+ if (!r) throw Error("Publish upload index mismatch");
2410
+ return {
2411
+ ...r,
2412
+ txId: n
2413
+ };
2414
+ });
2415
+ await Ri(f.map((e) => e.txId));
2416
+ let m = await c.getPublishPayload(f, { publishMode: e.publishMode ?? "patch" }), h = (Array.isArray(m) ? m : [m]).map((e) => {
2417
+ let t = (e?.listOfAttestations ?? []).map((e) => {
2418
+ let t = Array.isArray(e?.data) ? e.data : [];
2419
+ return {
2420
+ schema: Y(e?.schema),
2421
+ data: t.map((e) => ({
2422
+ ...e,
2423
+ refUID: Y(e?.refUID),
2424
+ data: Da(e?.data)
2425
+ })),
2426
+ ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
2427
+ ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {}
2428
+ };
2429
+ }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
2430
+ ...e,
2431
+ propertySchemaUid: Y(e?.propertySchemaUid)
2432
+ }));
2433
+ return {
2434
+ ...e,
2435
+ seedUid: Y(e?.seedUid),
2436
+ seedSchemaUid: Y(e?.seedSchemaUid),
2437
+ versionUid: Y(e?.versionUid),
2438
+ versionSchemaUid: Y(e?.versionSchemaUid),
2439
+ listOfAttestations: t,
2440
+ propertiesToUpdate: n
2441
+ };
2442
+ }), _ = new Map(h.map((e) => [e.localId, e])), y = {
2443
+ recipient: Ft,
2444
+ expirationTime: BigInt(0),
2445
+ revocable: !0,
2446
+ refUID: g,
2447
+ data: g,
2448
+ value: BigInt(0)
2449
+ };
2450
+ for (let e of h) for (let t of e.propertiesToUpdate ?? []) {
2451
+ let e = t.publishLocalId, n = Y(t.propertySchemaUid);
2452
+ if (!e || !n) continue;
2453
+ let r = _.get(e);
2454
+ if (!r?.listOfAttestations) continue;
2455
+ let i = r.listOfAttestations.find((e) => Y(e?.schema)?.toLowerCase() === n?.toLowerCase());
2456
+ i && (!Array.isArray(i.data) || i.data.length === 0) && (i.data = [{
2457
+ ...y,
2458
+ refUID: g
2459
+ }]);
2460
+ }
2461
+ let b = Date.now(), x = [];
2462
+ for (let e = 0; e < h.length; e++) {
2463
+ let t = h[e], r = t.seedUid, i = t.versionUid;
2464
+ if (r === g) {
2465
+ let e = v({
2466
+ schema: t.seedSchemaUid,
2467
+ data: {
2468
+ refUID: g,
2469
+ data: s(t.seedSchemaUid),
2470
+ revocable: t.seedIsRevocable
2471
+ }
2472
+ }), n = await d.sendTransaction(e), i = await C(n.transactionHash);
2473
+ if (!i) throw Error("Failed to create Seed attestation");
2474
+ b = await q(i);
2475
+ let { easContractAddress: a } = T(), o = u(i, a);
2476
+ if (!o || o === g) throw Error("Failed to get Seed UID from attestation receipt");
2477
+ r = o, t.seedUid = o, x.push(o), Ta("created Seed attestation", r);
2478
+ } else r !== g && x.push(r);
2479
+ if (r !== g && i === g) {
2480
+ let e = v({
2481
+ schema: t.versionSchemaUid,
2482
+ data: {
2483
+ refUID: r,
2484
+ data: s(t.versionSchemaUid),
2485
+ revocable: !0
2486
+ }
2487
+ }), a = await d.sendTransaction(e), o = await C(a.transactionHash);
2488
+ if (!o) throw Error("Failed to create Version attestation");
2489
+ b = await q(o);
2490
+ let { easContractAddress: c } = T(), l = u(o, c);
2491
+ if (!l || l === g) throw Error("Failed to get Version UID from attestation receipt");
2492
+ i = l, t.versionUid = l, x.push(l), await tt({
2493
+ seedLocalId: t.localId,
2494
+ versionUid: l,
2495
+ publisher: n,
2496
+ attestationCreatedAt: b
2497
+ }), Ta("created Version attestation", i);
2498
+ } else i !== g && x.push(i);
2499
+ for (let e of t.listOfAttestations) for (let t of e.data) t.refUID = i;
2500
+ for (let e of t.propertiesToUpdate ?? []) {
2501
+ let t = _.get(e.publishLocalId);
2502
+ if (!t?.listOfAttestations) continue;
2503
+ let n = Y(e.propertySchemaUid), i = t.listOfAttestations.find((e) => Y(e?.schema)?.toLowerCase() === n?.toLowerCase());
2504
+ i?.data?.[0] && (i.data[0].data = s(r));
2505
+ }
2506
+ let a = t.listOfAttestations.map((e) => ({
2507
+ schema: e.schema,
2508
+ data: e.data.map((e) => ({
2509
+ recipient: e.recipient ?? Ft,
2510
+ expirationTime: e.expirationTime ?? 0n,
2511
+ revocable: e.revocable ?? !0,
2512
+ refUID: e.refUID ?? g,
2513
+ data: e.data ?? "0x",
2514
+ value: e.value ?? 0n
2515
+ }))
2516
+ }));
2517
+ if (a.length > 0) {
2518
+ let n = ke(a), r = await d.sendTransaction(n), o = await C(r.transactionHash);
2519
+ if (!o) throw Error("Failed to create property attestations");
2520
+ b = await q(o), Ta("created property attestations for request", e);
2521
+ let { easContractAddress: s } = T(), c = p(o, s);
2522
+ for (let e of c) e.uid && x.push(e.uid);
2523
+ let l = t.listOfAttestations, u = c.length === l.length;
2524
+ await Ne({
2525
+ seedLocalId: t.localId,
2526
+ attestationCreatedAtMs: b ?? null,
2527
+ versionUid: i === g ? null : i,
2528
+ pairs: c.map((e, t) => ({
2529
+ schemaUid: e.schemaUid,
2530
+ attestationUid: e.uid,
2531
+ propertyName: u && typeof l[t]?._propertyName == "string" && l[t]._propertyName !== "" ? l[t]._propertyName : void 0
2532
+ }))
2533
+ });
2534
+ }
2535
+ }
2536
+ Ii(c, h);
2537
+ let ee = c;
2538
+ h[0]?.seedUid && h[0].seedUid !== g && await Li(ee, n, b);
2539
+ try {
2540
+ await wa({
2541
+ normalizedRequests: h,
2542
+ item: c
2543
+ });
2544
+ } catch (e) {
2545
+ throw e instanceof de || Ta("verifyAttestations failed (non-verification error):", e), e;
2546
+ }
2547
+ Ta("direct EAS publish complete"), ta(e);
2548
+ try {
2549
+ let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk");
2550
+ await e(c.seedLocalId);
2551
+ } catch {}
2552
+ let { collectPublishedBatch: te } = await import("./collectBatchUids-CnIe9jUB.js").then((e) => e.t), S = h.find((e) => e?.localId === c.seedLocalId) ?? h[0];
2553
+ return {
2554
+ easPayload: m,
2555
+ publishedBatch: S?.seedUid ? te({
2556
+ seedUid: String(S.seedUid),
2557
+ versionUid: S.versionUid ? String(S.versionUid) : void 0,
2558
+ extraUids: x
2559
+ }) : null
2560
+ };
2561
+ }), Aa = async (e) => {
2562
+ let t;
2563
+ try {
2564
+ t = await M.find({ seedLocalId: e });
2565
+ } catch {}
2566
+ return t || new Promise((t) => {
2567
+ let n = setInterval(() => {
2568
+ M.find({ seedLocalId: e }).then((e) => {
2569
+ e && (clearInterval(n), t(e));
2570
+ }).catch(() => {});
2571
+ }, 200);
2572
+ });
2573
+ };
2574
+ async function ja(e) {
2575
+ let t = typeof e.getPublishUploads == "function" ? e : await Aa(e.seedLocalId);
2576
+ return await Ge(t);
2577
+ }
2578
+ //#endregion
2579
+ //#region src/services/publish/actors/checking.ts
2580
+ var X = /* @__PURE__ */ new Set();
2581
+ async function Ma(e) {
2582
+ let t = T();
2583
+ return t.useDirectEas ? "directEas" : t.useModularExecutor || await ce(e) ? "multiPublish" : "directEas";
2584
+ }
2585
+ var Na = zt(({ sendBack: e, input: { context: t } }) => {
2586
+ let { item: n, account: r, wallet: i, publishMode: a, address: o } = t;
2587
+ return (async () => {
2588
+ if (!await Ue(n)) {
2589
+ e({ type: "notOwner" });
2590
+ return;
2591
+ }
2592
+ if (X.has(n.seedLocalId)) {
2593
+ e({ type: "redundantPublishProcess" });
2594
+ return;
2595
+ }
2596
+ X.add(n.seedLocalId);
2597
+ try {
2598
+ await Fe(), await ue();
2599
+ let t = i ?? r;
2600
+ t && await xn(n, t, { managedAddress: typeof o == "string" ? o : void 0 });
2601
+ let s = await nt(n, [], { publishMode: a ?? "patch" });
2602
+ if (!s.isValid) {
2603
+ X.delete(n.seedLocalId), e({
2604
+ type: "validationFailed",
2605
+ errors: s.errors
2606
+ });
2607
+ return;
2608
+ }
2609
+ if (!o || typeof o != "string" || !o.trim()) {
2610
+ X.delete(n.seedLocalId), e({
2611
+ type: "validationFailed",
2612
+ errors: [{ message: "No publisher address for publish. Connect a wallet and try again." }]
2613
+ });
2614
+ return;
2615
+ }
2616
+ let c;
2617
+ try {
2618
+ c = await Ma(o.trim());
2619
+ } catch (t) {
2620
+ X.delete(n.seedLocalId), e({
2621
+ type: "checkingFailed",
2622
+ error: Error(`Could not verify whether the publisher is a deployed contract on ${E()}. Check your RPC connection and retry.`, { cause: t })
2623
+ });
2624
+ return;
2625
+ }
2626
+ let l = await ja(n), u = T().useArweaveBundler, d = { attestationStrategy: c };
2627
+ e(l ? u ? {
2628
+ type: "validPublishProcessBundler",
2629
+ ...d
2630
+ } : {
2631
+ type: "validPublishProcess",
2632
+ ...d
2633
+ } : {
2634
+ type: "skipArweave",
2635
+ ...d
2636
+ });
2637
+ } catch (t) {
2638
+ X.delete(n.seedLocalId), console.error("[checking] failed", t), e({
2639
+ type: "checkingFailed",
2640
+ error: t instanceof Error ? t : Error(String(t))
2641
+ });
2642
+ }
2643
+ })().catch((t) => {
2644
+ X.delete(n.seedLocalId), console.error("[checking] unhandled rejection", t), e({
2645
+ type: "checkingFailed",
2646
+ error: t instanceof Error ? t : Error(String(t))
2647
+ });
2648
+ }), () => {
2649
+ X.delete(n.seedLocalId);
2650
+ };
2651
+ }), { SUCCESS: Pa, FAILURE: Z } = ge;
2652
+ function Fa(e) {
2653
+ let t = e.attestationStrategy;
2654
+ return t === "directEas" || t !== "multiPublish" && T().useDirectEas;
2655
+ }
2656
+ function Ia(e) {
2657
+ let t = e.attestationStrategy;
2658
+ return t === "multiPublish" || t !== "directEas" && !T().useDirectEas;
2659
+ }
2660
+ function Q(e) {
2661
+ let t = e;
2662
+ return t.error ?? t.data;
2663
+ }
2664
+ var La = Bt({
2665
+ types: {
2666
+ context: {},
2667
+ input: {}
2668
+ },
2669
+ actors: {
2670
+ createArweaveTransactions: En,
2671
+ createArweaveTransactionsPhase2: Dn,
2672
+ createArweaveDataItems: pr,
2673
+ createArweaveDataItemsPhase2: hr,
2674
+ sendReimbursementRequest: Sr,
2675
+ pollForConfirmation: Cr,
2676
+ uploadData: Tr,
2677
+ uploadViaBundler: Ar,
2678
+ createAttestations: _a,
2679
+ createAttestationsDirectToEas: ka,
2680
+ checking: Na,
2681
+ preparingHtmlEmbedded: On,
2682
+ rewritingHtmlEmbedded: An
2683
+ },
2684
+ actions: {
2685
+ handleError: ({ event: e }) => {
2686
+ let t = Q(e);
2687
+ t == null ? console.error("Unknown error (full event):", e) : console.error(t);
2688
+ },
2689
+ assignErrorCreatingArweaveTransactions: I({
2690
+ error: ({ event: e }) => Q(e),
2691
+ errorStep: () => "creatingArweaveTransactions"
2692
+ }),
2693
+ assignErrorCreatingArweaveDataItems: I({
2694
+ error: ({ event: e }) => Q(e),
2695
+ errorStep: () => "creatingArweaveDataItems"
2696
+ }),
2697
+ assignErrorSendingReimbursementRequest: I({
2698
+ error: ({ event: e }) => Q(e),
2699
+ errorStep: () => "sendingReimbursementRequest"
2700
+ }),
2701
+ assignErrorPollingForConfirmation: I({
2702
+ error: ({ event: e }) => Q(e),
2703
+ errorStep: () => "pollingForConfirmation"
2704
+ }),
2705
+ assignErrorUploadingData: I({
2706
+ error: ({ event: e }) => Q(e),
2707
+ errorStep: () => "uploadingData"
2708
+ }),
2709
+ assignErrorPreparingHtmlEmbedded: I({
2710
+ error: ({ event: e }) => Q(e),
2711
+ errorStep: () => "preparingHtmlEmbedded"
2712
+ }),
2713
+ assignErrorRewritingHtmlEmbedded: I({
2714
+ error: ({ event: e }) => Q(e),
2715
+ errorStep: () => "rewritingHtmlEmbedded"
2716
+ }),
2717
+ assignErrorCreatingArweaveTransactionsPhase2: I({
2718
+ error: ({ event: e }) => Q(e),
2719
+ errorStep: () => "creatingArweaveTransactionsPhase2"
2720
+ }),
2721
+ assignErrorUploadingDataPhase2: I({
2722
+ error: ({ event: e }) => Q(e),
2723
+ errorStep: () => "uploadingDataPhase2"
2724
+ }),
2725
+ assignErrorUploadingViaBundler: I({
2726
+ error: ({ event: e }) => Q(e),
2727
+ errorStep: () => "uploadingViaBundler"
2728
+ }),
2729
+ assignErrorCreatingArweaveDataItemsPhase2: I({
2730
+ error: ({ event: e }) => Q(e),
2731
+ errorStep: () => "creatingArweaveDataItemsPhase2"
2732
+ }),
2733
+ assignErrorUploadingViaBundlerPhase2: I({
2734
+ error: ({ event: e }) => Q(e),
2735
+ errorStep: () => "uploadingViaBundlerPhase2"
2736
+ }),
2737
+ assignErrorCreatingAttestations: I({
2738
+ error: ({ event: e }) => Q(e),
2739
+ errorStep: () => "creatingAttestations"
2740
+ }),
2741
+ assignErrorCreatingAttestationsDirectToEas: I({
2742
+ error: ({ event: e }) => Q(e),
2743
+ errorStep: () => "creatingAttestationsDirectToEas"
2744
+ }),
2745
+ assignAccountFromRetry: I({
2746
+ wallet: ({ event: e }) => {
2747
+ let t = e;
2748
+ return t.wallet ?? t.account;
2749
+ },
2750
+ account: ({ event: e }) => {
2751
+ let t = e;
2752
+ return t.wallet ?? t.account;
2753
+ }
2754
+ }),
2755
+ assignErrorNotOwner: I({
2756
+ error: () => /* @__PURE__ */ Error("Item is read-only: you do not own this item. Only the publisher can publish."),
2757
+ errorStep: () => "checking"
2758
+ }),
2759
+ assignErrorValidationFailed: I({
2760
+ error: ({ event: e }) => {
2761
+ 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);
2762
+ return r.validationErrors = t, r;
2763
+ },
2764
+ errorStep: () => "checking"
2765
+ }),
2766
+ assignErrorCheckingFailed: I({
2767
+ error: ({ event: e }) => {
2768
+ let t = e.error;
2769
+ return t instanceof Error ? t : Error(String(t ?? "Publish check failed"));
2770
+ },
2771
+ errorStep: () => "checking"
2772
+ })
2773
+ }
2774
+ }).createMachine({
2775
+ id: "publish",
2776
+ initial: "checking",
2777
+ context: ({ input: e }) => e,
2778
+ states: {
2779
+ checking: {
2780
+ on: {
2781
+ notOwner: {
2782
+ target: Z,
2783
+ actions: ["assignErrorNotOwner", "handleError"]
2784
+ },
2785
+ validationFailed: {
2786
+ target: Z,
2787
+ actions: ["assignErrorValidationFailed", "handleError"]
2788
+ },
2789
+ redundantPublishProcess: { target: "stopping" },
2790
+ checkingFailed: {
2791
+ target: Z,
2792
+ actions: ["assignErrorCheckingFailed", "handleError"]
2793
+ },
2794
+ validPublishProcess: {
2795
+ target: "preparingHtmlEmbedded",
2796
+ actions: I({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2797
+ },
2798
+ validPublishProcessBundler: {
2799
+ target: "preparingHtmlEmbedded",
2800
+ actions: I({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2801
+ },
2802
+ skipArweave: [{
2803
+ guard: ({ context: e }) => Fa(e),
2804
+ target: "creatingAttestationsDirectToEas",
2805
+ actions: I({
2806
+ arweaveTransactions: () => [],
2807
+ publishUploads: () => [],
2808
+ attestationStrategy: ({ event: e }) => e.attestationStrategy
2809
+ })
2810
+ }, {
2811
+ guard: ({ context: e }) => Ia(e),
2812
+ target: "creatingAttestations",
2813
+ actions: I({
2814
+ arweaveTransactions: () => [],
2815
+ publishUploads: () => [],
2816
+ attestationStrategy: ({ event: e }) => e.attestationStrategy
2817
+ })
2818
+ }]
2819
+ },
2820
+ invoke: {
2821
+ src: "checking",
2822
+ input: ({ context: e }) => ({ context: e })
2823
+ }
2824
+ },
2825
+ preparingHtmlEmbedded: { invoke: {
2826
+ src: "preparingHtmlEmbedded",
2827
+ input: ({ context: e }) => ({ context: e }),
2828
+ onDone: [{
2829
+ guard: () => T().useArweaveBundler,
2830
+ target: "creatingArweaveDataItems",
2831
+ actions: I({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2832
+ }, {
2833
+ target: "creatingArweaveTransactions",
2834
+ actions: I({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2835
+ }],
2836
+ onError: {
2837
+ target: Z,
2838
+ actions: ["assignErrorPreparingHtmlEmbedded", "handleError"]
2839
+ }
2840
+ } },
2841
+ creatingArweaveTransactions: { invoke: {
2842
+ src: "createArweaveTransactions",
2843
+ input: ({ context: e, event: t }) => ({
2844
+ context: e,
2845
+ event: t
2846
+ }),
2847
+ onDone: {
2848
+ target: "sendingReimbursementRequest",
2849
+ actions: I({
2850
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2851
+ publishUploads: ({ event: e }) => e.output.publishUploads
2852
+ })
2853
+ },
2854
+ onError: {
2855
+ target: "failure",
2856
+ actions: ["assignErrorCreatingArweaveTransactions", "handleError"]
2857
+ }
2858
+ } },
2859
+ creatingArweaveDataItems: { invoke: {
2860
+ src: "createArweaveDataItems",
2861
+ input: ({ context: e, event: t }) => ({
2862
+ context: e,
2863
+ event: t
2864
+ }),
2865
+ onDone: {
2866
+ target: "uploadingViaBundler",
2867
+ actions: I({
2868
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2869
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2870
+ signedDataItems: ({ event: e }) => e.output.signedDataItems
2871
+ })
2872
+ },
2873
+ onError: {
2874
+ target: "failure",
2875
+ actions: ["assignErrorCreatingArweaveDataItems", "handleError"]
2876
+ }
2877
+ } },
2878
+ sendingReimbursementRequest: { invoke: {
2879
+ src: "sendReimbursementRequest",
2880
+ input: ({ context: e, event: t }) => ({
2881
+ context: e,
2882
+ event: t
2883
+ }),
2884
+ onDone: {
2885
+ target: "pollingForConfirmation",
2886
+ actions: I({
2887
+ requestResponse: ({ event: e }) => e.output,
2888
+ reimbursementTransactionId: ({ event: e }) => e.output.transactionId
2889
+ })
2890
+ },
2891
+ onError: {
2892
+ target: "failure",
2893
+ actions: ["assignErrorSendingReimbursementRequest", "handleError"]
2894
+ }
2895
+ } },
2896
+ pollingForConfirmation: { invoke: {
2897
+ src: "pollForConfirmation",
2898
+ input: ({ context: e, event: t }) => ({
2899
+ context: e,
2900
+ event: t
2901
+ }),
2902
+ onDone: {
2903
+ target: "uploadingData",
2904
+ actions: I({ reimbursementConfirmed: !0 })
2905
+ },
2906
+ onError: {
2907
+ target: "failure",
2908
+ actions: ["assignErrorPollingForConfirmation", "handleError"]
2909
+ }
2910
+ } },
2911
+ uploadingViaBundler: {
2912
+ on: {
2913
+ uploadComplete: [
2914
+ {
2915
+ guard: ({ context: e }) => Fa(e),
2916
+ target: "creatingAttestationsDirectToEas",
2917
+ actions: I({
2918
+ completionPercentage: 100,
2919
+ signedDataItems: () => void 0,
2920
+ arweaveUploadData: () => void 0
2921
+ })
2922
+ },
2923
+ {
2924
+ guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
2925
+ target: "rewritingHtmlEmbedded",
2926
+ actions: I({
2927
+ htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
2928
+ htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? [],
2929
+ signedDataItems: () => void 0,
2930
+ arweaveUploadData: () => void 0
2931
+ })
2932
+ },
2933
+ {
2934
+ guard: ({ context: e }) => Ia(e),
2935
+ target: "creatingAttestations",
2936
+ actions: I({
2937
+ completionPercentage: 100,
2938
+ signedDataItems: () => void 0,
2939
+ arweaveUploadData: () => void 0
2940
+ })
2941
+ }
2942
+ ],
2943
+ uploadError: {
2944
+ target: "failure",
2945
+ actions: ["assignErrorUploadingViaBundler", "handleError"]
2946
+ }
2947
+ },
2948
+ invoke: {
2949
+ src: "uploadViaBundler",
2950
+ input: ({ context: e }) => ({ context: e })
2951
+ }
2952
+ },
2953
+ creatingArweaveDataItemsPhase2: { invoke: {
2954
+ src: "createArweaveDataItemsPhase2",
2955
+ input: ({ context: e, event: t }) => ({
2956
+ context: e,
2957
+ event: t
2958
+ }),
2959
+ onDone: {
2960
+ target: "uploadingViaBundlerPhase2",
2961
+ actions: I({
2962
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2963
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2964
+ signedDataItems: ({ event: e }) => e.output.signedDataItems,
2965
+ uploaderState: () => void 0,
2966
+ currentTransactionIndex: () => void 0
2967
+ })
2968
+ },
2969
+ onError: {
2970
+ target: Z,
2971
+ actions: ["assignErrorCreatingArweaveDataItemsPhase2", "handleError"]
2972
+ }
2973
+ } },
2974
+ uploadingViaBundlerPhase2: {
2975
+ on: {
2976
+ uploadComplete: [{
2977
+ guard: ({ context: e }) => Fa(e),
2978
+ target: "creatingAttestationsDirectToEas",
2979
+ actions: I({
2980
+ completionPercentage: 100,
2981
+ signedDataItems: () => void 0,
2982
+ arweaveUploadData: () => void 0
2983
+ })
2984
+ }, {
2985
+ guard: ({ context: e }) => Ia(e),
2986
+ target: "creatingAttestations",
2987
+ actions: I({
2988
+ completionPercentage: 100,
2989
+ signedDataItems: () => void 0,
2990
+ arweaveUploadData: () => void 0,
2991
+ publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
2992
+ arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
2993
+ })
2994
+ }],
2995
+ uploadError: {
2996
+ target: Z,
2997
+ actions: ["assignErrorUploadingViaBundlerPhase2", "handleError"]
2998
+ }
2999
+ },
3000
+ invoke: {
3001
+ src: "uploadViaBundler",
3002
+ input: ({ context: e }) => ({ context: e })
3003
+ }
3004
+ },
3005
+ uploadingData: {
3006
+ on: {
3007
+ updatePercentage: { actions: I({
3008
+ completionPercentage: ({ event: e }) => e.completionPercentage,
3009
+ uploaderState: ({ event: e }) => e.uploaderState,
3010
+ currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
3011
+ }) },
3012
+ uploadComplete: [
3013
+ {
3014
+ guard: ({ context: e }) => Fa(e),
3015
+ target: "creatingAttestationsDirectToEas",
3016
+ actions: I({ completionPercentage: 100 })
3017
+ },
3018
+ {
3019
+ guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
3020
+ target: "rewritingHtmlEmbedded",
3021
+ actions: I({
3022
+ htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
3023
+ htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? []
3024
+ })
3025
+ },
3026
+ {
3027
+ guard: ({ context: e }) => Ia(e),
3028
+ target: "creatingAttestations",
3029
+ actions: I({ completionPercentage: 100 })
3030
+ }
3031
+ ],
3032
+ uploadError: {
3033
+ target: "failure",
3034
+ actions: ["assignErrorUploadingData", "handleError"]
3035
+ }
3036
+ },
3037
+ invoke: {
3038
+ src: "uploadData",
3039
+ input: ({ context: e }) => ({ context: e })
3040
+ }
3041
+ },
3042
+ rewritingHtmlEmbedded: { invoke: {
3043
+ src: "rewritingHtmlEmbedded",
3044
+ input: ({ context: e }) => ({ context: e }),
3045
+ onDone: [{
3046
+ guard: () => !T().useArweaveBundler,
3047
+ target: "creatingArweaveTransactionsPhase2"
3048
+ }, {
3049
+ guard: () => T().useArweaveBundler,
3050
+ target: "creatingArweaveDataItemsPhase2"
3051
+ }],
3052
+ onError: {
3053
+ target: Z,
3054
+ actions: ["assignErrorRewritingHtmlEmbedded", "handleError"]
3055
+ }
3056
+ } },
3057
+ creatingArweaveTransactionsPhase2: { invoke: {
3058
+ src: "createArweaveTransactionsPhase2",
3059
+ input: ({ context: e, event: t }) => ({
3060
+ context: e,
3061
+ event: t
3062
+ }),
3063
+ onDone: {
3064
+ target: "uploadingDataPhase2",
3065
+ actions: I({
3066
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
3067
+ publishUploads: ({ event: e }) => e.output.publishUploads,
3068
+ uploaderState: () => void 0,
3069
+ currentTransactionIndex: () => void 0
3070
+ })
3071
+ },
3072
+ onError: {
3073
+ target: Z,
3074
+ actions: ["assignErrorCreatingArweaveTransactionsPhase2", "handleError"]
3075
+ }
3076
+ } },
3077
+ uploadingDataPhase2: {
3078
+ on: {
3079
+ updatePercentage: { actions: I({
3080
+ completionPercentage: ({ event: e }) => e.completionPercentage,
3081
+ uploaderState: ({ event: e }) => e.uploaderState,
3082
+ currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
3083
+ }) },
3084
+ uploadComplete: [{
3085
+ guard: ({ context: e }) => Fa(e),
3086
+ target: "creatingAttestationsDirectToEas",
3087
+ actions: I({ completionPercentage: 100 })
3088
+ }, {
3089
+ guard: ({ context: e }) => Ia(e),
3090
+ target: "creatingAttestations",
3091
+ actions: I({
3092
+ completionPercentage: 100,
3093
+ publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
3094
+ arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
3095
+ })
3096
+ }],
3097
+ uploadError: {
3098
+ target: Z,
3099
+ actions: ["assignErrorUploadingDataPhase2", "handleError"]
3100
+ }
3101
+ },
3102
+ invoke: {
3103
+ src: "uploadData",
3104
+ input: ({ context: e }) => ({ context: e })
3105
+ }
3106
+ },
3107
+ creatingAttestations: { invoke: {
3108
+ src: "createAttestations",
3109
+ input: ({ context: e, event: t }) => ({
3110
+ context: e,
3111
+ event: t
3112
+ }),
3113
+ onDone: {
3114
+ target: Pa,
3115
+ actions: I({
3116
+ easPayload: ({ event: e }) => e.output?.easPayload,
3117
+ publishedBatch: ({ event: e }) => e.output?.publishedBatch ?? null
3118
+ })
3119
+ },
3120
+ onError: {
3121
+ target: "attestationFailureRecoverable",
3122
+ actions: ["assignErrorCreatingAttestations", "handleError"]
3123
+ }
3124
+ } },
3125
+ attestationFailureRecoverable: { on: { retry: {
3126
+ target: "creatingAttestations",
3127
+ actions: ["assignAccountFromRetry"]
3128
+ } } },
3129
+ creatingAttestationsDirectToEas: { invoke: {
3130
+ src: "createAttestationsDirectToEas",
3131
+ input: ({ context: e, event: t }) => ({
3132
+ context: e,
3133
+ event: t
3134
+ }),
3135
+ onDone: {
3136
+ target: Pa,
3137
+ actions: I({
3138
+ easPayload: ({ event: e }) => e.output?.easPayload,
3139
+ publishedBatch: ({ event: e }) => e.output?.publishedBatch ?? null
3140
+ })
3141
+ },
3142
+ onError: {
3143
+ target: "attestationFailureRecoverableDirectToEas",
3144
+ actions: ["assignErrorCreatingAttestationsDirectToEas", "handleError"]
3145
+ }
3146
+ } },
3147
+ attestationFailureRecoverableDirectToEas: { on: { retry: {
3148
+ target: "creatingAttestationsDirectToEas",
3149
+ actions: ["assignAccountFromRetry"]
3150
+ } } },
3151
+ stopping: {
3152
+ entry: ({ context: e }) => {
3153
+ console.log(`Actor for ${e.item?.seedLocalId} stopped`);
3154
+ },
3155
+ type: "final"
3156
+ },
3157
+ [Pa]: {
3158
+ entry: ({ context: e }) => {
3159
+ let t = e.publishedBatch, n = e.onPublished;
3160
+ if (!n || !t?.seedUid) return;
3161
+ let r = e.item?.seedLocalId;
3162
+ r && Promise.resolve(n({
3163
+ seedLocalId: r,
3164
+ seedUid: t.seedUid,
3165
+ versionUid: t.versionUid,
3166
+ attestationUids: t.attestationUids
3167
+ })).catch((e) => {
3168
+ console.warn("[publish] onPublished callback failed:", e);
3169
+ });
3170
+ },
3171
+ type: "final"
3172
+ },
3173
+ [Z]: {
3174
+ entry: ({ context: e }) => {},
3175
+ type: "final"
3176
+ }
3177
+ }
3178
+ }), Ra = I(({ context: e, event: t }) => {
3179
+ let n = t, r = n.publishProcesses ?? /* @__PURE__ */ new Map(), i = n.subscriptions ?? /* @__PURE__ */ new Map();
3180
+ return {
3181
+ publishProcesses: new Map(r),
3182
+ subscriptions: new Map(i)
3183
+ };
3184
+ }), za = null;
3185
+ function Ba(e) {
3186
+ za = e;
3187
+ }
3188
+ function Va() {
3189
+ return za;
3190
+ }
3191
+ //#endregion
3192
+ //#region src/services/publishManager/actors/subscribe.ts
3193
+ var Ha = R("seedProtocol:services:PublishManager:actors:subscribe");
3194
+ function Ua(e) {
3195
+ let t = e.value;
3196
+ return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
3197
+ }
3198
+ function Wa(e) {
3199
+ return a.includes(e);
3200
+ }
3201
+ var Ga = zt(({ receive: e, input: { publishProcess: n, seedLocalId: r } }) => {
3202
+ let i = Va(), a = null, o = () => {
3203
+ a != null && (clearInterval(a), a = null);
3204
+ }, s = (e) => {
3205
+ let s = Ua(e);
3206
+ Wa(s) && a == null && i ? a = setInterval(() => {
3207
+ try {
3208
+ let e = n.getSnapshot();
3209
+ if (e.status === "done") {
3210
+ o();
3211
+ return;
3212
+ }
3213
+ if (!Wa(Ua(e))) {
3214
+ o();
3215
+ return;
3216
+ }
3217
+ } catch {
3218
+ return;
3219
+ }
3220
+ i?.savePublish(r, n);
3221
+ }, t) : Wa(s) || o();
3222
+ }, c = n.subscribe(async (e) => {
3223
+ Ha("Publish state:", e.value), i && (e.status === "done" ? (o(), i.savePublish(r, n, { triggerPublishDone: !0 })) : (i.savePublish(r, n), s(e)));
3224
+ });
3225
+ e(({ type: e }) => {
3226
+ e === "UNSUBSCRIBE" && (Ha("Received UNSUBSCRIBE event"), o(), c.unsubscribe(), i?.removeSubscription(r));
3227
+ });
3228
+ }), Ka = /* @__PURE__ */ new Map(), qa = 1;
3229
+ function Ja(e) {
3230
+ let t = qa++;
3231
+ return Ka.set(t, e), t;
3232
+ }
3233
+ function Ya(e, t) {
3234
+ if (e == null) return;
3235
+ let n = Ka.get(e);
3236
+ n && (Ka.delete(e), n(t));
3237
+ }
3238
+ //#endregion
3239
+ //#region src/services/publishManager/actions/createPublish.ts
3240
+ function Xa(e) {
3241
+ if (e) {
3242
+ if (i(e)) return e;
3243
+ if (m(e)) {
3244
+ let t = he();
3245
+ if (t && t.signer.address.toLowerCase() === e.address.toLowerCase()) return t;
3246
+ throw Error("@seedprotocol/publish: createPublish requires a PublishWallet (signer + txSender). Use fromEthersWallet, fromEip1193Provider, or fromThirdwebAccount.");
3247
+ }
3248
+ throw Error("@seedprotocol/publish: createPublish account must be a PublishWallet. Thirdweb Account must be wrapped with fromThirdwebAccount from @seedprotocol/publish/thirdweb.");
3249
+ }
3250
+ }
3251
+ function Za(e) {
3252
+ if (e) {
3253
+ if (e instanceof F.Wallet) return e;
3254
+ if (i(e)) return e.signer;
3255
+ if (m(e)) return e;
3256
+ }
3257
+ }
3258
+ var Qa = Rt(({ event: e, enqueue: t }) => {
3259
+ let { item: n, address: r, account: i, options: a, createToken: o } = e;
3260
+ if (!(r != null && typeof r == "string" && r.trim().length > 0)) {
3261
+ console.warn("[createPublish] No valid wallet address; skipping spawn."), Ya(o, void 0);
3262
+ return;
3263
+ }
3264
+ t.assign(({ context: e, spawn: t }) => {
3265
+ let { publishProcesses: s } = e;
3266
+ if (s && s.has(n.seedLocalId)) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" already exists.`), Ya(o, void 0), e;
3267
+ let c = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `run_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`, l = T(), u = [...l.arweaveUploadTags ?? [], ...a?.arweaveUploadTags ?? []], d = Xa(i) ?? he() ?? void 0, f = t(La, { input: {
3268
+ item: n,
3269
+ address: r,
3270
+ wallet: d,
3271
+ account: d,
3272
+ modelName: n.modelName,
3273
+ schemaId: n.schemaUid,
3274
+ signDataItems: a?.signDataItems,
3275
+ dataItemSigner: Za(a?.dataItemSigner),
3276
+ signArweaveTransactions: a?.signArweaveTransactions,
3277
+ arweaveJwk: a?.arweaveJwk,
3278
+ publishMode: a?.publishMode ?? "patch",
3279
+ publishRunId: c,
3280
+ arweaveUploadTags: u.length ? u : void 0,
3281
+ htmlEmbeddedDataUriPolicy: a?.htmlEmbeddedDataUriPolicy ?? l.htmlEmbeddedDataUriPolicy ?? "materialize",
3282
+ onPublished: a?.onPublished ?? l.onPublished
3283
+ } });
3284
+ s.set(n.seedLocalId, f);
3285
+ let p = new Map(e.settledPublishes);
3286
+ return p.delete(n.seedLocalId), Ya(o, f), {
3287
+ ...e,
3288
+ publishProcesses: s,
3289
+ settledPublishes: p
3290
+ };
3291
+ }), t.assign(({ context: e, spawn: t }) => {
3292
+ let { subscriptions: r, publishProcesses: i } = e, a = i.get(n.seedLocalId);
3293
+ if (!a) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" does not exist.`), e;
3294
+ if (r.has(n.seedLocalId)) return console.warn(`Subscription with seedLocalId "${n.seedLocalId}" already exists.`), e;
3295
+ let o = t(Ga, { input: {
3296
+ publishProcess: a,
3297
+ seedLocalId: n.seedLocalId
3298
+ } });
3299
+ return r.set(n.seedLocalId, o), {
3300
+ ...e,
3301
+ subscriptions: new Map(r)
3302
+ };
3303
+ });
3304
+ }), $a = ({ context: e, event: t }) => {
3305
+ let { seedLocalId: n, account: r } = t, a = e.publishProcesses.get(n);
3306
+ if (!a) {
3307
+ console.warn(`Publish process with seedLocalId "${n}" does not exist.`);
3308
+ return;
3309
+ }
3310
+ let o = r == null ? he() ?? void 0 : i(r) ? r : void 0;
3311
+ r != null && !o && console.warn("[retryAttestations] account must be a PublishWallet. Use fromThirdwebAccount / fromEip1193Provider / fromEthersWallet."), a.send({
3312
+ type: "retry",
3313
+ account: o,
3314
+ wallet: o
3315
+ });
3316
+ };
3317
+ //#endregion
3318
+ //#region src/services/publishManager/actions/stopScopedOrStandaloneChild.ts
3319
+ function eo(e, t, n) {
3320
+ t._parent === e ? n.stopChild(t) : t.stop();
3321
+ }
3322
+ //#endregion
3323
+ //#region src/services/publishManager/actors/savePublish.ts
3324
+ var to = R("seedProtocol:services:PublishManager:actors:savePublish"), no = /* @__PURE__ */ new Map();
3325
+ function ro(e, t) {
3326
+ let n = (no.get(e) ?? Promise.resolve()).then(t);
3327
+ return no.set(e, n.catch(() => {})), n;
3328
+ }
3329
+ function io(e) {
3330
+ return e === "completed" || e === "failed" || e === "interrupted";
3331
+ }
3332
+ function ao(e) {
3333
+ return e.status === "done" ? e.value === "success" ? "completed" : e.value === "failure" ? "failed" : "completed" : "in_progress";
3334
+ }
3335
+ var oo = 500, so = 2e3, co = 100;
3336
+ function lo(e) {
3337
+ return JSON.stringify(e, (e, t) => typeof t == "bigint" ? t.toString() : t);
3338
+ }
3339
+ function uo(e) {
3340
+ if (typeof e != "object" || !e) return;
3341
+ let t = e, n = t.snapshot, r = (t.context ?? n?.context)?.publishRunId;
3342
+ return typeof r == "string" && r.length > 0 ? r : void 0;
3343
+ }
3344
+ function fo(e) {
3345
+ if (e instanceof Error) return e.message;
3346
+ if (typeof e == "object") {
3347
+ let t = e.message;
3348
+ return typeof t == "string" ? t : void 0;
3349
+ }
3350
+ return String(e);
3351
+ }
3352
+ function po(e) {
3353
+ if (typeof e != "object" || !e) return;
3354
+ let t = e.code;
3355
+ return typeof t == "string" && t.length > 0 ? t.slice(0, co) : void 0;
3356
+ }
3357
+ function mo(e, t) {
3358
+ if (!e?.error || t !== "failed" && t !== "in_progress") return {};
3359
+ let n = e.error, r = fo(n)?.slice(0, oo), i = e.errorStep, a = po(n), o;
3360
+ if (n instanceof Error && n.stack) o = n.stack.slice(0, so);
3361
+ else if (typeof n == "object" && n) try {
3362
+ o = JSON.stringify(n).slice(0, so);
3363
+ } catch {
3364
+ o = String(n).slice(0, so);
3365
+ }
3366
+ else n != null && (o = String(n).slice(0, so));
3367
+ return {
3368
+ ...r === void 0 ? {} : { errorMessage: r },
3369
+ errorStep: i,
3370
+ ...n instanceof Error || r !== void 0 ? { errorDetails: o } : {},
3371
+ errorCode: a ?? null
3372
+ };
3373
+ }
3374
+ function ho(e) {
3375
+ return ro(e, async () => {
3376
+ let t = A.getAppDb();
3377
+ if (!t) {
3378
+ to("markInProgressPublishInterrupted: DB not ready, skipping");
3379
+ return;
3380
+ }
3381
+ let n = await t.select().from(N).where(Vt(z(N.seedLocalId, e), z(N.status, "in_progress"))).orderBy(Ht(N.updatedAt)).limit(1);
3382
+ if (n.length === 0) return;
3383
+ let r = Date.now();
3384
+ await t.update(N).set({
3385
+ status: "interrupted",
3386
+ completedAt: r,
3387
+ updatedAt: r,
3388
+ errorMessage: null,
3389
+ errorStep: null,
3390
+ errorDetails: null,
3391
+ errorCode: null
3392
+ }).where(z(N.id, n[0].id));
3393
+ });
3394
+ }
3395
+ var go = zt(({ sendBack: e, input: { persistedSnapshot: t, seedLocalId: n, triggerPublishDone: r } }) => {
3396
+ to("savePublish seedLocalId", n);
3397
+ let i = t;
3398
+ ro(n, async () => {
3399
+ let a = A.getAppDb();
3400
+ if (!a) {
3401
+ to("savePublish: DB not ready, skipping"), e({
3402
+ type: "SAVE_PUBLISH_DONE",
3403
+ seedLocalId: n,
3404
+ triggerPublishDone: r
3405
+ });
3406
+ return;
3407
+ }
3408
+ let o = await a.select().from(N).where(Vt(z(N.seedLocalId, n), z(N.status, "in_progress"))).orderBy(Ht(N.updatedAt)).limit(1), s = typeof t == "string" ? t : lo(t), c = ao(i), l = Date.now(), u = mo(i.context, c);
3409
+ if (o.length > 0) {
3410
+ let e = o[0];
3411
+ await a.update(N).set({
3412
+ persistedSnapshot: s,
3413
+ status: c,
3414
+ updatedAt: l,
3415
+ ...i.status === "done" && c !== "in_progress" ? { completedAt: l } : {},
3416
+ ...u
3417
+ }).where(z(N.id, e.id));
3418
+ } else {
3419
+ let e = uo(i);
3420
+ if (e != null && c === "in_progress" && i.status !== "done") {
3421
+ let t = (await a.select().from(N).where(z(N.seedLocalId, n)).orderBy(Ht(N.startedAt)).limit(1))[0];
3422
+ if (t && io(t.status)) try {
3423
+ if (uo(JSON.parse(t.persistedSnapshot)) === e) {
3424
+ to("savePublish: skip stale insert — same publishRunId as latest terminal row", n, e);
3425
+ return;
3426
+ }
3427
+ } catch {}
3428
+ }
3429
+ let t = i.context?.item, r = i.context?.modelName ?? t?.modelName ?? "", o = i.context?.schemaId ?? t?.schemaId;
3430
+ await a.insert(N).values({
3431
+ seedLocalId: n,
3432
+ modelName: r,
3433
+ schemaId: o ?? null,
3434
+ status: c,
3435
+ startedAt: l,
3436
+ persistedSnapshot: s,
3437
+ createdAt: l,
3438
+ updatedAt: l,
3439
+ ...u
3440
+ });
3441
+ }
3442
+ }).then(() => {
3443
+ e({
3444
+ type: "SAVE_PUBLISH_DONE",
3445
+ seedLocalId: n,
3446
+ triggerPublishDone: r
3447
+ });
3448
+ }).catch((t) => {
3449
+ to("savePublish error", t), e({
3450
+ type: "SAVE_PUBLISH_DONE",
3451
+ seedLocalId: n,
3452
+ triggerPublishDone: r
3453
+ });
3454
+ });
3455
+ }), _o = Rt(({ context: e, event: t, enqueue: n, self: r }) => {
3456
+ let { publishProcesses: i, subscriptions: a } = e, { seedLocalId: o } = t;
3457
+ ho(o).catch((e) => {
3458
+ console.warn(`[stopPublish] Failed to mark publish_processes row interrupted for "${o}":`, e);
3459
+ });
3460
+ let s = i.get(o);
3461
+ if (!s) {
3462
+ console.warn(`Publish process with seedLocalId "${o}" does not exist.`);
3463
+ return;
3464
+ }
3465
+ eo(r, s, n);
3466
+ let c = a.get(o);
3467
+ c && eo(r, c, n);
3468
+ let l = new Map(i);
3469
+ l.delete(o);
3470
+ let u = new Map(a);
3471
+ u.delete(o), n.assign({
3472
+ publishProcesses: l,
3473
+ subscriptions: u
3474
+ });
3475
+ }), vo = R("seedProtocol:PublishManager:index"), yo = Rt(({ context: e, enqueue: t, self: n }) => {
3476
+ vo("Stopping all actors..."), e.publishProcesses.forEach((e) => {
3477
+ eo(n, e, t);
3478
+ }), e.subscriptions.forEach((e) => {
3479
+ eo(n, e, t);
3480
+ }), t.assign({
3481
+ publishProcesses: /* @__PURE__ */ new Map(),
3482
+ subscriptions: /* @__PURE__ */ new Map()
3483
+ });
3484
+ }), bo = Rt(({ context: e, event: t, enqueue: n }) => {
3485
+ let { seedLocalId: r } = t, i = e.publishProcesses.get(r);
3486
+ if (!i) {
3487
+ console.warn(`Publish process with seedLocalId "${r}" does not exist.`);
3488
+ return;
3489
+ }
3490
+ n.stopChild(i);
3491
+ let a = e.subscriptions.get(r);
3492
+ a && n.stopChild(a);
3493
+ let o = new Map(e.publishProcesses);
3494
+ o.delete(r);
3495
+ let s = new Map(e.subscriptions);
3496
+ s.delete(r), n.assign({
3497
+ publishProcesses: o,
3498
+ subscriptions: s
3499
+ });
3500
+ }), xo = I(({ context: e, event: t }) => {
3501
+ let { subscriptions: n } = e, { seedLocalId: r, newSubscription: i } = t;
3502
+ return i && n.set(r, i), { subscriptions: new Map(n) };
3503
+ }), So = ["signedDataItems", "arweaveUploadData"];
3504
+ function Co(e) {
3505
+ if (typeof e != "object" || !e) return e;
3506
+ let t = { ...e };
3507
+ for (let e of So) delete t[e];
3508
+ return t;
3509
+ }
3510
+ function wo(e) {
3511
+ if (typeof e != "object" || !e) return e;
3512
+ let t = e, n = { ...t };
3513
+ t.context != null && typeof t.context == "object" && (n.context = Co(t.context));
3514
+ let r = t.snapshot;
3515
+ if (typeof r == "object" && r) {
3516
+ let e = r, t = { ...e };
3517
+ e.context != null && typeof e.context == "object" && (t.context = Co(e.context)), n.snapshot = t;
3518
+ }
3519
+ return n;
3520
+ }
3521
+ function To(e) {
3522
+ try {
3523
+ return wo(e.getPersistedSnapshot?.() ?? e.getSnapshot());
3524
+ } catch {
3525
+ let t = e.getSnapshot(), n = t.context;
3526
+ if (!n?.item) return wo(t);
3527
+ let r = n.item;
3528
+ return wo({
3529
+ ...t,
3530
+ context: {
3531
+ ...n,
3532
+ item: {
3533
+ seedLocalId: r.seedLocalId,
3534
+ modelName: r.modelName,
3535
+ schemaId: r.schemaId
3536
+ }
3537
+ }
3538
+ });
3539
+ }
3540
+ }
3541
+ var Eo = I(({ context: e, event: t, spawn: n }) => {
3542
+ let { publishProcesses: r } = e, { seedLocalId: i, publishProcess: a, triggerPublishDone: o } = t;
3543
+ if (!a) return e;
3544
+ let s = new Map(r);
3545
+ s.set(i, a);
3546
+ let c = To(a);
3547
+ return n(go, {
3548
+ id: `savePublish_${i}_${Date.now()}`,
3549
+ input: {
3550
+ persistedSnapshot: c,
3551
+ seedLocalId: i,
3552
+ triggerPublishDone: o
3553
+ }
3554
+ }), { publishProcesses: s };
3555
+ }), Do = I(({ context: e, event: t }) => {
3556
+ let { publishProcesses: n, subscriptions: r, settledPublishes: i } = e, a = t.seedLocalId, o = r.get(a);
3557
+ o && o.send({ type: "UNSUBSCRIBE" });
3558
+ let s = n.get(a), c = new Map(n);
3559
+ c.delete(a);
3560
+ let l = new Map(r);
3561
+ l.delete(a);
3562
+ let u = new Map(i);
3563
+ return s && u.set(a, s), {
3564
+ publishProcesses: c,
3565
+ subscriptions: l,
3566
+ settledPublishes: u
3567
+ };
3568
+ }), Oo = I(({ context: e, event: t }) => {
3569
+ let { subscriptions: n } = e, r = t.seedLocalId, i = new Map(n);
3570
+ return i.delete(r), { subscriptions: i };
3571
+ }), ko = 6e4, Ao = 2e3;
3572
+ function jo(e, t) {
3573
+ let n = typeof process < "u" ? process.env[e] : void 0;
3574
+ if (n == null || n === "") return t;
3575
+ let r = Number(n);
3576
+ return Number.isFinite(r) && r >= 0 ? r : t;
3577
+ }
3578
+ async function Mo(e, t) {
3579
+ let n = Date.now() + e;
3580
+ for (; Date.now() < n;) {
3581
+ try {
3582
+ if (A.isAppDbReady() && A.getAppDb()) return !0;
3583
+ } catch {}
3584
+ await new Promise((e) => setTimeout(e, t));
3585
+ }
3586
+ return !1;
3587
+ }
3588
+ function No(e) {
3589
+ let t = e.value;
3590
+ return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
3591
+ }
3592
+ function Po(e) {
3593
+ let t = No(e);
3594
+ if (t === "pollingForConfirmation" && (!e.context?.reimbursementTransactionId || !e.context?.requestResponse)) return !1;
3595
+ if (t === "uploadingData") {
3596
+ let t = e.context?.arweaveTransactions, n = e.context?.publishUploads;
3597
+ if (!Array.isArray(t) || t.length === 0 || !Array.isArray(n)) return !1;
3598
+ }
3599
+ return !0;
3600
+ }
3601
+ function Fo(e) {
3602
+ return typeof e == "object" && !!e && "xstate$$type" in e && e.xstate$$type === 1 && typeof e.id == "string";
3603
+ }
3604
+ function Io(e, t, n) {
3605
+ e.context = e.context ?? {};
3606
+ let r = e.context.item;
3607
+ if (Fo(r)) {
3608
+ e.context.item = {
3609
+ seedLocalId: t,
3610
+ modelName: e.context.modelName ?? n.modelName ?? "",
3611
+ schemaId: e.context.schemaId ?? n.schemaId ?? void 0
3612
+ };
3613
+ return;
3614
+ }
3615
+ e.context.item = {
3616
+ ...typeof r == "object" && r && !Array.isArray(r) ? r : {},
3617
+ seedLocalId: t,
3618
+ modelName: r?.modelName ?? e.context.modelName ?? n.modelName ?? "",
3619
+ schemaId: r?.schemaId ?? e.context.schemaId ?? n.schemaId ?? void 0
3620
+ };
3621
+ }
3622
+ var Lo = zt(({ sendBack: e, input: { context: t } }) => {
3623
+ let n = async () => {
3624
+ let e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map();
3625
+ if (!await Mo(jo("SEED_PUBLISH_RESTORE_WAIT_MS", ko), jo("SEED_PUBLISH_RESTORE_POLL_MS", Ao))) return {
3626
+ newPublishProcesses: e,
3627
+ newSubscriptions: t
3628
+ };
3629
+ let n = A.getAppDb();
3630
+ if (!n) return {
3631
+ newPublishProcesses: e,
3632
+ newSubscriptions: t
3633
+ };
3634
+ let r = await n.select().from(N).where(z(N.status, "in_progress")), i = /* @__PURE__ */ new Map(), a = [...r].sort((e, t) => (t.updatedAt ?? t.createdAt ?? 0) - (e.updatedAt ?? e.createdAt ?? 0));
3635
+ for (let e of a) i.has(e.seedLocalId) || i.set(e.seedLocalId, e);
3636
+ let o = Array.from(i.values());
3637
+ for (let n of o) {
3638
+ let r;
3639
+ try {
3640
+ r = JSON.parse(n.persistedSnapshot);
3641
+ } catch {
3642
+ continue;
3643
+ }
3644
+ if (r.status === "done") continue;
3645
+ let i = r.context?.item?.seedLocalId ?? n.seedLocalId;
3646
+ if (!i || !Po(r)) continue;
3647
+ Io(r, i, n);
3648
+ let a = Lt(La, {
3649
+ snapshot: r,
3650
+ input: void 0
3651
+ }), o = Lt(Ga, { input: {
3652
+ publishProcess: a,
3653
+ seedLocalId: i
3654
+ } });
3655
+ e.set(i, a), t.set(i, o), a.start(), o.start();
3656
+ }
3657
+ return {
3658
+ newPublishProcesses: e,
3659
+ newSubscriptions: t
3660
+ };
3661
+ }, r = () => ({
3662
+ newPublishProcesses: /* @__PURE__ */ new Map(),
3663
+ newSubscriptions: /* @__PURE__ */ new Map()
3664
+ });
3665
+ n().then((t) => {
3666
+ let { newPublishProcesses: n, newSubscriptions: i } = t ?? r();
3667
+ e({
3668
+ type: "RESTORE_FROM_DB_DONE",
3669
+ publishProcesses: n,
3670
+ subscriptions: i
3671
+ });
3672
+ }).catch(() => {
3673
+ let { newPublishProcesses: t, newSubscriptions: n } = r();
3674
+ e({
3675
+ type: "RESTORE_FROM_DB_DONE",
3676
+ publishProcesses: t,
3677
+ subscriptions: n
3678
+ });
3679
+ });
3680
+ }), Ro = I(({ context: e, event: t }) => ({ pendingCreates: [...e.pendingCreates ?? [], t] })), zo = Rt(({ context: e, enqueue: t }) => {
3681
+ let n = e.pendingCreates ?? [];
3682
+ if (n.length !== 0) {
3683
+ t.assign({ pendingCreates: [] });
3684
+ for (let e of n) t.raise(e);
3685
+ }
3686
+ }), Bo = R("seedProtocol:PublishManager:index"), Vo = Bt({
3687
+ types: {
3688
+ context: {},
3689
+ input: {},
3690
+ events: {}
3691
+ },
3692
+ actors: { restoreFromDb: Lo },
3693
+ actions: {
3694
+ assignRestoreFromDb: Ra,
3695
+ createPublish: Qa,
3696
+ queueCreatePublish: Ro,
3697
+ drainPendingCreates: zo,
3698
+ addSubscription: xo,
3699
+ requestSavePublish: Eo,
3700
+ publishDone: Do,
3701
+ removeSubscription: Oo,
3702
+ retryAttestations: $a,
3703
+ stopPublish: _o,
3704
+ stopAll: yo,
3705
+ query: bo
3706
+ }
3707
+ }).createMachine({
3708
+ id: "publishManager",
3709
+ initial: "restoreFromDb",
3710
+ context: {
3711
+ publishProcesses: /* @__PURE__ */ new Map(),
3712
+ subscriptions: /* @__PURE__ */ new Map(),
3713
+ pendingCreates: [],
3714
+ settledPublishes: /* @__PURE__ */ new Map()
3715
+ },
3716
+ states: {
3717
+ restoreFromDb: {
3718
+ on: {
3719
+ RESTORE_FROM_DB_DONE: {
3720
+ target: "active",
3721
+ actions: ["assignRestoreFromDb"]
3722
+ },
3723
+ CREATE_PUBLISH: { actions: ["queueCreatePublish"] }
3724
+ },
3725
+ invoke: {
3726
+ src: "restoreFromDb",
3727
+ input: ({ context: e }) => ({ context: e })
3728
+ }
3729
+ },
3730
+ active: {
3731
+ entry: "drainPendingCreates",
3732
+ on: {
3733
+ CREATE_PUBLISH: { actions: ["createPublish"] },
3734
+ ADD_SUBSCRIPTION: { actions: ["addSubscription"] },
3735
+ REQUEST_SAVE_PUBLISH: { actions: ["requestSavePublish"] },
3736
+ SAVE_PUBLISH_DONE: [{
3737
+ guard: ({ event: e }) => e.triggerPublishDone === !0,
3738
+ actions: ["publishDone"]
3739
+ }],
3740
+ PUBLISH_DONE: { actions: ["publishDone"] },
3741
+ REMOVE_SUBSCRIPTION: { actions: ["removeSubscription"] },
3742
+ RETRY_ATTESTATIONS: { actions: ["retryAttestations"] },
3743
+ STOP_PUBLISH: { actions: ["stopPublish"] },
3744
+ QUERY: { actions: ["query"] },
3745
+ STOP_ALL: { actions: ["stopAll"] }
3746
+ }
3747
+ }
3748
+ }
3749
+ }), $ = Lt(Vo, { input: {
3750
+ publishProcesses: /* @__PURE__ */ new Map(),
3751
+ subscriptions: /* @__PURE__ */ new Map(),
3752
+ pendingCreates: [],
3753
+ settledPublishes: /* @__PURE__ */ new Map()
3754
+ } }), Ho = !1;
3755
+ function Uo() {
3756
+ if (!Ho) {
3757
+ try {
3758
+ $.start();
3759
+ } catch (e) {
3760
+ let t = e instanceof Error ? e.message : String(e);
3761
+ if (!/already started/i.test(t)) throw e;
3762
+ }
3763
+ Ho = !0;
3764
+ }
3765
+ }
3766
+ Ba({
3767
+ savePublish: (e, t, n) => {
3768
+ $.send({
3769
+ type: "REQUEST_SAVE_PUBLISH",
3770
+ seedLocalId: e,
3771
+ publishProcess: t,
3772
+ triggerPublishDone: n?.triggerPublishDone
3773
+ });
3774
+ },
3775
+ onPublishDone: (e) => {
3776
+ $.send({
3777
+ type: "PUBLISH_DONE",
3778
+ seedLocalId: e
3779
+ });
3780
+ },
3781
+ removeSubscription: (e) => {
3782
+ $.send({
3783
+ type: "REMOVE_SUBSCRIPTION",
3784
+ seedLocalId: e
3785
+ });
3786
+ }
3787
+ });
3788
+ var Wo = $.subscribe((e) => {
3789
+ Bo("PublishManager snapshot:", e);
3790
+ });
3791
+ typeof document < "u" && (Uo(), window.addEventListener("load", () => {
3792
+ Bo("PublishManager started");
3793
+ }), window.addEventListener("beforeunload", () => {
3794
+ Wo.unsubscribe(), $.stop();
3795
+ }));
3796
+ var Go = {
3797
+ getService: () => $,
3798
+ ready: () => (Uo(), $.getSnapshot().value === "active" ? Promise.resolve() : new Promise((e) => {
3799
+ let t = $.subscribe((n) => {
3800
+ n.value === "active" && (t.unsubscribe(), e());
3801
+ });
3802
+ $.getSnapshot().value === "active" && (t.unsubscribe(), e());
3803
+ })),
3804
+ createPublish: (e, t, n, r) => new Promise((i) => {
3805
+ let a = Ja(i);
3806
+ $.send({
3807
+ type: "CREATE_PUBLISH",
3808
+ item: e,
3809
+ address: t,
3810
+ account: n,
3811
+ options: r,
3812
+ createToken: a
3813
+ });
3814
+ }),
3815
+ retryAttestations: (e, t) => $.send({
3816
+ type: "RETRY_ATTESTATIONS",
3817
+ seedLocalId: e,
3818
+ account: t
3819
+ }),
3820
+ stopPublish: (e) => $.send({
3821
+ type: "STOP_PUBLISH",
3822
+ seedLocalId: e
3823
+ }),
3824
+ query: (e) => $.send({
3825
+ type: "QUERY",
3826
+ seedLocalId: e
3827
+ }),
3828
+ stopAll: () => $.send({ type: "STOP_ALL" }),
3829
+ getPublish: (e) => {
3830
+ let t = $.getSnapshot().context;
3831
+ return t.publishProcesses.get(e) ?? t.settledPublishes.get(e);
3832
+ },
3833
+ savePublish: (e, t) => $.send({
3834
+ type: "REQUEST_SAVE_PUBLISH",
3835
+ seedLocalId: e,
3836
+ publishProcess: t
3837
+ }),
3838
+ addSubscription: (e, t) => $.send({
3839
+ type: "ADD_SUBSCRIPTION",
3840
+ seedLocalId: e,
3841
+ newSubscription: t
3842
+ }),
3843
+ removeSubscription: (e) => $.send({
3844
+ type: "REMOVE_SUBSCRIPTION",
3845
+ seedLocalId: e
3846
+ })
3847
+ };
3848
+ //#endregion
3849
+ //#region src/helpers/approvedTargetsForAutomationPublish.ts
3850
+ function Ko() {
3851
+ let e = T().modularAccountModuleContract?.trim();
3852
+ if (!e || !/^0x[0-9a-fA-F]{40}$/.test(e)) throw Error("@seedprotocol/publish: session keys require PublishConfig.modularAccountModuleContract (their only approved target is the Seed executor module).");
3853
+ return [e.toLowerCase()];
3854
+ }
3855
+ //#endregion
3856
+ //#region src/helpers/automationSessionKeyPermissions.ts
3857
+ var qo = "publish,revoke";
3858
+ function Jo(e) {
3859
+ let t = {
3860
+ approvedTargets: Ko(),
3861
+ nativeTokenLimitPerTransaction: 0
3862
+ };
3863
+ return typeof e?.expiresAt == "number" && e.expiresAt > 0 && (t.expiresAt = Math.trunc(e.expiresAt)), t;
3864
+ }
3865
+ function Yo(e, t = qo) {
3866
+ let n = `${[...e.approvedTargets].map((e) => e.toLowerCase()).sort().join(",")}|${e.nativeTokenLimitPerTransaction}|${e.expiresAt ?? 0}|${t.trim()}`;
3867
+ return ft(pt(n));
3868
+ }
3869
+ function Xo(e) {
3870
+ let t = {
3871
+ approvedTargets: e.approvedTargets,
3872
+ nativeTokenLimitPerTransaction: e.nativeTokenLimitPerTransaction
3873
+ };
3874
+ return e.expiresAt != null && e.expiresAt > 0 ? {
3875
+ ...t,
3876
+ permissionEndTimestamp: /* @__PURE__ */ new Date(e.expiresAt * 1e3)
3877
+ } : t;
3878
+ }
3879
+ //#endregion
3880
+ //#region src/services/publishAuthorization/index.ts
3881
+ var Zo = "0x0000000000000000000000000000000000000000", Qo = !0, $o = "0x0000000000000000000000000000000000000000";
3882
+ function es(e) {
3883
+ if (i(e)) return e.txSender;
3884
+ if (_e(e)) return e;
3885
+ throw Error("@seedprotocol/publish: publish authorization write APIs require a PublishWallet or SeedTxSender");
3886
+ }
3887
+ async function ts(e, t) {
3888
+ let n = await e.sendTransaction(t);
3889
+ return C(n.transactionHash);
3890
+ }
3891
+ function ns(e, t) {
3892
+ let n = t.trim();
3893
+ if (!/^0x[0-9a-fA-F]{40}$/.test(n)) throw Error(`@seedprotocol/publish: ${e} must be a valid address`);
3894
+ return n;
3895
+ }
3896
+ function rs() {
3897
+ return Pt.getSchemaUID(ht, Zo, Qo);
3898
+ }
3899
+ async function is(e) {
3900
+ let t = es(e), n = rs();
3901
+ return await V(n) || (await ts(t, cn({
3902
+ schema: ht,
3903
+ resolverAddress: Zo,
3904
+ revocable: Qo
3905
+ })), await ts(t, un({
3906
+ schemaUid: n,
3907
+ schemaName: _t
3908
+ }))), n;
3909
+ }
3910
+ function as(e) {
3911
+ return new Nt(ht).encodeData([
3912
+ {
3913
+ name: "identity",
3914
+ value: e.identity,
3915
+ type: "address"
3916
+ },
3917
+ {
3918
+ name: "sessionKey",
3919
+ value: e.sessionKey,
3920
+ type: "address"
3921
+ },
3922
+ {
3923
+ name: "app",
3924
+ value: e.app,
3925
+ type: "address"
3926
+ },
3927
+ {
3928
+ name: "scopes",
3929
+ value: e.scopes,
3930
+ type: "string"
3931
+ },
3932
+ {
3933
+ name: "grantedAt",
3934
+ value: e.grantedAt,
3935
+ type: "uint64"
3936
+ },
3937
+ {
3938
+ name: "expiresAt",
3939
+ value: e.expiresAt,
3940
+ type: "uint64"
3941
+ },
3942
+ {
3943
+ name: "permissionsHash",
3944
+ value: Tt(e.permissionsHash),
3945
+ type: "bytes32"
3946
+ }
3947
+ ]);
3948
+ }
3949
+ async function os(e) {
3950
+ let t = es(e.wallet), n = e.ensureSchema === !1 ? rs() : await is(e.wallet), r = ns("identity", e.identity), i = ns("sessionKey", e.sessionKey), a = e.app?.trim() ? ns("app", e.app) : $o, o = e.grantedAt ?? Math.floor(Date.now() / 1e3), s = typeof e.expiresAt == "number" && e.expiresAt > 0 ? Math.trunc(e.expiresAt) : 0, c = e.scopes ?? yt, l = Tt(e.permissionsHash ?? Yo(Jo({ expiresAt: s > 0 ? s : void 0 }), c === yt ? "publish,revoke" : c));
3951
+ if (l === It) throw Error("@seedprotocol/publish: attestPublishAuthorization requires a non-zero permissionsHash");
3952
+ let d = typeof e.expirationTime == "number" && e.expirationTime > 0 ? e.expirationTime : s > 0 ? s : o + mt, f = as({
3953
+ identity: r,
3954
+ sessionKey: i,
3955
+ app: a,
3956
+ scopes: c,
3957
+ grantedAt: o,
3958
+ expiresAt: s,
3959
+ permissionsHash: l
3960
+ }), p = await ts(t, v({
3961
+ schema: n,
3962
+ data: {
3963
+ recipient: i,
3964
+ expirationTime: BigInt(d),
3965
+ revocable: !0,
3966
+ refUID: It,
3967
+ data: f,
3968
+ value: 0n
3969
+ }
3970
+ }));
3971
+ if (!p) throw Error("@seedprotocol/publish: attestPublishAuthorization failed — no receipt");
3972
+ let { easContractAddress: m } = T(), h = u(p, m);
3973
+ if (!h || !wt(h)) throw Error("@seedprotocol/publish: attestPublishAuthorization failed — could not parse attestation UID");
3974
+ return {
3975
+ uid: h,
3976
+ schemaUid: n,
3977
+ permissionsHash: l,
3978
+ grantedAt: o,
3979
+ expiresAt: s,
3980
+ expirationTime: d
3981
+ };
3982
+ }
3983
+ async function ss(e) {
3984
+ let t = es(e.wallet), r = e.schemaUid ?? rs(), i = Tt(e.uid);
3985
+ if (!wt(i)) throw Error("@seedprotocol/publish: revokePublishAuthorization requires a valid attestation uid");
3986
+ if (!await ts(t, n([{
3987
+ schema: r,
3988
+ data: [{ uid: i }]
3989
+ }]))) throw Error("@seedprotocol/publish: revokePublishAuthorization failed — no receipt");
3990
+ }
3991
+ async function cs(e) {
3992
+ let t = (await Ct({
3993
+ identities: e.identities,
3994
+ excludeRevoked: !1
3995
+ })).find((t) => t.id?.toLowerCase() === e.uid.toLowerCase());
3996
+ if (!t) return null;
3997
+ let n = St(t.decodedDataJson ?? "[]"), r = typeof t.expirationTime == "number" ? t.expirationTime : typeof t.expirationTime == "string" ? Number(t.expirationTime) : null;
3998
+ return {
3999
+ uid: t.id,
4000
+ decoded: n,
4001
+ assess: xt({
4002
+ decoded: n,
4003
+ expirationTime: r
4004
+ }),
4005
+ expirationTime: r
4006
+ };
4007
+ }
4008
+ //#endregion
4009
+ export { B as $, Qr as A, zr as B, mi as C, Xr as D, Zr as E, Wr as F, jr as G, Ur as H, si as I, lr as J, Nr as K, Gr as L, ii as M, oi as N, Yr as O, Rr as P, cn as Q, Kr as R, vi as S, Jr as T, Hr as U, Pr as V, Vr as W, un as X, xn as Y, V as Z, ca as _, os as a, ji as b, rs as c, Jo as d, nn as et, Yo as f, La as g, Go as h, cs as i, ei as j, $r as k, ss as l, Ko as m, vt as n, Yt as nt, as as o, Xo as p, qn as q, bt as r, is as s, gt as t, Jt as tt, qo as u, la as v, gi as w, Ai as x, Ei as y, qr as z };
4010
+
4011
+ //# sourceMappingURL=publishAuthorization-CvK_coYp.js.map