@asteby/metacore-runtime-react 52.0.0 → 53.0.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 (101) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/addon-loader.d.ts +22 -1
  3. package/dist/addon-loader.d.ts.map +1 -1
  4. package/dist/addon-loader.js +23 -5
  5. package/dist/addon-page-host.d.ts +80 -0
  6. package/dist/addon-page-host.d.ts.map +1 -0
  7. package/dist/addon-page-host.js +216 -0
  8. package/dist/addon-page-loader.d.ts +40 -0
  9. package/dist/addon-page-loader.d.ts.map +1 -0
  10. package/dist/addon-page-loader.js +87 -0
  11. package/dist/dynamic-view.d.ts +20 -1
  12. package/dist/dynamic-view.d.ts.map +1 -1
  13. package/dist/dynamic-view.js +26 -3
  14. package/dist/federated-error-boundary.d.ts +46 -0
  15. package/dist/federated-error-boundary.d.ts.map +1 -0
  16. package/dist/federated-error-boundary.js +55 -0
  17. package/dist/host-api.d.ts +22 -0
  18. package/dist/host-api.d.ts.map +1 -0
  19. package/dist/host-api.js +113 -0
  20. package/dist/index.d.ts +8 -2
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +12 -2
  23. package/dist/testing.d.ts +42 -0
  24. package/dist/testing.d.ts.map +1 -0
  25. package/dist/testing.js +53 -0
  26. package/dist/types.d.ts +13 -0
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/views/calendar-view.d.ts +23 -0
  29. package/dist/views/calendar-view.d.ts.map +1 -0
  30. package/dist/views/calendar-view.js +138 -0
  31. package/dist/views/chart-view.d.ts +14 -0
  32. package/dist/views/chart-view.d.ts.map +1 -0
  33. package/dist/views/chart-view.js +77 -0
  34. package/dist/views/data-source.d.ts +30 -0
  35. package/dist/views/data-source.d.ts.map +1 -0
  36. package/dist/views/data-source.js +103 -0
  37. package/dist/views/index.d.ts +4 -0
  38. package/dist/views/index.d.ts.map +1 -0
  39. package/dist/views/index.js +2 -0
  40. package/dist/views/map-view.d.ts +39 -0
  41. package/dist/views/map-view.d.ts.map +1 -0
  42. package/dist/views/map-view.js +143 -0
  43. package/dist/views/panels.d.ts +13 -0
  44. package/dist/views/panels.d.ts.map +1 -0
  45. package/dist/views/panels.js +119 -0
  46. package/dist/views/registry.d.ts +46 -0
  47. package/dist/views/registry.d.ts.map +1 -0
  48. package/dist/views/registry.js +139 -0
  49. package/dist/views/skeleton.d.ts +5 -0
  50. package/dist/views/skeleton.d.ts.map +1 -0
  51. package/dist/views/skeleton.js +6 -0
  52. package/dist/views/split-view.d.ts +6 -0
  53. package/dist/views/split-view.d.ts.map +1 -0
  54. package/dist/views/split-view.js +52 -0
  55. package/dist/views/timeline-view.d.ts +25 -0
  56. package/dist/views/timeline-view.d.ts.map +1 -0
  57. package/dist/views/timeline-view.js +130 -0
  58. package/dist/views/types.d.ts +87 -0
  59. package/dist/views/types.d.ts.map +1 -0
  60. package/dist/views/types.js +1 -0
  61. package/dist/widgets/charts.d.ts +9 -0
  62. package/dist/widgets/charts.d.ts.map +1 -0
  63. package/dist/widgets/charts.js +55 -0
  64. package/dist/widgets/lazy-charts.d.ts +10 -0
  65. package/dist/widgets/lazy-charts.d.ts.map +1 -0
  66. package/dist/widgets/lazy-charts.js +30 -0
  67. package/dist/widgets/renderers.d.ts +5 -5
  68. package/dist/widgets/renderers.d.ts.map +1 -1
  69. package/dist/widgets/renderers.js +3 -53
  70. package/dist/widgets/widget-renderer.d.ts.map +1 -1
  71. package/dist/widgets/widget-renderer.js +2 -1
  72. package/package.json +21 -5
  73. package/src/__tests__/addon-page-host.test.tsx +122 -0
  74. package/src/__tests__/addon-page-loader.test.tsx +201 -0
  75. package/src/__tests__/declarative-views.test.tsx +351 -0
  76. package/src/__tests__/host-api.test.ts +87 -0
  77. package/src/__tests__/index-static-graph.test.ts +83 -0
  78. package/src/addon-loader.tsx +51 -8
  79. package/src/addon-page-host.tsx +319 -0
  80. package/src/addon-page-loader.tsx +203 -0
  81. package/src/dynamic-view.tsx +61 -3
  82. package/src/federated-error-boundary.tsx +121 -0
  83. package/src/host-api.ts +143 -0
  84. package/src/index.ts +47 -4
  85. package/src/testing.tsx +108 -0
  86. package/src/types.ts +13 -0
  87. package/src/views/calendar-view.tsx +234 -0
  88. package/src/views/chart-view.tsx +122 -0
  89. package/src/views/data-source.ts +127 -0
  90. package/src/views/index.ts +37 -0
  91. package/src/views/map-view.tsx +217 -0
  92. package/src/views/panels.tsx +177 -0
  93. package/src/views/registry.tsx +202 -0
  94. package/src/views/skeleton.tsx +13 -0
  95. package/src/views/split-view.tsx +115 -0
  96. package/src/views/timeline-view.tsx +229 -0
  97. package/src/views/types.ts +105 -0
  98. package/src/widgets/charts.tsx +225 -0
  99. package/src/widgets/lazy-charts.tsx +51 -0
  100. package/src/widgets/renderers.tsx +5 -210
  101. package/src/widgets/widget-renderer.tsx +6 -4
