@pkcprotocol/pkc-js 0.0.143 → 0.0.144

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 (49) hide show
  1. package/dist/browser/clients/base-client-manager.d.ts +7 -1
  2. package/dist/browser/clients/base-client-manager.js +106 -28
  3. package/dist/browser/clients/base-client-manager.js.map +1 -1
  4. package/dist/browser/community/community-client-manager.js +40 -24
  5. package/dist/browser/community/community-client-manager.js.map +1 -1
  6. package/dist/browser/generated-version.d.ts +1 -1
  7. package/dist/browser/generated-version.js +1 -1
  8. package/dist/browser/pkc/pkc.d.ts +2 -1
  9. package/dist/browser/pkc/pkc.js +12 -2
  10. package/dist/browser/pkc/pkc.js.map +1 -1
  11. package/dist/browser/publications/comment/comment-client-manager.js +5 -2
  12. package/dist/browser/publications/comment/comment-client-manager.js.map +1 -1
  13. package/dist/browser/publications/comment/comment.js +4 -1
  14. package/dist/browser/publications/comment/comment.js.map +1 -1
  15. package/dist/browser/util/inflight-fetch-manager.d.ts +7 -2
  16. package/dist/browser/util/inflight-fetch-manager.js +49 -7
  17. package/dist/browser/util/inflight-fetch-manager.js.map +1 -1
  18. package/dist/bundled/bundle-manifest.json +40 -40
  19. package/dist/bundled/challenges.js +1 -1
  20. package/dist/bundled/chunks/{helia-for-pkc-DpsMZzv8.js → helia-for-pkc--Xw7hTTu.js} +2 -2
  21. package/dist/bundled/chunks/{local-community-DEaDtekb.js → local-community-CH8vMgTr.js} +1 -1
  22. package/dist/bundled/chunks/{local-community-BglT8AUy.js → local-community-DCVtQSci.js} +3 -3
  23. package/dist/bundled/chunks/{node-Tkx_TCqE.js → node-Coyk7lC6.js} +13 -10
  24. package/dist/bundled/chunks/{page-sort-scoring-DY7SvqJA.js → page-sort-scoring-DaW6urZ2.js} +1 -1
  25. package/dist/bundled/chunks/{rpc-local-community-Br_xomgn.js → rpc-local-community-KgRrTYjv.js} +139 -52
  26. package/dist/bundled/chunks/{util-C5RiQF_G.js → util-BYT-7zVn.js} +1 -1
  27. package/dist/bundled/chunks/{util-DIkZirPy.js → util-DN7FMpHT.js} +1 -1
  28. package/dist/bundled/chunks/{validate-package-factories-DnW2JiL5.js → validate-package-factories-CPVyODKw.js} +2 -2
  29. package/dist/bundled/index.js +1 -1
  30. package/dist/bundled/page-sorts.js +1 -1
  31. package/dist/bundled/rpc/src/index.js +4 -4
  32. package/dist/node/clients/base-client-manager.d.ts +7 -1
  33. package/dist/node/clients/base-client-manager.js +106 -28
  34. package/dist/node/clients/base-client-manager.js.map +1 -1
  35. package/dist/node/community/community-client-manager.js +40 -24
  36. package/dist/node/community/community-client-manager.js.map +1 -1
  37. package/dist/node/generated-version.d.ts +1 -1
  38. package/dist/node/generated-version.js +1 -1
  39. package/dist/node/pkc/pkc.d.ts +2 -1
  40. package/dist/node/pkc/pkc.js +12 -2
  41. package/dist/node/pkc/pkc.js.map +1 -1
  42. package/dist/node/publications/comment/comment-client-manager.js +5 -2
  43. package/dist/node/publications/comment/comment-client-manager.js.map +1 -1
  44. package/dist/node/publications/comment/comment.js +4 -1
  45. package/dist/node/publications/comment/comment.js.map +1 -1
  46. package/dist/node/util/inflight-fetch-manager.d.ts +7 -2
  47. package/dist/node/util/inflight-fetch-manager.js +49 -7
  48. package/dist/node/util/inflight-fetch-manager.js.map +1 -1
  49. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { i as __toESM, n as __exportAll, r as __require, t as __commonJSMin } from "./chunk-2rV9d50f.js";
