@pkcprotocol/pkc-js 0.0.153 → 0.0.155

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 (192) hide show
  1. package/README.md +23 -3
  2. package/dist/browser/clients/rpc-client/schema.js +2 -2
  3. package/dist/browser/clients/rpc-client/schema.js.map +1 -1
  4. package/dist/browser/community/remote-community.js +8 -2
  5. package/dist/browser/community/remote-community.js.map +1 -1
  6. package/dist/browser/community/schema.js +4 -0
  7. package/dist/browser/community/schema.js.map +1 -1
  8. package/dist/browser/community-list/community-list.js +3 -2
  9. package/dist/browser/community-list/community-list.js.map +1 -1
  10. package/dist/browser/errors.d.ts +18 -2
  11. package/dist/browser/errors.js +18 -2
  12. package/dist/browser/errors.js.map +1 -1
  13. package/dist/browser/generated-version.d.ts +1 -1
  14. package/dist/browser/generated-version.js +1 -1
  15. package/dist/browser/pkc/pkc.js +13 -4
  16. package/dist/browser/pkc/pkc.js.map +1 -1
  17. package/dist/browser/pkc-error.d.ts +1 -1
  18. package/dist/browser/publications/comment/comment.d.ts +1 -0
  19. package/dist/browser/publications/comment/comment.js +82 -21
  20. package/dist/browser/publications/comment/comment.js.map +1 -1
  21. package/dist/browser/publications/comment/crosspost-runtime.js +10 -2
  22. package/dist/browser/publications/comment/crosspost-runtime.js.map +1 -1
  23. package/dist/browser/publications/comment/schema.d.ts +1 -1
  24. package/dist/browser/publications/comment/schema.js +30 -1
  25. package/dist/browser/publications/comment/schema.js.map +1 -1
  26. package/dist/browser/publications/publication.d.ts +12 -1
  27. package/dist/browser/publications/publication.js +511 -167
  28. package/dist/browser/publications/publication.js.map +1 -1
  29. package/dist/browser/publications/types.d.ts +1 -0
  30. package/dist/browser/rpc/src/index.js +15 -8
  31. package/dist/browser/rpc/src/index.js.map +1 -1
  32. package/dist/browser/runtime/browser/util.d.ts +3 -1
  33. package/dist/browser/runtime/browser/util.js +8 -2
  34. package/dist/browser/runtime/browser/util.js.map +1 -1
  35. package/dist/browser/runtime/node/blockstore.d.ts +2 -2
  36. package/dist/browser/runtime/node/blockstore.js +2 -2
  37. package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js +2 -1
  38. package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
  39. package/dist/browser/runtime/node/community/communities-registry.d.ts +96 -0
  40. package/dist/browser/runtime/node/community/communities-registry.js +964 -0
  41. package/dist/browser/runtime/node/community/communities-registry.js.map +1 -0
  42. package/dist/browser/runtime/node/community/db-handler.d.ts +8 -7
  43. package/dist/browser/runtime/node/community/db-handler.js +128 -84
  44. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  45. package/dist/browser/runtime/node/community/local-community/cleanup.js +62 -12
  46. package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
  47. package/dist/browser/runtime/node/community/local-community/db-state.d.ts +1 -1
  48. package/dist/browser/runtime/node/community/local-community/db-state.js +31 -39
  49. package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
  50. package/dist/browser/runtime/node/community/local-community/editing.js +84 -27
  51. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  52. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js +1 -1
  53. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  54. package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  55. package/dist/browser/runtime/node/community/local-community/lifecycle.js +88 -61
  56. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  57. package/dist/browser/runtime/node/community/local-community/publication-validation.d.ts +1 -2
  58. package/dist/browser/runtime/node/community/local-community/publication-validation.js +23 -0
  59. package/dist/browser/runtime/node/community/local-community/publication-validation.js.map +1 -1
  60. package/dist/browser/runtime/node/community/local-community.d.ts +6 -3
  61. package/dist/browser/runtime/node/community/local-community.js +16 -16
  62. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  63. package/dist/browser/runtime/node/community/pkc-instance-lock.d.ts +17 -0
  64. package/dist/browser/runtime/node/community/pkc-instance-lock.js +142 -0
  65. package/dist/browser/runtime/node/community/pkc-instance-lock.js.map +1 -0
  66. package/dist/browser/runtime/node/storage.js +5 -0
  67. package/dist/browser/runtime/node/storage.js.map +1 -1
  68. package/dist/browser/runtime/node/util.d.ts +4 -6
  69. package/dist/browser/runtime/node/util.js +32 -270
  70. package/dist/browser/runtime/node/util.js.map +1 -1
  71. package/dist/browser/schema/schema-util.js +18 -4
  72. package/dist/browser/schema/schema-util.js.map +1 -1
  73. package/dist/browser/signer/author-wallet-proof.d.ts +19 -0
  74. package/dist/browser/signer/author-wallet-proof.js +89 -0
  75. package/dist/browser/signer/author-wallet-proof.js.map +1 -0
  76. package/dist/browser/signer/signatures.js +29 -0
  77. package/dist/browser/signer/signatures.js.map +1 -1
  78. package/dist/browser/test/test-util.d.ts +12 -0
  79. package/dist/browser/test/test-util.js +23 -0
  80. package/dist/browser/test/test-util.js.map +1 -1
  81. package/dist/browser/unknown-props.d.ts +24 -0
  82. package/dist/browser/unknown-props.js +95 -0
  83. package/dist/browser/unknown-props.js.map +1 -0
  84. package/dist/browser/util.js +7 -0
  85. package/dist/browser/util.js.map +1 -1
  86. package/dist/browser/version.js +1 -1
  87. package/dist/bundled/bundle-manifest.json +47 -49
  88. package/dist/bundled/challenges.js +1 -1
  89. package/dist/bundled/chunks/{helia-for-pkc-COJ3xMF9.js → helia-for-pkc-Oiy9zYBR.js} +4 -4
  90. package/dist/bundled/chunks/{local-community-BTx2HxIm.js → local-community-BlJfnxcr.js} +1 -1
  91. package/dist/bundled/chunks/{local-community-CflGu_ET.js → local-community-PMJTbzmG.js} +293 -167
  92. package/dist/bundled/chunks/{node-B0b6lAIX.js → node-Bf1DjAFe.js} +488 -208
  93. package/dist/bundled/chunks/{page-sort-scoring-DAMnUmDY.js → page-sort-scoring-DVAvzj4W.js} +1 -1
  94. package/dist/bundled/chunks/{rpc-local-community-Cy03QajY.js → rpc-local-community-BqJ_olvR.js} +4529 -3007
  95. package/dist/bundled/chunks/{util-C4y8KHmp.js → util-BpiQT2hV.js} +1 -1
  96. package/dist/bundled/chunks/{util-D7AtfLYH.js → util-N_HlPQHv.js} +66 -18
  97. package/dist/bundled/chunks/{validate-package-factories-EH9ydbPR.js → validate-package-factories-DoC8xXMu.js} +2 -2
  98. package/dist/bundled/index.js +1 -1
  99. package/dist/bundled/page-sorts.js +1 -1
  100. package/dist/bundled/rpc/src/index.js +15 -11
  101. package/dist/node/clients/rpc-client/schema.js +2 -2
  102. package/dist/node/clients/rpc-client/schema.js.map +1 -1
  103. package/dist/node/community/remote-community.js +8 -2
  104. package/dist/node/community/remote-community.js.map +1 -1
  105. package/dist/node/community/schema.js +4 -0
  106. package/dist/node/community/schema.js.map +1 -1
  107. package/dist/node/community-list/community-list.js +3 -2
  108. package/dist/node/community-list/community-list.js.map +1 -1
  109. package/dist/node/errors.d.ts +18 -2
  110. package/dist/node/errors.js +18 -2
  111. package/dist/node/errors.js.map +1 -1
  112. package/dist/node/generated-version.d.ts +1 -1
  113. package/dist/node/generated-version.js +1 -1
  114. package/dist/node/pkc/pkc.js +13 -4
  115. package/dist/node/pkc/pkc.js.map +1 -1
  116. package/dist/node/pkc-error.d.ts +1 -1
  117. package/dist/node/publications/comment/comment.d.ts +1 -0
  118. package/dist/node/publications/comment/comment.js +82 -21
  119. package/dist/node/publications/comment/comment.js.map +1 -1
  120. package/dist/node/publications/comment/crosspost-runtime.js +10 -2
  121. package/dist/node/publications/comment/crosspost-runtime.js.map +1 -1
  122. package/dist/node/publications/comment/schema.d.ts +1 -1
  123. package/dist/node/publications/comment/schema.js +30 -1
  124. package/dist/node/publications/comment/schema.js.map +1 -1
  125. package/dist/node/publications/publication.d.ts +12 -1
  126. package/dist/node/publications/publication.js +511 -167
  127. package/dist/node/publications/publication.js.map +1 -1
  128. package/dist/node/publications/types.d.ts +1 -0
  129. package/dist/node/rpc/src/index.js +15 -8
  130. package/dist/node/rpc/src/index.js.map +1 -1
  131. package/dist/node/runtime/browser/util.d.ts +3 -1
  132. package/dist/node/runtime/browser/util.js +8 -2
  133. package/dist/node/runtime/browser/util.js.map +1 -1
  134. package/dist/node/runtime/node/blockstore.d.ts +2 -2
  135. package/dist/node/runtime/node/blockstore.js +2 -2
  136. package/dist/node/runtime/node/community/challenges/validate-challenge-result.js +2 -1
  137. package/dist/node/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
  138. package/dist/node/runtime/node/community/communities-registry.d.ts +96 -0
  139. package/dist/node/runtime/node/community/communities-registry.js +964 -0
  140. package/dist/node/runtime/node/community/communities-registry.js.map +1 -0
  141. package/dist/node/runtime/node/community/db-handler.d.ts +8 -7
  142. package/dist/node/runtime/node/community/db-handler.js +128 -84
  143. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  144. package/dist/node/runtime/node/community/local-community/cleanup.js +62 -12
  145. package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
  146. package/dist/node/runtime/node/community/local-community/db-state.d.ts +1 -1
  147. package/dist/node/runtime/node/community/local-community/db-state.js +31 -39
  148. package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
  149. package/dist/node/runtime/node/community/local-community/editing.js +84 -27
  150. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  151. package/dist/node/runtime/node/community/local-community/ipns-publishing.js +1 -1
  152. package/dist/node/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  153. package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  154. package/dist/node/runtime/node/community/local-community/lifecycle.js +88 -61
  155. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  156. package/dist/node/runtime/node/community/local-community/publication-validation.d.ts +1 -2
  157. package/dist/node/runtime/node/community/local-community/publication-validation.js +23 -0
  158. package/dist/node/runtime/node/community/local-community/publication-validation.js.map +1 -1
  159. package/dist/node/runtime/node/community/local-community.d.ts +6 -3
  160. package/dist/node/runtime/node/community/local-community.js +16 -16
  161. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  162. package/dist/node/runtime/node/community/pkc-instance-lock.d.ts +17 -0
  163. package/dist/node/runtime/node/community/pkc-instance-lock.js +142 -0
  164. package/dist/node/runtime/node/community/pkc-instance-lock.js.map +1 -0
  165. package/dist/node/runtime/node/storage.js +5 -0
  166. package/dist/node/runtime/node/storage.js.map +1 -1
  167. package/dist/node/runtime/node/util.d.ts +4 -6
  168. package/dist/node/runtime/node/util.js +32 -270
  169. package/dist/node/runtime/node/util.js.map +1 -1
  170. package/dist/node/schema/schema-util.js +18 -4
  171. package/dist/node/schema/schema-util.js.map +1 -1
  172. package/dist/node/signer/author-wallet-proof.d.ts +19 -0
  173. package/dist/node/signer/author-wallet-proof.js +89 -0
  174. package/dist/node/signer/author-wallet-proof.js.map +1 -0
  175. package/dist/node/signer/signatures.js +29 -0
  176. package/dist/node/signer/signatures.js.map +1 -1
  177. package/dist/node/test/test-util.d.ts +12 -0
  178. package/dist/node/test/test-util.js +23 -0
  179. package/dist/node/test/test-util.js.map +1 -1
  180. package/dist/node/unknown-props.d.ts +24 -0
  181. package/dist/node/unknown-props.js +95 -0
  182. package/dist/node/unknown-props.js.map +1 -0
  183. package/dist/node/util.js +7 -0
  184. package/dist/node/util.js.map +1 -1
  185. package/dist/node/version.js +1 -1
  186. package/package.json +3 -3
  187. package/dist/browser/runtime/node/community/start-lock.d.ts +0 -8
  188. package/dist/browser/runtime/node/community/start-lock.js +0 -18
  189. package/dist/browser/runtime/node/community/start-lock.js.map +0 -1
  190. package/dist/node/runtime/node/community/start-lock.d.ts +0 -8
  191. package/dist/node/runtime/node/community/start-lock.js +0 -18
  192. package/dist/node/runtime/node/community/start-lock.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { i as __toESM, r as __require, t as __commonJSMin } from "./chunk-2rV9d50f.js";
