@asteby/metacore-runtime-react 53.4.1 → 53.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +73 -0
  3. package/dist/index.d.ts +2 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +4 -0
  6. package/dist/setup/addon-config-surface.d.ts +119 -0
  7. package/dist/setup/addon-config-surface.d.ts.map +1 -0
  8. package/dist/setup/addon-config-surface.js +662 -0
  9. package/dist/setup/connector-blocks-model.d.ts +79 -0
  10. package/dist/setup/connector-blocks-model.d.ts.map +1 -0
  11. package/dist/setup/connector-blocks-model.js +96 -0
  12. package/dist/setup/connector-blocks.d.ts +48 -0
  13. package/dist/setup/connector-blocks.d.ts.map +1 -0
  14. package/dist/setup/connector-blocks.js +132 -0
  15. package/dist/setup/connector-form-model.d.ts +40 -0
  16. package/dist/setup/connector-form-model.d.ts.map +1 -0
  17. package/dist/setup/connector-form-model.js +76 -0
  18. package/dist/setup/flow-model.d.ts +49 -0
  19. package/dist/setup/flow-model.d.ts.map +1 -0
  20. package/dist/setup/flow-model.js +124 -0
  21. package/dist/setup/health-card.d.ts +25 -0
  22. package/dist/setup/health-card.d.ts.map +1 -0
  23. package/dist/setup/health-card.js +21 -0
  24. package/dist/setup/index.d.ts +13 -0
  25. package/dist/setup/index.d.ts.map +1 -0
  26. package/dist/setup/index.js +15 -0
  27. package/dist/setup/messages.d.ts +15 -0
  28. package/dist/setup/messages.d.ts.map +1 -0
  29. package/dist/setup/messages.js +320 -0
  30. package/dist/setup/records-table.d.ts +24 -0
  31. package/dist/setup/records-table.d.ts.map +1 -0
  32. package/dist/setup/records-table.js +80 -0
  33. package/dist/setup/setup-flow.d.ts +30 -0
  34. package/dist/setup/setup-flow.d.ts.map +1 -0
  35. package/dist/setup/setup-flow.js +277 -0
  36. package/dist/setup/setup-form-step.d.ts +20 -0
  37. package/dist/setup/setup-form-step.d.ts.map +1 -0
  38. package/dist/setup/setup-form-step.js +173 -0
  39. package/dist/setup/step-status-badge.d.ts +12 -0
  40. package/dist/setup/step-status-badge.d.ts.map +1 -0
  41. package/dist/setup/step-status-badge.js +21 -0
  42. package/dist/setup/tone.d.ts +8 -0
  43. package/dist/setup/tone.d.ts.map +1 -0
  44. package/dist/setup/tone.js +33 -0
  45. package/dist/setup/types.d.ts +130 -0
  46. package/dist/setup/types.d.ts.map +1 -0
  47. package/dist/setup/types.js +1 -0
  48. package/package.json +9 -5
  49. package/src/__tests__/addon-config-surface.test.tsx +260 -0
  50. package/src/__tests__/connector-blocks.test.tsx +302 -0
  51. package/src/__tests__/setup-components.test.tsx +147 -0
  52. package/src/__tests__/setup-flow-model.test.ts +117 -0
  53. package/src/__tests__/setup-flow.test.tsx +424 -0
  54. package/src/index.ts +29 -0
  55. package/src/setup/addon-config-surface.tsx +1426 -0
  56. package/src/setup/connector-blocks-model.ts +163 -0
  57. package/src/setup/connector-blocks.tsx +341 -0
  58. package/src/setup/connector-form-model.ts +115 -0
  59. package/src/setup/flow-model.ts +156 -0
  60. package/src/setup/health-card.tsx +131 -0
  61. package/src/setup/index.ts +35 -0
  62. package/src/setup/messages.ts +334 -0
  63. package/src/setup/records-table.tsx +186 -0
  64. package/src/setup/setup-flow.tsx +562 -0
  65. package/src/setup/setup-form-step.tsx +342 -0
  66. package/src/setup/step-status-badge.tsx +47 -0
  67. package/src/setup/tone.ts +44 -0
  68. package/src/setup/types.ts +147 -0