@@ -0,0 +1,203 @@
1
+ // AddonPageLoader — mounts one `frontend.pages[]` entry of a federated remote.
2
+ //
3
+ // The host has already decided WHERE (embedded `/a/…` or full screen
4
+ // `/addons/…`) and WHETHER (permission) from the manifest; this component
5
+ // downloads the page's expose, verifies the remote entry (SRI), and renders
6
+ // the page inside:
7
+ // FederatedErrorBoundary → a crashing page never takes the shell down
8
+ // AddonPageHost → useHostApi / useHostContext / useAddonNavigate…
9
+ // a sized container → `contain: layout paint` + `isolation: isolate`
10
+ // so the page cannot paint over the host chrome
11
+ //
12
+ // Load failures (network, 404 expose, integrity) are not render errors: they
13
+ // show `errorFallback` (default: the boundary's card) with a retry that
14
+ // re-runs the load. `timeoutMs` turns a hung remote into that same error.
15
+ import { useEffect, useState, type ComponentType, type ReactNode } from 'react'
16
+ import {
17
+ resolvePageModule,
18
+ type AddonHostContext,
19
+ type AddonPageProps,
20
+ type FrontendPage,
21
+ type HostApi,
22
+ } from '@asteby/metacore-sdk'
23
+ import { loadFederatedModule } from './addon-loader'
24
+ import { AddonPageHost, addonSubpath, type AddonPageHostProps, type PageChromeStore } from './addon-page-host'
25
+ import {
26
+ FederatedErrorBoundary,
27
+ type FederatedErrorBoundaryProps,
28
+ type FederatedErrorInfo,
29
+ } from './federated-error-boundary'
30
+
31
+ export interface AddonPageLoaderProps {
32
+ /** Federation container name (`metacore_shipping`). */
33
+ scope: string
34
+ /** remoteEntry.js URL (may carry the `?v=` cache-bust). */
35
+ url: string
36
+ /** `manifest.frontend.integrity`. */
37
+ integrity?: string
38
+ /** Addon key (incidents, data attributes). */
39
+ addonKey: string
40
+ /** The manifest page being mounted. */
41
+ page: FrontendPage
42
+ /** Absolute mount path (`pageMountPath(addonKey, page, frontend.layout)`). */
43
+ basePath: string
44
+ host: AddonHostContext
45
+ api: HostApi
46
+ location: AddonPageHostProps['location']
47
+ navigate: AddonPageHostProps['navigate']
48
+ chrome?: PageChromeStore
49
+ /** Extra route params the host router extracted. */
50
+ params?: Record<string, string>
51
+ /** Shown while the remote downloads (default: page skeleton). */
52
+ fallback?: ReactNode
53
+ /** Abort the load after this many ms (default 10 000; 0 disables). */
54
+ timeoutMs?: number
55
+ /** Load failure or render crash, for telemetry (reportFrontendIncident). */
56
+ onError?: (error: Error, info: FederatedErrorInfo & { phase: 'load' | 'render' }) => void
57
+ /** Override the error UI (load and render). */
58
+ errorFallback?: FederatedErrorBoundaryProps['fallback']
59
+ errorStrings?: FederatedErrorBoundaryProps['strings']
60
+ }
61
+
62
+ type LoadState =
63
+ | { status: 'loading' }
64
+ | { status: 'ready'; Page: ComponentType<AddonPageProps> }
65
+ | { status: 'error'; error: Error }
66
+
67
+ /** Page-sized skeleton: header line + content block, fixed heights (no layout shift). */
68
+ export function AddonPageSkeleton() {
69
+ return (
70
+ <div aria-busy="true" data-testid="addon-page-skeleton" className="flex flex-col gap-4 p-4">
71
+ <div className="h-7 w-56 animate-pulse rounded-md bg-muted" />
72
+ <div className="h-[60vh] w-full animate-pulse rounded-lg bg-muted/70" />
73
+ </div>
74
+ )
75
+ }
76
+
77
+ function withTimeout<T>(p: Promise<T>, ms: number, what: string): Promise<T> {
78
+ if (!ms) return p
79
+ return new Promise<T>((resolve, reject) => {
80
+ const t = setTimeout(() => reject(new Error(`metacore: ${what} did not load within ${ms} ms`)), ms)
81
+ p.then(
82
+ (v) => {
83
+ clearTimeout(t)
84
+ resolve(v)
85
+ },
86
+ (e) => {
87
+ clearTimeout(t)
88
+ reject(e)
89
+ },
90
+ )
91
+ })
92
+ }
93
+
94
+ export function AddonPageLoader({
95
+ scope,
96
+ url,
97
+ integrity,
98
+ addonKey,
99
+ page,
100
+ basePath,
101
+ host,
102
+ api,
103
+ location,
104
+ navigate,
105
+ chrome,
106
+ params,
107
+ fallback,
108
+ timeoutMs = 10_000,
109
+ onError,
110
+ errorFallback,
111
+ errorStrings,
112
+ }: AddonPageLoaderProps) {
113
+ const [state, setState] = useState<LoadState>({ status: 'loading' })
114
+ const [attempt, setAttempt] = useState(0)
115
+
116
+ useEffect(() => {
117
+ let cancelled = false
118
+ setState({ status: 'loading' })
119
+ withTimeout(
120
+ loadFederatedModule(scope, url, page.expose, integrity),
121
+ timeoutMs,
122
+ `page "${page.expose}" of ${addonKey}`,
123
+ )
124
+ .then((mod) => {
125
+ if (cancelled) return
126
+ setState({ status: 'ready', Page: resolvePageModule(mod, page.expose) })
127
+ })
128
+ .catch((e: unknown) => {
129
+ if (cancelled) return
130
+ const error = e instanceof Error ? e : new Error(String(e))
131
+ setState({ status: 'error', error })
132
+ onError?.(error, { addonKey, expose: page.expose, phase: 'load' })
133
+ })
134
+ return () => {
135
+ cancelled = true
136
+ }
137
+ // onError identity is not part of the fiber identity.
138
+ // eslint-disable-next-line react-hooks/exhaustive-deps
139
+ }, [scope, url, page.expose, integrity, addonKey, timeoutMs, attempt])
140
+
141
+ const retry = () => {
142
+ setState({ status: 'loading' })
143
+ setAttempt((n) => n + 1)
144
+ }
145
+ const subpath = addonSubpath(basePath, location.pathname)
146
+
147
+ let body: ReactNode
148
+ if (state.status === 'loading') {
149
+ body = fallback ?? <AddonPageSkeleton />
150
+ } else if (state.status === 'error') {
151
+ // Reuse the boundary's UI for load failures so both look the same.
152
+ body = (
153
+ <FederatedErrorBoundary
154
+ addonKey={addonKey}
155
+ expose={page.expose}
156
+ fallback={errorFallback}
157
+ strings={errorStrings}
158
+ onReset={retry}
159
+ >
160
+ <ThrowError error={state.error} />
161
+ </FederatedErrorBoundary>
162
+ )
163
+ } else {
164
+ const { Page } = state
165
+ body = (
166
+ <FederatedErrorBoundary
167
+ addonKey={addonKey}
168
+ expose={page.expose}
169
+ resetKeys={[url, page.expose]}
170
+ fallback={errorFallback}
171
+ strings={errorStrings}
172
+ onError={(error, info) => onError?.(error, { ...info, phase: 'render' })}
173
+ >
174
+ <Page host={host} basePath={basePath} params={{ ...params, '*': subpath }} page={page} />
175
+ </FederatedErrorBoundary>
176
+ )
177
+ }
178
+
179
+ return (
180
+ <div
181
+ data-addon-page={`${addonKey}:${page.key}`}
182
+ className="relative min-h-0 w-full"
183
+ style={{ contain: 'layout paint', isolation: 'isolate' }}
184
+ >
185
+ <AddonPageHost
186
+ host={host}
187
+ api={api}
188
+ basePath={basePath}
189
+ location={location}
190
+ navigate={navigate}
191
+ chrome={chrome}
192
+ >
193
+ {body}
194
+ </AddonPageHost>
195
+ </div>
196
+ )
197
+ }
198
+
199
+ // Throws the load error during render so the boundary paints it; the
200
+ // boundary's retry (onReset) re-runs the load, not only the render.
201
+ function ThrowError({ error }: { error: Error }): null {
202
+ throw error
203
+ }
@@ -13,12 +13,15 @@
13
13
  // Both child components fetch their own metadata (cache-backed), so the extra