2
- import { $ as retryKuboIpfsAdd, At as ChallengeAnswerMessageSchema, C as hideClassPrivateProps, D as isIpfsCid, Dt as require_sha256, E as isAbortError, Et as untrackUpdatingCommunity, Hr as setErrorMap, In as CommentUpdateForChallengeVerificationSchema, Ir as FailedToFetchPageIpfsFromGatewaysError, It as ChallengeVerificationMessageSchema, Jt as version_default, Lr as PKCError, Mr as FailedToFetchCommentIpfsFromGatewaysError, Mt as ChallengeMessageSchema, Nr as FailedToFetchCommentUpdateFromGatewaysError, Ot as TimeoutError, Pt as ChallengeRequestMessageSchema, Rr as messages, Sr as e$1, St as trackUpdatingComment, T as ipnsNameToIpnsOverPubsubTopic, Tt as untrackUpdatingComment, U as rejectWhenAbortSignalFires, W as rejectWhenCommunityStopsOrAborts, X as replaceXWithY, Y as removeUndefinedValuesRecursively, Z as resolveWhenPredicateIsTrue, _t as listUpdatingCommunities, a as calculateStringSizeSameAsIpfsAddCidV0Sync, at as throwIfAbortSignalAborted, br as t$1, cn as CommunityAnchorSchema, d as deepMergeRuntimeFields, dt as findStartedCommunity, et as retryKuboIpfsAddAndProvide, ft as findUpdatingComment, gr as n$2, gt as listUpdatingComments, hr as isStringDomain, ht as listStartedCommunities, i as calculateStringSizeSameAsIpfsAddCidV0, jn as CommentIpfsSchema, jr as require_retry$1, k as isIpns, kt as pTimeout, ni as en_default, nt as shortifyCid, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsSchema, pt as findUpdatingCommunity, r as calculateIpfsCidV0, rt as sleepUntilTimeoutOrAbort, st as waitForUpdateInCommunityInstanceWithErrorAndTimeout, tt as shortifyAddress, u as createAbortError, vr as n$1, vt as refreshTrackedCommentAliases, wr as r, x as getPostUpdateTimestampRange, xn as PubsubTopicSchema, xr as e, z as linkAbortSignals, zn as CommentUpdateSchema, zr as logger_default } from "./util-D7AtfLYH.js";
3
- import { $n as buildRuntimeCommunityFields, $t as RpcPublishCommunityListParamSchema, A as findCommentInParsedPages, At as parseRpcCommentUpdateEventWithPKCErrorIfItFails, B as GenericStateClient, Bn as verifyCommunityEdit, Bt as RpcCommunityIdentifierParamSchema, C as RepliesPages, Cn as signCommentModeration, Cr as getDefaultDataPath, Ct as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, D as extractCommunityRuntimeFieldsFromParsedPages, Dn as signCommunityEdit, Dr as monitorCommunitiesDirectory, Dt as parseJsonWithPKCErrorIfFails, Er as listCommunitiesSync, Et as parseDecryptedChallengeWithPKCErrorIfItFails, F as cloneCrosspostForRuntime, Fn as verifyCommentIpfs, Fr as toCommunitiesEntry, Ft as RpcAuthorNameParamSchema, G as PKCTypedEmitter, Gn as getAuthorNameFromRuntime, Gr as t$2, Gt as RpcExportCommunityParamSchema, H as InflightResourceTypes, Hn as verifyVote, Hr as t$3, Ht as RpcEditCommunityParamSchema, I as collectCrosspostAuthorsToResolve, In as verifyCommentModeration, It as RpcCancelExportParamSchema, J as decodeRpcChallengeRequestPubsubMsg, Jn as CreateCommunityListWithCidOptionsSchema, Jr as MAX_FILE_SIZE_BYTES_FOR_COMMENT_UPDATE, Jt as RpcFetchCidResultSchema, K as decodeRpcChallengeAnswerPubsubMsg, Kn as getAuthorNameFromWire, Kr as t$4, Kt as RpcExportCommunityResultSchema, Ln as verifyCommentPubsubMessage, Lt as RpcCidParamSchema, M as parseRawPages, Mr as setNativeFunctions$1, Nn as verifyChallengeVerification, Nr as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, Nt as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, O as findCommentInPageInstance, On as signCommunityList, Ot as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, P as applyNameResolvedCacheToCrosspost, Pn as verifyCommentEdit, Pr as findCommunitiesEntry, Pt as RpcAnchorPublishPreparationResultSchema, Qt as RpcPublishChallengeAnswersParamSchema, R as stripNameResolvedFromCrosspost, Rn as verifyCommentUpdate, Rt as RpcCommentRepliesPageParamSchema, Sn as signCommentEdit, St as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, Tt as parseDecryptedChallengeVerification, Un as buildRuntimeAuthor, Ur as n$3, Ut as RpcExportCommunityModLogsParamSchema, V as InflightFetchManager, Vn as verifyCommunityList, Vt as RpcCommunityPageParamSchema, Wn as cleanWireAuthor, Wt as RpcExportCommunityModLogsResultSchema, Xn as MAX_COMMUNITY_LIST_SIZE_BYTES, Xr as NAME_RESOLVED_TRUE_TTL_MS, Xt as RpcFetchCommunityListResultSchema, Y as decodeRpcChallengeVerificationPubsubMsg, Yn as CreateNewCommunityListOptionsSchema, Yr as NAME_RESOLVED_FALSE_TTL_MS, Yt as RpcFetchCommunityListParamSchema, Zr as NAME_RESOLVE_FAILED_RETRY_FLOOR_MS, Zt as RpcPublishAnchorRecordParamSchema, _n as signChallengeAnswer, _t as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, an as RpcUnsubscribeParamSchema, b as KeyvBetterSqlite3, br as findLocalCommunityAddress, ct as parseCommentUpdateSchemaWithPKCErrorIfItFails, dn as decryptEd25519AesGcm, ei as nativeFunctions$2, en as RpcPublishCommunityListResultSchema, er as getCommunityAddressFromRecord, et as parseCidStringSchemaWithPKCErrorIfItFails, ft as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, gn as cleanUpBeforePublishing, gt as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, hr as createKuboRpcClient, ht as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, in as RpcSuccessResultSchema, ir as decode, it as parseCommentIpfsSchemaWithPKCErrorIfItFails, jn as verifyChallengeMessage, jt as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, k as findCommentInPageInstanceRecursively, kn as signVote, kt as parseRpcCommentEventWithPKCErrorIfItFails, l as pkcJsPageSorts, ln as createSigner, lr as getPKCAddressFromPublicKeySync, lt as parseCommunityAddressWithPKCErrorIfItFails, m as pkcJsChallenges, mt as parseCommunityListSchemaWithPKCErrorIfItFails, n as RpcRemoteCommunity, nn as RpcResolveAuthorNameResultSchema, nr as getCommunityPublicKeyFromWire, on as findCommunityRecordNameMismatch, or as getBufferedPKCAddressFromPublicKey, ot as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, pn as encryptEd25519AesGcm, q as decodeRpcChallengePubsubMsg, qn as normalizeCreatePublicationAuthor, qt as RpcFetchCidParamSchema, rn as RpcSubscriptionIdResultSchema, rr as normalizeCommunityInputFromCommunity, rt as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, sn as require_lib$1, st as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, t as RpcLocalCommunity, tn as RpcPublishedAnchorRecordResultSchema, tr as getCommunityNameFromWire, un as createAnchorIpnsRecord$1, v as TrackedInstanceRegistry, vt as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, x as RemoteCommunity, xn as signComment, xt as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, y as LRUCache, yn as signChallengeRequest, z as PKCClientsManager, zr as t$5, zt as RpcCommunitiesChangeEventResultSchema } from "./rpc-local-community-Cy03QajY.js";
4
- import { s as getHeliaDebugContext } from "./util-C4y8KHmp.js";
2
+ import { $ as retryKuboIpfsAdd, At as ChallengeAnswerMessageSchema, Br as messages, C as hideClassPrivateProps, Cr as e, D as isIpfsCid, Dt as require_sha256, E as isAbortError, Er as r, Et as untrackUpdatingCommunity, Fr as FailedToFetchCommentUpdateFromGatewaysError, In as CommentUpdateForChallengeVerificationSchema, It as ChallengeVerificationMessageSchema, Jt as version_default, Mt as ChallengeMessageSchema, Nr as require_retry$1, Ot as TimeoutError, Pr as FailedToFetchCommentIpfsFromGatewaysError, Pt as ChallengeRequestMessageSchema, Rr as FailedToFetchPageIpfsFromGatewaysError, Sr as t$1, St as trackUpdatingComment, T as ipnsNameToIpnsOverPubsubTopic, Tt as untrackUpdatingComment, U as rejectWhenAbortSignalFires, Vr as logger_default, W as rejectWhenCommunityStopsOrAborts, Wr as setErrorMap, X as replaceXWithY, Y as removeUndefinedValuesRecursively, Z as resolveWhenPredicateIsTrue, _t as listUpdatingCommunities, a as calculateStringSizeSameAsIpfsAddCidV0Sync, at as throwIfAbortSignalAborted, br as n$1, cn as CommunityAnchorSchema, d as deepMergeRuntimeFields, dt as findStartedCommunity, et as retryKuboIpfsAddAndProvide, ft as findUpdatingComment, gr as isStringDomain, gt as listUpdatingComments, ht as listStartedCommunities, i as calculateStringSizeSameAsIpfsAddCidV0, ii as en_default, jn as CommentIpfsSchema, k as isIpns, kt as pTimeout, nt as shortifyCid, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsSchema, pt as findUpdatingCommunity, r as calculateIpfsCidV0, rt as sleepUntilTimeoutOrAbort, st as waitForUpdateInCommunityInstanceWithErrorAndTimeout, tt as shortifyAddress, u as createAbortError, vr as n$2, vt as refreshTrackedCommentAliases, wr as e$1, x as getPostUpdateTimestampRange, xn as PubsubTopicSchema, z as linkAbortSignals, zn as CommentUpdateSchema, zr as PKCError } from "./util-N_HlPQHv.js";
3
+ import { $r as t$2, $t as RpcPublishCommunityListParamSchema, A as findCommentInParsedPages, An as signVote, At as parseRpcCommentUpdateEventWithPKCErrorIfItFails, B as GenericStateClient, Br as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, Bt as RpcCommunityIdentifierParamSchema, C as RepliesPages, Cn as signCommentEdit, Ct as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, D as extractCommunityRuntimeFieldsFromParsedPages, Dt as parseJsonWithPKCErrorIfFails, Er as findLocalCommunityAddress, Et as parseDecryptedChallengeWithPKCErrorIfItFails, F as cloneCrosspostForRuntime, Fn as verifyCommentEdit, Ft as RpcAuthorNameParamSchema, G as PKCTypedEmitter, Gr as toCommunitiesEntry, Gt as RpcExportCommunityParamSchema, H as InflightResourceTypes, Hn as verifyCommunityList, Ht as RpcEditCommunityParamSchema, I as collectCrosspostAuthorsToResolve, In as verifyCommentIpfs, Ir as registerLocalCommunity, It as RpcCancelExportParamSchema, J as decodeRpcChallengeRequestPubsubMsg, Jn as buildRuntimeAuthor, Jt as RpcFetchCidResultSchema, K as decodeRpcChallengeAnswerPubsubMsg, Kn as mergeAuthorProps, Kt as RpcExportCommunityResultSchema, Ln as verifyCommentModeration, Lt as RpcCidParamSchema, M as parseRawPages, Mn as verifyChallengeMessage, Mr as isLocalCommunityAddress, Nr as markLocalCommunityDbAsBeingWritten, Nt as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, O as findCommentInPageInstance, On as signCommunityEdit, Ot as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, P as applyNameResolvedCacheToCrosspost, Pn as verifyChallengeVerification, Pr as monitorCommunitiesDirectory, Pt as RpcAnchorPublishPreparationResultSchema, Qn as normalizeCreatePublicationAuthor, Qt as RpcPublishChallengeAnswersParamSchema, R as stripNameResolvedFromCrosspost, Rn as verifyCommentPubsubMessage, Rt as RpcCommentRepliesPageParamSchema, Sn as signComment, St as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, Tt as parseDecryptedChallengeVerification, Un as verifyVote, Ut as RpcExportCommunityModLogsParamSchema, V as InflightFetchManager, Vn as verifyCommunityEdit, Vt as RpcCommunityPageParamSchema, Wn as assignUnknownProps, Wr as findCommunitiesEntry, Wt as RpcExportCommunityModLogsResultSchema, Xn as getAuthorNameFromRuntime, Xr as t$3, Xt as RpcFetchCommunityListResultSchema, Y as decodeRpcChallengeVerificationPubsubMsg, Yn as cleanWireAuthor, Yt as RpcFetchCommunityListParamSchema, Zn as getAuthorNameFromWire, Zr as n$3, Zt as RpcPublishAnchorRecordParamSchema, _n as cleanUpBeforePublishing, _t as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, an as RpcUnsubscribeParamSchema, ar as buildRuntimeCommunityFields, b as KeyvBetterSqlite3, bn as signChallengeRequest, cn as require_lib$1, cr as getCommunityPublicKeyFromWire, ct as parseCommentUpdateSchemaWithPKCErrorIfItFails, dn as createAnchorIpnsRecord$1, ei as t$4, en as RpcPublishCommunityListResultSchema, er as CreateCommunityListWithCidOptionsSchema, et as parseCidStringSchemaWithPKCErrorIfItFails, fn as decryptEd25519AesGcm, fr as getBufferedPKCAddressFromPublicKey, ft as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, gt as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, hr as getPKCAddressFromPublicKeySync, ht as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, ii as NAME_RESOLVE_FAILED_RETRY_FLOOR_MS, in as RpcSuccessResultSchema, it as parseCommentIpfsSchemaWithPKCErrorIfItFails, jt as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, k as findCommentInPageInstanceRecursively, kn as signCommunityList, kr as getDefaultDataPath, kt as parseRpcCommentEventWithPKCErrorIfItFails, l as pkcJsPageSorts, lr as normalizeCommunityInputFromCommunity, lt as parseCommunityAddressWithPKCErrorIfItFails, m as pkcJsChallenges, mn as encryptEd25519AesGcm, mt as parseCommunityListSchemaWithPKCErrorIfItFails, n as RpcRemoteCommunity, ni as NAME_RESOLVED_FALSE_TTL_MS, nn as RpcResolveAuthorNameResultSchema, nr as MAX_COMMUNITY_LIST_SIZE_BYTES, on as findCommunityRecordNameMismatch, or as getCommunityAddressFromRecord, ot as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, q as decodeRpcChallengePubsubMsg, qn as withoutForbiddenKeys, qr as t$5, qt as RpcFetchCidParamSchema, ri as NAME_RESOLVED_TRUE_TTL_MS, rn as RpcSubscriptionIdResultSchema, rt as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, si as nativeFunctions$2, sn as verifyAuthorWalletEntry, sr as getCommunityNameFromWire, st as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, t as RpcLocalCommunity, ti as MAX_FILE_SIZE_BYTES_FOR_COMMENT_UPDATE, tn as RpcPublishedAnchorRecordResultSchema, tr as CreateNewCommunityListOptionsSchema, un as createSigner, ur as decode, v as TrackedInstanceRegistry, vn as signChallengeAnswer, vt as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, wn as signCommentModeration, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, x as RemoteCommunity, xr as createKuboRpcClient, xt as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, y as LRUCache, z as PKCClientsManager, zn as verifyCommentUpdate, zr as setNativeFunctions$1, zt as RpcCommunitiesChangeEventResultSchema } from "./rpc-local-community-BqJ_olvR.js";
4
+ import { s as getHeliaDebugContext } from "./util-BpiQT2hV.js";
5
5
  import path from "path";
