@asteby/metacore-runtime-react 23.9.3 → 23.11.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 (36) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +44 -0
  3. package/dist/action-modal-dispatcher.d.ts.map +1 -1
  4. package/dist/action-modal-dispatcher.js +122 -0
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +1 -0
  8. package/dist/license/index.d.ts +5 -0
  9. package/dist/license/index.d.ts.map +1 -0
  10. package/dist/license/index.js +4 -0
  11. package/dist/license/license-expiry-banner.d.ts +16 -0
  12. package/dist/license/license-expiry-banner.d.ts.map +1 -0
  13. package/dist/license/license-expiry-banner.js +85 -0
  14. package/dist/license/license-gate.d.ts +47 -0
  15. package/dist/license/license-gate.d.ts.map +1 -0
  16. package/dist/license/license-gate.js +111 -0
  17. package/dist/license/license-status-badge.d.ts +7 -0
  18. package/dist/license/license-status-badge.d.ts.map +1 -0
  19. package/dist/license/license-status-badge.js +57 -0
  20. package/dist/license/types.d.ts +63 -0
  21. package/dist/license/types.d.ts.map +1 -0
  22. package/dist/license/types.js +45 -0
  23. package/dist/types.d.ts +8 -0
  24. package/dist/types.d.ts.map +1 -1
  25. package/package.json +1 -1
  26. package/src/__tests__/license-gate.test.tsx +282 -0
  27. package/src/__tests__/wizard-action-modal.test.tsx +121 -0
  28. package/src/action-modal-dispatcher.tsx +233 -0
  29. package/src/index.ts +15 -0
  30. package/src/license/index.ts +21 -0
  31. package/src/license/license-expiry-banner.tsx +151 -0
  32. package/src/license/license-gate.tsx +305 -0
  33. package/src/license/license-status-badge.tsx +93 -0
  34. package/src/license/types.ts +90 -0
  35. package/src/types.ts +9 -0
  36. package/LICENSE +0 -201
