@asteby/metacore-runtime-react 53.0.0 → 53.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/dist/api-context.d.ts.map +1 -1
- package/dist/api-context.js +15 -1
- package/dist/cache-coherence.d.ts +65 -0
- package/dist/cache-coherence.d.ts.map +1 -0
- package/dist/cache-coherence.js +191 -0
- package/dist/dynamic-columns-helpers.d.ts +32 -0
- package/dist/dynamic-columns-helpers.d.ts.map +1 -1
- package/dist/dynamic-columns-helpers.js +33 -0
- package/dist/dynamic-columns.d.ts.map +1 -1
- package/dist/dynamic-columns.js +25 -3
- package/dist/host-api.d.ts.map +1 -1
- package/dist/host-api.js +34 -7
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/query-batch.d.ts +7 -0
- package/dist/query-batch.d.ts.map +1 -1
- package/dist/query-batch.js +10 -0
- package/package.json +5 -5
- package/src/__tests__/cache-coherence.test.tsx +248 -0
- package/src/__tests__/host-api.test.ts +66 -0
- package/src/__tests__/stage-column-labels.test.ts +54 -0
- package/src/api-context.tsx +22 -1
- package/src/cache-coherence.ts +215 -0
- package/src/dynamic-columns-helpers.ts +48 -0
- package/src/dynamic-columns.tsx +26 -3
- package/src/host-api.ts +30 -7
- package/src/index.ts +1 -0
- package/src/query-batch.ts +10 -0
package/dist/query-batch.d.ts
CHANGED
|
@@ -47,6 +47,13 @@ export declare function resetQueryBatchCache(): void;
|
|
|
47
47
|
* again instead of the copy from before the save. Metadata and i18n stay.
|
|
48
48
|
*/
|
|
49
49
|
export declare function invalidateQueryBatchData(): void;
|
|
50
|
+
/**
|
|
51
|
+
* Forgets EVERYTHING the batch remembered, metadata and i18n reads included
|
|
52
|
+
* (invalidateQueryBatchData keeps those on purpose: a save does not change
|
|
53
|
+
* them). Used when the cache epoch moves — an addon was installed, upgraded,
|
|
54
|
+
* enabled, disabled or uninstalled — because then they are exactly what is stale.
|
|
55
|
+
*/
|
|
56
|
+
export declare function invalidateQueryBatchAll(): void;
|
|
50
57
|
export declare function optionsModelFromUrl(url: string): string | null;
|
|
51
58
|
export declare function optionsBatchToken(model: string, field: string, query: string, limit: number | undefined, filter: string | undefined, context?: Record<string, string>): string;
|
|
52
59
|
/** Names each distinct token so the server can key the response. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-batch.d.ts","sourceRoot":"","sources":["../src/query-batch.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAE9C,MAAM,WAAW,SAAS;IACtB,OAAO,EAAE,OAAO,CAAA;IAChB,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,YAAY,CAAC,EAAE,OAAO,CAAA;CACzB;AAyCD,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAA;IACb,GAAG,EAAE,MAAM,EAAE,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;CAChB;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI,CAuB9D;AAkBD,MAAM,WAAW,UAAU;IACvB,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;IAC/B,UAAU,EAAE,MAAM,EAAE,CAAA;IACpB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;CAChB;AAED,0FAA0F;AAC1F,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,SAAa,GAAG,UAAU,GAAG,IAAI,CAsBhF;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAC1B,KAAK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D;AAED,wBAAgB,iBAAiB,CAC7B,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC,MAAM,CAQR;AAED,oEAAoE;AACpE,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,CAYjG;AAED,wBAAgB,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAsB/E;AAwED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,IAAI,CA8BxF;AAMD;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE;;;GA2BxG"}
|
package/dist/query-batch.js
CHANGED
|
@@ -153,6 +153,16 @@ export function invalidateQueryBatchData() {
|
|
|
153
153
|
}
|
|
154
154
|
entityCache.clear();
|
|
155
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Forgets EVERYTHING the batch remembered, metadata and i18n reads included
|
|
158
|
+
* (invalidateQueryBatchData keeps those on purpose: a save does not change
|
|
159
|
+
* them). Used when the cache epoch moves — an addon was installed, upgraded,
|
|
160
|
+
* enabled, disabled or uninstalled — because then they are exactly what is stale.
|
|
161
|
+
*/
|
|
162
|
+
export function invalidateQueryBatchAll() {
|
|
163
|
+
partCache.clear();
|
|
164
|
+
entityCache.clear();
|
|
165
|
+
}
|
|
156
166
|
let waiters = [];
|
|
157
167
|
let timer = null;
|
|
158
168
|
let transport = null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@asteby/metacore-runtime-react",
|
|
3
|
-
"version": "53.
|
|
3
|
+
"version": "53.2.0",
|
|
4
4
|
"description": "React runtime for metacore hosts — renders addon contributions dynamically",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -37,8 +37,8 @@
|
|
|
37
37
|
"zod": "^4.3.0"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
|
-
"@asteby/metacore-sdk": "^3.
|
|
41
|
-
"@asteby/metacore-ui": "^2.
|
|
40
|
+
"@asteby/metacore-sdk": "^3.17.0",
|
|
41
|
+
"@asteby/metacore-ui": "^2.29.0",
|
|
42
42
|
"@tanstack/react-query": ">=5",
|
|
43
43
|
"@tanstack/react-router": ">=1.100",
|
|
44
44
|
"@tanstack/react-table": ">=8",
|
|
@@ -69,8 +69,8 @@
|
|
|
69
69
|
}
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
|
-
"@asteby/metacore-sdk": "3.
|
|
73
|
-
"@asteby/metacore-ui": "2.
|
|
72
|
+
"@asteby/metacore-sdk": "3.17.0",
|
|
73
|
+
"@asteby/metacore-ui": "2.29.0",
|
|
74
74
|
"@tanstack/react-query": "^5.95.0",
|
|
75
75
|
"@tanstack/react-router": "^1.168.0",
|
|
76
76
|
"@tanstack/react-table": "^8.20.0",
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// Client side of the server's cache epoch: what runtime-react drops when it
|
|
4
|
+
// moves, how react-query is invalidated per addon, and the stale-plan retry of
|
|
5
|
+
// the ApiProvider interceptor.
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
7
|
+
import { cleanup, render } from '@testing-library/react'
|
|
8
|
+
import { QueryClient } from '@tanstack/react-query'
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
CACHE_EPOCH_CHANGED_EVENT,
|
|
12
|
+
CACHE_EPOCH_OBSERVED_EVENT,
|
|
13
|
+
dropAddonDerivedCaches,
|
|
14
|
+
epochFromAxiosHeaders,
|
|
15
|
+
invalidateAddonQueries,
|
|
16
|
+
isStaleStateError,
|
|
17
|
+
onCacheEpochChanged,
|
|
18
|
+
queryKeyBelongsToAddon,
|
|
19
|
+
reportCacheEpoch,
|
|
20
|
+
STALE_RETRIED_FLAG,
|
|
21
|
+
useCacheEpochSync,
|
|
22
|
+
} from '../cache-coherence'
|
|
23
|
+
import { ApiProvider, type ApiClient } from '../api-context'
|
|
24
|
+
import { useMetadataCache } from '../metadata-cache'
|
|
25
|
+
import { invalidateQueryBatchAll } from '../query-batch'
|
|
26
|
+
import { onOptionsCacheInvalidated } from '../use-options-resolver'
|
|
27
|
+
|
|
28
|
+
afterEach(cleanup)
|
|
29
|
+
|
|
30
|
+
function emitChanged(detail = { epoch: 'b', previous: 'a', source: 'header' as const }) {
|
|
31
|
+
window.dispatchEvent(new CustomEvent(CACHE_EPOCH_CHANGED_EVENT, { detail }))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
describe('window protocol', () => {
|
|
35
|
+
it('reportCacheEpoch dispatches the observed event and ignores junk', () => {
|
|
36
|
+
const seen: unknown[] = []
|
|
37
|
+
const h = (e: Event) => seen.push((e as CustomEvent).detail)
|
|
38
|
+
window.addEventListener(CACHE_EPOCH_OBSERVED_EVENT, h)
|
|
39
|
+
reportCacheEpoch('tok.1.2')
|
|
40
|
+
reportCacheEpoch('')
|
|
41
|
+
reportCacheEpoch(undefined)
|
|
42
|
+
reportCacheEpoch(7)
|
|
43
|
+
window.removeEventListener(CACHE_EPOCH_OBSERVED_EVENT, h)
|
|
44
|
+
expect(seen).toEqual([{ epoch: 'tok.1.2' }])
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('onCacheEpochChanged receives the change and unsubscribes', () => {
|
|
48
|
+
const fn = vi.fn()
|
|
49
|
+
const off = onCacheEpochChanged(fn)
|
|
50
|
+
emitChanged()
|
|
51
|
+
expect(fn).toHaveBeenCalledWith({ epoch: 'b', previous: 'a', source: 'header' })
|
|
52
|
+
off()
|
|
53
|
+
emitChanged()
|
|
54
|
+
expect(fn).toHaveBeenCalledTimes(1)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('reads the header from axios bags', () => {
|
|
58
|
+
expect(epochFromAxiosHeaders({ 'x-cache-epoch': 'a.1' })).toBe('a.1')
|
|
59
|
+
expect(epochFromAxiosHeaders({ get: (k: string) => (k === 'x-cache-epoch' ? 'a.2' : undefined) })).toBe('a.2')
|
|
60
|
+
expect(epochFromAxiosHeaders(undefined)).toBeUndefined()
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
describe('dropping what the epoch makes stale', () => {
|
|
65
|
+
beforeEach(() => useMetadataCache.getState().clearAll())
|
|
66
|
+
|
|
67
|
+
it('clears metadata, the read batch and the option lists', () => {
|
|
68
|
+
useMetadataCache.getState().setMetadata('suppliers', { title: 'Old' } as never)
|
|
69
|
+
expect(useMetadataCache.getState().getMetadata('suppliers')).toBeDefined()
|
|
70
|
+
const optionsDropped = vi.fn()
|
|
71
|
+
const off = onOptionsCacheInvalidated(optionsDropped)
|
|
72
|
+
dropAddonDerivedCaches()
|
|
73
|
+
off()
|
|
74
|
+
expect(useMetadataCache.getState().getMetadata('suppliers')).toBeUndefined()
|
|
75
|
+
expect(optionsDropped).toHaveBeenCalledTimes(1)
|
|
76
|
+
expect(() => invalidateQueryBatchAll()).not.toThrow()
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('useCacheEpochSync drops the caches and invalidates react-query when the epoch moves', () => {
|
|
80
|
+
useMetadataCache.getState().setMetadata('suppliers', { title: 'Old' } as never)
|
|
81
|
+
const qc = { invalidateQueries: vi.fn().mockResolvedValue(undefined) }
|
|
82
|
+
const onChange = vi.fn()
|
|
83
|
+
function Host() {
|
|
84
|
+
useCacheEpochSync({ queryClient: qc, onChange })
|
|
85
|
+
return null
|
|
86
|
+
}
|
|
87
|
+
render(<Host />)
|
|
88
|
+
emitChanged()
|
|
89
|
+
expect(useMetadataCache.getState().getMetadata('suppliers')).toBeUndefined()
|
|
90
|
+
expect(qc.invalidateQueries).toHaveBeenCalledTimes(1)
|
|
91
|
+
expect(onChange).toHaveBeenCalledWith({ epoch: 'b', previous: 'a', source: 'header' })
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
it('stops listening on unmount', () => {
|
|
95
|
+
const qc = { invalidateQueries: vi.fn().mockResolvedValue(undefined) }
|
|
96
|
+
function Host() {
|
|
97
|
+
useCacheEpochSync({ queryClient: qc })
|
|
98
|
+
return null
|
|
99
|
+
}
|
|
100
|
+
const { unmount } = render(<Host />)
|
|
101
|
+
unmount()
|
|
102
|
+
emitChanged()
|
|
103
|
+
expect(qc.invalidateQueries).not.toHaveBeenCalled()
|
|
104
|
+
})
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
describe('per-addon react-query invalidation', () => {
|
|
108
|
+
it('matches keys that mention the addon, by exact name or namespaced prefix', () => {
|
|
109
|
+
expect(queryKeyBelongsToAddon(['crm'], 'crm')).toBe(true)
|
|
110
|
+
expect(queryKeyBelongsToAddon(['data', 'crm.Lead', { page: 1 }], 'crm')).toBe(true)
|
|
111
|
+
expect(queryKeyBelongsToAddon(['x', 'crm:Lead'], 'crm')).toBe(true)
|
|
112
|
+
expect(queryKeyBelongsToAddon(['addon', { settings: '/addons/crm/settings' }], 'crm')).toBe(true)
|
|
113
|
+
expect(queryKeyBelongsToAddon(['data', 'crmx.Lead'], 'crm')).toBe(false)
|
|
114
|
+
expect(queryKeyBelongsToAddon(['data', 'pos.Order'], 'crm')).toBe(false)
|
|
115
|
+
expect(queryKeyBelongsToAddon(['data'], '')).toBe(false)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it('invalidates the addon queries and the shell roots, not unrelated data', async () => {
|
|
119
|
+
const qc = new QueryClient()
|
|
120
|
+
const seed = (key: unknown[]) => qc.setQueryData(key, 'x')
|
|
121
|
+
seed(['crm', 'leads'])
|
|
122
|
+
seed(['data', 'crm.Lead'])
|
|
123
|
+
seed(['marketplace', 'installed'])
|
|
124
|
+
seed(['navigation'])
|
|
125
|
+
seed(['data', 'pos.Order'])
|
|
126
|
+
seed(['customers', 'list'])
|
|
127
|
+
await invalidateAddonQueries(qc, 'crm')
|
|
128
|
+
const state = (key: unknown[]) => qc.getQueryState(key)?.isInvalidated
|
|
129
|
+
expect(state(['crm', 'leads'])).toBe(true)
|
|
130
|
+
expect(state(['data', 'crm.Lead'])).toBe(true)
|
|
131
|
+
expect(state(['marketplace', 'installed'])).toBe(true)
|
|
132
|
+
expect(state(['navigation'])).toBe(true)
|
|
133
|
+
expect(state(['data', 'pos.Order'])).toBeFalsy()
|
|
134
|
+
expect(state(['customers', 'list'])).toBeFalsy()
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
it('extra roots are honoured', async () => {
|
|
138
|
+
const qc = new QueryClient()
|
|
139
|
+
qc.setQueryData(['my-shell-thing'], 1)
|
|
140
|
+
await invalidateAddonQueries(qc, 'crm', { extraRoots: ['my-shell-thing'] })
|
|
141
|
+
expect(qc.getQueryState(['my-shell-thing'])?.isInvalidated).toBe(true)
|
|
142
|
+
})
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
describe('stale server state', () => {
|
|
146
|
+
it('recognises the incident error in the shapes it arrives in', () => {
|
|
147
|
+
const msg = 'ERROR: cached plan must not change result type (SQLSTATE 0A000)'
|
|
148
|
+
expect(isStaleStateError(new Error(msg))).toBe(true)
|
|
149
|
+
expect(isStaleStateError({ response: { status: 500, data: { error: { message: msg } } } })).toBe(true)
|
|
150
|
+
expect(isStaleStateError({ response: { data: { message: 'prepared statement "s" does not exist' } } })).toBe(true)
|
|
151
|
+
expect(isStaleStateError(new Error('duplicate key'))).toBe(false)
|
|
152
|
+
expect(isStaleStateError(undefined)).toBe(false)
|
|
153
|
+
})
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
describe('ApiProvider interceptor', () => {
|
|
157
|
+
function axiosLike() {
|
|
158
|
+
let onOk: (r: any) => any = (r) => r
|
|
159
|
+
let onErr: (e: any) => any = (e) => Promise.reject(e)
|
|
160
|
+
const eject = vi.fn()
|
|
161
|
+
const request = vi.fn()
|
|
162
|
+
const client = {
|
|
163
|
+
get: vi.fn(),
|
|
164
|
+
post: vi.fn(),
|
|
165
|
+
put: vi.fn(),
|
|
166
|
+
delete: vi.fn(),
|
|
167
|
+
request,
|
|
168
|
+
interceptors: {
|
|
169
|
+
response: {
|
|
170
|
+
use: (a: any, b: any) => {
|
|
171
|
+
onOk = a
|
|
172
|
+
onErr = b
|
|
173
|
+
return 3
|
|
174
|
+
},
|
|
175
|
+
eject,
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
return { client: client as unknown as ApiClient, ok: (r: any) => onOk(r), err: (e: any) => onErr(e), request, eject }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
it('reports the epoch of every answer, ok or failed', async () => {
|
|
183
|
+
const ax = axiosLike()
|
|
184
|
+
const seen: string[] = []
|
|
185
|
+
const h = (e: Event) => seen.push((e as CustomEvent).detail.epoch)
|
|
186
|
+
window.addEventListener(CACHE_EPOCH_OBSERVED_EVENT, h)
|
|
187
|
+
render(
|
|
188
|
+
<ApiProvider client={ax.client} batch={false}>
|
|
189
|
+
<div />
|
|
190
|
+
</ApiProvider>,
|
|
191
|
+
)
|
|
192
|
+
ax.ok({ headers: { 'x-cache-epoch': 'e.1' }, config: { method: 'get', url: '/x' } })
|
|
193
|
+
await ax.err({ response: { headers: { 'x-cache-epoch': 'e.2' } }, config: { method: 'get', url: '/x' } }).catch(() => {})
|
|
194
|
+
window.removeEventListener(CACHE_EPOCH_OBSERVED_EVENT, h)
|
|
195
|
+
expect(seen).toEqual(['e.1', 'e.2'])
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
it('re-sends a request that hit a stale plan exactly once', async () => {
|
|
199
|
+
vi.useFakeTimers()
|
|
200
|
+
try {
|
|
201
|
+
const ax = axiosLike()
|
|
202
|
+
render(
|
|
203
|
+
<ApiProvider client={ax.client} batch={false}>
|
|
204
|
+
<div />
|
|
205
|
+
</ApiProvider>,
|
|
206
|
+
)
|
|
207
|
+
const config: Record<string, unknown> = { method: 'post', url: '/addresses' }
|
|
208
|
+
const stale = {
|
|
209
|
+
config,
|
|
210
|
+
response: { status: 500, data: { error: { message: 'cached plan must not change result type (SQLSTATE 0A000)' } } },
|
|
211
|
+
}
|
|
212
|
+
ax.request.mockResolvedValueOnce({ data: 'saved', config })
|
|
213
|
+
const p = ax.err(stale)
|
|
214
|
+
await vi.advanceTimersByTimeAsync(300)
|
|
215
|
+
await expect(p).resolves.toMatchObject({ data: 'saved' })
|
|
216
|
+
expect(ax.request).toHaveBeenCalledTimes(1)
|
|
217
|
+
expect(config[STALE_RETRIED_FLAG]).toBe(true)
|
|
218
|
+
// the same request failing again is not retried again
|
|
219
|
+
await expect(ax.err(stale)).rejects.toBe(stale)
|
|
220
|
+
expect(ax.request).toHaveBeenCalledTimes(1)
|
|
221
|
+
} finally {
|
|
222
|
+
vi.useRealTimers()
|
|
223
|
+
}
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
it('does not retry ordinary failures', async () => {
|
|
227
|
+
const ax = axiosLike()
|
|
228
|
+
render(
|
|
229
|
+
<ApiProvider client={ax.client} batch={false}>
|
|
230
|
+
<div />
|
|
231
|
+
</ApiProvider>,
|
|
232
|
+
)
|
|
233
|
+
const e = { config: { method: 'get', url: '/x' }, response: { status: 403, data: { message: 'forbidden' } } }
|
|
234
|
+
await expect(ax.err(e)).rejects.toBe(e)
|
|
235
|
+
expect(ax.request).not.toHaveBeenCalled()
|
|
236
|
+
})
|
|
237
|
+
|
|
238
|
+
it('ejects the interceptor on unmount', () => {
|
|
239
|
+
const ax = axiosLike()
|
|
240
|
+
const { unmount } = render(
|
|
241
|
+
<ApiProvider client={ax.client} batch={false}>
|
|
242
|
+
<div />
|
|
243
|
+
</ApiProvider>,
|
|
244
|
+
)
|
|
245
|
+
unmount()
|
|
246
|
+
expect(ax.eject).toHaveBeenCalledWith(3)
|
|
247
|
+
})
|
|
248
|
+
})
|
|
@@ -43,6 +43,72 @@ describe('createHostApi', () => {
|
|
|
43
43
|
expect(client.get).toHaveBeenLastCalledWith('/plain')
|
|
44
44
|
})
|
|
45
45
|
|
|
46
|
+
it('responseType blob: asks the transport for a Blob and resolves to it, nothing else', async () => {
|
|
47
|
+
const pdf = new Blob(['%PDF-1.4'], { type: 'application/pdf' })
|
|
48
|
+
const client = axiosLike()
|
|
49
|
+
;(client.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
|
50
|
+
data: pdf,
|
|
51
|
+
headers: { 'content-type': 'application/pdf' },
|
|
52
|
+
config: { headers: { Authorization: TOKEN } },
|
|
53
|
+
})
|
|
54
|
+
const api = createHostApi(client, { batchGets: true })
|
|
55
|
+
const out = await api.get<Blob>('/data/WarehouseOrder/1/documents/ticket.pdf', { responseType: 'blob' })
|
|
56
|
+
expect(out).toBe(pdf)
|
|
57
|
+
expect(client.get).toHaveBeenCalledWith('/data/WarehouseOrder/1/documents/ticket.pdf', { responseType: 'blob' })
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('responseType blob works on post and wraps raw bytes in a Blob', async () => {
|
|
61
|
+
const client = axiosLike()
|
|
62
|
+
;(client.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ data: new Uint8Array([1, 2, 3]) })
|
|
63
|
+
const out = await createHostApi(client).post<Blob>('/export', { a: 1 }, { responseType: 'blob' })
|
|
64
|
+
expect(out).toBeInstanceOf(Blob)
|
|
65
|
+
expect(out.size).toBe(3)
|
|
66
|
+
expect(client.post).toHaveBeenCalledWith('/export', { a: 1 }, { responseType: 'blob' })
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('responseType blob: a non-binary success body is rejected', async () => {
|
|
70
|
+
const client = axiosLike()
|
|
71
|
+
await expect(
|
|
72
|
+
createHostApi(client).get('/x', { responseType: 'blob' }),
|
|
73
|
+
).rejects.toBeInstanceOf(HostApiError)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('responseType blob: error bodies delivered as Blob are decoded to code/message and never leak the token', async () => {
|
|
77
|
+
const client = axiosLike()
|
|
78
|
+
;(client.get as ReturnType<typeof vi.fn>).mockRejectedValueOnce({
|
|
79
|
+
message: 'boom',
|
|
80
|
+
config: { headers: { Authorization: TOKEN } },
|
|
81
|
+
response: {
|
|
82
|
+
status: 409,
|
|
83
|
+
data: new Blob([JSON.stringify({ code: 'invalid_state', message: 'No imprimible' })]),
|
|
84
|
+
},
|
|
85
|
+
})
|
|
86
|
+
const err = await createHostApi(client)
|
|
87
|
+
.get('/doc.pdf', { responseType: 'blob' })
|
|
88
|
+
.catch((e) => e)
|
|
89
|
+
expect(err).toBeInstanceOf(HostApiError)
|
|
90
|
+
expect(err.status).toBe(409)
|
|
91
|
+
expect(err.code).toBe('invalid_state')
|
|
92
|
+
expect(err.message).toBe('No imprimible')
|
|
93
|
+
expect(JSON.stringify(err)).not.toContain('secret-jwt')
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
it('responseType blob: a non-JSON error blob falls back to the status message', async () => {
|
|
97
|
+
const client = axiosLike()
|
|
98
|
+
;(client.get as ReturnType<typeof vi.fn>).mockRejectedValueOnce({
|
|
99
|
+
response: { status: 500, data: new Blob(['<html>'])},
|
|
100
|
+
})
|
|
101
|
+
const err = await createHostApi(client).get('/doc.pdf', { responseType: 'blob' }).catch((e) => e)
|
|
102
|
+
expect(err.status).toBe(500)
|
|
103
|
+
expect(err.message).toBe('Request failed with status 500')
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it('json (default) requests are unchanged: no responseType forwarded', async () => {
|
|
107
|
+
const client = axiosLike()
|
|
108
|
+
await createHostApi(client).get('/x', { responseType: 'json' })
|
|
109
|
+
expect(client.get).toHaveBeenCalledWith('/x', {})
|
|
110
|
+
})
|
|
111
|
+
|
|
46
112
|
it('posts capability queries to the host endpoint', async () => {
|
|
47
113
|
const client = axiosLike()
|
|
48
114
|
const api = createHostApi(client, { capabilityPath: '/caps' })
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Enum/status cells never show the raw value: a stage column with no options
|
|
3
|
+
// paints the translated stage label («Listo»), and an option whose label is an
|
|
4
|
+
// unresolved catalog key is translated (or humanized), never printed as a key.
|
|
5
|
+
import { describe, expect, it } from 'vitest'
|
|
6
|
+
import { resolveColumnOptions } from '../dynamic-columns-helpers'
|
|
7
|
+
|
|
8
|
+
const catalog: Record<string, string> = {
|
|
9
|
+
'channel_orders.stage.ready': 'Listo',
|
|
10
|
+
'channel_orders.stage.fulfilled': 'Cumplido',
|
|
11
|
+
'channel_orders.option.channel.web': 'Web',
|
|
12
|
+
}
|
|
13
|
+
const t = (key: string, o?: { defaultValue?: string }) => catalog[key] ?? o?.defaultValue ?? key
|
|
14
|
+
|
|
15
|
+
const stages = [
|
|
16
|
+
{ key: 'imported', label: 'channel_orders.stage.imported', color: 'slate' },
|
|
17
|
+
{ key: 'ready', label: 'channel_orders.stage.ready', color: 'cyan' },
|
|
18
|
+
{ key: 'fulfilled', label: 'Cumplido (literal)', color: 'green' },
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
describe('resolveColumnOptions', () => {
|
|
22
|
+
it('la columna de etapa sin options usa las etiquetas traducidas de stages', () => {
|
|
23
|
+
const opts = resolveColumnOptions({ columnKey: 'status', stages, stageField: 'status', translate: t })!
|
|
24
|
+
expect(opts.map((o) => [o.value, o.label])).toEqual([
|
|
25
|
+
['imported', 'Imported'], // sin traducción en el catálogo: humanizada, nunca la clave
|
|
26
|
+
['ready', 'Listo'],
|
|
27
|
+
['fulfilled', 'Cumplido (literal)'],
|
|
28
|
+
])
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('otra columna no toma las etapas', () => {
|
|
32
|
+
expect(resolveColumnOptions({ columnKey: 'channel', stages, stageField: 'status', translate: t })).toBeUndefined()
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('labelKey no resuelta por el servidor se traduce en el cliente', () => {
|
|
36
|
+
const opts = resolveColumnOptions({
|
|
37
|
+
columnKey: 'channel',
|
|
38
|
+
options: [{ value: 'web', label: 'Web', labelKey: 'channel_orders.option.channel.web' }],
|
|
39
|
+
translate: t,
|
|
40
|
+
})!
|
|
41
|
+
expect(opts[0].label).toBe('Web')
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it('las options propias de la columna ganan sobre las etapas', () => {
|
|
45
|
+
const opts = resolveColumnOptions({
|
|
46
|
+
columnKey: 'status',
|
|
47
|
+
options: [{ value: 'ready', label: 'Propia' }],
|
|
48
|
+
stages,
|
|
49
|
+
stageField: 'status',
|
|
50
|
+
translate: t,
|
|
51
|
+
})!
|
|
52
|
+
expect(opts).toEqual([{ value: 'ready', label: 'Propia' }])
|
|
53
|
+
})
|
|
54
|
+
})
|
package/src/api-context.tsx
CHANGED
|
@@ -5,6 +5,13 @@
|
|
|
5
5
|
import React, { createContext, useContext, useEffect, useMemo } from 'react'
|
|
6
6
|
import { batchGet, invalidateQueryBatchData } from './query-batch'
|
|
7
7
|
import { invalidateOptionsCache } from './use-options-resolver'
|
|
8
|
+
import {
|
|
9
|
+
epochFromAxiosHeaders,
|
|
10
|
+
isStaleStateError,
|
|
11
|
+
reportCacheEpoch,
|
|
12
|
+
STALE_RETRIED_FLAG,
|
|
13
|
+
STALE_RETRY_DELAY_MS,
|
|
14
|
+
} from './cache-coherence'
|
|
8
15
|
|
|
9
16
|
/** Minimal axios-compatible client shape consumed by runtime-react. */
|
|
10
17
|
export interface ApiClient {
|
|
@@ -42,11 +49,24 @@ export function ApiProvider({ client, batch = true, children }: ApiProviderProps
|
|
|
42
49
|
}
|
|
43
50
|
const id = interceptors.use(
|
|
44
51
|
(res: any) => {
|
|
52
|
+
// Every answer carries the server's cache epoch: a token that
|
|
53
|
+
// moved means an addon changed since this tab last looked.
|
|
54
|
+
reportCacheEpoch(epochFromAxiosHeaders(res?.headers))
|
|
45
55
|
onSettled(res?.config)
|
|
46
56
|
return res
|
|
47
57
|
},
|
|
48
|
-
(err: any) => {
|
|
58
|
+
async (err: any) => {
|
|
59
|
+
reportCacheEpoch(epochFromAxiosHeaders(err?.response?.headers))
|
|
49
60
|
onSettled(err?.config)
|
|
61
|
+
// A prepared plan outdated by an addon migration fails ONCE
|
|
62
|
+
// (SQLSTATE 0A000 / 26000) before the statement runs and the
|
|
63
|
+
// server drops it: re-send the request one time.
|
|
64
|
+
const config = err?.config as Record<string, unknown> | undefined
|
|
65
|
+
if (config && !config[STALE_RETRIED_FLAG] && isStaleStateError(err) && typeof (client as AxiosLike).request === 'function') {
|
|
66
|
+
config[STALE_RETRIED_FLAG] = true
|
|
67
|
+
await new Promise((r) => setTimeout(r, STALE_RETRY_DELAY_MS))
|
|
68
|
+
return (client as AxiosLike).request!(config)
|
|
69
|
+
}
|
|
50
70
|
return Promise.reject(err)
|
|
51
71
|
},
|
|
52
72
|
)
|
|
@@ -60,6 +80,7 @@ export function ApiProvider({ client, batch = true, children }: ApiProviderProps
|
|
|
60
80
|
}
|
|
61
81
|
|
|
62
82
|
interface AxiosLike {
|
|
83
|
+
request?: (config: any) => Promise<any>
|
|
63
84
|
interceptors?: {
|
|
64
85
|
response?: {
|
|
65
86
|
use?: (onFulfilled: (res: any) => any, onRejected: (err: any) => any) => number
|