@pkcprotocol/pkc-js 0.0.149 → 0.0.150

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 (76) hide show
  1. package/dist/browser/errors.d.ts +1 -0
  2. package/dist/browser/errors.js +1 -0
  3. package/dist/browser/errors.js.map +1 -1
  4. package/dist/browser/generated-version.d.ts +1 -1
  5. package/dist/browser/generated-version.js +1 -1
  6. package/dist/browser/helia/helia-for-pkc.js +15 -10
  7. package/dist/browser/helia/helia-for-pkc.js.map +1 -1
  8. package/dist/browser/helia/util.d.ts +3 -2
  9. package/dist/browser/helia/util.js +17 -7
  10. package/dist/browser/helia/util.js.map +1 -1
  11. package/dist/browser/pkc-error.d.ts +1 -1
  12. package/dist/browser/runtime/node/community/local-community/cleanup.js +3 -0
  13. package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
  14. package/dist/browser/runtime/node/community/local-community/comment-updates.js +30 -62
  15. package/dist/browser/runtime/node/community/local-community/comment-updates.js.map +1 -1
  16. package/dist/browser/runtime/node/community/local-community/post-updates-bucket.d.ts +7 -5
  17. package/dist/browser/runtime/node/community/local-community/post-updates-bucket.js +122 -121
  18. package/dist/browser/runtime/node/community/local-community/post-updates-bucket.js.map +1 -1
  19. package/dist/browser/runtime/node/community/local-community/unixfs-directory-patch.d.ts +20 -0
  20. package/dist/browser/runtime/node/community/local-community/unixfs-directory-patch.js +231 -0
  21. package/dist/browser/runtime/node/community/local-community/unixfs-directory-patch.js.map +1 -0
  22. package/dist/browser/runtime/node/community/local-community.d.ts +1 -1
  23. package/dist/browser/runtime/node/community/local-community.js +3 -4
  24. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  25. package/dist/browser/util.d.ts +1 -12
  26. package/dist/browser/util.js +0 -53
  27. package/dist/browser/util.js.map +1 -1
  28. package/dist/bundled/bundle-manifest.json +135 -121
  29. package/dist/bundled/challenges.js +1 -1
  30. package/dist/bundled/chunks/{helia-for-pkc-8iett8xl.js → helia-for-pkc-1sdkdugl.js} +43 -42
  31. package/dist/bundled/chunks/{local-community-ChZZa9bm.js → local-community-BGml0_JD.js} +1 -1
  32. package/dist/bundled/chunks/{local-community-BlBIYSsF.js → local-community-Dadvhqoi.js} +406 -188
  33. package/dist/bundled/chunks/{node-BH_HrtON.js → node-DOdTF4o2.js} +5 -5
  34. package/dist/bundled/chunks/{page-sort-scoring-NpdjWYfa.js → page-sort-scoring-DozAWSgg.js} +1 -1
  35. package/dist/bundled/chunks/{rpc-local-community-Byj5ZmMa.js → rpc-local-community-DaCMetml.js} +3 -3
  36. package/dist/bundled/chunks/src-66iuMY_4.js +2 -0
  37. package/dist/bundled/chunks/{src-evzEHW9W.js → src-BSYNGtIQ.js} +2 -44
  38. package/dist/bundled/chunks/{src-CNab3O7M.js → src-CAvdjq_i.js} +2 -2
  39. package/dist/bundled/chunks/{src-Bj5iE3qB.js → src-DIOHVUq9.js} +5 -4
  40. package/dist/bundled/chunks/src-DeIT_BDx.js +44 -0
  41. package/dist/bundled/chunks/{src-ltPxiZKf.js → src-NvrGEL7T.js} +2 -1
  42. package/dist/bundled/chunks/{util-DmmLFRbV.js → util-B9XQRGR7.js} +19 -7
  43. package/dist/bundled/chunks/{util-CUZ1U2Go.js → util-BUFRgvXt.js} +4 -45
  44. package/dist/bundled/chunks/{validate-package-factories-CkU4qFQx.js → validate-package-factories-NPflVcyZ.js} +2 -2
  45. package/dist/bundled/index.js +1 -1
  46. package/dist/bundled/page-sorts.js +1 -1
  47. package/dist/bundled/rpc/src/index.js +4 -4
  48. package/dist/node/errors.d.ts +1 -0
  49. package/dist/node/errors.js +1 -0
  50. package/dist/node/errors.js.map +1 -1
  51. package/dist/node/generated-version.d.ts +1 -1
  52. package/dist/node/generated-version.js +1 -1
  53. package/dist/node/helia/helia-for-pkc.js +15 -10
  54. package/dist/node/helia/helia-for-pkc.js.map +1 -1
  55. package/dist/node/helia/util.d.ts +3 -2
  56. package/dist/node/helia/util.js +17 -7
  57. package/dist/node/helia/util.js.map +1 -1
  58. package/dist/node/pkc-error.d.ts +1 -1
  59. package/dist/node/runtime/node/community/local-community/cleanup.js +3 -0
  60. package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
  61. package/dist/node/runtime/node/community/local-community/comment-updates.js +30 -62
  62. package/dist/node/runtime/node/community/local-community/comment-updates.js.map +1 -1
  63. package/dist/node/runtime/node/community/local-community/post-updates-bucket.d.ts +7 -5
  64. package/dist/node/runtime/node/community/local-community/post-updates-bucket.js +122 -121
  65. package/dist/node/runtime/node/community/local-community/post-updates-bucket.js.map +1 -1
  66. package/dist/node/runtime/node/community/local-community/unixfs-directory-patch.d.ts +20 -0
  67. package/dist/node/runtime/node/community/local-community/unixfs-directory-patch.js +231 -0
  68. package/dist/node/runtime/node/community/local-community/unixfs-directory-patch.js.map +1 -0
  69. package/dist/node/runtime/node/community/local-community.d.ts +1 -1
  70. package/dist/node/runtime/node/community/local-community.js +3 -4
  71. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  72. package/dist/node/util.d.ts +1 -12
  73. package/dist/node/util.js +0 -53
  74. package/dist/node/util.js.map +1 -1
  75. package/package.json +3 -1
  76. package/dist/bundled/chunks/src-BC60-Q7v.js +0 -2
@@ -1,12 +1,14 @@
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-CUZ1U2Go.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-Byj5ZmMa.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-NpdjWYfa.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-BUFRgvXt.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-DaCMetml.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-DozAWSgg.js";
5
+ import { c as prepare, n as decode$1, r as encode$1 } from "./src-BSYNGtIQ.js";
6
+ import { t as UnixFS } from "./src-CAvdjq_i.js";
5
7
  import { fileURLToPath, pathToFileURL } from "node:url";
6
- import Path from "node:path";
8
+ import path from "node:path";
7
9
  import os from "os";
