@altertable/data-app 0.68.0 → 0.69.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 (175) hide show
  1. package/AGENTS.md +6 -0
  2. package/CONTRIBUTING.md +27 -1
  3. package/README.md +18 -21
  4. package/THIRD_PARTY_NOTICES +18 -0
  5. package/dist/chunks/index-22d576sn.js +153 -0
  6. package/dist/chunks/index-22d576sn.js.map +11 -0
  7. package/dist/chunks/{index-ktmvs916.js → index-2sbp9h2b.js} +37 -21
  8. package/dist/chunks/index-2sbp9h2b.js.map +13 -0
  9. package/dist/chunks/{index-23dktynd.js → index-ap60vggk.js} +4 -4
  10. package/dist/chunks/{index-m6n8ctfc.js → index-cv36cyna.js} +4 -4
  11. package/dist/chunks/index-cv36cyna.js.map +10 -0
  12. package/dist/chunks/{index-ag0cgnvq.js → index-k766wwwr.js} +13 -9
  13. package/dist/chunks/index-k766wwwr.js.map +13 -0
  14. package/dist/chunks/{index-mt93ff2b.js → index-kwnqycjt.js} +2 -2
  15. package/dist/chunks/index-kwnqycjt.js.map +10 -0
  16. package/dist/chunks/index-m0gbxtgp.js +355 -0
  17. package/dist/chunks/index-m0gbxtgp.js.map +13 -0
  18. package/dist/chunks/{index-gvers8jw.js → index-qhzdzca2.js} +3709 -2170
  19. package/dist/chunks/index-qhzdzca2.js.map +118 -0
  20. package/dist/chunks/{index-x69p7cv7.js → index-r7b1ftwy.js} +3 -3
  21. package/dist/chunks/index-r7b1ftwy.js.map +10 -0
  22. package/dist/chunks/{index-ev2b5aaf.js → index-sx488hvs.js} +4 -4
  23. package/dist/chunks/{index-f5cnbrjz.js → index-wss3gd3h.js} +39 -9
  24. package/dist/chunks/index-wss3gd3h.js.map +13 -0
  25. package/dist/chunks/{index-qd5xgx6y.js → index-zcqxfwdq.js} +5 -12
  26. package/dist/chunks/index-zcqxfwdq.js.map +13 -0
  27. package/dist/client/index.js +6 -6
  28. package/dist/core/appearance.js +1 -1
  29. package/dist/core/config.js +3 -3
  30. package/dist/core/contract.js +3 -3
  31. package/dist/core/format.js +10 -2
  32. package/dist/core/format.js.map +1 -1
  33. package/dist/embed/index.js +26 -25
  34. package/dist/embed/index.js.map +4 -4
  35. package/dist/index.js +3 -3
  36. package/dist/local.js +166 -144
  37. package/dist/local.js.map +8 -7
  38. package/dist/preview.js +1456 -0
  39. package/dist/preview.js.map +17 -0
  40. package/dist/react/embed/index.js +1 -1
  41. package/dist/react/index.js +250 -93
  42. package/dist/react/index.js.map +10 -10
  43. package/dist/react/ui/index.js +1168 -1165
  44. package/dist/react/ui/index.js.map +13 -11
  45. package/dist/server.js +68 -57
  46. package/dist/server.js.map +7 -6
  47. package/dist/types/client/download.d.ts +5 -0
  48. package/dist/types/client/iframe.d.ts +4 -2
  49. package/dist/types/client/logger.d.ts +10 -2
  50. package/dist/types/core/annotations.d.ts +5 -0
  51. package/dist/types/core/appearance.d.ts +2 -0
  52. package/dist/types/core/bridge-endpoint.d.ts +2 -2
  53. package/dist/types/core/bridge.d.ts +22 -0
  54. package/dist/types/core/config.d.ts +5 -0
  55. package/dist/types/core/contract.d.ts +3 -1
  56. package/dist/types/core/date-format.d.ts +24 -0
  57. package/dist/types/core/dimension.d.ts +2 -1
  58. package/dist/types/core/filters.d.ts +4 -3
  59. package/dist/types/core/format.d.ts +5 -3
  60. package/dist/types/core/messages.d.ts +3 -1
  61. package/dist/types/core/operation-types.d.ts +7 -7
  62. package/dist/types/core/time-interval.d.ts +96 -0
  63. package/dist/types/core/variables.d.ts +13 -4
  64. package/dist/types/embed/host.d.ts +4 -4
  65. package/dist/types/react/annotations/annotation-editor-state.d.ts +2 -0
  66. package/dist/types/react/annotations/annotation-targets.d.ts +1 -0
  67. package/dist/types/react/annotations/getAnnotationProps.d.ts +5 -3
  68. package/dist/types/react/annotations/useAnnotationGeometry.d.ts +2 -2
  69. package/dist/types/react/bindings.d.ts +26 -3
  70. package/dist/types/react/date-formatting.d.ts +12 -0
  71. package/dist/types/react/hooks.d.ts +10 -9
  72. package/dist/types/react/index.d.ts +7 -2
  73. package/dist/types/react/search-suggestions.d.ts +8 -0
  74. package/dist/types/react/style-contract.d.ts +1 -5
  75. package/dist/types/react/ui/ChartLegend.d.ts +3 -2
  76. package/dist/types/react/ui/ChoicePicker.d.ts +2 -0
  77. package/dist/types/react/ui/DataApp.d.ts +5 -4
  78. package/dist/types/react/ui/DataAppFrame.d.ts +14 -3
  79. package/dist/types/react/ui/DataTable.d.ts +6 -4
  80. package/dist/types/react/ui/DataWidget.d.ts +4 -0
  81. package/dist/types/react/ui/DateDisplay.d.ts +9 -0
  82. package/dist/types/react/ui/DateRangePicker.d.ts +3 -1
  83. package/dist/types/react/ui/DateTimeTooltip.d.ts +3 -2
  84. package/dist/types/react/ui/DimensionPicker.d.ts +3 -1
  85. package/dist/types/react/ui/EmptyState.d.ts +1 -1
  86. package/dist/types/react/ui/GradientScroll.d.ts +8 -0
  87. package/dist/types/react/ui/Grid.d.ts +1 -1
  88. package/dist/types/react/ui/MetricWidget.d.ts +2 -0
  89. package/dist/types/react/ui/NumberFilterPicker.d.ts +3 -1
  90. package/dist/types/react/ui/PeriodSummary.d.ts +2 -1
  91. package/dist/types/react/ui/PickerField.d.ts +15 -0
  92. package/dist/types/react/ui/PopoverSurface.d.ts +5 -0
  93. package/dist/types/react/ui/RequestHint.d.ts +2 -2
  94. package/dist/types/react/ui/SearchField.d.ts +3 -1
  95. package/dist/types/react/ui/SearchTypeahead.d.ts +15 -0
  96. package/dist/types/react/ui/SectionHeading.d.ts +8 -0
  97. package/dist/types/react/ui/Select.d.ts +5 -1
  98. package/dist/types/react/ui/Sheet.d.ts +3 -1
  99. package/dist/types/react/ui/TableWidget.d.ts +8 -0
  100. package/dist/types/react/ui/Tabs.d.ts +4 -3
  101. package/dist/types/react/ui/VariableBar.d.ts +1 -1
  102. package/dist/types/react/ui/VisualizationWidget.d.ts +1 -1
  103. package/dist/types/react/ui/chart-date-axis.d.ts +15 -0
  104. package/dist/types/react/ui/chart-interaction.d.ts +21 -0
  105. package/dist/types/react/ui/chart-primitives.d.ts +4 -4
  106. package/dist/types/react/ui/chart-time.d.ts +16 -0
  107. package/dist/types/react/ui/chartColor.d.ts +1 -1
  108. package/dist/types/react/ui/icons.d.ts +3 -1
  109. package/dist/types/react/ui/index.d.ts +8 -4
  110. package/dist/types/react/ui/metric-comparison.d.ts +2 -2
  111. package/dist/types/react/ui/metric.d.ts +2 -2
  112. package/dist/types/react/ui/presentation.d.ts +2 -0
  113. package/dist/types/react/ui/searchItems.d.ts +2 -0
  114. package/dist/types/react/ui/variables.d.ts +1 -1
  115. package/dist/types/react/view-control-bar.d.ts +16 -0
  116. package/dist/types/react/view-controls.d.ts +3 -2
  117. package/dist/types/react/view-runtime.d.ts +3 -1
  118. package/dist/types/react/view.d.ts +14 -2
  119. package/dist/types/server/local.d.ts +3 -1
  120. package/dist/types/server/preview/host.d.ts +1 -0
  121. package/dist/types/server/preview/index.d.ts +16 -0
  122. package/dist/types/server/reload-channel.d.ts +6 -0
  123. package/dist/types/server/request-body.d.ts +4 -0
  124. package/dist/worker.js +1 -1
  125. package/docs/app-authoring.md +17 -9
  126. package/docs/client.md +1 -1
  127. package/docs/contract.md +8 -9
  128. package/docs/embed.md +11 -3
  129. package/docs/formatting-and-appearance.md +36 -5
  130. package/docs/layout.md +31 -8
  131. package/docs/react-embed.md +4 -4
  132. package/docs/react.md +1 -1
  133. package/docs/server-bun.md +25 -0
  134. package/docs/server.md +1 -1
  135. package/docs/styling.md +7 -28
  136. package/docs/ui.md +21 -18
  137. package/docs/variables.md +92 -15
  138. package/docs/views.md +13 -36
  139. package/docs/widgets.md +38 -26
  140. package/examples/starter-data-app/index.tsx +0 -1
  141. package/examples/starter-local-data-app/.bun-version +1 -0
  142. package/examples/starter-local-data-app/.node-version +1 -0
  143. package/examples/starter-local-data-app/.oxfmtrc.json +4 -0
  144. package/examples/starter-local-data-app/.oxlintrc.json +33 -0
  145. package/examples/starter-local-data-app/AGENTS.md +22 -0
  146. package/examples/starter-local-data-app/README.md +54 -0
  147. package/examples/starter-local-data-app/app.ts +22 -0
  148. package/examples/starter-local-data-app/bunfig.toml +2 -0
  149. package/examples/starter-local-data-app/package.json +33 -0
  150. package/examples/starter-local-data-app/src/App.tsx +8 -0
  151. package/examples/starter-local-data-app/src/assets.d.ts +1 -0
  152. package/examples/starter-local-data-app/src/data-context.ts +21 -0
  153. package/examples/starter-local-data-app/src/favicon.svg +13 -0
  154. package/examples/starter-local-data-app/src/index.html +14 -0
  155. package/examples/starter-local-data-app/src/main.tsx +7 -0
  156. package/examples/starter-local-data-app/src/operations.ts +6 -0
  157. package/examples/starter-local-data-app/src/server.ts +6 -0
  158. package/examples/starter-local-data-app/tsconfig.json +15 -0
  159. package/package.json +13 -3
  160. package/dist/chunks/index-ag0cgnvq.js.map +0 -13
  161. package/dist/chunks/index-dq7b35fn.js +0 -307
  162. package/dist/chunks/index-dq7b35fn.js.map +0 -13
  163. package/dist/chunks/index-f5cnbrjz.js.map +0 -13
  164. package/dist/chunks/index-gvers8jw.js.map +0 -109
  165. package/dist/chunks/index-ktmvs916.js.map +0 -13
  166. package/dist/chunks/index-m6n8ctfc.js.map +0 -10
  167. package/dist/chunks/index-mev09s5v.js +0 -77
  168. package/dist/chunks/index-mev09s5v.js.map +0 -10
  169. package/dist/chunks/index-mt93ff2b.js.map +0 -10
  170. package/dist/chunks/index-qd5xgx6y.js.map +0 -13
  171. package/dist/chunks/index-x69p7cv7.js.map +0 -10
  172. package/dist/types/react/shellStyles.d.ts +0 -3
  173. package/dist/types/react/ui/DataAppSkeleton.d.ts +0 -7
  174. /package/dist/chunks/{index-23dktynd.js.map → index-ap60vggk.js.map} +0 -0
  175. /package/dist/chunks/{index-ev2b5aaf.js.map → index-sx488hvs.js.map} +0 -0
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 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 X(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 U="altertable:data-app";var J=128,Z=60000;function M(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,128}$/.test(e)}function g({wire:e,from:t,session:r,parse:n}){return{wire:e,from:t,session:r,parse:n}}function j(e){if(!M(e.id))throw Error("Invalid request ID.");return e.id}function L(e,t){let r=e[t];if(typeof r!=="string")throw Error(`Invalid ${t}.`);return r}function A(){return{}}var m={channel:U,version:1,events:{connect:g({wire:"bridge:connect",from:"host",session:"none",parse:A}),ready:g({wire:"bridge:ready",from:"app",session:"none",parse:A}),initialize:g({wire:"bridge:initialize",from:"host",session:"establish",parse:(e)=>({state:e.state})}),request:g({wire:"bridge:request",from:"app",session:"current",parse:(e)=>{let t=L(e,"route");if(!t||t.length>256)throw Error("Invalid message route.");return{id:j(e),route:t,payload:e.payload}}}),result:g({wire:"bridge:result",from:"host",session:"current",parse:(e)=>{if(!Object.hasOwn(e,"response"))throw Error("Missing response.");return{id:j(e),response:e.response}}}),error:g({wire:"bridge:error",from:"host",session:"current",parse:(e)=>{if(e.requestId!==void 0&&typeof e.requestId!=="string")throw Error("Invalid requestId.");return{id:j(e),code:L(e,"code"),message:L(e,"message"),...e.requestId===void 0?{}:{requestId:e.requestId}}}}),cancel:g({wire:"bridge:cancel",from:"app",session:"current",parse:(e)=>({id:j(e)})}),disconnect:g({wire:"bridge:disconnect",from:"app",session:"current",parse:A}),scriptLoad:g({wire:"script:load",from:"host",session:"current",parse:(e)=>({javascript:L(e,"javascript")})}),stateUpdate:g({wire:"state:update",from:"host",session:"current",parse:(e)=>({state:e.state})}),runtimeLog:g({wire:"runtime:log",from:"app",session:"current",parse:(e)=>{if(!X(e.payload))throw Error("Invalid log entry.");return{payload:e.payload}}}),runtimeReady:g({wire:"runtime:ready",from:"app",session:"current",parse:A}),runtimeError:g({wire:"runtime:error",from:"app",session:"current",parse:A})}},_=new Map;for(let e of Object.keys(m.events)){let t=m.events[e].wire;if(_.has(t))throw Error(`Duplicate bridge event: ${t}`);_.set(t,e)}function C(e){return _.get(e)}function F(e){if(!e||typeof e!=="object")return;let t=e;if(t.channel!==U||t.version!==m.version||typeof t.type!=="string"||typeof t.documentId!=="string"||!t.documentId||t.documentId.length>128||t.sessionId!==void 0&&!M(t.sessionId)||t.token!==void 0&&typeof t.token!=="string")return;return t}function W(e,t){try{return{channel:U,version:m.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 Y(e){let t=F(e);if(!t)return;let r=C(t.type);if(!r)return;let n=m.events[r];if(n.session!=="none"&&t.sessionId===void 0)return;return W(t,n)}function ee({role:e,origin:t,source:r,opaque:n,context:o,post:d,diagnostic:a,invalidRequest:u,handlers:l}){let c=!1;function p(b,R){if(c)throw Error("The bridge endpoint has closed.");let i=m.events[b],f=o(),k=Y({...R,channel:m.channel,version:m.version,type:i.wire,documentId:b==="connect"?"host":f.documentId,sessionId:f.sessionId,token:n?f.token:void 0});if(!k||n&&!M(f.token))throw Error("The bridge is not ready to send this event.");if(a?.("send",i.wire),c)return;d(k)}function v(b){let R=r();if(c||!R||b.origin!==t||b.source!==R)return;let i=F(b.data);if(!i)return;let f=o(),k=e==="app"&&i.type===m.events.connect.wire;if(n&&(k?!M(i.token):!f.token||i.token!==f.token))return;let B=C(i.type);if(!B)return;let x=m.events[B];if(x.from===e)return;if(x.session==="establish"){if(i.documentId!==f.documentId||i.sessionId===void 0)return}else if(x.session==="current"){if(!f.sessionId||i.sessionId!==f.sessionId||i.documentId!==f.documentId)return}let N=W(i,x);if(!N){if(e==="host"&&B==="request"&&M(i.id))u?.(i.id);return}if(a?.("receive",x.wire),c)return;let T=l[B];T(N)}return{send:p,receive:v,dispose(){c=!0}}}function ge(e){return e===null||typeof e==="string"||typeof e==="boolean"||typeof e==="number"&&Number.isFinite(e)}function V(e){return!!e&&typeof e==="object"&&!Array.isArray(e)&&Object.values(e).every(ge)}var te=Symbol.for("@altertable/data-app/MessageRoutingError");class h extends Error{code;requestId;[te]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[te]===!0}constructor(e,t,r){super(t);this.code=e;this.requestId=r;this.name="MessageRoutingError"}}function me(e){return e}function re(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,r){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 o=n.body;if(n.status<200||n.status>=300){let a=o.error;throw new h(typeof a?.code==="string"?a.code:"request_failed",typeof a?.message==="string"?a.message:"Could not load data.",typeof a?.requestId==="string"?a.requestId:void 0)}if(!("data"in o)||typeof o.requestId!=="string"||typeof o.queriedAt!=="string"||!Array.isArray(o.queryIds)||!o.queryIds.every((a)=>typeof a==="string"))throw Error("Invalid data envelope.");if(o.queries!==void 0&&(!Array.isArray(o.queries)||!o.queries.every((a)=>a&&typeof a==="object"&&typeof a.name==="string"&&typeof a.statement==="string"&&(a.params===void 0||V(a.params))&&(a.queryId===void 0||typeof a.queryId==="string"))))throw Error("Invalid query evidence.");let d=e?.[r.operation];return{status:n.status,body:{...o,data:d?d.output(o.data):o.data}}}}}var ne=me({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&&!V(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 oe(e,t){return{async request(r,n,{signal:o}={}){if(o?.throwIfAborted(),!Object.hasOwn(e,r))throw new h("unknown_route","Unknown message route.");let d=e[r],a;try{a=d.input(n)}catch{throw new h("invalid_payload","Invalid message payload.")}let u=await t({route:r,payload:a},o);o?.throwIfAborted();try{return d.output(u,a)}catch(l){if(l instanceof h)throw l;throw new h("invalid_response","Invalid message response.")}}}}var se=Symbol.for("@altertable/data-app/DataAppError");class E extends Error{code;requestId;[se]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[se]===!0}constructor(e,t,r){super(e);this.code=t;this.requestId=r;this.name="DataAppError"}}function ae(e,t){function r(o){if(o.length===1&&typeof o[0]==="function"){let d=o[0]();return Array.isArray(d)?d:[d]}return o.map((d)=>typeof d==="function"?d():d)}function n(o,d){if(!e())return;try{t({method:o,args:r(d)})}catch{}}return{log:(...o)=>n("log",o),info:(...o)=>n("info",o),warn:(...o)=>n("warn",o),error:(...o)=>n("error",o)}}function ie(e,t){if(t.type==="runtime:log")return;e.log(()=>{let r={type:t.type};if("id"in t)r.id=t.id;if(t.type==="bridge:request"){r.route=t.route;let n=t.payload;if(t.route==="data:query"&&n&&typeof n==="object"&&"operation"in n&&typeof n.operation==="string")r.operation=n.operation}return["Sending message to parent",r]})}function de(e){if(e instanceof h)throw new E(e.message,e.code,e.requestId);throw e}function ue({parentOrigin:e,window:t=window,timeoutMs:r=Z,mode:n="url",loadScript:o}){if(new URL(e).origin!==e)throw Error("Expected an exact parent origin.");let d=q(),a,u,l=!1,c=new Map,p,v=new Set,b=ae(()=>!l&&!!u&&!!p&&typeof p==="object"&&("logging"in p)&&p.logging===!0,(s)=>i("runtimeLog",{payload:s})),R=ee({role:"app",origin:e,source:()=>t.parent,opaque:n==="bundle",context:()=>({documentId:d,sessionId:u,token:a}),post(s){t.parent.postMessage(s,e),ie(b,s)},handlers:{connect(s){if(n==="bundle")a=s.token;i("ready",{})},initialize(s){if(u&&u!==s.sessionId)for(let I of c.values())I.reject(new E("The preview reconnected. Retry the request.","bridge_reset"));let y=!u;if(u=s.sessionId,k(s.state),y)for(let I of c.values())I.start();if(l)return;if(n==="url")i("runtimeReady",{})},stateUpdate(s){k(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 h(s.code,s.message,s.requestId))}}}),{send:i,receive:f}=R;function k(s){p=s;for(let y of v)y(s)}t.addEventListener("message",f);function B(s,y){return new Promise((I,w)=>{if(l)return w(new E("The preview has closed.","bridge_closed"));if(y?.aborted)return w(y.reason);if(c.size>=J)return w(new E("Too many pending data requests.","bridge_busy"));let O=q(),Q=!1;function P(){clearTimeout(ye),y?.removeEventListener("abort",G),c.delete(O)}function G(){if(Q)i("cancel",{id:O});P(),w(y?.reason)}let ye=setTimeout(()=>{if(Q)i("cancel",{id:O});P(),w(new E(u?"The data request timed out.":"The preview shell is unavailable. Reload the preview.",u?"timeout":"bridge_unavailable"))},r),K={start(){if(Q)return;try{i("request",{id:O,route:s.route,payload:s.payload}),Q=!0}catch{P(),w(new E("The message payload could not be sent.","invalid_payload"))}},resolve(S){P(),I(S)},reject(S){P(),w(S)}};if(c.set(O,K),y?.addEventListener("abort",G,{once:!0}),u)K.start();else if(n==="url"||a)i("ready",{})})}let x=oe({"data:query":re(),"data:sql":ne},B);function N(s,y,I){return x.request("data:query",{operation:s,input:y},{signal:I}).catch(de)}function T(){if(u)i("disconnect",{});u=void 0;for(let s of c.values())s.reject(new E("The preview has closed.","bridge_closed"))}function H(s){if(s.persisted&&(n==="url"||a))i("ready",{})}function fe(){if(l)return;T(),l=!0,R.dispose(),t.removeEventListener("message",f),t.removeEventListener("pagehide",T),t.removeEventListener("pageshow",H),v.clear()}if(t.addEventListener("pagehide",T),t.addEventListener("pageshow",H),n==="url")i("ready",{});return{logger:b,request:B,transport:N,lakehouse:{queryAll(s,{limit:y,signal:I,params:w}){return x.request("data:sql",{statement:s,limit:y,...w===void 0?{}:{params:w}},{signal:I}).catch(de)}},dispose:fe,mode:n,snapshot(){return p},subscribe(s){return v.add(s),()=>{v.delete(s)}},ready(){if(!l&&u)i("runtimeReady",{})},fail(){if(!l&&u)i("runtimeError",{})}}}var z=Symbol.for("altertable.localFrameBridge"),D=Symbol.for("altertable.installedTransport");function pe(e,t=window){let r=t;if(r[D])throw Error("A data app transport is already installed.");return r[z]=e,r[D]=e,()=>{if(r[z]===e)delete r[z];if(r[D]===e)delete r[D];e.dispose()}}function ce({parentOrigin:e,window:t=window}){let r,n=!1,o=`altertable-data-app-${q()}.js`,d=ue({parentOrigin:e,window:t,mode:"bundle",loadScript(p){if(r!==void 0){if(p===r)if(n)d.fail();else d.ready();else d.fail();return}r=p;try{let v=t.document.createElement("script");if(v.textContent=`${p}\n//# sourceURL=${o}`,t.document.body.append(v),!n)d.ready()}catch{a()}}});function a(){n=!0,d.fail()}function u(p){if(p.filename===o)a()}function l(p){if(p.reason instanceof Error&&p.reason.stack?.includes(o))a()}t.addEventListener("error",u),t.addEventListener("unhandledrejection",l);let c=pe(d,t);return()=>{t.removeEventListener("error",u),t.removeEventListener("unhandledrejection",l),c()}}var le=document.currentScript?.dataset.parentOrigin;if(!le)throw Error("Missing trusted parent origin.");ce({parentOrigin:le});})();\n'.replace(/<\/script/gi, (match) => `<\\${match.slice(1)}`);
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)}`);
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>
@@ -1,7 +1,7 @@
1
1
  # Author a data app
2
2
 
3
3
  Build an exploration that answers the user's question and a story that presents
4
- its strongest findings. Include CSV export so readers can take the displayed
4
+ its strongest findings. Include CSV export so users can take the displayed
5
5
  results into their own tools. Exploration, export, and story use the same
6
6
  queries, definitions, and evidence.
7
7
 
@@ -17,6 +17,15 @@ Derive displays, exports, and findings from their results. See
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
+ ## Choose the visualizations
21
+
22
+ Before implementing queries and rendering, identify the question each visual
23
+ answers, [choose its component](widgets.md#choose-a-visualization), and establish
24
+ the required result shape: population, grain, units, ordering, and observation
25
+ status. Prefer a specialized chart when its semantics fit. Check the component's
26
+ input contract before reducing results to generic labels and values; preserve
27
+ supplied query definitions when adapting their results.
28
+
20
29
  ## Build the exploration
21
30
 
22
31
  Choose the execution path:
@@ -37,7 +46,7 @@ and internal execution settings out of filter controls.
37
46
 
38
47
  Register inspected tables and fields with `defineDataIdentifiers()` and use
39
48
  `<DataIdentifier>` when naming sources. Register terms and query evidence so
40
- readers can inspect the source of each claim.
49
+ users can inspect the source of each claim.
41
50
 
42
51
  Connect visualizations with introductions and explanations. Use `<TextWidget>`
43
52
  for a narrative panel with the standard widget frame, or `<TextContent>` for
@@ -67,12 +76,12 @@ on the view so tables, exports, and stories share values and evidence.
67
76
  Every data app supplies a [story and CSV export](stories-and-export.md)
68
77
  from the displayed result. Export all distinct datasets at their displayed grain;
69
78
  reuse a dataset when several visuals derive from the same rows. Present the
70
- findings that answer the reader's question, rather than every row or chart.
79
+ findings that answer the user's question, rather than every row or chart.
71
80
  Use the [standard layout](layout.md) and built-in toolbar actions.
72
81
 
73
82
  ### Organize the exploration
74
83
 
75
- Use sections for a focused question and for findings readers should compare
84
+ Use sections for a focused question and for findings users should compare
76
85
  side by side. Add app-level `<Tabs>` from `/react/ui` when the exploration has
77
86
  distinct analytical questions, such as Overview, Retention, and Segments, each
78
87
  with its own context and group of widgets. Lead with the most useful overview
@@ -80,7 +89,7 @@ and label tabs by the question or subject they explore.
80
89
 
81
90
  Use `<VisualizationWidget>`'s `views` for alternate representations of the same
82
91
  dataset, such as a chart and its rows. Keep these choices within the widget;
83
- use filter variables when the reader is changing the data scope.
92
+ use filter variables when the user is changing the data scope.
84
93
 
85
94
  Navigation tabs, widget views, and declared data views have different roles.
86
95
  A declared view owns inputs, requests, and displayed results; a tab does not
@@ -90,15 +99,14 @@ needs separate requests. Keep filter placement consistent across tabs and make
90
99
  each filter's scope clear. Derive findings, story, and export from the displayed
91
100
  results and their inputs.
92
101
 
93
- Choose each visual for the question it answers; see
94
- [visualization selection](widgets.md#choose-a-visualization).
95
-
96
102
  ## Verify the app
97
103
 
98
104
  Follow the [UI quality contract](ui-quality.md) for hierarchy, responsive
99
105
  composition, typography, and control states.
100
106
 
101
- Verify findings against the source and the user's question. Distinguish measured
107
+ Verify that each visual answers its intended question and preserves the source
108
+ population, units, ordering, and missing or incomplete observations. Check
109
+ findings against the source and the user's question. Distinguish measured
102
110
  zero, unavailable values, and empty results. Check filters, refresh, loading,
103
111
  empty, error, and stale states, then present the story. Download CSV from the
104
112
  standalone and embedded toolbar and verify its filename, columns, raw values,
package/docs/client.md CHANGED
@@ -53,7 +53,7 @@ const client = createDataClient({
53
53
  const response = await client.query('connection', {});
54
54
  ```
