@asteby/metacore-runtime-react 53.7.0 → 53.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/action-modal-dispatcher.d.ts.map +1 -1
  3. package/dist/action-modal-dispatcher.js +3 -1
  4. package/dist/api-context.d.ts.map +1 -1
  5. package/dist/api-context.js +15 -0
  6. package/dist/cache-scope.d.ts +52 -0
  7. package/dist/cache-scope.d.ts.map +1 -0
  8. package/dist/cache-scope.js +200 -0
  9. package/dist/capability-providers/index.d.ts +4 -0
  10. package/dist/capability-providers/index.d.ts.map +1 -0
  11. package/dist/capability-providers/index.js +3 -0
  12. package/dist/capability-providers/model.d.ts +201 -0
  13. package/dist/capability-providers/model.d.ts.map +1 -0
  14. package/dist/capability-providers/model.js +293 -0
  15. package/dist/capability-providers/provider-sortable-list.d.ts +86 -0
  16. package/dist/capability-providers/provider-sortable-list.d.ts.map +1 -0
  17. package/dist/capability-providers/provider-sortable-list.js +263 -0
  18. package/dist/capability-providers/reorder.d.ts +10 -0
  19. package/dist/capability-providers/reorder.d.ts.map +1 -0
  20. package/dist/capability-providers/reorder.js +31 -0
  21. package/dist/dashboard-types.d.ts +2 -4
  22. package/dist/dashboard-types.d.ts.map +1 -1
  23. package/dist/dynamic-kanban.d.ts.map +1 -1
  24. package/dist/dynamic-kanban.js +9 -4
  25. package/dist/dynamic-relation.d.ts.map +1 -1
  26. package/dist/dynamic-relation.js +5 -2
  27. package/dist/dynamic-table.d.ts +2 -0
  28. package/dist/dynamic-table.d.ts.map +1 -1
  29. package/dist/dynamic-table.js +40 -6
  30. package/dist/dynamic-view.d.ts.map +1 -1
  31. package/dist/dynamic-view.js +3 -1
  32. package/dist/index.d.ts +4 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +5 -1
  35. package/dist/metadata-cache.d.ts +22 -2
  36. package/dist/metadata-cache.d.ts.map +1 -1
  37. package/dist/metadata-cache.js +73 -13
  38. package/dist/query-batch.d.ts +12 -0
  39. package/dist/query-batch.d.ts.map +1 -1
  40. package/dist/query-batch.js +70 -29
  41. package/dist/use-option-ids.d.ts.map +1 -1
  42. package/dist/use-option-ids.js +3 -1
  43. package/dist/use-options-resolver.d.ts +4 -1
  44. package/dist/use-options-resolver.d.ts.map +1 -1
  45. package/dist/use-options-resolver.js +27 -16
  46. package/dist/widgets/charts.d.ts.map +1 -1
  47. package/dist/widgets/charts.js +11 -43
  48. package/dist/widgets/widget-format.d.ts +1 -41
  49. package/dist/widgets/widget-format.d.ts.map +1 -1
  50. package/dist/widgets/widget-format.js +3 -138
  51. package/package.json +4 -4
  52. package/src/__tests__/charts-reexport.test.ts +30 -0
  53. package/src/action-modal-dispatcher.tsx +3 -1
  54. package/src/api-context.tsx +14 -0
  55. package/src/cache-scope-inflight.test.ts +369 -0
  56. package/src/cache-scope.test.ts +234 -0
  57. package/src/cache-scope.ts +202 -0
  58. package/src/capability-providers/index.ts +46 -0
  59. package/src/capability-providers/model.test.ts +186 -0
  60. package/src/capability-providers/model.ts +464 -0
  61. package/src/capability-providers/provider-sortable-list.test.tsx +284 -0
  62. package/src/capability-providers/provider-sortable-list.tsx +452 -0
  63. package/src/capability-providers/reorder.ts +29 -0
  64. package/src/dashboard-types.ts +2 -11
  65. package/src/dynamic-kanban.tsx +9 -4
  66. package/src/dynamic-relation.tsx +5 -2
  67. package/src/dynamic-table.tsx +41 -10
  68. package/src/dynamic-view.tsx +3 -1
  69. package/src/index.ts +13 -0
  70. package/src/metadata-cache.ts +85 -15
  71. package/src/query-batch.ts +71 -30
  72. package/src/use-option-ids.ts +3 -1
  73. package/src/use-options-resolver.ts +28 -15
  74. package/src/widgets/charts.tsx +26 -189
  75. package/src/widgets/widget-format.ts +14 -181
  76. package/vitest.setup.ts +16 -0
