@altertable/data-app 0.69.0 → 0.70.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 (107) hide show
  1. package/AGENTS.md +4 -0
  2. package/dist/chunks/{index-m0gbxtgp.js → index-2ajhmsc4.js} +3 -3
  3. package/dist/chunks/{index-m0gbxtgp.js.map → index-2ajhmsc4.js.map} +1 -1
  4. package/dist/chunks/{index-2sbp9h2b.js → index-58kks6a8.js} +1 -1
  5. package/dist/chunks/{index-2sbp9h2b.js.map → index-58kks6a8.js.map} +2 -2
  6. package/dist/chunks/{index-ap60vggk.js → index-7q99hf1z.js} +18 -11
  7. package/dist/chunks/index-7q99hf1z.js.map +10 -0
  8. package/dist/chunks/{index-kwnqycjt.js → index-9zqbrv2z.js} +7 -3
  9. package/dist/chunks/index-9zqbrv2z.js.map +10 -0
  10. package/dist/chunks/{index-k766wwwr.js → index-q1w84fv9.js} +167 -24
  11. package/dist/chunks/index-q1w84fv9.js.map +15 -0
  12. package/dist/chunks/{index-zcqxfwdq.js → index-rew95tbg.js} +85 -10
  13. package/dist/chunks/index-rew95tbg.js.map +13 -0
  14. package/dist/chunks/{index-qhzdzca2.js → index-vtpygsbq.js} +2392 -991
  15. package/dist/chunks/index-vtpygsbq.js.map +126 -0
  16. package/dist/chunks/{index-r7b1ftwy.js → index-wjt6cavj.js} +5 -3
  17. package/dist/chunks/index-wjt6cavj.js.map +10 -0
  18. package/dist/chunks/{index-sx488hvs.js → index-xzb7sx6g.js} +3 -3
  19. package/dist/client/index.js +5 -5
  20. package/dist/core/config.js +2 -2
  21. package/dist/core/contract.js +6 -6
  22. package/dist/core/contract.js.map +1 -1
  23. package/dist/embed/index.js +5 -5
  24. package/dist/index.js +2 -2
  25. package/dist/local.js +35 -2
  26. package/dist/local.js.map +8 -6
  27. package/dist/preview.js +15 -15
  28. package/dist/preview.js.map +6 -6
  29. package/dist/react/embed/index.js +1 -1
  30. package/dist/react/index.js +273 -331
  31. package/dist/react/index.js.map +5 -8
  32. package/dist/react/ui/index.js +874 -502
  33. package/dist/react/ui/index.js.map +24 -23
  34. package/dist/server.js +35 -2
  35. package/dist/server.js.map +8 -6
  36. package/dist/types/client/data-client.d.ts +21 -10
  37. package/dist/types/core/config.d.ts +20 -17
  38. package/dist/types/core/contract.d.ts +23 -13
  39. package/dist/types/core/dimension-source.d.ts +64 -0
  40. package/dist/types/core/dimension.d.ts +31 -23
  41. package/dist/types/core/facets.d.ts +13 -0
  42. package/dist/types/core/keys.d.ts +2 -0
  43. package/dist/types/core/operation-types.d.ts +6 -5
  44. package/dist/types/core/queries.d.ts +75 -7
  45. package/dist/types/core/variables.d.ts +38 -12
  46. package/dist/types/embed/sql.d.ts +1 -1
  47. package/dist/types/index.d.ts +1 -1
  48. package/dist/types/react/actions.d.ts +53 -0
  49. package/dist/types/react/bindings.d.ts +36 -0
  50. package/dist/types/react/details.d.ts +46 -0
  51. package/dist/types/react/exploration.d.ts +44 -0
  52. package/dist/types/react/hooks.d.ts +76 -38
  53. package/dist/types/react/index.d.ts +3 -0
  54. package/dist/types/react/style-contract.d.ts +1 -1
  55. package/dist/types/react/ui/AboutData.d.ts +9 -4
  56. package/dist/types/react/ui/AreaChart.d.ts +2 -2
  57. package/dist/types/react/ui/BarChart.d.ts +2 -2
  58. package/dist/types/react/ui/Button.d.ts +2 -1
  59. package/dist/types/react/ui/ComposedChartLegend.d.ts +2 -1
  60. package/dist/types/react/ui/DataApp.d.ts +3 -0
  61. package/dist/types/react/ui/DataWidget.d.ts +3 -0
  62. package/dist/types/react/ui/DimensionPicker.d.ts +2 -2
  63. package/dist/types/react/ui/ExplorationActionControl.d.ts +60 -0
  64. package/dist/types/react/ui/InspectionProvider.d.ts +2 -2
  65. package/dist/types/react/ui/LineChart.d.ts +2 -2
  66. package/dist/types/react/ui/Menu.d.ts +3 -2
  67. package/dist/types/react/ui/MetricWidget.d.ts +2 -0
  68. package/dist/types/react/ui/PickerField.d.ts +9 -1
  69. package/dist/types/react/ui/PieChart.d.ts +2 -2
  70. package/dist/types/react/ui/Select.d.ts +5 -1
  71. package/dist/types/react/ui/Sheet.d.ts +1 -1
  72. package/dist/types/react/ui/TrendChart.d.ts +3 -3
  73. package/dist/types/react/ui/VisualizationWidget.d.ts +1 -1
  74. package/dist/types/react/ui/chart-data.d.ts +8 -6
  75. package/dist/types/react/ui/chart-date-axis.d.ts +1 -1
  76. package/dist/types/react/ui/chart-interaction.d.ts +15 -9
  77. package/dist/types/react/ui/chart-time.d.ts +8 -5
  78. package/dist/types/react/ui/icons.d.ts +2 -0
  79. package/dist/types/react/ui/index.d.ts +2 -0
  80. package/dist/types/react/ui/use-chart-scroll-to-end.d.ts +2 -0
  81. package/dist/types/react/view-control-bar.d.ts +6 -4
  82. package/dist/types/react/view-runtime.d.ts +5 -2
  83. package/dist/types/react/view.d.ts +15 -6
  84. package/dist/types/react/widgets.d.ts +22 -11
  85. package/dist/worker.js +1 -1
  86. package/docs/app-authoring.md +10 -3
  87. package/docs/client.md +5 -6
  88. package/docs/composition.md +84 -0
  89. package/docs/contract.md +41 -21
  90. package/docs/data-context.md +2 -0
  91. package/docs/server.md +1 -1
  92. package/docs/styling.md +4 -0
  93. package/docs/ui.md +12 -1
  94. package/docs/variables.md +83 -11
  95. package/docs/views.md +56 -2
  96. package/docs/widgets.md +93 -0
  97. package/examples/starter-data-app/index.tsx +10 -22
  98. package/examples/starter-local-data-app/app.ts +7 -1
  99. package/examples/starter-local-data-app/tsconfig.json +7 -1
  100. package/package.json +1 -1
  101. package/dist/chunks/index-ap60vggk.js.map +0 -10
  102. package/dist/chunks/index-k766wwwr.js.map +0 -13
  103. package/dist/chunks/index-kwnqycjt.js.map +0 -10
  104. package/dist/chunks/index-qhzdzca2.js.map +0 -118
  105. package/dist/chunks/index-r7b1ftwy.js.map +0 -10
  106. package/dist/chunks/index-zcqxfwdq.js.map +0 -13
  107. /package/dist/chunks/{index-sx488hvs.js.map → index-xzb7sx6g.js.map} +0 -0
@@ -1,3 +1,6 @@
1
+ import { type ExplorationActions } from './actions.js';
2
+ import { type BreakdownTarget } from './exploration.js';
3
+ import { type ItemActions } from './ui/ExplorationActionControl.js';
1
4
  import { type Dataset, type Metric, type ViewSource } from './bindings.js';
2
5
  import { type MetricWidgetProps as DisplayMetricProps } from './ui/MetricWidget.js';
3
6
  import { type TableWidgetProps as DisplayTableProps, type TableDisplayMode } from './ui/TableWidget.js';
@@ -8,29 +11,35 @@ import type { MetricValues } from '../core/reading.js';
8
11
  import type { MetricDefinition } from './ui/metric.js';
9
12
  import type { ReactNode } from 'react';
10
13
  import type { DataReading } from '../core/reading.js';
14
+ import { MetricRecords } from './bindings.js';
11
15
  export type MetricWidgetProps<Data = unknown, Input = unknown> = Omit<Extract<DisplayMetricProps, {
12
16
  metric: MetricDefinition;
13
- }>, 'metric' | 'reading'> & {
17
+ }>, 'metric' | 'reading' | 'records'> & {
14
18
  metric: Metric<Data, Input>;
15
- source: ViewSource<Data, Input>;
19
+ source: ViewSource<NoInfer<Data>, NoInfer<Input>>;
20
+ records?: MetricRecords<Data, Input, any, any>;
21
+ actions?: ExplorationActions<void, NoInfer<Input>>;
16
22
  };
