@oxyhq/core 18.0.0 → 19.1.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.
Files changed (62) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/i18n/locales/en-US.json +49 -5
  3. package/dist/cjs/i18n/locales/es-ES.json +49 -5
  4. package/dist/cjs/i18n/locales/locales/en-US.json +49 -5
  5. package/dist/cjs/i18n/locales/locales/es-ES.json +49 -5
  6. package/dist/cjs/index.js +17 -6
  7. package/dist/cjs/mixins/OxyServices.accounts.js +69 -31
  8. package/dist/cjs/mixins/OxyServices.followGraph.js +204 -0
  9. package/dist/cjs/mixins/OxyServices.user.js +17 -20
  10. package/dist/cjs/mixins/index.js +4 -0
  11. package/dist/cjs/server/index.js +8 -2
  12. package/dist/cjs/server/userInvalidation.js +6 -28
  13. package/dist/cjs/session/accountProjection.js +45 -9
  14. package/dist/cjs/utils/accountCacheSweep.js +80 -0
  15. package/dist/cjs/utils/identityCacheSweep.js +97 -0
  16. package/dist/esm/.tsbuildinfo +1 -1
  17. package/dist/esm/i18n/locales/en-US.json +49 -5
  18. package/dist/esm/i18n/locales/es-ES.json +49 -5
  19. package/dist/esm/i18n/locales/locales/en-US.json +49 -5
  20. package/dist/esm/i18n/locales/locales/es-ES.json +49 -5
  21. package/dist/esm/index.js +8 -2
  22. package/dist/esm/mixins/OxyServices.accounts.js +64 -30
  23. package/dist/esm/mixins/OxyServices.followGraph.js +201 -0
  24. package/dist/esm/mixins/OxyServices.user.js +17 -20
  25. package/dist/esm/mixins/index.js +4 -0
  26. package/dist/esm/server/index.js +5 -1
  27. package/dist/esm/server/userInvalidation.js +5 -26
  28. package/dist/esm/session/accountProjection.js +44 -9
  29. package/dist/esm/utils/accountCacheSweep.js +75 -0
  30. package/dist/esm/utils/identityCacheSweep.js +92 -0
  31. package/dist/types/.tsbuildinfo +1 -1
  32. package/dist/types/index.d.ts +3 -3
  33. package/dist/types/mixins/OxyServices.accounts.d.ts +91 -34
  34. package/dist/types/mixins/OxyServices.followGraph.d.ts +211 -0
  35. package/dist/types/mixins/OxyServices.user.d.ts +10 -7
  36. package/dist/types/mixins/index.d.ts +2 -1
  37. package/dist/types/models/interfaces.d.ts +11 -3
  38. package/dist/types/server/index.d.ts +4 -2
  39. package/dist/types/server/userInvalidation.d.ts +5 -24
  40. package/dist/types/session/accountProjection.d.ts +38 -4
  41. package/dist/types/utils/accountCacheSweep.d.ts +75 -0
  42. package/dist/types/utils/identityCacheSweep.d.ts +80 -0
  43. package/package.json +2 -2
  44. package/src/i18n/locales/en-US.json +49 -5
  45. package/src/i18n/locales/es-ES.json +49 -5
  46. package/src/index.ts +15 -2
  47. package/src/mixins/OxyServices.accounts.ts +123 -45
  48. package/src/mixins/OxyServices.followGraph.ts +266 -0
  49. package/src/mixins/OxyServices.user.ts +17 -20
  50. package/src/mixins/__tests__/accounts.test.ts +5 -0
  51. package/src/mixins/__tests__/followGraph.test.ts +128 -0
  52. package/src/mixins/__tests__/identityWriteCacheInvalidation.test.ts +407 -0
  53. package/src/mixins/index.ts +5 -0
  54. package/src/models/interfaces.ts +11 -3
  55. package/src/server/__tests__/userInvalidation.test.ts +3 -20
  56. package/src/server/index.ts +5 -2
  57. package/src/server/userInvalidation.ts +8 -36
  58. package/src/session/__tests__/accountProjection.test.ts +109 -2
  59. package/src/session/accountProjection.ts +47 -9
  60. package/src/utils/__tests__/identityCacheSweep.test.ts +151 -0
  61. package/src/utils/accountCacheSweep.ts +93 -0
  62. package/src/utils/identityCacheSweep.ts +104 -0
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Follow Graph Mixin (`/v2/follows`)
3
+ *
4
+ * The user-owned follow graph: one relationship per user and target, shared by
5
+ * every application, with per-application context on top. This is the SDK half
6
+ * of #809 and the replacement for the per-app follow endpoints each application
7
+ * grew for itself.
8
+ *
9
+ * ## Why this is not `followUser` with more parameters
10
+ *
11
+ * `followUser` answers "does A follow B" and nothing else. This answers "what
12
+ * does this user follow, anywhere, and which applications act on it" — a
13
+ * different question with a different owner. The legacy methods stay for the
14
+ * Mongo-backed social graph they were written for; new kinds (topics, stores,
15
+ * artists, channels) come here, and users will migrate behind an adapter rather
16
+ * than through a flag day.
17
+ *
18
+ * ## Caching
19
+ *
20
+ * Every method is `cache: false`. A follow status is exactly the shape that
21
+ * must never be served stale: the SDK's GET cache is identity-scoped but
22
+ * time-based, and a status cached across a write is the "follow reverts after
23
+ * navigating away and back" bug — which the legacy `followUser` had to fix with
24
+ * explicit invalidation. Not caching at this layer means an app's own store
25
+ * (React Query, Zustand) is the single cache authority, which is the rule the
26
+ * ecosystem already follows for anything written and read in the same session.
27
+ */
28
+ import { buildUrl } from '../utils/apiUtils.js';
29
+ export function OxyServicesFollowGraphMixin(Base) {
30
+ return class extends Base {
31
+ constructor(...args) {
32
+ super(...args);
33
+ }
34
+ /**
35
+ * Follow a target. Idempotent — following something already followed
36
+ * returns the same relationship with `created: false`.
37
+ *
38
+ * The follower and the acting application are BOTH derived server-side from
39
+ * the session. There is deliberately no parameter for either: a client that
40
+ * could name them could forge a follow on another user's behalf, or record
41
+ * one as coming from an application it is not.
42
+ *
43
+ * @param targetId - The registered target's id, not its URI. Registration is
44
+ * a separate operation precisely so following cannot silently create
45
+ * targets — a typo would otherwise become a permanent row nobody follows.
46
+ * @param options.expiresIn - Seconds until the follow lapses on its own. For
47
+ * an event, a trial, a topic followed for a week. The server bounds it.
48
+ */
49
+ async followTarget(targetId, options) {
50
+ try {
51
+ return await this.makeRequest('PUT', `/v2/follows/${encodeURIComponent(targetId)}`, options?.expiresIn !== undefined ? { expiresIn: options.expiresIn } : {}, { cache: false });
52
+ }
53
+ catch (error) {
54
+ throw this.handleError(error);
55
+ }
56
+ }
57
+ /**
58
+ * Unfollow everywhere.
59
+ *
60
+ * There is no "unfollow here" — that is `setFollowApplicationMode(...,
61
+ * 'disabled')`, and keeping the two distinct is the point of the design. An
62
+ * application that quietly turned a global unfollow into a local one would
63
+ * leave the user believing they had stopped following something they still
64
+ * follow everywhere else.
65
+ *
66
+ * Idempotent: `removed: false` when it was already gone, because the state
67
+ * the caller asked for is the state that holds.
68
+ */
69
+ async unfollowTarget(relationshipId) {
70
+ try {
71
+ return await this.makeRequest('DELETE', `/v2/follows/${encodeURIComponent(relationshipId)}`, undefined, { cache: false });
72
+ }
73
+ catch (error) {
74
+ throw this.handleError(error);
75
+ }
76
+ }
77
+ /**
78
+ * The three-part status: globally, in this application, and in effect.
79
+ *
80
+ * Render `effectiveState` on the button and keep the other two for the
81
+ * explanation. A UI that collapses them cannot tell the user why a follow
82
+ * they can see in their list is not showing up in this app's feed.
83
+ */
84
+ async getFollowTargetStatus(targetId) {
85
+ try {
86
+ return await this.makeRequest('GET', `/v2/follows/${encodeURIComponent(targetId)}/status`, undefined, { cache: false });
87
+ }
88
+ catch (error) {
89
+ throw this.handleError(error);
90
+ }
91
+ }
92
+ /**
93
+ * Turn a relationship off, or back on, in ONE application.
94
+ *
95
+ * Omit `applicationId` and it applies to the calling application, which is
96
+ * the only form an ordinary app should ever need. Naming a DIFFERENT
97
+ * application requires `follows:manage` server-side — acting on another
98
+ * app's behalf is exactly the cross-application authority this design
99
+ * otherwise refuses, so it is a distinct permission and not a parameter an
100
+ * app happens to fill in.
101
+ */
102
+ async setFollowApplicationMode(relationshipId, mode, applicationId) {
103
+ try {
104
+ return await this.makeRequest('PUT', `/v2/follows/${encodeURIComponent(relationshipId)}/context`, { mode, ...(applicationId ? { applicationId } : {}) }, { cache: false });
105
+ }
106
+ catch (error) {
107
+ throw this.handleError(error);
108
+ }
109
+ }
110
+ /**
111
+ * Drop the override so this application follows the global relationship
112
+ * again. Distinct from setting `enabled`: inheriting means a later global
113
+ * change takes effect here, and an explicit `enabled` means it does not.
114
+ */
115
+ async restoreFollowInheritance(relationshipId, applicationId) {
116
+ try {
117
+ const path = buildUrl(`/v2/follows/${encodeURIComponent(relationshipId)}/context`, applicationId ? { applicationId } : {});
118
+ return await this.makeRequest('DELETE', path, undefined, { cache: false });
119
+ }
120
+ catch (error) {
121
+ throw this.handleError(error);
122
+ }
123
+ }
124
+ /**
125
+ * Resolve a target by canonical URI, registering it the first time anyone
126
+ * asks. The call an application makes on the way into a screen, before it
127
+ * can render a button.
128
+ *
129
+ * Idempotent on the URI, which is what makes two applications describing
130
+ * the same thing — the same fediverse actor, the same topic — arrive at ONE
131
+ * row, and therefore at one relationship per user rather than one per app.
132
+ *
133
+ * `metadata` is a display snapshot (name, handle, icon) and is refreshed
134
+ * only for the application that provides the target: a second application
135
+ * passing its own idea of the name would make the display flip depending on
136
+ * which app last looked.
137
+ */
138
+ async ensureFollowTarget(input) {
139
+ try {
140
+ return await this.makeRequest('POST', '/v2/follow-targets', input, { cache: false });
141
+ }
142
+ catch (error) {
143
+ throw this.handleError(error);
144
+ }
145
+ }
146
+ /**
147
+ * Claim a namespace for the calling application. First come, and idempotent
148
+ * for the holder — an application that registers on every boot must not
149
+ * fail the second time.
150
+ */
151
+ async claimFollowNamespace(namespace) {
152
+ try {
153
+ return await this.makeRequest('POST', '/v2/follow-targets/namespaces', { namespace }, { cache: false });
154
+ }
155
+ catch (error) {
156
+ throw this.handleError(error);
157
+ }
158
+ }
159
+ /**
160
+ * Declare what following a kind of thing MEANS: the verb clients render,
161
+ * whether reverse lookups are public, whether it federates.
162
+ *
163
+ * Declared once by the application that owns the concept, rather than
164
+ * passed per call site — otherwise two screens of one app can disagree
165
+ * about whether a store is followed or subscribed to.
166
+ */
167
+ async registerFollowKind(input) {
168
+ try {
169
+ return await this.makeRequest('POST', '/v2/follow-targets/kinds', input, {
170
+ cache: false,
171
+ });
172
+ }
173
+ catch (error) {
174
+ throw this.handleError(error);
175
+ }
176
+ }
177
+ /**
178
+ * Everything the signed-in user follows, newest first.
179
+ *
180
+ * Owner-only by construction server-side — there is no parameter naming a
181
+ * user, so this cannot be pointed at somebody else's graph.
182
+ *
183
+ * Paginate by passing back `nextCursor`, never an offset: the list changes
184
+ * while it is being read, and an offset silently skips or repeats rows
185
+ * exactly when it does.
186
+ */
187
+ async listFollows(params) {
188
+ try {
189
+ const path = buildUrl('/v2/me/follows', {
190
+ ...(params?.kind ? { kind: params.kind } : {}),
191
+ ...(params?.cursor ? { cursor: params.cursor } : {}),
192
+ ...(params?.limit ? { limit: params.limit } : {}),
193
+ });
194
+ return await this.makeRequest('GET', path, undefined, { cache: false });
195
+ }
196
+ catch (error) {
197
+ throw this.handleError(error);
198
+ }
199
+ }
200
+ };
201
+ }
@@ -3,6 +3,8 @@ import { buildQueryParams, buildPaginationParams, } from '../utils/apiUtils.js';
3
3
  import { KeyManager } from '../crypto/keyManager.js';
