@asteby/metacore-runtime-react 53.5.0 → 53.7.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.
@@ -112,6 +112,61 @@ describe('AddonConfigSurface', () => {
112
112
  expect(onSaved).toHaveBeenCalled()
113
113
  })
114
114
 
115
+ it('stored fields open locked: pencil unlocks, eye reveals a secret only for owners', async () => {
116
+ const values = { 'GET /integrations/mp/values': { data: { values: { public_key: 'APP_USR-x' }, secrets_set: ['access_token'] } } }
117
+ const reveal = { 'GET /integrations/mp/values/access_token/reveal?environment=sandbox': { data: { value: 'APP_USR-secret' } } }
118
+ const { calls } = setup({ connector, canRevealSecrets: true }, { ...values, ...reveal })
119
+ const pub = (await screen.findByLabelText(/Llave pública/)) as HTMLInputElement
120
+ const secret = screen.getByLabelText(/Token/) as HTMLInputElement
121
+ await waitFor(() => expect(pub.readOnly).toBe(true))
122
+ expect(secret.readOnly).toBe(true)
123
+ // eye on the locked secret fetches the value on demand
124
+ fireEvent.click(screen.getAllByLabelText('Ver')[0])
125
+ await waitFor(() => expect(secret.value).toBe('APP_USR-secret'))
126
+ expect(calls.some((c) => c.url === '/integrations/mp/values/access_token/reveal?environment=sandbox')).toBe(true)
127
+ // pencil unlocks the public key for editing
128
+ fireEvent.click(screen.getAllByLabelText('Editar')[0])
129
+ await waitFor(() => expect(pub.readOnly).toBe(false))
130
+ })
131
+
132
+ it('flipping the environment swaps the scoped fields for that environment\'s stored ones', async () => {
133
+ const conn: ConnectorEntry = {
134
+ ...connector,
135
+ credentials: [connector.credentials![2], connector.credentials![0], connector.credentials![1]].map((f) =>
136
+ f.key === 'env' ? { ...f, default: 'sandbox' } : f,
137
+ ),
138
+ }
139
+ const { calls } = setup(
140
+ { connector: conn },
141
+ {
142
+ 'GET /integrations/mp/values': { data: { values: { public_key: 'TEST-pub', env: 'sandbox' }, secrets_set: ['access_token'], env_scoped: ['public_key', 'access_token'] } },
143
+ 'GET /integrations/mp/values?environment=prod': { data: { values: {}, secrets_set: [], env_scoped: ['public_key', 'access_token'] } },
144
+ },
145
+ )
146
+ const pub = (await screen.findByLabelText(/Llave pública/)) as HTMLInputElement
147
+ await waitFor(() => expect(pub.value).toBe('TEST-pub'))
148
+ expect(pub.readOnly).toBe(true)
149
+ // flip to production: the sandbox keys go away, the fields open empty (nothing stored there yet)
150
+ const trigger = screen.getByRole('combobox')
151
+ fireEvent.pointerDown(trigger)
152
+ fireEvent.click(trigger)
153
+ fireEvent.click(await screen.findByText('prod'))
154
+ await waitFor(() => expect(calls.some((c) => c.url === '/integrations/mp/values?environment=prod')).toBe(true))
155
+ await waitFor(() => expect(pub.value).toBe(''))
156
+ expect(screen.queryByLabelText('Editar')).toBeNull()
157
+ })
158
+
159
+ it('without owner rights a locked secret has no eye and nothing is fetched', async () => {
160
+ const { calls } = setup(
161
+ { connector },
162
+ { 'GET /integrations/mp/values': { data: { values: { public_key: 'APP_USR-x' }, secrets_set: ['access_token'] } } },
163
+ )
164
+ const secret = (await screen.findByLabelText(/Token/)) as HTMLInputElement
165
+ await waitFor(() => expect(secret.readOnly).toBe(true))
166
+ expect(screen.queryByLabelText('Ver')).toBeNull()
167
+ expect(calls.some((c) => c.url.endsWith('/reveal'))).toBe(false)
168
+ })
169
+
115
170
  it('does not fetch stored values for non-admins and explains why', async () => {
116
171
  const { calls } = setup({ connector, canManageIssuer: false })
117
172
  expect(await screen.findByText(/Solo un administrador de la organización/)).toBeTruthy()
@@ -131,15 +186,27 @@ describe('AddonConfigSurface', () => {
131
186
  setup({ connector })
132
187
  const secret = await screen.findByLabelText(/Token/)
133
188
  fireEvent.change(secret, { target: { value: PUB } })
134
- const warn = await screen.findByRole('status')
135
- expect(warn.textContent).toContain('Llave pública')
189
+ await waitFor(() =>
190
+ expect(screen.getAllByRole('status').some((w) => w.textContent?.includes('Llave pública'))).toBe(true),
191
+ )
136
192
  })
137
193
 
138
- it('Probar conexión posts to /test and reports ok / failure', async () => {
139
- const { calls, notify } = setup({ connector }, { 'POST /integrations/mp/test': { data: { ok: false, message: 'Credenciales inválidas' } } })
140
- fireEvent.click(await screen.findByText('Probar conexión'))
141
- await waitFor(() => expect(notify.error).toHaveBeenCalledWith('Credenciales inválidas'))
194
+ it('Probar conexión runs inside the form (not the footer) and shows the result inline', async () => {
195
+ const { calls, notify } = setup(
196
+ { connector },
197
+ { 'POST /integrations/mp/test': { success: true, data: { ok: false, message: 'Credenciales inválidas' } } },
198
+ )
199
+ const btn = await screen.findByText('Probar conexión')
200
+ const footer = document.querySelector('[data-wizard-footer]') as HTMLElement
201
+ expect(footer.contains(btn)).toBe(false)
202
+ fireEvent.click(btn)
203
+ const msg = await screen.findByText('Credenciales inválidas')
204
+ expect(msg.closest('[data-result-status]')?.getAttribute('data-result-status')).toBe('error')
205
+ expect(msg.closest('[aria-live="polite"]')).toBeTruthy()
142
206
  expect(calls.some((c) => c.m === 'POST' && c.url === '/integrations/mp/test')).toBe(true)
207
+ expect(notify.error).not.toHaveBeenCalled()
208
+ // The retry keeps the same action reachable.
209
+ expect(screen.getByText(/Reintentar: Probar conexión/)).toBeTruthy()
143
210
  })
144
211
 
145
212
  it('dynamic_select lists options from the host lookup once per export', async () => {
@@ -0,0 +1,302 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest'
3
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
4
+ import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
5
+
6
+ vi.mock('react-i18next', () => {
7
+ const dict: Record<string, string> = {
8
+ 'mp.section.connection': 'Conexión',
9
+ 'mp.section.advanced': 'Avanzado',
10
+ 'mp.section.advanced_help': 'Webhooks y modo de pruebas.',
11
+ 'mp.field.token': 'Access token',
12
+ 'mp.field.secret': 'Secreto del webhook',
13
+ 'mp.block.webhook.title': 'URL de notificaciones',
14
+ 'mp.block.webhook.panel': 'Abrir panel de Mercado Pago',
15
+ 'mp.block.order.label': 'Crear orden de prueba',
16
+ 'mp.block.order.title': 'Prueba de cobro',
17
+ }
18
+ const t = (k: string, o?: { defaultValue?: string }) => dict[k] ?? o?.defaultValue ?? k
19
+ return { useTranslation: () => ({ t, i18n: { language: 'es', exists: () => true } }) }
20
+ })
21
+
22
+ import { ApiProvider } from '../api-context'
23
+ import { AddonConfigSurface, type ConnectorEntry } from '../setup/addon-config-surface'
24
+ import {
25
+ buildWizardSteps,
26
+ hasExplicitTest,
27
+ normalizeBlockResult,
28
+ safeHttpsUrl,
29
+ stepStatus,
30
+ } from '../setup/connector-blocks-model'
31
+
32
+ afterEach(cleanup)
33
+
34
+ const WEBHOOK = 'https://panel.example.com/api/webhooks/0b6f/mercadopago/notifications'
35
+
36
+ describe('connector-blocks-model', () => {
37
+ it('normalizes envelopes without inventing success', () => {
38
+ expect(normalizeBlockResult({ success: true, data: { ok: true, message: 'Listo' } })).toEqual({
39
+ status: 'ok',
40
+ message: 'Listo',
41
+ details: [],
42
+ })
43
+ expect(normalizeBlockResult({ success: false, error: { message: 'sin token' } }).status).toBe('error')
44
+ expect(normalizeBlockResult({ success: true, data: {} }, 'falló')).toEqual({ status: 'error', message: 'falló', details: [] })
45
+ // explicit ok:false beats a status that claims success
46
+ expect(normalizeBlockResult({ data: { ok: false, status: 'ok' } }).status).toBe('error')
47
+ const r = normalizeBlockResult({
48
+ success: true,
49
+ data: { ok: true, status: 'pending', details: [{ key: 'id', label: 'ID', value: 123, kind: 'id' }, { value: {} }] },
50
+ })
51
+ expect(r.status).toBe('pending')
52
+ expect(r.details).toEqual([{ key: 'id', label: 'ID', value: '123', kind: 'id' }])
53
+ })
54
+
55
+ it('only https URLs become links', () => {
56
+ expect(safeHttpsUrl('https://x.example/a')).toBe('https://x.example/a')
57
+ expect(safeHttpsUrl('http://x.example')).toBeNull()
58
+ expect(safeHttpsUrl('javascript:alert(1)')).toBeNull()
59
+ expect(safeHttpsUrl('https://user:pw@x.example')).toBeNull()
60
+ })
61
+
62
+ it('a section with only blocks is a step; settings append a last step', () => {
63
+ const steps = buildWizardSteps(
64
+ [{ key: 'a' }, { key: 'b', blocks: [{ key: 'w', kind: 'webhook_url' }] }, { key: 'c' }],
65
+ ['a'],
66
+ true,
67
+ )
68
+ expect(steps.map((s) => s.key)).toEqual(['a', 'b', '__settings'])
69
+ expect(hasExplicitTest([{ key: 'a', blocks: [{ key: 't', kind: 'action', export: 'ping' }] }], 'ping')).toBe(true)
70
+ expect(hasExplicitTest([{ key: 'a' }], 'ping')).toBe(false)
71
+ })
72
+
73
+ it('step status: errors win, then verification, then visited', () => {
74
+ const base = { index: 0, current: 1, fieldKeys: ['a'], fieldErrors: {}, blockKeys: ['t'], results: {} }
75
+ expect(stepStatus(base)).toBe('ok')
76
+ expect(stepStatus({ ...base, fieldErrors: { a: 'x' } })).toBe('error')
77
+ expect(stepStatus({ ...base, results: { t: { status: 'error', message: '', details: [] } } })).toBe('error')
78
+ expect(stepStatus({ ...base, index: 1, results: { t: { status: 'ok', message: '', details: [] } } })).toBe('ok')
79
+ expect(stepStatus({ ...base, index: 2 })).toBe('pending')
80
+ })
81
+ })
82
+
83
+ function makeApi(routes: Record<string, any> = {}) {
84
+ const calls: { m: string; url: string; body?: any }[] = []
85
+ const handle = (m: string) => async (url: string, body?: any) => {
86
+ calls.push({ m, url, body })
87
+ const r = routes[`${m} ${url}`]
88
+ if (r instanceof Error) throw r
89
+ return { data: typeof r === 'function' ? r(body) : (r ?? { data: {} }) }
90
+ }
91
+ return { client: { get: handle('GET'), post: handle('POST'), put: handle('PUT'), delete: handle('DELETE') }, calls }
92
+ }
93
+
94
+ const addon = { addon_key: 'mercadopago', manifest: { name: 'Mercado Pago', settings_defs: [] as any[] } }
95
+
96
+ const mp: ConnectorEntry = {
97
+ addon_key: 'mercadopago',
98
+ provider: 'mercadopago',
99
+ auth: 'token',
100
+ connected: true,
101
+ test_export: 'handle_connector_test',
102
+ form_layout: {
103
+ mode: 'steps',
104
+ sections: [
105
+ { key: 'connection', title: 'mp.section.connection' },
106
+ {
107
+ key: 'advanced',
108
+ title: 'mp.section.advanced',
109
+ description: 'mp.section.advanced_help',
110
+ blocks: [
111
+ {
112
+ key: 'webhook_url',
113
+ kind: 'webhook_url',
114
+ webhook: 'notifications',
115
+ title: 'mp.block.webhook.title',
116
+ value: WEBHOOK,
117
+ links: [{ label: 'mp.block.webhook.panel', url: 'https://www.mercadopago.com.mx/developers/panel/app' }],
118
+ },
119
+ { key: 'test_order', kind: 'action', export: 'handle_setup_test_order', label: 'mp.block.order.label', title: 'mp.block.order.title' },
120
+ ],
121
+ },
122
+ ],
123
+ },
124
+ credentials: [
125
+ { key: 'access_token', label: 'mp.field.token', type: 'secret', secret: true, required: true, section: 'connection' },
126
+ { key: 'webhook_secret', label: 'mp.field.secret', type: 'secret', secret: true, section: 'advanced' },
127
+ ],
128
+ }
129
+
130
+ function setup(connector: ConnectorEntry | null, routes: Record<string, any> = {}, extra: Record<string, any> = {}) {
131
+ const api = makeApi(routes)
132
+ const notify = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
133
+ const qc = new QueryClient({ defaultOptions: { mutations: { retry: false }, queries: { retry: false } } })
134
+ const onOpenChange = vi.fn()
135
+ render(
136
+ <QueryClientProvider client={qc}>
137
+ <ApiProvider client={api.client as any} batch={false}>
138
+ <AddonConfigSurface addon={addon} connector={connector} open onOpenChange={onOpenChange} notify={notify} {...extra} />
139
+ </ApiProvider>
140
+ </QueryClientProvider>,
141
+ )
142
+ return { ...api, notify, onOpenChange }
143
+ }
144
+
145
+ const footer = () => document.querySelector('[data-wizard-footer]') as HTMLElement
146
+
147
+ describe('AddonConfigSurface with setup blocks', () => {
148
+ it('step 2 shows the org webhook URL with copy, the panel link and the test-order action', async () => {
149
+ const writeText = vi.fn().mockResolvedValue(undefined)
150
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
151
+ setup(mp)
152
+ await screen.findByText('Access token')
153
+ fireEvent.click(within(footer()).getByText('Siguiente'))
154
+ expect(await screen.findByText(WEBHOOK)).toBeTruthy()
155
+ const link = screen.getByText('Abrir panel de Mercado Pago').closest('a')!
156
+ expect(link.getAttribute('href')).toBe('https://www.mercadopago.com.mx/developers/panel/app')
157
+ expect(link.getAttribute('rel')).toContain('noopener')
158
+ fireEvent.click(screen.getByRole('button', { name: 'Copiar URL de notificaciones' }))
159
+ await waitFor(() => expect(writeText).toHaveBeenCalledWith(WEBHOOK))
160
+ // The explicit test is the last credentials step's; the implicit one joins it.
161
+ expect(screen.getByText('Crear orden de prueba')).toBeTruthy()
162
+ expect(screen.getByText('Probar conexión')).toBeTruthy()
163
+ // Focus moved to the new step heading.
164
+ expect(document.activeElement?.textContent).toBe('Avanzado')
165
+ // Reading order: URL to paste, then the secret field, then the verifications.
166
+ const url = screen.getByText(WEBHOOK)
167
+ const secret = screen.getByLabelText(/Secreto del webhook/)
168
+ const action = screen.getByText('Crear orden de prueba')
169
+ expect(url.compareDocumentPosition(secret) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
170
+ expect(secret.compareDocumentPosition(action) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
171
+ })
172
+
173
+ it('runs the action block through the host route and shows ID + status live', async () => {
174
+ const { calls } = setup(mp, {
175
+ 'POST /integrations/mercadopago/blocks/test_order/run': {
176
+ success: true,
177
+ data: {
178
+ ok: true,
179
+ status: 'ok',
180
+ message: 'Preferencia de prueba creada',
181
+ details: [
182
+ { key: 'preference_id', label: 'ID de la preferencia', value: '123-abc', kind: 'id' },
183
+ { key: 'link', label: 'Pagar en sandbox', value: 'https://sandbox.mercadopago.com.mx/checkout/v1/redirect?pref_id=123-abc', kind: 'url' },
184
+ ],
185
+ },
186
+ },
187
+ })
188
+ await screen.findByText('Access token')
189
+ fireEvent.click(within(footer()).getByText('Siguiente'))
190
+ fireEvent.click(await screen.findByText('Crear orden de prueba'))
191
+ const msg = await screen.findByText('Preferencia de prueba creada')
192
+ const live = msg.closest('[aria-live="polite"]') as HTMLElement
193
+ expect(live.getAttribute('role')).toBe('status')
194
+ expect(within(live).getByText('123-abc')).toBeTruthy()
195
+ expect(within(live).getByText('Abrir enlace').closest('a')!.getAttribute('href')).toContain('sandbox.mercadopago.com.mx')
196
+ expect(calls.filter((c) => c.url === '/integrations/mercadopago/blocks/test_order/run')).toHaveLength(1)
197
+ // Stepper marks the verified step.
198
+ expect(document.querySelector('[data-step-status="ok"]')).toBeTruthy()
199
+ // Retry runs it again.
200
+ fireEvent.click(screen.getByText('Reintentar: Crear orden de prueba'))
201
+ await waitFor(() => expect(calls.filter((c) => c.url === '/integrations/mercadopago/blocks/test_order/run')).toHaveLength(2))
202
+ })
203
+
204
+ it('saves typed credentials before running an action (the host tests what is stored)', async () => {
205
+ const { calls } = setup(mp, {
206
+ 'POST /integrations/mercadopago/blocks/test_order/run': { success: true, data: { ok: true, message: 'ok' } },
207
+ })
208
+ await screen.findByText('Access token')
209
+ fireEvent.click(within(footer()).getByText('Siguiente'))
210
+ fireEvent.change(await screen.findByLabelText(/Secreto del webhook/), { target: { value: 'whsec' } })
211
+ expect(screen.getAllByText('Se guardarán tus cambios antes de probar.').length).toBeGreaterThan(0)
212
+ fireEvent.click(screen.getByText('Crear orden de prueba'))
213
+ await screen.findByText('ok')
214
+ const save = calls.findIndex((c) => c.m === 'POST' && c.url === '/integrations/mercadopago')
215
+ const run = calls.findIndex((c) => c.url.endsWith('/blocks/test_order/run'))
216
+ expect(save).toBeGreaterThanOrEqual(0)
217
+ expect(save).toBeLessThan(run)
218
+ expect(calls[save].body).toEqual({ webhook_secret: 'whsec' })
219
+ })
220
+
221
+ it('a failed HTTP call is an error result, never success', async () => {
222
+ const err = Object.assign(new Error('x'), { response: { data: { message: 'Guarda las credenciales antes de probar' } } })
223
+ setup(mp, { 'POST /integrations/mercadopago/blocks/test_order/run': err })
224
+ await screen.findByText('Access token')
225
+ fireEvent.click(within(footer()).getByText('Siguiente'))
226
+ fireEvent.click(await screen.findByText('Crear orden de prueba'))
227
+ const msg = await screen.findByText('Guarda las credenciales antes de probar')
228
+ expect(msg.closest('[data-result-status]')!.getAttribute('data-result-status')).toBe('error')
229
+ expect(document.querySelector('[data-step-status="error"]')).toBeTruthy()
230
+ })
231
+
232
+ it('Siguiente validates the current step before moving on', async () => {
233
+ setup({ ...mp, connected: false })
234
+ await screen.findByText('Access token')
235
+ fireEvent.click(within(footer()).getByText('Siguiente'))
236
+ expect((await screen.findByText(/Faltan campos obligatorios: Access token/)).getAttribute('role')).toBe('alert')
237
+ expect(screen.queryByText(WEBHOOK)).toBeNull()
238
+ })
239
+
240
+ it('footer: one primary, full width on phones; Atrás + Cancelar share a row', async () => {
241
+ setup(mp)
242
+ await screen.findByText('Access token')
243
+ fireEvent.click(within(footer()).getByText('Siguiente'))
244
+ await screen.findByText(WEBHOOK)
245
+ const buttons = within(footer()).getAllByRole('button')
246
+ expect(buttons.map((b) => b.textContent)).toEqual(['Guardar', 'Atrás', 'Cancelar'])
247
+ expect(buttons[0].className).toContain('col-span-2')
248
+ expect(buttons[0].className).toContain('h-11')
249
+ expect(buttons[1].className).not.toContain('col-span-2')
250
+ expect(buttons[2].className).not.toContain('col-span-2')
251
+ expect(within(footer()).queryByText('Probar conexión')).toBeNull()
252
+ expect(footer().className).toContain('grid-cols-2')
253
+ })
254
+
255
+ it('an explicit action bound to test_export replaces the implicit test', async () => {
256
+ const explicit: ConnectorEntry = {
257
+ ...mp,
258
+ form_layout: {
259
+ mode: 'steps',
260
+ sections: [
261
+ { key: 'connection', title: 'mp.section.connection', blocks: [{ key: 'ping', kind: 'action', export: 'handle_connector_test', label: 'Probar ahora' }] },
262
+ { key: 'advanced', title: 'mp.section.advanced' },
263
+ ],
264
+ },
265
+ }
266
+ setup(explicit)
267
+ expect(await screen.findByText('Probar ahora')).toBeTruthy()
268
+ fireEvent.click(within(footer()).getByText('Siguiente'))
269
+ await screen.findByText('Secreto del webhook')
270
+ expect(screen.queryByText('Probar conexión')).toBeNull()
271
+ })
272
+
273
+ it('long help expands instead of being cut', async () => {
274
+ const long = 'Ayuda '.repeat(60).trim()
275
+ setup({ ...mp, form_layout: { mode: 'steps', sections: [{ key: 'connection', title: 'mp.section.connection', description: long }, { key: 'advanced' }] } })
276
+ const p = await screen.findByText(long)
277
+ expect(p.className).toContain('line-clamp-3')
278
+ const more = screen.getByRole('button', { name: 'Ver más' })
279
+ expect(more.getAttribute('aria-expanded')).toBe('false')
280
+ fireEvent.click(more)
281
+ expect(p.className).not.toContain('line-clamp-3')
282
+ expect(screen.getByRole('button', { name: 'Ver menos' }).getAttribute('aria-expanded')).toBe('true')
283
+ })
284
+
285
+ it('OAuth connectors show their state and hand "Conectar cuenta" to the host', async () => {
286
+ const onConnectOAuth = vi.fn()
287
+ const gh: ConnectorEntry = { addon_key: 'mercadopago', provider: 'github', auth: 'oauth2', connected: false }
288
+ setup(gh, {}, { onConnectOAuth })
289
+ expect(await screen.findByText('Sin conectar')).toBeTruthy()
290
+ fireEvent.click(screen.getByText('Conectar cuenta'))
291
+ expect(onConnectOAuth).toHaveBeenCalledWith(gh)
292
+ })
293
+
294
+ it('an addon with nothing to configure shows a useful empty state and a single Cerrar', async () => {
295
+ const { onOpenChange } = setup(null)
296
+ expect(await screen.findByText('Nada que configurar')).toBeTruthy()
297
+ const buttons = within(footer()).getAllByRole('button')
298
+ expect(buttons.map((b) => b.textContent)).toEqual(['Cerrar'])
299
+ fireEvent.click(buttons[0])
300
+ expect(onOpenChange).toHaveBeenCalledWith(false)
301
+ })
302
+ })
package/src/index.ts CHANGED
@@ -199,6 +199,10 @@ export {
199
199
  HealthCard,
200
200
  StepStatusBadge,
201
201
  AddonConfigSurface,
202
+ ConnectorBlocks,
203
+ type ConnectorBlocksProps,
204
+ type ConnectorFormBlock,
205
+ type BlockResult,
202
206
  type SetupFlowProps,
203
207
  type SetupCustomStepProps,
204
208
  type SetupFormStepProps,