@@ -0,0 +1,163 @@
1
+ // Pure model of the connector setup blocks (kernel
2
+ // `connectors[].form_layout.sections[].blocks`, manifest/v3/connector_blocks.go)
3
+ // and of the wizard built from a connector form_layout. No React here: the
4
+ // components and the tests share these helpers.
5
+ import type { StepStatus } from './types'
6
+
7
+ export type ConnectorBlockKind = 'webhook_url' | 'instructions' | 'action'
8
+
9
+ export interface ConnectorBlockLink {
10
+ label: string
11
+ url: string
12
+ }
13
+
14
+ /** One non-input element of a connector setup step, as the host serves it. */
15
+ export interface ConnectorFormBlock {
16
+ key: string
17
+ kind: ConnectorBlockKind | string
18
+ title?: string
19
+ description?: string
20
+ /** kind=webhook_url: webhooks[].key (the host fills `value`). */
21
+ webhook?: string
22
+ links?: ConnectorBlockLink[]
23
+ /** kind=action: wasm export the host runs. */
24
+ export?: string
25
+ /** kind=action: button text (literal or i18n key). */
26
+ label?: string
27
+ /** Host-computed value (kind=webhook_url: the org's absolute URL). */
28
+ value?: string
29
+ }
30
+
31
+ export type BlockDetailKind = 'text' | 'id' | 'url'
32
+
33
+ export interface BlockResultDetail {
34
+ key?: string
35
+ label?: string
36
+ value: string
37
+ kind?: BlockDetailKind | string
38
+ }
39
+
40
+ /** Normalized outcome of an action block run. */
41
+ export interface BlockResult {
42
+ status: StepStatus
43
+ message: string
44
+ details: BlockResultDetail[]
45
+ }
46
+
47
+ const STATUSES: StepStatus[] = ['pending', 'running', 'ok', 'warn', 'error', 'blocked']
48
+
49
+ /** Only absolute https URLs are ever turned into links. */
50
+ export function safeHttpsUrl(raw: unknown): string | null {
51
+ if (typeof raw !== 'string') return null
52
+ try {
53
+ const u = new URL(raw)
54
+ if (u.protocol !== 'https:' || !u.host || u.username || u.password) return null
55
+ return u.toString()
56
+ } catch {
57
+ return null
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Reads what an action export (or a connector test_export) answered. Accepts
63
+ * the kernel envelope `{success, data, error}` or a bare `data`. Never invents
64
+ * success: anything without an explicit ok/ok-status is an error.
65
+ */
66
+ export function normalizeBlockResult(raw: unknown, fallbackError = ''): BlockResult {
67
+ const env = (raw ?? {}) as Record<string, any>
68
+ const hasEnvelope = 'success' in env || 'data' in env || 'error' in env
69
+ if (hasEnvelope && env.success === false) {
70
+ const msg = env.error?.message ?? env.message ?? fallbackError
71
+ return { status: 'error', message: String(msg ?? ''), details: [] }
72
+ }
73
+ const data = ((hasEnvelope ? env.data : env) ?? {}) as Record<string, any>
74
+ let status: StepStatus
75
+ if (typeof data.status === 'string' && (STATUSES as string[]).includes(data.status)) {
76
+ status = data.status as StepStatus
77
+ } else {
78
+ status = data.ok === true ? 'ok' : 'error'
79
+ }
80
+ // An explicit ok:false wins over a status that claims success.
81
+ if (data.ok === false && (status === 'ok' || status === 'warn')) status = 'error'
82
+ const details: BlockResultDetail[] = Array.isArray(data.details)
83
+ ? data.details
84
+ .filter((d: any) => d && (typeof d.value === 'string' || typeof d.value === 'number'))
85
+ .slice(0, 12)
86
+ .map((d: any) => ({
87
+ key: typeof d.key === 'string' ? d.key : undefined,
88
+ label: typeof d.label === 'string' ? d.label : undefined,
89
+ value: String(d.value),
90
+ kind: d.kind === 'id' || d.kind === 'url' ? d.kind : 'text',
91
+ }))
92
+ : []
93
+ const message = typeof data.message === 'string' && data.message ? data.message : status === 'error' ? fallbackError : ''
94
+ return { status, message, details }
95
+ }
96
+
97
+ /** Message of a failed HTTP call (axios-like error), or the fallback. */
98
+ export function errorMessage(err: unknown, fallback: string): string {
99
+ const e = err as { response?: { data?: { message?: string; error?: { message?: string } } }; message?: string }
100
+ return e?.response?.data?.message || e?.response?.data?.error?.message || fallback
101
+ }
102
+
103
+ export interface WizardSectionInput {
104
+ key: string
105
+ title?: string
106
+ description?: string
107
+ blocks?: ConnectorFormBlock[]
108
+ }
109
+
110
+ export interface WizardStep {
111
+ key: string
112
+ title?: string
113
+ description?: string
114
+ kind: 'creds' | 'settings'
115
+ blocks: ConnectorFormBlock[]
116
+ }
117
+
118
+ /**
119
+ * Wizard steps of a connector form_layout: every section that has fields OR
120
+ * blocks (a step that only shows the webhook URL and a test is a real step),
121
+ * plus a final "Ajustes" step when the addon ships settings.
122
+ */
123
+ export function buildWizardSteps(
124
+ sections: WizardSectionInput[],
125
+ fieldSections: (string | undefined)[],
126
+ hasSettings: boolean,
127
+ settingsTitle = 'installed_addons.section_settings',
128
+ ): WizardStep[] {
129
+ const withFields = new Set(fieldSections.filter(Boolean))
130
+ const steps: WizardStep[] = sections
131
+ .filter((s) => withFields.has(s.key) || (s.blocks?.length ?? 0) > 0)
132
+ .map((s) => ({ key: s.key, title: s.title, description: s.description, kind: 'creds', blocks: s.blocks ?? [] }))
133
+ if (hasSettings) steps.push({ key: '__settings', title: settingsTitle, kind: 'settings', blocks: [] })
134
+ return steps
135
+ }
136
+
137
+ /** Whether an explicit action block already runs the connector's test_export. */
138
+ export function hasExplicitTest(sections: WizardSectionInput[], testExport?: string): boolean {
139
+ if (!testExport) return false
140
+ return sections.some((s) => (s.blocks ?? []).some((b) => b.kind === 'action' && b.export === testExport))
141
+ }
142
+
143
+ /**
144
+ * Status of a wizard step for the stepper: an error (failed field or action)
145
+ * wins; then a finished verification; then "visited".
146
+ */
147
+ export function stepStatus(opts: {
148
+ index: number
149
+ current: number
150
+ fieldKeys: string[]
151
+ fieldErrors: Record<string, string>
152
+ blockKeys: string[]
153
+ results: Record<string, BlockResult | undefined>
154
+ }): StepStatus {
155
+ const { index, current, fieldKeys, fieldErrors, blockKeys, results } = opts
156
+ if (fieldKeys.some((k) => !!fieldErrors[k])) return 'error'
157
+ const rs = blockKeys.map((k) => results[k]).filter(Boolean) as BlockResult[]
158
+ if (rs.some((r) => r.status === 'error' || r.status === 'blocked')) return 'error'
159
+ if (rs.some((r) => r.status === 'warn')) return 'warn'
160
+ if (rs.length > 0 && rs.every((r) => r.status === 'ok')) return 'ok'
161
+ if (index < current) return 'ok'
162
+ return 'pending'
163
+ }
@@ -0,0 +1,341 @@
1
+ // Connector setup blocks: what a step of the "Configurar <addon>" wizard shows
2
+ // besides inputs. Declared by the addon manifest (kernel
3
+ // connectors[].form_layout.sections[].blocks), computed / run by the host, and
4
+ // rendered here the same for every addon:
5
+ // • webhook_url — the org's webhook URL, read-only, with Copy + links
6
+ // • instructions — help text (expandable) + https links to the provider
7
+ // • action — a verification button with a live, structured result
8
+ // Plus the small building blocks the wizard reuses: HelpText (long help never
9
+ // gets cut: it expands) and CopyValue.
10
+ import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from 'react'
11
+ import { useTranslation } from 'react-i18next'
12
+ import { Check, Copy, ExternalLink, Loader2, Play, RotateCcw } from 'lucide-react'
13
+ import { Button } from '@asteby/metacore-ui/primitives'
14
+ import { cn } from '@asteby/metacore-ui/lib'
15
+ import { useSetupT } from './messages'
16
+ import { copyText } from './records-table'
17
+ import { StepStatusBadge } from './step-status-badge'
18
+ import { STEP_TONE, TONE_BADGE } from './tone'
19
+ import { textOrFallback } from './connector-form-model'
20
+ import { safeHttpsUrl, type BlockResult, type ConnectorFormBlock } from './connector-blocks-model'
21
+
22
+ /** Resolves an addon i18n key (or literal); never paints a raw dotted key. */
23
+ function useAddonText() {
24
+ const { t } = useTranslation()
25
+ return useCallback(
26
+ (key: string | undefined, fallback = '') => {
27
+ if (!key) return fallback
28
+ const out = t(key, { defaultValue: '' }) as string
29
+ const resolved = textOrFallback(out, key, '')
30
+ if (resolved) return resolved
31
+ // A literal sentence (has spaces, no dots-only shape) is shown as is.
32
+ return /\s/.test(key) || !key.includes('.') ? key : fallback
33
+ },
34
+ [t],
35
+ )
36
+ }
37
+
38
+ // ─── HelpText ────────────────────────────────────────────────────────────────
39
+ /** Long help is clamped to 3 lines with a "Ver más" toggle: never cut for good. */
40
+ export function HelpText({
41
+ text,
42
+ id,
43
+ className,
44
+ clampAt = 160,
45
+ }: {
46
+ text: string
47
+ id?: string
48
+ className?: string
49
+ /** Characters above which the text starts collapsed. */
50
+ clampAt?: number
51
+ }) {
52
+ const st = useSetupT()
53
+ const [open, setOpen] = useState(false)
54
+ const autoId = useId()
55
+ const bodyId = id ?? `${autoId}-help`
56
+ if (!text) return null
57
+ const long = text.length > clampAt
58
+ return (
59
+ <div className={cn('flex flex-col items-start gap-0.5', className)}>
60
+ <p
61
+ id={bodyId}
62
+ className={cn(
63
+ 'text-xs leading-relaxed whitespace-pre-line break-words text-muted-foreground',
64
+ long && !open && 'line-clamp-3',
65
+ )}
66
+ >
67
+ {text}
68
+ </p>
69
+ {long ? (
70
+ <button
71
+ type='button'
72
+ className='inline-flex min-h-11 items-center text-xs font-medium text-primary underline-offset-2 hover:underline focus-visible:outline-2 focus-visible:outline-ring sm:min-h-6'
73
+ aria-expanded={open}
74
+ aria-controls={bodyId}
75
+ onClick={() => setOpen((v) => !v)}
76
+ >
77
+ {open ? st('blocks.less') : st('blocks.more')}
78
+ </button>
79
+ ) : null}
80
+ </div>
81
+ )
82
+ }
83
+
84
+ // ─── CopyValue ───────────────────────────────────────────────────────────────
85
+ /** A read-only value (wraps, never truncates) with a 44px Copy button. */
86
+ export function CopyValue({ value, label, mono = true }: { value: string; label: string; mono?: boolean }) {
87
+ const st = useSetupT()
88
+ const [state, setState] = useState<'idle' | 'copied' | 'failed'>('idle')
89
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
90
+ useEffect(() => () => clearTimeout(timer.current), [])
91
+ const onCopy = async () => {
92
+ const ok = await copyText(value)
93
+ setState(ok ? 'copied' : 'failed')
94
+ clearTimeout(timer.current)
95
+ timer.current = setTimeout(() => setState('idle'), 2500)
96
+ }
97
+ return (
98
+ <div className='flex flex-col gap-1'>
99
+ <div className='flex items-stretch gap-2'>
100
+ <output
101
+ aria-label={label}
102
+ className={cn(
103
+ 'min-w-0 flex-1 rounded-md border bg-muted/50 px-3 py-2.5 text-sm break-all select-all',
104
+ mono && 'font-mono text-[13px]',
105
+ )}
106
+ >
107
+ {value}
108
+ </output>
109
+ <Button
110
+ type='button'
111
+ variant='outline'
112
+ className='h-auto min-h-11 shrink-0 gap-1.5 px-3'
113
+ onClick={onCopy}
114
+ aria-label={st('blocks.copy_label', { what: label })}
115
+ >
116
+ {state === 'copied' ? <Check aria-hidden='true' className='h-4 w-4' /> : <Copy aria-hidden='true' className='h-4 w-4' />}
117
+ <span className='hidden sm:inline'>{state === 'copied' ? st('records.copied') : st('records.copy')}</span>
118
+ </Button>
119
+ </div>
120
+ <p className='sr-only' role='status' aria-live='polite'>
121
+ {state === 'copied' ? st('records.copied') : state === 'failed' ? st('records.copy_failed') : ''}
122
+ </p>
123
+ {state === 'failed' ? <p className='text-xs text-destructive'>{st('records.copy_failed')}</p> : null}
124
+ </div>
125
+ )
126
+ }
127
+
128
+ function BlockLinks({ links }: { links?: ConnectorFormBlock['links'] }) {
129
+ const tx = useAddonText()
130
+ const safe = (links ?? []).map((l) => ({ ...l, href: safeHttpsUrl(l.url) })).filter((l) => !!l.href)
131
+ if (safe.length === 0) return null
132
+ return (
133
+ <ul className='flex flex-wrap gap-x-4 gap-y-1'>
134
+ {safe.map((l) => (
135
+ <li key={l.href!}>
136
+ <a
137
+ href={l.href!}
138
+ target='_blank'
139
+ rel='noopener noreferrer'
140
+ className='inline-flex min-h-11 items-center gap-1.5 text-sm font-medium text-primary underline-offset-2 hover:underline sm:min-h-8'
141
+ >
142
+ <ExternalLink aria-hidden='true' className='h-3.5 w-3.5' />
143
+ {tx(l.label, l.href!)}
144
+ </a>
145
+ </li>
146
+ ))}
147
+ </ul>
148
+ )
149
+ }
150
+
151
+ function BlockFrame({ title, children, className }: { title?: string; children: ReactNode; className?: string }) {
152
+ return (
153
+ <section className={cn('flex flex-col gap-2 rounded-lg border border-border/70 bg-card p-3', className)}>
154
+ {title ? <h4 className='text-sm font-medium'>{title}</h4> : null}
155
+ {children}
156
+ </section>
157
+ )
158
+ }
159
+
160
+ // ─── webhook_url ─────────────────────────────────────────────────────────────
161
+ export function WebhookUrlBlock({ block }: { block: ConnectorFormBlock }) {
162
+ const st = useSetupT()
163
+ const tx = useAddonText()
164
+ const title = tx(block.title, st('blocks.webhook_title'))
165
+ const value = typeof block.value === 'string' ? block.value.trim() : ''
166
+ return (
167
+ <BlockFrame title={title}>
168
+ {value ? (
169
+ <CopyValue value={value} label={title} />
170
+ ) : (
171
+ <p className='text-sm text-muted-foreground' role='note'>
172
+ {st('blocks.webhook_unavailable')}
173
+ </p>
174
+ )}
175
+ <HelpText text={tx(block.description, st('blocks.webhook_help'))} />
176
+ <BlockLinks links={block.links} />
177
+ </BlockFrame>
178
+ )
179
+ }
180
+
181
+ // ─── instructions ────────────────────────────────────────────────────────────
182
+ export function InstructionsBlock({ block }: { block: ConnectorFormBlock }) {
183
+ const tx = useAddonText()
184
+ return (
185
+ <BlockFrame title={tx(block.title)} className='bg-muted/30'>
186
+ <HelpText text={tx(block.description)} clampAt={240} />
187
+ <BlockLinks links={block.links} />
188
+ </BlockFrame>
189
+ )
190
+ }
191
+
192
+ // ─── action ──────────────────────────────────────────────────────────────────
193
+ export interface ActionBlockProps {
194
+ block: ConnectorFormBlock
195
+ /** Runs the action; resolves to the normalized result (never throws). */
196
+ run: () => Promise<BlockResult>
197
+ result?: BlockResult
198
+ onResult?: (r: BlockResult) => void
199
+ disabled?: boolean
200
+ /** Shown under the button (e.g. "Se guardarán tus cambios antes de probar"). */
201
+ note?: string
202
+ }
203
+
204
+ export function ActionBlock({ block, run, result, onResult, disabled, note }: ActionBlockProps) {
205
+ const st = useSetupT()
206
+ const tx = useAddonText()
207
+ const [busy, setBusy] = useState(false)
208
+ const [local, setLocal] = useState<BlockResult | undefined>(undefined)
209
+ const shown = result ?? local
210
+ const label = tx(block.label, st('blocks.run'))
211
+ const onRun = async () => {
212
+ setBusy(true)
213
+ try {
214
+ const r = await run()
215
+ setLocal(r)
216
+ onResult?.(r)
217
+ } finally {
218
+ setBusy(false)
219
+ }
220
+ }
221
+ const failed = shown && (shown.status === 'error' || shown.status === 'blocked')
222
+ return (
223
+ <BlockFrame title={tx(block.title)}>
224
+ <HelpText text={tx(block.description)} />
225
+ <div className='flex flex-wrap items-center gap-2'>
226
+ <Button
227
+ type='button'
228
+ variant={failed ? 'outline' : 'secondary'}
229
+ className='h-auto min-h-11 gap-2 whitespace-normal text-left'
230
+ onClick={onRun}
231
+ disabled={busy || disabled}
232
+ aria-describedby={note ? `${block.key}-note` : undefined}
233
+ >
234
+ {busy ? (
235
+ <Loader2 aria-hidden='true' className='h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none' />
236
+ ) : shown ? (
237
+ <RotateCcw aria-hidden='true' className='h-4 w-4 shrink-0' />
238
+ ) : (
239
+ <Play aria-hidden='true' className='h-4 w-4 shrink-0' />
240
+ )}
241
+ {busy ? st('blocks.running') : shown ? st('blocks.retry_with', { label }) : label}
242
+ </Button>
243
+ {note ? (
244
+ <span id={`${block.key}-note`} className='text-xs text-muted-foreground'>
245
+ {note}
246
+ </span>
247
+ ) : null}
248
+ </div>
249
+ {/* Live region: always mounted so screen readers announce the outcome. */}
250
+ <div role='status' aria-live='polite' aria-atomic='true' className='empty:hidden'>
251
+ {shown ? <BlockResultView result={shown} /> : null}
252
+ </div>
253
+ </BlockFrame>
254
+ )
255
+ }
256
+
257
+ export function BlockResultView({ result }: { result: BlockResult }) {
258
+ const st = useSetupT()
259
+ const tone = STEP_TONE[result.status] ?? 'neutral'
260
+ return (
261
+ <div className={cn('flex flex-col gap-2 rounded-md border px-3 py-2', TONE_BADGE[tone])} data-result-status={result.status}>
262
+ <div className='flex flex-wrap items-center gap-2'>
263
+ <StepStatusBadge status={result.status} label={st(`blocks.result.${result.status}`)} />
264
+ {result.message ? <span className='text-sm break-words text-foreground'>{result.message}</span> : null}
265
+ </div>
266
+ {result.details.length > 0 ? (
267
+ <dl className='flex flex-col gap-2'>
268
+ {result.details.map((d, i) => {
269
+ const label = d.label || d.key || ''
270
+ const href = d.kind === 'url' ? safeHttpsUrl(d.value) : null
271
+ return (
272
+ <div key={d.key ?? i} className='flex flex-col gap-1'>
273
+ <dt className='text-xs font-medium text-muted-foreground'>{label}</dt>
274
+ <dd className='text-sm text-foreground'>
275
+ {d.kind === 'id' ? (
276
+ <CopyValue value={d.value} label={label || st('blocks.value')} />
277
+ ) : href ? (
278
+ <a
279
+ href={href}
280
+ target='_blank'
281
+ rel='noopener noreferrer'
282
+ className='inline-flex min-h-11 items-center gap-1.5 break-all font-medium text-primary underline-offset-2 hover:underline sm:min-h-8'
283
+ >
284
+ <ExternalLink aria-hidden='true' className='h-3.5 w-3.5 shrink-0' />
285
+ {st('blocks.open_link')}
286
+ </a>
287
+ ) : (
288
+ <span className='break-words'>{d.value}</span>
289
+ )}
290
+ </dd>
291
+ </div>
292
+ )
293
+ })}
294
+ </dl>
295
+ ) : null}
296
+ </div>
297
+ )
298
+ }
299
+
300
+ // ─── Dispatcher ──────────────────────────────────────────────────────────────
301
+ export interface ConnectorBlocksProps {
302
+ blocks: ConnectorFormBlock[]
303
+ /** Runs an action block by key. */
304
+ runAction: (block: ConnectorFormBlock) => Promise<BlockResult>
305
+ results?: Record<string, BlockResult | undefined>
306
+ onResult?: (key: string, r: BlockResult) => void
307
+ /** Disables actions (e.g. the viewer may not run them). */
308
+ actionsDisabled?: boolean
309
+ actionNote?: string
310
+ }
311
+
312
+ /** Renders a step's blocks in declared order; unknown kinds are skipped. */
313
+ export function ConnectorBlocks({ blocks, runAction, results, onResult, actionsDisabled, actionNote }: ConnectorBlocksProps) {
314
+ if (blocks.length === 0) return null
315
+ return (
316
+ <div className='flex flex-col gap-3'>
317
+ {blocks.map((b) => {
318
+ switch (b.kind) {
319
+ case 'webhook_url':
320
+ return <WebhookUrlBlock key={b.key} block={b} />
321
+ case 'instructions':
322
+ return <InstructionsBlock key={b.key} block={b} />
323
+ case 'action':
324
+ return (
325
+ <ActionBlock
326
+ key={b.key}
327
+ block={b}
328
+ run={() => runAction(b)}
329
+ result={results?.[b.key]}
330
+ onResult={(r) => onResult?.(b.key, r)}
331
+ disabled={actionsDisabled}
332
+ note={actionNote}
333
+ />
334
+ )
335
+ default:
336
+ return null
337
+ }
338
+ })}
339
+ </div>
340
+ )
341
+ }
@@ -0,0 +1,115 @@
1
+ // Pure helpers for the connector credentials form (no React, no i18n instance):
2
+ // shape detection of pasted values, save-error parsing and required-field
3
+ // checks. Kept free of any provider name on purpose: the rules look at the
4
+ // SHAPE of a value and at how the form's own fields are declared, so every
5
+ // connector (any addon) benefits and none is special-cased.
6
+
7
+ /** The minimum a credential definition needs for these helpers. */
8
+ export interface CredentialLike {
9
+ key: string
10
+ label?: string
11
+ required?: boolean
12
+ secret?: boolean
13
+ type?: string
14
+ default?: string
15
+ }
16
+
17
+ export type CredentialShape = 'public_key' | 'secret_key'
18
+
19
+ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
20
+ // Public (publishable) keys are short identifiers: "<PREFIX>-<uuid>" or the
21
+ // pk_live_/pk_test_ family. Server-side tokens are longer, numeric/hex blobs
22
+ // or sk_/rk_ prefixed. These are generic conventions, not one provider's.
23
+ const PUBLIC_SHAPES = [new RegExp(`^(?:[A-Z_]+-)?${UUID}$`, 'i'), /^pk_(?:live|test)_[A-Za-z0-9]+$/]
24
+ const SECRET_SHAPES = [/^(?:sk|rk)_(?:live|test)_[A-Za-z0-9]+$/, /^[A-Z_]+-\d{6,}-\d{4,}-[0-9a-f]{16,}-\d+$/i]
25
+
26
+ /** What a pasted value looks like, or null when it is not recognisable. */
27
+ export function credentialShape(raw: string): CredentialShape | null {
28
+ const v = raw.trim()
29
+ if (!v) return null
30
+ if (PUBLIC_SHAPES.some((r) => r.test(v))) return 'public_key'
31
+ if (SECRET_SHAPES.some((r) => r.test(v))) return 'secret_key'
32
+ return null
33
+ }
34
+
35
+ export const isSecretCredential = (f: CredentialLike) => !!f.secret || f.type === 'secret'
36
+
37
+ const looksPublic = (f: CredentialLike) => /public|publishable|client_id/i.test(f.key)
38
+
39
+ export interface ShapeMismatch {
40
+ /** What the value looks like. */
41
+ shape: CredentialShape
42
+ /** The sibling field the value probably belongs to, when the form has one. */
43
+ suggestedKey?: string
44
+ }
45
+
46
+ /**
47
+ * A value pasted in the wrong box: a public key in the secret token field, or
48
+ * a secret in the public-key field. Only a warning (never blocks), and only
49
+ * raised when the form really has a field for what the value looks like.
50
+ */
51
+ export function shapeMismatch(
52
+ field: CredentialLike,
53
+ value: string,
54
+ fields: CredentialLike[],
55
+ ): ShapeMismatch | null {
56
+ const shape = credentialShape(value)
57
+ if (!shape) return null
58
+ const siblings = fields.filter((f) => f.key !== field.key)
59
+ if (shape === 'public_key' && isSecretCredential(field) && !looksPublic(field)) {
60
+ const target = siblings.find(looksPublic)
61
+ return target ? { shape, suggestedKey: target.key } : null
62
+ }
63
+ if (shape === 'secret_key' && looksPublic(field)) {
64
+ const target = siblings.find((f) => isSecretCredential(f) && !looksPublic(f))
65
+ return target ? { shape, suggestedKey: target.key } : null
66
+ }
67
+ return null
68
+ }
69
+
70
+ /** Required fields still empty. A stored secret (connected) counts as filled. */
71
+ export function missingRequired(
72
+ fields: CredentialLike[],
73
+ values: Record<string, string>,
74
+ connected: boolean,
75
+ ): string[] {
76
+ return fields
77
+ .filter((f) => f.required)
78
+ .filter((f) => !(values[f.key] ?? '').trim())
79
+ .filter((f) => !(connected && isSecretCredential(f)))
80
+ .filter((f) => !(f.default != null && f.default !== ''))
81
+ .map((f) => f.key)
82
+ }
83
+
84
+ export interface SaveError {
85
+ /** The complete server message, never shortened. */
86
+ message: string
87
+ /** Fields the server (or the client check) says need attention. */
88
+ fieldKeys: string[]
89
+ }
90
+
91
+ /** Reads the kernel/ops error envelope: {message, errors: {field: [{code}]}}. */
92
+ export function parseSaveError(err: unknown, fallback: string): SaveError {
93
+ const data = (err as { response?: { data?: { message?: unknown; errors?: unknown } } })?.response
94
+ ?.data
95
+ const message =
96
+ typeof data?.message === 'string' && data.message.trim() ? data.message.trim() : fallback
97
+ const errors = data?.errors
98
+ const fieldKeys =
99
+ errors && typeof errors === 'object' && !Array.isArray(errors) ? Object.keys(errors) : []
100
+ return { message, fieldKeys }
101
+ }
102
+
103
+ /** Never show a raw dotted key: fall back to `fallback` when the text is the key. */
104
+ export function textOrFallback(text: string | undefined, key: string, fallback: string): string {
105
+ if (!text || text === key) return fallback
106
+ return text
107
+ }
108
+
109
+ /** Cheap content hash so a re-published bundle with the same key count re-merges. */
110
+ export function bundleSignature(labels: Record<string, unknown>): string {
111
+ let h = 5381
112
+ const s = JSON.stringify(labels)
113
+ for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0
114
+ return `${Object.keys(labels).length}:${(h >>> 0).toString(36)}`
115
+ }