@pkcprotocol/pkc-js 0.0.145 → 0.0.147

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 (102) hide show
  1. package/README.md +88 -55
  2. package/dist/browser/clients/base-client-manager.js +14 -2
  3. package/dist/browser/clients/base-client-manager.js.map +1 -1
  4. package/dist/browser/errors.d.ts +3 -0
  5. package/dist/browser/errors.js +3 -0
  6. package/dist/browser/errors.js.map +1 -1
  7. package/dist/browser/generated-version.d.ts +1 -1
  8. package/dist/browser/generated-version.js +1 -1
  9. package/dist/browser/pkc-error.d.ts +1 -1
  10. package/dist/browser/publications/comment/comment-client-manager.d.ts +15 -3
  11. package/dist/browser/publications/comment/comment-client-manager.js +221 -10
  12. package/dist/browser/publications/comment/comment-client-manager.js.map +1 -1
  13. package/dist/browser/publications/comment/comment.js +1 -0
  14. package/dist/browser/publications/comment/comment.js.map +1 -1
  15. package/dist/browser/publications/publication.d.ts +1 -0
  16. package/dist/browser/publications/publication.js +24 -5
  17. package/dist/browser/publications/publication.js.map +1 -1
  18. package/dist/browser/runtime/node/community/challenges/index.js +14 -0
  19. package/dist/browser/runtime/node/community/challenges/index.js.map +1 -1
  20. package/dist/browser/runtime/node/community/db-handler.d.ts +5 -1
  21. package/dist/browser/runtime/node/community/db-handler.js +64 -12
  22. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  23. package/dist/browser/runtime/node/community/local-community/db-state.d.ts +3 -1
  24. package/dist/browser/runtime/node/community/local-community/db-state.js +104 -16
  25. package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
  26. package/dist/browser/runtime/node/community/local-community/defaults.d.ts +1 -0
  27. package/dist/browser/runtime/node/community/local-community/defaults.js +5 -0
  28. package/dist/browser/runtime/node/community/local-community/defaults.js.map +1 -1
  29. package/dist/browser/runtime/node/community/local-community/editing.js +121 -24
  30. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  31. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js +2 -1
  32. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  33. package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +2 -0
  34. package/dist/browser/runtime/node/community/local-community/lifecycle.js +153 -30
  35. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  36. package/dist/browser/runtime/node/community/local-community.d.ts +5 -0
  37. package/dist/browser/runtime/node/community/local-community.js +10 -1
  38. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  39. package/dist/browser/runtime/node/util.d.ts +9 -0
  40. package/dist/browser/runtime/node/util.js +141 -25
  41. package/dist/browser/runtime/node/util.js.map +1 -1
  42. package/dist/browser/test/test-util.d.ts +7 -1
  43. package/dist/browser/test/test-util.js +45 -16
  44. package/dist/browser/test/test-util.js.map +1 -1
  45. package/dist/bundled/bundle-manifest.json +40 -40
  46. package/dist/bundled/challenges.js +1 -1
  47. package/dist/bundled/chunks/{helia-for-pkc-7vdzP67t.js → helia-for-pkc-jM3y3OXF.js} +2 -2
  48. package/dist/bundled/chunks/{local-community-UB_rVgR9.js → local-community-5X7bvOoN.js} +332 -70
  49. package/dist/bundled/chunks/{local-community-Bi1JGMMa.js → local-community-P9e5jksW.js} +1 -1
  50. package/dist/bundled/chunks/{node-BT3m9Nml.js → node-By3og2hw.js} +173 -17
  51. package/dist/bundled/chunks/{page-sort-scoring-Bsc4MAy1.js → page-sort-scoring-DwYGP_0d.js} +1 -1
  52. package/dist/bundled/chunks/{rpc-local-community-DVykDP0T.js → rpc-local-community-WnhiTbxm.js} +132 -29
  53. package/dist/bundled/chunks/{util-BxfB5cRB.js → util-7QtFMzpc.js} +1 -1
  54. package/dist/bundled/chunks/{util-D6z8nIoj.js → util-DMr7Hj-w.js} +4 -1
  55. package/dist/bundled/chunks/{validate-package-factories-CiY6DjnH.js → validate-package-factories-TwRblx9f.js} +2 -2
  56. package/dist/bundled/index.js +1 -1
  57. package/dist/bundled/page-sorts.js +1 -1
  58. package/dist/bundled/rpc/src/index.js +4 -4
  59. package/dist/node/clients/base-client-manager.js +14 -2
  60. package/dist/node/clients/base-client-manager.js.map +1 -1
  61. package/dist/node/errors.d.ts +3 -0
  62. package/dist/node/errors.js +3 -0
  63. package/dist/node/errors.js.map +1 -1
  64. package/dist/node/generated-version.d.ts +1 -1
  65. package/dist/node/generated-version.js +1 -1
  66. package/dist/node/pkc-error.d.ts +1 -1
  67. package/dist/node/publications/comment/comment-client-manager.d.ts +15 -3
  68. package/dist/node/publications/comment/comment-client-manager.js +221 -10
  69. package/dist/node/publications/comment/comment-client-manager.js.map +1 -1
  70. package/dist/node/publications/comment/comment.js +1 -0
  71. package/dist/node/publications/comment/comment.js.map +1 -1
  72. package/dist/node/publications/publication.d.ts +1 -0
  73. package/dist/node/publications/publication.js +24 -5
  74. package/dist/node/publications/publication.js.map +1 -1
  75. package/dist/node/runtime/node/community/challenges/index.js +14 -0
  76. package/dist/node/runtime/node/community/challenges/index.js.map +1 -1
  77. package/dist/node/runtime/node/community/db-handler.d.ts +5 -1
  78. package/dist/node/runtime/node/community/db-handler.js +64 -12
  79. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  80. package/dist/node/runtime/node/community/local-community/db-state.d.ts +3 -1
  81. package/dist/node/runtime/node/community/local-community/db-state.js +104 -16
  82. package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
  83. package/dist/node/runtime/node/community/local-community/defaults.d.ts +1 -0
  84. package/dist/node/runtime/node/community/local-community/defaults.js +5 -0
  85. package/dist/node/runtime/node/community/local-community/defaults.js.map +1 -1
  86. package/dist/node/runtime/node/community/local-community/editing.js +121 -24
  87. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  88. package/dist/node/runtime/node/community/local-community/ipns-publishing.js +2 -1
  89. package/dist/node/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  90. package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +2 -0
  91. package/dist/node/runtime/node/community/local-community/lifecycle.js +153 -30
  92. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  93. package/dist/node/runtime/node/community/local-community.d.ts +5 -0
  94. package/dist/node/runtime/node/community/local-community.js +10 -1
  95. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  96. package/dist/node/runtime/node/util.d.ts +9 -0
  97. package/dist/node/runtime/node/util.js +141 -25
  98. package/dist/node/runtime/node/util.js.map +1 -1
  99. package/dist/node/test/test-util.d.ts +7 -1
  100. package/dist/node/test/test-util.js +45 -16
  101. package/dist/node/test/test-util.js.map +1 -1
  102. package/package.json +1 -1
@@ -1,11 +1,11 @@
1
1
  import { i as __toESM } from "./chunk-2rV9d50f.js";