2
- import { $n as CommentEditSignedPropertyNames, $r as record, $t as CommunityEditPubsubMessagePublicationSchema, A as isIpnsPath, An as CommentChallengeRequestToEncryptSchema, Ar as t$9, At as pTimeout, B as pubsubTopicToDhtKey, Bn as CommentUpdateSchema, Br as logger_default, C as hideClassPrivateProps, Cn as RpcRemoteCommunityUpdateEventResultSchema, Cr as e$5, D as isIpfsCid, Dr as n$8, Dt as untrackUpdatingCommunity, E as isAbortError, En as VotePubsubMessagePublicationSchema, Er as t$12, Fn as CommentSignedPropertyNames, Fr as FailedToFetchCommunityFromGatewaysError, Gn as GetPageParamSchema, Gr as array, Gt as NameResolverSerializedSchema, H as raceAgainstAbort, Hr as require_ms$1, Ht as DecryptedChallengeSchema, In as CommentUpdateChallengeReservedFieldNames, Ir as FailedToFetchGenericIpfsFromGatewaysError, It as ChallengeRequestMessageSignedPropertyNames, Jn as isReservedObjectKey, Jr as literal, Jt as PKCUserOptionsSchema, Kn as ModQueuePageIpfsSchema, Kr as boolean, Kt as PKCParsedOptionsSchema, L as isRequestPubsubPublicationOfPost, Lr as FailedToFetchPageIpfsFromGatewaysError, Mn as CommentIpfsSchema, Mr as require_retry$2, Mt as ChallengeAnswerMessageSignedPropertyNames, Nr as FailedToFetchCommentIpfsFromGatewaysError, O as isIpfsPath, On as VoteSignedPropertyNames, Or as r$7, Ot as require_sha256$1, Pn as CommentPubsubMessageWithFlexibleAuthorRefinementSchema, Pr as FailedToFetchCommentUpdateFromGatewaysError, Pt as ChallengeMessageSignedPropertyNames, Qr as preprocess, Qt as CommunityEditPublicationSignedPropertyNames, R as isRequestPubsubPublicationOfReply, Rn as CommentUpdateForChallengeVerificationSignedPropertyNames, Rr as PKCError, Rt as ChallengeVerificationMessageSignedPropertyNames, S as hasTransientNetworkErrorCode, Sr as e$6, St as trackStartedCommunity, T as ipnsNameToIpnsOverPubsubTopic, Tn as VoteChallengeRequestToEncryptSchema, Tr as r$8, Tt as untrackStartedCommunity, Ut as DecryptedChallengeVerificationSchema, Vn as CommentUpdateSignedPropertyNames, Vr as require_supports_color, Wn as CreateCommentOptionsWithRefinementSchema, Wr as _enum, Wt as NameResolveCacheOptionsSchema, Xr as number, Xt as CommunityEditPublicationChallengeRequestToEncryptSchema, Yn as CommentEditChallengeRequestToEncryptSchema, Yr as looseObject, Zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Zr as object, _n as CreateRemoteCommunityFunctionArgumentSchema, _r as n$9, an as CommentModerationsTableRowSchema, ar as AuthorReservedFields, at as throwIfAbortSignalAborted, bn as PageSortFileFactorySchema, bt as refreshTrackedCommunityAliases, cn as ChallengeFileSchema, cr as CidStringSchema, d as deepMergeRuntimeFields, dn as CommunityEditOptionsSchema, dr as CreateSignerSchema, ei as string, en as CreateCommunityEditPublicationOptionsWithRefinementSchema, f as derivePublicationFromChallengeRequest, fn as CommunityExportRecordsSchema, fr as JsonSignatureSchema, ft as findStartedCommunity, gn as CreateNewLocalCommunityUserOptionsSchema, gr as isStringDomain, h as fetchAndValidateIpnsRecordFromGateway, hn as CommunitySignedPropertyNames, hr as areEquivalentNames, ht as forgetTrackedUpdatingCommunityName, in as CommentModerationSignedPropertyNames, ir as AuthorPubsubSchema, jn as CommentIpfsReservedFields, jr as e$4, k as isIpns, kr as t$10, lr as CommunityAddressSchema, m as extractNetworkErrorDetails, mn as CommunityIpfsSchema, mr as ProtocolVersionSchema, mt as findUpdatingCommunity, nn as CommentModerationPubsubMessagePublicationSchema, nr as AuthorAddressSchema, nt as shortifyCid, on as CreateCommentModerationOptionsWithRefinementSchema, or as ChallengeAnswersSchema, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsReservedFields, pr as PKCTimestampSchema, q as removeNullUndefinedEmptyObjectsValuesRecursively, qn as PageIpfsSchema, qr as custom, qt as PKCUserOptionBaseSchema, r as calculateIpfsCidV0, rr as AuthorCommentIpfsReservedFields, rt as sleepUntilTimeoutOrAbort, sn as ChallengeFileFactorySchema, sr as CidPathSchema, t as areEquivalentCommunityAddresses, ti as union, tn as CommentModerationChallengeRequestToEncryptSchema, tr as CreateCommentEditOptionsWithRefinementSchema, tt as shortifyAddress, u as createAbortError, un as CommunityChallengeSettingSchema, ur as CommunityAuthorChallengeReservedFieldNames, vn as CreateRpcCommunityFunctionArgumentSchema, w as interruptibleSleep, wn as CreateVoteUserOptionsWithRefinementSchema, wr as t$11, wt as trackUpdatingCommunity, xn as PageSortFileSchema, xr as t$13, yn as ExportCommunityModLogsOptionsSchema, yr as n$10, z as linkAbortSignals, zn as CommentUpdateReservedFields, zr as messages, zt as DecryptedChallengeAnswerSchema } from "./util-C5RiQF_G.js";
2
+ import { $n as CommentEditSignedPropertyNames, $r as record, $t as CommunityEditPubsubMessagePublicationSchema, A as isIpnsPath, An as CommentChallengeRequestToEncryptSchema, Ar as t$9, At as pTimeout, B as pubsubTopicToDhtKey, Bn as CommentUpdateSchema, Br as logger_default, C as hideClassPrivateProps, Cn as RpcRemoteCommunityUpdateEventResultSchema, Cr as e$5, D as isIpfsCid, Dr as n$8, Dt as untrackUpdatingCommunity, E as isAbortError, En as VotePubsubMessagePublicationSchema, Er as t$12, Fn as CommentSignedPropertyNames, Fr as FailedToFetchCommunityFromGatewaysError, Gn as GetPageParamSchema, Gr as array, Gt as NameResolverSerializedSchema, H as raceAgainstAbort, Hr as require_ms$1, Ht as DecryptedChallengeSchema, In as CommentUpdateChallengeReservedFieldNames, Ir as FailedToFetchGenericIpfsFromGatewaysError, It as ChallengeRequestMessageSignedPropertyNames, Jn as isReservedObjectKey, Jr as literal, Jt as PKCUserOptionsSchema, Kn as ModQueuePageIpfsSchema, Kr as boolean, Kt as PKCParsedOptionsSchema, L as isRequestPubsubPublicationOfPost, Lr as FailedToFetchPageIpfsFromGatewaysError, Mn as CommentIpfsSchema, Mr as require_retry$2, Mt as ChallengeAnswerMessageSignedPropertyNames, Nr as FailedToFetchCommentIpfsFromGatewaysError, O as isIpfsPath, On as VoteSignedPropertyNames, Or as r$7, Ot as require_sha256$1, Pn as CommentPubsubMessageWithFlexibleAuthorRefinementSchema, Pr as FailedToFetchCommentUpdateFromGatewaysError, Pt as ChallengeMessageSignedPropertyNames, Qr as preprocess, Qt as CommunityEditPublicationSignedPropertyNames, R as isRequestPubsubPublicationOfReply, Rn as CommentUpdateForChallengeVerificationSignedPropertyNames, Rr as PKCError, Rt as ChallengeVerificationMessageSignedPropertyNames, S as hasTransientNetworkErrorCode, Sr as e$6, St as trackStartedCommunity, T as ipnsNameToIpnsOverPubsubTopic, Tn as VoteChallengeRequestToEncryptSchema, Tr as r$8, Tt as untrackStartedCommunity, Ut as DecryptedChallengeVerificationSchema, Vn as CommentUpdateSignedPropertyNames, Vr as require_supports_color, Wn as CreateCommentOptionsWithRefinementSchema, Wr as _enum, Wt as NameResolveCacheOptionsSchema, Xr as number, Xt as CommunityEditPublicationChallengeRequestToEncryptSchema, Yn as CommentEditChallengeRequestToEncryptSchema, Yr as looseObject, Zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Zr as object, _n as CreateRemoteCommunityFunctionArgumentSchema, _r as n$9, an as CommentModerationsTableRowSchema, ar as AuthorReservedFields, at as throwIfAbortSignalAborted, bn as PageSortFileFactorySchema, bt as refreshTrackedCommunityAliases, cn as ChallengeFileSchema, cr as CidStringSchema, d as deepMergeRuntimeFields, dn as CommunityEditOptionsSchema, dr as CreateSignerSchema, ei as string, en as CreateCommunityEditPublicationOptionsWithRefinementSchema, f as derivePublicationFromChallengeRequest, fn as CommunityExportRecordsSchema, fr as JsonSignatureSchema, ft as findStartedCommunity, gn as CreateNewLocalCommunityUserOptionsSchema, gr as isStringDomain, h as fetchAndValidateIpnsRecordFromGateway, hn as CommunitySignedPropertyNames, hr as areEquivalentNames, ht as forgetTrackedUpdatingCommunityName, in as CommentModerationSignedPropertyNames, ir as AuthorPubsubSchema, jn as CommentIpfsReservedFields, jr as e$4, k as isIpns, kr as t$10, lr as CommunityAddressSchema, m as extractNetworkErrorDetails, mn as CommunityIpfsSchema, mr as ProtocolVersionSchema, mt as findUpdatingCommunity, nn as CommentModerationPubsubMessagePublicationSchema, nr as AuthorAddressSchema, nt as shortifyCid, on as CreateCommentModerationOptionsWithRefinementSchema, or as ChallengeAnswersSchema, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsReservedFields, pr as PKCTimestampSchema, q as removeNullUndefinedEmptyObjectsValuesRecursively, qn as PageIpfsSchema, qr as custom, qt as PKCUserOptionBaseSchema, r as calculateIpfsCidV0, rr as AuthorCommentIpfsReservedFields, rt as sleepUntilTimeoutOrAbort, sn as ChallengeFileFactorySchema, sr as CidPathSchema, t as areEquivalentCommunityAddresses, ti as union, tn as CommentModerationChallengeRequestToEncryptSchema, tr as CreateCommentEditOptionsWithRefinementSchema, tt as shortifyAddress, u as createAbortError, un as CommunityChallengeSettingSchema, ur as CommunityAuthorChallengeReservedFieldNames, vn as CreateRpcCommunityFunctionArgumentSchema, w as interruptibleSleep, wn as CreateVoteUserOptionsWithRefinementSchema, wr as t$11, wt as trackUpdatingCommunity, xn as PageSortFileSchema, xr as t$13, yn as ExportCommunityModLogsOptionsSchema, yr as n$10, z as linkAbortSignals, zn as CommentUpdateReservedFields, zr as messages, zt as DecryptedChallengeAnswerSchema } from "./util-BYT-7zVn.js";
3
3
  import { t as all } from "./src-CYIMjhjK.js";