4
4
  import { SignatureService } from '../crypto/signatureService.js';
5
5
  import { normalizeUserIdentity, normalizeUserIdentityOrNull } from '../utils/userIdentity.js';
6
+ import { evictOxyIdentityCache } from '../utils/identityCacheSweep.js';
7
+ import { evictOxyAccountForestCache } from '../utils/accountCacheSweep.js';
6
8
  import { logger } from '../logger/index.js';
7
9
  import { extractErrorStatus } from '../utils/errorUtils.js';
8
10
  /**
@@ -344,28 +346,24 @@ export function OxyServicesUserMixin(Base) {
344
346
  /**
345
347
  * Update user profile.
346
348
  *
347
- * Invalidates the SDK-side response cache for every endpoint that
348
- * returns the current user (`GET /users/me`, `GET /session/user/*`,
349
- * `GET /users/<id>`, `GET /profiles/username/*`) so the next read
350
- * doesn't return a stale snapshot. Without this, a follow-up
351
- * `getUserBySession` call inside the 2-minute cache window can return
352
- * the pre-update user most visibly during onboarding, where it
353
- * causes the username step to flicker back as if nothing was saved.
349
+ * Invalidates the SDK-side response cache for every endpoint that can
350
+ * return this user — the list is owned by {@link evictOxyIdentityCache}, so
351
+ * a new identity read is added in one place instead of to each writer
352
+ * separately (this method's own hand-written copy had already drifted from
353
+ * the server-side one, missing `GET /auth/lookup/*` and
354
+ * `GET /profiles/resolve`). The account forest (`GET /accounts` and the
355
+ * caller's own detail row) is swept too a personal account IS this user,
356
+ * and `AccountNode.account` embeds the whole profile — from the list that
357
+ * {@link evictOxyAccountForestCache} owns, for the same reason: the accounts
358
+ * mixin writes those keys as well, and two hand-written copies drift.
354
359
  *
355
360
  * TanStack Query handles offline queuing automatically.
356
361
  */
