@loaders.gl/sql 5.0.0-alpha.1 → 5.0.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +14 -3
  2. package/README.md +107 -0
  3. package/dist/arrow-query.cjs +1404 -0
  4. package/dist/arrow-query.cjs.map +6 -0
  5. package/dist/arrow-query.d.ts +5 -0
  6. package/dist/arrow-query.d.ts.map +1 -0
  7. package/dist/arrow-query.js +6 -0
  8. package/dist/arrow-query.js.map +1 -0
  9. package/dist/arrow-table-source.d.ts +27 -0
  10. package/dist/arrow-table-source.d.ts.map +1 -0
  11. package/dist/arrow-table-source.js +79 -0
  12. package/dist/arrow-table-source.js.map +1 -0
  13. package/dist/bind-sql-predicate.d.ts +4 -0
  14. package/dist/bind-sql-predicate.d.ts.map +1 -0
  15. package/dist/bind-sql-predicate.js +11 -0
  16. package/dist/bind-sql-predicate.js.map +1 -0
  17. package/dist/compile-table-query.d.ts +55 -0
  18. package/dist/compile-table-query.d.ts.map +1 -0
  19. package/dist/compile-table-query.js +255 -0
  20. package/dist/compile-table-query.js.map +1 -0
  21. package/dist/duckdb-sql-source.d.ts +51 -3
  22. package/dist/duckdb-sql-source.d.ts.map +1 -1
  23. package/dist/duckdb-sql-source.js +21 -7
  24. package/dist/duckdb-sql-source.js.map +1 -1
  25. package/dist/index.cjs +3352 -37
  26. package/dist/index.cjs.map +3 -4
  27. package/dist/index.d.ts +16 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +9 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/parse-sql-predicate.d.ts +10 -0
  32. package/dist/parse-sql-predicate.d.ts.map +1 -0
  33. package/dist/parse-sql-predicate.js +322 -0
  34. package/dist/parse-sql-predicate.js.map +1 -0
  35. package/dist/query-arrow-table.d.ts +83 -0
  36. package/dist/query-arrow-table.d.ts.map +1 -0
  37. package/dist/query-arrow-table.js +663 -0
  38. package/dist/query-arrow-table.js.map +1 -0
  39. package/dist/snowflake-sql-source.d.ts +51 -3
  40. package/dist/snowflake-sql-source.d.ts.map +1 -1
  41. package/dist/snowflake-sql-source.js +9 -6
  42. package/dist/snowflake-sql-source.js.map +1 -1
  43. package/dist/sql-predicate-schema.d.ts +156 -0
  44. package/dist/sql-predicate-schema.d.ts.map +1 -0
  45. package/dist/sql-predicate-schema.js +226 -0
  46. package/dist/sql-predicate-schema.js.map +1 -0
  47. package/dist/sql-predicate-types.d.ts +45 -0
  48. package/dist/sql-predicate-types.d.ts.map +1 -0
  49. package/dist/sql-predicate-types.js +9 -0
  50. package/dist/sql-predicate-types.js.map +1 -0
  51. package/dist/sql-predicate-zod.cjs +54 -0
  52. package/dist/sql-predicate-zod.cjs.map +6 -0
  53. package/dist/sql-predicate-zod.d.ts +11 -0
  54. package/dist/sql-predicate-zod.d.ts.map +1 -0
  55. package/dist/sql-predicate-zod.js +45 -0
  56. package/dist/sql-predicate-zod.js.map +1 -0
  57. package/dist/sql-predicate.cjs +607 -0
  58. package/dist/sql-predicate.cjs.map +6 -0
  59. package/dist/sql-predicate.d.ts +6 -0
  60. package/dist/sql-predicate.d.ts.map +1 -0
  61. package/dist/sql-predicate.js +8 -0
  62. package/dist/sql-predicate.js.map +1 -0
  63. package/dist/sql-source.d.ts +16 -3
  64. package/dist/sql-source.d.ts.map +1 -1
  65. package/dist/sql-source.js +34 -5
  66. package/dist/sql-source.js.map +1 -1
  67. package/dist/sql-types.d.ts +3 -0
  68. package/dist/sql-types.d.ts.map +1 -1
  69. package/dist/table-query-capabilities.d.ts +6 -0
  70. package/dist/table-query-capabilities.d.ts.map +1 -0
  71. package/dist/table-query-capabilities.js +26 -0
  72. package/dist/table-query-capabilities.js.map +1 -0
  73. package/dist/table-query.cjs +286 -0
  74. package/dist/table-query.cjs.map +6 -0
  75. package/dist/table-query.d.ts +29 -0
  76. package/dist/table-query.d.ts.map +1 -0
  77. package/dist/table-query.js +30 -0
  78. package/dist/table-query.js.map +1 -0
  79. package/package.json +45 -8
  80. package/src/arrow-query.ts +17 -0
  81. package/src/arrow-table-source.ts +111 -0
  82. package/src/bind-sql-predicate.ts +21 -0
  83. package/src/compile-table-query.ts +354 -0
  84. package/src/duckdb-sql-source.ts +30 -6
  85. package/src/index.ts +57 -0
  86. package/src/parse-sql-predicate.ts +381 -0
  87. package/src/query-arrow-table.ts +846 -0
  88. package/src/snowflake-sql-source.ts +8 -5
  89. package/src/sql-predicate-schema.ts +251 -0
  90. package/src/sql-predicate-types.ts +87 -0
  91. package/src/sql-predicate-zod.ts +52 -0
  92. package/src/sql-predicate.ts +28 -0
  93. package/src/sql-source.ts +40 -5
  94. package/src/sql-types.ts +4 -0
  95. package/src/table-query-capabilities.ts +29 -0
  96. package/src/table-query.ts +78 -0
package/dist/index.cjs CHANGED
@@ -28,24 +28,2323 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
30
  // dist/index.js
31
- var dist_exports = {};
32
- __export(dist_exports, {
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ ARROW_TABLE_QUERY_CAPABILITIES: () => ARROW_TABLE_QUERY_CAPABILITIES,
34
+ ArrowTableSource: () => ArrowTableSource,
33
35
  DuckDBSQLDataSource: () => DuckDBSQLDataSource,
34
36
  DuckDBSQLSource: () => DuckDBSQLSource,
35
37
  SQLDataSource: () => SQLDataSource,
38
+ SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES: () => SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES,
39
+ SQL_PREDICATE_JSON_SCHEMA: () => SQL_PREDICATE_JSON_SCHEMA,
36
40
  SnowflakeSQLDataSource: () => SnowflakeSQLDataSource,
37
41
  SnowflakeSQLSource: () => SnowflakeSQLSource,
42
+ bindSQLPredicate: () => bindSQLPredicate,
43
+ compileSQLTableQuery: () => compileSQLTableQuery,
44
+ explainArrowTableQuery: () => explainArrowTableQuery,
45
+ explainTableQuery: () => explainTableQuery2,
38
46
  getSQLAdapterFactory: () => getSQLAdapterFactory,
39
- registerSQLAdapter: () => registerSQLAdapter
47
+ getSQLPredicateColumnNames: () => getSQLPredicateColumnNames,
48
+ isSQLPredicate: () => isSQLPredicate,
49
+ isSQLPredicateParameter: () => isSQLPredicateParameter,
50
+ parseSQLPredicate: () => parseSQLPredicate,
51
+ planTableQuery: () => planTableQuery2,
52
+ queryArrowTable: () => queryArrowTable,
53
+ registerSQLAdapter: () => registerSQLAdapter,
54
+ validateSQLPredicate: () => validateSQLPredicate
40
55
  });
41
- module.exports = __toCommonJS(dist_exports);
56
+ module.exports = __toCommonJS(index_exports);
42
57
 
