@xemahq/ui-kernel 0.11.1 → 0.11.2

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 (234) hide show
  1. package/package.json +1 -2
  2. package/src/index.ts +0 -17
  3. package/src/lib/biome-host/agent-validation.ts +0 -239
  4. package/src/lib/biome-host/biome-builders.ts +0 -112
  5. package/src/lib/biome-host/biome-mode.ts +0 -6
  6. package/src/lib/biome-host/biome-navigation.ts +0 -37
  7. package/src/lib/biome-host/biome-registry.ts +0 -299
  8. package/src/lib/biome-host/biome-scope-hooks.ts +0 -41
  9. package/src/lib/biome-host/biome-scope.tsx +0 -52
  10. package/src/lib/biome-host/biome-scoped-query.ts +0 -134
  11. package/src/lib/biome-host/create-biome-orval-config.ts +0 -82
  12. package/src/lib/biome-host/define-web-biome.spec.ts +0 -221
  13. package/src/lib/biome-host/define-web-biome.ts +0 -222
  14. package/src/lib/biome-host/errors.ts +0 -220
  15. package/src/lib/biome-host/frontend-biome.ts +0 -256
  16. package/src/lib/biome-host/host-bridge.ts +0 -281
  17. package/src/lib/biome-host/host-sources.ts +0 -54
  18. package/src/lib/biome-host/i18n-hooks.ts +0 -51
  19. package/src/lib/biome-host/i18n-port.test.ts +0 -50
  20. package/src/lib/biome-host/i18n-port.ts +0 -96
  21. package/src/lib/biome-host/index.ts +0 -35
  22. package/src/lib/biome-host/realtime-hooks.ts +0 -75
  23. package/src/lib/biome-host/realtime-port.ts +0 -115
  24. package/src/lib/biome-host/session-contributions.ts +0 -296
  25. package/src/lib/biome-host/use-mutation-with-error-toast.ts +0 -90
  26. package/src/lib/biome-host/use-page-state.ts +0 -248
  27. package/src/lib/capabilities/capability-context.ts +0 -25
  28. package/src/lib/capabilities/capability-provider.tsx +0 -73
  29. package/src/lib/capabilities/index.ts +0 -17
  30. package/src/lib/capabilities/types.ts +0 -69
  31. package/src/lib/capabilities/use-capability.ts +0 -79
  32. package/src/lib/contribution-registry/contribution-registry.spec.ts +0 -141
  33. package/src/lib/contribution-registry/contribution-registry.ts +0 -204
  34. package/src/lib/contribution-registry/index.ts +0 -9
  35. package/src/lib/contribution-registry/renderable-registry.ts +0 -142
  36. package/src/lib/system-bus/capability-invoke.ts +0 -92
  37. package/src/lib/system-bus/deeplink.ts +0 -210
  38. package/src/lib/system-bus/enums.ts +0 -86
  39. package/src/lib/system-bus/host-ports.ts +0 -93
  40. package/src/lib/system-bus/index.ts +0 -16
  41. package/src/lib/system-bus/intent-registry.ts +0 -109
  42. package/src/lib/system-bus/intents.ts +0 -113
  43. package/src/lib/system-bus/palette.ts +0 -78
  44. package/src/lib/system-bus/system-bus-builder.ts +0 -159
  45. package/src/lib/system-bus/system-bus.ts +0 -37
  46. package/src/lib/system-bus/windows.ts +0 -51
  47. package/src/offline/id.ts +0 -16
  48. package/src/offline/index.ts +0 -54
  49. package/src/offline/mutation.ts +0 -75
  50. package/src/offline/offline-status-badge.tsx +0 -51
  51. package/src/offline/online-controller.ts +0 -105
  52. package/src/offline/outbox.test.ts +0 -172
  53. package/src/offline/outbox.ts +0 -348
  54. package/src/offline/react-hooks.ts +0 -40
  55. package/src/offline/react.tsx +0 -32
  56. package/src/offline/storage.ts +0 -112
  57. package/src/offline/types.ts +0 -77
  58. package/src/org-db/components/DbResultTable.tsx +0 -176
  59. package/src/org-db/index.ts +0 -1
  60. package/src/pdf/index.ts +0 -11
  61. package/src/registry/index.ts +0 -9
  62. package/src/registry/lib/agent-validation-host.ts +0 -36
  63. package/src/registry/lib/biome-slot.tsx +0 -50
  64. package/src/registry/lib/biomes-enabled-context.ts +0 -20
  65. package/src/registry/lib/extension-points.ts +0 -134
  66. package/src/registry/lib/primitives/SessionEventCard.tsx +0 -164
  67. package/src/registry/lib/primitives/SessionEventTimeline.tsx +0 -95
  68. package/src/registry/lib/primitives/SessionMutationBar.tsx +0 -76
  69. package/src/registry/lib/primitives/SessionTabbedDrawer.tsx +0 -165
  70. package/src/registry/lib/primitives/index.ts +0 -18
  71. package/src/registry/lib/session-context-builder.ts +0 -84
  72. package/src/registry/lib/session-context-provider.tsx +0 -33
  73. package/src/registry/lib/session-context.ts +0 -21
  74. package/src/registry/lib/session-selectors.ts +0 -272
  75. package/src/session/comments/CommentRail.tsx +0 -164
  76. package/src/session/index.ts +0 -3
  77. package/src/session/lib/cn.ts +0 -11
  78. package/src/session/shell/SessionWorkspaceShell.tsx +0 -147
  79. package/src/session-kit/approvals/ApprovalButton.tsx +0 -89
  80. package/src/session-kit/approvals/ApprovalCard.tsx +0 -341
  81. package/src/session-kit/approvals/ApprovalsCenter.tsx +0 -336
  82. package/src/session-kit/approvals/CapabilityApprovalStickyBar.tsx +0 -118
  83. package/src/session-kit/approvals/Obligation.tsx +0 -111
  84. package/src/session-kit/approvals/ScopedBody.tsx +0 -392
  85. package/src/session-kit/approvals/approval-icons.ts +0 -31
  86. package/src/session-kit/approvals/approval-model.ts +0 -204
  87. package/src/session-kit/approvals/index.ts +0 -22
  88. package/src/session-kit/approvals/obligation-display.ts +0 -100
  89. package/src/session-kit/approvals/risk-accent.ts +0 -47
  90. package/src/session-kit/approvals/scope-icons.ts +0 -19
  91. package/src/session-kit/combobox/Combobox.tsx +0 -358
  92. package/src/session-kit/combobox/use-click-outside.ts +0 -21
  93. package/src/session-kit/display/ContextHeader.tsx +0 -148
  94. package/src/session-kit/display/FileDiffCard.tsx +0 -140
  95. package/src/session-kit/display/MD.tsx +0 -162
  96. package/src/session-kit/display/MessageTurn.tsx +0 -157
  97. package/src/session-kit/display/ThinkingPanel.tsx +0 -81
  98. package/src/session-kit/display/TodoChecklist.tsx +0 -120
  99. package/src/session-kit/display/TokenMeter.tsx +0 -89
  100. package/src/session-kit/display/ToolStrip.tsx +0 -278
  101. package/src/session-kit/display/TypingDots.tsx +0 -24
  102. package/src/session-kit/index.ts +0 -44
  103. package/src/session-kit/lib/enums.ts +0 -66
  104. package/src/session-kit/lib/portal-accent.ts +0 -30
  105. package/src/session-kit/lib/status-dot.ts +0 -68
  106. package/src/session-kit/primitives/Avatar.tsx +0 -44
  107. package/src/session-kit/primitives/PortalGlyph.tsx +0 -51
  108. package/src/session-kit/primitives/RiskPill.tsx +0 -95
  109. package/src/session-kit/primitives/ScopeDot.tsx +0 -47
  110. package/src/session-kit/primitives/Segmented.tsx +0 -71
  111. package/src/ui/branding/app-branding-context.ts +0 -20
  112. package/src/ui/branding/app-branding-provider.tsx +0 -123
  113. package/src/ui/branding/sanitize.ts +0 -89
  114. package/src/ui/breakpoints.ts +0 -14
  115. package/src/ui/capture/document-preview.tsx +0 -166
  116. package/src/ui/capture/field-spec-to-zod.test.ts +0 -81
  117. package/src/ui/capture/field-spec-to-zod.ts +0 -174
  118. package/src/ui/capture/field-spec-validate.ts +0 -236
  119. package/src/ui/capture/field-spec.test.ts +0 -49
  120. package/src/ui/capture/field-spec.ts +0 -274
  121. package/src/ui/capture/index.ts +0 -51
  122. package/src/ui/capture/schema-field-input.tsx +0 -620
  123. package/src/ui/capture/schema-form.tsx +0 -149
  124. package/src/ui/capture/submit-values.test.ts +0 -70
  125. package/src/ui/capture/submit-values.ts +0 -63
  126. package/src/ui/capture/use-prefill.ts +0 -186
  127. package/src/ui/capture/use-schema-validation.ts +0 -145
  128. package/src/ui/capture/use-wizard.ts +0 -180
  129. package/src/ui/capture/value-format.ts +0 -32
  130. package/src/ui/capture/wizard.tsx +0 -105
  131. package/src/ui/charts/bar-chart.tsx +0 -139
  132. package/src/ui/charts/chart-frame.tsx +0 -125
  133. package/src/ui/charts/chart-types.ts +0 -52
  134. package/src/ui/charts/chart-utils.ts +0 -190
  135. package/src/ui/charts/charts.test.tsx +0 -204
  136. package/src/ui/charts/donut-chart.tsx +0 -129
  137. package/src/ui/charts/index.ts +0 -27
  138. package/src/ui/charts/line-chart.tsx +0 -202
  139. package/src/ui/charts/sparkline.tsx +0 -109
  140. package/src/ui/chrome/AsyncBoundary.tsx +0 -74
  141. package/src/ui/chrome/EmptyState.tsx +0 -257
  142. package/src/ui/chrome/ErrorCard.tsx +0 -63
  143. package/src/ui/chrome/LoadingState.tsx +0 -61
  144. package/src/ui/chrome/PageHeader.tsx +0 -137
  145. package/src/ui/chrome/RecordCardList.tsx +0 -98
  146. package/src/ui/chrome/StateCard.tsx +0 -150
  147. package/src/ui/chrome/confirm-delete-dialog.tsx +0 -59
  148. package/src/ui/chrome/page-shell.spec.tsx +0 -117
  149. package/src/ui/chrome/page-shell.tsx +0 -221
  150. package/src/ui/chrome/scope-badge.tsx +0 -40
  151. package/src/ui/chrome/status-badge.tsx +0 -79
  152. package/src/ui/cn.ts +0 -32
  153. package/src/ui/design-tokens.ts +0 -372
  154. package/src/ui/hooks/use-debounced-value.ts +0 -16
  155. package/src/ui/hooks/use-is-mobile.ts +0 -28
  156. package/src/ui/index.ts +0 -110
  157. package/src/ui/pdf/pdf-preview.tsx +0 -122
  158. package/src/ui/primitives/alert-dialog.tsx +0 -104
  159. package/src/ui/primitives/async-combobox.tsx +0 -182
  160. package/src/ui/primitives/badge-variants.ts +0 -21
  161. package/src/ui/primitives/badge.tsx +0 -25
  162. package/src/ui/primitives/button-variants.ts +0 -31
  163. package/src/ui/primitives/button.tsx +0 -29
  164. package/src/ui/primitives/card.tsx +0 -43
  165. package/src/ui/primitives/checkbox.tsx +0 -26
  166. package/src/ui/primitives/collapsible.tsx +0 -9
  167. package/src/ui/primitives/dialog.tsx +0 -103
  168. package/src/ui/primitives/dropdown-menu.tsx +0 -179
  169. package/src/ui/primitives/form-stepper.tsx +0 -94
  170. package/src/ui/primitives/form-stepper.types.ts +0 -15
  171. package/src/ui/primitives/input.tsx +0 -22
  172. package/src/ui/primitives/label.tsx +0 -17
  173. package/src/ui/primitives/overflow-tabs.tsx +0 -331
  174. package/src/ui/primitives/popover.tsx +0 -33
  175. package/src/ui/primitives/preview-device-frame.tsx +0 -213
  176. package/src/ui/primitives/radio-group.tsx +0 -36
  177. package/src/ui/primitives/resizable.tsx +0 -67
  178. package/src/ui/primitives/scroll-area.tsx +0 -38
  179. package/src/ui/primitives/select.tsx +0 -143
  180. package/src/ui/primitives/separator.tsx +0 -20
  181. package/src/ui/primitives/sheet.tsx +0 -107
  182. package/src/ui/primitives/skeleton.tsx +0 -99
  183. package/src/ui/primitives/switch.tsx +0 -27
  184. package/src/ui/primitives/table.tsx +0 -72
  185. package/src/ui/primitives/tabs.tsx +0 -53
  186. package/src/ui/primitives/tag-multi-select.tsx +0 -261
  187. package/src/ui/primitives/textarea.tsx +0 -21
  188. package/src/ui/primitives/tooltip.tsx +0 -30
  189. package/src/ui/primitives/url-preview-chrome.tsx +0 -103
  190. package/src/vista/GenericCatalogueSurface.tsx +0 -179
  191. package/src/vista/SurfaceFallbackCard.tsx +0 -109
  192. package/src/vista/VistaPanel.tsx +0 -163
  193. package/src/vista/form-payload.spec.ts +0 -139
  194. package/src/vista/html/CustomUiFrame.spec.tsx +0 -127
  195. package/src/vista/html/CustomUiFrame.tsx +0 -206
  196. package/src/vista/html/custom-ui-frame-bridge.spec.ts +0 -191
  197. package/src/vista/html/custom-ui-frame-bridge.ts +0 -98
  198. package/src/vista/html/custom-ui-frame-contract.ts +0 -88
  199. package/src/vista/html/custom-ui-intents.spec.ts +0 -135
  200. package/src/vista/html/custom-ui-intents.ts +0 -155
  201. package/src/vista/html/custom-ui-srcdoc.spec.ts +0 -151
  202. package/src/vista/html/custom-ui-srcdoc.ts +0 -193
  203. package/src/vista/html/index.ts +0 -13
  204. package/src/vista/index.ts +0 -52
  205. package/src/vista/surface-catalogue.spec.ts +0 -140
  206. package/src/vista/surface-catalogue.ts +0 -90
  207. package/src/vista/surface-icons.ts +0 -57
  208. package/src/vista/surface-registry.ts +0 -56
  209. package/src/vista/surfaces/ChartSurface.tsx +0 -34
  210. package/src/vista/surfaces/FilesSurface.tsx +0 -202
  211. package/src/vista/surfaces/FormSurface.tsx +0 -380
  212. package/src/vista/surfaces/HtmlSurface.tsx +0 -43
  213. package/src/vista/surfaces/TableSurface.tsx +0 -100
  214. package/src/vista/surfaces/UrlSurface.tsx +0 -40
  215. package/src/vista/surfaces/blob-surfaces.tsx +0 -139
  216. package/src/vista/surfaces/elicitation-transport.spec.ts +0 -369
  217. package/src/vista/surfaces/elicitation-transport.ts +0 -367
  218. package/src/vista/surfaces/file-surface-utils.ts +0 -69
  219. package/src/vista/surfaces/index.ts +0 -24
  220. package/src/vista/surfaces/register-surfaces.tsx +0 -139
  221. package/src/vista/surfaces/text-surfaces.tsx +0 -132
  222. package/src/vista/use-vista-tabs.ts +0 -196
  223. package/src/vista/vista-code-renderer-context.ts +0 -16
  224. package/src/vista/vista-code-renderer.tsx +0 -35
  225. package/src/vista/vista-file-context.ts +0 -14
  226. package/src/vista/vista-file-source.tsx +0 -141
  227. package/src/vista/vista-form-context.ts +0 -20
  228. package/src/vista/vista-form-host.tsx +0 -48
  229. package/src/vista/vista-model.ts +0 -137
  230. package/src/vista/vista-open-context.tsx +0 -27
  231. package/src/vista/vista-open-state.ts +0 -11
  232. package/src/vista/vista-payloads.ts +0 -635
  233. package/src/vista/vista-tabs-manifest.ts +0 -138
  234. package/src/vista/vista-tools.ts +0 -232
