@asteby/metacore-runtime-react 53.2.0 → 53.3.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 (38) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/license/index.d.ts +3 -1
  6. package/dist/license/index.d.ts.map +1 -1
  7. package/dist/license/index.js +3 -1
  8. package/dist/license/license-expiry-banner.d.ts +8 -1
  9. package/dist/license/license-expiry-banner.d.ts.map +1 -1
  10. package/dist/license/license-expiry-banner.js +96 -54
  11. package/dist/license/license-gate.d.ts +14 -4
  12. package/dist/license/license-gate.d.ts.map +1 -1
  13. package/dist/license/license-gate.js +75 -63
  14. package/dist/license/license-status-badge.d.ts.map +1 -1
  15. package/dist/license/license-status-badge.js +8 -9
  16. package/dist/license/messages.d.ts +29 -0
  17. package/dist/license/messages.d.ts.map +1 -0
  18. package/dist/license/messages.js +159 -0
  19. package/dist/license/types.d.ts +30 -7
  20. package/dist/license/types.d.ts.map +1 -1
  21. package/dist/license/types.js +20 -6
  22. package/dist/license/use-license-t.d.ts +11 -0
  23. package/dist/license/use-license-t.d.ts.map +1 -0
  24. package/dist/license/use-license-t.js +18 -0
  25. package/dist/license/view.d.ts +40 -0
  26. package/dist/license/view.d.ts.map +1 -0
  27. package/dist/license/view.js +62 -0
  28. package/package.json +1 -1
  29. package/src/__tests__/license-states.test.tsx +381 -0
  30. package/src/index.ts +13 -0
  31. package/src/license/index.ts +19 -0
  32. package/src/license/license-expiry-banner.tsx +155 -94
  33. package/src/license/license-gate.tsx +210 -147
  34. package/src/license/license-status-badge.tsx +8 -10
  35. package/src/license/messages.ts +185 -0
  36. package/src/license/types.ts +38 -6
  37. package/src/license/use-license-t.ts +23 -0
  38. package/src/license/view.ts +93 -0
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Textos del blindaje de licencia, en español e inglés. Son el copy exacto de
3
+ * cada estado: dicen QUÉ pasó y QUÉ sigue, sin repetir lo que ya dicen las
4
+ * etiquetas y botones de la pantalla (nada de "pega tu clave" junto a un campo
5
+ * que ya se llama "Clave…").
6
+ *
7
+ * Cada componente los pide con `t(key, { defaultValue })`: un host con i18n
8
+ * puede sobrescribir cualquier clave en su bundle; sin i18n sale este texto.
9
+ * `registerLicenseMessages(i18n)` los siembra en un i18next sin pisar lo del host.
10
+ *
11
+ * El SDK es genérico: aquí no hay marca, vertical ni vendedor concreto. El
12
+ * contacto del vendedor llega en el propio estado de la licencia.
13
+ */
14
+ export type LicenseLang = 'es' | 'en'
15
+
16
+ export function licenseLang(language?: string): LicenseLang {
17
+ return (language ?? '').toLowerCase().startsWith('en') ? 'en' : 'es'
18
+ }
19
+
20
+ export const LICENSE_MESSAGES: Record<LicenseLang, Record<string, string>> = {
21
+ es: {
22
+ // Insignias
23
+ 'license.status.valid': 'Activa',
24
+ 'license.status.stale': 'Sin verificar',
25
+ 'license.status.grace': 'En gracia',
26
+ 'license.status.expired': 'Vencida',
27
+ 'license.status.missing': 'Sin licencia',
28
+ 'license.status.invalid': 'Inválida',
29
+ 'license.status.revoked': 'Desactivada',
30
+
31
+ // Modal bloqueante
32
+ 'license.gate.instance': 'Esta instancia',
33
+ 'license.gate.title': 'Activa tu licencia',
34
+ 'license.gate.missing_description': 'Esta instancia todavía no tiene una licencia activa.',
35
+ 'license.gate.invalid_description': 'No pudimos validar la licencia de esta instancia.',
36
+ 'license.gate.expired_title': 'Tu licencia venció',
37
+ 'license.gate.expired_description': 'Tu licencia venció el {{date}} y el periodo de gracia terminó.',
38
+ 'license.gate.expired_description_nodate': 'Tu licencia venció y el periodo de gracia terminó.',
39
+ 'license.gate.trial_title': 'Tu prueba gratuita terminó',
40
+ 'license.gate.trial_description': 'La prueba gratuita de esta instancia terminó.',
41
+ 'license.gate.revoked_title': 'Licencia desactivada',
42
+ 'license.gate.revoked_description': '{{who}} desactivó la licencia de esta instancia.',
43
+ 'license.gate.read_only': 'Contacta al administrador de la plataforma para activar la licencia.',
44
+ 'license.gate.code_label': 'Clave o token de licencia',
45
+ 'license.gate.code_label_link': 'Enlace, código o clave de licencia',
46
+ 'license.gate.code_placeholder': 'lic_… o pega el token firmado',
47
+ 'license.gate.code_placeholder_link': 'https://…/a/acs_…, acs_… o lic_…',
48
+ 'license.gate.activate': 'Activar licencia',
49
+ 'license.gate.activating': 'Activando…',
50
+ 'license.gate.activate_error': 'No se pudo activar la licencia.',
51
+ 'license.gate.export': 'Exportar mis datos',
52
+ 'license.gate.provider': 'Tu proveedor',
53
+ 'license.gate.contact_label': 'Contacto',
54
+
55
+ // Errores de un enlace o código de activación (código estable del hub)
56
+ 'license.link.activation_not_found': 'No reconocemos ese enlace o código. Revisa que esté completo o pide uno nuevo a tu proveedor.',
57
+ 'license.link.activation_used': 'Este enlace ya se usó en otro servidor. Pide uno nuevo a tu proveedor.',
58
+ 'license.link.activation_conflict': 'Esta licencia ya funciona en otro servidor. Si lo reinstalaste, pide a tu proveedor que la libere.',
59
+ 'license.link.activation_expired': 'El enlace venció. Tu proveedor puede generarte otro en un minuto.',
60
+ 'license.link.activation_revoked': 'Tu proveedor revocó este enlace. Contáctalo para recibir uno nuevo.',
61
+ 'license.link.license_revoked': 'Tu proveedor desactivó esta licencia. Contáctalo para reactivarla.',
62
+ 'license.link.license_expired': 'La licencia de este enlace ya venció. Tu proveedor puede renovarla.',
63
+ 'license.link.rate_limited': 'Demasiados intentos. Espera unos minutos y vuelve a probar.',
64
+
65
+ // Banner
66
+ 'license.banner.upcoming': 'Tu licencia vence en {{days}} días.',
67
+ 'license.banner.upcoming_one': 'Tu licencia vence mañana.',
68
+ 'license.banner.upcoming_today': 'Tu licencia vence hoy.',
69
+ 'license.banner.grace': 'Tu licencia venció el {{date}}. Tienes {{days}} días para renovarla antes de que se bloqueen los cambios.',
70
+ 'license.banner.grace_nodate': 'Tu licencia venció. Tienes {{days}} días para renovarla antes de que se bloqueen los cambios.',
71
+ 'license.banner.expired_read_only': 'Tu licencia venció el {{date}}. Tu información sigue disponible para consultar y exportar; renueva para volver a registrar cambios.',
72
+ 'license.banner.expired_read_only_nodate': 'Tu licencia venció. Tu información sigue disponible para consultar y exportar; renueva para volver a registrar cambios.',
73
+ 'license.banner.expired': 'Tu licencia venció. Algunas acciones están bloqueadas.',
74
+ 'license.banner.revoked': '{{who}} desactivó esta licencia. Tu información sigue disponible para consultar y exportar hasta el {{date}}.',
75
+ 'license.banner.revoked_nodate': '{{who}} desactivó esta licencia. Tu información sigue disponible para consultar y exportar.',
76
+ 'license.banner.stale': 'No pudimos contactar al servidor de licencias desde el {{date}}. Seguimos funcionando.',
77
+ 'license.banner.stale_nodate': 'No pudimos contactar al servidor de licencias. Seguimos funcionando.',
78
+ 'license.banner.cloned': 'Detectamos esta licencia activa en otro servidor. Si no fue a propósito, avisa a {{who}}.',
79
+ 'license.banner.manage': 'Gestionar licencia',
80
+ 'license.banner.renew': 'Renovar',
81
+ 'license.banner.export': 'Exportar mis datos',
82
+ 'license.banner.dismiss': 'Descartar',
83
+ 'license.banner.contact': 'Contacto: {{contact}}',
84
+ 'license.banner.provider': 'tu proveedor',
85
+ },
86
+ en: {
87
+ 'license.status.valid': 'Active',
88
+ 'license.status.stale': 'Not verified',
89
+ 'license.status.grace': 'In grace period',
90
+ 'license.status.expired': 'Expired',
91
+ 'license.status.missing': 'No license',
92
+ 'license.status.invalid': 'Invalid',
93
+ 'license.status.revoked': 'Deactivated',
94
+
95
+ 'license.gate.instance': 'This instance',
96
+ 'license.gate.title': 'Activate your license',
97
+ 'license.gate.missing_description': "This instance doesn't have an active license yet.",
98
+ 'license.gate.invalid_description': "We couldn't validate this instance's license.",
99
+ 'license.gate.expired_title': 'Your license has expired',
100
+ 'license.gate.expired_description': 'Your license expired on {{date}} and the grace period has ended.',
101
+ 'license.gate.expired_description_nodate': 'Your license expired and the grace period has ended.',
102
+ 'license.gate.trial_title': 'Your free trial has ended',
103
+ 'license.gate.trial_description': "This instance's free trial has ended.",
104
+ 'license.gate.revoked_title': 'License deactivated',
105
+ 'license.gate.revoked_description': '{{who}} deactivated this instance\'s license.',
106
+ 'license.gate.read_only': 'Contact the platform administrator to activate the license.',
107
+ 'license.gate.code_label': 'License key or token',
108
+ 'license.gate.code_label_link': 'Activation link, code or license key',
109
+ 'license.gate.code_placeholder': 'lic_… or the signed token',
110
+ 'license.gate.code_placeholder_link': 'https://…/a/acs_…, acs_… or lic_…',
111
+ 'license.gate.activate': 'Activate license',
112
+ 'license.gate.activating': 'Activating…',
113
+ 'license.gate.activate_error': "The license couldn't be activated.",
114
+ 'license.gate.export': 'Export my data',
115
+ 'license.gate.provider': 'Your provider',
116
+ 'license.gate.contact_label': 'Contact',
117
+
118
+ 'license.link.activation_not_found': "We don't recognize that link or code. Check that it's complete, or ask your provider for a new one.",
119
+ 'license.link.activation_used': 'This link was already used on another server. Ask your provider for a new one.',
120
+ 'license.link.activation_conflict': 'This license already runs on another server. If you reinstalled, ask your provider to release it.',
121
+ 'license.link.activation_expired': 'The link has expired. Your provider can generate another in a minute.',
122
+ 'license.link.activation_revoked': 'Your provider revoked this link. Contact them to get a new one.',
123
+ 'license.link.license_revoked': 'Your provider deactivated this license. Contact them to reactivate it.',
124
+ 'license.link.license_expired': "This link's license has already expired. Your provider can renew it.",
125
+ 'license.link.rate_limited': 'Too many attempts. Wait a few minutes and try again.',
126
+
127
+ 'license.banner.upcoming': 'Your license expires in {{days}} days.',
128
+ 'license.banner.upcoming_one': 'Your license expires tomorrow.',
129
+ 'license.banner.upcoming_today': 'Your license expires today.',
130
+ 'license.banner.grace': 'Your license expired on {{date}}. You have {{days}} days to renew it before changes are blocked.',
131
+ 'license.banner.grace_nodate': 'Your license expired. You have {{days}} days to renew it before changes are blocked.',
132
+ 'license.banner.expired_read_only': 'Your license expired on {{date}}. Your data is still available to view and export; renew to record changes again.',
133
+ 'license.banner.expired_read_only_nodate': 'Your license expired. Your data is still available to view and export; renew to record changes again.',
134
+ 'license.banner.expired': 'Your license expired. Some actions are blocked.',
135
+ 'license.banner.revoked': '{{who}} deactivated this license. Your data stays available to view and export until {{date}}.',
136
+ 'license.banner.revoked_nodate': '{{who}} deactivated this license. Your data stays available to view and export.',
137
+ 'license.banner.stale': "We couldn't reach the license server since {{date}}. Everything keeps working.",
138
+ 'license.banner.stale_nodate': "We couldn't reach the license server. Everything keeps working.",
139
+ 'license.banner.cloned': "We detected this license active on another server. If that wasn't intended, let {{who}} know.",
140
+ 'license.banner.manage': 'Manage license',
141
+ 'license.banner.renew': 'Renew',
142
+ 'license.banner.export': 'Export my data',
143
+ 'license.banner.dismiss': 'Dismiss',
144
+ 'license.banner.contact': 'Contact: {{contact}}',
145
+ 'license.banner.provider': 'your provider',
146
+ },
147
+ }
148
+
149
+ /** Fecha corta y estable (UTC) para los textos de licencia. */
150
+ export function formatLicenseDate(iso: string | undefined, lang: LicenseLang): string | undefined {
151
+ if (!iso) return undefined
152
+ const d = new Date(iso)
153
+ if (Number.isNaN(d.getTime())) return undefined
154
+ return d.toLocaleDateString(lang === 'en' ? 'en-US' : 'es-MX', {
155
+ day: 'numeric',
156
+ month: 'long',
157
+ year: 'numeric',
158
+ timeZone: 'UTC',
159
+ })
160
+ }
161
+
162
+ /** Minimal i18next surface needed to seed the bundles. */
163
+ interface I18nLike {
164
+ addResourceBundle?: (lng: string, ns: string, res: object, deep?: boolean, overwrite?: boolean) => unknown
165
+ }
166
+
167
+ /**
168
+ * Siembra es/en en el i18next del host SIN pisar lo que ya tenga (overwrite=false):
169
+ * el host manda, el SDK solo rellena lo que falta.
170
+ */
171
+ export function registerLicenseMessages(i18n: I18nLike | undefined, ns = 'translation'): void {
172
+ if (!i18n?.addResourceBundle) return
173
+ for (const lang of ['es', 'en'] as const) {
174
+ const nested: Record<string, unknown> = {}
175
+ for (const [key, value] of Object.entries(LICENSE_MESSAGES[lang])) {
176
+ const parts = key.split('.')
177
+ let cur = nested
178
+ parts.slice(0, -1).forEach((p) => {
179
+ cur = (cur[p] ??= {}) as Record<string, unknown>
180
+ })
181
+ cur[parts[parts.length - 1]] = value
182
+ }
183
+ i18n.addResourceBundle(lang, ns, nested, true, false)
184
+ }
185
+ }
@@ -20,6 +20,20 @@ export type LicenseStatus =
20
20
  | 'expired'
