@pkcprotocol/pkc-js 0.0.152 → 0.0.154

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 (132) hide show
  1. package/README.md +21 -1
  2. package/dist/browser/clients/rpc-client/schema.d.ts +1 -1
  3. package/dist/browser/clients/rpc-client/schema.js +1 -1
  4. package/dist/browser/clients/rpc-client/schema.js.map +1 -1
  5. package/dist/browser/errors.d.ts +4 -2
  6. package/dist/browser/errors.js +4 -2
  7. package/dist/browser/errors.js.map +1 -1
  8. package/dist/browser/generated-version.d.ts +1 -1
  9. package/dist/browser/generated-version.js +1 -1
  10. package/dist/browser/pkc-error.d.ts +1 -1
  11. package/dist/browser/publications/comment/comment.d.ts +1 -0
  12. package/dist/browser/publications/comment/comment.js +57 -12
  13. package/dist/browser/publications/comment/comment.js.map +1 -1
  14. package/dist/browser/publications/comment/schema.d.ts +1 -0
  15. package/dist/browser/publications/comment/schema.js +6 -2
  16. package/dist/browser/publications/comment/schema.js.map +1 -1
  17. package/dist/browser/publications/publication.d.ts +8 -1
  18. package/dist/browser/publications/publication.js +393 -146
  19. package/dist/browser/publications/publication.js.map +1 -1
  20. package/dist/browser/publications/types.d.ts +1 -0
  21. package/dist/browser/rpc/src/index.js +12 -5
  22. package/dist/browser/rpc/src/index.js.map +1 -1
  23. package/dist/browser/runtime/node/blockstore.d.ts +2 -2
  24. package/dist/browser/runtime/node/blockstore.js +2 -2
  25. package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js +7 -2
  26. package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
  27. package/dist/browser/runtime/node/community/comment-update-row.d.ts +9 -0
  28. package/dist/browser/runtime/node/community/comment-update-row.js +49 -0
  29. package/dist/browser/runtime/node/community/comment-update-row.js.map +1 -0
  30. package/dist/browser/runtime/node/community/db-handler.d.ts +5 -7
  31. package/dist/browser/runtime/node/community/db-handler.js +89 -87
  32. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  33. package/dist/browser/runtime/node/community/db-row-parser.js +15 -1
  34. package/dist/browser/runtime/node/community/db-row-parser.js.map +1 -1
  35. package/dist/browser/runtime/node/community/local-community/cleanup.js +62 -12
  36. package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
  37. package/dist/browser/runtime/node/community/local-community/comment-updates.js +17 -8
  38. package/dist/browser/runtime/node/community/local-community/comment-updates.js.map +1 -1
  39. package/dist/browser/runtime/node/community/local-community/db-state.d.ts +1 -1
  40. package/dist/browser/runtime/node/community/local-community/db-state.js +31 -39
  41. package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
  42. package/dist/browser/runtime/node/community/local-community/editing.js +71 -22
  43. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  44. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js +1 -1
  45. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  46. package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  47. package/dist/browser/runtime/node/community/local-community/lifecycle.js +50 -72
  48. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  49. package/dist/browser/runtime/node/community/local-community.d.ts +4 -2
  50. package/dist/browser/runtime/node/community/local-community.js +11 -7
  51. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  52. package/dist/browser/runtime/node/community/start-lock.d.ts +14 -5
  53. package/dist/browser/runtime/node/community/start-lock.js +153 -10
  54. package/dist/browser/runtime/node/community/start-lock.js.map +1 -1
  55. package/dist/browser/runtime/node/util.js +20 -11
  56. package/dist/browser/runtime/node/util.js.map +1 -1
  57. package/dist/browser/signer/signatures.js +12 -6
  58. package/dist/browser/signer/signatures.js.map +1 -1
  59. package/dist/browser/version.js +1 -1
  60. package/dist/bundled/bundle-manifest.json +36 -44
  61. package/dist/bundled/challenges.js +1 -1
  62. package/dist/bundled/chunks/{helia-for-pkc-DSBGaWoX.js → helia-for-pkc-CG9YohPs.js} +35 -35
  63. package/dist/bundled/chunks/{local-community-CKRKoJii.js → local-community-CaQmhX8D.js} +1 -1
  64. package/dist/bundled/chunks/{local-community-nvuF7v2h.js → local-community-V8_VyEhO.js} +302 -203
  65. package/dist/bundled/chunks/{node-POly7vn3.js → node-c4vpD2VN.js} +340 -172
  66. package/dist/bundled/chunks/{page-sort-scoring-B12LzU3B.js → page-sort-scoring-d1frahfd.js} +1 -1
  67. package/dist/bundled/chunks/{rpc-local-community-BpvBPdXg.js → rpc-local-community-DDAibWpE.js} +154 -1437
  68. package/dist/bundled/chunks/{util-BjNpPYD5.js → util-B_dKP7Te.js} +1 -1
  69. package/dist/bundled/chunks/{util-sMOCDTgY.js → util-BwEIge-b.js} +9 -6
  70. package/dist/bundled/chunks/{validate-package-factories-DC853tZf.js → validate-package-factories-DfpNf4oq.js} +2 -2
  71. package/dist/bundled/index.js +1 -1
  72. package/dist/bundled/page-sorts.js +1 -1
  73. package/dist/bundled/rpc/src/index.js +14 -9
  74. package/dist/node/clients/rpc-client/schema.d.ts +1 -1
  75. package/dist/node/clients/rpc-client/schema.js +1 -1
  76. package/dist/node/clients/rpc-client/schema.js.map +1 -1
  77. package/dist/node/errors.d.ts +4 -2
  78. package/dist/node/errors.js +4 -2
  79. package/dist/node/errors.js.map +1 -1
  80. package/dist/node/generated-version.d.ts +1 -1
  81. package/dist/node/generated-version.js +1 -1
  82. package/dist/node/pkc-error.d.ts +1 -1
  83. package/dist/node/publications/comment/comment.d.ts +1 -0
  84. package/dist/node/publications/comment/comment.js +57 -12
  85. package/dist/node/publications/comment/comment.js.map +1 -1
  86. package/dist/node/publications/comment/schema.d.ts +1 -0
  87. package/dist/node/publications/comment/schema.js +6 -2
  88. package/dist/node/publications/comment/schema.js.map +1 -1
  89. package/dist/node/publications/publication.d.ts +8 -1
  90. package/dist/node/publications/publication.js +393 -146
  91. package/dist/node/publications/publication.js.map +1 -1
  92. package/dist/node/publications/types.d.ts +1 -0
  93. package/dist/node/rpc/src/index.js +12 -5
  94. package/dist/node/rpc/src/index.js.map +1 -1
  95. package/dist/node/runtime/node/blockstore.d.ts +2 -2
  96. package/dist/node/runtime/node/blockstore.js +2 -2
  97. package/dist/node/runtime/node/community/challenges/validate-challenge-result.js +7 -2
  98. package/dist/node/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
  99. package/dist/node/runtime/node/community/comment-update-row.d.ts +9 -0
  100. package/dist/node/runtime/node/community/comment-update-row.js +49 -0
  101. package/dist/node/runtime/node/community/comment-update-row.js.map +1 -0
  102. package/dist/node/runtime/node/community/db-handler.d.ts +5 -7
  103. package/dist/node/runtime/node/community/db-handler.js +89 -87
  104. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  105. package/dist/node/runtime/node/community/db-row-parser.js +15 -1
  106. package/dist/node/runtime/node/community/db-row-parser.js.map +1 -1
  107. package/dist/node/runtime/node/community/local-community/cleanup.js +62 -12
  108. package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
  109. package/dist/node/runtime/node/community/local-community/comment-updates.js +17 -8
  110. package/dist/node/runtime/node/community/local-community/comment-updates.js.map +1 -1
  111. package/dist/node/runtime/node/community/local-community/db-state.d.ts +1 -1
  112. package/dist/node/runtime/node/community/local-community/db-state.js +31 -39
  113. package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
  114. package/dist/node/runtime/node/community/local-community/editing.js +71 -22
  115. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  116. package/dist/node/runtime/node/community/local-community/ipns-publishing.js +1 -1
  117. package/dist/node/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  118. package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  119. package/dist/node/runtime/node/community/local-community/lifecycle.js +50 -72
  120. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  121. package/dist/node/runtime/node/community/local-community.d.ts +4 -2
  122. package/dist/node/runtime/node/community/local-community.js +11 -7
  123. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  124. package/dist/node/runtime/node/community/start-lock.d.ts +14 -5
  125. package/dist/node/runtime/node/community/start-lock.js +153 -10
  126. package/dist/node/runtime/node/community/start-lock.js.map +1 -1
  127. package/dist/node/runtime/node/util.js +20 -11
  128. package/dist/node/runtime/node/util.js.map +1 -1
  129. package/dist/node/signer/signatures.js +12 -6
  130. package/dist/node/signer/signatures.js.map +1 -1
  131. package/dist/node/version.js +1 -1
  132. package/package.json +1 -2