2
- import { Ar as t$2, At as pTimeout, B as pubsubTopicToDhtKey, Bn as CommentUpdateSchema, Br as logger_default, Bt as DecryptedChallengeRequestPublicationSchema, C as hideClassPrivateProps, Cr as e, Dn as VotePubsubReservedFields, Dt as untrackUpdatingCommunity, En as VotePubsubMessagePublicationSchema, Er as t$3, F as isLinkOfVideo, Ft as ChallengeRequestMessageSchema, G as removeBlocksFromKuboNode, Hn as CommentUpdateTableRowSchema, I as isLinkValid, J as removeNullUndefinedValues, K as removeMfsFilesSafely, Lt as ChallengeVerificationMessageSchema, M as isLinkOfAudio, Mn as CommentIpfsSchema, Mr as require_retry, N as isLinkOfImage, Nn as CommentPubsubMessageReservedFields, Nt as ChallengeMessageSchema, Ot as require_sha256, P as isLinkOfMedia, Q as retryKuboBlockPutPinAndProvidePubsubTopic, Qn as CommentEditReservedFields, Rr as PKCError, Sr as e$1, St as trackStartedCommunity, T as ipnsNameToIpnsOverPubsubTopic, Tr as r$1, Tt as untrackStartedCommunity, Un as CommentsTableRowSchema, Vt as DecryptedChallengeRequestSchema, Xn as CommentEditPubsubMessagePublicationSchema, Yt as version_default, Zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Zt as CommunityEditPublicationPubsubReservedFields, _ as genToArray, _r as n$3, an as CommentModerationsTableRowSchema, ar as AuthorReservedFields, b as getIpnsRecordInLocalKuboNode, br as t$5, c as contentContainsMarkdownImages, ct as withSortedKeys, dt as findCommunityInRegistry, er as CommentEditsTableRowSchema, et as retryKuboIpfsAddAndProvide, f as derivePublicationFromChallengeRequest, ft as findStartedCommunity, g as findMalformedUnicodeString, gr as isStringDomain, hn as CommunitySignedPropertyNames, i as calculateStringSizeSameAsIpfsAddCidV0, it as statMfsPathSafely, j as isLinkOfAnimatedImage, jt as ChallengeAnswerMessageSchema, kn as VoteTablesRowSchema, kr as t$4, l as contentContainsMarkdownVideos, lt as withSortedKeysDeep, mn as CommunityIpfsSchema, mt as findUpdatingCommunity, ni as ZodError, nn as CommentModerationPubsubMessagePublicationSchema, o as calculateUnixFsDagSizeCidV0, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, r as calculateIpfsCidV0, rn as CommentModerationReservedFields, rt as sleepUntilTimeoutOrAbort, s as contentContainsMarkdownAudio, ut as writeKuboFilesWithTimeout, v as getEquivalentCommunityAddresses, vr as t$7, wt as trackUpdatingCommunity, xr as t$6, xt as syncCommunityRegistryEntry, y as getErrorCodeFromMessage, yr as n$2, zr as messages } from "./util-D6z8nIoj.js";
3
- import { $ as createSchemaRowParser, An as verifyChallengeAnswer, Bn as verifyCommunityEdit, Br as t$8, Cr as getThumbnailPropsOfLink, Dr as moveCommunityDbToDeletedDirectory, Dt as parseJsonWithPKCErrorIfFails, En as signCommunity, Fn as verifyCommentIpfs, Fr as isCommunityStartLocked, Gr as stringify, Hn as verifyVote, Hr as n$4, In as verifyCommentModeration, Ir as require_src, Kn as getAuthorNameFromWire, Ln as verifyCommentPubsubMessage, Lr as t$10, Mn as verifyChallengeRequest, Mr as findCommunitiesEntry, N as MAX_PAGE_SIZE_BYTES, Or as refreshCommunitiesList, Pn as verifyCommentEdit, Q as collectSchemaRowCoercions, Qn as effectiveMaxCrosspostDepth, Rn as verifyCommentUpdate, Rr as t$11, S as MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS, Sn as signCommentEdit, Tn as signCommentUpdateForChallengeVerification, Un as buildRuntimeAuthor, Vr as n$5, W as pLimit, Wn as cleanWireAuthor, Wr as t$9, X as coerceSchemaRowBoolean, Xr as STORAGE_KEYS, Z as coerceSchemaRowJson, Zn as crosspostChainDepthUpTo, Zr as require_lodash_merge, _ as createAuthorIdentityMatcher, _r as deriveCommentIpfsFromCommentTableRow, a as generatePagesReportingFailedSorts, ar as encode, b as KeyvBetterSqlite3, bn as signChallengeVerification, c as resolvePageSortsOrThrow, cn as SignerWithPublicKeyAddress, cr as getPKCAddressFromPublicKey, d as getChallengeVerification, dr as BackupAbortError, dt as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, f as getCommunityChallengeFromCommunityChallengeSettings, fn as decryptEd25519AesGcmPublicKeyBuffer, fr as backupCommunityDb, g as authorNameResolveFailureReason, gn as cleanUpBeforePublishing, gr as deleteOldCommunityInWindows, h as authorIdentityMatcherForRequest, hn as _validateSignatureOfPKCRecord, i as derivePublicPageSorts, ir as decode, j as iterateOverPageCidsToFindAllCids, kr as resolveDbPostsCidRefs, lr as getPKCAddressFromPublicKeySync, m as pkcJsChallenges, mn as encryptEd25519AesGcmPublicKeyBuffer, mr as calculateInlineRepliesBudget, nr as getCommunityPublicKeyFromWire, o as loadPageSortsForStartedCommunity, p as loadChallengeFileFromCommunityChallengeSettings, pr as calculateExpectedSignatureSize, pt as parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails, r as computePageSortsFingerprint, s as lookupPageSortFactories, sr as getIpfsKeyFromPrivateKey, t as RpcLocalCommunity, tr as getCommunityNameFromWire, u as deriveCommunityChallengesOrThrow, ur as getPublicKeyFromPrivateKey, v as TrackedInstanceRegistry, vn as signChallengeMessage, vr as deriveDbPosts, w as TIMEFRAMES_TO_SECONDS, wn as signCommentUpdate, wr as importSignerIntoKuboNode, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, xn as signComment, xr as getDefaultCommunityDbConfig, y as LRUCache, yr as deriveDbReplies, zn as verifyCommunity, zr as r$2 } from "./rpc-local-community-DVykDP0T.js";
4
- import { a as scorePageCommentsWithFile, i as partitionPageCommentsForSort, n as filterRepliesForPageSort, o as stripRepliesFromPageComment, r as orderPageCommentsByScore, t as createDescendantsLookup } from "./page-sort-scoring-Bsc4MAy1.js";
2
+ import { Ar as t$2, At as pTimeout, B as pubsubTopicToDhtKey, Bn as CommentUpdateSchema, Br as logger_default, Bt as DecryptedChallengeRequestPublicationSchema, C as hideClassPrivateProps, Cr as e, Dn as VotePubsubReservedFields, Dt as untrackUpdatingCommunity, En as VotePubsubMessagePublicationSchema, Er as t$3, F as isLinkOfVideo, Ft as ChallengeRequestMessageSchema, G as removeBlocksFromKuboNode, Hn as CommentUpdateTableRowSchema, I as isLinkValid, J as removeNullUndefinedValues, K as removeMfsFilesSafely, Lt as ChallengeVerificationMessageSchema, M as isLinkOfAudio, Mn as CommentIpfsSchema, Mr as require_retry, N as isLinkOfImage, Nn as CommentPubsubMessageReservedFields, Nt as ChallengeMessageSchema, Ot as require_sha256, P as isLinkOfMedia, Q as retryKuboBlockPutPinAndProvidePubsubTopic, Qn as CommentEditReservedFields, Rr as PKCError, Sr as e$1, St as trackStartedCommunity, T as ipnsNameToIpnsOverPubsubTopic, Tr as r$1, Tt as untrackStartedCommunity, Un as CommentsTableRowSchema, Vt as DecryptedChallengeRequestSchema, Xn as CommentEditPubsubMessagePublicationSchema, Yt as version_default, Zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Zt as CommunityEditPublicationPubsubReservedFields, _ as genToArray, _r as n$3, an as CommentModerationsTableRowSchema, ar as AuthorReservedFields, b as getIpnsRecordInLocalKuboNode, br as t$5, c as contentContainsMarkdownImages, ct as withSortedKeys, dt as findCommunityInRegistry, er as CommentEditsTableRowSchema, et as retryKuboIpfsAddAndProvide, f as derivePublicationFromChallengeRequest, ft as findStartedCommunity, g as findMalformedUnicodeString, gr as isStringDomain, hn as CommunitySignedPropertyNames, i as calculateStringSizeSameAsIpfsAddCidV0, it as statMfsPathSafely, j as isLinkOfAnimatedImage, jt as ChallengeAnswerMessageSchema, kn as VoteTablesRowSchema, kr as t$4, l as contentContainsMarkdownVideos, lt as withSortedKeysDeep, mn as CommunityIpfsSchema, mt as findUpdatingCommunity, ni as ZodError, nn as CommentModerationPubsubMessagePublicationSchema, o as calculateUnixFsDagSizeCidV0, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, r as calculateIpfsCidV0, rn as CommentModerationReservedFields, rt as sleepUntilTimeoutOrAbort, s as contentContainsMarkdownAudio, ut as writeKuboFilesWithTimeout, v as getEquivalentCommunityAddresses, vr as t$7, wt as trackUpdatingCommunity, xr as t$6, xt as syncCommunityRegistryEntry, y as getErrorCodeFromMessage, yr as n$2, zr as messages } from "./util-DMr7Hj-w.js";
3
+ import { $ as createSchemaRowParser, $r as require_lodash_merge, An as verifyChallengeAnswer, Ar as removeFileRetryingWhileBusy, Bn as verifyCommunityEdit, Br as t$11, Dt as parseJsonWithPKCErrorIfFails, En as signCommunity, Fn as verifyCommentIpfs, Hn as verifyVote, Hr as t$8, In as verifyCommentModeration, Kn as getAuthorNameFromWire, Kr as t$9, Ln as verifyCommentPubsubMessage, Lr as isCommunityStartLocked, Mn as verifyChallengeRequest, N as MAX_PAGE_SIZE_BYTES, Or as moveCommunityDbToDeletedDirectory, Pn as verifyCommentEdit, Pr as findCommunitiesEntry, Q as collectSchemaRowCoercions, Qn as effectiveMaxCrosspostDepth, Qr as STORAGE_KEYS, Rn as verifyCommentUpdate, Rr as require_src, S as MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS, Sn as signCommentEdit, Sr as getDefaultCommunityDbConfig, Tn as signCommentUpdateForChallengeVerification, Tr as importSignerIntoKuboNode, Un as buildRuntimeAuthor, Ur as n$5, Vr as r$2, W as pLimit, Wn as cleanWireAuthor, Wr as n$4, X as coerceSchemaRowBoolean, Z as coerceSchemaRowJson, Zn as crosspostChainDepthUpTo, _ as createAuthorIdentityMatcher, _r as deriveCommentIpfsFromCommentTableRow, a as generatePagesReportingFailedSorts, ar as encode, b as KeyvBetterSqlite3, bn as signChallengeVerification, c as resolvePageSortsOrThrow, cn as SignerWithPublicKeyAddress, cr as getPKCAddressFromPublicKey, d as getChallengeVerification, dr as BackupAbortError, dt as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, f as getCommunityChallengeFromCommunityChallengeSettings, fn as decryptEd25519AesGcmPublicKeyBuffer, fr as backupCommunityDb, g as authorNameResolveFailureReason, gn as cleanUpBeforePublishing, gr as deleteOldCommunityInWindows, h as authorIdentityMatcherForRequest, hn as _validateSignatureOfPKCRecord, i as derivePublicPageSorts, ir as decode, j as iterateOverPageCidsToFindAllCids, jr as resolveDbPostsCidRefs, kr as refreshCommunitiesList, lr as getPKCAddressFromPublicKeySync, m as pkcJsChallenges, mn as encryptEd25519AesGcmPublicKeyBuffer, mr as calculateInlineRepliesBudget, nr as getCommunityPublicKeyFromWire, o as loadPageSortsForStartedCommunity, p as loadChallengeFileFromCommunityChallengeSettings, pr as calculateExpectedSignatureSize, pt as parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails, qr as stringify, r as computePageSortsFingerprint, s as lookupPageSortFactories, sr as getIpfsKeyFromPrivateKey, t as RpcLocalCommunity, tr as getCommunityNameFromWire, u as deriveCommunityChallengesOrThrow, ur as getPublicKeyFromPrivateKey, v as TrackedInstanceRegistry, vn as signChallengeMessage, vr as deriveDbPosts, w as TIMEFRAMES_TO_SECONDS, wn as signCommentUpdate, wr as getThumbnailPropsOfLink, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, xn as signComment, xr as forgetCommunityThatFailedToBeDeleted, y as LRUCache, yr as deriveDbReplies, zn as verifyCommunity, zr as t$10 } from "./rpc-local-community-WnhiTbxm.js";
4
+ import { a as scorePageCommentsWithFile, i as partitionPageCommentsForSort, n as filterRepliesForPageSort, o as stripRepliesFromPageComment, r as orderPageCommentsByScore, t as createDescendantsLookup } from "./page-sort-scoring-DwYGP_0d.js";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import path from "node:path";
7
7
  import os from "os";
