@zestl/zvolv-widgets 0.0.0 → 0.0.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.
package/dist/index.d.cts CHANGED
@@ -458,7 +458,21 @@ declare const WidgetShell: React.FC<WidgetShellProps>;
458
458
 
459
459
  /** Heuristic: a plain number in the ~2000–2100 ms-epoch band is a timestamp, not a value. */
460
460
  declare function isLikelyTimestamp(v: any): boolean;
461
- type DateGapUnit = "day" | "week" | "month";
461
+ type DateGapUnit = "day" | "week" | "month" | "quarter" | "year";
462
+ /**
463
+ * Start of the period containing `d`. Weeks start on Monday (ISO), matching
464
+ * Elasticsearch's `1w` calendar_interval; quarters start Jan/Apr/Jul/Oct.
465
+ * Periods are in the browser's zone unless `timeZone` (IANA) is given.
466
+ */
467
+ declare function startOfPeriod(d: dayjs.Dayjs, unit: DateGapUnit, timeZone?: string): dayjs.Dayjs;
468
+ /** The period after `d` (which must already be a period start). */
469
+ declare function addPeriod(d: dayjs.Dayjs, unit: DateGapUnit, timeZone?: string): dayjs.Dayjs;
470
+ /**
471
+ * Parses an x-value. Epoch ms and strings with an explicit offset are instants;
472
+ * other strings ("2026-01-05", "2026-01-05 10:00") are wall time in `timeZone`
473
+ * when given, else in the browser's zone.
474
+ */
475
+ declare function parseDateValue(v: any, timeZone?: string): dayjs.Dayjs;
462
476
  interface FillDateGapsArgs {
463
477
  rows: any[];
464
478
  xKey: string;
@@ -470,14 +484,41 @@ interface FillDateGapsArgs {
470
484
  start: dayjs.Dayjs;
471
485
  end: dayjs.Dayjs;
472
486
  } | null;
487
+ /**
488
+ * How rows falling in the same period combine. "sum" (default) adds each
489
+ * series valueField and keeps the first row's other fields (x included).
490
+ * "last" keeps only the last row per period — the pre-0.0.2 behaviour, which
491
+ * drops data when day-level rows are shown weekly or monthly.
492
+ */
493
+ merge?: "sum" | "last";
494
+ /**
495
+ * x-value format for inserted zero rows when it cannot be inferred from the
496
+ * data (e.g. empty input). Default: "date" ("YYYY-MM-DD"), or "timestamp"
497
+ * when the first row's x is epoch ms.
498
+ */
499
+ xFormat?: "timestamp" | "date";
500
+ /**
501
+ * IANA zone periods are computed in. Must match the ES `time_zone` the rows
502
+ * were bucketed in (`groupBy(..., { timeZone })`). Default: browser zone.
503
+ */
504
+ timeZone?: string;
473
505
  }
474
506
  /**
475
507
  * Inserts zero rows for periods with no data so a time axis reads continuously.
476
508
  *
477
- * Keying by each period's start date (rather than a week/month number) avoids
478
- * needing dayjs's weekOfYear plugin and stays unambiguous across year boundaries.
509
+ * Periods are keyed by their start instant, so keys stay unambiguous across
510
+ * year boundaries. A period's existing row keeps its own x-value and format
511
+ * (epoch ms stays epoch ms, strings stay strings); inserted zero rows use the
512
+ * period start in the same format.
479
513
  */
480
- declare function fillDateGaps({ rows, xKey, series, unit, range }: FillDateGapsArgs): any[];
514
+ declare function fillDateGaps({ rows, xKey, series, unit, range, merge, xFormat, timeZone, }: FillDateGapsArgs): any[];
515
+ /**
516
+ * Running totals ("level over time"): replaces each `fields` value with the sum
517
+ * of itself and every earlier row, starting from `baseline[field]` (the total
518
+ * before the first row). Rows are ordered by `xKey` date first; rows whose x is
519
+ * not a date keep their position at the end.
520
+ */
521
+ declare function applyCumulative(rows: any[], xKey: string, fields: string[], baseline?: Record<string, number>): any[];
481
522
  declare function coerceSeriesNumbers(rows: any[], series: {
482
523
  valueField: string;
483
524
  }[]): any[];
@@ -528,14 +569,35 @@ interface DataSourceField {
528
569
  filter?: FieldFilter;
529
570
  formula?: any[];
530
571
  }
572
+ type DateInterval = "day" | "week" | "month" | "quarter" | "year";
531
573
  interface PivotRow {
532
574
  /** Output column name. Must match the series `argumentField`. */
533
575
  title: string;
576
+ /** The Elasticsearch field grouped on. */
534
577
  masterField: string;
535
578
  masterFieldType?: string;
536
579
  masterFieldDataType?: MasterFieldDataType;
580
+ /**
581
+ * Date fields only: bucket by calendar period (ES `date_histogram`) instead of
582
+ * by exact value. Weeks start on Monday (ISO). Row keys are epoch ms.
583
+ */
584
+ interval?: DateInterval;
585
+ /** IANA zone for `interval` bucket boundaries. Default: the browser's zone. */
586
+ timeZone?: string;
587
+ }
588
+ type AggregationType = "sum" | "avg" | "min" | "max" | "count" | "value_count" | "cardinality" | "percentiles";
589
+ type DateDiffUnit = "days" | "hours" | "minutes";
590
+ /** `end - start` between two date fields, as built by `dateDiff()`. */
591
+ interface DateDiffSpec {
592
+ /** Start date masterfield. */
593
+ start: string;
594
+ /**
595
+ * End date masterfield; or a fixed end: a date token (`{@[TODAY]}`,
596
+ * `{@[7DAYSAGO]}`, …) or a literal date ("2026-03-31", ISO date-time).
597
+ */
598
+ end: string;
599
+ unit: DateDiffUnit;
537
600
  }