@@ -1,14 +1,14 @@
1
1
  import { i as __toESM } from "./chunk-2rV9d50f.js";
2
- import { $n as CommentEditsTableRowSchema, At as ChallengeAnswerMessageSchema, B as pubsubTopicToDhtKey, Bt as DecryptedChallengeRequestSchema, C as hideClassPrivateProps, Ct as trackUpdatingCommunity, Dt as require_sha256, En as VotePubsubReservedFields, Et as untrackUpdatingCommunity, F as isLinkOfVideo, G as removeBlocksFromKuboNode, Hn as CommentsTableRowSchema, I as isLinkValid, It as ChallengeVerificationMessageSchema, J as removeNullUndefinedValues, Jt as version_default, K as removeMfsFilesSafely, Lr as PKCError, M as isLinkOfAudio, Mn as CommentPubsubMessageReservedFields, Mt as ChallengeMessageSchema, N as isLinkOfImage, On as VoteTablesRowSchema, Or as t$4, P as isLinkOfMedia, Pt as ChallengeRequestMessageSchema, Q as retryKuboBlockPutPinAndProvidePubsubTopic, Rr as messages, Sr as e, T as ipnsNameToIpnsOverPubsubTopic, Tn as VotePubsubMessagePublicationSchema, Tr as t$3, Vn as CommentUpdateTableRowSchema, Xn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Xt as CommunityEditPublicationPubsubReservedFields, Yn as CommentEditPubsubMessagePublicationSchema, Zn as CommentEditReservedFields, _ as genToArray, _r as t$7, b as getIpnsRecordInLocalKuboNode, br as t$6, bt as syncCommunityRegistryEntry, c as contentContainsMarkdownImages, ct as withSortedKeys, dt as findStartedCommunity, et as retryKuboIpfsAddAndProvide, f as derivePublicationFromChallengeRequest, g as findMalformedUnicodeString, gr as n$3, hr as isStringDomain, i as calculateStringSizeSameAsIpfsAddCidV0, in as CommentModerationsTableRowSchema, ir as AuthorReservedFields, it as statMfsPathSafely, j as isLinkOfAnimatedImage, jn as CommentIpfsSchema, jr as require_retry, kr as t$2, kt as pTimeout, l as contentContainsMarkdownVideos, lt as withSortedKeysDeep, mn as CommunitySignedPropertyNames, nn as CommentModerationReservedFields, o as calculateUnixFsDagSizeCidV0, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsSchema, pt as findUpdatingCommunity, r as calculateIpfsCidV0, rt as sleepUntilTimeoutOrAbort, s as contentContainsMarkdownAudio, ti as ZodError, tn as CommentModerationPubsubMessagePublicationSchema, ut as findCommunityInRegistry, v as getEquivalentCommunityAddresses, vr as n$2, wr as r$1, wt as untrackStartedCommunity, xr as e$1, xt as trackStartedCommunity, y as getErrorCodeFromMessage, yr as t$5, zn as CommentUpdateSchema, zr as logger_default, zt as DecryptedChallengeRequestPublicationSchema } from "./util-sMOCDTgY.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-BpvBPdXg.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-B12LzU3B.js";
2
+ import { $n as CommentEditsTableRowSchema, At as ChallengeAnswerMessageSchema, B as pubsubTopicToDhtKey, Bt as DecryptedChallengeRequestSchema, C as hideClassPrivateProps, Ct as trackUpdatingCommunity, Dt as require_sha256, En as VotePubsubReservedFields, Et as untrackUpdatingCommunity, F as isLinkOfVideo, G as removeBlocksFromKuboNode, Hn as CommentsTableRowSchema, I as isLinkValid, It as ChallengeVerificationMessageSchema, J as removeNullUndefinedValues, Jt as version_default, K as removeMfsFilesSafely, Lr as PKCError, M as isLinkOfAudio, Mn as CommentPubsubMessageReservedFields, Mt as ChallengeMessageSchema, N as isLinkOfImage, On as VoteTablesRowSchema, Or as t$4, P as isLinkOfMedia, Pt as ChallengeRequestMessageSchema, Q as retryKuboBlockPutPinAndProvidePubsubTopic, Rr as messages, Sr as e, T as ipnsNameToIpnsOverPubsubTopic, Tn as VotePubsubMessagePublicationSchema, Tr as t$3, Vn as CommentUpdateTableRowSchema, Xn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Xt as CommunityEditPublicationPubsubReservedFields, Yn as CommentEditPubsubMessagePublicationSchema, Zn as CommentEditReservedFields, _ as genToArray, _r as t$7, b as getIpnsRecordInLocalKuboNode, br as t$6, bt as syncCommunityRegistryEntry, c as contentContainsMarkdownImages, ct as withSortedKeys, dt as findStartedCommunity, et as retryKuboIpfsAddAndProvide, f as derivePublicationFromChallengeRequest, g as findMalformedUnicodeString, gr as n$3, hr as isStringDomain, i as calculateStringSizeSameAsIpfsAddCidV0, in as CommentModerationsTableRowSchema, ir as AuthorReservedFields, it as statMfsPathSafely, j as isLinkOfAnimatedImage, jn as CommentIpfsSchema, jr as require_retry, kr as t$2, kt as pTimeout, l as contentContainsMarkdownVideos, lt as withSortedKeysDeep, mn as CommunitySignedPropertyNames, nn as CommentModerationReservedFields, o as calculateUnixFsDagSizeCidV0, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsSchema, pt as findUpdatingCommunity, r as calculateIpfsCidV0, rt as sleepUntilTimeoutOrAbort, s as contentContainsMarkdownAudio, ti as ZodError, tn as CommentModerationPubsubMessagePublicationSchema, ut as findCommunityInRegistry, v as getEquivalentCommunityAddresses, vr as n$2, wr as r$1, wt as untrackStartedCommunity, xr as e$1, xt as trackStartedCommunity, y as getErrorCodeFromMessage, yr as t$5, zn as CommentUpdateSchema, zr as logger_default, zt as DecryptedChallengeRequestPublicationSchema } from "./util-BwEIge-b.js";
3
+ import { $ as createSchemaRowParser, An as verifyChallengeAnswer, Ar as removeFileRetryingWhileBusy, Bn as verifyCommunityEdit, Br as takeStartLock, Dt as parseJsonWithPKCErrorIfFails, En as signCommunity, Fn as verifyCommentIpfs, Gr as n$5, Hn as verifyVote, Hr as t$11, In as verifyCommentModeration, Jr as t$9, Kn as getAuthorNameFromWire, Kr as n$4, Ln as verifyCommentPubsubMessage, Lr as getStartLockPath, Mn as verifyChallengeRequest, N as MAX_PAGE_SIZE_BYTES, Or as moveCommunityDbToDeletedDirectory, Pn as verifyCommentEdit, Pr as findCommunitiesEntry, Q as collectSchemaRowCoercions, Qn as effectiveMaxCrosspostDepth, Rn as verifyCommentUpdate, Rr as isCommunityStartLocked, 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 r$2, Vr as t$10, W as pLimit, Wn as cleanWireAuthor, Wr as t$8, X as coerceSchemaRowBoolean, Yr as stringify, 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, ei as STORAGE_KEYS, 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, r as computePageSortsFingerprint, s as lookupPageSortFactories, sr as getIpfsKeyFromPrivateKey, t as RpcLocalCommunity, ti as require_lodash_merge, 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 releaseStartLock } from "./rpc-local-community-DDAibWpE.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-d1frahfd.js";
5
5
  import { c as prepare, n as decode$1, r as encode$1 } from "./src-BSYNGtIQ.js";
6
6
  import { t as UnixFS } from "./src-CAvdjq_i.js";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
- import Path from "node:path";
8
+ import path from "node:path";
9
9
  import os from "os";
10
10
  import fs, { closeSync, existsSync, openSync, promises } from "node:fs";
11
- import path from "path";
11
+ import path$1 from "path";
12
12
  import assert from "assert";
13
13
  import { Buffer as Buffer$1 } from "buffer";
14
14
  import fs$1 from "fs";
@@ -187,6 +187,34 @@ async function reprovideAnchorRecordIfDue(community) {
187
187
  await reprovideAnchorRecordIfNeeded(community);
188
188
  }
189
189
  //#endregion