@@ -1,149 +0,0 @@
1
- // ═══════════════════════════════════════════════════════════════════════════
2
- // <SchemaForm> — the ONE kernel schema→form renderer
3
- //
4
- // Consolidates the three parallel schema→form implementations (app-forge-web's
5
- // RecordForm/FieldInput, the pipelines with-schema-form, the rjsf install
6
- // wizard) into a single reusable primitive. Give it a flat `fields` list OR
7
- // titled `sections`; it renders one typed input per field (10 scalar types +
8
- // nested `object` + repeatable `list`), inline per-field errors, and an "AI
9
- // suggested" badge for machine-prefilled fields.
10
- //
11
- // Controlled: owns no value state — `values` in, `onChange` out. Pair it with
12
- // `useSchemaValidation` for live errors and `usePrefill` for suggestions.
13
- // ═══════════════════════════════════════════════════════════════════════════
14
- import { Sparkles } from 'lucide-react';
15
- import { type ReactNode } from 'react';
16
-
17
- import { cn } from '../cn';
18
- import {
19
- type CaptureFieldSpec,
20
- type CaptureSchema,
21
- type CaptureSection,
22
- type CaptureValues,
23
- toSections,
24
- } from './field-spec';
25
- import { SchemaFieldInput, type RenderReference } from './schema-field-input';
26
- import { Badge } from '../primitives/badge';
27
- import { Label } from '../primitives/label';
28
-
29
- export interface SchemaFormProps {
30
- /** Flat schema. Mutually exclusive with `sections`. */
31
- readonly fields?: readonly CaptureFieldSpec[];
32
- /** Sectioned schema. Mutually exclusive with `fields`. */
33
- readonly sections?: readonly CaptureSection[];
34
- /** Pre-built schema object (either face). Lowest precedence. */
35
- readonly schema?: CaptureSchema;
36
- readonly values: CaptureValues;
37
- readonly onChange: (values: CaptureValues) => void;
38
- /** Per-field errors keyed by dot-path (from `useSchemaValidation` / server). */
39
- readonly errors?: Readonly<Record<string, string>>;
40
- /** Field keys to badge as machine-suggested (from `usePrefill`). */
41
- readonly suggestedKeys?: ReadonlySet<string> | readonly string[];
42
- readonly disabled?: boolean;
43
- /** Inject a record-backed picker for `reference` fields. */
44
- readonly renderReference?: RenderReference;
45
- /** Show section titles (default true when a section has a title). */
46
- readonly className?: string;
47
- /** Optional slot rendered after the fields (e.g. a submit bar). */
48
- readonly footer?: ReactNode;
49
- }
50
-
51
- function toSet(keys: SchemaFormProps['suggestedKeys']): ReadonlySet<string> {
52
- if (!keys) {
53
- return new Set();
54
- }
55
- return keys instanceof Set ? keys : new Set(keys as readonly string[]);
56
- }
57
-
58
- /**
59
- * @example
60
- * const [values, setValues] = useState({});
61
- * const { errors } = useSchemaValidation(fields, values);
62
- * <SchemaForm fields={fields} values={values} onChange={setValues} errors={errors} />
63
- */
64
- export function SchemaForm({
65
- fields,
66
- sections,
67
- schema,
68
- values,
69
- onChange,
70
- errors,
71
- suggestedKeys,
72
- disabled,
73
- renderReference,
74
- className,
75
- footer,
76
- }: SchemaFormProps) {
77
- const resolved: readonly CaptureSection[] = toSections(
78
- sections ?? (fields ? fields : schema) ?? [],
79
- );
80
- const suggested = toSet(suggestedKeys);
81
-
82
- const setField = (key: string, value: unknown) =>
83
- onChange({ ...values, [key]: value });
84
-
85
- return (
86
- <div className={cn('space-y-6', className)}>
87
- {resolved.map((section) => (
88
- <fieldset
89
- key={section.key}
90
- className="space-y-3 border-0 p-0"
91
- disabled={disabled}
92
- >
93
- {section.title ? (
94
- <legend className="mb-1 text-subtitle font-semibold text-ink">
95
- {section.title}
96
- {section.description ? (
97
- <span className="mt-0.5 block text-caption font-normal text-ink-3">
98
- {section.description}
99
- </span>
100
- ) : null}
101
- </legend>
102
- ) : null}
103
- {section.fields.map((field) => {
104
- const error = errors?.[field.key];
105
- const isSuggested = suggested.has(field.key);
106
- return (
107
- <div key={field.key}>
108
- <div className="flex items-center gap-2">
109
- <Label htmlFor={`field-${field.key}`}>
110
- {field.label}
111
- {field.required ? (
112
- <span className="text-destructive"> *</span>
113
- ) : null}
114
- </Label>
115
- {isSuggested ? (
116
- <Badge
117
- variant="outline"
118
- className="gap-1 border-primary/30 bg-primary/10 px-1.5 py-0 text-caption text-primary"
119
- >
120
- <Sparkles className="h-3 w-3" /> AI suggested
121
- </Badge>
122
- ) : null}
123
- </div>
124
- {field.description ? (
125
- <p className="mb-1 text-caption text-ink-3">
126
- {field.description}
127
- </p>
128
- ) : null}
129
- <SchemaFieldInput
130
- field={field}
131
- value={values[field.key]}
132
- onChange={(v) => setField(field.key, v)}
133
- disabled={disabled}
134
- path={field.key}
135
- errors={errors}
136
- renderReference={renderReference}
137
- />
138
- {error ? (
139
- <p className="mt-1 text-caption text-destructive">{error}</p>
140
- ) : null}
141
- </div>
142
- );
143
- })}
144
- </fieldset>
145
- ))}
146
- {footer}
147
- </div>
148
- );
149
- }
@@ -1,70 +0,0 @@
1
- // Pure-logic proofs for the ONE values→wire projection and the declared
2
- // transform. Runs under the host-web vitest runner (this package carries no
3
- // vitest dep — see tsconfig exclude).
4
- import { describe, expect, it } from 'vitest';
5
-
6
- import { applyCaptureTransform, CaptureFieldTransform, CaptureFieldType, type CaptureFieldSpec } from './field-spec';
7
- import { fieldSpecToZod } from './field-spec-to-zod';
8
- import { captureValuesToStringMap, captureValuesToSubmitPayload } from './submit-values';
9
-
10
- const fields: CaptureFieldSpec[] = [
11
- { key: 'apiKey', label: 'API key', type: CaptureFieldType.String, required: true, isSecret: true },
12
- { key: 'baseUrl', label: 'Base URL', type: CaptureFieldType.Url, required: true },
13
- { key: 'serviceAccount', label: 'Service account', type: CaptureFieldType.Json, required: false },
14
- ];
15
-
16
- describe('applyCaptureTransform', () => {
17
- it('applies only the DECLARED transform', () => {
18
- expect(applyCaptureTransform(' a ', CaptureFieldTransform.Trim)).toBe('a');
19
- expect(applyCaptureTransform('a', CaptureFieldTransform.Uppercase)).toBe('A');
20
- expect(applyCaptureTransform('A', CaptureFieldTransform.Lowercase)).toBe('a');
21
- expect(applyCaptureTransform(' a ', CaptureFieldTransform.None)).toBe(' a ');
22
- // Absent = no normalization. There is no implicit blanket trim.
23
- expect(applyCaptureTransform(' a ', undefined)).toBe(' a ');
24
- });
25
- });
26
-
27
- describe('captureValuesToStringMap', () => {
28
- it('projects ONLY declared keys, as strings', () => {
29
- expect(
30
- captureValuesToStringMap(fields, {
31
- apiKey: 'sk-1',
32
- baseUrl: 'https://acme.test',
33
- rogue: 'should not travel',
34
- }),
35
- ).toEqual({ apiKey: 'sk-1', baseUrl: 'https://acme.test', serviceAccount: '' });
36
- });
37
- });
38
-
39
- describe('captureValuesToSubmitPayload', () => {
40
- it('parses a json field and leaves the rest untouched', () => {
41
- expect(
42
- captureValuesToSubmitPayload(fields, {
43
- apiKey: 'sk-1',
44
- baseUrl: 'https://acme.test',
45
- serviceAccount: '{"a":1}',
46
- }),
47
- ).toEqual({ apiKey: 'sk-1', baseUrl: 'https://acme.test', serviceAccount: { a: 1 } });
48
- });
49
-
50
- it('does not drop an unparseable json value — validation is the gate', () => {
51
- expect(captureValuesToSubmitPayload(fields, { serviceAccount: '{' }).serviceAccount).toBe('{');
52
- });
53
- });
54
-
55
- describe('json field validation', () => {
56
- const schema = fieldSpecToZod(fields);
57
-
58
- it('rejects an unparseable json blob', () => {
59
- expect(schema.safeParse({ apiKey: 'k', baseUrl: 'u', serviceAccount: '{' }).success).toBe(false);
60
- });
61
-
62
- it('accepts a parseable json blob and an omitted optional one', () => {
63
- expect(schema.safeParse({ apiKey: 'k', baseUrl: 'u', serviceAccount: '{"a":1}' }).success).toBe(true);
64
- expect(schema.safeParse({ apiKey: 'k', baseUrl: 'u' }).success).toBe(true);
65
- });
66
-
67
- it('requires a non-empty url/email field when required', () => {
68
- expect(schema.safeParse({ apiKey: 'k', baseUrl: '' }).success).toBe(false);
69
- });
70
- });
@@ -1,63 +0,0 @@
1
- // ═══════════════════════════════════════════════════════════════════════════
2
- // Capture values → submit payload
3
- //
4
- // The ONE projection from the form's in-memory `CaptureValues` to what goes on
5
- // the wire. Two faces, because two wire contracts exist and neither should grow
6
- // its own inline projection:
7
- //
8
- // • `captureValuesToStringMap` — every field as a STRING (the shape a
9
- // credential submit takes: `fields: Record<string, string>`).
10
- // • `captureValuesToSubmitPayload` — same, except a `json` field is PARSED
11
- // into its structured value (the shape the connection credential write
12
- // takes: `credentials: Record<string, unknown>`).
13
- //
14
- // Both are field-driven: only DECLARED keys are projected, so a stray key in
15
- // the values record can never reach the wire. Neither performs an undeclared
16
- // normalization — trimming/casing is `CaptureFieldTransform`, applied once at
17
- // the input boundary. A blanket trim here would silently override a field that
18
- // declared `transform: none`.
19
- // ═══════════════════════════════════════════════════════════════════════════
20
- import { CaptureFieldType, toFieldList, type CaptureFieldSpec, type CaptureSchema, type CaptureSection, type CaptureValues } from './field-spec';
21
- import { asString } from './value-format';
22
-
23
- type Schema = CaptureSchema | readonly CaptureFieldSpec[] | readonly CaptureSection[];
24
-
25
- /** Project the declared fields to a flat `string` map (fields-only wire). */
26
- export function captureValuesToStringMap(
27
- schema: Schema,
28
- values: CaptureValues,
29
- ): Record<string, string> {
30
- const payload: Record<string, string> = {};
31
- for (const field of toFieldList(schema)) {
32
- payload[field.key] = asString(values[field.key]);
33
- }
34
- return payload;
35
- }
36
-
37
- /**
38
- * Project the declared fields, parsing `json` fields into structured values.
39
- *
40
- * A `json` field that does not parse is left as its raw string — validation is
41
- * `useSchemaValidation`'s job and it must run first; this projection does not
42
- * silently drop a value it cannot parse.
43
- */
44
- export function captureValuesToSubmitPayload(
45
- schema: Schema,
46
- values: CaptureValues,
47
- ): CaptureValues {
48
- const payload: CaptureValues = {};
49
- for (const field of toFieldList(schema)) {
50
- const raw = values[field.key];
51
- if (field.type !== CaptureFieldType.Json) {
52
- payload[field.key] = raw;
53
- continue;
54
- }
55
- const text = asString(raw);
56
- try {
57
- payload[field.key] = JSON.parse(text);
58
- } catch {
59
- payload[field.key] = text;
60
- }
61
- }
62
- return payload;
63
- }
@@ -1,186 +0,0 @@
1
- // ═══════════════════════════════════════════════════════════════════════════
2
- // usePrefill — field-level pre-fill from an async, source-agnostic default
3
- // source (AI, prior-context, a template service — the caller supplies it).
4
- //
5
- // It populates initial field values WITHOUT clobbering user edits, and tracks
6
- // which fields were machine-suggested so the UI can badge them. A field the
7
- // user has touched is never overwritten by a (re)load, and reading a field back
8
- // after the user edits it clears its "suggested" mark.
9
- // ═══════════════════════════════════════════════════════════════════════════
10
- import { useCallback, useEffect, useRef, useState } from 'react';
11
-
12
- import type { CaptureValues } from './field-spec';
13
-
14
- export interface UsePrefillOptions<T extends CaptureValues = CaptureValues> {
15
- /**
16
- * Async source of default values keyed by field key. Called on mount (unless
17
- * `enabled` is false) and on `reload()`. May return a partial record — only
18
- * the keys it returns are considered suggestions.
19
- */
20
- readonly fetchDefaults: () => Promise<Partial<T>>;
21
- /** Seed values (e.g. an edit form's existing record). Never treated as suggested. */
22
- readonly initialValues?: T;
23
- /** Gate the initial fetch (default true). */
24
- readonly enabled?: boolean;
25
- }
26
-
27
- export interface UsePrefillResult<T extends CaptureValues = CaptureValues> {
28
- readonly values: T;
29
- /** Set one field (a user edit) — clears its suggested mark. */
30
- readonly setValue: (key: string, value: unknown) => void;
31
- /** Replace/patch values (a user edit) — clears suggested marks for changed keys. */
32
- readonly setValues: (updater: Partial<T> | ((prev: T) => T)) => void;
33
- /** Keys populated by the default source and NOT yet edited by the user. */
34
- readonly suggestedKeys: ReadonlySet<string>;
35
- readonly isSuggested: (key: string) => boolean;
36
- readonly loading: boolean;
37
- readonly error: unknown;
38
- /** Re-run `fetchDefaults`; still respects user-touched keys. */
39
- readonly reload: () => void;
40
- }
41
-
42
- /**
43
- * @example
44
- * const prefill = usePrefill({
45
- * fetchDefaults: () => api.suggestDefaults(contextId), // → { title: 'Draft', owner: 'me' }
46
- * initialValues: { title: '', owner: '' },
47
- * });
48
- * <SchemaForm
49
- * fields={fields}
50
- * values={prefill.values}
51
- * onChange={prefill.setValues}
52
- * suggestedKeys={prefill.suggestedKeys} // renders an "AI suggested" badge
53
- * />
54
- */
55
- export function usePrefill<T extends CaptureValues = CaptureValues>(
56
- options: UsePrefillOptions<T>,
57
- ): UsePrefillResult<T> {
58
- const { fetchDefaults, initialValues, enabled = true } = options;
59
-
60
- const [values, setValuesState] = useState<T>(() => ({
61
- ...(initialValues ?? ({} as T)),
62
- }));
63
- const [suggested, setSuggested] = useState<ReadonlySet<string>>(
64
- () => new Set(),
65
- );
66
- const [loading, setLoading] = useState(false);
67
- const [error, setError] = useState<unknown>(null);
68
-
69
- // Keys the user has explicitly touched — a (re)load must never clobber these.
70
- const touched = useRef<Set<string>>(new Set());
71
- // Monotonic request id guards against a stale fetch resolving after a newer
72
- // one (or after user edits) — no timeout-based races.
73
- const requestId = useRef(0);
74
-
75
- const setValue = useCallback((key: string, value: unknown) => {
76
- touched.current.add(key);
77
- setValuesState((prev) => ({ ...prev, [key]: value }));
78
- setSuggested((prev) => {
79
- if (!prev.has(key)) {
80
- return prev;
81
- }
82
- const next = new Set(prev);
83
- next.delete(key);
84
- return next;
85
- });
86
- }, []);
87
-
88
- const setValues = useCallback((updater: Partial<T> | ((prev: T) => T)) => {
89
- setValuesState((prev) => {
90
- const next =
91
- typeof updater === 'function' ? updater(prev) : { ...prev, ...updater };
92
- const changed = new Set<string>();
93
- for (const k of Object.keys(next)) {
94
- if (next[k] !== prev[k]) {
95
- touched.current.add(k);
96
- changed.add(k);
97
- }
98
- }
99
- if (changed.size > 0) {
100
- setSuggested((prevSug) => {
101
- if (![...changed].some((k) => prevSug.has(k))) {
102
- return prevSug;
103
- }
104
- const n = new Set(prevSug);
105
- for (const k of changed) {
106
- n.delete(k);
107
- }
108
- return n;
109
- });
110
- }
111
- return next;
112
- });
113
- }, []);
114
-
115
- const run = useCallback(() => {
116
- const id = ++requestId.current;
117
- setLoading(true);
118
- setError(null);
119
- void fetchDefaults()
120
- .then((defaults) => {
121
- if (id !== requestId.current) {
122
- return;
123
- } // superseded — drop
124
- const applied: string[] = [];
125
- setValuesState((prev) => {
126
- const next = { ...prev };
127
- for (const [key, value] of Object.entries(defaults)) {
128
- // Only fill keys the user hasn't touched and that are still empty.
129
- const current = prev[key];
130
- const isEmpty =
131
- current === undefined || current === null || current === '';
132
- if (!touched.current.has(key) && isEmpty && value !== undefined) {
133
- (next as CaptureValues)[key] = value;
134
- applied.push(key);
135
- }
136
- }
137
- return next;
138
- });
139
- setSuggested((prev) => {
140
- if (applied.length === 0) {
141
- return prev;
142
- }
143
- const n = new Set(prev);
144
- for (const k of applied) {
145
- n.add(k);
146
- }
147
- return n;
148
- });
149
- })
150
- .catch((e: unknown) => {
151
- if (id !== requestId.current) {
152
- return;
153
- }
154
- setError(e);
155
- })
156
- .finally(() => {
157
- if (id === requestId.current) {
158
- setLoading(false);
159
- }
160
- });
161
- }, [fetchDefaults]);
162
-
163
- useEffect(() => {
164
- if (enabled) {
165
- run();
166
- }
167
- // Run once on mount / when re-enabled; `reload()` is the explicit re-fetch.
168
- // eslint-disable-next-line react-hooks/exhaustive-deps
169
- }, [enabled]);
170
-
171
- const isSuggested = useCallback(
172
- (key: string) => suggested.has(key),
173
- [suggested],
174
- );
175
-
176
- return {
177
- values,
178
- setValue,
179
- setValues,
180
- suggestedKeys: suggested,
181
- isSuggested,
182
- loading,
183
- error,
184
- reload: run,
185
- };
186
- }
@@ -1,145 +0,0 @@
1
- // ═══════════════════════════════════════════════════════════════════════════
2
- // useSchemaValidation — client-side validation + "missing info" sweep
3
- //
4
- // Runs BEFORE any server round-trip, on every change/blur. Accepts either a
5
- // hand-written `zod` schema OR a `CaptureFieldSpec[]` / `CaptureSection[]` /
6
- // `CaptureSchema` (auto-adapted via `fieldSpecToZod`). Returns per-field errors
7
- // keyed by dot-path plus a deterministic `missingRequired` list so a guided UX
8
- // can nudge "you still need to fill X" without waiting for a 422.
9
- // ═══════════════════════════════════════════════════════════════════════════
10
- import { useMemo } from 'react';
11
- import { type z } from 'zod';
12
-
13
- import {
14
- CaptureFieldType,
15
- type CaptureFieldSpec,
16
- type CaptureSchema,
17
- type CaptureSection,
18
- type CaptureValues,
19
- toFieldList,
20
- } from './field-spec';
21
- import { fieldSpecToZod, isEmptyValue } from './field-spec-to-zod';
22
-
23
- export interface SchemaValidationResult {
24
- /** First error per field, keyed by dot-path (`tags.0.name`, `address.city`). */
25
- readonly errors: Readonly<Record<string, string>>;
26
- /** Dot-paths of required fields still empty — the "missing info" sweep. */
27
- readonly missingRequired: readonly string[];
28
- /** True when there are no errors AND nothing required is missing. */
29
- readonly isValid: boolean;
30
- }
31
-
32
- type ValidationInput =
33
- | z.ZodType
34
- | CaptureSchema
35
- | readonly CaptureFieldSpec[]
36
- | readonly CaptureSection[];
37
-
38
- function isZodSchema(input: ValidationInput): input is z.ZodType {
39
- return 'safeParse' in input && typeof input.safeParse === 'function';
40
- }
41
-
42
- /** Deterministic required sweep over the flat spec list (nested-aware). */
43
- function sweepMissing(
44
- fields: readonly CaptureFieldSpec[],
45
- values: CaptureValues,
46
- prefix = '',
47
- ): string[] {
48
- const missing: string[] = [];
49
- for (const field of fields) {
50
- const path = prefix ? `${prefix}.${field.key}` : field.key;
51
- const value = values[field.key];
52
- if (field.type === CaptureFieldType.Object) {
53
- if (field.required && isEmptyValue(value)) {
54
- missing.push(path);
55
- }
56
- if (value && typeof value === 'object' && !Array.isArray(value)) {
57
- missing.push(
58
- ...sweepMissing(field.fields ?? [], value as CaptureValues, path),
59
- );
60
- }
61
- continue;
62
- }
63
- if (field.type === CaptureFieldType.List) {
64
- if (field.required && isEmptyValue(value)) {
65
- missing.push(path);
66
- }
67
- if (Array.isArray(value)) {
68
- value.forEach((item, i) => {
69
- if (item && typeof item === 'object') {
70
- missing.push(
71
- ...sweepMissing(
72
- field.fields ?? [],
73
- item as CaptureValues,
74
- `${path}.${i}`,
75
- ),
76
- );
77
- }
78
- });
79
- }
80
- continue;
81
- }
82
- if (field.required && isEmptyValue(value)) {
83
- missing.push(path);
84
- }
85
- }
86
- return missing;
87
- }
88
-
89
- /**
90
- * @example
91
- * const { errors, missingRequired, isValid } = useSchemaValidation(fields, values);
92
- * // live under each input:
93
- * errors['email'] // → 'Email must be a valid address' | undefined
94
- * missingRequired // → ['email', 'address.city']
95
- * // gate a wizard step / submit button:
96
- * <Button disabled={!isValid}>Continue</Button>
97
- */
98
- export function useSchemaValidation(
99
- input: ValidationInput,
100
- values: CaptureValues,
101
- ): SchemaValidationResult {
102
- // Field specs (when supplied) drive the deterministic required sweep and the
103
- // auto-adapted zod schema; a raw zod schema is used as-is.
104
- const fields = useMemo<readonly CaptureFieldSpec[] | null>(
105
- () => (isZodSchema(input) ? null : toFieldList(input)),
106
- [input],
107
- );
108
- const schema = useMemo<z.ZodType>(
109
- () => (isZodSchema(input) ? input : fieldSpecToZod(input)),
110
- [input],
111
- );
112
-
113
- return useMemo<SchemaValidationResult>(() => {
114
- const errors: Record<string, string> = {};
115
- const result = schema.safeParse(values);
116
- if (!result.success) {
117
- for (const issue of result.error.issues) {
118
- const path = issue.path.map(String).join('.');
119
- // First error per path wins (deterministic, matches display order).
120
- if (!(path in errors)) {
121
- errors[path] = issue.message;
122
- }
123
- }
124
- }
125
-
126
- // Deterministic sweep when we have specs; otherwise derive "missing" from
127
- // zod issues that fired on an empty value (so a bare zod schema still works).
128
- const missingRequired = fields
129
- ? sweepMissing(fields, values)
130
- : Object.keys(errors).filter((path) => {
131
- const segments = path.split('.');
132
- let cur: unknown = values;
133
- for (const seg of segments) {
134
- cur = (cur as CaptureValues | undefined)?.[seg];
135
- }
136
- return isEmptyValue(cur);
137
- });
138
-
139
- return {
140
- errors,
141
- missingRequired,
142
- isValid: Object.keys(errors).length === 0 && missingRequired.length === 0,
143
- };
144
- }, [schema, fields, values]);
145
- }