8
10
  import fs, { closeSync, existsSync, openSync, promises } from "node:fs";
9
- import path from "path";
11
+ import path$1 from "path";
10
12
  import assert from "assert";
11
13
  import { Buffer as Buffer$1 } from "buffer";
12
14
  import fs$1 from "fs";
@@ -15,6 +17,8 @@ import { CID } from "multiformats/cid";
15
17
  import { peerIdFromString } from "@libp2p/peer-id";
16
18
  import { of } from "typestub-ipfs-only-hash";
17
19
  import v8 from "node:v8";
20
+ import { sha256 } from "multiformats/hashes/sha2";
21
+ import { murmur3128 } from "@multiformats/murmur3";
18
22
  //#region node_modules/remeda/dist/entries.js
19
23
  function t$1(...t) {
20
24
  return t$2(Object.entries, t);
@@ -316,15 +320,15 @@ async function throwIfChallengeSettingsAreInvalid({ challengeSettings, pkc, comm
316
320
  const processStartedCommunities = new TrackedInstanceRegistry();
317
321
  function normalizeRegistryDataPath(dataPath) {
318
322
  if (dataPath === void 0) return void 0;
319
- const resolved = path.resolve(dataPath);
323
+ const resolved = path$1.resolve(dataPath);
320
324
  let existing = resolved;
321
325
  let tail = "";
322
326
  while (true) try {
323
- return path.join(fs$1.realpathSync.native(existing), tail);
327
+ return path$1.join(fs$1.realpathSync.native(existing), tail);
324
328
  } catch {
325
- const parent = path.dirname(existing);
329
+ const parent = path$1.dirname(existing);
326
330
  if (parent === existing) return resolved;
327
- tail = path.join(path.basename(existing), tail);
331
+ tail = path$1.join(path$1.basename(existing), tail);
328
332
  existing = parent;
329
333
  }
330
334
  }
@@ -1792,9 +1796,9 @@ var DbHandler = class {
1792
1796
  if (needToMigrate) {
1793
1797
  if (dbExistsAlready && currentDbVersion > 0) {
1794
1798
  this.destoryConnection();
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 });
1799
+ backupDbPath = path$1.join(path$1.dirname(dbPath), ".backup_before_migration", `${path$1.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
1800
+ log(`Copying db ${path$1.basename(dbPath)} to ${backupDbPath} before migration`);
1801
+ if (!fs$1.existsSync(path$1.dirname(backupDbPath))) await fs$1.promises.mkdir(path$1.dirname(backupDbPath), { recursive: true });
1798
1802
  const sourceDb = new Database(dbPath, { fileMustExist: true });
1799
1803
  await sourceDb.backup(backupDbPath);
1800
1804
  sourceDb.close();
@@ -3865,10 +3869,10 @@ var DbHandler = class {
3865
3869
  if (this._db || this._keyv) await this.destoryConnection();
3866
3870
  this._transactionDepth = 0;
3867
3871
  const dataPath = this._community._pkc.dataPath;
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 });
3872
+ const oldPathString = path$1.join(dataPath, "communities", oldDbName);
3873
+ const newPathString = path$1.join(dataPath, "communities", newDbName);
3874
+ await fs$1.promises.mkdir(path$1.dirname(oldPathString), { recursive: true });
3875
+ await fs$1.promises.mkdir(path$1.dirname(newPathString), { recursive: true });
3872
3876
  try {
3873
3877
  if (!fs$1.existsSync(oldPathString)) log(`Old DB file ${oldPathString} does not exist. Cannot backup/rename.`);
3874
3878
  else {
@@ -3895,8 +3899,8 @@ var DbHandler = class {
3895
3899
  async lockCommunityStart({ onCompromised }) {
3896
3900
  const log = logger_default("pkc-js:local-community:db-handler:lock:start");
3897
3901
  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);
3902
+ const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3903
+ const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3900
3904
  const startLock = {};
3901
3905
  try {
3902
3906
  await import_src.default.lock(communityDbPath, {
@@ -3925,8 +3929,8 @@ var DbHandler = class {
3925
3929
  const log = logger_default("pkc-js:local-community:db-handler:unlock:start");
3926
3930
  log.trace(`Attempting to unlock the start of community (${communityAddress})`);
3927
3931
  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);
3932
+ const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3933
+ const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3930
3934
  if (!fs$1.existsSync(lockfilePath) || !fs$1.existsSync(communityDbPath)) return;
3931
3935
  try {
3932
3936
  await import_src.default.unlock(communityDbPath, { lockfilePath });
@@ -3944,8 +3948,8 @@ var DbHandler = class {
3944
3948
  }
3945
3949
  async lockCommunityState() {
3946
3950
  const log = logger_default("pkc-js:local-community:db-handler:lock:lockCommunityState");
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);
3951
+ const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3952
+ const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
3949
3953
  try {
3950
3954
  await import_src.default.lock(communityDbPath, {
3951
3955
  lockfilePath,
@@ -3962,8 +3966,8 @@ var DbHandler = class {
3962
3966
  }
3963
3967
  async unlockCommunityState() {
3964
3968
  const log = logger_default("pkc-js:local-community:db-handler:lock:unlockCommunityState");
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);
3969
+ const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3970
+ const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
3967
3971
  if (!fs$1.existsSync(lockfilePath)) return;
3968
3972
  try {
3969
3973
  await import_src.default.unlock(communityDbPath, { lockfilePath });
@@ -3973,7 +3977,7 @@ var DbHandler = class {
3973
3977
  }
3974
3978
  }
3975
3979
  communityDbExists() {
3976
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
3980
+ const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
3977
3981
  return fs$1.existsSync(communityDbPath);
3978
3982
  }
3979
3983
  markCommentsAsPublishedToPostUpdates(commentCids) {
@@ -4144,10 +4148,247 @@ var DbHandler = class {
4144
4148
  }
4145
4149
  };
4146
4150
  //#endregion
4151
+ //#region dist/node/runtime/node/community/local-community/unixfs-directory-patch.js
4152
+ const HAMT_FANOUT = 256n;
4153
+ const HAMT_HASH_TYPE_MURMUR3_X64_64 = 34n;
4154
+ const HAMT_MAX_DEPTH = 8;
4155
+ const HAMT_SLOT_PREFIX_LENGTH = 2;
4156
+ const SHARD_FETCH_CONCURRENCY = 32;
4157
+ const textEncoder$1 = new TextEncoder();
4158
+ var HamtShard = class {
4159
+ constructor(stored) {
4160
+ this.slots = /* @__PURE__ */ new Map();
4161
+ this.stored = stored;
4162
+ this.loaded = stored === void 0;
4163
+ }
4164
+ };
4165
+ async function patchUnixFsDirectory({ directoryCid, entriesToPut, namesToRemove = [], getBlock, shardSplitThresholdBytes }) {
4166
+ const cidVersion = directoryCid?.version ?? 0;
4167
+ const newBlocks = [];
4168
+ const storeNode = async (node) => {
4169
+ const bytes = encode$1(prepare(node));
4170
+ const cid = CID.create(cidVersion, 112, await sha256.digest(bytes));
4171
+ newBlocks.push({
4172
+ cid,
4173
+ bytes
4174
+ });
4175
+ return {
4176
+ cid,
4177
+ bytes
4178
+ };
4179
+ };
4180
+ const slotsByName = /* @__PURE__ */ new Map();
4181
+ const slotsOf = async (name) => {
4182
+ let slots = slotsByName.get(name);
4183
+ if (!slots) {
4184
+ slots = (await murmur3128.encode(textEncoder$1.encode(name))).subarray(0, HAMT_MAX_DEPTH);
4185
+ slotsByName.set(name, slots);
4186
+ }
4187
+ return slots;
4188
+ };
4189
+ const slotAt = async (name, depth) => {
4190
+ if (depth >= HAMT_MAX_DEPTH) throw Error(`The HAMT is deeper than ${HAMT_MAX_DEPTH} levels at entry ${name}`);
4191
+ return (await slotsOf(name))[depth];
4192
+ };
4193
+ const loadShard = async (shard) => {
4194
+ if (shard.loaded) return;
4195
+ shard.loading ??= (async () => {
4196
+ const stored = shard.stored;
4197
+ const node = decode$1(await getBlock(stored.cid));
4198
+ readHamtShardMetadata(node, stored.cid);
4199
+ for (const link of node.Links) {
4200
+ const linkName = link.Name ?? "";
4201
+ const slot = parseInt(linkName.slice(0, HAMT_SLOT_PREFIX_LENGTH), 16);
4202
+ if (linkName.length < HAMT_SLOT_PREFIX_LENGTH || !Number.isInteger(slot)) throw Error(`HAMT shard ${stored.cid.toString()} has a link without a slot prefix: "${linkName}"`);
4203
+ const child = {
4204
+ cid: CID.decode(link.Hash.bytes),
4205
+ size: link.Tsize ?? 0
4206
+ };
4207
+ shard.slots.set(slot, linkName.length === HAMT_SLOT_PREFIX_LENGTH ? new HamtShard(child) : {
4208
+ name: linkName.slice(HAMT_SLOT_PREFIX_LENGTH),
4209
+ ...child
4210
+ });
4211
+ }
4212
+ shard.loaded = true;
4213
+ })();
4214
+ await shard.loading;
4215
+ };
4216
+ const putEntry = async (shard, depth, entry) => {
4217
+ await loadShard(shard);
4218
+ const slot = await slotAt(entry.name, depth);
4219
+ const occupant = shard.slots.get(slot);
4220
+ if (occupant instanceof HamtShard) {
4221
+ if (!await putEntry(occupant, depth + 1, entry)) return false;
4222
+ } else if (!occupant || occupant.name === entry.name) {
4223
+ if (occupant && occupant.cid.equals(entry.cid) && occupant.size === entry.size) return false;
4224
+ shard.slots.set(slot, entry);
4225
+ } else {
4226
+ const subShard = new HamtShard();
4227
+ await putEntry(subShard, depth + 1, occupant);
4228
+ await putEntry(subShard, depth + 1, entry);
4229
+ shard.slots.set(slot, subShard);
4230
+ }
4231
+ shard.stored = void 0;
4232
+ return true;
4233
+ };
4234
+ const removeEntry = async (shard, depth, name) => {
4235
+ await loadShard(shard);
4236
+ const slot = await slotAt(name, depth);
4237
+ const occupant = shard.slots.get(slot);
4238
+ if (!occupant) return false;
4239
+ if (occupant instanceof HamtShard) {
4240
+ if (!await removeEntry(occupant, depth + 1, name)) return false;
4241
+ if (occupant.slots.size === 0) shard.slots.delete(slot);
4242
+ else if (occupant.slots.size === 1) {
4243
+ const [onlyOccupant] = occupant.slots.values();
4244
+ if (!(onlyOccupant instanceof HamtShard)) shard.slots.set(slot, onlyOccupant);
4245
+ }
4246
+ } else {
4247
+ if (occupant.name !== name) return false;
4248
+ shard.slots.delete(slot);
4249
+ }
4250
+ shard.stored = void 0;
4251
+ return true;
4252
+ };
4253
+ const storeShard = async (shard, metadata) => {
4254
+ if (shard.stored) return shard.stored;
4255
+ const links = [];
4256
+ let highestSlot = -1;
4257
+ for (const slot of shard.slots.keys()) if (slot > highestSlot) highestSlot = slot;
4258
+ const bitfield = new Uint8Array(highestSlot < 0 ? 0 : (highestSlot >> 3) + 1);
4259
+ let linkedSize = 0;
4260
+ for (const [slot, occupant] of shard.slots) {
4261
+ bitfield[bitfield.length - 1 - (slot >> 3)] |= 1 << (slot & 7);
4262
+ const prefix = slot.toString(16).toUpperCase().padStart(HAMT_SLOT_PREFIX_LENGTH, "0");
4263
+ const link = occupant instanceof HamtShard ? {
4264
+ Name: prefix,
4265
+ ...await storeShard(occupant)
4266
+ } : {
4267
+ Name: prefix + occupant.name,
4268
+ cid: occupant.cid,
4269
+ size: occupant.size
4270
+ };
4271
+ links.push({
4272
+ Name: link.Name,
4273
+ Hash: link.cid,
4274
+ Tsize: link.size
4275
+ });
4276
+ linkedSize += link.size;
4277
+ }
4278
+ const { cid, bytes } = await storeNode({
4279
+ Data: new UnixFS({
4280
+ type: "hamt-sharded-directory",
4281
+ data: bitfield,
4282
+ fanout: HAMT_FANOUT,
4283
+ hashType: HAMT_HASH_TYPE_MURMUR3_X64_64,
4284
+ mode: metadata?.mode,
4285
+ mtime: metadata?.mtime
4286
+ }).marshal(),
4287
+ Links: links
4288
+ });
4289
+ shard.stored = {
4290
+ cid,
4291
+ size: bytes.length + linkedSize
4292
+ };
4293
+ return shard.stored;
4294
+ };
4295
+ const loadShardsOnPathsOf = async (root, names) => {
4296
+ const limit = pLimit(SHARD_FETCH_CONCURRENCY);
4297
+ await Promise.all(names.map((name) => limit(async () => {
4298
+ let shard = root;
4299
+ for (let depth = 0; depth < HAMT_MAX_DEPTH; depth++) {
4300
+ await loadShard(shard);
4301
+ const occupant = shard.slots.get(await slotAt(name, depth));
4302
+ if (!(occupant instanceof HamtShard)) return;
4303
+ shard = occupant;
4304
+ }
4305
+ })));
4306
+ };
4307
+ const patchHamt = async (root, metadata) => {
4308
+ await loadShardsOnPathsOf(root, [...namesToRemove, ...entriesToPut.map((entry) => entry.name)]);
4309
+ for (const name of namesToRemove) await removeEntry(root, 0, name);
4310
+ for (const entry of entriesToPut) await putEntry(root, 0, entry);
4311
+ return (await storeShard(root, metadata)).cid;
4312
+ };
4313
+ const entries = /* @__PURE__ */ new Map();
4314
+ let metadata = {};
4315
+ if (directoryCid) {
4316
+ const node = decode$1(await getBlock(directoryCid));
4317
+ if (!node.Data) throw Error(`Expected a UnixFS directory at ${directoryCid.toString()}, got a node without data`);
4318
+ const unixfs = UnixFS.unmarshal(node.Data);
4319
+ metadata = {
4320
+ mode: unixfs.mode,
4321
+ mtime: unixfs.mtime
4322
+ };
4323
+ if (unixfs.type === "hamt-sharded-directory") return {
4324
+ cid: await patchHamt(new HamtShard({
4325
+ cid: directoryCid,
4326
+ size: 0
4327
+ }), metadata),
4328
+ newBlocks
4329
+ };
4330
+ if (unixfs.type !== "directory") throw Error(`Expected a UnixFS directory at ${directoryCid.toString()}, got ${unixfs.type}`);
4331
+ for (const link of node.Links) {
4332
+ const name = link.Name ?? "";
4333
+ entries.set(name, {
4334
+ name,
4335
+ cid: CID.decode(link.Hash.bytes),
4336
+ size: link.Tsize ?? 0
4337
+ });
4338
+ }
4339
+ }
4340
+ let changed = directoryCid === void 0;
4341
+ for (const name of namesToRemove) if (entries.delete(name)) changed = true;
4342
+ for (const entry of entriesToPut) {
4343
+ const existing = entries.get(entry.name);
4344
+ if (existing && existing.cid.equals(entry.cid) && existing.size === entry.size) continue;
4345
+ entries.set(entry.name, entry);
4346
+ changed = true;
4347
+ }
4348
+ if (!changed) return {
4349
+ cid: directoryCid,
4350
+ newBlocks
4351
+ };
4352
+ let linksBytes = 0;
4353
+ for (const entry of entries.values()) linksBytes += textEncoder$1.encode(entry.name).length + entry.cid.bytes.length;
4354
+ if (linksBytes > shardSplitThresholdBytes) {
4355
+ const root = new HamtShard();
4356
+ for (const entry of entries.values()) await putEntry(root, 0, entry);
4357
+ return {
4358
+ cid: (await storeShard(root, metadata)).cid,
4359
+ newBlocks
4360
+ };
4361
+ }
4362
+ const { cid } = await storeNode({
4363
+ Data: new UnixFS({
4364
+ type: "directory",
4365
+ mode: metadata.mode,
4366
+ mtime: metadata.mtime
4367
+ }).marshal(),
4368
+ Links: [...entries.values()].map((entry) => ({
4369
+ Name: entry.name,
4370
+ Hash: entry.cid,
4371
+ Tsize: entry.size
4372
+ }))
4373
+ });
4374
+ return {
4375
+ cid,
4376
+ newBlocks
4377
+ };
4378
+ }
4379
+ function readHamtShardMetadata(node, cid) {
4380
+ if (!node.Data) throw Error(`Expected a HAMT shard at ${cid.toString()}, got a node without data`);
4381
+ const unixfs = UnixFS.unmarshal(node.Data);
4382
+ if (unixfs.type !== "hamt-sharded-directory") throw Error(`Expected a HAMT shard at ${cid.toString()}, got ${unixfs.type}`);
4383
+ if (unixfs.fanout !== HAMT_FANOUT) throw Error(`HAMT shard ${cid.toString()} has fanout ${unixfs.fanout}, only ${HAMT_FANOUT} is supported`);
4384
+ return unixfs;
4385
+ }
4386
+ //#endregion
4147
4387
  //#region dist/node/runtime/node/community/local-community/post-updates-bucket.js
4148
4388
  const MFS_OP_TIMEOUT_MS = 600 * 1e3;
4149
4389
  const MFS_SHARD_SPLIT_THRESHOLD_BYTES = 256 * 1024;
4150
4390
  const POST_UPDATES_BUCKET_NEXT_SUFFIX = ".next";
4391
+ const MAX_ATTEMPTS_TO_SWAP_POST_UPDATES_BUCKET = 4;
4151
4392
  const isAbsentPathError = (error) => error instanceof Error && error.message.includes("file does not exist");
4152
4393
  async function statMfsPathOrUndefined(kuboRpcClient, path, log) {
4153
4394
  try {
@@ -4161,38 +4402,8 @@ async function statMfsPathOrUndefined(kuboRpcClient, path, log) {
4161
4402
  throw error;
4162
4403
  }
4163
4404
  }
4164
- async function listUnixFsDirectoryLinks(kubo, directoryCid) {
4165
- const { UnixFS } = await import("./src-BC60-Q7v.js");
4166
- const links = [];
4167
- const walk = async (cid) => {
4168
- const node = (await kubo.dag.get(cid, { timeout: MFS_OP_TIMEOUT_MS })).value;
4169
- if (!isPbNode(node)) throw Error(`Expected a dag-pb directory node at ${cid.toString()}`);
4170
- const unixfs = UnixFS.unmarshal(node.Data);
4171
- if (unixfs.type === "hamt-sharded-directory") {
4172
- const prefixLength = Math.max(1, Math.ceil(Math.log2(Number(unixfs.fanout ?? 256)) / 4));
4173
- for (const link of node.Links) if (link.Name.length === prefixLength) await walk(link.Hash);
4174
- else links.push({
4175
- name: link.Name.slice(prefixLength),
4176
- cid: link.Hash,
4177
- size: BigInt(link.Tsize ?? 0)
4178
- });
4179
- } else if (unixfs.type === "directory") for (const link of node.Links) links.push({
4180
- name: link.Name,
4181
- cid: link.Hash,
4182
- size: BigInt(link.Tsize ?? 0)
4183
- });
4184
- else throw Error(`Expected a UnixFS directory at ${cid.toString()}, got ${unixfs.type}`);
4185
- };
4186
- await walk(directoryCid);
4187
- return links;
4188
- }
4189
- function isPbNode(value) {
4190
- if (typeof value !== "object" || value === null) return false;
4191
- const node = value;
4192
- return node.Data instanceof Uint8Array && Array.isArray(node.Links) && node.Links.every((link) => typeof link?.Name === "string" && (link.Tsize === void 0 || typeof link.Tsize === "number") && link.Hash instanceof CID);
4193
- }
4194
- async function buildPostUpdatesBucketDag({ existingLinks, changedPosts }) {
4195
- const { importer } = await import("./src-Bj5iE3qB.js");
4405
+ async function buildPostUpdateFiles(posts) {
4406
+ const { importer } = await import("./src-DIOHVUq9.js");
4196
4407
  const blocks = /* @__PURE__ */ new Map();
4197
4408
  const blockstore = { put: async (cid, bytes) => {
4198
4409
  blocks.set(cid.toString(), {
@@ -4201,55 +4412,29 @@ async function buildPostUpdatesBucketDag({ existingLinks, changedPosts }) {
4201
4412
  });
4202
4413
  return cid;
4203
4414
  } };
4204
- const layoutOptions = {
4415
+ const entries = [];
4416
+ for await (const entry of importer(posts.map((post) => ({
4417
+ path: `${post.postCid}/update`,
4418
+ content: post.updateFileBytes
4419
+ })), blockstore, {
4205
4420
  profile: "unixfs-v0-2015",
4206
4421
  cidVersion: 0,
4207
4422
  rawLeaves: false,
4208
4423
  reduceSingleLeafToSelf: true,
4209
- shardSplitThresholdBytes: MFS_SHARD_SPLIT_THRESHOLD_BYTES
4210
- };
4211
- const postDirectoryLinks = /* @__PURE__ */ new Map();
4212
- for await (const entry of importer(changedPosts.map((post) => ({
4213
- path: `${post.postCid}/update`,
4214
- content: post.updateFileBytes
4215
- })), blockstore, {
4216
- ...layoutOptions,
4424
+ shardSplitThresholdBytes: MFS_SHARD_SPLIT_THRESHOLD_BYTES,
4217
4425
  wrapWithDirectory: false
4218
- })) if (entry.path && !entry.path.includes("/")) postDirectoryLinks.set(entry.path, {
4426
+ })) if (entry.path && !entry.path.includes("/")) entries.push({
4219
4427
  name: entry.path,
4220
4428
  cid: entry.cid,
4221
- size: entry.size
4429
+ size: Number(entry.size)
4222
4430
  });
4223
- if (postDirectoryLinks.size !== changedPosts.length) throw Error(`Built ${postDirectoryLinks.size} post directories for ${changedPosts.length} changed posts`);
4224
- const bucketName = "bucket";
4225
- const knownLinks = /* @__PURE__ */ new Map();
4226
- for (const link of existingLinks) knownLinks.set(`${bucketName}/${link.name}`, link);
4227
- for (const link of postDirectoryLinks.values()) knownLinks.set(`${bucketName}/${link.name}`, link);
4228
- let root;
4229
- for await (const entry of importer([...knownLinks.keys()].map((path) => ({
4230
- path,
4231
- content: new Uint8Array(0)
4232
- })), blockstore, {
4233
- ...layoutOptions,
4234
- wrapWithDirectory: false,
4235
- fileBuilder: async (file) => {
4236
- for await (const chunk of file.content);
4237
- const link = file.path ? knownLinks.get(file.path) : void 0;
4238
- if (!link) throw Error(`No known link for bucket entry ${file.path}`);
4239
- return {
4240
- cid: link.cid,
4241
- size: link.size,
4242
- path: file.path
4243
- };
4244
- }
4245
- })) if (entry.path === bucketName) root = entry.cid;
4246
- if (!root) throw Error("The rebuilt postUpdates bucket has no root");
4431
+ if (entries.length !== posts.length) throw Error(`Built ${entries.length} post directories for ${posts.length} posts`);
4247
4432
  return {
4248
- root,
4433
+ entries,
4249
4434
  blocks: [...blocks.values()]
4250
4435
  };
4251
4436
  }
4252
- async function encodeCarV1(root, blocks) {
4437
+ async function encodeCarV1(roots, blocks) {
4253
4438
  const dagCbor = await import("./src-BHqirG63.js");
4254
4439
  const varint = (value) => {
4255
4440
  const out = [];
@@ -4261,7 +4446,7 @@ async function encodeCarV1(root, blocks) {
4261
4446
  return Uint8Array.from(out);
4262
4447
  };
4263
4448
  const header = dagCbor.encode({
4264
- roots: [root],
4449
+ roots,
4265
4450
  version: 1
4266
4451
  });
4267
4452
  const parts = [varint(header.length), header];
@@ -4274,66 +4459,125 @@ async function encodeCarV1(root, blocks) {
4274
4459
  }
4275
4460
  return car;
4276
4461
  }
4462
+ const SWAP_PIN_MANIFEST_MAX_LINKS = 4e3;
4463
+ const RAW_CODEC = 85;
4464
+ async function buildSwapPinManifests({ postEntries, directoryNodes }) {
4465
+ const dagPb = await import("./src-66iuMY_4.js");
4466
+ const { sha256 } = await import("multiformats/hashes/sha2");
4467
+ const pinned = [...postEntries.map((entry) => entry.cid), ...directoryNodes.map((node) => CID.createV1(RAW_CODEC, node.cid.multihash))];
4468
+ const manifests = [];
4469
+ for (let index = 0; index < pinned.length; index += SWAP_PIN_MANIFEST_MAX_LINKS) {
4470
+ const bytes = dagPb.encode(dagPb.prepare({ Links: pinned.slice(index, index + SWAP_PIN_MANIFEST_MAX_LINKS).map((cid) => ({
4471
+ Name: "",
4472
+ Hash: cid
4473
+ })) }));
4474
+ manifests.push({
4475
+ cid: CID.createV1(dagPb.code, await sha256.digest(bytes)),
4476
+ bytes
4477
+ });
4478
+ }
4479
+ return manifests;
4480
+ }
4277
4481
  async function recoverInterruptedBucketSwap(kuboRpcClient, bucketPath, log) {
4278
4482
  const kubo = kuboRpcClient._client;
4279
4483
  const nextPath = bucketPath + POST_UPDATES_BUCKET_NEXT_SUFFIX;
4280
4484
  const next = await statMfsPathOrUndefined(kuboRpcClient, nextPath, log);
4281
4485
  let live = await statMfsPathOrUndefined(kuboRpcClient, bucketPath, log);
4282
- if (next) {
4283
- if (live) {
4284
- log(`Discarding the stale rebuilt bucket ${nextPath} left by an interrupted swap`);
4285
- await kubo.files.rm(nextPath, {
4286
- recursive: true,
4287
- timeout: MFS_OP_TIMEOUT_MS
4288
- });
4289
- } else {
4290
- log(`Finishing the interrupted swap of ${nextPath} into ${bucketPath}`);
4291
- await kubo.files.mv(nextPath, bucketPath, {
4292
- flush: true,
4293
- timeout: MFS_OP_TIMEOUT_MS
4294
- });
4295
- live = next;
4296
- }
4297
- await kubo.pin.rm(next.cid, { timeout: MFS_OP_TIMEOUT_MS }).catch(() => void 0);
4486
+ if (next) if (live) {
4487
+ log(`Discarding the stale rebuilt bucket ${nextPath} left by an interrupted swap`);
4488
+ await kubo.files.rm(nextPath, {
4489
+ recursive: true,
4490
+ timeout: MFS_OP_TIMEOUT_MS
4491
+ });
4492
+ } else {
4493
+ log(`Finishing the interrupted swap of ${nextPath} into ${bucketPath}`);
4494
+ await kubo.files.mv(nextPath, bucketPath, {
4495
+ flush: true,
4496
+ timeout: MFS_OP_TIMEOUT_MS
4497
+ });
4498
+ live = await statMfsPathOrUndefined(kuboRpcClient, bucketPath, log);
4499
+ if (!live?.cid.equals(next.cid)) throw Error(`MFS holds ${live?.cid.toString()} at ${bucketPath} after the interrupted swap of ${next.cid.toString()} was finished`);
4298
4500
  }
4299
4501
  return live;
4300
4502
  }
4301
- async function rebuildPostUpdatesBucket({ community, bucketPath, posts }) {
4302
- const log = logger_default("pkc-js:local-community:sync:rebuildPostUpdatesBucket");
4503
+ async function writePostUpdatesToBucket({ community, bucketPath, posts }) {
4504
+ const log = logger_default("pkc-js:local-community:sync:writePostUpdatesToBucket");
4303
4505
  const kuboRpcClient = community._clientsManager.getDefaultKuboRpcClient();
4304
4506
  const kubo = kuboRpcClient._client;
4305
4507
  const nextPath = bucketPath + POST_UPDATES_BUCKET_NEXT_SUFFIX;
4306
- const live = await recoverInterruptedBucketSwap(kuboRpcClient, bucketPath, log);
4307
- const changedPostCids = new Set(posts.map((post) => post.postCid));
4308
- const existingLinks = live ? (await listUnixFsDirectoryLinks(kubo, live.cid)).filter((link) => !changedPostCids.has(link.name) && community._dbHandler.commentExistsInDb(link.name)) : [];
4309
- const { root, blocks } = await buildPostUpdatesBucketDag({
4310
- existingLinks,
4311
- changedPosts: posts
4312
- });
4313
- const car = await encodeCarV1(root, blocks);
4314
- for await (const result of kubo.dag.import([car], {
4315
- pinRoots: true,
4316
- timeout: MFS_OP_TIMEOUT_MS
4317
- })) if (result.root.pinErrorMsg) throw Error(`Failed to pin the rebuilt bucket ${root.toString()}: ${result.root.pinErrorMsg}`);
4318
- log(`Built bucket ${bucketPath} in node: ${posts.length} posts written, ${existingLinks.length} kept, ${blocks.length} new blocks (${car.length} bytes), root ${root.toString()}`);
4319
- try {
4320
- await kubo.files.cp(`/ipfs/${root.toString()}`, nextPath, {
4321
- parents: true,
4322
- flush: true,
4323
- timeout: MFS_OP_TIMEOUT_MS
4508
+ const { entries, blocks: fileBlocks } = await buildPostUpdateFiles(posts);
4509
+ const bucketBlocks = /* @__PURE__ */ new Map();
4510
+ const getBlock = async (cid) => {
4511
+ const key = cid.toString();
4512
+ let bytes = bucketBlocks.get(key);
4513
+ if (!bytes) {
4514
+ bytes = await kubo.block.get(cid, { timeout: MFS_OP_TIMEOUT_MS });
4515
+ bucketBlocks.set(key, bytes);
4516
+ }
4517
+ return bytes;
4518
+ };
4519
+ let live = await recoverInterruptedBucketSwap(kuboRpcClient, bucketPath, log);
4520
+ let bucketExisted = false;
4521
+ for (let attempt = 1;; attempt++) {
4522
+ if (live) bucketExisted = true;
4523
+ else if (bucketExisted) throw new PKCError("ERR_POST_UPDATES_BUCKET_SWAP_WAS_LOST", {
4524
+ communityAddress: community.address,
4525
+ bucketPath,
4526
+ attempt
4324
4527
  });
4325
- if (live) await kubo.files.rm(bucketPath, {
4326
- recursive: true,
4327
- timeout: MFS_OP_TIMEOUT_MS
4528
+ const { cid: root, newBlocks } = await patchUnixFsDirectory({
4529
+ directoryCid: live?.cid,
4530
+ entriesToPut: entries,
4531
+ getBlock,
4532
+ shardSplitThresholdBytes: MFS_SHARD_SPLIT_THRESHOLD_BYTES
4328
4533
  });
4329
- await kubo.files.mv(nextPath, bucketPath, {
4330
- flush: true,
4331
- timeout: MFS_OP_TIMEOUT_MS
4534
+ if (live && root.equals(live.cid)) return;
4535
+ if (attempt > MAX_ATTEMPTS_TO_SWAP_POST_UPDATES_BUCKET) throw new PKCError("ERR_POST_UPDATES_BUCKET_SWAP_WAS_LOST", {
4536
+ communityAddress: community.address,
4537
+ bucketPath,
4538
+ attempts: attempt - 1,
4539
+ bucketCidInMfs: live?.cid.toString(),
4540
+ bucketCidWithThePosts: root.toString()
4332
4541
  });
4333
- } finally {
4334
- await kubo.pin.rm(root, { timeout: MFS_OP_TIMEOUT_MS }).catch((error) => log.error(`Failed to unpin the rebuilt bucket root ${root.toString()}`, error));
4542
+ for (const block of newBlocks) bucketBlocks.set(block.cid.toString(), block.bytes);
4543
+ const manifests = await buildSwapPinManifests({
4544
+ postEntries: entries,
4545
+ directoryNodes: newBlocks
4546
+ });
4547
+ const car = await encodeCarV1(manifests.map((manifest) => manifest.cid), [
4548
+ ...manifests,
4549
+ ...fileBlocks,
4550
+ ...newBlocks
4551
+ ]);
4552
+ try {
4553
+ for await (const result of kubo.dag.import([car], {
4554
+ pinRoots: true,
4555
+ timeout: MFS_OP_TIMEOUT_MS
4556
+ })) if (result.root.pinErrorMsg) throw Error(`Failed to pin the new blocks of bucket ${bucketPath} (${result.root.cid.toString()}): ${result.root.pinErrorMsg}`);
4557
+ log(`Bucket ${bucketPath}: ${posts.length} posts written, ${newBlocks.length} of the bucket's nodes rebuilt (${car.length} bytes imported), root ${root.toString()}`);
4558
+ await kubo.files.cp(`/ipfs/${root.toString()}`, nextPath, {
4559
+ parents: true,
4560
+ flush: true,
4561
+ timeout: MFS_OP_TIMEOUT_MS
4562
+ });
4563
+ if (live) await kubo.files.rm(bucketPath, {
4564
+ recursive: true,
4565
+ timeout: MFS_OP_TIMEOUT_MS
4566
+ });
4567
+ await kubo.files.mv(nextPath, bucketPath, {
4568
+ flush: true,
4569
+ timeout: MFS_OP_TIMEOUT_MS
4570
+ });
4571
+ } finally {
4572
+ for (const manifest of manifests) await kubo.pin.rm(manifest.cid, { timeout: MFS_OP_TIMEOUT_MS }).catch((error) => {
4573
+ if (!(error instanceof Error && error.message.includes("not pinned"))) log.error(`Failed to unpin ${manifest.cid.toString()}, which pinned the new blocks of bucket ${bucketPath}`, error);
4574
+ });
4575
+ }
4576
+ const swapped = await statMfsPathOrUndefined(kuboRpcClient, bucketPath, log);
4577
+ if (swapped?.cid.equals(root)) return;
4578
+ log.error(`Bucket ${bucketPath} is ${swapped?.cid.toString()} in MFS after ${root.toString()} was swapped in (attempt ${attempt}), checking it for the posts' files`);
4579
+ live = await recoverInterruptedBucketSwap(kuboRpcClient, bucketPath, log);
4335
4580
  }
4336
- return { keptPostCids: existingLinks.map((link) => link.name) };
4337
4581
  }
4338
4582
  //#endregion
4339
4583
  //#region dist/node/runtime/node/community/local-community/comment-updates.js
@@ -4493,7 +4737,6 @@ async function writePostUpdatesToMfs(community, postCommentUpdateRows) {
4493
4737
  if (purgedMidSyncCount > 0) log(`Skipping ${purgedMidSyncCount} post CommentUpdate(s) for community ${community.address} whose comment was purged mid-sync`);
4494
4738
  const kuboRpc = community._clientsManager.getDefaultKuboRpcClient();
4495
4739
  await rmUnneededMfsPaths(community);
4496
- let postUpdatesDirectoryCid;
4497
4740
  const rowsByBucketPath = /* @__PURE__ */ new Map();
4498
4741
  for (const row of liveCommentUpdates) {
4499
4742
  const bucket = row.newCommentUpdateToWriteToDb.postUpdatesBucket;
@@ -4503,14 +4746,10 @@ async function writePostUpdatesToMfs(community, postCommentUpdateRows) {
4503
4746
  if (bucketRows) bucketRows.push(row);
4504
4747
  else rowsByBucketPath.set(bucketPath, [row]);
4505
4748
  }
4506
- const rowsToWriteOneByOne = [];
4507
- const keptPostsByRebuiltBucket = [];
4508
- for (const [bucketPath, rows] of rowsByBucketPath) {
4509
- if (rows.length < community._postUpdatesNodeBuiltBucketMinPosts) {
4510
- rowsToWriteOneByOne.push(...rows);
4511
- continue;
4512
- }
4513
- const { keptPostCids } = await rebuildPostUpdatesBucket({
4749
+ const mfsPathsRemovedDuringWrites = new Set(community._mfsPathsToRemove);
4750
+ community._mfsPathRemovalWatchers.add(mfsPathsRemovedDuringWrites);
4751
+ try {
4752
+ for (const [bucketPath, rows] of rowsByBucketPath) await writePostUpdatesToBucket({
4514
4753
  community,
4515
4754
  bucketPath,
4516
4755
  posts: rows.map((row) => ({
@@ -4518,40 +4757,18 @@ async function writePostUpdatesToMfs(community, postCommentUpdateRows) {
4518
4757
  updateFileBytes: textEncoder.encode(stringify(row.newCommentUpdate))
4519
4758
  }))
4520
4759
  });
4521
- keptPostsByRebuiltBucket.push({
4522
- bucketPath,
4523
- keptPostCids
4524
- });
4525
- }
4526
- const BATCH_SIZE = 50;
4527
- for (let index = 0; index < rowsToWriteOneByOne.length; index += BATCH_SIZE) {
4528
- const batch = rowsToWriteOneByOne.slice(index, index + BATCH_SIZE);
4529
- await Promise.all(batch.map(async (row) => {
4530
- const { localMfsPath, newCommentUpdate } = row;
4531
- const content = stringify(newCommentUpdate);
4532
- await writeKuboFilesWithTimeout({
4533
- ipfsClient: kuboRpc._client,
4534
- log,
4535
- path: localMfsPath,
4536
- content,
4537
- options: {
4538
- create: true,
4539
- truncate: true,
4540
- parents: true,
4541
- flush: false
4542
- }
4543
- });
4544
- }));
4545
- postUpdatesDirectoryCid = await kuboRpc._client.files.flush(postUpdatesDirectory);
4760
+ } finally {
4761
+ community._mfsPathRemovalWatchers.delete(mfsPathsRemovedDuringWrites);
4546
4762
  }
4547
- if (rowsToWriteOneByOne.length === 0 && keptPostsByRebuiltBucket.length > 0) postUpdatesDirectoryCid = await kuboRpc._client.files.flush(postUpdatesDirectory);
4548
- const mfsPathsPurgedDuringWrites = [...liveCommentUpdates.filter((row) => !community._dbHandler.commentExistsInDb(row.newCommentUpdate.cid)).map((row) => row.localMfsPath), ...keptPostsByRebuiltBucket.flatMap(({ bucketPath, keptPostCids }) => keptPostCids.filter((postCid) => !community._dbHandler.commentExistsInDb(postCid)).map((postCid) => `${bucketPath}/${postCid}`))];
4763
+ const writtenMfsPaths = new Set(liveCommentUpdates.filter((row) => community._dbHandler.commentExistsInDb(row.newCommentUpdate.cid)).map((row) => row.localMfsPath));
4764
+ const swappedBucketPaths = [...rowsByBucketPath.keys()];
4765
+ const mfsPathsPurgedDuringWrites = [...liveCommentUpdates.filter((row) => !community._dbHandler.commentExistsInDb(row.newCommentUpdate.cid)).map((row) => row.localMfsPath), ...[...mfsPathsRemovedDuringWrites].filter((mfsPath) => swappedBucketPaths.some((bucketPath) => mfsPath.startsWith(`${bucketPath}/`)) && !writtenMfsPaths.has(mfsPath) && !writtenMfsPaths.has(`${mfsPath}/update`)).map((mfsPath) => mfsPath.replace(/\/update$/, ""))];
4549
4766
  if (mfsPathsPurgedDuringWrites.length > 0) {
4550
4767
  log(`${mfsPathsPurgedDuringWrites.length} post CommentUpdate(s) of community ${community.address} were purged during the MFS writes. Removing their MFS entries`);
4551
4768
  for (const mfsPath of mfsPathsPurgedDuringWrites) community._mfsPathsToRemove.add(mfsPath);
4552
4769
  await rmUnneededMfsPaths(community);
4553
- postUpdatesDirectoryCid = await kuboRpc._client.files.flush(postUpdatesDirectory);
4554
4770
  }
4771
+ const postUpdatesDirectoryCid = liveCommentUpdates.length > 0 ? await kuboRpc._client.files.flush(postUpdatesDirectory) : void 0;
4555
4772
  log("Community", community.address, "Synced", liveCommentUpdates.length, "post CommentUpdates", "with MFS postUpdates directory", postUpdatesDirectoryCid?.toString());
4556
4773
  return liveCommentUpdates.length;
4557
4774
  }
@@ -4666,6 +4883,7 @@ async function rmUnneededMfsPaths(community, opts) {
4666
4883
  if (community._mfsPathsToRemove.size > 0) {
4667
4884
  const toDeleteMfsPaths = Array.from(community._mfsPathsToRemove.values());
4668
4885
  const kuboRpc = community._clientsManager.getDefaultKuboRpcClient();
4886
+ for (const watcher of community._mfsPathRemovalWatchers) for (const path of toDeleteMfsPaths) watcher.add(path);
4669
4887
  try {
4670
4888
  await removeMfsFilesSafely({
4671
4889
  kuboRpcClient: kuboRpc,
@@ -7321,9 +7539,9 @@ async function restartCommunityAfterFailedRename({ community, oldAddress, newAdd
7321
7539
  }
7322
7540
  }
7323
7541
  async function removePartialDbCopy({ community, oldAddress, newAddress, log }) {
7324
- const communitiesPath = Path.join(community._pkc.dataPath, "communities");
7325
- const partialDbCopyPath = Path.join(communitiesPath, newAddress);
7326
- if (!fs.existsSync(Path.join(communitiesPath, oldAddress))) return {
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 {
7327
7545
  removed: false,
7328
7546
  path: partialDbCopyPath
7329
7547
  };
@@ -7340,7 +7558,7 @@ async function removePartialDbCopy({ community, oldAddress, newAddress, log }) {
7340
7558
  }
7341
7559
  }
7342
7560
  async function undoRenameAfterDbRenameFailed({ community, oldAddress, newAddress, dbRenameError, log }) {
7343
- const communitiesPath = Path.join(community._pkc.dataPath, "communities");
7561
+ const communitiesPath = path.join(community._pkc.dataPath, "communities");
7344
7562
  const partialDbCopy = await removePartialDbCopy({
7345
7563
  community,
7346
7564
  oldAddress,
@@ -7358,8 +7576,8 @@ async function undoRenameAfterDbRenameFailed({ community, oldAddress, newAddress
7358
7576
  error: new PKCError("ERR_FAILED_TO_RENAME_COMMUNITY_DB", {
7359
7577
  oldAddress,
7360
7578
  newAddress,
7361
- oldDbPath: Path.join(communitiesPath, oldAddress),
7362
- newDbPath: Path.join(communitiesPath, newAddress),
7579
+ oldDbPath: path.join(communitiesPath, oldAddress),
7580
+ newDbPath: path.join(communitiesPath, newAddress),
7363
7581
  error: dbRenameError,
7364
7582
  errorMessage: renameError?.message,
7365
7583
  errorName: renameError?.name,
@@ -7542,11 +7760,11 @@ async function edit(community, newCommunityOptions) {
7542
7760
  const EXPORTS_KEY = STORAGE_KEYS[STORAGE_KEYS.EXPORTS];
7543
7761
  function defaultExportPathFor(community, exportId) {
7544
7762
  if (typeof community._pkc.dataPath !== "string") throw new PKCError("ERR_DATA_PATH_IS_NOT_DEFINED", { communityAddress: community.address });
7545
- return Path.join(community._pkc.dataPath, "exports", `${exportId}.sqlite`);
7763
+ return path.join(community._pkc.dataPath, "exports", `${exportId}.sqlite`);
7546
7764
  }
7547
7765
  function sourceDbPathFor(community) {
7548
7766
  if (typeof community._pkc.dataPath !== "string") throw new PKCError("ERR_DATA_PATH_IS_NOT_DEFINED", { communityAddress: community.address });
7549
- return Path.join(community._pkc.dataPath, "communities", community.address);
7767
+ return path.join(community._pkc.dataPath, "communities", community.address);
7550
7768
  }
7551
7769
  async function persistExports(community) {
7552
7770
  if (!community._dbHandler) return;
@@ -7622,9 +7840,9 @@ async function runExportTask(community, exportId, opts) {
7622
7840
  async function exportCommunityEmbedded(community, options = {}) {
7623
7841
  if (options.signal?.aborted) throw options.signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
7624
7842
  const exportId = v4();
7625
- const destPath = options.exportPath ? Path.resolve(options.exportPath) : defaultExportPathFor(community, exportId);
7843
+ const destPath = options.exportPath ? path.resolve(options.exportPath) : defaultExportPathFor(community, exportId);
7626
7844
  const includePrivateKey = options.includePrivateKey === true;
7627
- if (Path.resolve(destPath) === Path.resolve(sourceDbPathFor(community))) throw new PKCError("ERR_EXPORT_PATH_TARGETS_LIVE_DB", {
7845
+ if (path.resolve(destPath) === path.resolve(sourceDbPathFor(community))) throw new PKCError("ERR_EXPORT_PATH_TARGETS_LIVE_DB", {
7628
7846
  communityAddress: community.address,
7629
7847
  exportPath: destPath
7630
7848
  });
@@ -7746,7 +7964,6 @@ var LocalCommunity = class extends RpcLocalCommunity {
7746
7964
  2592e3,
7747
7965
  31536e5
7748
7966
  ];
7749
- this._postUpdatesNodeBuiltBucketMinPosts = 200;
7750
7967
  this._defaultCommunityChallenges = generateDefaultChallenges();
7751
7968
  this._challengeExchangesFromLocalPublishers = {};
7752
7969
  this._inFlightPublicationExchanges = /* @__PURE__ */ new Map();
@@ -7755,6 +7972,7 @@ var LocalCommunity = class extends RpcLocalCommunity {
7755
7972
  this._slowGetChallengeWarningMs = SLOW_GET_CHALLENGE_WARNING_MS;
7756
7973
  this._cidsToUnPin = /* @__PURE__ */ new Set();
7757
7974
  this._mfsPathsToRemove = /* @__PURE__ */ new Set();
7975
+ this._mfsPathRemovalWatchers = /* @__PURE__ */ new Set();
7758
7976
  this._communityUpdateTriggerValue = false;
7759
7977
  this._updateTriggerGeneration = 0;
7760
7978
  this._combinedHashOfPendingCommentsCids = (0, import_sha256.sha256)("");