190
+ //#region dist/node/runtime/node/community/comment-update-row.js
191
+ const commentUpdateSchemaKeys = new Set(Object.keys(CommentUpdateSchema.shape));
192
+ function commentUpdateExtraKeys(update) {
193
+ return Object.keys(update).filter((key) => !commentUpdateSchemaKeys.has(key));
194
+ }
195
+ function commentUpdateToDbRow({ update, dbOnlyFields }) {
196
+ const record = { ...update };
197
+ const extraProps = {};
198
+ for (const key of commentUpdateExtraKeys(update)) {
199
+ const value = record[key];
200
+ delete record[key];
201
+ if (value !== void 0) extraProps[key] = value;
202
+ }
203
+ const row = {
204
+ ...record,
205
+ ...dbOnlyFields
206
+ };
207
+ if (Object.keys(extraProps).length > 0) row.extraProps = extraProps;
208
+ return row;
209
+ }
210
+ function spreadCommentUpdateExtraProps(record, extraProps) {
211
+ if (!extraProps || typeof extraProps !== "object") return;
212
+ for (const [key, value] of Object.entries(extraProps)) {
213
+ if (value === null || value === void 0 || commentUpdateSchemaKeys.has(key)) continue;
214
+ record[key] = value;
215
+ }
216
+ }
217
+ //#endregion
190
218
  //#region node_modules/uuid/dist-node/rng.js
191
219
  const rnds8 = new Uint8Array(16);
192
220
  function rng() {
@@ -320,15 +348,15 @@ async function throwIfChallengeSettingsAreInvalid({ challengeSettings, pkc, comm
320
348
  const processStartedCommunities = new TrackedInstanceRegistry();
321
349
  function normalizeRegistryDataPath(dataPath) {
322
350
  if (dataPath === void 0) return void 0;
323
- const resolved = path.resolve(dataPath);
351
+ const resolved = path$1.resolve(dataPath);
324
352
  let existing = resolved;
325
353
  let tail = "";
326
354
  while (true) try {
327
- return path.join(fs$1.realpathSync.native(existing), tail);
355
+ return path$1.join(fs$1.realpathSync.native(existing), tail);
328
356
  } catch {
329
- const parent = path.dirname(existing);
357
+ const parent = path$1.dirname(existing);
330
358
  if (parent === existing) return resolved;
331
- tail = path.join(path.basename(existing), tail);
359
+ tail = path$1.join(path$1.basename(existing), tail);
332
360
  existing = parent;
333
361
  }
334
362
  }
@@ -978,19 +1006,14 @@ async function importCommunitySignerIntoIpfsIfNeeded(community) {
978
1006
  headers: community._pkc.kuboRpcClientsOptions[0].headers
979
1007
  });
980
1008
  }
981
- async function getDbInternalState(community, lock) {
1009
+ function getDbInternalState(community) {
982
1010
  const log = logger_default("pkc-js:local-community:_getDbInternalState");
983
1011
  if (!community._dbHandler.keyvHas(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY])) throw new PKCError("ERR_COMMUNITY_HAS_NO_INTERNAL_STATE", {
984
1012
  address: community.address,
985
1013
  dataPath: community._pkc.dataPath
986
1014
  });
987
- let lockedIt = false;
988
1015
  try {
989
- if (lock) {
990
- await community._dbHandler.lockCommunityState();
991
- lockedIt = true;
992
- }
993
- const internalState = await community._dbHandler.keyvGet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY]);
1016
+ const internalState = community._dbHandler.keyvGet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY]);
994
1017
  if (!internalState) throw new PKCError("ERR_COMMUNITY_HAS_NO_INTERNAL_STATE", {
995
1018
  address: community.address,
996
1019
  dataPath: community._pkc.dataPath
@@ -999,8 +1022,6 @@ async function getDbInternalState(community, lock) {
999
1022
  } catch (e) {
1000
1023
  log.error("Failed to get community", community.address, "internal state from db", e);
1001
1024
  throw e;
1002
- } finally {
1003
- if (lockedIt) await community._dbHandler.unlockCommunityState();
1004
1025
  }
1005
1026
  }
1006
1027
  async function updateDbInternalState(community, propsOrBuildProps) {
@@ -1008,26 +1029,27 @@ async function updateDbInternalState(community, propsOrBuildProps) {
1008
1029
  if (typeof propsOrBuildProps !== "function" && e(propsOrBuildProps)) throw Error("props to update DB internal state should not be empty");
1009
1030
  await community._dbHandler.initDbIfNeeded();
1010
1031
  let props = typeof propsOrBuildProps === "function" ? {} : propsOrBuildProps;
1011
- let lockedIt = false;
1012
1032
  try {
1013
- await community._dbHandler.lockCommunityState();
1014
- lockedIt = true;
1015
- if (typeof propsOrBuildProps === "function") props = propsOrBuildProps();
1016
- props._internalStateUpdateId = v4();
1017
- const internalStateBefore = await community._getDbInternalState(false);
1018
- const propsToStore = "posts" in props && props.posts ? {
1019
- ...props,
1020
- posts: deriveDbPosts({
1021
- posts: props.posts,
1022
- allPageCids: community._postsAllPageCids
1023
- })
1024
- } : props;
1025
- const mergedInternalState = {
1026
- ...internalStateBefore,
1027
- ...propsToStore
1028
- };
1029
- await community._dbHandler.keyvSet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY], mergedInternalState);
1030
- community._internalStateUpdateId = props._internalStateUpdateId;
1033
+ const internalStateUpdateId = v4();
1034
+ const mergedInternalState = community._dbHandler.runInWriteTransaction(() => {
1035
+ if (typeof propsOrBuildProps === "function") props = Object.assign(propsOrBuildProps(), ...community._editsStoredNotApplied);
1036
+ props._internalStateUpdateId = internalStateUpdateId;
1037
+ const internalStateBefore = community._getDbInternalState();
1038
+ const propsToStore = "posts" in props && props.posts ? {
1039
+ ...props,
1040
+ posts: deriveDbPosts({
1041
+ posts: props.posts,
1042
+ allPageCids: community._postsAllPageCids
1043
+ })
1044
+ } : props;
1045
+ const merged = {
1046
+ ...internalStateBefore,
1047
+ ...propsToStore
1048
+ };
1049
+ community._dbHandler.keyvSet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY], merged);
1050
+ return merged;
1051
+ });
1052
+ community._internalStateUpdateId = internalStateUpdateId;
1031
1053
  log.trace("Updated community", community.address, "internal state in db with new props", Object.keys(props));
1032
1054
  if (community.updateCid && community.raw.communityIpfs) community.raw.localCommunity = community.toJSONInternalRpcAfterFirstUpdate();
1033
1055
  else if (community.settings) community.raw.localCommunity = community.toJSONInternalRpcBeforeFirstUpdate();
@@ -1035,12 +1057,10 @@ async function updateDbInternalState(community, propsOrBuildProps) {
1035
1057
  } catch (e) {
1036
1058
  log.error("Failed to update community", community.address, "internal state in db with new props", Object.keys(props), e);
1037
1059
  throw e;
1038
- } finally {
1039
- if (lockedIt) await community._dbHandler.unlockCommunityState();
1040
1060
  }
1041
1061
  }