6
6
  import assert from "assert";
7
7
  import fs from "fs";
@@ -27366,6 +27366,7 @@ var PublicationClientsManager = class extends PKCClientsManager {
27366
27366
  };
27367
27367
  //#endregion
27368
27368
  //#region dist/node/publications/publication.js
27369
+ const LOCAL_COMMUNITY_PROVIDER = "publishing directly to local community instance";
27369
27370
  var Publication = class extends import_lib.TypedEmitter {
27370
27371
  constructor(pkc) {
27371
27372
  super();
@@ -27373,12 +27374,15 @@ var Publication = class extends import_lib.TypedEmitter {
27373
27374
  this._community = void 0;
27374
27375
  this._signedWithKnownCommunityFields = void 0;
27375
27376
  this._challengeExchanges = {};
27377
+ this._isPublishSpent = false;
27378
+ this._isPublishCallRunning = false;
27379
+ this._publishEndedBy = void 0;
27376
27380
  this._rpcPublishSubscriptionId = void 0;
27377
27381
  this._pkc = pkc;
27378
27382
  this._updatePublishingStateWithEmission("stopped");
27379
27383
  this._setStateWithEmission("stopped");
27380
27384
  this._initClients();
27381
- this._handleChallengeExchange = this._handleChallengeExchange.bind(this);
27385
+ this._handleChallengeExchange = this._guardDetachedHandler("_handleChallengeExchange", this._handleChallengeExchange.bind(this));
27382
27386
  this.publish = this.publish.bind(this);
27383
27387
  this.on("error", (...args) => this.listenerCount("error") === 1 && this._pkc.emit("error", ...args));
27384
27388
  this._publishToDifferentProviderThresholdSeconds = 10;
@@ -27405,10 +27409,16 @@ var Publication = class extends import_lib.TypedEmitter {
27405
27409
  author: props.author,
27406
27410
  signaturePublicKey: props.signature.publicKey
27407
27411
  });
27408
- this.author = {
27409
- ...runtimeAuthor,
27410
- shortAddress: shortifyAddress(runtimeAuthor.address)
27411
- };
27412
+ const author = {};
27413
+ const { skipped } = mergeAuthorProps({
27414
+ target: author,
27415
+ props: {
27416
+ ...runtimeAuthor,
27417
+ shortAddress: shortifyAddress(runtimeAuthor.address)
27418
+ }
27419
+ });
27420
+ if (skipped.length > 0) logger_default("pkc-js:publication:_initAuthor").error("Refused author props of a record that collide with an object", skipped);
27421
+ this.author = author;
27412
27422
  this.protocolVersion = props.protocolVersion;
27413
27423
  }
27414
27424
  _initUnsignedLocalProps(opts) {
@@ -27486,28 +27496,27 @@ var Publication = class extends import_lib.TypedEmitter {
27486
27496
  };
27487
27497
  }
27488
27498
  async _handleRpcChallengeVerification(verification, runtimeFields) {
27489
- const log = logger_default("pkc-js:publication:_handleRpcChallengeVerification");
27490
- if (verification.comment) await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(verification);
27491
- if (this instanceof Comment && runtimeFields) deepMergeRuntimeFields(this, runtimeFields);
27492
- this._setRpcClientState("stopped");
27493
- const newPublishingState = verification.challengeSuccess ? "succeeded" : "failed";
27494
- this._changePublicationStateEmitEventEmitStateChangeEvent({
27495
- newPublishingState,
27496
- newState: "stopped",
27497
- event: {
27498
- name: "challengeverification",
27499
- args: [verification, this instanceof Comment && verification.comment ? this : void 0]
27500
- }
27501
- });
27502
- this._unregisterFromPkcOncePublishWorkSettles();
27503
- if (this._rpcPublishSubscriptionId) {
27504
- const subscriptionId = this._rpcPublishSubscriptionId;
27505
- this._rpcPublishSubscriptionId = void 0;
27506
- try {
27507
- await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
27508
- } catch (e) {
27509
- log.error("Failed to unsubscribe from publication publish", e);
27510
- }
27499
+ if (verification.comment) try {
27500
+ await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(verification);
27501
+ } catch (e) {
27502
+ logger_default("pkc-js:publication:_handleRpcChallengeVerification").error("The comment in a successful challenge verification does not verify", e);
27503
+ await this._tearDownThenWriteFailure(e);
27504
+ return;
27505
+ }
27506
+ try {
27507
+ if (this instanceof Comment && runtimeFields) deepMergeRuntimeFields(this, runtimeFields);
27508
+ this._setRpcClientState("stopped");
27509
+ const newPublishingState = verification.challengeSuccess ? "succeeded" : "failed";
27510
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
27511
+ newPublishingState,
27512
+ newState: "stopped",
27513
+ event: {
27514
+ name: "challengeverification",
27515
+ args: [verification, this instanceof Comment && verification.comment ? this : void 0]
27516
+ }
27517
+ });
27518
+ } finally {
27519
+ await this._tearDownWithoutThrowing();
27511
27520
  }
27512
27521
  }
27513
27522
  async _handleIncomingChallengePubsubMessage(msg) {
@@ -27518,19 +27527,13 @@ var Publication = class extends import_lib.TypedEmitter {
27518
27527
  communityChallengeSignerAddress: this._communityChallengeMsgSignerAddress(),
27519
27528
  validateTimestampRange: true
27520
27529
  });
27530
+ if (this._hasPublishEnded()) return;
27521
27531
  if (!challengeMsgValidity.valid) {
27522
27532
  const error = new PKCError("ERR_CHALLENGE_SIGNATURE_IS_INVALID", {
27523
27533
  pubsubMsg: msg,
27524
27534
  reason: challengeMsgValidity.reason
27525
27535
  });
27526
- log.error("received challenge message with invalid signature", error.toString());
27527
- this._changePublicationStateEmitEventEmitStateChangeEvent({
27528
- newPublishingState: "failed",
27529
- event: {
27530
- name: "error",
27531
- args: [error]
27532
- }
27533
- });
27536
+ log.error("Dropping a challenge message with an invalid signature", error.toString());
27534
27537
  return;
27535
27538
  }
27536
27539
  log(`Received encrypted challenges. Will decrypt and emit them on "challenge" event. User shoud publish solution by calling publishChallengeAnswers`);
