@altertable/data-app 0.72.0 → 0.74.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 (112) hide show
  1. package/AGENTS.md +5 -61
  2. package/CONTRIBUTING.md +130 -181
  3. package/README.md +3 -4
  4. package/REFERENCE.md +35 -345
  5. package/dist/chunks/contract-BeLPJwlO.js +558 -0
  6. package/dist/chunks/contract-BeLPJwlO.js.map +1 -0
  7. package/dist/chunks/contract-Di8SP74I.js +462 -0
  8. package/dist/chunks/contract-Di8SP74I.js.map +1 -0
  9. package/dist/chunks/diagnostics-BTZSlNtW.js +967 -0
  10. package/dist/chunks/diagnostics-BTZSlNtW.js.map +1 -0
  11. package/dist/chunks/format-BdFlv_xa.js +148 -0
  12. package/dist/chunks/format-BdFlv_xa.js.map +1 -0
  13. package/dist/chunks/operation-CSM9UmO3.js +134 -0
  14. package/dist/chunks/operation-CSM9UmO3.js.map +1 -0
  15. package/dist/chunks/request-body-H1qPmmTN.js +50 -0
  16. package/dist/chunks/request-body-H1qPmmTN.js.map +1 -0
  17. package/dist/client/index.js +273 -285
  18. package/dist/client/index.js.map +1 -13
  19. package/dist/core/appearance.js +171 -162
  20. package/dist/core/appearance.js.map +1 -10
  21. package/dist/core/config.js +49 -11
  22. package/dist/core/config.js.map +1 -9
  23. package/dist/core/contract.js +3 -73
  24. package/dist/core/format.js +1 -26
  25. package/dist/index.js +1 -12
  26. package/dist/internal.js +352 -397
  27. package/dist/internal.js.map +1 -15
  28. package/dist/server/index.js +85 -97
  29. package/dist/server/index.js.map +1 -10
  30. package/dist/types/chunks/appearance.d.ts +45 -0
  31. package/dist/types/chunks/contract.d.ts +720 -0
  32. package/dist/types/chunks/index.d.ts +240 -0
  33. package/dist/types/client/index.d.ts +3 -13
  34. package/dist/types/core/appearance.d.ts +2 -42
  35. package/dist/types/core/config.d.ts +36 -39
  36. package/dist/types/core/contract.d.ts +2 -114
  37. package/dist/types/core/format.d.ts +44 -17
  38. package/dist/types/index.d.ts +3 -3
  39. package/dist/types/internal.d.ts +312 -22
  40. package/dist/types/server/index.d.ts +15 -4
  41. package/docs/app-authoring.md +77 -128
  42. package/docs/client.md +29 -63
  43. package/docs/composition.md +44 -75
  44. package/docs/contract.md +60 -100
  45. package/docs/data-context.md +35 -61
  46. package/docs/diagnostics.md +45 -0
  47. package/docs/embed.md +86 -55
  48. package/docs/formatting-and-appearance.md +17 -38
  49. package/docs/hosted-apps.md +7 -14
  50. package/docs/layout.md +30 -47
  51. package/docs/local-data-apps.md +7 -7
  52. package/docs/react-embed.md +20 -26
  53. package/docs/react.md +10 -27
  54. package/docs/server-bun.md +2 -27
  55. package/docs/server.md +6 -12
  56. package/docs/stories-and-export.md +38 -40
  57. package/docs/styling.md +14 -22
  58. package/docs/ui-quality.md +5 -5
  59. package/docs/ui.md +93 -70
  60. package/docs/variables.md +142 -254
  61. package/docs/views.md +85 -116
  62. package/docs/widgets.md +100 -153
  63. package/docs/worker.md +15 -27
  64. package/package.json +3 -2
  65. package/dist/chunks/index-5a27erdg.js +0 -54
  66. package/dist/chunks/index-5a27erdg.js.map +0 -10
  67. package/dist/chunks/index-9yxr7nmm.js +0 -742
  68. package/dist/chunks/index-9yxr7nmm.js.map +0 -17
  69. package/dist/chunks/index-j5q5n3ra.js +0 -151
  70. package/dist/chunks/index-j5q5n3ra.js.map +0 -10
  71. package/dist/chunks/index-q75zm3a7.js +0 -153
  72. package/dist/chunks/index-q75zm3a7.js.map +0 -11
  73. package/dist/chunks/index-vhaec7m5.js +0 -30
  74. package/dist/chunks/index-vhaec7m5.js.map +0 -10
  75. package/dist/chunks/index-zp78caex.js +0 -1047
  76. package/dist/chunks/index-zp78caex.js.map +0 -19
  77. package/dist/core/contract.js.map +0 -9
  78. package/dist/core/format.js.map +0 -9
  79. package/dist/index.js.map +0 -9
  80. package/dist/types/client/annotations.d.ts +0 -27
  81. package/dist/types/client/data-client.d.ts +0 -43
  82. package/dist/types/client/download.d.ts +0 -5
  83. package/dist/types/client/iframe.d.ts +0 -59
  84. package/dist/types/client/location.d.ts +0 -13
  85. package/dist/types/client/logger.d.ts +0 -14
  86. package/dist/types/client/messages.d.ts +0 -7
  87. package/dist/types/client/navigation.d.ts +0 -15
  88. package/dist/types/client/transport.d.ts +0 -15
  89. package/dist/types/core/annotations.d.ts +0 -99
  90. package/dist/types/core/bridge-endpoint.d.ts +0 -21
  91. package/dist/types/core/bridge.d.ts +0 -172
  92. package/dist/types/core/data-view.d.ts +0 -46
  93. package/dist/types/core/date-format.d.ts +0 -24
  94. package/dist/types/core/date-range.d.ts +0 -20
  95. package/dist/types/core/dimension-source.d.ts +0 -64
  96. package/dist/types/core/dimension.d.ts +0 -71
  97. package/dist/types/core/facets.d.ts +0 -13
  98. package/dist/types/core/filters.d.ts +0 -45
  99. package/dist/types/core/invariant.d.ts +0 -2
  100. package/dist/types/core/keys.d.ts +0 -2
  101. package/dist/types/core/logger.d.ts +0 -12
  102. package/dist/types/core/messages.d.ts +0 -62
  103. package/dist/types/core/navigation.d.ts +0 -11
  104. package/dist/types/core/operation-types.d.ts +0 -80
  105. package/dist/types/core/operation.d.ts +0 -20
  106. package/dist/types/core/presentation.d.ts +0 -9
  107. package/dist/types/core/queries.d.ts +0 -84
  108. package/dist/types/core/reading.d.ts +0 -17
  109. package/dist/types/core/uuid.d.ts +0 -2
  110. package/dist/types/core/variables.d.ts +0 -133
  111. package/dist/types/server/handler.d.ts +0 -13
  112. package/dist/types/server/request-body.d.ts +0 -4