21
21
  | 'missing'
22
22
  | 'invalid'
23
+ /** El emisor desactivó la licencia (el hub respondió `license_revoked`). */
24
+ | 'revoked'
25
+
26
+ /** Contacto de quien vendió la licencia. Solo se muestra si la licencia lo trae. */
27
+ export interface LicenseSeller {
28
+ name?: string
29
+ email?: string
30
+ phone?: string
31
+ url?: string
32
+ }
33
+
34
+ /** Qué hace la instancia cuando la licencia termina: `read_only` deja consultar y
35
+ * exportar sin registrar cambios; `block` es el comportamiento clásico (modal). */
36
+ export type LicenseOnExpiry = 'read_only' | 'block'
23
37
 
24
38
  export interface LicenseState {
25
39
  /** Licensing activo en esta instancia (LICENSING_ENFORCE). Si es false el
@@ -43,24 +57,42 @@ export interface LicenseState {
43
57
  grace_until?: string
44
58
  days_remaining: number
45
59
  last_checked_at?: string
60
+ /** Quien vendió la licencia, si el hub lo informó. */
61
+ seller?: LicenseSeller
62
+ /** Política al vencer. Ausente = `block` (instancias sin enlace de activación). */
63
+ on_expiry?: LicenseOnExpiry
64
+ /** Avisos para el dueño, p. ej. `clone_suspected` (licencia activa en otro servidor). */
65
+ notices?: string[]
46
66
  }