@@ -27540,6 +27543,7 @@ var Publication = class extends import_lib.TypedEmitter {
27540
27543
  try {
27541
27544
  decryptedRawString = await decryptEd25519AesGcm(msg.encrypted, pubsubSigner.privateKey, this._community.encryption.publicKey);
27542
27545
  } catch (e) {
27546
+ if (this._hasPublishEnded()) return;
27543
27547
  const pkcError = new PKCError("ERR_PUBLICATION_FAILED_TO_DECRYPT_CHALLENGE", { decryptErr: e });
27544
27548
  log.error("could not decrypt challengemessage.encrypted", pkcError.toString());
27545
27549
  this._changePublicationStateEmitEventEmitStateChangeEvent({
@@ -27555,6 +27559,7 @@ var Publication = class extends import_lib.TypedEmitter {
27555
27559
  try {
27556
27560
  decryptedJson = await parseJsonWithPKCErrorIfFails(decryptedRawString);
27557
27561
  } catch (e) {
27562
+ if (this._hasPublishEnded()) return;
27558
27563
  log.error("could not parse decrypted challengemessage.encrypted as a json", String(e));
27559
27564
  this._changePublicationStateEmitEventEmitStateChangeEvent({
27560
27565
  newPublishingState: "failed",
@@ -27569,6 +27574,7 @@ var Publication = class extends import_lib.TypedEmitter {
27569
27574
  try {
27570
27575
  decryptedChallenge = parseDecryptedChallengeWithPKCErrorIfItFails(decryptedJson);
27571
27576
  } catch (e) {
27577
+ if (this._hasPublishEnded()) return;
27572
27578
  log.error("could not parse z challengemessage.encrypted as a json", String(e));
27573
27579
  this._changePublicationStateEmitEventEmitStateChangeEvent({
27574
27580
  newPublishingState: "failed",
@@ -27587,6 +27593,7 @@ var Publication = class extends import_lib.TypedEmitter {
27587
27593
  log.trace("Received a copy of a challenge that was already handled, ignoring it");
27588
27594
  return;
27589
27595
  }
27596
+ if (this._hasPublishEnded()) return;
27590
27597
  this._challengeExchanges[msg.challengeRequestId.toString()].challenge = decryptedChallengeMsg;
27591
27598
  this._updatePublishingStateWithEmission("waiting-challenge-answers");
27592
27599
  const challengeTopic = this._community?.pubsubTopic;
@@ -27601,19 +27608,13 @@ var Publication = class extends import_lib.TypedEmitter {
27601
27608
  communityChallengeSignerAddress: this._communityChallengeMsgSignerAddress(),
27602
27609
  validateTimestampRange: true
27603
27610
  });
27611
+ if (this._hasPublishEnded()) return;
27604
27612
  if (!signatureValidation.valid) {
27605
27613
  const error = new PKCError("ERR_CHALLENGE_VERIFICATION_SIGNATURE_IS_INVALID", {
27606
27614
  pubsubMsg: msg,
27607
27615
  reason: signatureValidation.reason
27608
27616
  });
27609
- log.error("Publication received a challenge verification with invalid signature", error);
27610
- this._changePublicationStateEmitEventEmitStateChangeEvent({
27611
- newPublishingState: "failed",
27612
- event: {
27613
- name: "error",
27614
- args: [error]
27615
- }
27616
- });
27617
+ log.error("Dropping a challenge verification with an invalid signature", error);
27617
27618
  return;
27618
27619
  }
27619
27620
  let decryptedChallengeVerification;
@@ -27633,7 +27634,10 @@ var Publication = class extends import_lib.TypedEmitter {
27633
27634
  challenegVerificationMsg: msg
27634
27635
  });
27635
27636
  log.error("could not decrypt challengeverification.encrypted", pkcError);
27636
- this.emit("error", pkcError);
27637
+ await this._endExchangeWithUnreadableChallengeVerification({
27638
+ verification: msg,
27639
+ error: pkcError
27640
+ });
27637
27641
  return;
27638
27642
  }
27639
27643
  let decryptedJson;
@@ -27641,14 +27645,20 @@ var Publication = class extends import_lib.TypedEmitter {
27641
27645
  decryptedJson = await parseJsonWithPKCErrorIfFails(decryptedRawString);
27642
27646
  } catch (e) {
27643
27647
  log.error("could not parse decrypted challengeverification.encrypted as a json", e);
27644
- this.emit("error", e);
27648
+ await this._endExchangeWithUnreadableChallengeVerification({
27649
+ verification: msg,
27650
+ error: e
27651
+ });
27645
27652
  return;
27646
27653
  }
27647
27654
  try {
27648
27655
  decryptedChallengeVerification = parseDecryptedChallengeVerification(decryptedJson);
27649
27656
  } catch (e) {
27650
27657
  log.error("could not parse challengeverification.encrypted due to invalid schema", e);
27651
- this.emit("error", e);
27658
+ await this._endExchangeWithUnreadableChallengeVerification({
27659
+ verification: msg,
27660
+ error: e
27661
+ });
27652
27662
  return;
27653
27663
  }
27654
27664
  }
@@ -27664,21 +27674,66 @@ var Publication = class extends import_lib.TypedEmitter {
27664
27674
  log.trace("Received a copy of a challenge verification that was already handled, ignoring it");
27665
27675
  return;
27666
27676
  }
27677
+ if (!this._claimPublishEnd("verification")) return;
27667
27678
  this._challengeExchanges[msg.challengeRequestId.toString()].challengeVerification = challengeVerificationMsg;
27668
27679
  if (decryptedChallengeVerification?.comment) {
27669
- await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(decryptedChallengeVerification);
27680
+ try {
27681
+ await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(decryptedChallengeVerification);
27682
+ } catch (e) {
27683
+ log.error("The comment in a successful challenge verification does not verify", e);
27684
+ await this._tearDownThenWriteFailure(e);
27685
+ return;
27686
+ }
27670
27687
  log("Updated the props of this instance with challengeverification.encrypted");
27671
27688
  }
27672
- Object.values(this._challengeExchanges).forEach((exchange) => this._updatePubsubState("stopped", exchange.providerUrl));
27689
+ try {
27690
+ Object.values(this._challengeExchanges).forEach((exchange) => this._updatePubsubState("stopped", exchange.providerUrl));
27691
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
27692
+ newPublishingState,
27693
+ newState: "stopped",
27694
+ event: {
27695
+ name: "challengeverification",
27696
+ args: [challengeVerificationMsg, this instanceof Comment && decryptedChallengeVerification ? this : void 0]
27697
+ }
27698
+ });
27699
+ } finally {
27700
+ await this._tearDownWithoutThrowing();
27701
+ }
27702
+ }
27703
+ async _endExchangeWithUnreadableChallengeVerification({ verification, error }) {
27704
+ const exchange = this._challengeExchanges[verification.challengeRequestId.toString()];
27705
+ if (exchange.challengeVerification || this._hasPublishEnded()) return;
27706
+ exchange.challengeVerification = verification;
27707
+ await this._endPublishWithFailure(() => this._changePublicationStateEmitEventEmitStateChangeEvent({
27708
+ newPublishingState: "failed",
27709
+ event: {
27710
+ name: "error",
27711
+ args: [error]
27712
+ }
27713
+ }));
27714
+ }
27715
+ _claimPublishEnd(endedBy) {
27716
+ if (this._publishEndedBy) return false;
27717
+ this._publishEndedBy = endedBy;
27718
+ return true;
27719
+ }
27720
+ _hasPublishEnded() {
27721
+ return this._publishEndedBy !== void 0 || this._pkc.destroyed;
27722
+ }
27723
+ async _endPublishWithFailure(writeFailure) {
27724
+ if (!this._claimPublishEnd("failure")) return void 0;
27725
+ await this._postSucessOrFailurePublishing();
27726
+ return writeFailure();
27727
+ }
27728
+ async _tearDownThenWriteFailure(error) {
27729
+ await this._tearDownWithoutThrowing();
27673
27730
  this._changePublicationStateEmitEventEmitStateChangeEvent({
27674
- newPublishingState,
27675
- newState: "stopped",
27731
+ newPublishingState: "failed",
27676
27732
  event: {
27677
- name: "challengeverification",
27678
- args: [challengeVerificationMsg, this instanceof Comment && decryptedChallengeVerification ? this : void 0]
27733
+ name: "error",
27734
+ args: [error]
27679
27735
  }
27680
27736
  });
27681
- await this._postSucessOrFailurePublishing();
27682
27737
  }
27683
27738
  async _handleChallengeExchange(pubsubMsg) {
27684
27739
  const log = logger_default("pkc-js:publication:handleChallengeExchange");
@@ -27727,6 +27782,12 @@ var Publication = class extends import_lib.TypedEmitter {
27727
27782
  challengeAnswers: toEncryptAnswers.challengeAnswers
27728
27783
  });
27729
27784
  }
27785
+ if (this._publishEndedBy) throw new PKCError("ERR_PUBLICATION_CHALLENGE_EXCHANGE_ENDED", {
27786
+ publicationType: this.getType(),
27787
+ state: this.state,
27788
+ publishingState: this.publishingState,
27789
+ endedBy: this._publishEndedBy
27790
+ });
27730
27791
  const challengeExchangesWithChallenge = Object.values(this._challengeExchanges).filter((exchange) => exchange.challenge);
27731
27792
  if (challengeExchangesWithChallenge.length === 0) throw Error("No challenge exchanges with challenge");
27732
27793
  if (challengeExchangesWithChallenge.length > 1) throw Error("We should only have one challenge exchange with challenge");
@@ -27761,15 +27822,29 @@ var Publication = class extends import_lib.TypedEmitter {
27761
27822
  challengeExchange.challengeAnswerPublishInFlight = false;
27762
27823
  throw e;
27763
27824
  }
27825
+ const throwIfExchangeEnded = () => {
27826
+ if (!this._publishEndedBy) return;
27827
+ challengeExchange.challengeAnswerPublishInFlight = false;
27828
+ throw new PKCError("ERR_PUBLICATION_CHALLENGE_EXCHANGE_ENDED", {
27829
+ publicationType: this.getType(),
27830
+ state: this.state,
27831
+ publishingState: this.publishingState,
27832
+ endedBy: this._publishEndedBy
27833
+ });
27834
+ };
27835
+ throwIfExchangeEnded();
27764
27836
  this._updatePublishingStateWithEmission("publishing-challenge-answer");
27837
+ throwIfExchangeEnded();
27765
27838
  this._updatePubsubState("publishing-challenge-answer", challengeExchange.providerUrl);
27766
27839
  if (this._publishingToLocalCommunity) try {
27767
27840
  await this._publishingToLocalCommunity.handleChallengeAnswer(answerMsgToPublish);
27768
27841
  } catch (e) {
27769
27842
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishError = e;
27770
27843
  challengeExchange.challengeAnswerPublishInFlight = false;
27771
- this._updatePublishingStateWithEmission("failed");
27772
- this._updatePubsubState("stopped", challengeExchange.providerUrl);
27844
+ if (!this._publishEndedBy) {
27845
+ this._updatePublishingStateWithEmission("failed");
27846
+ this._updatePubsubState("stopped", challengeExchange.providerUrl);
27847
+ }
27773
27848
  throw e;
27774
27849
  }
27775
27850
  else try {
@@ -27777,8 +27852,10 @@ var Publication = class extends import_lib.TypedEmitter {
27777
27852
  } catch (e) {
27778
27853
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishError = e;
27779
27854
  challengeExchange.challengeAnswerPublishInFlight = false;
27780
- this._updatePublishingStateWithEmission("failed");
27781
- this._updatePubsubState("stopped", challengeExchange.providerUrl);
27855
+ if (!this._publishEndedBy) {
27856
+ this._updatePublishingStateWithEmission("failed");
27857
+ this._updatePubsubState("stopped", challengeExchange.providerUrl);
27858
+ }
27782
27859
  throw e;
27783
27860
  }
27784
27861
  const decryptedChallengeAnswer = {
@@ -27787,9 +27864,12 @@ var Publication = class extends import_lib.TypedEmitter {
27787
27864
  };
27788
27865
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswer = decryptedChallengeAnswer;
27789
27866
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishTimestamp = timestamp();
27790
- this._updatePublishingStateWithEmission("waiting-challenge-verification");
27791
- const challengeTopic = this._community?.pubsubTopic;
27792
- Object.entries(this._clientsManager.pubsubProviderSubscriptions).filter(([, pubsubTopics]) => typeof challengeTopic === "string" && pubsubTopics.includes(challengeTopic)).map(([provider]) => provider).forEach((provider) => this._updatePubsubState("waiting-challenge-verification", provider));
27867
+ if (this._publishEndedBy === "stop") return;
27868
+ if (!this._publishEndedBy) {
27869
+ this._updatePublishingStateWithEmission("waiting-challenge-verification");
27870
+ const challengeTopic = this._community?.pubsubTopic;
27871
+ Object.entries(this._clientsManager.pubsubProviderSubscriptions).filter(([, pubsubTopics]) => typeof challengeTopic === "string" && pubsubTopics.includes(challengeTopic)).map(([provider]) => provider).forEach((provider) => this._updatePubsubState("waiting-challenge-verification", provider));
27872
+ }
27793
27873
  log(`Responded to challenge with answers`, challengeAnswers);
27794
27874
  this.emit("challengeanswer", decryptedChallengeAnswer);
27795
27875
  }
@@ -27807,6 +27887,27 @@ var Publication = class extends import_lib.TypedEmitter {
27807
27887
  communityAddress: this.communityAddress
27808
27888
  });
27809
27889
  }
27890
+ _validateAuthorWalletProofs() {
27891
+ const signed = this.raw.pubsubMessageToPublish;
27892
+ const wallets = signed?.author?.wallets;
27893
+ if (!wallets || !signed?.signature?.publicKey) return;
27894
+ const authorPublicKey = getPKCAddressFromPublicKeySync(signed.signature.publicKey);
27895
+ for (const [chainTicker, entry] of Object.entries(wallets)) {
27896
+ const result = verifyAuthorWalletEntry({
27897
+ entry,
27898
+ authorPublicKey,
27899
+ nowSeconds: timestamp()
27900
+ });
27901
+ if (result.outcome === "invalid") {
27902
+ if (this.state === "publishing") this._setStateWithEmission("stopped");
27903
+ throw new PKCError("ERR_AUTHOR_WALLET_PROOF_IS_INVALID", {
27904
+ chainTicker,
27905
+ reason: result.reason,
27906
+ entry
27907
+ });
27908
+ }
27909
+ }
27910
+ }
27810
27911
  _validateCommunityFields() {
27811
27912
  if (typeof this._community?.encryption?.publicKey !== "string") throw new PKCError("ERR_COMMUNITY_MISSING_FIELD", { communityPublicKey: this._community?.encryption?.publicKey });
27812
27913
  }
@@ -27875,8 +27976,9 @@ var Publication = class extends import_lib.TypedEmitter {
27875
27976
  publicationType: this.getType(),
27876
27977
  communityAddress: this.communityAddress
27877
27978
  }));
27878
- if (this._backgroundCommunityRefresh) await this._backgroundCommunityRefresh;
27979
+ const refresh = this._backgroundCommunityRefresh;
27879
27980
  this._resetCommunityFetchAbortSignal();
27981
+ if (refresh) await refresh;
27880
27982
  }