357
362
  async updateProfile(updates) {
358
363
  try {
359
364
  const result = normalizeUserIdentity(await this.makeRequest('PUT', '/users/me', updates, { cache: false }));
360
- // Bust every cached representation of the current user. We use a
361
- // prefix sweep rather than an enumeration because the SDK never
362
- // tracks the set of active session IDs centrally.
363
- this.clearCacheByPrefix('GET:/session/user/');
364
- this.clearCacheByPrefix('GET:/users/me');
365
- this.clearCacheByPrefix('GET:/profiles/username/');
366
- if (result?.id) {
367
- this.clearCacheEntry(`GET:/users/${result.id}`);
368
- }
365
+ evictOxyIdentityCache(this, result?.id);
366
+ evictOxyAccountForestCache(this, result?.id);
369
367
  return result;
370
368
  }
371
369
  catch (error) {
@@ -418,10 +416,9 @@ export function OxyServicesUserMixin(Base) {
418
416
  const result = await this.makeRequest('PATCH', `/privacy/${id}/privacy`, settings, {
419
417
  cache: false,
420
418
  });
421
- this.clearCacheByPrefix('GET:/session/user/');
422
- this.clearCacheByPrefix('GET:/users/me');
423
- this.clearCacheByPrefix('GET:/profiles/username/');
424
- this.clearCacheEntry(`GET:/users/${id}`);
419
+ // Privacy settings ride the user DTO, so every identity read goes stale
420
+ // too — same key list as any other profile write.
421
+ evictOxyIdentityCache(this, id);
425
422
  this.clearCacheEntry(`GET:/privacy/${id}/privacy`);
426
423
  return result;
427
424
  }
@@ -29,6 +29,7 @@ import { OxyServicesAppDataMixin } from './OxyServices.appData.js';
29
29
  import { OxyServicesCivicMixin } from './OxyServices.civic.js';
30
30
  import { OxyServicesNodesMixin } from './OxyServices.nodes.js';
31
31
  import { OxyServicesLinksMixin } from './OxyServices.links.js';
32
+ import { OxyServicesFollowGraphMixin } from './OxyServices.followGraph.js';
32
33
  import { OxyServicesDeviceBootMixin } from './OxyServices.deviceBoot.js';
33
34
  import { OxyServicesDeviceTransferMixin } from './OxyServices.deviceTransfer.js';
34
35
  /**
@@ -85,6 +86,9 @@ const MIXIN_PIPELINE = [
85
86
  // Link previews / unfurls: SDK-owned link-metadata resolution via oxy-api,
86
87
  // so apps stop scraping link metadata locally.
87
88
  OxyServicesLinksMixin,
89
+ // The user-owned follow graph (#809). One relationship per user and target,
90
+ // shared across applications, with per-application context on top.
91
+ OxyServicesFollowGraphMixin,
88
92
  // Device-first token mint: the client half of the zero-cookie transport
89
93
  // (`mintFromDeviceSecret` → `POST /session/device/token`).
90
94
  OxyServicesDeviceBootMixin,
@@ -27,7 +27,11 @@ export { buildOxyCspDirectives, buildOxyPagesHeaders, createOxySecurityHeaders,
27
27
  export { verifySecret } from './verifySecret.js';
28
28
  // Cross-service user-invalidation signal: oxy-api publishes when identity
29
29
  // changes, every consuming backend sweeps its caches instead of waiting out a TTL.
30
- export { createOxyUserInvalidationHandler, evictOxyIdentityCache, publishOxyUserInvalidation, } from './userInvalidation.js';
30
+ export { createOxyUserInvalidationHandler, publishOxyUserInvalidation, } from './userInvalidation.js';
31
+ // The identity-key enumeration itself is platform-neutral (`src/utils/`) so the
32
+ // client mixins and this Node-only subscriber sweep the SAME list — a second
33
+ // copy is what let `updateAccount` and `updateProfile` drift apart.
34
+ export { evictOxyIdentityCache, oxyUserByIdCacheKey, OXY_IDENTITY_CACHE_PREFIXES } from '../utils/identityCacheSweep.js';
31
35
  // Registrable-apex (eTLD+1) derivation via the Public Suffix List — the SINGLE
32
36
  // SOURCE OF TRUTH shared with the IdP worker and the client FAPI auto-detect.
33
37
  // Pure host handling (no browser deps), so it is safe on the server subpath and
@@ -6,10 +6,10 @@
6
6
  * Every Oxy backend caches Oxy identity, and none of them find out when it
7
7
  * changes. The `OxyServices` GET response cache holds `GET /users/:id` and
8
8
  * `GET /profiles/username/:name` for five minutes; it is swept when THIS process
9
- * writes the profile (see the `clearCacheEntry` calls in the user mixin) and
10
- * never when somebody else does — which is the normal case, since profiles are
11
- * edited in Oxy's own apps. So an avatar or display-name change is invisible to
12
- * every consuming backend for up to five minutes, per process.
9
+ * writes the profile (the `evictOxyIdentityCache` calls in the user and accounts
10
+ * mixins) and never when somebody else does — which is the normal case, since
11
+ * profiles are edited in Oxy's own apps. So an avatar or display-name change is
12
+ * invisible to every consuming backend for up to five minutes, per process.
13
13
  *
14
14
  * oxy-api broadcasts {@link OXY_USER_INVALIDATION_CHANNEL} on the shared Valkey
15
15
  * when a user's identity changes. This module is the consumer half: it parses
@@ -51,6 +51,7 @@
51
51
  * Node-only; exported solely from `@oxyhq/core/server`.
52
52
  */
53
53
  import { OXY_USER_INVALIDATION_CHANNEL, isPublishedOxyUserChangeReason, oxyUserInvalidationEventSchema, } from '@oxyhq/contracts';
54
+ import { evictOxyIdentityCache, } from '../utils/identityCacheSweep.js';
54
55
  /**
55
56
  * Broadcast that an Oxy user's record changed.
56
57
  *
@@ -149,25 +150,3 @@ export function createOxyUserInvalidationHandler(options = {}) {
149
150
  }
150
151
  };
151
152
  }
152
- /**
153
- * Sweep an `OxyServices` GET response cache of everything that could carry the
154
- * given user's identity.
155
- *
156
- * The by-id entry is exact. The by-username and resolve entries are keyed by
157
- * HANDLE, which cannot be derived from an id without the very lookup we are
158
- * invalidating, so those are swept by prefix — the same imprecision the SDK
159
- * already accepts when it sweeps its own cache after a local profile write, and
160
- * bounded by the fact that over-eviction costs a refetch and can never serve
161
- * wrong data.
162
- */
163
- export function evictOxyIdentityCache(oxy, userId) {
164
- // Match the sweep the user mixin runs after a local profile write — session-
165
- // bound and /users/me entries are keyed without the user id, so they must be
166
- // prefix-swept on cross-service invalidation too.
167
- oxy.clearCacheByPrefix('GET:/session/user/');
168
- oxy.clearCacheByPrefix('GET:/users/me');
169
- oxy.clearCacheByPrefix('GET:/auth/lookup/');
170
- oxy.clearCacheEntry(`GET:/users/${userId}`);
171
- oxy.clearCacheByPrefix('GET:/profiles/username/');
172
- oxy.clearCacheByPrefix('GET:/profiles/resolve');
173
- }
@@ -19,6 +19,35 @@
19
19
  import { isActAsEligibleKind } from '@oxyhq/contracts';
20
20
  import { getAccountDisplayName, getAccountFallbackHandle } from '../utils/accountUtils.js';
21
21
  import { getNormalizedUserHandle } from '../utils/userHandle.js';
22
+ /**
23
+ * Whether the caller can BECOME this account — the one question every account
24
+ * switcher asks, answered here so no surface has to re-derive it.
25
+ *
26
+ * Two independent grounds, either of which suffices:
27
+ *
28
+ * - **It is already the caller's own identity** (`relationship: 'self'`).
29
+ * `GET /accounts` resolves its caller through `resolveOperatorId`, so `self`
30
+ * is the HUMAN operator's personal account even while they are operating an
31
+ * org — never the operated account. Kind is irrelevant on this ground: the
32
+ * caller IS that account, so returning to it asks the server for nothing.
33
+ * - **The server will mint a session for it** — `isActAsEligibleKind(kind)` is
34
+ * the exact predicate `POST /accounts/:id/switch` enforces, so a row offered
35
+ * on this ground is never a dead button.
36
+ *
37
+ * `isActAsEligibleKind` ALONE is not this question, and reaching for it
38
+ * directly is the mistake this function exists to prevent: it is false for
39
+ * `personal` as well as `channel`, so a switcher gated on it alone renders an
40
+ * empty list rather than a filtered one. Equally, `kind !== 'channel'` is not
41
+ * this question either — it silently admits every kind invented after it was
42
+ * written, which is the same trap `isActAsEligibleKind` was introduced to close
43
+ * on the server.
44
+ *
45
+ * Takes a structural subset rather than a whole {@link AccountNode} so a caller
46
+ * holding a projected {@link SwitchableAccount} can ask it too.
47
+ */
48
+ export function isSwitchTargetAccount(node) {
49
+ return node.relationship === 'self' || isActAsEligibleKind(node.kind);
50
+ }
22
51
  /**
23
52
  * Pure union of device sign-ins and account-graph nodes into the flat
24
53
  * {@link SwitchableAccount}[] every switcher renders.
@@ -28,8 +57,9 @@ import { getNormalizedUserHandle } from '../utils/userHandle.js';
28
57
  * and a graph node is deduped into ONE device row enriched with the graph
29
58
  * metadata (relationship / kind / parent / membership).
30
59
  *
31
- * Graph nodes of a kind nobody may act as (`channel`) are omitted see the
32
- * filter below.
60
+ * Graph nodes that are not switch targets a `channel`, which nobody may act
61
+ * as — are omitted. {@link isSwitchTargetAccount} is the rule; see the filter
62
+ * below.
33
63
  */
34
64
  export function projectSwitchableAccounts(input) {
35
65
  const { state, graph, profilesById, activeUser, locale, resolveAvatarUrl } = input;
@@ -104,10 +134,12 @@ export function projectSwitchableAccounts(input) {
104
134
  // construction": the graph contributes accounts that have no device session
105
135
  // and no credentials at all, which is exactly how an org first becomes
106
136
  // switchable. So a kind that must never be switched into has to be filtered
107
- // HERE, and `isActAsEligibleKind` is the same predicate the server enforces
108
- // on `POST /accounts/:id/switch` — offering a row the server would 403 is a
109
- // dead button.
110
- if (!isActAsEligibleKind(node.kind)) {
137
+ // HERE offering a row the server would 403 is a dead button.
138
+ //
139
+ // An account already on the device skipped this check via the branch above,
140
+ // and correctly: whatever its kind, the caller is signed into it, so
141
+ // switching is a local activation that asks the server for nothing.
142
+ if (!isSwitchTargetAccount(node)) {
111
143
  continue;
112
144
  }
113
145
  remember(toRow(node.account, {
@@ -129,8 +161,11 @@ export function projectSwitchableAccounts(input) {
129
161
  * document, but including their ids lets the caller pass one id set and lets the
130
162
  * projection prefer freshly-fetched profiles uniformly.
131
163
  *
132
- * Applies the SAME act-as filter as {@link projectSwitchableAccounts} to graph
133
- * nodes, so this never fetches a profile for a row the projection will drop.
164
+ * Applies the SAME {@link isSwitchTargetAccount} filter as
165
+ * {@link projectSwitchableAccounts} to graph nodes, so this never fetches a
166
+ * profile for a row the projection will drop — and, just as importantly, never
167
+ * SKIPS one the projection will keep, which would leave that row unrendered
168
+ * until some later fetch happened to resolve it.
134
169
  */
135
170
  export function switchableAccountIds(state, graph) {
136
171
  const ids = new Set();
@@ -140,7 +175,7 @@ export function switchableAccountIds(state, graph) {
140
175
  }
141
176
  }
142
177
  for (const node of graph) {
143
- if (node.accountId && isActAsEligibleKind(node.kind)) {
178
+ if (node.accountId && isSwitchTargetAccount(node)) {
144
179
  ids.add(node.accountId);
145
180
  }
146
181
  }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * THE enumeration of `OxyServices` GET-cache keys that serve the ACCOUNT FOREST
3
+ * — the caller's accessible accounts, as lists and as individual detail rows —
4
+ * and the one sweep that clears them.
5
+ *
6
+ * WHY THIS IS NOT A METHOD ON THE ACCOUNTS MIXIN
7
+ * ---------------------------------------------
8
+ * `AccountNode.account` is a whole `User`, so a forest read embeds the very
9
+ * profile the identity reads serve. That makes an IDENTITY write a writer of
10
+ * these keys too: `updateProfile` edits the caller's own personal account,
11
+ * which is a row in `GET /accounts` and is its own `GET /accounts/<id>`. Leave
12
+ * those cached and the account switcher keeps drawing the pre-edit name and
13
+ * picture for the full TTL, against a perfectly healthy server.
14
+ *
15
+ * The mixins compose into one class at runtime but are typed one at a time, so
16
+ * the user mixin cannot call a method the accounts mixin owns. The key list
17
+ * therefore lives here, once, and every writer calls {@link
18
+ * evictOxyAccountForestCache} — exactly like the identity key list in
19
+ * `identityCacheSweep`, which the accounts mixin already calls for the
20
+ * mirror-image case (an account write staling the identity reads). The
21
+ * alternative — a second hand-written copy of these keys in the other mixin —
22
+ * is the drift that shipped the two stale-profile bugs `identityCacheSweep`
23
+ * documents.
24
+ *
25
+ * WHY THE LIST NEEDS A PREFIX AND THE DETAIL DOES NOT
26
+ * --------------------------------------------------
27
+ * `listAccounts({tree?})` keys the flat list as `GET:/accounts` and every
28
+ * option variant as `GET:/accounts?<query>` (the query string is part of the
29
+ * URL, hence of the key), and a writer cannot enumerate which variants a caller
30
+ * has read. The detail key, by contrast, is derivable from the account id the
31
+ * writer already holds.
32
+ *
33
+ * The `GET:/accounts?` prefix matches ONLY the query-string list variants —
34
+ * never `GET:/accounts/<id>` or its `…/members`, `…/credentials`, `…/children`
35
+ * sub-resources, which are the accounts mixin's own business and stay there.
36
+ */
37
+ /** The cache key `listAccounts()` reads under with no options. */
38
+ export const OXY_ACCOUNT_LIST_CACHE_KEY = 'GET:/accounts';
39
+ /**
40
+ * The prefix covering every option-carrying `listAccounts(opts)` variant
41
+ * (`?tree=true`, …), none of which a writer can enumerate.
42
+ */
43
+ export const OXY_ACCOUNT_LIST_CACHE_QUERY_PREFIX = 'GET:/accounts?';
44
+ /**
45
+ * Prefix covering every per-account sub-resource cache key
46
+ * (`GET:/accounts/<id>`, `…/members`, `…/credentials`, `…/children`). A
47
+ * membership mutation on an ancestor must sweep ALL of these, not only the
48
+ * account named in the path: descendant member rosters embed inherited rows
49
+ * resolved from that ancestor, and the writer cannot enumerate which descendant
50
+ * ids a caller has already read. The trailing slash deliberately excludes the
51
+ * forest list keys (`GET:/accounts`, `GET:/accounts?…`) documented above.
52
+ */
53
+ export const OXY_ACCOUNT_PER_ACCOUNT_CACHE_PREFIX = 'GET:/accounts/';
54
+ /**
55
+ * Build the exact cache key `getAccount(accountId)` reads under.
56
+ */
57
+ export function oxyAccountDetailCacheKey(accountId) {
58
+ return `GET:/accounts/${encodeURIComponent(accountId)}`;
59
+ }
60
+ /**
61
+ * Sweep an `OxyServices` GET response cache of the account forest.
62
+ *
63
+ * @param oxy - Anything exposing the SDK's two eviction methods.
64
+ * @param accountId - The account whose detail row to drop as well. Optional: a
65
+ * writer that changed the SHAPE of the forest rather than one
66
+ * account in it (create, archive, ownership transfer) has no
67
+ * detail row to name, and clears only the lists.
68
+ */
69
+ export function evictOxyAccountForestCache(oxy, accountId) {
70
+ oxy.clearCacheEntry(OXY_ACCOUNT_LIST_CACHE_KEY);
71
+ oxy.clearCacheByPrefix(OXY_ACCOUNT_LIST_CACHE_QUERY_PREFIX);
72
+ if (accountId) {
73
+ oxy.clearCacheEntry(oxyAccountDetailCacheKey(accountId));
74
+ }
75
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * THE enumeration of `OxyServices` GET-cache keys that can carry a single
3
+ * account's identity, and the one sweep that clears them.
4
+ *
5
+ * WHY THIS IS ONE LIST
6
+ * --------------------
7
+ * An Oxy account is readable under SEVERAL cache keys, and a write that only
8
+ * busts the key it happens to know about leaves every other one serving the
9
+ * pre-write snapshot for up to its TTL — from the caller's OWN in-memory cache,
10
+ * with a perfectly healthy server. That failure has already shipped twice with
11
+ * two different sets of keys:
12
+ *
13
+ * - `updateAccount` busted `GET:/accounts/<id>` and the account lists, but a
14
+ * profile screen reads `GET:/profiles/username/<name>` and
15
+ * `GET:/users/<id>`, so a channel's new picture stayed invisible for the
16
+ * full 5-minute profile TTL.
17
+ * - `updateProfile` busted four of the six keys below, missing
18
+ * `GET:/auth/lookup/` (the login-flow avatar/display-name lookup) and
19
+ * `GET:/profiles/resolve` (handle resolution) — two independently-drifted
20
+ * copies of a list that has to agree.
21
+ *
22
+ * So the list lives here, once, and every writer calls
23
+ * {@link evictOxyIdentityCache}. Adding a new identity read means adding its key
24
+ * HERE and every writer inherits it.
25
+ *
26
+ * WHERE THE LINE IS DRAWN
27
+ * -----------------------
28
+ * These are the SINGLE-PROFILE reads — the account is the subject of the
29
+ * response and is addressable by id, handle, or session. Reads that merely
30
+ * CONTAIN an account among many (`GET:/profiles/search`,
31
+ * `GET:/users/<other>/followers`, `GET:/profiles/<other>/similar`) are
32
+ * deliberately NOT swept: an account cannot be located in them without the very
33
+ * lookup being invalidated, so sweeping them means sweeping the whole namespace
34
+ * on every identity change — a real cost on a backend consuming the
35
+ * cross-service invalidation signal, for a surface where a stale thumbnail
36
+ * expires on its own in ~2 minutes.
37
+ *
38
+ * WHY PREFIXES RATHER THAN EXACT KEYS
39
+ * -----------------------------------
40
+ * Only the by-id key can be built from a user id. The handle-keyed and
41
+ * session-keyed entries cannot — deriving a handle from an id needs the lookup
42
+ * we are invalidating, and the SDK never tracks active session ids centrally.
43
+ * Prefix sweeping is also what makes a USERNAME CHANGE correct: the entry under
44
+ * the OLD handle is unreachable by construction (nothing in the write response
45
+ * carries it), and a sweep targeted at the new handle alone would leave the old
46
+ * one serving the pre-rename profile until its TTL. Over-eviction costs a
47
+ * refetch; under-eviction serves wrong data.
48
+ *
49
+ * Platform-neutral by construction (no imports, no `OxyServices` reference) so
50
+ * the client mixins and the Node-only `@oxyhq/core/server` invalidation
51
+ * subscriber can share it without either pulling in the other.
52
+ */
53
+ /**
54
+ * Cache-key PREFIXES under which an account's identity can be served, for the
55
+ * reads whose key cannot be derived from a user id. Swept wholesale.
56
+ */
57
+ export const OXY_IDENTITY_CACHE_PREFIXES = [
58
+ // `getUserBySession` — keyed by session id, which the SDK never enumerates.
59
+ 'GET:/session/user/',
60
+ // `getCurrentUser` (and `GET:/users/me/graph`, harmlessly included).
61
+ 'GET:/users/me',
62
+ // `lookupUsername` — the pre-session login lookup; carries avatar + display name.
63
+ 'GET:/auth/lookup/',
64
+ // `getProfileByUsername` — keyed by handle, including the pre-rename handle.
65
+ 'GET:/profiles/username/',
66
+ // `resolveProfile` — keyed by fediverse handle in the query payload.
67
+ 'GET:/profiles/resolve',
68
+ ];
69
+ /**
70
+ * Build the exact cache key `getUserById` reads under. The only identity key
71
+ * derivable from a user id, so the only one that does not need a prefix sweep.
72
+ */
73
+ export function oxyUserByIdCacheKey(userId) {
74
+ return `GET:/users/${userId}`;
75
+ }
76
+ /**
77
+ * Sweep an `OxyServices` GET response cache of everything that could carry the
78
+ * given account's identity.
79
+ *
80
+ * @param oxy - Anything exposing the SDK's two eviction methods.
81
+ * @param userId - The account whose by-id entry to drop. Optional: a caller
82
+ * that does not know the id still clears every handle-, session-
83
+ * and self-keyed entry, which is the majority of the surface.
84
+ */
85
+ export function evictOxyIdentityCache(oxy, userId) {
86
+ for (const prefix of OXY_IDENTITY_CACHE_PREFIXES) {
87
+ oxy.clearCacheByPrefix(prefix);
88
+ }
89
+ if (userId) {
90
+ oxy.clearCacheEntry(oxyUserByIdCacheKey(userId));
91
+ }
92
+ }