@asteby/metacore-runtime-react 53.13.1 → 53.15.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 (66) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/action-modal-dispatcher.d.ts +1 -1
  3. package/dist/action-modal-dispatcher.d.ts.map +1 -1
  4. package/dist/action-modal-dispatcher.js +31 -6
  5. package/dist/dialogs/dynamic-record.d.ts +8 -1
  6. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  7. package/dist/dialogs/dynamic-record.js +34 -4
  8. package/dist/dynamic-columns.d.ts.map +1 -1
  9. package/dist/dynamic-columns.js +4 -0
  10. package/dist/dynamic-form-schema.d.ts.map +1 -1
  11. package/dist/dynamic-form-schema.js +5 -1
  12. package/dist/dynamic-form.d.ts.map +1 -1
  13. package/dist/dynamic-form.js +28 -3
  14. package/dist/dynamic-kanban.d.ts.map +1 -1
  15. package/dist/dynamic-kanban.js +33 -1
  16. package/dist/dynamic-line-items.d.ts.map +1 -1
  17. package/dist/dynamic-line-items.js +9 -1
  18. package/dist/dynamic-table.d.ts.map +1 -1
  19. package/dist/dynamic-table.js +7 -0
  20. package/dist/field-grid.d.ts +3 -1
  21. package/dist/field-grid.d.ts.map +1 -1
  22. package/dist/field-grid.js +2 -2
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +1 -0
  26. package/dist/nullable-boolean.d.ts +48 -0
  27. package/dist/nullable-boolean.d.ts.map +1 -0
  28. package/dist/nullable-boolean.js +80 -0
  29. package/dist/slots/addon-slot.d.ts +91 -0
  30. package/dist/slots/addon-slot.d.ts.map +1 -0
  31. package/dist/slots/addon-slot.js +219 -0
  32. package/dist/slots/index.d.ts +3 -0
  33. package/dist/slots/index.d.ts.map +1 -0
  34. package/dist/slots/index.js +2 -0
  35. package/dist/slots/sdk-range.d.ts +6 -0
  36. package/dist/slots/sdk-range.d.ts.map +1 -0
  37. package/dist/slots/sdk-range.js +92 -0
  38. package/dist/tri-state-boolean-impl.d.ts +24 -0
  39. package/dist/tri-state-boolean-impl.d.ts.map +1 -0
  40. package/dist/tri-state-boolean-impl.js +35 -0
  41. package/dist/tri-state-boolean.d.ts +15 -0
  42. package/dist/tri-state-boolean.d.ts.map +1 -0
  43. package/dist/tri-state-boolean.js +24 -0
  44. package/dist/use-dynamic-filters.d.ts.map +1 -1
  45. package/dist/use-dynamic-filters.js +10 -0
  46. package/package.json +5 -5
  47. package/src/__tests__/addon-slot.test.tsx +280 -0
  48. package/src/__tests__/nullable-boolean.test.tsx +458 -0
  49. package/src/__tests__/slot-legacy.test.tsx +34 -0
  50. package/src/action-modal-dispatcher.tsx +32 -6
  51. package/src/dialogs/dynamic-record.tsx +53 -5
  52. package/src/dynamic-columns.tsx +3 -0
  53. package/src/dynamic-form-schema.ts +4 -1
  54. package/src/dynamic-form.tsx +31 -2
  55. package/src/dynamic-kanban.tsx +6 -1
  56. package/src/dynamic-line-items.tsx +9 -1
  57. package/src/dynamic-table.tsx +5 -0
  58. package/src/field-grid.tsx +4 -0
  59. package/src/index.ts +1 -0
  60. package/src/nullable-boolean.ts +96 -0
  61. package/src/slots/addon-slot.tsx +452 -0
  62. package/src/slots/index.ts +18 -0
  63. package/src/slots/sdk-range.ts +86 -0
  64. package/src/tri-state-boolean-impl.tsx +71 -0
  65. package/src/tri-state-boolean.tsx +39 -0
  66. package/src/use-dynamic-filters.ts +8 -0