27881
27983
  _resetCommunityFetchAbortSignal() {
27882
27984
  this._communityFetchAbortController = void 0;
@@ -27890,9 +27992,6 @@ var Publication = class extends import_lib.TypedEmitter {
27890
27992
  if (!this._publishRunWaitSignal) this._beginPublishRun();
27891
27993
  return this._publishRunWaitSignal;
27892
27994
  }
27893
- _isPublishRunOver(runSignal) {
27894
- return this._pkc.destroyed || runSignal.aborted;
27895
- }
27896
27995
  _getCommunityCache() {
27897
27996
  const cache = this._pkc._memCaches.communityForPublishing;
27898
27997
  if (cache.has(this.communityAddress)) return cache.get(this.communityAddress);
@@ -27954,20 +28053,26 @@ var Publication = class extends import_lib.TypedEmitter {
27954
28053
  } else return this._clientsManager.fetchCommunityForPublishingWithCacheGuard();
27955
28054
  }
27956
28055
  async stop() {
28056
+ const wasPublishCalled = this._isPublishSpent || this._isPublishCallRunning;
28057
+ if (wasPublishCalled) this._isPublishSpent = true;
28058
+ const endedByThisStop = wasPublishCalled ? this._claimPublishEnd("stop") : true;
27957
28059
  this._communityFetchAbortController?.abort(new PKCError("ERR_GET_COMMUNITY_ABORTED", {
27958
28060
  publicationType: this.getType(),
27959
28061
  communityAddress: this.communityAddress
27960
28062
  }));
28063
+ if (!wasPublishCalled) this._resetCommunityFetchAbortSignal();
27961
28064
  try {
27962
28065
  await this._postSucessOrFailurePublishing();
27963
28066
  } finally {
27964
- if (this._backgroundCommunityRefresh) await this._backgroundCommunityRefresh;
27965
- this._updatePublishingStateWithEmission("stopped");
28067
+ if (wasPublishCalled && this._backgroundCommunityRefresh) await this._backgroundCommunityRefresh;
28068
+ const publishStartedSinceThisStop = !wasPublishCalled && (this._isPublishSpent || this._isPublishCallRunning);
28069
+ if (endedByThisStop && !publishStartedSinceThisStop) this._updatePublishingStateWithEmission("stopped");
27966
28070
  }
27967
28071
  }
27968
28072
  _isAllAttemptsExhausted(maxNumOfChallengeExchanges) {
27969
- if (Object.keys(this._challengeExchanges).length !== maxNumOfChallengeExchanges) return false;
27970
- return Object.values(this._challengeExchanges).every((exchange) => {
28073
+ const challengeExchanges = Object.values(this._challengeExchanges);
28074
+ if (challengeExchanges.length !== maxNumOfChallengeExchanges) return false;
28075
+ return challengeExchanges.every((exchange) => {
27971
28076
  if (exchange.challenge || exchange.challengeVerification) return false;
27972
28077
  if (exchange.challengeRequestPublishError || exchange.challengeAnswerPublishError) return true;
27973
28078
  return typeof exchange.challengeRequestPublishTimestamp === "number" && exchange.challengeRequestPublishTimestamp + this._setProviderFailureThresholdSeconds <= timestamp();
@@ -27977,7 +28082,7 @@ var Publication = class extends import_lib.TypedEmitter {
27977
28082
  return Object.values(this._challengeExchanges).some((exchange) => typeof exchange.challengeRequestPublishTimestamp === "number" && !exchange.challengeRequestPublishError);
27978
28083
  }
27979
28084
  async _abandonProviderIfStoppedWhileSubscribing(providerUrl) {
27980
- if (!this._pkc.destroyed && this.state !== "stopped") return false;
28085
+ if (!this._hasPublishEnded() && this.state !== "stopped") return false;
27981
28086
  const log = logger_default("pkc-js:publication:publish:_abandonProviderIfStoppedWhileSubscribing");
27982
28087
  log("Publication was stopped while subscribing to pubsub, will not publish a challenge request", providerUrl);
27983
28088
  try {
@@ -27993,11 +28098,55 @@ var Publication = class extends import_lib.TypedEmitter {
27993
28098
  if (refresh) refresh.finally(() => this._pkc._publishingPublications.delete(this));
27994
28099
  else this._pkc._publishingPublications.delete(this);
27995
28100
  }
28101
+ _guardDetachedHandler(entryPoint, handler) {
28102
+ return async (...args) => {
28103
+ try {
28104
+ await handler(...args);
28105
+ } catch (e) {
28106
+ await this._endPublicationAfterDetachedFailure(entryPoint, e);
28107
+ }
28108
+ };
28109
+ }
28110
+ async _endPublicationAfterDetachedFailure(entryPoint, cause) {
28111
+ const log = logger_default("pkc-js:publication:_endPublicationAfterDetachedFailure");
28112
+ log.error(`Handler ${entryPoint} of a publication threw`, cause);
28113
+ const error = new PKCError("ERR_PUBLICATION_INTERNAL_ERROR", {
28114
+ entryPoint,
28115
+ cause
28116
+ });
28117
+ const endedBefore = this._publishEndedBy;
28118
+ const failsThePublication = this._claimPublishEnd("failure");
28119
+ try {
28120
+ if (failsThePublication) {
28121
+ try {
28122
+ await this._postSucessOrFailurePublishing();
28123
+ } catch (teardownError) {
28124
+ log.error(`Teardown after the failure of ${entryPoint} threw as well`, teardownError);
28125
+ }
28126
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28127
+ newPublishingState: "failed",
28128
+ event: {
28129
+ name: "error",
28130
+ args: [error]
28131
+ }
28132
+ });
28133
+ } else if (endedBefore !== "stop") this.emit("error", error);
28134
+ } catch (emitError) {
28135
+ log.error(`Could not report the failure of ${entryPoint}`, emitError);
28136
+ }
28137
+ }
28138
+ async _tearDownWithoutThrowing() {
28139
+ try {
28140
+ await this._postSucessOrFailurePublishing();
28141
+ } catch (teardownError) {
28142
+ logger_default("pkc-js:publication:_tearDownWithoutThrowing").error("The teardown that ends the publish threw", teardownError);
28143
+ }
28144
+ }
27996
28145
  async _postSucessOrFailurePublishing() {
27997
28146
  const log = logger_default("pkc-js:publication:_postSucessOrFailurePublishing");
27998
28147
  this._publishRunAbortController?.abort();
27999
28148
  this._unregisterFromPkcOncePublishWorkSettles();
28000
- this._setStateWithEmission("stopped");
28149
+ if (this.state === "publishing") this._setStateWithEmission("stopped");
28001
28150
  if (this._rpcPublishSubscriptionId) {
28002
28151
  const subscriptionId = this._rpcPublishSubscriptionId;
28003
28152
  this._rpcPublishSubscriptionId = void 0;
@@ -28046,6 +28195,7 @@ var Publication = class extends import_lib.TypedEmitter {
28046
28195
  async _handleIncomingChallengeVerificationFromRpc(args) {
28047
28196
  const { challengeVerification: encoded, runtimeFields } = args.params.result;
28048
28197
  const decoded = decodeRpcChallengeVerificationPubsubMsg(encoded);
28198
+ if (!this._claimPublishEnd("verification")) return;
28049
28199
  this._challengeExchanges[decoded.challengeRequestId.toString()] = {
28050
28200
  ...this._challengeExchanges[decoded.challengeRequestId.toString()],
28051
28201
  challengeVerification: decoded
@@ -28064,11 +28214,23 @@ var Publication = class extends import_lib.TypedEmitter {
28064
28214
  async _handleIncomingErrorFromRpc(args) {
28065
28215
  const log = logger_default("pkc-js:publication:publish:_publishWithRpc:_handleIncomingErrorFromRpc");
28066
28216
  const error = args.params.result;
28067
- if (error.details?.newPublishingState) this._updatePublishingStateNoEmission(error.details.newPublishingState);
28068
- if (error.details?.publishThrowError) {
28069
- log.error("RPC server threw an error on publish(), will stop publication", error);
28217
+ if (error.details?.publishThrowError || error.details?.newState === "stopped") {
28218
+ if (!this._claimPublishEnd("failure")) {
28219
+ if (!error.details?.publishThrowError) this.emit("error", error);
28220
+ return;
28221
+ }
28222
+ log.error("The publication failed on the RPC server, will stop publication", error);
28070
28223
  await this._postSucessOrFailurePublishing();
28224
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28225
+ newPublishingState: error.details?.newPublishingState ?? "failed",
28226
+ event: {
28227
+ name: "error",
28228
+ args: [error]
28229
+ }
28230
+ });
28231
+ return;
28071
28232
  }
28233
+ if (error.details?.newPublishingState) this._updatePublishingStateNoEmission(error.details.newPublishingState);
28072
28234
  this.emit("error", error);
28073
28235
  }
28074
28236
  async _publishWithRpc() {
@@ -28082,11 +28244,22 @@ var Publication = class extends import_lib.TypedEmitter {
28082
28244
  commentModeration: rpcClient.publishCommentModeration,
28083
28245
  communityEdit: rpcClient.publishCommunityEdit
28084
28246
  }[this.getType()].bind(rpcClient)(this.toJSONPubsubRequestToEncrypt());
28247
+ if (this._hasPublishEnded()) {
28248
+ try {
28249
+ await rpcClient.unsubscribe(subscriptionId);
28250
+ } catch (e) {
28251
+ logger_default("pkc-js:publication:publish:_publishWithRpc").error("Failed to unsubscribe from a publish stopped while starting", e);
28252
+ }
28253
+ return;
28254
+ }
28085
28255
  this._rpcPublishSubscriptionId = subscriptionId;
28256
+ const unlessStopped = (handler) => (args) => {
28257
+ if (this._publishEndedBy !== "stop" && this._publishEndedBy !== "failure") return handler(args);
28258
+ };
28086
28259
  rpcClient.attachSubscriptionHandlersDeferred({
28087
28260
  subscriptionId,
28088
28261
  isStale: () => this._rpcPublishSubscriptionId !== subscriptionId,
28089
- attach: (subscription) => subscription.on("challengerequest", this._handleIncomingChallengeRequestFromRpc.bind(this)).on("challenge", this._handleIncomingChallengeFromRpc.bind(this)).on("challengeanswer", this._handleIncomingChallengeAnswerFromRpc.bind(this)).on("challengeverification", this._handleIncomingChallengeVerificationFromRpc.bind(this)).on("publishingstatechange", this._handleIncomingPublishingStateFromRpc.bind(this)).on("statechange", this._handleIncomingStateFromRpc.bind(this)).on("error", this._handleIncomingErrorFromRpc.bind(this)),
28262
+ attach: (subscription) => subscription.on("challengerequest", unlessStopped(this._guardDetachedHandler("_handleIncomingChallengeRequestFromRpc", this._handleIncomingChallengeRequestFromRpc.bind(this)))).on("challenge", unlessStopped(this._guardDetachedHandler("_handleIncomingChallengeFromRpc", this._handleIncomingChallengeFromRpc.bind(this)))).on("challengeanswer", unlessStopped(this._guardDetachedHandler("_handleIncomingChallengeAnswerFromRpc", this._handleIncomingChallengeAnswerFromRpc.bind(this)))).on("challengeverification", unlessStopped(this._guardDetachedHandler("_handleIncomingChallengeVerificationFromRpc", this._handleIncomingChallengeVerificationFromRpc.bind(this)))).on("publishingstatechange", unlessStopped(this._guardDetachedHandler("_handleIncomingPublishingStateFromRpc", this._handleIncomingPublishingStateFromRpc.bind(this)))).on("statechange", unlessStopped(this._guardDetachedHandler("_handleIncomingStateFromRpc", this._handleIncomingStateFromRpc.bind(this)))).on("error", unlessStopped(this._guardDetachedHandler("_handleIncomingErrorFromRpc", this._handleIncomingErrorFromRpc.bind(this)))),
28090
28263
  replayErrorContainment: {
28091
28264
  entityName: "publication",
28092
28265
  log: logger_default("pkc-js:publication:publish:_publishWithRpc"),
@@ -28150,8 +28323,10 @@ var Publication = class extends import_lib.TypedEmitter {
28150
28323
  this._community = await this._fetchCommunityForPublishing();
28151
28324
  this._validateCommunityFields();
28152
28325
  } catch (e) {
28153
- this._setStateWithEmission("stopped");
28154
- this._updatePublishingStateWithEmission("failed");
28326
+ if (!this._hasPublishEnded()) {
28327
+ this._setStateWithEmission("stopped");
28328
+ this._updatePublishingStateWithEmission("failed");
28329
+ }
28155
28330
  throw e;
28156
28331
  }
28157
28332
  }
@@ -28190,7 +28365,7 @@ var Publication = class extends import_lib.TypedEmitter {
28190
28365
  async _handleNotReceivingResponseToChallengeRequest({ providers, currentPubsubProviderIndex, acceptedChallengeTypes }) {
28191
28366
  const runSignal = this._getPublishRunWaitSignal();
28192
28367
  await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1e3, runSignal);
28193
- if (this._isPublishRunOver(runSignal)) return;
28368
+ if (this._hasPublishEnded()) return;
28194
28369
  if (this._didWeReceiveChallengeOrChallengeVerification()) return;
28195
28370
  const currentPubsubProvider = providers[currentPubsubProviderIndex];
28196
28371
  this._pkc._stats.recordGatewayFailure(currentPubsubProvider, "pubsub-publish");
@@ -28198,59 +28373,62 @@ var Publication = class extends import_lib.TypedEmitter {
28198
28373
  const log = logger_default("pkc-js:publication:publish:_handleNotReceivingResponseToChallengeRequest");
28199
28374
  if (this._isAllAttemptsExhausted(providers.length)) {
28200
28375
  log.error(`Failed to receive any response for publication`, this.getType());
28201
- await this._postSucessOrFailurePublishing();
28202
- const error = new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
28203
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
28204
- publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
28205
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28206
- });
28207
- this._changePublicationStateEmitEventEmitStateChangeEvent({
28208
- newPublishingState: "failed",
28209
- event: {
28210
- name: "error",
28211
- args: [error]
28212
- }
28376
+ await this._endPublishWithFailure(() => {
28377
+ const error = new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
28378
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
28379
+ publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
28380
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28381
+ });
28382
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28383
+ newPublishingState: "failed",
28384
+ event: {
28385
+ name: "error",
28386
+ args: [error]
28387
+ }
28388
+ });
28213
28389
  });
28214
28390
  } else if (this.state === "stopped") {
28215
28391
  log.error(`Publication is stopped, will not re-publish`);
28216
28392
  await this._postSucessOrFailurePublishing();
28217
- } else if (currentPubsubProviderIndex + 1 === providers.length) {
28218
- log.error(`Failed to receive any response for publication`, this.getType(), "after publishing to all providers", providers);
28219
- await this._postSucessOrFailurePublishing();
28220
28393
  } else {
28221
- log(`Re-publishing publication after ${this._publishToDifferentProviderThresholdSeconds}s of not receiving challenge from provider (${currentPubsubProvider})`);
28222
- currentPubsubProviderIndex += 1;
28223
- while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
28224
- const providerUrl = providers[currentPubsubProviderIndex];
28225
- if (this._isPublishRunOver(runSignal)) return;
28226
- const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, acceptedChallengeTypes);
28227
- this._updatePublishingStateWithEmission("publishing-challenge-request");
28228
- this._updatePubsubState("subscribing-pubsub", providerUrl);
28229
- try {
28230
- await this._clientsManager.pubsubSubscribeOnProvider(this._communityChallengePubsubExchangeTopic(), this._handleChallengeExchange, providerUrl);
28231
- if (await this._abandonProviderIfStoppedWhileSubscribing(providerUrl)) return;
28232
- this._updatePubsubState("publishing-challenge-request", providerUrl);
28233
- await this._clientsManager.pubsubPublishOnProvider(this._communityChallengePubsubExchangeTopic(), challengeRequest, providerUrl);
28234
- this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
28235
- } catch (e) {
28236
- log.error("Failed to publish challenge request using provider ", providerUrl, e);
28237
- this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
28238
- continue;
28239
- } finally {
28240
- currentPubsubProviderIndex += 1;
28241
- }
28242
- const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
28243
- if (!this._didWeReceiveChallengeOrChallengeVerification()) {
28244
- this._updatePubsubState("waiting-challenge", providerUrl);
28245
- this._updatePublishingStateWithEmission("waiting-challenge");
28394
+ if (currentPubsubProviderIndex + 1 < providers.length) {
28395
+ log(`Re-publishing publication after ${this._publishToDifferentProviderThresholdSeconds}s of not receiving challenge from provider (${currentPubsubProvider})`);
28396
+ currentPubsubProviderIndex += 1;
28397
+ while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
28398
+ const providerUrl = providers[currentPubsubProviderIndex];
28399
+ if (this._hasPublishEnded()) return;
28400
+ const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, acceptedChallengeTypes);
28401
+ if (this._hasPublishEnded()) return;
28402
+ this._updatePublishingStateWithEmission("publishing-challenge-request");
28403
+ this._updatePubsubState("subscribing-pubsub", providerUrl);
28404
+ try {
28405
+ await this._clientsManager.pubsubSubscribeOnProvider(this._communityChallengePubsubExchangeTopic(), this._handleChallengeExchange, providerUrl);
28406
+ if (await this._abandonProviderIfStoppedWhileSubscribing(providerUrl)) return;
28407
+ this._updatePubsubState("publishing-challenge-request", providerUrl);
28408
+ await this._clientsManager.pubsubPublishOnProvider(this._communityChallengePubsubExchangeTopic(), challengeRequest, providerUrl);
28409
+ this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
28410
+ } catch (e) {
28411
+ if (this._hasPublishEnded()) return;
28412
+ log.error("Failed to publish challenge request using provider ", providerUrl, e);
28413
+ this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
28414
+ continue;
28415
+ } finally {
28416
+ currentPubsubProviderIndex += 1;
28417
+ }
28418
+ if (this._hasPublishEnded()) return;
28419
+ const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
28420
+ if (!this._didWeReceiveChallengeOrChallengeVerification()) {
28421
+ this._updatePubsubState("waiting-challenge", providerUrl);
28422
+ this._updatePublishingStateWithEmission("waiting-challenge");
28423
+ }
28424
+ log(`Published a challenge request of publication`, this.getType(), "with provider", providerUrl);
28425
+ this.emit("challengerequest", decryptedRequest);
28426
+ if (currentPubsubProviderIndex !== providers.length) await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1e3, runSignal);
28427
+ if (this._hasPublishEnded()) return;
28246
28428
  }
28247
- log(`Published a challenge request of publication`, this.getType(), "with provider", providerUrl);
28248
- this.emit("challengerequest", decryptedRequest);
28249
- if (currentPubsubProviderIndex !== providers.length) await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1e3, runSignal);
28250
- if (this._isPublishRunOver(runSignal)) return;
28251
- }
28429
+ } else log(`No response from the last provider (${currentPubsubProvider}), will wait for it until the failure threshold`);
28252
28430
  await sleepUntilTimeoutOrAbort(this._setProviderFailureThresholdSeconds * 1e3, runSignal);
28253
- if (this._isPublishRunOver(runSignal)) return;
28431
+ if (this._hasPublishEnded()) return;
28254
28432
  if (this.state === "stopped") return;
28255
28433
  if (this._didWeReceiveChallengeOrChallengeVerification()) {
28256
28434
  log(`Received a challenge or challenge verification while waiting for retried providers, will keep the exchange alive`);
@@ -28258,25 +28436,26 @@ var Publication = class extends import_lib.TypedEmitter {
28258
28436
  }
28259
28437
  if (this._isAllAttemptsExhausted(providers.length)) {
28260
28438
  const aRequestWasPublished = this._wasAnyChallengeRequestPublished();
28261
- await this._postSucessOrFailurePublishing();
28262
- const allAttemptsFailedError = aRequestWasPublished ? new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
28263
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
28264
- pubsubTopic: this._community?.pubsubTopic,
28265
- publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
28266
- setProviderFailureThresholdSeconds: this._setProviderFailureThresholdSeconds,
28267
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28268
- }) : new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
28269
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
28270
- pubsubTopic: this._community?.pubsubTopic,
28271
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28272
- });
28273
- log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
28274
- this._changePublicationStateEmitEventEmitStateChangeEvent({
28275
- newPublishingState: "failed",
28276
- event: {
28277
- name: "error",
28278
- args: [allAttemptsFailedError]
28279
- }
28439
+ await this._endPublishWithFailure(() => {
28440
+ const allAttemptsFailedError = aRequestWasPublished ? new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
28441
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
28442
+ pubsubTopic: this._community?.pubsubTopic,
28443
+ publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
28444
+ setProviderFailureThresholdSeconds: this._setProviderFailureThresholdSeconds,
28445
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28446
+ }) : new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
28447
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
28448
+ pubsubTopic: this._community?.pubsubTopic,
28449
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28450
+ });
28451
+ log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
28452
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28453
+ newPublishingState: "failed",
28454
+ event: {
28455
+ name: "error",
28456
+ args: [allAttemptsFailedError]
28457
+ }
28458
+ });
28280
28459
  });
28281
28460
  return;
28282
28461
  }
@@ -28292,20 +28471,24 @@ var Publication = class extends import_lib.TypedEmitter {
28292
28471
  this._publishingToLocalCommunity = community;
28293
28472
  const log = logger_default("pkc-js:publication:publish:_publishWithLocalCommunity");
28294
28473
  log("Community is local, will not publish over pubsub, and instead will publish directly to the community by accessing pkc._startedCommunities");
28295
- const communityChallengeListener = async (challenge) => {
28474
+ const communityChallengeListener = this._guardDetachedHandler("communityChallengeListener", async (challenge) => {
28475
+ if (this._hasPublishEnded()) return;
28296
28476
  if (challenge.challengeRequestId.toString() === challengeRequest.challengeRequestId.toString()) {
28297
28477
  const encryptedFields = ["challenges"];
28298
28478
  log("Received a challenge from the local community", challenge);
28299
28479
  await this._handleIncomingChallengePubsubMessage(n$1(challenge, encryptedFields));
28300
28480
  }
28301
- };
28481
+ });
28302
28482
  community.on("challenge", communityChallengeListener);
28303
- const communityChallengeVerificationListener = async (decryptedChallengeVerification) => {
28483
+ let verificationHandling;
28484
+ const communityChallengeVerificationListener = this._guardDetachedHandler("communityChallengeVerificationListener", async (decryptedChallengeVerification) => {
28485
+ if (this._hasPublishEnded()) return;
28304
28486
  if (decryptedChallengeVerification.challengeRequestId.toString() === challengeRequest.challengeRequestId.toString()) {
28305
28487
  log("Received a challenge verification from the local community", decryptedChallengeVerification);
28306
- await this._handleIncomingChallengeVerificationPubsubMessage(n$1(decryptedChallengeVerification, ["comment", "commentUpdate"]));
28488
+ verificationHandling = this._handleIncomingChallengeVerificationPubsubMessage(n$1(decryptedChallengeVerification, ["comment", "commentUpdate"]));
28489
+ await verificationHandling;
28307
28490
  }
28308
- };
28491
+ });
28309
28492
  community.on("challengeverification", communityChallengeVerificationListener);
28310
28493
  this.emit("challengerequest", challengeRequest);
28311
28494
  community.handleChallengeRequest(challengeRequest, true).then(() => {
@@ -28313,17 +28496,40 @@ var Publication = class extends import_lib.TypedEmitter {
28313
28496
  ...this._challengeExchanges[challengeRequest.challengeRequestId.toString()],
28314
28497
  challengeRequestPublishTimestamp: timestamp()
28315
28498
  };
28316
- }).catch((e) => {
28499
+ }).catch(async (e) => {
28317
28500
  log.error("Failed to handle challenge request with local community", e);
28318
- this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
28319
- throw e;
28501
+ const challengeRequestId = challengeRequest.challengeRequestId.toString();
28502
+ this._challengeExchanges[challengeRequestId].challengeRequestPublishError = e;
28503
+ await verificationHandling?.catch(() => {});
28504
+ try {
28505
+ await this._endPublishWithFailure(() => this._changePublicationStateEmitEventEmitStateChangeEvent({
28506
+ newPublishingState: "failed",
28507
+ event: {
28508
+ name: "error",
28509
+ args: [e]
28510
+ }
28511
+ }));
28512
+ } catch (endError) {
28513
+ log.error("Failed to end the exchange the local community rejected", endError);
28514
+ }
28320
28515
  }).finally(() => {
28321
28516
  community.removeListener("challenge", communityChallengeListener);
28322
28517
  community.removeListener("challengeverification", communityChallengeVerificationListener);
28323
28518
  });
28324
28519
  }
28325
28520
  async publish() {
28521
+ if (this._isPublishSpent || this._isPublishCallRunning) {
28522
+ const exchanges = Object.values(this._challengeExchanges);
28523
+ throw new PKCError("ERR_PUBLICATION_PUBLISH_ALREADY_CALLED", {
28524
+ publicationType: this.getType(),
28525
+ state: this.state,
28526
+ publishingState: this.publishingState,
28527
+ receivedChallenge: exchanges.some((exchange) => exchange.challenge),
28528
+ receivedChallengeVerification: exchanges.some((exchange) => exchange.challengeVerification)
28529
+ });
28530
+ }
28326
28531
  this._validatePublicationFields();
28532
+ this._isPublishCallRunning = true;
28327
28533
  if (this._getCommunityFetchAbortSignal().aborted) this._resetCommunityFetchAbortSignal();
28328
28534
  this._beginPublishRun();
28329
28535
  this._pkc._publishingPublications.add(this);
@@ -28333,6 +28539,8 @@ var Publication = class extends import_lib.TypedEmitter {
28333
28539
  this._unregisterFromPkcOncePublishWorkSettles();
28334
28540
  this._publishRunAbortController?.abort();
28335
28541
  throw e;
28542
+ } finally {
28543
+ this._isPublishCallRunning = false;
28336
28544
  }
28337
28545
  }
28338
28546
  async _publishAfterRegistering() {
@@ -28347,36 +28555,47 @@ var Publication = class extends import_lib.TypedEmitter {
28347
28555
  await this._signPublicationWithCommunityFields();
28348
28556
  }
28349
28557
  await this._validateSignatureHook();
28558
+ this._validateAuthorWalletProofs();
28559
+ if (this._hasPublishEnded()) return;
28560
+ this._isPublishSpent = true;
28350
28561
  if (this._pkc._pkcRpcClient) return this._publishWithRpc();
28351
28562
  const options = { acceptedChallengeTypes: [] };
28352
28563
  const startedCommunity = findStartedCommunity(this._pkc, {
28353
28564
  publicKey: this.communityPublicKey,
28354
28565
  name: this.communityName
28355
28566
  });
28356
- if (startedCommunity) return this._publishWithLocalCommunity(startedCommunity, await this._generateChallengeRequestToPublish("publishing directly to local community instance", options.acceptedChallengeTypes));
28567
+ if (startedCommunity) {
28568
+ const challengeRequest = await this._generateChallengeRequestToPublish(LOCAL_COMMUNITY_PROVIDER, options.acceptedChallengeTypes);
28569
+ if (this._hasPublishEnded()) return;
28570
+ return this._publishWithLocalCommunity(startedCommunity, challengeRequest);
28571
+ }
28357
28572
  if (typeof this._community?.pubsubTopic !== "string") {
28358
- await this._postSucessOrFailurePublishing();
28359
- const error = new PKCError("ERR_COMMUNITY_CHALLENGE_EXCHANGE_DISABLED", {
28360
- communityAddress: this._community?.address ?? this.communityAddress,
28361
- communityName: this._community?.name ?? this.communityName,
28362
- communityPublicKey: this._community?.publicKey ?? this.communityPublicKey,
28363
- publicationType: this.getType()
28364
- });
28365
- log.error("Community has its challenge exchange disabled, will not publish", this.getType(), error);
28366
- this._changePublicationStateEmitEventEmitStateChangeEvent({
28367
- newPublishingState: "failed",
28368
- event: {
28369
- name: "error",
28370
- args: [error]
28371
- }
28573
+ const disabledError = await this._endPublishWithFailure(() => {
28574
+ const error = new PKCError("ERR_COMMUNITY_CHALLENGE_EXCHANGE_DISABLED", {
28575
+ communityAddress: this._community?.address ?? this.communityAddress,
28576
+ communityName: this._community?.name ?? this.communityName,
28577
+ communityPublicKey: this._community?.publicKey ?? this.communityPublicKey,
28578
+ publicationType: this.getType()
28579
+ });
28580
+ log.error("Community has its challenge exchange disabled, will not publish", this.getType(), error);
28581
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28582
+ newPublishingState: "failed",
28583
+ event: {
28584
+ name: "error",
28585
+ args: [error]
28586
+ }
28587
+ });
28588
+ return error;
28372
28589
  });
28373
- throw error;
28590
+ if (disabledError) throw disabledError;
28591
+ return;
28374
28592
  }
28375
28593
  const providers = this._getPubsubProviders();
28376
28594
  let currentPubsubProviderIndex = 0;
28377
28595
  while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
28378
28596
  const providerUrl = providers[currentPubsubProviderIndex];
28379
28597
  const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, options.acceptedChallengeTypes);
28598
+ if (this._hasPublishEnded()) return;
28380
28599
  this._updatePublishingStateWithEmission("publishing-challenge-request");
28381
28600
  this._updatePubsubState("subscribing-pubsub", providerUrl);
28382
28601
  try {
@@ -28386,28 +28605,33 @@ var Publication = class extends import_lib.TypedEmitter {
28386
28605
  await this._clientsManager.pubsubPublishOnProvider(this._communityChallengePubsubExchangeTopic(), challengeRequest, providerUrl);
28387
28606
  this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
28388
28607
  } catch (e) {
28608
+ if (this._hasPublishEnded()) return;
28389
28609
  this._updatePubsubState("stopped", providerUrl);
28390
28610
  log.error("Failed to publish challenge request using provider ", providerUrl, e);
28391
28611
  currentPubsubProviderIndex += 1;
28392
28612
  this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
28393
28613
  if (this._isAllAttemptsExhausted(providers.length)) {
28394
- await this._postSucessOrFailurePublishing();
28395
- const allAttemptsFailedError = new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
28396
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
28397
- pubsubTopic: this._community?.pubsubTopic,
28398
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28399
- });
28400
- log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
28401
- this._changePublicationStateEmitEventEmitStateChangeEvent({
28402
- newPublishingState: "failed",
28403
- event: {
28404
- name: "error",
28405
- args: [allAttemptsFailedError]
28406
- }
28614
+ const failure = await this._endPublishWithFailure(() => {
28615
+ const allAttemptsFailedError = new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
28616
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
28617
+ pubsubTopic: this._community?.pubsubTopic,
28618
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28619
+ });
28620
+ log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
28621
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28622
+ newPublishingState: "failed",
28623
+ event: {
28624
+ name: "error",
28625
+ args: [allAttemptsFailedError]
28626
+ }
28627
+ });
28628
+ return allAttemptsFailedError;
28407
28629
  });
