@asteby/metacore-runtime-react 53.28.0 → 53.29.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 (63) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/business/customer-picker.d.ts.map +1 -1
  3. package/dist/business/customer-picker.js +4 -0
  4. package/dist/dialogs/create-record-dialog.d.ts +1 -1
  5. package/dist/dialogs/create-record-dialog.d.ts.map +1 -1
  6. package/dist/dialogs/create-record-dialog.js +2 -2
  7. package/dist/dialogs/dynamic-record.d.ts +16 -1
  8. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  9. package/dist/dialogs/dynamic-record.js +49 -3
  10. package/dist/dialogs/types.d.ts +4 -0
  11. package/dist/dialogs/types.d.ts.map +1 -1
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +1 -0
  15. package/dist/loom/index.d.ts +9 -0
  16. package/dist/loom/index.d.ts.map +1 -0
  17. package/dist/loom/index.js +9 -0
  18. package/dist/loom/overlay.d.ts +74 -0
  19. package/dist/loom/overlay.d.ts.map +1 -0
  20. package/dist/loom/overlay.js +142 -0
  21. package/dist/loom/proposals.d.ts +26 -0
  22. package/dist/loom/proposals.d.ts.map +1 -0
  23. package/dist/loom/proposals.js +74 -0
  24. package/dist/loom/provider.d.ts +28 -0
  25. package/dist/loom/provider.d.ts.map +1 -0
  26. package/dist/loom/provider.js +31 -0
  27. package/dist/loom/resolve.d.ts +23 -0
  28. package/dist/loom/resolve.d.ts.map +1 -0
  29. package/dist/loom/resolve.js +138 -0
  30. package/dist/loom/seam.d.ts +28 -0
  31. package/dist/loom/seam.d.ts.map +1 -0
  32. package/dist/loom/seam.js +127 -0
  33. package/dist/loom/seams.d.ts +31 -0
  34. package/dist/loom/seams.d.ts.map +1 -0
  35. package/dist/loom/seams.js +21 -0
  36. package/dist/loom/store.d.ts +16 -0
  37. package/dist/loom/store.d.ts.map +1 -0
  38. package/dist/loom/store.js +72 -0
  39. package/dist/loom/types.d.ts +153 -0
  40. package/dist/loom/types.d.ts.map +1 -0
  41. package/dist/loom/types.js +1 -0
  42. package/dist/record-picker-dialog.d.ts +7 -1
  43. package/dist/record-picker-dialog.d.ts.map +1 -1
  44. package/dist/record-picker-dialog.js +18 -3
  45. package/package.json +6 -6
  46. package/src/__tests__/dynamic-record-seam.test.tsx +194 -0
  47. package/src/__tests__/loom-overlay.test.ts +94 -0
  48. package/src/__tests__/loom-resolve.test.ts +108 -0
  49. package/src/business/customer-picker.tsx +4 -0
  50. package/src/dialogs/create-record-dialog.tsx +4 -0
  51. package/src/dialogs/dynamic-record.tsx +83 -0
  52. package/src/dialogs/types.ts +4 -0
  53. package/src/index.ts +1 -0
  54. package/src/loom/index.ts +36 -0
  55. package/src/loom/overlay.ts +196 -0
  56. package/src/loom/proposals.tsx +156 -0
  57. package/src/loom/provider.tsx +69 -0
  58. package/src/loom/resolve.ts +136 -0
  59. package/src/loom/seam.tsx +235 -0
  60. package/src/loom/seams.ts +42 -0
  61. package/src/loom/store.ts +81 -0
  62. package/src/loom/types.ts +167 -0
  63. package/src/record-picker-dialog.tsx +37 -1