538
- type AggregationType = "sum" | "avg" | "min" | "max" | "count" | "value_count" | "cardinality";
539
601
  interface PivotSummary {
540
602
  title: string;
541
603
  masterField: string;
@@ -544,6 +606,15 @@ interface PivotSummary {
544
606
  /** Output name of the aggregated value. Must match the series `valueField`. */
545
607
  value: string;
546
608
  type: AggregationType;
609
+ /** Aggregate a date difference (script) instead of a stored field. */
610
+ dateDiff?: DateDiffSpec;
611
+ /** `percentiles` only: which percentiles. Rows get `<value>_p50`-style keys. */
612
+ percents?: number[];
613
+ /**
614
+ * Conditions from `aggregate(..., { where })`. `pivot()` / `formSource()` /
615
+ * `taskSource()` move them into `pivot.filters`; they are not read from here.
616
+ */
617
+ filters?: PivotFilter[];
547
618
  }
548
619
  interface PivotFilter {
549
620
  field: string;
@@ -553,6 +624,12 @@ interface PivotFilter {
553
624
  masterFieldDataType?: MasterFieldDataType;
554
625
  operator: FilterOperator;
555
626
  value: any[];
627
+ /**
628
+ * "AND": AND this condition with every other entry targeting the same
629
+ * `field` (summary). Without it, only the last entry per field applies —
630
+ * the original behaviour, kept for stored configs.
631
+ */
632
+ combine?: "AND";
556
633
  }
557
634
  type PostOperator = "ADD" | "SUB" | "MUL" | "DIV" | "PERCENT";
558
635
  interface PostOperation {
@@ -595,13 +672,49 @@ declare function field(header: string, masterFieldType: MasterFieldType | string
595
672
  * "Status" becomes masterfield "status" automatically.
596
673
  */
597
674
  declare function taskField(header: string, masterFieldType?: MasterFieldType | string, options?: Partial<DataSourceField>): DataSourceField;
598
- /** A group-by dimension. `title` is what a series' `argumentField` must match. */
599
- declare function groupBy(f: DataSourceField, title?: string): PivotRow;
675
+ /**
676
+ * A group-by dimension. `title` is what a series' `argumentField` must match;
677
+ * the query groups on the field's masterfield.
678
+ *
679
+ * Pass `{ interval }` on a date field to bucket by calendar period:
680
+ * `groupBy(requestDate, "Month", { interval: "month" })`.
681
+ */
682
+ declare function groupBy(f: DataSourceField, title?: string, options?: {
683
+ interval?: DateInterval;
684
+ timeZone?: string;
685
+ }): PivotRow;
686
+ /** A field-like spec for `aggregate()`: the time from `start` to `end`. */
687
+ interface DateDiffField extends DataSourceField {
688
+ dateDiff: DateDiffSpec;
689
+ }
690
+ /**
691
+ * The time between two date fields, for `aggregate()` (avg / min / max / sum /
692
+ * percentiles). Documents missing either date are skipped.
693
+ *
694
+ * `end` is a date field, or a fixed end that only needs `start` to exist:
695
+ * `"TODAY"` / a date token like `{@[30DAYSAGO]}` (start of that day), or a
696
+ * literal date such as `"2026-03-31"` (local midnight) or an ISO date-time.
697
+ * Any other string is treated as a field name; an unknown `{@[…]}` token warns.
698
+ *
699
+ * aggregate(dateDiff(requestDate, offerDate, "days"), "avg", "Avg Days to Offer")
700
+ */
701
+ declare function dateDiff(start: DataSourceField, end: DataSourceField | "TODAY" | string, unit?: DateDiffUnit): DateDiffField;
702
+ interface AggregateOptions {
703
+ /** `percentiles` only. Default (ES): 1, 5, 25, 50, 75, 95, 99. */
704
+ percents?: number[];
705
+ /**
706
+ * Conditions this metric alone is filtered by, AND-ed together. Several
707
+ * filtered metrics on one form still run as one request.
708
+ *
709
+ * aggregate(amount, "sum", "Billed", { where: [[status, where("IN", "Invoiced", "Paid")]] })
710
+ */
711
+ where?: [DataSourceField, FieldFilter][];
712
+ }
600
713
  /**
601
714
  * An aggregated metric. `outputName` is what a series' `valueField` must match,
602
715
  * and what a postOperation references as an operand.
603
716
  */
604
- declare function aggregate(f: DataSourceField, type?: AggregationType, outputName?: string): PivotSummary;
717
+ declare function aggregate(f: DataSourceField, type?: AggregationType, outputName?: string, options?: AggregateOptions): PivotSummary;
605
718
  /**
606
719
  * A value derived from other aggregates, computed after the query returns.
607
720
  *
@@ -769,11 +882,8 @@ interface UseWidgetDataArgs {
769
882
  */
770
883
  localFilters?: any;
771
884
  rowLimit?: number;
772
- dateGap?: {
773
- unit: DateGapUnit;
774
- start?: string;
775
- end?: string;
776
- } | null;
885
+ /** Fill empty periods (and optionally accumulate) on a date x-axis. See `DateGapOptions`. */
886
+ dateGap?: DateGapOptions | null;
777
887
  /** Rows supplied by an automation binding; when provided, no query is issued. */
778
888
  automationRows?: any[] | null;
779
889
  automationLoading?: boolean;
@@ -788,6 +898,39 @@ interface UseWidgetDataArgs {
788
898
  /** Debounce for remote search, ms. Default 400. */
789
899
  searchDebounceMs?: number;
790
900
  }
901
+ interface DateGapOptions {
902
+ unit: DateGapUnit;
903
+ /** Range to fill, inclusive. Both are needed to insert zero rows. */
904
+ start?: string;
905
+ end?: string;
906
+ /** How rows in the same period combine. Default "sum"; "last" is the pre-0.0.2 behaviour. */
907
+ merge?: "sum" | "last";
908
+ /**
909
+ * IANA zone for period boundaries. Default: the `timeZone` of the pivot row
910
+ * plotted on x (`groupBy(..., { interval, timeZone })`), else the browser's.
911
+ */
912
+ timeZone?: string;
913
+ /**
914
+ * Running totals after gap filling: `true` for every series valueField, or a
915
+ * list of fields. Each row then holds the level at the end of its period.
916
+ * Rows before `start` are dropped (they belong to the baseline), even when
917
+ * `end` is not given.
918
+ */
919
+ cumulative?: string[] | true;
920
+ /** Starting value per cumulative field: the total before `start`. */
921
+ baseline?: Record<string, number>;
922
+ /**
923
+ * Fetch `baseline` instead of passing it: a summary-only data source whose
924
+ * summary output names match the cumulative fields. The hook adds
925
+ * `dateField < start` and the widget's dashboard / widget filters (not the
926
+ * dashboard date range, which would exclude everything before `start`).
927
+ * One extra request. An explicit `baseline` value wins per field.
928
+ */
929
+ baselineSource?: {
930
+ dataSource: ZvolvDataSource;
931
+ dateField: string;
932
+ };
933
+ }
791
934
  /**
792
935
  * Fetches, normalizes and shapes a widget's rows.
793
936
  *
@@ -1008,6 +1151,11 @@ interface KpiWidgetProps extends Omit<InteractiveWidgetProps, "widgetType"> {
1008
1151
  className?: string;
1009
1152
  style?: React.CSSProperties;
1010
1153
  onItemClick?: (vm: any, index: number) => void;
1154
+ /**
1155
+ * Sparkline series per content index, for `seriesSource.mode: "timeseries"`
1156
+ * items you fetch yourself. Wins over a self-fetched `seriesSource.dataSource`.
1157
+ */
1158
+ externalSeriesByIndex?: Record<number, number[]>;
1011
1159
  }
1012
1160
  declare const KpiWidget: React.FC<KpiWidgetProps>;
1013
1161
 
@@ -1652,7 +1800,7 @@ interface FieldOption {
1652
1800
  * The UI family a field belongs to. A host draws one control per kind; the
1653
1801
  * library owns everything behind it (value shape, validation, submit format).
1654
1802
  */
1655
- type FieldKind = "text" | "textarea" | "email" | "phone" | "url" | "number" | "currency" | "percent" | "select" | "radio" | "checkbox" | "lookup" | "user" | "date" | "time" | "datetime" | "daterange" | "rating" | "slider" | "file" | "signature" | "richtext" | "scan" | "timer" | "location" | "formula" | "display" | "autonumber" | "section" | "container" | "tabs" | "steps" | "matrix" | "table" | "sheet" | "comments" | "action" | "onbehalf" | "system" | "unknown";
1803
+ type FieldKind = "text" | "textarea" | "email" | "phone" | "url" | "number" | "currency" | "percent" | "select" | "radio" | "checkbox" | "lookup" | "user" | "date" | "time" | "datetime" | "daterange" | "rating" | "slider" | "file" | "signature" | "richtext" | "scan" | "timer" | "location" | "formula" | "display" | "autonumber" | "section" | "container" | "tabs" | "steps" | "matrix" | "table" | "sheet" | "comments" | "action" | "onbehalf" | "trials" | "system" | "unknown";
1656
1804
 
1657
1805
  /** Types never sent in a submission body. */
1658
1806
  declare const SUBMISSION_SKIP_TYPES: Set<string>;
@@ -1709,6 +1857,22 @@ declare function submissionIdOf(res: any): string | null;
1709
1857
  declare function createSubmission(client: any, form: FormDefinition, elements: FormElement[], values: FormValues, opts?: SubmitOptions): Promise<any>;
1710
1858
  declare function updateSubmission(client: any, form: FormDefinition, submissionId: string, elements: FormElement[], values: FormValues, opts?: SubmitOptions): Promise<any>;
1711
1859
  declare function invokeTrigger(client: any, triggerId: string | number, body: Record<string, any>): Promise<any>;
1860
+ /** TRIGGER_AUTOMATION with properties.automationType "ZENO" (zvolv-web onTriggerZeno → invokeNuclioAutomation). */
1861
+ declare function invokeZeno(client: any, automationUuid: string, body: Record<string, any>): Promise<any>;
1862
+ /**
1863
+ * INVOKE_AGENT.
1864
+ * 1. With properties.flowId: POST /api/v1/zwall/agent/invoke/{flowId}/{agentId} — the
1865
+ * zvolv-web / ZAI-Dashboard call (legacy agent flows).
1866
+ * 2. Without a flowId, or when that server has no such flow (it answers
1867
+ * `{ error: true, reply: "Error: '<flowId>'" }`): POST
1868
+ * /api/v1/zwall/v3/agent_manager/agent_flow/{agentId} — how the platform calls
1869
+ * current ZAI agents (zvolv-mcp zagent.call_agent).
1870
+ * Called directly, not through the SDK's workflow.invokeAgent, whose handleRequest
1871
+ * rejects any reply without `error: false` ("Error fetching data").
1872
+ */
1873
+ declare function invokeAgent(client: any, body: any, flowId?: string, agentId?: string): Promise<any>;
1874
+ /** Field map from an agent reply: `{formData}` or wrapped in `response`, possibly JSON-encoded (ZAI extractAgentFormData). */
1875
+ declare function extractAgentFormData(reply: any): Record<string, any> | null;
1712
1876
  interface UploadedFile {
1713
1877
  media_name: string;
1714
1878
  media_type: string;
@@ -1799,7 +1963,7 @@ interface FormField {
1799
1963
  * Visual intent: action buttons (primary / outline); checkbox "switch" when
1800
1964
  * attributes.showAsSwitch is set (ZAI CheckboxField / zvolv-web nz-switch).
1801
1965
  */
1802
- variant?: "primary" | "outline" | "switch";
1966
+ variant?: "primary" | "outline" | "switch" | "dropdown";
1803
1967
  /** Read-only text to show (ON_BEHALF_OF: the user's name rather than their id). */
1804
1968
  displayText?: string;
1805
1969
  /** DATE_PICKER display format from properties.format (dayjs tokens), default DD/MM/YYYY. */
@@ -1869,18 +2033,50 @@ interface ZvolvFormApi {
1869
2033
  response: any;
1870
2034
  } | null>;
1871
2035
  reset: () => void;
1872
- runAction: (field: FormField) => Promise<ActionOutcome>;
2036
+ /**
2037
+ * Run an action button. For ACTION_DROPDOWN pass the picked option's label
2038
+ * (field.options) — only that action (or its cascade) runs, as in zvolv-web.
2039
+ */
2040
+ runAction: (field: FormField, choice?: string) => Promise<ActionOutcome>;
2041
+ /** Re-fetch the form (and the saved submission). Used by properties.refreshForm. */
2042
+ reload: () => void;
1873
2043
  /** Field ids with an action / automation in flight. */
1874
2044
  busy: Set<string>;
1875
2045
  client: any;
1876
2046
  /** Sheet child definitions register here so submit can post their rows. */
1877
2047
  registerSheet: (fieldId: string, def: FormDefinition) => void;
2048
+ /** A registered sheet's child form (after useSheetField loaded it). */
2049
+ sheetDefinition: (fieldId: string) => FormDefinition | undefined;
2050
+ /** Bumps whenever a sheet definition registers — memo key for inspectors. */
2051
+ sheetVersion: number;
1878
2052
  }
2053
+ /** Elements that go into the POST/PUT /api/v1/submissions body. */
2054
+ declare function submitElementsOf(elements: FormElement[]): FormElement[];
1879
2055
  declare const FormApiContext: React.Context<ZvolvFormApi | null>;
1880
2056
  /** The nearest form's api, for field components rendered inside <ZvolvForm>. */
1881
2057
  declare function useFormApi(): ZvolvFormApi;
1882
2058
  declare function useZvolvForm(args: UseZvolvFormArgs): ZvolvFormApi;
1883
2059
 
2060
+ /**
2061
+ * What an "open another screen" action button wants, for the host's onAction —
2062
+ * mirrors ZAI-Dashboard ActionButtonField:
2063
+ * CREATE_SUBMISSION → NEW on properties.formId
2064
+ * EDIT_SUBMISSION / OPEN_TASK → EDIT on the button's value (a submission / task id)
2065
+ * SAVE_SUBMISSION → properties.formId, EDIT when the button holds an id, else NEW,
2066
+ * prefilled through properties.inputMap (source → destination elementId)
2067
+ * OPEN_PROJECT → the button's value is a project WID
2068
+ * After the host saves, write the new id back with form.setValue(field.id, id).
2069
+ */
2070
+ interface OpenFormRequest {
2071
+ actionType: string;
2072
+ formId?: string;
2073
+ submissionId?: string;
2074
+ projectId?: string;
2075
+ mode: "NEW" | "EDIT";
2076
+ defaultValues?: Record<string, any>;
2077
+ }
2078
+ declare function openFormRequest(field: FormField, form: Pick<ZvolvFormApi, "values">): OpenFormRequest | null;
2079
+
1884
2080
  /**
1885
2081
  * <ZvolvForm> — renders a Zvolv form with whatever field kit the host
1886
2082
  * supplies. Behaviour comes from useZvolvForm; appearance comes from
@@ -2103,6 +2299,19 @@ declare function getPostOpOperandSet(postOperations?: any[]): Set<string>;
2103
2299
  */
2104
2300
  declare function alignSummaryToSeries(dataSource: any, series: any[]): any;
2105
2301
 
2302
+ /**
2303
+ * Percentiles summaries come back as an object of percent → value rather than
2304
+ * a number. These helpers spread it into flat, chartable keys.
2305
+ */
2306
+ /** Output key for one percentile: ("Days", 50) → "Days_p50", 99.9 → "Days_p99_9". */
2307
+ declare function percentileKey(name: string, percent: number | string): string;
2308
+ /**
2309
+ * For each named percentiles summary, writes `<name>_p<percent>` keys and sets
2310
+ * `<name>` itself to the median (p50) when it was requested. Rows whose value
2311
+ * is already a number, or flat `<name>_p..` keys from the server, are left as is.
2312
+ */
2313
+ declare function flattenPercentiles(rows: any[], names: string[]): any[];
2314
+
2106
2315
  declare const PREFIX_UNITS: Record<string, string>;
2107
2316
  declare const SUFFIX_UNITS: Record<string, string>;
2108
2317
  /** Mirrors Angular formatAmountValue() from dashboards.utils */
@@ -2134,6 +2343,21 @@ declare function usesFormFramework(dataSource: ZvolvDataSource): boolean;
2134
2343
  * did not author.
2135
2344
  */
2136
2345
 
2346
+ /**
2347
+ * A KPI sparkline that fetches its own series. The widget runs one query per
2348
+ * content item through `useWidgetData`, applies `dateGap`, and plots
2349
+ * `rows[].valueField` in x order.
2350
+ */
2351
+ interface KpiTimeseriesSource {
2352
+ mode: "timeseries";
2353
+ /** Usually a pivot grouped by a date row with `interval`. */
2354
+ dataSource: ZvolvDataSource;
2355
+ /** Row key of the period — the groupBy title. */
2356
+ xField: string;
2357
+ /** Row key of the plotted value — the aggregate output name. */
2358
+ valueField: string;
2359
+ dateGap?: DateGapOptions;
2360
+ }
2137
2361
  interface AxisConfig {
2138
2362
  title?: string;
2139
2363
  valueFormat?: string;
@@ -2160,7 +2384,7 @@ interface ChartConfig extends WidgetChromeConfig {
2160
2384
  stackOrder?: "none" | "asc" | "desc";
2161
2385
  /** Insert zero rows for empty periods so a time axis reads continuously. */
2162
2386
  fillDateGaps?: boolean;
2163
- dateGapUnit?: "day" | "week" | "month";
2387
+ dateGapUnit?: DateGapUnit;
2164
2388
  }
2165
2389
  interface KpiContentConfig {
2166
2390
  title?: string;
@@ -2193,7 +2417,12 @@ interface KpiContentConfig {
2193
2417
  statusFallbackTone?: string;
2194
2418
  seriesPoints?: string[];
2195
2419
  seriesPoint?: string;
2196
- seriesSource?: {
2420
+ /**
2421
+ * `{ mode: "timeseries", dataSource, xField, valueField, dateGap }` makes the
2422
+ * widget fetch the sparkline itself. `{ mode: "timeseries" }` alone still
2423
+ * reads the `externalSeriesByIndex` prop.
2424
+ */
2425
+ seriesSource?: KpiTimeseriesSource | {
2197
2426
  mode?: "timeseries" | "fields";
2198
2427
  [k: string]: any;
2199
2428
  };
@@ -2528,6 +2757,8 @@ interface FieldOptionsOptions {
2528
2757
  autofillExtraLabels?: boolean;
2529
2758
  }
2530
2759
  declare function useFieldOptions(form: ZvolvFormApi, field: FormField, opts?: FieldOptionsOptions): FieldOptionsState;
2760
+ /** Extensions the platform refuses (ZAI-Dashboard utils/constant BLOCKED_FILE_EXTENSIONS). */
2761
+ declare const BLOCKED_FILE_EXTENSIONS: Set<string>;
2531
2762
  interface FileItem {
2532
2763
  key: string;
2533
2764
  name: string;
@@ -2581,6 +2812,60 @@ interface SheetFieldState {
2581
2812
  }
2582
2813
  declare function useSheetField(form: ZvolvFormApi, field: FormField): SheetFieldState;
2583
2814
 
2815
+ interface TrialButton {
2816
+ label: string;
2817
+ icon?: string;
2818
+ color?: string;
2819
+ hideLabel?: boolean;
2820
+ disabled?: boolean;
2821
+ /** Second-level buttons shown after this response is pressed. */
2822
+ prompts: {
2823
+ label: string;
2824
+ icon?: string;
2825
+ color?: string;
2826
+ hideLabel?: boolean;
2827
+ }[];
2828
+ }
2829
+ interface TrialLogEntry {
2830
+ label: string;
2831
+ correct: boolean;
2832
+ detail?: string;
2833
+ }
2834
+ interface TrialFieldState {
2835
+ type: "percent" | "time" | "task";
2836
+ /** Response buttons for the current trial (task analysis: for the current step). */
2837
+ buttons: TrialButton[];
2838
+ /** Set after a response with prompt buttons is pressed; pick one with prompt(). */
2839
+ activeResponse?: string;
2840
+ prompts: TrialButton["prompts"];
2841
+ respond: (label: string) => void;
2842
+ prompt: (label: string) => void;
2843
+ cancelPrompt: () => void;
2844
+ /** Percent correct / task analysis: undo the last trial. */
2845
+ prev: () => void;
2846
+ currentTrial: number;
2847
+ maxTrials: number;
2848
+ complete: boolean;
2849
+ /** Share of responses labelled IND / NR / CHECK (ZAI's "correct" set), 0–100. */
2850
+ percentCorrect: number;
2851
+ log: TrialLogEntry[];
2852
+ disabled: boolean;
2853
+ timer: number;
2854
+ formattedTimer: string;
2855
+ running: boolean;
2856
+ start: () => void;
2857
+ pause: () => void;
2858
+ reset: () => void;
2859
+ interval: number;
2860
+ intervalCount: number;
2861
+ timeLimit: number;
2862
+ steps: string[];
2863
+ currentStep: number;
2864
+ stepName: string;
2865
+ chain: "forward" | "backward" | "whole";
2866
+ }
2867
+ declare function useTrialField(form: ZvolvFormApi, field: FormField): TrialFieldState;
2868
+
2584
2869
  /**
2585
2870
  * Form definition + submission normalisation. Ported from ZAI-Dashboard
2586
2871
  * `formApi.ts` (normaliseForm / normaliseElement / flattenElements /
@@ -2627,6 +2912,7 @@ interface RuleOverride {
2627
2912
  }
2628
2913
  /** Does `dep` (declared on `src`) match the current values? */
2629
2914
  declare function ruleMatches(src: FormElement, dep: any, values: FormValues): boolean;
2915
+ declare function rulesOf(el: FormElement): any[];
2630
2916
  /**
2631
2917
  * Hidden / disabled / required overrides per target elementId. A matching rule
2632
2918
  * for a target wins over a non-matching one on the same aspect (Angular's
@@ -2651,6 +2937,8 @@ declare function optionFilterRules(elements: FormElement[], targetId: string): {
2651
2937
  masterField: string;
2652
2938
  }[];
2653
2939
 
2940
+ /** Legacy formulas reference bare labels — wrap them in {…}, longest first. */
2941
+ declare function toBraceFormula(formula: string, labels: string[]): string;
2654
2942
  /**
2655
2943
  * Evaluate `formula` with `valueOf(label)` resolving field references.
2656
2944
  * Returns null when the formula is invalid or the result is not finite.
@@ -2658,6 +2946,125 @@ declare function optionFilterRules(elements: FormElement[], targetId: string): {
2658
2946
  declare function evaluateFormula(formula: string, valueOf: (label: string) => any, labels?: string[]): any;
2659
2947
  /** Labels a formula depends on (for recompute triggers). */
2660
2948
  declare function formulaLabels(formula: string, labels?: string[]): string[];
2949
+ /**
2950
+ * True when the platform can evaluate `formula` itself. The submission API
2951
+ * re-evaluates INPUT_FORMULA fields and rejects a mismatch ("Evaluated value
2952
+ * \"0\" and existing value \"8000\" … do not match"); it only resolves
2953
+ * `{Label}` references — bare labels (`MUL(Qty, Price)`) evaluate to 0 there.
2954
+ */
2955
+ declare function isServerSafeFormula(formula: string, labels?: string[]): boolean;
2956
+ /**
2957
+ * Recompute every INPUT_FORMULA cell of one sheet row (references are the
2958
+ * child form's labels). Returns a new row; other cells are untouched.
2959
+ */
2960
+ declare function computeRowFormulas(elements: {
2961
+ elementId: string;
2962
+ label: string;
2963
+ type: string;
2964
+ attributes?: any;
2965
+ properties?: any;
2966
+ }[], row: Record<string, any>): Record<string, any>;
2967
+
2968
+ type RuleEffect = "show" | "hide" | "required" | "optional" | "editable" | "read-only";
2969
+ interface RuleInsight {
2970
+ sourceId: string;
2971
+ sourceLabel: string;
2972
+ sourceValue: string;
2973
+ action: string;
2974
+ effect: RuleEffect;
2975
+ targetId: string;
2976
+ targetLabel: string;
2977
+ /** What the rule waits for, in words. */
2978
+ expected: string;
2979
+ matched: boolean;
2980
+ /** "triage" (properties.triage) or "dependencies". */
2981
+ origin: "triage" | "dependencies";
2982
+ }
2983
+ interface FilterInsight {
2984
+ targetId: string;
2985
+ targetLabel: string;
2986
+ sourceForm: string;
2987
+ kind: "dependent" | "dynamic" | "static";
2988
+ /** Label on the source form the filter is applied to. */
2989
+ masterField: string;
2990
+ /** The local field whose value feeds the filter (dependent / dynamic). */
2991
+ sourceLabel?: string;
2992
+ sourceValue?: string;
2993
+ /** Static filters: the configured value. */
2994
+ value?: string;
2995
+ active: boolean;
2996
+ }
2997
+ interface ValidationInsight {
2998
+ id: string;
2999
+ label: string;
3000
+ type: string;
3001
+ /** e.g. Accessories · row 2 — for sheet cells. */
3002
+ scope?: string;
3003
+ required: boolean;
3004
+ hidden: boolean;
3005
+ checks: string[];
3006
+ value: string;
3007
+ /** What validateField says right now. */
3008
+ error?: string;
3009
+ /** What the user currently sees (set on submit, cleared on change). */
3010
+ shownError?: string;
3011
+ }
3012
+ interface FormulaInsight {
3013
+ fieldId: string;
3014
+ label: string;
3015
+ scope: "form" | "row";
3016
+ sheetLabel?: string;
3017
+ row?: number;
3018
+ formula: string;
3019
+ /** The same formula with {Label} references — what the platform understands. */
3020
+ serverFormula: string;
3021
+ serverSafe: boolean;
3022
+ inputs: {
3023
+ label: string;
3024
+ value: any;
3025
+ }[];
3026
+ /** The library's result for the current inputs. */
3027
+ expected: any;
3028
+ /** The value that will be submitted. */
3029
+ current: any;
3030
+ inSync: boolean;
3031
+ }
3032
+ interface DefaultInsight {
3033
+ id: string;
3034
+ label: string;
3035
+ source: string;
3036
+ value: string;
3037
+ }
3038
+ interface PayloadInsight {
3039
+ formId: string;
3040
+ elements: any[];
3041
+ sheets: {
3042
+ fieldId: string;
3043
+ label: string;
3044
+ formId: string;
3045
+ rows: any[][];
3046
+ }[];
3047
+ }
3048
+ interface FormInspection {
3049
+ rules: RuleInsight[];
3050
+ filters: FilterInsight[];
3051
+ validation: ValidationInsight[];
3052
+ formulas: FormulaInsight[];
3053
+ defaults: DefaultInsight[];
3054
+ payload: PayloadInsight | null;
3055
+ summary: {
3056
+ rules: number;
3057
+ matched: number;
3058
+ filters: number;
3059
+ activeFilters: number;
3060
+ errors: number;
3061
+ formulas: number;
3062
+ formulaIssues: number;
3063
+ };
3064
+ }
3065
+ declare function inspectForm(form: ZvolvFormApi): FormInspection;
3066
+ /** inspectForm, memoised on the form's values, definition and loaded sheets. */
3067
+ declare function useFormInspector(form: ZvolvFormApi): FormInspection;
2661
3068
 
2662
3069
  /**
2663
3070
  * Authoring helpers: build a platform `create_form` payload and the FORM
@@ -2841,4 +3248,4 @@ declare function formWidget(o: {
2841
3248
  Description: string;
2842
3249
  };
2843
3250
 
2844
- export { ActionCardWidget, type ActionCardWidgetProps, type ActionConfig, type ActionItem, type ActionOutcome, type ActionRenderArgs, ActivityFeedWidget, type AggregationType, AreaChartWidget, type AxisConfig, type BadgeTone, BannerWidget, BarChartWidget, COLUMN_FILTER_BLANK, CONTAINER_KINDS, CalendarWidget, CardListWidget, CarouselWidget, type CellArgs, type ChartConfig, type ChartRenderArgs, ChartWidget, type ChartWidgetProps, ChildTableWidget, type CollectionConfig, type CollectionItem, type CollectionMappingConfig, type CollectionRenderArgs, CollectionWidget, type CollectionWidgetProps, type ColumnFilterSlotArgs, type ColumnFilters, type CreateZvolvRuntimeOptions, type DashboardFilterDef, type DashboardFilterValue, type DashboardNode, DashboardTableWidget, type DataSourceDefinition, type DataSourceField, DatabaseTableWidget, type DateGapUnit, type DateRange, type DateRangeToken, type DateToken, type DeepPartial, DefaultField, DoughnutChartWidget, EMPTY_INTERACTIONS, type ElementSpec, EntityGalleryWidget, type FieldFilter, type FieldKind, type FieldOption, type FieldOptionsState, type FileFieldState, type FileItem, type FilterControl, type FilterOperator, type FilterPanelConfig, type FilterPanelRenderArgs, FilterPanelWidget, type FilterPanelWidgetProps, type FilterableField, FormApiContext, type FormConfig, type FormDefinition, type FormElement, type FormErrors, type FormField, FormFields, type FormKit, FormKitSlot, type FormMode, type FormSpec, type FormStatus, type FormValues, FormWidget, type FormWidgetProps, GRID, GanttChartWidget, type GaugeConfig, GaugeMeterWidget, type GaugeMeterWidgetProps, type GaugeRenderArgs, GoogleMapWidget, GridCardWidget, type GridItem, type HeatCell, type HeatMapConfig, type HeatMapRenderArgs, HeatMapWidget, type HeatMapWidgetProps, type HtmlConfig, type HtmlRenderArgs, HtmlWidget, type HtmlWidgetProps, type IframeConfig, IframeWidget, type IframeWidgetProps, type InteractionMode, type InteractionProps, type InteractionStateProps, type InteractionUiProps, type InteractiveWidgetData, type InteractiveWidgetProps, KPI_DEFAULT_TEMPLATES, type KpiConfig, type KpiContentConfig, type KpiContentVM, Delta as KpiDelta, Label as KpiLabel, Sparkline as KpiSparkline, type KpiTemplateId, type KpiTemplateProps, Value as KpiValue, KpiWidget, type KpiWidgetProps, type LegendConfig, LineChartWidget, type LookupConfig, type MapConfig, type MapMarker, type MapRenderArgs, type MapWidgetProps, type MasterFieldDataType, type MasterFieldType, MeetingSchedulerWidget, type MockQuery, type MockRuntimeOptions, NON_INPUT_TYPES, NON_RENDERING_TYPES, type NormalizedWidget, PREFIX_UNITS, PieChartWidget, type PivotConfig, type PivotFilter, PivotGridWidget, type PivotGridWidgetProps, type PivotRenderArgs, type PivotRow, type PivotSummary, type PostOperation, type PostOperator, RankingBarWidget, type RankingBarWidgetProps, type RankingConfig, type RankingRenderArgs, type RankingRow, RawHtmlWidget, type ResolvedChromeConfig, type RuleOverride, SAMPLE_ROWS, SUBMISSION_SKIP_TYPES, SUFFIX_UNITS, ScatterChartWidget, type SearchSlotArgs, type SeriesConfig, type SheetColumn, type SheetFieldState, type SortDirection, type SortSlotArgs, type SortState, type StepItem, type StepperConfig, type StepperRenderArgs, StepperWidget, type StepperWidgetProps, type SubmitOptions, type TabConfig, type TabItem, type TabRenderArgs, TabWidget, type TabWidgetProps, type TableColumn, type TableColumnConfig, type TableConfig, type TableRenderArgs, TableWidget, type TableWidgetProps, TaskTrackerTableWidget, type TemplateComponent, type TemplateMap, TemplateProvider, type TemporalConfig, type TemporalEvent, type TemporalMappingConfig, type TemporalRenderArgs, TemporalWidget, type TemporalWidgetProps, TimelineWidget, type Tone, type ToolbarSlotArgs, type TreeConfig, type TreeNode, type TreeRenderArgs, TreeWidget, type TreeWidgetProps, type UploadedFile, type UseKpiContentsArgs, type UseWidgetDataArgs, type UseZvolvFormArgs, WIDGET_REGISTRY, type WidgetChrome, type WidgetChromeConfig, type WidgetConfigurations, type WidgetDataResult, type WidgetDefinition, type WidgetFilter, type WidgetFilterSlotArgs, type WidgetInteractionState, type WidgetInteractions, WidgetShell, type WidgetShellProps, type WidgetState, type WidgetStateRenderArgs, WidgetStateSlot, type WidgetStyleOverrides, type WidgetTypeId, ZaiChatWidget, type ZaiChatWidgetProps, type ZvolvDataSource, ZvolvForm, type ZvolvFormApi, type ZvolvFormProps, ZvolvProvider, type ZvolvProviderProps, type ZvolvRuntime, ZvolvThemeProvider, type ZvolvTokens, ZvolvWidget, type ZvolvWidgetProps, aggregate, alignSummaryToSeries, applyLocalColumnFilters, applyLocalSearch, applyLocalSort, applyLocalWidgetFilters, applyPostOperations, applyRules, automationSource, buildColumnFilterClauses, buildDashFilters, buildDashboardTree, buildInitialValues, buildRemoteSort, buildSearchClause, buildSubmissionElements, buildTree, buildTriggerBody, buildWidgetFilterClauses, cascade, cdateFiltersFor, childIdsOf, cleanTitle, clearLookupCache, coerceSeriesNumbers, createMockRuntime, createSubmission, createZvolvRuntime, dashboardDefaultDateToken, dashboardFilterDefs, dateRangeFor, defaultTokens, defineConfig, defineForm, derive, describeWidgetFilter, distinctColumnValues, eid, el, evaluateFormula, fetchForm, fetchLookupOptions, fetchSubmission, field, fieldKind, fieldKindOf, fillDateGaps, filterableFields, formSource, formWidget, formatAmountValue, formatCompact, formatFieldValue, formulaLabels, getDataType, getEmptyValue, getPostOpOperandSet, getPostOpResult, gridHeight, gridWidgets, groupBy, hasActiveInteractions, interpolate, invokeTrigger, isDataSourceConfigured, isLegacyId, isLikelyTimestamp, lookupConfigOf, mergeTokens, normaliseElement, normaliseForm, normalizeWidget, operatorsForKind, optionFilterRules, parseConfig, parseDeep, pivot, renderHtmlVariables, resetQueryUser, resolveChrome, resolveChromeConfig, resolveCollectionMapping, resolveDashboardLayout, resolveDateToken, resolveDrillDown, resolveFieldType, resolveFilterMode, resolveFormWidget, resolveSeries, resolveTableMode, resolveWidget, resolveWidgetDefaults, resolveXKey, rowSubmissionIds, ruleMatches, searchPeople, serializeElementValue, statusTone, submissionIdOf, submissionToValues, taskField, taskSource, toNum, toRelational, toneColor, toneSurface, updateSubmission, uploadFile, useCollectionItems, useFieldOptions, useFileField, useFormApi, useInteractiveWidgetData, useKpiContents, useSheetField, useTableColumns, useTemplateOverride, useTemporalEvents, useTokens, useWidgetData, useWidgetInteractions, useZvolvClient, useZvolvForm, useZvolvRuntime, usesFormFramework, validateField, validateForm, when, where };
3251
+ export { ActionCardWidget, type ActionCardWidgetProps, type ActionConfig, type ActionItem, type ActionOutcome, type ActionRenderArgs, ActivityFeedWidget, type AggregateOptions, type AggregationType, AreaChartWidget, type AxisConfig, BLOCKED_FILE_EXTENSIONS, type BadgeTone, BannerWidget, BarChartWidget, COLUMN_FILTER_BLANK, CONTAINER_KINDS, CalendarWidget, CardListWidget, CarouselWidget, type CellArgs, type ChartConfig, type ChartRenderArgs, ChartWidget, type ChartWidgetProps, ChildTableWidget, type CollectionConfig, type CollectionItem, type CollectionMappingConfig, type CollectionRenderArgs, CollectionWidget, type CollectionWidgetProps, type ColumnFilterSlotArgs, type ColumnFilters, type CreateZvolvRuntimeOptions, type DashboardFilterDef, type DashboardFilterValue, type DashboardNode, DashboardTableWidget, type DataSourceDefinition, type DataSourceField, DatabaseTableWidget, type DateDiffField, type DateDiffSpec, type DateDiffUnit, type DateGapOptions, type DateGapUnit, type DateInterval, type DateRange, type DateRangeToken, type DateToken, type DeepPartial, DefaultField, type DefaultInsight, DoughnutChartWidget, EMPTY_INTERACTIONS, type ElementSpec, EntityGalleryWidget, type FieldFilter, type FieldKind, type FieldOption, type FieldOptionsState, type FileFieldState, type FileItem, type FillDateGapsArgs, type FilterControl, type FilterInsight, type FilterOperator, type FilterPanelConfig, type FilterPanelRenderArgs, FilterPanelWidget, type FilterPanelWidgetProps, type FilterableField, FormApiContext, type FormConfig, type FormDefinition, type FormElement, type FormErrors, type FormField, FormFields, type FormInspection, type FormKit, FormKitSlot, type FormMode, type FormSpec, type FormStatus, type FormValues, FormWidget, type FormWidgetProps, type FormulaInsight, GRID, GanttChartWidget, type GaugeConfig, GaugeMeterWidget, type GaugeMeterWidgetProps, type GaugeRenderArgs, GoogleMapWidget, GridCardWidget, type GridItem, type HeatCell, type HeatMapConfig, type HeatMapRenderArgs, HeatMapWidget, type HeatMapWidgetProps, type HtmlConfig, type HtmlRenderArgs, HtmlWidget, type HtmlWidgetProps, type IframeConfig, IframeWidget, type IframeWidgetProps, type InteractionMode, type InteractionProps, type InteractionStateProps, type InteractionUiProps, type InteractiveWidgetData, type InteractiveWidgetProps, KPI_DEFAULT_TEMPLATES, type KpiConfig, type KpiContentConfig, type KpiContentVM, Delta as KpiDelta, Label as KpiLabel, Sparkline as KpiSparkline, type KpiTemplateId, type KpiTemplateProps, type KpiTimeseriesSource, Value as KpiValue, KpiWidget, type KpiWidgetProps, type LegendConfig, LineChartWidget, type LookupConfig, type MapConfig, type MapMarker, type MapRenderArgs, type MapWidgetProps, type MasterFieldDataType, type MasterFieldType, MeetingSchedulerWidget, type MockQuery, type MockRuntimeOptions, NON_INPUT_TYPES, NON_RENDERING_TYPES, type NormalizedWidget, type OpenFormRequest, PREFIX_UNITS, type PayloadInsight, PieChartWidget, type PivotConfig, type PivotFilter, PivotGridWidget, type PivotGridWidgetProps, type PivotRenderArgs, type PivotRow, type PivotSummary, type PostOperation, type PostOperator, RankingBarWidget, type RankingBarWidgetProps, type RankingConfig, type RankingRenderArgs, type RankingRow, RawHtmlWidget, type ResolvedChromeConfig, type RuleEffect, type RuleInsight, type RuleOverride, SAMPLE_ROWS, SUBMISSION_SKIP_TYPES, SUFFIX_UNITS, ScatterChartWidget, type SearchSlotArgs, type SeriesConfig, type SheetColumn, type SheetFieldState, type SortDirection, type SortSlotArgs, type SortState, type StepItem, type StepperConfig, type StepperRenderArgs, StepperWidget, type StepperWidgetProps, type SubmitOptions, type TabConfig, type TabItem, type TabRenderArgs, TabWidget, type TabWidgetProps, type TableColumn, type TableColumnConfig, type TableConfig, type TableRenderArgs, TableWidget, type TableWidgetProps, TaskTrackerTableWidget, type TemplateComponent, type TemplateMap, TemplateProvider, type TemporalConfig, type TemporalEvent, type TemporalMappingConfig, type TemporalRenderArgs, TemporalWidget, type TemporalWidgetProps, TimelineWidget, type Tone, type ToolbarSlotArgs, type TreeConfig, type TreeNode, type TreeRenderArgs, TreeWidget, type TreeWidgetProps, type TrialButton, type TrialFieldState, type TrialLogEntry, type UploadedFile, type UseKpiContentsArgs, type UseWidgetDataArgs, type UseZvolvFormArgs, type ValidationInsight, WIDGET_REGISTRY, type WidgetChrome, type WidgetChromeConfig, type WidgetConfigurations, type WidgetDataResult, type WidgetDefinition, type WidgetFilter, type WidgetFilterSlotArgs, type WidgetInteractionState, type WidgetInteractions, WidgetShell, type WidgetShellProps, type WidgetState, type WidgetStateRenderArgs, WidgetStateSlot, type WidgetStyleOverrides, type WidgetTypeId, ZaiChatWidget, type ZaiChatWidgetProps, type ZvolvDataSource, ZvolvForm, type ZvolvFormApi, type ZvolvFormProps, ZvolvProvider, type ZvolvProviderProps, type ZvolvRuntime, ZvolvThemeProvider, type ZvolvTokens, ZvolvWidget, type ZvolvWidgetProps, addPeriod, aggregate, alignSummaryToSeries, applyCumulative, applyLocalColumnFilters, applyLocalSearch, applyLocalSort, applyLocalWidgetFilters, applyPostOperations, applyRules, automationSource, buildColumnFilterClauses, buildDashFilters, buildDashboardTree, buildInitialValues, buildRemoteSort, buildSearchClause, buildSubmissionElements, buildTree, buildTriggerBody, buildWidgetFilterClauses, cascade, cdateFiltersFor, childIdsOf, cleanTitle, clearLookupCache, coerceSeriesNumbers, computeRowFormulas, createMockRuntime, createSubmission, createZvolvRuntime, dashboardDefaultDateToken, dashboardFilterDefs, dateDiff, dateRangeFor, defaultTokens, defineConfig, defineForm, derive, describeWidgetFilter, distinctColumnValues, eid, el, evaluateFormula, extractAgentFormData, fetchForm, fetchLookupOptions, fetchSubmission, field, fieldKind, fieldKindOf, fillDateGaps, filterableFields, flattenPercentiles, formSource, formWidget, formatAmountValue, formatCompact, formatFieldValue, formulaLabels, getDataType, getEmptyValue, getPostOpOperandSet, getPostOpResult, gridHeight, gridWidgets, groupBy, hasActiveInteractions, inspectForm, interpolate, invokeAgent, invokeTrigger, invokeZeno, isDataSourceConfigured, isLegacyId, isLikelyTimestamp, isServerSafeFormula, lookupConfigOf, mergeTokens, normaliseElement, normaliseForm, normalizeWidget, openFormRequest, operatorsForKind, optionFilterRules, parseConfig, parseDateValue, parseDeep, percentileKey, pivot, renderHtmlVariables, resetQueryUser, resolveChrome, resolveChromeConfig, resolveCollectionMapping, resolveDashboardLayout, resolveDateToken, resolveDrillDown, resolveFieldType, resolveFilterMode, resolveFormWidget, resolveSeries, resolveTableMode, resolveWidget, resolveWidgetDefaults, resolveXKey, rowSubmissionIds, ruleMatches, rulesOf, searchPeople, serializeElementValue, startOfPeriod, statusTone, submissionIdOf, submissionToValues, submitElementsOf, taskField, taskSource, toBraceFormula, toNum, toRelational, toneColor, toneSurface, updateSubmission, uploadFile, useCollectionItems, useFieldOptions, useFileField, useFormApi, useFormInspector, useInteractiveWidgetData, useKpiContents, useSheetField, useTableColumns, useTemplateOverride, useTemporalEvents, useTokens, useTrialField, useWidgetData, useWidgetInteractions, useZvolvClient, useZvolvForm, useZvolvRuntime, usesFormFramework, validateField, validateForm, when, where };