17
- export declare function MetricWidget<Data, Input>({ metric, source, ...presentation }: MetricWidgetProps<Data, Input>): import("react").JSX.Element;
23
+ export declare function MetricWidget<Data, Input>({ metric, source, records, actions, action, ...presentation }: MetricWidgetProps<Data, Input>): import("react").JSX.Element;
18
24
  type BoundTableProps<Row> = Extract<DisplayTableProps<Row>, {
19
25
  reading: DataReading<readonly Row[]>;
20
26
  }>;
21
27
  type TablePresentation<Row> = Pick<BoundTableProps<Row>, 'title' | 'columns' | 'rowKey' | 'reading' | 'evidence' | 'emptyFallback'>;
22
28
  export type TableWidgetProps<Row, Data = unknown, Input = unknown> = Omit<BoundTableProps<Row>, keyof TablePresentation<Row> | 'limit' | 'pagination'> & TableDisplayMode & {
23
29
  dataset: Dataset<Data, Input, Row>;
24
- source: ViewSource<Data, Input>;
30
+ source: ViewSource<NoInfer<Data>, NoInfer<Input>>;
25
31
  title?: ReactNode;
32
+ actions?: ExplorationActions<NoInfer<Row>, NoInfer<Input>>;
26
33
  };
27
- export declare function TableWidget<Row, Data, Input>({ dataset, source, title, ...presentation }: TableWidgetProps<Row, Data, Input>): import("react").JSX.Element;
34
+ export declare function TableWidget<Row, Data, Input>({ dataset, source, title, actions, ...presentation }: TableWidgetProps<Row, Data, Input>): import("react").JSX.Element;
28
35
  type BoundVisual<Row> = Extract<DisplayVisualProps<readonly Row[]>, {
29
36
  reading: DataReading<readonly Row[]>;
30
37
  }>;