4
- import { s as validatePageSortFile } from "./page-sort-scoring-DY7SvqJA.js";
4
+ import { s as validatePageSortFile } from "./page-sort-scoring-DaW6urZ2.js";
5
5
  import { createHash } from "node:crypto";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import dns from "node:dns";
@@ -148034,14 +148034,15 @@ async function pRetry(input, options = {}) {
148034
148034
  //#endregion
148035
148035
  //#region dist/node/util/inflight-fetch-manager.js
148036
148036
  var InflightFetchManager = class {
148037
- constructor() {
148037
+ constructor({ isDestroyed } = {}) {
148038
148038
  this._inflightFetches = /* @__PURE__ */ new Map();
148039
+ this._isDestroyed = isDestroyed ?? (() => false);
148039
148040
  }
148040
148041
  _getKey(resourceType, identifier) {
148041
148042
  return `${resourceType}::${identifier}`;
148042
148043
  }
148043
- async withKey(key, fetcher) {
148044
- let inflight = this._inflightFetches.get(key);
148044
+ async withKey(key, fetcher, abortSignal) {
148045
+ const inflight = this._inflightFetches.get(key);
148045
148046
  if (!inflight) {
148046
148047
  let fetchPromiseRef;
148047
148048
  const fetchPromise = (async () => {
@@ -148055,14 +148056,38 @@ var InflightFetchManager = class {
148055
148056
  })();
148056
148057
  fetchPromiseRef = fetchPromise;
148057
148058
  this._inflightFetches.set(key, fetchPromise);
148058
- inflight = fetchPromise;
148059
+ return fetchPromise;
148060
+ }
148061
+ try {
148062
+ return await this._waitUnlessAborted(inflight, abortSignal);
148063
+ } catch (e) {
148064
+ if (!(e instanceof Error && e.name === "AbortError") || abortSignal?.aborted || this._isDestroyed()) throw e;
148065
+ if (this._inflightFetches.get(key) === inflight) this._inflightFetches.delete(key);
148066
+ return this.withKey(key, fetcher, abortSignal);
148067
+ }
148068
+ }
148069
+ async _waitUnlessAborted(inflight, abortSignal) {
148070
+ if (!abortSignal) return inflight;
148071
+ let onAbort;
148072
+ try {
148073
+ return await Promise.race([inflight, new Promise((_, reject) => {
148074
+ const rejectWithAbort = () => {
148075
+ const error = /* @__PURE__ */ new Error("The caller that joined this fetch was stopped");
148076
+ error.name = "AbortError";
148077
+ reject(error);
148078
+ };
148079
+ if (abortSignal.aborted) return rejectWithAbort();
148080
+ onAbort = rejectWithAbort;
148081
+ abortSignal.addEventListener("abort", onAbort, { once: true });
148082
+ })]);
148083
+ } finally {
148084
+ if (onAbort) abortSignal.removeEventListener("abort", onAbort);
148059
148085
  }
148060
- return inflight;
148061
148086
  }
148062
- async withResource(resourceType, identifier, fetcher) {
148087
+ async withResource(resourceType, identifier, fetcher, abortSignal) {
148063
148088
  if (!resourceType) throw new Error("resourceType is required for inflight fetches");
148064
148089
  if (typeof identifier !== "string" || identifier.length === 0) throw new Error("identifier is required for inflight fetches and must be a string");
148065
- return this.withKey(this._getKey(resourceType, identifier), fetcher);
148090
+ return this.withKey(this._getKey(resourceType, identifier), fetcher, abortSignal);
148066
148091
  }
148067
148092
  };
148068
148093
  const InflightResourceTypes = {
@@ -148116,6 +148141,23 @@ const createUrlFromSubdomainResolution = (gateway, opts) => {
148116
148141
  };
148117
148142
  const GATEWAYS_THAT_SUPPORT_SUBDOMAIN_RESOLUTION = {};
148118
148143
  const MAX_CONCURRENT_AUTHOR_NAME_RESOLUTIONS = 100;
148144
+ const waitForAuthorNameResolveInFlight = ({ inFlightResolve, abortSignal }) => new Promise((resolve) => {
148145
+ if (abortSignal?.aborted) return resolve("aborted");
148146
+ const onAbort = () => finish("aborted");
148147
+ const finish = (outcome) => {
148148
+ inFlightResolve.joiners.delete(finish);
148149
+ if (abortSignal) {
148150
+ inFlightResolve.callers.delete(abortSignal);
148151
+ abortSignal.removeEventListener("abort", onAbort);
148152
+ }
148153
+ resolve(outcome);
148154
+ };
148155
+ inFlightResolve.joiners.add(finish);
148156
+ if (abortSignal) {
148157
+ inFlightResolve.callers.add(abortSignal);
148158
+ abortSignal.addEventListener("abort", onAbort, { once: true });
148159
+ }
148160
+ });
148119
148161
  var BaseClientsManager = class BaseClientsManager {
148120
148162
  constructor(pkc) {
148121
148163
  this.pubsubProviderSubscriptions = {};
@@ -148486,16 +148528,23 @@ var BaseClientsManager = class BaseClientsManager {
148486
148528
  throwIfAbortSignalAborted(loadOpts.abortSignal);
148487
148529
  loadOpts.abortSignal.addEventListener("abort", onParentAbort, { once: true });
148488
148530
  }
148489
- for (const gateway of gatewaysSorted) {
148531
+ for (const [i, gateway] of gatewaysSorted.entries()) {
148490
148532
  const abortController = new AbortController();
148491
- gatewayFetches[gateway] = {
148533
+ const gatewayFetch = {
148492
148534
  abortController,
148493
- promise: queueLimit(() => this._fetchWithGateway(gateway, {
148535
+ timeoutId: void 0
148536
+ };
148537
+ gatewayFetches[gateway] = gatewayFetch;
148538
+ const armTimeout = () => gatewayFetch.timeoutId = setTimeout(() => abortController.abort("Gateway request timed out"), timeoutMs);
148539
+ const startsAtOnce = i < concurrencyLimit;
148540
+ if (startsAtOnce) armTimeout();
148541
+ gatewayFetch.promise = queueLimit(() => {
148542
+ if (!startsAtOnce && !abortController.signal.aborted) armTimeout();
148543
+ return this._fetchWithGateway(gateway, {
148494
148544
  ...loadOpts,
148495
148545
  abortController
148496
- })),
148497
- timeoutId: setTimeout(() => abortController.abort("Gateway request timed out"), timeoutMs)
148498
- };
148546
+ });
148547
+ });
148499
148548
  }
148500
148549
  const gatewayPromises = Object.values(gatewayFetches).map((fetching) => fetching.promise);
148501
148550
  const res = await Promise.race([this._firstResolve(gatewayPromises), Promise.allSettled(gatewayPromises)]);
@@ -148872,6 +148921,7 @@ var BaseClientsManager = class BaseClientsManager {
148872
148921
  const failedRecently = this._pkc._memCaches.nameResolveFailedCache;
148873
148922
  const seen = /* @__PURE__ */ new Set();
148874
148923
  const toResolve = [];
148924
+ const joined = [];
148875
148925
  for (const { authorName, signaturePublicKey } of authors) {
148876
148926
  if (!isStringDomain(authorName)) continue;
148877
148927
  if (!this.canResolveName(authorName)) continue;
@@ -148879,21 +148929,30 @@ var BaseClientsManager = class BaseClientsManager {
148879
148929
  if (seen.has(cacheKey)) continue;
148880
148930
  seen.add(cacheKey);
148881
148931
  if (typeof verificationCache.get(cacheKey) === "boolean") continue;
148882
- if (inFlight.has(cacheKey)) continue;
148932
+ const inFlightResolve = inFlight.get(cacheKey);
148933
+ if (inFlightResolve) {
148934
+ if (!abortSignal || !inFlightResolve.callers.has(abortSignal)) joined.push({
148935
+ author: {
148936
+ authorName,
148937
+ signaturePublicKey
148938
+ },
148939
+ inFlightResolve
148940
+ });
148941
+ continue;
148942
+ }
148883
148943
  if (failedRecently.get(cacheKey)) continue;
148884
- inFlight.add(cacheKey);
148885
148944
  toResolve.push({
148886
148945
  authorName,
148887
148946
  signaturePublicKey,
148888
148947
  cacheKey
148889
148948
  });
148890
148949
  }
148891
- if (toResolve.length === 0) return;
148950
+ if (toResolve.length === 0 && joined.length === 0) return;
148892
148951
  const setVerdict = (cacheKey, verdict) => verdict ? verificationCache.set(cacheKey, true, { ttl: this._pkc._nameResolvedTrueTtlMs }) : verificationCache.set(cacheKey, false, { ttl: this._pkc._nameResolvedFalseTtlMs });
148893
148952
  const limit = pLimit(MAX_CONCURRENT_AUTHOR_NAME_RESOLUTIONS);
148894
148953
  const resolveOne = async (entry) => {
148895
148954
  try {
148896
- if (abortSignal?.aborted) return false;
148955
+ if (abortSignal?.aborted) return "aborted";
148897
148956
  const { resolvedAuthorName: resolved } = await this.resolveAuthorNameIfNeeded({
148898
148957
  authorName: entry.authorName,
148899
148958
  abortSignal,
@@ -148901,26 +148960,49 @@ var BaseClientsManager = class BaseClientsManager {
148901
148960
  });
148902
148961
  if (typeof resolved !== "string") {
148903
148962
  setVerdict(entry.cacheKey, false);
148904
- return true;
148963
+ return "verdict";
148905
148964
  }
148906
148965
  const signerAddress = await getPKCAddressFromPublicKey(entry.signaturePublicKey);
148907
148966
  setVerdict(entry.cacheKey, resolved === signerAddress);
148908
- return true;
148967
+ return "verdict";
148909
148968
  } catch (e) {
148910
- if (isAbortError(e)) return false;
148969
+ if (isAbortError(e)) return "aborted";
148911
148970
  if (e instanceof PKCError && e.code === "ERR_RESOLVED_TEXT_RECORD_TO_NON_IPNS") {
148912
148971
  setVerdict(entry.cacheKey, false);
148913
- return true;
148972
+ return "verdict";
148914
148973
  }
148915
148974
  log.error("Failed to resolve author name in background", entry.authorName, e);
148916
148975
  failedRecently.set(entry.cacheKey, true, { ttl: this._pkc._nameResolveFailedRetryFloorMs });
148917
- return false;
148918
- } finally {
148919
- inFlight.delete(entry.cacheKey);
148976
+ return "failed";
148920
148977
  }
148921
148978
  };
148922
- Promise.allSettled(toResolve.map((entry) => limit(() => resolveOne(entry)))).then((results) => {
148923
- if (results.some((r) => r.status === "fulfilled" && r.value === true)) onResolved();
148979
+ const ownAttempts = toResolve.map((entry) => {
148980
+ const inFlightResolve = {
148981
+ callers: new Set(abortSignal ? [abortSignal] : []),
148982
+ joiners: /* @__PURE__ */ new Set()
148983
+ };
148984
+ inFlight.set(entry.cacheKey, inFlightResolve);
148985
+ const settle = (outcome) => {
148986
+ if (inFlight.get(entry.cacheKey) === inFlightResolve) inFlight.delete(entry.cacheKey);
148987
+ for (const joiner of inFlightResolve.joiners) joiner(outcome);
148988
+ return outcome;
148989
+ };
148990
+ return limit(() => resolveOne(entry)).then(settle, () => settle("failed"));
148991
+ });
148992
+ for (const { author, inFlightResolve } of joined) waitForAuthorNameResolveInFlight({
148993
+ inFlightResolve,
148994
+ abortSignal
148995
+ }).then((outcome) => {
148996
+ if (abortSignal?.aborted) return;
148997
+ if (outcome === "verdict") onResolved();
148998
+ else if (outcome === "aborted" && !this._pkc.destroyed) this.resolveAuthorNamesInBackground({
148999
+ authors: [author],
149000
+ onResolved,
149001
+ abortSignal
149002
+ });
149003
+ }).catch((e) => log.error("Unexpected error in resolveAuthorNamesInBackground", e));
149004
+ if (ownAttempts.length > 0) Promise.allSettled(ownAttempts).then((results) => {
149005
+ if (results.some((r) => r.status === "fulfilled" && r.value === "verdict") && !abortSignal?.aborted) onResolved();
148924
149006
  }).catch((e) => log.error("Unexpected error in resolveAuthorNamesInBackground", e));
148925
149007
  }
148926
149008
  emitError(e) {
@@ -148929,8 +149011,8 @@ var BaseClientsManager = class BaseClientsManager {
148929
149011
  calculateIpfsCid(content) {
148930
149012
  return calculateIpfsCidV0(content);
148931
149013
  }
148932
- async _withInflightCommunityFetch(communityAddress, fetcher) {
148933
- return this._pkc._inflightFetchManager.withResource(InflightResourceTypes.COMMUNITY_IPNS, communityAddress, fetcher);
149014
+ async _withInflightCommunityFetch(communityAddress, fetcher, abortSignal) {
149015
+ return this._pkc._inflightFetchManager.withResource(InflightResourceTypes.COMMUNITY_IPNS, communityAddress, fetcher, abortSignal);
148934
149016
  }
148935
149017
  };
148936
149018
  BaseClientsManager.MAX_IPNS_HOPS = 1;
@@ -150715,7 +150797,7 @@ var CommunityClientsManager = class extends PKCClientsManager {
150715
150797
  if (this._community.publicKey && (isDomain || hasAnchorClaim || !isDomain && this._community.name && this._community.nameResolved === true)) return this._community.publicKey;
150716
150798
  }
150717
150799
  async fetchNewUpdateForCommunity(communityAddress) {
150718
- return this._withInflightCommunityFetch(communityAddress, async () => {
150800
+ const fetchCommunity = async () => {
150719
150801
  let ipnsName;
150720
150802
  const isDomain = isStringDomain(communityAddress);
150721
150803
  const pinnedIpnsName = this._pinnedIpnsName();
@@ -150774,7 +150856,8 @@ var CommunityClientsManager = class extends PKCClientsManager {
150774
150856
  if (anchorIdentityAddress !== identityPublicKey) this._pkc._memCaches.communityForPublishing.set(identityPublicKey, communityForPublishing);
150775
150857
  }
150776
150858
  return subRes;
150777
- });
150859
+ };
150860
+ return this._withInflightCommunityFetch(communityAddress, fetchCommunity, this._community._getStopAbortSignal());
150778
150861
  }
150779
150862
  _isIpnsPushChannelHealthyForName(libp2pJsClient, ipnsName) {
150780
150863
  try {
@@ -150867,7 +150950,21 @@ var CommunityClientsManager = class extends PKCClientsManager {
150867
150950
  });
150868
150951
  const gatewaysSorted = t$13(this._pkc.clients.ipfsGateways).length <= concurrencyLimit ? t$13(this._pkc.clients.ipfsGateways) : await this._pkc._stats.sortGatewaysAccordingToScore("ipns");
150869
150952
  const gatewayFetches = {};
150870
- for (const gatewayUrl of gatewaysSorted) {
150953
+ const stopSignal = this._community._getStopAbortSignal();
150954
+ const onStopAbort = () => cleanUp();
150955
+ const cleanUp = () => {
150956
+ queueLimit.clearQueue();
150957
+ Object.values(gatewayFetches).forEach((gateway) => {
150958
+ if (!gateway.communityRecord && !gateway.error) gateway.abortController.abort("Cleaning up requests for community");
150959
+ clearTimeout(gateway.timeoutId);
150960
+ });
150961
+ if (stopSignal) stopSignal.removeEventListener("abort", onStopAbort);
150962
+ };
150963
+ if (stopSignal) {
150964
+ throwIfAbortSignalAborted(stopSignal);
150965
+ stopSignal.addEventListener("abort", onStopAbort, { once: true });
150966
+ }
150967
+ for (const [gatewayIndex, gatewayUrl] of gatewaysSorted.entries()) {
150871
150968
  const abortController = new AbortController();
150872
150969
  const throwIfGatewayRespondsWithInvalidCommunity = async (gatewayRes) => {
150873
150970
  if (typeof gatewayRes.resText !== "string") throw Error("Gateway response has no body");
@@ -150974,9 +151071,14 @@ var CommunityClientsManager = class extends PKCClientsManager {
150974
151071
  if (this._community.updateCid) etagsForConditionalRequest.add(`"${this._community.updateCid}"`);
150975
151072
  for (const cid of Array.from(this._updateCidsAlreadyLoaded.values()).slice(-5)) etagsForConditionalRequest.add(`"${cid}"`);
150976
151073
  const requestHeaders = etagsForConditionalRequest.size > 0 ? { "If-None-Match": Array.from(etagsForConditionalRequest).join(", ") } : void 0;
150977
- gatewayFetches[gatewayUrl] = {
150978
- abortController,
150979
- promise: queueLimit(() => this._fetchWithGateway(gatewayUrl, {
151074
+ const gatewayFetch = { abortController };
151075
+ gatewayFetches[gatewayUrl] = gatewayFetch;
151076
+ const armTimeout = () => gatewayFetch.timeoutId = setTimeout(() => abortController.abort("Aborting community IPNS request because it timed out after " + timeoutMs + "ms"), timeoutMs);
151077
+ const startsAtOnce = gatewayIndex < concurrencyLimit;
151078
+ if (startsAtOnce) armTimeout();
151079
+ gatewayFetch.promise = queueLimit(() => {
151080
+ if (!startsAtOnce && !abortController.signal.aborted) armTimeout();
151081
+ return this._fetchWithGateway(gatewayUrl, {
150980
151082
  recordIpfsType: "ipns",
150981
151083
  root: ipnsName,
150982
151084
  recordPKCType: "community",
@@ -150987,23 +151089,8 @@ var CommunityClientsManager = class extends PKCClientsManager {
150987
151089
  timeoutMs: this._pkc._timeouts["community-ipns"],
150988
151090
  log,
150989
151091
  requestHeaders
150990
- })),
150991
- timeoutId: setTimeout(() => abortController.abort("Aborting community IPNS request because it timed out after " + timeoutMs + "ms"), timeoutMs)
150992
- };
150993
- }
150994
- const stopSignal = this._community._getStopAbortSignal();
150995
- const onStopAbort = () => cleanUp();
150996
- const cleanUp = () => {
150997
- queueLimit.clearQueue();
150998
- Object.values(gatewayFetches).forEach((gateway) => {
150999
- if (!gateway.communityRecord && !gateway.error) gateway.abortController.abort("Cleaning up requests for community");
151000
- clearTimeout(gateway.timeoutId);
151092
+ });
151001
151093
  });
151002
- if (stopSignal) stopSignal.removeEventListener("abort", onStopAbort);
151003
- };
151004
- if (stopSignal) {
151005
- throwIfAbortSignalAborted(stopSignal);
151006
- stopSignal.addEventListener("abort", onStopAbort, { once: true });
151007
151094
  }
151008
151095
  const _findRecentCommunity = () => {
151009
151096
  const winner = selectWinningGatewayCommunity({
@@ -16553,7 +16553,7 @@ const CommunityEditPublicationPubsubReservedFields = r$2([
16553
16553
  ], t$3(CommunityEditPubsubMessagePublicationSchema.shape));
16554
16554
  //#endregion
16555
16555
  //#region dist/node/generated-version.js
16556
- const version = "0.0.143";
16556
+ const version = "0.0.144";
16557
16557
  //#endregion
16558
16558
  //#region dist/node/version.js
16559
16559
  const protocolVersion = ProtocolVersionSchema.parse("1.0.0");
@@ -1,4 +1,4 @@
1
- import { Rr as PKCError, V as pubsubTopicToDhtKeyCid } from "./util-C5RiQF_G.js";
1
+ import { Rr as PKCError, V as pubsubTopicToDhtKeyCid } from "./util-BYT-7zVn.js";
2
2
  import { ipnsSelector } from "ipns/selector";
3
3
  import { ipnsValidator } from "ipns/validator";
4
4
  import { unmarshalIPNSRecord } from "ipns";
@@ -1,5 +1,5 @@
1
- import { Rr as PKCError, bn as PageSortFileFactorySchema, cn as ChallengeFileSchema, sn as ChallengeFileFactorySchema } from "./util-C5RiQF_G.js";
2
- import { s as validatePageSortFile } from "./page-sort-scoring-DY7SvqJA.js";
1
+ import { Rr as PKCError, bn as PageSortFileFactorySchema, cn as ChallengeFileSchema, sn as ChallengeFileFactorySchema } from "./util-BYT-7zVn.js";
2
+ import { s as validatePageSortFile } from "./page-sort-scoring-DaW6urZ2.js";
3
3
  //#region dist/node/validate-package-factories.js
4
4
  function validateChallengeFileFactory(factory, { name }) {
5
5
  try {
@@ -1,2 +1,2 @@
1
- import { a as getShortCid, c as setNativeFunctions, i as getShortAddress, n as challenges, o as nativeFunctions, r as createAnchorIpnsRecord, s as pageSorts, t as PKC } from "./chunks/node-Tkx_TCqE.js";
1
+ import { a as getShortCid, c as setNativeFunctions, i as getShortAddress, n as challenges, o as nativeFunctions, r as createAnchorIpnsRecord, s as pageSorts, t as PKC } from "./chunks/node-Coyk7lC6.js";
2
2
  export { challenges, createAnchorIpnsRecord, PKC as default, getShortAddress, getShortCid, nativeFunctions, pageSorts, setNativeFunctions };
@@ -1,2 +1,2 @@
1
- import { n as validatePageSortFileFactory } from "./chunks/validate-package-factories-DnW2JiL5.js";
1
+ import { n as validatePageSortFileFactory } from "./chunks/validate-package-factories-CPVyODKw.js";
2
2
  export { validatePageSortFileFactory };
@@ -1,7 +1,7 @@
1
- import { At as pTimeout, Br as logger_default, C as hideClassPrivateProps, Rr as PKCError, X as replaceXWithY, et as retryKuboIpfsAddAndProvide, ft as findStartedCommunity, i as calculateStringSizeSameAsIpfsAddCidV0, xr as t, yr as n } from "../../chunks/util-C5RiQF_G.js";
2
- import { S as parseRpcUnsubscribeParam, _ as parseRpcExportCommunityParam, b as parseRpcPublishChallengeAnswersParam, d as parseRpcCidParam, f as parseRpcCommentRepliesPageParam, g as parseRpcExportCommunityModLogsParam, h as parseRpcEditCommunityParam, l as parseRpcAuthorNameParam, m as parseRpcCommunityPageParam, p as parseRpcCommunityIdentifierParam, t as PKC, u as parseRpcCancelExportParam, v as parseRpcFetchCommunityListParam, x as parseRpcPublishCommunityListParam, y as parseRpcPublishAnchorRecordParam } from "../../chunks/node-Tkx_TCqE.js";
3
- import { Dt as parseJsonWithPKCErrorIfFails, E as buildPagesRuntimeFields, Gr as stringify, L as extractCrosspostRuntimeFields, Mt as parseVoteChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, Pr as toCommunitiesWireEntry, Rr as t$1, T as buildPageRuntimeFields, Tr as listCommunitiesSync, U as pRetry, Vn as verifyCommunityList, W as pLimit, Xn as MAX_COMMUNITY_LIST_SIZE_BYTES, at as parseCommentModerationChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, br as findLocalCommunityAddress, bt as parseCreatePKCWsServerOptionsSchemaWithPKCErrorIfItFails, dt as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, jt as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, mt as parseCommunityListSchemaWithPKCErrorIfItFails, nt as parseCommentEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, sn as require_lib, tt as parseCommentChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, ut as parseCommunityEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, yt as parseCreateNewLocalCommunityUserOptionsSchemaWithPKCErrorIfItFails } from "../../chunks/rpc-local-community-Br_xomgn.js";
4
- import { t as LocalCommunity } from "../../chunks/local-community-BglT8AUy.js";
1
+ import { At as pTimeout, Br as logger_default, C as hideClassPrivateProps, Rr as PKCError, X as replaceXWithY, et as retryKuboIpfsAddAndProvide, ft as findStartedCommunity, i as calculateStringSizeSameAsIpfsAddCidV0, xr as t, yr as n } from "../../chunks/util-BYT-7zVn.js";
2
+ import { S as parseRpcUnsubscribeParam, _ as parseRpcExportCommunityParam, b as parseRpcPublishChallengeAnswersParam, d as parseRpcCidParam, f as parseRpcCommentRepliesPageParam, g as parseRpcExportCommunityModLogsParam, h as parseRpcEditCommunityParam, l as parseRpcAuthorNameParam, m as parseRpcCommunityPageParam, p as parseRpcCommunityIdentifierParam, t as PKC, u as parseRpcCancelExportParam, v as parseRpcFetchCommunityListParam, x as parseRpcPublishCommunityListParam, y as parseRpcPublishAnchorRecordParam } from "../../chunks/node-Coyk7lC6.js";
3
+ import { Dt as parseJsonWithPKCErrorIfFails, E as buildPagesRuntimeFields, Gr as stringify, L as extractCrosspostRuntimeFields, Mt as parseVoteChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, Pr as toCommunitiesWireEntry, Rr as t$1, T as buildPageRuntimeFields, Tr as listCommunitiesSync, U as pRetry, Vn as verifyCommunityList, W as pLimit, Xn as MAX_COMMUNITY_LIST_SIZE_BYTES, at as parseCommentModerationChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, br as findLocalCommunityAddress, bt as parseCreatePKCWsServerOptionsSchemaWithPKCErrorIfItFails, dt as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, jt as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, mt as parseCommunityListSchemaWithPKCErrorIfItFails, nt as parseCommentEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, sn as require_lib, tt as parseCommentChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, ut as parseCommunityEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, yt as parseCreateNewLocalCommunityUserOptionsSchemaWithPKCErrorIfItFails } from "../../chunks/rpc-local-community-KgRrTYjv.js";
4
+ import { t as LocalCommunity } from "../../chunks/local-community-DCVtQSci.js";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import path from "path";
7
7
  import assert from "assert";
@@ -33,6 +33,11 @@ export type OptionsToLoadFromGateway = {
33
33
  }) => Promise<void>;
34
34
  log: Logger;
35
35
  };
36
+ type AuthorNameResolveOutcome = "verdict" | "failed" | "aborted";
37
+ export type AuthorNameResolveInFlight = {
38
+ callers: Set<AbortSignal>;
39
+ joiners: Set<(outcome: AuthorNameResolveOutcome) => void>;
40
+ };
36
41
  export declare class BaseClientsManager {
37
42
  _pkc: PKC;
38
43
  pubsubProviderSubscriptions: Record<string, string[]>;
@@ -151,5 +156,6 @@ export declare class BaseClientsManager {
151
156
  }): void;
152
157
  emitError(e: PKCError): void;
153
158
  calculateIpfsCid(content: string): Promise<string>;
154
- protected _withInflightCommunityFetch(communityAddress: string, fetcher: () => Promise<ResultOfFetchingCommunity>): Promise<ResultOfFetchingCommunity>;
159
+ protected _withInflightCommunityFetch(communityAddress: string, fetcher: () => Promise<ResultOfFetchingCommunity>, abortSignal?: AbortSignal): Promise<ResultOfFetchingCommunity>;
155
160
  }
161
+ export {};
@@ -51,6 +51,27 @@ const GATEWAYS_THAT_SUPPORT_SUBDOMAIN_RESOLUTION = {}; // gateway url -> whether
51
51
  // 100 sits above the realistic batch window, so coalescing survives, and caps the burst for the
52
52
  // resolvers that do not batch.
53
53
  const MAX_CONCURRENT_AUTHOR_NAME_RESOLUTIONS = 100;
54
+ // Waits for a resolve another caller started. A resolve is bounded only by its owner's signal, so the wait
55
+ // ends as soon as the joiner is stopped and leaves nothing on the resolve: a stopped Comment or community must
56
+ // not stay referenced through its onResolved until someone else's resolve settles.
57
+ const waitForAuthorNameResolveInFlight = ({ inFlightResolve, abortSignal }) => new Promise((resolve) => {
58
+ if (abortSignal?.aborted)
59
+ return resolve("aborted");
60
+ const onAbort = () => finish("aborted");
61
+ const finish = (outcome) => {
62
+ inFlightResolve.joiners.delete(finish);
63
+ if (abortSignal) {
64
+ inFlightResolve.callers.delete(abortSignal);
65
+ abortSignal.removeEventListener("abort", onAbort);
66
+ }
67
+ resolve(outcome);
68
+ };
69
+ inFlightResolve.joiners.add(finish);
70
+ if (abortSignal) {
71
+ inFlightResolve.callers.add(abortSignal);
72
+ abortSignal.addEventListener("abort", onAbort, { once: true });
73
+ }
74
+ });
54
75
  export class BaseClientsManager {
55
76
  constructor(pkc) {
56
77
  this.pubsubProviderSubscriptions = {}; // To keep track of subscriptions of each kubo pubsub provider/helia
@@ -474,13 +495,25 @@ export class BaseClientsManager {
474
495
  throwIfAbortSignalAborted(loadOpts.abortSignal);
475
496
  loadOpts.abortSignal.addEventListener("abort", onParentAbort, { once: true });
476
497
  }
477
- for (const gateway of gatewaysSorted) {
498
+ for (const [i, gateway] of gatewaysSorted.entries()) {
478
499
  const abortController = new AbortController();
479
- gatewayFetches[gateway] = {
480
- abortController,
481
- promise: queueLimit(() => this._fetchWithGateway(gateway, { ...loadOpts, abortController })),
482
- timeoutId: setTimeout(() => abortController.abort("Gateway request timed out"), timeoutMs)
483
- };
500
+ const gatewayFetch = { abortController, timeoutId: undefined };
501
+ gatewayFetches[gateway] = gatewayFetch;
502
+ const armTimeout = () => (gatewayFetch.timeoutId = setTimeout(() => abortController.abort("Gateway request timed out"), timeoutMs));
503
+ // The timeout is this gateway's own, so it runs from when the gateway can send its request. The first
504
+ // `concurrencyLimit` gateways get a slot at once, so theirs is armed now, before the caller arms a deadline of
505
+ // the same length (getComment's is the comment-ipfs timeout too): when the gateways hang, their errors reach the
506
+ // caller first. A gateway that waits for a slot gets its timeout when its request starts. Armed at enqueue, it
507
+ // would run down in the queue, and a gateway queued behind 3 hanging ones would start aborted. A gateway that
508
+ // cleanUp() reached first starts aborted anyway, and gets no timer cleanUp() can't clear
509
+ const startsAtOnce = i < concurrencyLimit;
510
+ if (startsAtOnce)
511
+ armTimeout();
512
+ gatewayFetch.promise = queueLimit(() => {
513
+ if (!startsAtOnce && !abortController.signal.aborted)
514
+ armTimeout();
515
+ return this._fetchWithGateway(gateway, { ...loadOpts, abortController });
516
+ });
484
517
  }
485
518
  const gatewayPromises = Object.values(gatewayFetches).map((fetching) => fetching.promise);
486
519
  //@ts-expect-error
@@ -924,6 +957,8 @@ export class BaseClientsManager {
924
957
  // Deduplicate and skip already-cached entries
925
958
  const seen = new Set();
926
959
  const toResolve = [];
960
+ // Authors another caller is already resolving, with that caller's resolve
961
+ const joined = [];
927
962
  for (const { authorName, signaturePublicKey } of authors) {
928
963
  if (!isStringDomain(authorName))
929
964
  continue;
@@ -941,18 +976,24 @@ export class BaseClientsManager {
941
976
  // An attempt for this exact name and signer is already outstanding. A resolve is bounded only by
942
977
  // the caller's abort signal, so a reachable-but-slow resolver would otherwise collect one attempt
943
978
  // per caller per update: the floor below is measured from when an attempt finished, and one that
944
- // has not answered yet has finished nothing.
945
- if (inFlight.has(cacheKey))
979
+ // has not answered yet has finished nothing. Join it rather than skip it: its verdict is this
980
+ // caller's too, and onResolved is the only way this caller gets a verdict applied to its objects.
981
+ // Unless this caller already waits for it (it started it, or joined it on an earlier ask): that ask
982
+ // tells it. Callers without a stop signal cannot be told apart, so each of their asks waits.
983
+ const inFlightResolve = inFlight.get(cacheKey);
984
+ if (inFlightResolve) {
985
+ if (!abortSignal || !inFlightResolve.callers.has(abortSignal))
986
+ joined.push({ author: { authorName, signaturePublicKey }, inFlightResolve });
946
987
  continue;
988
+ }
947
989
  // The last attempt learned nothing. The verdict is still undefined, which is also the marker that
948
990
  // allows a retry, so without this every caller would reach the network for as long as the
949
991
  // resolvers stayed down. The entry expires on its own, which is what ends the pacing.
950
992
  if (failedRecently.get(cacheKey))
951
993
  continue;
952
- inFlight.add(cacheKey);
953
994
  toResolve.push({ authorName, signaturePublicKey, cacheKey });
954
995
  }
955
- if (toResolve.length === 0)
996
+ if (toResolve.length === 0 && joined.length === 0)
956
997
  return;
957
998
  // A `false` verdict is an accusation resting on evidence nothing persists, and the states that
958
999
  // produce one (no record yet, a record that is not a key) are exactly what a domain looks like while
@@ -965,7 +1006,7 @@ export class BaseClientsManager {
965
1006
  const resolveOne = async (entry) => {
966
1007
  try {
967
1008
  if (abortSignal?.aborted)
968
- return false;
1009
+ return "aborted";
969
1010
  const { resolvedAuthorName: resolved } = await this.resolveAuthorNameIfNeeded({
970
1011
  authorName: entry.authorName,
971
1012
  abortSignal,
@@ -976,19 +1017,19 @@ export class BaseClientsManager {
976
1017
  // this signer, so cache false. An all-resolvers-errored outcome no longer arrives here, it
977
1018
  // throws ERR_ALL_NAME_RESOLVERS_FAILED and is left undefined for retry below. Issue #353.
978
1019
  setVerdict(entry.cacheKey, false);
979
- return true; // newly set
1020
+ return "verdict"; // newly set
980
1021
  }
981
1022
  const signerAddress = await getPKCAddressFromPublicKey(entry.signaturePublicKey);
982
1023
  setVerdict(entry.cacheKey, resolved === signerAddress);
983
- return true; // newly set
1024
+ return "verdict"; // newly set
984
1025
  }
985
1026
  catch (e) {
986
1027
  if (isAbortError(e))
987
- return false;
1028
+ return "aborted";
988
1029
  if (e instanceof PKCError && e.code === "ERR_RESOLVED_TEXT_RECORD_TO_NON_IPNS") {
989
1030
  // The resolvers answered: the record exists and is not a key. Definitive non-match.
990
1031
  setVerdict(entry.cacheKey, false);
991
- return true; // newly set
1032
+ return "verdict"; // newly set
992
1033
  }
993
1034
  log.error("Failed to resolve author name in background", entry.authorName, e);
994
1035
  // We never got an answer (every resolver errored, or the resolve timed out). "We could not find
@@ -997,19 +1038,54 @@ export class BaseClientsManager {
997
1038
  // no verdict to pace the retry, and undefined is what invites one. An abort is deliberately
998
1039
  // not recorded here, since the caller going away is not the resolvers failing. Issue #353.
999
1040
  failedRecently.set(entry.cacheKey, true, { ttl: this._pkc._nameResolveFailedRetryFloorMs });
1000
- return false;
1001
- }
1002
- finally {
1003
- inFlight.delete(entry.cacheKey);
1041
+ return "failed";
1004
1042
  }
1005
1043
  };
1006
- Promise.allSettled(toResolve.map((entry) => limit(() => resolveOne(entry))))
1007
- .then((results) => {
1008
- const anyNewlySet = results.some((r) => r.status === "fulfilled" && r.value === true);
1009
- if (anyNewlySet)
1010
- onResolved();
1011
- })
1012
- .catch((e) => log.error("Unexpected error in resolveAuthorNamesInBackground", e));
1044
+ const ownAttempts = toResolve.map((entry) => {
1045
+ const inFlightResolve = { callers: new Set(abortSignal ? [abortSignal] : []), joiners: new Set() };
1046
+ inFlight.set(entry.cacheKey, inFlightResolve);
1047
+ const settle = (outcome) => {
1048
+ // Released before the joiners hear, so one that has to ask again finds the name free
1049
+ if (inFlight.get(entry.cacheKey) === inFlightResolve)
1050
+ inFlight.delete(entry.cacheKey);
1051
+ for (const joiner of inFlightResolve.joiners)
1052
+ joiner(outcome);
1053
+ return outcome;
1054
+ };
1055
+ return limit(() => resolveOne(entry)).then(settle, () => settle("failed"));
1056
+ });
1057
+ // The caller hears about the resolves it started once they have all settled, as before joining existed, and
1058
+ // about each resolve it joined as that one lands. A background resolve has no timeout of its own: it is
1059
+ // bounded only by its owner's signal. So a verdict must not wait for a resolve another caller owns, neither
1060
+ // the caller's own verdicts nor the verdict of another resolve it joined.
1061
+ //
1062
+ // A caller that was stopped in the meantime is not notified. Its stop aborts what is still outstanding,
1063
+ // which settles the batch, and a verdict that landed before the stop would otherwise reach a stopped
1064
+ // Comment, whose onResolved changes what it renders and emits "update".
1065
+ for (const { author, inFlightResolve } of joined)
1066
+ waitForAuthorNameResolveInFlight({ inFlightResolve, abortSignal })
1067
+ .then((outcome) => {
1068
+ // This caller was stopped while it waited, so it gets nothing, as if its own attempt had been aborted
1069
+ if (abortSignal?.aborted)
1070
+ return;
1071
+ if (outcome === "verdict")
1072
+ onResolved();
1073
+ // Its owner was stopped before it learned anything, which says nothing about the name: ask on this
1074
+ // caller's behalf, and that call runs onResolved itself on a verdict. A failed attempt is not retried
1075
+ // here, nameResolveFailedCache paces that for joiners as for owners. Not once the pkc is destroyed:
1076
+ // destroy() is what stopped the owner, and it closes the storage and caches a new resolve would use.
1077
+ else if (outcome === "aborted" && !this._pkc.destroyed)
1078
+ this.resolveAuthorNamesInBackground({ authors: [author], onResolved, abortSignal });
1079
+ })
1080
+ .catch((e) => log.error("Unexpected error in resolveAuthorNamesInBackground", e));
1081
+ if (ownAttempts.length > 0)
1082
+ Promise.allSettled(ownAttempts)
1083
+ .then((results) => {
1084
+ const anyNewlySet = results.some((r) => r.status === "fulfilled" && r.value === "verdict");
1085
+ if (anyNewlySet && !abortSignal?.aborted)
1086
+ onResolved();
1087
+ })
1088
+ .catch((e) => log.error("Unexpected error in resolveAuthorNamesInBackground", e));
1013
1089
  }
1014
1090
  // Misc functions
1015
1091
  emitError(e) {
@@ -1018,8 +1094,10 @@ export class BaseClientsManager {
1018
1094
  calculateIpfsCid(content) {
1019
1095
  return calculateIpfsCidV0(content);
1020
1096
  }
1021
- async _withInflightCommunityFetch(communityAddress, fetcher) {
1022
- return this._pkc._inflightFetchManager.withResource(InflightResourceTypes.COMMUNITY_IPNS, communityAddress, fetcher);
1097
+ // abortSignal is the caller's own cancellation: a caller that joined another community's fetch fetches again
1098
+ // when that community is stopped, unless it was stopped too
1099
+ async _withInflightCommunityFetch(communityAddress, fetcher, abortSignal) {
1100
+ return this._pkc._inflightFetchManager.withResource(InflightResourceTypes.COMMUNITY_IPNS, communityAddress, fetcher, abortSignal);
1023
1101
  }
1024
1102
  }
1025
1103
  // IPFS P2P methods