43
- // dist/sql-source.js
44
- var import_loader_utils = require("@loaders.gl/loader-utils");
58
+ // ../loader-utils/src/lib/log-utils/log.ts
59
+ var import_log = require("@probe.gl/log");
60
+ var VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
61
+ var version = VERSION[0] >= "0" && VERSION[0] <= "9" ? `v${VERSION}` : "";
62
+ function createLog() {
63
+ const log2 = new import_log.Log({ id: "loaders.gl" });
64
+ globalThis.loaders ||= {};
65
+ globalThis.loaders.log = log2;
66
+ globalThis.loaders.version = version;
67
+ globalThis.probe ||= {};
68
+ globalThis.probe.loaders = log2;
69
+ return log2;
70
+ }
71
+ var log = createLog();
72
+
73
+ // ../loader-utils/src/lib/javascript-utils/is-type.ts
74
+ var isObject = (value) => value !== null && typeof value === "object";
75
+ var isPureObject = (value) => isObject(value) && value.constructor === {}.constructor;
76
+
77
+ // ../loader-utils/src/lib/option-utils/merge-options.ts
78
+ function mergeOptions(baseOptions, newOptions) {
79
+ return mergeOptionsRecursively(baseOptions || {}, newOptions);
80
+ }
81
+ function mergeOptionsRecursively(baseOptions, newOptions, level = 0) {
82
+ if (level > 3) {
83
+ return newOptions;
84
+ }
85
+ const options = { ...baseOptions };
86
+ for (const [key, newValue] of Object.entries(newOptions)) {
87
+ if (isPureObject(newValue)) {
88
+ options[key] = mergeOptionsRecursively(
89
+ options[key] || {},
90
+ newOptions[key],
91
+ level + 1
92
+ );
93
+ } else {
94
+ options[key] = newOptions[key];
95
+ }
96
+ }
97
+ return options;
98
+ }
99
+
100
+ // ../loader-utils/src/lib/request-utils/authentication.ts
101
+ function resolveCredentials(credentials, authentications = []) {
102
+ if (credentials.every(isAuthentication)) return credentials;
103
+ return credentials.map((credential, index) => {
104
+ if (isAuthentication(credential)) return credential;
105
+ const AuthenticationClass = authentications.find(
106
+ (authentication2) => authentication2.type === (credential == null ? void 0 : credential.type)
107
+ );
108
+ if (!AuthenticationClass) {
109
+ throw new Error(`No authentication class registered for credential at index ${index}.`);
110
+ }
111
+ let authentication;
112
+ try {
113
+ authentication = new AuthenticationClass(credential);
114
+ } catch {
115
+ throw new Error(`Invalid authentication configuration at index ${index}.`);
116
+ }
117
+ if (!isAuthentication(authentication)) {
118
+ throw new Error(`Authentication class returned an invalid credential at index ${index}.`);
119
+ }
120
+ return authentication;
121
+ });
122
+ }
123
+ function resolveAuthenticationOptions(options) {
124
+ var _a, _b;
125
+ if (!((_b = (_a = options.core) == null ? void 0 : _a.credentials) == null ? void 0 : _b.length)) return options;
126
+ const credentials = resolveCredentials(options.core.credentials, options.core.authentications);
127
+ if (credentials === options.core.credentials) return options;
128
+ return { ...options, core: { ...options.core, credentials } };
129
+ }
130
+ function isAuthentication(credential) {
131
+ if (!credential || typeof credential !== "object") return false;
132
+ if (typeof credential.id !== "string" || !Array.isArray(credential.origins)) return false;
133
+ if (credential.type === "request") return typeof credential.authenticate === "function";
134
+ return (credential.type === "header" || credential.type === "query-parameter") && typeof credential.name === "string" && (typeof credential.token === "string" || typeof credential.token === "function") && Array.isArray(credential.refreshStatusCodes);
135
+ }
136
+
137
+ // ../loader-utils/src/lib/request-utils/request-credentials.ts
138
+ var AUTHENTICATED_FETCH = /* @__PURE__ */ Symbol("loaders.gl.authenticated-fetch");
139
+ var refreshPromises = /* @__PURE__ */ new WeakMap();
140
+ function createAuthenticatedFetch(options) {
141
+ const suppliedFetch = options.fetch || ((url, requestOptions) => fetch(url, requestOptions));
142
+ const existingMetadata = suppliedFetch[AUTHENTICATED_FETCH];
143
+ const credentialResolutions = new Map(existingMetadata == null ? void 0 : existingMetadata.credentialResolutions);
144
+ const resolvedCredentials = resolveCredentials(
145
+ options.credentials.map((credential) => credentialResolutions.get(credential) || credential),
146
+ options.authentications
147
+ );
148
+ options.credentials.forEach((credential, index) => {
149
+ credentialResolutions.set(credential, resolvedCredentials[index]);
150
+ });
151
+ if (!options.fetchOptions && (!resolvedCredentials.length || (existingMetadata == null ? void 0 : existingMetadata.credentials.length) === resolvedCredentials.length && resolvedCredentials.every(
152
+ (credential, index) => credential === existingMetadata.credentials[index]
153
+ )))
154
+ return suppliedFetch;
155
+ const baseFetch = (existingMetadata == null ? void 0 : existingMetadata.fetch) || suppliedFetch;
156
+ const credentials = existingMetadata ? [.../* @__PURE__ */ new Set([...resolvedCredentials, ...existingMetadata.credentials])] : resolvedCredentials;
157
+ const fetchOptions = mergeFetchOptions(
158
+ (existingMetadata == null ? void 0 : existingMetadata.fetchOptions) || {},
159
+ options.fetchOptions
160
+ );
161
+ const tokenCredentials = credentials.filter(
162
+ (credential) => credential.type !== "request"
163
+ );
164
+ const requestCredentials = credentials.filter(
165
+ (credential) => credential.type === "request"
166
+ );
167
+ for (const credential of requestCredentials) normalizeRequestOrigins(credential.origins);
168
+ const authenticatedFetch = async (url, requestOptions = {}) => {
169
+ var _a, _b, _c, _d, _e, _f, _g;
170
+ requestOptions = mergeFetchOptions(fetchOptions, requestOptions);
171
+ if ((_a = requestOptions.signal) == null ? void 0 : _a.aborted) throw createAbortError();
172
+ if (!credentials.length) return baseFetch(url, requestOptions);
173
+ const resolvedURL = parseHTTPURL(url);
174
+ const authorization = resolvedURL ? await authorizeRequest(resolvedURL, requestOptions, tokenCredentials) : { url, options: requestOptions, credentials: [] };
175
+ const signedRequest = await authenticateRequest(authorization, requestCredentials, "request");
176
+ const response = await baseFetch(signedRequest.url, signedRequest.options);
177
+ const refreshableCredentials = [];
178
+ for (const resolvedCredential of authorization.credentials) {
179
+ const { credential } = resolvedCredential;
180
+ if (typeof credential.token === "function" && (isReplayableRequest(requestOptions) || ((_b = credential.canReplayRequest) == null ? void 0 : _b.call(credential, url, requestOptions))) && (isReplayableRequest(signedRequest.options) || ((_c = credential.canReplayRequest) == null ? void 0 : _c.call(credential, signedRequest.url, signedRequest.options))) && (credential.refreshStatusCodes.includes(response.status) || await ((_d = credential.shouldRefresh) == null ? void 0 : _d.call(credential, response))))
181
+ refreshableCredentials.push(resolvedCredential);
182
+ }
183
+ const shouldRetrySignature = isReplayableRequest(requestOptions) && isReplayableRequest(signedRequest.options) && signedRequest.credentials.some(
184
+ (credential) => {
185
+ var _a2;
186
+ return (_a2 = credential.refreshStatusCodes) == null ? void 0 : _a2.includes(response.status);
187
+ }
188
+ );
189
+ if (!refreshableCredentials.length && !shouldRetrySignature) return response;
190
+ if ((_e = requestOptions.signal) == null ? void 0 : _e.aborted) throw createAbortError();
191
+ const refreshedTokens = /* @__PURE__ */ new Map();
192
+ await Promise.all(
193
+ refreshableCredentials.map(async ({ credential }) => {
194
+ const token = await refreshCredential(credential, url, response);
195
+ if (token) refreshedTokens.set(credential, token);
196
+ })
197
+ );
198
+ if (!refreshedTokens.size && !shouldRetrySignature) return response;
199
+ await ((_f = response.body) == null ? void 0 : _f.cancel().catch(() => {
200
+ }));
201
+ if ((_g = requestOptions.signal) == null ? void 0 : _g.aborted) throw createAbortError();
202
+ const replayAuthorization = resolvedURL ? await authorizeRequest(
203
+ resolvedURL,
204
+ requestOptions,
205
+ tokenCredentials,
206
+ refreshedTokens,
207
+ authorization.credentials
208
+ ) : { url, options: requestOptions };
209
+ const replayRequest = await authenticateRequest(
210
+ replayAuthorization,
211
+ requestCredentials,
212
+ "retry",
213
+ response
214
+ );
215
+ return baseFetch(replayRequest.url, replayRequest.options);
216
+ };
217
+ Object.defineProperty(authenticatedFetch, AUTHENTICATED_FETCH, {
218
+ value: {
219
+ fetch: baseFetch,
220
+ credentials,
221
+ credentialResolutions,
222
+ fetchOptions
223
+ }
224
+ });
225
+ return authenticatedFetch;
226
+ }
227
+ function getAuthenticatedFetch(options = {}) {
228
+ var _a, _b, _c;
229
+ const fetchOption = options.fetch ?? ((_a = options.core) == null ? void 0 : _a.fetch);
230
+ let fetchFunction;
231
+ if (typeof fetchOption === "function") {
232
+ fetchFunction = fetchOption;
233
+ } else {
234
+ fetchFunction = (url, requestOptions) => fetch(url, requestOptions);
235
+ }
236
+ return createAuthenticatedFetch({
237
+ fetch: fetchFunction,
238
+ fetchOptions: typeof fetchOption === "object" && fetchOption ? fetchOption : void 0,
239
+ credentials: ((_b = options.core) == null ? void 0 : _b.credentials) || [],
240
+ authentications: (_c = options.core) == null ? void 0 : _c.authentications
241
+ });
242
+ }
243
+ function mergeFetchOptions(defaultOptions, requestOptions) {
244
+ const mergedOptions = { ...defaultOptions, ...requestOptions };
245
+ if (defaultOptions.headers || (requestOptions == null ? void 0 : requestOptions.headers)) {
246
+ const headers = new Headers(defaultOptions.headers);
247
+ new Headers(requestOptions == null ? void 0 : requestOptions.headers).forEach((value, key) => headers.set(key, value));
248
+ mergedOptions.headers = headers;
249
+ }
250
+ return mergedOptions;
251
+ }
252
+ async function authenticateRequest(request, credentials, reason, response) {
253
+ const appliedCredentials = [];
254
+ const signal = request.options.signal;
255
+ for (const credential of credentials) {
256
+ const origin = getRequestOrigin(request.url);
257
+ if (!origin || !normalizeRequestOrigins(credential.origins).includes(origin)) continue;
258
+ if (signal == null ? void 0 : signal.aborted) throw createAbortError();
259
+ const authenticatedRequest = await credential.authenticate({
260
+ url: request.url,
261
+ options: { ...request.options, headers: new Headers(request.options.headers) },
262
+ reason,
263
+ response: response ? { status: response.status, headers: new Headers(response.headers) } : void 0
264
+ });
265
+ if (!authenticatedRequest || typeof authenticatedRequest.url !== "string" || !authenticatedRequest.options || typeof authenticatedRequest.options !== "object") {
266
+ throw new Error("Authentication callback returned an invalid request.");
267
+ }
268
+ request = {
269
+ url: authenticatedRequest.url,
270
+ options: { ...authenticatedRequest.options, ...signal ? { signal } : {} }
271
+ };
272
+ appliedCredentials.push(credential);
273
+ }
274
+ if (signal == null ? void 0 : signal.aborted) throw createAbortError();
275
+ return { ...request, credentials: appliedCredentials };
276
+ }
277
+ function getRequestOrigin(url) {
278
+ try {
279
+ const parsedURL = new URL(url);
280
+ if (!parsedURL.host || parsedURL.username || parsedURL.password) return null;
281
+ return parsedURL.origin !== "null" ? parsedURL.origin : `${parsedURL.protocol}//${parsedURL.host}`;
282
+ } catch {
283
+ return null;
284
+ }
285
+ }
286
+ function normalizeRequestOrigins(origins) {
287
+ if (!origins.length)
288
+ throw new Error("Request authentication requires at least one exact origin.");
289
+ return origins.map((origin) => {
290
+ const resolvedOrigin = getRequestOrigin(origin);
291
+ let url;
292
+ try {
293
+ url = new URL(origin);
294
+ } catch {
295
+ throw new Error("Invalid request authentication origin.");
296
+ }
297
+ if (!resolvedOrigin || url.pathname && url.pathname !== "/" || url.search || url.hash) {
298
+ throw new Error("Invalid request authentication origin.");
299
+ }
300
+ return resolvedOrigin;
301
+ });
302
+ }
303
+ async function authorizeRequest(sourceURL, requestOptions, credentials, tokenOverrides = /* @__PURE__ */ new Map(), previousCredentials = []) {
304
+ const url = new URL(sourceURL);
305
+ const headers = new Headers(requestOptions.headers);
306
+ const resolvedCredentials = [];
307
+ const previousTokens = new Map(
308
+ previousCredentials.map(({ credential, token }) => [credential, token])
309
+ );
310
+ for (const credential of credentials) {
311
+ if (!credential.origins.includes(url.origin)) continue;
312
+ const overrideToken = tokenOverrides.get(credential);
313
+ const previousToken = previousTokens.get(credential);
314
+ const ownsQueryParameter = credential.type === "query-parameter" && previousToken !== void 0;
315
+ const ownsHeader = credential.type === "header" && previousToken !== void 0;
316
+ if (credential.type === "query-parameter" && url.searchParams.has(credential.name) && !ownsQueryParameter || credential.type === "header" && headers.has(credential.name) && !ownsHeader) {
317
+ continue;
318
+ }
319
+ const token = overrideToken ?? previousToken ?? await resolveToken(credential.token, { url: sourceURL.toString(), reason: "request" });
320
+ if (!token) continue;
321
+ if (credential.type === "query-parameter") {
322
+ url.searchParams.set(credential.name, token);
323
+ } else {
324
+ headers.set(credential.name, `${credential.prefix || ""}${token}`);
325
+ }
326
+ resolvedCredentials.push({ credential, token });
327
+ }
328
+ return {
329
+ url: url.toString(),
330
+ options: { ...requestOptions, headers },
331
+ credentials: resolvedCredentials
332
+ };
333
+ }
334
+ async function refreshCredential(credential, url, response) {
335
+ const existingPromise = refreshPromises.get(credential);
336
+ if (existingPromise) return existingPromise;
337
+ const tokenProvider = credential.token;
338
+ const promise = Promise.resolve(
339
+ tokenProvider({
340
+ url,
341
+ reason: "refresh",
342
+ response: { status: response.status, headers: response.headers }
343
+ })
344
+ ).finally(() => refreshPromises.delete(credential));
345
+ refreshPromises.set(credential, promise);
346
+ return promise;
347
+ }
348
+ async function resolveToken(token, context) {
349
+ return typeof token === "function" ? token(context) : token;
350
+ }
351
+ function parseHTTPURL(url) {
352
+ try {
353
+ const parsedURL = new URL(url);
354
+ return ["http:", "https:"].includes(parsedURL.protocol) ? parsedURL : null;
355
+ } catch {
356
+ return null;
357
+ }
358
+ }
359
+ function isReplayableRequest(options) {
360
+ const method = (options.method || "GET").toUpperCase();
361
+ if (!["GET", "HEAD", "OPTIONS", "PUT", "DELETE"].includes(method)) return false;
362
+ return !(options.body && typeof ReadableStream !== "undefined" && options.body instanceof ReadableStream);
363
+ }
364
+ function createAbortError() {
365
+ return new DOMException("The operation was aborted.", "AbortError");
366
+ }
367
+
368
+ // ../loader-utils/src/lib/path-utils/file-aliases.ts
369
+ var pathPrefix = "";
370
+ var fileAliases = {};
371
+ function resolvePath(filename) {
372
+ for (const alias in fileAliases) {
373
+ if (filename.startsWith(alias)) {
374
+ const replacement = fileAliases[alias];
375
+ filename = filename.replace(alias, replacement);
376
+ }
377
+ }
378
+ if (!filename.startsWith("http://") && !filename.startsWith("https://")) {
379
+ filename = `${pathPrefix}${filename}`;
380
+ }
381
+ return filename;
382
+ }
383
+
384
+ // ../loader-utils/src/lib/sources/data-source.ts
385
+ var UNAVAILABLE_CORE_API = {
386
+ fetchFile: unavailableCoreApiMethod("fetchFile"),
387
+ parse: unavailableCoreApiMethod("parse"),
388
+ parseFile: unavailableCoreApiMethod("parseFile"),
389
+ parseSync: unavailableCoreApiMethod("parseSync"),
390
+ parseInBatches: unavailableCoreApiMethod("parseInBatches"),
391
+ load: unavailableCoreApiMethod("load"),
392
+ loadInBatches: unavailableCoreApiMethod("loadInBatches")
393
+ };
394
+ var DataSource = class _DataSource {
395
+ static defaultOptions = {
396
+ core: {
397
+ type: "auto",
398
+ attributions: [],
399
+ loaders: [],
400
+ onError: void 0
401
+ }
402
+ };
403
+ optionsType;
404
+ options;
405
+ data;
406
+ url;
407
+ /** Shared parser options derived from the source options, excluding source-only core controls. */
408
+ loadOptions;
409
+ /** A resolved fetch function extracted from the shared core options. */
410
+ fetch;
411
+ /** Shared source-level runtime hooks, when supplied by the source factory. */
412
+ coreApi;
413
+ /** Whether a real CoreAPI instance was injected by the integration layer. */
414
+ hasCoreApi;
415
+ _needsRefresh = true;
416
+ constructor(data, options, defaultOptions, coreApi) {
417
+ this.options = mergeOptions(
418
+ mergeOptions(_DataSource.defaultOptions, defaultOptions || {}),
419
+ options
420
+ );
421
+ this.data = data;
422
+ this.url = typeof data === "string" ? resolvePath(data) : "";
423
+ const loadOptions = resolveAuthenticationOptions(getSourceLoaderOptions(this.options));
424
+ this.loadOptions = loadOptions;
425
+ const fetch2 = getFetchFunction(loadOptions);
426
+ this.coreApi = coreApi || UNAVAILABLE_CORE_API;
427
+ this.hasCoreApi = Boolean(coreApi);
428
+ this.fetch = fetch2;
429
+ }
430
+ setProps(options) {
431
+ const mergedOptions = mergeOptions(this.options, options);
432
+ const loadOptions = resolveAuthenticationOptions(getSourceLoaderOptions(mergedOptions));
433
+ this.options = mergedOptions;
434
+ this.loadOptions = loadOptions;
435
+ this.fetch = getFetchFunction(loadOptions);
436
+ this.setNeedsRefresh();
437
+ }
438
+ /** Mark this data source as needing a refresh (redraw) */
439
+ setNeedsRefresh() {
440
+ this._needsRefresh = true;
441
+ }
442
+ /**
443
+ * Does this data source need refreshing?
444
+ * @note The specifics of the refresh mechanism depends on type of data source
445
+ */
446
+ getNeedsRefresh(clear = true) {
447
+ const needsRefresh = this._needsRefresh;
448
+ if (clear) {
449
+ this._needsRefresh = false;
450
+ }
451
+ return needsRefresh;
452
+ }
453
+ /** Reports a source-level failure through the configured callback or the shared logger. */
454
+ reportError(error, message) {
455
+ var _a;
456
+ const normalizedError = normalizeError(error, message);
457
+ const callback = (_a = this.options.core) == null ? void 0 : _a.onError;
458
+ if (callback) {
459
+ callback(normalizedError, this);
460
+ } else {
461
+ log.warn(`${this.constructor.name}: ${normalizedError.message}`)();
462
+ }
463
+ return normalizedError;
464
+ }
465
+ };
466
+ function getFetchFunction(options) {
467
+ return getAuthenticatedFetch(options);
468
+ }
469
+ function getSourceLoaderOptions(options) {
470
+ var _a;
471
+ if (options.loadOptions !== void 0 || ((_a = options.core) == null ? void 0 : _a.loadOptions) !== void 0) {
472
+ throw new Error(
473
+ "Source loadOptions and core.loadOptions were removed. Use core and root loader namespaces directly."
474
+ );
475
+ }
476
+ const loadOptions = { ...options };
477
+ if (options == null ? void 0 : options.core) {
478
+ loadOptions.core = { ...options.core };
479
+ const parserCore = loadOptions.core;
480
+ for (const key of ["type", "attributions", "loaders", "onError", "loadOptions"]) {
481
+ delete parserCore[key];
482
+ }
483
+ if (Object.keys(parserCore).length === 0) {
484
+ delete loadOptions.core;
485
+ }
486
+ }
487
+ const topLevelBaseUri = typeof loadOptions.baseUri === "string" ? loadOptions.baseUri : void 0;
488
+ const topLevelBaseUrl = typeof loadOptions.baseUrl === "string" ? loadOptions.baseUrl : void 0;
489
+ if (topLevelBaseUri !== void 0 || topLevelBaseUrl !== void 0) {
490
+ loadOptions.core ||= {};
491
+ if (loadOptions.core.baseUrl === void 0) {
492
+ loadOptions.core.baseUrl = topLevelBaseUrl ?? topLevelBaseUri;
493
+ }
494
+ delete loadOptions.baseUri;
495
+ delete loadOptions.baseUrl;
496
+ }
497
+ return loadOptions;
498
+ }
499
+ function normalizeError(error, message) {
500
+ if (error instanceof Error) {
501
+ return error;
502
+ }
503
+ if (typeof error === "string") {
504
+ return new Error(error);
505
+ }
506
+ return new Error(message);
507
+ }
508
+ function unavailableCoreApiMethod(methodName) {
509
+ return () => {
510
+ throw new Error(
511
+ `CoreAPI.${methodName} is unavailable. Use @loaders.gl/core.createDataSource().`
512
+ );
513
+ };
514
+ }
515
+
516
+ // ../loader-utils/src/lib/scan-utils/columnar-predicate.ts
517
+ function getColumnarPredicateColumns(predicate) {
518
+ return [...new Set(getColumnarPredicatePaths(predicate).map((path) => path[0]))];
519
+ }
520
+ function getColumnarPredicatePath(property) {
521
+ return typeof property.property === "string" ? [property.property] : [...property.property];
522
+ }
523
+ function getColumnarPredicatePaths(predicate) {
524
+ const paths = /* @__PURE__ */ new Map();
525
+ visitColumnarPredicate(predicate, (child) => {
526
+ if ("property" in child.args[0]) {
527
+ const path = getColumnarPredicatePath(child.args[0]);
528
+ paths.set(path.join("\0"), path);
529
+ }
530
+ });
531
+ return [...paths.values()];
532
+ }
533
+ function validateColumnarPredicate(predicate, availableColumns) {
534
+ visitColumnarPredicate(predicate, (child) => {
535
+ if (child.op === "and" || child.op === "or") {
536
+ if (child.args.length < 2)
537
+ throw new Error(`Columnar predicate ${child.op} requires at least two child predicates`);
538
+ return;
539
+ }
540
+ if (child.op === "not") return;
541
+ const leaf = child;
542
+ const path = getColumnarPredicatePath(leaf.args[0]);
543
+ if (!path.length || path.some((component) => !component)) {
544
+ throw new Error("Columnar predicate property path must contain non-empty strings");
545
+ }
546
+ if (!availableColumns.has(path[0]))
547
+ throw new Error(`Columnar predicate column not found: ${path.join(".")}`);
548
+ if (leaf.op === "in" && leaf.args[1].length === 0) {
549
+ throw new Error("Columnar predicate in requires at least one value");
550
+ }
551
+ });
552
+ }
553
+ function isColumnarPredicateParameter(value) {
554
+ const parameterValue = value;
555
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 1 && Object.hasOwn(value, "parameter") && typeof parameterValue.parameter === "string" && parameterValue.parameter.length > 0;
556
+ }
557
+ function isColumnarPredicateValue(value) {
558
+ return typeof value === "boolean" || typeof value === "bigint" || typeof value === "string" || typeof value === "number" && Number.isFinite(value) || value instanceof Date && Number.isFinite(value.getTime()) || value instanceof Uint8Array;
559
+ }
560
+ function bindColumnarPredicateParameters(predicate, parameters) {
561
+ switch (predicate.op) {
562
+ case "and":
563
+ case "or":
564
+ return {
565
+ op: predicate.op,
566
+ args: predicate.args.map((child) => bindColumnarPredicateParameters(child, parameters))
567
+ };
568
+ case "not":
569
+ return {
570
+ op: "not",
571
+ args: [bindColumnarPredicateParameters(predicate.args[0], parameters)]
572
+ };
573
+ case "isNull":
574
+ return { op: "isNull", args: [copyColumnarPredicateProperty(predicate.args[0])] };
575
+ case "in":
576
+ return {
577
+ op: "in",
578
+ args: [
579
+ copyColumnarPredicateProperty(predicate.args[0]),
580
+ predicate.args[1].map((value) => bindColumnarPredicateValue(value, parameters))
581
+ ]
582
+ };
583
+ default:
584
+ return {
585
+ op: predicate.op,
586
+ args: [
587
+ copyColumnarPredicateProperty(predicate.args[0]),
588
+ bindColumnarPredicateValue(predicate.args[1], parameters)
589
+ ]
590
+ };
591
+ }
592
+ }
593
+ function visitColumnarPredicate(predicate, visitor) {
594
+ visitor(predicate);
595
+ if (predicate.op === "and" || predicate.op === "or")
596
+ predicate.args.forEach((child) => visitColumnarPredicate(child, visitor));
597
+ else if (predicate.op === "not") visitColumnarPredicate(predicate.args[0], visitor);
598
+ }
599
+ function bindColumnarPredicateValue(value, parameters) {
600
+ if (!isColumnarPredicateParameter(value)) return value;
601
+ if (!Object.hasOwn(parameters, value.parameter)) {
602
+ throw new Error(`Columnar predicate parameter ":${value.parameter}" requires a value`);
603
+ }
604
+ const parameterValue = parameters[value.parameter];
605
+ if (isColumnarPredicateParameter(parameterValue)) {
606
+ throw new Error(
607
+ `Columnar predicate parameter ":${value.parameter}" cannot reference another parameter`
608
+ );
609
+ }
610
+ if (!isColumnarPredicateValue(parameterValue)) {
611
+ throw new Error(`Columnar predicate parameter ":${value.parameter}" has an unsupported value`);
612
+ }
613
+ return copyColumnarPredicateValue(parameterValue);
614
+ }
615
+ function copyColumnarPredicateProperty(property) {
616
+ return {
617
+ ...property,
618
+ property: typeof property.property === "string" ? property.property : [...property.property]
619
+ };
620
+ }
621
+ function copyColumnarPredicateValue(value) {
622
+ if (value instanceof Uint8Array) return value.slice();
623
+ if (value instanceof Date) return new Date(value.getTime());
624
+ return value;
625
+ }
626
+
627
+ // ../loader-utils/src/lib/scan-utils/scan-query-metadata.ts
628
+ var import_crs = require("@math.gl/crs");
629
+ function createScanQueryMetadata(options) {
630
+ validateScanExecutionSupport(options.queryType, options.execution);
631
+ const schema = Object.freeze({
632
+ fields: Object.freeze(
633
+ options.schema.fields.map(
634
+ (field) => Object.freeze({ ...field, metadata: Object.freeze({ ...field.metadata }) })
635
+ )
636
+ ),
637
+ metadata: Object.freeze({ ...options.schema.metadata })
638
+ });
639
+ const columns = schema.fields.map(
640
+ (field) => {
641
+ var _a;
642
+ return Object.freeze({
643
+ name: field.name,
644
+ type: field.type,
645
+ nullable: field.nullable !== false,
646
+ role: ((_a = options.columnRoles) == null ? void 0 : _a[field.name]) || "attribute",
647
+ title: getNonEmptyMetadataValue(field.metadata, "title"),
648
+ description: getNonEmptyMetadataValue(field.metadata, "description"),
649
+ metadata: field.metadata || Object.freeze({})
650
+ });
651
+ }
652
+ );
653
+ return Object.freeze({
654
+ sourceType: options.sourceType,
655
+ queryType: options.queryType,
656
+ execution: Object.freeze({ ...options.execution }),
657
+ name: options.name,
658
+ description: options.description,
659
+ schema,
660
+ columns: Object.freeze(columns),
661
+ capabilities: Object.freeze({ ...options.capabilities }),
662
+ spatial: options.spatial ? Object.freeze({
663
+ ...options.spatial,
664
+ bounds: options.spatial.bounds ? Object.freeze({
665
+ minimum: Object.freeze([...options.spatial.bounds.minimum]),
666
+ maximum: Object.freeze([...options.spatial.bounds.maximum])
667
+ }) : void 0,
668
+ coordinateReferenceSystems: options.spatial.coordinateReferenceSystems ? Object.freeze([...options.spatial.coordinateReferenceSystems]) : void 0,
669
+ spatialReference: options.spatial.spatialReference ? (0, import_crs.createSpatialReference)(options.spatial.spatialReference) : void 0
670
+ }) : void 0,
671
+ statistics: options.statistics ? Object.freeze({ ...options.statistics }) : void 0,
672
+ levels: options.levels ? Object.freeze(
673
+ options.levels.map(
674
+ (level) => Object.freeze({
675
+ ...level,
676
+ scale: level.scale ? Object.freeze([...level.scale]) : void 0
677
+ })
678
+ )
679
+ ) : void 0
680
+ });
681
+ }
682
+ function validateScanExecutionSupport(queryType, execution) {
683
+ if (execution.status === "metadata-only") {
684
+ if (!execution.reason.trim()) {
685
+ throw new Error("Metadata-only scan support requires a concrete reason");
686
+ }
687
+ return;
688
+ }
689
+ const validMethods = {
690
+ table: ["read", "query"],
691
+ raster: ["getRaster"],
692
+ "point-cloud": ["scan"]
693
+ };
694
+ if (!validMethods[queryType].includes(execution.method)) {
695
+ throw new Error(
696
+ `Scan execution method "${execution.method}" is not valid for ${queryType} queries`
697
+ );
698
+ }
699
+ }
700
+ function getNonEmptyMetadataValue(metadata, key) {
701
+ const value = metadata == null ? void 0 : metadata[key];
702
+ return value || void 0;
703
+ }
704
+
705
+ // ../loader-utils/src/lib/scan-utils/table-query.ts
706
+ function planTableQuery(sourceColumnNames, options = {}) {
707
+ validateTableQueryOptions(sourceColumnNames, options);
708
+ const outputColumnNames = options.columns ? [...options.columns] : [...sourceColumnNames];
709
+ const predicateColumnNames = options.predicate ? getColumnarPredicateColumns(options.predicate) : [];
710
+ const requiredColumnNames = /* @__PURE__ */ new Set([...outputColumnNames, ...predicateColumnNames]);
711
+ const scanColumnNames = sourceColumnNames.filter(
712
+ (columnName) => requiredColumnNames.has(columnName)
713
+ );
714
+ const steps = [
715
+ Object.freeze({ kind: "scan", columns: Object.freeze(scanColumnNames) })
716
+ ];
717
+ if (options.predicate) {
718
+ steps.push(Object.freeze({ kind: "filter", predicate: options.predicate }));
719
+ }
720
+ steps.push(Object.freeze({ kind: "project", columns: Object.freeze(outputColumnNames) }));
721
+ if (options.limit !== void 0) {
722
+ steps.push(Object.freeze({ kind: "limit", limit: options.limit }));
723
+ }
724
+ return Object.freeze(steps);
725
+ }
726
+ function validateTableQueryOptions(sourceColumnNames, options) {
727
+ const availableColumnNames = new Set(sourceColumnNames);
728
+ const outputColumnNames = options.columns ?? sourceColumnNames;
729
+ const seenColumnNames = /* @__PURE__ */ new Set();
730
+ for (const columnName of outputColumnNames) {
731
+ if (!availableColumnNames.has(columnName)) {
732
+ throw new Error(`Table query column not found: ${columnName}`);
733
+ }
734
+ if (seenColumnNames.has(columnName)) {
735
+ throw new Error(`Table query column was selected more than once: ${columnName}`);
736
+ }
737
+ seenColumnNames.add(columnName);
738
+ }
739
+ validateTableQueryLimit(options.limit);
740
+ if (options.predicate) {
741
+ validateColumnarPredicate(options.predicate, availableColumnNames);
742
+ }
743
+ }
744
+ function validateTableQueryLimit(limit) {
745
+ if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0)) {
746
+ throw new Error("Table query limit must be a non-negative safe integer.");
747
+ }
748
+ }
749
+
750
+ // ../loader-utils/src/lib/scan-utils/table-scan-batch.ts
751
+ function makeTableScanBatch(table) {
752
+ return { ...table, batchType: "data", length: table.data.numRows };
753
+ }
754
+
755
+ // ../loader-utils/src/lib/scan-utils/relational-query.ts
756
+ function planRelationalQuery(sourceColumnNames, options = {}) {
757
+ var _a, _b, _c, _d, _e, _f;
758
+ const available = new Set(sourceColumnNames);
759
+ const expressionNames = /* @__PURE__ */ new Set();
760
+ for (const expression of options.expressions || []) {
761
+ if (!expression.name) throw new Error("Relational expression names must be non-empty.");
762
+ if (available.has(expression.name) || expressionNames.has(expression.name)) {
763
+ throw new Error(`Relational expression duplicates column: ${expression.name}`);
764
+ }
765
+ expressionNames.add(expression.name);
766
+ }
767
+ const aggregateNames = new Set((options.aggregates || []).map((aggregate) => aggregate.name));
768
+ const requiredColumns = /* @__PURE__ */ new Set();
769
+ const availableColumns = new Set(sourceColumnNames);
770
+ for (const expression of options.expressions || []) {
771
+ const definition = expression.expression;
772
+ if (definition.op === "column") {
773
+ validateRelationalColumnReference(definition.column, availableColumns);
774
+ if (available.has(definition.column)) requiredColumns.add(definition.column);
775
+ }
776
+ if ("left" in definition) {
777
+ validateRelationalColumnReference(definition.left, availableColumns);
778
+ validateRelationalColumnReference(definition.right, availableColumns);
779
+ if (available.has(definition.left)) requiredColumns.add(definition.left);
780
+ if (available.has(definition.right)) requiredColumns.add(definition.right);
781
+ }
782
+ availableColumns.add(expression.name);
783
+ }
784
+ for (const key of options.orderBy || []) requiredColumns.add(key.column);
785
+ for (const key of options.groupBy || []) requiredColumns.add(key);
786
+ for (const aggregate of options.aggregates || []) {
787
+ if (aggregate.column) requiredColumns.add(aggregate.column);
788
+ }
789
+ const outputColumns = (_a = options.columns) == null ? void 0 : _a.filter(
790
+ (column) => !expressionNames.has(column) && !aggregateNames.has(column)
791
+ );
792
+ const tablePlan = [
793
+ ...planTableQuery(sourceColumnNames, {
794
+ ...options,
795
+ columns: outputColumns,
796
+ predicate: options.predicate
797
+ })
798
+ ];
799
+ const scanStep = tablePlan[0];
800
+ if ((scanStep == null ? void 0 : scanStep.kind) === "scan") {
801
+ const scanColumns = new Set(scanStep.columns);
802
+ for (const column of requiredColumns) {
803
+ if (available.has(column)) scanColumns.add(column);
804
+ }
805
+ tablePlan[0] = Object.freeze({ kind: "scan", columns: Object.freeze([...scanColumns]) });
806
+ }
807
+ for (const expression of expressionNames) available.add(expression);
808
+ for (const aggregate of aggregateNames) available.add(aggregate);
809
+ for (const key of options.orderBy || []) {
810
+ if (!available.has(key.column))
811
+ throw new Error(`Relational order column not found: ${key.column}`);
812
+ }
813
+ for (const key of options.groupBy || []) {
814
+ if (!available.has(key)) throw new Error(`Relational group column not found: ${key}`);
815
+ }
816
+ for (const aggregate of options.aggregates || []) {
817
+ if (!aggregate.name) throw new Error("Relational aggregate names must be non-empty.");
818
+ if (aggregate.function !== "count" && !aggregate.column) {
819
+ throw new Error(`Relational aggregate ${aggregate.function} requires a column.`);
820
+ }
821
+ if (aggregate.column && !available.has(aggregate.column)) {
822
+ throw new Error(`Relational aggregate column not found: ${aggregate.column}`);
823
+ }
824
+ }
825
+ const relationalSteps = [];
826
+ if ((_b = options.expressions) == null ? void 0 : _b.length)
827
+ relationalSteps.push({ kind: "expression", detail: options.expressions });
828
+ if ((_c = options.orderBy) == null ? void 0 : _c.length) relationalSteps.push({ kind: "order", detail: options.orderBy });
829
+ if (((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.groupBy) == null ? void 0 : _e.length)) {
830
+ relationalSteps.push({
831
+ kind: "aggregate",
832
+ detail: { groupBy: options.groupBy, aggregates: options.aggregates }
833
+ });
834
+ }
835
+ if ((_f = options.union) == null ? void 0 : _f.length) relationalSteps.push({ kind: "union", detail: options.union });
836
+ if (options.join) relationalSteps.push({ kind: "join", detail: options.join });
837
+ return { tablePlan, relationalSteps: Object.freeze(relationalSteps) };
838
+ }
839
+ function validateRelationalColumnReference(columnName, availableColumns) {
840
+ if (!availableColumns.has(columnName)) {
841
+ throw new Error(`Relational expression column not found: ${columnName}`);
842
+ }
843
+ }
844
+
845
+ // ../loader-utils/src/lib/scan-utils/table-query-explain.ts
846
+ function explainTableQuery(sourceColumnNames, options, capabilities) {
847
+ const plan = planTableQuery(sourceColumnNames, options);
848
+ const outputColumns = options.columns ? [...options.columns] : [...sourceColumnNames];
849
+ const predicateColumns = options.predicate ? getColumnarPredicateColumns(options.predicate) : [];
850
+ const requiredColumns = [...plan[0].kind === "scan" ? plan[0].columns : []];
851
+ return Object.freeze({
852
+ sourceColumns: Object.freeze([...sourceColumnNames]),
853
+ outputColumns: Object.freeze(outputColumns),
854
+ requiredColumns: Object.freeze(requiredColumns),
855
+ predicateColumns: Object.freeze(predicateColumns),
856
+ plan,
857
+ capabilities: Object.freeze({ ...capabilities }),
858
+ operators: Object.freeze({
859
+ projection: createOperatorExplanation(options.columns !== void 0, capabilities.projection),
860
+ predicate: createOperatorExplanation(options.predicate !== void 0, capabilities.predicate),
861
+ limit: createOperatorExplanation(options.limit !== void 0, capabilities.limit)
862
+ })
863
+ });
864
+ }
865
+ function createOperatorExplanation(enabled, support) {
866
+ return Object.freeze({ enabled, support });
867
+ }
868
+
869
+ // dist/sql-predicate-types.js
870
+ function isSQLPredicateParameter(value) {
871
+ return isColumnarPredicateParameter(value);
872
+ }
873
+
874
+ // dist/sql-predicate-schema.js
875
+ var MAXIMUM_PREDICATE_DEPTH = 64;
876
+ var MAXIMUM_PREDICATE_NODES = 4096;
877
+ var SQL_PREDICATE_JSON_SCHEMA = {
878
+ $schema: "https://json-schema.org/draft/2020-12/schema",
879
+ $id: "https://loaders.gl/schemas/sql-predicate.schema.json",
880
+ title: "loaders.gl SQL predicate",
881
+ oneOf: [
882
+ { $ref: "#/$defs/comparison" },
883
+ { $ref: "#/$defs/in" },
884
+ { $ref: "#/$defs/isNull" },
885
+ { $ref: "#/$defs/logical" },
886
+ { $ref: "#/$defs/not" }
887
+ ],
888
+ $defs: {
889
+ property: {
890
+ type: "object",
891
+ required: ["property"],
892
+ properties: {
893
+ property: { type: "string", minLength: 1 },
894
+ quoted: { type: "boolean" }
895
+ },
896
+ additionalProperties: false
897
+ },
898
+ value: {
899
+ oneOf: [
900
+ { type: ["boolean", "number", "string"] },
901
+ {
902
+ type: "object",
903
+ required: ["parameter"],
904
+ properties: { parameter: { type: "string", minLength: 1 } },
905
+ additionalProperties: false
906
+ }
907
+ ]
908
+ },
909
+ comparison: {
910
+ type: "object",
911
+ required: ["op", "args"],
912
+ properties: {
913
+ op: { enum: ["=", "<>", "<", "<=", ">", ">="] },
914
+ args: {
915
+ type: "array",
916
+ prefixItems: [{ $ref: "#/$defs/property" }, { $ref: "#/$defs/value" }],
917
+ minItems: 2,
918
+ maxItems: 2
919
+ }
920
+ },
921
+ additionalProperties: false
922
+ },
923
+ in: {
924
+ type: "object",
925
+ required: ["op", "args"],
926
+ properties: {
927
+ op: { const: "in" },
928
+ args: {
929
+ type: "array",
930
+ prefixItems: [
931
+ { $ref: "#/$defs/property" },
932
+ { type: "array", items: { $ref: "#/$defs/value" }, minItems: 1 }
933
+ ],
934
+ minItems: 2,
935
+ maxItems: 2
936
+ }
937
+ },
938
+ additionalProperties: false
939
+ },
940
+ isNull: {
941
+ type: "object",
942
+ required: ["op", "args"],
943
+ properties: {
944
+ op: { const: "isNull" },
945
+ args: {
946
+ type: "array",
947
+ prefixItems: [{ $ref: "#/$defs/property" }],
948
+ minItems: 1,
949
+ maxItems: 1
950
+ }
951
+ },
952
+ additionalProperties: false
953
+ },
954
+ logical: {
955
+ type: "object",
956
+ required: ["op", "args"],
957
+ properties: {
958
+ op: { enum: ["and", "or"] },
959
+ args: { type: "array", items: { $ref: "#" }, minItems: 2 }
960
+ },
961
+ additionalProperties: false
962
+ },
963
+ not: {
964
+ type: "object",
965
+ required: ["op", "args"],
966
+ properties: {
967
+ op: { const: "not" },
968
+ args: { type: "array", prefixItems: [{ $ref: "#" }], minItems: 1, maxItems: 1 }
969
+ },
970
+ additionalProperties: false
971
+ }
972
+ }
973
+ };
974
+ function isSQLPredicate(value) {
975
+ try {
976
+ validateSQLPredicate(value);
977
+ return true;
978
+ } catch {
979
+ return false;
980
+ }
981
+ }
982
+ function validateSQLPredicate(value) {
983
+ const state = { nodes: 0 };
984
+ validatePredicateNode(value, "$", 0, state);
985
+ }
986
+ function validatePredicateNode(value, path, depth, state) {
987
+ if (depth > MAXIMUM_PREDICATE_DEPTH) {
988
+ throw new Error(`SQL predicate ${path} exceeds the maximum nesting depth`);
989
+ }
990
+ state.nodes++;
991
+ if (state.nodes > MAXIMUM_PREDICATE_NODES) {
992
+ throw new Error("SQL predicate exceeds the maximum node count");
993
+ }
994
+ if (!isRecord(value) || !hasExactKeys(value, ["op", "args"])) {
995
+ throw new Error(`SQL predicate ${path} must contain only op and args`);
996
+ }
997
+ if (typeof value.op !== "string" || !Array.isArray(value.args)) {
998
+ throw new Error(`SQL predicate ${path} requires string op and array args`);
999
+ }
1000
+ switch (value.op) {
1001
+ case "and":
1002
+ case "or":
1003
+ if (value.args.length < 2) {
1004
+ throw new Error(`SQL predicate ${path}.${value.op} requires at least two arguments`);
1005
+ }
1006
+ for (let index = 0; index < value.args.length; index++) {
1007
+ validatePredicateNode(value.args[index], `${path}.args[${index}]`, depth + 1, state);
1008
+ }
1009
+ return;
1010
+ case "not":
1011
+ if (value.args.length !== 1) {
1012
+ throw new Error(`SQL predicate ${path}.not requires exactly one argument`);
1013
+ }
1014
+ validatePredicateNode(value.args[0], `${path}.args[0]`, depth + 1, state);
1015
+ return;
1016
+ case "isNull":
1017
+ if (value.args.length !== 1) {
1018
+ throw new Error(`SQL predicate ${path}.isNull requires exactly one argument`);
1019
+ }
1020
+ validatePredicateProperty(value.args[0], `${path}.args[0]`);
1021
+ return;
1022
+ case "in":
1023
+ if (value.args.length !== 2 || !Array.isArray(value.args[1]) || value.args[1].length === 0) {
1024
+ throw new Error(`SQL predicate ${path}.in requires a property and non-empty value list`);
1025
+ }
1026
+ validatePredicateProperty(value.args[0], `${path}.args[0]`);
1027
+ value.args[1].forEach((item, index) => validatePredicateValue(item, `${path}.args[1][${index}]`));
1028
+ return;
1029
+ case "=":
1030
+ case "<>":
1031
+ case "<":
1032
+ case "<=":
1033
+ case ">":
1034
+ case ">=":
1035
+ if (value.args.length !== 2) {
1036
+ throw new Error(`SQL predicate ${path}.${value.op} requires exactly two arguments`);
1037
+ }
1038
+ validatePredicateProperty(value.args[0], `${path}.args[0]`);
1039
+ validatePredicateValue(value.args[1], `${path}.args[1]`);
1040
+ return;
1041
+ default:
1042
+ throw new Error(`SQL predicate ${path} has unsupported operator ${JSON.stringify(value.op)}`);
1043
+ }
1044
+ }
1045
+ function validatePredicateProperty(value, path) {
1046
+ if (!isRecord(value) || !hasAllowedKeys(value, ["property", "quoted"]) || typeof value.property !== "string" || value.property.length === 0 || value.quoted !== void 0 && typeof value.quoted !== "boolean") {
1047
+ throw new Error(`SQL predicate ${path} requires a non-empty property reference`);
1048
+ }
1049
+ }
1050
+ function validatePredicateValue(value, path) {
1051
+ if (isSQLPredicateParameter(value)) {
1052
+ return;
1053
+ }
1054
+ if (typeof value === "boolean" || typeof value === "bigint" || typeof value === "string" || value instanceof Uint8Array) {
1055
+ return;
1056
+ }
1057
+ if (typeof value === "number" && Number.isFinite(value)) {
1058
+ return;
1059
+ }
1060
+ if (value instanceof Date && Number.isFinite(value.getTime())) {
1061
+ return;
1062
+ }
1063
+ throw new Error(`SQL predicate ${path} contains an unsupported scalar value`);
1064
+ }
1065
+ function isRecord(value) {
1066
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1067
+ }
1068
+ function hasExactKeys(value, expectedKeys) {
1069
+ const keys = Object.keys(value);
1070
+ return keys.length === expectedKeys.length && expectedKeys.every((key) => keys.includes(key));
1071
+ }
1072
+ function hasAllowedKeys(value, allowedKeys) {
1073
+ return Object.keys(value).every((key) => allowedKeys.includes(key));
1074
+ }
1075
+
1076
+ // dist/compile-table-query.js
1077
+ function compileSQLTableQuery(query, options) {
1078
+ validateSQLTableQuery(query);
1079
+ const context = {
1080
+ dialect: options.dialect,
1081
+ namedParameters: options.parameters,
1082
+ parameters: []
1083
+ };
1084
+ return {
1085
+ sql: compileTableStatement(query, context),
1086
+ parameters: context.parameters
1087
+ };
1088
+ }
1089
+ function compileTableStatement(query, context) {
1090
+ var _a, _b;
1091
+ const projection = compileProjection(query);
1092
+ const table = [query.catalogName, query.schemaName, query.tableName].filter((identifier) => identifier !== void 0).map(quoteSQLIdentifier).join(".");
1093
+ const fromClause = query.join ? compileJoinFromClause(query, table, context) : `FROM ${table}`;
1094
+ const clauses = [`SELECT ${projection}`, fromClause];
1095
+ if (query.predicate) {
1096
+ clauses.push(`WHERE ${compileSQLPredicate(query.predicate, context)}`);
1097
+ }
1098
+ if ((_a = query.groupBy) == null ? void 0 : _a.length) {
1099
+ clauses.push(`GROUP BY ${query.groupBy.map(quoteSQLIdentifier).join(", ")}`);
1100
+ }
1101
+ let sql = clauses.join("\n");
1102
+ for (const child of query.union || []) {
1103
+ const childQuery = {
1104
+ tableName: child.source,
1105
+ ...child.query || {}
1106
+ };
1107
+ validateSQLTableQuery(childQuery);
1108
+ const childSQL = compileTableStatement(childQuery, context);
1109
+ const branchSQL = hasBranchLocalModifiers(childQuery) ? `(${childSQL})` : childSQL;
1110
+ sql = `${sql}
1111
+ UNION ALL
1112
+ ${branchSQL}`;
1113
+ }
1114
+ if ((_b = query.orderBy) == null ? void 0 : _b.length)
1115
+ sql += `
1116
+ ORDER BY ${query.orderBy.map(compileOrderKey).join(", ")}`;
1117
+ if (query.limit !== void 0)
1118
+ sql += `
1119
+ LIMIT ${query.limit}`;
1120
+ return sql;
1121
+ }
1122
+ function compileJoinFromClause(query, table, context) {
1123
+ const join = query.join;
1124
+ if (!join)
1125
+ return `FROM ${table}`;
1126
+ validateSQLIdentifier(join.child.source);
1127
+ validateSQLIdentifier(join.left);
1128
+ validateSQLIdentifier(join.right);
1129
+ const childTable = quoteSQLIdentifier(join.child.source);
1130
+ const rightRelation = join.child.query ? `(${compileTableStatement({ tableName: join.child.source, ...join.child.query }, context)})` : childTable;
1131
+ return `FROM ${table} JOIN ${rightRelation} AS ${childTable} ON ${table}.${quoteSQLIdentifier(join.left)} = ${childTable}.${quoteSQLIdentifier(join.right)}`;
1132
+ }
1133
+ function compileProjection(query) {
1134
+ var _a, _b;
1135
+ const expressions = query.expressions || [];
1136
+ const expressionByName = new Map(expressions.map((expression) => [expression.name, expression]));
1137
+ const aggregates = query.aggregates || [];
1138
+ const aggregateByName = new Map(aggregates.map((aggregate) => [aggregate.name, aggregate]));
1139
+ const columns = query.columns === void 0 ? void 0 : [...query.columns];
1140
+ const projectionColumns = columns || (((_a = query.groupBy) == null ? void 0 : _a.length) || ((_b = query.aggregates) == null ? void 0 : _b.length) ? [...query.groupBy || []] : []);
1141
+ const selections = projectionColumns.map((column) => {
1142
+ const expression = expressionByName.get(column);
1143
+ if (expression) {
1144
+ return `${compileRelationalExpression(expression.expression)} AS ${quoteSQLIdentifier(expression.name)}`;
1145
+ }
1146
+ const aggregate = aggregateByName.get(column);
1147
+ return aggregate ? `${compileAggregate(aggregate)} AS ${quoteSQLIdentifier(aggregate.name)}` : compileProjectionColumn(column, query);
1148
+ });
1149
+ if (!selections.length)
1150
+ return expressions.length ? expressions.map((expression) => `${compileRelationalExpression(expression.expression)} AS ${quoteSQLIdentifier(expression.name)}`).join(", ") : aggregates.length ? aggregates.map((aggregate) => `${compileAggregate(aggregate)} AS ${quoteSQLIdentifier(aggregate.name)}`).join(", ") : "*";
1151
+ return selections.join(", ");
1152
+ }
1153
+ function compileProjectionColumn(column, query) {
1154
+ var _a;
1155
+ const childSource = (_a = query.join) == null ? void 0 : _a.child.source;
1156
+ return childSource && column.startsWith(`${childSource}.`) ? column.split(".").map(quoteSQLIdentifier).join(".") : quoteSQLIdentifier(column);
1157
+ }
1158
+ function hasBranchLocalModifiers(query) {
1159
+ var _a, _b;
1160
+ return Boolean(query.limit !== void 0 || ((_a = query.orderBy) == null ? void 0 : _a.length) || ((_b = query.union) == null ? void 0 : _b.length));
1161
+ }
1162
+ function compileRelationalExpression(expression) {
1163
+ switch (expression.op) {
1164
+ case "column":
1165
+ return quoteSQLIdentifier(expression.column);
1166
+ case "literal":
1167
+ return expression.value === null ? "NULL" : typeof expression.value === "string" ? `'${expression.value.replace(/'/g, "''")}'` : String(expression.value);
1168
+ case "add":
1169
+ return `(${quoteSQLIdentifier(expression.left)} + ${quoteSQLIdentifier(expression.right)})`;
1170
+ case "subtract":
1171
+ return `(${quoteSQLIdentifier(expression.left)} - ${quoteSQLIdentifier(expression.right)})`;
1172
+ case "multiply":
1173
+ return `(${quoteSQLIdentifier(expression.left)} * ${quoteSQLIdentifier(expression.right)})`;
1174
+ case "divide":
1175
+ return `(${quoteSQLIdentifier(expression.left)} / NULLIF(${quoteSQLIdentifier(expression.right)}, 0))`;
1176
+ }
1177
+ }
1178
+ function compileAggregate(aggregate) {
1179
+ const column = aggregate.column ? quoteSQLIdentifier(aggregate.column) : "*";
1180
+ return `${aggregate.function.toUpperCase()}(${column})`;
1181
+ }
1182
+ function compileOrderKey(orderKey) {
1183
+ var _a;
1184
+ const direction = ((_a = orderKey.direction) == null ? void 0 : _a.toUpperCase()) || "ASC";
1185
+ const nulls = orderKey.nulls ? ` NULLS ${orderKey.nulls.toUpperCase()}` : "";
1186
+ return `${quoteSQLIdentifier(orderKey.column)} ${direction}${nulls}`;
1187
+ }
1188
+ function compileSQLPredicate(predicate, context) {
1189
+ switch (predicate.op) {
1190
+ case "and":
1191
+ case "or":
1192
+ return `(${predicate.args.map((child) => compileSQLPredicate(child, context)).join(` ${predicate.op.toUpperCase()} `)})`;
1193
+ case "not":
1194
+ return `(NOT ${compileSQLPredicate(predicate.args[0], context)})`;
1195
+ case "isNull":
1196
+ return `(${quoteSQLProperty(predicate.args[0])} IS NULL)`;
1197
+ case "in":
1198
+ return `(${quoteSQLProperty(predicate.args[0])} IN (${predicate.args[1].map((value) => compileSQLPredicateValue(value, context)).join(", ")}))`;
1199
+ default:
1200
+ return `(${quoteSQLProperty(predicate.args[0])} ${predicate.op} ${compileSQLPredicateValue(predicate.args[1], context)})`;
1201
+ }
1202
+ }
1203
+ function compileSQLPredicateValue(value, context) {
1204
+ const scalar = isSQLPredicateParameter(value) ? resolveSQLPredicateParameter(value.parameter, context.namedParameters) : value;
1205
+ context.parameters.push(scalar);
1206
+ return getSQLPlaceholder(context.dialect, context.parameters.length);
1207
+ }
1208
+ function resolveSQLPredicateParameter(parameterName, parameters) {
1209
+ if (!parameters || !Object.hasOwn(parameters, parameterName)) {
1210
+ throw new Error(`SQL predicate parameter ":${parameterName}" requires a value`);
1211
+ }
1212
+ const value = parameters[parameterName];
1213
+ validateSQLPredicate({ op: "=", args: [{ property: "_parameter" }, value] });
1214
+ return value;
1215
+ }
1216
+ function getSQLPlaceholder(_dialect, _position) {
1217
+ return "?";
1218
+ }
1219
+ function quoteSQLProperty(property) {
1220
+ return property.quoted ? quoteSQLIdentifier(property.property) : property.property.split(".").map(quoteSQLIdentifier).join(".");
1221
+ }
1222
+ function quoteSQLIdentifier(identifier) {
1223
+ validateSQLIdentifier(identifier);
1224
+ return `"${identifier.replace(/"/g, '""')}"`;
1225
+ }
1226
+ function validateSQLTableQuery(query) {
1227
+ var _a;
1228
+ validateSQLIdentifier(query.tableName);
1229
+ if (query.schemaName !== void 0)
1230
+ validateSQLIdentifier(query.schemaName);
1231
+ if (query.catalogName !== void 0)
1232
+ validateSQLIdentifier(query.catalogName);
1233
+ const seenColumns = /* @__PURE__ */ new Set();
1234
+ if (((_a = query.columns) == null ? void 0 : _a.length) === 0) {
1235
+ throw new Error("SQL table-query projections must select at least one column.");
1236
+ }
1237
+ for (const column of query.columns ?? []) {
1238
+ validateSQLIdentifier(column);
1239
+ if (seenColumns.has(column)) {
1240
+ throw new Error(`Table query column was selected more than once: ${column}`);
1241
+ }
1242
+ seenColumns.add(column);
1243
+ }
1244
+ if (query.limit !== void 0 && (!Number.isSafeInteger(query.limit) || query.limit < 0)) {
1245
+ throw new Error("Table query limit must be a non-negative safe integer.");
1246
+ }
1247
+ if (query.predicate)
1248
+ validateSQLPredicate(query.predicate);
1249
+ validateRelationalQuery(query);
1250
+ }
1251
+ function validateRelationalQuery(query) {
1252
+ const expressionNames = /* @__PURE__ */ new Set();
1253
+ for (const expression of query.expressions || []) {
1254
+ validateSQLIdentifier(expression.name);
1255
+ if (expressionNames.has(expression.name))
1256
+ throw new Error(`Relational expression duplicates column: ${expression.name}`);
1257
+ expressionNames.add(expression.name);
1258
+ const definition = expression.expression;
1259
+ if (definition.op === "column")
1260
+ validateSQLIdentifier(definition.column);
1261
+ if ("left" in definition) {
1262
+ validateSQLIdentifier(definition.left);
1263
+ validateSQLIdentifier(definition.right);
1264
+ }
1265
+ }
1266
+ for (const column of query.groupBy || [])
1267
+ validateSQLIdentifier(column);
1268
+ for (const key of query.orderBy || []) {
1269
+ validateSQLIdentifier(key.column);
1270
+ if (key.direction && key.direction !== "asc" && key.direction !== "desc")
1271
+ throw new Error(`Invalid order direction: ${key.direction}`);
1272
+ if (key.nulls && key.nulls !== "first" && key.nulls !== "last")
1273
+ throw new Error(`Invalid null placement: ${key.nulls}`);
1274
+ }
1275
+ for (const aggregate of query.aggregates || []) {
1276
+ validateSQLIdentifier(aggregate.name);
1277
+ if (aggregate.function !== "count" && !aggregate.column)
1278
+ throw new Error(`Relational aggregate ${aggregate.function} requires a column.`);
1279
+ if (aggregate.column)
1280
+ validateSQLIdentifier(aggregate.column);
1281
+ }
1282
+ }
1283
+ function validateSQLIdentifier(identifier) {
1284
+ if (!identifier || identifier.includes("\0")) {
1285
+ throw new Error("SQL table-query identifiers must be non-empty and cannot contain NUL bytes.");
1286
+ }
1287
+ }
1288
+
1289
+ // dist/sql-utils.js
1290
+ var arrow5 = __toESM(require("apache-arrow"), 1);
1291
+
1292
+ // ../schema-utils/src/lib/schema/data-type.ts
1293
+ var import_types = require("@math.gl/types");
1294
+ function getDataTypeFromValue(value, defaultNumberType = "float32") {
1295
+ if (value instanceof Date) {
1296
+ return "date-millisecond";
1297
+ }
1298
+ if (typeof value === "number") {
1299
+ return defaultNumberType;
1300
+ }
1301
+ if (typeof value === "boolean") {
1302
+ return "bool";
1303
+ }
1304
+ if (typeof value === "string") {
1305
+ return "utf8";
1306
+ }
1307
+ if (value === null || value === "undefined") {
1308
+ return "null";
1309
+ }
1310
+ return "null";
1311
+ }
1312
+ function getDataTypeFromArray(array) {
1313
+ let type = getDataTypeFromTypedArray(array);
1314
+ if (type !== "null") {
1315
+ return { type, nullable: false };
1316
+ }
1317
+ if (array.length > 0) {
1318
+ type = getDataTypeFromValue(array[0]);
1319
+ return { type, nullable: true };
1320
+ }
1321
+ return { type: "null", nullable: true };
1322
+ }
1323
+ function getDataTypeFromTypedArray(array) {
1324
+ if (typeof Float16Array !== "undefined" && array instanceof Float16Array) {
1325
+ return "float16";
1326
+ }
1327
+ switch (array.constructor) {
1328
+ case Int8Array:
1329
+ return "int8";
1330
+ case Uint8Array:
1331
+ case Uint8ClampedArray:
1332
+ return "uint8";
1333
+ case Int16Array:
1334
+ return "int16";
1335
+ case Uint16Array:
1336
+ return "uint16";
1337
+ case Int32Array:
1338
+ return "int32";
1339
+ case Uint32Array:
1340
+ return "uint32";
1341
+ case BigInt64Array:
1342
+ return "int64";
1343
+ case BigUint64Array:
1344
+ return "uint64";
1345
+ case Float32Array:
1346
+ return "float32";
1347
+ case Float64Array:
1348
+ return "float64";
1349
+ default:
1350
+ return "null";
1351
+ }
1352
+ }
1353
+ function getArrayTypeFromDataType(type, nullable) {
1354
+ if (!nullable) {
1355
+ switch (type) {
1356
+ case "int8":
1357
+ return Int8Array;
1358
+ case "uint8":
1359
+ return Uint8Array;
1360
+ case "int16":
1361
+ return Int16Array;
1362
+ case "uint16":
1363
+ return Uint16Array;
1364
+ case "int32":
1365
+ return Int32Array;
1366
+ case "uint32":
1367
+ return Uint32Array;
1368
+ case "float32":
1369
+ return Float32Array;
1370
+ case "float64":
1371
+ return Float64Array;
1372
+ case "float16":
1373
+ return (0, import_types.getFloat16ArrayConstructor)();
1374
+ default:
1375
+ break;
1376
+ }
1377
+ }
1378
+ return Array;
1379
+ }
1380
+
1381
+ // ../schema-utils/src/lib/schema/convert-arrow-schema.ts
1382
+ var arrow = __toESM(require("apache-arrow"), 1);
1383
+ function convertArrowToSchema(arrowSchema) {
1384
+ return serializeArrowSchema(arrowSchema);
1385
+ }
1386
+ function convertSchemaToArrow(schema, options) {
1387
+ return deserializeArrowSchema(schema, options);
1388
+ }
1389
+ function serializeArrowSchema(arrowSchema) {
1390
+ return {
1391
+ fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
1392
+ metadata: serializeArrowMetadata(arrowSchema.metadata)
1393
+ };
1394
+ }
1395
+ function deserializeArrowSchema(schema, options) {
1396
+ return new arrow.Schema(
1397
+ schema.fields.map((field) => deserializeArrowField(field, options)),
1398
+ deserializeArrowMetadata(schema.metadata)
1399
+ );
1400
+ }
1401
+ function serializeArrowMetadata(arrowMetadata) {
1402
+ return Object.fromEntries(arrowMetadata);
1403
+ }
1404
+ function deserializeArrowMetadata(metadata) {
1405
+ return metadata ? new Map(Object.entries(metadata)) : /* @__PURE__ */ new Map();
1406
+ }
1407
+ function serializeArrowField(field) {
1408
+ return {
1409
+ name: field.name,
1410
+ type: serializeArrowType(field.type),
1411
+ nullable: field.nullable,
1412
+ metadata: serializeArrowMetadata(field.metadata)
1413
+ };
1414
+ }
1415
+ function deserializeArrowField(field, options) {
1416
+ return new arrow.Field(
1417
+ field.name,
1418
+ deserializeArrowType(field.type, options),
1419
+ field.nullable,
1420
+ deserializeArrowMetadata(field.metadata)
1421
+ );
1422
+ }
1423
+ function serializeArrowType(arrowType) {
1424
+ if (isArrowViewType(arrowType, "BinaryView")) {
1425
+ return "binary-view";
1426
+ }
1427
+ if (isArrowViewType(arrowType, "Utf8View")) {
1428
+ return "utf8-view";
1429
+ }
1430
+ if (isOptionalArrowType(arrowType, "LargeList")) {
1431
+ const largeListType = arrowType;
1432
+ return {
1433
+ type: "large-list",
1434
+ children: [serializeArrowField(largeListType.valueField)]
1435
+ };
1436
+ }
1437
+ switch (arrowType.constructor) {
1438
+ case arrow.Null:
1439
+ return "null";
1440
+ case arrow.Binary:
1441
+ return "binary";
1442
+ case arrow.FixedSizeBinary:
1443
+ return {
1444
+ type: "fixed-size-binary",
1445
+ byteWidth: arrowType.byteWidth
1446
+ };
1447
+ case arrow.Bool:
1448
+ return "bool";
1449
+ case arrow.Int:
1450
+ const intType = arrowType;
1451
+ return `${intType.isSigned ? "" : "u"}int${intType.bitWidth}`;
1452
+ case arrow.Int8:
1453
+ return "int8";
1454
+ case arrow.Int16:
1455
+ return "int16";
1456
+ case arrow.Int32:
1457
+ return "int32";
1458
+ case arrow.Int64:
1459
+ return "int64";
1460
+ case arrow.Uint8:
1461
+ return "uint8";
1462
+ case arrow.Uint16:
1463
+ return "uint16";
1464
+ case arrow.Uint32:
1465
+ return "uint32";
1466
+ case arrow.Uint64:
1467
+ return "uint64";
1468
+ case arrow.Float:
1469
+ const precision = arrowType.precision;
1470
+ switch (precision) {
1471
+ case arrow.Precision.HALF:
1472
+ return "float16";
1473
+ case arrow.Precision.SINGLE:
1474
+ return "float32";
1475
+ case arrow.Precision.DOUBLE:
1476
+ return "float64";
1477
+ default:
1478
+ return "float16";
1479
+ }
1480
+ case arrow.Float16:
1481
+ return "float16";
1482
+ case arrow.Float32:
1483
+ return "float32";
1484
+ case arrow.Float64:
1485
+ return "float64";
1486
+ case arrow.Utf8:
1487
+ return "utf8";
1488
+ case arrow.Decimal:
1489
+ const decimal = arrowType;
1490
+ return {
1491
+ type: "decimal",
1492
+ bitWidth: decimal.bitWidth,
1493
+ precision: decimal.precision,
1494
+ scale: decimal.scale
1495
+ };
1496
+ case arrow.Date_:
1497
+ const dateUnit = arrowType.unit;
1498
+ return dateUnit === arrow.DateUnit.DAY ? "date-day" : "date-millisecond";
1499
+ case arrow.DateDay:
1500
+ return "date-day";
1501
+ case arrow.DateMillisecond:
1502
+ return "date-millisecond";
1503
+ case arrow.Time:
1504
+ const timeUnit = arrowType.unit;
1505
+ switch (timeUnit) {
1506
+ case arrow.TimeUnit.SECOND:
1507
+ return "time-second";
1508
+ case arrow.TimeUnit.MILLISECOND:
1509
+ return "time-millisecond";
1510
+ case arrow.TimeUnit.MICROSECOND:
1511
+ return "time-microsecond";
1512
+ case arrow.TimeUnit.NANOSECOND:
1513
+ return "time-nanosecond";
1514
+ default:
1515
+ return "time-second";
1516
+ }
1517
+ case arrow.TimeMillisecond:
1518
+ return "time-millisecond";
1519
+ case arrow.TimeSecond:
1520
+ return "time-second";
1521
+ case arrow.TimeMicrosecond:
1522
+ return "time-microsecond";
1523
+ case arrow.TimeNanosecond:
1524
+ return "time-nanosecond";
1525
+ case arrow.Timestamp:
1526
+ const timeStampUnit = arrowType.unit;
1527
+ switch (timeStampUnit) {
1528
+ case arrow.TimeUnit.SECOND:
1529
+ return "timestamp-second";
1530
+ case arrow.TimeUnit.MILLISECOND:
1531
+ return "timestamp-millisecond";
1532
+ case arrow.TimeUnit.MICROSECOND:
1533
+ return "timestamp-microsecond";
1534
+ case arrow.TimeUnit.NANOSECOND:
1535
+ return "timestamp-nanosecond";
1536
+ default:
1537
+ return "timestamp-second";
1538
+ }
1539
+ case arrow.TimestampSecond:
1540
+ return "timestamp-second";
1541
+ case arrow.TimestampMillisecond:
1542
+ return "timestamp-millisecond";
1543
+ case arrow.TimestampMicrosecond:
1544
+ return "timestamp-microsecond";
1545
+ case arrow.TimestampNanosecond:
1546
+ return "timestamp-nanosecond";
1547
+ case arrow.Interval:
1548
+ const intervalUnit = arrowType.unit;
1549
+ switch (intervalUnit) {
1550
+ case arrow.IntervalUnit.DAY_TIME:
1551
+ return "interval-daytime";
1552
+ case arrow.IntervalUnit.YEAR_MONTH:
1553
+ return "interval-yearmonth";
1554
+ default:
1555
+ return "interval-daytime";
1556
+ }
1557
+ case arrow.IntervalDayTime:
1558
+ return "interval-daytime";
1559
+ case arrow.IntervalYearMonth:
1560
+ return "interval-yearmonth";
1561
+ case arrow.Map_:
1562
+ const mapType = arrowType;
1563
+ return {
1564
+ type: "map",
1565
+ keysSorted: mapType.keysSorted,
1566
+ children: mapType.children.map((arrowField) => serializeArrowField(arrowField))
1567
+ };
1568
+ case arrow.List:
1569
+ const listType = arrowType;
1570
+ const listField = listType.valueField;
1571
+ return {
1572
+ type: "list",
1573
+ children: [serializeArrowField(listField)]
1574
+ };
1575
+ case arrow.FixedSizeList:
1576
+ const fixedSizeList = arrowType;
1577
+ return {
1578
+ type: "fixed-size-list",
1579
+ listSize: fixedSizeList.listSize,
1580
+ children: [serializeArrowField(fixedSizeList.children[0])]
1581
+ };
1582
+ case arrow.Struct:
1583
+ const structType = arrowType;
1584
+ return {
1585
+ type: "struct",
1586
+ children: structType.children.map((arrowField) => serializeArrowField(arrowField))
1587
+ };
1588
+ case arrow.SparseUnion:
1589
+ case arrow.DenseUnion:
1590
+ const unionType = arrowType;
1591
+ return {
1592
+ type: unionType instanceof arrow.DenseUnion ? "dense-union" : "sparse-union",
1593
+ typeIds: unionType.typeIds,
1594
+ children: unionType.children.map((arrowField) => serializeArrowField(arrowField)),
1595
+ typeIdToChildIndex: { ...unionType.typeIdToChildIndex }
1596
+ };
1597
+ case arrow.Dictionary:
1598
+ const dictionaryType = arrowType;
1599
+ return {
1600
+ type: "dictionary",
1601
+ id: dictionaryType.id,
1602
+ indices: serializeArrowDictionaryKeyType(dictionaryType.indices),
1603
+ dictionary: serializeArrowType(dictionaryType.dictionary),
1604
+ isOrdered: dictionaryType.isOrdered
1605
+ };
1606
+ default:
1607
+ throw new Error(`arrow type not supported: ${arrowType.constructor.name}`);
1608
+ }
1609
+ }
1610
+ function deserializeArrowType(dataType, options) {
1611
+ if (typeof dataType === "object") {
1612
+ switch (dataType.type) {
1613
+ case "decimal":
1614
+ return new arrow.Decimal(dataType.scale, dataType.precision, dataType.bitWidth);
1615
+ case "map": {
1616
+ const children = dataType.children.map(
1617
+ (arrowField) => deserializeArrowField(arrowField, options)
1618
+ );
1619
+ return new arrow.Map_(children[0], dataType.keysSorted);
1620
+ }
1621
+ case "list": {
1622
+ const field = deserializeArrowField(dataType.children[0], options);
1623
+ return new arrow.List(field);
1624
+ }
1625
+ case "large-list": {
1626
+ const field = deserializeArrowField(dataType.children[0], options);
1627
+ const LargeList = getOptionalArrowConstructor("LargeList");
1628
+ if (!LargeList) {
1629
+ throw new Error(
1630
+ "LargeList requires an Apache Arrow runtime that exports the LargeList constructor"
1631
+ );
1632
+ }
1633
+ return new LargeList(field);
1634
+ }
1635
+ case "fixed-size-list": {
1636
+ const child = deserializeArrowField(dataType.children[0], options);
1637
+ return new arrow.FixedSizeList(dataType.listSize, child);
1638
+ }
1639
+ case "fixed-size-binary":
1640
+ return new arrow.FixedSizeBinary(dataType.byteWidth);
1641
+ case "struct": {
1642
+ const children = dataType.children.map(
1643
+ (arrowField) => deserializeArrowField(arrowField, options)
1644
+ );
1645
+ return new arrow.Struct(children);
1646
+ }
1647
+ case "sparse-union":
1648
+ case "dense-union": {
1649
+ const children = dataType.children.map(
1650
+ (arrowField) => deserializeArrowField(arrowField, options)
1651
+ );
1652
+ return dataType.type === "dense-union" ? new arrow.DenseUnion(dataType.typeIds, children) : new arrow.SparseUnion(dataType.typeIds, children);
1653
+ }
1654
+ case "dictionary": {
1655
+ return new arrow.Dictionary(
1656
+ deserializeArrowType(dataType.dictionary, options),
1657
+ deserializeArrowDictionaryKeyType(dataType.indices),
1658
+ dataType.id,
1659
+ dataType.isOrdered
1660
+ );
1661
+ }
1662
+ default:
1663
+ throw new Error("array type not supported");
1664
+ }
1665
+ }
1666
+ switch (dataType) {
1667
+ case "null":
1668
+ return new arrow.Null();
1669
+ case "binary":
1670
+ return makeVariableWidthArrowType("BinaryView", new arrow.Binary(), options);
1671
+ case "binary-view":
1672
+ return makeRequiredArrowViewType("BinaryView");
1673
+ case "bool":
1674
+ return new arrow.Bool();
1675
+ case "int8":
1676
+ return new arrow.Int8();
1677
+ case "int16":
1678
+ return new arrow.Int16();
1679
+ case "int32":
1680
+ return new arrow.Int32();
1681
+ case "int64":
1682
+ return new arrow.Int64();
1683
+ case "uint8":
1684
+ return new arrow.Uint8();
1685
+ case "uint16":
1686
+ return new arrow.Uint16();
1687
+ case "uint32":
1688
+ return new arrow.Uint32();
1689
+ case "uint64":
1690
+ return new arrow.Uint64();
1691
+ case "float16":
1692
+ return new arrow.Float16();
1693
+ case "float32":
1694
+ return new arrow.Float32();
1695
+ case "float64":
1696
+ return new arrow.Float64();
1697
+ case "utf8":
1698
+ return makeVariableWidthArrowType("Utf8View", new arrow.Utf8(), options);
1699
+ case "utf8-view":
1700
+ return makeRequiredArrowViewType("Utf8View");
1701
+ case "date-day":
1702
+ return new arrow.DateDay();
1703
+ case "date-millisecond":
1704
+ return new arrow.DateMillisecond();
1705
+ case "time-second":
1706
+ return new arrow.TimeSecond();
1707
+ case "time-millisecond":
1708
+ return new arrow.TimeMillisecond();
1709
+ case "time-microsecond":
1710
+ return new arrow.TimeMicrosecond();
1711
+ case "time-nanosecond":
1712
+ return new arrow.TimeNanosecond();
1713
+ case "timestamp-second":
1714
+ return new arrow.TimestampSecond();
1715
+ case "timestamp-millisecond":
1716
+ return new arrow.TimestampMillisecond();
1717
+ case "timestamp-microsecond":
1718
+ return new arrow.TimestampMicrosecond();
1719
+ case "timestamp-nanosecond":
1720
+ return new arrow.TimestampNanosecond();
1721
+ case "interval-daytime":
1722
+ return new arrow.IntervalDayTime();
1723
+ case "interval-yearmonth":
1724
+ return new arrow.IntervalYearMonth();
1725
+ default:
1726
+ throw new Error("array type not supported");
1727
+ }
1728
+ }
1729
+ function getOptionalArrowConstructor(typeName) {
1730
+ return arrow[typeName];
1731
+ }
1732
+ function isArrowViewType(arrowType, viewTypeName) {
1733
+ const constructor = getOptionalArrowConstructor(viewTypeName);
1734
+ if (constructor && arrowType instanceof constructor) {
1735
+ return true;
1736
+ }
1737
+ const guards = arrow.DataType;
1738
+ const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
1739
+ return Boolean(guard == null ? void 0 : guard(arrowType));
1740
+ }
1741
+ function isOptionalArrowType(arrowType, typeName) {
1742
+ const constructor = getOptionalArrowConstructor(typeName);
1743
+ return Boolean(constructor && arrowType instanceof constructor);
1744
+ }
1745
+ function makeVariableWidthArrowType(viewTypeName, fallbackType, options) {
1746
+ const viewTypeMode = (options == null ? void 0 : options.viewTypes) || "never";
1747
+ if (viewTypeMode === "never") {
1748
+ return fallbackType;
1749
+ }
1750
+ const constructor = getOptionalArrowConstructor(viewTypeName);
1751
+ if (constructor) {
1752
+ return new constructor();
1753
+ }
1754
+ if (viewTypeMode === "require") {
1755
+ throw new Error(
1756
+ `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
1757
+ );
1758
+ }
1759
+ return fallbackType;
1760
+ }
1761
+ function makeRequiredArrowViewType(viewTypeName) {
1762
+ const constructor = getOptionalArrowConstructor(viewTypeName);
1763
+ if (!constructor) {
1764
+ throw new Error(
1765
+ `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
1766
+ );
1767
+ }
1768
+ return new constructor();
1769
+ }
1770
+ function serializeArrowDictionaryKeyType(arrowType) {
1771
+ if (arrowType instanceof arrow.Int) {
1772
+ const prefix = arrowType.isSigned ? "int" : "uint";
1773
+ const keyType = `${prefix}${arrowType.bitWidth}`;
1774
+ if (isSchemaDictionaryKeyType(keyType)) {
1775
+ return keyType;
1776
+ }
1777
+ }
1778
+ switch (arrowType.constructor) {
1779
+ case arrow.Int8:
1780
+ return "int8";
1781
+ case arrow.Int16:
1782
+ return "int16";
1783
+ case arrow.Int32:
1784
+ return "int32";
1785
+ case arrow.Uint8:
1786
+ return "uint8";
1787
+ case arrow.Uint16:
1788
+ return "uint16";
1789
+ case arrow.Uint32:
1790
+ return "uint32";
1791
+ default:
1792
+ throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
1793
+ }
1794
+ }
1795
+ function isSchemaDictionaryKeyType(keyType) {
1796
+ return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
1797
+ }
1798
+ function deserializeArrowDictionaryKeyType(keyType) {
1799
+ switch (keyType) {
1800
+ case "int8":
1801
+ return new arrow.Int8();
1802
+ case "int16":
1803
+ return new arrow.Int16();
1804
+ case "int32":
1805
+ return new arrow.Int32();
1806
+ case "uint8":
1807
+ return new arrow.Uint8();
1808
+ case "uint16":
1809
+ return new arrow.Uint16();
1810
+ case "uint32":
1811
+ return new arrow.Uint32();
1812
+ default:
1813
+ throw new Error(`schema dictionary index type not supported: ${keyType}`);
1814
+ }
1815
+ }
1816
+
1817
+ // ../schema-utils/src/lib/schema/deduce-table-schema.ts
1818
+ function deduceTableSchema(table) {
1819
+ switch (table.shape) {
1820
+ case "array-row-table":
1821
+ case "object-row-table":
1822
+ return deduceSchemaFromRows(table.data);
1823
+ case "geojson-table":
1824
+ return deduceSchemaFromGeoJSON(table.features);
1825
+ case "columnar-table":
1826
+ return deduceSchemaFromColumns(table.data);
1827
+ case "arrow-table":
1828
+ default:
1829
+ throw new Error("Deduce schema");
1830
+ }
1831
+ }
1832
+ function deduceSchemaFromColumns(columnarTable) {
1833
+ const fields = [];
1834
+ for (const [columnName, column] of Object.entries(columnarTable)) {
1835
+ const field = deduceFieldFromColumn(column, columnName);
1836
+ fields.push(field);
1837
+ }
1838
+ return { fields, metadata: {} };
1839
+ }
1840
+ function deduceSchemaFromRows(rowTable) {
1841
+ if (!rowTable.length) {
1842
+ throw new Error("deduce from empty table");
1843
+ }
1844
+ const fields = [];
1845
+ const row0 = rowTable[0];
1846
+ for (const [columnName, value] of Object.entries(row0)) {
1847
+ fields.push(deduceFieldFromValue(value, columnName));
1848
+ }
1849
+ return { fields, metadata: {} };
1850
+ }
1851
+ function deduceSchemaFromGeoJSON(features) {
1852
+ if (!features.length) {
1853
+ throw new Error("deduce from empty table");
1854
+ }
1855
+ const fields = [];
1856
+ const row0 = features[0].properties || {};
1857
+ for (const [columnName, value] of Object.entries(row0)) {
1858
+ fields.push(deduceFieldFromValue(value, columnName));
1859
+ }
1860
+ return { fields, metadata: {} };
1861
+ }
1862
+ function deduceFieldFromColumn(column, name) {
1863
+ if (ArrayBuffer.isView(column)) {
1864
+ const type = getDataTypeFromArray(column);
1865
+ return {
1866
+ name,
1867
+ type: type.type || "null",
1868
+ nullable: type.nullable
1869
+ // metadata: {}
1870
+ };
1871
+ }
1872
+ if (Array.isArray(column) && column.length > 0) {
1873
+ const value = column[0];
1874
+ const type = getDataTypeFromValue(value);
1875
+ return {
1876
+ name,
1877
+ type,
1878
+ nullable: true
1879
+ // metadata: {},
1880
+ };
1881
+ }
1882
+ throw new Error("empty table");
1883
+ }
1884
+ function deduceFieldFromValue(value, name) {
1885
+ const type = getDataTypeFromValue(value);
1886
+ return {
1887
+ name,
1888
+ type,
1889
+ nullable: true
1890
+ // metadata: {}
1891
+ };
1892
+ }
1893
+
1894
+ // ../schema-utils/src/lib/table/tables/make-table.ts
1895
+ var arrow2 = __toESM(require("apache-arrow"), 1);
1896
+ function makeTableFromData(data) {
1897
+ let table;
1898
+ switch (getTableShapeFromData(data)) {
1899
+ case "array-row-table":
1900
+ table = { shape: "array-row-table", data };
1901
+ break;
1902
+ case "object-row-table":
1903
+ table = { shape: "object-row-table", data };
1904
+ break;
1905
+ case "columnar-table":
1906
+ table = { shape: "columnar-table", data };
1907
+ break;
1908
+ case "arrow-table":
1909
+ table = { shape: "arrow-table", data };
1910
+ break;
1911
+ default:
1912
+ throw new Error("table");
1913
+ }
1914
+ const schema = deduceTableSchema(table);
1915
+ return { ...table, schema };
1916
+ }
1917
+ function getTableShapeFromData(data) {
1918
+ if (data instanceof arrow2.Table) {
1919
+ return "arrow-table";
1920
+ }
1921
+ if (Array.isArray(data)) {
1922
+ if (data.length === 0) {
1923
+ throw new Error("cannot deduce type of empty table");
1924
+ }
1925
+ const firstRow = data[0];
1926
+ if (Array.isArray(firstRow)) {
1927
+ return "array-row-table";
1928
+ }
1929
+ if (firstRow && typeof firstRow === "object") {
1930
+ return "object-row-table";
1931
+ }
1932
+ }
1933
+ if (data && typeof data === "object") {
1934
+ return "columnar-table";
1935
+ }
1936
+ throw new Error("invalid table");
1937
+ }
1938
+
1939
+ // ../schema-utils/src/lib/table/tables/table-accessors.ts
1940
+ function getTableLength(table) {
1941
+ switch (table.shape) {
1942
+ case "array-row-table":
1943
+ case "object-row-table":
1944
+ return table.data.length;
1945
+ case "geojson-table":
1946
+ return table.features.length;
1947
+ case "arrow-table":
1948
+ const arrowTable = table.data;
1949
+ return arrowTable.numRows;
1950
+ case "columnar-table":
1951
+ for (const column of Object.values(table.data)) {
1952
+ return column.length || 0;
1953
+ }
1954
+ return 0;
1955
+ default:
1956
+ throw new Error("table");
1957
+ }
1958
+ }
1959
+ function getTableNumCols(table) {
1960
+ if (table.schema) {
1961
+ return table.schema.fields.length;
1962
+ }
1963
+ if (getTableLength(table) === 0) {
1964
+ throw new Error("empty table");
1965
+ }
1966
+ switch (table.shape) {
1967
+ case "array-row-table":
1968
+ return table.data[0].length;
1969
+ case "object-row-table":
1970
+ return Object.keys(table.data[0]).length;
1971
+ case "geojson-table":
1972
+ return Object.keys(table.features[0]).length;
1973
+ case "columnar-table":
1974
+ return Object.keys(table.data).length;
1975
+ case "arrow-table":
1976
+ const arrowTable = table.data;
1977
+ return arrowTable.numCols;
1978
+ default:
1979
+ throw new Error("table");
1980
+ }
1981
+ }
1982
+ function getTableCell(table, rowIndex, columnName) {
1983
+ var _a;
1984
+ switch (table.shape) {
1985
+ case "array-row-table":
1986
+ const columnIndex = getTableColumnIndex(table, columnName);
1987
+ return table.data[rowIndex][columnIndex];
1988
+ case "object-row-table":
1989
+ return table.data[rowIndex][columnName];
1990
+ case "geojson-table":
1991
+ return table.features[rowIndex][columnName];
1992
+ case "columnar-table":
1993
+ const column = table.data[columnName];
1994
+ return column[rowIndex];
1995
+ case "arrow-table":
1996
+ const arrowTable = table.data;
1997
+ const arrowColumnIndex = arrowTable.schema.fields.findIndex(
1998
+ (field) => field.name === columnName
1999
+ );
2000
+ return (_a = arrowTable.getChildAt(arrowColumnIndex)) == null ? void 0 : _a.get(rowIndex);
2001
+ default:
2002
+ throw new Error("todo");
2003
+ }
2004
+ }
2005
+ function getTableCellAt(table, rowIndex, columnIndex) {
2006
+ var _a;
2007
+ switch (table.shape) {
2008
+ case "array-row-table":
2009
+ return table.data[rowIndex][columnIndex];
2010
+ case "object-row-table":
2011
+ const columnName1 = getTableColumnName(table, columnIndex);
2012
+ return table.data[rowIndex][columnName1];
2013
+ case "geojson-table":
2014
+ const columnName2 = getTableColumnName(table, columnIndex);
2015
+ return table.features[rowIndex][columnName2];
2016
+ case "columnar-table":
2017
+ const columnName3 = getTableColumnName(table, columnIndex);
2018
+ const column = table.data[columnName3];
2019
+ return column[rowIndex];
2020
+ case "arrow-table":
2021
+ const arrowTable = table.data;
2022
+ return (_a = arrowTable.getChildAt(columnIndex)) == null ? void 0 : _a.get(rowIndex);
2023
+ default:
2024
+ throw new Error("todo");
2025
+ }
2026
+ }
2027
+ function getTableColumnIndex(table, columnName) {
2028
+ var _a;
2029
+ const columnIndex = (_a = table.schema) == null ? void 0 : _a.fields.findIndex((field) => field.name === columnName);
2030
+ if (columnIndex === void 0) {
2031
+ throw new Error(columnName);
2032
+ }
2033
+ return columnIndex;
2034
+ }
2035
+ function getTableColumnName(table, columnIndex) {
2036
+ var _a, _b;
2037
+ const columnName = (_b = (_a = table.schema) == null ? void 0 : _a.fields[columnIndex]) == null ? void 0 : _b.name;
2038
+ if (!columnName) {
2039
+ throw new Error(`${columnIndex}`);
2040
+ }
2041
+ return columnName;
2042
+ }
2043
+ function getTableRowAsObject(table, rowIndex, target, copy) {
2044
+ switch (table.shape) {
2045
+ case "object-row-table":
2046
+ return copy ? Object.fromEntries(Object.entries(table.data[rowIndex])) : table.data[rowIndex];
2047
+ case "array-row-table":
2048
+ if (table.schema) {
2049
+ const objectRow2 = target || {};
2050
+ for (let i = 0; i < table.schema.fields.length; i++) {
2051
+ objectRow2[table.schema.fields[i].name] = table.data[rowIndex][i];
2052
+ }
2053
+ return objectRow2;
2054
+ }
2055
+ throw new Error("no schema");
2056
+ case "geojson-table":
2057
+ if (table.schema) {
2058
+ const objectRow2 = target || {};
2059
+ for (let i = 0; i < table.schema.fields.length; i++) {
2060
+ objectRow2[table.schema.fields[i].name] = table.features[rowIndex][table.schema.fields[i].name];
2061
+ }
2062
+ return objectRow2;
2063
+ }
2064
+ throw new Error("no schema");
2065
+ case "columnar-table":
2066
+ if (table.schema) {
2067
+ const objectRow2 = target || {};
2068
+ for (let i = 0; i < table.schema.fields.length; i++) {
2069
+ objectRow2[table.schema.fields[i].name] = table.data[table.schema.fields[i].name][rowIndex];
2070
+ }
2071
+ return objectRow2;
2072
+ } else {
2073
+ const objectRow2 = target || {};
2074
+ for (const [name, column] of Object.entries(table.data)) {
2075
+ objectRow2[name] = column[rowIndex];
2076
+ }
2077
+ return objectRow2;
2078
+ }
2079
+ case "arrow-table":
2080
+ const arrowTable = table.data;
2081
+ const objectRow = target || {};
2082
+ const row = arrowTable.get(rowIndex);
2083
+ const schema = arrowTable.schema;
2084
+ for (let i = 0; i < schema.fields.length; i++) {
2085
+ objectRow[schema.fields[i].name] = row == null ? void 0 : row[schema.fields[i].name];
2086
+ }
2087
+ return objectRow;
2088
+ default:
2089
+ throw new Error("shape");
2090
+ }
2091
+ }
2092
+ function getTableRowAsArray(table, rowIndex, target, copy) {
2093
+ switch (table.shape) {
2094
+ case "array-row-table":
2095
+ return copy ? Array.from(table.data[rowIndex]) : table.data[rowIndex];
2096
+ case "object-row-table":
2097
+ if (table.schema) {
2098
+ const arrayRow2 = target || [];
2099
+ for (let i = 0; i < table.schema.fields.length; i++) {
2100
+ arrayRow2[i] = table.data[rowIndex][table.schema.fields[i].name];
2101
+ }
2102
+ return arrayRow2;
2103
+ }
2104
+ return Object.values(table.data[rowIndex]);
2105
+ case "geojson-table":
2106
+ if (table.schema) {
2107
+ const arrayRow2 = target || [];
2108
+ for (let i = 0; i < table.schema.fields.length; i++) {
2109
+ arrayRow2[i] = table.features[rowIndex][table.schema.fields[i].name];
2110
+ }
2111
+ return arrayRow2;
2112
+ }
2113
+ return Object.values(table.features[rowIndex]);
2114
+ case "columnar-table":
2115
+ if (table.schema) {
2116
+ const arrayRow2 = target || [];
2117
+ for (let i = 0; i < table.schema.fields.length; i++) {
2118
+ arrayRow2[i] = table.data[table.schema.fields[i].name][rowIndex];
2119
+ }
2120
+ return arrayRow2;
2121
+ } else {
2122
+ const arrayRow2 = target || [];
2123
+ let i = 0;
2124
+ for (const column of Object.values(table.data)) {
2125
+ arrayRow2[i] = column[rowIndex];
2126
+ i++;
2127
+ }
2128
+ return arrayRow2;
2129
+ }
2130
+ case "arrow-table":
2131
+ const arrowTable = table.data;
2132
+ const arrayRow = target || [];
2133
+ const row = arrowTable.get(rowIndex);
2134
+ const schema = arrowTable.schema;
2135
+ for (let i = 0; i < schema.fields.length; i++) {
2136
+ arrayRow[i] = row == null ? void 0 : row[schema.fields[i].name];
2137
+ }
2138
+ return arrayRow;
2139
+ default:
2140
+ throw new Error("shape");
2141
+ }
2142
+ }
2143
+
2144
+ // ../schema-utils/src/lib/table/tables/table-column.ts
2145
+ function makeColumnFromField(field, length) {
2146
+ const ArrayType = getArrayTypeFromDataType(field.type, field.nullable);
2147
+ return new ArrayType(length);
2148
+ }
2149
+
2150
+ // ../schema-utils/src/lib/table/tables/convert-arrow-table.ts
2151
+ var arrow4 = __toESM(require("apache-arrow"), 1);
2152
+
2153
+ // ../schema-utils/src/lib/table/batches/make-arrow-batch-iterator.ts
2154
+ var arrow3 = __toESM(require("apache-arrow"), 1);
2155
+ function* makeArrowRecordBatchIterator(table, options) {
2156
+ const arrowSchema = convertSchemaToArrow(table.schema);
2157
+ const length = getTableLength(table);
2158
+ const numColumns = getTableNumCols(table);
2159
+ const batchSize = (options == null ? void 0 : options.batchSize) || length;
2160
+ const builders = arrowSchema == null ? void 0 : arrowSchema.fields.map(
2161
+ (arrowField) => arrow3.makeBuilder({
2162
+ type: arrowField.type,
2163
+ nullValues: [null, void 0]
2164
+ })
2165
+ );
2166
+ const structField = new arrow3.Struct(arrowSchema.fields);
2167
+ let batchLength = 0;
2168
+ for (let rowIndex = 0; rowIndex < length; rowIndex++) {
2169
+ for (let columnIndex = 0; columnIndex < numColumns; ++columnIndex) {
2170
+ const value = getTableCellAt(table, rowIndex, columnIndex);
2171
+ const builder = builders[columnIndex];
2172
+ builder.append(value);
2173
+ }
2174
+ batchLength++;
2175
+ if (batchLength >= batchSize) {
2176
+ const datas = builders.map((builder) => builder.flush());
2177
+ const structData = new arrow3.Data(structField, 0, batchLength, 0, void 0, datas);
2178
+ yield new arrow3.RecordBatch(arrowSchema, structData);
2179
+ batchLength = 0;
2180
+ }
2181
+ }
2182
+ if (batchLength > 0) {
2183
+ const datas = builders.map((builder) => builder.flush());
2184
+ const structData = new arrow3.Data(structField, 0, batchLength, 0, void 0, datas);
2185
+ yield new arrow3.RecordBatch(arrowSchema, structData);
2186
+ batchLength = 0;
2187
+ }
2188
+ builders.map((builder) => builder.finish());
2189
+ }
2190
+
2191
+ // ../schema-utils/src/lib/table/tables/convert-arrow-table.ts
2192
+ function convertTableToArrow(table, options) {
2193
+ switch (table.shape) {
2194
+ case "arrow-table":
2195
+ return table.data;
2196
+ case "columnar-table":
2197
+ // TODO - optimized implementation is possible
2198
+ // return convertColumnarTableToArrow(table, options);
2199
+ // fall through
2200
+ default:
2201
+ const arrowBatchIterator = makeArrowRecordBatchIterator(table, options);
2202
+ return new arrow4.Table(arrowBatchIterator);
2203
+ }
2204
+ }
2205
+ function convertArrowToTable(arrowTable, shape) {
2206
+ switch (shape) {
2207
+ case "arrow-table":
2208
+ return convertArrowToArrowTable(arrowTable);
2209
+ case "array-row-table":
2210
+ return convertArrowToArrayRowTable(arrowTable);
2211
+ case "object-row-table":
2212
+ return convertArrowToObjectRowTable(arrowTable);
2213
+ case "columnar-table":
2214
+ return convertArrowToColumnarTable(arrowTable);
2215
+ case "geojson-table":
2216
+ return convertArrowToGeoJSONTable(arrowTable);
2217
+ default:
2218
+ throw new Error(shape);
2219
+ }
2220
+ }
2221
+ function convertArrowToArrowTable(arrowTable) {
2222
+ return {
2223
+ shape: "arrow-table",
2224
+ schema: convertArrowToSchema(arrowTable.schema),
2225
+ data: arrowTable
2226
+ };
2227
+ }
2228
+ function convertArrowToArrayRowTable(arrowTable) {
2229
+ const columnarTable = convertArrowToColumnarTable(arrowTable);
2230
+ return convertTable(columnarTable, "array-row-table");
2231
+ }
2232
+ function convertArrowToObjectRowTable(arrowTable) {
2233
+ const columnarTable = convertArrowToColumnarTable(arrowTable);
2234
+ return convertTable(columnarTable, "object-row-table");
2235
+ }
2236
+ function convertArrowToColumnarTable(arrowTable) {
2237
+ const columns = {};
2238
+ for (const field of arrowTable.schema.fields) {
2239
+ const arrowColumn = arrowTable.getChild(field.name);
2240
+ const values = arrowColumn == null ? void 0 : arrowColumn.toArray();
2241
+ columns[field.name] = values;
2242
+ }
2243
+ const schema = convertArrowToSchema(arrowTable.schema);
2244
+ return {
2245
+ shape: "columnar-table",
2246
+ schema,
2247
+ data: columns
2248
+ };
2249
+ }
2250
+ function convertArrowToGeoJSONTable(arrowTable) {
2251
+ var _a;
2252
+ const schema = convertArrowToSchema(arrowTable.schema);
2253
+ const features = [];
2254
+ for (let row = 0; row < arrowTable.numRows; row++) {
2255
+ const properties = ((_a = arrowTable.get(row)) == null ? void 0 : _a.toJSON()) || {};
2256
+ features.push({ type: "Feature", geometry: null, properties });
2257
+ }
2258
+ return {
2259
+ shape: "geojson-table",
2260
+ type: "FeatureCollection",
2261
+ schema,
2262
+ features
2263
+ };
2264
+ }
2265
+
2266
+ // ../schema-utils/src/lib/table/tables/convert-table.ts
2267
+ function convertTable(table, shape) {
2268
+ switch (shape) {
2269
+ case "object-row-table":
2270
+ return convertToObjectRowTable(table);
2271
+ case "array-row-table":
2272
+ return convertToArrayRowTable(table);
2273
+ case "columnar-table":
2274
+ return convertToColumnarTable(table);
2275
+ case "arrow-table":
2276
+ return convertToArrowTable(table);
2277
+ default:
2278
+ throw new Error(shape);
2279
+ }
2280
+ }
2281
+ function convertToColumnarTable(table) {
2282
+ const schema = table.schema || deduceTableSchema(table);
2283
+ const fields = schema.fields;
2284
+ if (table.shape === "columnar-table") {
2285
+ return { ...table, schema };
2286
+ }
2287
+ const length = getTableLength(table);
2288
+ const columns = {};
2289
+ for (const field of fields) {
2290
+ const column = makeColumnFromField(field, length);
2291
+ columns[field.name] = column;
2292
+ for (let rowIndex = 0; rowIndex < length; rowIndex++) {
2293
+ column[rowIndex] = getTableCell(table, rowIndex, field.name);
2294
+ }
2295
+ }
2296
+ return {
2297
+ shape: "columnar-table",
2298
+ schema,
2299
+ data: columns
2300
+ };
2301
+ }
2302
+ function convertToArrayRowTable(table) {
2303
+ if (table.shape === "array-row-table") {
2304
+ return table;
2305
+ }
2306
+ const length = getTableLength(table);
2307
+ const data = new Array(length);
2308
+ for (let rowIndex = 0; rowIndex < length; rowIndex++) {
2309
+ data[rowIndex] = getTableRowAsArray(table, rowIndex);
2310
+ }
2311
+ return {
2312
+ shape: "array-row-table",
2313
+ schema: table.schema,
2314
+ data
2315
+ };
2316
+ }
2317
+ function convertToObjectRowTable(table) {
2318
+ if (table.shape === "object-row-table") {
2319
+ return table;
2320
+ }
2321
+ const length = getTableLength(table);
2322
+ const data = new Array(length);
2323
+ for (let rowIndex = 0; rowIndex < length; rowIndex++) {
2324
+ data[rowIndex] = getTableRowAsObject(table, rowIndex);
2325
+ }
2326
+ return {
2327
+ shape: "object-row-table",
2328
+ schema: table.schema,
2329
+ data
2330
+ };
2331
+ }
2332
+ function convertToArrowTable(table) {
2333
+ const schema = table.schema || deduceTableSchema(table);
2334
+ const arrowTable = convertTableToArrow({ ...table, schema });
2335
+ return {
2336
+ shape: "arrow-table",
2337
+ schema,
2338
+ data: arrowTable
2339
+ };
2340
+ }
2341
+
2342
+ // ../schema-utils/src/deprecated.ts
2343
+ var convertArrowToTable2 = ((...args) => convertArrowToTable(
2344
+ ...args
2345
+ ));
45
2346
 