@@ -0,0 +1,305 @@
1
+ /**
2
+ * <LicenseGate> — el primitivo del blindaje. Un host lo monta en UNA línea
3
+ * envolviendo su app autenticada:
4
+ *
5
+ * <LicenseGate state={state} onActivate={activate}>
6
+ * <AppShell />
7
+ * </LicenseGate>
8
+ *
9
+ * Comportamiento según el estado (resuelto por el backend del host):
10
+ * - Sin enforcement, o estado operable (valid/stale/grace) → renderiza children.
11
+ * stale/grace además montan el <LicenseExpiryBanner> degradado por encima.
12
+ * - enforcement && missing/invalid/expired → modal BLOQUEANTE full-screen,
13
+ * no descartable, con el formulario de activación. Al activar con éxito el
14
+ * host refresca el estado y el gate se abre sin recargar.
15
+ *
16
+ * Es branding-aware si el host pasa `branding` (logo/nombre desde el
17
+ * PlatformConfig del SDK); si no, cae a un encabezado neutro.
18
+ *
19
+ * INDEPENDIENTE del kernel: no importa su cliente ni fija su versión. Solo
20
+ * consume `LicenseState` y una promesa `onActivate`.
21
+ */
22
+ import { useState, type ReactNode } from 'react'
23
+ import { useTranslation } from 'react-i18next'
24
+ import { ShieldAlert, Clock, Loader2 } from 'lucide-react'
25
+ import { Button, Input } from '@asteby/metacore-ui'
26
+ import {
27
+ isLicenseBlocking,
28
+ isTrialExpired,
29
+ type LicenseState,
30
+ type LicenseBranding,
31
+ } from './types'
32
+ import { LicenseStatusBadge } from './license-status-badge'
33
+ import { LicenseExpiryBanner } from './license-expiry-banner'
34
+
35
+ function cx(...parts: Array<string | false | undefined>): string {
36
+ return parts.filter(Boolean).join(' ')
37
+ }
38
+
39
+ export interface LicenseGateProps {
40
+ /** Estado actual, resuelto por el backend del host. `undefined` mientras
41
+ * carga → fail-open (renderiza children, nunca destella el candado). */
42
+ state: LicenseState | undefined
43
+ /** Activa una licencia con el código/token pegado. Resuelve → el host
44
+ * refresca `state` y el gate se abre. Rechaza con un Error cuyo `message`
45
+ * se muestra al usuario. */
46
+ onActivate: (code: string) => Promise<void>
47
+ children: ReactNode
48
+ /** Branding opcional (logo/nombre) para el encabezado del modal. */
49
+ branding?: LicenseBranding
50
+ /** Acción "Gestionar licencia" del banner degradado (opcional). */
51
+ onManage?: () => void
52
+ /** Si el usuario actual puede activar la licencia (p. ej. Platform Root /
53
+ * superadmin). Default true — backward-compatible. Cuando es false, el modal
54
+ * bloqueante se muestra SIN el formulario de activación y en su lugar
55
+ * aparece `readOnlyMessage`. */
56
+ canActivate?: boolean
57
+ /** Mensaje mostrado en el modal bloqueante cuando `canActivate` es false. */
58
+ readOnlyMessage?: string
59
+ className?: string
60
+ }
61
+
62
+ export function LicenseGate({
63
+ state,
64
+ onActivate,
65
+ children,
66
+ branding,
67
+ onManage,
68
+ canActivate = true,
69
+ readOnlyMessage,
70
+ className,
71
+ }: LicenseGateProps) {
72
+ const blocking = isLicenseBlocking(state)
73
+
74
+ return (
75
+ <>
76
+ {/* stale/grace/upcoming degradan con banner; el propio banner
77
+ decide si mostrarse. Bloqueado → no hace falta, el modal manda. */}
78
+ {!blocking && (
79
+ <LicenseExpiryBanner state={state} onManage={onManage} />
80
+ )}
81
+ {children}
82
+ {blocking && state && (
83
+ <LicenseGateModal
84
+ state={state}
85
+ onActivate={onActivate}
86
+ branding={branding}
87
+ canActivate={canActivate}
88
+ readOnlyMessage={readOnlyMessage}
89
+ className={className}
90
+ />
91
+ )}
92
+ </>
93
+ )
94
+ }
95
+
96
+ interface LicenseGateModalProps {
97
+ state: LicenseState
98
+ onActivate: (code: string) => Promise<void>
99
+ branding?: LicenseBranding
100
+ canActivate: boolean
101
+ readOnlyMessage?: string
102
+ className?: string
103
+ }
104
+
105
+ function LicenseGateModal({
106
+ state,
107
+ onActivate,
108
+ branding,
109
+ canActivate,
110
+ readOnlyMessage,
111
+ className,
112
+ }: LicenseGateModalProps) {
113
+ const { t } = useTranslation()
114
+ const [code, setCode] = useState('')
115
+ const [submitting, setSubmitting] = useState(false)
116
+ const [error, setError] = useState<string | null>(null)
117
+
118
+ const trialExpired = isTrialExpired(state)
119
+
120
+ const title = trialExpired
121
+ ? t('license.gate.trial_title', {
122
+ defaultValue: 'Tu prueba gratuita terminó',
123
+ })
124
+ : t('license.gate.title', { defaultValue: 'Activa tu licencia' })
125
+
126
+ const description = trialExpired
127
+ ? t('license.gate.trial_description', {
128
+ defaultValue:
129
+ 'Tu prueba gratuita terminó. Activa una licencia para continuar. Pega tu clave (lic_…) o el token firmado que te entregaron.',
130
+ })
131
+ : state.status === 'expired'
132
+ ? t('license.gate.expired_description', {
133
+ defaultValue:
134
+ 'Tu licencia venció y el periodo de gracia terminó. Activa una licencia vigente para seguir operando. Pega tu clave (lic_…) o el token firmado.',
135
+ })
136
+ : state.status === 'invalid'
137
+ ? t('license.gate.invalid_description', {
138
+ defaultValue:
139
+ 'La licencia de esta instancia no es válida. Pega una clave (lic_…) o el token firmado que te entregó tu proveedor para reactivarla.',
140
+ })
141
+ : t('license.gate.missing_description', {
142
+ defaultValue:
143
+ 'Esta instancia necesita una licencia activa para operar. Pega tu clave (lic_…) o el token firmado para activarla.',
144
+ })
145
+
146
+ const canSubmit = code.trim().length > 0 && !submitting
147
+
148
+ const submit = async () => {
149
+ if (!canSubmit) return
150
+ setSubmitting(true)
151
+ setError(null)
152
+ try {
153
+ await onActivate(code.trim())
154
+ // Éxito → el host refresca `state`; el gate se re-renderiza y este
155
+ // modal se desmonta solo. No recargamos.
156
+ } catch (e) {
157
+ const message =
158
+ e instanceof Error && e.message
159
+ ? e.message
160
+ : t('license.gate.activate_error', {
161
+ defaultValue: 'No se pudo activar la licencia.',
162
+ })
163
+ setError(message)
164
+ setSubmitting(false)
165
+ }
166
+ }
167
+
168
+ return (
169
+ <div
170
+ role="dialog"
171
+ aria-modal="true"
172
+ aria-labelledby="license-gate-title"
173
+ data-license-status={state.status}
174
+ className={cx(
175
+ 'fixed inset-0 z-[100] flex items-center justify-center bg-background/90 p-4 backdrop-blur-sm',
176
+ className,
177
+ )}
178
+ >
179
+ <div className="w-full max-w-lg overflow-hidden rounded-2xl border bg-card text-card-foreground shadow-2xl">
180
+ <div className="flex flex-col gap-4 p-6">
181
+ <div className="flex items-start gap-3">
182
+ {branding?.logo ? (
183
+ <img
184
+ src={branding.logo}
185
+ alt={branding.name ?? ''}
186
+ className="h-10 w-10 shrink-0 rounded-xl object-contain"
187
+ />
188
+ ) : (
189
+ <div
190
+ className={cx(
191
+ 'flex h-10 w-10 shrink-0 items-center justify-center rounded-xl',
192
+ trialExpired
193
+ ? 'bg-primary/10 text-primary'
194
+ : 'bg-destructive/10 text-destructive',
195
+ )}
196
+ >
197
+ {trialExpired ? (
198
+ <Clock className="h-5 w-5" aria-hidden />
199
+ ) : (
200
+ <ShieldAlert className="h-5 w-5" aria-hidden />
201
+ )}
202
+ </div>
203
+ )}
204
+ <div className="flex min-w-0 flex-col gap-1">
205
+ <h2
206
+ id="license-gate-title"
207
+ className="text-lg leading-tight font-semibold"
208
+ >
209
+ {title}
210
+ </h2>
211
+ <div className="flex flex-wrap items-center gap-2">
212
+ <LicenseStatusBadge status={state.status} />
213
+ <span className="text-muted-foreground text-xs">
214
+ {branding?.name
215
+ ? branding.name
216
+ : t('license.gate.instance', {
217
+ defaultValue: 'Esta instancia',
218
+ })}
219
+ </span>
220
+ </div>
221
+ </div>
222
+ </div>
223
+
224
+ <p className="text-muted-foreground text-sm">{description}</p>
225
+
226
+ {state.reason && (
227
+ <p className="bg-muted/50 text-muted-foreground rounded-md px-3 py-2 text-xs">
228
+ {state.reason}
229
+ </p>
230
+ )}
231
+
232
+ {!canActivate ? (
233
+ <p
234
+ role="note"
235
+ className="border-border bg-muted/40 text-muted-foreground rounded-md border px-3 py-3 text-sm"
236
+ >
237
+ {readOnlyMessage ??
238
+ t('license.gate.read_only', {
239
+ defaultValue:
240
+ 'Contacta al administrador de la plataforma para activar la licencia.',
241
+ })}
242
+ </p>
243
+ ) : (
244
+ <form
245
+ className="flex flex-col gap-2"
246
+ onSubmit={(e) => {
247
+ e.preventDefault()
248
+ void submit()
249
+ }}
250
+ >
251
+ <label
252
+ htmlFor="license-gate-code"
253
+ className="text-sm font-medium"
254
+ >
255
+ {t('license.gate.code_label', {
256
+ defaultValue: 'Clave o token de licencia',
257
+ })}
258
+ </label>
259
+ <Input
260
+ id="license-gate-code"
261
+ autoFocus
262
+ autoComplete="off"
263
+ spellCheck={false}
264
+ placeholder={t('license.gate.code_placeholder', {
265
+ defaultValue: 'lic_… o pega el token firmado',
266
+ })}
267
+ value={code}
268
+ disabled={submitting}
269
+ aria-invalid={error ? true : undefined}
270
+ onChange={(e) => {
271
+ setCode(e.target.value)
272
+ if (error) setError(null)
273
+ }}
274
+ />
275
+ {error && (
276
+ <p role="alert" className="text-destructive text-sm">
277
+ {error}
278
+ </p>
279
+ )}
280
+ <Button
281
+ type="submit"
282
+ className="mt-1 w-full"
283
+ disabled={!canSubmit}
284
+ >
285
+ {submitting && (
286
+ <Loader2
287
+ className="h-4 w-4 animate-spin"
288
+ aria-hidden
289
+ />
290
+ )}
291
+ {submitting
292
+ ? t('license.gate.activating', {
293
+ defaultValue: 'Activando…',
294
+ })
295
+ : t('license.gate.activate', {
296
+ defaultValue: 'Activar licencia',
297
+ })}
298
+ </Button>
299
+ </form>
300
+ )}
301
+ </div>
302
+ </div>
303
+ </div>
304
+ )
305
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Insignia de estado de licencia — un chip que traduce el `LicenseStatus` a
3
+ * color + etiqueta legible. Reutilizable suelto (p. ej. en Ajustes de licencia)
4
+ * o embebido en el encabezado del <LicenseGate>.
5
+ */
6
+ import { useTranslation } from 'react-i18next'
7
+ import {
8
+ ShieldCheck,
9
+ ShieldAlert,
10
+ ShieldQuestion,
11
+ Clock,
12
+ CloudOff,
13
+ } from 'lucide-react'
14
+ import { Badge } from '@asteby/metacore-ui'
15
+ import type { LicenseStatus } from './types'
16
+
17
+ type BadgeVariant = 'default' | 'secondary' | 'destructive' | 'outline'
18
+
19
+ interface StatusMeta {
20
+ variant: BadgeVariant
21
+ Icon: typeof ShieldCheck
22
+ key: string
23
+ defaultValue: string
24
+ /** Tinte amarillo para posturas degradadas (grace/stale) que `variant` no
25
+ * cubre — el sistema de badges no tiene "warning". */
26
+ warn?: boolean
27
+ }
28
+
29
+ const STATUS_META: Record<LicenseStatus, StatusMeta> = {
30
+ valid: {
31
+ variant: 'default',
32
+ Icon: ShieldCheck,
33
+ key: 'license.status.valid',
34
+ defaultValue: 'Activa',
35
+ },
36
+ stale: {
37
+ variant: 'outline',
38
+ Icon: CloudOff,
39
+ key: 'license.status.stale',
40
+ defaultValue: 'Sin verificar',
41
+ warn: true,
42
+ },
43
+ grace: {
44
+ variant: 'outline',
45
+ Icon: Clock,
46
+ key: 'license.status.grace',
47
+ defaultValue: 'En gracia',
48
+ warn: true,
49
+ },
50
+ expired: {
51
+ variant: 'destructive',
52
+ Icon: ShieldAlert,
53
+ key: 'license.status.expired',
54
+ defaultValue: 'Vencida',
55
+ },
56
+ missing: {
57
+ variant: 'secondary',
58
+ Icon: ShieldQuestion,
59
+ key: 'license.status.missing',
60
+ defaultValue: 'Sin licencia',
61
+ },
62
+ invalid: {
63
+ variant: 'destructive',
64
+ Icon: ShieldAlert,
65
+ key: 'license.status.invalid',
66
+ defaultValue: 'Inválida',
67
+ },
68
+ }
69
+
70
+ export interface LicenseStatusBadgeProps {
71
+ status: LicenseStatus
72
+ className?: string
73
+ }
74
+
75
+ export function LicenseStatusBadge({ status, className }: LicenseStatusBadgeProps) {
76
+ const { t } = useTranslation()
77
+ const meta = STATUS_META[status] ?? STATUS_META.missing
78
+ const { Icon } = meta
79
+
80
+ return (
81
+ <Badge
82
+ variant={meta.variant}
83
+ className={
84
+ (meta.warn
85
+ ? 'border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400 '
86
+ : '') + (className ?? '')
87
+ }
88
+ >
89
+ <Icon aria-hidden />
90
+ {t(meta.key, { defaultValue: meta.defaultValue })}
91
+ </Badge>
92
+ )
93
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Licencia de instancia — el contrato de estado que el backend del host (ops
3
+ * vía kernel `LicenseService`) expone y que este módulo pinta. El SDK NO habla
4
+ * con el kernel ni impone su versión: el host resuelve el `LicenseState` con su
5
+ * propio transporte y se lo pasa a <LicenseGate>. Así el gate es un primitivo
6
+ * reutilizable e INDEPENDIENTE del release del kernel.
7
+ *
8
+ * División de responsabilidades del blindaje:
9
+ * - kernel → enforcement (qué está permitido; firma/verifica el estado).
10
+ * - SDK → UX (este módulo: gate, banner, badge).
11
+ * - hub → emisión (mintea el token Ed25519).
12
+ * - hosts → wiring (resuelven el estado y montan <LicenseGate> en 1 línea).
13
+ */
14
+
15
+ /** El estado operativo de la licencia, tal como lo deriva el backend. */
16
+ export type LicenseStatus =
17
+ | 'valid'
18
+ | 'stale'
19
+ | 'grace'
20
+ | 'expired'
21
+ | 'missing'
22
+ | 'invalid'
23
+
24
+ export interface LicenseState {
25
+ /** Licensing activo en esta instancia (LICENSING_ENFORCE). Si es false el
26
+ * gate es transparente: nunca bloquea ni degrada. */
27
+ enforced: boolean
28
+ configured: boolean
29
+ valid: boolean
30
+ status: LicenseStatus
31
+ reason?: string
32
+ org_id?: string
33
+ plan?: string
34
+ preset?: string
35
+ entitlements: string[]
36
+ wildcard: boolean
37
+ /** Lease: la instancia falló su check-in obligatorio con el hub. */
38
+ stale: boolean
39
+ max_offline_hours?: number
40
+ issued_at?: string
41
+ expires_at?: string
42
+ in_grace: boolean
43
+ grace_until?: string
44
+ days_remaining: number
45
+ last_checked_at?: string
46
+ }
47
+
48
+ /** La licencia es OPERABLE cuando permite operar (aunque sea degradada):
49
+ * valid, la postura `stale` del lease, o dentro de la ventana de gracia.
50
+ * missing/invalid/expired no son operables. Sin enforcement → siempre operable.
51
+ * Espeja `State.Operable()` del backend. */
52
+ export function isLicenseOperable(state: LicenseState | undefined): boolean {
53
+ if (!state || !state.enforced) return true
54
+ return state.valid || state.in_grace
55
+ }
56
+
57
+ /** La instancia debe BLOQUEARSE tras el modal de activación cuando hay
58
+ * enforcement y la licencia es missing/invalid/expired (pasada la gracia).
59
+ * grace/stale degradan con banner en vez de bloquear. Espeja `State.Blocking()`.
60
+ * Mientras el estado aún carga (undefined) NO bloquea: fail-open en la UI para
61
+ * que un check lento/fallido nunca destelle un candado sobre la app. */
62
+ export function isLicenseBlocking(state: LicenseState | undefined): boolean {
63
+ if (!state || !state.enforced) return false
64
+ return !isLicenseOperable(state)
65
+ }
66
+
67
+ /** Un preset/vertical está habilitado si la licencia otorga wildcard o lo lista
68
+ * explícitamente. Sin enforcement → todo habilitado. */
69
+ export function isPresetEntitled(
70
+ state: LicenseState | undefined,
71
+ presetKey: string,
72
+ ): boolean {
73
+ if (!state || !state.enforced) return true
74
+ if (state.wildcard) return true
75
+ return state.entitlements?.includes(presetKey) ?? false
76
+ }
77
+
78
+ /** Marca trial vencido: el copy del gate cambia a "tu prueba terminó". */
79
+ export function isTrialExpired(state: LicenseState | undefined): boolean {
80
+ return !!state && state.plan === 'trial' && state.status === 'expired'
81
+ }
82
+
83
+ /** Branding opcional para teñir el gate/banner. El host lo pasa desde su
84
+ * PlatformConfig del SDK (o cualquier fuente); sin él, fallback neutro. */
85
+ export interface LicenseBranding {
86
+ /** Nombre de la plataforma/tenant, para el encabezado del gate. */
87
+ name?: string
88
+ /** URL del logo (se embebe como <img>). */
89
+ logo?: string
90
+ }
package/src/types.ts CHANGED
@@ -554,6 +554,13 @@ export interface PaginationMeta {
554
554
  // ActionMetadata re-exported from the sdk's action-registry. We mirror the
555
555
  // subset needed for the dispatcher so consumers of runtime-react don't have to
556
556
  // import the sdk directly for prop typings.
557
+ /** One page of a multi-step (wizard) action. Mirrors the sdk's ActionStep. */
558
+ export interface ActionStep {
559
+ title: string
560
+ description?: string
561
+ fields: ActionFieldDef[]
562
+ }
563
+
557
564
  export interface ActionMetadata {
558
565
  key: string
559
566
  label: string
@@ -562,6 +569,8 @@ export interface ActionMetadata {
562
569
  confirm?: boolean
563
570
  confirmMessage?: string
564
571
  fields?: ActionFieldDef[]
572
+ /** Multi-step wizard form; when present the dispatcher renders a wizard. */
573
+ steps?: ActionStep[]
565
574
  requiresState?: string[]
566
575
  executable?: boolean
567
576
  placement?: 'row' | 'table' | 'create'