47
67
 
48
68
  /** La licencia es OPERABLE cuando permite operar (aunque sea degradada):
49
69
  * 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. */
70
+ * missing/invalid/expired/revoked no son operables. Sin enforcement → siempre
71
+ * operable. Espeja `State.Operable()` del backend. */
52
72
  export function isLicenseOperable(state: LicenseState | undefined): boolean {
53
73
  if (!state || !state.enforced) return true
54
74
  return state.valid || state.in_grace
55
75
  }
56
76
 
77
+ /** Vencida con política de solo lectura: la app sigue abierta para consultar y
78
+ * exportar, y el backend rechaza las escrituras. Solo aplica si el hub informó
79
+ * `on_expiry: 'read_only'`; sin él, vencida = bloqueo (comportamiento clásico). */
80
+ export function isLicenseReadOnly(state: LicenseState | undefined): boolean {
81
+ if (!state || !state.enforced) return false
82
+ if (state.on_expiry === 'read_only' && state.status === 'expired') return true
83
+ // Revocada dentro de su plazo corto de aviso: se puede consultar y exportar.
84
+ return state.status === 'revoked' && state.in_grace
85
+ }
86
+
57
87
  /** 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. */
88
+ * enforcement y la licencia es missing/invalid/revoked/expired (pasada la
89
+ * gracia), salvo que la política sea de solo lectura. grace/stale degradan con
90
+ * banner en vez de bloquear. Espeja `State.Blocking()`. Mientras el estado aún
91
+ * carga (undefined) NO bloquea: fail-open en la UI para que un check lento o
92
+ * fallido nunca destelle un candado sobre la app. */
62
93
  export function isLicenseBlocking(state: LicenseState | undefined): boolean {
63
94
  if (!state || !state.enforced) return false
95
+ if (isLicenseReadOnly(state)) return false
64
96
  return !isLicenseOperable(state)
65
97
  }