46
2347
  // dist/sql-utils.js
47
- var arrow = __toESM(require("apache-arrow"), 1);
48
- var import_schema_utils = require("@loaders.gl/schema-utils");
49
2348
  function isNodeRuntime() {
50
2349
  var _a;
51
2350
  return typeof process !== "undefined" && Boolean((_a = process.versions) == null ? void 0 : _a.node);
@@ -57,19 +2356,19 @@ function quoteSqlIdentifier(identifier) {
57
2356
  return `"${identifier.replace(/"/g, '""')}"`;
58
2357
  }
59
2358
  function convertRowsToArrowTable(rows) {
60
- const table = rows.length > 0 ? (0, import_schema_utils.makeTableFromData)(rows) : { shape: "object-row-table", schema: { fields: [], metadata: {} }, data: rows };
2359
+ const table = rows.length > 0 ? makeTableFromData(rows) : { shape: "object-row-table", schema: { fields: [], metadata: {} }, data: rows };
61
2360
  const schema = deducePrimitiveAwareSchema(table);
62
2361
  if (table.data.length === 0 || schema.fields.length === 0) {
63
2362
  return {
64
2363
  shape: "arrow-table",
65
2364
  schema,
66
- data: new arrow.Table(new arrow.Schema([]))
2365
+ data: new arrow5.Table(new arrow5.Schema([]))
67
2366
  };
68
2367
  }
69
2368
  return {
70
2369
  shape: "arrow-table",
71
2370
  schema,
72
- data: arrow.tableFromJSON(table.data)
2371
+ data: arrow5.tableFromJSON(table.data)
73
2372
  };
74
2373
  }
75
2374
  function convertSQLColumnsToSchema(columns) {
@@ -121,7 +2420,7 @@ function deducePrimitiveAwareSchema(table) {
121
2420
  return field;
122
2421
  }
123
2422
  const columnValues = table.data.map((row) => row[field.name]);
124
- const inferredType = (0, import_schema_utils.getDataTypeFromArray)(columnValues);
2423
+ const inferredType = getDataTypeFromArray(columnValues);
125
2424
  return { ...field, type: inferredType.type, nullable: inferredType.nullable };
126
2425
  })
