@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
@@ -0,0 +1,369 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3
+ import {
4
+ cacheScope,
5
+ peekCacheScope,
6
+ resetCacheScopeTracking,
7
+ setCacheScopeLanguageProvider,
8
+ setCacheScopeProvider,
9
+ } from './cache-scope'
10
+ import { clearMetadataCache, useMetadataCache } from './metadata-cache'
11
+ import { loadQueryPart, narrowInToken, resetQueryBatchCache } from './query-batch'
12
+ import { renderHook, waitFor } from '@testing-library/react'
13
+ import { createElement, type ReactNode } from 'react'
14
+ import { ApiProvider } from './api-context'
15
+ import { optionsScope, useOptionsResolver } from './use-options-resolver'
16
+ import type { TableMetadata } from './types'
17
+
18
+ function login(user: string, org: string, lang = 'es') {
19
+ localStorage.setItem('auth_user', JSON.stringify({ id: user, organization_id: org }))
20
+ localStorage.setItem('i18nextLng', lang)
21
+ }
22
+ const meta = (title: string) => ({ title, actions: [{ key: 'x' }] }) as unknown as TableMetadata
23
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
24
+
25
+ function jwt(claims: Record<string, unknown>): string {
26
+ const enc = (o: unknown) =>
27
+ btoa(JSON.stringify(o)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
28
+ return `${enc({ alg: 'HS256', typ: 'JWT' })}.${enc(claims)}.sig`
29
+ }
30
+
31
+ /** A POST /q the test releases by hand, to simulate a slow network. */
32
+ function heldApi() {
33
+ let release: (body: unknown) => void = () => {}
34
+ const gate = new Promise<unknown>((resolve) => (release = resolve))
35
+ const posts: { parts: string[]; inm: Record<string, string> }[] = []
36
+ const api = {
37
+ get: vi.fn(async () => ({ data: { success: true, data: [] } })),
38
+ post: vi.fn(async (_u: string, body: { parts: string[]; inm: Record<string, string> }) => {
39
+ posts.push(body)
40
+ return { data: await gate }
41
+ }),
42
+ put: vi.fn(),
43
+ delete: vi.fn(),
44
+ }
45
+ return { api, release, posts }
46
+ }
47
+
48
+ /** First answer for `token` (stored under u1 with a content etag). */
49
+ async function seedU1(token: string) {
50
+ const api = {
51
+ get: vi.fn(),
52
+ post: vi.fn(async () => ({
53
+ data: {
54
+ success: true,
55
+ parts: { q1: { success: true, data: [{ id: 'u1-row' }], etag: '"qh-1"' } },
56
+ },
57
+ })),
58
+ put: vi.fn(),
59
+ delete: vi.fn(),
60
+ }
61
+ const part = await loadQueryPart(api, token)
62
+ expect(part.data).toEqual([{ id: 'u1-row' }])
63
+ }
64
+
65
+ beforeEach(() => {
66
+ vi.useRealTimers()
67
+ setCacheScopeProvider(null)
68
+ setCacheScopeLanguageProvider(null)
69
+ localStorage.removeItem('auth_token')
70
+ resetQueryBatchCache()
71
+ clearMetadataCache()
72
+ resetCacheScopeTracking()
73
+ login('u1', 'o1')
74
+ cacheScope()
75
+ })
76
+ afterEach(() => {
77
+ setCacheScopeProvider(null)
78
+ localStorage.removeItem('auth_token')
79
+ login('u-test', 'o-test', 'en')
80
+ })
81
+
82
+ describe('in-flight batch answers (H1, H5a)', () => {
83
+ it('not_modified for a request that left under u1 never serves u1 rows to u2', async () => {
84
+ await seedU1('t:Sale?q=a')
85
+ const { api, release, posts } = heldApi()
86
+ const waiting = loadQueryPart(api, 't:Sale?q=a')
87
+ const outcome = waiting.then(
88
+ (part) => ({ ok: true as const, part }),
89
+ (error: Error) => ({ ok: false as const, error }),
90
+ )
91
+ await sleep(30)
92
+ expect(posts).toHaveLength(1)
93
+ expect(posts[0]!.inm).toEqual({ q1: '"qh-1"' })
94
+ login('u2', 'o1') // the identity changes while the POST travels
95
+ release({ success: true, parts: { q1: { success: true, not_modified: true } } })
96
+ const res = await outcome
97
+ expect(res.ok).toBe(false)
98
+ if (!res.ok) expect(res.error.message).toBe('batch scope changed')
99
+ })
100
+
101
+ it('rows for a request that left under u1 are rejected and nothing is stored', async () => {
102
+ const { api, release, posts } = heldApi()
103
+ const outcome = loadQueryPart(api, 't:Sale?q=b').then(
104
+ () => 'resolved',
105
+ (e: Error) => e.message,
106
+ )
107
+ await sleep(30)
108
+ expect(posts).toHaveLength(1)
109
+ login('u2', 'o1')
110
+ release({ success: true, parts: { q1: { success: true, data: [{ id: 'u1-secret' }], etag: '"qh-9"' } } })
111
+ expect(await outcome).toBe('batch scope changed')
112
+ // Back to u1 without notification: a stored entry would show up as an etag.
113
+ resetCacheScopeTracking()
114
+ login('u1', 'o1')
115
+ const next = heldApi()
116
+ const p = loadQueryPart(next.api, 't:Sale?q=b').catch(() => undefined)
117
+ await sleep(30)
118
+ expect(next.posts[0]!.inm).toEqual({})
119
+ next.release({ success: true, parts: { q1: { success: true, data: [] } } })
120
+ await p
121
+ })
122
+
123
+ it('an in: list answered after the identity changed is not remembered', async () => {
124
+ const { api, release } = heldApi()
125
+ const token = 't:Stock?product_id=in:a,b'
126
+ const outcome = loadQueryPart(api, token).then(
127
+ () => 'resolved',
128
+ (e: Error) => e.message,
129
+ )
130
+ await sleep(30)
131
+ login('u2', 'o1')
132
+ release({ success: true, parts: { q1: { success: true, data: [{ product_id: 'a' }] } } })
133
+ expect(await outcome).toBe('batch scope changed')
134
+ resetCacheScopeTracking()
135
+ login('u1', 'o1')
136
+ expect(narrowInToken(token)).toBeNull()
137
+ })
138
+ })
139
+
140
+ describe('prefetchAll with the identity changing mid-request (H5b)', () => {
141
+ it('drops the catalog fetched for the previous identity', async () => {
142
+ let release: () => void = () => {}
143
+ const gate = new Promise<void>((r) => (release = r))
144
+ const api = {
145
+ get: vi.fn(async () => {
146
+ await gate
147
+ return { data: { data: { tables: { Sale: meta('u1-secret') }, modals: {}, version: 'v1' } } }
148
+ }),
149
+ }
150
+ const p = useMetadataCache.getState().prefetchAll(api)
151
+ login('u2', 'o1')
152
+ release()
153
+ await p
154
+ expect(useMetadataCache.getState().cache).toEqual({})
155
+ expect(useMetadataCache.getState().prefetched).toBe(false)
156
+ resetCacheScopeTracking()
157
+ login('u1', 'o1')
158
+ expect(useMetadataCache.getState().getMetadata('Sale')).toBeUndefined()
159
+ })
160
+ })
161
+
162
+ describe('metadata written with the scope captured at request time (H3)', () => {
163
+ it('drops a direct GET answer that returns after the identity changed', () => {
164
+ const asked = cacheScope() // u1 asks
165
+ login('u2', 'o1')
166
+ useMetadataCache.getState().setMetadata('Sale', meta('u1-secret'), { scope: asked })
167
+ useMetadataCache.getState().setModalMetadata('Sale', meta('u1-secret'), { scope: asked })
168
+ expect(useMetadataCache.getState().getMetadata('Sale')).toBeUndefined()
169
+ expect(useMetadataCache.getState().getModalMetadata('Sale')).toBeUndefined()
170
+ expect(useMetadataCache.getState().cache).toEqual({})
171
+ })
172
+
173
+ it('stores when the scope still matches, and discards a captured null', () => {
174
+ useMetadataCache.getState().setMetadata('Sale', meta('mine'), { scope: cacheScope() })
175
+ expect(useMetadataCache.getState().getMetadata('Sale')?.title).toBe('mine')
176
+ useMetadataCache.getState().setMetadata('Other', meta('x'), { scope: null })
177
+ expect(useMetadataCache.getState().getMetadata('Other')).toBeUndefined()
178
+ })
179
+ })
180
+
181
+ describe('identity tied to the token (H2)', () => {
182
+ it('is null when the stored JWT belongs to another user or organization', () => {
183
+ login('u1', 'o1')
184
+ localStorage.setItem('auth_token', jwt({ sub: 'u2', org: 'o1' }))
185
+ expect(peekCacheScope()).toBeNull()
186
+ localStorage.setItem('auth_token', jwt({ sub: 'u1', org: 'o2' }))
187
+ expect(peekCacheScope()).toBeNull()
188
+ localStorage.setItem('auth_token', jwt({ ID: 'u2', OrganizationID: 'o1' }))
189
+ expect(peekCacheScope()).toBeNull()
190
+ })
191
+
192
+ it('matches when token and auth_user agree', () => {
193
+ localStorage.setItem('auth_token', jwt({ sub: 'u1', org: 'o1', exp: 9999999999 }))
194
+ expect(peekCacheScope()).toBe('o1:u1:es')
195
+ })
196
+
197
+ it('keeps trusting auth_user when the token is not a decodable JWT', () => {
198
+ localStorage.setItem('auth_token', 'opaque-session-token')
199
+ expect(peekCacheScope()).toBe('o1:u1:es')
200
+ localStorage.setItem('auth_token', 'a.%%%.c')
201
+ expect(peekCacheScope()).toBe('o1:u1:es')
202
+ })
203
+
204
+ it('the metadata cache is unreadable while the SSO token and auth_user disagree', () => {
205
+ useMetadataCache.getState().setMetadata('Sale', meta('mine'))
206
+ localStorage.setItem('auth_token', jwt({ sub: 'u2', org: 'o1' }))
207
+ expect(useMetadataCache.getState().getMetadata('Sale')).toBeUndefined()
208
+ })
209
+
210
+ it('setCacheScopeProvider feeds the scope and wins over localStorage', () => {
211
+ localStorage.setItem('auth_token', jwt({ sub: 'u9', org: 'o9' }))
212
+ setCacheScopeProvider(() => ({ org: 'oh', user: 'uh', lang: 'en' }))
213
+ expect(peekCacheScope()).toBe('oh:uh:en')
214
+ setCacheScopeProvider(() => ({ org: 'oh', user: 'uh' }))
215
+ expect(peekCacheScope()).toBe('oh:uh:es')
216
+ setCacheScopeProvider(() => null)
217
+ expect(peekCacheScope()).toBeNull()
218
+ setCacheScopeProvider(null)
219
+ expect(peekCacheScope()).toBeNull() // token of u9 vs auth_user u1
220
+ })
221
+ })
222
+
223
+ describe('options scope (H4)', () => {
224
+ it('keys by org:user:lang and branch, and is empty without identity', () => {
225
+ expect(optionsScope()).toBe('o1:u1:es|')
226
+ localStorage.setItem('active_branch_id', 'b1')
227
+ expect(optionsScope()).toBe('o1:u1:es|b1')
228
+ login('u2', 'o1')
229
+ expect(optionsScope()).toBe('o1:u2:es|b1')
230
+ localStorage.removeItem('auth_user')
231
+ expect(optionsScope()).toBe('')
232
+ localStorage.removeItem('active_branch_id')
233
+ })
234
+ })
235
+
236
+ describe('useOptionsResolver across identities (H4)', () => {
237
+ function client() {
238
+ return {
239
+ get: vi.fn(async () => ({
240
+ data: { success: true, data: [{ value: 'a', label: 'A' }], meta: { type: 'dynamic', count: 1 } },
241
+ })),
242
+ // Rejects like a host without /q: the resolver must fall back to GET.
243
+ post: vi.fn(async () => {
244
+ throw new Error('batch unavailable')
245
+ }),
246
+ put: vi.fn(),
247
+ delete: vi.fn(),
248
+ }
249
+ }
250
+ const wrap = (api: ReturnType<typeof client>) => ({ children }: { children: ReactNode }) =>
251
+ createElement(ApiProvider, { client: api as never, batch: false, children })
252
+
253
+ it('does not reuse one account options for the next one', async () => {
254
+ const api = client()
255
+ const args = { modelKey: 'Customer', fieldKey: 'id', query: 'zz-scope' }
256
+ const first = renderHook(() => useOptionsResolver(args), { wrapper: wrap(api) })
257
+ await waitFor(() => expect(first.result.current.options).toHaveLength(1))
258
+ first.unmount()
259
+ const calls = api.get.mock.calls.length
260
+ const again = renderHook(() => useOptionsResolver(args), { wrapper: wrap(api) })
261
+ await waitFor(() => expect(again.result.current.options).toHaveLength(1))
262
+ expect(api.get.mock.calls.length).toBe(calls) // same account: cached
263
+ again.unmount()
264
+ login('u2', 'o1')
265
+ cacheScope()
266
+ const other = renderHook(() => useOptionsResolver(args), { wrapper: wrap(api) })
267
+ await waitFor(() => expect(other.result.current.options).toHaveLength(1))
268
+ expect(api.get.mock.calls.length).toBe(calls + 1) // new account: asked again
269
+ other.unmount()
270
+ })
271
+
272
+ it('falls back to the plain GET when the batch is dropped by a scope change', async () => {
273
+ const api = client()
274
+ api.post = vi.fn(async () => ({ data: { success: true, parts: { q1: { success: true, data: [] } } } })) as never
275
+ const hook = renderHook(() => useOptionsResolver({ modelKey: 'Customer', fieldKey: 'id', query: 'zz-miss' }), {
276
+ wrapper: wrap(api),
277
+ })
278
+ login('u2', 'o1') // before the 8ms window closes
279
+ await waitFor(() => expect(hook.result.current.options).toHaveLength(1))
280
+ expect(hook.result.current.error).toBeNull()
281
+ expect(api.get).toHaveBeenCalled()
282
+ hook.unmount()
283
+ })
284
+ })
285
+
286
+ describe('row cache of the table (sessionStorage)', () => {
287
+ it('is wiped on a scope change', async () => {
288
+ const { clearTableDataCache } = await import('./dynamic-table')
289
+ sessionStorage.setItem('mc:tbl:data:v1|o1:u1:es|Sale||', '{"rows":[{"id":"u1-row"}],"rowCount":1,"ts":1}')
290
+ sessionStorage.setItem('unrelated', 'keep')
291
+ login('u2', 'o1')
292
+ cacheScope()
293
+ expect(sessionStorage.getItem('mc:tbl:data:v1|o1:u1:es|Sale||')).toBeNull()
294
+ expect(sessionStorage.getItem('unrelated')).toBe('keep')
295
+ sessionStorage.setItem('mc:tbl:data:v1|x', '1')
296
+ clearTableDataCache()
297
+ expect(sessionStorage.getItem('mc:tbl:data:v1|x')).toBeNull()
298
+ sessionStorage.removeItem('unrelated')
299
+ // The first import of dynamic-table is heavy: slow CI runners exceeded the 5 s default.
300
+ }, 60_000)
301
+ })
302
+
303
+ describe('JWT decoding memo', () => {
304
+ it('decodes the stored token once per distinct text, not on every peek', () => {
305
+ localStorage.setItem('auth_token', jwt({ sub: 'u1', org: 'o1', n: 'memo-a' }))
306
+ const atob = vi.spyOn(globalThis, 'atob')
307
+ try {
308
+ expect(peekCacheScope()).toBe('o1:u1:es')
309
+ const first = atob.mock.calls.length
310
+ expect(first).toBeGreaterThan(0)
311
+ for (let i = 0; i < 5; i++) peekCacheScope()
312
+ expect(atob.mock.calls.length).toBe(first)
313
+ // A different token is decoded again (and still checked against auth_user).
314
+ localStorage.setItem('auth_token', jwt({ sub: 'u2', org: 'o1', n: 'memo-b' }))
315
+ expect(peekCacheScope()).toBeNull()
316
+ expect(atob.mock.calls.length).toBeGreaterThan(first)
317
+ } finally {
318
+ atob.mockRestore()
319
+ }
320
+ })
321
+ })
322
+
323
+ describe('useOptionsResolver without identity (scope null)', () => {
324
+ it('neither reads the cache, shares the in-flight request nor writes', async () => {
325
+ const mk = () => ({
326
+ get: vi.fn(async () => ({
327
+ data: { success: true, data: [{ value: 'a', label: 'A' }], meta: { type: 'dynamic', count: 1 } },
328
+ })),
329
+ post: vi.fn(async () => {
330
+ throw new Error('batch unavailable')
331
+ }),
332
+ put: vi.fn(),
333
+ delete: vi.fn(),
334
+ })
335
+ const wrap = (api: ReturnType<typeof mk>) => ({ children }: { children: ReactNode }) =>
336
+ createElement(ApiProvider, { client: api as never, batch: false, children })
337
+ const args = { modelKey: 'Customer', fieldKey: 'id', query: 'zz-noident' }
338
+
339
+ // 1) With identity, warm the cache for this exact lookup.
340
+ const warm = mk()
341
+ const h0 = renderHook(() => useOptionsResolver(args), { wrapper: wrap(warm) })
342
+ await waitFor(() => expect(h0.result.current.options).toHaveLength(1))
343
+ h0.unmount()
344
+ expect(warm.get).toHaveBeenCalledTimes(1)
345
+
346
+ // 2) Identity lost: the warm entry must not be served.
347
+ localStorage.removeItem('auth_user')
348
+ expect(cacheScope()).toBeNull()
349
+ const api = mk()
350
+ const h1 = renderHook(() => useOptionsResolver(args), { wrapper: wrap(api) })
351
+ const h2 = renderHook(() => useOptionsResolver(args), { wrapper: wrap(api) })
352
+ await waitFor(() => expect(h1.result.current.options).toHaveLength(1))
353
+ await waitFor(() => expect(h2.result.current.options).toHaveLength(1))
354
+ // no cache read + no shared in-flight: each hook asked on its own
355
+ expect(api.get).toHaveBeenCalledTimes(2)
356
+ h1.unmount()
357
+ h2.unmount()
358
+
359
+ // 3) Nothing was written: once logged in again, the lookup goes to the network.
360
+ login('u1', 'o1')
361
+ cacheScope()
362
+ const after = mk()
363
+ const h3 = renderHook(() => useOptionsResolver({ ...args, query: 'zz-noident' }), { wrapper: wrap(after) })
364
+ await waitFor(() => expect(h3.result.current.options).toHaveLength(1))
365
+ // the warm entry was dropped by the scope change, and the no-identity runs wrote nothing
366
+ expect(after.get).toHaveBeenCalledTimes(1)
367
+ h3.unmount()
368
+ })
369
+ })
@@ -0,0 +1,234 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3
+ import { cacheScope, resetCacheScopeTracking, setCacheScopeLanguageProvider, syncCacheScope } from './cache-scope'
4
+ import { useMetadataCache, clearMetadataCache } from './metadata-cache'
5
+ import {
6
+ batchGet,
7
+ clearQueryBatchCaches,
8
+ loadQueryPart,
9
+ narrowInToken,
10
+ rememberInRows,
11
+ resetQueryBatchCache,
12
+ } from './query-batch'
13
+ import type { TableMetadata } from './types'
14
+
15
+ function login(user: string, org: string, lang = 'es') {
16
+ localStorage.setItem('auth_user', JSON.stringify({ id: user, organization_id: org }))
17
+ localStorage.setItem('i18nextLng', lang)
18
+ }
19
+ function logout() {
20
+ localStorage.removeItem('auth_user')
21
+ }
22
+ const meta = (title: string) => ({ title, actions: [{ key: 'x' }] }) as unknown as TableMetadata
23
+
24
+ beforeEach(() => {
25
+ vi.useRealTimers()
26
+ setCacheScopeLanguageProvider(null)
27
+ resetQueryBatchCache()
28
+ clearMetadataCache()
29
+ resetCacheScopeTracking()
30
+ login('u1', 'o1')
31
+ cacheScope()
32
+ })
33
+ afterEach(() => {
34
+ login('u-test', 'o-test', 'en')
35
+ })
36
+
37
+ describe('cacheScope', () => {
38
+ it('is org:user:lang and fails closed when a part is missing', () => {
39
+ expect(cacheScope()).toBe('o1:u1:es')
40
+ localStorage.setItem('auth_user', JSON.stringify({ id: 'u1' }))
41
+ expect(cacheScope()).toBeNull()
42
+ login('u1', 'o1')
43
+ localStorage.removeItem('i18nextLng')
44
+ expect(cacheScope()).toBeNull()
45
+ setCacheScopeLanguageProvider(() => 'fr')
46
+ expect(cacheScope()).toBe('o1:u1:fr')
47
+ })
48
+ })
49
+
50
+ describe('metadata store scoping', () => {
51
+ it('does not show another user, organization or language the cached metadata', () => {
52
+ const s = useMetadataCache.getState()
53
+ s.setMetadata('Sale', meta('mine'))
54
+ expect(useMetadataCache.getState().getMetadata('Sale')?.title).toBe('mine')
55
+ for (const [u, o, l] of [
56
+ ['u2', 'o1', 'es'],
57
+ ['u1', 'o2', 'es'],
58
+ ['u1', 'o1', 'en'],
59
+ ] as const) {
60
+ login(u, o, l)
61
+ expect(useMetadataCache.getState().getMetadata('Sale')).toBeUndefined()
62
+ expect(useMetadataCache.getState().hasMetadata('Sale')).toBe(false)
63
+ }
64
+ })
65
+
66
+ it('clears itself (memory and persisted copy) when the scope changes', () => {
67
+ useMetadataCache.getState().setMetadata('Sale', meta('mine'))
68
+ expect(localStorage.getItem('metacore-metadata-cache')).toContain('mine')
69
+ login('u2', 'o1')
70
+ syncCacheScope()
71
+ expect(useMetadataCache.getState().cache).toEqual({})
72
+ expect(localStorage.getItem('metacore-metadata-cache')).toBeNull()
73
+ })
74
+
75
+ it('clearMetadataCache wipes memory and storage; logout leaves nothing readable', () => {
76
+ useMetadataCache.getState().setMetadata('Sale', meta('mine'))
77
+ clearMetadataCache()
78
+ expect(useMetadataCache.getState().getMetadata('Sale')).toBeUndefined()
79
+ expect(localStorage.getItem('metacore-metadata-cache')).toBeNull()
80
+ })
81
+
82
+ it('does not cache without a scope', () => {
83
+ logout()
84
+ useMetadataCache.getState().setMetadata('Sale', meta('x'))
85
+ login('u1', 'o1')
86
+ expect(useMetadataCache.getState().getMetadata('Sale')).toBeUndefined()
87
+ })
88
+
89
+ it('writing under a new scope drops the previous scope entries', () => {
90
+ useMetadataCache.getState().setMetadata('Sale', meta('u1'))
91
+ login('u2', 'o1')
92
+ useMetadataCache.getState().setMetadata('Other', meta('u2'))
93
+ expect(Object.keys(useMetadataCache.getState().cache)).toEqual(['Other'])
94
+ login('u1', 'o1')
95
+ expect(useMetadataCache.getState().getMetadata('Sale')).toBeUndefined()
96
+ })
97
+
98
+ it('prefetchAll does nothing without a scope and rebuilds on a new one', async () => {
99
+ const api = {
100
+ get: vi.fn(async () => ({ data: { data: { tables: { Sale: meta('t') }, modals: {}, version: 'v1' } } })),
101
+ }
102
+ logout()
103
+ await useMetadataCache.getState().prefetchAll(api)
104
+ expect(api.get).not.toHaveBeenCalled()
105
+ login('u1', 'o1')
106
+ await useMetadataCache.getState().prefetchAll(api)
107
+ await useMetadataCache.getState().prefetchAll(api)
108
+ expect(api.get).toHaveBeenCalledTimes(1)
109
+ login('u2', 'o1')
110
+ await useMetadataCache.getState().prefetchAll(api)
111
+ expect(api.get).toHaveBeenCalledTimes(2)
112
+ })
113
+
114
+ it('discards a persisted v5 store on migration', async () => {
115
+ localStorage.setItem(
116
+ 'metacore-metadata-cache',
117
+ JSON.stringify({ state: { cache: { Sale: meta('old') }, modalCache: {}, metadataVersion: 'v' }, version: 5 }),
118
+ )
119
+ await useMetadataCache.persist.rehydrate()
120
+ expect(useMetadataCache.getState().cache).toEqual({})
121
+ expect(useMetadataCache.getState().getMetadata('Sale')).toBeUndefined()
122
+ })
123
+ })
124
+
125
+ function okApi(parts: Record<string, unknown>) {
126
+ return {
127
+ get: vi.fn(async () => ({ data: { success: true, data: [] } })),
128
+ post: vi.fn(async (_u: string, body: { parts: string[] }) => {
129
+ const out: Record<string, unknown> = {}
130
+ body.parts.forEach((p, i) => {
131
+ const token = p.slice(p.indexOf('=') + 1)
132
+ out[`q${i + 1}`] = parts[token] ?? { success: true, data: [] }
133
+ })
134
+ return { data: { success: true, parts: out } }
135
+ }),
136
+ put: vi.fn(),
137
+ delete: vi.fn(),
138
+ }
139
+ }
140
+
141
+ describe('query batch scoping', () => {
142
+ it('keeps two users, organizations and languages apart', async () => {
143
+ const api = okApi({ 'm:Sale': { success: true, data: { who: 'u1' }, etag: '"qh-1"' } })
144
+ await loadQueryPart(api, 'm:Sale')
145
+ await loadQueryPart(api, 'm:Sale')
146
+ expect(api.post).toHaveBeenCalledTimes(1)
147
+ for (const [u, o, l] of [
148
+ ['u2', 'o1', 'es'],
149
+ ['u1', 'o2', 'es'],
150
+ ['u1', 'o1', 'en'],
151
+ ] as const) {
152
+ login(u, o, l)
153
+ await loadQueryPart(api, 'm:Sale')
154
+ const last = api.post.mock.calls.at(-1)![1] as { inm: Record<string, string> }
155
+ expect(last.inm).toEqual({}) // no etag of the other scope leaks
156
+ }
157
+ expect(api.post).toHaveBeenCalledTimes(4)
158
+ })
159
+
160
+ it('does not cache without a scope', async () => {
161
+ const api = okApi({})
162
+ logout()
163
+ await loadQueryPart(api, 'm:Sale')
164
+ await loadQueryPart(api, 'm:Sale')
165
+ expect(api.post).toHaveBeenCalledTimes(2)
166
+ rememberInRows('t:Stock?product_id=in:a', ['a'], [{ product_id: 'a' }])
167
+ login('u1', 'o1')
168
+ expect(narrowInToken('t:Stock?product_id=in:a')).toBeNull()
169
+ })
170
+
171
+ it('clearQueryBatchCaches and a scope change forget parts and entities', async () => {
172
+ const api = okApi({})
173
+ await loadQueryPart(api, 'm:Sale')
174
+ rememberInRows('t:Stock?product_id=in:a', ['a'], [{ product_id: 'a' }])
175
+ clearQueryBatchCaches()
176
+ await loadQueryPart(api, 'm:Sale')
177
+ expect(api.post).toHaveBeenCalledTimes(2)
178
+ expect(narrowInToken('t:Stock?product_id=in:a')).toBeNull()
179
+
180
+ rememberInRows('t:Stock?product_id=in:a', ['a'], [{ product_id: 'a' }])
181
+ login('u2', 'o1')
182
+ syncCacheScope()
183
+ login('u1', 'o1')
184
+ syncCacheScope()
185
+ expect(narrowInToken('t:Stock?product_id=in:a')).toBeNull()
186
+ })
187
+
188
+ it('drops an answer that arrives after the identity changed', async () => {
189
+ const api = okApi({})
190
+ const p = loadQueryPart(api, 'm:Sale')
191
+ login('u2', 'o1')
192
+ await expect(p).rejects.toThrow()
193
+ login('u1', 'o1')
194
+ const again = await loadQueryPart(api, 'm:Sale')
195
+ expect(again.success).toBe(true)
196
+ })
197
+ })
198
+
199
+ describe('per-part status', () => {
200
+ const fail = (status: number | undefined, message = 'boom') => ({ success: false, message, status })
201
+ const run = async (part: unknown, getOk = true) => {
202
+ const api = okApi({ 'm:Sale': part })
203
+ if (!getOk) api.get.mockRejectedValueOnce(Object.assign(new Error('get failed'), { status: 500 }))
204
+ return { api, result: batchGet(api, '/metadata/table/Sale') }
205
+ }
206
+
207
+ it('403 is forbidden even without the word', async () => {
208
+ const { api, result } = await run(fail(403, 'nope'))
209
+ await expect(result).rejects.toMatchObject({ status: 403 })
210
+ expect(api.get).not.toHaveBeenCalled()
211
+ })
212
+ it('424 rejects without a direct GET', async () => {
213
+ const { api, result } = await run(fail(424))
214
+ await expect(result).rejects.toMatchObject({ status: 424 })
215
+ expect(api.get).not.toHaveBeenCalled()
216
+ })
217
+ it.each([500, 504, 413])('%i retries once by direct GET', async (status) => {
218
+ const { api, result } = await run(fail(status))
219
+ await expect(result).resolves.toMatchObject({ data: { success: true } })
220
+ expect(api.get).toHaveBeenCalledTimes(1)
221
+ })
222
+ it('a failing retry propagates (one retry only)', async () => {
223
+ const { api, result } = await run(fail(504), false)
224
+ await expect(result).rejects.toThrow('get failed')
225
+ expect(api.get).toHaveBeenCalledTimes(1)
226
+ })
227
+ it('without status keeps the message heuristic', async () => {
228
+ const forbidden = await run(fail(undefined, 'Forbidden: sin permiso'))
229
+ await expect(forbidden.result).rejects.toMatchObject({ status: 403 })
230
+ const other = await run(fail(undefined, 'weird'))
231
+ await expect(other.result).resolves.toBeDefined()
232
+ expect(other.api.get).toHaveBeenCalledTimes(1)
233
+ })
234
+ })