@@ -0,0 +1,967 @@
1
+ import { f as defineDataQueryRoute, h as sqlQueryRoute, l as MessageRoutingError, s as isAnnotationPresentation } from "./contract-Di8SP74I.js";
2
+ //#region src/core/uuid.ts
3
+ /** Opaque documents can lack randomUUID even when cryptographic randomness is available. */
4
+ function randomUuid() {
5
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
6
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
7
+ bytes[6] = bytes[6] & 15 | 64;
8
+ bytes[8] = bytes[8] & 63 | 128;
9
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
10
+ return [
11
+ hex.slice(0, 4),
12
+ hex.slice(4, 6),
13
+ hex.slice(6, 8),
14
+ hex.slice(8, 10),
15
+ hex.slice(10)
16
+ ].map((part) => part.join("")).join("-");
17
+ }
18
+ //#endregion
19
+ //#region src/core/diagnostics.ts
20
+ /** Omit query values, URL parameters and common credential forms from error text. */
21
+ function diagnosticText(value, limit = 800) {
22
+ const text = value.replace(/https?:\/\/[^\s)]+/g, (url) => {
23
+ try {
24
+ const parsed = new URL(url);
25
+ return `${parsed.origin}${parsed.pathname}`;
26
+ } catch {
27
+ return "[url]";
28
+ }
29
+ }).replace(/\b((?:set-cookie|cookie|(?:x-)?api[-_]?key)\s*[:=]\s*)[^\r\n]*/gi, "$1[redacted]").replace(/\b((?:proxy-)?authorization\s*[:=]\s*)(?:(?:bearer|basic)\s+)?(?:"[^"\n]*"|'[^'\n]*'|[^\s,;]+)/gi, "$1[redacted]").replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, "[email]").replace(/\b(bearer\s+|(?:password|token|secret)\s*[:=]\s*)(?:"[^"\n]*"|'[^'\n]*'|[^\s,;]+)/gi, "$1[redacted]").replace(/\b[\w.-]+\s*=\s*[^\s,;]+/g, "[parameter]").replace(/(['"`])[^\n]*?\1/g, "[value]");
30
+ return text.length > limit ? `${text.slice(0, limit)}… [truncated]` : text;
31
+ }
32
+ function appFailure(kind, name, error) {
33
+ const source = error instanceof Error ? sourceLocation(error.stack) : void 0;
34
+ return {
35
+ kind,
36
+ name: diagnosticText(name, 120),
37
+ message: diagnosticText(error instanceof Error ? error.message : "Unknown failure"),
38
+ ...source ? { source } : {}
39
+ };
40
+ }
41
+ const MAX_STACK_LENGTH = 16384;
42
+ /** Extract one location, excluding stack text, URL parameters and local directory paths. */
43
+ function sourceLocation(stack) {
44
+ const frames = stack?.slice(0, MAX_STACK_LENGTH).split("\n").slice(1) ?? [];
45
+ if (stack && stack.length > MAX_STACK_LENGTH) frames.pop();
46
+ for (const frame of frames) for (const token of frame.split(/[\s()]+/)) {
47
+ const columnSeparator = token.lastIndexOf(":");
48
+ const lineSeparator = token.lastIndexOf(":", columnSeparator - 1);
49
+ if (lineSeparator < 1 || columnSeparator <= lineSeparator) continue;
50
+ const lineText = token.slice(lineSeparator + 1, columnSeparator);
51
+ const columnText = token.slice(columnSeparator + 1);
52
+ if (!/^\d+$/.test(lineText) || !/^\d+$/.test(columnText)) continue;
53
+ const line = Number(lineText);
54
+ const column = Number(columnText);
55
+ if (!Number.isSafeInteger(line) || line < 1 || !Number.isSafeInteger(column) || column < 1) continue;
56
+ return {
57
+ file: diagnosticText(token.slice(0, lineSeparator).split(/[/\\]/).at(-1), 200),
58
+ line,
59
+ column
60
+ };
61
+ }
62
+ }
63
+ function parseSource(value) {
64
+ if (!value || typeof value !== "object") throw new Error("Invalid source location");
65
+ const source = value;
66
+ if (typeof source.file !== "string" || !Number.isSafeInteger(source.line) || source.line < 1 || !Number.isSafeInteger(source.column) || source.column < 1) throw new Error("Invalid source location");
67
+ return {
68
+ file: diagnosticText(source.file.split(/[?#]/, 1)[0].split(/[/\\]/).at(-1), 200),
69
+ line: source.line,
70
+ column: source.column
71
+ };
72
+ }
73
+ /** Validate and project iframe reports. Unknown fields (including query inputs) never cross this boundary. */
74
+ function parseAppDiagnosticReport(value) {
75
+ if (!value || typeof value !== "object") throw new Error("Invalid diagnostic report");
76
+ const report = value;
77
+ if (!Array.isArray(report.failures) || report.failures.length > 30 || !Number.isSafeInteger(report.pending) || report.pending < 0 || !Number.isSafeInteger(report.truncated) || report.truncated < 0) throw new Error("Invalid diagnostic report");
78
+ return {
79
+ failures: report.failures.map((failure) => {
80
+ if (!failure || ![
81
+ "query",
82
+ "operation",
83
+ "render"
84
+ ].includes(failure.kind) || typeof failure.name !== "string" || typeof failure.message !== "string") throw new Error("Invalid diagnostic failure");
85
+ return {
86
+ kind: failure.kind,
87
+ ...typeof failure.id === "string" ? { id: diagnosticText(failure.id, 120) } : {},
88
+ name: diagnosticText(failure.name, 120),
89
+ message: diagnosticText(failure.message),
90
+ ...failure.source ? { source: parseSource(failure.source) } : {}
91
+ };
92
+ }),
93
+ pending: report.pending,
94
+ truncated: report.truncated
95
+ };
96
+ }
97
+ //#endregion
98
+ //#region src/core/logger.ts
99
+ function isLogEntry(value) {
100
+ if (!value || typeof value !== "object") return false;
101
+ const entry = value;
102
+ return (entry.method === "log" || entry.method === "info" || entry.method === "warn" || entry.method === "error") && Array.isArray(entry.args) && entry.args.length <= 128;
103
+ }
104
+ //#endregion
105
+ //#region src/core/bridge.ts
106
+ /** Data app delivery protocol. IDs identify a document, a shell session, and an individual call. */
107
+ const BRIDGE = "altertable:data-app";
108
+ const PARENT_PARAM = "__altertable_parent";
109
+ /** Bound pending requests in the client and host independently.
110
+ * The host enforces its own limit because frames can send messages directly. */
111
+ const MAX_PENDING = 128;
112
+ const REQUEST_TIMEOUT_MS = 6e4;
113
+ function validId(value) {
114
+ return typeof value === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(value);
115
+ }
116
+ function event({ wire, from, session, parse }) {
117
+ return {
118
+ wire,
119
+ from,
120
+ session,
121
+ parse
122
+ };
123
+ }
124
+ function id(fields) {
125
+ if (!validId(fields.id)) throw new Error("Invalid request ID.");
126
+ return fields.id;
127
+ }
128
+ function string(fields, key) {
129
+ const value = fields[key];
130
+ if (typeof value !== "string") throw new Error(`Invalid ${key}.`);
131
+ return value;
132
+ }
133
+ function length(fields, key) {
134
+ const value = fields[key];
135
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error(`Invalid ${key}.`);
136
+ return value;
137
+ }
138
+ function empty() {
139
+ return {};
140
+ }
141
+ /** Parsers project known fields; opaque values are validated by their owning route or adapter. */
142
+ const bridgeProtocol = {
143
+ channel: BRIDGE,
144
+ version: 1,
145
+ events: {
146
+ connect: event({
147
+ wire: "bridge:connect",
148
+ from: "host",
149
+ session: "none",
150
+ parse: empty
151
+ }),
152
+ ready: event({
153
+ wire: "bridge:ready",
154
+ from: "app",
155
+ session: "none",
156
+ parse: empty
157
+ }),
158
+ initialize: event({
159
+ wire: "bridge:initialize",
160
+ from: "host",
161
+ session: "establish",
162
+ parse: (fields) => ({ state: fields.state })
163
+ }),
164
+ request: event({
165
+ wire: "bridge:request",
166
+ from: "app",
167
+ session: "current",
168
+ parse: (fields) => {
169
+ const route = string(fields, "route");
170
+ if (!route || route.length > 256) throw new Error("Invalid message route.");
171
+ return {
172
+ id: id(fields),
173
+ route,
174
+ payload: fields.payload
175
+ };
176
+ }
177
+ }),
178
+ result: event({
179
+ wire: "bridge:result",
180
+ from: "host",
181
+ session: "current",
182
+ parse: (fields) => {
183
+ if (!Object.hasOwn(fields, "response")) throw new Error("Missing response.");
184
+ return {
185
+ id: id(fields),
186
+ response: fields.response
187
+ };
188
+ }
189
+ }),
190
+ error: event({
191
+ wire: "bridge:error",
192
+ from: "host",
193
+ session: "current",
194
+ parse: (fields) => {
195
+ if (fields.requestId !== void 0 && typeof fields.requestId !== "string") throw new Error("Invalid requestId.");
196
+ return {
197
+ id: id(fields),
198
+ code: string(fields, "code"),
199
+ message: string(fields, "message"),
200
+ ...fields.requestId === void 0 ? {} : { requestId: fields.requestId }
201
+ };
202
+ }
203
+ }),
204
+ cancel: event({
205
+ wire: "bridge:cancel",
206
+ from: "app",
207
+ session: "current",
208
+ parse: (fields) => ({ id: id(fields) })
209
+ }),
210
+ disconnect: event({
211
+ wire: "bridge:disconnect",
212
+ from: "app",
213
+ session: "current",
214
+ parse: empty
215
+ }),
216
+ scriptLoad: event({
217
+ wire: "script:load",
218
+ from: "host",
219
+ session: "current",
220
+ parse: (fields) => ({ javascript: string(fields, "javascript") })
221
+ }),
222
+ stateUpdate: event({
223
+ wire: "state:update",
224
+ from: "host",
225
+ session: "current",
226
+ parse: (fields) => ({ state: fields.state })
227
+ }),
228
+ runtimeLog: event({
229
+ wire: "runtime:log",
230
+ from: "app",
231
+ session: "current",
232
+ parse: (fields) => {
233
+ if (!isLogEntry(fields.payload)) throw new Error("Invalid log entry.");
234
+ return { payload: fields.payload };
235
+ }
236
+ }),
237
+ runtimeReady: event({
238
+ wire: "runtime:ready",
239
+ from: "app",
240
+ session: "current",
241
+ parse: empty
242
+ }),
243
+ runtimeError: event({
244
+ wire: "runtime:error",
245
+ from: "app",
246
+ session: "current",
247
+ parse: empty
248
+ }),
249
+ /** Content height in CSS pixels; hosts apply it only to content-sized frames. */
250
+ runtimeResize: event({
251
+ wire: "runtime:resize",
252
+ from: "app",
253
+ session: "current",
254
+ parse: (fields) => ({ height: length(fields, "height") })
255
+ }),
256
+ /** CSS pixels of a content-sized frame hidden above and below the parent's visible area. */
257
+ viewportUpdate: event({
258
+ wire: "viewport:update",
259
+ from: "host",
260
+ session: "current",
261
+ parse: (fields) => ({
262
+ top: length(fields, "top"),
263
+ bottom: length(fields, "bottom")
264
+ })
265
+ })
266
+ }
267
+ };
268
+ function bridgeMessageMetadata(message) {
269
+ const metadata = { type: message.type };
270
+ if ("id" in message) metadata.id = message.id;
271
+ if (message.type === "bridge:request") {
272
+ metadata.route = message.route;
273
+ const payload = message.payload;
274
+ if (message.route === "data:query" && payload && typeof payload === "object" && "operation" in payload && typeof payload.operation === "string") metadata.operation = payload.operation.slice(0, 256);
275
+ }
276
+ if (message.type === "bridge:error") metadata.error = {
277
+ code: message.code,
278
+ message: message.message,
279
+ ...message.requestId === void 0 ? {} : { requestId: message.requestId }
280
+ };
281
+ return metadata;
282
+ }
283
+ const byWire = /* @__PURE__ */ new Map();
284
+ for (const name of Object.keys(bridgeProtocol.events)) {
285
+ const wire = bridgeProtocol.events[name].wire;
286
+ if (byWire.has(wire)) throw new Error(`Duplicate bridge event: ${wire}`);
287
+ byWire.set(wire, name);
288
+ }
289
+ function bridgeEventName(wire) {
290
+ return byWire.get(wire);
291
+ }
292
+ /** Envelope parsing precedes authentication; event-specific fields remain untrusted. */
293
+ function parseBridgeEnvelope(value) {
294
+ if (!value || typeof value !== "object") return;
295
+ const fields = value;
296
+ if (fields.channel !== BRIDGE || fields.version !== bridgeProtocol.version || typeof fields.type !== "string" || typeof fields.documentId !== "string" || !fields.documentId || fields.documentId.length > 128 || fields.sessionId !== void 0 && !validId(fields.sessionId) || fields.token !== void 0 && typeof fields.token !== "string") return;
297
+ return fields;
298
+ }
299
+ /** Project event fields after the caller has checked envelope eligibility. */
300
+ function parseBridgePayload(envelope, definition) {
301
+ try {
302
+ return {
303
+ channel: BRIDGE,
304
+ version: bridgeProtocol.version,
305
+ documentId: envelope.documentId,
306
+ ...envelope.sessionId === void 0 ? {} : { sessionId: envelope.sessionId },
307
+ ...envelope.token === void 0 ? {} : { token: envelope.token },
308
+ type: definition.wire,
309
+ ...definition.parse(envelope)
310
+ };
311
+ } catch {
312
+ return;
313
+ }
314
+ }
315
+ function parseBridgeMessage(value) {
316
+ const envelope = parseBridgeEnvelope(value);
317
+ if (!envelope) return;
318
+ const name = bridgeEventName(envelope.type);
319
+ if (!name) return;
320
+ const definition = bridgeProtocol.events[name];
321
+ if (definition.session !== "none" && envelope.sessionId === void 0) return;
322
+ return parseBridgePayload(envelope, definition);
323
+ }
324
+ //#endregion
325
+ //#region src/core/bridge-endpoint.ts
326
+ /** The connection owns IDs and token rotation; callers can only supply event payloads. */
327
+ function createBridgeEndpoint({ role, origin, source, opaque, context, post, diagnostic, invalidRequest, handlers }) {
328
+ let disposed = false;
329
+ function drop(reason, type) {
330
+ diagnostic?.({
331
+ direction: "drop",
332
+ reason,
333
+ ...typeof type === "string" ? { type: type.slice(0, 64) } : {}
334
+ });
335
+ }
336
+ function send(name, payload) {
337
+ if (disposed) throw new Error("The bridge endpoint has closed.");
338
+ const definition = bridgeProtocol.events[name];
339
+ const current = context();
340
+ const message = parseBridgeMessage({
341
+ ...payload,
342
+ channel: bridgeProtocol.channel,
343
+ version: bridgeProtocol.version,
344
+ type: definition.wire,
345
+ documentId: name === "connect" ? "host" : current.documentId,
346
+ sessionId: current.sessionId,
347
+ token: opaque ? current.token : void 0
348
+ });
349
+ if (!message || opaque && !validId(current.token)) throw new Error("The bridge is not ready to send this event.");
350
+ diagnostic?.({
351
+ direction: "send",
352
+ ...bridgeMessageMetadata(message)
353
+ });
354
+ if (disposed) return;
355
+ post(message);
356
+ }
357
+ function receive(event) {
358
+ const peer = source();
359
+ if (disposed || !peer || event.origin !== origin || event.source !== peer) return;
360
+ const envelope = parseBridgeEnvelope(event.data);
361
+ if (!envelope) {
362
+ const data = event.data;
363
+ if (data && typeof data === "object" && "channel" in data && data.channel === bridgeProtocol.channel) drop("invalid_envelope", "type" in data ? data.type : void 0);
364
+ return;
365
+ }
366
+ const current = context();
367
+ const connecting = role === "app" && envelope.type === bridgeProtocol.events.connect.wire;
368
+ if (opaque && (connecting ? !validId(envelope.token) : !current.token || envelope.token !== current.token)) return drop("token_mismatch", envelope.type);
369
+ const name = bridgeEventName(envelope.type);
370
+ if (!name) return drop("unexpected_type", envelope.type);
371
+ const definition = bridgeProtocol.events[name];
372
+ if (definition.from === role) return drop("unexpected_type", envelope.type);
373
+ if (definition.session === "establish") {
374
+ if (envelope.documentId !== current.documentId || envelope.sessionId === void 0) return drop("session_mismatch", envelope.type);
375
+ } else if (definition.session === "current") {
376
+ if (!current.sessionId || envelope.sessionId !== current.sessionId || envelope.documentId !== current.documentId) return drop("session_mismatch", envelope.type);
377
+ }
378
+ const message = parseBridgePayload(envelope, definition);
379
+ if (!message) {
380
+ drop("invalid_payload", envelope.type);
381
+ if (role === "host" && name === "request" && validId(envelope.id)) invalidRequest?.(envelope.id);
382
+ return;
383
+ }
384
+ diagnostic?.({
385
+ direction: "receive",
386
+ ...bridgeMessageMetadata(message)
387
+ });
388
+ if (disposed) return;
389
+ const handler = handlers[name];
390
+ handler(message);
391
+ }
392
+ return {
393
+ send,
394
+ receive,
395
+ dispose() {
396
+ disposed = true;
397
+ }
398
+ };
399
+ }
400
+ //#endregion
401
+ //#region src/core/presentation.ts
402
+ function isDataAppPresentation(value) {
403
+ if (!value || typeof value !== "object") return false;
404
+ const presentation = value;
405
+ return (presentation.surface === "embedded" || presentation.surface === "standalone") && (presentation.theme === "light" || presentation.theme === "dark") && (presentation.annotations === void 0 || isAnnotationPresentation(presentation.annotations)) && (presentation.sizing === void 0 || presentation.sizing === "frame" || presentation.sizing === "content");
406
+ }
407
+ //#endregion
408
+ //#region src/client/frame-sizing.ts
409
+ /** Reports the document height to a parent that sizes the iframe to its content.
410
+ * Sizing applies only while the parent requests it and a UI owner whose styles support it
411
+ * has opted in, so older app styles under a newer bootstrap stay frame-sized.
412
+ * The root attribute and inset properties let fixed overlays stay within the parent's visible area. */
413
+ function createFrameSizing(document, report) {
414
+ const root = document.documentElement;
415
+ const frame = document.defaultView;
416
+ let observer;
417
+ let reported;
418
+ let requested = false;
419
+ let owners = 0;
420
+ let viewport;
421
+ function measure() {
422
+ const height = Math.ceil(root.getBoundingClientRect().height);
423
+ if (height === reported && height !== frame?.innerHeight) return;
424
+ reported = height;
425
+ report(height);
426
+ }
427
+ function stop() {
428
+ observer?.disconnect();
429
+ observer = void 0;
430
+ frame?.removeEventListener("resize", measure);
431
+ reported = void 0;
432
+ delete root.dataset.atblFrameSizing;
433
+ root.style.removeProperty("--atbl-frame-inset-top");
434
+ root.style.removeProperty("--atbl-frame-inset-bottom");
435
+ }
436
+ function applyViewport() {
437
+ if (!observer || !viewport) return;
438
+ root.style.setProperty("--atbl-frame-inset-top", `${viewport.top}px`);
439
+ root.style.setProperty("--atbl-frame-inset-bottom", `${viewport.bottom}px`);
440
+ }
441
+ function sync() {
442
+ if (!requested || !owners) return stop();
443
+ if (observer) return;
444
+ root.dataset.atblFrameSizing = "content";
445
+ observer = new (document.defaultView ?? globalThis).ResizeObserver(measure);
446
+ observer.observe(root);
447
+ frame?.addEventListener("resize", measure);
448
+ applyViewport();
449
+ }
450
+ return {
451
+ /** A new session starts with a parent that has not received the current height. */
452
+ update(state, session) {
453
+ const presentation = state && typeof state === "object" && "presentation" in state ? state.presentation : void 0;
454
+ requested = isDataAppPresentation(presentation) && presentation.sizing === "content";
455
+ if (!requested) viewport = void 0;
456
+ if (session === "new") reported = void 0;
457
+ if (observer && requested) measure();
458
+ sync();
459
+ },
460
+ support() {
461
+ owners++;
462
+ sync();
463
+ let released = false;
464
+ return () => {
465
+ if (released) return;
466
+ released = true;
467
+ owners--;
468
+ sync();
469
+ };
470
+ },
471
+ viewport(top, bottom) {
472
+ if (!requested) return;
473
+ viewport = {
474
+ top,
475
+ bottom
476
+ };
477
+ applyViewport();
478
+ },
479
+ dispose() {
480
+ requested = false;
481
+ viewport = void 0;
482
+ owners = 0;
483
+ stop();
484
+ }
485
+ };
486
+ }
487
+ //#endregion
488
+ //#region src/client/logger.ts
489
+ /** Lazy arguments run in the iframe; only resolved values cross the bridge. */
490
+ function createBridgeLogger(enabled, send) {
491
+ function resolve(args) {
492
+ if (args.length === 1 && typeof args[0] === "function") {
493
+ const value = args[0]();
494
+ return Array.isArray(value) ? value : [value];
495
+ }
496
+ return args.map((arg) => typeof arg === "function" ? arg() : arg);
497
+ }
498
+ function write(method, args) {
499
+ if (!enabled()) return;
500
+ try {
501
+ send({
502
+ method,
503
+ args: resolve(args)
504
+ });
505
+ } catch {}
506
+ }
507
+ return {
508
+ log: (...args) => write("log", args),
509
+ info: (...args) => write("info", args),
510
+ warn: (...args) => write("warn", args),
511
+ error: (...args) => write("error", args)
512
+ };
513
+ }
514
+ const diagnosticLabels = {
515
+ send: "Sending message to parent",
516
+ receive: "Received message from parent",
517
+ drop: "Ignored message from parent"
518
+ };
519
+ /** Log only delivery metadata; payloads and session credentials stay private. */
520
+ function logBridgeDiagnostic(logger, { direction, ...metadata }) {
521
+ if (metadata.type === "runtime:log" || metadata.type === "runtime:resize" || metadata.type === "viewport:update") return;
522
+ logger.log(diagnosticLabels[direction], metadata);
523
+ }
524
+ /** Error instances do not survive every logger, so only their text crosses the bridge. */
525
+ function describeError(error) {
526
+ if (error instanceof Error) return {
527
+ name: error.name,
528
+ message: error.message,
529
+ ...error.stack ? { stack: error.stack } : {}
530
+ };
531
+ return { message: String(error) };
532
+ }
533
+ //#endregion
534
+ //#region src/client/messages.ts
535
+ /** Both ends validate using the same contracts; the transport owns delivery and cancellation. */
536
+ function createMessageClient(routes, transport) {
537
+ return { async request(route, payload, { signal } = {}) {
538
+ signal?.throwIfAborted();
539
+ if (!Object.hasOwn(routes, route)) throw new MessageRoutingError("unknown_route", "Unknown message route.");
540
+ const contract = routes[route];
541
+ let input;
542
+ try {
543
+ input = contract.input(payload);
544
+ } catch {
545
+ throw new MessageRoutingError("invalid_payload", "Invalid message payload.");
546
+ }
547
+ const response = await transport({
548
+ route,
549
+ payload: input
550
+ }, signal);
551
+ signal?.throwIfAborted();
552
+ try {
553
+ return contract.output(response, input);
554
+ } catch (error) {
555
+ if (error instanceof MessageRoutingError) throw error;
556
+ throw new MessageRoutingError("invalid_response", "Invalid message response.");
557
+ }
558
+ } };
559
+ }
560
+ //#endregion
561
+ //#region src/client/transport.ts
562
+ const errorBrand = Symbol.for("@altertable/data-app/DataAppError");
563
+ var DataAppError = class extends Error {
564
+ code;
565
+ requestId;
566
+ [errorBrand] = true;
567
+ static [Symbol.hasInstance](value) {
568
+ return value instanceof Error && value[errorBrand] === true;
569
+ }
570
+ constructor(message, code, requestId) {
571
+ super(message);
572
+ this.code = code;
573
+ this.requestId = requestId;
574
+ this.name = "DataAppError";
575
+ }
576
+ };
577
+ function createHttpTransport({ endpoint = "/api/data", fetch: request = globalThis.fetch } = {}) {
578
+ async function requestData(operation, input, signal) {
579
+ const response = await request(`${endpoint.replace(/\/$/, "")}/${encodeURIComponent(operation)}`, {
580
+ method: "POST",
581
+ headers: { "content-type": "application/json" },
582
+ body: JSON.stringify(input),
583
+ signal
584
+ });
585
+ try {
586
+ return {
587
+ status: response.status,
588
+ body: await response.json()
589
+ };
590
+ } catch (error) {
591
+ if (signal?.aborted) throw error;
592
+ throw new DataAppError(response.ok ? "The data response was invalid." : "Could not load data.", response.ok ? "invalid_response" : "request_failed");
593
+ }
594
+ }
595
+ return requestData;
596
+ }
597
+ //#endregion
598
+ //#region src/client/iframe.ts
599
+ /** Data clients expose one error type for HTTP and message delivery. */
600
+ function rethrowDataMessageError(error) {
601
+ if (error instanceof MessageRoutingError) throw new DataAppError(error.message, error.code, error.requestId);
602
+ throw error;
603
+ }
604
+ /** One bridge per document, shared by all clients and retained across module hot replacement. */
605
+ function createIframeTransport({ parentOrigin, window: frame = window, timeoutMs = REQUEST_TIMEOUT_MS, mode = "url", loadScript }) {
606
+ if (new URL(parentOrigin).origin !== parentOrigin) throw new Error("Expected an exact parent origin.");
607
+ const documentId = randomUuid();
608
+ let token;
609
+ let sessionId;
610
+ let disposed = false;
611
+ const pending = /* @__PURE__ */ new Map();
612
+ let hostState;
613
+ let diagnosticsWaiting = false;
614
+ let diagnosticTimer;
615
+ const unsubscribeDiagnostics = appDiagnostics.subscribe(scheduleDiagnostics);
616
+ function scheduleDiagnostics() {
617
+ clearTimeout(diagnosticTimer);
618
+ diagnosticTimer = setTimeout(() => {
619
+ if (!hostState || typeof hostState !== "object" || !("repair" in hostState) || typeof hostState.repair !== "string") return;
620
+ if (pending.size >= 128) {
621
+ diagnosticsWaiting = true;
622
+ return;
623
+ }
624
+ diagnosticsWaiting = false;
625
+ if (!disposed && sessionId) requestMessage({
626
+ route: "diagnostics:report",
627
+ payload: appDiagnostics.snapshot()
628
+ }).catch(() => {});
629
+ }, 150);
630
+ }
631
+ const stateListeners = /* @__PURE__ */ new Set();
632
+ const logger = createBridgeLogger(() => !disposed && !!sessionId && !!hostState && typeof hostState === "object" && "logging" in hostState && hostState.logging === true, (entry) => send("runtimeLog", { payload: entry }));
633
+ const endpoint = createBridgeEndpoint({
634
+ role: "app",
635
+ origin: parentOrigin,
636
+ source: () => frame.parent,
637
+ opaque: mode === "bundle",
638
+ context: () => ({
639
+ documentId,
640
+ sessionId,
641
+ token
642
+ }),
643
+ post(message) {
644
+ frame.parent.postMessage(message, parentOrigin);
645
+ },
646
+ diagnostic: (event) => logBridgeDiagnostic(logger, event),
647
+ handlers: {
648
+ connect(message) {
649
+ if (mode === "bundle") token = message.token;
650
+ send("ready", {});
651
+ },
652
+ initialize(message) {
653
+ if (sessionId && sessionId !== message.sessionId) {
654
+ if (pending.size) logger.warn("Preview reconnected; rejecting pending requests", { count: pending.size });
655
+ for (const entry of pending.values()) entry.reject(new DataAppError("The preview reconnected. Retry the request.", "bridge_reset"));
656
+ }
657
+ const first = !sessionId;
658
+ sessionId = message.sessionId;
659
+ receiveState(message.state, "new");
660
+ if (first) for (const entry of pending.values()) entry.start();
661
+ if (disposed) return;
662
+ if (mode === "url") send("runtimeReady", {});
663
+ },
664
+ stateUpdate(message) {
665
+ receiveState(message.state, "current");
666
+ },
667
+ viewportUpdate(message) {
668
+ frameSizing.viewport(message.top, message.bottom);
669
+ },
670
+ scriptLoad(message) {
671
+ if (mode === "bundle") loadScript?.(message.javascript);
672
+ },
673
+ result(message) {
674
+ pending.get(message.id)?.resolve(message.response);
675
+ },
676
+ error(message) {
677
+ pending.get(message.id)?.reject(new MessageRoutingError(message.code, message.message, message.requestId));
678
+ }
679
+ }
680
+ });
681
+ const send = endpoint.send;
682
+ const receive = endpoint.receive;
683
+ const frameSizing = createFrameSizing(frame.document, (height) => {
684
+ if (!disposed && sessionId) send("runtimeResize", { height });
685
+ });
686
+ function receiveState(state, session) {
687
+ if (session === "new") scheduleDiagnostics();
688
+ hostState = state;
689
+ frameSizing.update(state, session);
690
+ for (const listener of stateListeners) listener(state);
691
+ }
692
+ frame.addEventListener("message", receive);
693
+ function requestMessage(message, signal) {
694
+ return new Promise((resolve, reject) => {
695
+ if (disposed) return reject(new DataAppError("The preview has closed.", "bridge_closed"));
696
+ if (signal?.aborted) return reject(signal.reason);
697
+ if (pending.size >= 128) return reject(new DataAppError("Too many pending data requests.", "bridge_busy"));
698
+ const id = randomUuid();
699
+ let sent = false;
700
+ function cleanup() {
701
+ clearTimeout(timer);
702
+ signal?.removeEventListener("abort", abort);
703
+ pending.delete(id);
704
+ if (diagnosticsWaiting) scheduleDiagnostics();
705
+ }
706
+ function abort() {
707
+ if (sent) send("cancel", { id });
708
+ cleanup();
709
+ reject(signal?.reason);
710
+ }
711
+ const timer = setTimeout(() => {
712
+ logger.warn("Message request timed out", {
713
+ id,
714
+ route: message.route,
715
+ timeoutMs,
716
+ sent
717
+ });
718
+ if (sent) send("cancel", { id });
719
+ cleanup();
720
+ reject(new DataAppError(sessionId ? "The data request timed out." : "The preview shell is unavailable. Reload the preview.", sessionId ? "timeout" : "bridge_unavailable"));
721
+ }, timeoutMs);
722
+ const entry = {
723
+ start() {
724
+ if (sent) return;
725
+ try {
726
+ send("request", {
727
+ id,
728
+ route: message.route,
729
+ payload: message.payload
730
+ });
731
+ sent = true;
732
+ } catch {
733
+ cleanup();
734
+ reject(new DataAppError("The message payload could not be sent.", "invalid_payload"));
735
+ }
736
+ },
737
+ resolve(value) {
738
+ cleanup();
739
+ resolve(value);
740
+ },
741
+ reject(error) {
742
+ cleanup();
743
+ reject(error);
744
+ }
745
+ };
746
+ pending.set(id, entry);
747
+ signal?.addEventListener("abort", abort, { once: true });
748
+ if (sessionId) entry.start();
749
+ else if (mode === "url" || token) send("ready", {});
750
+ });
751
+ }
752
+ const messages = createMessageClient({
753
+ "data:query": defineDataQueryRoute(),
754
+ "data:sql": sqlQueryRoute
755
+ }, requestMessage);
756
+ function queryOperation(operation, input, signal) {
757
+ return messages.request("data:query", {
758
+ operation,
759
+ input
760
+ }, { signal }).catch(rethrowDataMessageError);
761
+ }
762
+ function disconnect() {
763
+ if (sessionId) send("disconnect", {});
764
+ sessionId = void 0;
765
+ for (const entry of pending.values()) entry.reject(new DataAppError("The preview has closed.", "bridge_closed"));
766
+ }
767
+ function resume(event) {
768
+ if (event.persisted && (mode === "url" || token)) send("ready", {});
769
+ }
770
+ function dispose() {
771
+ if (disposed) return;
772
+ disconnect();
773
+ disposed = true;
774
+ clearTimeout(diagnosticTimer);
775
+ unsubscribeDiagnostics();
776
+ endpoint.dispose();
777
+ frameSizing.dispose();
778
+ frame.removeEventListener("message", receive);
779
+ frame.removeEventListener("pagehide", disconnect);
780
+ frame.removeEventListener("pageshow", resume);
781
+ stateListeners.clear();
782
+ }
783
+ frame.addEventListener("pagehide", disconnect);
784
+ frame.addEventListener("pageshow", resume);
785
+ if (mode === "url") send("ready", {});
786
+ return {
787
+ diagnostics: appDiagnostics,
788
+ logger,
789
+ request: requestMessage,
790
+ transport: queryOperation,
791
+ lakehouse: { queryAll(statement, { limit, signal, params }) {
792
+ return messages.request("data:sql", {
793
+ statement,
794
+ limit,
795
+ ...params === void 0 ? {} : { params }
796
+ }, { signal }).catch(rethrowDataMessageError);
797
+ } },
798
+ dispose,
799
+ mode,
800
+ snapshot() {
801
+ return hostState;
802
+ },
803
+ subscribe(listener) {
804
+ stateListeners.add(listener);
805
+ return () => {
806
+ stateListeners.delete(listener);
807
+ };
808
+ },
809
+ ready() {
810
+ if (!disposed && sessionId) send("runtimeReady", {});
811
+ },
812
+ /** The UI owner calls this once its styles support content sizing; the parent's
813
+ * `sizing: 'content'` presentation then applies until the returned release runs. */
814
+ supportContentSizing() {
815
+ return frameSizing.support();
816
+ },
817
+ /** Reports a fatal app failure; the cause reaches the host logger only. */
818
+ fail(cause) {
819
+ if (disposed || !sessionId) return;
820
+ appDiagnostics.record("render", "App startup", cause);
821
+ if (cause !== void 0) logger.error(() => ["Data app failed", describeError(cause)]);
822
+ send("runtimeError", {});
823
+ }
824
+ };
825
+ }
826
+ const bridgeKey = Symbol.for("altertable.localFrameBridge");
827
+ const installedKey = Symbol.for("altertable.installedTransport");
828
+ /** The URL opts into local preview; only same-origin server configuration establishes trust. */
829
+ function localFrameBridge(window) {
830
+ const activeWindow = window ?? (typeof globalThis.window === "undefined" ? void 0 : globalThis.window);
831
+ if (!activeWindow) return void 0;
832
+ const frame = activeWindow;
833
+ if (frame[bridgeKey]) return frame[bridgeKey];
834
+ const parentOrigin = new URL(frame.location.href).searchParams.get("__altertable_parent") ?? "";
835
+ if (!parentOrigin) return void 0;
836
+ async function connect(parentOrigin) {
837
+ try {
838
+ const response = await frame.fetch("/__altertable/parent", { signal: AbortSignal.timeout(5e3) });
839
+ const config = await response.json();
840
+ if (!response.ok || config.origin !== parentOrigin || frame.parent === frame) throw new Error("Invalid local parent configuration.");
841
+ if (frame[installedKey]) return frame[installedKey];
842
+ if (frame[bridgeKey] !== proxy) throw new Error("Preview transport owner changed.");
843
+ const bridge = createIframeTransport({
844
+ parentOrigin,
845
+ window: frame
846
+ });
847
+ frame[bridgeKey] = bridge;
848
+ frame[installedKey] = bridge;
849
+ return bridge;
850
+ } catch {
851
+ throw new DataAppError("The preview shell could not be verified. Open the URL printed by altertable app dev.", "bridge_unavailable");
852
+ }
853
+ }
854
+ let connection;
855
+ function getConnection() {
856
+ const installed = frame[installedKey];
857
+ if (installed) return Promise.resolve(installed);
858
+ if (!connection) {
859
+ const attempt = connect(parentOrigin);
860
+ connection = attempt;
861
+ attempt.catch(() => {
862
+ if (connection === attempt) connection = void 0;
863
+ });
864
+ }
865
+ return connection;
866
+ }
867
+ const proxy = {
868
+ async transport(operation, input, signal) {
869
+ signal?.throwIfAborted();
870
+ const attempt = getConnection();
871
+ let abort;
872
+ try {
873
+ const bridge = signal ? await Promise.race([attempt, new Promise((_, reject) => {
874
+ const requestSignal = signal;
875
+ function handleAbort() {
876
+ reject(requestSignal.reason);
877
+ }
878
+ abort = handleAbort;
879
+ requestSignal.addEventListener("abort", handleAbort, { once: true });
880
+ })]) : await attempt;
881
+ signal?.throwIfAborted();
882
+ return bridge.transport(operation, input, signal);
883
+ } finally {
884
+ if (abort) signal?.removeEventListener("abort", abort);
885
+ }
886
+ },
887
+ connect: getConnection
888
+ };
889
+ frame[bridgeKey] = proxy;
890
+ getConnection().catch(() => {});
891
+ return proxy;
892
+ }
893
+ /** Install an explicitly trusted transport for hosted apps and their URL-backed controls. */
894
+ function installDataAppTransport(bridge, frame = window) {
895
+ const target = frame;
896
+ if (target[installedKey]) throw new Error("A data app transport is already installed.");
897
+ target[bridgeKey] = bridge;
898
+ target[installedKey] = bridge;
899
+ return () => {
900
+ if (target[bridgeKey] === bridge) delete target[bridgeKey];
901
+ if (target[installedKey] === bridge) delete target[installedKey];
902
+ bridge.dispose();
903
+ };
904
+ }
905
+ /** The bootstrap installs this before executing app code. URL apps can install an explicit connection. */
906
+ function getDataAppTransport(frame = window) {
907
+ return frame[installedKey];
908
+ }
909
+ //#endregion
910
+ //#region src/client/diagnostics.ts
911
+ const listeners = /* @__PURE__ */ new Set();
912
+ const failures = /* @__PURE__ */ new Map();
913
+ let pending = 0;
914
+ function publish() {
915
+ for (const listener of listeners) listener();
916
+ }
917
+ function installed() {
918
+ const diagnostics = typeof window === "undefined" ? void 0 : getDataAppTransport()?.diagnostics;
919
+ return diagnostics !== appDiagnostics ? diagnostics : void 0;
920
+ }
921
+ const appDiagnostics = {
922
+ snapshot() {
923
+ if (installed()) return installed().snapshot();
924
+ const observed = [];
925
+ for (const failure of failures.values()) {
926
+ observed.push(failure);
927
+ if (observed.length === 30) break;
928
+ }
929
+ return {
930
+ failures: observed,
931
+ pending,
932
+ truncated: Math.max(0, failures.size - 30)
933
+ };
934
+ },
935
+ subscribe(listener) {
936
+ if (installed()) return installed().subscribe(listener);
937
+ listeners.add(listener);
938
+ return () => {
939
+ listeners.delete(listener);
940
+ };
941
+ },
942
+ record(kind, name, error, identity) {
943
+ if (installed()) return installed().record(kind, name, error, identity);
944
+ const failure = appFailure(kind, name, error);
945
+ if (identity) failure.id = identity;
946
+ const key = `${kind}:${identity ?? name}`;
947
+ failures.set(key, failure);
948
+ publish();
949
+ },
950
+ clear(kind, name, identity) {
951
+ if (installed()) return installed().clear(kind, name, identity);
952
+ if (failures.delete(`${kind}:${identity ?? name}`)) publish();
953
+ },
954
+ begin() {
955
+ if (installed()) return installed().begin();
956
+ pending++;
957
+ publish();
958
+ return () => {
959
+ pending--;
960
+ publish();
961
+ };
962
+ }
963
+ };
964
+ //#endregion
965
+ export { localFrameBridge as a, createMessageClient as c, MAX_PENDING as d, PARENT_PARAM as f, randomUuid as g, parseAppDiagnosticReport as h, installDataAppTransport as i, isDataAppPresentation as l, validId as m, createIframeTransport as n, DataAppError as o, REQUEST_TIMEOUT_MS as p, getDataAppTransport as r, createHttpTransport as s, appDiagnostics as t, createBridgeEndpoint as u };
966
+
967
+ //# sourceMappingURL=diagnostics-BTZSlNtW.js.map