127
2426
  };
@@ -131,6 +2430,28 @@ function getQualifiedTableName(options) {
131
2430
  return identifiers.map((identifier) => quoteSqlIdentifier(identifier)).join(".");
132
2431
  }
133
2432
 
2433
+ // dist/table-query-capabilities.js
2434
+ var ARROW_TABLE_QUERY_CAPABILITIES = Object.freeze({
2435
+ projection: "residual",
2436
+ predicate: "residual",
2437
+ limit: "residual",
2438
+ streaming: false,
2439
+ cancellation: true,
2440
+ expressions: "residual",
2441
+ orderBy: "residual",
2442
+ aggregates: "residual"
2443
+ });
2444
+ var SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES = Object.freeze({
2445
+ projection: "pushdown",
2446
+ predicate: "pushdown",
2447
+ limit: "pushdown",
2448
+ streaming: false,
2449
+ cancellation: false,
2450
+ expressions: "pushdown",
2451
+ orderBy: "pushdown",
2452
+ aggregates: "pushdown"
2453
+ });
2454
+
134
2455
  // dist/sql-source.js
135
2456
  var SQL_ADAPTER_FACTORIES = /* @__PURE__ */ new Map();
136
2457
  function registerSQLAdapter(type, factory) {
@@ -163,7 +2484,9 @@ var SQL_SOURCE_DEFAULT_OPTIONS = {
163
2484
  authenticator: void 0
164
2485
  }
165
2486
  };