14
14
  // read this wrapper does to learn `view_type` is served from the same cache —
15
15
  // no duplicate network round-trip in practice.
16
- import { useEffect, useState } from 'react'
16
+ import { useEffect, useMemo, useState } from 'react'
17
17
  import { useApi } from './api-context'
18
18
  import { useMetadataCache } from './metadata-cache'
19
19
  import { DynamicTable, type DynamicTableProps } from './dynamic-table'
20
20
  import { DynamicKanban, type DynamicKanbanProps } from './dynamic-kanban'
21
21
  import type { TableMetadata, ApiResponse } from './types'
22
+ import { DeclarativeView, isDeclarativeViewType } from './views/registry'
23
+ import { createApiViewDataSource } from './views/data-source'
24
+ import type { ViewDataSource } from './views/types'
22
25
 
23
26
  /**
24
27
  * Pure routing decision: which renderer a `view_type` maps onto. Exported so a
@@ -30,6 +33,23 @@ export function resolveViewRenderer(
30
33
  return viewType === 'kanban' ? 'kanban' : 'table'
31
34
  }
32
35
 
36
+ /**
37
+ * Full routing decision including the declarative views: `'declarative'`
38
+ * when the type is map/timeline/calendar/chart/split AND the metadata carries
39
+ * its `view` block; otherwise the same table/kanban rule as
40
+ * {@link resolveViewRenderer} (a host that does not serve `view` keeps the
41
+ * table, exactly like before).
42
+ */
43
+ export function resolveViewKind(
44
+ viewType: string | undefined,
45
+ meta: Pick<TableMetadata, 'view'> | null | undefined,
46
+ ): 'declarative' | 'kanban' | 'table' {
47
+ if (isDeclarativeViewType(viewType) && meta?.view && (meta.view as Record<string, unknown>)[viewType]) {
48
+ return 'declarative'
49
+ }
50
+ return resolveViewRenderer(viewType)
51
+ }
52
+
33
53
  /**
34
54
  * Reads the `view` selector out of a URL search string (`?view=kanban`, a bare
35
55
  * `view=kanban`, or a full href). Returns `undefined` when absent. The query is
@@ -76,14 +96,32 @@ export interface DynamicViewProps extends DynamicTableProps {
76
96
  * kanban-only extras (e.g. `onCardClick`, `pageSize`).
77
97
  */