@@ -66,6 +66,7 @@ import { Inbox, Download, Upload, Trash2 } from 'lucide-react'
66
66
  import { toast } from 'sonner'
67
67
  import { Progress } from './dialogs/_primitives'
68
68
  import { useMetadataCache } from './metadata-cache'
69
+ import { cacheScope, onCacheScopeChange, peekCacheScope } from './cache-scope'
69
70
  import { useRecordMutationTick } from './use-record-mutation-tick'
70
71
  import { useApi, useCurrentBranch } from './api-context'
71
72
  import { useReasonPrompt } from './reason-prompt'
@@ -114,20 +115,43 @@ import {
114
115
  const TBL_DATA_CACHE_PREFIX = 'mc:tbl:data:v1'
115
116
  interface TableDataCacheEntry { rows: any[]; rowCount: number; ts: number }
116
117
 
118
+ // The key carries the org:user:lang scope, and the whole prefix is wiped when the
119
+ // scope changes (logout+login in the same tab). Unknown scope = no cache.
117
120
  function tableDataCacheKey(
118
121
  model: string | undefined,
119
122
  endpoint: string | undefined,
120
123
  branchId: string | number | null | undefined,
121
124
  search: string,
125
+ // Render passes `peekCacheScope()` (no listeners fired mid-render); effects
126
+ // and handlers use the default, which also notices a scope change.
127
+ scope: string | null = cacheScope(),
122
128
  ): string {
129
+ if (!scope) return ''
123
130
  const p = new URLSearchParams(search)
124
131
  const parts: string[] = []
125
132
  p.forEach((v, k) => parts.push(`${k}=${v}`))
126
133
  parts.sort()
127
- return `${TBL_DATA_CACHE_PREFIX}|${model || ''}|${endpoint || ''}|${branchId || ''}|${parts.join('&')}`
134
+ return `${TBL_DATA_CACHE_PREFIX}|${scope}|${model || ''}|${endpoint || ''}|${branchId || ''}|${parts.join('&')}`
128
135
  }
129
136
 
137
+ /** Drops every persisted first-page row set (all scopes). */
138
+ export function clearTableDataCache(): void {
139
+ try {
140
+ const doomed: string[] = []
141
+ for (let i = 0; i < sessionStorage.length; i++) {
142
+ const k = sessionStorage.key(i)
143
+ if (k && k.startsWith(TBL_DATA_CACHE_PREFIX)) doomed.push(k)
144
+ }
145
+ for (const k of doomed) sessionStorage.removeItem(k)
146
+ } catch {
147
+ /* storage unavailable */
148
+ }
149
+ }
150
+
151
+ onCacheScopeChange(() => clearTableDataCache())
152
+
130
153
  function readTableDataCache(key: string): TableDataCacheEntry | null {
154
+ if (!key) return null
131
155
  try {
132
156
  const raw = sessionStorage.getItem(key)
133
157
  if (!raw) return null
@@ -139,6 +163,7 @@ function readTableDataCache(key: string): TableDataCacheEntry | null {
139
163
  }
140
164
 
141
165
  function writeTableDataCache(key: string, rows: any[], rowCount: number): void {
166
+ if (!key) return
142
167
  try {
143
168
  sessionStorage.setItem(
144
169
  key,
@@ -430,14 +455,17 @@ export function DynamicTable({
430
455
  const [metadata, setMetadata] = useState<TableMetadata | null>(cachedMeta || null)
431
456
  // Read the row-data cache ONCE at mount (before the fetch effects run) so the
432
457
  // first paint uses the previous rows for this exact view instead of skeletons.
433
- const bootDataKey = tableDataCacheKey(
434
- model,
435
- endpoint,
436
- currentBranch?.id,
437
- typeof window !== 'undefined' ? window.location.search : '',
438
- )
439
458
  const bootDataRef = useRef<TableDataCacheEntry | null | undefined>(undefined)
440
459
  if (bootDataRef.current === undefined) {
460
+ // peekCacheScope: cacheScope() would notify its listeners (zustand `set`)
461
+ // in the middle of a render ("Cannot update a component while rendering").
462
+ const bootDataKey = tableDataCacheKey(
463
+ model,
464
+ endpoint,
465
+ currentBranch?.id,
466
+ typeof window !== 'undefined' ? window.location.search : '',
467
+ peekCacheScope(),
468
+ )
441
469
  bootDataRef.current = enableUrlSync ? readTableDataCache(bootDataKey) : null
442
470
  }
443
471
  const bootData = bootDataRef.current
@@ -818,13 +846,14 @@ export function DynamicTable({
818
846
  setLoading(true)
819
847
  }
820
848
  let meta: TableMetadata | null = cached || null
849
+ const askedScope = cacheScope()
821
850
  try {
822
851
  const res = await api.get(`/metadata/table/${model}`) as { data: ApiResponse<TableMetadata> }
823
852
  if (res.data.success) {
824
853
  const fresh = res.data.data
825
854
  meta = fresh
826
855
  setMetadata(fresh)
827
- cacheMetadata(model, fresh)
856
+ cacheMetadata(model, fresh, { scope: askedScope })
828
857
  defaultPerPage.current = fresh.defaultPerPage || 10
829
858
  if (!urlHadPerPage.current && storedPageSizeRef.current == null) setPagination((prev: PaginationState) => ({ ...prev, pageSize: fresh.defaultPerPage || 10 }))
830
859
  }
@@ -1017,6 +1046,7 @@ export function DynamicTable({
1017
1046
  ...buildFilterParams(),
1018
1047
  }
1019
1048
  if (relationInclude) params.include = relationInclude
1049
+ const askedScope = cacheScope()
1020
1050
  const res = await api.get(endpoint || `/data/${model}`, { params }) as { data: ApiResponse<any[]> }
1021
1051
  setForbidden(false)
1022
1052
  setLoadError(!res.data.success)
@@ -1026,7 +1056,7 @@ export function DynamicTable({
1026
1056
  if (res.data.meta) setRowCount(res.data.meta.total)
1027
1057
  // Cache the first page for an instant reload paint (see the cache
1028
1058
  // helpers). Keyed off the live URL so it matches the next mount.
1029
- if (enableUrlSync && pagination.pageIndex === 0) {
1059
+ if (enableUrlSync && pagination.pageIndex === 0 && cacheScope() === askedScope) {
1030
1060
  writeTableDataCache(
1031
1061
  tableDataCacheKey(model, endpoint, currentBranch?.id, window.location.search),
1032
1062
  rows,
@@ -1089,6 +1119,7 @@ export function DynamicTable({
1089
1119
  ...buildFilterParams(),
1090
1120
  }
1091
1121
  if (relationInclude) params.include = relationInclude
1122
+ const askedScope = cacheScope()
1092
1123
  const res = (await api.get(endpoint || `/data/${model}`, {
1093
1124
  params,
1094
1125
  })) as { data: ApiResponse<any[]> }
@@ -1099,7 +1130,7 @@ export function DynamicTable({
1099
1130
  setData((prev) => (append ? dedupeById(prev, rows) : rows))
1100
1131
  if (res.data.meta) setRowCount(res.data.meta.total)
1101
1132
  // Cache the first (replace) page for an instant reload paint.
1102
- if (!append && enableUrlSync) {
1133
+ if (!append && enableUrlSync && cacheScope() === askedScope) {
1103
1134
  writeTableDataCache(
1104
1135
  tableDataCacheKey(model, endpoint, currentBranch?.id, window.location.search),
1105
1136
  rows,
@@ -16,6 +16,7 @@
16
16
  import { useEffect, useMemo, useState } from 'react'
17
17
  import { useApi } from './api-context'
18
18
  import { useMetadataCache } from './metadata-cache'
19
+ import { cacheScope } from './cache-scope'
19
20
  import { DynamicTable, type DynamicTableProps } from './dynamic-table'
20
21
  import { DynamicKanban, type DynamicKanbanProps } from './dynamic-kanban'
21
22
  import type { TableMetadata, ApiResponse } from './types'
@@ -132,6 +133,7 @@ export function DynamicView({
132
133
  setMetaState(c)
133
134
  setResolved(true)
134
135
  }
136
+ const askedScope = cacheScope()
135
137
  api
136
138
  .get(`/metadata/table/${model}`)
137
139
  .then((res) => {
@@ -141,7 +143,7 @@ export function DynamicView({
141
143
  if (meta) {
142
144
  setViewType(meta.view_type)
143
145
  setMetaState(meta)
144
- setMeta(model, meta)
146
+ setMeta(model, meta, { scope: askedScope })
145
147
  }
146
148
  })
147
149
  .catch(() => {
package/src/index.ts CHANGED
@@ -468,6 +468,15 @@ export * from './print-document-button'
468
468
  export * from './use-org-document-templates'
469
469
  export * from './document-template-editor'
470
470
  export * from './metadata-cache'
471
+ export {
472
+ cacheScope,
473
+ peekCacheScope,
474
+ syncCacheScope,
475
+ onCacheScopeChange,
476
+ setCacheScopeLanguageProvider,
477
+ setCacheScopeProvider,
478
+ type CacheScopeParts,
479
+ } from './cache-scope'
471
480
  export {
472
481
  RealtimeProvider,
473
482
  useRealtimeClient,
@@ -683,6 +692,7 @@ export {
683
692
  rememberInRows,
684
693
  invalidateQueryBatchData,
685
694
  resetQueryBatchCache,
695
+ clearQueryBatchCaches,
686
696
  splitInToken,
687
697
  tokenForGet,
688
698
  type InListToken,
@@ -820,6 +830,8 @@ export {
820
830
  type AccentClasses,
821
831
  type WidgetFormatCtx,
822
832
  } from './widgets/widget-format'
833
+ // Dependency-free SVG sparkline from @asteby/metacore-charts (no recharts).
834
+ export { Sparkline, type SparklineProps } from '@asteby/metacore-charts'
823
835
  export { AssistInterview, AssistCardView } from './assist-interview'
824
836
  export type { AssistSession, AssistTurn, AssistQuestion, AssistCard, AssistProgressStep } from './assist-interview'
825
837
  export {
@@ -877,3 +889,4 @@ export {
877
889
  type ResolvedRecordAction,
878
890
  type SplitActions,
879
891
  } from './record-actions'
892
+ export * from './capability-providers'
@@ -10,6 +10,10 @@
10
10
  // including `actions[]`. Skipping the live fetch on a cache hit is how
11
11
  // cross-addon toolbar actions disappear after an addon upgrade while
12
12
  // localStorage still holds the pre-upgrade catalog.
13
+ // - Entries are keyed by the `org:user:lang` scope (see cache-scope.ts):
14
+ // metadata carries the user's permissions, so a different account,
15
+ // organization or language never sees them. Unknown scope = no cache.
16
+ // Hosts call `clearMetadataCache()` on logout.
13
17
  // - `prefetchAll` replaces the catalog from `/metadata/all` and advances
14
18
  // `metadataVersion`; a version change wipes the prior cache.
15
19
  //
@@ -19,6 +23,7 @@
19
23
  import { create } from 'zustand'
20
24
  import { persist } from 'zustand/middleware'
21
25
  import type { TableMetadata } from './types'
26
+ import { cacheScope, onCacheScopeChange, peekCacheScope } from './cache-scope'
22
27
 
23
28
  export interface MetadataApiClient {
24
29
  get: (url: string, config?: any) => Promise<{ data: any }>
@@ -49,15 +54,36 @@ export function defaultAddonKeyMatcher(cacheKey: string, addonKey: string): bool
49
54
  )
50
55
  }
51
56
 
57
+ export interface SetMetadataOptions {
58
+ /** Scope captured when the request was made (null = it was unknown: discard). */
59
+ scope?: string | null
60
+ }
61
+
62
+ /** Scope to write under, or null when the answer must be dropped. */
63
+ function writeScope(opts?: SetMetadataOptions): string | null {
64
+ const now = cacheScope()
65
+ if (!now) return null
66
+ if (opts && opts.scope !== undefined && opts.scope !== now) return null
67
+ return now
68
+ }
69
+
52
70
  interface MetadataCacheState {
53
71
  cache: Record<string, TableMetadata>
54
72
  modalCache: Record<string, TableMetadata>
55
73
  metadataVersion: string
56
74
  prefetched: boolean
75
+ /** `org:user:lang` the entries above were read for ('' = none). */
76
+ scope: string
57
77
  getMetadata: (key: string) => TableMetadata | undefined
58
78
  getModalMetadata: (key: string) => TableMetadata | undefined
59
- setMetadata: (key: string, metadata: TableMetadata) => void
60
- setModalMetadata: (key: string, metadata: TableMetadata) => void
79
+ /**
80
+ * `opts.scope` is the `cacheScope()` captured when the request was ASKED.
81
+ * If the identity moved while it travelled, the answer is dropped instead
82
+ * of being stored under the new account. Without it the scope is read at
83
+ * write time (only safe for synchronous writes).
84
+ */
85
+ setMetadata: (key: string, metadata: TableMetadata, opts?: SetMetadataOptions) => void
86
+ setModalMetadata: (key: string, metadata: TableMetadata, opts?: SetMetadataOptions) => void
61
87
  hasMetadata: (key: string) => boolean
62
88
  hasModalMetadata: (key: string) => boolean
63
89
  prefetchAll: (api: MetadataApiClient) => Promise<void>
@@ -90,24 +116,31 @@ export const useMetadataCache = create<MetadataCacheState>()(
90
116
  modalCache: {},
91
117
  metadataVersion: '',
92
118
  prefetched: false,
119
+ scope: '',
93
120
 
94
- getMetadata: (key: string) => get().cache[key],
95
- getModalMetadata: (key: string) => get().modalCache[key],
121
+ getMetadata: (key: string) => (inScope(get()) ? get().cache[key] : undefined),
122
+ getModalMetadata: (key: string) => (inScope(get()) ? get().modalCache[key] : undefined),
96
123
 
97
- setMetadata: (key: string, metadata: TableMetadata) => {
124
+ setMetadata: (key: string, metadata: TableMetadata, opts?: SetMetadataOptions) => {
125
+ const scope = writeScope(opts)
126
+ if (!scope) return
98
127
  set((state) => ({
99
- cache: { ...state.cache, [key]: metadata },
128
+ ...(state.scope === scope ? {} : emptyFor(scope)),
129
+ cache: { ...(state.scope === scope ? state.cache : {}), [key]: metadata },
100
130
  }))
101
131
  },
102
132
 
103
- setModalMetadata: (key: string, metadata: TableMetadata) => {
133
+ setModalMetadata: (key: string, metadata: TableMetadata, opts?: SetMetadataOptions) => {
134
+ const scope = writeScope(opts)
135
+ if (!scope) return
104
136
  set((state) => ({
105
- modalCache: { ...state.modalCache, [key]: metadata },
137
+ ...(state.scope === scope ? {} : emptyFor(scope)),
138
+ modalCache: { ...(state.scope === scope ? state.modalCache : {}), [key]: metadata },
106
139
  }))
107
140
  },
108
141
 
109
- hasMetadata: (key: string) => key in get().cache,
110
- hasModalMetadata: (key: string) => key in get().modalCache,
142
+ hasMetadata: (key: string) => inScope(get()) && key in get().cache,
143
+ hasModalMetadata: (key: string) => inScope(get()) && key in get().modalCache,
111
144
 
112
145
  invalidateAddon: (addonKey: string, matcher = defaultAddonKeyMatcher) => {
113
146
  if (!addonKey) return 0
@@ -147,17 +180,21 @@ export const useMetadataCache = create<MetadataCacheState>()(
147
180
  modalCache: {},
148
181
  metadataVersion: '',
149
182
  prefetched: false,
183
+ scope: '',
150
184
  })
151
185
  },
152
186
 
153
187
  prefetchAll: async (api: MetadataApiClient) => {
154
- if (get().prefetched) return
188
+ const scope = cacheScope()
189
+ // Unknown identity: do not fetch into a cache nobody may read.
190
+ if (!scope) return
191
+ if (get().prefetched && get().scope === scope) return
155
192
  try {
156
193
  const res = await api.get('/metadata/all')
157
194
  const { tables, modals, version } = res.data.data
158
195
 
159
196
  const serverVersion = version || ''
160
- const localVersion = get().metadataVersion
197
+ const localVersion = get().scope === scope ? get().metadataVersion : ''
161
198
 
162
199
  // Always rebuild from the server catalog. Merging into a
163
200
  // persisted cache left hosts with pre-upgrade actions /
@@ -177,15 +214,19 @@ export const useMetadataCache = create<MetadataCacheState>()(
177
214
  }
178
215
  }
179
216
 
217
+ // The identity moved while the request was in flight: this
218
+ // answer belongs to the previous scope, drop it.
219
+ if (peekCacheScope() !== scope) return
180
220
  set({
181
221
  cache: newCache,
182
222
  modalCache: newModalCache,
183
223
  metadataVersion: serverVersion || localVersion || String(Date.now()),
184
224
  prefetched: true,
225
+ scope,
185
226
  })
186
227
  } catch {
187
- // Offline or error — keep using cached data.
188
- set({ prefetched: true })
228
+ // Offline or error — keep using cached data of this scope.
229
+ if (get().scope === scope) set({ prefetched: true })
189
230
  }
190
231
  },
191
232
  }),
@@ -193,18 +234,47 @@ export const useMetadataCache = create<MetadataCacheState>()(
193
234
  name: 'metacore-metadata-cache',
194
235
  // Bump when display hints (e.g. image_stack) must wipe stale cache.
195
236
  // v5: always replace catalog on prefetchAll (no merge-with-stale).
196
- version: 5,
237
+ // v6: entries are keyed by the org:user:lang scope; anything
238
+ // persisted before has no owner and is discarded.
239
+ version: 6,
197
240
  migrate: () => ({
198
241
  cache: {},
199
242
  modalCache: {},
200
243
  metadataVersion: '',
201
244
  prefetched: false,
245
+ scope: '',
202
246
  }),
203
247
  partialize: (state) => ({
204
248
  cache: state.cache,
205
249
  modalCache: state.modalCache,
206
250
  metadataVersion: state.metadataVersion,
251
+ scope: state.scope,
207
252
  }),
208
253
  }
209
254
  )
210
255
  )
256
+
257
+ function inScope(state: { scope: string }): boolean {
258
+ const scope = peekCacheScope()
259
+ return !!scope && state.scope === scope
260
+ }
261
+
262
+ function emptyFor(scope: string) {
263
+ return { cache: {}, modalCache: {}, metadataVersion: '', prefetched: false, scope }
264
+ }
265
+
266
+ /**
267
+ * Logout / account switch: drops the in-memory metadata AND the persisted copy
268
+ * (`metacore-metadata-cache`). Hosts call it when the session ends; the cache
269
+ * also clears itself when the org/user/lang scope changes.
270
+ */
271
+ export function clearMetadataCache(): void {
272
+ useMetadataCache.getState().clearAll()
273
+ try {
274
+ useMetadataCache.persist.clearStorage()
275
+ } catch {
276
+ /* storage unavailable */
277
+ }
278
+ }
279
+
280
+ onCacheScopeChange(() => clearMetadataCache())
@@ -6,6 +6,7 @@
6
6
  * success, data and etag. A failed part does not reject the others.
7
7
  */
8
8
  import type { ApiClient } from './api-context'
9
+ import { cacheScope, onCacheScopeChange } from './cache-scope'
9
10
 
10
11
  export interface QueryPart {
11
12
  success: boolean
@@ -14,6 +15,11 @@ export interface QueryPart {
14
15
  message?: string
15
16
  etag?: string
16
17
  not_modified?: boolean
18
+ /**
19
+ * HTTP-like status of this part. Servers that do not send it leave it
20
+ * undefined and the message heuristics apply (v2 adds it).
21
+ */
22
+ status?: number
17
23
  }
18
24
 
19
25
  const WINDOW_MS = 8
@@ -28,6 +34,8 @@ type Waiter = {
28
34
  cachedRows?: Record<string, unknown>[]
29
35
  missingIds?: string[]
30
36
  field?: string
37
+ /** Scope the read was asked under; null = uncached. */
38
+ scope: string | null
31
39
  }
32
40
 
33
41
  type CachedPart = { part: QueryPart; at: number }
@@ -120,6 +128,8 @@ export function narrowInToken(token: string, now = Date.now()): NarrowedIn | nul
120
128
  const parsed = splitInToken(token)
121
129
  if (!parsed) return null
122
130
  const scope = cacheScope()
131
+ // Unknown org/user/lang: never serve rows from memory.
132
+ if (!scope) return null
123
133
  const rows: Record<string, unknown>[] = []
124
134
  const missingIds: string[] = []
125
135
  for (const id of parsed.ids) {
@@ -154,6 +164,7 @@ export function rememberInRows(
154
164
  const parsed = splitInToken(token)
155
165
  if (!parsed) return
156
166
  const scope = cacheScope()
167
+ if (!scope) return
157
168
  const field = rowField(parsed.field)
158
169
  const byId = new Map<string, Record<string, unknown>[]>()
159
170
  for (const id of ids) byId.set(id, [])
@@ -183,13 +194,27 @@ function errorStatus(err: unknown): number | undefined {
183
194
 
184
195
  export function resetQueryBatchCache(): void {
185
196
  unsupportedClients = new WeakSet<object>()
197
+ clearQueryBatchCaches()
198
+ }
199
+
200
+ /**
201
+ * Drops everything the batch remembers (parts, entities) and rejects reads
202
+ * still waiting for the window, so nothing asked under the previous identity
203
+ * resolves after it ended. Hosts call it on logout; it also runs by itself
204
+ * when the org/user/lang scope changes.
205
+ */
206
+ export function clearQueryBatchCaches(): void {
186
207
  partCache.clear()
187
208
  entityCache.clear()
209
+ const pending = waiters
188
210
  waiters = []
189
211
  if (timer != null) clearTimeout(timer)
190
212
  timer = null
213
+ for (const waiter of pending) waiter.reject(new Error('batch cache cleared'))
191
214
  }
192
215
 
216
+ onCacheScopeChange(() => clearQueryBatchCaches())
217
+
193
218
  /**
194
219
  * Forgets every row, record and option read. useApi calls it after each
195
220
  * mutation so the list that just gained, changed or lost a row reads it
@@ -222,17 +247,6 @@ function mergeCachedRows(cached: Record<string, unknown>[] | undefined, part: Qu
222
247
  return { ...part, data: [...cached, ...fresh] }
223
248
  }
224
249
 
225
- function cacheScope(): string {
226
- if (typeof localStorage === 'undefined') return ''
227
- try {
228
- const raw = localStorage.getItem('auth_user')
229
- if (!raw) return ''
230
- return String((JSON.parse(raw) as { organization_id?: string }).organization_id ?? '')
231
- } catch {
232
- return ''
233
- }
234
- }
235
-
236
250
  export function optionsModelFromUrl(url: string): string | null {
237
251
  const match = url.match(/^\/options\/([A-Za-z][A-Za-z0-9_]*)$/)
238
252
  return match ? match[1] : null
@@ -271,7 +285,8 @@ export function nameBatchTokens(tokens: string[]): { name: string; token: string
271
285
  }
272
286
 
273
287
  export function loadQueryPart(api: ApiClient, token: string): Promise<QueryPart> {
274
- const cached = partCache.get(`${cacheScope()}\n${token}`)
288
+ const scope = cacheScope()
289
+ const cached = scope ? partCache.get(`${scope}\n${token}`) : undefined
275
290
  if (cached && servedFromMemory(token) && Date.now() - cached.at < PART_TTL_MS && cached.part.success) {
276
291
  return Promise.resolve(cached.part)
277
292
  }
@@ -289,6 +304,7 @@ export function loadQueryPart(api: ApiClient, token: string): Promise<QueryPart>
289
304
  cachedRows: narrowed?.rows,
290
305
  missingIds: narrowed?.missingIds,
291
306
  field: narrowed?.field,
307
+ scope,
292
308
  })
293
309
  if (timer == null) timer = setTimeout(() => void flushQueryBatch(), WINDOW_MS)
294
310
  })
@@ -296,16 +312,21 @@ export function loadQueryPart(api: ApiClient, token: string): Promise<QueryPart>
296
312
 
297
313
  async function flushQueryBatch() {
298
314
  timer = null
299
- const batch = waiters
315
+ const all = waiters
300
316
  waiters = []
317
+ const scope = cacheScope()
318
+ // Reads asked under another identity never travel with this one.
319
+ const batch = all.filter((waiter) => waiter.scope === scope)
320
+ for (const waiter of all) {
321
+ if (waiter.scope !== scope) waiter.reject(new Error('batch scope changed'))
322
+ }
301
323
  const api = transport
302
324
  if (!api || batch.length === 0) return
303
325
  const named = nameBatchTokens(batch.map((waiter) => waiter.wire))
304
326
  const byToken = new Map(named.map((part) => [part.token, part.name]))
305
327
  const inm: Record<string, string> = {}
306
- const scope = cacheScope()
307
328
  for (const part of named) {
308
- const cached = partCache.get(`${scope}\n${part.token}`)
329
+ const cached = scope ? partCache.get(`${scope}\n${part.token}`) : undefined
309
330
  const etag = cached?.part.etag
310
331
  if (etag && (servedFromMemory(part.token) || contentEtag(etag))) inm[part.name] = etag
311
332
  }
@@ -316,6 +337,13 @@ async function flushQueryBatch() {
316
337
  throw new Error('batch unavailable')
317
338
  }
318
339
  for (const waiter of batch) {
340
+ // First of all: the identity may have changed while the request
341
+ // travelled. Neither the answer (rows or not_modified) nor the
342
+ // caches of the previous identity may reach this reader.
343
+ if (cacheScope() !== scope) {
344
+ waiter.reject(new Error('batch scope changed'))
345
+ continue
346
+ }
319
347
  const name = byToken.get(waiter.wire)
320
348
  const part = name ? (body.parts[name] as QueryPart | undefined) : undefined
321
349
  if (!part) {
@@ -323,7 +351,7 @@ async function flushQueryBatch() {
323
351
  continue
324
352
  }
325
353
  if (part.not_modified) {
326
- const cached = partCache.get(`${scope}\n${waiter.token}`)
354
+ const cached = scope ? partCache.get(`${scope}\n${waiter.token}`) : undefined
327
355
  if (cached) {
328
356
  cached.at = Date.now()
329
357
  waiter.resolve(cached.part)
@@ -335,10 +363,10 @@ async function flushQueryBatch() {
335
363
  continue
336
364
  }
337
365
  const merged = mergeCachedRows(waiter.cachedRows, part)
338
- if (waiter.missingIds && waiter.field) {
366
+ if (scope && waiter.missingIds && waiter.field) {
339
367
  rememberInRows(waiter.token, waiter.missingIds, part.data)
340
368
  }
341
- if (part.success) {
369
+ if (scope && part.success) {
342
370
  partCache.set(`${scope}\n${waiter.token}`, { part: merged, at: Date.now() })
343
371
  }
344
372
  waiter.resolve(merged)
@@ -400,8 +428,26 @@ export function tokenForGet(url: string, params?: Record<string, unknown>): stri
400
428
  )
401
429
  }
402
430
 
403
- function batchForbidden(message?: string): boolean {
404
- return /forbidden|permiso/i.test(message || '')
431
+ /**
432
+ * Reads a failed part. The per-part `status` (when the server sends it) wins:
433
+ * 403 forbidden, 424 dependency failed (rejects, no retry), 5xx/413 a failure
434
+ * that gets ONE direct GET. Without `status` the message heuristic applies.
435
+ */
436
+ function failureKind(part: QueryPart): 'forbidden' | 'dependency' | 'retry' | 'plain' {
437
+ const status = part.status
438
+ if (typeof status === 'number') {
439
+ if (status === 403) return 'forbidden'
440
+ if (status === 424) return 'dependency'
441
+ if (status === 413 || status >= 500) return 'retry'
442
+ }
443
+ return /forbidden|permiso/i.test(part.message || '') ? 'forbidden' : 'plain'
444
+ }
445
+
446
+ function statusError(message: string, status: number): Error {
447
+ const err = new Error(message) as Error & { status: number; response: { status: number } }
448
+ err.status = status
449
+ err.response = { status }
450
+ return err
405
451
  }
406
452
 
407
453
  /**
@@ -417,22 +463,17 @@ export async function batchGet(api: ApiClient, url: string, config?: { params?:
417
463
  try {
418
464
  const part = await loadQueryPart(api, token)
419
465
  if (!part.success) {
420
- if (batchForbidden(part.message)) {
421
- const err = new Error(part.message || 'forbidden') as Error & {
422
- status: number
423
- response: { status: number }
424
- }
425
- err.status = 403
426
- err.response = { status: 403 }
427
- throw err
428
- }
466
+ const kind = failureKind(part)
467
+ if (kind === 'forbidden') throw statusError(part.message || 'forbidden', 403)
468
+ if (kind === 'dependency') throw statusError(part.message || 'dependency failed', 424)
469
+ // 'retry' and 'plain': one direct GET, whose own error propagates.
429
470
  return plainGet()
430
471
  }
431
472
  return { data: { success: true, data: part.data, meta: part.meta } }
432
473
  } catch (err) {
433
474
  const status = (err as { status?: number; response?: { status?: number } })?.status
434
475
  ?? (err as { response?: { status?: number } })?.response?.status
435
- if (status === 403) throw err
476
+ if (status === 403 || status === 424) throw err
436
477
  return plainGet()
437
478
  }
438
479
  }
@@ -146,7 +146,9 @@ export function useResolveOptionIds(args: UseResolveOptionIdsArgs): UseResolveOp
146
146
  queries: (active ? list : []).map((id) => ({
147
147
  queryKey: [QUERY_ROOT, scope, url, effectiveField, id],
148
148
  queryFn: () => enqueue(api, scope, url, effectiveField, id),
149
- staleTime: OPTION_IDS_TTL_MS,
149
+ // Unknown identity: nothing may be reused from a previous account.
150
+ staleTime: scope ? OPTION_IDS_TTL_MS : 0,
151
+ ...(scope ? {} : { gcTime: 0 }),
150
152
  retry: false,
151
153
  refetchOnWindowFocus: false,
152
154
  })),