55
55
 
56
- The client runs input parsing, operation logic, and output parsing in the browser.
56
+ The client runs input parsing and operation logic in the browser.
57
57
  Operation policy bounds rows, duration, and response size and records query evidence. Each query sends `{ statement, limit, params? }`
58
58
  to the installed iframe bridge's `data:sql` route; the host needs no operation
59
59
  registry. Results include query evidence. Credentials remain backend-owned.
package/docs/contract.md CHANGED
@@ -35,19 +35,18 @@ const dataApp = defineDataApp({
35
35
 
36
36
  const products = dataApp.defineOperation({
37
37
  input: parseProductInput,
38
- output: parseProducts,
39
38
  checks: [{}],
40
39
  policy: { maxQueryRows: 100, maxDurationMs: 15000 },
41
40
  async run({ query }, input) {
42
41
  const result = await query('products', input);
43
- return rowsAsRecords(result, ['org_id']);
42
+ return parseProducts(rowsAsRecords(result, ['name', 'price']));
44
43
  },
45
44
  });
46
45
  ```
47
46
 
48
47
  `parseProductInput()` and `parseProducts()` are app-owned example functions, not
49
- package exports. Validate
50
- filter values in the input parser. `{}` declares a required parameter; `{ defaultValue }` supplies
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
51
50
  a fallback. `query(name, params, { limit })` executes only registered queries and
52
51
  inherits the operation's row limit and cancellation signal.
53
52
 
@@ -73,8 +72,8 @@ export const calendar = defineDateRangeContract({
73
72
  });
74
73
  ```
75
74
 
76
- `parseEmptyInput()`, `parseTrue()`, `parseCount()`, and `parseDateRangeInput()` validate
77
- common inputs and results. `connectionCheck(dataApp.queries)` runs the registered `connection` query. A successful connectivity check confirms access; it is not an
75
+ `parseEmptyInput()`, `parseCount()`, and `parseDateRangeInput()` validate common inputs
76
+ and query values. `connectionCheck(dataApp.queries)` runs the registered `connection` query. A successful connectivity check confirms access; it is not an
78
77
  analysis result.
79
78
 
80
79
  See [server authorization](server.md) and [React views](react.md) for the two
@@ -112,9 +111,9 @@ an intentional public code, message, and optional request ID; other handler
112
111
  errors are replaced with a generic failure.
113
112
 
114
113
  `defineDataQueryRoute(operationContracts)` validates the selected operation's
115
- input and output and preserves its response evidence. It infers the result type
116
- from the selected operation when used with `createMessageClient()`. Share input and
117
- output parsers, not operation implementations containing SQL or credentials.
114
+ input and preserves its response evidence. It infers the result type from the
115
+ selected operation's `run` when used with `createMessageClient()`. Share input
116
+ parsers and operation types, not operation implementations containing SQL or credentials.
118
117
  `dataAppRoutes` supplies generic `data:query` and `navigation:update` contracts;
119
118
  generic hosts must delegate operation validation and authorization to their
120
119
  server. Request handlers receive `{ signal }` for cancellation.
package/docs/embed.md CHANGED
@@ -100,9 +100,17 @@ client acknowledged initialization or a bundle script finished evaluation. It
100
100
  does not mean asynchronous data queries finished. Script errors report `failed`.
101
101
  The source bridge's `startupTimeoutMs` defaults to 30 seconds.
102
102
 
103
- `onDiagnostic` receives only message `direction` and `type`, never tokens or
104
- payloads. Routed handlers must authorize every data request. Message validation
105
- and iframe isolation do not grant access to data or execute SQL.
103
+ `onDiagnostic` receives delivery metadata, never tokens or payloads: `direction`
104
+ (`send`, `receive`, or `drop`), message `type`, and, when present, the request
105
+ `id`, `route`, query `operation`, and error `code`, `message`, and `requestId`.
106
+ Results and errors include `durationMs`, the host handling time. `drop` events
107
+ report why a message from the connected iframe was ignored, such as a stale
108
+ session or token; messages from other windows are not reported.
109
+
110
+ When a `logger` is set, the iframe also forwards its view of the bridge: messages
111
+ it sends, receives, and ignores, local timeouts, reconnect resets, and the cause
112
+ of a `failed` status. Routed handlers must authorize every data request. Message
113
+ validation and iframe isolation do not grant access to data or execute SQL.
106
114
 
107
115
  ## SQL query route
108
116
 
@@ -13,6 +13,9 @@ Import formatting helpers from `@altertable/data-app/format`.
13
13
  | `formatCount()` | Nonnegative integer counts, optionally compact |
14
14
  | `formatPercent()` | Ratios represented as a fraction, such as 0.12 for 12% |
15
15
  | `formatMetric()` | A metric definition's count, ratio, or currency format |
16
+ | `formatDate()` | Calendar dates without time-zone shifts |
17
+ | `formatDateTime()` | Event timestamps in the reporting time zone |
18
+ | `formatTime()` | Intraday chart labels |
16
19
  | `formatDateRange()` | Inclusive calendar ranges |
17
20
  | `pluralize()` | Count-dependent labels |
18
21
 
@@ -37,6 +40,32 @@ Import `chartColor()` from `/react` to select colors from the configured palette
37
40
  `<DateTimeTooltip>` expose readable timestamps with exact-date details.
38
41
  `<DataTableTimestamp>` and `<DataTableShare>` format custom table cells.
39
42
 
43
+ ## Display dates consistently
44
+
45
+ Declare date meaning on dataset columns so tables use readable values and CSV
46
+ keeps the originals:
47
+
48
+ ```ts
49
+ columns: {
50
+ day: { value: row => row.day, format: { kind: 'date' } },
51
+ observed: {
52
+ value: row => row.observed,
53
+ format: { kind: 'dateTime', precision: 'second' },
54
+ },
55
+ }
56
+ ```
57
+
58
+ Calendar dates use `YYYY-MM-DD`. Instants accept epoch milliseconds or timestamp
59
+ strings; `<DateDisplay>` also accepts `Date`. Timestamp strings require `Z` or an explicit
60
+ offset; convert database-local timestamps in the operation using their known
61
+ source zone. Ambiguous or invalid values display as missing.
62
+
63
+ Use `<DateDisplay>` for prose and `useDateFormatting()` with format helpers for
64
+ custom chart labels. Defaults are `en-US` and UTC; configure app-wide
65
+ `dateFormatting: { locale, timeZone }` when appropriate. A time view supplies its
66
+ reporting zone, and an explicit field zone overrides it. Keep seconds when event
67
+ ordering matters; exact-time details remain available on timestamps.
68
+
40
69
  ## Configure identity and appearance
41
70
 
42
71
  ```ts
@@ -48,7 +77,7 @@ const dataApp = defineDataApp({
48
77
  scope: { organization: 'Acme', environment: 'Production' },
49
78
  appearance: {
50
79
  theme: 'system',
51
- accentColor: '#405d47',
80
+ baseColor: 'neutral',
52
81
  density: 'comfortable',
53
82
  },
54
83
  queries: {},
@@ -56,13 +85,15 @@ const dataApp = defineDataApp({
56
85
  ```
57
86
 
58
87
  Scope labels describe the configured connection; they do not grant access.
59
- `dataAppTitle()` produces the scoped document title used by `mountDataApp()`.
60
88
 
61
89
  Title and description explain the app and can be revised when regenerating it.
62
90
  Omit appearance to use the standard defaults.
63
91
 
64
- Appearance controls the brand palette, typography, density, corner radius, and
65
- elevation. Those settings apply consistently to the app instead of tuning each
66
- widget. Theme preference is reader-owned in standalone apps. A trusted parent's
92
+ The default UI is neutral in light and dark themes. Use `baseColor` for the base
93
+ palette and `accentColor` with optional `darkAccentColor` for brand emphasis.
94
+ Configure chart colors separately with `chartColors`; preserve semantic status
95
+ colors for favorable and unfavorable outcomes.
96
+
97
+ Configure appearance once for the app. Theme preference is user-owned in standalone apps. A trusted parent's
67
98
  resolved theme takes precedence and hides local theme controls; see
68
99
  [parent presentation](embed.md#parent-presentation).
package/docs/layout.md CHANGED
@@ -2,20 +2,17 @@
2
2
 
3
3
  The shell owns page width, outer gutters, and header/body spacing. Use `<Stack>`
4
4
  for sections, `<Grid>` for peer widgets, and `<GridItem>` for spans. Use
5
- `<TextContent>` for prose. Widgets own their internal padding; their parents own
5
+ `<SectionHeading>` to name widget groups and `<TextContent>` for prose. Widgets own their internal padding; their parents own
6
6
  external spacing. Keep widget customization inside the widget so its parent can maintain consistent
7
7
  spacing between sections and cards.
8
8
 
9
- By default, section and widget gaps use `--atbl-layout-gap`, with density configured once
10
- in `app.appearance`. The package owns wrapping and span collapse based
11
- on the available container width and configured gap. Custom length values for
12
- `--atbl-layout-gap`, `--atbl-space-sm`, and `--atbl-space-md` also drive span
13
- collapse; a two-column span activates only when two minimum-width tracks fit.
9
+ Configure density once in `app.appearance`. `<Grid>` wraps to fit its container;
10
+ spans collapse when there is not enough space.
14
11
 
15
12
  ```tsx
16
13
  <Stack>
14
+ <SectionHeading>Activity</SectionHeading>
17
15
  <TextContent>
18
- <h2>Activity</h2>
19
16
  <p>Explore the sources behind this finding.</p>
20
17
  </TextContent>
21
18
  <Grid columns={3}>
@@ -25,9 +22,35 @@ collapse; a two-column span activates only when two minimum-width tracks fit.
25
22
  </Stack>
26
23
  ```
27
24
 
25
+ Set widget `headingLevel={3}` beneath a section heading; visual styling stays
26
+ consistent across widget types.
27
+
28
+ Use `<DataApp footer={...}>` for an optional source, coverage, or methodology
29
+ note below the app content. The footer provides muted body text across the content
30
+ width and top spacing. Compose paragraphs, links, lists, and inline components such
31
+ as `<DataIdentifier>` or `<DateDisplay>` directly; no `<TextContent>` wrapper is
32
+ needed. Keep headings and data widgets in the body, and app controls in
33
+ `footerActions`. Keep static notes outside loading sections.
34
+
35
+ ```tsx
36
+ <DataApp
37
+ {...appProps}
38
+ footer={
39
+ <>
40
+ <p>
41
+ <strong>Coverage.</strong> Records include the last 90 days.
42
+ </p>
43
+ <p>Counts reflect current inventory, not an activity log.</p>
44
+ </>
45
+ }
46
+ >
47
+ <DataSection content={content} />
48
+ </DataApp>
49
+ ```
50
+
28
51
  ## Verify rendered layouts
29
52
 
30
- Check computed section/widget gaps, sibling alignment, outer gutters, and
53
+ Check spacing, alignment, outer gutters, and
31
54
  horizontal overflow at phone and desktop iframe widths. Check loading, empty,
32
55
  error, ready, and stale states. Loading placeholders should use the same grid as
33
56
  the ready content.
@@ -94,10 +94,10 @@ are mutually exclusive.
94
94
 
95
95
  ## Loading an embedded app
96
96
 
97
- Use `<DataAppSkeleton>` from `/react/ui` while the host builds or starts an app.
98
- Call `injectDataAppShellStyles()` from `/react/ui` before rendering the placeholder.
99
- The host owns when to show it and supplies any surrounding header or footer.
100
- `/react/embed` itself remains independent of UI components and styles.
97
+ The host owns loading and generation UI while an app starts. Use a neutral
98
+ status that does not imply a particular app layout. `/react/embed` remains
99
+ independent of UI components and styles. Once the app loads, its query and
100
+ widget loading states describe the content they replace.
101
101
 
102
102
  ## Parent-owned presentation
103
103
 
package/docs/react.md CHANGED
@@ -7,7 +7,7 @@ React 19.2 or newer and React DOM 19.2 or newer are peer dependencies.
7
7
 
8
8
  Use `mountDataApp({ app, component })` to mount into `#root`. When mounting
9
9
  through another framework, wrap the root in `<DataAppProvider app={app}>` from `/react/ui`.
10
- `<DataApp>` inherits identity and appearance from that root. Mounting sets the document title before React renders.
10
+ `<DataApp>` inherits identity and appearance from that root.
11
11
 
12
12
  ```tsx
13
13
  import { injectDataAppStyles, mountDataApp } from '@altertable/data-app/react';
@@ -27,3 +27,28 @@ Missing credentials fail the query. Keep these variables out of browser code.
27
27
  Local serving does not authenticate hosted viewers.
28
28
  Use [the portable server handler](server.md) with per-request authorization when
29
29
  hosting an app for other people.
30
+
31
+ ## Preview a single-file app
32
+
33
+ Import `serveAppFile()` from `@altertable/data-app/server/bun/preview` to preview
34
+ an app in the hosted sandbox. The caller supplies the server-only lakehouse.
35
+ The runtime owns bundling, imported-file watching, reloads, navigation, and exports.
36
+
37
+ ```ts
38
+ import { serveAppFile } from '@altertable/data-app/server/bun/preview';
39
+ import { localLakehouse } from '@altertable/data-app/server/bun';
40
+
41
+ const preview = await serveAppFile({
42
+ file: '/absolute/path/index.tsx',
43
+ lakehouse: localLakehouse(),
44
+ });
45
+ console.log(preview.url);
46
+ // When the launcher stops:
47
+ await preview.stop();
48
+ ```
49
+
50
+ The preview resolves `@altertable/data-app` and React from its own installation.
51
+ It binds to localhost and accepts SQL only from its own origin,
52
+ with a streaming limit of 100,000 UTF-8 bytes per query request. The caller
53
+ owns profile validation, dependency installation, and credentials. This entry requires Bun and adds no Bun installation or dependency
54
+ to browser consumers. Keep it separate from browser imports.
package/docs/server.md CHANGED
@@ -27,7 +27,7 @@ returned lakehouse to the viewer's permitted data. Supply trusted registry
27
27
  parameters through `queryParams`; query callers cannot override these values. Origin and Fetch Metadata
28
28
  checks reject cross-site browser requests; they do not authenticate viewers.
29
29
 
30
- The handler validates operation input and output, enforces query row and duration
30
+ The handler validates operation input, enforces query row and duration
31
31
  bounds, propagates cancellation, and returns query evidence and request IDs.
32
32
  Keep credentials and operation implementations on the server.
33
33
 
package/docs/styling.md CHANGED
@@ -13,15 +13,6 @@ Configure theme, palette, accent, typography, density, radius, and elevation thr
13
13
  Add app-owned classes through `className`. Render package components rather than copying their classes onto markup;
14
14
  private descendants are not customization hooks. Public names and stable roots
15
15
  are listed in the [typed contract](https://github.com/altertable-ai/data-app/blob/main/src/react/style-contract.ts).
16
- CSS comments document [inherited defaults](https://github.com/altertable-ai/data-app/blob/main/src/react/tokens.css),
17
- [interaction overrides](https://github.com/altertable-ai/data-app/blob/main/src/react/interaction.css),
18
- and [focus overrides](https://github.com/altertable-ai/data-app/blob/main/src/react/ui/Focus.css).
19
- Widget-specific overrides live beside their uses in
20
- [metrics](https://github.com/altertable-ai/data-app/blob/main/src/react/ui/MetricWidget.css),
21
- [bar charts](https://github.com/altertable-ai/data-app/blob/main/src/react/ui/BarChart.css),
22
- [code](https://github.com/altertable-ai/data-app/blob/main/src/react/ui/QueryList.css),
23
- and [layout](https://github.com/altertable-ai/data-app/blob/main/src/react/ui/Grid.css).
24
- The `--atbl-` prefix means Altertable.
25
16
 
26
17
  ```css
27
18
  .app-action {
@@ -30,20 +21,10 @@ The `--atbl-` prefix means Altertable.
30
21
  }
31
22
  ```
32
23
 
33
- Set tokens on `:root` for the document or on a component for local overrides.
34
- Inherited tokens are usable in app CSS. Optional overrides fall back where they
35
- are consumed, so local colors, fonts, and spacing compose. Portals inherit from
36
- their actual DOM ancestors. Normal unlayered app CSS overrides package rules.
37
- `DataAppStyle` checks public inline custom-property names.
38
-
39
- `--atbl-control-text-size` controls editable text, including compact search fields,
40
- date segments, and annotation editors. It defaults to the body text size.
41
- Package controls and custom controls with `data-atbl-control="text"` enforce a
42
- 16px minimum on narrow or touch viewports to prevent browser focus zoom. Keep
43
- that minimum when adding app-owned input styles.
44
-
45
- When overriding `--atbl-accent` directly, also choose `--atbl-on-accent` with
46
- sufficient contrast. Prefer appearance configuration for brand and chart colors.
24
+ Type inline token overrides with `DataAppStyle`. Give optional tokens a `var()`
25
+ fallback in app CSS. Use `:root` for shared theme overrides, including menus and overlays.
26
+ Prefer `app.appearance` for brand and chart colors. When overriding accent tokens,
27
+ choose a contrasting foreground too. Keep text inputs at least 16px on mobile.
47
28
 
48
29
  ## Native controls
49
30
 
@@ -55,8 +36,6 @@ Use package controls when possible. For a custom native control:
55
36
  </button>
56
37
  ```
57
38
 
58
- These hooks provide cursor and focus styling; keep native semantics, accessible
59
- names, disabled state, and keyboard behavior. `DataAppStyleHooks` checks hook
60
- values. Use `default` for tooltip targets that only reveal information on hover
61
- or tap, and `action` for controls that perform an action. Use `inset` focus inside
62
- clipped surfaces and `group` when a wrapper owns an input's outline. See [UI quality](ui-quality.md) for rendered verification.
39
+ These hooks provide cursor and focus styling; keep accessible names, disabled
40
+ state, and keyboard behavior. See
41
+ [UI quality](ui-quality.md) for rendered verification.
package/docs/ui.md CHANGED
@@ -10,10 +10,14 @@ frame for deliberately custom content. Use `<GettingStarted>` for
10
10
  connection setup. Fetched data belongs to a declared view; avoid inventing
11
11
  request states to populate a shell.
12
12
 
13
+ Widget titles use the available header width and wrap when needed. Supplying
14
+ `status` reserves space for refresh and retry feedback, including while idle.
15
+
13
16
  Direct `<DateRangePicker>`, `<DimensionPicker>`, and `useAppVariables()` support
14
17
  custom control ownership. The caller supplies values and change handlers.
15
18
  Custom tables use `<DataTable>` and its cell helpers; controls and overlays
16
19
  include `<SearchField>`, `<ChoicePicker>`, `<Tabs>`, `<Sheet>`, and `<HelpPopover>`.
20
+ Horizontal `<TabList>` content scrolls with gradient cues at overflowing edges.
17
21
 
18
22
  Standalone `<AboutData>`, glossary components, and `<PresentStory>` support
19
23
  custom inspection and presentation. Supply registered context and evidence, and
@@ -106,15 +110,19 @@ Use `useSvgId()` for stable IDs when composing custom SVG definitions.
106
110
 
107
111
  Use `<FunnelChart>`, `<RetentionChart>`, and `<JourneyChart>` from `/react/ui`
108
112
  inside `<VisualizationWidget>`. Derive inputs from the displayed rows; the
109
- binding owns loading, evidence, CSV, and story content. Types and JSDoc describe
110
- input constraints; the gallery includes complete examples.
113
+ binding owns loading, evidence, CSV, and story content. The query owns counting,
114
+ conversion windows, and cohort definitions; these components visualize results.
115
+
116
+ - `<FunnelChart>`: ordered steps and aligned, nonincreasing counts per population.
117
+ - `<RetentionChart>`: numeric offsets, fractional rates (`0.25`, not `25`), retained
118
+ counts, and cohort size. Distinguish unobserved (`null`), observed zero, and
119
+ observed but still accumulating (`incomplete`) periods.
120
+ - `<JourneyChart>`: full ordered paths with counts and outcomes; preserve repeated
121
+ events and mark cut-off paths as `truncated`.
111
122
 
112
- - `<FunnelChart>` compares ordered step counts across populations. Each series
113
- uses its first step as the baseline; hatching shows previous-step drop-off.
114
- - `<RetentionChart>` plots query-defined rates and retained counts by interval
115
- offset. Use `null` for unobserved periods; `incomplete` produces a dotted tail.
116
- - `<JourneyChart>` derives expandable branches and outcomes from full paths.
117
- Truncated paths stop at the last loaded event.
123
+ See the [complete component examples](https://github.com/altertable-ai/data-app/blob/main/dev/fixtures/gallery-basics.tsx)
124
+ for input shapes and composition. Read the exported types and JSDoc for exact
125
+ constraints before adapting displayed rows.
118
126
 
119
127
  ### Composed charts
120
128
 
@@ -158,10 +166,8 @@ shared with chart tooltips and funnel summaries. Pass `kind="square"` explicitly
158
166
  when composing a marker.
159
167
  `<PieChart>` includes a legend by default; `showLegend={false}` omits it.
160
168
 
161
- Legends align cells in a container-responsive grid, truncate labels, and reserve
162
- an overflow cell for “+X more.” Use `maxVisibleItems` to choose the limit or
163
- `layout="vertical"` for a list. Legends describe series; authored toggles or a
164
- composed legend's `onClick` leave series visibility to the app.
169
+ Legends describe series; authored toggles or a composed legend's `onClick`
170
+ leave series visibility to the app.
165
171
 
166
172
  ## Filter controls
167
173
 
@@ -200,15 +206,12 @@ and emit only valid intervals. Numeric input and compact selects respect the
200
206
  shared mobile text-size minimum.
201
207
 
202
208
  Use `<FilterBar>` to arrange predicates and `<VariableBar>` for mixed app
203
- parameters. Each filter shows its current value; categorical single selection includes All.
204
- `<FilterActions>` provides one Clear icon with a tooltip, plus optional paired
205
- Apply/Cancel actions for app-owned drafts. The caller owns those actions; the
206
- components do not infer query state.
209
+ parameters. Use `<FilterActions>` for Clear or paired Apply/Cancel actions on
210
+ app-owned drafts; provide the handlers for your applied state.
207
211
 
208
212
  `<NumberFilterPicker>` composes numeric fields inside a dedicated popover. Edits
209
213
  remain local until Apply; Cancel and dismissal discard them. Use `<NumberField>`
210
214
  and `<NumberRangeField>` as inline input primitives when composing forms.
211
215
 
212
216
  Use `<Button variant="primary">` for the main committing action, such as Apply.
213
- Primary buttons use the theme foreground as their fill and the theme background
214
- for contrasting text. Use outline and ghost buttons for secondary actions.
217
+ Use outline and ghost buttons for secondary actions.