@altertable/data-app 0.78.0 → 0.79.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.
@@ -1,6 +1,6 @@
1
1
  import { l as invariant } from "./date-time-range-value-D-XfqVTT.js";
2
- import { M as facetSource, R as combineOperationFilters, X as withDimensionSelectors, t as DataSourceError, v as registeredQueryRoute } from "./contract-gu1rDsV0.js";
3
- import { _ as toDataOperationFailure, g as executeDataOperation, h as randomUuid, o as DataAppError, r as getDataAppTransport, t as appDiagnostics } from "./diagnostics-CX9SsU79.js";
2
+ import { M as facetSource, R as combineOperationFilters, X as withDimensionSelectors, t as DataSourceError, v as registeredQueryRoute } from "./contract-BTG-BUwW.js";
3
+ import { _ as toDataOperationFailure, g as executeDataOperation, h as randomUuid, o as DataAppError, r as getDataAppTransport, t as appDiagnostics } from "./diagnostics-BwpM9wGn.js";
4
4
  //#region src/client/local-query.ts
5
5
  const localQueryKey = Symbol.for("altertable.localQueryLakehouse");
6
6
  /** Send registered query IDs to the local Bun server; SQL never crosses this request. */
@@ -119,4 +119,4 @@ function createOperationClient(options) {
119
119
  //#endregion
120
120
  export { createLocalQueryLakehouse as n, installLocalQueryLakehouse as r, createDataClient as t };
121
121
 
122
- //# sourceMappingURL=data-client-BMdL73Ab.js.map
122
+ //# sourceMappingURL=data-client-C4Pay-UE.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"data-client-BMdL73Ab.js","names":[],"sources":["../../src/client/local-query.ts","../../src/client/data-client.ts"],"sourcesContent":["import { DataSourceError } from '../core/contract.ts';\nimport { registeredQueryRoute } from '../core/messages.ts';\nimport type { HostedLakehouse } from '../core/operation-types.ts';\n\nconst localQueryKey = Symbol.for('altertable.localQueryLakehouse');\ntype LocalQueryWindow = Window & { [localQueryKey]?: HostedLakehouse };\n\n/** Send registered query IDs to the local Bun server; SQL never crosses this request. */\nexport function createLocalQueryLakehouse(\n endpoint = '/api/query',\n request: typeof fetch = fetch\n): HostedLakehouse {\n return {\n async queryAllById(queryId, { limit, params, signal }) {\n const input = registeredQueryRoute.input({ queryId, limit, params });\n const response = await request(\n `${endpoint.replace(/\\/$/, '')}/${encodeURIComponent(queryId)}`,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ limit, params }),\n signal,\n }\n );\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new Error('Invalid local query response.');\n }\n if (!response.ok) {\n const reason = (body as { reason?: unknown } | null)?.reason;\n if (\n reason === 'unauthorized' ||\n reason === 'forbidden' ||\n reason === 'rate_limited' ||\n reason === 'query_rejected' ||\n reason === 'unavailable'\n )\n throw new DataSourceError(reason, response.status);\n throw new Error('Local query failed.');\n }\n return registeredQueryRoute.output(body, input);\n },\n };\n}\n\n/** Install the local query adapter before mounting an app with browser-run operations. */\nexport function installLocalQueryLakehouse(\n frame: Window = window,\n lakehouse: HostedLakehouse = createLocalQueryLakehouse()\n) {\n const target = frame as LocalQueryWindow;\n if (target[localQueryKey])\n throw new Error('A local query lakehouse is already installed.');\n target[localQueryKey] = lakehouse;\n return () => {\n if (target[localQueryKey] === lakehouse) delete target[localQueryKey];\n };\n}\n\nexport function getLocalQueryLakehouse(frame: Window = window) {\n return (frame as LocalQueryWindow)[localQueryKey];\n}\n","import type { FilterCollection } from '../core/app-filters.ts';\nimport type { DataOperations, Lakehouse } from '../core/contract.ts';\nimport { withDimensionSelectors } from '../core/dimension-source.ts';\nimport type { DimensionOption } from '../core/dimension.ts';\nimport { facetSource, type FacetFilter } from '../core/facets.ts';\nimport { invariant } from '../core/invariant.ts';\nimport { combineOperationFilters } from '../core/operation-filters.ts';\nimport type {\n DataQueryBody,\n InputOf,\n OutputOf,\n} from '../core/operation-types.ts';\nimport {\n executeDataOperation,\n toDataOperationFailure,\n} from '../core/operation.ts';\nimport type { IsUnion, KnownRecord } from '../core/queries.ts';\nimport { randomUuid } from '../core/uuid.ts';\nimport { appDiagnostics } from './diagnostics.ts';\nimport { getDataAppTransport } from './iframe.ts';\nimport { getLocalQueryLakehouse } from './local-query.ts';\nimport { DataAppError } from './transport.ts';\nexport type { InputOf, OutputOf } from '../core/operation-types.ts';\n\n/**\n * Parsed operation data and query evidence.\n */\nexport type DataResponse<Output, Input = unknown> = DataQueryBody<Output> & {\n /** The exact browser input that produced this response. */\n input: Input;\n};\n\n/** The filters each operation reads, for operations that read any. */\nexport type OperationFilters<Operations extends DataOperations> = {\n readonly [\n Name in keyof Operations as Operations[Name] extends {\n filters: infer Filters extends FilterCollection;\n }\n ? keyof Filters extends never\n ? never\n : Name\n : never\n ]: Operations[Name] extends { filters: infer Filters } ? Filters : never;\n};\n\ndeclare const clientContract: unique symbol;\nexport type DataClient<Operations extends DataOperations> = {\n /** Preserve the operation registry when passing clients through helpers. */\n readonly [clientContract]: (operations: Operations) => Operations;\n /** Each operation's filters; views derive their inputs and controls from them. */\n readonly filters: Readonly<Record<string, FilterCollection>>;\n query<Name extends keyof Operations & string>(\n this: void,\n name: Name & (true extends IsUnion<NoInfer<Name>> ? never : unknown),\n input: InputOf<Operations[NoInfer<Name>]>,\n options?: { signal?: AbortSignal }\n ): Promise<\n DataResponse<OutputOf<Operations[Name]>, InputOf<Operations[Name]>>\n >;\n};\n\n/** The factory is the only place that grants a client its invariant contract witness. */\nfunction typedClient<Operations extends DataOperations>(\n implementation: Pick<DataClient<Operations>, 'query' | 'filters'>\n): DataClient<Operations> {\n combineOperationFilters(implementation.filters);\n const query = implementation.query;\n implementation.query = async (name, input, options) => {\n const end = appDiagnostics.begin();\n try {\n const result = await query(name, input, options);\n appDiagnostics.clear('operation', name);\n return result;\n } catch (error) {\n if (!options?.signal?.aborted)\n appDiagnostics.record(\n 'operation',\n name,\n error instanceof Error && error.cause instanceof Error\n ? error.cause\n : error\n );\n throw error;\n } finally {\n end();\n }\n };\n return implementation as DataClient<Operations>;\n}\n\n/** Distribute over conditional filter members so each possible facet is checked. */\ntype UncheckedFacet<Operations extends DataOperations, Filter, Key> =\n Filter extends FacetFilter<infer Value, infer Source>\n ? Source extends keyof Operations\n ? OutputOf<Operations[Source]> extends readonly DimensionOption<Value>[]\n ? never\n : Key\n : Key\n : never;\n\n/** The filter names whose facet options are missing or mistyped. Only known names:\n * a typed contract may widen `filters` with an index signature. */\ntype UncheckedFacetNames<Operations extends DataOperations, Filters> = {\n [Key in keyof Filters as string extends Key ? never : Key]: UncheckedFacet<\n Operations,\n Filters[Key],\n Key\n >;\n} extends infer Checked\n ? Checked[keyof Checked]\n : never;\n\n/** Every facet filter loads its options from a registered operation returning them. */\ntype CheckedFacets<Operations extends DataOperations> = {\n [Name in keyof Operations]: Operations[Name] extends {\n filters: infer Filters;\n }\n ? UncheckedFacetNames<Operations, Filters>\n : never;\n}[keyof Operations] extends never\n ? unknown\n : {\n 'Facet filter options must name a registered operation returning DimensionOption[]': never;\n };\n/** Execute declared operations in the browser against registered query IDs. */\nexport type DataClientOptions<Operations extends DataOperations> =\n (KnownRecord<Operations> extends never\n ? never\n : true extends {\n [Name in keyof Operations]: IsUnion<Operations[Name]>;\n }[keyof Operations]\n ? never\n : unknown) & {\n operations: Operations;\n lakehouse?: Lakehouse;\n } & CheckedFacets<Operations>;\n\n/** Create a browser operation client. */\nexport function createDataClient<Operations extends DataOperations>(\n options: DataClientOptions<Operations>\n): DataClient<Operations> {\n return createOperationClient({\n operations: withDimensionSelectors(options.operations),\n lakehouse: options.lakehouse,\n });\n}\n\nfunction createOperationClient<Operations extends DataOperations>(options: {\n operations: Operations;\n lakehouse?: Lakehouse;\n}): DataClient<Operations> {\n const operations = Object.freeze({ ...options.operations });\n const filters: Record<string, FilterCollection> = {};\n for (const [name, operation] of Object.entries(operations))\n if (operation.filters && Object.keys(operation.filters).length)\n filters[name] = operation.filters;\n for (const operationFilters of Object.values(filters))\n for (const filter of Object.values(operationFilters)) {\n const facet = (filter as Partial<FacetFilter>)[facetSource];\n if (facet)\n invariant(\n Object.hasOwn(operations, facet.operation),\n `Facet filter ${filter.label} loads options from an unregistered operation: ${facet.operation}.`\n );\n }\n return typedClient<Operations>({\n filters: Object.freeze(filters),\n async query(name, input, { signal } = {}) {\n signal?.throwIfAborted();\n const requestId = randomUuid();\n if (!Object.hasOwn(operations, name))\n throw new DataAppError(\n 'Unknown data operation.',\n 'not_found',\n requestId\n );\n const lakehouse =\n options.lakehouse ??\n (typeof window === 'undefined'\n ? undefined\n : (getDataAppTransport()?.lakehouse ?? getLocalQueryLakehouse()));\n if (!lakehouse)\n throw new DataAppError(\n 'An authorized data bridge must be installed first.',\n 'bridge_unavailable',\n requestId\n );\n\n try {\n const { body } = await executeDataOperation(operations[name]!, input, {\n lakehouse,\n signal: signal ?? new AbortController().signal,\n requestId,\n operationName: name,\n onQuery(queryName, error) {\n if (error === undefined)\n appDiagnostics.clear('query', `${name}: ${queryName}`);\n else appDiagnostics.record('query', `${name}: ${queryName}`, error);\n },\n });\n\n return { ...body, input } as DataResponse<\n OutputOf<Operations[typeof name]>,\n InputOf<Operations[typeof name]>\n >;\n } catch (error) {\n if (signal?.aborted) throw signal.reason;\n if (error instanceof DataAppError) throw error;\n const failure = toDataOperationFailure(error);\n const publicError = new DataAppError(\n failure.message,\n failure.code,\n requestId\n );\n publicError.cause = error;\n throw publicError;\n }\n },\n });\n}\n"],"mappings":";;;;AAIA,MAAM,gBAAgB,OAAO,IAAI,gCAAgC;;AAIjE,SAAgB,0BACd,WAAW,cACX,UAAwB,OACP;CACjB,OAAO,EACL,MAAM,aAAa,SAAS,EAAE,OAAO,QAAQ,UAAU;EACrD,MAAM,QAAQ,qBAAqB,MAAM;GAAE;GAAS;GAAO;EAAO,CAAC;EACnE,MAAM,WAAW,MAAM,QACrB,GAAG,SAAS,QAAQ,OAAO,EAAE,EAAE,GAAG,mBAAmB,OAAO,KAC5D;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;GAC9C,MAAM,KAAK,UAAU;IAAE;IAAO;GAAO,CAAC;GACtC;EACF,CACF;EACA,IAAI;EACJ,IAAI;GACF,OAAO,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AAU,uBAAuB,KAAK;IAC5C,MAAM,cAAc,IAAI,aACtB,QAAQ,SACR,QAAQ,MACR,SACF;IACA,YAAY,QAAQ;IACpB,MAAM;GACR;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"data-client-C4Pay-UE.js","names":[],"sources":["../../src/client/local-query.ts","../../src/client/data-client.ts"],"sourcesContent":["import { DataSourceError } from '../core/contract.ts';\nimport { registeredQueryRoute } from '../core/messages.ts';\nimport type { HostedLakehouse } from '../core/operation-types.ts';\n\nconst localQueryKey = Symbol.for('altertable.localQueryLakehouse');\ntype LocalQueryWindow = Window & { [localQueryKey]?: HostedLakehouse };\n\n/** Send registered query IDs to the local Bun server; SQL never crosses this request. */\nexport function createLocalQueryLakehouse(\n endpoint = '/api/query',\n request: typeof fetch = fetch\n): HostedLakehouse {\n return {\n async queryAllById(queryId, { limit, params, signal }) {\n const input = registeredQueryRoute.input({ queryId, limit, params });\n const response = await request(\n `${endpoint.replace(/\\/$/, '')}/${encodeURIComponent(queryId)}`,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ limit, params }),\n signal,\n }\n );\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new Error('Invalid local query response.');\n }\n if (!response.ok) {\n const reason = (body as { reason?: unknown } | null)?.reason;\n if (\n reason === 'unauthorized' ||\n reason === 'forbidden' ||\n reason === 'rate_limited' ||\n reason === 'query_rejected' ||\n reason === 'unavailable'\n )\n throw new DataSourceError(reason, response.status);\n throw new Error('Local query failed.');\n }\n return registeredQueryRoute.output(body, input);\n },\n };\n}\n\n/** Install the local query adapter before mounting an app with browser-run operations. */\nexport function installLocalQueryLakehouse(\n frame: Window = window,\n lakehouse: HostedLakehouse = createLocalQueryLakehouse()\n) {\n const target = frame as LocalQueryWindow;\n if (target[localQueryKey])\n throw new Error('A local query lakehouse is already installed.');\n target[localQueryKey] = lakehouse;\n return () => {\n if (target[localQueryKey] === lakehouse) delete target[localQueryKey];\n };\n}\n\nexport function getLocalQueryLakehouse(frame: Window = window) {\n return (frame as LocalQueryWindow)[localQueryKey];\n}\n","import type { FilterCollection } from '../core/app-filters.ts';\nimport type { DataOperations, Lakehouse } from '../core/contract.ts';\nimport { withDimensionSelectors } from '../core/dimension-source.ts';\nimport type { DimensionOption } from '../core/dimension.ts';\nimport { facetSource, type FacetFilter } from '../core/facets.ts';\nimport { invariant } from '../core/invariant.ts';\nimport { combineOperationFilters } from '../core/operation-filters.ts';\nimport type {\n DataQueryBody,\n InputOf,\n OutputOf,\n} from '../core/operation-types.ts';\nimport {\n executeDataOperation,\n toDataOperationFailure,\n} from '../core/operation.ts';\nimport type { IsUnion, KnownRecord } from '../core/queries.ts';\nimport { randomUuid } from '../core/uuid.ts';\nimport { appDiagnostics } from './diagnostics.ts';\nimport { getDataAppTransport } from './iframe.ts';\nimport { getLocalQueryLakehouse } from './local-query.ts';\nimport { DataAppError } from './transport.ts';\nexport type { InputOf, OutputOf } from '../core/operation-types.ts';\n\n/**\n * Parsed operation data and query evidence.\n */\nexport type DataResponse<Output, Input = unknown> = DataQueryBody<Output> & {\n /** The exact browser input that produced this response. */\n input: Input;\n};\n\n/** The filters each operation reads, for operations that read any. */\nexport type OperationFilters<Operations extends DataOperations> = {\n readonly [\n Name in keyof Operations as Operations[Name] extends {\n filters: infer Filters extends FilterCollection;\n }\n ? keyof Filters extends never\n ? never\n : Name\n : never\n ]: Operations[Name] extends { filters: infer Filters } ? Filters : never;\n};\n\ndeclare const clientContract: unique symbol;\nexport type DataClient<Operations extends DataOperations> = {\n /** Preserve the operation registry when passing clients through helpers. */\n readonly [clientContract]: (operations: Operations) => Operations;\n /** Each operation's filters; views derive their inputs and controls from them. */\n readonly filters: Readonly<Record<string, FilterCollection>>;\n query<Name extends keyof Operations & string>(\n this: void,\n name: Name & (true extends IsUnion<NoInfer<Name>> ? never : unknown),\n input: InputOf<Operations[NoInfer<Name>]>,\n options?: { signal?: AbortSignal }\n ): Promise<\n DataResponse<OutputOf<Operations[Name]>, InputOf<Operations[Name]>>\n >;\n};\n\n/** The factory is the only place that grants a client its invariant contract witness. */\nfunction typedClient<Operations extends DataOperations>(\n implementation: Pick<DataClient<Operations>, 'query' | 'filters'>\n): DataClient<Operations> {\n combineOperationFilters(implementation.filters);\n const query = implementation.query;\n implementation.query = async (name, input, options) => {\n const end = appDiagnostics.begin();\n try {\n const result = await query(name, input, options);\n appDiagnostics.clear('operation', name);\n return result;\n } catch (error) {\n if (!options?.signal?.aborted)\n appDiagnostics.record(\n 'operation',\n name,\n error instanceof Error && error.cause instanceof Error\n ? error.cause\n : error\n );\n throw error;\n } finally {\n end();\n }\n };\n return implementation as DataClient<Operations>;\n}\n\n/** Distribute over conditional filter members so each possible facet is checked. */\ntype UncheckedFacet<Operations extends DataOperations, Filter, Key> =\n Filter extends FacetFilter<infer Value, infer Source>\n ? Source extends keyof Operations\n ? OutputOf<Operations[Source]> extends readonly DimensionOption<Value>[]\n ? never\n : Key\n : Key\n : never;\n\n/** The filter names whose facet options are missing or mistyped. Only known names:\n * a typed contract may widen `filters` with an index signature. */\ntype UncheckedFacetNames<Operations extends DataOperations, Filters> = {\n [Key in keyof Filters as string extends Key ? never : Key]: UncheckedFacet<\n Operations,\n Filters[Key],\n Key\n >;\n} extends infer Checked\n ? Checked[keyof Checked]\n : never;\n\n/** Every facet filter loads its options from a registered operation returning them. */\ntype CheckedFacets<Operations extends DataOperations> = {\n [Name in keyof Operations]: Operations[Name] extends {\n filters: infer Filters;\n }\n ? UncheckedFacetNames<Operations, Filters>\n : never;\n}[keyof Operations] extends never\n ? unknown\n : {\n 'Facet filter options must name a registered operation returning DimensionOption[]': never;\n };\n/** Execute declared operations in the browser against registered query IDs. */\nexport type DataClientOptions<Operations extends DataOperations> =\n (KnownRecord<Operations> extends never\n ? never\n : true extends {\n [Name in keyof Operations]: IsUnion<Operations[Name]>;\n }[keyof Operations]\n ? never\n : unknown) & {\n operations: Operations;\n lakehouse?: Lakehouse;\n } & CheckedFacets<Operations>;\n\n/** Create a browser operation client. */\nexport function createDataClient<Operations extends DataOperations>(\n options: DataClientOptions<Operations>\n): DataClient<Operations> {\n return createOperationClient({\n operations: withDimensionSelectors(options.operations),\n lakehouse: options.lakehouse,\n });\n}\n\nfunction createOperationClient<Operations extends DataOperations>(options: {\n operations: Operations;\n lakehouse?: Lakehouse;\n}): DataClient<Operations> {\n const operations = Object.freeze({ ...options.operations });\n const filters: Record<string, FilterCollection> = {};\n for (const [name, operation] of Object.entries(operations))\n if (operation.filters && Object.keys(operation.filters).length)\n filters[name] = operation.filters;\n for (const operationFilters of Object.values(filters))\n for (const filter of Object.values(operationFilters)) {\n const facet = (filter as Partial<FacetFilter>)[facetSource];\n if (facet)\n invariant(\n Object.hasOwn(operations, facet.operation),\n `Facet filter ${filter.label} loads options from an unregistered operation: ${facet.operation}.`\n );\n }\n return typedClient<Operations>({\n filters: Object.freeze(filters),\n async query(name, input, { signal } = {}) {\n signal?.throwIfAborted();\n const requestId = randomUuid();\n if (!Object.hasOwn(operations, name))\n throw new DataAppError(\n 'Unknown data operation.',\n 'not_found',\n requestId\n );\n const lakehouse =\n options.lakehouse ??\n (typeof window === 'undefined'\n ? undefined\n : (getDataAppTransport()?.lakehouse ?? getLocalQueryLakehouse()));\n if (!lakehouse)\n throw new DataAppError(\n 'An authorized data bridge must be installed first.',\n 'bridge_unavailable',\n requestId\n );\n\n try {\n const { body } = await executeDataOperation(operations[name]!, input, {\n lakehouse,\n signal: signal ?? new AbortController().signal,\n requestId,\n operationName: name,\n onQuery(queryName, error) {\n if (error === undefined)\n appDiagnostics.clear('query', `${name}: ${queryName}`);\n else appDiagnostics.record('query', `${name}: ${queryName}`, error);\n },\n });\n\n return { ...body, input } as DataResponse<\n OutputOf<Operations[typeof name]>,\n InputOf<Operations[typeof name]>\n >;\n } catch (error) {\n if (signal?.aborted) throw signal.reason;\n if (error instanceof DataAppError) throw error;\n const failure = toDataOperationFailure(error);\n const publicError = new DataAppError(\n failure.message,\n failure.code,\n requestId\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uBAAuB;GAClE,IAAI,CAAC,WACH,MAAM,IAAI,aACR,sDACA,sBACA,SACF;GAEF,IAAI;IACF,MAAM,EAAE,SAAS,MAAM,qBAAqB,WAAW,OAAQ,OAAO;KACpE;KACA,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;KACxC;KACA,eAAe;KACf,QAAQ,WAAW,OAAO;MACxB,IAAI,UAAU,KAAA,GACZ,eAAe,MAAM,SAAS,GAAG,KAAK,IAAI,WAAW;WAClD,eAAe,OAAO,SAAS,GAAG,KAAK,IAAI,aAAa,KAAK;KACpE;IACF,CAAC;IAED,OAAO;KAAE,GAAG;KAAM;IAAM;GAI1B,SAAS,OAAO;IACd,IAAI,QAAQ,SAAS,MAAM,OAAO;IAClC,IAAI,iBAAiB,cAAc,MAAM;IACzC,MAAM,UAAU,uBAAuB,KAAK;IAC5C,MAAM,cAAc,IAAI,aACtB,QAAQ,SACR,QAAQ,MACR,SACF;IACA,YAAY,QAAQ;IACpB,MAAM;GACR;EACF;CACF,CAAC;AACH"}
@@ -1,4 +1,4 @@
1
- import { f as MessageRoutingError, q as DimensionMembershipError, t as DataSourceError, u as isAnnotationPresentation, v as registeredQueryRoute } from "./contract-gu1rDsV0.js";
1
+ import { f as MessageRoutingError, q as DimensionMembershipError, t as DataSourceError, u as isAnnotationPresentation, v as registeredQueryRoute } from "./contract-BTG-BUwW.js";
2
2
  import { t as isRecord } from "./record-Cr4Uk1K3.js";
3
3
  //#region src/core/operation.ts
4
4
  /** Shared operation execution. Adapters own authorization, delivery, and public errors. */
@@ -1141,4 +1141,4 @@ const appDiagnostics = {
1141
1141
  //#endregion
1142
1142
  export { toDataOperationFailure as _, localFrameBridge as a, isDataAppPresentation as c, PARENT_PARAM as d, REQUEST_TIMEOUT_MS as f, executeDataOperation as g, randomUuid as h, installDataAppTransport as i, createBridgeEndpoint as l, parseAppDiagnosticReport as m, createIframeTransport as n, DataAppError as o, validId as p, getDataAppTransport as r, createMessageClient as s, appDiagnostics as t, MAX_PENDING as u };
1143
1143
 
1144
- //# sourceMappingURL=diagnostics-CX9SsU79.js.map
1144
+ //# sourceMappingURL=diagnostics-BwpM9wGn.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics-CX9SsU79.js","names":[],"sources":["../../src/core/operation.ts","../../src/core/uuid.ts","../../src/core/diagnostics.ts","../../src/core/actions.ts","../../src/core/logger.ts","../../src/core/bridge.ts","../../src/core/bridge-endpoint.ts","../../src/core/presentation.ts","../../src/client/frame-sizing.ts","../../src/client/logger.ts","../../src/client/messages.ts","../../src/client/transport.ts","../../src/client/iframe.ts","../../src/client/diagnostics.ts"],"sourcesContent":["import { DataSourceError } from './contract.ts';\nimport { DimensionMembershipError } from './dimension-source.ts';\nimport type {\n DataOperations,\n DisclosedQuery,\n Lakehouse,\n SqlLakehouse,\n OperationContext,\n DataQueryBody,\n} from './operation-types.ts';\n\ntype Operation = DataOperations[string];\ntype OperationExecutionOptions = {\n operationName: string;\n lakehouse: Lakehouse;\n signal: AbortSignal;\n requestId: string;\n queryParams?: OperationContext['queryParams'];\n onQuery?: (name: string, error?: unknown) => void;\n};\n\n/** Shared operation execution. Adapters own authorization, delivery, and public errors. */\nexport async function executeDataOperation(\n operation: Operation,\n value: unknown,\n {\n operationName,\n lakehouse,\n signal: requestSignal,\n requestId,\n queryParams,\n onQuery,\n }: OperationExecutionOptions\n) {\n requestSignal.throwIfAborted();\n let input: unknown;\n try {\n input = operation.input(value);\n } catch {\n throw new OperationInputError();\n }\n\n const signal = AbortSignal.any([\n requestSignal,\n AbortSignal.timeout(operation.policy.maxDurationMs),\n ]);\n const execution = createOperationLakehouse(\n operation,\n lakehouse,\n signal,\n operationName,\n onQuery\n );\n try {\n const output = await runOperation(operation, input, {\n lakehouse: execution.lakehouse,\n signal,\n queryParams,\n });\n const body: DataQueryBody<unknown> = {\n data: output,\n requestId,\n queriedAt: new Date().toISOString(),\n queryIds: execution.queryIds,\n queries: execution.queries,\n };\n const serializedBody = JSON.stringify(body);\n const responseBytes = new TextEncoder().encode(serializedBody).byteLength;\n if (responseBytes > (operation.policy.maxResponseBytes ?? 1_000_000))\n throw new Error('Response exceeds byte limit.');\n\n return { body, serializedBody };\n } catch (error) {\n if (signal.aborted && !(error instanceof DataSourceError))\n throw new OperationTimeoutError();\n throw error;\n }\n}\n\n/** Query evidence follows statement invocation order; query IDs retain completion order. */\nfunction createOperationLakehouse(\n operation: Operation,\n source: Lakehouse,\n signal: AbortSignal,\n operationName: string,\n onQuery?: (name: string, error?: unknown) => void\n) {\n const queryIds: string[] = [];\n const queries: DisclosedQuery[] = [];\n const lakehouse: SqlLakehouse = {\n async queryAll(statement, options) {\n signal.throwIfAborted();\n if (!Number.isInteger(options.limit) || options.limit < 1)\n throw new Error('Query needs a positive row limit.');\n if (\n operation.queryNames &&\n !Object.values(operation.queryNames).includes(options.name ?? '')\n )\n throw new Error(\n `Query name is not registered for operation ${operationName}.`\n );\n const query: DisclosedQuery = {\n name: options.name ?? `Query ${queries.length + 1}`,\n statement,\n ...(options.params === undefined ? {} : { params: options.params }),\n };\n queries.push(query);\n const limit = Math.min(options.limit, operation.policy.maxQueryRows);\n const querySignal = AbortSignal.any([signal, options.signal]);\n let result;\n try {\n const queryOptions = {\n limit,\n ...(options.params === undefined ? {} : { params: options.params }),\n signal: querySignal,\n };\n if ('queryAllById' in source) {\n if (!options.name || !operation.queryNames)\n throw new Error('A registered query name is required.');\n result = await source.queryAllById(options.name, queryOptions);\n } else {\n result = await source.queryAll(statement, {\n ...queryOptions,\n ...(options.name === undefined ? {} : { name: options.name }),\n });\n }\n } catch (error) {\n if (!querySignal.aborted) onQuery?.(query.name, error);\n if (error instanceof DataSourceError) error.queryName = query.name;\n throw error;\n }\n onQuery?.(query.name);\n if (result.rows.length > limit)\n throw new Error('Result exceeds row limit.');\n if (result.queryId) {\n query.queryId = result.queryId;\n queryIds.push(result.queryId);\n }\n\n return result;\n },\n };\n\n return { lakehouse, queries, queryIds };\n}\n\n/** Settle cancellation even when operation code or its lakehouse ignores the signal. */\nasync function runOperation(\n operation: Operation,\n input: unknown,\n { lakehouse, signal, queryParams }: OperationContext\n) {\n let abort: (() => void) | undefined;\n try {\n signal.throwIfAborted();\n const cancelled = new Promise<never>((_, reject) => {\n function rejectAborted() {\n reject(new Error('Request aborted.'));\n }\n abort = rejectAborted;\n signal.addEventListener('abort', rejectAborted, { once: true });\n if (signal.aborted) rejectAborted();\n });\n\n return await Promise.race([\n cancelled,\n Promise.resolve().then(() => {\n signal.throwIfAborted();\n\n return operation.run(\n { lakehouse, signal, queryParams },\n input as never\n );\n }),\n ]);\n } finally {\n if (abort) signal.removeEventListener('abort', abort);\n }\n}\n\nclass OperationTimeoutError extends Error {}\n\nclass OperationInputError extends Error {}\n\nconst sourceErrorMessages = {\n unauthorized:\n 'This app could not authenticate its data connection. Contact the app owner.',\n forbidden:\n 'This app cannot access the requested data. Contact the app owner.',\n rate_limited: 'The lakehouse is busy. Wait a moment and retry.',\n query_rejected:\n \"A lakehouse query was rejected. Check the app's data operation.\",\n unavailable: 'The lakehouse is unavailable. Check the connection and retry.',\n};\n\nexport function toDataOperationFailure(error: unknown, aborted = false) {\n if (\n error instanceof OperationInputError ||\n error instanceof DimensionMembershipError\n )\n return {\n status: 400,\n code: 'invalid_input',\n message: \"Check this operation's inputs.\",\n };\n if (error instanceof DataSourceError)\n return {\n status: error.reason === 'rate_limited' ? 429 : 502,\n code: `source_${error.reason}`,\n message: sourceErrorMessages[error.reason],\n };\n const timedOut = aborted || error instanceof OperationTimeoutError;\n return {\n status: timedOut ? 504 : 502,\n code: timedOut ? 'timeout' : 'query_failed',\n message: timedOut\n ? 'The data request timed out.'\n : 'The data request failed.',\n };\n}\n","/** Opaque documents can lack randomUUID even when cryptographic randomness is available. */\nexport function randomUuid(): string {\n if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 15) | 64;\n bytes[8] = (bytes[8]! & 63) | 128;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10),\n ]\n .map(part => part.join(''))\n .join('-');\n}\n","/** Failures observed during the checks and interactions actually exercised. */\nexport type AppFailure = {\n /** Mounted widget identity when multiple widgets share a label. */\n id?: string;\n kind: 'query' | 'operation' | 'render';\n name: string;\n message: string;\n /** Sanitized filename and one-based line/column. Source contents are never included. */\n source?: { file: string; line: number; column: number };\n};\nexport type AppDiagnosticReport = {\n /** Current observed failures, limited to 30 entries. */\n failures: AppFailure[];\n /** Observed checks that have not finished. */\n pending: number;\n /** Failures omitted from this report's bounded failure list. */\n truncated: number;\n};\n\n/** Omit query values, URL parameters and common credential forms from error text. */\nfunction diagnosticText(value: string, limit = 800) {\n const text = value\n .replace(/https?:\\/\\/[^\\s)]+/g, url => {\n try {\n const parsed = new URL(url);\n return `${parsed.origin}${parsed.pathname}`;\n } catch {\n return '[url]';\n }\n })\n .replace(\n /\\b((?:set-cookie|cookie|(?:x-)?api[-_]?key)\\s*[:=]\\s*)[^\\r\\n]*/gi,\n '$1[redacted]'\n )\n .replace(\n /\\b((?:proxy-)?authorization\\s*[:=]\\s*)(?:(?:bearer|basic)\\s+)?(?:\"[^\"\\n]*\"|'[^'\\n]*'|[^\\s,;]+)/gi,\n '$1[redacted]'\n )\n .replace(/\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi, '[email]')\n .replace(\n /\\b(bearer\\s+|(?:password|token|secret)\\s*[:=]\\s*)(?:\"[^\"\\n]*\"|'[^'\\n]*'|[^\\s,;]+)/gi,\n '$1[redacted]'\n )\n .replace(/\\b[\\w.-]+\\s*=\\s*[^\\s,;]+/g, '[parameter]')\n .replace(/(['\"`])[^\\n]*?\\1/g, '[value]');\n return text.length > limit ? `${text.slice(0, limit)}… [truncated]` : text;\n}\n\nexport function appFailure(\n kind: AppFailure['kind'],\n name: string,\n error: unknown\n): AppFailure {\n const source =\n error instanceof Error ? sourceLocation(error.stack) : undefined;\n\n return {\n kind,\n name: diagnosticText(name, 120),\n message: diagnosticText(\n error instanceof Error ? error.message : 'Unknown failure'\n ),\n ...(source ? { source } : {}),\n };\n}\n\nconst MAX_STACK_LENGTH = 16_384;\n\n/** Extract one location, excluding stack text, URL parameters and local directory paths. */\nfunction sourceLocation(stack?: string): AppFailure['source'] {\n // Inspect a bounded stack prefix; malformed frame tokens must not cause backtracking.\n const frames = stack?.slice(0, MAX_STACK_LENGTH).split('\\n').slice(1) ?? [];\n if (stack && stack.length > MAX_STACK_LENGTH) frames.pop();\n for (const frame of frames) {\n for (const token of frame.split(/[\\s()]+/)) {\n const columnSeparator = token.lastIndexOf(':');\n const lineSeparator = token.lastIndexOf(':', columnSeparator - 1);\n if (lineSeparator < 1 || columnSeparator <= lineSeparator) continue;\n const lineText = token.slice(lineSeparator + 1, columnSeparator);\n const columnText = token.slice(columnSeparator + 1);\n if (!/^\\d+$/.test(lineText) || !/^\\d+$/.test(columnText)) continue;\n const line = Number(lineText);\n const column = Number(columnText);\n if (\n !Number.isSafeInteger(line) ||\n line < 1 ||\n !Number.isSafeInteger(column) ||\n column < 1\n )\n continue;\n const file = token.slice(0, lineSeparator).split(/[/\\\\]/).at(-1)!;\n\n return { file: diagnosticText(file, 200), line, column };\n }\n }\n\n return undefined;\n}\nfunction parseSource(value: unknown): AppFailure['source'] {\n if (!value || typeof value !== 'object')\n throw new Error('Invalid source location');\n const source = value as NonNullable<AppFailure['source']>;\n if (\n typeof source.file !== 'string' ||\n !Number.isSafeInteger(source.line) ||\n source.line < 1 ||\n !Number.isSafeInteger(source.column) ||\n source.column < 1\n )\n throw new Error('Invalid source location');\n return {\n file: diagnosticText(\n source.file.split(/[?#]/, 1)[0]!.split(/[/\\\\]/).at(-1)!,\n 200\n ),\n line: source.line,\n column: source.column,\n };\n}\n\n/** Validate and project iframe reports. Unknown fields (including query inputs) never cross this boundary. */\nexport function parseAppDiagnosticReport(value: unknown): AppDiagnosticReport {\n if (!value || typeof value !== 'object')\n throw new Error('Invalid diagnostic report');\n const report = value as AppDiagnosticReport;\n if (\n !Array.isArray(report.failures) ||\n report.failures.length > 30 ||\n !Number.isSafeInteger(report.pending) ||\n report.pending < 0 ||\n !Number.isSafeInteger(report.truncated) ||\n report.truncated < 0\n )\n throw new Error('Invalid diagnostic report');\n return {\n failures: report.failures.map(failure => {\n if (\n !failure ||\n !['query', 'operation', 'render'].includes(failure.kind) ||\n typeof failure.name !== 'string' ||\n typeof failure.message !== 'string'\n )\n throw new Error('Invalid diagnostic failure');\n return {\n kind: failure.kind,\n ...(typeof failure.id === 'string'\n ? { id: diagnosticText(failure.id, 120) }\n : {}),\n name: diagnosticText(failure.name, 120),\n message: diagnosticText(failure.message),\n ...(failure.source ? { source: parseSource(failure.source) } : {}),\n };\n }),\n pending: report.pending,\n truncated: report.truncated,\n };\n}\n","import { isRecord } from './record.ts';\n\n/** Page actions an embedded app offers its host, replaced as a whole on every change.\n * An absent key means the app does not offer that action. */\nexport type DataAppActions = {\n /** Run `refresh`; while `refreshing`, run `cancelRefresh` if `cancellable`. */\n refresh?: { refreshing: boolean; cancellable: boolean };\n /** Run `exportCsv`. `tables` names the datasets an action's `table` may select. */\n exportCsv?: { enabled: boolean; tables: readonly string[] };\n /** Run `presentStory`; while `presenting`, run `closeStory`. */\n presentStory?: { enabled: boolean; presenting: boolean };\n /** Run `aboutData` to open the data inspector. */\n aboutData?: { enabled: boolean };\n};\n\n/** A host request to run an offered page action. The app ignores unavailable actions. */\nexport type DataAppAction =\n | { type: 'refresh' }\n | { type: 'cancelRefresh' }\n /** Omit `table` to export every dataset, as a ZIP when there are several. */\n | { type: 'exportCsv'; table?: string }\n | { type: 'presentStory' }\n | { type: 'closeStory' }\n | { type: 'aboutData' };\n\nconst MAX_TABLES = 64;\n\nexport function parseDataAppActions(value: unknown): DataAppActions {\n if (!isRecord(value)) throw new Error('Invalid actions.');\n const actions: DataAppActions = {};\n const { refresh, exportCsv } = value;\n if (refresh !== undefined) {\n if (\n !isRecord(refresh) ||\n typeof refresh.refreshing !== 'boolean' ||\n typeof refresh.cancellable !== 'boolean'\n )\n throw new Error('Invalid refresh action.');\n actions.refresh = {\n refreshing: refresh.refreshing,\n cancellable: refresh.cancellable,\n };\n }\n if (exportCsv !== undefined) {\n if (\n !isRecord(exportCsv) ||\n typeof exportCsv.enabled !== 'boolean' ||\n !Array.isArray(exportCsv.tables) ||\n exportCsv.tables.length > MAX_TABLES ||\n !exportCsv.tables.every(\n table => typeof table === 'string' && table.length <= 256\n )\n )\n throw new Error('Invalid export action.');\n actions.exportCsv = {\n enabled: exportCsv.enabled,\n tables: [...(exportCsv.tables as string[])],\n };\n }\n const { presentStory } = value;\n if (presentStory !== undefined) {\n if (\n !isRecord(presentStory) ||\n typeof presentStory.enabled !== 'boolean' ||\n typeof presentStory.presenting !== 'boolean'\n )\n throw new Error('Invalid story action.');\n actions.presentStory = {\n enabled: presentStory.enabled,\n presenting: presentStory.presenting,\n };\n }\n const { aboutData } = value;\n if (aboutData !== undefined) {\n if (!isRecord(aboutData) || typeof aboutData.enabled !== 'boolean')\n throw new Error('Invalid inspection action.');\n actions.aboutData = { enabled: aboutData.enabled };\n }\n return actions;\n}\n\nexport function parseDataAppAction(value: unknown): DataAppAction {\n if (!isRecord(value)) throw new Error('Invalid action.');\n switch (value.type) {\n case 'refresh':\n case 'cancelRefresh':\n case 'presentStory':\n case 'closeStory':\n case 'aboutData':\n return { type: value.type };\n case 'exportCsv':\n if (value.table !== undefined && typeof value.table !== 'string')\n throw new Error('Invalid export table.');\n return value.table === undefined\n ? { type: 'exportCsv' }\n : { type: 'exportCsv', table: value.table };\n default:\n throw new Error('Unknown action.');\n }\n}\n","/** Host-owned log sink; compatible with console and frontend createLogger(). */\nexport type DataAppLogger = {\n log: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n};\n\nexport type LogEntry = {\n method: keyof DataAppLogger;\n args: unknown[];\n};\n\nexport function isLogEntry(value: unknown): value is LogEntry {\n if (!value || typeof value !== 'object') return false;\n const entry = value as Record<string, unknown>;\n return (\n (entry.method === 'log' ||\n entry.method === 'info' ||\n entry.method === 'warn' ||\n entry.method === 'error') &&\n Array.isArray(entry.args) &&\n entry.args.length <= 128\n );\n}\n","import { parseDataAppAction, parseDataAppActions } from './actions.ts';\nimport { isLogEntry } from './logger.ts';\nimport { isRecord } from './record.ts';\n\n/** Data app delivery protocol. IDs identify a document, a shell session, and an individual call. */\nconst BRIDGE = 'altertable:data-app';\nexport const PARENT_PARAM = '__altertable_parent';\n/** Bound pending requests in the client and host independently.\n * The host enforces its own limit because frames can send messages directly. */\nexport const MAX_PENDING = 128;\nexport const REQUEST_TIMEOUT_MS = 60_000;\nexport { type TransportResponse } from './operation-types.ts';\n\nexport function validId(value: unknown): value is string {\n return typeof value === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(value);\n}\n\ntype Fields = Record<string, unknown>;\nexport type BridgeRole = 'host' | 'app';\ntype SessionRule = 'none' | 'establish' | 'current';\n\nfunction event<\n const Wire extends string,\n const Role extends BridgeRole,\n const Session extends SessionRule,\n Payload,\n>({\n wire,\n from,\n session,\n parse,\n}: {\n wire: Wire;\n from: Role;\n session: Session;\n parse: (fields: Fields) => Payload;\n}) {\n return { wire, from, session, parse };\n}\n\nfunction id(fields: Fields) {\n if (!validId(fields.id)) throw new Error('Invalid request ID.');\n return fields.id;\n}\n\nfunction string(fields: Fields, key: string) {\n const value = fields[key];\n if (typeof value !== 'string') throw new Error(`Invalid ${key}.`);\n return value;\n}\n\nfunction length(fields: Fields, key: string) {\n const value = fields[key];\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)\n throw new Error(`Invalid ${key}.`);\n return value;\n}\n\nfunction empty() {\n return {};\n}\n\n/** Parsers project known fields; opaque values are validated by their owning route or adapter. */\nexport const bridgeProtocol = {\n channel: BRIDGE,\n version: 1,\n events: {\n connect: event({\n wire: 'bridge:connect',\n from: 'host',\n session: 'none',\n parse: empty,\n }),\n ready: event({\n wire: 'bridge:ready',\n from: 'app',\n session: 'none',\n parse: empty,\n }),\n initialize: event({\n wire: 'bridge:initialize',\n from: 'host',\n session: 'establish',\n parse: fields => ({ state: fields.state }),\n }),\n request: event({\n wire: 'bridge:request',\n from: 'app',\n session: 'current',\n parse: fields => {\n const route = string(fields, 'route');\n if (!route || route.length > 256)\n throw new Error('Invalid message route.');\n return { id: id(fields), route, payload: fields.payload };\n },\n }),\n result: event({\n wire: 'bridge:result',\n from: 'host',\n session: 'current',\n parse: fields => {\n if (!Object.hasOwn(fields, 'response'))\n throw new Error('Missing response.');\n return { id: id(fields), response: fields.response };\n },\n }),\n error: event({\n wire: 'bridge:error',\n from: 'host',\n session: 'current',\n parse: fields => {\n if (\n fields.requestId !== undefined &&\n typeof fields.requestId !== 'string'\n )\n throw new Error('Invalid requestId.');\n return {\n id: id(fields),\n code: string(fields, 'code'),\n message: string(fields, 'message'),\n ...(fields.requestId === undefined\n ? {}\n : { requestId: fields.requestId }),\n };\n },\n }),\n cancel: event({\n wire: 'bridge:cancel',\n from: 'app',\n session: 'current',\n parse: fields => ({ id: id(fields) }),\n }),\n disconnect: event({\n wire: 'bridge:disconnect',\n from: 'app',\n session: 'current',\n parse: empty,\n }),\n scriptLoad: event({\n wire: 'script:load',\n from: 'host',\n session: 'current',\n parse: fields => ({ javascript: string(fields, 'javascript') }),\n }),\n stateUpdate: event({\n wire: 'state:update',\n from: 'host',\n session: 'current',\n parse: fields => ({ state: fields.state }),\n }),\n runtimeLog: event({\n wire: 'runtime:log',\n from: 'app',\n session: 'current',\n parse: fields => {\n if (!isLogEntry(fields.payload)) throw new Error('Invalid log entry.');\n return { payload: fields.payload };\n },\n }),\n runtimeReady: event({\n wire: 'runtime:ready',\n from: 'app',\n session: 'current',\n parse: empty,\n }),\n runtimeError: event({\n wire: 'runtime:error',\n from: 'app',\n session: 'current',\n parse: empty,\n }),\n /** Content height in CSS pixels; hosts apply it only to content-sized frames. */\n runtimeResize: event({\n wire: 'runtime:resize',\n from: 'app',\n session: 'current',\n parse: fields => ({ height: length(fields, 'height') }),\n }),\n /** The page actions the app currently offers; replaces the previous set. */\n actionsUpdate: event({\n wire: 'actions:update',\n from: 'app',\n session: 'current',\n parse: fields => ({ actions: parseDataAppActions(fields.actions) }),\n }),\n actionRun: event({\n wire: 'action:run',\n from: 'host',\n session: 'current',\n parse: fields => ({ action: parseDataAppAction(fields.action) }),\n }),\n /** CSS pixels of a content-sized frame hidden above and below the parent's visible area. */\n viewportUpdate: event({\n wire: 'viewport:update',\n from: 'host',\n session: 'current',\n parse: fields => ({\n top: length(fields, 'top'),\n bottom: length(fields, 'bottom'),\n }),\n }),\n },\n} as const;\n\ntype Events = typeof bridgeProtocol.events;\nexport type BridgeEventName = keyof Events;\nexport type BridgePayload<Name extends BridgeEventName> = ReturnType<\n Events[Name]['parse']\n>;\nexport type BridgeEnvelope = {\n channel: typeof BRIDGE;\n version: typeof bridgeProtocol.version;\n documentId: string;\n sessionId?: string;\n token?: string;\n};\nexport type BridgeEventMessage<Name extends BridgeEventName> =\n Name extends BridgeEventName\n ? BridgeEnvelope & {\n type: Events[Name]['wire'];\n } & (Events[Name]['session'] extends 'none'\n ? {}\n : { sessionId: string }) &\n BridgePayload<Name>\n : never;\nexport type BridgeMessage = {\n [Name in BridgeEventName]: BridgeEventMessage<Name>;\n}[BridgeEventName];\nexport type BridgeEventsFrom<Role extends BridgeRole> = {\n [Name in BridgeEventName]: Events[Name]['from'] extends Role ? Name : never;\n}[BridgeEventName];\nexport type BridgeHandlers<Role extends BridgeRole> = {\n [Name in BridgeEventsFrom<Role extends 'host' ? 'app' : 'host'>]: (\n message: BridgeEventMessage<Name>\n ) => void;\n};\n\n/** Delivery metadata safe to log on either side; never payloads or session credentials. */\nexport type BridgeMessageMetadata = {\n type: BridgeMessage['type'];\n id?: string;\n route?: string;\n operation?: string;\n error?: { code: string; message: string; requestId?: string };\n};\n\nexport function bridgeMessageMetadata(\n message: BridgeMessage\n): BridgeMessageMetadata {\n const metadata: BridgeMessageMetadata = { type: message.type };\n if ('id' in message) metadata.id = message.id;\n if (message.type === 'bridge:request') {\n metadata.route = message.route;\n const payload = message.payload;\n if (\n message.route === 'data:query' &&\n isRecord(payload) &&\n typeof payload.operation === 'string'\n )\n metadata.operation = payload.operation.slice(0, 256);\n }\n if (message.type === 'bridge:error')\n metadata.error = {\n code: message.code,\n message: message.message,\n ...(message.requestId === undefined\n ? {}\n : { requestId: message.requestId }),\n };\n return metadata;\n}\n\n/** Why a message from the connected peer was ignored. Messages from other windows are not reported. */\nexport type BridgeDropReason =\n | 'invalid_envelope'\n | 'token_mismatch'\n | 'unexpected_type'\n | 'session_mismatch'\n | 'invalid_payload';\n\nexport type BridgeDiagnostic =\n | ({ direction: 'send' | 'receive' } & BridgeMessageMetadata)\n | { direction: 'drop'; type?: string; reason: BridgeDropReason };\n\nconst byWire = new Map<string, BridgeEventName>();\nfor (const name of Object.keys(bridgeProtocol.events) as BridgeEventName[]) {\n const wire = bridgeProtocol.events[name].wire;\n if (byWire.has(wire)) throw new Error(`Duplicate bridge event: ${wire}`);\n byWire.set(wire, name);\n}\n\nexport function bridgeEventName(wire: string) {\n return byWire.get(wire);\n}\n\n/** Envelope parsing precedes authentication; event-specific fields remain untrusted. */\nexport function parseBridgeEnvelope(\n value: unknown\n): (BridgeEnvelope & Fields & { type: string }) | undefined {\n if (!value || typeof value !== 'object') return;\n const fields = value as Fields;\n if (\n fields.channel !== BRIDGE ||\n fields.version !== bridgeProtocol.version ||\n typeof fields.type !== 'string' ||\n typeof fields.documentId !== 'string' ||\n !fields.documentId ||\n fields.documentId.length > 128 ||\n (fields.sessionId !== undefined && !validId(fields.sessionId)) ||\n (fields.token !== undefined && typeof fields.token !== 'string')\n )\n return;\n return fields as BridgeEnvelope & Fields & { type: string };\n}\n\n/** Project event fields after the caller has checked envelope eligibility. */\nexport function parseBridgePayload(\n envelope: NonNullable<ReturnType<typeof parseBridgeEnvelope>>,\n definition: Events[BridgeEventName]\n): BridgeMessage | undefined {\n try {\n return {\n channel: BRIDGE,\n version: bridgeProtocol.version,\n documentId: envelope.documentId,\n ...(envelope.sessionId === undefined\n ? {}\n : { sessionId: envelope.sessionId }),\n ...(envelope.token === undefined ? {} : { token: envelope.token }),\n type: definition.wire,\n ...definition.parse(envelope),\n } as BridgeMessage;\n } catch {\n return;\n }\n}\n\nexport function parseBridgeMessage(value: unknown): BridgeMessage | undefined {\n const envelope = parseBridgeEnvelope(value);\n if (!envelope) return;\n const name = bridgeEventName(envelope.type);\n if (!name) return;\n const definition = bridgeProtocol.events[name];\n if (definition.session !== 'none' && envelope.sessionId === undefined) return;\n return parseBridgePayload(envelope, definition);\n}\n","import {\n bridgeProtocol,\n bridgeEventName,\n bridgeMessageMetadata,\n parseBridgeEnvelope,\n parseBridgeMessage,\n parseBridgePayload,\n validId,\n type BridgeDiagnostic,\n type BridgeDropReason,\n type BridgeMessage,\n type BridgeRole,\n type BridgeEventsFrom,\n type BridgePayload,\n type BridgeEnvelope,\n type BridgeHandlers,\n} from './bridge.ts';\nimport { isRecord } from './record.ts';\n\ntype ConnectionContext = Pick<BridgeEnvelope, 'sessionId' | 'token'> & {\n documentId?: string;\n};\n\n/** The connection owns IDs and token rotation; callers can only supply event payloads. */\nexport function createBridgeEndpoint<const Role extends BridgeRole>({\n role,\n origin,\n source,\n opaque,\n context,\n post,\n diagnostic,\n invalidRequest,\n handlers,\n}: {\n role: Role;\n handlers: BridgeHandlers<NoInfer<Role>>;\n origin: string;\n source: () => MessageEventSource | null;\n opaque: boolean;\n context: () => ConnectionContext;\n post: (message: BridgeMessage) => void;\n diagnostic?: (event: BridgeDiagnostic) => void;\n invalidRequest?: (id: string) => void;\n}) {\n let disposed = false;\n\n function drop(reason: BridgeDropReason, type: unknown) {\n diagnostic?.({\n direction: 'drop',\n reason,\n ...(typeof type === 'string' ? { type: type.slice(0, 64) } : {}),\n });\n }\n\n function send<\n Name extends BridgeEventsFrom<Role>,\n const Payload extends BridgePayload<NoInfer<Name>>,\n >(\n name: Name,\n payload: Payload &\n Record<Exclude<keyof Payload, keyof BridgePayload<NoInfer<Name>>>, never>\n ) {\n if (disposed) throw new Error('The bridge endpoint has closed.');\n const definition = bridgeProtocol.events[name];\n const current = context();\n const message = parseBridgeMessage({\n ...payload,\n channel: bridgeProtocol.channel,\n version: bridgeProtocol.version,\n type: definition.wire,\n documentId: name === 'connect' ? 'host' : current.documentId,\n sessionId: current.sessionId,\n token: opaque ? current.token : undefined,\n });\n if (!message || (opaque && !validId(current.token)))\n throw new Error('The bridge is not ready to send this event.');\n diagnostic?.({ direction: 'send', ...bridgeMessageMetadata(message) });\n if (disposed) return;\n post(message);\n }\n\n function receive(event: MessageEvent) {\n const peer = source();\n if (disposed || !peer || event.origin !== origin || event.source !== peer)\n return;\n const envelope = parseBridgeEnvelope(event.data);\n if (!envelope) {\n const data: unknown = event.data;\n if (isRecord(data) && data.channel === bridgeProtocol.channel)\n drop('invalid_envelope', 'type' in data ? data.type : undefined);\n return;\n }\n const current = context();\n // The app learns its opaque token from a trusted host connect message.\n const connecting =\n role === 'app' && envelope.type === bridgeProtocol.events.connect.wire;\n if (\n opaque &&\n (connecting\n ? !validId(envelope.token)\n : !current.token || envelope.token !== current.token)\n )\n return drop('token_mismatch', envelope.type);\n const name = bridgeEventName(envelope.type);\n if (!name) return drop('unexpected_type', envelope.type);\n const definition = bridgeProtocol.events[name];\n if (definition.from === role) return drop('unexpected_type', envelope.type);\n if (definition.session === 'establish') {\n if (\n envelope.documentId !== current.documentId ||\n envelope.sessionId === undefined\n )\n return drop('session_mismatch', envelope.type);\n } else if (definition.session === 'current') {\n if (\n !current.sessionId ||\n envelope.sessionId !== current.sessionId ||\n envelope.documentId !== current.documentId\n )\n return drop('session_mismatch', envelope.type);\n }\n const message = parseBridgePayload(envelope, definition);\n if (!message) {\n drop('invalid_payload', envelope.type);\n if (role === 'host' && name === 'request' && validId(envelope.id))\n invalidRequest?.(envelope.id);\n return;\n }\n diagnostic?.({ direction: 'receive', ...bridgeMessageMetadata(message) });\n if (disposed) return;\n // The catalog lookup correlates the key and parsed discriminated message.\n const handler = (handlers as Record<string, (message: unknown) => void>)[\n name\n ]!;\n handler(message);\n }\n\n return {\n send,\n receive,\n dispose() {\n disposed = true;\n },\n };\n}\n","import {\n isAnnotationPresentation,\n type DataAppAnnotationPresentation,\n} from './annotations.ts';\nimport { type Theme } from './appearance.ts';\n\n/** Presentation owned by the parent shell, delivered only over a trusted bridge. */\nexport type DataAppPresentation = {\n surface: 'embedded' | 'standalone';\n theme: Theme;\n annotations?: DataAppAnnotationPresentation;\n /** `frame` (default): the parent sizes the iframe and the app scrolls inside it.\n * `content`: the iframe follows the app's content height and the parent page scrolls. */\n sizing?: 'frame' | 'content';\n};\n\nexport function isDataAppPresentation(\n value: unknown\n): value is DataAppPresentation {\n if (!value || typeof value !== 'object') return false;\n const presentation = value as DataAppPresentation;\n\n return (\n (presentation.surface === 'embedded' ||\n presentation.surface === 'standalone') &&\n (presentation.theme === 'light' || presentation.theme === 'dark') &&\n (presentation.annotations === undefined ||\n isAnnotationPresentation(presentation.annotations)) &&\n (presentation.sizing === undefined ||\n presentation.sizing === 'frame' ||\n presentation.sizing === 'content')\n );\n}\n","import { isDataAppPresentation } from '../core/presentation.ts';\nimport { isRecord } from '../core/record.ts';\n\n/** Reports the document height to a parent that sizes the iframe to its content.\n * Sizing applies only while the parent requests it and a UI owner whose styles support it\n * has opted in, so older app styles under a newer bootstrap stay frame-sized.\n * The root attribute and inset properties let fixed overlays stay within the parent's visible area. */\nexport function createFrameSizing(\n document: Document,\n report: (height: number) => void\n) {\n const root = document.documentElement;\n const frame = document.defaultView;\n let observer: ResizeObserver | undefined;\n let reported: number | undefined;\n let requested = false;\n let owners = 0;\n let viewport: { top: number; bottom: number } | undefined;\n\n function measure() {\n const height = Math.ceil(root.getBoundingClientRect().height);\n // A matching viewport acknowledges convergence after the parent resized us.\n // Resend it even if the content did not change, so independent updates do\n // not accumulate as one feedback loop in the host.\n if (height === reported && height !== frame?.innerHeight) return;\n reported = height;\n report(height);\n }\n\n function stop() {\n observer?.disconnect();\n observer = undefined;\n frame?.removeEventListener('resize', measure);\n reported = undefined;\n delete root.dataset.atblFrameSizing;\n root.style.removeProperty('--atbl-frame-inset-top');\n root.style.removeProperty('--atbl-frame-inset-bottom');\n }\n\n function applyViewport() {\n if (!observer || !viewport) return;\n root.style.setProperty('--atbl-frame-inset-top', `${viewport.top}px`);\n root.style.setProperty('--atbl-frame-inset-bottom', `${viewport.bottom}px`);\n }\n\n function sync() {\n if (!requested || !owners) return stop();\n if (observer) return;\n root.dataset.atblFrameSizing = 'content';\n observer = new (document.defaultView ?? globalThis).ResizeObserver(measure);\n observer.observe(root);\n frame?.addEventListener('resize', measure);\n applyViewport();\n }\n\n return {\n /** A new session starts with a parent that has not received the current height. */\n update(state: unknown, session: 'new' | 'current') {\n const presentation = isRecord(state) ? state.presentation : undefined;\n requested =\n isDataAppPresentation(presentation) &&\n presentation.sizing === 'content';\n if (!requested) viewport = undefined;\n if (session === 'new') reported = undefined;\n if (observer && requested) measure();\n sync();\n },\n support() {\n owners++;\n sync();\n let released = false;\n\n return () => {\n if (released) return;\n released = true;\n owners--;\n sync();\n };\n },\n viewport(top: number, bottom: number) {\n if (!requested) return;\n viewport = { top, bottom };\n applyViewport();\n },\n dispose() {\n requested = false;\n viewport = undefined;\n owners = 0;\n stop();\n },\n };\n}\n","import { type BridgeDiagnostic } from '../core/bridge.ts';\nimport { type DataAppLogger, type LogEntry } from '../core/logger.ts';\n\n/** Lazy arguments run in the iframe; only resolved values cross the bridge. */\nexport function createBridgeLogger(\n enabled: () => boolean,\n send: (entry: LogEntry) => void\n): DataAppLogger {\n function resolve(args: unknown[]): unknown[] {\n if (args.length === 1 && typeof args[0] === 'function') {\n const value: unknown = args[0]();\n return Array.isArray(value) ? value : [value];\n }\n return args.map(arg => (typeof arg === 'function' ? arg() : arg));\n }\n\n function write(method: keyof DataAppLogger, args: unknown[]) {\n if (!enabled()) return;\n try {\n send({ method, args: resolve(args) });\n } catch {\n // Logging must not interrupt the app or recursively log delivery failures.\n }\n }\n\n return {\n log: (...args) => write('log', args),\n info: (...args) => write('info', args),\n warn: (...args) => write('warn', args),\n error: (...args) => write('error', args),\n };\n}\n\nconst diagnosticLabels = {\n send: 'Sending message to parent',\n receive: 'Received message from parent',\n drop: 'Ignored message from parent',\n} as const;\n\n/** Log only delivery metadata; payloads and session credentials stay private. */\nexport function logBridgeDiagnostic(\n logger: DataAppLogger,\n { direction, ...metadata }: BridgeDiagnostic\n) {\n // Log delivery and per-frame sizing messages would flood the host logger.\n if (\n metadata.type === 'runtime:log' ||\n metadata.type === 'runtime:resize' ||\n metadata.type === 'viewport:update'\n )\n return;\n logger.log(diagnosticLabels[direction], metadata);\n}\n\n/** Error instances do not survive every logger, so only their text crosses the bridge. */\nexport function describeError(error: unknown) {\n if (error instanceof Error)\n return {\n name: error.name,\n message: error.message,\n ...(error.stack ? { stack: error.stack } : {}),\n };\n return { message: String(error) };\n}\n","import {\n MessageRoutingError,\n type MessageInput,\n type MessageOutput,\n type MessageRoutes,\n type MessageTransport,\n} from '../core/messages.ts';\n\n/** Both ends validate using the same contracts; the transport owns delivery and cancellation. */\nexport function createMessageClient<const Routes extends MessageRoutes>(\n routes: Routes,\n transport: MessageTransport\n) {\n return {\n async request<\n Name extends keyof Routes & string,\n const Input extends MessageInput<NoInfer<Routes[Name]>>,\n >(\n route: Name,\n payload: Input,\n { signal }: { signal?: AbortSignal } = {}\n ): Promise<MessageOutput<Routes[Name], Input>> {\n signal?.throwIfAborted();\n if (!Object.hasOwn(routes, route))\n throw new MessageRoutingError(\n 'unknown_route',\n 'Unknown message route.'\n );\n const contract = routes[route]!;\n let input: unknown;\n try {\n input = contract.input(payload);\n } catch {\n throw new MessageRoutingError(\n 'invalid_payload',\n 'Invalid message payload.'\n );\n }\n const response = await transport({ route, payload: input }, signal);\n signal?.throwIfAborted();\n try {\n return contract.output(response, input as never) as MessageOutput<\n Routes[Name],\n Input\n >;\n } catch (error) {\n if (error instanceof MessageRoutingError) throw error;\n throw new MessageRoutingError(\n 'invalid_response',\n 'Invalid message response.'\n );\n }\n },\n };\n}\n","// A bootstrap and its app may bundle independent copies in the same window.\nconst errorBrand = Symbol.for('@altertable/data-app/DataAppError');\n\nexport class DataAppError extends Error {\n readonly [errorBrand] = true;\n\n static override [Symbol.hasInstance](value: unknown): boolean {\n return (\n value instanceof Error &&\n (value as { [errorBrand]?: unknown })[errorBrand] === true\n );\n }\n\n constructor(\n message: string,\n public readonly code: string,\n public readonly requestId?: string\n ) {\n super(message);\n this.name = 'DataAppError';\n }\n}\n","import { type DataAppAction, type DataAppActions } from '../core/actions.ts';\nimport { createBridgeEndpoint } from '../core/bridge-endpoint.ts';\nimport {\n PARENT_PARAM,\n MAX_PENDING,\n REQUEST_TIMEOUT_MS,\n} from '../core/bridge.ts';\nimport { type HostedLakehouse } from '../core/contract.ts';\nimport {\n registeredQueryRoute,\n MessageRoutingError,\n type RoutedMessage,\n} from '../core/messages.ts';\nimport { isRecord } from '../core/record.ts';\nimport { randomUuid } from '../core/uuid.ts';\nimport { appDiagnostics } from './diagnostics.ts';\nimport { createFrameSizing } from './frame-sizing.ts';\nimport {\n createBridgeLogger,\n describeError,\n logBridgeDiagnostic,\n} from './logger.ts';\nimport { createMessageClient } from './messages.ts';\nimport { DataAppError } from './transport.ts';\n\ntype Pending = {\n start: () => void;\n reject: (error: unknown) => void;\n resolve: (value: unknown) => void;\n};\n\n/** Data clients expose one error type for HTTP and message delivery. */\nfunction rethrowDataMessageError(error: unknown): never {\n if (error instanceof MessageRoutingError)\n throw new DataAppError(error.message, error.code, error.requestId);\n throw error;\n}\n\n/** One bridge per document, shared by all clients and retained across module hot replacement. */\nexport function createIframeTransport({\n parentOrigin,\n window: frame = window,\n timeoutMs = REQUEST_TIMEOUT_MS,\n mode = 'url',\n loadScript,\n}: {\n parentOrigin: string;\n window?: Window;\n timeoutMs?: number;\n mode?: 'url' | 'bundle';\n loadScript?: (javascript: string) => void;\n}) {\n if (new URL(parentOrigin).origin !== parentOrigin)\n throw new Error('Expected an exact parent origin.');\n const documentId = randomUuid();\n let token: string | undefined;\n let sessionId: string | undefined;\n let disposed = false;\n const pending = new Map<string, Pending>();\n let hostState: unknown;\n let diagnosticsWaiting = false;\n let diagnosticTimer: ReturnType<typeof setTimeout> | undefined;\n const unsubscribeDiagnostics = appDiagnostics.subscribe(scheduleDiagnostics);\n function scheduleDiagnostics() {\n clearTimeout(diagnosticTimer);\n diagnosticTimer = setTimeout(() => {\n if (\n !hostState ||\n typeof hostState !== 'object' ||\n !('repair' in hostState) ||\n typeof hostState.repair !== 'string'\n )\n return;\n if (pending.size >= MAX_PENDING) {\n diagnosticsWaiting = true;\n return;\n }\n diagnosticsWaiting = false;\n if (!disposed && sessionId)\n void requestMessage({\n route: 'diagnostics:report',\n payload: appDiagnostics.snapshot(),\n }).catch(() => {});\n }, 150);\n }\n const stateListeners = new Set<(state: unknown) => void>();\n // The page actions last offered to the host, compared by value.\n let actions: DataAppActions = {};\n let actionsIdentity = '{}';\n const actionListeners = new Set<(action: DataAppAction) => void>();\n const logger = createBridgeLogger(\n () =>\n !disposed &&\n !!sessionId &&\n isRecord(hostState) &&\n hostState.logging === true,\n entry => send('runtimeLog', { payload: entry })\n );\n\n const endpoint = createBridgeEndpoint({\n role: 'app',\n origin: parentOrigin,\n source: () => frame.parent,\n opaque: mode === 'bundle',\n context: () => ({ documentId, sessionId, token }),\n post(message) {\n frame.parent.postMessage(message, parentOrigin);\n },\n diagnostic: event => logBridgeDiagnostic(logger, event),\n handlers: {\n connect(message) {\n if (mode === 'bundle') token = message.token;\n send('ready', {});\n },\n initialize(message) {\n if (sessionId && sessionId !== message.sessionId) {\n if (pending.size)\n logger.warn('Preview reconnected; rejecting pending requests', {\n count: pending.size,\n });\n for (const entry of pending.values())\n entry.reject(\n new DataAppError(\n 'The preview reconnected. Retry the request.',\n 'bridge_reset'\n )\n );\n }\n const first = !sessionId;\n sessionId = message.sessionId;\n receiveState(message.state, 'new');\n if (first) for (const entry of pending.values()) entry.start();\n if (disposed) return;\n if (actionsIdentity !== '{}') send('actionsUpdate', { actions });\n if (mode === 'url') send('runtimeReady', {});\n },\n stateUpdate(message) {\n receiveState(message.state, 'current');\n },\n actionRun(message) {\n for (const listener of actionListeners) listener(message.action);\n },\n viewportUpdate(message) {\n frameSizing.viewport(message.top, message.bottom);\n },\n scriptLoad(message) {\n if (mode === 'bundle') loadScript?.(message.javascript);\n },\n result(message) {\n pending.get(message.id)?.resolve(message.response);\n },\n error(message) {\n pending\n .get(message.id)\n ?.reject(\n new MessageRoutingError(\n message.code,\n message.message,\n message.requestId\n )\n );\n },\n },\n });\n const send = endpoint.send;\n const receive = endpoint.receive;\n const frameSizing = createFrameSizing(frame.document, height => {\n if (!disposed && sessionId) send('runtimeResize', { height });\n });\n\n function receiveState(state: unknown, session: 'new' | 'current') {\n if (session === 'new') scheduleDiagnostics();\n hostState = state;\n frameSizing.update(state, session);\n for (const listener of stateListeners) listener(state);\n }\n\n frame.addEventListener('message', receive);\n\n function requestMessage(\n message: RoutedMessage,\n signal?: AbortSignal\n ): Promise<unknown> {\n return new Promise((resolve, reject) => {\n if (disposed)\n return reject(\n new DataAppError('The preview has closed.', 'bridge_closed')\n );\n if (signal?.aborted) return reject(signal.reason);\n if (pending.size >= MAX_PENDING)\n return reject(\n new DataAppError('Too many pending data requests.', 'bridge_busy')\n );\n const id = randomUuid();\n let sent = false;\n\n function cleanup() {\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n pending.delete(id);\n if (diagnosticsWaiting) scheduleDiagnostics();\n }\n\n function abort() {\n if (sent) send('cancel', { id });\n cleanup();\n reject(signal?.reason);\n }\n\n const timer = setTimeout(() => {\n logger.warn('Message request timed out', {\n id,\n route: message.route,\n timeoutMs,\n sent,\n });\n if (sent) send('cancel', { id });\n cleanup();\n reject(\n new DataAppError(\n sessionId\n ? 'The data request timed out.'\n : 'The preview shell is unavailable. Reload the preview.',\n sessionId ? 'timeout' : 'bridge_unavailable'\n )\n );\n }, timeoutMs);\n const entry: Pending = {\n start() {\n if (sent) return;\n try {\n send('request', {\n id,\n route: message.route,\n payload: message.payload,\n });\n sent = true;\n } catch {\n cleanup();\n reject(\n new DataAppError(\n 'The message payload could not be sent.',\n 'invalid_payload'\n )\n );\n }\n },\n resolve(value) {\n cleanup();\n resolve(value);\n },\n reject(error) {\n cleanup();\n reject(error);\n },\n };\n pending.set(id, entry);\n signal?.addEventListener('abort', abort, { once: true });\n if (sessionId) entry.start();\n else if (mode === 'url' || token) send('ready', {});\n });\n }\n\n const messages = createMessageClient(\n {\n 'data:query': registeredQueryRoute,\n },\n requestMessage\n );\n\n function disconnect() {\n if (sessionId) send('disconnect', {});\n sessionId = undefined;\n for (const entry of pending.values())\n entry.reject(\n new DataAppError('The preview has closed.', 'bridge_closed')\n );\n }\n\n function resume(event: PageTransitionEvent) {\n if (event.persisted && (mode === 'url' || token)) send('ready', {});\n }\n\n function dispose() {\n if (disposed) return;\n disconnect();\n disposed = true;\n clearTimeout(diagnosticTimer);\n unsubscribeDiagnostics();\n endpoint.dispose();\n frameSizing.dispose();\n frame.removeEventListener('message', receive);\n frame.removeEventListener('pagehide', disconnect);\n frame.removeEventListener('pageshow', resume);\n stateListeners.clear();\n actionListeners.clear();\n }\n\n frame.addEventListener('pagehide', disconnect);\n frame.addEventListener('pageshow', resume);\n if (mode === 'url') send('ready', {});\n\n return {\n diagnostics: appDiagnostics,\n logger,\n request: requestMessage,\n lakehouse: {\n queryAllById(queryId, { limit, signal, params }) {\n return messages\n .request(\n 'data:query',\n {\n queryId,\n limit,\n ...(params === undefined ? {} : { params }),\n },\n { signal }\n )\n .catch(rethrowDataMessageError);\n },\n } satisfies HostedLakehouse,\n dispose,\n mode,\n snapshot() {\n return hostState;\n },\n subscribe(listener: (state: unknown) => void) {\n stateListeners.add(listener);\n\n return () => {\n stateListeners.delete(listener);\n };\n },\n ready() {\n if (!disposed && sessionId) send('runtimeReady', {});\n },\n /** Offers page actions to the host, replacing the previous set; `{}` withdraws them.\n * Unchanged sets are not resent, so callers can report their latest set on every render.\n * The current set is resent when the host reconnects. */\n setActions(value: DataAppActions) {\n const identity = JSON.stringify(value);\n if (disposed || identity === actionsIdentity) return;\n actions = value;\n actionsIdentity = identity;\n if (sessionId) send('actionsUpdate', { actions });\n },\n /** Receives host requests to run offered page actions. */\n onAction(listener: (action: DataAppAction) => void) {\n actionListeners.add(listener);\n\n return () => {\n actionListeners.delete(listener);\n };\n },\n /** The UI owner calls this once its styles support content sizing; the parent's\n * `sizing: 'content'` presentation then applies until the returned release runs. */\n supportContentSizing() {\n return frameSizing.support();\n },\n /** Reports a fatal app failure; the cause reaches the host logger only. */\n fail(cause?: unknown) {\n if (disposed || !sessionId) return;\n appDiagnostics.record('render', 'App startup', cause);\n if (cause !== undefined)\n logger.error(() => ['Data app failed', describeError(cause)]);\n send('runtimeError', {});\n },\n };\n}\n\nexport type IframeTransport = ReturnType<typeof createIframeTransport>;\n\nconst bridgeKey = Symbol.for('altertable.localFrameBridge');\nconst installedKey = Symbol.for('altertable.installedTransport');\ntype LocalBridge = Partial<Pick<IframeTransport, 'request'>> & {\n connect?: () => Promise<IframeTransport>;\n};\ntype FrameWindow = Window & {\n [bridgeKey]?: LocalBridge;\n [installedKey]?: ReturnType<typeof createIframeTransport>;\n};\n\n/** The URL opts into local preview; only same-origin server configuration establishes trust. */\nexport function localFrameBridge(window?: Window): LocalBridge | undefined {\n const activeWindow =\n window ??\n (typeof globalThis.window === 'undefined' ? undefined : globalThis.window);\n if (!activeWindow) return undefined;\n const frame = activeWindow as FrameWindow;\n if (frame[bridgeKey]) return frame[bridgeKey];\n const parentOrigin =\n new URL(frame.location.href).searchParams.get(PARENT_PARAM) ?? '';\n if (!parentOrigin) return undefined;\n\n async function connect(parentOrigin: string) {\n try {\n const response = await frame.fetch('/__altertable/parent', {\n signal: AbortSignal.timeout(5000),\n });\n const config = (await response.json()) as { origin?: unknown };\n if (\n !response.ok ||\n config.origin !== parentOrigin ||\n frame.parent === frame\n )\n throw new Error('Invalid local parent configuration.');\n // Another owner can install a trusted bridge while configuration is pending.\n if (frame[installedKey]) return frame[installedKey];\n if (frame[bridgeKey] !== proxy)\n throw new Error('Preview transport owner changed.');\n const bridge = createIframeTransport({ parentOrigin, window: frame });\n frame[bridgeKey] = bridge;\n frame[installedKey] = bridge;\n\n return bridge;\n } catch {\n throw new DataAppError(\n 'The preview shell could not be verified. Open the URL printed by altertable app dev.',\n 'bridge_unavailable'\n );\n }\n }\n\n let connection: Promise<ReturnType<typeof createIframeTransport>> | undefined;\n\n function getConnection() {\n const installed = frame[installedKey];\n if (installed) return Promise.resolve(installed);\n if (!connection) {\n const attempt = connect(parentOrigin);\n connection = attempt;\n // Clear only this failed attempt; retained proxy references can explicitly retry.\n void attempt.catch(() => {\n if (connection === attempt) connection = undefined;\n });\n }\n\n return connection;\n }\n\n const proxy: LocalBridge = { connect: getConnection };\n frame[bridgeKey] = proxy;\n // Static mounting still verifies eagerly, without an unhandled rejection.\n void getConnection().catch(() => {});\n\n return proxy;\n}\n\n/** Install an explicitly trusted transport for hosted apps and their URL-backed controls. */\nexport function installDataAppTransport(\n bridge: ReturnType<typeof createIframeTransport>,\n frame: Window = window\n) {\n const target = frame as FrameWindow;\n if (target[installedKey])\n throw new Error('A data app transport is already installed.');\n target[bridgeKey] = bridge;\n target[installedKey] = bridge;\n\n return () => {\n if (target[bridgeKey] === bridge) delete target[bridgeKey];\n if (target[installedKey] === bridge) delete target[installedKey];\n bridge.dispose();\n };\n}\n\n/** The bootstrap installs this before executing app code. URL apps can install an explicit connection. */\nexport function getDataAppTransport(frame: Window = window) {\n return (frame as FrameWindow)[installedKey];\n}\n","import {\n appFailure,\n type AppFailure,\n type AppDiagnosticReport,\n} from '../core/diagnostics.ts';\nimport { getDataAppTransport } from './iframe.ts';\n\nconst listeners = new Set<() => void>();\nconst failures = new Map<string, AppFailure>();\nlet pending = 0;\nfunction publish() {\n for (const listener of listeners) listener();\n}\n\n/** Lightweight live observations only. No query values or result rows are retained. */\ntype Diagnostics = {\n snapshot: () => AppDiagnosticReport;\n subscribe: (listener: () => void) => () => void;\n record: (\n kind: AppFailure['kind'],\n name: string,\n error: unknown,\n identity?: string\n ) => void;\n clear: (kind: AppFailure['kind'], name: string, identity?: string) => void;\n begin: () => () => void;\n};\nfunction installed(): Diagnostics | undefined {\n const diagnostics =\n typeof window === 'undefined'\n ? undefined\n : getDataAppTransport()?.diagnostics;\n return diagnostics !== appDiagnostics ? diagnostics : undefined;\n}\nexport const appDiagnostics: Diagnostics = {\n snapshot(): AppDiagnosticReport {\n if (installed()) return installed()!.snapshot();\n const observed: AppFailure[] = [];\n for (const failure of failures.values()) {\n observed.push(failure);\n if (observed.length === 30) break;\n }\n return {\n failures: observed,\n pending,\n truncated: Math.max(0, failures.size - 30),\n };\n },\n subscribe(listener: () => void) {\n if (installed()) return installed()!.subscribe(listener);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n record(\n kind: AppFailure['kind'],\n name: string,\n error: unknown,\n identity?: string\n ) {\n if (installed()) return installed()!.record(kind, name, error, identity);\n const failure = appFailure(kind, name, error);\n if (identity) failure.id = identity;\n const key = `${kind}:${identity ?? name}`;\n // Retain active failures until cleared; bound messages and outgoing reports.\n failures.set(key, failure);\n publish();\n },\n clear(kind: AppFailure['kind'], name: string, identity?: string) {\n if (installed()) return installed()!.clear(kind, name, identity);\n if (failures.delete(`${kind}:${identity ?? name}`)) publish();\n },\n begin() {\n if (installed()) return installed()!.begin();\n pending++;\n publish();\n return () => {\n pending--;\n publish();\n };\n },\n};\n"],"mappings":";;;;AAsBA,eAAsB,qBACpB,WACA,OACA,EACE,eACA,WACA,QAAQ,eACR,WACA,aACA,WAEF;CACA,cAAc,eAAe;CAC7B,IAAI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O,UAAU,CAAC,CAAE,SAAS;EAC9C,MAAM,WAAyB,CAAC;EAChC,KAAK,MAAM,WAAW,SAAS,OAAO,GAAG;GACvC,SAAS,KAAK,OAAO;GACrB,IAAI,SAAS,WAAW,IAAI;EAC9B;EACA,OAAO;GACL,UAAU;GACV;GACA,WAAW,KAAK,IAAI,GAAG,SAAS,OAAO,EAAE;EAC3C;CACF;CACA,UAAU,UAAsB;EAC9B,IAAI,UAAU,GAAG,OAAO,UAAU,CAAC,CAAE,UAAU,QAAQ;EACvD,UAAU,IAAI,QAAQ;EACtB,aAAa;GACX,UAAU,OAAO,QAAQ;EAC3B;CACF;CACA,OACE,MACA,MACA,OACA,UACA;EACA,IAAI,UAAU,GAAG,OAAO,UAAU,CAAC,CAAE,OAAO,MAAM,MAAM,OAAO,QAAQ;EACvE,MAAM,UAAU,WAAW,MAAM,MAAM,KAAK;EAC5C,IAAI,UAAU,QAAQ,KAAK;EAC3B,MAAM,MAAM,GAAG,KAAK,GAAG,YAAY;EAEnC,SAAS,IAAI,KAAK,OAAO;EACzB,QAAQ;CACV;CACA,MAAM,MAA0B,MAAc,UAAmB;EAC/D,IAAI,UAAU,GAAG,OAAO,UAAU,CAAC,CAAE,MAAM,MAAM,MAAM,QAAQ;EAC/D,IAAI,SAAS,OAAO,GAAG,KAAK,GAAG,YAAY,MAAM,GAAG,QAAQ;CAC9D;CACA,QAAQ;EACN,IAAI,UAAU,GAAG,OAAO,UAAU,CAAC,CAAE,MAAM;EAC3C;EACA,QAAQ;EACR,aAAa;GACX;GACA,QAAQ;EACV;CACF;AACF"}
1
+ {"version":3,"file":"diagnostics-BwpM9wGn.js","names":[],"sources":["../../src/core/operation.ts","../../src/core/uuid.ts","../../src/core/diagnostics.ts","../../src/core/actions.ts","../../src/core/logger.ts","../../src/core/bridge.ts","../../src/core/bridge-endpoint.ts","../../src/core/presentation.ts","../../src/client/frame-sizing.ts","../../src/client/logger.ts","../../src/client/messages.ts","../../src/client/transport.ts","../../src/client/iframe.ts","../../src/client/diagnostics.ts"],"sourcesContent":["import { DataSourceError } from './contract.ts';\nimport { DimensionMembershipError } from './dimension-source.ts';\nimport type {\n DataOperations,\n DisclosedQuery,\n Lakehouse,\n SqlLakehouse,\n OperationContext,\n DataQueryBody,\n} from './operation-types.ts';\n\ntype Operation = DataOperations[string];\ntype OperationExecutionOptions = {\n operationName: string;\n lakehouse: Lakehouse;\n signal: AbortSignal;\n requestId: string;\n queryParams?: OperationContext['queryParams'];\n onQuery?: (name: string, error?: unknown) => void;\n};\n\n/** Shared operation execution. Adapters own authorization, delivery, and public errors. */\nexport async function executeDataOperation(\n operation: Operation,\n value: unknown,\n {\n operationName,\n lakehouse,\n signal: requestSignal,\n requestId,\n queryParams,\n onQuery,\n }: OperationExecutionOptions\n) {\n requestSignal.throwIfAborted();\n let input: unknown;\n try {\n input = operation.input(value);\n } catch {\n throw new OperationInputError();\n }\n\n const signal = AbortSignal.any([\n requestSignal,\n AbortSignal.timeout(operation.policy.maxDurationMs),\n ]);\n const execution = createOperationLakehouse(\n operation,\n lakehouse,\n signal,\n operationName,\n onQuery\n );\n try {\n const output = await runOperation(operation, input, {\n lakehouse: execution.lakehouse,\n signal,\n queryParams,\n });\n const body: DataQueryBody<unknown> = {\n data: output,\n requestId,\n queriedAt: new Date().toISOString(),\n queryIds: execution.queryIds,\n queries: execution.queries,\n };\n const serializedBody = JSON.stringify(body);\n const responseBytes = new TextEncoder().encode(serializedBody).byteLength;\n if (responseBytes > (operation.policy.maxResponseBytes ?? 1_000_000))\n throw new Error('Response exceeds byte limit.');\n\n return { body, serializedBody };\n } catch (error) {\n if (signal.aborted && !(error instanceof DataSourceError))\n throw new OperationTimeoutError();\n throw error;\n }\n}\n\n/** Query evidence follows statement invocation order; query IDs retain completion order. */\nfunction createOperationLakehouse(\n operation: Operation,\n source: Lakehouse,\n signal: AbortSignal,\n operationName: string,\n onQuery?: (name: string, error?: unknown) => void\n) {\n const queryIds: string[] = [];\n const queries: DisclosedQuery[] = [];\n const lakehouse: SqlLakehouse = {\n async queryAll(statement, options) {\n signal.throwIfAborted();\n if (!Number.isInteger(options.limit) || options.limit < 1)\n throw new Error('Query needs a positive row limit.');\n if (\n operation.queryNames &&\n !Object.values(operation.queryNames).includes(options.name ?? '')\n )\n throw new Error(\n `Query name is not registered for operation ${operationName}.`\n );\n const query: DisclosedQuery = {\n name: options.name ?? `Query ${queries.length + 1}`,\n statement,\n ...(options.params === undefined ? {} : { params: options.params }),\n };\n queries.push(query);\n const limit = Math.min(options.limit, operation.policy.maxQueryRows);\n const querySignal = AbortSignal.any([signal, options.signal]);\n let result;\n try {\n const queryOptions = {\n limit,\n ...(options.params === undefined ? {} : { params: options.params }),\n signal: querySignal,\n };\n if ('queryAllById' in source) {\n if (!options.name || !operation.queryNames)\n throw new Error('A registered query name is required.');\n result = await source.queryAllById(options.name, queryOptions);\n } else {\n result = await source.queryAll(statement, {\n ...queryOptions,\n ...(options.name === undefined ? {} : { name: options.name }),\n });\n }\n } catch (error) {\n if (!querySignal.aborted) onQuery?.(query.name, error);\n if (error instanceof DataSourceError) error.queryName = query.name;\n throw error;\n }\n onQuery?.(query.name);\n if (result.rows.length > limit)\n throw new Error('Result exceeds row limit.');\n if (result.queryId) {\n query.queryId = result.queryId;\n queryIds.push(result.queryId);\n }\n\n return result;\n },\n };\n\n return { lakehouse, queries, queryIds };\n}\n\n/** Settle cancellation even when operation code or its lakehouse ignores the signal. */\nasync function runOperation(\n operation: Operation,\n input: unknown,\n { lakehouse, signal, queryParams }: OperationContext\n) {\n let abort: (() => void) | undefined;\n try {\n signal.throwIfAborted();\n const cancelled = new Promise<never>((_, reject) => {\n function rejectAborted() {\n reject(new Error('Request aborted.'));\n }\n abort = rejectAborted;\n signal.addEventListener('abort', rejectAborted, { once: true });\n if (signal.aborted) rejectAborted();\n });\n\n return await Promise.race([\n cancelled,\n Promise.resolve().then(() => {\n signal.throwIfAborted();\n\n return operation.run(\n { lakehouse, signal, queryParams },\n input as never\n );\n }),\n ]);\n } finally {\n if (abort) signal.removeEventListener('abort', abort);\n }\n}\n\nclass OperationTimeoutError extends Error {}\n\nclass OperationInputError extends Error {}\n\nconst sourceErrorMessages = {\n unauthorized:\n 'This app could not authenticate its data connection. Contact the app owner.',\n forbidden:\n 'This app cannot access the requested data. Contact the app owner.',\n rate_limited: 'The lakehouse is busy. Wait a moment and retry.',\n query_rejected:\n \"A lakehouse query was rejected. Check the app's data operation.\",\n unavailable: 'The lakehouse is unavailable. Check the connection and retry.',\n};\n\nexport function toDataOperationFailure(error: unknown, aborted = false) {\n if (\n error instanceof OperationInputError ||\n error instanceof DimensionMembershipError\n )\n return {\n status: 400,\n code: 'invalid_input',\n message: \"Check this operation's inputs.\",\n };\n if (error instanceof DataSourceError)\n return {\n status: error.reason === 'rate_limited' ? 429 : 502,\n code: `source_${error.reason}`,\n message: sourceErrorMessages[error.reason],\n };\n const timedOut = aborted || error instanceof OperationTimeoutError;\n return {\n status: timedOut ? 504 : 502,\n code: timedOut ? 'timeout' : 'query_failed',\n message: timedOut\n ? 'The data request timed out.'\n : 'The data request failed.',\n };\n}\n","/** Opaque documents can lack randomUUID even when cryptographic randomness is available. */\nexport function randomUuid(): string {\n if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 15) | 64;\n bytes[8] = (bytes[8]! & 63) | 128;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10),\n ]\n .map(part => part.join(''))\n .join('-');\n}\n","/** Failures observed during the checks and interactions actually exercised. */\nexport type AppFailure = {\n /** Mounted widget identity when multiple widgets share a label. */\n id?: string;\n kind: 'query' | 'operation' | 'render';\n name: string;\n message: string;\n /** Sanitized filename and one-based line/column. Source contents are never included. */\n source?: { file: string; line: number; column: number };\n};\nexport type AppDiagnosticReport = {\n /** Current observed failures, limited to 30 entries. */\n failures: AppFailure[];\n /** Observed checks that have not finished. */\n pending: number;\n /** Failures omitted from this report's bounded failure list. */\n truncated: number;\n};\n\n/** Omit query values, URL parameters and common credential forms from error text. */\nfunction diagnosticText(value: string, limit = 800) {\n const text = value\n .replace(/https?:\\/\\/[^\\s)]+/g, url => {\n try {\n const parsed = new URL(url);\n return `${parsed.origin}${parsed.pathname}`;\n } catch {\n return '[url]';\n }\n })\n .replace(\n /\\b((?:set-cookie|cookie|(?:x-)?api[-_]?key)\\s*[:=]\\s*)[^\\r\\n]*/gi,\n '$1[redacted]'\n )\n .replace(\n /\\b((?:proxy-)?authorization\\s*[:=]\\s*)(?:(?:bearer|basic)\\s+)?(?:\"[^\"\\n]*\"|'[^'\\n]*'|[^\\s,;]+)/gi,\n '$1[redacted]'\n )\n .replace(/\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi, '[email]')\n .replace(\n /\\b(bearer\\s+|(?:password|token|secret)\\s*[:=]\\s*)(?:\"[^\"\\n]*\"|'[^'\\n]*'|[^\\s,;]+)/gi,\n '$1[redacted]'\n )\n .replace(/\\b[\\w.-]+\\s*=\\s*[^\\s,;]+/g, '[parameter]')\n .replace(/(['\"`])[^\\n]*?\\1/g, '[value]');\n return text.length > limit ? `${text.slice(0, limit)}… [truncated]` : text;\n}\n\nexport function appFailure(\n kind: AppFailure['kind'],\n name: string,\n error: unknown\n): AppFailure {\n const source =\n error instanceof Error ? sourceLocation(error.stack) : undefined;\n\n return {\n kind,\n name: diagnosticText(name, 120),\n message: diagnosticText(\n error instanceof Error ? error.message : 'Unknown failure'\n ),\n ...(source ? { source } : {}),\n };\n}\n\nconst MAX_STACK_LENGTH = 16_384;\n\n/** Extract one location, excluding stack text, URL parameters and local directory paths. */\nfunction sourceLocation(stack?: string): AppFailure['source'] {\n // Inspect a bounded stack prefix; malformed frame tokens must not cause backtracking.\n const frames = stack?.slice(0, MAX_STACK_LENGTH).split('\\n').slice(1) ?? [];\n if (stack && stack.length > MAX_STACK_LENGTH) frames.pop();\n for (const frame of frames) {\n for (const token of frame.split(/[\\s()]+/)) {\n const columnSeparator = token.lastIndexOf(':');\n const lineSeparator = token.lastIndexOf(':', columnSeparator - 1);\n if (lineSeparator < 1 || columnSeparator <= lineSeparator) continue;\n const lineText = token.slice(lineSeparator + 1, columnSeparator);\n const columnText = token.slice(columnSeparator + 1);\n if (!/^\\d+$/.test(lineText) || !/^\\d+$/.test(columnText)) continue;\n const line = Number(lineText);\n const column = Number(columnText);\n if (\n !Number.isSafeInteger(line) ||\n line < 1 ||\n !Number.isSafeInteger(column) ||\n column < 1\n )\n continue;\n const file = token.slice(0, lineSeparator).split(/[/\\\\]/).at(-1)!;\n\n return { file: diagnosticText(file, 200), line, column };\n }\n }\n\n return undefined;\n}\nfunction parseSource(value: unknown): AppFailure['source'] {\n if (!value || typeof value !== 'object')\n throw new Error('Invalid source location');\n const source = value as NonNullable<AppFailure['source']>;\n if (\n typeof source.file !== 'string' ||\n !Number.isSafeInteger(source.line) ||\n source.line < 1 ||\n !Number.isSafeInteger(source.column) ||\n source.column < 1\n )\n throw new Error('Invalid source location');\n return {\n file: diagnosticText(\n source.file.split(/[?#]/, 1)[0]!.split(/[/\\\\]/).at(-1)!,\n 200\n ),\n line: source.line,\n column: source.column,\n };\n}\n\n/** Validate and project iframe reports. Unknown fields (including query inputs) never cross this boundary. */\nexport function parseAppDiagnosticReport(value: unknown): AppDiagnosticReport {\n if (!value || typeof value !== 'object')\n throw new Error('Invalid diagnostic report');\n const report = value as AppDiagnosticReport;\n if (\n !Array.isArray(report.failures) ||\n report.failures.length > 30 ||\n !Number.isSafeInteger(report.pending) ||\n report.pending < 0 ||\n !Number.isSafeInteger(report.truncated) ||\n report.truncated < 0\n )\n throw new Error('Invalid diagnostic report');\n return {\n failures: report.failures.map(failure => {\n if (\n !failure ||\n !['query', 'operation', 'render'].includes(failure.kind) ||\n typeof failure.name !== 'string' ||\n typeof failure.message !== 'string'\n )\n throw new Error('Invalid diagnostic failure');\n return {\n kind: failure.kind,\n ...(typeof failure.id === 'string'\n ? { id: diagnosticText(failure.id, 120) }\n : {}),\n name: diagnosticText(failure.name, 120),\n message: diagnosticText(failure.message),\n ...(failure.source ? { source: parseSource(failure.source) } : {}),\n };\n }),\n pending: report.pending,\n truncated: report.truncated,\n };\n}\n","import { isRecord } from './record.ts';\n\n/** Page actions an embedded app offers its host, replaced as a whole on every change.\n * An absent key means the app does not offer that action. */\nexport type DataAppActions = {\n /** Run `refresh`; while `refreshing`, run `cancelRefresh` if `cancellable`. */\n refresh?: { refreshing: boolean; cancellable: boolean };\n /** Run `exportCsv`. `tables` names the datasets an action's `table` may select. */\n exportCsv?: { enabled: boolean; tables: readonly string[] };\n /** Run `presentStory`; while `presenting`, run `closeStory`. */\n presentStory?: { enabled: boolean; presenting: boolean };\n /** Run `aboutData` to open the data inspector. */\n aboutData?: { enabled: boolean };\n};\n\n/** A host request to run an offered page action. The app ignores unavailable actions. */\nexport type DataAppAction =\n | { type: 'refresh' }\n | { type: 'cancelRefresh' }\n /** Omit `table` to export every dataset, as a ZIP when there are several. */\n | { type: 'exportCsv'; table?: string }\n | { type: 'presentStory' }\n | { type: 'closeStory' }\n | { type: 'aboutData' };\n\nconst MAX_TABLES = 64;\n\nexport function parseDataAppActions(value: unknown): DataAppActions {\n if (!isRecord(value)) throw new Error('Invalid actions.');\n const actions: DataAppActions = {};\n const { refresh, exportCsv } = value;\n if (refresh !== undefined) {\n if (\n !isRecord(refresh) ||\n typeof refresh.refreshing !== 'boolean' ||\n typeof refresh.cancellable !== 'boolean'\n )\n throw new Error('Invalid refresh action.');\n actions.refresh = {\n refreshing: refresh.refreshing,\n cancellable: refresh.cancellable,\n };\n }\n if (exportCsv !== undefined) {\n if (\n !isRecord(exportCsv) ||\n typeof exportCsv.enabled !== 'boolean' ||\n !Array.isArray(exportCsv.tables) ||\n exportCsv.tables.length > MAX_TABLES ||\n !exportCsv.tables.every(\n table => typeof table === 'string' && table.length <= 256\n )\n )\n throw new Error('Invalid export action.');\n actions.exportCsv = {\n enabled: exportCsv.enabled,\n tables: [...(exportCsv.tables as string[])],\n };\n }\n const { presentStory } = value;\n if (presentStory !== undefined) {\n if (\n !isRecord(presentStory) ||\n typeof presentStory.enabled !== 'boolean' ||\n typeof presentStory.presenting !== 'boolean'\n )\n throw new Error('Invalid story action.');\n actions.presentStory = {\n enabled: presentStory.enabled,\n presenting: presentStory.presenting,\n };\n }\n const { aboutData } = value;\n if (aboutData !== undefined) {\n if (!isRecord(aboutData) || typeof aboutData.enabled !== 'boolean')\n throw new Error('Invalid inspection action.');\n actions.aboutData = { enabled: aboutData.enabled };\n }\n return actions;\n}\n\nexport function parseDataAppAction(value: unknown): DataAppAction {\n if (!isRecord(value)) throw new Error('Invalid action.');\n switch (value.type) {\n case 'refresh':\n case 'cancelRefresh':\n case 'presentStory':\n case 'closeStory':\n case 'aboutData':\n return { type: value.type };\n case 'exportCsv':\n if (value.table !== undefined && typeof value.table !== 'string')\n throw new Error('Invalid export table.');\n return value.table === undefined\n ? { type: 'exportCsv' }\n : { type: 'exportCsv', table: value.table };\n default:\n throw new Error('Unknown action.');\n }\n}\n","/** Host-owned log sink; compatible with console and frontend createLogger(). */\nexport type DataAppLogger = {\n log: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n};\n\nexport type LogEntry = {\n method: keyof DataAppLogger;\n args: unknown[];\n};\n\nexport function isLogEntry(value: unknown): value is LogEntry {\n if (!value || typeof value !== 'object') return false;\n const entry = value as Record<string, unknown>;\n return (\n (entry.method === 'log' ||\n entry.method === 'info' ||\n entry.method === 'warn' ||\n entry.method === 'error') &&\n Array.isArray(entry.args) &&\n entry.args.length <= 128\n );\n}\n","import { parseDataAppAction, parseDataAppActions } from './actions.ts';\nimport { isLogEntry } from './logger.ts';\nimport { isRecord } from './record.ts';\n\n/** Data app delivery protocol. IDs identify a document, a shell session, and an individual call. */\nconst BRIDGE = 'altertable:data-app';\nexport const PARENT_PARAM = '__altertable_parent';\n/** Bound pending requests in the client and host independently.\n * The host enforces its own limit because frames can send messages directly. */\nexport const MAX_PENDING = 128;\nexport const REQUEST_TIMEOUT_MS = 60_000;\nexport { type TransportResponse } from './operation-types.ts';\n\nexport function validId(value: unknown): value is string {\n return typeof value === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(value);\n}\n\ntype Fields = Record<string, unknown>;\nexport type BridgeRole = 'host' | 'app';\ntype SessionRule = 'none' | 'establish' | 'current';\n\nfunction event<\n const Wire extends string,\n const Role extends BridgeRole,\n const Session extends SessionRule,\n Payload,\n>({\n wire,\n from,\n session,\n parse,\n}: {\n wire: Wire;\n from: Role;\n session: Session;\n parse: (fields: Fields) => Payload;\n}) {\n return { wire, from, session, parse };\n}\n\nfunction id(fields: Fields) {\n if (!validId(fields.id)) throw new Error('Invalid request ID.');\n return fields.id;\n}\n\nfunction string(fields: Fields, key: string) {\n const value = fields[key];\n if (typeof value !== 'string') throw new Error(`Invalid ${key}.`);\n return value;\n}\n\nfunction length(fields: Fields, key: string) {\n const value = fields[key];\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)\n throw new Error(`Invalid ${key}.`);\n return value;\n}\n\nfunction empty() {\n return {};\n}\n\n/** Parsers project known fields; opaque values are validated by their owning route or adapter. */\nexport const bridgeProtocol = {\n channel: BRIDGE,\n version: 1,\n events: {\n connect: event({\n wire: 'bridge:connect',\n from: 'host',\n session: 'none',\n parse: empty,\n }),\n ready: event({\n wire: 'bridge:ready',\n from: 'app',\n session: 'none',\n parse: empty,\n }),\n initialize: event({\n wire: 'bridge:initialize',\n from: 'host',\n session: 'establish',\n parse: fields => ({ state: fields.state }),\n }),\n request: event({\n wire: 'bridge:request',\n from: 'app',\n session: 'current',\n parse: fields => {\n const route = string(fields, 'route');\n if (!route || route.length > 256)\n throw new Error('Invalid message route.');\n return { id: id(fields), route, payload: fields.payload };\n },\n }),\n result: event({\n wire: 'bridge:result',\n from: 'host',\n session: 'current',\n parse: fields => {\n if (!Object.hasOwn(fields, 'response'))\n throw new Error('Missing response.');\n return { id: id(fields), response: fields.response };\n },\n }),\n error: event({\n wire: 'bridge:error',\n from: 'host',\n session: 'current',\n parse: fields => {\n if (\n fields.requestId !== undefined &&\n typeof fields.requestId !== 'string'\n )\n throw new Error('Invalid requestId.');\n return {\n id: id(fields),\n code: string(fields, 'code'),\n message: string(fields, 'message'),\n ...(fields.requestId === undefined\n ? {}\n : { requestId: fields.requestId }),\n };\n },\n }),\n cancel: event({\n wire: 'bridge:cancel',\n from: 'app',\n session: 'current',\n parse: fields => ({ id: id(fields) }),\n }),\n disconnect: event({\n wire: 'bridge:disconnect',\n from: 'app',\n session: 'current',\n parse: empty,\n }),\n scriptLoad: event({\n wire: 'script:load',\n from: 'host',\n session: 'current',\n parse: fields => ({ javascript: string(fields, 'javascript') }),\n }),\n stateUpdate: event({\n wire: 'state:update',\n from: 'host',\n session: 'current',\n parse: fields => ({ state: fields.state }),\n }),\n runtimeLog: event({\n wire: 'runtime:log',\n from: 'app',\n session: 'current',\n parse: fields => {\n if (!isLogEntry(fields.payload)) throw new Error('Invalid log entry.');\n return { payload: fields.payload };\n },\n }),\n runtimeReady: event({\n wire: 'runtime:ready',\n from: 'app',\n session: 'current',\n parse: empty,\n }),\n runtimeError: event({\n wire: 'runtime:error',\n from: 'app',\n session: 'current',\n parse: empty,\n }),\n /** Content height in CSS pixels; hosts apply it only to content-sized frames. */\n runtimeResize: event({\n wire: 'runtime:resize',\n from: 'app',\n session: 'current',\n parse: fields => ({ height: length(fields, 'height') }),\n }),\n /** The page actions the app currently offers; replaces the previous set. */\n actionsUpdate: event({\n wire: 'actions:update',\n from: 'app',\n session: 'current',\n parse: fields => ({ actions: parseDataAppActions(fields.actions) }),\n }),\n actionRun: event({\n wire: 'action:run',\n from: 'host',\n session: 'current',\n parse: fields => ({ action: parseDataAppAction(fields.action) }),\n }),\n /** CSS pixels of a content-sized frame hidden above and below the parent's visible area. */\n viewportUpdate: event({\n wire: 'viewport:update',\n from: 'host',\n session: 'current',\n parse: fields => ({\n top: length(fields, 'top'),\n bottom: length(fields, 'bottom'),\n }),\n }),\n },\n} as const;\n\ntype Events = typeof bridgeProtocol.events;\nexport type BridgeEventName = keyof Events;\nexport type BridgePayload<Name extends BridgeEventName> = ReturnType<\n Events[Name]['parse']\n>;\nexport type BridgeEnvelope = {\n channel: typeof BRIDGE;\n version: typeof bridgeProtocol.version;\n documentId: string;\n sessionId?: string;\n token?: string;\n};\nexport type BridgeEventMessage<Name extends BridgeEventName> =\n Name extends BridgeEventName\n ? BridgeEnvelope & {\n type: Events[Name]['wire'];\n } & (Events[Name]['session'] extends 'none'\n ? {}\n : { sessionId: string }) &\n BridgePayload<Name>\n : never;\nexport type BridgeMessage = {\n [Name in BridgeEventName]: BridgeEventMessage<Name>;\n}[BridgeEventName];\nexport type BridgeEventsFrom<Role extends BridgeRole> = {\n [Name in BridgeEventName]: Events[Name]['from'] extends Role ? Name : never;\n}[BridgeEventName];\nexport type BridgeHandlers<Role extends BridgeRole> = {\n [Name in BridgeEventsFrom<Role extends 'host' ? 'app' : 'host'>]: (\n message: BridgeEventMessage<Name>\n ) => void;\n};\n\n/** Delivery metadata safe to log on either side; never payloads or session credentials. */\nexport type BridgeMessageMetadata = {\n type: BridgeMessage['type'];\n id?: string;\n route?: string;\n operation?: string;\n error?: { code: string; message: string; requestId?: string };\n};\n\nexport function bridgeMessageMetadata(\n message: BridgeMessage\n): BridgeMessageMetadata {\n const metadata: BridgeMessageMetadata = { type: message.type };\n if ('id' in message) metadata.id = message.id;\n if (message.type === 'bridge:request') {\n metadata.route = message.route;\n const payload = message.payload;\n if (\n message.route === 'data:query' &&\n isRecord(payload) &&\n typeof payload.operation === 'string'\n )\n metadata.operation = payload.operation.slice(0, 256);\n }\n if (message.type === 'bridge:error')\n metadata.error = {\n code: message.code,\n message: message.message,\n ...(message.requestId === undefined\n ? {}\n : { requestId: message.requestId }),\n };\n return metadata;\n}\n\n/** Why a message from the connected peer was ignored. Messages from other windows are not reported. */\nexport type BridgeDropReason =\n | 'invalid_envelope'\n | 'token_mismatch'\n | 'unexpected_type'\n | 'session_mismatch'\n | 'invalid_payload';\n\nexport type BridgeDiagnostic =\n | ({ direction: 'send' | 'receive' } & BridgeMessageMetadata)\n | { direction: 'drop'; type?: string; reason: BridgeDropReason };\n\nconst byWire = new Map<string, BridgeEventName>();\nfor (const name of Object.keys(bridgeProtocol.events) as BridgeEventName[]) {\n const wire = bridgeProtocol.events[name].wire;\n if (byWire.has(wire)) throw new Error(`Duplicate bridge event: ${wire}`);\n byWire.set(wire, name);\n}\n\nexport function bridgeEventName(wire: string) {\n return byWire.get(wire);\n}\n\n/** Envelope parsing precedes authentication; event-specific fields remain untrusted. */\nexport function parseBridgeEnvelope(\n value: unknown\n): (BridgeEnvelope & Fields & { type: string }) | undefined {\n if (!value || typeof value !== 'object') return;\n const fields = value as Fields;\n if (\n fields.channel !== BRIDGE ||\n fields.version !== bridgeProtocol.version ||\n typeof fields.type !== 'string' ||\n typeof fields.documentId !== 'string' ||\n !fields.documentId ||\n fields.documentId.length > 128 ||\n (fields.sessionId !== undefined && !validId(fields.sessionId)) ||\n (fields.token !== undefined && typeof fields.token !== 'string')\n )\n return;\n return fields as BridgeEnvelope & Fields & { type: string };\n}\n\n/** Project event fields after the caller has checked envelope eligibility. */\nexport function parseBridgePayload(\n envelope: NonNullable<ReturnType<typeof parseBridgeEnvelope>>,\n definition: Events[BridgeEventName]\n): BridgeMessage | undefined {\n try {\n return {\n channel: BRIDGE,\n version: bridgeProtocol.version,\n documentId: envelope.documentId,\n ...(envelope.sessionId === undefined\n ? {}\n : { sessionId: envelope.sessionId }),\n ...(envelope.token === undefined ? {} : { token: envelope.token }),\n type: definition.wire,\n ...definition.parse(envelope),\n } as BridgeMessage;\n } catch {\n return;\n }\n}\n\nexport function parseBridgeMessage(value: unknown): BridgeMessage | undefined {\n const envelope = parseBridgeEnvelope(value);\n if (!envelope) return;\n const name = bridgeEventName(envelope.type);\n if (!name) return;\n const definition = bridgeProtocol.events[name];\n if (definition.session !== 'none' && envelope.sessionId === undefined) return;\n return parseBridgePayload(envelope, definition);\n}\n","import {\n bridgeProtocol,\n bridgeEventName,\n bridgeMessageMetadata,\n parseBridgeEnvelope,\n parseBridgeMessage,\n parseBridgePayload,\n validId,\n type BridgeDiagnostic,\n type BridgeDropReason,\n type BridgeMessage,\n type BridgeRole,\n type BridgeEventsFrom,\n type BridgePayload,\n type BridgeEnvelope,\n type BridgeHandlers,\n} from './bridge.ts';\nimport { isRecord } from './record.ts';\n\ntype ConnectionContext = Pick<BridgeEnvelope, 'sessionId' | 'token'> & {\n documentId?: string;\n};\n\n/** The connection owns IDs and token rotation; callers can only supply event payloads. */\nexport function createBridgeEndpoint<const Role extends BridgeRole>({\n role,\n origin,\n source,\n opaque,\n context,\n post,\n diagnostic,\n invalidRequest,\n handlers,\n}: {\n role: Role;\n handlers: BridgeHandlers<NoInfer<Role>>;\n origin: string;\n source: () => MessageEventSource | null;\n opaque: boolean;\n context: () => ConnectionContext;\n post: (message: BridgeMessage) => void;\n diagnostic?: (event: BridgeDiagnostic) => void;\n invalidRequest?: (id: string) => void;\n}) {\n let disposed = false;\n\n function drop(reason: BridgeDropReason, type: unknown) {\n diagnostic?.({\n direction: 'drop',\n reason,\n ...(typeof type === 'string' ? { type: type.slice(0, 64) } : {}),\n });\n }\n\n function send<\n Name extends BridgeEventsFrom<Role>,\n const Payload extends BridgePayload<NoInfer<Name>>,\n >(\n name: Name,\n payload: Payload &\n Record<Exclude<keyof Payload, keyof BridgePayload<NoInfer<Name>>>, never>\n ) {\n if (disposed) throw new Error('The bridge endpoint has closed.');\n const definition = bridgeProtocol.events[name];\n const current = context();\n const message = parseBridgeMessage({\n ...payload,\n channel: bridgeProtocol.channel,\n version: bridgeProtocol.version,\n type: definition.wire,\n documentId: name === 'connect' ? 'host' : current.documentId,\n sessionId: current.sessionId,\n token: opaque ? current.token : undefined,\n });\n if (!message || (opaque && !validId(current.token)))\n throw new Error('The bridge is not ready to send this event.');\n diagnostic?.({ direction: 'send', ...bridgeMessageMetadata(message) });\n if (disposed) return;\n post(message);\n }\n\n function receive(event: MessageEvent) {\n const peer = source();\n if (disposed || !peer || event.origin !== origin || event.source !== peer)\n return;\n const envelope = parseBridgeEnvelope(event.data);\n if (!envelope) {\n const data: unknown = event.data;\n if (isRecord(data) && data.channel === bridgeProtocol.channel)\n drop('invalid_envelope', 'type' in data ? data.type : undefined);\n return;\n }\n const current = context();\n // The app learns its opaque token from a trusted host connect message.\n const connecting =\n role === 'app' && envelope.type === bridgeProtocol.events.connect.wire;\n if (\n opaque &&\n (connecting\n ? !validId(envelope.token)\n : !current.token || envelope.token !== current.token)\n )\n return drop('token_mismatch', envelope.type);\n const name = bridgeEventName(envelope.type);\n if (!name) return drop('unexpected_type', envelope.type);\n const definition = bridgeProtocol.events[name];\n if (definition.from === role) return drop('unexpected_type', envelope.type);\n if (definition.session === 'establish') {\n if (\n envelope.documentId !== current.documentId ||\n envelope.sessionId === undefined\n )\n return drop('session_mismatch', envelope.type);\n } else if (definition.session === 'current') {\n if (\n !current.sessionId ||\n envelope.sessionId !== current.sessionId ||\n envelope.documentId !== current.documentId\n )\n return drop('session_mismatch', envelope.type);\n }\n const message = parseBridgePayload(envelope, definition);\n if (!message) {\n drop('invalid_payload', envelope.type);\n if (role === 'host' && name === 'request' && validId(envelope.id))\n invalidRequest?.(envelope.id);\n return;\n }\n diagnostic?.({ direction: 'receive', ...bridgeMessageMetadata(message) });\n if (disposed) return;\n // The catalog lookup correlates the key and parsed discriminated message.\n const handler = (handlers as Record<string, (message: unknown) => void>)[\n name\n ]!;\n handler(message);\n }\n\n return {\n send,\n receive,\n dispose() {\n disposed = true;\n },\n };\n}\n","import {\n isAnnotationPresentation,\n type DataAppAnnotationPresentation,\n} from './annotations.ts';\nimport { type Theme } from './appearance.ts';\n\n/** Presentation owned by the parent shell, delivered only over a trusted bridge. */\nexport type DataAppPresentation = {\n surface: 'embedded' | 'standalone';\n theme: Theme;\n annotations?: DataAppAnnotationPresentation;\n /** `frame` (default): the parent sizes the iframe and the app scrolls inside it.\n * `content`: the iframe follows the app's content height and the parent page scrolls. */\n sizing?: 'frame' | 'content';\n};\n\nexport function isDataAppPresentation(\n value: unknown\n): value is DataAppPresentation {\n if (!value || typeof value !== 'object') return false;\n const presentation = value as DataAppPresentation;\n\n return (\n (presentation.surface === 'embedded' ||\n presentation.surface === 'standalone') &&\n (presentation.theme === 'light' || presentation.theme === 'dark') &&\n (presentation.annotations === undefined ||\n isAnnotationPresentation(presentation.annotations)) &&\n (presentation.sizing === undefined ||\n presentation.sizing === 'frame' ||\n presentation.sizing === 'content')\n );\n}\n","import { isDataAppPresentation } from '../core/presentation.ts';\nimport { isRecord } from '../core/record.ts';\n\n/** Reports the document height to a parent that sizes the iframe to its content.\n * Sizing applies only while the parent requests it and a UI owner whose styles support it\n * has opted in, so older app styles under a newer bootstrap stay frame-sized.\n * The root attribute and inset properties let fixed overlays stay within the parent's visible area. */\nexport function createFrameSizing(\n document: Document,\n report: (height: number) => void\n) {\n const root = document.documentElement;\n const frame = document.defaultView;\n let observer: ResizeObserver | undefined;\n let reported: number | undefined;\n let requested = false;\n let owners = 0;\n let viewport: { top: number; bottom: number } | undefined;\n\n function measure() {\n const height = Math.ceil(root.getBoundingClientRect().height);\n // A matching viewport acknowledges convergence after the parent resized us.\n // Resend it even if the content did not change, so independent updates do\n // not accumulate as one feedback loop in the host.\n if (height === reported && height !== frame?.innerHeight) return;\n reported = height;\n report(height);\n }\n\n function stop() {\n observer?.disconnect();\n observer = undefined;\n frame?.removeEventListener('resize', measure);\n reported = undefined;\n delete root.dataset.atblFrameSizing;\n root.style.removeProperty('--atbl-frame-inset-top');\n root.style.removeProperty('--atbl-frame-inset-bottom');\n }\n\n function applyViewport() {\n if (!observer || !viewport) return;\n root.style.setProperty('--atbl-frame-inset-top', `${viewport.top}px`);\n root.style.setProperty('--atbl-frame-inset-bottom', `${viewport.bottom}px`);\n }\n\n function sync() {\n if (!requested || !owners) return stop();\n if (observer) return;\n root.dataset.atblFrameSizing = 'content';\n observer = new (document.defaultView ?? globalThis).ResizeObserver(measure);\n observer.observe(root);\n frame?.addEventListener('resize', measure);\n applyViewport();\n }\n\n return {\n /** A new session starts with a parent that has not received the current height. */\n update(state: unknown, session: 'new' | 'current') {\n const presentation = isRecord(state) ? state.presentation : undefined;\n requested =\n isDataAppPresentation(presentation) &&\n presentation.sizing === 'content';\n if (!requested) viewport = undefined;\n if (session === 'new') reported = undefined;\n if (observer && requested) measure();\n sync();\n },\n support() {\n owners++;\n sync();\n let released = false;\n\n return () => {\n if (released) return;\n released = true;\n owners--;\n sync();\n };\n },\n viewport(top: number, bottom: number) {\n if (!requested) return;\n viewport = { top, bottom };\n applyViewport();\n },\n dispose() {\n requested = false;\n viewport = undefined;\n owners = 0;\n stop();\n },\n };\n}\n","import { type BridgeDiagnostic } from '../core/bridge.ts';\nimport { type DataAppLogger, type LogEntry } from '../core/logger.ts';\n\n/** Lazy arguments run in the iframe; only resolved values cross the bridge. */\nexport function createBridgeLogger(\n enabled: () => boolean,\n send: (entry: LogEntry) => void\n): DataAppLogger {\n function resolve(args: unknown[]): unknown[] {\n if (args.length === 1 && typeof args[0] === 'function') {\n const value: unknown = args[0]();\n return Array.isArray(value) ? value : [value];\n }\n return args.map(arg => (typeof arg === 'function' ? arg() : arg));\n }\n\n function write(method: keyof DataAppLogger, args: unknown[]) {\n if (!enabled()) return;\n try {\n send({ method, args: resolve(args) });\n } catch {\n // Logging must not interrupt the app or recursively log delivery failures.\n }\n }\n\n return {\n log: (...args) => write('log', args),\n info: (...args) => write('info', args),\n warn: (...args) => write('warn', args),\n error: (...args) => write('error', args),\n };\n}\n\nconst diagnosticLabels = {\n send: 'Sending message to parent',\n receive: 'Received message from parent',\n drop: 'Ignored message from parent',\n} as const;\n\n/** Log only delivery metadata; payloads and session credentials stay private. */\nexport function logBridgeDiagnostic(\n logger: DataAppLogger,\n { direction, ...metadata }: BridgeDiagnostic\n) {\n // Log delivery and per-frame sizing messages would flood the host logger.\n if (\n metadata.type === 'runtime:log' ||\n metadata.type === 'runtime:resize' ||\n metadata.type === 'viewport:update'\n )\n return;\n logger.log(diagnosticLabels[direction], metadata);\n}\n\n/** Error instances do not survive every logger, so only their text crosses the bridge. */\nexport function describeError(error: unknown) {\n if (error instanceof Error)\n return {\n name: error.name,\n message: error.message,\n ...(error.stack ? { stack: error.stack } : {}),\n };\n return { message: String(error) };\n}\n","import {\n MessageRoutingError,\n type MessageInput,\n type MessageOutput,\n type MessageRoutes,\n type MessageTransport,\n} from '../core/messages.ts';\n\n/** Both ends validate using the same contracts; the transport owns delivery and cancellation. */\nexport function createMessageClient<const Routes extends MessageRoutes>(\n routes: Routes,\n transport: MessageTransport\n) {\n return {\n async request<\n Name extends keyof Routes & string,\n const Input extends MessageInput<NoInfer<Routes[Name]>>,\n >(\n route: Name,\n payload: Input,\n { signal }: { signal?: AbortSignal } = {}\n ): Promise<MessageOutput<Routes[Name], Input>> {\n signal?.throwIfAborted();\n if (!Object.hasOwn(routes, route))\n throw new MessageRoutingError(\n 'unknown_route',\n 'Unknown message route.'\n );\n const contract = routes[route]!;\n let input: unknown;\n try {\n input = contract.input(payload);\n } catch {\n throw new MessageRoutingError(\n 'invalid_payload',\n 'Invalid message payload.'\n );\n }\n const response = await transport({ route, payload: input }, signal);\n signal?.throwIfAborted();\n try {\n return contract.output(response, input as never) as MessageOutput<\n Routes[Name],\n Input\n >;\n } catch (error) {\n if (error instanceof MessageRoutingError) throw error;\n throw new MessageRoutingError(\n 'invalid_response',\n 'Invalid message response.'\n );\n }\n },\n };\n}\n","// A bootstrap and its app may bundle independent copies in the same window.\nconst errorBrand = Symbol.for('@altertable/data-app/DataAppError');\n\nexport class DataAppError extends Error {\n readonly [errorBrand] = true;\n\n static override [Symbol.hasInstance](value: unknown): boolean {\n return (\n value instanceof Error &&\n (value as { [errorBrand]?: unknown })[errorBrand] === true\n );\n }\n\n constructor(\n message: string,\n public readonly code: string,\n public readonly requestId?: string\n ) {\n super(message);\n this.name = 'DataAppError';\n }\n}\n","import { type DataAppAction, type DataAppActions } from '../core/actions.ts';\nimport { createBridgeEndpoint } from '../core/bridge-endpoint.ts';\nimport {\n PARENT_PARAM,\n MAX_PENDING,\n REQUEST_TIMEOUT_MS,\n} from '../core/bridge.ts';\nimport { type HostedLakehouse } from '../core/contract.ts';\nimport {\n registeredQueryRoute,\n MessageRoutingError,\n type RoutedMessage,\n} from '../core/messages.ts';\nimport { isRecord } from '../core/record.ts';\nimport { randomUuid } from '../core/uuid.ts';\nimport { appDiagnostics } from './diagnostics.ts';\nimport { createFrameSizing } from './frame-sizing.ts';\nimport {\n createBridgeLogger,\n describeError,\n logBridgeDiagnostic,\n} from './logger.ts';\nimport { createMessageClient } from './messages.ts';\nimport { DataAppError } from './transport.ts';\n\ntype Pending = {\n start: () => void;\n reject: (error: unknown) => void;\n resolve: (value: unknown) => void;\n};\n\n/** Data clients expose one error type for HTTP and message delivery. */\nfunction rethrowDataMessageError(error: unknown): never {\n if (error instanceof MessageRoutingError)\n throw new DataAppError(error.message, error.code, error.requestId);\n throw error;\n}\n\n/** One bridge per document, shared by all clients and retained across module hot replacement. */\nexport function createIframeTransport({\n parentOrigin,\n window: frame = window,\n timeoutMs = REQUEST_TIMEOUT_MS,\n mode = 'url',\n loadScript,\n}: {\n parentOrigin: string;\n window?: Window;\n timeoutMs?: number;\n mode?: 'url' | 'bundle';\n loadScript?: (javascript: string) => void;\n}) {\n if (new URL(parentOrigin).origin !== parentOrigin)\n throw new Error('Expected an exact parent origin.');\n const documentId = randomUuid();\n let token: string | undefined;\n let sessionId: string | undefined;\n let disposed = false;\n const pending = new Map<string, Pending>();\n let hostState: unknown;\n let diagnosticsWaiting = false;\n let diagnosticTimer: ReturnType<typeof setTimeout> | undefined;\n const unsubscribeDiagnostics = appDiagnostics.subscribe(scheduleDiagnostics);\n function scheduleDiagnostics() {\n clearTimeout(diagnosticTimer);\n diagnosticTimer = setTimeout(() => {\n if (\n !hostState ||\n typeof hostState !== 'object' ||\n !('repair' in hostState) ||\n typeof hostState.repair !== 'string'\n )\n return;\n if (pending.size >= MAX_PENDING) {\n diagnosticsWaiting = true;\n return;\n }\n diagnosticsWaiting = false;\n if (!disposed && sessionId)\n void requestMessage({\n route: 'diagnostics:report',\n payload: appDiagnostics.snapshot(),\n }).catch(() => {});\n }, 150);\n }\n const stateListeners = new Set<(state: unknown) => void>();\n // The page actions last offered to the host, compared by value.\n let actions: DataAppActions = {};\n let actionsIdentity = '{}';\n const actionListeners = new Set<(action: DataAppAction) => void>();\n const logger = createBridgeLogger(\n () =>\n !disposed &&\n !!sessionId &&\n isRecord(hostState) &&\n hostState.logging === true,\n entry => send('runtimeLog', { payload: entry })\n );\n\n const endpoint = createBridgeEndpoint({\n role: 'app',\n origin: parentOrigin,\n source: () => frame.parent,\n opaque: mode === 'bundle',\n context: () => ({ documentId, sessionId, token }),\n post(message) {\n frame.parent.postMessage(message, parentOrigin);\n },\n diagnostic: event => logBridgeDiagnostic(logger, event),\n handlers: {\n connect(message) {\n if (mode === 'bundle') token = message.token;\n send('ready', {});\n },\n initialize(message) {\n if (sessionId && sessionId !== message.sessionId) {\n if (pending.size)\n logger.warn('Preview reconnected; rejecting pending requests', {\n count: pending.size,\n });\n for (const entry of pending.values())\n entry.reject(\n new DataAppError(\n 'The preview reconnected. Retry the request.',\n 'bridge_reset'\n )\n );\n }\n const first = !sessionId;\n sessionId = message.sessionId;\n receiveState(message.state, 'new');\n if (first) for (const entry of pending.values()) entry.start();\n if (disposed) return;\n if (actionsIdentity !== '{}') send('actionsUpdate', { actions });\n if (mode === 'url') send('runtimeReady', {});\n },\n stateUpdate(message) {\n receiveState(message.state, 'current');\n },\n actionRun(message) {\n for (const listener of actionListeners) listener(message.action);\n },\n viewportUpdate(message) {\n frameSizing.viewport(message.top, message.bottom);\n },\n scriptLoad(message) {\n if (mode === 'bundle') loadScript?.(message.javascript);\n },\n result(message) {\n pending.get(message.id)?.resolve(message.response);\n },\n error(message) {\n pending\n .get(message.id)\n ?.reject(\n new MessageRoutingError(\n message.code,\n message.message,\n message.requestId\n )\n );\n },\n },\n });\n const send = endpoint.send;\n const receive = endpoint.receive;\n const frameSizing = createFrameSizing(frame.document, height => {\n if (!disposed && sessionId) send('runtimeResize', { height });\n });\n\n function receiveState(state: unknown, session: 'new' | 'current') {\n if (session === 'new') scheduleDiagnostics();\n hostState = state;\n frameSizing.update(state, session);\n for (const listener of stateListeners) listener(state);\n }\n\n frame.addEventListener('message', receive);\n\n function requestMessage(\n message: RoutedMessage,\n signal?: AbortSignal\n ): Promise<unknown> {\n return new Promise((resolve, reject) => {\n if (disposed)\n return reject(\n new DataAppError('The preview has closed.', 'bridge_closed')\n );\n if (signal?.aborted) return reject(signal.reason);\n if (pending.size >= MAX_PENDING)\n return reject(\n new DataAppError('Too many pending data requests.', 'bridge_busy')\n );\n const id = randomUuid();\n let sent = false;\n\n function cleanup() {\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n pending.delete(id);\n if (diagnosticsWaiting) scheduleDiagnostics();\n }\n\n function abort() {\n if (sent) send('cancel', { id });\n cleanup();\n reject(signal?.reason);\n }\n\n const timer = setTimeout(() => {\n logger.warn('Message request timed out', {\n id,\n route: message.route,\n timeoutMs,\n sent,\n });\n if (sent) send('cancel', { id });\n cleanup();\n reject(\n new DataAppError(\n sessionId\n ? 'The data request timed out.'\n : 'The preview shell is unavailable. Reload the preview.',\n sessionId ? 'timeout' : 'bridge_unavailable'\n )\n );\n }, timeoutMs);\n const entry: Pending = {\n start() {\n if (sent) return;\n try {\n send('request', {\n id,\n route: message.route,\n payload: message.payload,\n });\n sent = true;\n } catch {\n cleanup();\n reject(\n new DataAppError(\n 'The message payload could not be sent.',\n 'invalid_payload'\n )\n );\n }\n },\n resolve(value) {\n cleanup();\n resolve(value);\n },\n reject(error) {\n cleanup();\n reject(error);\n },\n };\n pending.set(id, entry);\n signal?.addEventListener('abort', abort, { once: true });\n if (sessionId) entry.start();\n else if (mode === 'url' || token) send('ready', {});\n });\n }\n\n const messages = createMessageClient(\n {\n 'data:query': registeredQueryRoute,\n },\n requestMessage\n );\n\n function disconnect() {\n if (sessionId) send('disconnect', {});\n sessionId = undefined;\n for (const entry of pending.values())\n entry.reject(\n new DataAppError('The preview has closed.', 'bridge_closed')\n );\n }\n\n function resume(event: PageTransitionEvent) {\n if (event.persisted && (mode === 'url' || token)) send('ready', {});\n }\n\n function dispose() {\n if (disposed) return;\n disconnect();\n disposed = true;\n clearTimeout(diagnosticTimer);\n unsubscribeDiagnostics();\n endpoint.dispose();\n frameSizing.dispose();\n frame.removeEventListener('message', receive);\n frame.removeEventListener('pagehide', disconnect);\n frame.removeEventListener('pageshow', resume);\n stateListeners.clear();\n actionListeners.clear();\n }\n\n frame.addEventListener('pagehide', disconnect);\n frame.addEventListener('pageshow', resume);\n if (mode === 'url') send('ready', {});\n\n return {\n diagnostics: appDiagnostics,\n logger,\n request: requestMessage,\n lakehouse: {\n queryAllById(queryId, { limit, signal, params }) {\n return messages\n .request(\n 'data:query',\n {\n queryId,\n limit,\n ...(params === undefined ? {} : { params }),\n },\n { signal }\n )\n .catch(rethrowDataMessageError);\n },\n } satisfies HostedLakehouse,\n dispose,\n mode,\n snapshot() {\n return hostState;\n },\n subscribe(listener: (state: unknown) => void) {\n stateListeners.add(listener);\n\n return () => {\n stateListeners.delete(listener);\n };\n },\n ready() {\n if (!disposed && sessionId) send('runtimeReady', {});\n },\n /** Offers page actions to the host, replacing the previous set; `{}` withdraws them.\n * Unchanged sets are not resent, so callers can report their latest set on every render.\n * The current set is resent when the host reconnects. */\n setActions(value: DataAppActions) {\n const identity = JSON.stringify(value);\n if (disposed || identity === actionsIdentity) return;\n actions = value;\n actionsIdentity = identity;\n if (sessionId) send('actionsUpdate', { actions });\n },\n /** Receives host requests to run offered page actions. */\n onAction(listener: (action: DataAppAction) => void) {\n actionListeners.add(listener);\n\n return () => {\n actionListeners.delete(listener);\n };\n },\n /** The UI owner calls this once its styles support content sizing; the parent's\n * `sizing: 'content'` presentation then applies until the returned release runs. */\n supportContentSizing() {\n return frameSizing.support();\n },\n /** Reports a fatal app failure; the cause reaches the host logger only. */\n fail(cause?: unknown) {\n if (disposed || !sessionId) return;\n appDiagnostics.record('render', 'App startup', cause);\n if (cause !== undefined)\n logger.error(() => ['Data app failed', describeError(cause)]);\n send('runtimeError', {});\n },\n };\n}\n\nexport type IframeTransport = ReturnType<typeof createIframeTransport>;\n\nconst bridgeKey = Symbol.for('altertable.localFrameBridge');\nconst installedKey = Symbol.for('altertable.installedTransport');\ntype LocalBridge = Partial<Pick<IframeTransport, 'request'>> & {\n connect?: () => Promise<IframeTransport>;\n};\ntype FrameWindow = Window & {\n [bridgeKey]?: LocalBridge;\n [installedKey]?: ReturnType<typeof createIframeTransport>;\n};\n\n/** The URL opts into local preview; only same-origin server configuration establishes trust. */\nexport function localFrameBridge(window?: Window): LocalBridge | undefined {\n const activeWindow =\n window ??\n (typeof globalThis.window === 'undefined' ? undefined : globalThis.window);\n if (!activeWindow) return undefined;\n const frame = activeWindow as FrameWindow;\n if (frame[bridgeKey]) return frame[bridgeKey];\n const parentOrigin =\n new URL(frame.location.href).searchParams.get(PARENT_PARAM) ?? '';\n if (!parentOrigin) return undefined;\n\n async function connect(parentOrigin: string) {\n try {\n const response = await frame.fetch('/__altertable/parent', {\n signal: AbortSignal.timeout(5000),\n });\n const config = (await response.json()) as { origin?: unknown };\n if (\n !response.ok ||\n config.origin !== parentOrigin ||\n frame.parent === frame\n )\n throw new Error('Invalid local parent configuration.');\n // Another owner can install a trusted bridge while configuration is pending.\n if (frame[installedKey]) return frame[installedKey];\n if (frame[bridgeKey] !== proxy)\n throw new Error('Preview transport owner changed.');\n const bridge = createIframeTransport({ parentOrigin, window: frame });\n frame[bridgeKey] = bridge;\n frame[installedKey] = bridge;\n\n return bridge;\n } catch {\n throw new DataAppError(\n 'The preview shell could not be verified. Open the URL printed by altertable app dev.',\n 'bridge_unavailable'\n );\n }\n }\n\n let connection: Promise<ReturnType<typeof createIframeTransport>> | undefined;\n\n function getConnection() {\n const installed = frame[installedKey];\n if (installed) return Promise.resolve(installed);\n if (!connection) {\n const attempt = connect(parentOrigin);\n connection = attempt;\n // Clear only this failed attempt; retained proxy references can explicitly retry.\n void attempt.catch(() => {\n if (connection === attempt) connection = undefined;\n });\n }\n\n return connection;\n }\n\n const proxy: LocalBridge = { connect: getConnection };\n frame[bridgeKey] = proxy;\n // Static mounting still verifies eagerly, without an unhandled rejection.\n void getConnection().catch(() => {});\n\n return proxy;\n}\n\n/** Install an explicitly trusted transport for hosted apps and their URL-backed controls. */\nexport function installDataAppTransport(\n bridge: ReturnType<typeof createIframeTransport>,\n frame: Window = window\n) {\n const target = frame as FrameWindow;\n if (target[installedKey])\n throw new Error('A data app transport is already installed.');\n target[bridgeKey] = bridge;\n target[installedKey] = bridge;\n\n return () => {\n if (target[bridgeKey] === bridge) delete target[bridgeKey];\n if (target[installedKey] === bridge) delete target[installedKey];\n bridge.dispose();\n };\n}\n\n/** The bootstrap installs this before executing app code. URL apps can install an explicit connection. */\nexport function getDataAppTransport(frame: Window = window) {\n return (frame as FrameWindow)[installedKey];\n}\n","import {\n appFailure,\n type AppFailure,\n type AppDiagnosticReport,\n} from '../core/diagnostics.ts';\nimport { getDataAppTransport } from './iframe.ts';\n\nconst listeners = new Set<() => void>();\nconst failures = new Map<string, AppFailure>();\nlet pending = 0;\nfunction publish() {\n for (const listener of listeners) listener();\n}\n\n/** Lightweight live observations only. No query values or result rows are retained. */\ntype Diagnostics = {\n snapshot: () => AppDiagnosticReport;\n subscribe: (listener: () => void) => () => void;\n record: (\n kind: AppFailure['kind'],\n name: string,\n error: unknown,\n identity?: string\n ) => void;\n clear: (kind: AppFailure['kind'], name: string, identity?: string) => void;\n begin: () => () => void;\n};\nfunction installed(): Diagnostics | undefined {\n const diagnostics =\n typeof window === 'undefined'\n ? undefined\n : getDataAppTransport()?.diagnostics;\n return diagnostics !== appDiagnostics ? diagnostics : undefined;\n}\nexport const appDiagnostics: Diagnostics = {\n snapshot(): AppDiagnosticReport {\n if (installed()) return installed()!.snapshot();\n const observed: AppFailure[] = [];\n for (const failure of failures.values()) {\n observed.push(failure);\n if (observed.length === 30) break;\n }\n return {\n failures: observed,\n pending,\n truncated: Math.max(0, failures.size - 30),\n };\n },\n subscribe(listener: () => void) {\n if (installed()) return installed()!.subscribe(listener);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n record(\n kind: AppFailure['kind'],\n name: string,\n error: unknown,\n identity?: string\n ) {\n if (installed()) return installed()!.record(kind, name, error, identity);\n const failure = appFailure(kind, name, error);\n if (identity) failure.id = identity;\n const key = `${kind}:${identity ?? name}`;\n // Retain active failures until cleared; bound messages and outgoing reports.\n failures.set(key, failure);\n publish();\n },\n clear(kind: AppFailure['kind'], name: string, identity?: string) {\n if (installed()) return installed()!.clear(kind, name, identity);\n if (failures.delete(`${kind}:${identity ?? name}`)) publish();\n },\n begin() {\n if (installed()) return installed()!.begin();\n pending++;\n publish();\n return () => {\n pending--;\n publish();\n };\n },\n};\n"],"mappings":";;;;AAsBA,eAAsB,qBACpB,WACA,OACA,EACE,eACA,WACA,QAAQ,eACR,WACA,aACA,WAEF;CACA,cAAc,eAAe;CAC7B,IAAI;CACJ,IAAI;EACF,QAAQ,UAAU,MAAM,KAAK;CAC/B,QAAQ;EACN,MAAM,IAAI,oBAAoB;CAChC;CAEA,MAAM,SAAS,YAAY,IAAI,CAC7B,eACA,YAAY,QAAQ,UAAU,OAAO,aAAa,CACpD,CAAC;CACD,MAAM,YAAY,yBAChB,WACA,WACA,QACA,eACA,OACF;CACA,IAAI;EAMF,MAAM,OAA+B;GACnC,MAAM,MANa,aAAa,WAAW,OAAO;IAClD,WAAW,UAAU;IACrB;IACA;GACF,CAAC;GAGC;GACA,4BAAW,IAAI,KAAK,EAAA,CAA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AU,OAAO,QAAQ;EAC3B;CACF;CACA,OACE,MACA,MACA,OACA,UACA;EACA,IAAI,UAAU,GAAG,OAAO,UAAU,CAAC,CAAE,OAAO,MAAM,MAAM,OAAO,QAAQ;EACvE,MAAM,UAAU,WAAW,MAAM,MAAM,KAAK;EAC5C,IAAI,UAAU,QAAQ,KAAK;EAC3B,MAAM,MAAM,GAAG,KAAK,GAAG,YAAY;EAEnC,SAAS,IAAI,KAAK,OAAO;EACzB,QAAQ;CACV;CACA,MAAM,MAA0B,MAAc,UAAmB;EAC/D,IAAI,UAAU,GAAG,OAAO,UAAU,CAAC,CAAE,MAAM,MAAM,MAAM,QAAQ;EAC/D,IAAI,SAAS,OAAO,GAAG,KAAK,GAAG,YAAY,MAAM,GAAG,QAAQ;CAC9D;CACA,QAAQ;EACN,IAAI,UAAU,GAAG,OAAO,UAAU,CAAC,CAAE,MAAM;EAC3C;EACA,QAAQ;EACR,aAAa;GACX;GACA,QAAQ;EACV;CACF;AACF"}
@@ -1,6 +1,6 @@
1
- import { _ as navigationUpdateRoute, a as annotationDraftRoute, c as annotationSendRoute, f as MessageRoutingError, i as resolveExternalLinkTarget, l as annotationUpdateRoute, n as openExternalLinkRoute, o as annotationEditorStateRoute, s as annotationModeRoute, y as validLocation } from "../chunks/contract-gu1rDsV0.js";
2
- import { a as localFrameBridge, d as PARENT_PARAM, i as installDataAppTransport, n as createIframeTransport, o as DataAppError, r as getDataAppTransport, s as createMessageClient, t as appDiagnostics } from "../chunks/diagnostics-CX9SsU79.js";
3
- import { n as createLocalQueryLakehouse, r as installLocalQueryLakehouse, t as createDataClient } from "../chunks/data-client-BMdL73Ab.js";
1
+ import { _ as navigationUpdateRoute, a as annotationDraftRoute, c as annotationSendRoute, f as MessageRoutingError, i as resolveExternalLinkTarget, l as annotationUpdateRoute, n as openExternalLinkRoute, o as annotationEditorStateRoute, s as annotationModeRoute, y as validLocation } from "../chunks/contract-BTG-BUwW.js";
2
+ import { a as localFrameBridge, d as PARENT_PARAM, i as installDataAppTransport, n as createIframeTransport, o as DataAppError, r as getDataAppTransport, s as createMessageClient, t as appDiagnostics } from "../chunks/diagnostics-BwpM9wGn.js";
3
+ import { n as createLocalQueryLakehouse, r as installLocalQueryLakehouse, t as createDataClient } from "../chunks/data-client-C4Pay-UE.js";
4
4
  //#region src/client/location.ts
5
5
  /** Opaque sandboxes keep app state in memory; URL frames retain their real URL for HMR. */
6
6
  function createAppLocation(frame, virtual, publish) {
@@ -1,5 +1,5 @@
1
- import { $ as snapshotQueries, J as bindDimensionSource, x as defineOperation } from "../chunks/contract-gu1rDsV0.js";
2
- import { t as createDataClient } from "../chunks/data-client-BMdL73Ab.js";
1
+ import { $ as snapshotQueries, J as bindDimensionSource, x as defineOperation } from "../chunks/contract-BTG-BUwW.js";
2
+ import { t as createDataClient } from "../chunks/data-client-C4Pay-UE.js";
3
3
  //#region src/core/config.ts
4
4
  /**
5
5
  * App configuration shared by browser and server.
@@ -31,6 +31,7 @@ function defineDataApp(config) {
31
31
  return Object.freeze({
32
32
  ...config,
33
33
  queries,
34
+ queryNames: Object.freeze(Object.fromEntries(Object.keys(queries).map((name) => [name, name]))),
34
35
  defineDimension(config) {
35
36
  return bindDimensionSource(config, queries);
36
37
  },
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":[],"sources":["../../src/core/config.ts"],"sourcesContent":["/**\n * App configuration shared by browser and server.\n * @module @altertable/data-app\n */\nimport {\n defineOperation,\n type DefinedOperation,\n type FilterOperationDefinition,\n type InputOperationDefinition,\n type WithFilterInput,\n} from '../authoring/contract.ts';\nimport { createDataClient, type DataClient } from '../client/data-client.ts';\nimport type { FilterCollection } from './app-filters.ts';\nimport type { AppearanceOptions } from './appearance.ts';\nimport {\n bindDimensionSource,\n type DimensionSourceConfig,\n type DimensionSourceQueryName,\n type SourceDimensionFilter,\n} from './dimension-source.ts';\nimport type { FilterInput } from './operation-filters.ts';\nimport type { DataOperations } from './operation-types.ts';\nimport {\n snapshotQueries,\n type QueryDefinitions,\n type CheckedQueries,\n type QuerySnapshot,\n} from './queries.ts';\nexport type {\n QueryDefinitions,\n QueryParameterValue,\n QueryParameter,\n QueryValueType,\n QueryField,\n QueryProjections,\n QueryRow,\n} from './queries.ts';\n\nexport type DataAppConfig<Queries extends QueryDefinitions = QueryDefinitions> =\n {\n title: string;\n /** Display labels; scope does not grant data access. */\n scope: { organization: string; environment: string };\n /** Explain what the app helps readers explore. */\n description: string;\n /** Omit to use the standard appearance. */\n appearance?: AppearanceOptions;\n /** Shared date display defaults. Reporting views and individual fields may override the time zone. */\n dateFormatting?: { locale?: string; timeZone?: string };\n /** Named SQL statements with typed parameters and result projections. */\n queries: Queries;\n };\n\nexport type DataAppOperationRegistry<Operations extends DataOperations> =\n Operations & {\n /** Run operations in the browser using its installed query bridge. */\n createDataClient(): DataClient<Operations>;\n };\n\n/** An app declaration with operations bound to its query registry. */\nexport type DataAppDefinition<\n Queries extends QueryDefinitions = QueryDefinitions,\n> = Readonly<Omit<DataAppConfig<Queries>, 'queries'>> & {\n readonly queries: QuerySnapshot<Queries>;\n defineDimension<const Type extends 'string' | 'number'>(\n config: DimensionSourceConfig<Type> & {\n source: { query: DimensionSourceQueryName<Queries, NoInfer<Type>> };\n }\n ): SourceDimensionFilter<{ string: string; number: number }[Type]>;\n /** Parse a destination's own input, such as a record id, and list valid `checks`.\n * Declare `filters` too when it reads the displayed scope. */\n defineOperation<Input, Output, const Filters extends FilterCollection = {}>(\n operation: InputOperationDefinition<Input, Output, Queries, Filters>\n ): DefinedOperation<\n WithFilterInput<Filters, Input>,\n Output,\n Queries,\n keyof Filters extends never ? undefined : Filters\n >;\n /** Declare the filters the operation reads; its input, checks, and views derive from them. */\n defineOperation<\n const Filters extends FilterCollection = {},\n Output = unknown,\n >(\n operation: FilterOperationDefinition<Filters, Output, Queries>\n ): DefinedOperation<FilterInput<Filters>, Output, Queries, Filters>;\n /** Bind a named registry to these queries and derive its client and filters. */\n defineOperations<const Operations extends DataOperations>(\n operations: Operations\n ): DataAppOperationRegistry<Operations>;\n};\n\n/**\n * Define the app's query source of truth while preserving exact query and parameter names.\n * Use `dataApp.defineOperation()` to bind operations to these queries. Pass the app once\n * to `mountDataApp({ app: dataApp, component })` or `<DataAppProvider app={dataApp}>`.\n * The app owns an immutable snapshot of its registry; later input mutations do not change it.\n * This declaration does not execute queries or mount UI. Static apps use `queries: {}`.\n *\n * Declare the app once at module scope using the named import from `@altertable/data-app`.\n * Import aliases are allowed. Prefer a `const` initializer; top-level variable\n * initializers, default exports, and standalone calls are supported.\n * Use literal objects, arrays, strings (including templates without interpolation),\n * finite signed numbers, booleans, and null. Parentheses, `as`, and `satisfies` are\n * allowed. Keep executable composition outside the call; omit spreads, computed keys,\n * references, and callbacks. Extraction reads literals without executing app code.\n * TypeScript and runtime query rules own configuration validation.\n *\n * Statements use DuckDB SQL and bound parameters without SDK-only SQL syntax.\n * Declare each parameter's type and optional defaultValue.\n * Values are scalars or declared datetime ranges, never SQL fragments or identifiers.\n * Host queryParams supply protected values; callers cannot override them.\n */\nexport function defineDataApp<const Queries extends QueryDefinitions>(\n config: DataAppConfig<Queries> & { queries: CheckedQueries<Queries> }\n): DataAppDefinition<Queries> {\n const queries = snapshotQueries<Queries>(config.queries);\n return Object.freeze({\n ...config,\n queries,\n defineDimension<const Type extends 'string' | 'number'>(\n config: DimensionSourceConfig<Type> & {\n source: { query: DimensionSourceQueryName<Queries, NoInfer<Type>> };\n }\n ) {\n return bindDimensionSource<Type>(config, queries);\n },\n defineOperation(operation: object): any {\n return defineOperation({\n ...operation,\n queries: queries as unknown as CheckedQueries<Queries>,\n } as never);\n },\n defineOperations(operations: DataOperations) {\n if (Object.hasOwn(operations, 'createDataClient'))\n throw new Error('Operation name createDataClient is reserved.');\n const registry = {\n ...operations,\n } as DataAppOperationRegistry<DataOperations>;\n Object.setPrototypeOf(registry, {\n createDataClient() {\n return (\n createDataClient as (options: object) => DataClient<DataOperations>\n )({\n operations: registry,\n });\n },\n });\n return Object.freeze(registry);\n },\n }) as unknown as DataAppDefinition<Queries>;\n}\n\nexport function dataAppTitle(\n config: Pick<DataAppConfig, 'title' | 'scope'>\n): string {\n return `${config.title} • ${config.scope.organization}/${config.scope.environment} • Altertable app`;\n}\n\nexport type {\n DateTimeRange,\n AbsoluteOrRelativeDateTime,\n RelativeDateTime,\n RelativeAnchor,\n RelativeOffset,\n RelativeUnit,\n} from './date-time-range.ts';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA,SAAgB,cACd,QAC4B;CAC5B,MAAM,UAAU,gBAAyB,OAAO,OAAO;CACvD,OAAO,OAAO,OAAO;EACnB,GAAG;EACH;EACA,gBACE,QAGA;GACA,OAAO,oBAA0B,QAAQ,OAAO;EAClD;EACA,gBAAgB,WAAwB;GACtC,OAAO,gBAAgB;IACrB,GAAG;IACM;GACX,CAAU;EACZ;EACA,iBAAiB,YAA4B;GAC3C,IAAI,OAAO,OAAO,YAAY,kBAAkB,GAC9C,MAAM,IAAI,MAAM,8CAA8C;GAChE,MAAM,WAAW,EACf,GAAG,WACL;GACA,OAAO,eAAe,UAAU,EAC9B,mBAAmB;IACjB,OACE,iBACA,EACA,YAAY,SACd,CAAC;GACH,EACF,CAAC;GACD,OAAO,OAAO,OAAO,QAAQ;EAC/B;CACF,CAAC;AACH;AAEA,SAAgB,aACd,QACQ;CACR,OAAO,GAAG,OAAO,MAAM,KAAK,OAAO,MAAM,aAAa,GAAG,OAAO,MAAM,YAAY;AACpF"}
1
+ {"version":3,"file":"config.js","names":[],"sources":["../../src/core/config.ts"],"sourcesContent":["/**\n * App configuration shared by browser and server.\n * @module @altertable/data-app\n */\nimport {\n defineOperation,\n type DefinedOperation,\n type FilterOperationDefinition,\n type InputOperationDefinition,\n type WithFilterInput,\n} from '../authoring/contract.ts';\nimport { createDataClient, type DataClient } from '../client/data-client.ts';\nimport type { FilterCollection } from './app-filters.ts';\nimport type { AppearanceOptions } from './appearance.ts';\nimport {\n bindDimensionSource,\n type DimensionSourceConfig,\n type DimensionSourceQueryName,\n type SourceDimensionFilter,\n} from './dimension-source.ts';\nimport type { FilterInput } from './operation-filters.ts';\nimport type { DataOperations } from './operation-types.ts';\nimport {\n snapshotQueries,\n type QueryDefinitions,\n type CheckedQueries,\n type QuerySnapshot,\n} from './queries.ts';\nexport type {\n QueryDefinitions,\n QueryParameterValue,\n QueryParameter,\n QueryValueType,\n QueryField,\n QueryProjections,\n QueryRow,\n} from './queries.ts';\n\nexport type DataAppConfig<Queries extends QueryDefinitions = QueryDefinitions> =\n {\n title: string;\n /** Display labels; scope does not grant data access. */\n scope: { organization: string; environment: string };\n /** Explain what the app helps readers explore. */\n description: string;\n /** Omit to use the standard appearance. */\n appearance?: AppearanceOptions;\n /** Shared date display defaults. Reporting views and individual fields may override the time zone. */\n dateFormatting?: { locale?: string; timeZone?: string };\n /** Named SQL statements with typed parameters and result projections. */\n queries: Queries;\n };\n\nexport type DataAppOperationRegistry<Operations extends DataOperations> =\n Operations & {\n /** Run operations in the browser using its installed query bridge. */\n createDataClient(): DataClient<Operations>;\n };\n\n/** An app declaration with operations bound to its query registry. */\nexport type DataAppDefinition<\n Queries extends QueryDefinitions = QueryDefinitions,\n> = Readonly<Omit<DataAppConfig<Queries>, 'queries'>> & {\n readonly queries: QuerySnapshot<Queries>;\n /** Every registered query name, keyed by itself. Pass it to `createDataContext()`,\n * then cite the queries behind each glossary entry. */\n readonly queryNames: { readonly [Name in keyof Queries & string]: Name };\n defineDimension<const Type extends 'string' | 'number'>(\n config: DimensionSourceConfig<Type> & {\n source: { query: DimensionSourceQueryName<Queries, NoInfer<Type>> };\n }\n ): SourceDimensionFilter<{ string: string; number: number }[Type]>;\n /** Parse a destination's own input, such as a record id, and list valid `checks`.\n * Declare `filters` too when it reads the displayed scope. */\n defineOperation<Input, Output, const Filters extends FilterCollection = {}>(\n operation: InputOperationDefinition<Input, Output, Queries, Filters>\n ): DefinedOperation<\n WithFilterInput<Filters, Input>,\n Output,\n Queries,\n keyof Filters extends never ? undefined : Filters\n >;\n /** Declare the filters the operation reads; its input, checks, and views derive from them. */\n defineOperation<\n const Filters extends FilterCollection = {},\n Output = unknown,\n >(\n operation: FilterOperationDefinition<Filters, Output, Queries>\n ): DefinedOperation<FilterInput<Filters>, Output, Queries, Filters>;\n /** Bind a named registry to these queries and derive its client and filters. */\n defineOperations<const Operations extends DataOperations>(\n operations: Operations\n ): DataAppOperationRegistry<Operations>;\n};\n\n/**\n * Define the app's query source of truth while preserving exact query and parameter names.\n * Use `dataApp.defineOperation()` to bind operations to these queries. Pass the app once\n * to `mountDataApp({ app: dataApp, component })` or `<DataAppProvider app={dataApp}>`.\n * The app owns an immutable snapshot of its registry; later input mutations do not change it.\n * This declaration does not execute queries or mount UI. Static apps use `queries: {}`.\n *\n * Declare the app once at module scope using the named import from `@altertable/data-app`.\n * Import aliases are allowed. Prefer a `const` initializer; top-level variable\n * initializers, default exports, and standalone calls are supported.\n * Use literal objects, arrays, strings (including templates without interpolation),\n * finite signed numbers, booleans, and null. Parentheses, `as`, and `satisfies` are\n * allowed. Keep executable composition outside the call; omit spreads, computed keys,\n * references, and callbacks. Extraction reads literals without executing app code.\n * TypeScript and runtime query rules own configuration validation.\n *\n * Statements use DuckDB SQL and bound parameters without SDK-only SQL syntax.\n * Declare each parameter's type and optional defaultValue.\n * Values are scalars or declared datetime ranges, never SQL fragments or identifiers.\n * Host queryParams supply protected values; callers cannot override them.\n */\nexport function defineDataApp<const Queries extends QueryDefinitions>(\n config: DataAppConfig<Queries> & { queries: CheckedQueries<Queries> }\n): DataAppDefinition<Queries> {\n const queries = snapshotQueries<Queries>(config.queries);\n return Object.freeze({\n ...config,\n queries,\n queryNames: Object.freeze(\n Object.fromEntries(Object.keys(queries).map(name => [name, name]))\n ),\n defineDimension<const Type extends 'string' | 'number'>(\n config: DimensionSourceConfig<Type> & {\n source: { query: DimensionSourceQueryName<Queries, NoInfer<Type>> };\n }\n ) {\n return bindDimensionSource<Type>(config, queries);\n },\n defineOperation(operation: object): any {\n return defineOperation({\n ...operation,\n queries: queries as unknown as CheckedQueries<Queries>,\n } as never);\n },\n defineOperations(operations: DataOperations) {\n if (Object.hasOwn(operations, 'createDataClient'))\n throw new Error('Operation name createDataClient is reserved.');\n const registry = {\n ...operations,\n } as DataAppOperationRegistry<DataOperations>;\n Object.setPrototypeOf(registry, {\n createDataClient() {\n return (\n createDataClient as (options: object) => DataClient<DataOperations>\n )({\n operations: registry,\n });\n },\n });\n return Object.freeze(registry);\n },\n }) as unknown as DataAppDefinition<Queries>;\n}\n\nexport function dataAppTitle(\n config: Pick<DataAppConfig, 'title' | 'scope'>\n): string {\n return `${config.title} • ${config.scope.organization}/${config.scope.environment} • Altertable app`;\n}\n\nexport type {\n DateTimeRange,\n AbsoluteOrRelativeDateTime,\n RelativeDateTime,\n RelativeAnchor,\n RelativeOffset,\n RelativeUnit,\n} from './date-time-range.ts';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoHA,SAAgB,cACd,QAC4B;CAC5B,MAAM,UAAU,gBAAyB,OAAO,OAAO;CACvD,OAAO,OAAO,OAAO;EACnB,GAAG;EACH;EACA,YAAY,OAAO,OACjB,OAAO,YAAY,OAAO,KAAK,OAAO,CAAC,CAAC,KAAI,SAAQ,CAAC,MAAM,IAAI,CAAC,CAAC,CACnE;EACA,gBACE,QAGA;GACA,OAAO,oBAA0B,QAAQ,OAAO;EAClD;EACA,gBAAgB,WAAwB;GACtC,OAAO,gBAAgB;IACrB,GAAG;IACM;GACX,CAAU;EACZ;EACA,iBAAiB,YAA4B;GAC3C,IAAI,OAAO,OAAO,YAAY,kBAAkB,GAC9C,MAAM,IAAI,MAAM,8CAA8C;GAChE,MAAM,WAAW,EACf,GAAG,WACL;GACA,OAAO,eAAe,UAAU,EAC9B,mBAAmB;IACjB,OACE,iBACA,EACA,YAAY,SACd,CAAC;GACH,EACF,CAAC;GACD,OAAO,OAAO,OAAO,QAAQ;EAC/B;CACF,CAAC;AACH;AAEA,SAAgB,aACd,QACQ;CACR,OAAO,GAAG,OAAO,MAAM,KAAK,OAAO,MAAM,aAAa,GAAG,OAAO,MAAM,YAAY;AACpF"}