78
98
  kanbanProps?: Partial<Omit<DynamicKanbanProps, 'model' | 'endpoint'>>
99
+ /**
100
+ * Data source for declarative views (map/timeline/calendar/chart/split).
101
+ * Default: {@link createApiViewDataSource} over the injected ApiClient.
102
+ */
103
+ viewDataSource?: ViewDataSource
104
+ /** Open a record from a declarative view (host detail route or drawer). */
105
+ onOpenRecord?: (row: Record<string, unknown>) => void
106
+ /** BCP-47 locale for declarative views. */
107
+ locale?: string
79
108
  }
80
109
 
81
- export function DynamicView({ view, kanbanProps, ...tableProps }: DynamicViewProps) {
110
+ export function DynamicView({
111
+ view,
112
+ kanbanProps,
113
+ viewDataSource,
114
+ onOpenRecord,
115
+ locale,
116
+ ...tableProps
117
+ }: DynamicViewProps) {
82
118
  const { model, endpoint, refreshTrigger, timeZone, currency } = tableProps
83
119
  const api = useApi()
84
120
  const cached = useMetadataCache((s) => s.getMetadata(model))
85
121
  const setMeta = useMetadataCache((s) => s.setMetadata)
86
122
  const [viewType, setViewType] = useState<string | undefined>(cached?.view_type)
123
+ const [meta, setMetaState] = useState<TableMetadata | null>(cached ?? null)
124
+ const dataSource = useMemo(() => viewDataSource ?? createApiViewDataSource(api), [viewDataSource, api])
87
125
  const [resolved, setResolved] = useState<boolean>(!!cached)
88
126
 
89
127
  useEffect(() => {
@@ -91,6 +129,7 @@ export function DynamicView({ view, kanbanProps, ...tableProps }: DynamicViewPro
91
129
  const c = useMetadataCache.getState().getMetadata(model)
92
130
  if (c) {
93
131
  setViewType(c.view_type)
132
+ setMetaState(c)
94
133
  setResolved(true)
95
134
  }
96
135
  api
@@ -101,6 +140,7 @@ export function DynamicView({ view, kanbanProps, ...tableProps }: DynamicViewPro
101
140
  const meta = body?.success ? body.data : (res.data as TableMetadata)
102
141
  if (meta) {
103
142
  setViewType(meta.view_type)
143
+ setMetaState(meta)
104
144
  setMeta(model, meta)
105
145
  }
106
146
  })
@@ -129,7 +169,25 @@ export function DynamicView({ view, kanbanProps, ...tableProps }: DynamicViewPro
129
169
  if (!resolved && !cached && view === undefined && !readViewFromSearch(search))
130
170
  return null
131
171
 
132
- if (resolveViewRenderer(effectiveView) === 'kanban') {
172
+ const kind = resolveViewKind(effectiveView, meta)
173
+ if (kind === 'declarative' && effectiveView) {
174
+ return (
175
+ <DeclarativeView
176
+ viewType={effectiveView}
177
+ view={meta?.view}
178
+ model={model}
179
+ metadata={meta}
180
+ data={dataSource}
181
+ onOpenRecord={onOpenRecord}
182
+ locale={locale}
183
+ currency={currency}
184
+ timeZone={timeZone}
185
+ fallback={<DynamicTable {...tableProps} />}
186
+ />
187
+ )
188
+ }
189
+
190
+ if (kind === 'kanban') {
133
191
  return (
134
192
  <DynamicKanban
135
193
  model={model}
@@ -0,0 +1,121 @@
1
+ // FederatedErrorBoundary — isolates a federated remote (page, panel, widget,
2
+ // register() fiber children) from the host shell. A render error inside the
3
+ // remote paints a contained error card with "Reintentar"; the sidebar, header
4
+ // and every other addon keep working. The host reports the incident through
5
+ // `onError` (ops: reportFrontendIncident) — the boundary itself never logs to
6
+ // the network.
7
+ import { Component, type ErrorInfo, type ReactNode } from 'react'
8
+ import { AlertTriangle, RotateCcw } from 'lucide-react'
9
+ import { Button } from '@asteby/metacore-ui/primitives'
10
+
11
+ export interface FederatedErrorInfo {
12
+ /** Addon key (or remote scope) that failed. */
13
+ addonKey?: string
14
+ /** Exposed module that failed (`./pages/control-tower`). */
15
+ expose?: string
16
+ componentStack?: string | null
17
+ }
18
+
19
+ export interface FederatedErrorFallbackProps {
20
+ error: Error
21
+ reset: () => void
22
+ addonKey?: string
23
+ }
24
+
25
+ export interface FederatedErrorBoundaryProps {
26
+ addonKey?: string
27
+ expose?: string
28
+ /** Report the failure (telemetry / incident). Called once per error. */
29
+ onError?: (error: Error, info: FederatedErrorInfo) => void
30
+ /** Custom fallback. Default: contained card with the message and a retry button. */
31
+ fallback?: (props: FederatedErrorFallbackProps) => ReactNode
32
+ /** Changing any of these clears the error (e.g. a new `?v=` remote URL). */
33
+ resetKeys?: readonly unknown[]
34
+ /** Called after the user (or a resetKeys change) clears the error. */
35
+ onReset?: () => void
36
+ /** Copy for the default fallback. */
37
+ strings?: Partial<FederatedErrorStrings>
38
+ children?: ReactNode
39
+ }
40
+
41
+ export interface FederatedErrorStrings {
42
+ title: string
43
+ description: string
44
+ retry: string
45
+ }
46
+
47
+ const DEFAULT_STRINGS: FederatedErrorStrings = {
48
+ title: 'Esta sección no se pudo mostrar',
49
+ description: 'El resto de la aplicación sigue funcionando. Puedes reintentar.',
50
+ retry: 'Reintentar',
51
+ }
52
+
53
+ interface State {
54
+ error: Error | null
55
+ }
56
+
57
+ function changed(a: readonly unknown[] = [], b: readonly unknown[] = []): boolean {
58
+ return a.length !== b.length || a.some((v, i) => !Object.is(v, b[i]))
59
+ }
60
+
61
+ export class FederatedErrorBoundary extends Component<FederatedErrorBoundaryProps, State> {
62
+ state: State = { error: null }
63
+
64
+ static getDerivedStateFromError(error: unknown): State {
65
+ return { error: error instanceof Error ? error : new Error(String(error)) }
66
+ }
67
+
68
+ componentDidCatch(error: unknown, info: ErrorInfo): void {
69
+ const err = error instanceof Error ? error : new Error(String(error))
70
+ try {
71
+ this.props.onError?.(err, {
72
+ addonKey: this.props.addonKey,
73
+ expose: this.props.expose,
74
+ componentStack: info.componentStack,
75
+ })
76
+ } catch {
77
+ /* a failing reporter must not take the shell down */
78
+ }
79
+ }
80
+
81
+ componentDidUpdate(prev: FederatedErrorBoundaryProps): void {
82
+ if (this.state.error && changed(prev.resetKeys, this.props.resetKeys)) this.reset()
83
+ }
84
+
85
+ reset = (): void => {
86
+ this.setState({ error: null })
87
+ this.props.onReset?.()
88
+ }
89
+
90
+ render(): ReactNode {
91
+ const { error } = this.state
92
+ if (!error) return this.props.children
93
+ if (this.props.fallback) {
94
+ return this.props.fallback({ error, reset: this.reset, addonKey: this.props.addonKey })
95
+ }
96
+ const s = { ...DEFAULT_STRINGS, ...this.props.strings }
97
+ return (
98
+ <div
99
+ role="alert"
100
+ data-testid="federated-error"
101
+ data-addon={this.props.addonKey}
102
+ className="flex min-h-[12rem] flex-col items-center justify-center gap-3 rounded-lg border border-destructive/30 bg-destructive/5 p-6 text-center"
103
+ >
104
+ <AlertTriangle aria-hidden className="h-6 w-6 text-destructive" />
105
+ <div className="space-y-1">
106
+ <p className="text-sm font-medium text-foreground">{s.title}</p>
107
+ <p className="text-xs text-muted-foreground">{s.description}</p>
108
+ {error.message ? (
109
+ <p className="max-w-md break-words font-mono text-[11px] text-muted-foreground/80">
110
+ {error.message}
111
+ </p>
112
+ ) : null}
113
+ </div>
114
+ <Button size="sm" variant="outline" onClick={this.reset}>
115
+ <RotateCcw aria-hidden className="mr-1.5 h-3.5 w-3.5" />
116
+ {s.retry}
117
+ </Button>
118
+ </div>
119
+ )
120
+ }
121
+ }
@@ -0,0 +1,143 @@
1
+ // createHostApi — the HostApi a host hands to federated pages and panels.
2
+ //
3
+ // Built on the host's own authenticated ApiClient (axios-like). The wrapper is
4
+ // the security boundary between the host transport and remote code:
5
+ // - every method resolves to the response BODY only — never the axios
6
+ // response, whose `config.headers` carries the bearer token;
7
+ // - every failure is re-thrown as a HostApiError with status, server message
8
+ // and server body only — never the axios error, whose `config` and
9
+ // `request` carry the same headers;
10
+ // - the remote can address any API path the operator could (the kernel
11
+ // enforces permissions server-side), but it cannot read or replace the
12
+ // credentials the host attaches.
13
+ import { HostApiError } from '@asteby/metacore-sdk'
14
+ import type {
15
+ HostApi,
16
+ HostApiRequestOptions,
17
+ HostQueryPart,
18
+ } from '@asteby/metacore-sdk'
19
+ import type { ApiClient } from './api-context'
20
+ import { batchGet } from './query-batch'
21
+
22
+ export interface CreateHostApiOptions {
23
+ /**
24
+ * Endpoint the host serves capability queries on (`POST`, body
25
+ * `{ capability, input }`, response = the contract's output). The host runs
26
+ * the query with the viewer's permissions. Default `/capabilities/query`.
27
+ */
28
+ capabilityPath?: string
29
+ /**
30
+ * Group `get()` reads into `POST /q` like runtime-react's own reads.
31
+ * Default `false`: remote reads go straight to their GET; `q()` always
32
+ * batches.
33
+ */
34
+ batchGets?: boolean
35
+ }
36
+
37
+ type AxiosLikeError = {
38
+ message?: string
39
+ response?: { status?: number; data?: unknown }
40
+ status?: number
41
+ }
42
+
43
+ function errorMessage(data: unknown, fallback: string): string {
44
+ if (data && typeof data === 'object') {
45
+ const d = data as Record<string, unknown>
46
+ for (const k of ['message', 'error', 'detail']) {
47
+ if (typeof d[k] === 'string' && d[k]) return d[k] as string
48
+ }
49
+ }
50
+ return fallback
51
+ }
52
+
53
+ /** Strip transport details from any error before it reaches remote code. */
54
+ export function toHostApiError(e: unknown): HostApiError {
55
+ if (e instanceof HostApiError) return e
56
+ const err = (e ?? {}) as AxiosLikeError
57
+ const status = err.response?.status ?? err.status ?? 0
58
+ const data = err.response?.data
59
+ const message = errorMessage(data, status ? `Request failed with status ${status}` : 'Network error')
60
+ const code =
61
+ data && typeof data === 'object' && typeof (data as { code?: unknown }).code === 'string'
62
+ ? ((data as { code: string }).code)
63
+ : undefined
64
+ return new HostApiError(message, status, { code, data: safeData(data) })
65
+ }
66
+
67
+ // Server bodies are JSON the operator could already see; anything else
68
+ // (functions, DOM nodes, a Request) is dropped.
69
+ function safeData(data: unknown): unknown {
70
+ if (data === null || data === undefined) return undefined
71
+ if (typeof data !== 'object') return data
72
+ try {
73
+ return JSON.parse(JSON.stringify(data))
74
+ } catch {
75
+ return undefined
76
+ }
77
+ }
78
+
79
+ function toConfig(opts?: HostApiRequestOptions): Record<string, unknown> | undefined {
80
+ if (!opts) return undefined
81
+ const config: Record<string, unknown> = {}
82
+ if (opts.params) config.params = opts.params
83
+ if (opts.signal) config.signal = opts.signal
84
+ return config
85
+ }
86
+
87
+ async function bodyOf<T>(p: Promise<{ data: unknown }>): Promise<T> {
88
+ try {
89
+ const res = await p
90
+ return res.data as T
91
+ } catch (e) {
92
+ throw toHostApiError(e)
93
+ }
94
+ }
95
+
96
+ /** Build the remote-facing {@link HostApi} over the host's ApiClient. */
97
+ export function createHostApi(client: ApiClient, options: CreateHostApiOptions = {}): HostApi {
98
+ const capabilityPath = options.capabilityPath ?? '/capabilities/query'
99
+ const withConfig = <A extends unknown[]>(args: A, opts?: HostApiRequestOptions) => {
100
+ const config = toConfig(opts)
101
+ return config ? ([...args, config] as unknown[]) : (args as unknown[])
102
+ }
103
+ const patch = (client as ApiClient & {
104
+ patch?: (url: string, body?: unknown, config?: unknown) => Promise<{ data: unknown }>
105
+ }).patch
106
+ return Object.freeze({
107
+ get: <T,>(path: string, opts?: HostApiRequestOptions) => {
108
+ const args = withConfig([path], opts) as [string, { params?: Record<string, unknown> }?]
109
+ return bodyOf<T>(options.batchGets ? batchGet(client, ...args) : client.get(...args))
110
+ },
111
+ post: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) =>
112
+ bodyOf<T>(client.post(...(withConfig([path, body], opts) as [string, unknown, unknown?]))),
113
+ put: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) =>
114
+ bodyOf<T>(client.put(...(withConfig([path, body], opts) as [string, unknown, unknown?]))),
115
+ patch: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) => {
116
+ if (typeof patch !== 'function') {
117
+ return Promise.reject(new HostApiError('PATCH is not supported by this host', 0))
118
+ }
119
+ return bodyOf<T>(patch.call(client, ...(withConfig([path, body], opts) as [string, unknown, unknown?])))
120
+ },
121
+ delete: <T,>(path: string, opts?: HostApiRequestOptions) =>
122
+ bodyOf<T>(client.delete(...(withConfig([path], opts) as [string, unknown?]))),
123
+ q: async <T,>(path: string, opts?: Pick<HostApiRequestOptions, 'params'>): Promise<HostQueryPart<T>> => {
124
+ try {
125
+ const url = path.startsWith('/') ? path : `/${path}`
126
+ const res = await (opts?.params
127
+ ? batchGet(client, url, { params: opts.params as Record<string, unknown> })
128
+ : batchGet(client, url))
129
+ const body = res.data as { success?: boolean; data?: T; meta?: unknown; message?: string }
130
+ return {
131
+ success: body?.success !== false,
132
+ data: body?.data as T,
133
+ meta: body?.meta,
134
+ message: body?.message,
135
+ }
136
+ } catch (e) {
137
+ throw toHostApiError(e)
138
+ }
139
+ },
140
+ capability: <T,>(key: string, input: Record<string, unknown>) =>
141
+ bodyOf<T>(client.post(capabilityPath, { capability: key, input })),
142
+ }) as HostApi
143
+ }
package/src/index.ts CHANGED
@@ -129,6 +129,7 @@ export {
129
129
  export {
130
130
  DynamicView,
131
131
  resolveViewRenderer,
132
+ resolveViewKind,
132
133
  readViewFromSearch,
133
134
  resolveActiveView,
134
135
  type DynamicViewProps,
@@ -234,6 +235,43 @@ export {
234
235
  } from './cfdi-stamp-panel'
235
236
  export { useRecordMutationTick } from './use-record-mutation-tick'
236
237
  export * from './addon-loader'
238
+ // Federated pages (frontend.pages[]): host-side loader + remote-facing hooks.
239
+ export {
240
+ AddonPageLoader,
241
+ AddonPageSkeleton,
242
+ type AddonPageLoaderProps,
243
+ } from './addon-page-loader'
244
+ export {
245
+ AddonPageHost,
246
+ createPageChromeStore,
247
+ usePageChromeState,
248
+ useHostContext,
249
+ useHostApi,
250
+ useAddonNavigate,
251
+ useAddonLocation,
252
+ useAddonSearchParams,
253
+ useBreadcrumbs,
254
+ usePageChrome,
255
+ useIsInAddonPage,
256
+ resolveAddonPath,
257
+ addonSubpath,
258
+ type AddonPageHostProps,
259
+ type AddonPageHostValue,
260
+ type AddonPageLocation,
261
+ type AddonNavigateOptions,
262
+ type PageChromeState,
263
+ type PageChromeStore,
264
+ } from './addon-page-host'
265
+ export { createHostApi, toHostApiError, type CreateHostApiOptions } from './host-api'
266
+ export {
267
+ FederatedErrorBoundary,
268
+ type FederatedErrorBoundaryProps,
269
+ type FederatedErrorFallbackProps,
270
+ type FederatedErrorInfo,
271
+ type FederatedErrorStrings,
272
+ } from './federated-error-boundary'
273
+ // Declarative views & detail panels: registry + lazy renderers by type.
274
+ export * from './views'
237
275
  export {
238
276
  PURGE_ADDON_MESSAGE,
239
277
  isAddonFrontendCacheUrl,
@@ -701,15 +739,20 @@ export type {
701
739
  } from './dashboard-types'
702
740
  export {
703
741
  StatWidget,
742
+ ListWidget,
743
+ ProgressWidget,
744
+ type WidgetRenderProps,
745
+ } from './widgets/renderers'
746
+ // recharts-backed widgets: lazy facades, recharts stays out of the index graph.
747
+ // The eager components are at '@asteby/metacore-runtime-react/charts'.
748
+ export {
704
749
  BarWidget,
705
750
  LineWidget,
706
751
  AreaWidget,
707
752
  PieWidget,
708
753
  DonutWidget,
709
- ListWidget,
710
- ProgressWidget,
711
- type WidgetRenderProps,
712
- } from './widgets/renderers'
754
+ preloadWidgetCharts,
755
+ } from './widgets/lazy-charts'
713
756
  export {
714
757
  WidgetRenderer,
715
758
  WidgetSkeleton,