@@ -0,0 +1,452 @@
1
+ // AddonSlot — punto de montaje de contribuciones de addons en un host.
2
+ //
3
+ // <AddonSlot kind="invoice.footer" context={{ invoiceId }} />
4
+ //
5
+ // Qué pinta, en este orden (`order` ascendente y luego `priority` descendente,
6
+ // ver docs/slot-priority.md):
7
+ // 1. contribuciones declaradas en los manifests instalados
8
+ // (`contributions.slots[]`, ya filtradas por el servidor: permiso,
9
+ // `condition` y org), que se bajan como remoto federado (`slot.entry` es
10
+ // el `expose`);
11
+ // 2. contribuciones en proceso registradas en el slot store canónico
12
+ // (`Registry.registerSlot`, `slotRegistry.register`): una sola lista.
13
+ //
14
+ // Cada contribución vive aislada en su propio ErrorBoundary + Suspense con un
15
+ // timeout: si un remoto lanza, se cuelga o no es compatible, emite
16
+ // `addon_slot_failed{addon,kind,reason}` por el canal de errores del host y
17
+ // muestra su fallback; sus hermanos y el shell no se enteran.
18
+ //
19
+ // Contrato del remoto (C2): `export default function SlotComponent({ context,
20
+ // props, sdk })`. Sin provider ni manifests, solo se pintan las contribuciones
21
+ // en proceso (equivale al `<Slot>` histórico).
22
+ import React, {
23
+ createContext,
24
+ Suspense,
25
+ useContext,
26
+ useEffect,
27
+ useMemo,
28
+ useRef,
29
+ useState,
30
+ useSyncExternalStore,
31
+ type ComponentType,
32
+ type ReactNode,
33
+ } from 'react'
34
+ import { slotStore, type SlotEntry } from '@asteby/metacore-sdk'
35
+ import { loadFederatedModule } from '../addon-loader'
36
+ import { FederatedErrorBoundary } from '../federated-error-boundary'
37
+ import { useInstalledAddons } from '../installed-addons-context'
38
+ import { satisfiesSdkRange } from './sdk-range'
39
+
40
+ export const ADDON_SLOT_FAILED = 'addon_slot_failed'
41
+ export const DEFAULT_ADDON_SLOT_TIMEOUT_MS = 10_000
42
+ /** Rango permitido por el contrato C1 para `slot.timeout_ms` del manifest. */
43
+ export const MIN_SLOT_TIMEOUT_MS = 1_000
44
+ export const MAX_SLOT_TIMEOUT_MS = 30_000
45
+
46
+ /**
47
+ * `timeout_ms` del manifest acotado a 1000..30000. Un valor no numérico, NaN,
48
+ * 0 o negativo se ignora y manda el del host (nunca anula el timeout).
49
+ */
50
+ export function resolveSlotTimeout(slotValue: unknown, hostMs: number): number {
51
+ if (typeof slotValue !== 'number' || !Number.isFinite(slotValue) || slotValue <= 0) return hostMs
52
+ return Math.min(MAX_SLOT_TIMEOUT_MS, Math.max(MIN_SLOT_TIMEOUT_MS, slotValue))
53
+ }
54
+
55
+ export type AddonSlotFailureReason =
56
+ | 'timeout'
57
+ | 'load'
58
+ | 'render'
59
+ | 'missing_expose'
60
+ | 'integrity_required'
61
+ | 'sdk_incompatible'
62
+
63
+ export interface AddonSlotFailure {
64
+ addon: string
65
+ kind: string
66
+ reason: AddonSlotFailureReason
67
+ /** Mensaje del error, si lo hubo. */
68
+ message?: string
69
+ }
70
+
71
+ export type AddonSlotEventHandler = (event: typeof ADDON_SLOT_FAILED, data: AddonSlotFailure) => void
72
+
73
+ /** Subconjunto del manifest que AddonSlot necesita (cabe un `ManifestV3` completo). */
74
+ export interface AddonSlotManifest {
75
+ key: string
76
+ version?: string
77
+ frontend?: {
78
+ entry: string
79
+ container?: string
80
+ integrity?: string
81
+ /** Rango semver del SDK con el que se compiló el bundle. */
82
+ sdk?: string
83
+ }
84
+ contributions?: { slots?: AddonSlotContribution[] }
85
+ }
86
+
87
+ export interface AddonSlotContribution {
88
+ slot_kind: string
89
+ /** `expose` del remoto (p. ej. "./slots/invoice-footer"). */
90
+ entry: string
91
+ order?: number
92
+ props?: Record<string, unknown>
93
+ timeout_ms?: number
94
+ }
95
+
96
+ /** Lo que recibe el componente del remoto además de `context` y `props`. */
97
+ export interface AddonSlotSDK {
98
+ addon: string
99
+ kind: string
100
+ /** Versión del SDK que el host expone a los remotos, si la declaró. */
101
+ sdkVersion?: string
102
+ }
103
+
104
+ export interface AddonSlotComponentProps {
105
+ context: Record<string, unknown>
106
+ props: Record<string, unknown>
107
+ sdk: AddonSlotSDK
108
+ }
109
+
110
+ interface Config {
111
+ manifests: readonly AddonSlotManifest[]
112
+ sdkVersion?: string
113
+ requireIntegrity: boolean
114
+ timeoutMs: number
115
+ onEvent?: AddonSlotEventHandler
116
+ }
117
+
118
+ const Ctx = createContext<Config | null>(null)
119
+
120
+ export interface AddonSlotProviderProps {
121
+ /** Manifests instalados, ya filtrados por el servidor. */
122
+ manifests: readonly AddonSlotManifest[]
123
+ /** Versión de `@asteby/metacore-sdk` que el host expone; habilita la comprobación de `frontend.sdk`. */
124
+ sdkVersion?: string
125
+ /** Rechaza remotos sin `frontend.integrity` (por omisión false = comportamiento histórico). */
126
+ requireIntegrity?: boolean
127
+ /** Timeout por omisión de carga de cada remoto (ms; 0 lo desactiva). */
128
+ timeoutMs?: number
129
+ /** Canal de errores del host (telemetría / incidentes). */
130
+ onEvent?: AddonSlotEventHandler
131
+ children?: ReactNode
132
+ }
133
+
134
+ export function AddonSlotProvider({
135
+ manifests,
136
+ sdkVersion,
137
+ requireIntegrity = false,
138
+ timeoutMs = DEFAULT_ADDON_SLOT_TIMEOUT_MS,
139
+ onEvent,
140
+ children,
141
+ }: AddonSlotProviderProps) {
142
+ const onEventRef = useRef(onEvent)
143
+ onEventRef.current = onEvent
144
+ const value = useMemo<Config>(
145
+ () => ({
146
+ manifests,
147
+ sdkVersion,
148
+ requireIntegrity,
149
+ timeoutMs,
150
+ onEvent: (e, d) => onEventRef.current?.(e, d),
151
+ }),
152
+ [manifests, sdkVersion, requireIntegrity, timeoutMs],
153
+ )
154
+ return <Ctx.Provider value={value}>{children}</Ctx.Provider>
155
+ }
156
+
157
+ export interface AddonSlotProps {
158
+ kind: string
159
+ context?: Record<string, unknown>
160
+ className?: string
161
+ /** Sustituye a la configuración del provider (timeout por omisión, ms). */
162
+ timeoutMs?: number
163
+ requireIntegrity?: boolean
164
+ onEvent?: AddonSlotEventHandler
165
+ /** Mientras un remoto baja. Por omisión nada. */
166
+ loading?: ReactNode
167
+ /** Qué se pinta en el lugar de una contribución que falló. Por omisión nada. */
168
+ fallback?: ReactNode | ((failure: AddonSlotFailure) => ReactNode)
169
+ /** Qué se pinta cuando el slot no tiene ninguna contribución (por omisión nada). */
170
+ empty?: ReactNode
171
+ }
172
+
173
+ type RemoteItem_ = {
174
+ type: 'remote'
175
+ id: string
176
+ addon: string
177
+ order: number
178
+ priority: number
179
+ manifest: AddonSlotManifest
180
+ slot: AddonSlotContribution
181
+ }
182
+ type LocalItem_ = { type: 'local'; id: string; addon: string; order: number; priority: number; entry: SlotEntry }
183
+ type Item = RemoteItem_ | LocalItem_
184
+
185
+ const EMPTY_OBJ: Record<string, unknown> = Object.freeze({}) as Record<string, unknown>
186
+
187
+ /** Orden canónico: `order` ascendente, luego `priority` descendente, luego inserción. */
188
+ export function sortSlotItems<T extends { order: number; priority: number }>(items: readonly T[]): T[] {
189
+ return items
190
+ .map((it, i) => ({ it, i }))
191
+ .sort((a, b) => a.it.order - b.it.order || b.it.priority - a.it.priority || a.i - b.i)
192
+ .map((x) => x.it)
193
+ }
194
+
195
+ function withTimeout<T>(p: Promise<T>, ms: number, onTimeout: () => Error): Promise<T> {
196
+ if (!ms || ms <= 0) return p
197
+ return new Promise<T>((resolve, reject) => {
198
+ const t = setTimeout(() => reject(onTimeout()), ms)
199
+ p.then(
200
+ (v) => {
201
+ clearTimeout(t)
202
+ resolve(v)
203
+ },
204
+ (e) => {
205
+ clearTimeout(t)
206
+ reject(e)
207
+ },
208
+ )
209
+ })
210
+ }
211
+
212
+ class SlotLoadError extends Error {
213
+ readonly reason: AddonSlotFailureReason
214
+ constructor(reason: AddonSlotFailureReason, message: string) {
215
+ super(message)
216
+ this.name = 'SlotLoadError'
217
+ this.reason = reason
218
+ }
219
+ }
220
+
221
+ function containerScope(m: AddonSlotManifest): string {
222
+ return m.frontend?.container || `metacore_${m.key.replace(/[^a-zA-Z0-9]/g, '_')}`
223
+ }
224
+
225
+ function toComponent(mod: unknown): ComponentType<AddonSlotComponentProps> | null {
226
+ const candidate = (mod as { default?: unknown } | null)?.default ?? mod
227
+ if (typeof candidate === 'function') return candidate as ComponentType<AddonSlotComponentProps>
228
+ // React.lazy / React.memo / forwardRef son objetos con $$typeof.
229
+ if (candidate && typeof candidate === 'object' && '$$typeof' in (candidate as object)) {
230
+ return candidate as ComponentType<AddonSlotComponentProps>
231
+ }
232
+ return null
233
+ }
234
+
235
+ type RemoteState =
236
+ | { status: 'loading' }
237
+ | { status: 'ready'; C: ComponentType<AddonSlotComponentProps> }
238
+ | { status: 'failed'; failure: AddonSlotFailure }
239
+
240
+ function RemoteItem({
241
+ kind,
242
+ item,
243
+ context,
244
+ cfg,
245
+ requireIntegrity,
246
+ timeoutMs,
247
+ loading,
248
+ renderFallback,
249
+ report,
250
+ }: {
251
+ kind: string
252
+ item: RemoteItem_
253
+ context: Record<string, unknown>
254
+ cfg: Config | null
255
+ requireIntegrity: boolean
256
+ timeoutMs: number
257
+ loading: ReactNode
258
+ renderFallback: (f: AddonSlotFailure) => ReactNode
259
+ report: (f: AddonSlotFailure) => void
260
+ }) {
261
+ const { manifest, slot, addon } = item
262
+ const fe = manifest.frontend
263
+ const [state, setState] = useState<RemoteState>({ status: 'loading' })
264
+ const reportRef = useRef(report)
265
+ reportRef.current = report
266
+ const effectiveTimeout = resolveSlotTimeout(slot.timeout_ms, timeoutMs)
267
+ const hostSdk = cfg?.sdkVersion
268
+
269
+ useEffect(() => {
270
+ let cancelled = false
271
+ const fail = (reason: AddonSlotFailureReason, message: string) => {
272
+ if (cancelled) return
273
+ const failure: AddonSlotFailure = { addon, kind, reason, message }
274
+ setState({ status: 'failed', failure })
275
+ reportRef.current(failure)
276
+ }
277
+ setState({ status: 'loading' })
278
+ if (!fe?.entry) {
279
+ fail('load', `addon ${addon} declares a slot but has no frontend.entry`)
280
+ return
281
+ }
282
+ if (requireIntegrity && !fe.integrity) {
283
+ fail('integrity_required', `addon ${addon} has no frontend.integrity and the host requires it`)
284
+ return
285
+ }
286
+ if (satisfiesSdkRange(hostSdk, fe.sdk) === false) {
287
+ fail('sdk_incompatible', `addon ${addon} needs SDK ${fe.sdk}, host provides ${hostSdk}`)
288
+ return
289
+ }
290
+ let loadPromise: Promise<unknown>
291
+ try {
292
+ loadPromise = Promise.resolve(loadFederatedModule(containerScope(manifest), fe.entry, slot.entry, fe.integrity))
293
+ } catch (e) {
294
+ loadPromise = Promise.reject(e)
295
+ }
296
+ withTimeout(
297
+ loadPromise,
298
+ effectiveTimeout,
299
+ () => new SlotLoadError('timeout', `slot "${slot.entry}" of ${addon} did not load within ${effectiveTimeout} ms`),
300
+ )
301
+ .then((mod) => {
302
+ if (cancelled) return
303
+ const C = toComponent(mod)
304
+ if (!C) throw new SlotLoadError('missing_expose', `expose "${slot.entry}" of ${addon} has no default component`)
305
+ setState({ status: 'ready', C })
306
+ })
307
+ .catch((e: unknown) => {
308
+ const err = e instanceof Error ? e : new Error(String(e))
309
+ fail(e instanceof SlotLoadError ? e.reason : 'load', err.message)
310
+ })
311
+ return () => {
312
+ cancelled = true
313
+ }
314
+ // eslint-disable-next-line react-hooks/exhaustive-deps
315
+ }, [addon, kind, fe?.entry, fe?.integrity, fe?.sdk, slot.entry, requireIntegrity, effectiveTimeout, hostSdk])
316
+
317
+ if (state.status === 'loading') return <>{loading}</>
318
+ if (state.status === 'failed') return <>{renderFallback(state.failure)}</>
319
+ const { C } = state
320
+ const sdk: AddonSlotSDK = { addon, kind, sdkVersion: hostSdk }
321
+ return (
322
+ <RenderGuard addon={addon} kind={kind} renderFallback={renderFallback} report={report} resetKey={fe?.entry}>
323
+ <C context={context} props={slot.props ?? EMPTY_OBJ} sdk={sdk} />
324
+ </RenderGuard>
325
+ )
326
+ }
327
+
328
+ function RenderGuard({
329
+ addon,
330
+ kind,
331
+ resetKey,
332
+ renderFallback,
333
+ report,
334
+ children,
335
+ }: {
336
+ addon: string
337
+ kind: string
338
+ resetKey?: unknown
339
+ renderFallback: (f: AddonSlotFailure) => ReactNode
340
+ report: (f: AddonSlotFailure) => void
341
+ children: ReactNode
342
+ }) {
343
+ return (
344
+ <FederatedErrorBoundary
345
+ addonKey={addon}
346
+ resetKeys={[resetKey]}
347
+ onError={(error) => report({ addon, kind, reason: 'render', message: error.message })}
348
+ fallback={({ error }) => <>{renderFallback({ addon, kind, reason: 'render', message: error.message })}</>}
349
+ >
350
+ <Suspense fallback={null}>{children}</Suspense>
351
+ </FederatedErrorBoundary>
352
+ )
353
+ }
354
+
355
+ export function AddonSlot({
356
+ kind,
357
+ context,
358
+ className,
359
+ timeoutMs,
360
+ requireIntegrity,
361
+ onEvent,
362
+ loading = null,
363
+ fallback = null,
364
+ empty = null,
365
+ }: AddonSlotProps) {
366
+ const cfg = useContext(Ctx)
367
+ const installed = useInstalledAddons()
368
+ const ctx = context ?? EMPTY_OBJ
369
+ const local = useSyncExternalStore(
370
+ (cb) => slotStore.subscribe(cb),
371
+ () => slotStore.get(kind),
372
+ () => slotStore.get(kind),
373
+ )
374
+
375
+ const items = useMemo(() => {
376
+ const out: Item[] = []
377
+ for (const m of cfg?.manifests ?? []) {
378
+ if (installed && !installed.addons.has(m.key)) continue
379
+ ;(m.contributions?.slots ?? []).forEach((slot, i) => {
380
+ if (slot.slot_kind !== kind) return
381
+ out.push({
382
+ type: 'remote',
383
+ id: `${m.key}:${slot.entry}:${i}`,
384
+ addon: m.key,
385
+ order: slot.order ?? 0,
386
+ priority: 0,
387
+ manifest: m,
388
+ slot,
389
+ })
390
+ })
391
+ }
392
+ local.forEach((entry, i) => {
393
+ if (entry.owner && installed && !installed.addons.has(entry.owner)) return
394
+ out.push({
395
+ type: 'local',
396
+ id: `local:${entry.source ?? 'anon'}:${i}`,
397
+ addon: entry.owner ?? entry.source ?? 'host',
398
+ order: 0,
399
+ priority: entry.priority ?? 0,
400
+ entry,
401
+ })
402
+ })
403
+ return sortSlotItems(out)
404
+ }, [cfg?.manifests, installed, local, kind])
405
+
406
+ const effTimeout = timeoutMs ?? cfg?.timeoutMs ?? DEFAULT_ADDON_SLOT_TIMEOUT_MS
407
+ const effRequire = requireIntegrity ?? cfg?.requireIntegrity ?? false
408
+ const handlerRef = useRef(onEvent ?? cfg?.onEvent)
409
+ handlerRef.current = onEvent ?? cfg?.onEvent
410
+
411
+ const report = useRef((f: AddonSlotFailure) => {
412
+ try {
413
+ handlerRef.current?.(ADDON_SLOT_FAILED, f)
414
+ } catch {
415
+ /* un reporter roto no tumba el shell */
416
+ }
417
+ }).current
418
+ const renderFallback = (f: AddonSlotFailure): ReactNode =>
419
+ typeof fallback === 'function' ? (fallback as (f: AddonSlotFailure) => ReactNode)(f) : fallback
420
+
421
+ if (items.length === 0) return <>{empty}</>
422
+ return (
423
+ <div data-addon-slot={kind} className={className} style={className ? undefined : { display: 'contents' }}>
424
+ {items.map((item) => (
425
+ <div key={item.id} data-addon-slot-item={item.addon} style={{ display: 'contents' }}>
426
+ {item.type === 'remote' ? (
427
+ <RemoteItem
428
+ kind={kind}
429
+ item={item}
430
+ context={ctx}
431
+ cfg={cfg}
432
+ requireIntegrity={effRequire}
433
+ timeoutMs={effTimeout}
434
+ loading={loading}
435
+ renderFallback={renderFallback}
436
+ report={report}
437
+ />
438
+ ) : (
439
+ <RenderGuard addon={item.addon} kind={kind} renderFallback={renderFallback} report={report}>
440
+ <item.entry.component
441
+ {...ctx}
442
+ context={ctx}
443
+ props={EMPTY_OBJ}
444
+ sdk={{ addon: item.addon, kind, sdkVersion: cfg?.sdkVersion } satisfies AddonSlotSDK}
445
+ />
446
+ </RenderGuard>
447
+ )}
448
+ </div>
449
+ ))}
450
+ </div>
451
+ )
452
+ }
@@ -0,0 +1,18 @@
1
+ export {
2
+ AddonSlot,
3
+ AddonSlotProvider,
4
+ sortSlotItems,
5
+ ADDON_SLOT_FAILED,
6
+ DEFAULT_ADDON_SLOT_TIMEOUT_MS,
7
+ resolveSlotTimeout,
8
+ type AddonSlotProps,
9
+ type AddonSlotProviderProps,
10
+ type AddonSlotManifest,
11
+ type AddonSlotContribution,
12
+ type AddonSlotSDK,
13
+ type AddonSlotComponentProps,
14
+ type AddonSlotFailure,
15
+ type AddonSlotFailureReason,
16
+ type AddonSlotEventHandler,
17
+ } from './addon-slot'
18
+ export { satisfiesSdkRange } from './sdk-range'
@@ -0,0 +1,86 @@
1
+ // Comprobación mínima de rangos semver para `manifest.frontend.sdk`
2
+ // (p. ej. "^4.0.0", ">=3.2 <5", "~3.18", "3.x", "^3 || ^4"). Sin dependencias.
3
+ // Un rango que no se entiende devuelve `null` (desconocido): el llamador NO lo
4
+ // trata como incompatible, para no romper addons por un rango exótico.
5
+
6
+ type V = [number, number, number]
7
+
8
+ function parseVersion(s: string): V | null {
9
+ const m = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/.exec(s.trim())
10
+ if (!m) return null
11
+ return [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)]
12
+ }
13
+
14
+ function cmp(a: V, b: V): number {
15
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
16
+ return 0
17
+ }
18
+
19
+ /** Un comparador simple (`^1.2.3`, `>=1`, `1.x`, `=1.2.3`) contra `v`. null = no se entiende. */
20
+ function matchComparator(token: string, v: V): boolean | null {
21
+ const m = /^(\^|~|>=|<=|>|<|=)?\s*v?([\dxX*]+(?:\.[\dxX*]+){0,2}(?:[-+][\w.-]+)?)$/.exec(token)
22
+ if (!m) return null
23
+ const op = m[1] ?? ''
24
+ const raw = m[2]
25
+ const parts = raw.split(/[-+]/)[0].split('.')
26
+ const isWild = (p: string | undefined) => p === undefined || /^[xX*]$/.test(p)
27
+ const nums = parts.map((p) => (isWild(p) ? null : Number(p)))
28
+ if (nums[0] === null) return op === '<' ? false : true // "*" / "x"
29
+ const lo: V = [nums[0], nums[1] ?? 0, nums[2] ?? 0]
30
+ const specified = nums.filter((n) => n !== null).length // 1..3
31
+ // Límite superior exclusivo para comodín / parcial ("1.2" => <1.3.0).
32
+ const bump = (n: number): V => (n === 1 ? [lo[0] + 1, 0, 0] : n === 2 ? [lo[0], lo[1] + 1, 0] : [lo[0], lo[1], lo[2] + 1])
33
+ switch (op) {
34
+ case '':
35
+ case '=':
36
+ return cmp(v, lo) >= 0 && cmp(v, bump(specified)) < 0
37
+ case '>=':
38
+ return cmp(v, lo) >= 0
39
+ case '>':
40
+ return cmp(v, bump(specified)) >= 0
41
+ case '<':
42
+ return cmp(v, lo) < 0
43
+ case '<=':
44
+ return cmp(v, bump(specified)) < 0
45
+ case '~':
46
+ return cmp(v, lo) >= 0 && cmp(v, bump(specified === 1 ? 1 : 2)) < 0
47
+ case '^': {
48
+ let hi: V
49
+ if (lo[0] > 0 || specified === 1) hi = [lo[0] + 1, 0, 0]
50
+ else if (lo[1] > 0 || specified === 2) hi = [0, lo[1] + 1, 0]
51
+ else hi = [0, 0, lo[2] + 1]
52
+ return cmp(v, lo) >= 0 && cmp(v, hi) < 0
53
+ }
54
+ }
55
+ return null
56
+ }
57
+
58
+ /**
59
+ * ¿`version` cumple `range`? `true`/`false` si ambos se entienden, `null` si
60
+ * alguno no (rango vacío o versión ilegible = sin restricción conocida).
61
+ */
62
+ export function satisfiesSdkRange(version: string | undefined, range: string | undefined): boolean | null {
63
+ if (!version || !range || !range.trim()) return null
64
+ const v = parseVersion(version)
65
+ if (!v) return null
66
+ let unknown = false
67
+ for (const alt of range.split('||')) {
68
+ // "1.2.3 - 2.0.0" no se soporta: cae en `unknown`.
69
+ const tokens = alt.trim().split(/\s+/).filter(Boolean)
70
+ if (tokens.length === 0) {
71
+ return true
72
+ }
73
+ let ok = true
74
+ for (const t of tokens) {
75
+ const r = matchComparator(t, v)
76
+ if (r === null) {
77
+ unknown = true
78
+ ok = false
79
+ break
80
+ }
81
+ if (!r) ok = false
82
+ }
83
+ if (ok) return true
84
+ }
85
+ return unknown ? null : false
86
+ }
@@ -0,0 +1,71 @@
1
+ // Control de tres estados para booleanos opcionales (ver nullable-boolean.ts).
2
+ // Se carga diferido desde tri-state-boolean.tsx para no pesar en el shell.
3
+ import { useTranslation } from 'react-i18next'
4
+ import { SegmentedControl } from '@asteby/metacore-ui/primitives'
5
+
6
+ export type TriState = 'true' | 'false' | 'null'
7
+
8
+ /** Valor de formulario → estado del control. `''`/null/undefined son «Sin definir». */
9
+ export function toTriState(value: unknown): TriState {
10
+ if (value === true || value === 'true') return 'true'
11
+ if (value === false || value === 'false') return 'false'
12
+ return 'null'
13
+ }
14
+
15
+ /** Estado del control → valor que viaja al servidor. */
16
+ export function fromTriState(state: TriState): boolean | null {
17
+ if (state === 'true') return true
18
+ if (state === 'false') return false
19
+ return null
20
+ }
21
+
22
+ export interface TriStateBooleanFieldProps {
23
+ id?: string
24
+ value: unknown
25
+ onChange: (value: boolean | null) => void
26
+ disabled?: boolean
27
+ /** Nombre accesible del grupo (la etiqueta del campo; se traduce como las demás). */
28
+ label?: string
29
+ /** id del <label> visible: el radiogroup no es «labelable», se asocia por aria-labelledby. */
30
+ labelledBy?: string
31
+ size?: 'sm' | 'default'
32
+ invalid?: boolean
33
+ }
34
+
35
+ /**
36
+ * Control de tres estados para un booleano opcional. Es un `radiogroup`
37
+ * (SegmentedControl de metacore-ui): flechas para moverse, el estado elegido
38
+ * se marca con relleno y `aria-checked`. «Sin definir» envía `null`.
39
+ */
40
+ export function TriStateBooleanField({
41
+ id,
42
+ value,
43
+ onChange,
44
+ disabled,
45
+ label,
46
+ labelledBy,
47
+ size = 'sm',
48
+ invalid,
49
+ }: TriStateBooleanFieldProps) {
50
+ const { t } = useTranslation()
51
+ const items = [
52
+ { value: 'true' as const, label: t('common.yes', { defaultValue: 'Sí' }), disabled },
53
+ { value: 'false' as const, label: t('common.no', { defaultValue: 'No' }), disabled },
54
+ { value: 'null' as const, label: t('common.unset', { defaultValue: 'Sin definir' }), disabled },
55
+ ]
56
+ return (
57
+ <SegmentedControl<TriState>
58
+ id={id}
59
+ items={items}
60
+ value={toTriState(value)}
61
+ onValueChange={(s) => onChange(fromTriState(s))}
62
+ aria-label={label ? t(label, { defaultValue: label }) : t('common.unset', { defaultValue: 'Sin definir' })}
63
+ aria-labelledby={labelledBy}
64
+ aria-invalid={invalid || undefined}
65
+ aria-disabled={disabled || undefined}
66
+ data-tri-state=""
67
+ size={size}
68
+ className="w-fit"
69
+ />
70
+ )
71
+ }
@@ -0,0 +1,39 @@
1
+ // Booleanos opcionales: control de tres estados (diferido) y marca de NULL.
2
+ // El control vive en tri-state-boolean-impl.tsx y se carga con React.lazy: sólo
3
+ // lo baja quien abre un formulario con un booleano opcional, así no suma al
4
+ // shell inicial de la app.
5
+ import { Suspense, lazy } from 'react'
6
+ import { useTranslation } from 'react-i18next'
7
+ import type { TriStateBooleanFieldProps } from './tri-state-boolean-impl'
8
+
9
+ export type { TriStateBooleanFieldProps } from './tri-state-boolean-impl'
10
+
11
+ const Impl = lazy(() =>
12
+ import('./tri-state-boolean-impl').then((m) => ({ default: m.TriStateBooleanField })),
13
+ )
14
+
15
+ /**
16
+ * Control Sí / No / Sin definir para un booleano opcional. «Sin definir»
17
+ * envía `null`. Accesible (radiogroup con flechas) y con i18n es/en.
18
+ */
19
+ export function TriStateBooleanField(props: TriStateBooleanFieldProps) {
20
+ return (
21
+ <Suspense fallback={<span className="inline-block h-8" aria-busy="true" />}>
22
+ <Impl {...props} />
23
+ </Suspense>
24
+ )
25
+ }
26
+
27
+ /**
28
+ * Celda/vista de solo lectura para un booleano NULL: «—» (misma convención que
29
+ * `formatDisplayValue`), con «Sin definir» como nombre accesible y tooltip.
30
+ */
31
+ export function NullBooleanMark({ className }: { className?: string }) {
32
+ const { t } = useTranslation()
33
+ const label = t('common.unset', { defaultValue: 'Sin definir' })
34
+ return (
35
+ <span className={className ?? 'text-muted-foreground'} title={label} aria-label={label} data-bool-null="">
36
+ —
37
+ </span>
38
+ )
39
+ }