31
- export type VisualizationWidgetView<Row> = DisplayVisualizationView<readonly Row[]>;
38
+ export type VisualizationWidgetView<Row> = Omit<DisplayVisualizationView<readonly Row[]>, 'render'> & {
39
+ render: (rows: readonly Row[], actions: ItemActions<Row>) => ReactNode;
40
+ };
32
41
  type VisualContent<Row> = {
33
- children: (rows: readonly Row[]) => ReactNode;
42
+ children: (rows: readonly Row[], actions: ItemActions<Row>) => ReactNode;
34
43
  views?: never;
35
44
  viewLabel?: never;
36
45
  initialView?: never;
@@ -42,19 +51,21 @@ type VisualContent<Row> = {
42
51
  };
43
52
  export type VisualizationWidgetProps<Row, Data = unknown, Input = unknown> = Omit<BoundVisual<Row>, 'reading' | 'isEmpty' | 'emptyFallback' | 'evidence' | 'title' | 'children' | 'views' | 'viewLabel' | 'initialView'> & VisualContent<Row> & {
44
53
  dataset: Dataset<Data, Input, Row>;
45
- source: ViewSource<Data, Input>;
54
+ source: ViewSource<NoInfer<Data>, NoInfer<Input>>;
46
55
  title?: ReactNode;
56
+ actions?: ExplorationActions<NoInfer<Row>, NoInfer<Input>>;
57
+ breakdown?: BreakdownTarget<any>;
47
58
  };
48
- export declare function VisualizationWidget<Row, Data, Input>({ dataset, source, title, ...presentation }: VisualizationWidgetProps<Row, Data, Input>): import("react").JSX.Element;
59
+ export declare function VisualizationWidget<Row, Data, Input>({ dataset, source, title, actions, breakdown, children, views, viewLabel, initialView, ...presentation }: VisualizationWidgetProps<Row, Data, Input>): import("react").JSX.Element;
49
60
  type NarrativeBinding<Data, Input, Row> = {
50
61
  metric: Metric<Data, Input>;
51
62
  dataset?: never;
52
- source: ViewSource<Data, Input>;
63
+ source: ViewSource<NoInfer<Data>, NoInfer<Input>>;
53
64
  children?: (values: MetricValues) => ReactNode;
54
65
  } | {
55
66
  metric?: never;
56
67
  dataset: Dataset<Data, Input, Row>;
57
- source: ViewSource<Data, Input>;
68
+ source: ViewSource<NoInfer<Data>, NoInfer<Input>>;
58
69
  children: (rows: readonly Row[]) => ReactNode;
59
70
  };
60
71
  export type TextWidgetProps<Data = unknown, Input = unknown, Row = never> = Omit<Extract<DisplayTextProps<unknown>, {
package/dist/worker.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/embed/runtime-html.ts
2
2
  var PAGE_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'none'; form-action 'none'; base-uri 'none'";
3
- var inlineBootstrap = '(()=>{function D(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,(n)=>n.toString(16).padStart(2,"0"));return[t.slice(0,4),t.slice(4,6),t.slice(6,8),t.slice(8,10),t.slice(10)].map((n)=>n.join("")).join("-")}function Z(e){if(!e||typeof e!=="object")return!1;let t=e;return(t.method==="log"||t.method==="info"||t.method==="warn"||t.method==="error")&&Array.isArray(t.args)&&t.args.length<=128}var F="altertable:data-app";var Y=128,ee=60000;function P(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,128}$/.test(e)}function w({wire:e,from:t,session:n,parse:r}){return{wire:e,from:t,session:n,parse:r}}function L(e){if(!P(e.id))throw Error("Invalid request ID.");return e.id}function S(e,t){let n=e[t];if(typeof n!=="string")throw Error(`Invalid ${t}.`);return n}function j(){return{}}var h={channel:F,version:1,events:{connect:w({wire:"bridge:connect",from:"host",session:"none",parse:j}),ready:w({wire:"bridge:ready",from:"app",session:"none",parse:j}),initialize:w({wire:"bridge:initialize",from:"host",session:"establish",parse:(e)=>({state:e.state})}),request:w({wire:"bridge:request",from:"app",session:"current",parse:(e)=>{let t=S(e,"route");if(!t||t.length>256)throw Error("Invalid message route.");return{id:L(e),route:t,payload:e.payload}}}),result:w({wire:"bridge:result",from:"host",session:"current",parse:(e)=>{if(!Object.hasOwn(e,"response"))throw Error("Missing response.");return{id:L(e),response:e.response}}}),error:w({wire:"bridge:error",from:"host",session:"current",parse:(e)=>{if(e.requestId!==void 0&&typeof e.requestId!=="string")throw Error("Invalid requestId.");return{id:L(e),code:S(e,"code"),message:S(e,"message"),...e.requestId===void 0?{}:{requestId:e.requestId}}}}),cancel:w({wire:"bridge:cancel",from:"app",session:"current",parse:(e)=>({id:L(e)})}),disconnect:w({wire:"bridge:disconnect",from:"app",session:"current",parse:j}),scriptLoad:w({wire:"script:load",from:"host",session:"current",parse:(e)=>({javascript:S(e,"javascript")})}),stateUpdate:w({wire:"state:update",from:"host",session:"current",parse:(e)=>({state:e.state})}),runtimeLog:w({wire:"runtime:log",from:"app",session:"current",parse:(e)=>{if(!Z(e.payload))throw Error("Invalid log entry.");return{payload:e.payload}}}),runtimeReady:w({wire:"runtime:ready",from:"app",session:"current",parse:j}),runtimeError:w({wire:"runtime:error",from:"app",session:"current",parse:j})}};function W(e){let t={type:e.type};if("id"in e)t.id=e.id;if(e.type==="bridge:request"){t.route=e.route;let n=e.payload;if(e.route==="data:query"&&n&&typeof n==="object"&&"operation"in n&&typeof n.operation==="string")t.operation=n.operation.slice(0,256)}if(e.type==="bridge:error")t.error={code:e.code,message:e.message,...e.requestId===void 0?{}:{requestId:e.requestId}};return t}var C=new Map;for(let e of Object.keys(h.events)){let t=h.events[e].wire;if(C.has(t))throw Error(`Duplicate bridge event: ${t}`);C.set(t,e)}function z(e){return C.get(e)}function V(e){if(!e||typeof e!=="object")return;let t=e;if(t.channel!==F||t.version!==h.version||typeof t.type!=="string"||typeof t.documentId!=="string"||!t.documentId||t.documentId.length>128||t.sessionId!==void 0&&!P(t.sessionId)||t.token!==void 0&&typeof t.token!=="string")return;return t}function H(e,t){try{return{channel:F,version:h.version,documentId:e.documentId,...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.token===void 0?{}:{token:e.token},type:t.wire,...t.parse(e)}}catch{return}}function te(e){let t=V(e);if(!t)return;let n=z(t.type);if(!n)return;let r=h.events[n];if(r.session!=="none"&&t.sessionId===void 0)return;return H(t,r)}function ne({role:e,origin:t,source:n,opaque:r,context:o,post:a,diagnostic:l,invalidRequest:u,handlers:f}){let c=!1;function i(y,p){l?.({direction:"drop",reason:y,...typeof p==="string"?{type:p.slice(0,64)}:{}})}function v(y,p){if(c)throw Error("The bridge endpoint has closed.");let d=h.events[y],g=o(),x=te({...p,channel:h.channel,version:h.version,type:d.wire,documentId:y==="connect"?"host":g.documentId,sessionId:g.sessionId,token:r?g.token:void 0});if(!x||r&&!P(g.token))throw Error("The bridge is not ready to send this event.");if(l?.({direction:"send",...W(x)}),c)return;a(x)}function B(y){let p=n();if(c||!p||y.origin!==t||y.source!==p)return;let d=V(y.data);if(!d){let k=y.data;if(k&&typeof k==="object"&&"channel"in k&&k.channel===h.channel)i("invalid_envelope","type"in k?k.type:void 0);return}let g=o(),x=e==="app"&&d.type===h.events.connect.wire;if(r&&(x?!P(d.token):!g.token||d.token!==g.token))return i("token_mismatch",d.type);let M=z(d.type);if(!M)return i("unexpected_type",d.type);let T=h.events[M];if(T.from===e)return i("unexpected_type",d.type);if(T.session==="establish"){if(d.documentId!==g.documentId||d.sessionId===void 0)return i("session_mismatch",d.type)}else if(T.session==="current"){if(!g.sessionId||d.sessionId!==g.sessionId||d.documentId!==g.documentId)return i("session_mismatch",d.type)}let q=H(d,T);if(!q){if(i("invalid_payload",d.type),e==="host"&&M==="request"&&P(d.id))u?.(d.id);return}if(l?.({direction:"receive",...W(q)}),c)return;let Q=f[M];Q(q)}return{send:v,receive:B,dispose(){c=!0}}}function we(e){return e===null||typeof e==="string"||typeof e==="boolean"||typeof e==="number"&&Number.isFinite(e)}function G(e){return!!e&&typeof e==="object"&&!Array.isArray(e)&&Object.values(e).every(we)}var re=Symbol.for("@altertable/data-app/MessageRoutingError");class I extends Error{code;requestId;[re]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[re]===!0}constructor(e,t,n,r){super(t,r);this.code=e;this.requestId=n;this.name="MessageRoutingError"}}function he(e){return e}function oe(e){return{operations:e,input(t){if(!t||typeof t!=="object")throw Error("Invalid query.");let n=t;if(typeof n.operation!=="string"||!n.operation||n.operation.length>256||n.operation.includes("/"))throw Error("Invalid operation.");let r=e&&Object.hasOwn(e,n.operation)?e[n.operation]:void 0;if(e&&!r)throw Error("Unknown operation.");return{operation:n.operation,input:r?r.input(n.input):n.input}},output(t){if(!t||typeof t!=="object")throw Error("Invalid data response.");let n=t;if(!Number.isInteger(n.status)||n.status<100||n.status>599||!n.body||typeof n.body!=="object"||Array.isArray(n.body))throw Error("Invalid data response.");let r=n.body;if(n.status<200||n.status>=300){let o=r.error;throw new I(typeof o?.code==="string"?o.code:"request_failed",typeof o?.message==="string"?o.message:"Could not load data.",typeof o?.requestId==="string"?o.requestId:void 0)}if(!("data"in r)||typeof r.requestId!=="string"||typeof r.queriedAt!=="string"||!Array.isArray(r.queryIds)||!r.queryIds.every((o)=>typeof o==="string"))throw Error("Invalid data envelope.");if(r.queries!==void 0&&(!Array.isArray(r.queries)||!r.queries.every((o)=>o&&typeof o==="object"&&typeof o.name==="string"&&typeof o.statement==="string"&&(o.params===void 0||G(o.params))&&(o.queryId===void 0||typeof o.queryId==="string"))))throw Error("Invalid query evidence.");return{status:n.status,body:r}}}}var se=he({input(e){if(!e||typeof e!=="object")throw Error("Invalid SQL query.");let t=e;if(typeof t.statement!=="string"||!t.statement.trim()||typeof t.limit!=="number"||!Number.isSafeInteger(t.limit)||t.limit<1||t.params!==void 0&&!G(t.params))throw Error("Invalid SQL query.");return{statement:t.statement,limit:t.limit,...t.params===void 0?{}:{params:t.params}}},output(e,t){if(!e||typeof e!=="object")throw Error("Invalid query result.");let n=e;if(!Array.isArray(n.columns)||!n.columns.every((r)=>r&&typeof r.name==="string"&&(r.type===void 0||typeof r.type==="string"))||!Array.isArray(n.rows)||n.rows.length>t.limit||!n.rows.every((r)=>Array.isArray(r)&&r.length===n.columns.length)||n.queryId!==void 0&&typeof n.queryId!=="string")throw Error("Invalid query result.");return{columns:n.columns,rows:n.rows,...n.queryId===void 0?{}:{queryId:n.queryId}}}});function ie(e,t){return{async request(n,r,{signal:o}={}){if(o?.throwIfAborted(),!Object.hasOwn(e,n))throw new I("unknown_route","Unknown message route.");let a=e[n],l;try{l=a.input(r)}catch{throw new I("invalid_payload","Invalid message payload.")}let u=await t({route:n,payload:l},o);o?.throwIfAborted();try{return a.output(u,l)}catch(f){if(f instanceof I)throw f;throw new I("invalid_response","Invalid message response.")}}}}var ae=Symbol.for("@altertable/data-app/DataAppError");class R extends Error{code;requestId;[ae]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[ae]===!0}constructor(e,t,n){super(e);this.code=t;this.requestId=n;this.name="DataAppError"}}function de(e,t){function n(o){if(o.length===1&&typeof o[0]==="function"){let a=o[0]();return Array.isArray(a)?a:[a]}return o.map((a)=>typeof a==="function"?a():a)}function r(o,a){if(!e())return;try{t({method:o,args:n(a)})}catch{}}return{log:(...o)=>r("log",o),info:(...o)=>r("info",o),warn:(...o)=>r("warn",o),error:(...o)=>r("error",o)}}var ve={send:"Sending message to parent",receive:"Received message from parent",drop:"Ignored message from parent"};function ue(e,{direction:t,...n}){if(n.type==="runtime:log")return;e.log(ve[t],n)}function pe(e){if(e instanceof Error)return{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{}};return{message:String(e)}}function ce(e){if(e instanceof I)throw new R(e.message,e.code,e.requestId);throw e}function le({parentOrigin:e,window:t=window,timeoutMs:n=ee,mode:r="url",loadScript:o}){if(new URL(e).origin!==e)throw Error("Expected an exact parent origin.");let a=D(),l,u,f=!1,c=new Map,i,v=new Set,B=de(()=>!f&&!!u&&!!i&&typeof i==="object"&&("logging"in i)&&i.logging===!0,(s)=>p("runtimeLog",{payload:s})),y=ne({role:"app",origin:e,source:()=>t.parent,opaque:r==="bundle",context:()=>({documentId:a,sessionId:u,token:l}),post(s){t.parent.postMessage(s,e)},diagnostic:(s)=>ue(B,s),handlers:{connect(s){if(r==="bundle")l=s.token;p("ready",{})},initialize(s){if(u&&u!==s.sessionId){if(c.size)B.warn("Preview reconnected; rejecting pending requests",{count:c.size});for(let E of c.values())E.reject(new R("The preview reconnected. Retry the request.","bridge_reset"))}let m=!u;if(u=s.sessionId,g(s.state),m)for(let E of c.values())E.start();if(f)return;if(r==="url")p("runtimeReady",{})},stateUpdate(s){g(s.state)},scriptLoad(s){if(r==="bundle")o?.(s.javascript)},result(s){c.get(s.id)?.resolve(s.response)},error(s){c.get(s.id)?.reject(new I(s.code,s.message,s.requestId))}}}),{send:p,receive:d}=y;function g(s){i=s;for(let m of v)m(s)}t.addEventListener("message",d);function x(s,m){return new Promise((E,b)=>{if(f)return b(new R("The preview has closed.","bridge_closed"));if(m?.aborted)return b(m.reason);if(c.size>=Y)return b(new R("Too many pending data requests.","bridge_busy"));let O=D(),A=!1;function N(){clearTimeout(me),m?.removeEventListener("abort",X),c.delete(O)}function X(){if(A)p("cancel",{id:O});N(),b(m?.reason)}let me=setTimeout(()=>{if(B.warn("Message request timed out",{id:O,route:s.route,timeoutMs:n,sent:A}),A)p("cancel",{id:O});N(),b(new R(u?"The data request timed out.":"The preview shell is unavailable. Reload the preview.",u?"timeout":"bridge_unavailable"))},n),J={start(){if(A)return;try{p("request",{id:O,route:s.route,payload:s.payload}),A=!0}catch{N(),b(new R("The message payload could not be sent.","invalid_payload"))}},resolve(U){N(),E(U)},reject(U){N(),b(U)}};if(c.set(O,J),m?.addEventListener("abort",X,{once:!0}),u)J.start();else if(r==="url"||l)p("ready",{})})}let M=ie({"data:query":oe(),"data:sql":se},x);function T(s,m,E){return M.request("data:query",{operation:s,input:m},{signal:E}).catch(ce)}function q(){if(u)p("disconnect",{});u=void 0;for(let s of c.values())s.reject(new R("The preview has closed.","bridge_closed"))}function Q(s){if(s.persisted&&(r==="url"||l))p("ready",{})}function k(){if(f)return;q(),f=!0,y.dispose(),t.removeEventListener("message",d),t.removeEventListener("pagehide",q),t.removeEventListener("pageshow",Q),v.clear()}if(t.addEventListener("pagehide",q),t.addEventListener("pageshow",Q),r==="url")p("ready",{});return{logger:B,request:x,transport:T,lakehouse:{queryAll(s,{limit:m,signal:E,params:b}){return M.request("data:sql",{statement:s,limit:m,...b===void 0?{}:{params:b}},{signal:E}).catch(ce)}},dispose:k,mode:r,snapshot(){return i},subscribe(s){return v.add(s),()=>{v.delete(s)}},ready(){if(!f&&u)p("runtimeReady",{})},fail(s){if(f||!u)return;if(s!==void 0)B.error(()=>["Data app failed",pe(s)]);p("runtimeError",{})}}}var K=Symbol.for("altertable.localFrameBridge"),_=Symbol.for("altertable.installedTransport");function fe(e,t=window){let n=t;if(n[_])throw Error("A data app transport is already installed.");return n[K]=e,n[_]=e,()=>{if(n[K]===e)delete n[K];if(n[_]===e)delete n[_];e.dispose()}}function ge({parentOrigin:e,window:t=window}){let n,r,o=`altertable-data-app-${D()}.js`,a=le({parentOrigin:e,window:t,mode:"bundle",loadScript(i){if(n!==void 0){if(i!==n)a.fail(Error("This frame already evaluated a different app script."));else if(r)a.fail(r.cause);else a.ready();return}n=i;try{let v=t.document.createElement("script");if(v.textContent=`${i}\n//# sourceURL=${o}`,t.document.body.append(v),!r)a.ready()}catch(v){l(v)}}});function l(i){r={cause:i},a.fail(i)}function u(i){if(i.filename===o)l(i.error??i.message)}function f(i){if(i.reason instanceof Error&&i.reason.stack?.includes(o))l(i.reason)}t.addEventListener("error",u),t.addEventListener("unhandledrejection",f);let c=fe(a,t);return()=>{t.removeEventListener("error",u),t.removeEventListener("unhandledrejection",f),c()}}var ye=document.currentScript?.dataset.parentOrigin;if(!ye)throw Error("Missing trusted parent origin.");ge({parentOrigin:ye});})();\n'.replace(/<\/script/gi, (match) => `<\\${match.slice(1)}`);
3
+ var inlineBootstrap = '(()=>{function q(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,(r)=>r.toString(16).padStart(2,"0"));return[t.slice(0,4),t.slice(4,6),t.slice(6,8),t.slice(8,10),t.slice(10)].map((r)=>r.join("")).join("-")}function Y(e){if(!e||typeof e!=="object")return!1;let t=e;return(t.method==="log"||t.method==="info"||t.method==="warn"||t.method==="error")&&Array.isArray(t.args)&&t.args.length<=128}var C="altertable:data-app";var Z=128,ee=60000;function T(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,128}$/.test(e)}function w({wire:e,from:t,session:r,parse:n}){return{wire:e,from:t,session:r,parse:n}}function F(e){if(!T(e.id))throw Error("Invalid request ID.");return e.id}function S(e,t){let r=e[t];if(typeof r!=="string")throw Error(`Invalid ${t}.`);return r}function O(){return{}}var h={channel:C,version:1,events:{connect:w({wire:"bridge:connect",from:"host",session:"none",parse:O}),ready:w({wire:"bridge:ready",from:"app",session:"none",parse:O}),initialize:w({wire:"bridge:initialize",from:"host",session:"establish",parse:(e)=>({state:e.state})}),request:w({wire:"bridge:request",from:"app",session:"current",parse:(e)=>{let t=S(e,"route");if(!t||t.length>256)throw Error("Invalid message route.");return{id:F(e),route:t,payload:e.payload}}}),result:w({wire:"bridge:result",from:"host",session:"current",parse:(e)=>{if(!Object.hasOwn(e,"response"))throw Error("Missing response.");return{id:F(e),response:e.response}}}),error:w({wire:"bridge:error",from:"host",session:"current",parse:(e)=>{if(e.requestId!==void 0&&typeof e.requestId!=="string")throw Error("Invalid requestId.");return{id:F(e),code:S(e,"code"),message:S(e,"message"),...e.requestId===void 0?{}:{requestId:e.requestId}}}}),cancel:w({wire:"bridge:cancel",from:"app",session:"current",parse:(e)=>({id:F(e)})}),disconnect:w({wire:"bridge:disconnect",from:"app",session:"current",parse:O}),scriptLoad:w({wire:"script:load",from:"host",session:"current",parse:(e)=>({javascript:S(e,"javascript")})}),stateUpdate:w({wire:"state:update",from:"host",session:"current",parse:(e)=>({state:e.state})}),runtimeLog:w({wire:"runtime:log",from:"app",session:"current",parse:(e)=>{if(!Y(e.payload))throw Error("Invalid log entry.");return{payload:e.payload}}}),runtimeReady:w({wire:"runtime:ready",from:"app",session:"current",parse:O}),runtimeError:w({wire:"runtime:error",from:"app",session:"current",parse:O})}};function V(e){let t={type:e.type};if("id"in e)t.id=e.id;if(e.type==="bridge:request"){t.route=e.route;let r=e.payload;if(e.route==="data:query"&&r&&typeof r==="object"&&"operation"in r&&typeof r.operation==="string")t.operation=r.operation.slice(0,256)}if(e.type==="bridge:error")t.error={code:e.code,message:e.message,...e.requestId===void 0?{}:{requestId:e.requestId}};return t}var U=new Map;for(let e of Object.keys(h.events)){let t=h.events[e].wire;if(U.has(t))throw Error(`Duplicate bridge event: ${t}`);U.set(t,e)}function W(e){return U.get(e)}function z(e){if(!e||typeof e!=="object")return;let t=e;if(t.channel!==C||t.version!==h.version||typeof t.type!=="string"||typeof t.documentId!=="string"||!t.documentId||t.documentId.length>128||t.sessionId!==void 0&&!T(t.sessionId)||t.token!==void 0&&typeof t.token!=="string")return;return t}function K(e,t){try{return{channel:C,version:h.version,documentId:e.documentId,...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.token===void 0?{}:{token:e.token},type:t.wire,...t.parse(e)}}catch{return}}function te(e){let t=z(e);if(!t)return;let r=W(t.type);if(!r)return;let n=h.events[r];if(n.session!=="none"&&t.sessionId===void 0)return;return K(t,n)}function re({role:e,origin:t,source:r,opaque:n,context:o,post:i,diagnostic:l,invalidRequest:u,handlers:y}){let c=!1;function a(g,p){l?.({direction:"drop",reason:g,...typeof p==="string"?{type:p.slice(0,64)}:{}})}function b(g,p){if(c)throw Error("The bridge endpoint has closed.");let d=h.events[g],f=o(),E=te({...p,channel:h.channel,version:h.version,type:d.wire,documentId:g==="connect"?"host":f.documentId,sessionId:f.sessionId,token:n?f.token:void 0});if(!E||n&&!T(f.token))throw Error("The bridge is not ready to send this event.");if(l?.({direction:"send",...V(E)}),c)return;i(E)}function Q(g){let p=r();if(c||!p||g.origin!==t||g.source!==p)return;let d=z(g.data);if(!d){let k=g.data;if(k&&typeof k==="object"&&"channel"in k&&k.channel===h.channel)a("invalid_envelope","type"in k?k.type:void 0);return}let f=o(),E=e==="app"&&d.type===h.events.connect.wire;if(n&&(E?!T(d.token):!f.token||d.token!==f.token))return a("token_mismatch",d.type);let P=W(d.type);if(!P)return a("unexpected_type",d.type);let N=h.events[P];if(N.from===e)return a("unexpected_type",d.type);if(N.session==="establish"){if(d.documentId!==f.documentId||d.sessionId===void 0)return a("session_mismatch",d.type)}else if(N.session==="current"){if(!f.sessionId||d.sessionId!==f.sessionId||d.documentId!==f.documentId)return a("session_mismatch",d.type)}let B=K(d,N);if(!B){if(a("invalid_payload",d.type),e==="host"&&P==="request"&&T(d.id))u?.(d.id);return}if(l?.({direction:"receive",...V(B)}),c)return;let D=y[P];D(B)}return{send:b,receive:Q,dispose(){c=!0}}}function we(e){return e===null||typeof e==="string"||typeof e==="boolean"||typeof e==="number"&&Number.isFinite(e)}function H(e){return!!e&&typeof e==="object"&&!Array.isArray(e)&&Object.values(e).every(we)}var ne=Symbol.for("@altertable/data-app/MessageRoutingError");class R extends Error{code;requestId;[ne]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[ne]===!0}constructor(e,t,r,n){super(t,n);this.code=e;this.requestId=r;this.name="MessageRoutingError"}}function he(e){return e}function oe(e){return{operations:e,input(t){if(!t||typeof t!=="object")throw Error("Invalid query.");let r=t;if(typeof r.operation!=="string"||!r.operation||r.operation.length>256||r.operation.includes("/"))throw Error("Invalid operation.");let n=e&&Object.hasOwn(e,r.operation)?e[r.operation]:void 0;if(e&&!n)throw Error("Unknown operation.");return{operation:r.operation,input:n?n.input(r.input):r.input}},output(t){if(!t||typeof t!=="object")throw Error("Invalid data response.");let r=t;if(!Number.isInteger(r.status)||r.status<100||r.status>599||!r.body||typeof r.body!=="object"||Array.isArray(r.body))throw Error("Invalid data response.");let n=r.body;if(r.status<200||r.status>=300){let o=n.error;throw new R(typeof o?.code==="string"?o.code:"request_failed",typeof o?.message==="string"?o.message:"Could not load data.",typeof o?.requestId==="string"?o.requestId:void 0)}if(!("data"in n)||typeof n.requestId!=="string"||typeof n.queriedAt!=="string"||!Array.isArray(n.queryIds)||!n.queryIds.every((o)=>typeof o==="string"))throw Error("Invalid data envelope.");if(n.queries!==void 0&&(!Array.isArray(n.queries)||!n.queries.every((o)=>o&&typeof o==="object"&&typeof o.name==="string"&&typeof o.statement==="string"&&(o.params===void 0||H(o.params))&&(o.queryId===void 0||typeof o.queryId==="string"))))throw Error("Invalid query evidence.");return{status:r.status,body:n}}}}var se=he({input(e){if(!e||typeof e!=="object")throw Error("Invalid SQL query.");let t=e;if(typeof t.statement!=="string"||!t.statement.trim()||typeof t.limit!=="number"||!Number.isSafeInteger(t.limit)||t.limit<1||t.params!==void 0&&!H(t.params))throw Error("Invalid SQL query.");return{statement:t.statement,limit:t.limit,...t.params===void 0?{}:{params:t.params}}},output(e,t){if(!e||typeof e!=="object")throw Error("Invalid query result.");let r=e;if(!Array.isArray(r.columns)||!r.columns.every((n)=>n&&typeof n.name==="string"&&(n.type===void 0||typeof n.type==="string"))||!Array.isArray(r.rows)||r.rows.length>t.limit||!r.rows.every((n)=>Array.isArray(n)&&n.length===r.columns.length)||r.queryId!==void 0&&typeof r.queryId!=="string")throw Error("Invalid query result.");return{columns:r.columns,rows:r.rows,...r.queryId===void 0?{}:{queryId:r.queryId}}}});function ae(e,t){return{async request(r,n,{signal:o}={}){if(o?.throwIfAborted(),!Object.hasOwn(e,r))throw new R("unknown_route","Unknown message route.");let i=e[r],l;try{l=i.input(n)}catch{throw new R("invalid_payload","Invalid message payload.")}let u=await t({route:r,payload:l},o);o?.throwIfAborted();try{return i.output(u,l)}catch(y){if(y instanceof R)throw y;throw new R("invalid_response","Invalid message response.")}}}}var ie=Symbol.for("@altertable/data-app/DataAppError");class x extends Error{code;requestId;[ie]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[ie]===!0}constructor(e,t,r){super(e);this.code=t;this.requestId=r;this.name="DataAppError"}}function de(e,t){function r(o){if(o.length===1&&typeof o[0]==="function"){let i=o[0]();return Array.isArray(i)?i:[i]}return o.map((i)=>typeof i==="function"?i():i)}function n(o,i){if(!e())return;try{t({method:o,args:r(i)})}catch{}}return{log:(...o)=>n("log",o),info:(...o)=>n("info",o),warn:(...o)=>n("warn",o),error:(...o)=>n("error",o)}}var be={send:"Sending message to parent",receive:"Received message from parent",drop:"Ignored message from parent"};function ue(e,{direction:t,...r}){if(r.type==="runtime:log")return;e.log(be[t],r)}function pe(e){if(e instanceof Error)return{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{}};return{message:String(e)}}function ce(e){if(e instanceof R)throw new x(e.message,e.code,e.requestId);throw e}function le({parentOrigin:e,window:t=window,timeoutMs:r=ee,mode:n="url",loadScript:o}){if(new URL(e).origin!==e)throw Error("Expected an exact parent origin.");let i=q(),l,u,y=!1,c=new Map,a,b=new Set,Q=de(()=>!y&&!!u&&!!a&&typeof a==="object"&&("logging"in a)&&a.logging===!0,(s)=>p("runtimeLog",{payload:s})),g=re({role:"app",origin:e,source:()=>t.parent,opaque:n==="bundle",context:()=>({documentId:i,sessionId:u,token:l}),post(s){t.parent.postMessage(s,e)},diagnostic:(s)=>ue(Q,s),handlers:{connect(s){if(n==="bundle")l=s.token;p("ready",{})},initialize(s){if(u&&u!==s.sessionId){if(c.size)Q.warn("Preview reconnected; rejecting pending requests",{count:c.size});for(let I of c.values())I.reject(new x("The preview reconnected. Retry the request.","bridge_reset"))}let m=!u;if(u=s.sessionId,f(s.state),m)for(let I of c.values())I.start();if(y)return;if(n==="url")p("runtimeReady",{})},stateUpdate(s){f(s.state)},scriptLoad(s){if(n==="bundle")o?.(s.javascript)},result(s){c.get(s.id)?.resolve(s.response)},error(s){c.get(s.id)?.reject(new R(s.code,s.message,s.requestId))}}}),{send:p,receive:d}=g;function f(s){a=s;for(let m of b)m(s)}t.addEventListener("message",d);function E(s,m){return new Promise((I,v)=>{if(y)return v(new x("The preview has closed.","bridge_closed"));if(m?.aborted)return v(m.reason);if(c.size>=Z)return v(new x("Too many pending data requests.","bridge_busy"));let j=q(),M=!1;function A(){clearTimeout(me),m?.removeEventListener("abort",J),c.delete(j)}function J(){if(M)p("cancel",{id:j});A(),v(m?.reason)}let me=setTimeout(()=>{if(Q.warn("Message request timed out",{id:j,route:s.route,timeoutMs:r,sent:M}),M)p("cancel",{id:j});A(),v(new x(u?"The data request timed out.":"The preview shell is unavailable. Reload the preview.",u?"timeout":"bridge_unavailable"))},r),X={start(){if(M)return;try{p("request",{id:j,route:s.route,payload:s.payload}),M=!0}catch{A(),v(new x("The message payload could not be sent.","invalid_payload"))}},resolve(L){A(),I(L)},reject(L){A(),v(L)}};if(c.set(j,X),m?.addEventListener("abort",J,{once:!0}),u)X.start();else if(n==="url"||l)p("ready",{})})}let P=ae({"data:query":oe(),"data:sql":se},E);function N(s,m,I){return P.request("data:query",{operation:s,input:m},{signal:I}).catch(ce)}function B(){if(u)p("disconnect",{});u=void 0;for(let s of c.values())s.reject(new x("The preview has closed.","bridge_closed"))}function D(s){if(s.persisted&&(n==="url"||l))p("ready",{})}function k(){if(y)return;B(),y=!0,g.dispose(),t.removeEventListener("message",d),t.removeEventListener("pagehide",B),t.removeEventListener("pageshow",D),b.clear()}if(t.addEventListener("pagehide",B),t.addEventListener("pageshow",D),n==="url")p("ready",{});return{logger:Q,request:E,transport:N,lakehouse:{queryAll(s,{limit:m,signal:I,params:v}){return P.request("data:sql",{statement:s,limit:m,...v===void 0?{}:{params:v}},{signal:I}).catch(ce)}},dispose:k,mode:n,snapshot(){return a},subscribe(s){return b.add(s),()=>{b.delete(s)}},ready(){if(!y&&u)p("runtimeReady",{})},fail(s){if(y||!u)return;if(s!==void 0)Q.error(()=>["Data app failed",pe(s)]);p("runtimeError",{})}}}var G=Symbol.for("altertable.localFrameBridge"),_=Symbol.for("altertable.installedTransport");function ye(e,t=window){let r=t;if(r[_])throw Error("A data app transport is already installed.");return r[G]=e,r[_]=e,()=>{if(r[G]===e)delete r[G];if(r[_]===e)delete r[_];e.dispose()}}function fe({parentOrigin:e,window:t=window}){let r,n,o=`altertable-data-app-${q()}.js`,i=le({parentOrigin:e,window:t,mode:"bundle",loadScript(a){if(r!==void 0){if(a!==r)i.fail(Error("This frame already evaluated a different app script."));else if(n)i.fail(n.cause);else i.ready();return}r=a;try{let b=t.document.createElement("script");if(b.textContent=`${a}\n//# sourceURL=${o}`,t.document.body.append(b),!n)i.ready()}catch(b){l(b)}}});function l(a){n={cause:a},i.fail(a)}function u(a){if(a.filename===o)l(a.error??a.message)}function y(a){if(a.reason instanceof Error&&a.reason.stack?.includes(o))l(a.reason)}t.addEventListener("error",u),t.addEventListener("unhandledrejection",y);let c=ye(i,t);return()=>{t.removeEventListener("error",u),t.removeEventListener("unhandledrejection",y),c()}}var ge=document.currentScript?.dataset.parentOrigin;if(!ge)throw Error("Missing trusted parent origin.");fe({parentOrigin:ge});})();\n'.replace(/<\/script/gi, (match) => `<\\${match.slice(1)}`);
4
4
  function runtimeHtml(parentOrigin) {
5
5
  const attribute = parentOrigin.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("'", "&#39;");
6
6
  return `<!doctype html>
@@ -11,12 +11,19 @@ Declare the query source of truth with `defineDataApp()`. Generate
11
11
  operations with `dataApp.defineOperation()` and execute queries by
12
12
  name with parameter values. When a query registry is supplied, use only its queries
13
13
  and preserve its SQL. Otherwise, inspect the data and declare the queries the app needs.
14
- Derive displays, exports, and findings from their results. See
15
- [named queries](contract.md#execute-named-queries).
14
+ Declare inspected result aliases in `projections` and derive displays, exports,
15
+ and findings from the typed rows. See [named queries](contract.md#execute-named-queries).
16
16
 
17
17
  Inspect the relevant catalogs, tables, and fields, their time coverage, and
18
18
  existing definitions. Choose a question the available data can answer.
19
19
 
20
+ ## Compose the exploration
21
+
22
+ Plan the question, analytical sequence, and role of each display before choosing
23
+ components. Follow [Compose an exploration](composition.md) to connect filters,
24
+ widgets, layout, and narrative into a coherent investigation, then distill its
25
+ supported findings into a story.
26
+
20
27
  ## Choose the visualizations
21
28
 
22
29
  Before implementing queries and rendering, identify the question each visual
@@ -59,7 +66,7 @@ refresh, and failure.
59
66
  | Task | Documentation |
60
67
  | ------------------------------------------------ | ----------------------------------------------------------------- |
61
68
  | Choose components, CSS tokens, and styling hooks | [Styling](styling.md) |
62
- | Define queries, inputs, and result parsing | [Operations](contract.md) |
69
+ | Define queries, inputs, and typed results | [Operations](contract.md) |
63
70
  | Build views, filters, and request states | [Views](views.md) |
64
71
  | Introduce and explain visualizations | [Narrative text](widgets.md#narrative-text) |
65
72
  | Find formatters and presentation helpers | [App helpers](formatting-and-appearance.md) |
package/docs/client.md CHANGED
@@ -15,18 +15,17 @@ const response = await client.query('activity', input, { signal });
15
15
  ```
16
16
 
17
17
  The app defines `operations`, `input`, and an optional cancellation `signal`.
18
- Operation input and output types are inferred from the server operation map. Keep the
19
- server operation map import type-only so its implementations stay on the server.
20
- The shared app declaration contains the query registry and is browser-safe.
18
+ Inputs and data are inferred from the operation map and `run()`. Keep the import
19
+ type-only so operation implementations stay on the server.
21
20
 
22
21
  The default endpoint is `/api/data`. Override it with
23
- `createDataClient({ endpoint, fetch })` to change the base URL or supply a Fetch
22
+ `createDataClient<typeof operations>({ endpoint, fetch })` to change the base URL or supply a Fetch
24
23
  implementation. Calls POST JSON to `/api/data/:operation`; the client sends
25
24
  operation inputs rather than SQL or credentials.
26
25
 
27
26
  `DataResponse` contains `data`, the exact request `input`, `requestId`,
28
27
  `queriedAt`, `queryIds`, and executed `queries`. Use the returned input when labeling stale data during a refresh.
29
- HTTP and iframe delivery validate the same success envelope: data, request ID,
28
+ HTTP and iframe delivery validate the success envelope: data, request ID,
30
29
  query timestamp, query IDs, and optional query evidence. Malformed responses
31
30
  reject with `invalid_response`.
32
31
 
@@ -72,7 +71,7 @@ the host through the existing bridge cancellation protocol.
72
71
 
73
72
  ## Iframe transport
74
73
 
75
- `createDataClient({ transport })` accepts a `DataTransport`. Without an explicit
74
+ `createDataClient<typeof operations>({ transport })` accepts a `DataTransport`. Without an explicit
76
75
  transport, endpoint, or Fetch implementation, it discovers an installed iframe
77
76
  transport before falling back to HTTP. Explicit endpoint/Fetch options select
78
77
  HTTP. `createHttpTransport()` provides the underlying operation delivery adapter.
@@ -0,0 +1,84 @@
1
+ # Compose an exploration
2
+
3
+ Start with the question the user needs to answer. Define its population, period,
4
+ measures, and comparison. Choose the analytical flow before choosing widgets;
5
+ a focused answer may need only a chart and a paragraph.
6
+
7
+ ## Build a sequence of questions
8
+
9
+ Lead with the strongest supported result and visible scope. Give each section a
10
+ question that advances the investigation: what happened, when or against what
11
+ baseline, where it differs, and which details support the finding. Omit steps
12
+ that add no useful evidence.
13
+
14
+ Give each element a purpose:
15
+
16
+ | Element | Purpose |
17
+ | --------- | ------------------------------------------------------------------------ |
18
+ | Metric | Establish magnitude or change. |
19
+ | Chart | Reveal the pattern that answers the section's question. |
20
+ | Narrative | Explain interpretation, qualify a claim, or suggest the next comparison. |
21
+ | Table | Support exact comparisons and inspection. |
22
+ | Filter | Test a relevant hypothesis or change the scope. |
23
+
24
+ Use `<Stack>` for reading order, `<SectionHeading>` for questions, and `<Grid>`
25
+ for peer widgets users should compare together. Give the main visual enough
26
+ space and preserve reading order on phones. Place explanations beside their
27
+ evidence, using `<TextContent>` for introductions or `<TextWidget>` for a panel.
28
+ See [layout](layout.md) and [widget selection](widgets.md#choose-a-visualization).
29
+
30
+ Keep a connected investigation on one page. Use app tabs for distinct analytical
31
+ questions and widget `views` for alternate representations of the same dataset.
32
+
33
+ ## Make filters serve the question
34
+
35
+ Offer controls with a clear analytical use, such as dates to locate a change or
36
+ channels to test whether it is widespread. Choose useful defaults with adequate
37
+ coverage and make each filter's scope clear.
38
+
39
+ Keep related metrics, charts, and prose consistent in population, definitions,
40
+ units, and comparison periods. Explain deliberate differences. Show counts
41
+ alongside rates when sample size matters; calculate overall rates from their
42
+ numerators and denominators rather than averaging subgroup rates.
43
+
44
+ Derive findings and qualifications from the displayed result and its input.
45
+ A claim about all channels may no longer hold after selecting one. Retain the
46
+ displayed scope during refresh or failure. See [variables](variables.md) and
47
+ [displayed results](views.md#preserve-displayed-results).
48
+
49
+ ## Example: where are we losing signups?
50
+
51
+ Define funnel entry, the completion window, and channel attribution. Compare
52
+ populations with equal opportunity to complete; identify incomplete observations.
53
+ Then compose the page in this order:
54
+
55
+ | Question | Display and purpose |
56
+ | -------------------------------------- | ---------------------------------------------------------------------------------------------------- |
57
+ | How many starters complete? | Conversion against a comparable prior period, with starter and completion counts to establish scale. |
58
+ | When does conversion change? | Trend to locate the change, with incomplete periods identified. |
59
+ | At which step, and for which channels? | Funnel and channel comparisons with counts and rates to locate differences. |
60
+ | What supports the comparison? | Table of channel and step counts, denominators, and rates for inspection and export. |
61
+
62
+ Use one declared view for these related datasets. Put outcome metrics in a
63
+ `<Grid>`, give the trend its own row, then show the funnel, channel comparison,
64
+ and table. Reuse datasets for charts and tables, and bind narrative to the same
65
+ source. See [views](views.md) and [bindings](widgets.md#declare-datasets-and-metrics).
66
+
67
+ Let the date filter select funnel entry dates and the channel filter affect every
68
+ section. Start with all channels and adequate coverage. Selecting one channel
69
+ should help compare its steps and periods; update the headline to match that scope.
70
+
71
+ ## Distill the story
72
+
73
+ Select one to four findings that answer the main question from the displayed
74
+ result. Reuse its bindings, scope, and evidence in the story and CSV export.
75
+ See [stories and export](stories-and-export.md).
76
+
77
+ For the signup example, present the conversion change, the step or channel where
78
+ the difference is largest, and any qualification about counts or coverage, when
79
+ supported. Observed differences suggest where to investigate; they do not
80
+ establish a cause.
81
+
82
+ Verify the initial scope and a changed filter: does each section advance the
83
+ question, and does the story agree with the visible evidence? Check reading order
84
+ and context on phones and through the [UI quality states](ui-quality.md).
package/docs/contract.md CHANGED
@@ -8,17 +8,12 @@ import operation types using `import type`.
8
8
 
9
9
  ## Execute named queries
10
10
 
11
- Declare SQL once with `defineDataApp()` to preserve exact query and parameter
12
- names. Use stable `lowerCamelCase` IDs describing the result, such as `products`,
13
- `productsByCategory`, or `dailyRevenue`. Use plural names for row lists; keep parameter
14
- values in `params`. Every query must include `params`; use `{}` when it declares no
15
- parameters.
16
- The app owns an immutable registry snapshot. Define operations with
17
- `dataApp.defineOperation()`.
11
+ Declare queries with `defineDataApp()` and operations with `dataApp.defineOperation()`.
12
+ Use descriptive `lowerCamelCase` query names. Declare parameter types in `params`
13
+ (use `{}` for none) and returned aliases in `projections`.
18
14
 
19
15
  ```ts
20
16
  import { defineDataApp } from '@altertable/data-app';
21
- import { rowsAsRecords } from '@altertable/data-app/contract';
22
17
 
23
18
  const dataApp = defineDataApp({
24
19
  title: 'Products',
@@ -27,8 +22,16 @@ const dataApp = defineDataApp({
27
22
  appearance: { theme: 'system' },
28
23
  queries: {
29
24
  products: {
30
- statement: 'SELECT * FROM products WHERE org_id = $orgId LIMIT $limit',
31
- params: { orgId: {}, limit: { defaultValue: 10 } },
25
+ statement:
26
+ 'SELECT name, unit_price AS "unitPrice" FROM products WHERE org_id = $orgId LIMIT $limit',
27
+ params: {
28
+ orgId: { type: 'string' },
29
+ limit: { type: 'number', defaultValue: 10 },
30
+ },
31
+ projections: {
32
+ name: { type: 'string' },
33
+ unitPrice: { type: 'number', nullable: true },
34
+ },
32
35
  },
33
36
  },
34
37
  });
@@ -39,21 +42,38 @@ const products = dataApp.defineOperation({
39
42
  policy: { maxQueryRows: 100, maxDurationMs: 15000 },
40
43
  async run({ query }, input) {
41
44
  const result = await query('products', input);
42
- return parseProducts(rowsAsRecords(result, ['name', 'price']));
45
+ return result.rows;
43
46
  },
44
47
  });
45
48
  ```
46
49
 
47
- `parseProductInput()` and `parseProducts()` are app-owned example functions, not
48
- package exports. Validate filter values in the input parser. Parse query rows once, in
49
- `run`: the value it returns is the operation's data and type, sent to the view as is. `{}` declares a required parameter; `{ defaultValue }` supplies
50
- a fallback. `query(name, params, { limit })` executes only registered queries and
51
- inherits the operation's row limit and cancellation signal.
52
-
53
- SQL and resolved parameter values pass unchanged to the backend. Results include
54
- query evidence; use `products.queryNames` with `createDataContext()` to bind it.
55
- For HTTP apps, authorization can supply protected `queryParams`, such as `orgId`.
56
- The host/backend enforces data access and limits.
50
+ `parseProductInput()` is app-owned. Validate inputs there and business rules in
51
+ `run()`. Derive operation data from `query()` rows; clients and views infer the
52
+ returned type. Handle empty results. HTTP results must be JSON-serializable.
53
+ Include representative valid inputs in `checks`.
54
+
55
+ Host `queryParams` supplies protected parameters; callers cannot override them.
56
+ Other values come from `query()` arguments or `defaultValue`. Missing values are
57
+ checked before execution. `query(name, params, { limit })` inherits the operation's
58
+ row limit and cancellation signal.
59
+
60
+ ### Declare query projections
61
+
62
+ Inspect each query and declare every returned alias with `{ type, nullable? }`.
63
+ Result keys keep the exact SQL names; alias columns in SQL to change casing, as
64
+ with `"unitPrice"` above.
65
+ Determine nullability from the schema and SQL, even when sampled rows contain no
66
+ nulls. Update projections when changing SQL.
67
+
68
+ `query()` converts result cells to the declared types before `run()` uses them.
69
+ Numbers that cannot be converted become `"##ERROR##"`; booleans use JavaScript
70
+ truthiness. Nulls pass through unless `nullable: false`. Parameters are validated
71
+ without conversion. For exact numeric precision, return SQL text
72
+ and declare `string`.
73
+
74
+ Results include query evidence; use `products.queryNames` with `createDataContext()`
75
+ to bind it. The host/backend enforces data access and limits; see
76
+ [server authorization](server.md).
57
77
 
58
78
  ## Shared date ranges
59
79
 
@@ -2,6 +2,8 @@
2
2
 
3
3
  Set `dataContext: context` in each view for source descriptions, glossary, and
4
4
  permitted query evidence. App inspection and the view's sections use that context.
5
+ Keep glossary query references scoped to that view's executed queries. Detail
6
+ views declare their own context when their queries differ.
5
7
  Render registered identifiers where `<DataIdentifier>` is used.
6
8
 
7
9
  Physical source identifiers name inspected tables and columns. Glossary entries
package/docs/server.md CHANGED
@@ -24,7 +24,7 @@ export const handleDataRequest = createDataHandler(
24
24
  The app supplies `authenticate()` and `lakehouseFor()`, then routes `/api/data/*`
25
25
  requests to the handler. Authorize every viewer and operation, and scope the
26
26
  returned lakehouse to the viewer's permitted data. Supply trusted registry
27
- parameters through `queryParams`; query callers cannot override these values. Origin and Fetch Metadata
27
+ parameters through `queryParams`; query callers cannot override them. Origin and Fetch Metadata
28
28
  checks reject cross-site browser requests; they do not authenticate viewers.
29
29
 
30
30
  The handler validates operation input, enforces query row and duration
package/docs/styling.md CHANGED
@@ -26,6 +26,10 @@ fallback in app CSS. Use `:root` for shared theme overrides, including menus and
26
26
  Prefer `app.appearance` for brand and chart colors. When overriding accent tokens,
27
27
  choose a contrasting foreground too. Keep text inputs at least 16px on mobile.
28
28
 
29
+ Menus and selection dropdowns share `--atbl-dropdown-padding`,
30
+ `--atbl-dropdown-item-padding-block`, `--atbl-dropdown-item-padding-inline`, and
31
+ `--atbl-dropdown-item-gap`. Their default padding follows the control density.
32
+
29
33
  ## Native controls
30
34
 
31
35
  Use package controls when possible. For a custom native control:
package/docs/ui.md CHANGED
@@ -116,7 +116,8 @@ conversion windows, and cohort definitions; these components visualize results.
116
116
  - `<FunnelChart>`: ordered steps and aligned, nonincreasing counts per population.
117
117
  - `<RetentionChart>`: numeric offsets, fractional rates (`0.25`, not `25`), retained
118
118
  counts, and cohort size. Distinguish unobserved (`null`), observed zero, and
119
- observed but still accumulating (`incomplete`) periods.
119
+ observed but still accumulating (`incomplete`) periods. Offset labels come from
120
+ supplied points; numeric spacing preserves elapsed distance.
120
121
  - `<JourneyChart>`: full ordered paths with counts and outcomes; preserve repeated
121
122
  events and mark cut-off paths as `truncated`.
122
123
 
@@ -151,6 +152,13 @@ primitives are also available.
151
152
  </VisualizationWidget>
152
153
  ```
153
154
 
155
+ For irregular time intervals, use `<ComposedChart.XAxis>` with ISO dates, zoned
156
+ ISO timestamps, or `Date` values; spacing follows elapsed time. Use `scale="utc"`
157
+ for epoch milliseconds, or `type="category"` to keep date-like labels categorical.
158
+ On UTC axes, supplied `ticks` and `tickFormatter` take precedence over automatic labels.
159
+ Preserve missing measures as `null` and choose `connectNulls` deliberately; do not
160
+ replace missing observations with zero.
161
+
154
162
  Label series and units clearly. See component JSDoc and the
155
163
  [Recharts API](https://recharts.github.io/en-US/api/ComposedChart/) for options.
156
164
  The dataset owns loading, empty results, evidence, CSV, and story content; keep
@@ -215,3 +223,6 @@ and `<NumberRangeField>` as inline input primitives when composing forms.
215
223
 
216
224
  Use `<Button variant="primary">` for the main committing action, such as Apply.
217
225
  Use outline and ghost buttons for secondary actions.
226
+ Use `<Button variant="inline">` for actions within text or table cells. It has no
227
+ control padding or background and underlines on hover. Keep button semantics for
228
+ opening a sheet; use links for navigation to a URL.
package/docs/variables.md CHANGED
@@ -13,9 +13,10 @@ Bindings are required when the operation input cannot supply a compatible
13
13
  top-level filter field or the calendar request. Keep parsed selections in the
14
14
  operation input and derive SQL parameters inside the operation.
15
15
 
16
- `dimensionFilter()` from `/contract` requires exactly one option source: fixed `options` or a `facet`.
17
- Use `defineFacetFilter()` to bind a facet operation and its typed input. `<DimensionPicker>` offers missing values separately and keeps selected values
18
- available when they have zero matches.
16
+ `dimensionFilter()` from `/contract` uses fixed `options`. Use `defineFacetFilter()`
17
+ for options derived from declared variable context, or `app.defineDimension()`
18
+ for independent source options and exact member lookup. `<DimensionPicker>` offers missing values separately and keeps selected values
19
+ available when options refresh or fail; unknown counts remain undisclosed.
19
20
 
20
21
  ## Declare controls once
21
22
 
@@ -82,7 +83,7 @@ suppress autocomplete for a particular app.
82
83
 
83
84
  Declare controls in priority order for the user's task. Keep useful scope filters
84
85
  visible and set `presentation.prominence: 'secondary'` for less frequent ones in
85
- the Filters sheet. Active secondary filters remain available for direct editing.
86
+ the Filters sheet. Active filter summaries reopen the same Filters sheet.
86
87
  Choose useful defaults rather than exposing every field; declare each label once.
87
88
 
88
89
  Set `presentation.group: 'display'` for ordering or presentation choices. These
@@ -160,22 +161,28 @@ facet operation returns parsed dimension options. Its input mapper uses current
160
161
  resolved variables, including other filters:
161
162
 
162
163
  ```ts
163
- const { defineFacetFilter, defineTimeView } = createDataHooks(client);
164
+ const { defineFacetFilter } = createDataHooks(client);
165
+ const period = dateRangeVariable({
166
+ key: 'period',
167
+ contract: calendar,
168
+ defaultValue: { kind: 'preset', id: 'last-7' },
169
+ });
164
170
  const region = defineFacetFilter({
165
171
  key: 'region',
166
172
  label: 'Region',
167
173
  valueType: 'string',
168
174
  selectionMode: 'multiple',
169
175
  facet: {
176
+ context: { period },
170
177
  operation: 'regions',
171
- input: values => ({ period: values.period as DateRangeRequest }),
178
+ input: values => ({ period: values.period }),
172
179
  },
173
180
  });
174
181
  ```
175
182
 
176
- The client's operation map defines `regions` and its typed period input;
177
- import `DateRangeRequest` from `/contract`. Put `region` in the view's `variables`
178
- alongside its period. Use `parseFacetOptions()` to validate facet results.
183
+ Declare mapper dependencies in `facet.context` (`{}` for none), and include them
184
+ alongside the facet in the view's `variables`. Mapper inputs and option values are
185
+ inferred from the variables and operation; options must match `valueType`.
179
186
  For the operation's input parser, use `parseDimensionSelection(value, region)` from `/contract`.
180
187
  A dimension without an explicit selection represents all members.
181
188
  Map parsed selections to the query's declared parameters; do not construct SQL
@@ -184,13 +191,16 @@ from filter values. Choose selection modes supported by the registered query.
184
191
  Choose `selectionMode: 'single'` when one value replaces another and
185
192
  `selectionMode: 'multiple'` for independent values. `All` is an explicit choice for a single-value
186
193
  filter and the meaning of an empty selection for a multiple-value filter.
194
+ Single-value filters always have a selection limit of one.
187
195
 
188
196
  ## Fixed choices
189
197
 
190
198
  `choiceVariable()` requires labeled `options` and a valid `defaultValue`.
191
199
  `multiChoiceVariable()` stores unique option IDs with an optional selection limit.
192
- An empty fixed-choice collection means no choices; categorical filters use
193
- `dimensionFilter()` when an empty selection should mean all records.
200
+ Fixed-choice declarations need at least one option. Inline options or `as const`
201
+ preserve their IDs so TypeScript checks defaults against them. An empty selected
202
+ collection means no choices; categorical filters use `dimensionFilter()` when
203
+ an empty selection should mean all records.
194
204
 
195
205
  ```ts
196
206
  const variables = {
@@ -246,3 +256,65 @@ with paired Apply/Cancel handlers; derive queries and visible controls from appl
246
256
  values while a draft is being edited.
247
257
 
248
258
  Filters apply immediately; use app-owned drafts only when the task needs Apply/Cancel.
259
+
260
+ ## Independent filters and chart breakdowns
261
+
262
+ Each dimension owns its selection. Readers can select Germany without selecting
263
+ a region; changing or clearing Region preserves Country and Customer. Filters
264
+ combine in the operation's query. Incompatible selections can return an empty
265
+ result; keep the selections visible so readers can correct them.
266
+
267
+ Use `dimensionFilter()` for static options or `app.defineDimension()` for query-backed
268
+ options. `variableInput()` from `/contract` validates named variables alongside an
269
+ app-owned base parser. Use it on every operation consuming these filters, including
270
+ details. Declare the same variables on the view and preserve them in operation input.
271
+
272
+ ```ts
273
+ const country = app.defineDimension({
274
+ key: 'country',
275
+ label: 'Country',
276
+ valueType: 'string',
277
+ selectionMode: 'single',
278
+ presentation: { prominence: 'secondary' },
279
+ source: { query: 'countries' },
280
+ });
281
+ const revenueBy = choiceVariable({
282
+ key: 'revenue-by',
283
+ label: 'Revenue breakdown',
284
+ defaultValue: 'region',
285
+ options: [
286
+ { id: 'region', label: 'Region' },
287
+ { id: 'country', label: 'Country' },
288
+ ],
289
+ presentation: { group: 'display', control: 'widget' },
290
+ });
291
+ const parseInput = variableInput(parsePeriodInput, { country, revenueBy });
292
+ ```
293
+
294
+ A breakdown is an ordinary display choice, independent of population filters.
295
+ `<VisualizationWidget breakdown={view.breakdown('revenueBy')}>` renders that
296
+ choice in its header. `presentation.control: 'widget'` omits it from the toolbar.
297
+ Scope filters still appear in the Filters sheet, active summaries, and Clear filters.
298
+ Primary controls stay in the toolbar. Active non-primary filters appear beside them
299
+ as editable controls. Once the toolbar scrolls above the viewport,
300
+ a floating summary shows every active filter and opens the Filters sheet.
301
+ Declare each chart's choice separately when readers should control them independently.
302
+
303
+ Each source query declares a nullable `member` parameter matching `valueType` and
304
+ nonnullable projections for `value` (the same type), `label` (string), and optional
305
+ `count` (number). `member = null` requests at most 200 options; a selected value requests
306
+ an exact lookup. Other query parameters need defaults or trusted server values.
307
+ Keep SQL and parameter declarations literal in `defineDataApp()`.
308
+
309
+ ```sql
310
+ SELECT code AS value, name AS label
311
+ FROM countries
312
+ WHERE ($member IS NULL OR code = $member)
313
+ ORDER BY name
314
+ ```
315
+
316
+ Exact selected-member lookups run before business queries, sharing authorization,
317
+ cancellation, execution limits, and query evidence. Labels resolve separately from
318
+ the options page, including when it fails. Picker search searches supplied options;
319
+ it does not fetch additional members. Clear filters preserves search and display
320
+ choices and returns dates to their configured defaults.