@pkcprotocol/pkc-js 0.0.146 → 0.0.148

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/runtime/node/community/challenges/exclude/exclude.js +1 -1
  16. package/dist/browser/runtime/node/community/challenges/exclude/exclude.js.map +1 -1
  17. package/dist/browser/runtime/node/community/challenges/exclude/rate-limiter.d.ts +2 -2
  18. package/dist/browser/runtime/node/community/challenges/exclude/rate-limiter.js +21 -17
  19. package/dist/browser/runtime/node/community/challenges/exclude/rate-limiter.js.map +1 -1
  20. package/dist/browser/runtime/node/community/challenges/index.js +1 -1
  21. package/dist/browser/runtime/node/community/challenges/index.js.map +1 -1
  22. package/dist/browser/runtime/node/community/db-handler.d.ts +5 -1
  23. package/dist/browser/runtime/node/community/db-handler.js +64 -12
  24. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  25. package/dist/browser/runtime/node/community/local-community/challenges.js +21 -11
  26. package/dist/browser/runtime/node/community/local-community/challenges.js.map +1 -1
  27. package/dist/browser/runtime/node/community/local-community/db-state.js +95 -13
  28. package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
  29. package/dist/browser/runtime/node/community/local-community/editing.js +92 -22
  30. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  31. package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +2 -0
  32. package/dist/browser/runtime/node/community/local-community/lifecycle.js +72 -20
  33. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  34. package/dist/browser/runtime/node/community/local-community/publication-store.js +9 -0
  35. package/dist/browser/runtime/node/community/local-community/publication-store.js.map +1 -1
  36. package/dist/browser/runtime/node/community/local-community.d.ts +1 -0
  37. package/dist/browser/runtime/node/community/local-community.js +3 -0
  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-PaZmkxgn.js → helia-for-pkc-BUVgQgXa.js} +33 -33
  48. package/dist/bundled/chunks/{local-community-CeuVhBBn.js → local-community-GWqz4s3g.js} +1 -1
  49. package/dist/bundled/chunks/{local-community-BY1ouP1-.js → local-community-dVaQtJNM.js} +292 -91
  50. package/dist/bundled/chunks/{node-BXilwSVE.js → node-fEBX1Nar.js} +162 -16
  51. package/dist/bundled/chunks/{page-sort-scoring-DgSzIxmE.js → page-sort-scoring-DbI7k_K5.js} +1 -1
  52. package/dist/bundled/chunks/{rpc-local-community-BK_HGb_u.js → rpc-local-community-ouDezuGZ.js} +146 -47
  53. package/dist/bundled/chunks/{util-Bnqvxk-6.js → util-B81IOt07.js} +4 -1
  54. package/dist/bundled/chunks/{util-DRSzW-LU.js → util-DofMBAFz.js} +1 -1
  55. package/dist/bundled/chunks/{validate-package-factories-MG5ehoSU.js → validate-package-factories-Bi1OLIPw.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/runtime/node/community/challenges/exclude/exclude.js +1 -1
  73. package/dist/node/runtime/node/community/challenges/exclude/exclude.js.map +1 -1
  74. package/dist/node/runtime/node/community/challenges/exclude/rate-limiter.d.ts +2 -2
  75. package/dist/node/runtime/node/community/challenges/exclude/rate-limiter.js +21 -17
  76. package/dist/node/runtime/node/community/challenges/exclude/rate-limiter.js.map +1 -1
  77. package/dist/node/runtime/node/community/challenges/index.js +1 -1
  78. package/dist/node/runtime/node/community/challenges/index.js.map +1 -1
  79. package/dist/node/runtime/node/community/db-handler.d.ts +5 -1
  80. package/dist/node/runtime/node/community/db-handler.js +64 -12
  81. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  82. package/dist/node/runtime/node/community/local-community/challenges.js +21 -11
  83. package/dist/node/runtime/node/community/local-community/challenges.js.map +1 -1
  84. package/dist/node/runtime/node/community/local-community/db-state.js +95 -13
  85. package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
  86. package/dist/node/runtime/node/community/local-community/editing.js +92 -22
  87. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  88. package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +2 -0
  89. package/dist/node/runtime/node/community/local-community/lifecycle.js +72 -20
  90. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  91. package/dist/node/runtime/node/community/local-community/publication-store.js +9 -0
  92. package/dist/node/runtime/node/community/local-community/publication-store.js.map +1 -1
  93. package/dist/node/runtime/node/community/local-community.d.ts +1 -0
  94. package/dist/node/runtime/node/community/local-community.js +3 -0
  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,12 +1,12 @@
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-Bnqvxk-6.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-BK_HGb_u.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-DgSzIxmE.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-B81IOt07.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-ouDezuGZ.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-DbI7k_K5.js";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
- import path from "node:path";
6
+ import Path from "node:path";
7
7
  import os from "os";
8
- import fs, { existsSync, promises } from "node:fs";
9
- import path$1 from "path";
8
+ import fs, { closeSync, existsSync, openSync, promises } from "node:fs";
9
+ import path from "path";
10
10
  import assert from "assert";
11
11
  import { Buffer as Buffer$1 } from "buffer";
12
12
  import fs$1 from "fs";
@@ -316,15 +316,15 @@ async function throwIfChallengeSettingsAreInvalid({ challengeSettings, pkc, comm
316
316
  const processStartedCommunities = new TrackedInstanceRegistry();
317
317
  function normalizeRegistryDataPath(dataPath) {
318
318
  if (dataPath === void 0) return void 0;
319
- const resolved = path$1.resolve(dataPath);
319
+ const resolved = path.resolve(dataPath);
320
320
  let existing = resolved;
321
321
  let tail = "";
322
322
  while (true) try {
323
- return path$1.join(fs$1.realpathSync.native(existing), tail);
323
+ return path.join(fs$1.realpathSync.native(existing), tail);
324
324
  } catch {
325
- const parent = path$1.dirname(existing);
325
+ const parent = path.dirname(existing);
326
326
  if (parent === existing) return resolved;
327
- tail = path$1.join(path$1.basename(existing), tail);
327
+ tail = path.join(path.basename(existing), tail);
328
328
  existing = parent;
329
329
  }
330
330
  }
@@ -1038,12 +1038,15 @@ async function updateDbInternalState(community, propsOrBuildProps) {
1038
1038
  async function updateInstanceStateWithDbState(community) {
1039
1039
  const currentDbState = await community._getDbInternalState(false);
1040
1040
  if ("updatedAt" in currentDbState) {
1041
- if (currentDbState.posts && !("pages" in currentDbState.posts)) {
1041
+ if (currentDbState.posts && !("pages" in currentDbState.posts)) if (community._dbHandler.hasCommentsAndCommentUpdatesTables()) {
1042
1042
  const dbPosts = currentDbState.posts;
1043
1043
  currentDbState.posts = resolveDbPostsCidRefs({
1044
1044
  dbPosts,
1045
1045
  dbHandler: community._dbHandler
1046
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;
1047
1050
  }
1048
1051
  await community.initInternalCommunityAfterFirstUpdateNoMerge(currentDbState);
1049
1052
  } else await community.initInternalCommunityBeforeFirstUpdateNoMerge(currentDbState);
@@ -1107,11 +1110,26 @@ async function setChallengesToDefaultIfNotDefined(community, log) {
1107
1110
  }
1108
1111
  }
1109
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
+ }
1110
1131
  async function createNewLocalCommunityDb(community) {
1111
1132
  const log = logger_default("pkc-js:local-community:_createNewLocalCommunityDb");
1112
- await community.initDbHandlerIfNeeded();
1113
- await community._dbHandler.initDbIfNeeded({ fileMustExist: false });
1114
- await community._dbHandler.createOrMigrateTablesIfNeeded();
1115
1133
  await initSignerProps(community, community.signer);
1116
1134
  if (!community.pubsubTopic && !community.settings?.disablePubsubChallengeExchange) community.pubsubTopic = t$9(community.signer.address);
1117
1135
  if (typeof community.createdAt !== "number") community.createdAt = timestamp();
@@ -1151,9 +1169,53 @@ async function createNewLocalCommunityDb(community) {
1151
1169
  pagesSettings: community.settings.pages,
1152
1170
  resolved: community._pageSorts
1153
1171
  });
1154
- if (community._dbHandler.keyvHas(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY])) throw Error("Internal state exists already");
1155
- await community._dbHandler.keyvSet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY], community.toJSONInternalBeforeFirstUpdate());
1156
- 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
+ }
1157
1219
  community._dbHandler.destoryConnection();
1158
1220
  community._updateIpnsPubsubPropsIfNeeded({
1159
1221
  ...community.toJSONInternalBeforeFirstUpdate(),
@@ -1363,6 +1425,7 @@ var DbHandler = class {
1363
1425
  constructor(community) {
1364
1426
  this._transactionGeneration = 0;
1365
1427
  this._publicationWriteGeneration = 0;
1428
+ this._heldStartLock = void 0;
1366
1429
  this._community = community;
1367
1430
  this._transactionDepth = 0;
1368
1431
  this._createdTables = false;
@@ -1462,8 +1525,11 @@ var DbHandler = class {
1462
1525
  destoryConnection() {
1463
1526
  const log = logger_default("pkc-js:local-community:dbHandler:destroyConnection");
1464
1527
  this._preparedStatements.clear();
1465
- if (this._db && this._db.open) {
1528
+ if (this._db && this._db.open) try {
1466
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 {
1467
1533
  this._db.close();
1468
1534
  }
1469
1535
  if (this._keyv) this._keyv.disconnect();
@@ -1726,9 +1792,9 @@ var DbHandler = class {
1726
1792
  if (needToMigrate) {
1727
1793
  if (dbExistsAlready && currentDbVersion > 0) {
1728
1794
  this.destoryConnection();
1729
- backupDbPath = path$1.join(path$1.dirname(dbPath), ".backup_before_migration", `${path$1.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
1730
- log(`Copying db ${path$1.basename(dbPath)} to ${backupDbPath} before migration`);
1731
- if (!fs$1.existsSync(path$1.dirname(backupDbPath))) await fs$1.promises.mkdir(path$1.dirname(backupDbPath), { recursive: true });
1795
+ backupDbPath = path.join(path.dirname(dbPath), ".backup_before_migration", `${path.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
1796
+ log(`Copying db ${path.basename(dbPath)} to ${backupDbPath} before migration`);
1797
+ if (!fs$1.existsSync(path.dirname(backupDbPath))) await fs$1.promises.mkdir(path.dirname(backupDbPath), { recursive: true });
1732
1798
  const sourceDb = new Database(dbPath, { fileMustExist: true });
1733
1799
  await sourceDb.backup(backupDbPath);
1734
1800
  sourceDb.close();
@@ -1759,17 +1825,22 @@ var DbHandler = class {
1759
1825
  for (let i = 0; i < tables.length; i++) {
1760
1826
  const tableName = tables[i];
1761
1827
  const tableExists = this._tableExists(tableName);
1762
- 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) {
1763
1833
  log(`Table ${tableName} does not exist. Will create schema`);
1764
1834
  createTableFunctions[i](tableName);
1765
1835
  } else if (tableExists && needToMigrate) {
1766
1836
  log(`Migrating table ${tableName} to new schema`);
1767
- const tempTableName = `${tableName}_${version_default.DB_VERSION}_new`;
1768
1837
  this._db.exec(`DROP TABLE IF EXISTS ${tempTableName}`);
1769
1838
  createTableFunctions[i](tempTableName);
1770
1839
  await this._copyTable(tableName, tempTableName, currentDbVersion);
1771
- this._db.exec(`DROP TABLE ${tableName}`);
1772
- 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
+ })();
1773
1844
  }
1774
1845
  }
1775
1846
  this._createCommentsIndexes();
@@ -1811,7 +1882,14 @@ var DbHandler = class {
1811
1882
  this._columnNamesByTable = {};
1812
1883
  this._preparedStatements.clear();
1813
1884
  if (needToMigrate) log(`Created/migrated the tables to the latest (${newDbVersion}) version and saved to path`, this._dbConfig.filename);
1814
- 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);
1815
1893
  }
1816
1894
  _tableExists(tableName) {
1817
1895
  return !!this._db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?").get(tableName);
@@ -3787,16 +3865,20 @@ var DbHandler = class {
3787
3865
  if (this._db || this._keyv) await this.destoryConnection();
3788
3866
  this._transactionDepth = 0;
3789
3867
  const dataPath = this._community._pkc.dataPath;
3790
- const oldPathString = path$1.join(dataPath, "communities", oldDbName);
3791
- const newPathString = path$1.join(dataPath, "communities", newDbName);
3792
- await fs$1.promises.mkdir(path$1.dirname(oldPathString), { recursive: true });
3793
- await fs$1.promises.mkdir(path$1.dirname(newPathString), { recursive: true });
3868
+ const oldPathString = path.join(dataPath, "communities", oldDbName);
3869
+ const newPathString = path.join(dataPath, "communities", newDbName);
3870
+ await fs$1.promises.mkdir(path.dirname(oldPathString), { recursive: true });
3871
+ await fs$1.promises.mkdir(path.dirname(newPathString), { recursive: true });
3794
3872
  try {
3795
3873
  if (!fs$1.existsSync(oldPathString)) log(`Old DB file ${oldPathString} does not exist. Cannot backup/rename.`);
3796
3874
  else {
3797
3875
  const sourceDb = new Database(oldPathString, { fileMustExist: true });
3798
3876
  await sourceDb.backup(newPathString);
3799
3877
  sourceDb.close();
3878
+ await forgetCommunityThatFailedToBeDeleted({
3879
+ communityAddress: newDbName,
3880
+ pkc: this._community._pkc
3881
+ });
3800
3882
  if (os.type() === "Windows_NT") await deleteOldCommunityInWindows(oldPathString, this._community._pkc);
3801
3883
  else await fs$1.promises.rm(oldPathString, { force: true });
3802
3884
  }
@@ -3810,15 +3892,23 @@ var DbHandler = class {
3810
3892
  };
3811
3893
  log(`Changed db path from (${oldPathString}) to (${newPathString})`);
3812
3894
  }
3813
- async lockCommunityStart(communityAddress = this._community.address) {
3895
+ async lockCommunityStart({ onCompromised }) {
3814
3896
  const log = logger_default("pkc-js:local-community:db-handler:lock:start");
3815
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3816
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3897
+ const communityAddress = this._community.address;
3898
+ const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3899
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3900
+ const startLock = {};
3817
3901
  try {
3818
3902
  await import_src.default.lock(communityDbPath, {
3819
3903
  lockfilePath,
3820
- 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
+ }
3821
3910
  });
3911
+ this._heldStartLock = startLock;
3822
3912
  log(`Locked the start of community (${communityAddress}) successfully`);
3823
3913
  } catch (e) {
3824
3914
  if (e instanceof Error && e.message === "Lock file is already being held") throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", {
@@ -3834,8 +3924,9 @@ var DbHandler = class {
3834
3924
  async unlockCommunityStart(communityAddress = this._community.address) {
3835
3925
  const log = logger_default("pkc-js:local-community:db-handler:unlock:start");
3836
3926
  log.trace(`Attempting to unlock the start of community (${communityAddress})`);
3837
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3838
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3927
+ this._heldStartLock = void 0;
3928
+ const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3929
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3839
3930
  if (!fs$1.existsSync(lockfilePath) || !fs$1.existsSync(communityDbPath)) return;
3840
3931
  try {
3841
3932
  await import_src.default.unlock(communityDbPath, { lockfilePath });
@@ -3853,8 +3944,8 @@ var DbHandler = class {
3853
3944
  }
3854
3945
  async lockCommunityState() {
3855
3946
  const log = logger_default("pkc-js:local-community:db-handler:lock:lockCommunityState");
3856
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3857
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
3947
+ const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3948
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
3858
3949
  try {
3859
3950
  await import_src.default.lock(communityDbPath, {
3860
3951
  lockfilePath,
@@ -3871,8 +3962,8 @@ var DbHandler = class {
3871
3962
  }
3872
3963
  async unlockCommunityState() {
3873
3964
  const log = logger_default("pkc-js:local-community:db-handler:lock:unlockCommunityState");
3874
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3875
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
3965
+ const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3966
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
3876
3967
  if (!fs$1.existsSync(lockfilePath)) return;
3877
3968
  try {
3878
3969
  await import_src.default.unlock(communityDbPath, { lockfilePath });
@@ -3882,7 +3973,7 @@ var DbHandler = class {
3882
3973
  }
3883
3974
  }
3884
3975
  communityDbExists() {
3885
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
3976
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
3886
3977
  return fs$1.existsSync(communityDbPath);
3887
3978
  }
3888
3979
  markCommentsAsPublishedToPostUpdates(commentCids) {
@@ -5189,12 +5280,19 @@ async function handleChallengeRequest(community, request, isLocalPublisher) {
5189
5280
  community._challengeExchangesFromLocalPublishers[request.challengeRequestId.toString()] = true;
5190
5281
  }
5191
5282
  community._ongoingChallengeExchanges.set(request.challengeRequestId.toString(), true);
5192
- const requestSignatureValidation = await verifyChallengeRequest({
5193
- request,
5194
- validateTimestampRange: true
5195
- });
5196
- if (!requestSignatureValidation.valid) throw new PKCError(getErrorCodeFromMessage(requestSignatureValidation.reason), { challengeRequest: n$2(request, ["encrypted"]) });
5197
- const decrypted = await parseChallengeRequest(community, request, log);
5283
+ let decrypted;
5284
+ try {
5285
+ const requestSignatureValidation = await verifyChallengeRequest({
5286
+ request,
5287
+ validateTimestampRange: true
5288
+ });
5289
+ if (!requestSignatureValidation.valid) throw new PKCError(getErrorCodeFromMessage(requestSignatureValidation.reason), { challengeRequest: n$2(request, ["encrypted"]) });
5290
+ decrypted = await parseChallengeRequest(community, request, log);
5291
+ } catch (e) {
5292
+ community._ongoingChallengeExchanges.delete(request.challengeRequestId.toString());
5293
+ delete community._challengeExchangesFromLocalPublishers[request.challengeRequestId.toString()];
5294
+ throw e;
5295
+ }
5198
5296
  if (!decrypted) return;
5199
5297
  const publicationSignature = decrypted.publication.signature.signature;
5200
5298
  let waitedForInFlightExchange = false;
@@ -5250,12 +5348,7 @@ async function handleChallengeAnswer(community, challengeAnswer) {
5250
5348
  answer: challengeAnswer,
5251
5349
  validateTimestampRange: true
5252
5350
  });
5253
- if (!answerSignatureValidation.valid) {
5254
- cleanUpChallengeAnswerPromise(community, challengeAnswer.challengeRequestId.toString());
5255
- community._ongoingChallengeExchanges.delete(challengeAnswer.challengeRequestId.toString());
5256
- delete community._challengeExchangesFromLocalPublishers[challengeAnswer.challengeRequestId.toString()];
5257
- throw new PKCError(getErrorCodeFromMessage(answerSignatureValidation.reason), { challengeAnswer });
5258
- }
5351
+ if (!answerSignatureValidation.valid) throw new PKCError(getErrorCodeFromMessage(answerSignatureValidation.reason), { challengeAnswer });
5259
5352
  const decryptedAnswers = await parseChallengeAnswerOrRespondWithFailure(community, challengeAnswer, await decryptOrRespondWithFailure(community, challengeAnswer));
5260
5353
  const decryptedChallengeAnswerPubsubMessage = {
5261
5354
  ...challengeAnswer,
@@ -5915,6 +6008,10 @@ async function storeCommentModeration(community, commentModRaw, challengeRequest
5915
6008
  } else if ("approved" in modTableRow.commentModeration) if (modTableRow.commentModeration.approved) {
5916
6009
  log("commentModeration.approved=true, and therefore move comment from pending approval and add it to IPFS", "comment cid is", modTableRow.commentCid);
5917
6010
  await community._addCommentRowToIPFS(commentToBeEdited, logger_default("pkc-js:local-community:storeCommentModeration:_addCommentRowToIPFS"));
6011
+ if (!community._dbHandler.queryComment(modTableRow.commentCid)) {
6012
+ addAllCidsUnderPurgedCommentToBeRemoved(community, { commentTableRow: commentToBeEdited });
6013
+ throw new PKCError("ERR_COMMENT_MODERATION_NO_COMMENT_TO_EDIT", { commentCid: modTableRow.commentCid });
6014
+ }
5918
6015
  community._dbHandler.approvePendingComment({ cid: modTableRow.commentCid });
5919
6016
  } else {
5920
6017
  const shouldPurgeDisapprovedComment = Object.keys(modTableRow.commentModeration).length === 1;
@@ -6589,7 +6686,7 @@ async function publishLoop(community, syncIntervalMs) {
6589
6686
  const log = logger_default("pkc-js:local-community:_publishLoop");
6590
6687
  let syncFailedSinceStop = false;
6591
6688
  const shouldStopPublishLoop = () => {
6592
- return community.state !== "started" || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
6689
+ return community.state !== "started" || community._startLockLost || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
6593
6690
  };
6594
6691
  const waitUntilNextSync = async ({ lastSyncFailed }) => {
6595
6692
  const doneWithLoopTime = Date.now();
@@ -6704,6 +6801,9 @@ async function startCommunity({ community, releaseMark }) {
6704
6801
  publicKey: community.publicKey,
6705
6802
  name: community.name
6706
6803
  }) || findProcessStartedCommunity(community)) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
6804
+ community._startLockLost = false;
6805
+ let startLockLostDuringStart;
6806
+ let startFinished = false;
6707
6807
  try {
6708
6808
  await initBeforeStarting(community);
6709
6809
  if (community.anchor && !getPersistedAnchorRecordBytes(community)) throw new PKCError("ERR_DELEGATED_COMMUNITY_HAS_NO_ANCHOR_RECORD", {
@@ -6716,7 +6816,15 @@ async function startCommunity({ community, releaseMark }) {
6716
6816
  pkc: community._pkc,
6717
6817
  communityAddress: community.address
6718
6818
  });
6719
- await community._dbHandler.lockCommunityStart();
6819
+ await community._dbHandler.lockCommunityStart({ onCompromised: (error) => {
6820
+ community._startLockLost = true;
6821
+ const lostLockError = new PKCError("ERR_COMMUNITY_START_LOCK_COMPROMISED", {
6822
+ communityAddress: community.address,
6823
+ error
6824
+ });
6825
+ if (startFinished) stopAfterLosingStartLock(community, lostLockError);
6826
+ else startLockLostDuringStart = lostLockError;
6827
+ } });
6720
6828
  community._setState("started");
6721
6829
  await community._updateStartedValue();
6722
6830
  trackStartedCommunity(community._pkc, community);
@@ -6739,11 +6847,14 @@ async function startCommunity({ community, releaseMark }) {
6739
6847
  community._setStartedStateWithEmission("publishing-ipns");
6740
6848
  await community._repinCommentsIPFSIfNeeded();
6741
6849
  await repinCommentUpdateIfNeeded(community);
6850
+ if (startLockLostDuringStart) throw startLockLostDuringStart;
6742
6851
  await community._listenToIncomingRequests();
6743
6852
  await emitChallengeSettingsValidationErrors(community, log);
6744
6853
  community._pageSorts = void 0;
6745
6854
  community._pageSortFactories = void 0;
6746
6855
  await syncPageSortsWithRegistry(community);
6856
+ if (startLockLostDuringStart) throw startLockLostDuringStart;
6857
+ startFinished = true;
6747
6858
  } catch (e) {
6748
6859
  releaseMark();
6749
6860
  await community.stop();
@@ -6759,6 +6870,12 @@ async function startCommunity({ community, releaseMark }) {
6759
6870
  community.emit("error", err);
6760
6871
  });
6761
6872
  }
6873
+ function stopAfterLosingStartLock(community, error) {
6874
+ const log = logger_default("pkc-js:local-community:stopAfterLosingStartLock");
6875
+ if (community.state !== "started") return;
6876
+ if (!community._stopHasBeenCalled) community.stop().catch((e) => log.error(`Failed to stop community (${community.address}) after losing its start lock`, e));
6877
+ community.emit("error", error);
6878
+ }
6762
6879
  async function initMirroringStartedOrUpdatingCommunity(community, startedCommunity) {
6763
6880
  const updatingStateChangeListener = (newState) => {
6764
6881
  community._setUpdatingStateWithEventEmissionIfNewState(newState);
@@ -6927,20 +7044,23 @@ async function stopCommunity(community) {
6927
7044
  }
6928
7045
  community._publishLoopPromise = void 0;
6929
7046
  }
6930
- try {
6931
- await unpinStaleCids(community, { bypassGracePeriod: true });
6932
- } catch (e) {
6933
- log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
6934
- }
6935
- try {
6936
- await updateDbInternalState(community, () => community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
6937
- } catch (e) {
6938
- log.error("Failed to update db internal state before stopping", e);
6939
- }
6940
- try {
6941
- await community._dbHandler.unlockCommunityStart();
6942
- } catch (e) {
6943
- log.error(`Failed to unlock start lock on community (${community.address})`, e);
7047
+ if (community._startLockLost) log(`Community (${community.address}) lost its start lock, stopping without writing its state, unpinning or unlocking`);
7048
+ else {
7049
+ try {
7050
+ await unpinStaleCids(community, { bypassGracePeriod: true });
7051
+ } catch (e) {
7052
+ log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
7053
+ }
7054
+ try {
7055
+ await updateDbInternalState(community, () => community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
7056
+ } catch (e) {
7057
+ log.error("Failed to update db internal state before stopping", e);
7058
+ }
7059
+ try {
7060
+ await community._dbHandler.unlockCommunityStart();
7061
+ } catch (e) {
7062
+ log.error(`Failed to unlock start lock on community (${community.address})`, e);
7063
+ }
6944
7064
  }
6945
7065
  const kuboRpcClient = community._clientsManager.getDefaultKuboRpcClient();
6946
7066
  community._setStartedStateWithEmission("stopped");
@@ -7159,24 +7279,89 @@ function deriveNameAndAddressEdit(community, editOptions) {
7159
7279
  function listRenamedCommunityNow(community) {
7160
7280
  refreshCommunitiesList(community._pkc);
7161
7281
  }
7162
- async function restoreCommunityAfterFailedRename({ community, oldAddress, newAddress, postUpdatesFolderMoved, log }) {
7282
+ async function movePostUpdatesFolderBack({ community, oldAddress, newAddress, log }) {
7283
+ try {
7284
+ await movePostUpdatesFolderToNewAddress(community, newAddress, oldAddress);
7285
+ return;
7286
+ } catch (moveBackError) {
7287
+ log.error(`Failed to move the postUpdates folder of community (${oldAddress}) back from ${newAddress}`, moveBackError);
7288
+ return moveBackError;
7289
+ }
7290
+ }
7291
+ function emitRenameUndoError({ community, error, log }) {
7292
+ try {
7293
+ community.emit("error", error);
7294
+ } catch (emitError) {
7295
+ log.error(`Nothing listens for the errors of community (${community.address}), the error it could not report was`, error);
7296
+ }
7297
+ }
7298
+ async function restartCommunityAfterFailedRename({ community, oldAddress, newAddress, log }) {
7163
7299
  try {
7164
- if (postUpdatesFolderMoved) await movePostUpdatesFolderToNewAddress(community, newAddress, oldAddress);
7165
7300
  await community.start();
7166
- } catch (restoreError) {
7167
- log.error(`Failed to restore community (${oldAddress}) after its rename to ${newAddress} failed`, restoreError);
7168
- community.emit("error", restoreError);
7301
+ } catch (restartError) {
7302
+ log.error(`Failed to restart community (${oldAddress}) after its rename to ${newAddress} failed`, restartError);
7303
+ emitRenameUndoError({
7304
+ community,
7305
+ error: restartError,
7306
+ log
7307
+ });
7169
7308
  }
7170
7309
  }
7171
7310
  async function removePartialDbCopy({ community, oldAddress, newAddress, log }) {
7172
- const communitiesPath = path.join(community._pkc.dataPath, "communities");
7173
- if (!fs.existsSync(path.join(communitiesPath, oldAddress))) return;
7311
+ const communitiesPath = Path.join(community._pkc.dataPath, "communities");
7312
+ const partialDbCopyPath = Path.join(communitiesPath, newAddress);
7313
+ if (!fs.existsSync(Path.join(communitiesPath, oldAddress))) return {
7314
+ removed: false,
7315
+ path: partialDbCopyPath
7316
+ };
7174
7317
  try {
7175
- await fs.promises.rm(path.join(communitiesPath, newAddress), { force: true });
7318
+ await removeFileRetryingWhileBusy(partialDbCopyPath, { log });
7319
+ return { removed: true };
7176
7320
  } catch (e) {
7177
- log.error(`Failed to remove the partial DB copy of community (${oldAddress}) at ${newAddress}`, e);
7321
+ log.error(`Failed to remove the partial DB copy of community (${oldAddress}) at ${partialDbCopyPath}`, e);
7322
+ return {
7323
+ removed: false,
7324
+ path: partialDbCopyPath,
7325
+ error: e
7326
+ };
7178
7327
  }
7179
7328
  }
7329
+ async function undoRenameAfterDbRenameFailed({ community, oldAddress, newAddress, dbRenameError, log }) {
7330
+ const communitiesPath = Path.join(community._pkc.dataPath, "communities");
7331
+ const partialDbCopy = await removePartialDbCopy({
7332
+ community,
7333
+ oldAddress,
7334
+ newAddress,
7335
+ log
7336
+ });
7337
+ const moveBackError = await movePostUpdatesFolderBack({
7338
+ community,
7339
+ oldAddress,
7340
+ newAddress,
7341
+ log
7342
+ });
7343
+ const renameError = dbRenameError;
7344
+ return {
7345
+ error: new PKCError("ERR_FAILED_TO_RENAME_COMMUNITY_DB", {
7346
+ oldAddress,
7347
+ newAddress,
7348
+ oldDbPath: Path.join(communitiesPath, oldAddress),
7349
+ newDbPath: Path.join(communitiesPath, newAddress),
7350
+ error: dbRenameError,
7351
+ errorMessage: renameError?.message,
7352
+ errorName: renameError?.name,
7353
+ errorCode: renameError?.code,
7354
+ partialDbCopyRemoved: partialDbCopy.removed,
7355
+ ...partialDbCopy.removed ? {} : {
7356
+ partialDbCopyPath: partialDbCopy.path,
7357
+ partialDbCopyRemovalError: partialDbCopy.error
7358
+ },
7359
+ postUpdatesFolderMovedBack: moveBackError === void 0,
7360
+ ...moveBackError ? { postUpdatesFolderMoveBackError: moveBackError } : {}
7361
+ }),
7362
+ moveBackError
7363
+ };
7364
+ }
7180
7365
  async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEdit) {
7181
7366
  const log = logger_default("pkc-js:local-community:start:editPropsOnStartedCommunity");
7182
7367
  const oldAddress = t$9(community.address);
@@ -7189,11 +7374,10 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7189
7374
  try {
7190
7375
  await movePostUpdatesFolderToNewAddress(community, oldAddress, newAddress);
7191
7376
  } catch (e) {
7192
- await restoreCommunityAfterFailedRename({
7377
+ await restartCommunityAfterFailedRename({
7193
7378
  community,
7194
7379
  oldAddress,
7195
7380
  newAddress,
7196
- postUpdatesFolderMoved: false,
7197
7381
  log
7198
7382
  });
7199
7383
  throw e;
@@ -7201,20 +7385,25 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7201
7385
  try {
7202
7386
  await community._dbHandler.changeDbFilename(oldAddress, newAddress);
7203
7387
  } catch (e) {
7204
- await removePartialDbCopy({
7388
+ const { error, moveBackError } = await undoRenameAfterDbRenameFailed({
7205
7389
  community,
7206
7390
  oldAddress,
7207
7391
  newAddress,
7392
+ dbRenameError: e,
7208
7393
  log
7209
7394
  });
7210
- await restoreCommunityAfterFailedRename({
7395
+ if (moveBackError) emitRenameUndoError({
7396
+ community,
7397
+ error: moveBackError,
7398
+ log
7399
+ });
7400
+ else await restartCommunityAfterFailedRename({
7211
7401
  community,
7212
7402
  oldAddress,
7213
7403
  newAddress,
7214
- postUpdatesFolderMoved: true,
7215
7404
  log
7216
7405
  });
7217
- throw e;
7406
+ throw error;
7218
7407
  }
7219
7408
  listRenamedCommunityNow(community);
7220
7409
  community.setAddress(newAddress);
@@ -7269,9 +7458,20 @@ async function editPropsOnNotStartedCommunity(community, parsedEditOptions, page
7269
7458
  await validateNewAddressBeforeEditing(community, parsedEditOptions.address, log);
7270
7459
  log(`Attempting to edit community.address from ${oldAddress} to ${parsedEditOptions.address}`);
7271
7460
  log("will rename the community", community.address, "db in edit() because the community is not being ran anywhere else");
7272
- await movePostUpdatesFolderToNewAddress(community, community.address, parsedEditOptions.address);
7273
- community._dbHandler.destoryConnection();
7274
- await community._dbHandler.changeDbFilename(community.address, parsedEditOptions.address);
7461
+ const newAddress = parsedEditOptions.address;
7462
+ await movePostUpdatesFolderToNewAddress(community, oldAddress, newAddress);
7463
+ await community._dbHandler.destoryConnection();
7464
+ try {
7465
+ await community._dbHandler.changeDbFilename(oldAddress, newAddress);
7466
+ } catch (e) {
7467
+ throw (await undoRenameAfterDbRenameFailed({
7468
+ community,
7469
+ oldAddress,
7470
+ newAddress,
7471
+ dbRenameError: e,
7472
+ log
7473
+ })).error;
7474
+ }
7275
7475
  listRenamedCommunityNow(community);
7276
7476
  await community._dbHandler.initDbIfNeeded();
7277
7477
  community.setAddress(parsedEditOptions.address);
@@ -7329,11 +7529,11 @@ async function edit(community, newCommunityOptions) {
7329
7529
  const EXPORTS_KEY = STORAGE_KEYS[STORAGE_KEYS.EXPORTS];
7330
7530
  function defaultExportPathFor(community, exportId) {
7331
7531
  if (typeof community._pkc.dataPath !== "string") throw new PKCError("ERR_DATA_PATH_IS_NOT_DEFINED", { communityAddress: community.address });
7332
- return path.join(community._pkc.dataPath, "exports", `${exportId}.sqlite`);
7532
+ return Path.join(community._pkc.dataPath, "exports", `${exportId}.sqlite`);
7333
7533
  }
7334
7534
  function sourceDbPathFor(community) {
7335
7535
  if (typeof community._pkc.dataPath !== "string") throw new PKCError("ERR_DATA_PATH_IS_NOT_DEFINED", { communityAddress: community.address });
7336
- return path.join(community._pkc.dataPath, "communities", community.address);
7536
+ return Path.join(community._pkc.dataPath, "communities", community.address);
7337
7537
  }
7338
7538
  async function persistExports(community) {
7339
7539
  if (!community._dbHandler) return;
@@ -7409,9 +7609,9 @@ async function runExportTask(community, exportId, opts) {
7409
7609
  async function exportCommunityEmbedded(community, options = {}) {
7410
7610
  if (options.signal?.aborted) throw options.signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
7411
7611
  const exportId = v4();
7412
- const destPath = options.exportPath ? path.resolve(options.exportPath) : defaultExportPathFor(community, exportId);
7612
+ const destPath = options.exportPath ? Path.resolve(options.exportPath) : defaultExportPathFor(community, exportId);
7413
7613
  const includePrivateKey = options.includePrivateKey === true;
7414
- if (path.resolve(destPath) === path.resolve(sourceDbPathFor(community))) throw new PKCError("ERR_EXPORT_PATH_TARGETS_LIVE_DB", {
7614
+ if (Path.resolve(destPath) === Path.resolve(sourceDbPathFor(community))) throw new PKCError("ERR_EXPORT_PATH_TARGETS_LIVE_DB", {
7415
7615
  communityAddress: community.address,
7416
7616
  exportPath: destPath
7417
7617
  });
@@ -7548,6 +7748,7 @@ var LocalCommunity = class extends RpcLocalCommunity {
7548
7748
  this._pageSorts = void 0;
7549
7749
  this._pageSortFactories = void 0;
7550
7750
  this._reportedChallengeLoadFailures = void 0;
7751
+ this._startLockLost = false;
7551
7752
  this._publishLoopPromise = void 0;
7552
7753
  this._updateLoopPromise = void 0;
7553
7754
  this._startOrUpdateInFlight = void 0;