@@ -0,0 +1,69 @@
1
+ // LoomProvider — lo que el anfitrión sabe para resolver seams: los injertos que
2
+ // el SERVIDOR autorizó (respuesta de GET /api/ui/grafts, ver RFC 0005 §5), flags,
3
+ // ajustes de la organización y el canal de telemetría. Sin provider, <Seam> sólo
4
+ // monta injertos registrados en proceso (código local de confianza).
5
+ import { createContext, useContext, useMemo, useRef, type ReactNode } from 'react'
6
+ import type { GraftDef, LoomEvent } from './types'
7
+
8
+ export interface LoomConfig {
9
+ /** Injertos servidos por el servidor (ya filtrados por RBAC/ajustes/preset). */
10
+ grafts: readonly GraftDef[]
11
+ /**
12
+ * Si es true, sólo se montan injertos cuyo id está en `grafts` (los registrados en proceso
13
+ * sin autorización del servidor se explican como `not_granted`).
14
+ */
15
+ serverAuthoritative: boolean
16
+ flags?: ReadonlySet<string>
17
+ settings?: Readonly<Record<string, unknown>>
18
+ onEvent?: (e: LoomEvent) => void
19
+ /** Pinta el inspector de seams (desarrollo). */
20
+ inspect?: boolean
21
+ }
22
+
23
+ const Ctx = createContext<LoomConfig | null>(null)
24
+
25
+ export interface LoomProviderProps {
26
+ grafts?: readonly GraftDef[]
27
+ serverAuthoritative?: boolean
28
+ flags?: Iterable<string>
29
+ settings?: Readonly<Record<string, unknown>>
30
+ onEvent?: (e: LoomEvent) => void
31
+ inspect?: boolean
32
+ children?: ReactNode
33
+ }
34
+
35
+ export function LoomProvider({
36
+ grafts = [],
37
+ serverAuthoritative = false,
38
+ flags,
39
+ settings,
40
+ onEvent,
41
+ inspect = false,
42
+ children,
43
+ }: LoomProviderProps) {
44
+ const onEventRef = useRef(onEvent)
45
+ onEventRef.current = onEvent
46
+ const flagKey = flags ? [...flags].sort().join(',') : ''
47
+ const value = useMemo<LoomConfig>(
48
+ () => ({
49
+ grafts,
50
+ serverAuthoritative,
51
+ flags: new Set(flagKey ? flagKey.split(',') : []),
52
+ settings,
53
+ inspect,
54
+ onEvent: (e) => {
55
+ try {
56
+ onEventRef.current?.(e)
57
+ } catch {
58
+ /* un reporter roto no tumba al anfitrión */
59
+ }
60
+ },
61
+ }),
62
+ [grafts, serverAuthoritative, flagKey, settings, inspect],
63
+ )
64
+ return <Ctx.Provider value={value}>{children}</Ctx.Provider>
65
+ }
66
+
67
+ export function useLoomConfig(): LoomConfig | null {
68
+ return useContext(Ctx)
69
+ }
@@ -0,0 +1,136 @@
1
+ // Resolución pura de un seam: qué injertos se montan, en qué orden y por qué
2
+ // los demás no. Sin React: la usan <Seam>, el inspector y las pruebas de contrato.
3
+ import { satisfiesSdkRange } from '../slots/sdk-range'
4
+ import { getPart } from './store'
5
+ import type { DataClass, GraftDef, LoomEnv, ResolvedSeam, SeamContract, SkippedGraft } from './types'
6
+
7
+ const bare = (model: string) => model.split('.').pop() ?? model
8
+ const asList = (v: string | string[] | undefined) => (v == null ? [] : Array.isArray(v) ? v : [v])
9
+
10
+ function hasComponent(g: GraftDef): boolean {
11
+ if (g.component || g.load) return true
12
+ if (!g.part) return false
13
+ const p = getPart(g.part)
14
+ return !!(p && (p.component || p.load))
15
+ }
16
+
17
+ function check(g: GraftDef, contract: SeamContract, env: LoomEnv): SkippedGraft | null {
18
+ const skip = (reason: SkippedGraft['reason'], detail?: string): SkippedGraft => ({ graft: g, reason, detail })
19
+ if (env.granted && !env.granted.has(g.id)) return skip('not_granted', 'el servidor no lo listó para este usuario')
20
+ if (g.requires && satisfiesSdkRange(contract.version, g.requires) === false) {
21
+ return skip('version', `pide ${contract.id}@${g.requires}, el anfitrión publica ${contract.version}`)
22
+ }
23
+ const w = g.when
24
+ if (w) {
25
+ const missing = asList(w.permission).filter((p) => !env.can(p))
26
+ if (missing.length) return skip('permission', missing.join(', '))
27
+ if (w.anyPermission?.length && !w.anyPermission.some((p) => env.can(p))) {
28
+ return skip('permission', `alguno de ${w.anyPermission.join(', ')}`)
29
+ }
30
+ if (w.flag && !env.flags?.has(w.flag)) return skip('flag', w.flag)
31
+ if (w.setting) {
32
+ const v = env.settings?.[w.setting.key]
33
+ const ok = 'equals' in w.setting ? Object.is(v, w.setting.equals) : !!v
34
+ if (!ok) return skip('setting', w.setting.key)
35
+ }
36
+ if (w.model?.length) {
37
+ const m = env.model ? bare(env.model) : undefined
38
+ if (!m || !w.model.some((x) => bare(x) === m)) return skip('model', env.model ?? '(sin modelo)')
39
+ }
40
+ if (w.mode?.length && (!env.mode || !w.mode.includes(env.mode))) return skip('mode', env.mode ?? '(sin modo)')
41
+ }
42
+ if (!hasComponent(g)) return skip('no_component', g.part ? `Part ${g.part} no registrado` : undefined)
43
+ return null
44
+ }
45
+
46
+ /** Orden canónico: `order` ascendente, luego orden de entrada (estable). */
47
+ export function resolveSeam(contract: SeamContract, candidates: readonly GraftDef[], env: LoomEnv): ResolvedSeam {
48
+ const mounted: GraftDef[] = []
49
+ const skipped: SkippedGraft[] = []
50
+ for (const g of candidates) {
51
+ if (g.seam !== contract.id) continue
52
+ const s = check(g, contract, env)
53
+ if (s) skipped.push(s)
54
+ else mounted.push(g)
55
+ }
56
+ const indexed = mounted.map((g, i) => ({ g, i }))
57
+ indexed.sort((a, b) => (a.g.order ?? 0) - (b.g.order ?? 0) || a.i - b.i)
58
+ return { mounted: indexed.map((x) => x.g), skipped }
59
+ }
60
+
61
+ /** `fiscal_data.*` cubre `fiscal_data.rfc`; un nombre exacto, sólo a sí mismo. */
62
+ export function matchesWrite(key: string, patterns: readonly string[]): boolean {
63
+ return patterns.some((p) => (p.endsWith('.*') ? key.startsWith(p.slice(0, -1)) : p === key))
64
+ }
65
+
66
+ /**
67
+ * Atenúa un parche: sólo pasan claves que el injerto declaró en `writes` Y que el seam
68
+ * acepta (`writable`). Sin `writes`, el injerto no escribe nada.
69
+ */
70
+ export function attenuatePatch(
71
+ patch: Record<string, unknown>,
72
+ writes: readonly string[] | undefined,
73
+ writable: ReadonlySet<string> | undefined,
74
+ ): { allowed: Record<string, unknown>; dropped: string[] } {
75
+ const allowed: Record<string, unknown> = {}
76
+ const dropped: string[] = []
77
+ for (const [k, v] of Object.entries(patch ?? {})) {
78
+ if (writable && writable.has(k) && writes && matchesWrite(k, writes)) allowed[k] = v
79
+ else dropped.push(k)
80
+ }
81
+ return { allowed, dropped }
82
+ }
83
+
84
+ /** Sólo las lentes declaradas, congeladas (una lente no declarada no existe para el injerto). */
85
+ export function projectLenses(
86
+ lenses: Readonly<Record<string, unknown>>,
87
+ reads: readonly string[] | undefined,
88
+ ): Readonly<Record<string, unknown>> {
89
+ const out: Record<string, unknown> = {}
90
+ for (const k of reads ?? []) if (k in lenses) out[k] = freeze(snapshot(lenses[k]))
91
+ return Object.freeze(out)
92
+ }
93
+
94
+ /**
95
+ * Copia para congelar sin tocar el estado del anfitrión. Objetos planos y arrays se copian en
96
+ * profundidad; el resto (File, Date, instancias) pasa tal cual y no se congela.
97
+ */
98
+ function snapshot<T>(v: T): T {
99
+ if (Array.isArray(v)) return v.map(snapshot) as T
100
+ if (v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype) {
101
+ const o: Record<string, unknown> = {}
102
+ for (const [k, x] of Object.entries(v as object)) o[k] = snapshot(x)
103
+ return o as T
104
+ }
105
+ return v
106
+ }
107
+
108
+ function freeze<T>(v: T): T {
109
+ if (v && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype) return v
110
+ if (v && typeof v === 'object' && !Object.isFrozen(v)) {
111
+ Object.freeze(v)
112
+ for (const x of Object.values(v as object)) freeze(x)
113
+ }
114
+ return v
115
+ }
116
+
117
+ const SENSITIVE: ReadonlySet<DataClass> = new Set<DataClass>(['pii', 'pii.fiscal', 'secret'])
118
+
119
+ /** Clases sensibles que un injerto lee: si hay alguna, sus errores salen redactados. */
120
+ export function sensitiveClasses(contract: SeamContract, reads: readonly string[] | undefined): DataClass[] {
121
+ const out = new Set<DataClass>()
122
+ for (const r of reads ?? []) {
123
+ const c = contract.lenses[r]
124
+ if (c && SENSITIVE.has(c)) out.add(c)
125
+ }
126
+ return [...out]
127
+ }
128
+
129
+ /**
130
+ * Mensaje apto para telemetría. Un injerto que leyó datos sensibles puede haberlos metido en el
131
+ * mensaje de error (p. ej. `RFC XAXX010101000 inválido`): se sustituye entero.
132
+ */
133
+ export function redactMessage(message: string, classes: readonly DataClass[]): string {
134
+ if (!classes.length) return message
135
+ return `[redactado: ${classes.join(',')}]`
136
+ }
@@ -0,0 +1,235 @@
1
+ // <Seam> — punto de extensión tipado. El anfitrión publica el contrato (lentes con
2
+ // clase de datos, campos escribibles, intenciones) y Seam monta los injertos que
3
+ // lo cumplen: cada uno aislado (error boundary + Suspense + carga perezosa), con
4
+ // sólo las lentes que declaró y un `propose` atenuado a sus `writes`.
5
+ import {
6
+ lazy,
7
+ Suspense,
8
+ useCallback,
9
+ useMemo,
10
+ useRef,
11
+ useSyncExternalStore,
12
+ type ComponentType,
13
+ type LazyExoticComponent,
14
+ type ReactNode,
15
+ } from 'react'
16
+ import { FederatedErrorBoundary } from '../federated-error-boundary'
17
+ import { useCan } from '../permissions-context'
18
+ import { useLoomConfig } from './provider'
19
+ import { attenuatePatch, projectLenses, redactMessage, resolveSeam, sensitiveClasses } from './resolve'
20
+ import { getPart, listGrafts, loomVersion, subscribeLoom } from './store'
21
+ import type {
22
+ GraftCapabilities,
23
+ GraftComponent,
24
+ GraftDef,
25
+ GraftModule,
26
+ LoomEvent,
27
+ ProposalInput,
28
+ Proposal,
29
+ ResolvedSeam,
30
+ SeamContract,
31
+ } from './types'
32
+
33
+ export interface SeamHostContext {
34
+ model?: string
35
+ mode?: string
36
+ }
37
+
38
+ /** Injertos de un seam ya resueltos (montados + descartados con motivo). */
39
+ export function useSeam(contract: SeamContract, host: SeamHostContext = {}): ResolvedSeam {
40
+ const cfg = useLoomConfig()
41
+ const can = useCan()
42
+ const v = useSyncExternalStore(subscribeLoom, loomVersion, loomVersion)
43
+ return useMemo(() => {
44
+ const local = listGrafts(contract.id)
45
+ const byId = new Map<string, GraftDef>()
46
+ for (const g of local) byId.set(g.id, g)
47
+ // Lo servido manda en metadatos (orden, props); el código local aporta el componente.
48
+ for (const s of cfg?.grafts ?? []) {
49
+ if (s.seam !== contract.id) continue
50
+ const l = byId.get(s.id)
51
+ byId.set(s.id, l ? { ...l, ...s, component: l.component, load: s.load ?? l.load, part: s.part ?? l.part } : s)
52
+ }
53
+ const granted = cfg?.serverAuthoritative ? new Set((cfg.grafts ?? []).map((g) => g.id)) : undefined
54
+ return resolveSeam(contract, [...byId.values()], {
55
+ can,
56
+ flags: cfg?.flags,
57
+ settings: cfg?.settings,
58
+ model: host.model,
59
+ mode: host.mode,
60
+ granted,
61
+ })
62
+ // eslint-disable-next-line react-hooks/exhaustive-deps
63
+ }, [contract, cfg, can, host.model, host.mode, v])
64
+ }
65
+
66
+ const lazyCache = new WeakMap<() => Promise<GraftModule>, LazyExoticComponent<ComponentType<any>>>()
67
+
68
+ function toLazy(load: () => Promise<GraftModule>): LazyExoticComponent<ComponentType<any>> {
69
+ let c = lazyCache.get(load)
70
+ if (!c) {
71
+ c = lazy(async () => {
72
+ const mod = await load()
73
+ const C = (mod as { default?: GraftComponent }).default ?? mod
74
+ if (typeof C !== 'function' && !(C && typeof C === 'object' && '$$typeof' in C)) {
75
+ throw new Error('el módulo del injerto no exporta un componente')
76
+ }
77
+ return { default: C as ComponentType<any> }
78
+ })
79
+ lazyCache.set(load, c)
80
+ }
81
+ return c
82
+ }
83
+
84
+ function componentOf(g: GraftDef): ComponentType<any> | null {
85
+ if (g.component) return g.component
86
+ if (g.load) return toLazy(g.load)
87
+ const p = g.part ? getPart(g.part) : undefined
88
+ if (p?.component) return p.component
89
+ if (p?.load) return toLazy(p.load)
90
+ return null
91
+ }
92
+
93
+ export interface SeamProps {
94
+ contract: SeamContract
95
+ /** Valores de las lentes del contrato. */
96
+ lenses: Readonly<Record<string, unknown>>
97
+ host?: SeamHostContext
98
+ /** Recibe las propuestas ya atenuadas. Sin él, el seam no acepta propuestas. */
99
+ onProposal?: (p: Proposal) => void
100
+ /** Atiende una intención; devuelve true si la manejó. */
101
+ onIntent?: (intent: string, payload: unknown, graft: GraftDef) => boolean
102
+ /** Mientras un injerto perezoso baja. */
103
+ loading?: ReactNode
104
+ className?: string
105
+ }
106
+
107
+ let proposalSeq = 0
108
+
109
+ function GraftMount({
110
+ graft,
111
+ contract,
112
+ lenses,
113
+ onProposal,
114
+ onIntent,
115
+ loading,
116
+ report,
117
+ }: {
118
+ graft: GraftDef
119
+ contract: SeamContract
120
+ lenses: Readonly<Record<string, unknown>>
121
+ onProposal?: (p: Proposal) => void
122
+ onIntent?: SeamProps['onIntent']
123
+ loading: ReactNode
124
+ report: (e: LoomEvent) => void
125
+ }) {
126
+ const can = useCan()
127
+ const addon = graft.addon ?? graft.id.split('.')[0] ?? 'host'
128
+ const C = useMemo(() => componentOf(graft), [graft])
129
+ const view = useMemo(() => projectLenses(lenses, graft.reads), [lenses, graft.reads])
130
+ const classes = useMemo(() => sensitiveClasses(contract, graft.reads), [contract, graft.reads])
131
+ const live = useRef({ onProposal, onIntent, report })
132
+ live.current = { onProposal, onIntent, report }
133
+
134
+ const propose = useCallback(
135
+ (input: ProposalInput) => {
136
+ const { allowed, dropped } = attenuatePatch(input.patch, graft.writes, contract.writable)
137
+ if (dropped.length) {
138
+ live.current.report({ type: 'proposal_dropped_keys', seam: contract.id, graft: graft.id, addon, keys: dropped })
139
+ }
140
+ if (!Object.keys(allowed).length || !live.current.onProposal) return
141
+ live.current.onProposal({
142
+ ...input,
143
+ patch: allowed,
144
+ id: `${graft.id}#${++proposalSeq}`,
145
+ graft: graft.id,
146
+ addon,
147
+ previous: {},
148
+ dropped,
149
+ })
150
+ },
151
+ [graft.id, graft.writes, contract.id, contract.writable, addon],
152
+ )
153
+ const emit = useCallback(
154
+ (intent: string, payload?: unknown) => {
155
+ if (!contract.intents?.includes(intent)) return false
156
+ return live.current.onIntent?.(intent, payload, graft) ?? false
157
+ },
158
+ [contract.intents, graft],
159
+ )
160
+ const caps = useMemo<GraftCapabilities>(() => ({ propose, emit, can }), [propose, emit, can])
161
+ const meta = useMemo(() => ({ id: graft.id, addon, seam: contract.id }), [graft.id, addon, contract.id])
162
+
163
+ if (!C) return null
164
+ return (
165
+ <div data-loom-graft={graft.id} data-loom-addon={addon} style={{ display: 'contents' }}>
166
+ <FederatedErrorBoundary
167
+ addonKey={addon}
168
+ onError={(err) =>
169
+ report({
170
+ type: 'graft_failed',
171
+ seam: contract.id,
172
+ graft: graft.id,
173
+ addon,
174
+ reason: 'render',
175
+ message: redactMessage(err.message, classes),
176
+ })
177
+ }
178
+ // Falla en silencio: el anfitrión sigue igual que sin el injerto.
179
+ fallback={() => null}
180
+ >
181
+ <Suspense fallback={loading}>
182
+ <C lenses={view} props={graft.props ?? EMPTY} caps={caps} graft={meta} />
183
+ </Suspense>
184
+ </FederatedErrorBoundary>
185
+ </div>
186
+ )
187
+ }
188
+
189
+ const EMPTY: Record<string, unknown> = Object.freeze({}) as Record<string, unknown>
190
+
191
+ export function Seam({ contract, lenses, host, onProposal, onIntent, loading = null, className }: SeamProps) {
192
+ const cfg = useLoomConfig()
193
+ const resolved = useSeam(contract, host)
194
+ const report = useCallback((e: LoomEvent) => cfg?.onEvent?.(e), [cfg])
195
+ if (!resolved.mounted.length && !cfg?.inspect) return null
196
+ return (
197
+ <div data-loom-seam={contract.id} data-loom-seam-version={contract.version} className={className} style={className ? undefined : { display: 'contents' }}>
198
+ {resolved.mounted.map((g) => (
199
+ <GraftMount
200
+ key={g.id}
201
+ graft={g}
202
+ contract={contract}
203
+ lenses={lenses}
204
+ onProposal={onProposal}
205
+ onIntent={onIntent}
206
+ loading={loading}
207
+ report={report}
208
+ />
209
+ ))}
210
+ {cfg?.inspect ? <SeamInspector contract={contract} resolved={resolved} /> : null}
211
+ </div>
212
+ )
213
+ }
214
+
215
+ /** Inspector de desarrollo: qué llena el seam y por qué lo demás no se montó. */
216
+ export function SeamInspector({ contract, resolved }: { contract: SeamContract; resolved: ResolvedSeam }) {
217
+ return (
218
+ <details data-loom-inspector={contract.id} className="rounded border border-dashed border-primary/50 px-2 py-1 text-[11px] text-muted-foreground">
219
+ <summary>
220
+ {contract.id}@{contract.version} · {resolved.mounted.length} montados · {resolved.skipped.length} no
221
+ </summary>
222
+ <ul>
223
+ {resolved.mounted.map((g) => (
224
+ <li key={g.id}>montado: {g.id}</li>
225
+ ))}
226
+ {resolved.skipped.map((s) => (
227
+ <li key={s.graft.id}>
228
+ no montado: {s.graft.id}: {s.reason}
229
+ {s.detail ? ` (${s.detail})` : ''}
230
+ </li>
231
+ ))}
232
+ </ul>
233
+ </details>
234
+ )
235
+ }
@@ -0,0 +1,42 @@
1
+ // Catálogo de seams del SDK (contratos versionados). Cada seam documenta sus
2
+ // lentes (con clase de datos), lo que acepta como propuesta y sus intenciones.
3
+ import type { SeamContract } from './types'
4
+
5
+ /** Arriba del formulario de DynamicRecordDialog (alta/edición). */
6
+ export const RECORD_DIALOG_HEADER = 'record.dialog.header'
7
+ /** Debajo de los campos del formulario, antes del pie: contenido (no sólo botones) dentro del modal. */
8
+ export const RECORD_FORM_SECTION = 'record.form.section'
9
+ export type RecordFormSeam = typeof RECORD_DIALOG_HEADER | typeof RECORD_FORM_SECTION
10
+
11
+ export interface RecordDialogHeaderLenses {
12
+ /** Modelo del formulario (`Customer`). */
13
+ model: string
14
+ mode: 'create' | 'edit'
15
+ /** Id del registro en edición. */
16
+ recordId?: string
17
+ /** Valores vivos del formulario. Clase `pii`: pueden traer datos personales. */
18
+ values: Record<string, unknown>
19
+ /** Campos del formulario: `{ key, label, type }`. */
20
+ fields: Array<{ key: string; label: string; type?: string }>
21
+ }
22
+
23
+ /**
24
+ * Contrato v1 de `record.dialog.header` y `record.form.section` (mismas lentes y propuestas).
25
+ * `writable` = campos editables que el formulario
26
+ * declara (lo calcula el diálogo). Intenciones:
27
+ * - `record.select` `{ record }`: usar un registro existente en lugar de crear (p. ej. el
28
+ * RFC ya existe). Lo atiende quien abrió el diálogo (CustomerPicker la convierte en selección).
29
+ * - `record.edit` `{ id, patch }`: abrir la edición de otro registro con `patch` como propuesta.
30
+ */
31
+ export function recordDialogHeaderContract(
32
+ writable: ReadonlySet<string>,
33
+ id: RecordFormSeam = RECORD_DIALOG_HEADER,
34
+ ): SeamContract {
35
+ return {
36
+ id,
37
+ version: '1.0.0',
38
+ lenses: { model: 'public', mode: 'public', recordId: 'internal', values: 'pii', fields: 'public' },
39
+ writable,
40
+ intents: ['record.select', 'record.edit'],
41
+ }
42
+ }
@@ -0,0 +1,81 @@
1
+ // Registro en proceso de Parts e injertos. Mismo patrón observable que
2
+ // field-widget-registry / slotStore: Map de módulo + versión para useSyncExternalStore.
3
+ // Cada entrada lleva su addon dueño para soltarla en bloque (unbind del fiber).
4
+ import type { GraftDef, PartDef } from './types'
5
+
6
+ type Listener = () => void
7
+
8
+ const grafts = new Map<string, { def: GraftDef; seq: number }>()
9
+ const parts = new Map<string, PartDef>()
10
+ const listeners = new Set<Listener>()
11
+ let version = 0
12
+ let seq = 0
13
+
14
+ function emit(): void {
15
+ version++
16
+ for (const l of [...listeners]) l()
17
+ }
18
+
19
+ /** Registra (o reemplaza, mismo id) un injerto. Devuelve el disposer. */
20
+ export function registerGraft(def: GraftDef): () => void {
21
+ const entry = { def, seq: ++seq }
22
+ grafts.set(def.id, entry)
23
+ emit()
24
+ return () => {
25
+ if (grafts.get(def.id) === entry) {
26
+ grafts.delete(def.id)
27
+ emit()
28
+ }
29
+ }
30
+ }
31
+
32
+ /** Registra (o reemplaza) un componente expuesto. */
33
+ export function registerPart(def: PartDef): () => void {
34
+ parts.set(def.id, def)
35
+ emit()
36
+ return () => {
37
+ if (parts.get(def.id) === def) {
38
+ parts.delete(def.id)
39
+ emit()
40
+ }
41
+ }
42
+ }
43
+
44
+ export function getPart(id: string): PartDef | undefined {
45
+ return parts.get(id)
46
+ }
47
+
48
+ /** Injertos registrados para un seam, en orden de registro. */
49
+ export function listGrafts(seam?: string): GraftDef[] {
50
+ return [...grafts.values()]
51
+ .filter((e) => !seam || e.def.seam === seam)
52
+ .sort((a, b) => a.seq - b.seq)
53
+ .map((e) => e.def)
54
+ }
55
+
56
+ /** Quita todo lo de un addon (unbind). Devuelve cuántas entradas. */
57
+ export function unregisterLoomByAddon(addon: string): number {
58
+ let n = 0
59
+ for (const [id, e] of [...grafts]) if (e.def.addon === addon) (grafts.delete(id), n++)
60
+ for (const [id, p] of [...parts]) if (p.addon === addon) (parts.delete(id), n++)
61
+ if (n) emit()
62
+ return n
63
+ }
64
+
65
+ export function clearLoom(): void {
66
+ if (!grafts.size && !parts.size) return
67
+ grafts.clear()
68
+ parts.clear()
69
+ emit()
70
+ }
71
+
72
+ export function subscribeLoom(l: Listener): () => void {
73
+ listeners.add(l)
74
+ return () => {
75
+ listeners.delete(l)
76
+ }
77
+ }
78
+
79
+ export function loomVersion(): number {
80
+ return version
81
+ }