1042
1062
  async function updateInstanceStateWithDbState(community) {
1043
- const currentDbState = await community._getDbInternalState(false);
1063
+ const currentDbState = community._getDbInternalState();
1044
1064
  if ("updatedAt" in currentDbState) {
1045
1065
  if (currentDbState.posts && !("pages" in currentDbState.posts)) if (community._dbHandler.hasCommentsAndCommentUpdatesTables()) {
1046
1066
  const dbPosts = currentDbState.posts;
@@ -1351,7 +1371,10 @@ const commentIpfsCoercions = collectSchemaRowCoercions({
1351
1371
  ...CommentIpfsSchema.shape,
1352
1372
  extraProps: CommentsTableRowSchema.shape.extraProps
1353
1373
  });
1354
- const commentUpdateCoercions = collectSchemaRowCoercions(CommentUpdateSchema.shape);
1374
+ const commentUpdateCoercions = collectSchemaRowCoercions({
1375
+ ...CommentUpdateSchema.shape,
1376
+ extraProps: CommentUpdateTableRowSchema.shape.extraProps
1377
+ });
1355
1378
  function compileColumns(columns, coercions) {
1356
1379
  return columns.map((key) => ({
1357
1380
  key,
@@ -1394,6 +1417,15 @@ function createPositionalCommentRowMapper(cols) {
1394
1417
  }
1395
1418
  const commentUpdate = {};
1396
1419
  assignColumns(commentUpdate, row, updateOffset, updateColumns, "commentUpdate_");
1420
+ const commentUpdateExtraProps = commentUpdate.extraProps;
1421
+ if (commentUpdateExtraProps !== void 0) {
1422
+ delete commentUpdate.extraProps;
1423
+ spreadCommentUpdateExtraProps(commentUpdate, commentUpdateExtraProps);
1424
+ return {
1425
+ comment,
1426
+ commentUpdate: withSortedKeys(commentUpdate)
1427
+ };
1428
+ }
1397
1429
  return {
1398
1430
  comment,
1399
1431
  commentUpdate
@@ -1403,7 +1435,6 @@ function createPositionalCommentRowMapper(cols) {
1403
1435
  }
1404
1436
  //#endregion
1405
1437
  //#region dist/node/runtime/node/community/db-handler.js
1406
- var import_src = /* @__PURE__ */ __toESM(require_src(), 1);
1407
1438
  const createCommunityAuthorMemo = () => ({
1408
1439
  writeGeneration: -1,
1409
1440
  authors: /* @__PURE__ */ new Map(),
@@ -1429,7 +1460,7 @@ var DbHandler = class {
1429
1460
  constructor(community) {
1430
1461
  this._transactionGeneration = 0;
1431
1462
  this._publicationWriteGeneration = 0;
1432
- this._heldStartLock = void 0;
1463
+ this._startLockAddress = void 0;
1433
1464
  this._community = community;
1434
1465
  this._transactionDepth = 0;
1435
1466
  this._createdTables = false;
@@ -1498,7 +1529,7 @@ var DbHandler = class {
1498
1529
  } catch (e) {
1499
1530
  await this.initDbIfNeeded();
1500
1531
  log.error(`Community (${this._community.address}) failed to create/migrate tables. Current db version (${this.getDbVersion()}), latest db version (${version_default.DB_VERSION}). Error`, e);
1501
- await this.destoryConnection();
1532
+ if (this._startLockAddress === void 0) this.destoryConnection();
1502
1533
  throw e;
1503
1534
  }
1504
1535
  hideClassPrivateProps(this);
@@ -1528,6 +1559,13 @@ var DbHandler = class {
1528
1559
  }
1529
1560
  destoryConnection() {
1530
1561
  const log = logger_default("pkc-js:local-community:dbHandler:destroyConnection");
1562
+ if (this.holdsStartLock()) {
1563
+ const error = /* @__PURE__ */ new Error(`Refused to close the DB connection of community (${this._startLockAddress}) while it holds the community's start lock (issue #561)`);
1564
+ log.error(error);
1565
+ if (process.env["VITEST"]) throw error;
1566
+ return;
1567
+ }
1568
+ this._startLockAddress = void 0;
1531
1569
  this._preparedStatements.clear();
1532
1570
  if (this._db && this._db.open) try {
1533
1571
  if (!this._db.readonly) this._db.exec("PRAGMA wal_checkpoint");
@@ -1669,7 +1707,8 @@ var DbHandler = class {
1669
1707
  lastReplyTimestamp INTEGER NULLABLE,
1670
1708
  postUpdatesBucket INTEGER NULLABLE,
1671
1709
  publishedToPostUpdatesMFS INTEGER NOT NULL, -- BOOLEAN (0/1)
1672
- insertedAt INTEGER NOT NULL
1710
+ insertedAt INTEGER NOT NULL,
1711
+ extraProps TEXT NULLABLE -- JSON: unknown keys of the signed record (issue #572); a snapshot, this table is rebuilt on every DB_VERSION bump
1673
1712
  )
1674
1713
  `);
1675
1714
  }
@@ -1795,15 +1834,10 @@ var DbHandler = class {
1795
1834
  const dbExistsAlready = fs$1.existsSync(dbPath);
1796
1835
  if (needToMigrate) {
1797
1836
  if (dbExistsAlready && currentDbVersion > 0) {
1798
- this.destoryConnection();
1799
- backupDbPath = path.join(path.dirname(dbPath), ".backup_before_migration", `${path.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
1800
- log(`Copying db ${path.basename(dbPath)} to ${backupDbPath} before migration`);
1801
- if (!fs$1.existsSync(path.dirname(backupDbPath))) await fs$1.promises.mkdir(path.dirname(backupDbPath), { recursive: true });
1802
- const sourceDb = new Database(dbPath, { fileMustExist: true });
1803
- await sourceDb.backup(backupDbPath);
1804
- sourceDb.close();
1805
- this._db = new Database(dbPath);
1806
- this._db.pragma("journal_mode = WAL");
1837
+ backupDbPath = path$1.join(path$1.dirname(dbPath), ".backup_before_migration", `${path$1.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
1838
+ log(`Copying db ${path$1.basename(dbPath)} to ${backupDbPath} before migration`);
1839
+ if (!fs$1.existsSync(path$1.dirname(backupDbPath))) await fs$1.promises.mkdir(path$1.dirname(backupDbPath), { recursive: true });
1840
+ await this._db.backup(backupDbPath);
1807
1841
  }
1808
1842
  this._db.exec("PRAGMA foreign_keys = OFF");
1809
1843
  for (const tableName of [
@@ -2248,8 +2282,8 @@ var DbHandler = class {
2248
2282
  const columnNames = this._getColumnNames(TABLES.COMMENT_UPDATES);
2249
2283
  const stmt = this._prepareCached(`
2250
2284
  INSERT INTO ${TABLES.COMMENT_UPDATES}
2251
- (cid, edit, upvoteCount, downvoteCount, replyCount, childCount, number, postNumber, flairs, spoiler, nsfw, pinned, locked, archived, removed, approved, reason, updatedAt, protocolVersion, signature, author, replies, lastChildCid, lastReplyTimestamp, postUpdatesBucket, publishedToPostUpdatesMFS, insertedAt)
2252
- VALUES (@cid, @edit, @upvoteCount, @downvoteCount, @replyCount, @childCount, @number, @postNumber, @flairs, @spoiler, @nsfw, @pinned, @locked, @archived, @removed, @approved, @reason, @updatedAt, @protocolVersion, @signature, @author, @replies, @lastChildCid, @lastReplyTimestamp, @postUpdatesBucket, @publishedToPostUpdatesMFS, @insertedAt)
2285
+ (cid, edit, upvoteCount, downvoteCount, replyCount, childCount, number, postNumber, flairs, spoiler, nsfw, pinned, locked, archived, removed, approved, reason, updatedAt, protocolVersion, signature, author, replies, lastChildCid, lastReplyTimestamp, postUpdatesBucket, publishedToPostUpdatesMFS, insertedAt, extraProps)
2286
+ VALUES (@cid, @edit, @upvoteCount, @downvoteCount, @replyCount, @childCount, @number, @postNumber, @flairs, @spoiler, @nsfw, @pinned, @locked, @archived, @removed, @approved, @reason, @updatedAt, @protocolVersion, @signature, @author, @replies, @lastChildCid, @lastReplyTimestamp, @postUpdatesBucket, @publishedToPostUpdatesMFS, @insertedAt, @extraProps)
2253
2287
  ON CONFLICT(cid) DO UPDATE SET
2254
2288
  edit = excluded.edit, upvoteCount = excluded.upvoteCount, downvoteCount = excluded.downvoteCount, replyCount = excluded.replyCount, childCount = excluded.childCount,
2255
2289
  number = COALESCE(excluded.number, ${TABLES.COMMENT_UPDATES}.number),
@@ -2259,7 +2293,8 @@ var DbHandler = class {
2259
2293
  signature = excluded.signature, author = excluded.author, replies = excluded.replies, lastChildCid = excluded.lastChildCid,
2260
2294
  lastReplyTimestamp = excluded.lastReplyTimestamp, postUpdatesBucket = excluded.postUpdatesBucket,
2261
2295
  publishedToPostUpdatesMFS = excluded.publishedToPostUpdatesMFS,
2262
- insertedAt = excluded.insertedAt
2296
+ insertedAt = excluded.insertedAt,
2297
+ extraProps = excluded.extraProps
2263
2298
  `);
2264
2299
  const defaults = t$5(columnNames, (column) => [column, null]);
2265
2300
  this._db.transaction((items) => {
@@ -2385,7 +2420,7 @@ var DbHandler = class {
2385
2420
  };
2386
2421
  }
2387
2422
  _pageEntryMapper(commentUpdateFieldsToExclude, existingOnly = false) {
2388
- const commentUpdateCols = t$6(commentUpdateFieldsToExclude ? n$2(CommentUpdateSchema.shape, commentUpdateFieldsToExclude) : CommentUpdateSchema.shape);
2423
+ const commentUpdateCols = [...t$6(commentUpdateFieldsToExclude ? n$2(CommentUpdateSchema.shape, commentUpdateFieldsToExclude) : CommentUpdateSchema.shape), "extraProps"];
2389
2424
  const commentIpfsCols = [...t$6(CommentIpfsSchema.shape), "extraProps"];
2390
2425
  return this._positionalMapperFor({
2391
2426
  commentIpfsCols: existingOnly ? this._existingColumns(TABLES.COMMENTS, commentIpfsCols) : commentIpfsCols,
@@ -3869,10 +3904,10 @@ var DbHandler = class {
3869
3904
  if (this._db || this._keyv) await this.destoryConnection();
3870
3905
  this._transactionDepth = 0;
3871
3906
  const dataPath = this._community._pkc.dataPath;
3872
- const oldPathString = path.join(dataPath, "communities", oldDbName);
3873
- const newPathString = path.join(dataPath, "communities", newDbName);
3874
- await fs$1.promises.mkdir(path.dirname(oldPathString), { recursive: true });
3875
- await fs$1.promises.mkdir(path.dirname(newPathString), { recursive: true });
3907
+ const oldPathString = path$1.join(dataPath, "communities", oldDbName);
3908
+ const newPathString = path$1.join(dataPath, "communities", newDbName);
3909
+ await fs$1.promises.mkdir(path$1.dirname(oldPathString), { recursive: true });
3910
+ await fs$1.promises.mkdir(path$1.dirname(newPathString), { recursive: true });
3876
3911
  try {
3877
3912
  if (!fs$1.existsSync(oldPathString)) log(`Old DB file ${oldPathString} does not exist. Cannot backup/rename.`);
3878
3913
  else {
@@ -3885,6 +3920,10 @@ var DbHandler = class {
3885
3920
  });
3886
3921
  if (os.type() === "Windows_NT") await deleteOldCommunityInWindows(oldPathString, this._community._pkc);
3887
3922
  else await fs$1.promises.rm(oldPathString, { force: true });
3923
+ if (!fs$1.existsSync(oldPathString)) await fs$1.promises.rm(getStartLockPath({
3924
+ dataPath,
3925
+ communityAddress: oldDbName
3926
+ }), { force: true });
3888
3927
  }
3889
3928
  } catch (error) {
3890
3929
  log.error(`Failed to backup/rename database from ${oldPathString} to ${newPathString}: `, error);
@@ -3896,49 +3935,53 @@ var DbHandler = class {
3896
3935
  };
3897
3936
  log(`Changed db path from (${oldPathString}) to (${newPathString})`);
3898
3937
  }
3899
- async lockCommunityStart({ onCompromised }) {
3938
+ async lockCommunityStart() {
3900
3939
  const log = logger_default("pkc-js:local-community:db-handler:lock:start");
3901
3940
  const communityAddress = this._community.address;
3902
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3903
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3904
- const startLock = {};
3905
- try {
3906
- await import_src.default.lock(communityDbPath, {
3907
- lockfilePath,
3908
- onCompromised: (error) => {
3909
- if (this._heldStartLock !== startLock) return;
3910
- this._heldStartLock = void 0;
3911
- log.error(`Lost the start lock of community (${communityAddress}), taken over or removed`, error);
3912
- onCompromised(error);
3913
- }
3941
+ const dataPath = this._community._pkc.dataPath;
3942
+ await this.initDbIfNeeded();
3943
+ await fs$1.promises.rm(path$1.join(dataPath, "communities", `${communityAddress}.start.lock`), {
3944
+ recursive: true,
3945
+ force: true
3946
+ });
3947
+ if (!takeStartLock({
3948
+ db: this._db,
3949
+ dataPath,
3950
+ communityAddress
3951
+ })) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { communityAddress });
3952
+ if (!fs$1.existsSync(path$1.join(dataPath, "communities", communityAddress))) {
3953
+ releaseStartLock({
3954
+ db: this._db,
3955
+ dataPath,
3956
+ communityAddress
3914
3957
  });
3915
- this._heldStartLock = startLock;
3916
- log(`Locked the start of community (${communityAddress}) successfully`);
3917
- } catch (e) {
3918
- if (e instanceof Error && e.message === "Lock file is already being held") throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", {
3958
+ fs$1.rmSync(getStartLockPath({
3959
+ dataPath,
3960
+ communityAddress
3961
+ }), { force: true });
3962
+ throw new PKCError("CAN_NOT_LOAD_LOCAL_COMMUNITY_IF_DB_DOES_NOT_EXIST", {
3919
3963
  communityAddress,
3920
- error: e
3964
+ dataPath
3921
3965
  });
3922
- else {
3923
- log(`Error while trying to lock start of community (${communityAddress}): ${e}`);
3924
- throw e;
3925
- }
3926
3966
  }
3967
+ this._startLockAddress = communityAddress;
3968
+ log(`Locked the start of community (${communityAddress}) successfully`);
3927
3969
  }
3928
- async unlockCommunityStart(communityAddress = this._community.address) {
3970
+ holdsStartLock() {
3971
+ return this._startLockAddress !== void 0 && this._db?.open === true;
3972
+ }
3973
+ async unlockCommunityStart() {
3929
3974
  const log = logger_default("pkc-js:local-community:db-handler:unlock:start");
3930
- log.trace(`Attempting to unlock the start of community (${communityAddress})`);
3931
- this._heldStartLock = void 0;
3932
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3933
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3934
- if (!fs$1.existsSync(lockfilePath) || !fs$1.existsSync(communityDbPath)) return;
3935
- try {
3936
- await import_src.default.unlock(communityDbPath, { lockfilePath });
3937
- log(`Unlocked start of community (${communityAddress})`);
3938
- } catch (e) {
3939
- log(`Error while trying to unlock start of community (${communityAddress}): ${e}`);
3940
- throw e;
3941
- }
3975
+ const communityAddress = this._startLockAddress;
3976
+ if (communityAddress === void 0) return;
3977
+ this._startLockAddress = void 0;
3978
+ if (!this._db?.open) return;
3979
+ releaseStartLock({
3980
+ db: this._db,
3981
+ dataPath: this._community._pkc.dataPath,
3982
+ communityAddress
3983
+ });
3984
+ log(`Unlocked start of community (${communityAddress})`);
3942
3985
  }
3943
3986
  async isCommunityStartLocked(communityAddress = this._community.address) {
3944
3987
  return isCommunityStartLocked({
@@ -3946,38 +3989,28 @@ var DbHandler = class {
3946
3989
  communityAddress
3947
3990
  });
3948
3991
  }
3949
- async lockCommunityState() {
3950
- const log = logger_default("pkc-js:local-community:db-handler:lock:lockCommunityState");
3951
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3952
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
3992
+ runInWriteTransaction(write) {
3993
+ if (this._db.inTransaction) return write();
3953
3994
  try {
3954
- await import_src.default.lock(communityDbPath, {
3955
- lockfilePath,
3956
- retries: 5,
3957
- onCompromised: () => {}
3958
- });
3995
+ this._db.exec("BEGIN IMMEDIATE");
3959
3996
  } catch (e) {
3960
- log.error(`Error when attempting to lock community state`, this._community.address, e);
3961
- if (e instanceof Error && e.message === "Lock file is already being held") throw new PKCError("ERR_COMMUNITY_STATE_LOCKED", {
3997
+ if (typeof e.code === "string" && e.code.startsWith("SQLITE_BUSY")) throw new PKCError("ERR_COMMUNITY_STATE_LOCKED", {
3962
3998
  communityAddress: this._community.address,
3963
3999
  error: e
3964
4000
  });
4001
+ throw e;
3965
4002
  }
3966
- }
3967
- async unlockCommunityState() {
3968
- const log = logger_default("pkc-js:local-community:db-handler:lock:unlockCommunityState");
3969
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3970
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
3971
- if (!fs$1.existsSync(lockfilePath)) return;
3972
4003
  try {
3973
- await import_src.default.unlock(communityDbPath, { lockfilePath });
4004
+ const result = write();
4005
+ this._db.exec("COMMIT");
4006
+ return result;
3974
4007
  } catch (e) {
3975
- log.error(`Error when attempting to unlock community state`, this._community.address, e);
3976
- if (e instanceof Error && "code" in e && e.code !== "ENOTACQUIRED") throw e;
4008
+ if (this._db.inTransaction) this._db.exec("ROLLBACK");
4009
+ throw e;
3977
4010
  }
3978
4011
  }
3979
4012
  communityDbExists() {
3980
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
4013
+ const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
3981
4014
  return fs$1.existsSync(communityDbPath);
3982
4015
  }
3983
4016
  markCommentsAsPublishedToPostUpdates(commentCids) {
@@ -4655,17 +4688,19 @@ async function calculateNewCommentUpdate(opts) {
4655
4688
  }
4656
4689
  return {
4657
4690
  newCommentUpdate,
4658
- newCommentUpdateToWriteToDb: {
4659
- ...newCommentUpdate,
4660
- replies: deriveDbReplies({
4661
- replies: newCommentUpdate.replies,
4662
- allPageCids,
4663
- flatSortNames: generatedRepliesPages?.flatSortNames
4664
- }),
4665
- postUpdatesBucket: newPostUpdateBucket,
4666
- publishedToPostUpdatesMFS: false,
4667
- insertedAt: batchStartTimestamp
4668
- },
4691
+ newCommentUpdateToWriteToDb: commentUpdateToDbRow({
4692
+ update: newCommentUpdate,
4693
+ dbOnlyFields: {
4694
+ replies: deriveDbReplies({
4695
+ replies: newCommentUpdate.replies,
4696
+ allPageCids,
4697
+ flatSortNames: generatedRepliesPages?.flatSortNames
4698
+ }),
4699
+ postUpdatesBucket: newPostUpdateBucket,
4700
+ publishedToPostUpdatesMFS: false,
4701
+ insertedAt: batchStartTimestamp
4702
+ }
4703
+ }),
4669
4704
  localMfsPath: newLocalMfsPath,
4670
4705
  pendingApproval: comment.pendingApproval
4671
4706
  };
@@ -4924,8 +4959,49 @@ async function repinCommentUpdateIfNeeded(community) {
4924
4959
  community._dbHandler.forceUpdateOnAllComments();
4925
4960
  }
4926
4961
  const MIN_MS_BETWEEN_GC = 3600 * 1e3;
4927
- const lastGcFinishedAtByKuboUrl = /* @__PURE__ */ new Map();
4962
+ const intervalStartedAtByKuboUrl = /* @__PURE__ */ new Map();
4928
4963
  const inFlightGcByKuboUrl = /* @__PURE__ */ new Map();
4964
+ const gcIntervalStorageKey = (kuboUrl) => `repoGcIntervalStartedAt:${kuboUrl}`;
4965
+ async function _readStoredGcIntervalStart({ community, kuboUrl, log }) {
4966
+ try {
4967
+ const stored = await community._pkc._storage.getItem(gcIntervalStorageKey(kuboUrl));
4968
+ return typeof stored === "number" ? stored : void 0;
4969
+ } catch (e) {
4970
+ log.error("Failed to read when the GC interval of the kubo node", kuboUrl, "started", e);
4971
+ return;
4972
+ }
4973
+ }
4974
+ async function _startGcInterval({ community, kuboUrl, log }) {
4975
+ const now = Date.now();
4976
+ intervalStartedAtByKuboUrl.set(kuboUrl, now);
4977
+ try {
4978
+ await community._pkc._storage.setItem(gcIntervalStorageKey(kuboUrl), now);
4979
+ } catch (e) {
4980
+ log.error("Failed to store when the GC interval of the kubo node", kuboUrl, "started", e);
4981
+ }
4982
+ }
4983
+ async function _isRepoGcDue({ community, kuboUrl, log }) {
4984
+ const isRunning = (startedAt) => typeof startedAt === "number" && startedAt <= Date.now() && Date.now() - startedAt < MIN_MS_BETWEEN_GC;
4985
+ const inMemory = intervalStartedAtByKuboUrl.get(kuboUrl);
4986
+ if (isRunning(inMemory)) return false;
4987
+ const stored = await _readStoredGcIntervalStart({
4988
+ community,
4989
+ kuboUrl,
4990
+ log
4991
+ });
4992
+ const startedAt = typeof stored === "number" && typeof inMemory === "number" ? Math.max(stored, inMemory) : stored ?? inMemory;
4993
+ if (isRunning(startedAt)) {
4994
+ intervalStartedAtByKuboUrl.set(kuboUrl, startedAt);
4995
+ return false;
4996
+ }
4997
+ if (typeof startedAt === "number" && startedAt <= Date.now()) return true;
4998
+ await _startGcInterval({
4999
+ community,
5000
+ kuboUrl,
5001
+ log
5002
+ });
5003
+ return false;
5004
+ }
4929
5005
  async function cleanUpIpfsRepoIfDue(community, force = false) {
4930
5006
  const log = logger_default("pkc-js:local-community:syncIpnsWithDb:_cleanUpIpfsRepoIfDue");
4931
5007
  const kuboRpc = community._clientsManager.getDefaultKuboRpcClient();
@@ -4971,10 +5047,11 @@ function _describeReclaimedSpace({ before, after }) {
4971
5047
  }
4972
5048
  async function _runRepoGcIfDue({ community, kuboUrl, force, log }) {
4973
5049
  const kuboRpc = community._clientsManager.getDefaultKuboRpcClient();
4974
- if (!force) {
4975
- const lastGcFinishedAt = lastGcFinishedAtByKuboUrl.get(kuboUrl);
4976
- if (typeof lastGcFinishedAt === "number" && Date.now() - lastGcFinishedAt < MIN_MS_BETWEEN_GC) return;
4977
- }
5050
+ if (!force && !await _isRepoGcDue({
5051
+ community,
5052
+ kuboUrl,
5053
+ log
5054
+ })) return;
4978
5055
  const repoSizeBefore = await _readRepoSizeSafely({
4979
5056
  kuboRpc,
4980
5057
  kuboUrl,
@@ -4988,7 +5065,11 @@ async function _runRepoGcIfDue({ community, kuboUrl, force, log }) {
4988
5065
  log.error("Failed to GC ipfs repo due to error", e);
4989
5066
  return;
4990
5067
  } finally {
4991
- lastGcFinishedAtByKuboUrl.set(kuboUrl, Date.now());
5068
+ await _startGcInterval({
5069
+ community,
5070
+ kuboUrl,
5071
+ log
5072
+ });
4992
5073
  }
4993
5074
  const repoSizeAfter = await _readRepoSizeSafely({
4994
5075
  kuboRpc,
@@ -6918,7 +6999,7 @@ async function publishLoop(community, syncIntervalMs) {
6918
6999
  const log = logger_default("pkc-js:local-community:_publishLoop");
6919
7000
  let syncFailedSinceStop = false;
6920
7001
  const shouldStopPublishLoop = () => {
6921
- return community.state !== "started" || community._startLockLost || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
7002
+ return community.state !== "started" || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
6922
7003
  };
6923
7004
  const waitUntilNextSync = async ({ lastSyncFailed }) => {
6924
7005
  const doneWithLoopTime = Date.now();
@@ -7012,6 +7093,7 @@ async function runAsStartOrUpdateInFlight({ community, setUp }) {
7012
7093
  async function start(community) {
7013
7094
  if (community.state === "updating") throw new PKCError("ERR_NEED_TO_STOP_UPDATING_COMMUNITY_BEFORE_STARTING", { address: community.address });
7014
7095
  if (community.state === "started" || community._startOrUpdateInFlight) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
7096
+ if (community._deleteInFlight) throw new PKCError("ERR_COMMUNITY_IS_BEING_DELETED", { address: community.address });
7015
7097
  await runAsStartOrUpdateInFlight({
7016
7098
  community,
7017
7099
  setUp: (releaseMark) => startCommunity({
@@ -7022,6 +7104,7 @@ async function start(community) {
7022
7104
  }
7023
7105
  async function startCommunity({ community, releaseMark }) {
7024
7106
  const log = logger_default("pkc-js:local-community:start");
7107
+ while (community._stoppedEditsInFlight.size > 0) await Promise.allSettled([...community._stoppedEditsInFlight]);
7025
7108
  community._stopHasBeenCalled = false;
7026
7109
  community._lastProvidedBrowserDialableSelfAddrs = void 0;
7027
7110
  community._lastAddressReprovideCheckAt = void 0;
@@ -7032,9 +7115,6 @@ async function startCommunity({ community, releaseMark }) {
7032
7115
  publicKey: community.publicKey,
7033
7116
  name: community.name
7034
7117
  }) || findProcessStartedCommunity(community)) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
7035
- community._startLockLost = false;
7036
- let startLockLostDuringStart;
7037
- let startFinished = false;
7038
7118
  try {
7039
7119
  await initBeforeStarting(community);
7040
7120
  if (community.anchor && !getPersistedAnchorRecordBytes(community)) throw new PKCError("ERR_DELEGATED_COMMUNITY_HAS_NO_ANCHOR_RECORD", {
@@ -7047,15 +7127,7 @@ async function startCommunity({ community, releaseMark }) {
7047
7127
  pkc: community._pkc,
7048
7128
  communityAddress: community.address
7049
7129
  });
7050
- await community._dbHandler.lockCommunityStart({ onCompromised: (error) => {
7051
- community._startLockLost = true;
7052
- const lostLockError = new PKCError("ERR_COMMUNITY_START_LOCK_COMPROMISED", {
7053
- communityAddress: community.address,
7054
- error
7055
- });
7056
- if (startFinished) stopAfterLosingStartLock(community, lostLockError);
7057
- else startLockLostDuringStart = lostLockError;
7058
- } });
7130
+ await community._dbHandler.lockCommunityStart();
7059
7131
  community._setState("started");
7060
7132
  await community._updateStartedValue();
7061
7133
  trackStartedCommunity(community._pkc, community);
@@ -7078,14 +7150,11 @@ async function startCommunity({ community, releaseMark }) {
7078
7150
  community._setStartedStateWithEmission("publishing-ipns");
7079
7151
  await community._repinCommentsIPFSIfNeeded();
7080
7152
  await repinCommentUpdateIfNeeded(community);
7081
- if (startLockLostDuringStart) throw startLockLostDuringStart;
7082
7153
  await community._listenToIncomingRequests();
7083
7154
  await emitChallengeSettingsValidationErrors(community, log);
7084
7155
  community._pageSorts = void 0;
7085
7156
  community._pageSortFactories = void 0;
7086
7157
  await syncPageSortsWithRegistry(community);
7087
- if (startLockLostDuringStart) throw startLockLostDuringStart;
7088
- startFinished = true;
7089
7158
  } catch (e) {
7090
7159
  releaseMark();
7091
7160
  await community.stop();
@@ -7101,12 +7170,6 @@ async function startCommunity({ community, releaseMark }) {
7101
7170
  community.emit("error", err);
7102
7171
  });
7103
7172
  }
7104
- function stopAfterLosingStartLock(community, error) {
7105
- const log = logger_default("pkc-js:local-community:stopAfterLosingStartLock");
7106
- if (community.state !== "started") return;
7107
- if (!community._stopHasBeenCalled) community.stop().catch((e) => log.error(`Failed to stop community (${community.address}) after losing its start lock`, e));
7108
- community.emit("error", error);
7109
- }
7110
7173
  async function initMirroringStartedOrUpdatingCommunity(community, startedCommunity) {
7111
7174
  const updatingStateChangeListener = (newState) => {
7112
7175
  community._setUpdatingStateWithEventEmissionIfNewState(newState);
@@ -7275,23 +7338,20 @@ async function stopCommunity(community) {
7275
7338
  }
7276
7339
  community._publishLoopPromise = void 0;
7277
7340
  }
7278
- if (community._startLockLost) log(`Community (${community.address}) lost its start lock, stopping without writing its state, unpinning or unlocking`);
7279
- else {
7280
- try {
7281
- await unpinStaleCids(community, { bypassGracePeriod: true });
7282
- } catch (e) {
7283
- log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
7284
- }
7285
- try {
7286
- await updateDbInternalState(community, () => community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
7287
- } catch (e) {
7288
- log.error("Failed to update db internal state before stopping", e);
7289
- }
7290
- try {
7291
- await community._dbHandler.unlockCommunityStart();
7292
- } catch (e) {
7293
- log.error(`Failed to unlock start lock on community (${community.address})`, e);
7294
- }
7341
+ try {
7342
+ await unpinStaleCids(community, { bypassGracePeriod: true });
7343
+ } catch (e) {
7344
+ log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
7345
+ }
7346
+ try {
7347
+ await updateDbInternalState(community, () => community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
7348
+ } catch (e) {
7349
+ log.error("Failed to update db internal state before stopping", e);
7350
+ }
7351
+ try {
7352
+ await community._dbHandler.unlockCommunityStart();
7353
+ } catch (e) {
7354
+ log.error(`Failed to unlock start lock on community (${community.address})`, e);
7295
7355
  }
7296
7356
  const kuboRpcClient = community._clientsManager.getDefaultKuboRpcClient();
7297
7357
  community._setStartedStateWithEmission("stopped");
@@ -7300,7 +7360,6 @@ async function stopCommunity(community) {
7300
7360
  community._duplicatePublicationAttempts?.clear();
7301
7361
  community._inFlightPublicationExchanges.clear();
7302
7362
  await community._dbHandler.rollbackAllTransactions();
7303
- await community._dbHandler.unlockCommunityState();
7304
7363
  await community._updateStartedValue();
7305
7364
  community._clientsManager.updateKuboRpcState("stopped", kuboRpcClient.url);
7306
7365
  community._clientsManager.updateKuboRpcPubsubStateIfProviderExists("stopped");
@@ -7326,7 +7385,19 @@ async function stopCommunity(community) {
7326
7385
  }
7327
7386
  const DELETE_UNPIN_SLICE_SIZE = 5e3;
7328
7387
  async function deleteCommunity(community) {
7388
+ let settle;
7389
+ const inFlight = new Promise((resolve) => settle = resolve);
7390
+ community._deleteInFlight = inFlight;
7391
+ try {
7392
+ await deleteCommunityWhileMarked(community);
7393
+ } finally {
7394
+ if (community._deleteInFlight === inFlight) community._deleteInFlight = void 0;
7395
+ settle();
7396
+ }
7397
+ }
7398
+ async function deleteCommunityWhileMarked(community) {
7329
7399
  const log = logger_default("pkc-js:local-community:delete");
7400
+ while (community._startOrUpdateInFlight) await community._startOrUpdateInFlight;
7330
7401
  log.trace(`Attempting to stop the community (${community.address}) before deleting, if needed`);
7331
7402
  const startedCommunity = findStartedCommunity(community._pkc, {
7332
7403
  publicKey: community.publicKey,
@@ -7539,9 +7610,9 @@ async function restartCommunityAfterFailedRename({ community, oldAddress, newAdd
7539
7610
  }
7540
7611
  }
7541
7612
  async function removePartialDbCopy({ community, oldAddress, newAddress, log }) {
7542
- const communitiesPath = Path.join(community._pkc.dataPath, "communities");
7543
- const partialDbCopyPath = Path.join(communitiesPath, newAddress);
7544
- if (!fs.existsSync(Path.join(communitiesPath, oldAddress))) return {
7613
+ const communitiesPath = path.join(community._pkc.dataPath, "communities");
7614
+ const partialDbCopyPath = path.join(communitiesPath, newAddress);
7615
+ if (!fs.existsSync(path.join(communitiesPath, oldAddress))) return {
7545
7616
  removed: false,
7546
7617
  path: partialDbCopyPath
7547
7618
  };
@@ -7558,7 +7629,7 @@ async function removePartialDbCopy({ community, oldAddress, newAddress, log }) {
7558
7629
  }
7559
7630
  }
7560
7631
  async function undoRenameAfterDbRenameFailed({ community, oldAddress, newAddress, dbRenameError, log }) {
7561
- const communitiesPath = Path.join(community._pkc.dataPath, "communities");
7632
+ const communitiesPath = path.join(community._pkc.dataPath, "communities");
7562
7633
  const partialDbCopy = await removePartialDbCopy({
7563
7634
  community,
7564
7635
  oldAddress,
@@ -7576,8 +7647,8 @@ async function undoRenameAfterDbRenameFailed({ community, oldAddress, newAddress
7576
7647
  error: new PKCError("ERR_FAILED_TO_RENAME_COMMUNITY_DB", {
7577
7648
  oldAddress,
7578
7649
  newAddress,
7579
- oldDbPath: Path.join(communitiesPath, oldAddress),
7580
- newDbPath: Path.join(communitiesPath, newAddress),
7650
+ oldDbPath: path.join(communitiesPath, oldAddress),
7651
+ newDbPath: path.join(communitiesPath, newAddress),
7581
7652
  error: dbRenameError,
7582
7653
  errorMessage: renameError?.message,
7583
7654
  errorName: renameError?.name,
@@ -7597,6 +7668,7 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7597
7668
  const log = logger_default("pkc-js:local-community:start:editPropsOnStartedCommunity");
7598
7669
  const oldAddress = t$9(community.address);
7599
7670
  const uniqueEditId = (0, import_sha256.sha256)(stringify(parsedEditOptions));
7671
+ let storedEdit;
7600
7672
  if (typeof parsedEditOptions.address === "string" && community.address !== parsedEditOptions.address) {
7601
7673
  const newAddress = parsedEditOptions.address;
7602
7674
  await validateNewAddressBeforeEditing(community, newAddress, log);
@@ -7647,10 +7719,18 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7647
7719
  await community.start();
7648
7720
  } else {
7649
7721
  if (!e(parsedEditOptions)) {
7650
- const store = updateDbInternalState(community, { ...parsedEditOptions });
7722
+ const editToStore = { ...parsedEditOptions };
7723
+ const store = updateDbInternalState(community, () => {
7724
+ community._editsStoredNotApplied.add(editToStore);
7725
+ return { ...parsedEditOptions };
7726
+ });
7727
+ storedEdit = editToStore;
7651
7728
  community._editStoresInFlight.add(store);
7652
7729
  try {
7653
7730
  await store;
7731
+ } catch (e) {
7732
+ community._editsStoredNotApplied.delete(editToStore);
7733
+ throw e;
7654
7734
  } finally {
7655
7735
  community._editStoresInFlight.delete(store);
7656
7736
  }
@@ -7660,16 +7740,20 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7660
7740
  editId: uniqueEditId
7661
7741
  });
7662
7742
  }
7663
- if (community.updateCid) await community.initInternalCommunityAfterFirstUpdateNoMerge({
7664
- ...community.toJSONInternalAfterFirstUpdate(),
7665
- ...parsedEditOptions,
7666
- _internalStateUpdateId: uniqueEditId
7667
- });
7668
- else await community.initInternalCommunityBeforeFirstUpdateNoMerge({
7669
- ...community.toJSONInternalBeforeFirstUpdate(),
7670
- ...parsedEditOptions,
7671
- _internalStateUpdateId: uniqueEditId
7672
- });
7743
+ try {
7744
+ if (community.updateCid) await community.initInternalCommunityAfterFirstUpdateNoMerge({
7745
+ ...community.toJSONInternalAfterFirstUpdate(),
7746
+ ...parsedEditOptions,
7747
+ _internalStateUpdateId: uniqueEditId
7748
+ });
7749
+ else await community.initInternalCommunityBeforeFirstUpdateNoMerge({
7750
+ ...community.toJSONInternalBeforeFirstUpdate(),
7751
+ ...parsedEditOptions,
7752
+ _internalStateUpdateId: uniqueEditId
7753
+ });
7754
+ } finally {
7755
+ if (storedEdit) community._editsStoredNotApplied.delete(storedEdit);
7756
+ }
7673
7757
  await applyPagesEdit(community, pagesEdit);
7674
7758
  community._communityUpdateTrigger = true;
7675
7759
  log(`Community (${community.address}) props (${t$6(parsedEditOptions)}) has been edited. Will be including edited props in next update: `, t$10(community, t$6(parsedEditOptions)));
@@ -7681,6 +7765,17 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7681
7765
  return community;
7682
7766
  }
7683
7767
  async function editPropsOnNotStartedCommunity(community, parsedEditOptions, pagesEdit) {
7768
+ let settle;
7769
+ const inFlight = new Promise((resolve) => settle = resolve);
7770
+ community._stoppedEditsInFlight.add(inFlight);
7771
+ try {
7772
+ return await editPropsOnNotStartedCommunityWhileMarked(community, parsedEditOptions, pagesEdit);
7773
+ } finally {
7774
+ community._stoppedEditsInFlight.delete(inFlight);
7775
+ settle();
7776
+ }
7777
+ }
7778
+ async function editPropsOnNotStartedCommunityWhileMarked(community, parsedEditOptions, pagesEdit) {
7684
7779
  const log = logger_default("pkc-js:local-community:edit:editPropsOnNotStartedCommunity");
7685
7780
  const oldAddress = t$9(community.address);
7686
7781
  await community.initDbHandlerIfNeeded();
@@ -7711,12 +7806,13 @@ async function editPropsOnNotStartedCommunity(community, parsedEditOptions, page
7711
7806
  if ("updatedAt" in mergedInternalState && mergedInternalState.updatedAt) await community.initInternalCommunityAfterFirstUpdateNoMerge(mergedInternalState);
7712
7807
  else await community.initInternalCommunityBeforeFirstUpdateNoMerge(mergedInternalState);
7713
7808
  await applyPagesEdit(community, pagesEdit);
7714
- await community._dbHandler.destoryConnection();
7809
+ community._dbHandler.destoryConnection();
7715
7810
  community.emit("update", community);
7716
7811
  return community;
7717
7812
  }
7813
+ const isStartInFlight = (community) => community.state === "stopped" && community._startOrUpdateInFlight !== void 0;
7718
7814
  async function edit(community, newCommunityOptions) {
7719
- while (community._stopInFlight) await community._stopInFlight;
7815
+ while (community._stopInFlight || isStartInFlight(community)) await (community._stopInFlight ?? community._startOrUpdateInFlight);
7720
7816
  const startedCommunity = findStartedCommunity(community._pkc, {
7721
7817
  publicKey: community.publicKey,
7722
7818
  name: community.name
@@ -7729,6 +7825,7 @@ async function edit(community, newCommunityOptions) {
7729
7825
  }
7730
7826
  await community.initDbHandlerIfNeeded();
7731
7827
  await community._updateStartedValue();
7828
+ if (isStartInFlight(community)) return edit(community, newCommunityOptions);
7732
7829
  if (community.started && community.state !== "started") {
7733
7830
  community._dbHandler.destoryConnection();
7734
7831
  throw new PKCError("ERR_CAN_NOT_EDIT_A_LOCAL_COMMUNITY_THAT_IS_ALREADY_STARTED_IN_ANOTHER_PROCESS", {
@@ -7747,7 +7844,7 @@ async function edit(community, newCommunityOptions) {
7747
7844
  ...n$2(editWithDerivedName, ["roles"]),
7748
7845
  ...newInternalProps
7749
7846
  };
7750
- if (community._stopInFlight) return edit(community, newCommunityOptions);
7847
+ if (community._stopInFlight || isStartInFlight(community)) return edit(community, newCommunityOptions);
7751
7848
  if (!community.started && !startedCommunity) return editPropsOnNotStartedCommunity(community, newProps, pagesEdit);
7752
7849
  if (findStartedCommunity(community._pkc, {
7753
7850
  publicKey: community.publicKey,
@@ -7760,11 +7857,11 @@ async function edit(community, newCommunityOptions) {
7760
7857
  const EXPORTS_KEY = STORAGE_KEYS[STORAGE_KEYS.EXPORTS];
7761
7858
  function defaultExportPathFor(community, exportId) {
7762
7859
  if (typeof community._pkc.dataPath !== "string") throw new PKCError("ERR_DATA_PATH_IS_NOT_DEFINED", { communityAddress: community.address });
7763
- return Path.join(community._pkc.dataPath, "exports", `${exportId}.sqlite`);
7860
+ return path.join(community._pkc.dataPath, "exports", `${exportId}.sqlite`);
7764
7861
  }
7765
7862
  function sourceDbPathFor(community) {
7766
7863
  if (typeof community._pkc.dataPath !== "string") throw new PKCError("ERR_DATA_PATH_IS_NOT_DEFINED", { communityAddress: community.address });
7767
- return Path.join(community._pkc.dataPath, "communities", community.address);
7864
+ return path.join(community._pkc.dataPath, "communities", community.address);
7768
7865
  }
7769
7866
  async function persistExports(community) {
7770
7867
  if (!community._dbHandler) return;
@@ -7840,9 +7937,9 @@ async function runExportTask(community, exportId, opts) {
7840
7937
  async function exportCommunityEmbedded(community, options = {}) {
7841
7938
  if (options.signal?.aborted) throw options.signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
7842
7939
  const exportId = v4();
7843
- const destPath = options.exportPath ? Path.resolve(options.exportPath) : defaultExportPathFor(community, exportId);
7940
+ const destPath = options.exportPath ? path.resolve(options.exportPath) : defaultExportPathFor(community, exportId);
7844
7941
  const includePrivateKey = options.includePrivateKey === true;
7845
- if (Path.resolve(destPath) === Path.resolve(sourceDbPathFor(community))) throw new PKCError("ERR_EXPORT_PATH_TARGETS_LIVE_DB", {
7942
+ if (path.resolve(destPath) === path.resolve(sourceDbPathFor(community))) throw new PKCError("ERR_EXPORT_PATH_TARGETS_LIVE_DB", {
7846
7943
  communityAddress: community.address,
7847
7944
  exportPath: destPath
7848
7945
  });
@@ -7979,12 +8076,14 @@ var LocalCommunity = class extends RpcLocalCommunity {
7979
8076
  this._pageSorts = void 0;
7980
8077
  this._pageSortFactories = void 0;
7981
8078
  this._reportedChallengeLoadFailures = void 0;
7982
- this._startLockLost = false;
7983
8079
  this._publishLoopPromise = void 0;
7984
8080
  this._updateLoopPromise = void 0;
7985
8081
  this._startOrUpdateInFlight = void 0;
7986
8082
  this._stopInFlight = void 0;
8083
+ this._deleteInFlight = void 0;
8084
+ this._stoppedEditsInFlight = /* @__PURE__ */ new Set();
7987
8085
  this._editStoresInFlight = /* @__PURE__ */ new Set();
8086
+ this._editsStoredNotApplied = /* @__PURE__ */ new Set();
7988
8087
  this._internalStateUpdateId = "";
7989
8088
  this._lastPubsubTopicRoutingProvideAt = void 0;
7990
8089
  this._subscribedChallengePubsubTopic = void 0;
@@ -8238,7 +8337,7 @@ var LocalCommunity = class extends RpcLocalCommunity {
8238
8337
  try {
8239
8338
  return { moderations: this._dbHandler.queryAllCommentModerations(opts) };
8240
8339
  } finally {
8241
- if (this.state === "stopped") this._dbHandler.destoryConnection();
8340
+ if (this.state === "stopped" && !this._startOrUpdateInFlight) this._dbHandler.destoryConnection();
8242
8341
  }
8243
8342
  }
8244
8343
  async _cancelExport(exportId) {
@@ -8250,8 +8349,8 @@ var LocalCommunity = class extends RpcLocalCommunity {
8250
8349
  async _loadExportsFromKeyv() {
8251
8350
  return loadAndPruneExportsFromKeyv(this);
8252
8351
  }
8253
- async _getDbInternalState(includeMutable = false) {
8254
- return getDbInternalState(this, includeMutable);
8352
+ _getDbInternalState() {
8353
+ return getDbInternalState(this);
8255
8354
  }
8256
8355
  async _listenToIncomingRequests() {
8257
8356
  return listenToIncomingRequests(this);