28408
- throw allAttemptsFailedError;
28630
+ if (failure) throw failure;
28631
+ return;
28409
28632
  } else continue;
28410
28633
  }
28634
+ if (this._hasPublishEnded()) return;
28411
28635
  const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
28412
28636
  this._updatePubsubState("waiting-challenge", providerUrl);
28413
28637
  this._updatePublishingStateWithEmission("waiting-challenge");
@@ -28421,6 +28645,7 @@ var Publication = class extends import_lib.TypedEmitter {
28421
28645
  acceptedChallengeTypes: options.acceptedChallengeTypes
28422
28646
  }).catch((err) => {
28423
28647
  log.error("Failed to handle not receiving response to challenge request", err);
28648
+ this._endPublicationAfterDetachedFailure("_handleNotReceivingResponseToChallengeRequest", err);
28424
28649
  });
28425
28650
  }
28426
28651
  };
@@ -29639,6 +29864,7 @@ var Comment = class extends Publication {
29639
29864
  this._updateRpcSubscriptionId = void 0;
29640
29865
  this._stopAbortController = void 0;
29641
29866
  this._numOfListenersForUpdatingInstance = 0;
29867
+ this._updateAttempt = 0;
29642
29868
  this._updatingCommentInstance = void 0;
29643
29869
  this._setUpdatingStateWithEmissionIfNewState("stopped");
29644
29870
  this.publish = this.publish.bind(this);
@@ -29715,9 +29941,13 @@ var Comment = class extends Publication {
29715
29941
  this._initProps(props);
29716
29942
  const unknownProps = r(t$1(props), t$1(CommentIpfsSchema.shape));
29717
29943
  if (unknownProps.length > 0) {
29718
- const unknownPropsWithValues = t$5(props, unknownProps);
29719
- log(`Found unknown props on loaded CommentIpfs (cid: ${this.cid})`, unknownPropsWithValues, "Full props:", props, "Will set them on the Comment instance");
29720
- Object.assign(this, unknownPropsWithValues);
29944
+ log(`Found unknown props on loaded CommentIpfs (cid: ${this.cid})`, t$5(props, unknownProps), "Will set them on the Comment instance");
29945
+ const { skipped } = assignUnknownProps({
29946
+ target: this,
29947
+ record: props,
29948
+ knownKeys: t$1(CommentIpfsSchema.shape)
29949
+ });
29950
+ if (skipped.length > 0) log.error(`Refused unknown props of CommentIpfs (cid: ${this.cid}) that collide with the instance`, skipped);
29721
29951
  }
29722
29952
  this._setAuthorNameResolvedFromCache();
29723
29953
  }
@@ -29812,7 +30042,12 @@ var Comment = class extends Publication {
29812
30042
  const unknownProps = r(t$1(props), t$1(CommentUpdateSchema.shape));
29813
30043
  if (unknownProps.length > 0) {
29814
30044
  log("Found unknown props on CommentUpdate record", unknownProps, "Will set them on Comment instance");
29815
- Object.assign(this, t$5(props, unknownProps));
30045
+ const { skipped } = assignUnknownProps({
30046
+ target: this,
30047
+ record: props,
30048
+ knownKeys: t$1(CommentUpdateSchema.shape)
30049
+ });
30050
+ if (skipped.length > 0) log.error("Refused unknown props of CommentUpdate that collide with the instance", skipped);
29816
30051
  }
29817
30052
  }
29818
30053
  this.upvoteCount = props.upvoteCount;
@@ -29830,7 +30065,13 @@ var Comment = class extends Publication {
29830
30065
  this.protocolVersion = props.protocolVersion;
29831
30066
  this.spoiler = typeof props.spoiler === "boolean" ? props.spoiler : typeof props.edit?.spoiler === "boolean" ? props.edit?.spoiler : this.spoiler;
29832
30067
  this.nsfw = typeof props.nsfw === "boolean" ? props.nsfw : typeof props.edit?.nsfw === "boolean" ? props.edit?.nsfw : this.nsfw;
29833
- if (props.author) Object.assign(this.author, props.author);
30068
+ if (props.author) {
30069
+ const { skipped } = mergeAuthorProps({
30070
+ target: this.author,
30071
+ props: props.author
30072
+ });
30073
+ if (skipped.length > 0) logger_default("pkc-js:comment:_initCommentUpdate").error("Refused author props of CommentUpdate that collide with an object", skipped);
30074
+ }
29834
30075
  if (props.edit?.content) this.content = props.edit.content;
29835
30076
  this.flairs = props.flairs || props.edit?.flairs || this.flairs;
29836
30077
  this.author.flairs = props.author?.community?.flairs || props.edit?.author?.flairs || this.author?.flairs;
@@ -29889,7 +30130,6 @@ var Comment = class extends Publication {
29889
30130
  originalPubsubMsg: this.raw.pubsubMessageToPublish
29890
30131
  });
29891
30132
  log.error(error);
29892
- this.emit("error", error);
29893
30133
  return error;
29894
30134
  }