66
98
 
@@ -0,0 +1,23 @@
1
+ import { useTranslation } from 'react-i18next'
2
+ import { LICENSE_MESSAGES, licenseLang, type LicenseLang } from './messages'
3
+
4
+ /**
5
+ * `t` de licencia: pide la clave a i18next y, si el host no la define, cae al
6
+ * texto es/en del SDK según el idioma activo (español por omisión). Un host con
7
+ * su propio bundle gana siempre.
8
+ */
9
+ export function useLicenseT(): {
10
+ t: (key: string, vars?: Record<string, unknown>) => string
11
+ lang: LicenseLang
12
+ } {
13
+ const { t, i18n } = useTranslation()
14
+ const lang = licenseLang(i18n?.language)
15
+ return {
16
+ lang,
17
+ t: (key, vars) =>
18
+ t(key, {
19
+ defaultValue: LICENSE_MESSAGES[lang][key] ?? LICENSE_MESSAGES.es[key] ?? key,
20
+ ...vars,
21
+ }) as string,
22
+ }
23
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Una sola derivación del estado de licencia a "qué muestra la UI". Gate, banner
3
+ * y pantallas del host la comparten, así que todos cuentan lo mismo.
4
+ *
5
+ * Estados (solo con enforcement; sin él no hay vista):
6
+ * valid vigente
7
+ * expiring vigente, por vencer (≤ umbral de días)
8
+ * grace vencida, dentro de la gracia (se puede operar)
9
+ * expired vencida: solo lectura con exportación (`on_expiry: read_only`)
10
+ * o bloqueo con modal (política clásica)
11
+ * revoked desactivada por el emisor: solo lectura un tiempo corto y luego modal
12
+ * hub_unreachable sin contacto con el hub pero con lease vigente: opera; avisa solo al dueño
13
+ * missing/invalid sin licencia o no válida: modal de activación
14
+ * Además, `cloned` (licencia vista en otro servidor) es un aviso al dueño que se
15
+ * suma a cualquiera de los anteriores.
16
+ */
17
+ import { isLicenseBlocking, isLicenseReadOnly, isTrialExpired, type LicenseState } from './types'
18
+
19
+ export type LicenseCondition =
20
+ | 'valid'
21
+ | 'expiring'
22
+ | 'grace'
23
+ | 'expired'
24
+ | 'revoked'
25
+ | 'hub_unreachable'
26
+ | 'missing'
27
+ | 'invalid'
28
+
29
+ export type LicenseSeverity = 'ok' | 'notice' | 'warning' | 'critical'
30
+
31
+ export interface LicenseView {
32
+ condition: LicenseCondition
33
+ severity: LicenseSeverity
34
+ /** Modal bloqueante de pantalla completa. */
35
+ blocking: boolean
36
+ /** La app sigue abierta pero el backend rechaza escrituras (consultar y exportar). */
37
+ readOnly: boolean
38
+ /** El aviso es solo para el dueño/superadmin; el resto de usuarios no lo ve. */
39
+ ownerOnly: boolean
40
+ /** Licencia vista activa en otro servidor (aviso al dueño, no bloquea). */
41
+ cloned: boolean
42
+ trialExpired: boolean
43
+ }
44
+
45
+ export const CLONE_NOTICE = 'clone_suspected'
46
+
47
+ export function isLicenseCloned(state: LicenseState | undefined): boolean {
48
+ return !!state?.enforced && !!state.notices?.includes(CLONE_NOTICE)
49
+ }
50
+
51
+ export function deriveLicenseView(
52
+ state: LicenseState | undefined,
53
+ opts: { upcomingThresholdDays?: number } = {},
54
+ ): LicenseView | undefined {
55
+ if (!state || !state.enforced) return undefined
56
+ const threshold = opts.upcomingThresholdDays ?? 15
57
+ const blocking = isLicenseBlocking(state)
58
+ const readOnly = isLicenseReadOnly(state)
59
+ const base = {
60
+ blocking,
61
+ readOnly,
62
+ ownerOnly: false,
63
+ cloned: isLicenseCloned(state),
64
+ trialExpired: isTrialExpired(state),
65
+ }
66
+ switch (state.status) {
67
+ case 'missing':
68
+ return { ...base, condition: 'missing', severity: 'critical' }
69
+ case 'invalid':
70
+ return { ...base, condition: 'invalid', severity: 'critical' }
71
+ case 'revoked':
72
+ return { ...base, condition: 'revoked', severity: 'critical' }
73
+ case 'expired':
74
+ return { ...base, condition: 'expired', severity: 'critical' }
75
+ case 'grace':
76
+ return { ...base, condition: 'grace', severity: 'warning' }
77
+ case 'stale':
78
+ return { ...base, condition: 'hub_unreachable', severity: 'notice', ownerOnly: true }
79
+ default:
80
+ if (state.days_remaining <= threshold) {
81
+ return { ...base, condition: 'expiring', severity: 'warning' }
82
+ }
83
+ return { ...base, condition: 'valid', severity: 'ok' }
84
+ }
85
+ }
86
+
87
+ /** Texto de contacto de una línea ("Ana · ana@x.mx · +52…") o undefined. */
88
+ export function sellerContactLine(state: LicenseState | undefined): string | undefined {
89
+ const s = state?.seller
90
+ if (!s) return undefined
91
+ const parts = [s.email, s.phone, s.url].map((p) => p?.trim()).filter(Boolean) as string[]
92
+ return parts.length ? parts.join(' · ') : undefined
93
+ }