8
- import fs, { existsSync, promises } from "node:fs";
8
+ import fs, { closeSync, existsSync, openSync, promises } from "node:fs";
9
9
  import path$1 from "path";
10
10
  import assert from "assert";
11
11
  import { Buffer as Buffer$1 } from "buffer";
@@ -223,6 +223,7 @@ const DUPLICATE_PUBLICATION_ERRORS = new Set([
223
223
  messages.ERR_DUPLICATE_COMMENT_MODERATION
224
224
  ]);
225
225
  const CHALLENGE_EXCHANGE_TTL_MS = 600 * 1e3;
226
+ const SLOW_GET_CHALLENGE_WARNING_MS = 60 * 1e3;
226
227
  const defaultChallengeQuestionText = "What is the answer to this community's challenge? (check community.settings.challenges to see the answer, or set your own challenge)";
227
228
  function generateDefaultChallenges(answer) {
228
229
  return [{
@@ -998,15 +999,17 @@ async function getDbInternalState(community, lock) {
998
999
  if (lockedIt) await community._dbHandler.unlockCommunityState();
999
1000
  }
1000
1001
  }
1001
- async function updateDbInternalState(community, props) {
1002
+ async function updateDbInternalState(community, propsOrBuildProps) {
1002
1003
  const log = logger_default("pkc-js:local-community:_updateDbInternalState");
1003
- if (e(props)) throw Error("props to update DB internal state should not be empty");
1004
+ if (typeof propsOrBuildProps !== "function" && e(propsOrBuildProps)) throw Error("props to update DB internal state should not be empty");
1004
1005
  await community._dbHandler.initDbIfNeeded();
1005
- props._internalStateUpdateId = v4();
1006
+ let props = typeof propsOrBuildProps === "function" ? {} : propsOrBuildProps;
1006
1007
  let lockedIt = false;
1007
1008
  try {
1008
1009
  await community._dbHandler.lockCommunityState();
1009
1010
  lockedIt = true;
1011
+ if (typeof propsOrBuildProps === "function") props = propsOrBuildProps();
1012
+ props._internalStateUpdateId = v4();
1010
1013
  const internalStateBefore = await community._getDbInternalState(false);
1011
1014
  const propsToStore = "posts" in props && props.posts ? {
1012
1015
  ...props,
@@ -1035,12 +1038,15 @@ async function updateDbInternalState(community, props) {
1035
1038
  async function updateInstanceStateWithDbState(community) {
1036
1039
  const currentDbState = await community._getDbInternalState(false);
1037
1040
  if ("updatedAt" in currentDbState) {
1038
- if (currentDbState.posts && !("pages" in currentDbState.posts)) {
1041
+ if (currentDbState.posts && !("pages" in currentDbState.posts)) if (community._dbHandler.hasCommentsAndCommentUpdatesTables()) {
1039
1042
  const dbPosts = currentDbState.posts;
1040
1043
  currentDbState.posts = resolveDbPostsCidRefs({
1041
1044
  dbPosts,
1042
1045
  dbHandler: community._dbHandler
1043
1046
  });
1047
+ } else {
1048
+ logger_default("pkc-js:local-community:updateInstanceStateWithDbState").error(`The DB of community (${community.address}) is missing its comments or commentUpdates table, most likely after an interrupted migration. Loading it without posts, start() will restore them`);
1049
+ delete currentDbState.posts;
1044
1050
  }
1045
1051
  await community.initInternalCommunityAfterFirstUpdateNoMerge(currentDbState);
1046
1052
  } else await community.initInternalCommunityBeforeFirstUpdateNoMerge(currentDbState);
@@ -1104,11 +1110,26 @@ async function setChallengesToDefaultIfNotDefined(community, log) {
1104
1110
  }
1105
1111
  }
1106
1112
  }
1113
+ function doesDbFileHoldInternalState({ dbFilePath, internalStateKey, log }) {
1114
+ if (!existsSync(dbFilePath)) return false;
1115
+ let db;
1116
+ try {
1117
+ db = new Database(dbFilePath, {
1118
+ readonly: true,
1119
+ fileMustExist: true
1120
+ });
1121
+ return db.prepare("SELECT 1 FROM keyv WHERE key = ?").get(`keyv:${internalStateKey}`) !== void 0;
1122
+ } catch (e) {
1123
+ const code = e.code;
1124
+ if (typeof code === "string" && ["SQLITE_NOTADB", "SQLITE_ERROR"].includes(code)) return false;
1125
+ log.error(`Failed to tell whether ${dbFilePath} holds an internal state, leaving the file in place`, e);
1126
+ return;
1127
+ } finally {
1128
+ db?.close();
1129
+ }
1130
+ }
1107
1131
  async function createNewLocalCommunityDb(community) {
1108
1132
  const log = logger_default("pkc-js:local-community:_createNewLocalCommunityDb");
1109
- await community.initDbHandlerIfNeeded();
1110
- await community._dbHandler.initDbIfNeeded({ fileMustExist: false });
1111
- await community._dbHandler.createOrMigrateTablesIfNeeded();
1112
1133
  await initSignerProps(community, community.signer);
1113
1134
  if (!community.pubsubTopic && !community.settings?.disablePubsubChallengeExchange) community.pubsubTopic = t$9(community.signer.address);
1114
1135
  if (typeof community.createdAt !== "number") community.createdAt = timestamp();
@@ -1148,9 +1169,53 @@ async function createNewLocalCommunityDb(community) {
1148
1169
  pagesSettings: community.settings.pages,
1149
1170
  resolved: community._pageSorts
1150
1171
  });
1151
- if (community._dbHandler.keyvHas(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY])) throw Error("Internal state exists already");
1152
- await community._dbHandler.keyvSet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY], community.toJSONInternalBeforeFirstUpdate());
1153
- await community._updateStartedValue();
1172
+ await community.initDbHandlerIfNeeded();
1173
+ await forgetCommunityThatFailedToBeDeleted({
1174
+ communityAddress: community.address,
1175
+ pkc: community._pkc
1176
+ });
1177
+ await community._dbHandler.initDbConfigIfNeeded();
1178
+ const dbFilePath = community._dbHandler.getDbConfig().filename;
1179
+ let createdDbFile = false;
1180
+ if (dbFilePath !== ":memory:") try {
1181
+ closeSync(openSync(dbFilePath, "wx"));
1182
+ createdDbFile = true;
1183
+ } catch (e) {
1184
+ if (e.code !== "EEXIST") throw e;
1185
+ }
1186
+ const internalStateKey = STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY];
1187
+ try {
1188
+ await community._dbHandler.initDbIfNeeded({ fileMustExist: false });
1189
+ await community._dbHandler.createOrMigrateTablesIfNeeded();
1190
+ if (community._dbHandler.keyvHas(internalStateKey)) throw Error("Internal state exists already");
1191
+ await community._dbHandler.keyvSet(internalStateKey, community.toJSONInternalBeforeFirstUpdate());
1192
+ } catch (e) {
1193
+ try {
1194
+ community._dbHandler.destoryConnection();
1195
+ } catch (closeError) {
1196
+ log.error(`Failed to close the DB of community (${community.address}) after its creation failed`, closeError);
1197
+ }
1198
+ const isNotKnownToBeStateless = () => doesDbFileHoldInternalState({
1199
+ dbFilePath,
1200
+ internalStateKey,
1201
+ log
1202
+ }) !== false;
1203
+ if (createdDbFile) for (const filePath of [
1204
+ dbFilePath,
1205
+ `${dbFilePath}-wal`,
1206
+ `${dbFilePath}-shm`
1207
+ ]) await removeFileRetryingWhileBusy(filePath, {
1208
+ log,
1209
+ keepIf: isNotKnownToBeStateless
1210
+ }).catch((removeError) => log.error(`Failed to remove ${filePath} after the creation of community (${community.address}) failed`, removeError));
1211
+ throw e;
1212
+ }
1213
+ try {
1214
+ await community._updateStartedValue();
1215
+ } catch (e) {
1216
+ community._dbHandler.destoryConnection();
1217
+ throw e;
1218
+ }
1154
1219
  community._dbHandler.destoryConnection();
1155
1220
  community._updateIpnsPubsubPropsIfNeeded({
1156
1221
  ...community.toJSONInternalBeforeFirstUpdate(),
@@ -1360,6 +1425,7 @@ var DbHandler = class {
1360
1425
  constructor(community) {
1361
1426
  this._transactionGeneration = 0;
1362
1427
  this._publicationWriteGeneration = 0;
1428
+ this._heldStartLock = void 0;
1363
1429
  this._community = community;
1364
1430
  this._transactionDepth = 0;
1365
1431
  this._createdTables = false;
@@ -1459,8 +1525,11 @@ var DbHandler = class {
1459
1525
  destoryConnection() {
1460
1526
  const log = logger_default("pkc-js:local-community:dbHandler:destroyConnection");
1461
1527
  this._preparedStatements.clear();
1462
- if (this._db && this._db.open) {
1528
+ if (this._db && this._db.open) try {
1463
1529
  if (!this._db.readonly) this._db.exec("PRAGMA wal_checkpoint");
1530
+ } catch (e) {
1531
+ log.error("Failed to checkpoint the WAL of community", this._community.address, "before closing its DB", e);
1532
+ } finally {
1464
1533
  this._db.close();
1465
1534
  }
1466
1535
  if (this._keyv) this._keyv.disconnect();
@@ -1756,17 +1825,22 @@ var DbHandler = class {
1756
1825
  for (let i = 0; i < tables.length; i++) {
1757
1826
  const tableName = tables[i];
1758
1827
  const tableExists = this._tableExists(tableName);
1759
- if (!tableExists) {
1828
+ const tempTableName = `${tableName}_${version_default.DB_VERSION}_new`;
1829
+ if (!tableExists && needToMigrate && this._tableExists(tempTableName)) {
1830
+ log(`Table ${tableName} is missing but its migrated copy ${tempTableName} exists. Will restore the table from it`);
1831
+ this._db.exec(`ALTER TABLE ${tempTableName} RENAME TO ${tableName}`);
1832
+ } else if (!tableExists) {
1760
1833
  log(`Table ${tableName} does not exist. Will create schema`);
1761
1834
  createTableFunctions[i](tableName);
1762
1835
  } else if (tableExists && needToMigrate) {
1763
1836
  log(`Migrating table ${tableName} to new schema`);
1764
- const tempTableName = `${tableName}_${version_default.DB_VERSION}_new`;
1765
1837
  this._db.exec(`DROP TABLE IF EXISTS ${tempTableName}`);
1766
1838
  createTableFunctions[i](tempTableName);
1767
1839
  await this._copyTable(tableName, tempTableName, currentDbVersion);
1768
- this._db.exec(`DROP TABLE ${tableName}`);
1769
- this._db.exec(`ALTER TABLE ${tempTableName} RENAME TO ${tableName}`);
1840
+ this._db.transaction(() => {
1841
+ this._db.exec(`DROP TABLE ${tableName}`);
1842
+ this._db.exec(`ALTER TABLE ${tempTableName} RENAME TO ${tableName}`);
1843
+ })();
1770
1844
  }
1771
1845
  }
1772
1846
  this._createCommentsIndexes();
@@ -1808,7 +1882,14 @@ var DbHandler = class {
1808
1882
  this._columnNamesByTable = {};
1809
1883
  this._preparedStatements.clear();
1810
1884
  if (needToMigrate) log(`Created/migrated the tables to the latest (${newDbVersion}) version and saved to path`, this._dbConfig.filename);
1811
- if (backupDbPath) await fs$1.promises.rm(backupDbPath);
1885
+ if (backupDbPath) try {
1886
+ await removeFileRetryingWhileBusy(backupDbPath, { log });
1887
+ } catch (e) {
1888
+ log.error(`Failed to remove the pre-migration backup ${backupDbPath}. It is no longer needed and can be deleted`, e);
1889
+ }
1890
+ }
1891
+ hasCommentsAndCommentUpdatesTables() {
1892
+ return this._tableExists(TABLES.COMMENTS) && this._tableExists(TABLES.COMMENT_UPDATES);
1812
1893
  }
1813
1894
  _tableExists(tableName) {
1814
1895
  return !!this._db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?").get(tableName);
@@ -3794,6 +3875,10 @@ var DbHandler = class {
3794
3875
  const sourceDb = new Database(oldPathString, { fileMustExist: true });
3795
3876
  await sourceDb.backup(newPathString);
3796
3877
  sourceDb.close();
3878
+ await forgetCommunityThatFailedToBeDeleted({
3879
+ communityAddress: newDbName,
3880
+ pkc: this._community._pkc
3881
+ });
3797
3882
  if (os.type() === "Windows_NT") await deleteOldCommunityInWindows(oldPathString, this._community._pkc);
3798
3883
  else await fs$1.promises.rm(oldPathString, { force: true });
3799
3884
  }
@@ -3807,15 +3892,23 @@ var DbHandler = class {
3807
3892
  };
3808
3893
  log(`Changed db path from (${oldPathString}) to (${newPathString})`);
3809
3894
  }
3810
- async lockCommunityStart(communityAddress = this._community.address) {
3895
+ async lockCommunityStart({ onCompromised }) {
3811
3896
  const log = logger_default("pkc-js:local-community:db-handler:lock:start");
3897
+ const communityAddress = this._community.address;
3812
3898
  const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3813
3899
  const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3900
+ const startLock = {};
3814
3901
  try {
3815
3902
  await import_src.default.lock(communityDbPath, {
3816
3903
  lockfilePath,
3817
- onCompromised: () => {}
3904
+ onCompromised: (error) => {
3905
+ if (this._heldStartLock !== startLock) return;
3906
+ this._heldStartLock = void 0;
3907
+ log.error(`Lost the start lock of community (${communityAddress}), taken over or removed`, error);
3908
+ onCompromised(error);
3909
+ }
3818
3910
  });
3911
+ this._heldStartLock = startLock;
3819
3912
  log(`Locked the start of community (${communityAddress}) successfully`);
3820
3913
  } catch (e) {
3821
3914
  if (e instanceof Error && e.message === "Lock file is already being held") throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", {
@@ -3831,6 +3924,7 @@ var DbHandler = class {
3831
3924
  async unlockCommunityStart(communityAddress = this._community.address) {
3832
3925
  const log = logger_default("pkc-js:local-community:db-handler:unlock:start");
3833
3926
  log.trace(`Attempting to unlock the start of community (${communityAddress})`);
3927
+ this._heldStartLock = void 0;
3834
3928
  const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3835
3929
  const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3836
3930
  if (!fs$1.existsSync(lockfilePath) || !fs$1.existsSync(communityDbPath)) return;
@@ -6437,7 +6531,7 @@ async function publishCommunityRecordToIpns(community, build, newCommunityRecord
6437
6531
  }
6438
6532
  community._combinedHashOfPendingCommentsCids = newModQueue?.combinedHashOfCids || (0, import_sha256.sha256)("");
6439
6533
  log.trace("Updated combined hash of pending comments to", community._combinedHashOfPendingCommentsCids);
6440
- await community._updateDbInternalState(community.toJSONInternalAfterFirstUpdate());
6534
+ await community._updateDbInternalState(() => community.toJSONInternalAfterFirstUpdate());
6441
6535
  community._changeStateEmitEventEmitStateChangeEvent({
6442
6536
  newStartedState: "succeeded",
6443
6537
  event: {
@@ -6586,7 +6680,7 @@ async function publishLoop(community, syncIntervalMs) {
6586
6680
  const log = logger_default("pkc-js:local-community:_publishLoop");
6587
6681
  let syncFailedSinceStop = false;
6588
6682
  const shouldStopPublishLoop = () => {
6589
- return community.state !== "started" || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
6683
+ return community.state !== "started" || community._startLockLost || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
6590
6684
  };
6591
6685
  const waitUntilNextSync = async ({ lastSyncFailed }) => {
6592
6686
  const doneWithLoopTime = Date.now();
@@ -6663,9 +6757,33 @@ async function emitChallengeSettingsValidationErrors(community, log) {
6663
6757
  community.emit("error", error);
6664
6758
  }
6665
6759
  }
6760
+ async function runAsStartOrUpdateInFlight({ community, setUp }) {
6761
+ let settle;
6762
+ const inFlight = new Promise((resolve) => settle = resolve);
6763
+ community._startOrUpdateInFlight = inFlight;
6764
+ const releaseMark = () => {
6765
+ if (community._startOrUpdateInFlight === inFlight) community._startOrUpdateInFlight = void 0;
6766
+ };
6767
+ try {
6768
+ await setUp(releaseMark);
6769
+ } finally {
6770
+ releaseMark();
6771
+ settle();
6772
+ }
6773
+ }
6666
6774
  async function start(community) {
6667
- const log = logger_default("pkc-js:local-community:start");
6668
6775
  if (community.state === "updating") throw new PKCError("ERR_NEED_TO_STOP_UPDATING_COMMUNITY_BEFORE_STARTING", { address: community.address });
6776
+ if (community.state === "started" || community._startOrUpdateInFlight) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
6777
+ await runAsStartOrUpdateInFlight({
6778
+ community,
6779
+ setUp: (releaseMark) => startCommunity({
6780
+ community,
6781
+ releaseMark
6782
+ })
6783
+ });
6784
+ }
6785
+ async function startCommunity({ community, releaseMark }) {
6786
+ const log = logger_default("pkc-js:local-community:start");
6669
6787
  community._stopHasBeenCalled = false;
6670
6788
  community._firstUpdateAfterStart = true;
6671
6789
  community._lastProvidedBrowserDialableSelfAddrs = void 0;
@@ -6677,6 +6795,9 @@ async function start(community) {
6677
6795
  publicKey: community.publicKey,
6678
6796
  name: community.name
6679
6797
  }) || findProcessStartedCommunity(community)) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
6798
+ community._startLockLost = false;
6799
+ let startLockLostDuringStart;
6800
+ let startFinished = false;
6680
6801
  try {
6681
6802
  await initBeforeStarting(community);
6682
6803
  if (community.anchor && !getPersistedAnchorRecordBytes(community)) throw new PKCError("ERR_DELEGATED_COMMUNITY_HAS_NO_ANCHOR_RECORD", {
@@ -6689,9 +6810,17 @@ async function start(community) {
6689
6810
  pkc: community._pkc,
6690
6811
  communityAddress: community.address
6691
6812
  });
6813
+ await community._dbHandler.lockCommunityStart({ onCompromised: (error) => {
6814
+ community._startLockLost = true;
6815
+ const lostLockError = new PKCError("ERR_COMMUNITY_START_LOCK_COMPROMISED", {
6816
+ communityAddress: community.address,
6817
+ error
6818
+ });
6819
+ if (startFinished) stopAfterLosingStartLock(community, lostLockError);
6820
+ else startLockLostDuringStart = lostLockError;
6821
+ } });
6692
6822
  community._setState("started");
6693
6823
  await community._updateStartedValue();
6694
- await community._dbHandler.lockCommunityStart();
6695
6824
  trackStartedCommunity(community._pkc, community);
6696
6825
  syncProcessStartedCommunity(community);
6697
6826
  await community._updateStartedValue();
@@ -6712,13 +6841,18 @@ async function start(community) {
6712
6841
  community._setStartedStateWithEmission("publishing-ipns");
6713
6842
  await community._repinCommentsIPFSIfNeeded();
6714
6843
  await repinCommentUpdateIfNeeded(community);
6844
+ if (startLockLostDuringStart) throw startLockLostDuringStart;
6715
6845
  await community._listenToIncomingRequests();
6716
6846
  await emitChallengeSettingsValidationErrors(community, log);
6717
6847
  community._pageSorts = void 0;
6718
6848
  community._pageSortFactories = void 0;
6719
6849
  await syncPageSortsWithRegistry(community);
6850
+ if (startLockLostDuringStart) throw startLockLostDuringStart;
6851
+ startFinished = true;
6720
6852
  } catch (e) {
6853
+ releaseMark();
6721
6854
  await community.stop();
6855
+ if (community.state === "stopped" && !community._startOrUpdateInFlight) community._dbHandler.destoryConnection();
6722
6856
  e.details = {
6723
6857
  ...e.details,
6724
6858
  communityAddress: community.address
@@ -6730,6 +6864,12 @@ async function start(community) {
6730
6864
  community.emit("error", err);
6731
6865
  });
6732
6866
  }
6867
+ function stopAfterLosingStartLock(community, error) {
6868
+ const log = logger_default("pkc-js:local-community:stopAfterLosingStartLock");
6869
+ if (community.state !== "started") return;
6870
+ if (!community._stopHasBeenCalled) community.stop().catch((e) => log.error(`Failed to stop community (${community.address}) after losing its start lock`, e));
6871
+ community.emit("error", error);
6872
+ }
6733
6873
  async function initMirroringStartedOrUpdatingCommunity(community, startedCommunity) {
6734
6874
  const updatingStateChangeListener = (newState) => {
6735
6875
  community._setUpdatingStateWithEventEmissionIfNewState(newState);
@@ -6845,19 +6985,40 @@ async function updateLoop(community) {
6845
6985
  async function update(community) {
6846
6986
  if (community.state === "started") throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
6847
6987
  if (community.state === "updating") return;
6848
- community._stopHasBeenCalled = false;
6849
- community._setState("updating");
6988
+ if (community._startOrUpdateInFlight) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
6989
+ await runAsStartOrUpdateInFlight({
6990
+ community,
6991
+ setUp: async () => {
6992
+ community._stopHasBeenCalled = false;
6993
+ community._setState("updating");
6994
+ try {
6995
+ await updateOnce(community);
6996
+ } catch (e) {
6997
+ community.emit("error", e);
6998
+ }
6999
+ community._updateLoopAbortController = new AbortController();
7000
+ community._updateLoopPromise = updateLoop(community);
7001
+ }
7002
+ });
7003
+ }
7004
+ async function stop(community) {
7005
+ community._stopHasBeenCalled = true;
7006
+ while (community._startOrUpdateInFlight || community._stopInFlight || community._editStoresInFlight.size > 0) {
7007
+ await (community._startOrUpdateInFlight ?? community._stopInFlight ?? Promise.allSettled([...community._editStoresInFlight]));
7008
+ community._stopHasBeenCalled = true;
7009
+ }
7010
+ let settle;
7011
+ const stopInFlight = new Promise((resolve) => settle = resolve);
7012
+ community._stopInFlight = stopInFlight;
6850
7013
  try {
6851
- await updateOnce(community);
6852
- } catch (e) {
6853
- community.emit("error", e);
7014
+ await stopCommunity(community);
7015
+ } finally {
7016
+ if (community._stopInFlight === stopInFlight) community._stopInFlight = void 0;
7017
+ settle();
6854
7018
  }
6855
- community._updateLoopAbortController = new AbortController();
6856
- community._updateLoopPromise = updateLoop(community);
6857
7019
  }
6858
- async function stop(community) {
7020
+ async function stopCommunity(community) {
6859
7021
  const log = logger_default("pkc-js:local-community:stop");
6860
- community._stopHasBeenCalled = true;
6861
7022
  if (community._updateLoopAbortController) community._updateLoopAbortController.abort();
6862
7023
  community.posts._stop();
6863
7024
  if (community.state === "started") {
@@ -6877,20 +7038,23 @@ async function stop(community) {
6877
7038
  }
6878
7039
  community._publishLoopPromise = void 0;
6879
7040
  }
6880
- try {
6881
- await unpinStaleCids(community, { bypassGracePeriod: true });
6882
- } catch (e) {
6883
- log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
6884
- }
6885
- try {
6886
- await updateDbInternalState(community, community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
6887
- } catch (e) {
6888
- log.error("Failed to update db internal state before stopping", e);
6889
- }
6890
- try {
6891
- await community._dbHandler.unlockCommunityStart();
6892
- } catch (e) {
6893
- log.error(`Failed to unlock start lock on community (${community.address})`, e);
7041
+ if (community._startLockLost) log(`Community (${community.address}) lost its start lock, stopping without writing its state, unpinning or unlocking`);
7042
+ else {
7043
+ try {
7044
+ await unpinStaleCids(community, { bypassGracePeriod: true });
7045
+ } catch (e) {
7046
+ log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
7047
+ }
7048
+ try {
7049
+ await updateDbInternalState(community, () => community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
7050
+ } catch (e) {
7051
+ log.error("Failed to update db internal state before stopping", e);
7052
+ }
7053
+ try {
7054
+ await community._dbHandler.unlockCommunityStart();
7055
+ } catch (e) {
7056
+ log.error(`Failed to unlock start lock on community (${community.address})`, e);
7057
+ }
6894
7058
  }
6895
7059
  const kuboRpcClient = community._clientsManager.getDefaultKuboRpcClient();
6896
7060
  community._setStartedStateWithEmission("stopped");
@@ -7109,24 +7273,89 @@ function deriveNameAndAddressEdit(community, editOptions) {
7109
7273
  function listRenamedCommunityNow(community) {
7110
7274
  refreshCommunitiesList(community._pkc);
7111
7275
  }
7112
- async function restoreCommunityAfterFailedRename({ community, oldAddress, newAddress, postUpdatesFolderMoved, log }) {
7276
+ async function movePostUpdatesFolderBack({ community, oldAddress, newAddress, log }) {
7277
+ try {
7278
+ await movePostUpdatesFolderToNewAddress(community, newAddress, oldAddress);
7279
+ return;
7280
+ } catch (moveBackError) {
7281
+ log.error(`Failed to move the postUpdates folder of community (${oldAddress}) back from ${newAddress}`, moveBackError);
7282
+ return moveBackError;
7283
+ }
7284
+ }
7285
+ function emitRenameUndoError({ community, error, log }) {
7286
+ try {
7287
+ community.emit("error", error);
7288
+ } catch (emitError) {
7289
+ log.error(`Nothing listens for the errors of community (${community.address}), the error it could not report was`, error);
7290
+ }
7291
+ }
7292
+ async function restartCommunityAfterFailedRename({ community, oldAddress, newAddress, log }) {
7113
7293
  try {
7114
- if (postUpdatesFolderMoved) await movePostUpdatesFolderToNewAddress(community, newAddress, oldAddress);
7115
7294
  await community.start();
7116
- } catch (restoreError) {
7117
- log.error(`Failed to restore community (${oldAddress}) after its rename to ${newAddress} failed`, restoreError);
7118
- community.emit("error", restoreError);
7295
+ } catch (restartError) {
7296
+ log.error(`Failed to restart community (${oldAddress}) after its rename to ${newAddress} failed`, restartError);
7297
+ emitRenameUndoError({
7298
+ community,
7299
+ error: restartError,
7300
+ log
7301
+ });
7119
7302
  }
7120
7303
  }
7121
7304
  async function removePartialDbCopy({ community, oldAddress, newAddress, log }) {
7122
7305
  const communitiesPath = path.join(community._pkc.dataPath, "communities");
7123
- if (!fs.existsSync(path.join(communitiesPath, oldAddress))) return;
7306
+ const partialDbCopyPath = path.join(communitiesPath, newAddress);
7307
+ if (!fs.existsSync(path.join(communitiesPath, oldAddress))) return {
7308
+ removed: false,
7309
+ path: partialDbCopyPath
7310
+ };
7124
7311
  try {
7125
- await fs.promises.rm(path.join(communitiesPath, newAddress), { force: true });
7312
+ await removeFileRetryingWhileBusy(partialDbCopyPath, { log });
7313
+ return { removed: true };
7126
7314
  } catch (e) {
7127
- log.error(`Failed to remove the partial DB copy of community (${oldAddress}) at ${newAddress}`, e);
7315
+ log.error(`Failed to remove the partial DB copy of community (${oldAddress}) at ${partialDbCopyPath}`, e);
7316
+ return {
7317
+ removed: false,
7318
+ path: partialDbCopyPath,
7319
+ error: e
7320
+ };
7128
7321
  }
7129
7322
  }
7323
+ async function undoRenameAfterDbRenameFailed({ community, oldAddress, newAddress, dbRenameError, log }) {
7324
+ const communitiesPath = path.join(community._pkc.dataPath, "communities");
7325
+ const partialDbCopy = await removePartialDbCopy({
7326
+ community,
7327
+ oldAddress,
7328
+ newAddress,
7329
+ log
7330
+ });
7331
+ const moveBackError = await movePostUpdatesFolderBack({
7332
+ community,
7333
+ oldAddress,
7334
+ newAddress,
7335
+ log
7336
+ });
7337
+ const renameError = dbRenameError;
7338
+ return {
7339
+ error: new PKCError("ERR_FAILED_TO_RENAME_COMMUNITY_DB", {
7340
+ oldAddress,
7341
+ newAddress,
7342
+ oldDbPath: path.join(communitiesPath, oldAddress),
7343
+ newDbPath: path.join(communitiesPath, newAddress),
7344
+ error: dbRenameError,
7345
+ errorMessage: renameError?.message,
7346
+ errorName: renameError?.name,
7347
+ errorCode: renameError?.code,
7348
+ partialDbCopyRemoved: partialDbCopy.removed,
7349
+ ...partialDbCopy.removed ? {} : {
7350
+ partialDbCopyPath: partialDbCopy.path,
7351
+ partialDbCopyRemovalError: partialDbCopy.error
7352
+ },
7353
+ postUpdatesFolderMovedBack: moveBackError === void 0,
7354
+ ...moveBackError ? { postUpdatesFolderMoveBackError: moveBackError } : {}
7355
+ }),
7356
+ moveBackError
7357
+ };
7358
+ }
7130
7359
  async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEdit) {
7131
7360
  const log = logger_default("pkc-js:local-community:start:editPropsOnStartedCommunity");
7132
7361
  const oldAddress = t$9(community.address);
@@ -7139,11 +7368,10 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7139
7368
  try {
7140
7369
  await movePostUpdatesFolderToNewAddress(community, oldAddress, newAddress);
7141
7370
  } catch (e) {
7142
- await restoreCommunityAfterFailedRename({
7371
+ await restartCommunityAfterFailedRename({
7143
7372
  community,
7144
7373
  oldAddress,
7145
7374
  newAddress,
7146
- postUpdatesFolderMoved: false,
7147
7375
  log
7148
7376
  });
7149
7377
  throw e;
@@ -7151,20 +7379,25 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7151
7379
  try {
7152
7380
  await community._dbHandler.changeDbFilename(oldAddress, newAddress);
7153
7381
  } catch (e) {
7154
- await removePartialDbCopy({
7382
+ const { error, moveBackError } = await undoRenameAfterDbRenameFailed({
7155
7383
  community,
7156
7384
  oldAddress,
7157
7385
  newAddress,
7386
+ dbRenameError: e,
7158
7387
  log
7159
7388
  });
7160
- await restoreCommunityAfterFailedRename({
7389
+ if (moveBackError) emitRenameUndoError({
7390
+ community,
7391
+ error: moveBackError,
7392
+ log
7393
+ });
7394
+ else await restartCommunityAfterFailedRename({
7161
7395
  community,
7162
7396
  oldAddress,
7163
7397
  newAddress,
7164
- postUpdatesFolderMoved: true,
7165
7398
  log
7166
7399
  });
7167
- throw e;
7400
+ throw error;
7168
7401
  }
7169
7402
  listRenamedCommunityNow(community);
7170
7403
  community.setAddress(newAddress);
@@ -7175,10 +7408,21 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7175
7408
  editId: uniqueEditId
7176
7409
  });
7177
7410
  await community.start();
7178
- } else community._pendingEditProps.push({
7179
- ...parsedEditOptions,
7180
- editId: uniqueEditId
7181
- });
7411
+ } else {
7412
+ if (!e(parsedEditOptions)) {
7413
+ const store = updateDbInternalState(community, { ...parsedEditOptions });
7414
+ community._editStoresInFlight.add(store);
7415
+ try {
7416
+ await store;
7417
+ } finally {
7418
+ community._editStoresInFlight.delete(store);
7419
+ }
7420
+ }
7421
+ community._pendingEditProps.push({
7422
+ ...parsedEditOptions,
7423
+ editId: uniqueEditId
7424
+ });
7425
+ }
7182
7426
  if (community.updateCid) await community.initInternalCommunityAfterFirstUpdateNoMerge({
7183
7427
  ...community.toJSONInternalAfterFirstUpdate(),
7184
7428
  ...parsedEditOptions,
@@ -7208,9 +7452,20 @@ async function editPropsOnNotStartedCommunity(community, parsedEditOptions, page
7208
7452
  await validateNewAddressBeforeEditing(community, parsedEditOptions.address, log);
7209
7453
  log(`Attempting to edit community.address from ${oldAddress} to ${parsedEditOptions.address}`);
7210
7454
  log("will rename the community", community.address, "db in edit() because the community is not being ran anywhere else");
7211
- await movePostUpdatesFolderToNewAddress(community, community.address, parsedEditOptions.address);
7212
- community._dbHandler.destoryConnection();
7213
- await community._dbHandler.changeDbFilename(community.address, parsedEditOptions.address);
7455
+ const newAddress = parsedEditOptions.address;
7456
+ await movePostUpdatesFolderToNewAddress(community, oldAddress, newAddress);
7457
+ await community._dbHandler.destoryConnection();
7458
+ try {
7459
+ await community._dbHandler.changeDbFilename(oldAddress, newAddress);
7460
+ } catch (e) {
7461
+ throw (await undoRenameAfterDbRenameFailed({
7462
+ community,
7463
+ oldAddress,
7464
+ newAddress,
7465
+ dbRenameError: e,
7466
+ log
7467
+ })).error;
7468
+ }
7214
7469
  listRenamedCommunityNow(community);
7215
7470
  await community._dbHandler.initDbIfNeeded();
7216
7471
  community.setAddress(parsedEditOptions.address);
@@ -7224,6 +7479,7 @@ async function editPropsOnNotStartedCommunity(community, parsedEditOptions, page
7224
7479
  return community;
7225
7480
  }
7226
7481
  async function edit(community, newCommunityOptions) {
7482
+ while (community._stopInFlight) await community._stopInFlight;
7227
7483
  const startedCommunity = findStartedCommunity(community._pkc, {
7228
7484
  publicKey: community.publicKey,
7229
7485
  name: community.name
@@ -7254,6 +7510,7 @@ async function edit(community, newCommunityOptions) {
7254
7510
  ...n$2(editWithDerivedName, ["roles"]),
7255
7511
  ...newInternalProps
7256
7512
  };
7513
+ if (community._stopInFlight) return edit(community, newCommunityOptions);
7257
7514
  if (!community.started && !startedCommunity) return editPropsOnNotStartedCommunity(community, newProps, pagesEdit);
7258
7515
  if (findStartedCommunity(community._pkc, {
7259
7516
  publicKey: community.publicKey,
@@ -7476,6 +7733,7 @@ var LocalCommunity = class extends RpcLocalCommunity {
7476
7733
  this._inFlightPublicationExchanges = /* @__PURE__ */ new Map();
7477
7734
  this._pseudonymityAliasLocks = /* @__PURE__ */ new Map();
7478
7735
  this._challengeExchangeTtlMs = CHALLENGE_EXCHANGE_TTL_MS;
7736
+ this._slowGetChallengeWarningMs = SLOW_GET_CHALLENGE_WARNING_MS;
7479
7737
  this._cidsToUnPin = /* @__PURE__ */ new Set();
7480
7738
  this._mfsPathsToRemove = /* @__PURE__ */ new Set();
7481
7739
  this._communityUpdateTriggerValue = false;
@@ -7484,8 +7742,12 @@ var LocalCommunity = class extends RpcLocalCommunity {
7484
7742
  this._pageSorts = void 0;
7485
7743
  this._pageSortFactories = void 0;
7486
7744
  this._reportedChallengeLoadFailures = void 0;
7745
+ this._startLockLost = false;
7487
7746
  this._publishLoopPromise = void 0;
7488
7747
  this._updateLoopPromise = void 0;
7748
+ this._startOrUpdateInFlight = void 0;
7749
+ this._stopInFlight = void 0;
7750
+ this._editStoresInFlight = /* @__PURE__ */ new Set();
7489
7751
  this._firstUpdateAfterStart = true;
7490
7752
  this._internalStateUpdateId = "";
7491
7753
  this._lastPubsubTopicRoutingProvideAt = void 0;