29895
30135
  const calculatedCid = await of(JSON.stringify(decryptedVerification.comment));
@@ -29907,7 +30147,6 @@ var Comment = class extends Publication {
29907
30147
  decryptedChallengeVerification: decryptedVerification
29908
30148
  });
29909
30149
  log.error(error);
29910
- this.emit("error", error);
29911
30150
  return error;
29912
30151
  }
29913
30152
  const commentUpdateValidity = await verifyCommentUpdate({
@@ -29929,7 +30168,6 @@ var Comment = class extends Publication {
29929
30168
  decryptedChallengeVerification: decryptedVerification
29930
30169
  });
29931
30170
  log.error(error);
29932
- this.emit("error", error);
29933
30171
  return error;
29934
30172
  }
29935
30173
  if (calculatedCid !== decryptedVerification.commentUpdate.cid) {
@@ -29939,7 +30177,6 @@ var Comment = class extends Publication {
29939
30177
  decryptedChallengeVerification: decryptedVerification
29940
30178
  });
29941
30179
  log.error(error);
29942
- this.emit("error", error);
29943
30180
  return error;
29944
30181
  }
29945
30182
  }
@@ -29973,7 +30210,13 @@ var Comment = class extends Publication {
29973
30210
  }
29974
30211
  _initCommentUpdateFromChallengeVerificationProps(commentUpdate) {
29975
30212
  this.raw.commentUpdateFromChallengeVerification = commentUpdate;
29976
- if (commentUpdate.author) Object.assign(this.author, commentUpdate.author);
30213
+ if (commentUpdate.author) {
30214
+ const { skipped } = mergeAuthorProps({
30215
+ target: this.author,
30216
+ props: commentUpdate.author
30217
+ });
30218
+ if (skipped.length > 0) logger_default("pkc-js:comment:_initCommentUpdateFromChallengeVerificationProps").error("Refused author props of the challenge verification that collide with an object", skipped);
30219
+ }
29977
30220
  this.protocolVersion = commentUpdate.protocolVersion;
29978
30221
  if ("pendingApproval" in commentUpdate) this.pendingApproval = commentUpdate.pendingApproval;
29979
30222
  else this.pendingApproval = false;
@@ -29988,7 +30231,12 @@ var Comment = class extends Publication {
29988
30231
  const unknownProps = r(t$1(decryptedVerification.commentUpdate), t$1(CommentUpdateForChallengeVerificationSchema.shape));
29989
30232
  if (unknownProps.length > 0) {
29990
30233
  log("Found unknown props on decryptedVerification.commentUpdate record", unknownProps, "Will set them on Comment instance");
29991
- Object.assign(this, t$5(decryptedVerification.commentUpdate, unknownProps));
30234
+ const { skipped } = assignUnknownProps({
30235
+ target: this,
30236
+ record: decryptedVerification.commentUpdate,
30237
+ knownKeys: t$1(CommentUpdateForChallengeVerificationSchema.shape)
30238
+ });
30239
+ if (skipped.length > 0) log.error("Refused unknown props of the challenge verification that collide with the instance", skipped);
29992
30240
  }
29993
30241
  this.emit("update", this);
29994
30242
  if (!this._pkc._pkcRpcClient) this._resolveAuthorNamesInBackground();
@@ -29997,7 +30245,8 @@ var Comment = class extends Publication {
29997
30245
  const log = logger_default("pkc-js:comment:publish:_verifyDecryptedChallengeVerificationAndUpdateCommentProps");
29998
30246
  log("Received update props from community after succcessful challenge exchange. Will attempt to validate if not connected to RPC", decryptedVerification);
29999
30247
  if (!this._pkc._pkcRpcClient) {
30000
- if (await this._verifyChallengeVerificationCommentProps(decryptedVerification)) return;
30248
+ const errorInVerificationProps = await this._verifyChallengeVerificationCommentProps(decryptedVerification);
30249
+ if (errorInVerificationProps) throw errorInVerificationProps;
30001
30250
  }
30002
30251
  await this._updateCommentPropsFromDecryptedChallengeVerification(decryptedVerification);
30003
30252
  if (Object.keys(this._pkc.clients.kuboRpcClients).length > 0 || Object.keys(this._pkc.clients.libp2pJsClients).length > 0) this._addOwnCommentToIpfsIfConnectedToIpfsClient(decryptedVerification).catch((err) => log.error(`Failed to add the file of comment ipfs`, this.cid, "to ipfs network due to error", err));
@@ -30290,25 +30539,38 @@ var Comment = class extends Publication {
30290
30539
  const log = logger_default("pkc-js:comment:update:_updateViaRpc");
30291
30540
  if (!this._pkc.pkcRpcClientsOptions[0]) throw Error("Failed to get rpc url");
30292
30541
  if (!this.cid) throw Error("Can't start updating comment without defining this.cid");
30542
+ const updateAttempt = this._updateAttempt;
30543
+ let subscriptionId;
30293
30544
  try {
30294
- const { subscriptionId } = await this._pkc._pkcRpcClient.commentUpdateSubscribe({
30545
+ ({subscriptionId} = await this._pkc._pkcRpcClient.commentUpdateSubscribe({
30295
30546
  cid: this.cid,
30296
30547
  ...this.raw.comment || this.raw.commentUpdate ? { raw: this.raw } : void 0,
30297
30548
  communityName: this.communityName,
30298
30549
  communityPublicKey: this.communityPublicKey,
30299
30550
  parentCid: this.parentCid,
30300
30551
  postCid: this.postCid
30301
- });
30302
- this._updateRpcSubscriptionId = subscriptionId;
30552
+ }));
30303
30553
  } catch (e) {
30554
+ if (updateAttempt !== this._updateAttempt) {
30555
+ log.error("A commentUpdate subscribe that stop() made stale failed", e);
30556
+ return;
30557
+ }
30304
30558
  log.error("Failed to receive commentUpdate from RPC due to error", e);
30305
30559
  await this._stopUpdateLoop();
30306
30560
  this._setStateWithEmission("stopped");
30307
30561
  this._setUpdatingStateWithEmissionIfNewState("failed");
30308
30562
  throw e;
30309
30563
  }
30564
+ if (updateAttempt !== this._updateAttempt) {
30565
+ try {
30566
+ await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
30567
+ } catch (e) {
30568
+ log.error("Failed to unsubscribe from a commentUpdate subscription stopped while subscribing", e);
30569
+ }
30570
+ return;
30571
+ }
30572
+ this._updateRpcSubscriptionId = subscriptionId;
30310
30573
  this._setStateWithEmission("updating");
30311
- const subscriptionId = this._updateRpcSubscriptionId;
30312
30574
  this._pkc._pkcRpcClient.attachSubscriptionHandlersDeferred({
30313
30575
  subscriptionId,
30314
30576
  isStale: () => this._updateRpcSubscriptionId !== subscriptionId,
@@ -30442,7 +30704,9 @@ var Comment = class extends Publication {
30442
30704
  }
30443
30705
  async _setUpNewUpdatingCommentInstance() {
30444
30706
  const log = logger_default("pkc-js:comment:update:_setUpNewUpdatingCommentInstance");
30707
+ const updateAttempt = this._updateAttempt;
30445
30708
  const updatingCommentInstance = await this._pkc.createComment(this);
30709
+ if (updateAttempt !== this._updateAttempt) return;
30446
30710
  trackUpdatingComment(this._pkc, updatingCommentInstance);
30447
30711
  this._useUpdatingCommentFromPKC(updatingCommentInstance);
30448
30712
  updatingCommentInstance._setStateWithEmission("updating");
@@ -30453,7 +30717,9 @@ var Comment = class extends Publication {
30453
30717
  const log = logger_default("pkc-js:comment:update");
30454
30718
  if (this.state === "updating") return;
30455
30719
  if (!this.cid) throw Error("Can't call comment.update() without defining cid");
30720
+ const updateAttempt = ++this._updateAttempt;
30456
30721
  this._setStateWithEmission("updating");
30722
+ if (updateAttempt !== this._updateAttempt) return;
30457
30723
  const existingUpdatingComment = findUpdatingComment(this._pkc, { cid: this.cid });
30458
30724
  if (existingUpdatingComment) if (existingUpdatingComment === this) if (this._pkc._pkcRpcClient) await this._updateViaRpc();
30459
30725
  else this.loadCommentIpfsAndStartCommentUpdateSubscription().catch((e) => log.error("Failed to update comment", e));
@@ -30510,10 +30776,17 @@ var Comment = class extends Publication {
30510
30776
  this._clearStopAbortController();
30511
30777
  }
30512
30778
  async stop() {
30779
+ const updateAttempt = ++this._updateAttempt;
30513
30780
  this._abortStopOperations(`Aborting comment operations for ${this.cid || this.author?.address || "comment"} because comment.stop() was called`);
30514
- if (this.state === "publishing") await super.stop();
30515
- else await this._cancelBackgroundCommunityRefresh();
30516
- this._setStateWithEmission("stopped");
30781
+ const isPublishing = () => this.state === "publishing";
30782
+ if (isPublishing()) {
30783
+ await super.stop();
30784
+ if (updateAttempt !== this._updateAttempt) return;
30785
+ this._setStateWithEmission("stopped");
30786
+ } else {
30787
+ await this._cancelBackgroundCommunityRefresh();
30788
+ if (!isPublishing()) this._setStateWithEmission("stopped");
30789
+ }
30517
30790
  await this._stopUpdateLoop();
30518
30791
  this.replies._stop();
30519
30792
  this._setUpdatingStateWithEmissionIfNewState("stopped");
@@ -30697,6 +30970,7 @@ var Storage = class {
30697
30970
  dbFilePath = path.join(this._pkc.dataPath, "storage.db");
30698
30971
  }
30699
30972
  this._db = new Database(dbFilePath);
30973
+ if (dbFilePath !== ":memory:") this._db.pragma("journal_mode = WAL");
30700
30974
  this._keyv = new KeyvBetterSqlite3(this._db);
30701
30975
  this._keyv.on("error", (err) => {
30702
30976
  err.details = {
@@ -35673,14 +35947,14 @@ var CommunityList = class extends import_lib.TypedEmitter {
35673
35947
  _buildRuntimeEntry(entry) {
35674
35948
  const address = entry.name || entry.publicKey;
35675
35949
  return {
35676
- ...entry,
35950
+ ...withoutForbiddenKeys(entry),
35677
35951
  address,
35678
35952
  shortAddress: shortifyAddress(address)
35679
35953
  };
35680
35954
  }
35681
35955
  _buildRuntimeAuthor(wireAuthor, signaturePublicKey) {
35682
35956
  const runtimeAuthor = buildRuntimeAuthor({
35683
- author: wireAuthor,
35957
+ author: wireAuthor && withoutForbiddenKeys(wireAuthor),
35684
35958
  signaturePublicKey
35685
35959
  });
35686
35960
  return {
@@ -36109,7 +36383,7 @@ var PKC$1 = class extends PKCTypedEmitter {
36109
36383
  this.clients.libp2pJsClients = {};
36110
36384
  if (!this.libp2pJsClientsOptions) return;
36111
36385
  if (!this.httpRoutersOptions) throw Error("httpRoutersOptions is required for libp2pJsClient");
36112
- const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-COJ3xMF9.js");
36386
+ const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-Oiy9zYBR.js");
36113
36387
  for (const clientOptions of this.libp2pJsClientsOptions) {
36114
36388
  const heliaNode = await createLibp2pJsClientOrUseExistingOne({
36115
36389
  ...clientOptions,
@@ -36486,8 +36760,8 @@ var PKC$1 = class extends PKCTypedEmitter {
36486
36760
  const log = logger_default("pkc-js:pkc:createLocalCommunity");
36487
36761
  log.trace("Received community options to create a local community instance:", options);
36488
36762
  if (!this._canCreateNewLocalCommunity()) throw new PKCError("ERR_CAN_NOT_CREATE_A_LOCAL_COMMUNITY", { pkcOptions: this._userPKCOptions });
36489
- const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-BTx2HxIm.js");
36490
- const isLocalCommunity = (await listCommunitiesSync(this)).includes(options.address);
36763
+ const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-BlJfnxcr.js");
36764
+ const isLocalCommunity = isLocalCommunityAddress(this, options.address);
36491
36765
  const community = new LocalCommunity(this);
36492
36766
  if (isLocalCommunity) {
36493
36767
  community.setAddress(options.address);
@@ -36498,7 +36772,13 @@ var PKC$1 = class extends PKCTypedEmitter {
36498
36772
  } else if ("signer" in options) {
36499
36773
  const parsedOptions = options;
36500
36774
  await community.initNewLocalCommunityPropsNoMerge(parsedOptions);
36501
- await createNewLocalCommunityDb(community);
36775
+ const doneWritingDbFile = markLocalCommunityDbAsBeingWritten(this, community.address);
36776
+ try {
36777
+ await createNewLocalCommunityDb(community);
36778
+ } finally {
36779
+ doneWritingDbFile();
36780
+ }
36781
+ registerLocalCommunity(this, community.address);
36502
36782
  log.trace(`Created a new local community (${community.address}) with props:`);
36503
36783
  community.emit("update", community);
36504
36784
  await this._awaitCommunitiesToIncludeCommunity(community.address);