@bitsocial/bitsocial-react-hooks 0.1.65 → 0.2.0

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.
@@ -7,6 +7,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
10
21
  import assert from "../../lib/assert.js";
11
22
  import localForageLru from "../../lib/localforage-lru/index.js";
12
23
  const communitiesDatabase = localForageLru.createInstance({
@@ -22,9 +33,18 @@ import communitiesPagesStore from "../communities-pages/index.js";
22
33
  import { getCommunityLookupOptions, getCommunityRefKey } from "../../lib/community-ref.js";
23
34
  import { createPkcCommunity, getPkcCommunity, getPkcCommunityAddresses, getPkcCreateCommunity, getPkcGetCommunity, } from "../../lib/pkc-compat.js";
24
35
  export const COMMUNITY_UPDATE_INTERVAL_MS = 15 * 60 * 1000;
36
+ // How long a community keeps updating after nothing uses it anymore. pkc-js forgets the record
37
+ // CIDs and gateway ETags it already loaded when a community stops, so every restart downloads the
38
+ // whole record again, while a running loop downloads it once per publish. Communities publish
39
+ // between every ~20 seconds when busy and every 15 minutes when idle, so 2 minutes keeps quick
40
+ // back-and-forth navigation from re-downloading records and bounds what an abandoned busy
41
+ // community costs to about one restart's worth of downloads.
42
+ export const COMMUNITY_UPDATE_STOP_GRACE_MS = 2 * 60 * 1000;
25
43
  let pkcGetCommunityPending = {};
26
- // Key pollers by community so delete/reset can stop the matching live instance.
27
- const communityUpdatePollers = {};
44
+ const liveCommunities = {};
45
+ // hooks and feeds that need a community kept updating, the loop stops after the last one leaves
46
+ const communityUpdateSubscribers = {};
47
+ const communityStopTimers = {};
28
48
  // reset all event listeners in between tests
29
49
  const listeners = [];
30
50
  const COMMUNITY_ERROR_UPDATE_GRACE_MS = 1000;
@@ -73,35 +93,141 @@ const createCommunityWithLookupFallback = (pkc, communityLookupOptions, communit
73
93
  }
74
94
  throw Error(`communitiesStore.addCommunityToStore failed getting community '${communityKey}'`);
75
95
  });
