@pkcprotocol/pkc-js 0.0.149 → 0.0.151

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 (86) 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 +85 -11
  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/pkc.js +19 -5
  12. package/dist/browser/pkc/pkc.js.map +1 -1
  13. package/dist/browser/pkc-error.d.ts +1 -1
  14. package/dist/browser/publications/comment/comment.d.ts +3 -1
  15. package/dist/browser/publications/comment/comment.js +40 -28
  16. package/dist/browser/publications/comment/comment.js.map +1 -1
  17. package/dist/browser/runtime/node/community/local-community/cleanup.js +3 -0
  18. package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
  19. package/dist/browser/runtime/node/community/local-community/comment-updates.js +30 -62
  20. package/dist/browser/runtime/node/community/local-community/comment-updates.js.map +1 -1
  21. package/dist/browser/runtime/node/community/local-community/post-updates-bucket.d.ts +7 -5
  22. package/dist/browser/runtime/node/community/local-community/post-updates-bucket.js +122 -121
  23. package/dist/browser/runtime/node/community/local-community/post-updates-bucket.js.map +1 -1
  24. package/dist/browser/runtime/node/community/local-community/unixfs-directory-patch.d.ts +20 -0
  25. package/dist/browser/runtime/node/community/local-community/unixfs-directory-patch.js +231 -0
  26. package/dist/browser/runtime/node/community/local-community/unixfs-directory-patch.js.map +1 -0
  27. package/dist/browser/runtime/node/community/local-community.d.ts +1 -1
  28. package/dist/browser/runtime/node/community/local-community.js +3 -4
  29. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  30. package/dist/browser/util.d.ts +1 -12
  31. package/dist/browser/util.js +0 -53
  32. package/dist/browser/util.js.map +1 -1
  33. package/dist/bundled/bundle-manifest.json +122 -108
  34. package/dist/bundled/challenges.js +1 -1
  35. package/dist/bundled/chunks/{helia-for-pkc-8iett8xl.js → helia-for-pkc-C86lDfh5.js} +62 -12
  36. package/dist/bundled/chunks/{local-community-ChZZa9bm.js → local-community-DKZRsY97.js} +1 -1
  37. package/dist/bundled/chunks/{local-community-BlBIYSsF.js → local-community-k_ETfr57.js} +374 -156
  38. package/dist/bundled/chunks/{node-BH_HrtON.js → node-Br5aH83u.js} +43 -26
  39. package/dist/bundled/chunks/{page-sort-scoring-NpdjWYfa.js → page-sort-scoring-DK29vmN0.js} +1 -1
  40. package/dist/bundled/chunks/{rpc-local-community-Byj5ZmMa.js → rpc-local-community-Cfc2G6NP.js} +3 -3
  41. package/dist/bundled/chunks/src-66iuMY_4.js +2 -0
  42. package/dist/bundled/chunks/{src-evzEHW9W.js → src-BSYNGtIQ.js} +2 -44
  43. package/dist/bundled/chunks/{src-CNab3O7M.js → src-CAvdjq_i.js} +2 -2
  44. package/dist/bundled/chunks/{src-Bj5iE3qB.js → src-DIOHVUq9.js} +5 -4
  45. package/dist/bundled/chunks/src-DeIT_BDx.js +44 -0
  46. package/dist/bundled/chunks/{src-ltPxiZKf.js → src-NvrGEL7T.js} +2 -1
  47. package/dist/bundled/chunks/{util-CUZ1U2Go.js → util-Bmd1e0QJ.js} +4 -45
  48. package/dist/bundled/chunks/{util-DmmLFRbV.js → util-XNoDQ4hb.js} +19 -7
  49. package/dist/bundled/chunks/{validate-package-factories-CkU4qFQx.js → validate-package-factories-evt2DaRs.js} +2 -2
  50. package/dist/bundled/index.js +1 -1
  51. package/dist/bundled/page-sorts.js +1 -1
  52. package/dist/bundled/rpc/src/index.js +4 -4
  53. package/dist/node/errors.d.ts +1 -0
  54. package/dist/node/errors.js +1 -0
  55. package/dist/node/errors.js.map +1 -1
  56. package/dist/node/generated-version.d.ts +1 -1
  57. package/dist/node/generated-version.js +1 -1
  58. package/dist/node/helia/helia-for-pkc.js +85 -11
  59. package/dist/node/helia/helia-for-pkc.js.map +1 -1
  60. package/dist/node/helia/util.d.ts +3 -2
  61. package/dist/node/helia/util.js +17 -7
  62. package/dist/node/helia/util.js.map +1 -1
  63. package/dist/node/pkc/pkc.js +19 -5
  64. package/dist/node/pkc/pkc.js.map +1 -1
  65. package/dist/node/pkc-error.d.ts +1 -1
  66. package/dist/node/publications/comment/comment.d.ts +3 -1
  67. package/dist/node/publications/comment/comment.js +40 -28
  68. package/dist/node/publications/comment/comment.js.map +1 -1
  69. package/dist/node/runtime/node/community/local-community/cleanup.js +3 -0
  70. package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
  71. package/dist/node/runtime/node/community/local-community/comment-updates.js +30 -62
  72. package/dist/node/runtime/node/community/local-community/comment-updates.js.map +1 -1
  73. package/dist/node/runtime/node/community/local-community/post-updates-bucket.d.ts +7 -5
  74. package/dist/node/runtime/node/community/local-community/post-updates-bucket.js +122 -121
  75. package/dist/node/runtime/node/community/local-community/post-updates-bucket.js.map +1 -1
  76. package/dist/node/runtime/node/community/local-community/unixfs-directory-patch.d.ts +20 -0
  77. package/dist/node/runtime/node/community/local-community/unixfs-directory-patch.js +231 -0
  78. package/dist/node/runtime/node/community/local-community/unixfs-directory-patch.js.map +1 -0
  79. package/dist/node/runtime/node/community/local-community.d.ts +1 -1
  80. package/dist/node/runtime/node/community/local-community.js +3 -4
  81. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  82. package/dist/node/util.d.ts +1 -12
  83. package/dist/node/util.js +0 -53
  84. package/dist/node/util.js.map +1 -1
  85. package/package.json +3 -1
  86. package/dist/bundled/chunks/src-BC60-Q7v.js +0 -2
@@ -1,7 +1,9 @@
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-Bmd1e0QJ.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-Cfc2G6NP.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-DK29vmN0.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
8
  import Path from "node:path";
7
9
  import os from "os";
@@ -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);
@@ -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,
@@ -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)("");