166
- var SQLDataSource = class extends import_loader_utils.DataSource {
2487
+ var SQLDataSource = class extends DataSource {
2488
+ /** Optimization and execution capabilities of portable table-bound queries. */
2489
+ tableQueryCapabilities = SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES;
167
2490
  sourceType;
168
2491
  adapterFactory;
169
2492
  adapterPromise = null;
@@ -201,17 +2524,19 @@ var SQLDataSource = class extends import_loader_utils.DataSource {
201
2524
  return await adapter.getTableSchema(options);
202
2525
  }
203
2526
  /** Executes a SQL query and returns object rows. */
204
- async queryRows(sqlText, options = {}) {
2527
+ async queryRows(query, options = {}) {
205
2528
  const adapter = await this.getAdapter();
206
- return await adapter.executeRows(sqlText, options);
2529
+ const compiledQuery = this.compileQuery(query, options);
2530
+ return await adapter.executeRows(compiledQuery.sql, compiledQuery.options);
207
2531
  }
208
2532
  /** Executes a SQL query and returns a loaders.gl Arrow table. */
209
- async queryArrow(sqlText, options = {}) {
2533
+ async queryArrow(query, options = {}) {
210
2534
  const adapter = await this.getAdapter();
2535
+ const compiledQuery = this.compileQuery(query, options);
211
2536
  if (adapter.executeArrow) {
212
- return await adapter.executeArrow(sqlText, options);
2537
+ return await adapter.executeArrow(compiledQuery.sql, compiledQuery.options);
213
2538
  }
214
- const rows = await adapter.executeRows(sqlText, options);
2539
+ const rows = await adapter.executeRows(compiledQuery.sql, compiledQuery.options);
215
2540
  return convertRowsToArrowTable(rows);
216
2541
  }
217
2542
  /** Closes any underlying adapter connection. */
@@ -230,6 +2555,21 @@ var SQLDataSource = class extends import_loader_utils.DataSource {
230
2555
  }
231
2556
  return await this.adapterPromise;
232
2557
  }
2558
+ /** Converts a portable query object to SQL while leaving raw SQL text unchanged. */
2559
+ compileQuery(query, options) {
2560
+ if (typeof query === "string") {
2561
+ return { sql: query, options };
2562
+ }
2563
+ const namedParameters = options.parameters && !Array.isArray(options.parameters) ? options.parameters : void 0;
2564
+ const compiledQuery = compileSQLTableQuery(query, {
2565
+ dialect: getSQLTableQueryDialect(this.sourceType),
2566
+ parameters: namedParameters
2567
+ });
2568
+ return {
2569
+ sql: compiledQuery.sql,
2570
+ options: { signal: options.signal, parameters: compiledQuery.parameters }
2571
+ };
2572
+ }
233
2573
  async loadAdapter() {
234
2574
  var _a, _b;
235
2575
  try {
@@ -266,17 +2606,679 @@ var SQLDataSource = class extends import_loader_utils.DataSource {
266
2606
  };
267
2607
  }
268
2608
  };
2609
+ function getSQLTableQueryDialect(sourceType) {
2610
+ if (sourceType === "duckdb-sql")
2611
+ return "duckdb";
2612
+ if (sourceType === "snowflake-sql")
2613
+ return "snowflake";
2614
+ throw new Error(`Portable table queries are not supported for SQL source type "${sourceType}".`);
2615
+ }
2616
+
2617
+ // dist/query-arrow-table.js
2618
+ var arrow6 = __toESM(require("apache-arrow"), 1);
2619
+
2620
+ // dist/table-query.js
2621
+ function planTableQuery2(sourceColumnNames, options = {}) {
2622
+ if (options.predicate) {
2623
+ validateSQLPredicate(options.predicate);
2624
+ }
2625
+ return planTableQuery(sourceColumnNames, options);
2626
+ }
2627
+ function explainTableQuery2(sourceColumnNames, options = {}) {
2628
+ if (options.predicate) {
2629
+ validateSQLPredicate(options.predicate);
2630
+ }
2631
+ return explainTableQuery(sourceColumnNames, options, SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES);
2632
+ }
2633
+ function getSQLPredicateColumnNames(predicate) {
2634
+ return getColumnarPredicateColumns(predicate);
2635
+ }
2636
+
2637
+ // dist/query-arrow-table.js
2638
+ function explainArrowTableQuery(sourceTable, options = {}) {
2639
+ if (options.predicate) {
2640
+ validateSQLPredicate(options.predicate);
2641
+ }
2642
+ return explainTableQuery(sourceTable.data.schema.fields.map((field) => field.name), options, ARROW_TABLE_QUERY_CAPABILITIES);
2643
+ }
2644
+ function queryArrowTable(sourceTable, options = {}) {
2645
+ var _a, _b;
2646
+ throwIfAborted(options.signal);
2647
+ if (options.join) {
2648
+ validateArrowJoinQuery(sourceTable, options);
2649
+ }
2650
+ if (options.join && hasRelationalOperatorsExceptJoin(options)) {
2651
+ throw new Error("Arrow joins cannot yet be combined with other relational operators.");
2652
+ }
2653
+ if (options.join && !hasRelationalOperatorsExceptJoin(options)) {
2654
+ return queryArrowJoin(sourceTable, options);
2655
+ }
2656
+ if (hasRelationalOperators(options)) {
2657
+ return queryArrowTableRelational(sourceTable, options);
2658
+ }
2659
+ const sourceData = sourceTable.data;
2660
+ const plan = planTableQuery2(sourceData.schema.fields.map((field) => field.name), options);
2661
+ const scannedData = sourceData.select([...getScanStep(plan).columns]);
2662
+ const projectedData = scannedData.select([...getProjectStep(plan).columns]);
2663
+ const predicate = (_a = getFilterStep(plan)) == null ? void 0 : _a.predicate;
2664
+ const limit = ((_b = getLimitStep(plan)) == null ? void 0 : _b.limit) ?? Number.POSITIVE_INFINITY;
2665
+ if (!predicate) {
2666
+ return wrapArrowTable(projectedData.slice(0, limit));
2667
+ }
2668
+ const predicateColumns = getPredicateColumns(scannedData, getSQLPredicateColumnNames(predicate));
2669
+ const matchingRowIndices = [];
2670
+ for (let rowIndex = 0; rowIndex < scannedData.numRows && matchingRowIndices.length < limit; rowIndex++) {
2671
+ throwIfAborted(options.signal);
2672
+ if (evaluatePredicate(predicate, predicateColumns, rowIndex) === true) {
2673
+ matchingRowIndices.push(rowIndex);
2674
+ }
2675
+ }
2676
+ if (matchingRowIndices.length === 0) {
2677
+ return wrapArrowTable(projectedData.slice(0, 0));
2678
+ }
2679
+ const outputColumns = {};
2680
+ for (const field of projectedData.schema.fields) {
2681
+ const sourceColumn = projectedData.getChild(field.name);
2682
+ if (!sourceColumn) {
2683
+ throw new Error(`Arrow query could not read column "${field.name}".`);
2684
+ }
2685
+ const values = matchingRowIndices.map((rowIndex) => sourceColumn.get(rowIndex));
2686
+ outputColumns[field.name] = arrow6.vectorFromArray(values, sourceColumn.type);
2687
+ }
2688
+ return wrapArrowTable(new arrow6.Table(projectedData.schema, outputColumns));
2689
+ }
2690
+ function queryArrowTableRelational(sourceTable, options) {
2691
+ var _a, _b, _c, _d, _e, _f;
2692
+ const sourceData = sourceTable.data;
2693
+ const sourceColumnNames = sourceData.schema.fields.map((field) => field.name);
2694
+ const relationalPlan = planRelationalQuery(sourceColumnNames, options);
2695
+ const scanStep = relationalPlan.tablePlan.find((step) => step.kind === "scan");
2696
+ if (!scanStep || scanStep.kind !== "scan") {
2697
+ throw new Error("Arrow relational query plan is missing a scan step.");
2698
+ }
2699
+ const scannedTable = wrapArrowTable(sourceData.select([...scanStep.columns]));
2700
+ const filteredTable = queryArrowTable(scannedTable, {
2701
+ predicate: options.predicate,
2702
+ columns: scanStep.columns,
2703
+ signal: options.signal
2704
+ });
2705
+ let rows = arrowTableToRows(filteredTable.data);
2706
+ for (const child of options.union || []) {
2707
+ const childTable = (_a = options.tables) == null ? void 0 : _a[child.source];
2708
+ if (!childTable)
2709
+ throw new Error(`Arrow union source not found: ${child.source}`);
2710
+ const childResult = queryArrowTable(childTable, {
2711
+ ...child.query || {},
2712
+ columns: getUnionChildColumns(sourceColumnNames, options),
2713
+ signal: options.signal
2714
+ });
2715
+ rows = rows.concat(arrowTableToRows(childResult.data));
2716
+ }
2717
+ for (const expression of options.expressions || []) {
2718
+ for (const row of rows) {
2719
+ row[expression.name] = evaluateRelationalExpression(expression, row);
2720
+ }
2721
+ }
2722
+ if (((_b = options.groupBy) == null ? void 0 : _b.length) || ((_c = options.aggregates) == null ? void 0 : _c.length)) {
2723
+ rows = aggregateRows(rows, options.groupBy || [], options.aggregates || []);
2724
+ }
2725
+ if ((_d = options.orderBy) == null ? void 0 : _d.length) {
2726
+ const orderBy = options.orderBy;
2727
+ rows = rows.map((row, index) => ({ row, index })).sort((left, right) => compareRows(left.row, right.row, orderBy) || left.index - right.index).map((entry) => entry.row);
2728
+ }
2729
+ const outputColumns = options.columns || (((_e = options.groupBy) == null ? void 0 : _e.length) || ((_f = options.aggregates) == null ? void 0 : _f.length) ? [...options.groupBy || [], ...(options.aggregates || []).map((aggregate) => aggregate.name)] : sourceColumnNames);
2730
+ const outputRows = rows.map((row) => {
2731
+ const output = {};
2732
+ for (const columnName of outputColumns) {
2733
+ if (!(columnName in row)) {
2734
+ throw new Error(`Arrow relational query column not found: ${columnName}`);
2735
+ }
2736
+ output[columnName] = row[columnName];
2737
+ }
2738
+ return output;
2739
+ });
2740
+ const limit = options.limit === void 0 ? outputRows.length : options.limit;
2741
+ const limitedRows = outputRows.slice(0, limit);
2742
+ return limitedRows.length ? convertRowsToArrowTable(limitedRows) : createEmptyRelationalResult(sourceData, outputColumns, options);
2743
+ }
2744
+ function getUnionChildColumns(sourceColumnNames, options) {
2745
+ var _a, _b;
2746
+ const expressionNames = new Set((options.expressions || []).map((expression) => expression.name));
2747
+ const aggregateNames = new Set((options.aggregates || []).map((aggregate) => aggregate.name));
2748
+ const outputColumns = options.columns || (((_a = options.groupBy) == null ? void 0 : _a.length) || ((_b = options.aggregates) == null ? void 0 : _b.length) ? [...options.groupBy || [], ...(options.aggregates || []).map((aggregate) => aggregate.name)] : sourceColumnNames);
2749
+ const requiredColumns = new Set(outputColumns.filter((column) => !expressionNames.has(column) && !aggregateNames.has(column)));
2750
+ for (const expression of options.expressions || []) {
2751
+ const definition = expression.expression;
2752
+ if (definition.op === "column")
2753
+ requiredColumns.add(definition.column);
2754
+ if ("left" in definition) {
2755
+ requiredColumns.add(definition.left);
2756
+ requiredColumns.add(definition.right);
2757
+ }
2758
+ }
2759
+ for (const key of options.orderBy || []) {
2760
+ if (!expressionNames.has(key.column) && !aggregateNames.has(key.column)) {
2761
+ requiredColumns.add(key.column);
2762
+ }
2763
+ }
2764
+ for (const column of options.groupBy || [])
2765
+ requiredColumns.add(column);
2766
+ for (const aggregate of options.aggregates || []) {
2767
+ if (aggregate.column)
2768
+ requiredColumns.add(aggregate.column);
2769
+ }
2770
+ return sourceColumnNames.filter((column) => requiredColumns.has(column));
2771
+ }
2772
+ function hasRelationalOperators(options) {
2773
+ var _a, _b, _c, _d, _e;
2774
+ return Boolean(((_a = options.expressions) == null ? void 0 : _a.length) || ((_b = options.orderBy) == null ? void 0 : _b.length) || ((_c = options.groupBy) == null ? void 0 : _c.length) || ((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.union) == null ? void 0 : _e.length) || options.join);
2775
+ }
2776
+ function hasRelationalOperatorsExceptJoin(options) {
2777
+ var _a, _b, _c, _d, _e;
2778
+ return Boolean(((_a = options.expressions) == null ? void 0 : _a.length) || ((_b = options.orderBy) == null ? void 0 : _b.length) || ((_c = options.groupBy) == null ? void 0 : _c.length) || ((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.union) == null ? void 0 : _e.length));
2779
+ }
2780
+ function queryArrowJoin(sourceTable, options) {
2781
+ var _a;
2782
+ const join = options.join;
2783
+ if (!join)
2784
+ throw new Error("Arrow join query is missing a join definition.");
2785
+ const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
2786
+ if (!childTable)
2787
+ throw new Error(`Arrow join source not found: ${join.child.source}`);
2788
+ const leftResult = queryArrowTable(sourceTable, {
2789
+ predicate: options.predicate,
2790
+ columns: void 0,
2791
+ signal: options.signal
2792
+ });
2793
+ const rightResult = queryArrowTable(childTable, {
2794
+ ...join.child.query || {},
2795
+ signal: options.signal
2796
+ });
2797
+ const leftRows = arrowTableToRows(leftResult.data);
2798
+ const rightRows = arrowTableToRows(rightResult.data);
2799
+ const rightPrefix = `${join.child.source}.`;
2800
+ const defaultOutputColumns = [
2801
+ ...sourceTable.data.schema.fields.map((field) => field.name),
2802
+ ...rightResult.data.schema.fields.map((field) => `${rightPrefix}${field.name}`)
2803
+ ];
2804
+ const rows = [];
2805
+ for (const leftRow of leftRows) {
2806
+ for (const rightRow of rightRows) {
2807
+ if (leftRow[join.left] !== null && leftRow[join.left] !== void 0 && rightRow[join.right] !== null && rightRow[join.right] !== void 0 && compareSortValues(leftRow[join.left], rightRow[join.right]) === 0) {
2808
+ rows.push({
2809
+ ...leftRow,
2810
+ ...Object.fromEntries(Object.entries(rightRow).map(([key, value]) => [`${rightPrefix}${key}`, value]))
2811
+ });
2812
+ }
2813
+ }
2814
+ }
2815
+ const outputColumns = options.columns || defaultOutputColumns;
2816
+ const outputRows = rows.map((row) => Object.fromEntries(outputColumns.map((column) => [column, row[column]])));
2817
+ const limitedRows = outputRows.slice(0, options.limit);
2818
+ return limitedRows.length ? convertRowsToArrowTable(limitedRows) : createEmptyRelationalResult(sourceTable.data, outputColumns, options, new Map(rightResult.data.schema.fields.map((field) => [
2819
+ `${rightPrefix}${field.name}`,
2820
+ new arrow6.Field(`${rightPrefix}${field.name}`, field.type, field.nullable, field.metadata)
2821
+ ])));
2822
+ }
2823
+ function validateArrowJoinQuery(sourceTable, options) {
2824
+ var _a, _b, _c;
2825
+ const join = options.join;
2826
+ if (!join)
2827
+ return;
2828
+ const sourceColumnNames = sourceTable.data.schema.fields.map((field) => field.name);
2829
+ const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
2830
+ if (!childTable)
2831
+ throw new Error(`Arrow join source not found: ${join.child.source}`);
2832
+ const childColumnNames = childTable.data.schema.fields.map((field) => field.name);
2833
+ if (!sourceColumnNames.includes(join.left)) {
2834
+ throw new Error(`Arrow join column not found: ${join.left}`);
2835
+ }
2836
+ if (!childColumnNames.includes(join.right)) {
2837
+ throw new Error(`Arrow join column not found: ${join.right}`);
2838
+ }
2839
+ const childPrefix = `${join.child.source}.`;
2840
+ const rootColumns = (_b = options.columns) == null ? void 0 : _b.filter((column) => !column.startsWith(childPrefix));
2841
+ planTableQuery2(sourceColumnNames, {
2842
+ predicate: options.predicate,
2843
+ columns: (rootColumns == null ? void 0 : rootColumns.length) ? rootColumns : void 0,
2844
+ limit: options.limit,
2845
+ signal: options.signal
2846
+ });
2847
+ const childQuery = join.child.query || {};
2848
+ planTableQuery2(childColumnNames, childQuery);
2849
+ const childOutputColumns = childQuery.columns || childColumnNames;
2850
+ if (!childOutputColumns.includes(join.right)) {
2851
+ throw new Error(`Arrow join child projection must include: ${join.right}`);
2852
+ }
2853
+ const projectedChildColumns = ((_c = options.columns) == null ? void 0 : _c.filter((column) => column.startsWith(childPrefix))) || [];
2854
+ const seenChildColumns = /* @__PURE__ */ new Set();
2855
+ for (const projectedColumn of projectedChildColumns) {
2856
+ const childColumn = projectedColumn.slice(childPrefix.length);
2857
+ if (!childColumnNames.includes(childColumn)) {
2858
+ throw new Error(`Arrow join column not found: ${projectedColumn}`);
2859
+ }
2860
+ if (seenChildColumns.has(childColumn)) {
2861
+ throw new Error(`Arrow query column was selected more than once: ${projectedColumn}`);
2862
+ }
2863
+ seenChildColumns.add(childColumn);
2864
+ if (!childOutputColumns.includes(childColumn)) {
2865
+ throw new Error(`Arrow join child projection does not include: ${childColumn}`);
2866
+ }
2867
+ }
2868
+ }
2869
+ function arrowTableToRows(data) {
2870
+ const columns = data.schema.fields.map((field) => ({
2871
+ name: field.name,
2872
+ vector: data.getChild(field.name)
2873
+ }));
2874
+ return Array.from({ length: data.numRows }, (_, rowIndex) => {
2875
+ const row = {};
2876
+ for (const column of columns) {
2877
+ if (!column.vector)
2878
+ throw new Error(`Arrow relational query could not read ${column.name}`);
2879
+ row[column.name] = column.vector.get(rowIndex);
2880
+ }
2881
+ return row;
2882
+ });
2883
+ }
2884
+ function evaluateRelationalExpression(expression, row) {
2885
+ const definition = expression.expression;
2886
+ if (definition.op === "literal")
2887
+ return definition.value;
2888
+ if (definition.op === "column")
2889
+ return row[definition.column];
2890
+ const left = row[definition.left];
2891
+ const right = row[definition.right];
2892
+ if (left === null || left === void 0 || right === null || right === void 0)
2893
+ return null;
2894
+ if (typeof left !== "number" || typeof right !== "number") {
2895
+ throw new Error(`Arrow relational expression ${expression.name} requires numeric operands.`);
2896
+ }
2897
+ switch (definition.op) {
2898
+ case "add":
2899
+ return left + right;
2900
+ case "subtract":
2901
+ return left - right;
2902
+ case "multiply":
2903
+ return left * right;
2904
+ case "divide":
2905
+ return right === 0 ? null : left / right;
2906
+ }
2907
+ }
2908
+ function compareRows(left, right, orderBy) {
2909
+ for (const key of orderBy) {
2910
+ const leftValue = left[key.column];
2911
+ const rightValue = right[key.column];
2912
+ const nulls = key.nulls || "last";
2913
+ if (leftValue === null || leftValue === void 0 || rightValue === null || rightValue === void 0) {
2914
+ if (leftValue === rightValue)
2915
+ continue;
2916
+ const nullResult = leftValue === null || leftValue === void 0 ? -1 : 1;
2917
+ return nulls === "first" ? nullResult : -nullResult;
2918
+ }
2919
+ const result = compareSortValues(leftValue, rightValue);
2920
+ if (result)
2921
+ return (key.direction === "desc" ? -1 : 1) * result;
2922
+ }
2923
+ return 0;
2924
+ }
2925
+ function compareSortValues(left, right) {
2926
+ if (left instanceof Date && right instanceof Date)
2927
+ return compareNumbers(left.getTime(), right.getTime());
2928
+ if (typeof left === "bigint" && typeof right === "bigint")
2929
+ return left === right ? 0 : left < right ? -1 : 1;
2930
+ if (typeof left === "number" && typeof right === "number")
2931
+ return compareNumbers(left, right);
2932
+ if (typeof left === "string" && typeof right === "string")
2933
+ return left === right ? 0 : left < right ? -1 : 1;
2934
+ if (typeof left === "boolean" && typeof right === "boolean")
2935
+ return Number(left) - Number(right);
2936
+ throw new Error(`Arrow relational order cannot compare ${getValueType(left)} with ${getValueType(right)}.`);
2937
+ }
2938
+ function aggregateRows(rows, groupBy, aggregates) {
2939
+ const groups = /* @__PURE__ */ new Map();
2940
+ for (const row of rows) {
2941
+ const key = serializeGroupKey(groupBy.map((column) => row[column]));
2942
+ const group = groups.get(key) || [];
2943
+ group.push(row);
2944
+ groups.set(key, group);
2945
+ }
2946
+ if (!groupBy.length && !rows.length)
2947
+ groups.set("[]", []);
2948
+ return [...groups.values()].map((group) => {
2949
+ var _a;
2950
+ const output = {};
2951
+ for (const column of groupBy)
2952
+ output[column] = ((_a = group[0]) == null ? void 0 : _a[column]) ?? null;
2953
+ for (const aggregate of aggregates)
2954
+ output[aggregate.name] = evaluateAggregate(aggregate, group);
2955
+ return output;
2956
+ });
2957
+ }
2958
+ function serializeGroupKey(values) {
2959
+ return values.map((value) => {
2960
+ if (value === null || value === void 0)
2961
+ return "null:";
2962
+ if (value instanceof Date)
2963
+ return `date:${value.getTime()}`;
2964
+ if (value instanceof Uint8Array)
2965
+ return `bytes:${Array.from(value).join(".")}`;
2966
+ return `${typeof value}:${String(value)}`;
2967
+ }).join("");
2968
+ }
2969
+ function createEmptyRelationalResult(sourceData, outputColumns, options, additionalFields) {
2970
+ const sourceFields = new Map(sourceData.schema.fields.map((field) => [field.name, field]));
2971
+ const expressions = new Map((options.expressions || []).map((expression) => [expression.name, expression]));
2972
+ const aggregates = new Map((options.aggregates || []).map((aggregate) => [aggregate.name, aggregate]));
2973
+ const fields = outputColumns.map((columnName) => {
2974
+ const sourceField = sourceFields.get(columnName);
2975
+ if (sourceField)
2976
+ return sourceField;
2977
+ const additionalField = additionalFields == null ? void 0 : additionalFields.get(columnName);
2978
+ if (additionalField)
2979
+ return additionalField;
2980
+ const expression = expressions.get(columnName);
2981
+ if (expression)
2982
+ return new arrow6.Field(columnName, getExpressionType(expression, sourceFields), true);
2983
+ const aggregate = aggregates.get(columnName);
2984
+ if (aggregate)
2985
+ return new arrow6.Field(columnName, getAggregateType(aggregate, sourceFields), true);
2986
+ return new arrow6.Field(columnName, new arrow6.Utf8(), true);
2987
+ });
2988
+ const columns = {};
2989
+ for (const field of fields)
2990
+ columns[field.name] = arrow6.vectorFromArray([], field.type);
2991
+ return wrapArrowTable(new arrow6.Table(new arrow6.Schema(fields), columns));
2992
+ }
2993
+ function getExpressionType(expression, sourceFields) {
2994
+ var _a;
2995
+ if (expression.expression.op === "literal") {
2996
+ const value = expression.expression.value;
2997
+ if (typeof value === "boolean")
2998
+ return new arrow6.Bool();
2999
+ if (typeof value === "number")
3000
+ return new arrow6.Float64();
3001
+ return new arrow6.Utf8();
3002
+ }
3003
+ if (expression.expression.op === "column") {
3004
+ return ((_a = sourceFields.get(expression.expression.column)) == null ? void 0 : _a.type) || new arrow6.Utf8();
3005
+ }
3006
+ return new arrow6.Float64();
3007
+ }
3008
+ function getAggregateType(aggregate, sourceFields) {
3009
+ var _a;
3010
+ if (aggregate.function === "count")
3011
+ return new arrow6.Int32();
3012
+ return aggregate.column ? ((_a = sourceFields.get(aggregate.column)) == null ? void 0 : _a.type) || new arrow6.Float64() : new arrow6.Float64();
3013
+ }
3014
+ function evaluateAggregate(aggregate, rows) {
3015
+ if (aggregate.function === "count")
3016
+ return aggregate.column ? rows.filter((row) => row[aggregate.column] != null).length : rows.length;
3017
+ const values = rows.map((row) => row[aggregate.column]).filter((value) => value != null);
3018
+ if (!values.length)
3019
+ return null;
3020
+ if (!values.every((value) => typeof value === "number"))
3021
+ throw new Error(`Arrow aggregate ${aggregate.function} requires numeric values.`);
3022
+ const numericValues = values;
3023
+ switch (aggregate.function) {
3024
+ case "sum":
3025
+ return numericValues.reduce((sum, value) => sum + value, 0);
3026
+ case "avg":
3027
+ return numericValues.reduce((sum, value) => sum + value, 0) / numericValues.length;
3028
+ case "min":
3029
+ return Math.min(...numericValues);
3030
+ case "max":
3031
+ return Math.max(...numericValues);
3032
+ }
3033
+ }
3034
+ function getPredicateColumns(sourceTable, columnNames) {
3035
+ const columns = {};
3036
+ for (const columnName of columnNames) {
3037
+ const column = sourceTable.getChild(columnName);
3038
+ if (!column) {
3039
+ throw new Error(`Arrow query column not found: ${columnName}`);
3040
+ }
3041
+ columns[columnName] = column;
3042
+ }
3043
+ return columns;
3044
+ }
3045
+ function evaluatePredicate(predicate, columns, rowIndex) {
3046
+ if (isLogicalPredicate(predicate)) {
3047
+ const values = predicate.args.map((child) => evaluatePredicate(child, columns, rowIndex));
3048
+ return predicate.op === "and" ? evaluateAnd(values) : evaluateOr(values);
3049
+ }
3050
+ if (isNotPredicate(predicate)) {
3051
+ const value2 = evaluatePredicate(predicate.args[0], columns, rowIndex);
3052
+ return value2 === null ? null : !value2;
3053
+ }
3054
+ const value = getColumnValue(columns, predicate.args[0].property, rowIndex);
3055
+ if (isNullPredicate(predicate)) {
3056
+ return value === null;
3057
+ }
3058
+ if (isInPredicate(predicate)) {
3059
+ return evaluateIn(value, predicate.args[1]);
3060
+ }
3061
+ return evaluateComparison(value, predicate);
3062
+ }
3063
+ function getColumnValue(columns, columnName, rowIndex) {
3064
+ const column = columns[columnName];
3065
+ if (!column) {
3066
+ throw new Error(`Arrow query could not read predicate column "${columnName}".`);
3067
+ }
3068
+ return column.get(rowIndex);
3069
+ }
3070
+ function evaluateAnd(values) {
3071
+ if (values.includes(false)) {
3072
+ return false;
3073
+ }
3074
+ return values.includes(null) ? null : true;
3075
+ }
3076
+ function evaluateOr(values) {
3077
+ if (values.includes(true)) {
3078
+ return true;
3079
+ }
3080
+ return values.includes(null) ? null : false;
3081
+ }
3082
+ function evaluateIn(value, candidates) {
3083
+ if (value === null || value === void 0) {
3084
+ return null;
3085
+ }
3086
+ for (const candidate of candidates) {
3087
+ if (compareValues(value, candidate) === 0) {
3088
+ return true;
3089
+ }
3090
+ }
3091
+ return false;
3092
+ }
3093
+ function evaluateComparison(value, predicate) {
3094
+ if (value === null || value === void 0) {
3095
+ return null;
3096
+ }
3097
+ const comparison = compareValues(value, predicate.args[1]);
3098
+ switch (predicate.op) {
3099
+ case "=":
3100
+ return comparison === 0;
3101
+ case "<>":
3102
+ return comparison !== 0;
3103
+ case "<":
3104
+ return comparison < 0;
3105
+ case "<=":
3106
+ return comparison <= 0;
3107
+ case ">":
3108
+ return comparison > 0;
3109
+ case ">=":
3110
+ return comparison >= 0;
3111
+ }
3112
+ }
3113
+ function compareValues(left, right) {
3114
+ if (isSQLPredicateParameter(right)) {
3115
+ throw new Error(`Arrow query parameter ":${right.parameter}" must be bound before query execution.`);
3116
+ }
3117
+ if (left instanceof Date && right instanceof Date) {
3118
+ return compareNumbers(left.getTime(), right.getTime());
3119
+ }
3120
+ if (typeof left === "number" && right instanceof Date) {
3121
+ return compareNumbers(left, right.getTime());
3122
+ }
3123
+ if (left instanceof Uint8Array && right instanceof Uint8Array) {
3124
+ return compareBinary(left, right);
3125
+ }
3126
+ if (typeof left === "bigint" && typeof right === "bigint") {
3127
+ return left === right ? 0 : left < right ? -1 : 1;
3128
+ }
3129
+ if (typeof left === "bigint" && typeof right === "number" && Number.isSafeInteger(right)) {
3130
+ return compareValues(left, BigInt(right));
3131
+ }
3132
+ if (typeof left === "number" && typeof right === "bigint" && Number.isSafeInteger(left)) {
3133
+ return compareValues(BigInt(left), right);
3134
+ }
3135
+ if (typeof left === "number" && typeof right === "number") {
3136
+ return compareNumbers(left, right);
3137
+ }
3138
+ if (typeof left === "string" && typeof right === "string") {
3139
+ return left === right ? 0 : left < right ? -1 : 1;
3140
+ }
3141
+ if (typeof left === "boolean" && typeof right === "boolean") {
3142
+ return Number(left) - Number(right);
3143
+ }
3144
+ throw new Error(`Arrow query cannot compare ${getValueType(left)} with ${getValueType(right)} values.`);
3145
+ }
3146
+ function compareNumbers(left, right) {
3147
+ if (!Number.isFinite(left) || !Number.isFinite(right)) {
3148
+ throw new Error("Arrow query cannot compare non-finite numbers.");
3149
+ }
3150
+ return left === right ? 0 : left < right ? -1 : 1;
3151
+ }
3152
+ function compareBinary(left, right) {
3153
+ const commonLength = Math.min(left.length, right.length);
3154
+ for (let index = 0; index < commonLength; index++) {
3155
+ if (left[index] !== right[index]) {
3156
+ return left[index] < right[index] ? -1 : 1;
3157
+ }
3158
+ }
3159
+ return left.length === right.length ? 0 : left.length < right.length ? -1 : 1;
3160
+ }
3161
+ function getValueType(value) {
3162
+ if (value instanceof Date) {
3163
+ return "Date";
3164
+ }
3165
+ if (value instanceof Uint8Array) {
3166
+ return "Uint8Array";
3167
+ }
3168
+ return typeof value;
3169
+ }
3170
+ function isLogicalPredicate(predicate) {
3171
+ return predicate.op === "and" || predicate.op === "or";
3172
+ }
3173
+ function isNotPredicate(predicate) {
3174
+ return predicate.op === "not";
3175
+ }
3176
+ function isNullPredicate(predicate) {
3177
+ return predicate.op === "isNull";
3178
+ }
3179
+ function isInPredicate(predicate) {
3180
+ return predicate.op === "in";
3181
+ }
3182
+ function getScanStep(plan) {
3183
+ const step = plan.find((candidate) => candidate.kind === "scan");
3184
+ if (!step) {
3185
+ throw new Error("Arrow query plan is missing a scan step.");
3186
+ }
3187
+ return step;
3188
+ }
3189
+ function getFilterStep(plan) {
3190
+ return plan.find((candidate) => candidate.kind === "filter");
3191
+ }
3192
+ function getProjectStep(plan) {
3193
+ const step = plan.find((candidate) => candidate.kind === "project");
3194
+ if (!step) {
3195
+ throw new Error("Arrow query plan is missing a project step.");
3196
+ }
3197
+ return step;
3198
+ }
3199
+ function getLimitStep(plan) {
3200
+ return plan.find((candidate) => candidate.kind === "limit");
3201
+ }
3202
+ function throwIfAborted(signal) {
3203
+ if (signal == null ? void 0 : signal.aborted) {
3204
+ const error = new Error("Arrow query was aborted.");
3205
+ error.name = "AbortError";
3206
+ throw error;
3207
+ }
3208
+ }
3209
+ function wrapArrowTable(data) {
3210
+ return {
3211
+ shape: "arrow-table",
3212
+ schema: convertArrowToSchema(data.schema),
3213
+ data
3214
+ };
3215
+ }
3216
+
3217
+ // dist/arrow-table-source.js
3218
+ var ArrowTableSource = class extends DataSource {
3219
+ /** Creates a source over an existing Arrow table without copying its vectors. */
3220
+ constructor(data, options = {}) {
3221
+ super(data, options);
3222
+ }
3223
+ /** Discovers query-visible fields and capabilities without evaluating any rows. */
3224
+ async getQueryMetadata(options = {}) {
3225
+ throwIfAborted2(options.signal);
3226
+ const schema = convertArrowToSchema(this.data.data.schema);
3227
+ return createScanQueryMetadata({
3228
+ sourceType: "arrow-table",
3229
+ queryType: "table",
3230
+ execution: { status: "supported", method: "read" },
3231
+ schema,
3232
+ capabilities: { table: ARROW_TABLE_QUERY_CAPABILITIES },
3233
+ columnRoles: getArrowColumnRoles(schema.fields.map((field) => field.name)),
3234
+ statistics: { rowCount: this.data.data.numRows }
3235
+ });
3236
+ }
3237
+ /** Executes a portable query and returns an Arrow table result. */
3238
+ query(options = {}) {
3239
+ return queryArrowTable(this.data, options);
3240
+ }
3241
+ /** Explains a portable query without evaluating table rows. */
3242
+ explain(options = {}) {
3243
+ return explainArrowTableQuery(this.data, options);
3244
+ }
3245
+ /** Executes a query as one bounded Arrow batch. */
3246
+ async *read(options = {}) {
3247
+ const result = this.query(options);
3248
+ yield makeTableScanBatch(result);
3249
+ }
3250
+ };
3251
+ function getArrowColumnRoles(columnNames) {
3252
+ const roles = {};
3253
+ for (const columnName of columnNames) {
3254
+ const normalizedName = columnName.toLowerCase();
3255
+ if (normalizedName === "x" || normalizedName === "longitude" || normalizedName === "lon") {
3256
+ roles[columnName] = normalizedName === "x" ? "x" : "longitude";
3257
+ } else if (normalizedName === "y" || normalizedName === "latitude" || normalizedName === "lat") {
3258
+ roles[columnName] = normalizedName === "y" ? "y" : "latitude";
3259
+ } else if (normalizedName === "z" || normalizedName === "elevation" || normalizedName === "altitude") {
3260
+ roles[columnName] = normalizedName === "z" ? "z" : "attribute";
3261
+ } else if (normalizedName === "time" || normalizedName.endsWith("_time") || normalizedName.endsWith("timestamp")) {
3262
+ roles[columnName] = "time";
3263
+ }
3264
+ }
3265
+ return roles;
3266
+ }
3267
+ function throwIfAborted2(signal) {
3268
+ if (signal == null ? void 0 : signal.aborted) {
3269
+ throw new Error("Request aborted");
3270
+ }
3271
+ }
269
3272
 
270
3273
  // dist/duckdb-sql-source.js
271
- var import_schema_utils2 = require("@loaders.gl/schema-utils");
272
- var VERSION = true ? "5.0.0-alpha.1" : "latest";
3274
+ var VERSION2 = true ? "5.0.0-alpha.11" : "latest";
273
3275
  var DuckDBSQLSource = {
274
3276
  dataType: null,
275
3277
  batchType: null,
276
3278
  name: "DuckDBSQLSource",
277
3279
  id: "duckdb-sql",
278
3280
  module: "sql",
279
- version: VERSION,
3281
+ version: VERSION2,
280
3282
  extensions: ["duckdb", "db"],
281
3283
  mimeTypes: [],
282
3284
  type: "duckdb-sql",
@@ -448,9 +3450,9 @@ async function createDuckDBBrowserAdapter(context) {
448
3450
  const database = new duckdb.AsyncDuckDB(logger, worker);
449
3451
  await database.instantiate(bundles.mainModule, bundles.pthreadWorker);
450
3452
  const connection = await database.connect();
451
- const executeRows = async (sqlText) => {
452
- const result = await connection.query(sqlText);
453
- return (0, import_schema_utils2.convertArrowToTable)(result, "object-row-table").data;
3453
+ const executeRows = async (sqlText, options = {}) => {
3454
+ const result = await executeDuckDBBrowserQuery(connection, sqlText, options.parameters);
3455
+ return convertArrowToTable2(result, "object-row-table").data;
454
3456
  };
455
3457
  return {
456
3458
  capabilities: {
@@ -530,15 +3532,27 @@ async function createDuckDBBrowserAdapter(context) {
530
3532
  }));
531
3533
  return convertSQLColumnsToSchema(columns);
532
3534
  },
533
- async executeRows(sqlText) {
534
- return await executeRows(sqlText);
3535
+ async executeRows(sqlText, options = {}) {
3536
+ return await executeRows(sqlText, options);
535
3537
  },
536
- async executeArrow(sqlText) {
537
- const result = await connection.query(sqlText);
538
- return (0, import_schema_utils2.convertArrowToTable)(result, "arrow-table");
3538
+ async executeArrow(sqlText, options = {}) {
3539
+ const result = await executeDuckDBBrowserQuery(connection, sqlText, options.parameters);
3540
+ return convertArrowToTable2(result, "arrow-table");
539
3541
  }
540
3542
  };
541
3543
  }
3544
+ async function executeDuckDBBrowserQuery(connection, sqlText, parameters) {
3545
+ if (!parameters) {
3546
+ return await connection.query(sqlText);
3547
+ }
3548
+ const values = Array.isArray(parameters) ? parameters : Object.values(parameters);
3549
+ const statement = await connection.prepare(sqlText);
3550
+ try {
3551
+ return await statement.query(...values);
3552
+ } finally {
3553
+ await statement.close();
3554
+ }
3555
+ }
542
3556
  function getDuckDBDatabasePath(url, options) {
543
3557
  var _a;
544
3558
  if ((_a = options.duckdb) == null ? void 0 : _a.databasePath) {
@@ -553,14 +3567,14 @@ function getDuckDBDatabasePath(url, options) {
553
3567
  }
554
3568
 
555
3569
  // dist/snowflake-sql-source.js
556
- var VERSION2 = true ? "5.0.0-alpha.1" : "latest";
3570
+ var VERSION3 = true ? "5.0.0-alpha.11" : "latest";
557
3571
  var SnowflakeSQLSource = {
558
3572
  dataType: null,
559
3573
  batchType: null,
560
3574
  name: "SnowflakeSQLSource",
561
3575
  id: "snowflake-sql",
562
3576
  module: "sql",
563
- version: VERSION2,
3577
+ version: VERSION3,
564
3578
  extensions: [],
565
3579
  mimeTypes: [],
566
3580
  type: "snowflake-sql",
@@ -710,8 +3724,8 @@ async function executeSnowflakeStatement(context, baseStatementUrl, authorizatio
710
3724
  return response;
711
3725
  }
712
3726
  async function fetchSnowflakeJson(context, url, authorization, requestInit) {
713
- var _a, _b, _c;
714
- const customFetch = (_c = (_b = (_a = context.options.core) == null ? void 0 : _a.loadOptions) == null ? void 0 : _b.core) == null ? void 0 : _c.fetch;
3727
+ var _a;
3728
+ const customFetch = (_a = context.options.core) == null ? void 0 : _a.fetch;
715
3729
  const headers = new Headers(requestInit.headers);
716
3730
  headers.set("Authorization", authorization.startsWith("Bearer ") ? authorization : `Bearer ${authorization}`);
717
3731
  headers.set("Accept", "application/json");
@@ -729,14 +3743,15 @@ async function fetchSnowflakeJson(context, url, authorization, requestInit) {
729
3743
  return json;
730
3744
  }
731
3745
  function normalizeSnowflakeBindings(parameters) {
732
- if (!parameters || Array.isArray(parameters)) {
3746
+ if (!parameters) {
733
3747
  return void 0;
734
3748
  }
735
3749
  const bindings = {};
736
- for (const [key, value] of Object.entries(parameters)) {
3750
+ const entries = Array.isArray(parameters) ? parameters.map((value, index) => [String(index + 1), value]) : Object.entries(parameters);
3751
+ for (const [key, value] of entries) {
737
3752
  bindings[key] = {
738
- type: typeof value === "number" ? "FIXED" : "TEXT",
739
- value
3753
+ type: typeof value === "number" || typeof value === "bigint" ? "FIXED" : "TEXT",
3754
+ value: typeof value === "bigint" ? value.toString() : value
740
3755
  };
741
3756
  }
742
3757
  return bindings;
@@ -756,4 +3771,304 @@ function getSnowflakeBaseUrl(url, options) {
756
3771
  }
757
3772
  return `https://${account}.snowflakecomputing.com`;
758
3773
  }
3774
+
3775
+ // dist/parse-sql-predicate.js
3776
+ var MAXIMUM_SQL_LENGTH = 65536;
3777
+ var MAXIMUM_SQL_TOKENS = 4096;
3778
+ var MAXIMUM_EXPRESSION_DEPTH = 64;
3779
+ function parseSQLPredicate(source, options = {}) {
3780
+ const parser = new SQLPredicateParser(source, options.parameters ?? {}, options.preserveParameters === true);
3781
+ const predicate = parser.parse();
3782
+ validateSQLPredicate(predicate);
3783
+ return predicate;
3784
+ }
3785
+ var SQLPredicateParser = class {
3786
+ /** Token stream parsed by this parser instance. */
3787
+ tokens;
3788
+ /** Named scalar parameters available to the expression. */
3789
+ parameters;
3790
+ /** Whether named parameters remain references in the parsed AST. */
3791
+ preserveParameters;
3792
+ /** Current index in the token stream. */
3793
+ position = 0;
3794
+ constructor(source, parameters, preserveParameters) {
3795
+ this.tokens = tokenizeSQLPredicate(source);
3796
+ this.parameters = parameters;
3797
+ this.preserveParameters = preserveParameters;
3798
+ }
3799
+ /** Parses the complete token stream. */
3800
+ parse() {
3801
+ const predicate = this.parseOr(0);
3802
+ this.takeSymbol(";");
3803
+ const token = this.peek();
3804
+ if (token) {
3805
+ throw new Error(`SQL predicate contains unexpected token ${JSON.stringify(token.value)}`);
3806
+ }
3807
+ return predicate;
3808
+ }
3809
+ /** Parses left-associative disjunction. */
3810
+ parseOr(depth) {
3811
+ let predicate = this.parseAnd(depth + 1);
3812
+ while (this.takeKeyword("OR")) {
3813
+ predicate = combineLogicalPredicate("or", predicate, this.parseAnd(depth + 1));
3814
+ }
3815
+ return predicate;
3816
+ }
3817
+ /** Parses left-associative conjunction. */
3818
+ parseAnd(depth) {
3819
+ let predicate = this.parseNot(depth + 1);
3820
+ while (this.takeKeyword("AND")) {
3821
+ predicate = combineLogicalPredicate("and", predicate, this.parseNot(depth + 1));
3822
+ }
3823
+ return predicate;
3824
+ }
3825
+ /** Parses boolean negation and parenthesized predicates. */
3826
+ parseNot(depth) {
3827
+ this.assertDepth(depth);
3828
+ if (this.takeKeyword("NOT")) {
3829
+ return { op: "not", args: [this.parseNot(depth + 1)] };
3830
+ }
3831
+ if (this.takeSymbol("(")) {
3832
+ const predicate = this.parseOr(depth + 1);
3833
+ this.expectSymbol(")");
3834
+ return predicate;
3835
+ }
3836
+ return this.parseLeaf();
3837
+ }
3838
+ /** Parses one comparison, membership, or null predicate. */
3839
+ parseLeaf() {
3840
+ var _a, _b;
3841
+ const property = this.parseProperty();
3842
+ if (this.takeKeyword("IS")) {
3843
+ const negated = this.takeKeyword("NOT");
3844
+ this.expectKeyword("NULL");
3845
+ const predicate = { op: "isNull", args: [property] };
3846
+ return negated ? { op: "not", args: [predicate] } : predicate;
3847
+ }
3848
+ const negatedMembership = this.takeKeyword("NOT");
3849
+ if (negatedMembership || this.peekKeyword("IN")) {
3850
+ this.expectKeyword("IN");
3851
+ this.expectSymbol("(");
3852
+ if (((_a = this.peek()) == null ? void 0 : _a.kind) === "symbol" && ((_b = this.peek()) == null ? void 0 : _b.value) === ")") {
3853
+ throw new Error("SQL predicate IN requires at least one scalar value");
3854
+ }
3855
+ const values = [this.parseValue()];
3856
+ while (this.takeSymbol(",")) {
3857
+ values.push(this.parseValue());
3858
+ }
3859
+ this.expectSymbol(")");
3860
+ const predicate = { op: "in", args: [property, values] };
3861
+ return negatedMembership ? { op: "not", args: [predicate] } : predicate;
3862
+ }
3863
+ const token = this.take();
3864
+ if ((token == null ? void 0 : token.kind) !== "symbol" || !["=", "!=", "<>", "<", "<=", ">", ">="].includes(token.value)) {
3865
+ throw new Error("SQL predicate expected a comparison, IN, or IS NULL operator");
3866
+ }
3867
+ const operator = token.value === "!=" ? "<>" : token.value;
3868
+ return {
3869
+ op: operator,
3870
+ args: [property, this.parseValue()]
3871
+ };
3872
+ }
3873
+ /** Parses an identifier into a property reference. */
3874
+ parseProperty() {
3875
+ const token = this.take();
3876
+ if ((token == null ? void 0 : token.kind) !== "identifier") {
3877
+ throw new Error("SQL predicate expected a column identifier");
3878
+ }
3879
+ return token.quoted ? { property: token.value, quoted: true } : { property: token.value };
3880
+ }
3881
+ /** Parses one scalar literal or named parameter. */
3882
+ parseValue() {
3883
+ const negative = this.takeSymbol("-");
3884
+ const token = this.take();
3885
+ if (!token) {
3886
+ throw new Error("SQL predicate expected a scalar value");
3887
+ }
3888
+ if (negative && token.kind !== "number") {
3889
+ throw new Error("SQL predicate only permits unary minus on numeric literals");
3890
+ }
3891
+ if (token.kind === "number") {
3892
+ return parseNumericLiteral(negative ? `-${token.value}` : token.value);
3893
+ }
3894
+ if (negative) {
3895
+ throw new Error("SQL predicate expected a numeric literal after unary minus");
3896
+ }
3897
+ if (token.kind === "string") {
3898
+ return token.value;
3899
+ }
3900
+ if (token.kind === "parameter") {
3901
+ if (this.preserveParameters) {
3902
+ return { parameter: token.value };
3903
+ }
3904
+ if (!Object.hasOwn(this.parameters, token.value)) {
3905
+ throw new Error(`SQL predicate parameter ":${token.value}" requires a value`);
3906
+ }
3907
+ const value = this.parameters[token.value];
3908
+ validateParameterValue(value, token.value);
3909
+ return value;
3910
+ }
3911
+ if (token.kind === "identifier" && /^(TRUE|FALSE)$/i.test(token.value)) {
3912
+ return /^TRUE$/i.test(token.value);
3913
+ }
3914
+ if (token.kind === "identifier" && /^NULL$/i.test(token.value)) {
3915
+ throw new Error("SQL predicate comparisons with NULL must use IS NULL or IS NOT NULL");
3916
+ }
3917
+ throw new Error(`SQL predicate does not support scalar token ${JSON.stringify(token.value)}`);
3918
+ }
3919
+ /** Rejects excessively nested inputs before recursion can exhaust the stack. */
3920
+ assertDepth(depth) {
3921
+ if (depth > MAXIMUM_EXPRESSION_DEPTH) {
3922
+ throw new Error("SQL predicate nesting exceeds its safe limit");
3923
+ }
3924
+ }
3925
+ /** Consumes one required keyword. */
3926
+ expectKeyword(keyword) {
3927
+ if (!this.takeKeyword(keyword)) {
3928
+ throw new Error(`SQL predicate expected ${keyword}`);
3929
+ }
3930
+ }
3931
+ /** Returns whether the next token is a keyword without consuming it. */
3932
+ peekKeyword(keyword) {
3933
+ const token = this.peek();
3934
+ return (token == null ? void 0 : token.kind) === "identifier" && token.value.toUpperCase() === keyword;
3935
+ }
3936
+ /** Consumes one optional keyword. */
3937
+ takeKeyword(keyword) {
3938
+ if (!this.peekKeyword(keyword)) {
3939
+ return false;
3940
+ }
3941
+ this.position++;
3942
+ return true;
3943
+ }
3944
+ /** Consumes one required symbol. */
3945
+ expectSymbol(symbol) {
3946
+ if (!this.takeSymbol(symbol)) {
3947
+ throw new Error(`SQL predicate expected ${JSON.stringify(symbol)}`);
3948
+ }
3949
+ }
3950
+ /** Consumes one optional symbol. */
3951
+ takeSymbol(symbol) {
3952
+ const token = this.peek();
3953
+ if ((token == null ? void 0 : token.kind) !== "symbol" || token.value !== symbol) {
3954
+ return false;
3955
+ }
3956
+ this.position++;
3957
+ return true;
3958
+ }
3959
+ /** Consumes and returns the next token. */
3960
+ take() {
3961
+ const token = this.tokens[this.position];
3962
+ if (token) {
3963
+ this.position++;
3964
+ }
3965
+ return token;
3966
+ }
3967
+ /** Returns the next token without consuming it. */
3968
+ peek() {
3969
+ return this.tokens[this.position];
3970
+ }
3971
+ };
3972
+ function combineLogicalPredicate(operator, left, right) {
3973
+ return left.op === operator ? { op: operator, args: [...left.args, right] } : { op: operator, args: [left, right] };
3974
+ }
3975
+ function parseNumericLiteral(source) {
3976
+ if (/^-?\d+$/.test(source)) {
3977
+ const bigint = BigInt(source);
3978
+ if (bigint > BigInt(Number.MAX_SAFE_INTEGER) || bigint < BigInt(Number.MIN_SAFE_INTEGER)) {
3979
+ return bigint;
3980
+ }
3981
+ }
3982
+ const number = Number(source);
3983
+ if (!Number.isFinite(number)) {
3984
+ throw new Error("SQL predicate numeric literals must be finite");
3985
+ }
3986
+ return number;
3987
+ }
3988
+ function validateParameterValue(value, name) {
3989
+ const probe = { op: "=", args: [{ property: "_" }, value] };
3990
+ try {
3991
+ validateSQLPredicate(probe);
3992
+ } catch {
3993
+ throw new Error(`SQL predicate parameter ":${name}" has an unsupported value`);
3994
+ }
3995
+ }
3996
+ function tokenizeSQLPredicate(source) {
3997
+ if (typeof source !== "string" || source.trim().length === 0 || source.length > MAXIMUM_SQL_LENGTH) {
3998
+ throw new Error("SQL predicate requires a non-empty, safely bounded expression");
3999
+ }
4000
+ const tokens = [];
4001
+ let position = 0;
4002
+ while (position < source.length) {
4003
+ const character = source[position];
4004
+ if (/\s/.test(character)) {
4005
+ position++;
4006
+ continue;
4007
+ }
4008
+ if (character === "'") {
4009
+ const result = readQuotedToken(source, position, "'", "'");
4010
+ tokens.push({ kind: "string", value: result.value });
4011
+ position = result.position;
4012
+ } else if (character === '"') {
4013
+ const result = readQuotedToken(source, position, '"', '"');
4014
+ tokens.push({ kind: "identifier", value: result.value, quoted: true });
4015
+ position = result.position;
4016
+ } else if (character === ":") {
4017
+ const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(position + 1));
4018
+ if (!match) {
4019
+ throw new Error(`SQL predicate contains an invalid parameter at character ${position}`);
4020
+ }
4021
+ tokens.push({ kind: "parameter", value: match[0] });
4022
+ position += match[0].length + 1;
4023
+ } else {
4024
+ const numberMatch = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(source.slice(position));
4025
+ const identifierMatch = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/.exec(source.slice(position));
4026
+ if (numberMatch) {
4027
+ tokens.push({ kind: "number", value: numberMatch[0] });
4028
+ position += numberMatch[0].length;
4029
+ } else if (identifierMatch) {
4030
+ tokens.push({ kind: "identifier", value: identifierMatch[0] });
4031
+ position += identifierMatch[0].length;
4032
+ } else {
4033
+ const twoCharacters = source.slice(position, position + 2);
4034
+ if (["<=", ">=", "<>", "!="].includes(twoCharacters)) {
4035
+ tokens.push({ kind: "symbol", value: twoCharacters });
4036
+ position += 2;
4037
+ } else if ("(),;-=<>".includes(character)) {
4038
+ tokens.push({ kind: "symbol", value: character });
4039
+ position++;
4040
+ } else {
4041
+ throw new Error(`SQL predicate contains an unsupported token at character ${position}`);
4042
+ }
4043
+ }
4044
+ }
4045
+ if (tokens.length > MAXIMUM_SQL_TOKENS) {
4046
+ throw new Error("SQL predicate exceeds its safe token limit");
4047
+ }
4048
+ }
4049
+ return tokens;
4050
+ }
4051
+ function readQuotedToken(source, start, quote, escapedQuote) {
4052
+ let value = "";
4053
+ let position = start + 1;
4054
+ while (position < source.length) {
4055
+ if (source[position] !== quote) {
4056
+ value += source[position++];
4057
+ continue;
4058
+ }
4059
+ if (source[position + 1] === escapedQuote) {
4060
+ value += quote;
4061
+ position += 2;
4062
+ continue;
4063
+ }
4064
+ return { value, position: position + 1 };
4065
+ }
4066
+ throw new Error(`SQL predicate contains an unterminated quoted value at character ${start}`);
4067
+ }
4068
+
4069
+ // dist/bind-sql-predicate.js
4070
+ function bindSQLPredicate(predicate, parameters) {
4071
+ validateSQLPredicate(predicate);
4072
+ return bindColumnarPredicateParameters(predicate, parameters);
4073
+ }
759
4074
  //# sourceMappingURL=index.cjs.map