76
- const updateCommunity = (community, { communityAddressOrRef, communityKey, }) => {
77
- community.update().catch((error) => log.trace("community.update error", {
96
+ const getCommunityKey = (communityAddressOrRef) => typeof communityAddressOrRef === "string"
97
+ ? communityAddressOrRef
98
+ : getCommunityRefKey(communityAddressOrRef);
99
+ const hasCommunityUpdateSubscribers = (communityKey) => { var _a; return (((_a = communityUpdateSubscribers[communityKey]) === null || _a === void 0 ? void 0 : _a.size) || 0) > 0; };
100
+ const updateCommunity = (communityKey, liveCommunity) => {
101
+ const { community, communityAddressOrRef } = liveCommunity;
102
+ liveCommunity.updateCall = Promise.resolve()
103
+ .then(() => community.update())
104
+ .catch((error) => log.trace("community.update error", {
78
105
  communityAddressOrRef,
79
106
  communityKey,
80
107
  community,
81
108
  error,
82
109
  }));
83
110
  };
84
- const startCommunityUpdatePolling = (community, { communityAddressOrRef, communityKey, }) => {
85
- stopCommunityUpdatePolling(communityKey);
86
- updateCommunity(community, { communityAddressOrRef, communityKey });
87
- communityUpdatePollers[communityKey] = {
88
- community,
89
- updateInterval: setInterval(() => updateCommunity(community, { communityAddressOrRef, communityKey }), COMMUNITY_UPDATE_INTERVAL_MS),
90
- };
111
+ const startCommunityUpdatePolling = (communityKey, liveCommunity) => {
112
+ clearInterval(liveCommunity.updateInterval);
113
+ liveCommunity.openingUpdatePending = true;
114
+ liveCommunity.stopWhenOpeningUpdateEnds = false;
115
+ updateCommunity(communityKey, liveCommunity);
116
+ liveCommunity.updateInterval = setInterval(() => updateCommunity(communityKey, liveCommunity), COMMUNITY_UPDATE_INTERVAL_MS);
117
+ };
118
+ const pauseCommunityUpdatePolling = (communityKey) => {
119
+ const liveCommunity = liveCommunities[communityKey];
120
+ if (!(liveCommunity === null || liveCommunity === void 0 ? void 0 : liveCommunity.updateInterval)) {
121
+ return;
122
+ }
123
+ clearInterval(liveCommunity.updateInterval);
124
+ liveCommunity.updateInterval = undefined;
125
+ liveCommunity.openingUpdatePending = false;
126
+ liveCommunity.stopWhenOpeningUpdateEnds = false;
127
+ liveCommunity.replayRecordId = undefined;
128
+ clearPendingCommunityErrors(communityKey);
129
+ const { community, updateCall } = liveCommunity;
130
+ // stopping while update() is still attaching to the shared updating instance would leave its
131
+ // listeners attached, so wait for the call to return first
132
+ const stopping = (() => __awaiter(void 0, void 0, void 0, function* () {
133
+ yield updateCall;
134
+ if (typeof community.stop !== "function") {
135
+ return;
136
+ }
137
+ try {
138
+ yield community.stop();
139
+ }
140
+ catch (error) {
141
+ log.trace("community.stop error", { communityKey, community, error });
142
+ }
143
+ }))();
144
+ liveCommunity.stopping = stopping;
145
+ stopping.finally(() => {
146
+ if (liveCommunity.stopping === stopping) {
147
+ liveCommunity.stopping = undefined;
148
+ }
149
+ });
150
+ log("communitiesStore community update loop stopped", { communityKey });
151
+ };
152
+ const resumeCommunityUpdatePolling = (communityKey) => __awaiter(void 0, void 0, void 0, function* () {
153
+ var _a;
154
+ const liveCommunity = liveCommunities[communityKey];
155
+ if (!liveCommunity || liveCommunity.updateInterval) {
156
+ return;
157
+ }
158
+ // update() is a no-op until a stop in progress ends
159
+ if (liveCommunity.stopping) {
160
+ yield liveCommunity.stopping;
161
+ }
162
+ if (liveCommunities[communityKey] !== liveCommunity ||
163
+ liveCommunity.updateInterval ||
164
+ !hasCommunityUpdateSubscribers(communityKey)) {
165
+ return;
166
+ }
167
+ liveCommunity.replayRecordId = getCommunityRecordId(liveCommunity.community);
168
+ liveCommunity.replayRefreshesFetchedAt = false;
169
+ startCommunityUpdatePolling(communityKey, liveCommunity);
170
+ log("communitiesStore community update loop restarted", { communityKey });
171
+ // joining a shared pkc-js instance that another consumer kept updating emits no state change
172
+ // until its next fetch, so take its current state
173
+ yield liveCommunity.updateCall;
174
+ const { updatingState } = liveCommunity.community;
175
+ if (liveCommunity.updateInterval &&
176
+ typeof updatingState === "string" &&
177
+ updatingState !== "stopped" &&
178
+ ((_a = communitiesStore.getState().syncStatuses[communityKey]) === null || _a === void 0 ? void 0 : _a.stoppedUntilUsed)) {
179
+ liveCommunity.onUpdatingStateChange(updatingState);
180
+ }
181
+ });
182
+ const clearCommunityStopTimer = (communityKey) => {
183
+ clearTimeout(communityStopTimers[communityKey]);
184
+ delete communityStopTimers[communityKey];
185
+ };
186
+ const scheduleCommunityUpdateStop = (communityKey) => {
187
+ clearCommunityStopTimer(communityKey);
188
+ communityStopTimers[communityKey] = setTimeout(() => {
189
+ delete communityStopTimers[communityKey];
190
+ const liveCommunity = liveCommunities[communityKey];
191
+ if (hasCommunityUpdateSubscribers(communityKey) || !(liveCommunity === null || liveCommunity === void 0 ? void 0 : liveCommunity.updateInterval)) {
192
+ return;
193
+ }
194
+ // stopping before the first fetch ends would leave a store-level caller without the record
195
+ // it loaded the community for
196
+ if (liveCommunity.openingUpdatePending) {
197
+ liveCommunity.stopWhenOpeningUpdateEnds = true;
198
+ return;
199
+ }
200
+ pauseCommunityUpdatePolling(communityKey);
201
+ }, COMMUNITY_UPDATE_STOP_GRACE_MS);
202
+ };
203
+ const endOpeningCommunityUpdate = (communityKey, liveCommunity) => {
204
+ if (!liveCommunity.openingUpdatePending) {
205
+ return;
206
+ }
207
+ liveCommunity.openingUpdatePending = false;
208
+ if (!liveCommunity.stopWhenOpeningUpdateEnds) {
209
+ return;
210
+ }
211
+ liveCommunity.stopWhenOpeningUpdateEnds = false;
212
+ if (!hasCommunityUpdateSubscribers(communityKey)) {
213
+ pauseCommunityUpdatePolling(communityKey);
214
+ }
91
215
  };
92
216
  const stopCommunityUpdatePolling = (communityKey) => {
93
- const polling = communityUpdatePollers[communityKey];
94
- if (!polling) {
217
+ clearCommunityStopTimer(communityKey);
218
+ const liveCommunity = liveCommunities[communityKey];
219
+ if (!liveCommunity) {
95
220
  return;
96
221
  }
97
222
  clearPendingCommunityErrors(communityKey);
98
- clearInterval(polling.updateInterval);
99
- polling.community.removeAllListeners();
100
- const listenerIndex = listeners.indexOf(polling.community);
223
+ clearInterval(liveCommunity.updateInterval);
224
+ liveCommunity.updateInterval = undefined;
225
+ liveCommunity.community.removeAllListeners();
226
+ const listenerIndex = listeners.indexOf(liveCommunity.community);
101
227
  if (listenerIndex >= 0) {
102
228
  listeners.splice(listenerIndex, 1);
103
229
  }
104
- delete communityUpdatePollers[communityKey];
230
+ delete liveCommunities[communityKey];
105
231
  };
106
232
  const clearPendingCommunityErrors = (communityKey) => {
107
233
  var _a;
@@ -275,6 +401,11 @@ const communitiesStore = createStore((setState, getState) => ({
275
401
  if (!isFromCache) {
276
402
  yield communitiesDatabase.setItem(communityKey, firstCommunityState);
277
403
  }
404
+ // another load of this community, e.g. by another account, finished first and keeps it
405
+ // updating, so this instance is discarded before it starts updating
406
+ if (liveCommunities[communityKey]) {
407
+ return;
408
+ }
278
409
  log("communitiesStore.addCommunityToStore", {
279
410
  communityAddressOrRef,
280
411
  communityKey,
@@ -284,16 +415,46 @@ const communitiesStore = createStore((setState, getState) => ({
284
415
  setState((state) => ({
285
416
  communities: Object.assign(Object.assign({}, state.communities), { [communityKey]: firstCommunityState }),
286
417
  }));
287
- // pkc-js re-emits the record a community was created with when update() starts
288
- let cachedRecordId = isFromCache ? getCommunityRecordId(firstCommunityState) : undefined;
418
+ const liveCommunity = {
419
+ community,
420
+ communityAddressOrRef,
421
+ // pkc-js re-emits the record a community was created with when update() starts
422
+ replayRecordId: isFromCache ? getCommunityRecordId(firstCommunityState) : undefined,
423
+ replayRefreshesFetchedAt: true,
424
+ openingUpdatePending: false,
425
+ stopWhenOpeningUpdateEnds: false,
426
+ onUpdatingStateChange: (updatingState) => {
427
+ setState((state) => {
428
+ const syncStatuses = getNextSyncStatuses(state, communityKey, normalizeCommunitySyncState(updatingState));
429
+ const _a = syncStatuses[communityKey], { stoppedUntilUsed: _stoppedUntilUsed } = _a, syncStatus = __rest(_a, ["stoppedUntilUsed"]);
430
+ // the loop is not running when the store stopped the community itself
431
+ syncStatuses[communityKey] =
432
+ updatingState === "stopped" && !liveCommunity.updateInterval
433
+ ? Object.assign(Object.assign({}, syncStatus), { stoppedUntilUsed: true }) : syncStatus;
434
+ return {
435
+ syncStatuses,
436
+ communities: Object.assign(Object.assign({}, state.communities), { [communityKey]: Object.assign(Object.assign({}, state.communities[communityKey]), { updatingState }) }),
437
+ };
438
+ });
439
+ if (updatingState === "succeeded" ||
440
+ updatingState === "failed" ||
441
+ updatingState === "waiting-retry") {
442
+ endOpeningCommunityUpdate(communityKey, liveCommunity);
443
+ }
444
+ },
445
+ };
289
446
  // the community has published new posts
290
447
  community.on("update", (updatedCommunity) => __awaiter(this, void 0, void 0, function* () {
291
448
  clearPendingCommunityErrors(communityKey);
292
449
  setState((state) => clearStoredCommunityErrorsState(state, communityKey));
293
- const isCachedRecordReplay = cachedRecordId !== undefined &&
294
- getCommunityRecordId(updatedCommunity) === cachedRecordId;
295
- cachedRecordId = undefined;
296
- if (isCachedRecordReplay) {
450
+ const isRecordReplay = liveCommunity.replayRecordId !== undefined &&
451
+ getCommunityRecordId(updatedCommunity) === liveCommunity.replayRecordId;
452
+ liveCommunity.replayRecordId = undefined;
453
+ if (isRecordReplay && !liveCommunity.replayRefreshesFetchedAt) {
454
+ // a restarted loop replays the record the store already has, it was not fetched now
455
+ return;
456
+ }
457
+ if (isRecordReplay) {
297
458
  // the replayed record is already in the store and the database, only refresh fetchedAt
298
459
  // like a fetched update would, without cloning and rewriting the whole record
299
460
  setState((state) => {
@@ -315,27 +476,26 @@ const communitiesStore = createStore((setState, getState) => ({
315
476
  // add fetchedAt to be able to expire the cache
316
477
  // NOTE: fetchedAt is undefined on owner communities because never stale
317
478
  updatedCommunity.fetchedAt = Math.floor(Date.now() / 1000);
318
- yield communitiesDatabase.setItem(communityKey, updatedCommunity);
479
+ // pkc-js reports the fetch succeeded right after this event, so store the record first:
480
+ // a succeeded sync state must not be shown with the previous record, e.g. a stale one
481
+ // kept while the community was not updating
482
+ setState((state) => (Object.assign(Object.assign({}, state), { communities: Object.assign(Object.assign({}, state.communities), { [communityKey]: updatedCommunity }) })));
319
483
  log("communitiesStore community update", {
320
484
  communityAddressOrRef,
321
485
  communityKey,
322
486
  updatedCommunity,
323
487
  account,
324
488
  });
325
- setState((state) => (Object.assign(Object.assign({}, state), { communities: Object.assign(Object.assign({}, state.communities), { [communityKey]: updatedCommunity }) })));
489
+ yield communitiesDatabase.setItem(communityKey, updatedCommunity);
326
490
  // if a community has a role with an account's address add it to the account.communities
327
491
  accountsStore
328
492
  .getState()
329
493
  .accountsActionsInternal.addCommunityRoleToAccountsCommunities(updatedCommunity);
330
494
  // add page comments to communitiesPagesStore so they can be used in useComment
331
495
  communitiesPagesStore.getState().addCommunityPageCommentsToStore(updatedCommunity);
496
+ endOpeningCommunityUpdate(communityKey, liveCommunity);
332
497
  }));
333
- community.on("updatingstatechange", (updatingState) => {
334
- setState((state) => ({
335
- syncStatuses: getNextSyncStatuses(state, communityKey, normalizeCommunitySyncState(updatingState)),
336
- communities: Object.assign(Object.assign({}, state.communities), { [communityKey]: Object.assign(Object.assign({}, state.communities[communityKey]), { updatingState }) }),
337
- }));
338
- });
498
+ community.on("updatingstatechange", liveCommunity.onUpdatingStateChange);
339
499
  community.on("error", (error) => {
340
500
  scheduleCommunityError(setState, communityKey, error);
341
501
  });
@@ -362,7 +522,13 @@ const communitiesStore = createStore((setState, getState) => ({
362
522
  });
363
523
  });
364
524
  listeners.push(community);
365
- startCommunityUpdatePolling(community, { communityAddressOrRef, communityKey });
525
+ liveCommunities[communityKey] = liveCommunity;
526
+ startCommunityUpdatePolling(communityKey, liveCommunity);
527
+ // loaded without a subscriber, e.g. by a store-level caller: update until the grace period
528
+ // ends, and at least until the first fetch ends
529
+ if (!hasCommunityUpdateSubscribers(communityKey)) {
530
+ scheduleCommunityUpdateStop(communityKey);
531
+ }
366
532
  }
367
533
  catch (error) {
368
534
  updateCommunitySyncStatus(setState, communityKey, "failed");
@@ -373,6 +539,44 @@ const communitiesStore = createStore((setState, getState) => ({
373
539
  }
374
540
  });
375
541
  },
542
+ // keep a community updating while a subscriber (a mounted hook or feed) needs it, and restart
543
+ // its update loop if it stopped after its previous subscribers left
544
+ startCommunityAutoUpdate(communityAddressOrRef, subscriberId, account) {
545
+ return __awaiter(this, void 0, void 0, function* () {
546
+ const communityKey = getCommunityKey(communityAddressOrRef);
547
+ assert(communityKey !== "" && typeof communityKey === "string", `communitiesStore.startCommunityAutoUpdate invalid communityAddress argument '${communityAddressOrRef}'`);
548
+ assert(subscriberId && typeof subscriberId === "string", `communitiesStore.startCommunityAutoUpdate invalid subscriberId argument '${subscriberId}'`);
549
+ if (!communityUpdateSubscribers[communityKey]) {
550
+ communityUpdateSubscribers[communityKey] = new Set();
551
+ }
552
+ communityUpdateSubscribers[communityKey].add(subscriberId);
553
+ clearCommunityStopTimer(communityKey);
554
+ const liveCommunity = liveCommunities[communityKey];
555
+ if (liveCommunity) {
556
+ liveCommunity.stopWhenOpeningUpdateEnds = false;
557
+ yield resumeCommunityUpdatePolling(communityKey);
558
+ return;
559
+ }
560
+ yield getState().addCommunityToStore(communityAddressOrRef, account);
561
+ });
562
+ },
563
+ // the community stops updating a grace period after its last subscriber leaves
564
+ stopCommunityAutoUpdate(communityAddressOrRef, subscriberId) {
565
+ return __awaiter(this, void 0, void 0, function* () {
566
+ const communityKey = getCommunityKey(communityAddressOrRef);
567
+ const subscribers = communityUpdateSubscribers[communityKey];
568
+ if (!(subscribers === null || subscribers === void 0 ? void 0 : subscribers.delete(subscriberId))) {
569
+ return;
570
+ }
571
+ if (subscribers.size > 0) {
572
+ return;
573
+ }
574
+ delete communityUpdateSubscribers[communityKey];
575
+ if (liveCommunities[communityKey]) {
576
+ scheduleCommunityUpdateStop(communityKey);
577
+ }
578
+ });
579
+ },
376
580
  refreshCommunity(communityAddressOrRef, account) {
377
581
  return __awaiter(this, void 0, void 0, function* () {
378
582
  const communityLookupOptions = getCommunityLookupOptions(communityAddressOrRef);
@@ -487,7 +691,11 @@ export const resetCommunitiesStore = () => __awaiter(void 0, void 0, void 0, fun
487
691
  // remove all event listeners
488
692
  listeners.forEach((listener) => listener.removeAllListeners());
489
693
  listeners.length = 0;
490
- Object.keys(communityUpdatePollers).forEach(stopCommunityUpdatePolling);
694
+ Object.keys(liveCommunities).forEach(stopCommunityUpdatePolling);
695
+ Object.keys(communityStopTimers).forEach(clearCommunityStopTimer);
696
+ for (const communityKey in communityUpdateSubscribers) {
697
+ delete communityUpdateSubscribers[communityKey];
698
+ }
491
699
  // destroy all component subscriptions to the store
492
700
  communitiesStore.destroy();
493
701
  // restore original state
@@ -1 +1 @@
1
- {"version":3,"file":"communities-store.js","sourceRoot":"","sources":["../../../src/stores/communities/communities-store.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,MAAM,MAAM,kBAAkB,CAAC;AACtC,OAAO,cAAc,MAAM,2BAA2B,CAAC;AACvD,MAAM,mBAAmB,GAAG,cAAc,CAAC,cAAc,CAAC;IACxD,IAAI,EAAE,iCAAiC;IACvC,IAAI,EAAE,GAAG;CACV,CAAC,CAAC;AACH,OAAO,MAAM,MAAM,yBAAyB,CAAC;AAC7C,MAAM,GAAG,GAAG,MAAM,CAAC,0CAA0C,CAAC,CAAC;AAS/D,OAAO,KAAK,MAAM,iBAAiB,CAAC;AACpC,OAAO,WAAW,MAAM,SAAS,CAAC;AAClC,OAAO,aAAa,MAAM,aAAa,CAAC;AACxC,OAAO,qBAAqB,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAA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EAAE,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,CAAC;IACpE,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;IACrB,MAAM,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC,OAAO,CAAC,0BAA0B,CAAC,CAAC;IACxE,mDAAmD;IACnD,gBAAgB,CAAC,OAAO,EAAE,CAAC;IAC3B,yBAAyB;IACzB,gBAAgB,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;AAC3C,CAAC,CAAA,CAAC;AAEF,4CAA4C;AAC5C,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAAS,EAAE;IACzD,MAAM,cAAc,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,iCAAiC,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC;IACzF,MAAM,qBAAqB,EAAE,CAAC;AAChC,CAAC,CAAA,CAAC;AAEF,eAAe,gBAAgB,CAAC","sourcesContent":["import assert from \"../../lib/assert\";\nimport localForageLru from \"../../lib/localforage-lru\";\nconst communitiesDatabase = localForageLru.createInstance({\n name: \"bitsocialReactHooks-communities\",\n size: 500,\n});\nimport Logger from \"@pkcprotocol/pkc-logger\";\nconst log = Logger(\"bitsocial-react-hooks:communities:stores\");\nimport {\n Community,\n Communities,\n Account,\n CommunityIdentifier,\n CommunitySyncState,\n CreateCommunityOptions,\n} from \"../../types\";\nimport utils from \"../../lib/utils\";\nimport createStore from \"zustand\";\nimport accountsStore from \"../accounts\";\nimport communitiesPagesStore from \"../communities-pages\";\nimport { getCommunityLookupOptions, getCommunityRefKey } from \"../../lib/community-ref\";\nimport {\n createPkcCommunity,\n getPkcCommunity,\n getPkcCommunityAddresses,\n getPkcCreateCommunity,\n getPkcGetCommunity,\n} from \"../../lib/pkc-compat\";\n\nexport const COMMUNITY_UPDATE_INTERVAL_MS = 15 * 60 * 1000;\n\nlet pkcGetCommunityPending: { [key: string]: boolean } = {};\n// Key pollers by community so delete/reset can stop the matching live instance.\nconst communityUpdatePollers: {\n [communityKey: string]: {\n community: any;\n updateInterval: ReturnType<typeof setInterval>;\n };\n} = {};\n\n// reset all event listeners in between tests\nconst listeners: any = [];\n\nconst COMMUNITY_ERROR_UPDATE_GRACE_MS = 1000;\nconst pendingCommunityErrorTimers: {\n [communityKey: string]: ReturnType<typeof setTimeout>[];\n} = {};\n\ninterface CommunitySyncStatus {\n syncState: CommunitySyncState;\n lastFetchAttemptAt?: number;\n lastSuccessfulFetchAt?: number;\n // why the community is being retried; retriable errors stay out of `errors` so they do not\n // flash in the UI, but a community that never loads needs a reason to show\n lastRetriableError?: Error;\n}\n\nconst omitLastRetriableError = (syncStatus: CommunitySyncStatus): CommunitySyncStatus => {\n const nextSyncStatus = { ...syncStatus };\n delete nextSyncStatus.lastRetriableError;\n return nextSyncStatus;\n};\n\nconst getNowSeconds = () => Math.floor(Date.now() / 1000);\n\nconst normalizeCommunitySyncState = (updatingState: string): CommunitySyncState => {\n if (updatingState === \"waiting-retry\") {\n return \"retrying\";\n }\n if (updatingState === \"succeeded\" || updatingState === \"failed\" || updatingState === \"stopped\") {\n return updatingState;\n }\n return \"loading\";\n};\n\nconst getNextSyncStatuses = (\n state: CommunitiesState,\n communityKey: string,\n syncState: CommunitySyncState,\n) => {\n const previousStatus = state.syncStatuses[communityKey];\n const timestamp = getNowSeconds();\n const shouldRecordAttempt = syncState === \"loading\" && previousStatus?.syncState !== \"loading\";\n const nextStatus: CommunitySyncStatus = {\n ...previousStatus,\n syncState,\n ...(shouldRecordAttempt ? { lastFetchAttemptAt: timestamp } : undefined),\n ...(syncState === \"succeeded\" ? { lastSuccessfulFetchAt: timestamp } : undefined),\n };\n return {\n ...state.syncStatuses,\n // a success ends the retries, so their error is no longer current\n [communityKey]: syncState === \"succeeded\" ? omitLastRetriableError(nextStatus) : nextStatus,\n };\n};\n\nconst updateCommunitySyncStatus = (\n setState: Function,\n communityKey: string,\n syncState: CommunitySyncState,\n) => {\n setState((state: CommunitiesState) => ({\n ...state,\n syncStatuses: getNextSyncStatuses(state, communityKey, syncState),\n }));\n};\n\n// identifies a signed community record, to recognize pkc-js re-emitting a record already in the store\nconst getCommunityRecordId = (community: any): string | undefined => {\n const signature = community?.signature?.signature;\n if (typeof signature !== \"string\" || typeof community?.updatedAt !== \"number\") {\n return;\n }\n return `${community.updatedAt}:${signature}`;\n};\n\nconst createCommunityWithLookupFallback = async (\n pkc: any,\n communityLookupOptions: { address?: string; name?: string; publicKey?: string },\n communityKey: string,\n) => {\n const supportsAddressLookup = \"address\" in communityLookupOptions;\n const community = await createPkcCommunity(pkc, communityLookupOptions);\n if (community?.address || supportsAddressLookup) {\n return community;\n }\n throw Error(`communitiesStore.addCommunityToStore failed getting community '${communityKey}'`);\n};\n\nconst updateCommunity = (\n community: Community,\n {\n communityAddressOrRef,\n communityKey,\n }: { communityAddressOrRef: string | CommunityIdentifier; communityKey: string },\n) => {\n community.update().catch((error: unknown) =>\n log.trace(\"community.update error\", {\n communityAddressOrRef,\n communityKey,\n community,\n error,\n }),\n );\n};\n\nconst startCommunityUpdatePolling = (\n community: Community,\n {\n communityAddressOrRef,\n communityKey,\n }: { communityAddressOrRef: string | CommunityIdentifier; communityKey: string },\n) => {\n stopCommunityUpdatePolling(communityKey);\n updateCommunity(community, { communityAddressOrRef, communityKey });\n communityUpdatePollers[communityKey] = {\n community,\n updateInterval: setInterval(\n () => updateCommunity(community, { communityAddressOrRef, communityKey }),\n COMMUNITY_UPDATE_INTERVAL_MS,\n ),\n };\n};\n\nconst stopCommunityUpdatePolling = (communityKey: string) => {\n const polling = communityUpdatePollers[communityKey];\n if (!polling) {\n return;\n }\n\n clearPendingCommunityErrors(communityKey);\n clearInterval(polling.updateInterval);\n polling.community.removeAllListeners();\n const listenerIndex = listeners.indexOf(polling.community);\n if (listenerIndex >= 0) {\n listeners.splice(listenerIndex, 1);\n }\n delete communityUpdatePollers[communityKey];\n};\n\nconst clearPendingCommunityErrors = (communityKey: string) => {\n pendingCommunityErrorTimers[communityKey]?.forEach((timeout) => clearTimeout(timeout));\n delete pendingCommunityErrorTimers[communityKey];\n};\n\nconst clearStoredCommunityErrors = (state: CommunitiesState, communityKey: string) => {\n if (!state.errors[communityKey]) {\n return state.errors;\n }\n const nextErrors = { ...state.errors };\n delete nextErrors[communityKey];\n return nextErrors;\n};\n\n// returning the same state skips notifying subscribers when there is nothing to clear\nconst clearStoredCommunityErrorsState = (state: CommunitiesState, communityKey: string) => {\n const syncStatus = state.syncStatuses[communityKey];\n const hasRetriableError = syncStatus?.lastRetriableError !== undefined;\n if (!state.errors[communityKey] && !hasRetriableError) {\n return state;\n }\n return {\n ...state,\n errors: clearStoredCommunityErrors(state, communityKey),\n syncStatuses: hasRetriableError\n ? { ...state.syncStatuses, [communityKey]: omitLastRetriableError(syncStatus) }\n : state.syncStatuses,\n };\n};\n\nexport const isRetriableCommunityLoadError = (error: Error) => {\n const details = (error as Error & { details?: unknown }).details;\n return Boolean(\n details &&\n typeof details === \"object\" &&\n \"retriableError\" in details &&\n (details as { retriableError?: unknown }).retriableError === true,\n );\n};\n\nconst recordRetriableCommunityError = (setState: Function, communityKey: string, error: Error) => {\n setState((state: CommunitiesState) => {\n const syncStatus = state.syncStatuses[communityKey];\n // a deleted community has no sync status left to report on\n if (!syncStatus) {\n return state;\n }\n return {\n syncStatuses: {\n ...state.syncStatuses,\n [communityKey]: { ...syncStatus, lastRetriableError: error },\n },\n };\n });\n};\n\nconst scheduleCommunityError = (setState: Function, communityKey: string, error: Error) => {\n if (isRetriableCommunityLoadError(error)) {\n recordRetriableCommunityError(setState, communityKey, error);\n return;\n }\n\n const timeout = setTimeout(() => {\n const pendingTimeouts = pendingCommunityErrorTimers[communityKey];\n if (!pendingTimeouts?.includes(timeout)) {\n return;\n }\n\n const remainingTimeouts = pendingTimeouts.filter(\n (pendingTimeout) => pendingTimeout !== timeout,\n );\n if (remainingTimeouts.length === 0) {\n delete pendingCommunityErrorTimers[communityKey];\n } else {\n pendingCommunityErrorTimers[communityKey] = remainingTimeouts;\n }\n setState((state: CommunitiesState) => {\n const communityErrors = state.errors[communityKey] || [];\n return {\n ...state,\n errors: { ...state.errors, [communityKey]: [...communityErrors, error] },\n };\n });\n }, COMMUNITY_ERROR_UPDATE_GRACE_MS);\n\n pendingCommunityErrorTimers[communityKey] = [\n ...(pendingCommunityErrorTimers[communityKey] || []),\n timeout,\n ];\n};\n\nexport type CommunitiesState = {\n communities: Communities;\n errors: { [communityAddress: string]: Error[] };\n syncStatuses: { [communityAddress: string]: CommunitySyncStatus };\n addCommunityToStore: Function;\n refreshCommunity: Function;\n editCommunity: Function;\n createCommunity: Function;\n deleteCommunity: Function;\n};\n\nconst communitiesStore = createStore<CommunitiesState>(\n (setState: Function, getState: Function) => ({\n communities: {},\n errors: {},\n syncStatuses: {},\n\n async addCommunityToStore(\n communityAddressOrRef: string | CommunityIdentifier,\n account: Account,\n ) {\n const communityLookupOptions = getCommunityLookupOptions(communityAddressOrRef);\n const communityKey =\n typeof communityAddressOrRef === \"string\"\n ? communityAddressOrRef\n : getCommunityRefKey(communityAddressOrRef);\n assert(\n communityKey !== \"\" && typeof communityKey === \"string\",\n `communitiesStore.addCommunityToStore invalid communityAddress argument '${communityAddressOrRef}'`,\n );\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesStore.addCommunityToStore invalid account argument '${account}'`,\n );\n\n // community is in store already, do nothing\n const { communities } = getState();\n let community: Community | undefined = communities[communityKey];\n const pendingKey = communityKey + account.id;\n if (community || pkcGetCommunityPending[pendingKey]) {\n return;\n }\n\n // start trying to get community\n pkcGetCommunityPending[pendingKey] = true;\n updateCommunitySyncStatus(setState, communityKey, \"initializing\");\n let errorGettingCommunity: any;\n try {\n // try to find community in owner communities\n if (getPkcCommunityAddresses(account.pkc).includes(communityKey)) {\n try {\n community = await createCommunityWithLookupFallback(\n account.pkc,\n communityLookupOptions,\n communityKey,\n );\n } catch (e) {\n errorGettingCommunity = e;\n }\n }\n\n // try to find community in database\n let fetchedAt: number | undefined;\n let isFromCache = false;\n if (!community) {\n const communityData: any = await communitiesDatabase.getItem(communityKey);\n const lookupName =\n \"name\" in communityLookupOptions ? communityLookupOptions.name : undefined;\n const lookupPublicKey =\n \"publicKey\" in communityLookupOptions ? communityLookupOptions.publicKey : undefined;\n const lookupAddress =\n \"address\" in communityLookupOptions ? communityLookupOptions.address : undefined;\n const hasCachedPosts =\n Object.keys(communityData?.posts?.pageCids || {}).length > 0 ||\n Object.keys(communityData?.posts?.pages || {}).length > 0;\n const isUnresolvedNameCache =\n communityData &&\n lookupName &&\n !lookupPublicKey &&\n !lookupAddress &&\n !communityData.publicKey &&\n !communityData.updatedAt &&\n !communityData.updateCid &&\n !communityData.title &&\n !communityData.description &&\n !hasCachedPosts;\n if (communityData && !isUnresolvedNameCache) {\n fetchedAt = communityData.fetchedAt;\n delete communityData.fetchedAt; // not part of pkc-js schema\n try {\n community = await createPkcCommunity(account.pkc, communityData);\n isFromCache = Boolean(community);\n } catch (e) {\n fetchedAt = undefined;\n // need to log this always or it could silently fail in production and cache never be used\n console.error(\"failed pkc.createCommunity(cachedCommunity)\", {\n cachedCommunity: communityData,\n error: e,\n });\n }\n }\n if (community) {\n // add page comments to communitiesPagesStore so they can be used in useComment\n communitiesPagesStore.getState().addCommunityPageCommentsToStore(community);\n }\n }\n\n // community not in database, try to fetch from pkc-js\n if (!community) {\n try {\n community = await createCommunityWithLookupFallback(\n account.pkc,\n communityLookupOptions,\n communityKey,\n );\n } catch (e) {\n errorGettingCommunity = e;\n }\n }\n\n // failure getting community\n if (!community) {\n if (errorGettingCommunity) {\n setState((state: CommunitiesState) => {\n let communityErrors = state.errors[communityKey] || [];\n communityErrors = [...communityErrors, errorGettingCommunity];\n return { ...state, errors: { ...state.errors, [communityKey]: communityErrors } };\n });\n }\n\n throw (\n errorGettingCommunity ||\n Error(`communitiesStore.addCommunityToStore failed getting community '${communityKey}'`)\n );\n }\n\n // success getting community\n const firstCommunityState = utils.clone({\n ...community,\n ...(fetchedAt !== undefined ? { fetchedAt } : undefined),\n });\n // a cache hit already is the database entry, rewriting it would only delay the store\n // update behind an IndexedDB write of the whole record\n if (!isFromCache) {\n await communitiesDatabase.setItem(communityKey, firstCommunityState);\n }\n log(\"communitiesStore.addCommunityToStore\", {\n communityAddressOrRef,\n communityKey,\n community,\n account,\n });\n setState((state: any) => ({\n communities: { ...state.communities, [communityKey]: firstCommunityState },\n }));\n\n // pkc-js re-emits the record a community was created with when update() starts\n let cachedRecordId = isFromCache ? getCommunityRecordId(firstCommunityState) : undefined;\n\n // the community has published new posts\n community.on(\"update\", async (updatedCommunity: Community) => {\n clearPendingCommunityErrors(communityKey);\n setState((state: CommunitiesState) =>\n clearStoredCommunityErrorsState(state, communityKey),\n );\n\n const isCachedRecordReplay =\n cachedRecordId !== undefined &&\n getCommunityRecordId(updatedCommunity) === cachedRecordId;\n cachedRecordId = undefined;\n if (isCachedRecordReplay) {\n // the replayed record is already in the store and the database, only refresh fetchedAt\n // like a fetched update would, without cloning and rewriting the whole record\n setState((state: CommunitiesState) => {\n const storedCommunity = state.communities[communityKey];\n if (!storedCommunity) {\n return state;\n }\n return {\n communities: {\n ...state.communities,\n [communityKey]: { ...storedCommunity, fetchedAt: getNowSeconds() },\n },\n };\n });\n // pass the cloned record, account state keeps references to its roles\n accountsStore\n .getState()\n .accountsActionsInternal.addCommunityRoleToAccountsCommunities(firstCommunityState);\n return;\n }\n\n updatedCommunity = utils.clone(updatedCommunity);\n\n // add fetchedAt to be able to expire the cache\n // NOTE: fetchedAt is undefined on owner communities because never stale\n updatedCommunity.fetchedAt = Math.floor(Date.now() / 1000);\n\n await communitiesDatabase.setItem(communityKey, updatedCommunity);\n log(\"communitiesStore community update\", {\n communityAddressOrRef,\n communityKey,\n updatedCommunity,\n account,\n });\n setState((state: any) => ({\n ...state,\n communities: { ...state.communities, [communityKey]: updatedCommunity },\n }));\n\n // if a community has a role with an account's address add it to the account.communities\n accountsStore\n .getState()\n .accountsActionsInternal.addCommunityRoleToAccountsCommunities(updatedCommunity);\n\n // add page comments to communitiesPagesStore so they can be used in useComment\n communitiesPagesStore.getState().addCommunityPageCommentsToStore(updatedCommunity);\n });\n\n community.on(\"updatingstatechange\", (updatingState: string) => {\n setState((state: CommunitiesState) => ({\n syncStatuses: getNextSyncStatuses(\n state,\n communityKey,\n normalizeCommunitySyncState(updatingState),\n ),\n communities: {\n ...state.communities,\n [communityKey]: { ...state.communities[communityKey], updatingState },\n },\n }));\n });\n\n community.on(\"error\", (error: Error) => {\n scheduleCommunityError(setState, communityKey, error);\n });\n\n // set clients on community so the frontend can display it, dont persist in db because a reload cancels updating\n utils.clientsOnStateChange(\n community?.clients,\n (clientState: string, clientType: string, clientUrl: string, chainTicker?: string) => {\n setState((state: CommunitiesState) => {\n // make sure not undefined, sometimes happens in e2e tests\n if (!state.communities[communityKey]) {\n return state;\n }\n const clients = { ...state.communities[communityKey]?.clients };\n const client = { state: clientState };\n if (chainTicker) {\n const chainProviders = { ...clients[clientType][chainTicker], [clientUrl]: client };\n clients[clientType] = { ...clients[clientType], [chainTicker]: chainProviders };\n } else {\n clients[clientType] = { ...clients[clientType], [clientUrl]: client };\n }\n return {\n communities: {\n ...state.communities,\n [communityKey]: { ...state.communities[communityKey], clients },\n },\n };\n });\n },\n );\n\n listeners.push(community);\n startCommunityUpdatePolling(community, { communityAddressOrRef, communityKey });\n } catch (error) {\n updateCommunitySyncStatus(setState, communityKey, \"failed\");\n throw error;\n } finally {\n pkcGetCommunityPending[pendingKey] = false;\n }\n },\n\n async refreshCommunity(communityAddressOrRef: string | CommunityIdentifier, account: Account) {\n const communityLookupOptions = getCommunityLookupOptions(communityAddressOrRef);\n const communityKey =\n typeof communityAddressOrRef === \"string\"\n ? communityAddressOrRef\n : getCommunityRefKey(communityAddressOrRef);\n assert(\n communityKey !== \"\" && typeof communityKey === \"string\",\n `communitiesStore.refreshCommunity invalid communityAddress argument '${communityAddressOrRef}'`,\n );\n assert(\n typeof getPkcGetCommunity(account?.pkc) === \"function\",\n `communitiesStore.refreshCommunity invalid account argument '${account}'`,\n );\n\n const refreshedCommunity = utils.clone(\n await getPkcCommunity(account.pkc, communityLookupOptions),\n );\n refreshedCommunity.fetchedAt = Math.floor(Date.now() / 1000);\n\n await communitiesDatabase.setItem(communityKey, refreshedCommunity);\n log(\"communitiesStore.refreshCommunity\", {\n communityAddressOrRef,\n communityKey,\n refreshedCommunity,\n account,\n });\n setState((state: any) => ({\n communities: { ...state.communities, [communityKey]: refreshedCommunity },\n }));\n\n communitiesPagesStore.getState().addCommunityPageCommentsToStore(refreshedCommunity);\n\n return refreshedCommunity;\n },\n\n // user is the owner of the community and can edit it locally\n async editCommunity(communityAddress: string, communityEditOptions: any, account: Account) {\n assert(\n communityAddress !== \"\" && typeof communityAddress === \"string\",\n `communitiesStore.editCommunity invalid communityAddress argument '${communityAddress}'`,\n );\n assert(\n communityEditOptions && typeof communityEditOptions === \"object\",\n `communitiesStore.editCommunity invalid communityEditOptions argument '${communityEditOptions}'`,\n );\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesStore.editCommunity invalid account argument '${account}'`,\n );\n\n // if not added to store first, community.update() is never called\n await getState().addCommunityToStore(communityAddress, account);\n\n // `communityAddress` is different from `communityEditOptions.address` when editing the community address\n const community = await createPkcCommunity(account.pkc, {\n address: communityAddress,\n });\n\n // could fix some test issues\n community.on(\"error\", console.log);\n\n await community.edit(communityEditOptions);\n\n const updatedCommunity = utils.clone(community);\n // edit db of both old and new community address to not break the UI\n await communitiesDatabase.setItem(communityAddress, updatedCommunity);\n await communitiesDatabase.setItem(community.address, updatedCommunity);\n log(\"communitiesStore.editCommunity\", {\n communityAddress,\n communityEditOptions,\n community,\n account,\n });\n setState((state: any) => ({\n communities: {\n ...state.communities,\n // edit react state of both old and new community address to not break the UI\n [communityAddress]: updatedCommunity,\n [community.address]: updatedCommunity,\n },\n }));\n },\n\n // internal action called by accountsActions.createCommunity\n async createCommunity(createCommunityOptions: CreateCommunityOptions, account: Account) {\n assert(\n !createCommunityOptions || typeof createCommunityOptions === \"object\",\n `communitiesStore.createCommunity invalid createCommunityOptions argument '${createCommunityOptions}'`,\n );\n if (!createCommunityOptions?.signer) {\n assert(\n !createCommunityOptions?.address,\n `communitiesStore.createCommunity createCommunityOptions.address '${createCommunityOptions?.address}' must be undefined to create a community`,\n );\n }\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesStore.createCommunity invalid account argument '${account}'`,\n );\n\n const community = await createPkcCommunity(account.pkc, createCommunityOptions);\n\n // could fix some test issues\n community.on(\"error\", console.log);\n\n // if not added to store first, community.update() is never called\n await getState().addCommunityToStore(community.address, account);\n\n await communitiesDatabase.setItem(community.address, utils.clone(community));\n log(\"communitiesStore.createCommunity\", { createCommunityOptions, community, account });\n setState((state: any) => ({\n communities: { ...state.communities, [community.address]: utils.clone(community) },\n }));\n return community;\n },\n\n // internal action called by accountsActions.deleteCommunity\n async deleteCommunity(communityAddress: string, account: Account) {\n assert(\n communityAddress && typeof communityAddress === \"string\",\n `communitiesStore.deleteCommunity invalid communityAddress argument '${communityAddress}'`,\n );\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesStore.deleteCommunity invalid account argument '${account}'`,\n );\n\n const community = await createPkcCommunity(account.pkc, {\n address: communityAddress,\n });\n\n // could fix some test issues\n community.on(\"error\", console.log);\n\n await community.delete();\n stopCommunityUpdatePolling(communityAddress);\n await communitiesDatabase.removeItem(communityAddress);\n log(\"communitiesStore.deleteCommunity\", { communityAddress, community, account });\n setState((state: CommunitiesState) => {\n const syncStatuses = { ...state.syncStatuses };\n delete syncStatuses[communityAddress];\n const errors = { ...state.errors };\n delete errors[communityAddress];\n return {\n communities: { ...state.communities, [communityAddress]: undefined },\n errors,\n syncStatuses,\n };\n });\n },\n }),\n);\n\n// reset store in between tests\nconst originalState = communitiesStore.getState();\n// async function because some stores have async init\nexport const resetCommunitiesStore = async () => {\n pkcGetCommunityPending = {};\n Object.keys(pendingCommunityErrorTimers).forEach(clearPendingCommunityErrors);\n // remove all event listeners\n listeners.forEach((listener: any) => listener.removeAllListeners());\n listeners.length = 0;\n Object.keys(communityUpdatePollers).forEach(stopCommunityUpdatePolling);\n // destroy all component subscriptions to the store\n communitiesStore.destroy();\n // restore original state\n communitiesStore.setState(originalState);\n};\n\n// reset database and store in between tests\nexport const resetCommunitiesDatabaseAndStore = async () => {\n await localForageLru.createInstance({ name: \"bitsocialReactHooks-communities\" }).clear();\n await resetCommunitiesStore();\n};\n\nexport default communitiesStore;\n"]}
1
+ {"version":3,"file":"communities-store.js","sourceRoot":"","sources":["../../../src/stores/communities/communities-store.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,OAAO,MAAM,MAAM,kBAAkB,CAAC;AACtC,OAAO,cAAc,MAAM,2BAA2B,CAAC;AACvD,MAAM,mBAAmB,GAAG,cAAc,CAAC,cAAc,CAAC;IACxD,IAAI,EAAE,iCAAiC;IACvC,IAAI,EAAE,GAAG;CACV,CAAC,CAAC;AACH,OAAO,MAAM,MAAM,yBAAyB,CAAC;AAC7C,MAAM,GAAG,GAAG,MAAM,CAAC,0CAA0C,CAAC,CAAC;AAS/D,OAAO,KAAK,MAAM,iBAAiB,CAAC;AACpC,OAAO,WAAW,MAAM,SAAS,CAAC;AAClC,OAAO,aAAa,MAAM,aAAa,CAAC;AACxC,OAAO,qBAAqB,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AACxF,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,wBAAwB,EACxB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,sBAAsB,CAAC;AAE9B,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE3D,+FAA+F;AAC/F,kGAAkG;AAClG,8FAA8F;AAC9F,+FAA+F;AAC/F,0FAA0F;AAC1F,6DAA6D;AAC7D,MAAM,CAAC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CAAC,CAAA,CAAC;AAEF,eAAe,gBAAgB,CAAC","sourcesContent":["import assert from \"../../lib/assert\";\nimport localForageLru from \"../../lib/localforage-lru\";\nconst communitiesDatabase = localForageLru.createInstance({\n name: \"bitsocialReactHooks-communities\",\n size: 500,\n});\nimport Logger from \"@pkcprotocol/pkc-logger\";\nconst log = Logger(\"bitsocial-react-hooks:communities:stores\");\nimport {\n Community,\n Communities,\n Account,\n CommunityIdentifier,\n CommunitySyncState,\n CreateCommunityOptions,\n} from \"../../types\";\nimport utils from \"../../lib/utils\";\nimport createStore from \"zustand\";\nimport accountsStore from \"../accounts\";\nimport communitiesPagesStore from \"../communities-pages\";\nimport { getCommunityLookupOptions, getCommunityRefKey } from \"../../lib/community-ref\";\nimport {\n createPkcCommunity,\n getPkcCommunity,\n getPkcCommunityAddresses,\n getPkcCreateCommunity,\n getPkcGetCommunity,\n} from \"../../lib/pkc-compat\";\n\nexport const COMMUNITY_UPDATE_INTERVAL_MS = 15 * 60 * 1000;\n\n// How long a community keeps updating after nothing uses it anymore. pkc-js forgets the record\n// CIDs and gateway ETags it already loaded when a community stops, so every restart downloads the\n// whole record again, while a running loop downloads it once per publish. Communities publish\n// between every ~20 seconds when busy and every 15 minutes when idle, so 2 minutes keeps quick\n// back-and-forth navigation from re-downloading records and bounds what an abandoned busy\n// community costs to about one restart's worth of downloads.\nexport const COMMUNITY_UPDATE_STOP_GRACE_MS = 2 * 60 * 1000;\n\nlet pkcGetCommunityPending: { [key: string]: boolean } = {};\n\n// The pkc-js instance kept for each community in the store, keyed by community so\n// delete/reset can stop it and subscribers can stop and restart its update loop.\ntype LiveCommunity = {\n community: any;\n communityAddressOrRef: string | CommunityIdentifier;\n // defined while the update loop runs\n updateInterval?: ReturnType<typeof setInterval>;\n updateCall?: Promise<void>;\n stopping?: Promise<void>;\n // update() re-emits the record the instance already holds, recognized so it is not stored as\n // a new fetch\n replayRecordId?: string;\n // the cached record replayed on the first update() counts as fetched, a record replayed on a\n // restart keeps the fetchedAt of its real fetch\n replayRefreshesFetchedAt: boolean;\n // the loop started and has neither fetched a record nor failed yet\n openingUpdatePending: boolean;\n stopWhenOpeningUpdateEnds: boolean;\n onUpdatingStateChange: (updatingState: string) => void;\n};\nconst liveCommunities: { [communityKey: string]: LiveCommunity } = {};\n// hooks and feeds that need a community kept updating, the loop stops after the last one leaves\nconst communityUpdateSubscribers: { [communityKey: string]: Set<string> } = {};\nconst communityStopTimers: { [communityKey: string]: ReturnType<typeof setTimeout> } = {};\n\n// reset all event listeners in between tests\nconst listeners: any = [];\n\nconst COMMUNITY_ERROR_UPDATE_GRACE_MS = 1000;\nconst pendingCommunityErrorTimers: {\n [communityKey: string]: ReturnType<typeof setTimeout>[];\n} = {};\n\ninterface CommunitySyncStatus {\n syncState: CommunitySyncState;\n lastFetchAttemptAt?: number;\n lastSuccessfulFetchAt?: number;\n // why the community is being retried; retriable errors stay out of `errors` so they do not\n // flash in the UI, but a community that never loads needs a reason to show\n lastRetriableError?: Error;\n // stopped because nothing used it, the next subscriber restarts it\n stoppedUntilUsed?: true;\n}\n\nconst omitLastRetriableError = (syncStatus: CommunitySyncStatus): CommunitySyncStatus => {\n const nextSyncStatus = { ...syncStatus };\n delete nextSyncStatus.lastRetriableError;\n return nextSyncStatus;\n};\n\nconst getNowSeconds = () => Math.floor(Date.now() / 1000);\n\nconst normalizeCommunitySyncState = (updatingState: string): CommunitySyncState => {\n if (updatingState === \"waiting-retry\") {\n return \"retrying\";\n }\n if (updatingState === \"succeeded\" || updatingState === \"failed\" || updatingState === \"stopped\") {\n return updatingState;\n }\n return \"loading\";\n};\n\nconst getNextSyncStatuses = (\n state: CommunitiesState,\n communityKey: string,\n syncState: CommunitySyncState,\n) => {\n const previousStatus = state.syncStatuses[communityKey];\n const timestamp = getNowSeconds();\n const shouldRecordAttempt = syncState === \"loading\" && previousStatus?.syncState !== \"loading\";\n const nextStatus: CommunitySyncStatus = {\n ...previousStatus,\n syncState,\n ...(shouldRecordAttempt ? { lastFetchAttemptAt: timestamp } : undefined),\n ...(syncState === \"succeeded\" ? { lastSuccessfulFetchAt: timestamp } : undefined),\n };\n return {\n ...state.syncStatuses,\n // a success ends the retries, so their error is no longer current\n [communityKey]: syncState === \"succeeded\" ? omitLastRetriableError(nextStatus) : nextStatus,\n };\n};\n\nconst updateCommunitySyncStatus = (\n setState: Function,\n communityKey: string,\n syncState: CommunitySyncState,\n) => {\n setState((state: CommunitiesState) => ({\n ...state,\n syncStatuses: getNextSyncStatuses(state, communityKey, syncState),\n }));\n};\n\n// identifies a signed community record, to recognize pkc-js re-emitting a record already in the store\nconst getCommunityRecordId = (community: any): string | undefined => {\n const signature = community?.signature?.signature;\n if (typeof signature !== \"string\" || typeof community?.updatedAt !== \"number\") {\n return;\n }\n return `${community.updatedAt}:${signature}`;\n};\n\nconst createCommunityWithLookupFallback = async (\n pkc: any,\n communityLookupOptions: { address?: string; name?: string; publicKey?: string },\n communityKey: string,\n) => {\n const supportsAddressLookup = \"address\" in communityLookupOptions;\n const community = await createPkcCommunity(pkc, communityLookupOptions);\n if (community?.address || supportsAddressLookup) {\n return community;\n }\n throw Error(`communitiesStore.addCommunityToStore failed getting community '${communityKey}'`);\n};\n\nconst getCommunityKey = (communityAddressOrRef: string | CommunityIdentifier) =>\n typeof communityAddressOrRef === \"string\"\n ? communityAddressOrRef\n : getCommunityRefKey(communityAddressOrRef);\n\nconst hasCommunityUpdateSubscribers = (communityKey: string) =>\n (communityUpdateSubscribers[communityKey]?.size || 0) > 0;\n\nconst updateCommunity = (communityKey: string, liveCommunity: LiveCommunity) => {\n const { community, communityAddressOrRef } = liveCommunity;\n liveCommunity.updateCall = Promise.resolve()\n .then(() => community.update())\n .catch((error: unknown) =>\n log.trace(\"community.update error\", {\n communityAddressOrRef,\n communityKey,\n community,\n error,\n }),\n );\n};\n\nconst startCommunityUpdatePolling = (communityKey: string, liveCommunity: LiveCommunity) => {\n clearInterval(liveCommunity.updateInterval);\n liveCommunity.openingUpdatePending = true;\n liveCommunity.stopWhenOpeningUpdateEnds = false;\n updateCommunity(communityKey, liveCommunity);\n liveCommunity.updateInterval = setInterval(\n () => updateCommunity(communityKey, liveCommunity),\n COMMUNITY_UPDATE_INTERVAL_MS,\n );\n};\n\nconst pauseCommunityUpdatePolling = (communityKey: string) => {\n const liveCommunity = liveCommunities[communityKey];\n if (!liveCommunity?.updateInterval) {\n return;\n }\n clearInterval(liveCommunity.updateInterval);\n liveCommunity.updateInterval = undefined;\n liveCommunity.openingUpdatePending = false;\n liveCommunity.stopWhenOpeningUpdateEnds = false;\n liveCommunity.replayRecordId = undefined;\n clearPendingCommunityErrors(communityKey);\n const { community, updateCall } = liveCommunity;\n // stopping while update() is still attaching to the shared updating instance would leave its\n // listeners attached, so wait for the call to return first\n const stopping = (async () => {\n await updateCall;\n if (typeof community.stop !== \"function\") {\n return;\n }\n try {\n await community.stop();\n } catch (error) {\n log.trace(\"community.stop error\", { communityKey, community, error });\n }\n })();\n liveCommunity.stopping = stopping;\n stopping.finally(() => {\n if (liveCommunity.stopping === stopping) {\n liveCommunity.stopping = undefined;\n }\n });\n log(\"communitiesStore community update loop stopped\", { communityKey });\n};\n\nconst resumeCommunityUpdatePolling = async (communityKey: string) => {\n const liveCommunity = liveCommunities[communityKey];\n if (!liveCommunity || liveCommunity.updateInterval) {\n return;\n }\n // update() is a no-op until a stop in progress ends\n if (liveCommunity.stopping) {\n await liveCommunity.stopping;\n }\n if (\n liveCommunities[communityKey] !== liveCommunity ||\n liveCommunity.updateInterval ||\n !hasCommunityUpdateSubscribers(communityKey)\n ) {\n return;\n }\n liveCommunity.replayRecordId = getCommunityRecordId(liveCommunity.community);\n liveCommunity.replayRefreshesFetchedAt = false;\n startCommunityUpdatePolling(communityKey, liveCommunity);\n log(\"communitiesStore community update loop restarted\", { communityKey });\n // joining a shared pkc-js instance that another consumer kept updating emits no state change\n // until its next fetch, so take its current state\n await liveCommunity.updateCall;\n const { updatingState } = liveCommunity.community;\n if (\n liveCommunity.updateInterval &&\n typeof updatingState === \"string\" &&\n updatingState !== \"stopped\" &&\n communitiesStore.getState().syncStatuses[communityKey]?.stoppedUntilUsed\n ) {\n liveCommunity.onUpdatingStateChange(updatingState);\n }\n};\n\nconst clearCommunityStopTimer = (communityKey: string) => {\n clearTimeout(communityStopTimers[communityKey]);\n delete communityStopTimers[communityKey];\n};\n\nconst scheduleCommunityUpdateStop = (communityKey: string) => {\n clearCommunityStopTimer(communityKey);\n communityStopTimers[communityKey] = setTimeout(() => {\n delete communityStopTimers[communityKey];\n const liveCommunity = liveCommunities[communityKey];\n if (hasCommunityUpdateSubscribers(communityKey) || !liveCommunity?.updateInterval) {\n return;\n }\n // stopping before the first fetch ends would leave a store-level caller without the record\n // it loaded the community for\n if (liveCommunity.openingUpdatePending) {\n liveCommunity.stopWhenOpeningUpdateEnds = true;\n return;\n }\n pauseCommunityUpdatePolling(communityKey);\n }, COMMUNITY_UPDATE_STOP_GRACE_MS);\n};\n\nconst endOpeningCommunityUpdate = (communityKey: string, liveCommunity: LiveCommunity) => {\n if (!liveCommunity.openingUpdatePending) {\n return;\n }\n liveCommunity.openingUpdatePending = false;\n if (!liveCommunity.stopWhenOpeningUpdateEnds) {\n return;\n }\n liveCommunity.stopWhenOpeningUpdateEnds = false;\n if (!hasCommunityUpdateSubscribers(communityKey)) {\n pauseCommunityUpdatePolling(communityKey);\n }\n};\n\nconst stopCommunityUpdatePolling = (communityKey: string) => {\n clearCommunityStopTimer(communityKey);\n const liveCommunity = liveCommunities[communityKey];\n if (!liveCommunity) {\n return;\n }\n\n clearPendingCommunityErrors(communityKey);\n clearInterval(liveCommunity.updateInterval);\n liveCommunity.updateInterval = undefined;\n liveCommunity.community.removeAllListeners();\n const listenerIndex = listeners.indexOf(liveCommunity.community);\n if (listenerIndex >= 0) {\n listeners.splice(listenerIndex, 1);\n }\n delete liveCommunities[communityKey];\n};\n\nconst clearPendingCommunityErrors = (communityKey: string) => {\n pendingCommunityErrorTimers[communityKey]?.forEach((timeout) => clearTimeout(timeout));\n delete pendingCommunityErrorTimers[communityKey];\n};\n\nconst clearStoredCommunityErrors = (state: CommunitiesState, communityKey: string) => {\n if (!state.errors[communityKey]) {\n return state.errors;\n }\n const nextErrors = { ...state.errors };\n delete nextErrors[communityKey];\n return nextErrors;\n};\n\n// returning the same state skips notifying subscribers when there is nothing to clear\nconst clearStoredCommunityErrorsState = (state: CommunitiesState, communityKey: string) => {\n const syncStatus = state.syncStatuses[communityKey];\n const hasRetriableError = syncStatus?.lastRetriableError !== undefined;\n if (!state.errors[communityKey] && !hasRetriableError) {\n return state;\n }\n return {\n ...state,\n errors: clearStoredCommunityErrors(state, communityKey),\n syncStatuses: hasRetriableError\n ? { ...state.syncStatuses, [communityKey]: omitLastRetriableError(syncStatus) }\n : state.syncStatuses,\n };\n};\n\nexport const isRetriableCommunityLoadError = (error: Error) => {\n const details = (error as Error & { details?: unknown }).details;\n return Boolean(\n details &&\n typeof details === \"object\" &&\n \"retriableError\" in details &&\n (details as { retriableError?: unknown }).retriableError === true,\n );\n};\n\nconst recordRetriableCommunityError = (setState: Function, communityKey: string, error: Error) => {\n setState((state: CommunitiesState) => {\n const syncStatus = state.syncStatuses[communityKey];\n // a deleted community has no sync status left to report on\n if (!syncStatus) {\n return state;\n }\n return {\n syncStatuses: {\n ...state.syncStatuses,\n [communityKey]: { ...syncStatus, lastRetriableError: error },\n },\n };\n });\n};\n\nconst scheduleCommunityError = (setState: Function, communityKey: string, error: Error) => {\n if (isRetriableCommunityLoadError(error)) {\n recordRetriableCommunityError(setState, communityKey, error);\n return;\n }\n\n const timeout = setTimeout(() => {\n const pendingTimeouts = pendingCommunityErrorTimers[communityKey];\n if (!pendingTimeouts?.includes(timeout)) {\n return;\n }\n\n const remainingTimeouts = pendingTimeouts.filter(\n (pendingTimeout) => pendingTimeout !== timeout,\n );\n if (remainingTimeouts.length === 0) {\n delete pendingCommunityErrorTimers[communityKey];\n } else {\n pendingCommunityErrorTimers[communityKey] = remainingTimeouts;\n }\n setState((state: CommunitiesState) => {\n const communityErrors = state.errors[communityKey] || [];\n return {\n ...state,\n errors: { ...state.errors, [communityKey]: [...communityErrors, error] },\n };\n });\n }, COMMUNITY_ERROR_UPDATE_GRACE_MS);\n\n pendingCommunityErrorTimers[communityKey] = [\n ...(pendingCommunityErrorTimers[communityKey] || []),\n timeout,\n ];\n};\n\nexport type CommunitiesState = {\n communities: Communities;\n errors: { [communityAddress: string]: Error[] };\n syncStatuses: { [communityAddress: string]: CommunitySyncStatus };\n addCommunityToStore: Function;\n startCommunityAutoUpdate: Function;\n stopCommunityAutoUpdate: Function;\n refreshCommunity: Function;\n editCommunity: Function;\n createCommunity: Function;\n deleteCommunity: Function;\n};\n\nconst communitiesStore = createStore<CommunitiesState>(\n (setState: Function, getState: Function) => ({\n communities: {},\n errors: {},\n syncStatuses: {},\n\n async addCommunityToStore(\n communityAddressOrRef: string | CommunityIdentifier,\n account: Account,\n ) {\n const communityLookupOptions = getCommunityLookupOptions(communityAddressOrRef);\n const communityKey =\n typeof communityAddressOrRef === \"string\"\n ? communityAddressOrRef\n : getCommunityRefKey(communityAddressOrRef);\n assert(\n communityKey !== \"\" && typeof communityKey === \"string\",\n `communitiesStore.addCommunityToStore invalid communityAddress argument '${communityAddressOrRef}'`,\n );\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesStore.addCommunityToStore invalid account argument '${account}'`,\n );\n\n // community is in store already, do nothing\n const { communities } = getState();\n let community: Community | undefined = communities[communityKey];\n const pendingKey = communityKey + account.id;\n if (community || pkcGetCommunityPending[pendingKey]) {\n return;\n }\n\n // start trying to get community\n pkcGetCommunityPending[pendingKey] = true;\n updateCommunitySyncStatus(setState, communityKey, \"initializing\");\n let errorGettingCommunity: any;\n try {\n // try to find community in owner communities\n if (getPkcCommunityAddresses(account.pkc).includes(communityKey)) {\n try {\n community = await createCommunityWithLookupFallback(\n account.pkc,\n communityLookupOptions,\n communityKey,\n );\n } catch (e) {\n errorGettingCommunity = e;\n }\n }\n\n // try to find community in database\n let fetchedAt: number | undefined;\n let isFromCache = false;\n if (!community) {\n const communityData: any = await communitiesDatabase.getItem(communityKey);\n const lookupName =\n \"name\" in communityLookupOptions ? communityLookupOptions.name : undefined;\n const lookupPublicKey =\n \"publicKey\" in communityLookupOptions ? communityLookupOptions.publicKey : undefined;\n const lookupAddress =\n \"address\" in communityLookupOptions ? communityLookupOptions.address : undefined;\n const hasCachedPosts =\n Object.keys(communityData?.posts?.pageCids || {}).length > 0 ||\n Object.keys(communityData?.posts?.pages || {}).length > 0;\n const isUnresolvedNameCache =\n communityData &&\n lookupName &&\n !lookupPublicKey &&\n !lookupAddress &&\n !communityData.publicKey &&\n !communityData.updatedAt &&\n !communityData.updateCid &&\n !communityData.title &&\n !communityData.description &&\n !hasCachedPosts;\n if (communityData && !isUnresolvedNameCache) {\n fetchedAt = communityData.fetchedAt;\n delete communityData.fetchedAt; // not part of pkc-js schema\n try {\n community = await createPkcCommunity(account.pkc, communityData);\n isFromCache = Boolean(community);\n } catch (e) {\n fetchedAt = undefined;\n // need to log this always or it could silently fail in production and cache never be used\n console.error(\"failed pkc.createCommunity(cachedCommunity)\", {\n cachedCommunity: communityData,\n error: e,\n });\n }\n }\n if (community) {\n // add page comments to communitiesPagesStore so they can be used in useComment\n communitiesPagesStore.getState().addCommunityPageCommentsToStore(community);\n }\n }\n\n // community not in database, try to fetch from pkc-js\n if (!community) {\n try {\n community = await createCommunityWithLookupFallback(\n account.pkc,\n communityLookupOptions,\n communityKey,\n );\n } catch (e) {\n errorGettingCommunity = e;\n }\n }\n\n // failure getting community\n if (!community) {\n if (errorGettingCommunity) {\n setState((state: CommunitiesState) => {\n let communityErrors = state.errors[communityKey] || [];\n communityErrors = [...communityErrors, errorGettingCommunity];\n return { ...state, errors: { ...state.errors, [communityKey]: communityErrors } };\n });\n }\n\n throw (\n errorGettingCommunity ||\n Error(`communitiesStore.addCommunityToStore failed getting community '${communityKey}'`)\n );\n }\n\n // success getting community\n const firstCommunityState = utils.clone({\n ...community,\n ...(fetchedAt !== undefined ? { fetchedAt } : undefined),\n });\n // a cache hit already is the database entry, rewriting it would only delay the store\n // update behind an IndexedDB write of the whole record\n if (!isFromCache) {\n await communitiesDatabase.setItem(communityKey, firstCommunityState);\n }\n // another load of this community, e.g. by another account, finished first and keeps it\n // updating, so this instance is discarded before it starts updating\n if (liveCommunities[communityKey]) {\n return;\n }\n log(\"communitiesStore.addCommunityToStore\", {\n communityAddressOrRef,\n communityKey,\n community,\n account,\n });\n setState((state: any) => ({\n communities: { ...state.communities, [communityKey]: firstCommunityState },\n }));\n\n const liveCommunity: LiveCommunity = {\n community,\n communityAddressOrRef,\n // pkc-js re-emits the record a community was created with when update() starts\n replayRecordId: isFromCache ? getCommunityRecordId(firstCommunityState) : undefined,\n replayRefreshesFetchedAt: true,\n openingUpdatePending: false,\n stopWhenOpeningUpdateEnds: false,\n onUpdatingStateChange: (updatingState: string) => {\n setState((state: CommunitiesState) => {\n const syncStatuses = getNextSyncStatuses(\n state,\n communityKey,\n normalizeCommunitySyncState(updatingState),\n );\n const { stoppedUntilUsed: _stoppedUntilUsed, ...syncStatus } =\n syncStatuses[communityKey];\n // the loop is not running when the store stopped the community itself\n syncStatuses[communityKey] =\n updatingState === \"stopped\" && !liveCommunity.updateInterval\n ? { ...syncStatus, stoppedUntilUsed: true }\n : syncStatus;\n return {\n syncStatuses,\n communities: {\n ...state.communities,\n [communityKey]: { ...state.communities[communityKey], updatingState },\n },\n };\n });\n if (\n updatingState === \"succeeded\" ||\n updatingState === \"failed\" ||\n updatingState === \"waiting-retry\"\n ) {\n endOpeningCommunityUpdate(communityKey, liveCommunity);\n }\n },\n };\n\n // the community has published new posts\n community.on(\"update\", async (updatedCommunity: Community) => {\n clearPendingCommunityErrors(communityKey);\n setState((state: CommunitiesState) =>\n clearStoredCommunityErrorsState(state, communityKey),\n );\n\n const isRecordReplay =\n liveCommunity.replayRecordId !== undefined &&\n getCommunityRecordId(updatedCommunity) === liveCommunity.replayRecordId;\n liveCommunity.replayRecordId = undefined;\n if (isRecordReplay && !liveCommunity.replayRefreshesFetchedAt) {\n // a restarted loop replays the record the store already has, it was not fetched now\n return;\n }\n if (isRecordReplay) {\n // the replayed record is already in the store and the database, only refresh fetchedAt\n // like a fetched update would, without cloning and rewriting the whole record\n setState((state: CommunitiesState) => {\n const storedCommunity = state.communities[communityKey];\n if (!storedCommunity) {\n return state;\n }\n return {\n communities: {\n ...state.communities,\n [communityKey]: { ...storedCommunity, fetchedAt: getNowSeconds() },\n },\n };\n });\n // pass the cloned record, account state keeps references to its roles\n accountsStore\n .getState()\n .accountsActionsInternal.addCommunityRoleToAccountsCommunities(firstCommunityState);\n return;\n }\n\n updatedCommunity = utils.clone(updatedCommunity);\n\n // add fetchedAt to be able to expire the cache\n // NOTE: fetchedAt is undefined on owner communities because never stale\n updatedCommunity.fetchedAt = Math.floor(Date.now() / 1000);\n\n // pkc-js reports the fetch succeeded right after this event, so store the record first:\n // a succeeded sync state must not be shown with the previous record, e.g. a stale one\n // kept while the community was not updating\n setState((state: any) => ({\n ...state,\n communities: { ...state.communities, [communityKey]: updatedCommunity },\n }));\n log(\"communitiesStore community update\", {\n communityAddressOrRef,\n communityKey,\n updatedCommunity,\n account,\n });\n await communitiesDatabase.setItem(communityKey, updatedCommunity);\n\n // if a community has a role with an account's address add it to the account.communities\n accountsStore\n .getState()\n .accountsActionsInternal.addCommunityRoleToAccountsCommunities(updatedCommunity);\n\n // add page comments to communitiesPagesStore so they can be used in useComment\n communitiesPagesStore.getState().addCommunityPageCommentsToStore(updatedCommunity);\n\n endOpeningCommunityUpdate(communityKey, liveCommunity);\n });\n\n community.on(\"updatingstatechange\", liveCommunity.onUpdatingStateChange);\n\n community.on(\"error\", (error: Error) => {\n scheduleCommunityError(setState, communityKey, error);\n });\n\n // set clients on community so the frontend can display it, dont persist in db because a reload cancels updating\n utils.clientsOnStateChange(\n community?.clients,\n (clientState: string, clientType: string, clientUrl: string, chainTicker?: string) => {\n setState((state: CommunitiesState) => {\n // make sure not undefined, sometimes happens in e2e tests\n if (!state.communities[communityKey]) {\n return state;\n }\n const clients = { ...state.communities[communityKey]?.clients };\n const client = { state: clientState };\n if (chainTicker) {\n const chainProviders = { ...clients[clientType][chainTicker], [clientUrl]: client };\n clients[clientType] = { ...clients[clientType], [chainTicker]: chainProviders };\n } else {\n clients[clientType] = { ...clients[clientType], [clientUrl]: client };\n }\n return {\n communities: {\n ...state.communities,\n [communityKey]: { ...state.communities[communityKey], clients },\n },\n };\n });\n },\n );\n\n listeners.push(community);\n liveCommunities[communityKey] = liveCommunity;\n startCommunityUpdatePolling(communityKey, liveCommunity);\n // loaded without a subscriber, e.g. by a store-level caller: update until the grace period\n // ends, and at least until the first fetch ends\n if (!hasCommunityUpdateSubscribers(communityKey)) {\n scheduleCommunityUpdateStop(communityKey);\n }\n } catch (error) {\n updateCommunitySyncStatus(setState, communityKey, \"failed\");\n throw error;\n } finally {\n pkcGetCommunityPending[pendingKey] = false;\n }\n },\n\n // keep a community updating while a subscriber (a mounted hook or feed) needs it, and restart\n // its update loop if it stopped after its previous subscribers left\n async startCommunityAutoUpdate(\n communityAddressOrRef: string | CommunityIdentifier,\n subscriberId: string,\n account: Account,\n ) {\n const communityKey = getCommunityKey(communityAddressOrRef);\n assert(\n communityKey !== \"\" && typeof communityKey === \"string\",\n `communitiesStore.startCommunityAutoUpdate invalid communityAddress argument '${communityAddressOrRef}'`,\n );\n assert(\n subscriberId && typeof subscriberId === \"string\",\n `communitiesStore.startCommunityAutoUpdate invalid subscriberId argument '${subscriberId}'`,\n );\n if (!communityUpdateSubscribers[communityKey]) {\n communityUpdateSubscribers[communityKey] = new Set();\n }\n communityUpdateSubscribers[communityKey].add(subscriberId);\n clearCommunityStopTimer(communityKey);\n\n const liveCommunity = liveCommunities[communityKey];\n if (liveCommunity) {\n liveCommunity.stopWhenOpeningUpdateEnds = false;\n await resumeCommunityUpdatePolling(communityKey);\n return;\n }\n await getState().addCommunityToStore(communityAddressOrRef, account);\n },\n\n // the community stops updating a grace period after its last subscriber leaves\n async stopCommunityAutoUpdate(\n communityAddressOrRef: string | CommunityIdentifier,\n subscriberId: string,\n ) {\n const communityKey = getCommunityKey(communityAddressOrRef);\n const subscribers = communityUpdateSubscribers[communityKey];\n if (!subscribers?.delete(subscriberId)) {\n return;\n }\n if (subscribers.size > 0) {\n return;\n }\n delete communityUpdateSubscribers[communityKey];\n if (liveCommunities[communityKey]) {\n scheduleCommunityUpdateStop(communityKey);\n }\n },\n\n async refreshCommunity(communityAddressOrRef: string | CommunityIdentifier, account: Account) {\n const communityLookupOptions = getCommunityLookupOptions(communityAddressOrRef);\n const communityKey =\n typeof communityAddressOrRef === \"string\"\n ? communityAddressOrRef\n : getCommunityRefKey(communityAddressOrRef);\n assert(\n communityKey !== \"\" && typeof communityKey === \"string\",\n `communitiesStore.refreshCommunity invalid communityAddress argument '${communityAddressOrRef}'`,\n );\n assert(\n typeof getPkcGetCommunity(account?.pkc) === \"function\",\n `communitiesStore.refreshCommunity invalid account argument '${account}'`,\n );\n\n const refreshedCommunity = utils.clone(\n await getPkcCommunity(account.pkc, communityLookupOptions),\n );\n refreshedCommunity.fetchedAt = Math.floor(Date.now() / 1000);\n\n await communitiesDatabase.setItem(communityKey, refreshedCommunity);\n log(\"communitiesStore.refreshCommunity\", {\n communityAddressOrRef,\n communityKey,\n refreshedCommunity,\n account,\n });\n setState((state: any) => ({\n communities: { ...state.communities, [communityKey]: refreshedCommunity },\n }));\n\n communitiesPagesStore.getState().addCommunityPageCommentsToStore(refreshedCommunity);\n\n return refreshedCommunity;\n },\n\n // user is the owner of the community and can edit it locally\n async editCommunity(communityAddress: string, communityEditOptions: any, account: Account) {\n assert(\n communityAddress !== \"\" && typeof communityAddress === \"string\",\n `communitiesStore.editCommunity invalid communityAddress argument '${communityAddress}'`,\n );\n assert(\n communityEditOptions && typeof communityEditOptions === \"object\",\n `communitiesStore.editCommunity invalid communityEditOptions argument '${communityEditOptions}'`,\n );\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesStore.editCommunity invalid account argument '${account}'`,\n );\n\n // if not added to store first, community.update() is never called\n await getState().addCommunityToStore(communityAddress, account);\n\n // `communityAddress` is different from `communityEditOptions.address` when editing the community address\n const community = await createPkcCommunity(account.pkc, {\n address: communityAddress,\n });\n\n // could fix some test issues\n community.on(\"error\", console.log);\n\n await community.edit(communityEditOptions);\n\n const updatedCommunity = utils.clone(community);\n // edit db of both old and new community address to not break the UI\n await communitiesDatabase.setItem(communityAddress, updatedCommunity);\n await communitiesDatabase.setItem(community.address, updatedCommunity);\n log(\"communitiesStore.editCommunity\", {\n communityAddress,\n communityEditOptions,\n community,\n account,\n });\n setState((state: any) => ({\n communities: {\n ...state.communities,\n // edit react state of both old and new community address to not break the UI\n [communityAddress]: updatedCommunity,\n [community.address]: updatedCommunity,\n },\n }));\n },\n\n // internal action called by accountsActions.createCommunity\n async createCommunity(createCommunityOptions: CreateCommunityOptions, account: Account) {\n assert(\n !createCommunityOptions || typeof createCommunityOptions === \"object\",\n `communitiesStore.createCommunity invalid createCommunityOptions argument '${createCommunityOptions}'`,\n );\n if (!createCommunityOptions?.signer) {\n assert(\n !createCommunityOptions?.address,\n `communitiesStore.createCommunity createCommunityOptions.address '${createCommunityOptions?.address}' must be undefined to create a community`,\n );\n }\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesStore.createCommunity invalid account argument '${account}'`,\n );\n\n const community = await createPkcCommunity(account.pkc, createCommunityOptions);\n\n // could fix some test issues\n community.on(\"error\", console.log);\n\n // if not added to store first, community.update() is never called\n await getState().addCommunityToStore(community.address, account);\n\n await communitiesDatabase.setItem(community.address, utils.clone(community));\n log(\"communitiesStore.createCommunity\", { createCommunityOptions, community, account });\n setState((state: any) => ({\n communities: { ...state.communities, [community.address]: utils.clone(community) },\n }));\n return community;\n },\n\n // internal action called by accountsActions.deleteCommunity\n async deleteCommunity(communityAddress: string, account: Account) {\n assert(\n communityAddress && typeof communityAddress === \"string\",\n `communitiesStore.deleteCommunity invalid communityAddress argument '${communityAddress}'`,\n );\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesStore.deleteCommunity invalid account argument '${account}'`,\n );\n\n const community = await createPkcCommunity(account.pkc, {\n address: communityAddress,\n });\n\n // could fix some test issues\n community.on(\"error\", console.log);\n\n await community.delete();\n stopCommunityUpdatePolling(communityAddress);\n await communitiesDatabase.removeItem(communityAddress);\n log(\"communitiesStore.deleteCommunity\", { communityAddress, community, account });\n setState((state: CommunitiesState) => {\n const syncStatuses = { ...state.syncStatuses };\n delete syncStatuses[communityAddress];\n const errors = { ...state.errors };\n delete errors[communityAddress];\n return {\n communities: { ...state.communities, [communityAddress]: undefined },\n errors,\n syncStatuses,\n };\n });\n },\n }),\n);\n\n// reset store in between tests\nconst originalState = communitiesStore.getState();\n// async function because some stores have async init\nexport const resetCommunitiesStore = async () => {\n pkcGetCommunityPending = {};\n Object.keys(pendingCommunityErrorTimers).forEach(clearPendingCommunityErrors);\n // remove all event listeners\n listeners.forEach((listener: any) => listener.removeAllListeners());\n listeners.length = 0;\n Object.keys(liveCommunities).forEach(stopCommunityUpdatePolling);\n Object.keys(communityStopTimers).forEach(clearCommunityStopTimer);\n for (const communityKey in communityUpdateSubscribers) {\n delete communityUpdateSubscribers[communityKey];\n }\n // destroy all component subscriptions to the store\n communitiesStore.destroy();\n // restore original state\n communitiesStore.setState(originalState);\n};\n\n// reset database and store in between tests\nexport const resetCommunitiesDatabaseAndStore = async () => {\n await localForageLru.createInstance({ name: \"bitsocialReactHooks-communities\" }).clear();\n await resetCommunitiesStore();\n};\n\nexport default communitiesStore;\n"]}