@math.gl/sql 0.0.0-stage → 5.0.0-beta.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 (334) hide show
  1. package/LICENSE +249 -0
  2. package/README.md +26 -2
  3. package/THIRD-PARTY-NOTICES.md +5 -0
  4. package/dist/arrow/aggregates.d.ts +46 -0
  5. package/dist/arrow/aggregates.d.ts.map +1 -0
  6. package/dist/arrow/aggregates.js +289 -0
  7. package/dist/arrow/aggregates.js.map +1 -0
  8. package/dist/arrow/buffers.d.ts +30 -0
  9. package/dist/arrow/buffers.d.ts.map +1 -0
  10. package/dist/arrow/buffers.js +177 -0
  11. package/dist/arrow/buffers.js.map +1 -0
  12. package/dist/arrow/cast.d.ts +19 -0
  13. package/dist/arrow/cast.d.ts.map +1 -0
  14. package/dist/arrow/cast.js +138 -0
  15. package/dist/arrow/cast.js.map +1 -0
  16. package/dist/arrow/compiler.d.ts +10 -0
  17. package/dist/arrow/compiler.d.ts.map +1 -0
  18. package/dist/arrow/compiler.js +1421 -0
  19. package/dist/arrow/compiler.js.map +1 -0
  20. package/dist/arrow/float16.d.ts +7 -0
  21. package/dist/arrow/float16.d.ts.map +1 -0
  22. package/dist/arrow/float16.js +26 -0
  23. package/dist/arrow/float16.js.map +1 -0
  24. package/dist/arrow/index.cjs +3220 -0
  25. package/dist/arrow/index.cjs.map +6 -0
  26. package/dist/arrow/index.d.ts +5 -0
  27. package/dist/arrow/index.d.ts.map +1 -0
  28. package/dist/arrow/index.js +7 -0
  29. package/dist/arrow/index.js.map +1 -0
  30. package/dist/arrow/like.d.ts +3 -0
  31. package/dist/arrow/like.d.ts.map +1 -0
  32. package/dist/arrow/like.js +75 -0
  33. package/dist/arrow/like.js.map +1 -0
  34. package/dist/arrow/list-values.d.ts +14 -0
  35. package/dist/arrow/list-values.d.ts.map +1 -0
  36. package/dist/arrow/list-values.js +180 -0
  37. package/dist/arrow/list-values.js.map +1 -0
  38. package/dist/arrow/predicate.d.ts +7 -0
  39. package/dist/arrow/predicate.d.ts.map +1 -0
  40. package/dist/arrow/predicate.js +10 -0
  41. package/dist/arrow/predicate.js.map +1 -0
  42. package/dist/arrow/query-arrow-aggregate-snapshots.d.ts +24 -0
  43. package/dist/arrow/query-arrow-aggregate-snapshots.d.ts.map +1 -0
  44. package/dist/arrow/query-arrow-aggregate-snapshots.js +64 -0
  45. package/dist/arrow/query-arrow-aggregate-snapshots.js.map +1 -0
  46. package/dist/arrow/query-arrow-sql.d.ts +8 -0
  47. package/dist/arrow/query-arrow-sql.d.ts.map +1 -0
  48. package/dist/arrow/query-arrow-sql.js +191 -0
  49. package/dist/arrow/query-arrow-sql.js.map +1 -0
  50. package/dist/arrow/query-arrow-table.d.ts +36 -0
  51. package/dist/arrow/query-arrow-table.d.ts.map +1 -0
  52. package/dist/arrow/query-arrow-table.js +208 -0
  53. package/dist/arrow/query-arrow-table.js.map +1 -0
  54. package/dist/arrow/query-worker-entry.d.ts +2 -0
  55. package/dist/arrow/query-worker-entry.d.ts.map +1 -0
  56. package/dist/arrow/query-worker-entry.js +7 -0
  57. package/dist/arrow/query-worker-entry.js.map +1 -0
  58. package/dist/arrow/query-worker.d.ts +65 -0
  59. package/dist/arrow/query-worker.d.ts.map +1 -0
  60. package/dist/arrow/query-worker.js +135 -0
  61. package/dist/arrow/query-worker.js.map +1 -0
  62. package/dist/arrow/registry.d.ts +4 -0
  63. package/dist/arrow/registry.d.ts.map +1 -0
  64. package/dist/arrow/registry.js +65 -0
  65. package/dist/arrow/registry.js.map +1 -0
  66. package/dist/arrow/relational-query.d.ts +36 -0
  67. package/dist/arrow/relational-query.d.ts.map +1 -0
  68. package/dist/arrow/relational-query.js +174 -0
  69. package/dist/arrow/relational-query.js.map +1 -0
  70. package/dist/arrow/replace-arrow-columns.d.ts +8 -0
  71. package/dist/arrow/replace-arrow-columns.d.ts.map +1 -0
  72. package/dist/arrow/replace-arrow-columns.js +63 -0
  73. package/dist/arrow/replace-arrow-columns.js.map +1 -0
  74. package/dist/arrow/signature.d.ts +6 -0
  75. package/dist/arrow/signature.d.ts.map +1 -0
  76. package/dist/arrow/signature.js +51 -0
  77. package/dist/arrow/signature.js.map +1 -0
  78. package/dist/arrow/temporal-cast.d.ts +9 -0
  79. package/dist/arrow/temporal-cast.d.ts.map +1 -0
  80. package/dist/arrow/temporal-cast.js +60 -0
  81. package/dist/arrow/temporal-cast.js.map +1 -0
  82. package/dist/arrow/types.d.ts +62 -0
  83. package/dist/arrow/types.d.ts.map +1 -0
  84. package/dist/arrow/types.js +5 -0
  85. package/dist/arrow/types.js.map +1 -0
  86. package/dist/arrow/worker-entry.d.ts +2 -0
  87. package/dist/arrow/worker-entry.d.ts.map +1 -0
  88. package/dist/arrow/worker-entry.js +9 -0
  89. package/dist/arrow/worker-entry.js.map +1 -0
  90. package/dist/arrow/worker.cjs +3973 -0
  91. package/dist/arrow/worker.cjs.map +6 -0
  92. package/dist/arrow/worker.d.ts +58 -0
  93. package/dist/arrow/worker.d.ts.map +1 -0
  94. package/dist/arrow/worker.js +84 -0
  95. package/dist/arrow/worker.js.map +1 -0
  96. package/dist/color/index.cjs +382 -0
  97. package/dist/color/index.cjs.map +6 -0
  98. package/dist/color/index.d.ts +26 -0
  99. package/dist/color/index.d.ts.map +1 -0
  100. package/dist/color/index.js +306 -0
  101. package/dist/color/index.js.map +1 -0
  102. package/dist/diagnostic-log.d.ts +8 -0
  103. package/dist/diagnostic-log.d.ts.map +1 -0
  104. package/dist/diagnostic-log.js +15 -0
  105. package/dist/diagnostic-log.js.map +1 -0
  106. package/dist/expressions/ast.d.ts +12 -0
  107. package/dist/expressions/ast.d.ts.map +1 -0
  108. package/dist/expressions/ast.js +112 -0
  109. package/dist/expressions/ast.js.map +1 -0
  110. package/dist/expressions/columnar-predicate.d.ts +56 -0
  111. package/dist/expressions/columnar-predicate.d.ts.map +1 -0
  112. package/dist/expressions/columnar-predicate.js +176 -0
  113. package/dist/expressions/columnar-predicate.js.map +1 -0
  114. package/dist/expressions/evaluation-error.d.ts +14 -0
  115. package/dist/expressions/evaluation-error.d.ts.map +1 -0
  116. package/dist/expressions/evaluation-error.js +26 -0
  117. package/dist/expressions/evaluation-error.js.map +1 -0
  118. package/dist/expressions/expression-eval.d.ts +96 -0
  119. package/dist/expressions/expression-eval.d.ts.map +1 -0
  120. package/dist/expressions/expression-eval.js +330 -0
  121. package/dist/expressions/expression-eval.js.map +1 -0
  122. package/dist/expressions/function-libraries.d.ts +63 -0
  123. package/dist/expressions/function-libraries.d.ts.map +1 -0
  124. package/dist/expressions/function-libraries.js +69 -0
  125. package/dist/expressions/function-libraries.js.map +1 -0
  126. package/dist/expressions/function-registry.d.ts +93 -0
  127. package/dist/expressions/function-registry.d.ts.map +1 -0
  128. package/dist/expressions/function-registry.js +139 -0
  129. package/dist/expressions/function-registry.js.map +1 -0
  130. package/dist/expressions/get.d.ts +9 -0
  131. package/dist/expressions/get.d.ts.map +1 -0
  132. package/dist/expressions/get.js +32 -0
  133. package/dist/expressions/get.js.map +1 -0
  134. package/dist/expressions/index.cjs +1888 -0
  135. package/dist/expressions/index.cjs.map +6 -0
  136. package/dist/expressions/index.d.ts +13 -0
  137. package/dist/expressions/index.d.ts.map +1 -0
  138. package/dist/expressions/index.js +14 -0
  139. package/dist/expressions/index.js.map +1 -0
  140. package/dist/expressions/numeric-functions.d.ts +277 -0
  141. package/dist/expressions/numeric-functions.d.ts.map +1 -0
  142. package/dist/expressions/numeric-functions.js +52 -0
  143. package/dist/expressions/numeric-functions.js.map +1 -0
  144. package/dist/expressions/parse-expression-string.d.ts +21 -0
  145. package/dist/expressions/parse-expression-string.d.ts.map +1 -0
  146. package/dist/expressions/parse-expression-string.js +61 -0
  147. package/dist/expressions/parse-expression-string.js.map +1 -0
  148. package/dist/expressions/predicate-expression.d.ts +7 -0
  149. package/dist/expressions/predicate-expression.d.ts.map +1 -0
  150. package/dist/expressions/predicate-expression.js +112 -0
  151. package/dist/expressions/predicate-expression.js.map +1 -0
  152. package/dist/expressions/scalar-type.d.ts +6 -0
  153. package/dist/expressions/scalar-type.d.ts.map +1 -0
  154. package/dist/expressions/scalar-type.js +23 -0
  155. package/dist/expressions/scalar-type.js.map +1 -0
  156. package/dist/expressions/vendor/jsep/runtime.d.ts +3 -0
  157. package/dist/expressions/vendor/jsep/runtime.d.ts.map +1 -0
  158. package/dist/expressions/vendor/jsep/runtime.js +972 -0
  159. package/dist/expressions/vendor/jsep/runtime.js.map +1 -0
  160. package/dist/expressions/vendor/jsep/types.d.ts +148 -0
  161. package/dist/expressions/vendor/jsep/types.d.ts.map +1 -0
  162. package/dist/expressions/vendor/jsep/types.js +6 -0
  163. package/dist/expressions/vendor/jsep/types.js.map +1 -0
  164. package/dist/index.cjs +4865 -0
  165. package/dist/index.cjs.map +6 -0
  166. package/dist/index.d.ts +9 -0
  167. package/dist/index.d.ts.map +1 -0
  168. package/dist/index.js +10 -0
  169. package/dist/index.js.map +1 -0
  170. package/dist/math/index.cjs +444 -0
  171. package/dist/math/index.cjs.map +6 -0
  172. package/dist/math/index.d.ts +44 -0
  173. package/dist/math/index.d.ts.map +1 -0
  174. package/dist/math/index.js +182 -0
  175. package/dist/math/index.js.map +1 -0
  176. package/dist/scales/arrow-domains.d.ts +15 -0
  177. package/dist/scales/arrow-domains.d.ts.map +1 -0
  178. package/dist/scales/arrow-domains.js +124 -0
  179. package/dist/scales/arrow-domains.js.map +1 -0
  180. package/dist/scales/arrow-scales.cjs +3837 -0
  181. package/dist/scales/arrow-scales.cjs.map +6 -0
  182. package/dist/scales/arrow-scales.d.ts +20 -0
  183. package/dist/scales/arrow-scales.d.ts.map +1 -0
  184. package/dist/scales/arrow-scales.js +109 -0
  185. package/dist/scales/arrow-scales.js.map +1 -0
  186. package/dist/scales/compile-scale.d.ts +7 -0
  187. package/dist/scales/compile-scale.d.ts.map +1 -0
  188. package/dist/scales/compile-scale.js +195 -0
  189. package/dist/scales/compile-scale.js.map +1 -0
  190. package/dist/scales/hdr-colors.d.ts +13 -0
  191. package/dist/scales/hdr-colors.d.ts.map +1 -0
  192. package/dist/scales/hdr-colors.js +115 -0
  193. package/dist/scales/hdr-colors.js.map +1 -0
  194. package/dist/scales/index.cjs +1214 -0
  195. package/dist/scales/index.cjs.map +6 -0
  196. package/dist/scales/index.d.ts +9 -0
  197. package/dist/scales/index.d.ts.map +1 -0
  198. package/dist/scales/index.js +10 -0
  199. package/dist/scales/index.js.map +1 -0
  200. package/dist/scales/palettes.d.ts +5 -0
  201. package/dist/scales/palettes.d.ts.map +1 -0
  202. package/dist/scales/palettes.js +85 -0
  203. package/dist/scales/palettes.js.map +1 -0
  204. package/dist/scales/parse-sql-scale.d.ts +14 -0
  205. package/dist/scales/parse-sql-scale.d.ts.map +1 -0
  206. package/dist/scales/parse-sql-scale.js +165 -0
  207. package/dist/scales/parse-sql-scale.js.map +1 -0
  208. package/dist/scales/quantile-sketch.d.ts +22 -0
  209. package/dist/scales/quantile-sketch.d.ts.map +1 -0
  210. package/dist/scales/quantile-sketch.js +108 -0
  211. package/dist/scales/quantile-sketch.js.map +1 -0
  212. package/dist/scales/scale-types.d.ts +92 -0
  213. package/dist/scales/scale-types.d.ts.map +1 -0
  214. package/dist/scales/scale-types.js +119 -0
  215. package/dist/scales/scale-types.js.map +1 -0
  216. package/dist/scales/streaming-domains.d.ts +18 -0
  217. package/dist/scales/streaming-domains.d.ts.map +1 -0
  218. package/dist/scales/streaming-domains.js +109 -0
  219. package/dist/scales/streaming-domains.js.map +1 -0
  220. package/dist/sql/bind-sql-predicate.d.ts +4 -0
  221. package/dist/sql/bind-sql-predicate.d.ts.map +1 -0
  222. package/dist/sql/bind-sql-predicate.js +11 -0
  223. package/dist/sql/bind-sql-predicate.js.map +1 -0
  224. package/dist/sql/index.cjs +1588 -0
  225. package/dist/sql/index.cjs.map +6 -0
  226. package/dist/sql/index.d.ts +10 -0
  227. package/dist/sql/index.d.ts.map +1 -0
  228. package/dist/sql/index.js +10 -0
  229. package/dist/sql/index.js.map +1 -0
  230. package/dist/sql/parse-sql-expression.d.ts +44 -0
  231. package/dist/sql/parse-sql-expression.d.ts.map +1 -0
  232. package/dist/sql/parse-sql-expression.js +455 -0
  233. package/dist/sql/parse-sql-expression.js.map +1 -0
  234. package/dist/sql/parse-sql-predicate.d.ts +13 -0
  235. package/dist/sql/parse-sql-predicate.d.ts.map +1 -0
  236. package/dist/sql/parse-sql-predicate.js +365 -0
  237. package/dist/sql/parse-sql-predicate.js.map +1 -0
  238. package/dist/sql/parse-sql-query.d.ts +8 -0
  239. package/dist/sql/parse-sql-query.d.ts.map +1 -0
  240. package/dist/sql/parse-sql-query.js +66 -0
  241. package/dist/sql/parse-sql-query.js.map +1 -0
  242. package/dist/sql/parse-sql-select.d.ts +55 -0
  243. package/dist/sql/parse-sql-select.d.ts.map +1 -0
  244. package/dist/sql/parse-sql-select.js +244 -0
  245. package/dist/sql/parse-sql-select.js.map +1 -0
  246. package/dist/sql/parse-sql-statement.d.ts +50 -0
  247. package/dist/sql/parse-sql-statement.d.ts.map +1 -0
  248. package/dist/sql/parse-sql-statement.js +182 -0
  249. package/dist/sql/parse-sql-statement.js.map +1 -0
  250. package/dist/sql/query-types.d.ts +56 -0
  251. package/dist/sql/query-types.d.ts.map +1 -0
  252. package/dist/sql/query-types.js +5 -0
  253. package/dist/sql/query-types.js.map +1 -0
  254. package/dist/sql/sql-parse-error.d.ts +13 -0
  255. package/dist/sql/sql-parse-error.d.ts.map +1 -0
  256. package/dist/sql/sql-parse-error.js +20 -0
  257. package/dist/sql/sql-parse-error.js.map +1 -0
  258. package/dist/sql/sql-predicate-schema.d.ts +164 -0
  259. package/dist/sql/sql-predicate-schema.d.ts.map +1 -0
  260. package/dist/sql/sql-predicate-schema.js +249 -0
  261. package/dist/sql/sql-predicate-schema.js.map +1 -0
  262. package/dist/sql/sql-predicate-types.d.ts +48 -0
  263. package/dist/sql/sql-predicate-types.d.ts.map +1 -0
  264. package/dist/sql/sql-predicate-types.js +9 -0
  265. package/dist/sql/sql-predicate-types.js.map +1 -0
  266. package/dist/sql/sql-predicate.d.ts +6 -0
  267. package/dist/sql/sql-predicate.d.ts.map +1 -0
  268. package/dist/sql/sql-predicate.js +8 -0
  269. package/dist/sql/sql-predicate.js.map +1 -0
  270. package/package.json +92 -4
  271. package/src/arrow/aggregates.ts +386 -0
  272. package/src/arrow/buffers.ts +177 -0
  273. package/src/arrow/cast.ts +160 -0
  274. package/src/arrow/compiler.ts +1659 -0
  275. package/src/arrow/float16.ts +25 -0
  276. package/src/arrow/index.ts +22 -0
  277. package/src/arrow/like.ts +72 -0
  278. package/src/arrow/list-values.ts +200 -0
  279. package/src/arrow/predicate.ts +19 -0
  280. package/src/arrow/query-arrow-aggregate-snapshots.ts +107 -0
  281. package/src/arrow/query-arrow-sql.ts +227 -0
  282. package/src/arrow/query-arrow-table.ts +298 -0
  283. package/src/arrow/query-worker-entry.ts +8 -0
  284. package/src/arrow/query-worker.ts +190 -0
  285. package/src/arrow/registry.ts +86 -0
  286. package/src/arrow/relational-query.ts +247 -0
  287. package/src/arrow/replace-arrow-columns.ts +71 -0
  288. package/src/arrow/signature.ts +50 -0
  289. package/src/arrow/temporal-cast.ts +66 -0
  290. package/src/arrow/types.ts +76 -0
  291. package/src/arrow/worker-entry.ts +10 -0
  292. package/src/arrow/worker.ts +139 -0
  293. package/src/color/index.ts +405 -0
  294. package/src/diagnostic-log.ts +20 -0
  295. package/src/expressions/ast.ts +141 -0
  296. package/src/expressions/columnar-predicate.ts +293 -0
  297. package/src/expressions/evaluation-error.ts +29 -0
  298. package/src/expressions/expression-eval.ts +480 -0
  299. package/src/expressions/function-libraries.ts +126 -0
  300. package/src/expressions/function-registry.ts +171 -0
  301. package/src/expressions/get.ts +37 -0
  302. package/src/expressions/index.ts +40 -0
  303. package/src/expressions/numeric-functions.ts +99 -0
  304. package/src/expressions/parse-expression-string.ts +80 -0
  305. package/src/expressions/predicate-expression.ts +128 -0
  306. package/src/expressions/scalar-type.ts +39 -0
  307. package/src/expressions/vendor/jsep/LICENSE.txt +23 -0
  308. package/src/expressions/vendor/jsep/README.md +22 -0
  309. package/src/expressions/vendor/jsep/runtime.ts +949 -0
  310. package/src/expressions/vendor/jsep/types.ts +191 -0
  311. package/src/index.ts +40 -0
  312. package/src/math/index.ts +235 -0
  313. package/src/scales/arrow-domains.ts +131 -0
  314. package/src/scales/arrow-scales.ts +156 -0
  315. package/src/scales/compile-scale.ts +217 -0
  316. package/src/scales/hdr-colors.ts +126 -0
  317. package/src/scales/index.ts +35 -0
  318. package/src/scales/palettes.ts +86 -0
  319. package/src/scales/parse-sql-scale.ts +195 -0
  320. package/src/scales/quantile-sketch.ts +106 -0
  321. package/src/scales/scale-types.ts +224 -0
  322. package/src/scales/streaming-domains.ts +133 -0
  323. package/src/sql/bind-sql-predicate.ts +21 -0
  324. package/src/sql/index.ts +28 -0
  325. package/src/sql/parse-sql-expression.ts +457 -0
  326. package/src/sql/parse-sql-predicate.ts +454 -0
  327. package/src/sql/parse-sql-query.ts +72 -0
  328. package/src/sql/parse-sql-select.ts +266 -0
  329. package/src/sql/parse-sql-statement.ts +242 -0
  330. package/src/sql/query-types.ts +71 -0
  331. package/src/sql/sql-parse-error.ts +33 -0
  332. package/src/sql/sql-predicate-schema.ts +279 -0
  333. package/src/sql/sql-predicate-types.ts +91 -0
  334. package/src/sql/sql-predicate.ts +28 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,4865 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // dist/index.js
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ ExpressionEvaluationError: () => ExpressionEvaluationError,
23
+ compileArrowAggregates: () => compileArrowAggregates,
24
+ isExpressionEvaluationError: () => isExpressionEvaluationError,
25
+ queryArrowAggregateSnapshots: () => queryArrowAggregateSnapshots,
26
+ queryArrowSQL: () => queryArrowSQL,
27
+ queryArrowTable: () => queryArrowTable,
28
+ queryArrowTableInBatches: () => queryArrowTableInBatches,
29
+ replaceArrowColumns: () => replaceArrowColumns
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // dist/sql/sql-parse-error.js
34
+ var SQLParseError = class extends SyntaxError {
35
+ constructor(reason, source, offset) {
36
+ var _a2;
37
+ const lines = source.slice(0, offset).split(/\r\n|\r|\n/);
38
+ const line = lines.length;
39
+ const column = lines[line - 1].length + 1;
40
+ const token = ((_a2 = source.slice(offset, offset + 32).match(/^:?\w+|^\S/u)) == null ? void 0 : _a2[0]) ?? null;
41
+ super(`${reason} (line ${line}, column ${column}${token ? `, near ${JSON.stringify(token)}` : ""})`);
42
+ this.reason = reason;
43
+ this.name = "SQLParseError";
44
+ this.offset = offset;
45
+ this.line = line;
46
+ this.column = column;
47
+ this.token = token;
48
+ }
49
+ };
50
+
51
+ // dist/sql/parse-sql-expression.js
52
+ var SQL_RESERVED_WORDS = /* @__PURE__ */ new Set([
53
+ "SELECT",
54
+ "ARRAY",
55
+ "FROM",
56
+ "WHERE",
57
+ "LIMIT",
58
+ "OFFSET",
59
+ "AS",
60
+ "TRUE",
61
+ "FALSE",
62
+ "NULL",
63
+ "ALL",
64
+ "AND",
65
+ "OR",
66
+ "NOT",
67
+ "IN",
68
+ "IS",
69
+ "DISTINCT",
70
+ "ORDER",
71
+ "GROUP",
72
+ "HAVING",
73
+ "JOIN",
74
+ "UNION"
75
+ ]);
76
+ function sqlCastType(name, source = name, offset = 0) {
77
+ const normalized = name.toLowerCase().replace(/\s+/g, " ").trim();
78
+ if (/^(?:u?int(?:8|16|32|64)|float(?:16|32|64))$/.test(normalized)) {
79
+ return normalized;
80
+ }
81
+ switch (normalized) {
82
+ case "smallint":
83
+ return "int16";
84
+ case "int":
85
+ case "integer":
86
+ return "int32";
87
+ case "bigint":
88
+ return "int64";
89
+ case "real":
90
+ return "float32";
91
+ case "double precision":
92
+ return "float64";
93
+ case "boolean":
94
+ return "bool";
95
+ case "utf8":
96
+ case "varchar":
97
+ case "character varying":
98
+ return "utf8";
99
+ default:
100
+ throw new SQLParseError(`Unsupported SQL CAST type: ${name}`, source, offset);
101
+ }
102
+ }
103
+ var SQLExpressionReader = class {
104
+ constructor(source, start = 0) {
105
+ this.source = source;
106
+ this.tokens = 0;
107
+ this.depths = /* @__PURE__ */ new WeakMap();
108
+ this.position = start;
109
+ if (start === 0 && (typeof source !== "string" || !source.trim() || source.length > 65536))
110
+ throw new SQLParseError("SQL expression requires non-empty input of at most 65536 characters", "", 0);
111
+ }
112
+ /** Creates an error at the current expression cursor. */
113
+ error(message, offset = this.position) {
114
+ return new SQLParseError(message, this.source, offset);
115
+ }
116
+ space() {
117
+ while (this.position < this.source.length && /\s/.test(this.source[this.position]))
118
+ this.position++;
119
+ if (this.source.startsWith("--", this.position) || this.source.startsWith("/*", this.position))
120
+ throw this.error("SQL comments are not supported.");
121
+ }
122
+ word(word) {
123
+ this.space();
124
+ if (this.source.slice(this.position, this.position + word.length).toUpperCase() !== word || /[A-Za-z0-9_]/.test(this.source[this.position + word.length] || ""))
125
+ return false;
126
+ this.position += word.length;
127
+ this.token();
128
+ return true;
129
+ }
130
+ take(symbol) {
131
+ this.space();
132
+ if (!this.source.startsWith(symbol, this.position))
133
+ return false;
134
+ this.position += symbol.length;
135
+ this.token();
136
+ return true;
137
+ }
138
+ symbol(symbol) {
139
+ if (!this.take(symbol))
140
+ throw this.error(`SQL expression expected ${symbol}`);
141
+ }
142
+ node(value, children = []) {
143
+ const depth = children.length ? 1 + Math.max(...children.map((child) => this.depths.get(child) || 0)) : 0;
144
+ if (depth > 64)
145
+ throw this.error("SQL expression exceeds nesting limit");
146
+ this.depths.set(value, depth);
147
+ return value;
148
+ }
149
+ expression(depth = 0, minimum = 0) {
150
+ if (depth > 64)
151
+ throw this.error("SQL expression exceeds nesting limit");
152
+ let left;
153
+ if (this.word("NOT")) {
154
+ const argument = this.expression(depth + 1, 3);
155
+ left = this.node({ type: "UnaryExpression", operator: "!", argument }, [argument]);
156
+ } else if (/^\s*[+-](?:\d|\.\d)/.test(this.source.slice(this.position))) {
157
+ left = this.primary(depth);
158
+ } else if (this.take("+") || this.take("-")) {
159
+ const operator = this.source[this.position - 1];
160
+ const argument = this.expression(depth + 1, 6);
161
+ left = this.node({ type: "UnaryExpression", operator, argument }, [argument]);
162
+ } else
163
+ left = this.primary(depth);
164
+ while (true) {
165
+ const start = this.position;
166
+ if (this.take("[")) {
167
+ const index = this.expression(depth + 1);
168
+ this.symbol("]");
169
+ left = this.call("LIST_EXTRACT", [left, index], true);
170
+ continue;
171
+ }
172
+ if (this.take(".")) {
173
+ left = this.memberAccess(left, this.readIdentifier(true));
174
+ continue;
175
+ }
176
+ if (this.take("::")) {
177
+ if (minimum > 7) {
178
+ this.position = start;
179
+ break;
180
+ }
181
+ left = this.cast(left);
182
+ continue;
183
+ }
184
+ if (minimum <= 3 && this.word("IS")) {
185
+ const negate = this.word("NOT");
186
+ if (!this.word("NULL"))
187
+ throw this.error("SQL IS requires NULL or NOT NULL");
188
+ left = this.call(negate ? "isNotNull" : "isNull", [left]);
189
+ continue;
190
+ }
191
+ if (minimum <= 3) {
192
+ const negate = this.word("NOT");
193
+ const insensitive = this.word("ILIKE");
194
+ if (insensitive || this.word("LIKE")) {
195
+ const pattern = this.expression(depth + 1, 4);
196
+ const args = [left, pattern];
197
+ if (this.word("ESCAPE"))
198
+ args.push(this.expression(depth + 1, 4));
199
+ left = this.call(insensitive ? "ilike" : "like", args);
200
+ if (negate)
201
+ left = this.node({ type: "UnaryExpression", operator: "!", argument: left }, [left]);
202
+ continue;
203
+ }
204
+ this.position = start;
205
+ }
206
+ this.space();
207
+ const match = /^(OR\b|AND\b|\|\||<>|!=|<=|>=|=|<|>|\+|-|\*|\/)/i.exec(this.source.slice(this.position));
208
+ if (!match)
209
+ break;
210
+ const token = match[0].toUpperCase();
211
+ const precedence = token === "OR" ? 1 : token === "AND" ? 2 : ["=", "<>", "!=", "<", ">", "<=", ">="].includes(token) ? 3 : token === "+" || token === "-" || token === "||" ? 4 : 5;
212
+ if (precedence < minimum)
213
+ break;
214
+ this.position += match[0].length;
215
+ this.token();
216
+ const right = this.expression(depth + 1, precedence + 1);
217
+ if (token === "||") {
218
+ left = this.call("concatStrict", [left, right]);
219
+ continue;
220
+ }
221
+ const operator = token === "OR" ? "||" : token === "AND" ? "&&" : token === "=" ? "==" : token === "<>" ? "!=" : token;
222
+ left = this.node({ type: "BinaryExpression", operator, left, right }, [left, right]);
223
+ }
224
+ return left;
225
+ }
226
+ call(name, args, sqlFunction = false) {
227
+ return this.node({
228
+ type: "CallExpression",
229
+ callee: { type: "Identifier", name },
230
+ arguments: args,
231
+ ...sqlFunction ? { sqlFunction: true } : {}
232
+ }, args);
233
+ }
234
+ cast(argument) {
235
+ this.space();
236
+ const start = this.position;
237
+ const match = /^[A-Za-z][A-Za-z0-9]*(?:\s+(?:PRECISION|VARYING)\b)?/i.exec(this.source.slice(this.position));
238
+ if (!match)
239
+ throw this.error("SQL cast requires a target type");
240
+ this.position += match[0].length;
241
+ this.token();
242
+ if (this.take("[")) {
243
+ this.space();
244
+ const width = /^\d+/.exec(this.source.slice(this.position));
245
+ if (!width)
246
+ throw this.error("SQL ARRAY cast requires a fixed length");
247
+ this.position += width[0].length;
248
+ this.token();
249
+ this.symbol("]");
250
+ const array = argument;
251
+ if (array.type !== "CallExpression" || !/^array(?:_(?:float(?:16|32|64)|uint8))?$/.test(array.callee.name) || Number(width[0]) !== array.arguments.length)
252
+ throw this.error("ARRAY cast length must match the number of components");
253
+ const type = sqlCastType(match[0], this.source, start);
254
+ if (!["float16", "float32", "float64", "uint8"].includes(type))
255
+ throw this.error("Unsupported ARRAY cast type");
256
+ if (array.callee.name !== "array" && (type === "uint8" || array.callee.name === "array_uint8"))
257
+ throw this.error("Chained UINT8 array casts are not supported");
258
+ return this.call(`array_${type}`, array.arguments);
259
+ }
260
+ const name = match[0].toLowerCase();
261
+ let target;
262
+ if (name === "timestamp")
263
+ target = this.timestampCastType();
264
+ else if (name === "date" || name === "geometry")
265
+ target = name;
266
+ else if (name === "dictionary")
267
+ target = this.dictionaryCastType();
268
+ else if (/^(?:binary|varbinary|blob|fixedsizebinary)$/.test(name))
269
+ target = this.binaryCastType(name);
270
+ else
271
+ target = sqlCastType(name, this.source, start);
272
+ return this.call("cast", [
273
+ argument,
274
+ this.node({ type: "Literal", value: target, raw: JSON.stringify(target) })
275
+ ]);
276
+ }
277
+ /** Parses the optional SQL time zone qualifier. */
278
+ timestampCastType() {
279
+ const zoned = this.word("WITH");
280
+ if (!zoned && !this.word("WITHOUT"))
281
+ return "timestamp";
282
+ if (!this.word("TIME") || !this.word("ZONE"))
283
+ throw this.error("Expected TIME ZONE");
284
+ return zoned ? "timestamp_utc" : "timestamp";
285
+ }
286
+ /** Parses the supported Arrow dictionary layout. */
287
+ dictionaryCastType() {
288
+ this.symbol("(");
289
+ if (!this.word("UTF8"))
290
+ throw this.error("Expected UTF8 dictionary values");
291
+ this.symbol(",");
292
+ if (!this.word("INT32"))
293
+ throw this.error("Expected INT32 dictionary indices");
294
+ this.symbol(")");
295
+ return "dictionary_utf8_int32";
296
+ }
297
+ /** Parses binary aliases and optional positive byte widths. */
298
+ binaryCastType(name) {
299
+ var _a2;
300
+ if (name === "blob")
301
+ return "binary";
302
+ if (!this.take("(")) {
303
+ if (name === "fixedsizebinary")
304
+ throw this.error("FIXEDSIZEBINARY requires a byte width");
305
+ return "binary";
306
+ }
307
+ this.space();
308
+ const width = ((_a2 = /^\d+/.exec(this.source.slice(this.position))) == null ? void 0 : _a2[0]) ?? "";
309
+ const byteWidth = Number(width);
310
+ if (byteWidth < 1 || byteWidth > 2147483647)
311
+ throw this.error("Binary CAST requires a positive 32-bit byte width");
312
+ this.position += width.length;
313
+ this.token();
314
+ this.symbol(")");
315
+ return `${name === "varbinary" ? "varbinary" : "fixedsizebinary"}:${byteWidth}`;
316
+ }
317
+ primary(depth) {
318
+ if (depth > 64)
319
+ throw this.error("SQL expression exceeds nesting limit");
320
+ if (this.take("(")) {
321
+ const value = this.expression(depth + 1);
322
+ this.symbol(")");
323
+ return value;
324
+ }
325
+ if (this.word("CAST")) {
326
+ this.symbol("(");
327
+ const argument = this.expression(depth + 1);
328
+ if (!this.word("AS"))
329
+ throw this.error("SQL CAST requires AS");
330
+ const result = this.cast(argument);
331
+ this.symbol(")");
332
+ return result;
333
+ }
334
+ if (this.word("ARRAY")) {
335
+ this.symbol("[");
336
+ const args = [];
337
+ do {
338
+ args.push(this.expression(depth + 1));
339
+ } while (this.take(","));
340
+ this.symbol("]");
341
+ return this.call("array", args);
342
+ }
343
+ if (this.word("CASE")) {
344
+ const clauses = [];
345
+ while (this.word("WHEN")) {
346
+ const test = this.expression(depth + 1);
347
+ if (!this.word("THEN"))
348
+ throw this.error("SQL CASE requires THEN");
349
+ clauses.push({ test, consequent: this.expression(depth + 1) });
350
+ }
351
+ if (!clauses.length)
352
+ throw this.error("SQL CASE requires WHEN");
353
+ let alternate = this.word("ELSE") ? this.expression(depth + 1) : this.node({ type: "Literal", value: null, raw: "null" });
354
+ if (!this.word("END"))
355
+ throw this.error("SQL CASE requires END");
356
+ for (let index = clauses.length - 1; index >= 0; index--) {
357
+ const { test, consequent } = clauses[index];
358
+ alternate = this.node({ type: "ConditionalExpression", test, consequent, alternate }, [
359
+ test,
360
+ consequent,
361
+ alternate
362
+ ]);
363
+ }
364
+ return alternate;
365
+ }
366
+ this.space();
367
+ const start = this.position;
368
+ const extended = this.extendedPrimary();
369
+ if (extended)
370
+ return extended;
371
+ const quote = this.source[this.position];
372
+ if (quote === '"' || quote === "'") {
373
+ const value = this.quoted(quote);
374
+ return quote === '"' ? this.identifier(value, depth, false) : this.node({ type: "Literal", value, raw: JSON.stringify(value) });
375
+ }
376
+ const number = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(this.source.slice(this.position));
377
+ if (number) {
378
+ this.position += number[0].length;
379
+ this.token();
380
+ const value = Number(number[0]);
381
+ if (!Number.isFinite(value) || /^[+-]?\d+$/.test(number[0]) && !Number.isSafeInteger(value))
382
+ throw this.error("SQL numeric literal must be finite and exactly representable; use a quoted BIGINT value", start);
383
+ return this.node({ type: "Literal", value, raw: number[0] });
384
+ }
385
+ for (const [keyword, value] of [
386
+ ["NULL", null],
387
+ ["TRUE", true],
388
+ ["FALSE", false]
389
+ ])
390
+ if (this.word(keyword))
391
+ return this.node({ type: "Literal", value, raw: keyword.toLowerCase() });
392
+ return this.identifier(this.readIdentifier(), depth, true);
393
+ }
394
+ /** Reads an identifier in projections, source references, and field access. */
395
+ readIdentifier(member = false) {
396
+ var _a2;
397
+ this.space();
398
+ if (this.source[this.position] === '"')
399
+ return this.quoted('"');
400
+ const identifier = (_a2 = /^[A-Za-z_][A-Za-z0-9_]*/.exec(this.source.slice(this.position))) == null ? void 0 : _a2[0];
401
+ if (!identifier || !member && (SQL_RESERVED_WORDS.has(identifier.toUpperCase()) || /^(WHEN|THEN|ELSE|END)$/i.test(identifier)))
402
+ throw this.error("SQL expression requires a column, literal or function");
403
+ this.position += identifier.length;
404
+ this.token();
405
+ return identifier;
406
+ }
407
+ /** Decodes a quoted token, including doubled quote escapes. */
408
+ quoted(quote) {
409
+ const start = this.position++;
410
+ this.token();
411
+ let value = "";
412
+ while (this.position < this.source.length) {
413
+ const character = this.source[this.position++];
414
+ if (character !== quote)
415
+ value += character;
416
+ else if (this.source[this.position] === quote) {
417
+ value += quote;
418
+ this.position++;
419
+ } else {
420
+ if (quote === '"' && !value)
421
+ throw this.error("SQL identifiers must not be empty", start);
422
+ return value;
423
+ }
424
+ }
425
+ throw this.error("Unterminated SQL expression quote", start);
426
+ }
427
+ identifier(name, depth, fold2) {
428
+ if (!this.take("("))
429
+ return this.node({ type: "Identifier", name });
430
+ const args = [];
431
+ const wildcard = fold2 && this.wildcardArgument(name);
432
+ if (wildcard) {
433
+ this.symbol(")");
434
+ return this.call(name, [wildcard], true);
435
+ }
436
+ if (!this.take(")")) {
437
+ do {
438
+ args.push(this.expression(depth + 1));
439
+ } while (this.take(","));
440
+ this.symbol(")");
441
+ }
442
+ return this.call(name, args, fold2);
443
+ }
444
+ extendedPrimary() {
445
+ return void 0;
446
+ }
447
+ /** Lowers field access to a portable expression call for Arrow binding. */
448
+ memberAccess(object, name) {
449
+ const key = this.node({ type: "Literal", value: name, raw: JSON.stringify(name) });
450
+ return this.call("STRUCT_EXTRACT", [object, key], true);
451
+ }
452
+ wildcardArgument(_name) {
453
+ return void 0;
454
+ }
455
+ token() {
456
+ if (++this.tokens > 4096)
457
+ throw this.error("SQL expression exceeds token limit");
458
+ }
459
+ };
460
+
461
+ // dist/sql/parse-sql-select.js
462
+ var MAXIMUM_SQL_LENGTH = 65536;
463
+ var MAXIMUM_SELECT_TOKENS = 4096;
464
+ var SQLQueryReader = class {
465
+ /** Rejects empty or oversized statements before scanning. */
466
+ constructor(sql) {
467
+ this.position = 0;
468
+ this.tokens = 0;
469
+ if (typeof sql !== "string" || !sql.trim() || sql.length > MAXIMUM_SQL_LENGTH)
470
+ throw new SQLParseError("SQL query requires a non-empty statement of at most 65536 characters.", "", 0);
471
+ this.sql = sql;
472
+ }
473
+ /** Reads a bounded scalar or fixed-array projection. */
474
+ selectionExpression() {
475
+ this.skipWhitespace();
476
+ this.countToken();
477
+ const reader = this.expressionReader();
478
+ const expression = reader.expression();
479
+ this.position = reader.position;
480
+ return expression;
481
+ }
482
+ /** Consumes one mandatory keyword. */
483
+ expectKeyword(keyword) {
484
+ if (!this.takeKeyword(keyword))
485
+ throw this.error(`SQL query expected ${keyword}.`);
486
+ }
487
+ /** Consumes an unquoted keyword without folding identifier names. */
488
+ takeKeyword(keyword) {
489
+ this.skipWhitespace();
490
+ const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(this.sql.slice(this.position));
491
+ if ((match == null ? void 0 : match[0].toUpperCase()) !== keyword)
492
+ return false;
493
+ this.position += match[0].length;
494
+ this.countToken();
495
+ return true;
496
+ }
497
+ /** Consumes a punctuation token. */
498
+ takeSymbol(symbol) {
499
+ this.skipWhitespace();
500
+ if (this.sql[this.position] !== symbol)
501
+ return false;
502
+ this.position++;
503
+ this.countToken();
504
+ return true;
505
+ }
506
+ /** Reads one literal identifier, including doubled double-quote escapes. */
507
+ identifier() {
508
+ this.countToken();
509
+ const reader = this.expressionReader();
510
+ const identifier = reader.readIdentifier();
511
+ this.position = reader.position;
512
+ return identifier;
513
+ }
514
+ /** Parses a WHERE fragment and translates its cursor back to the full statement. */
515
+ parseWhere(parse2) {
516
+ this.skipWhitespace();
517
+ const start = this.position;
518
+ const source = this.whereExpression();
519
+ try {
520
+ return parse2(source);
521
+ } catch (error) {
522
+ if (error instanceof SQLParseError)
523
+ throw new SQLParseError(error.reason, this.sql, start + error.offset);
524
+ throw error;
525
+ }
526
+ }
527
+ /** Creates an error at the current statement cursor. */
528
+ error(message, offset = this.position) {
529
+ return new SQLParseError(message, this.sql, offset);
530
+ }
531
+ /** Finds a top-level pagination clause or terminator without interpreting quoted predicate contents. */
532
+ whereExpression() {
533
+ this.skipWhitespace();
534
+ const start = this.position;
535
+ let quote = "";
536
+ let quoteStart = start;
537
+ let depth = 0;
538
+ let groupingDepth = 0;
539
+ const membershipParens = [];
540
+ while (this.position < this.sql.length) {
541
+ const character = this.sql[this.position];
542
+ if (quote) {
543
+ if (character === quote) {
544
+ if (this.sql[this.position + 1] === quote) {
545
+ this.position += 2;
546
+ continue;
547
+ }
548
+ quote = "";
549
+ }
550
+ } else if (character === '"' || character === "'") {
551
+ quote = character;
552
+ quoteStart = this.position;
553
+ } else if (this.sql.startsWith("--", this.position) || this.sql.startsWith("/*", this.position))
554
+ throw this.error("SQL comments are not supported.");
555
+ else if (character === "(") {
556
+ const membership = /\bIN\s*$/i.test(this.sql.slice(start, this.position));
557
+ membershipParens.push(membership);
558
+ depth++;
559
+ if (!membership && ++groupingDepth > 64)
560
+ throw this.error("SQL query exceeds its predicate nesting limit.");
561
+ } else if (character === ")") {
562
+ if (--depth < 0)
563
+ throw this.error("SQL query contains unbalanced parentheses.");
564
+ if (!membershipParens.pop())
565
+ groupingDepth--;
566
+ } else if (depth === 0 && (character === ";" || this.atPaginationClause()))
567
+ break;
568
+ this.position++;
569
+ }
570
+ if (quote || depth)
571
+ throw this.error("SQL query contains an unterminated predicate.", quote ? quoteStart : this.position);
572
+ const expression = this.sql.slice(start, this.position).trim();
573
+ if (!expression)
574
+ throw this.error("SQL WHERE requires a predicate.");
575
+ return expression;
576
+ }
577
+ /** Checks for an unquoted pagination keyword at the current predicate boundary. */
578
+ atPaginationClause() {
579
+ return !/[A-Za-z0-9_.:]/.test(this.sql[this.position - 1] || "") && /^(?:LIMIT|OFFSET)(?![A-Za-z0-9_.:])/i.test(this.sql.slice(this.position, this.position + 7));
580
+ }
581
+ /** Reads optional LIMIT and OFFSET in either order. */
582
+ pagination() {
583
+ let limit;
584
+ let offset;
585
+ while (true) {
586
+ if (this.takeKeyword("LIMIT")) {
587
+ if (limit !== void 0)
588
+ throw this.error("Duplicate SQL LIMIT clause.");
589
+ limit = this.rowCount("LIMIT");
590
+ } else if (this.takeKeyword("OFFSET")) {
591
+ if (offset !== void 0)
592
+ throw this.error("Duplicate SQL OFFSET clause.");
593
+ offset = this.rowCount("OFFSET");
594
+ if (!this.takeKeyword("ROWS"))
595
+ this.takeKeyword("ROW");
596
+ } else
597
+ break;
598
+ }
599
+ return {
600
+ ...offset === void 0 ? {} : { offset },
601
+ ...limit === void 0 ? {} : { limit }
602
+ };
603
+ }
604
+ /** Reads the non-negative safe integer for a pagination clause. */
605
+ rowCount(clause) {
606
+ this.skipWhitespace();
607
+ const match = /^\d+(?![A-Za-z0-9_.])/.exec(this.sql.slice(this.position));
608
+ const value = Number(match == null ? void 0 : match[0]);
609
+ if (!match || !Number.isSafeInteger(value))
610
+ throw this.error(`SQL ${clause} requires a non-negative safe integer.`);
611
+ this.position += match[0].length;
612
+ return value;
613
+ }
614
+ /** Requires one complete statement with at most one trailing semicolon. */
615
+ end() {
616
+ this.takeSymbol(";");
617
+ this.skipWhitespace();
618
+ if (this.position !== this.sql.length)
619
+ throw this.error("Unsupported SQL query syntax.");
620
+ }
621
+ /** Skips whitespace without altering quoted identifiers. */
622
+ skipWhitespace() {
623
+ while (this.position < this.sql.length && /\s/.test(this.sql[this.position]))
624
+ this.position++;
625
+ }
626
+ expressionReader() {
627
+ return new SQLExpressionReader(this.sql, this.position);
628
+ }
629
+ /** Bounds large projection lists independently of predicate parsing. */
630
+ countToken() {
631
+ if (++this.tokens > MAXIMUM_SELECT_TOKENS)
632
+ throw this.error("SQL query exceeds its structural token limit.");
633
+ }
634
+ };
635
+
636
+ // dist/sql/parse-sql-statement.js
637
+ function parseSQLSelectCompound(sql, options = {}) {
638
+ const reader = new RelationalQueryReader(sql, options);
639
+ const inputs = [readSelect(reader)];
640
+ while (reader.takeKeyword("UNION")) {
641
+ reader.expectKeyword("ALL");
642
+ inputs.push(readSelect(reader));
643
+ }
644
+ const tail = readTail(reader);
645
+ reader.end();
646
+ return { inputs, ...tail };
647
+ }
648
+ function readSelect(reader) {
649
+ reader.expectKeyword("SELECT");
650
+ const select = reader.takeSymbol("*") ? void 0 : readList(reader, () => {
651
+ const expression = reader.selectionExpression();
652
+ const alias = reader.takeKeyword("AS") ? reader.identifier() : void 0;
653
+ return { expression, ...alias === void 0 ? {} : { alias } };
654
+ });
655
+ reader.expectKeyword("FROM");
656
+ const from = readTable(reader);
657
+ const joins = [];
658
+ for (let type = readJoinType(reader); type; type = readJoinType(reader)) {
659
+ const table = readTable(reader);
660
+ reader.expectKeyword("ON");
661
+ joins.push({ type, table, on: reader.selectionExpression() });
662
+ }
663
+ const where = reader.takeKeyword("WHERE") ? reader.selectionExpression() : void 0;
664
+ const groupBy = readBy(reader, "GROUP", () => reader.selectionExpression());
665
+ return {
666
+ from,
667
+ joins,
668
+ ...select ? { select } : {},
669
+ ...where ? { where } : {},
670
+ ...groupBy ? { groupBy } : {}
671
+ };
672
+ }
673
+ function readTail(reader) {
674
+ const orderBy = readBy(reader, "ORDER", () => readSort(reader));
675
+ return { ...orderBy ? { orderBy } : {}, ...reader.pagination() };
676
+ }
677
+ function readBy(reader, clause, read) {
678
+ if (!reader.takeKeyword(clause))
679
+ return void 0;
680
+ reader.expectKeyword("BY");
681
+ return readList(reader, read);
682
+ }
683
+ function readTable(reader) {
684
+ const name = reader.tableName();
685
+ const alias = reader.takeKeyword("AS") ? reader.identifier() : reader.optionalAlias();
686
+ return { name, ...alias === void 0 ? {} : { alias } };
687
+ }
688
+ function readJoinType(reader) {
689
+ if (reader.takeKeyword("JOIN"))
690
+ return "inner";
691
+ let type;
692
+ if (reader.takeKeyword("INNER"))
693
+ type = "inner";
694
+ else if (reader.takeKeyword("LEFT")) {
695
+ reader.takeKeyword("OUTER");
696
+ type = "left";
697
+ } else if (reader.takeKeyword("SEMI"))
698
+ type = "semi";
699
+ else if (reader.takeKeyword("ANTI"))
700
+ type = "anti";
701
+ else
702
+ return void 0;
703
+ reader.expectKeyword("JOIN");
704
+ return type;
705
+ }
706
+ function readSort(reader) {
707
+ const expression = reader.selectionExpression();
708
+ const direction = reader.takeKeyword("DESC") ? "desc" : "asc";
709
+ if (direction === "asc")
710
+ reader.takeKeyword("ASC");
711
+ if (!reader.takeKeyword("NULLS"))
712
+ return { expression, direction };
713
+ if (reader.takeKeyword("FIRST"))
714
+ return { expression, direction, nulls: "first" };
715
+ reader.expectKeyword("LAST");
716
+ return { expression, direction, nulls: "last" };
717
+ }
718
+ function readList(reader, readItem) {
719
+ const items = [readItem()];
720
+ while (reader.takeSymbol(","))
721
+ items.push(readItem());
722
+ return items;
723
+ }
724
+ var RelationalQueryReader = class extends SQLQueryReader {
725
+ constructor(sql, options) {
726
+ super(sql);
727
+ this.options = options;
728
+ }
729
+ tableName() {
730
+ this.skipWhitespace();
731
+ if (/^LATERAL(?![A-Za-z0-9_])/i.test(this.sql.slice(this.position))) {
732
+ throw this.error("SQL LATERAL table expressions are not supported.");
733
+ }
734
+ return this.identifier();
735
+ }
736
+ /** Reads an implicit alias unless the next token starts a clause. */
737
+ optionalAlias() {
738
+ var _a2;
739
+ this.skipWhitespace();
740
+ if (this.sql[this.position] === '"')
741
+ return this.identifier();
742
+ const name = (_a2 = /^[A-Za-z_][A-Za-z0-9_]*/.exec(this.sql.slice(this.position))) == null ? void 0 : _a2[0];
743
+ if (name && !SQL_RESERVED_WORDS.has(name.toUpperCase()) && !/^(INNER|LEFT|RIGHT|FULL|CROSS|OUTER|SEMI|ANTI|NATURAL|LATERAL|ON)$/i.test(name))
744
+ return this.identifier();
745
+ return void 0;
746
+ }
747
+ expressionReader() {
748
+ return new RelationalExpressionReader(this.sql, this.position, this.options);
749
+ }
750
+ skipWhitespace() {
751
+ this.position = skipLineComments(this.sql, this.position);
752
+ }
753
+ };
754
+ var RelationalExpressionReader = class extends SQLExpressionReader {
755
+ constructor(source, position, options) {
756
+ super(source, position);
757
+ this.options = options;
758
+ }
759
+ space() {
760
+ this.position = skipLineComments(this.source, this.position);
761
+ super.space();
762
+ }
763
+ extendedPrimary() {
764
+ if (this.source[this.position] !== ":")
765
+ return void 0;
766
+ const parameter = /^:([A-Za-z_][A-Za-z0-9_]*)/.exec(this.source.slice(this.position));
767
+ if (!parameter || !this.options.parseParameter) {
768
+ throw this.error("SQL named parameters require a name and parseParameter callback");
769
+ }
770
+ this.position += parameter[0].length;
771
+ this.token();
772
+ return this.node(this.options.parseParameter(parameter[1]));
773
+ }
774
+ /** Preserves dot access until the planner can resolve table aliases. */
775
+ memberAccess(object, name) {
776
+ const property = this.node({ type: "Identifier", name });
777
+ return this.node({ type: "MemberExpression", computed: false, object, property }, [
778
+ object,
779
+ property
780
+ ]);
781
+ }
782
+ wildcardArgument(name) {
783
+ if (name.toUpperCase() !== "COUNT" || !this.take("*"))
784
+ return void 0;
785
+ return this.node({ type: "Identifier", name: "*", sqlWildcard: true });
786
+ }
787
+ };
788
+ function skipLineComments(source, position) {
789
+ while (position < source.length) {
790
+ if (/\s/.test(source[position]))
791
+ position++;
792
+ else if (source.startsWith("--", position)) {
793
+ while (position < source.length && !/[\r\n]/.test(source[position]))
794
+ position++;
795
+ } else
796
+ break;
797
+ }
798
+ return position;
799
+ }
800
+
801
+ // dist/arrow/query-arrow-table.js
802
+ var import_apache_arrow9 = require("apache-arrow");
803
+ var import_arrow2 = require("@math.gl/arrow");
804
+
805
+ // dist/arrow/compiler.js
806
+ var import_apache_arrow6 = require("apache-arrow");
807
+ var import_utf82 = require("@math.gl/arrow/utf8");
808
+
809
+ // dist/diagnostic-log.js
810
+ function reportDiagnosticError(log, error) {
811
+ if (log) {
812
+ try {
813
+ log.error(error instanceof Error ? error.message : String(error), error)();
814
+ } catch {
815
+ }
816
+ }
817
+ }
818
+
819
+ // dist/expressions/vendor/jsep/runtime.js
820
+ var Hooks = class {
821
+ /**
822
+ * @callback HookCallback
823
+ * @this {*|Jsep} this
824
+ * @param {Jsep} env
825
+ * @returns: void
826
+ */
827
+ /**
828
+ * Adds the given callback to the list of callbacks for the given hook.
829
+ *
830
+ * The callback will be invoked when the hook it is registered for is run.
831
+ *
832
+ * One callback function can be registered to multiple hooks and the same hook multiple times.
833
+ *
834
+ * @param {string|object} name The name of the hook, or an object of callbacks keyed by name
835
+ * @param {HookCallback|boolean} callback The callback function which is given environment variables.
836
+ * @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
837
+ * @public
838
+ */
839
+ add(name, callback, first) {
840
+ if (typeof arguments[0] != "string") {
841
+ for (let name2 in arguments[0]) {
842
+ this.add(name2, arguments[0][name2], arguments[1]);
843
+ }
844
+ } else {
845
+ (Array.isArray(name) ? name : [name]).forEach(function(name2) {
846
+ this[name2] = this[name2] || [];
847
+ if (callback) {
848
+ this[name2][first ? "unshift" : "push"](callback);
849
+ }
850
+ }, this);
851
+ }
852
+ }
853
+ /**
854
+ * Runs a hook invoking all registered callbacks with the given environment variables.
855
+ *
856
+ * Callbacks will be invoked synchronously and in the order in which they were registered.
857
+ *
858
+ * @param {string} name The name of the hook.
859
+ * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
860
+ * @public
861
+ */
862
+ run(name, env) {
863
+ this[name] = this[name] || [];
864
+ this[name].forEach(function(callback) {
865
+ callback.call(env && env.context ? env.context : env, env);
866
+ });
867
+ }
868
+ };
869
+ var Plugins = class {
870
+ constructor(jsep22) {
871
+ this.jsep = jsep22;
872
+ this.registered = {};
873
+ }
874
+ /**
875
+ * @callback PluginSetup
876
+ * @this {Jsep} jsep
877
+ * @returns: void
878
+ */
879
+ /**
880
+ * Adds the given plugin(s) to the registry
881
+ *
882
+ * @param {object} plugins
883
+ * @param {string} plugins.name The name of the plugin
884
+ * @param {PluginSetup} plugins.init The init function
885
+ * @public
886
+ */
887
+ register(...plugins) {
888
+ plugins.forEach((plugin) => {
889
+ if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
890
+ throw new Error("Invalid JSEP plugin format");
891
+ }
892
+ if (this.registered[plugin.name]) {
893
+ return;
894
+ }
895
+ plugin.init(this.jsep);
896
+ this.registered[plugin.name] = plugin;
897
+ });
898
+ }
899
+ };
900
+ var Jsep = class _Jsep {
901
+ /**
902
+ * @returns {string}
903
+ */
904
+ static get version() {
905
+ return "1.4.0";
906
+ }
907
+ /**
908
+ * @returns {string}
909
+ */
910
+ static toString() {
911
+ return "JavaScript Expression Parser (JSEP) v" + _Jsep.version;
912
+ }
913
+ // ==================== CONFIG ================================
914
+ /**
915
+ * @method addUnaryOp
916
+ * @param {string} op_name The name of the unary op to add
917
+ * @returns {Jsep}
918
+ */
919
+ static addUnaryOp(op_name) {
920
+ _Jsep.max_unop_len = Math.max(op_name.length, _Jsep.max_unop_len);
921
+ _Jsep.unary_ops[op_name] = 1;
922
+ return _Jsep;
923
+ }
924
+ /**
925
+ * @method jsep.addBinaryOp
926
+ * @param {string} op_name The name of the binary op to add
927
+ * @param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence
928
+ * @param {boolean} [isRightAssociative=false] whether operator is right-associative
929
+ * @returns {Jsep}
930
+ */
931
+ static addBinaryOp(op_name, precedence, isRightAssociative) {
932
+ _Jsep.max_binop_len = Math.max(op_name.length, _Jsep.max_binop_len);
933
+ _Jsep.binary_ops[op_name] = precedence;
934
+ if (isRightAssociative) {
935
+ _Jsep.right_associative.add(op_name);
936
+ } else {
937
+ _Jsep.right_associative.delete(op_name);
938
+ }
939
+ return _Jsep;
940
+ }
941
+ /**
942
+ * @method addIdentifierChar
943
+ * @param {string} char The additional character to treat as a valid part of an identifier
944
+ * @returns {Jsep}
945
+ */
946
+ static addIdentifierChar(char) {
947
+ _Jsep.additional_identifier_chars.add(char);
948
+ return _Jsep;
949
+ }
950
+ /**
951
+ * @method addLiteral
952
+ * @param {string} literal_name The name of the literal to add
953
+ * @param {*} literal_value The value of the literal
954
+ * @returns {Jsep}
955
+ */
956
+ static addLiteral(literal_name, literal_value) {
957
+ _Jsep.literals[literal_name] = literal_value;
958
+ return _Jsep;
959
+ }
960
+ /**
961
+ * @method removeUnaryOp
962
+ * @param {string} op_name The name of the unary op to remove
963
+ * @returns {Jsep}
964
+ */
965
+ static removeUnaryOp(op_name) {
966
+ delete _Jsep.unary_ops[op_name];
967
+ if (op_name.length === _Jsep.max_unop_len) {
968
+ _Jsep.max_unop_len = _Jsep.getMaxKeyLen(_Jsep.unary_ops);
969
+ }
970
+ return _Jsep;
971
+ }
972
+ /**
973
+ * @method removeAllUnaryOps
974
+ * @returns {Jsep}
975
+ */
976
+ static removeAllUnaryOps() {
977
+ _Jsep.unary_ops = {};
978
+ _Jsep.max_unop_len = 0;
979
+ return _Jsep;
980
+ }
981
+ /**
982
+ * @method removeIdentifierChar
983
+ * @param {string} char The additional character to stop treating as a valid part of an identifier
984
+ * @returns {Jsep}
985
+ */
986
+ static removeIdentifierChar(char) {
987
+ _Jsep.additional_identifier_chars.delete(char);
988
+ return _Jsep;
989
+ }
990
+ /**
991
+ * @method removeBinaryOp
992
+ * @param {string} op_name The name of the binary op to remove
993
+ * @returns {Jsep}
994
+ */
995
+ static removeBinaryOp(op_name) {
996
+ delete _Jsep.binary_ops[op_name];
997
+ if (op_name.length === _Jsep.max_binop_len) {
998
+ _Jsep.max_binop_len = _Jsep.getMaxKeyLen(_Jsep.binary_ops);
999
+ }
1000
+ _Jsep.right_associative.delete(op_name);
1001
+ return _Jsep;
1002
+ }
1003
+ /**
1004
+ * @method removeAllBinaryOps
1005
+ * @returns {Jsep}
1006
+ */
1007
+ static removeAllBinaryOps() {
1008
+ _Jsep.binary_ops = {};
1009
+ _Jsep.max_binop_len = 0;
1010
+ return _Jsep;
1011
+ }
1012
+ /**
1013
+ * @method removeLiteral
1014
+ * @param {string} literal_name The name of the literal to remove
1015
+ * @returns {Jsep}
1016
+ */
1017
+ static removeLiteral(literal_name) {
1018
+ delete _Jsep.literals[literal_name];
1019
+ return _Jsep;
1020
+ }
1021
+ /**
1022
+ * @method removeAllLiterals
1023
+ * @returns {Jsep}
1024
+ */
1025
+ static removeAllLiterals() {
1026
+ _Jsep.literals = {};
1027
+ return _Jsep;
1028
+ }
1029
+ // ==================== END CONFIG ============================
1030
+ /**
1031
+ * @returns {string}
1032
+ */
1033
+ get char() {
1034
+ return this.expr.charAt(this.index);
1035
+ }
1036
+ /**
1037
+ * @returns {number}
1038
+ */
1039
+ get code() {
1040
+ return this.expr.charCodeAt(this.index);
1041
+ }
1042
+ /**
1043
+ * @param {string} expr a string with the passed in express
1044
+ * @returns Jsep
1045
+ */
1046
+ constructor(expr) {
1047
+ this.expr = expr;
1048
+ this.index = 0;
1049
+ }
1050
+ /**
1051
+ * static top-level parser
1052
+ * @returns {jsep.Expression}
1053
+ */
1054
+ static parse(expr) {
1055
+ return new _Jsep(expr).parse();
1056
+ }
1057
+ /**
1058
+ * Get the longest key length of any object
1059
+ * @param {object} obj
1060
+ * @returns {number}
1061
+ */
1062
+ static getMaxKeyLen(obj) {
1063
+ return Math.max(0, ...Object.keys(obj).map((k) => k.length));
1064
+ }
1065
+ /**
1066
+ * `ch` is a character code in the next three functions
1067
+ * @param {number} ch
1068
+ * @returns {boolean}
1069
+ */
1070
+ static isDecimalDigit(ch) {
1071
+ return ch >= 48 && ch <= 57;
1072
+ }
1073
+ /**
1074
+ * Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.
1075
+ * @param {string} op_val
1076
+ * @returns {number}
1077
+ */
1078
+ static binaryPrecedence(op_val) {
1079
+ return _Jsep.binary_ops[op_val] || 0;
1080
+ }
1081
+ /**
1082
+ * Looks for start of identifier
1083
+ * @param {number} ch
1084
+ * @returns {boolean}
1085
+ */
1086
+ static isIdentifierStart(ch) {
1087
+ return ch >= 65 && ch <= 90 || // A...Z
1088
+ ch >= 97 && ch <= 122 || // a...z
1089
+ ch >= 128 && !_Jsep.binary_ops[String.fromCharCode(ch)] || // any non-ASCII that is not an operator
1090
+ _Jsep.additional_identifier_chars.has(String.fromCharCode(ch));
1091
+ }
1092
+ /**
1093
+ * @param {number} ch
1094
+ * @returns {boolean}
1095
+ */
1096
+ static isIdentifierPart(ch) {
1097
+ return _Jsep.isIdentifierStart(ch) || _Jsep.isDecimalDigit(ch);
1098
+ }
1099
+ /**
1100
+ * throw error at index of the expression
1101
+ * @param {string} message
1102
+ * @throws
1103
+ */
1104
+ throwError(message) {
1105
+ const error = new Error(message + " at character " + this.index);
1106
+ error.index = this.index;
1107
+ error.description = message;
1108
+ throw error;
1109
+ }
1110
+ /**
1111
+ * Run a given hook
1112
+ * @param {string} name
1113
+ * @param {jsep.Expression|false} [node]
1114
+ * @returns {?jsep.Expression}
1115
+ */
1116
+ runHook(name, node) {
1117
+ if (_Jsep.hooks[name]) {
1118
+ const env = { context: this, node };
1119
+ _Jsep.hooks.run(name, env);
1120
+ return env.node;
1121
+ }
1122
+ return node;
1123
+ }
1124
+ /**
1125
+ * Runs a given hook until one returns a node
1126
+ * @param {string} name
1127
+ * @returns {?jsep.Expression}
1128
+ */
1129
+ searchHook(name) {
1130
+ if (_Jsep.hooks[name]) {
1131
+ const env = { context: this };
1132
+ _Jsep.hooks[name].find(function(callback) {
1133
+ callback.call(env.context, env);
1134
+ return env.node;
1135
+ });
1136
+ return env.node;
1137
+ }
1138
+ }
1139
+ /**
1140
+ * Push `index` up to the next non-space character
1141
+ */
1142
+ gobbleSpaces() {
1143
+ let ch = this.code;
1144
+ while (ch === _Jsep.SPACE_CODE || ch === _Jsep.TAB_CODE || ch === _Jsep.LF_CODE || ch === _Jsep.CR_CODE) {
1145
+ ch = this.expr.charCodeAt(++this.index);
1146
+ }
1147
+ this.runHook("gobble-spaces");
1148
+ }
1149
+ /**
1150
+ * Top-level method to parse all expressions and returns compound or single node
1151
+ * @returns {jsep.Expression}
1152
+ */
1153
+ parse() {
1154
+ this.runHook("before-all");
1155
+ const nodes = this.gobbleExpressions();
1156
+ const node = nodes.length === 1 ? nodes[0] : {
1157
+ type: _Jsep.COMPOUND,
1158
+ body: nodes
1159
+ };
1160
+ return this.runHook("after-all", node);
1161
+ }
1162
+ /**
1163
+ * top-level parser (but can be reused within as well)
1164
+ * @param {number} [untilICode]
1165
+ * @returns {jsep.Expression[]}
1166
+ */
1167
+ gobbleExpressions(untilICode) {
1168
+ let nodes = [], ch_i, node;
1169
+ while (this.index < this.expr.length) {
1170
+ ch_i = this.code;
1171
+ if (ch_i === _Jsep.SEMCOL_CODE || ch_i === _Jsep.COMMA_CODE) {
1172
+ this.index++;
1173
+ } else {
1174
+ if (node = this.gobbleExpression()) {
1175
+ nodes.push(node);
1176
+ } else if (this.index < this.expr.length) {
1177
+ if (ch_i === untilICode) {
1178
+ break;
1179
+ }
1180
+ this.throwError('Unexpected "' + this.char + '"');
1181
+ }
1182
+ }
1183
+ }
1184
+ return nodes;
1185
+ }
1186
+ /**
1187
+ * The main parsing function.
1188
+ * @returns {?jsep.Expression}
1189
+ */
1190
+ gobbleExpression() {
1191
+ const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
1192
+ this.gobbleSpaces();
1193
+ return this.runHook("after-expression", node);
1194
+ }
1195
+ /**
1196
+ * Search for the operation portion of the string (e.g. `+`, `===`)
1197
+ * Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
1198
+ * and move down from 3 to 2 to 1 character until a matching binary operation is found
1199
+ * then, return that binary operation
1200
+ * @returns {string|boolean}
1201
+ */
1202
+ gobbleBinaryOp() {
1203
+ this.gobbleSpaces();
1204
+ let to_check = this.expr.substr(this.index, _Jsep.max_binop_len);
1205
+ let tc_len = to_check.length;
1206
+ while (tc_len > 0) {
1207
+ if (_Jsep.binary_ops.hasOwnProperty(to_check) && (!_Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !_Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
1208
+ this.index += tc_len;
1209
+ return to_check;
1210
+ }
1211
+ to_check = to_check.substr(0, --tc_len);
1212
+ }
1213
+ return false;
1214
+ }
1215
+ /**
1216
+ * This function is responsible for gobbling an individual expression,
1217
+ * e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
1218
+ * @returns {?jsep.BinaryExpression}
1219
+ */
1220
+ gobbleBinaryExpression() {
1221
+ let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
1222
+ left = this.gobbleToken();
1223
+ if (!left) {
1224
+ return left;
1225
+ }
1226
+ biop = this.gobbleBinaryOp();
1227
+ if (!biop) {
1228
+ return left;
1229
+ }
1230
+ biop_info = { value: biop, prec: _Jsep.binaryPrecedence(biop), right_a: _Jsep.right_associative.has(biop) };
1231
+ right = this.gobbleToken();
1232
+ if (!right) {
1233
+ this.throwError("Expected expression after " + biop);
1234
+ }
1235
+ stack = [left, biop_info, right];
1236
+ while (biop = this.gobbleBinaryOp()) {
1237
+ prec = _Jsep.binaryPrecedence(biop);
1238
+ if (prec === 0) {
1239
+ this.index -= biop.length;
1240
+ break;
1241
+ }
1242
+ biop_info = { value: biop, prec, right_a: _Jsep.right_associative.has(biop) };
1243
+ cur_biop = biop;
1244
+ const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
1245
+ while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
1246
+ right = stack.pop();
1247
+ biop = stack.pop().value;
1248
+ left = stack.pop();
1249
+ node = {
1250
+ type: _Jsep.BINARY_EXP,
1251
+ operator: biop,
1252
+ left,
1253
+ right
1254
+ };
1255
+ stack.push(node);
1256
+ }
1257
+ node = this.gobbleToken();
1258
+ if (!node) {
1259
+ this.throwError("Expected expression after " + cur_biop);
1260
+ }
1261
+ stack.push(biop_info, node);
1262
+ }
1263
+ i = stack.length - 1;
1264
+ node = stack[i];
1265
+ while (i > 1) {
1266
+ node = {
1267
+ type: _Jsep.BINARY_EXP,
1268
+ operator: stack[i - 1].value,
1269
+ left: stack[i - 2],
1270
+ right: node
1271
+ };
1272
+ i -= 2;
1273
+ }
1274
+ return node;
1275
+ }
1276
+ /**
1277
+ * An individual part of a binary expression:
1278
+ * e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
1279
+ * @returns {boolean|jsep.Expression}
1280
+ */
1281
+ gobbleToken() {
1282
+ let ch, to_check, tc_len, node;
1283
+ this.gobbleSpaces();
1284
+ node = this.searchHook("gobble-token");
1285
+ if (node) {
1286
+ return this.runHook("after-token", node);
1287
+ }
1288
+ ch = this.code;
1289
+ if (_Jsep.isDecimalDigit(ch) || ch === _Jsep.PERIOD_CODE) {
1290
+ return this.gobbleNumericLiteral();
1291
+ }
1292
+ if (ch === _Jsep.SQUOTE_CODE || ch === _Jsep.DQUOTE_CODE) {
1293
+ node = this.gobbleStringLiteral();
1294
+ } else if (ch === _Jsep.OBRACK_CODE) {
1295
+ node = this.gobbleArray();
1296
+ } else {
1297
+ to_check = this.expr.substr(this.index, _Jsep.max_unop_len);
1298
+ tc_len = to_check.length;
1299
+ while (tc_len > 0) {
1300
+ if (_Jsep.unary_ops.hasOwnProperty(to_check) && (!_Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !_Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
1301
+ this.index += tc_len;
1302
+ const argument = this.gobbleToken();
1303
+ if (!argument) {
1304
+ this.throwError("missing unaryOp argument");
1305
+ }
1306
+ return this.runHook("after-token", {
1307
+ type: _Jsep.UNARY_EXP,
1308
+ operator: to_check,
1309
+ argument,
1310
+ prefix: true
1311
+ });
1312
+ }
1313
+ to_check = to_check.substr(0, --tc_len);
1314
+ }
1315
+ if (_Jsep.isIdentifierStart(ch)) {
1316
+ node = this.gobbleIdentifier();
1317
+ if (_Jsep.literals.hasOwnProperty(node.name)) {
1318
+ node = {
1319
+ type: _Jsep.LITERAL,
1320
+ value: _Jsep.literals[node.name],
1321
+ raw: node.name
1322
+ };
1323
+ } else if (node.name === _Jsep.this_str) {
1324
+ node = { type: _Jsep.THIS_EXP };
1325
+ }
1326
+ } else if (ch === _Jsep.OPAREN_CODE) {
1327
+ node = this.gobbleGroup();
1328
+ }
1329
+ }
1330
+ if (!node) {
1331
+ return this.runHook("after-token", false);
1332
+ }
1333
+ node = this.gobbleTokenProperty(node);
1334
+ return this.runHook("after-token", node);
1335
+ }
1336
+ /**
1337
+ * Gobble properties of of identifiers/strings/arrays/groups.
1338
+ * e.g. `foo`, `bar.baz`, `foo['bar'].baz`
1339
+ * It also gobbles function calls:
1340
+ * e.g. `Math.acos(obj.angle)`
1341
+ * @param {jsep.Expression} node
1342
+ * @returns {jsep.Expression}
1343
+ */
1344
+ gobbleTokenProperty(node) {
1345
+ this.gobbleSpaces();
1346
+ let ch = this.code;
1347
+ while (ch === _Jsep.PERIOD_CODE || ch === _Jsep.OBRACK_CODE || ch === _Jsep.OPAREN_CODE || ch === _Jsep.QUMARK_CODE) {
1348
+ let optional;
1349
+ if (ch === _Jsep.QUMARK_CODE) {
1350
+ if (this.expr.charCodeAt(this.index + 1) !== _Jsep.PERIOD_CODE) {
1351
+ break;
1352
+ }
1353
+ optional = true;
1354
+ this.index += 2;
1355
+ this.gobbleSpaces();
1356
+ ch = this.code;
1357
+ }
1358
+ this.index++;
1359
+ if (ch === _Jsep.OBRACK_CODE) {
1360
+ node = {
1361
+ type: _Jsep.MEMBER_EXP,
1362
+ computed: true,
1363
+ object: node,
1364
+ property: this.gobbleExpression()
1365
+ };
1366
+ if (!node.property) {
1367
+ this.throwError('Unexpected "' + this.char + '"');
1368
+ }
1369
+ this.gobbleSpaces();
1370
+ ch = this.code;
1371
+ if (ch !== _Jsep.CBRACK_CODE) {
1372
+ this.throwError("Unclosed [");
1373
+ }
1374
+ this.index++;
1375
+ } else if (ch === _Jsep.OPAREN_CODE) {
1376
+ node = {
1377
+ type: _Jsep.CALL_EXP,
1378
+ "arguments": this.gobbleArguments(_Jsep.CPAREN_CODE),
1379
+ callee: node
1380
+ };
1381
+ } else if (ch === _Jsep.PERIOD_CODE || optional) {
1382
+ if (optional) {
1383
+ this.index--;
1384
+ }
1385
+ this.gobbleSpaces();
1386
+ node = {
1387
+ type: _Jsep.MEMBER_EXP,
1388
+ computed: false,
1389
+ object: node,
1390
+ property: this.gobbleIdentifier()
1391
+ };
1392
+ }
1393
+ if (optional) {
1394
+ node.optional = true;
1395
+ }
1396
+ this.gobbleSpaces();
1397
+ ch = this.code;
1398
+ }
1399
+ return node;
1400
+ }
1401
+ /**
1402
+ * Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
1403
+ * keep track of everything in the numeric literal and then calling `parseFloat` on that string
1404
+ * @returns {jsep.Literal}
1405
+ */
1406
+ gobbleNumericLiteral() {
1407
+ let number = "", ch, chCode;
1408
+ while (_Jsep.isDecimalDigit(this.code)) {
1409
+ number += this.expr.charAt(this.index++);
1410
+ }
1411
+ if (this.code === _Jsep.PERIOD_CODE) {
1412
+ number += this.expr.charAt(this.index++);
1413
+ while (_Jsep.isDecimalDigit(this.code)) {
1414
+ number += this.expr.charAt(this.index++);
1415
+ }
1416
+ }
1417
+ ch = this.char;
1418
+ if (ch === "e" || ch === "E") {
1419
+ number += this.expr.charAt(this.index++);
1420
+ ch = this.char;
1421
+ if (ch === "+" || ch === "-") {
1422
+ number += this.expr.charAt(this.index++);
1423
+ }
1424
+ while (_Jsep.isDecimalDigit(this.code)) {
1425
+ number += this.expr.charAt(this.index++);
1426
+ }
1427
+ if (!_Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
1428
+ this.throwError("Expected exponent (" + number + this.char + ")");
1429
+ }
1430
+ }
1431
+ chCode = this.code;
1432
+ if (_Jsep.isIdentifierStart(chCode)) {
1433
+ this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
1434
+ } else if (chCode === _Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === _Jsep.PERIOD_CODE) {
1435
+ this.throwError("Unexpected period");
1436
+ }
1437
+ return {
1438
+ type: _Jsep.LITERAL,
1439
+ value: parseFloat(number),
1440
+ raw: number
1441
+ };
1442
+ }
1443
+ /**
1444
+ * Parses a string literal, staring with single or double quotes with basic support for escape codes
1445
+ * e.g. `"hello world"`, `'this is\nJSEP'`
1446
+ * @returns {jsep.Literal}
1447
+ */
1448
+ gobbleStringLiteral() {
1449
+ let str = "";
1450
+ const startIndex = this.index;
1451
+ const quote = this.expr.charAt(this.index++);
1452
+ let closed = false;
1453
+ while (this.index < this.expr.length) {
1454
+ let ch = this.expr.charAt(this.index++);
1455
+ if (ch === quote) {
1456
+ closed = true;
1457
+ break;
1458
+ } else if (ch === "\\") {
1459
+ ch = this.expr.charAt(this.index++);
1460
+ switch (ch) {
1461
+ case "n":
1462
+ str += "\n";
1463
+ break;
1464
+ case "r":
1465
+ str += "\r";
1466
+ break;
1467
+ case "t":
1468
+ str += " ";
1469
+ break;
1470
+ case "b":
1471
+ str += "\b";
1472
+ break;
1473
+ case "f":
1474
+ str += "\f";
1475
+ break;
1476
+ case "v":
1477
+ str += "\v";
1478
+ break;
1479
+ default:
1480
+ str += ch;
1481
+ }
1482
+ } else {
1483
+ str += ch;
1484
+ }
1485
+ }
1486
+ if (!closed) {
1487
+ this.throwError('Unclosed quote after "' + str + '"');
1488
+ }
1489
+ return {
1490
+ type: _Jsep.LITERAL,
1491
+ value: str,
1492
+ raw: this.expr.substring(startIndex, this.index)
1493
+ };
1494
+ }
1495
+ /**
1496
+ * Gobbles only identifiers
1497
+ * e.g.: `foo`, `_value`, `$x1`
1498
+ * Also, this function checks if that identifier is a literal:
1499
+ * (e.g. `true`, `false`, `null`) or `this`
1500
+ * @returns {jsep.Identifier}
1501
+ */
1502
+ gobbleIdentifier() {
1503
+ let ch = this.code, start = this.index;
1504
+ if (_Jsep.isIdentifierStart(ch)) {
1505
+ this.index++;
1506
+ } else {
1507
+ this.throwError("Unexpected " + this.char);
1508
+ }
1509
+ while (this.index < this.expr.length) {
1510
+ ch = this.code;
1511
+ if (_Jsep.isIdentifierPart(ch)) {
1512
+ this.index++;
1513
+ } else {
1514
+ break;
1515
+ }
1516
+ }
1517
+ return {
1518
+ type: _Jsep.IDENTIFIER,
1519
+ name: this.expr.slice(start, this.index)
1520
+ };
1521
+ }
1522
+ /**
1523
+ * Gobbles a list of arguments within the context of a function call
1524
+ * or array literal. This function also assumes that the opening character
1525
+ * `(` or `[` has already been gobbled, and gobbles expressions and commas
1526
+ * until the terminator character `)` or `]` is encountered.
1527
+ * e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
1528
+ * @param {number} termination
1529
+ * @returns {jsep.Expression[]}
1530
+ */
1531
+ gobbleArguments(termination) {
1532
+ const args = [];
1533
+ let closed = false;
1534
+ let separator_count = 0;
1535
+ while (this.index < this.expr.length) {
1536
+ this.gobbleSpaces();
1537
+ let ch_i = this.code;
1538
+ if (ch_i === termination) {
1539
+ closed = true;
1540
+ this.index++;
1541
+ if (termination === _Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
1542
+ this.throwError("Unexpected token " + String.fromCharCode(termination));
1543
+ }
1544
+ break;
1545
+ } else if (ch_i === _Jsep.COMMA_CODE) {
1546
+ this.index++;
1547
+ separator_count++;
1548
+ if (separator_count !== args.length) {
1549
+ if (termination === _Jsep.CPAREN_CODE) {
1550
+ this.throwError("Unexpected token ,");
1551
+ } else if (termination === _Jsep.CBRACK_CODE) {
1552
+ for (let arg = args.length; arg < separator_count; arg++) {
1553
+ args.push(null);
1554
+ }
1555
+ }
1556
+ }
1557
+ } else if (args.length !== separator_count && separator_count !== 0) {
1558
+ this.throwError("Expected comma");
1559
+ } else {
1560
+ const node = this.gobbleExpression();
1561
+ if (!node || node.type === _Jsep.COMPOUND) {
1562
+ this.throwError("Expected comma");
1563
+ }
1564
+ args.push(node);
1565
+ }
1566
+ }
1567
+ if (!closed) {
1568
+ this.throwError("Expected " + String.fromCharCode(termination));
1569
+ }
1570
+ return args;
1571
+ }
1572
+ /**
1573
+ * Responsible for parsing a group of things within parentheses `()`
1574
+ * that have no identifier in front (so not a function call)
1575
+ * This function assumes that it needs to gobble the opening parenthesis
1576
+ * and then tries to gobble everything within that parenthesis, assuming
1577
+ * that the next thing it should see is the close parenthesis. If not,
1578
+ * then the expression probably doesn't have a `)`
1579
+ * @returns {boolean|jsep.Expression}
1580
+ */
1581
+ gobbleGroup() {
1582
+ this.index++;
1583
+ let nodes = this.gobbleExpressions(_Jsep.CPAREN_CODE);
1584
+ if (this.code === _Jsep.CPAREN_CODE) {
1585
+ this.index++;
1586
+ if (nodes.length === 1) {
1587
+ return nodes[0];
1588
+ } else if (!nodes.length) {
1589
+ return false;
1590
+ } else {
1591
+ return {
1592
+ type: _Jsep.SEQUENCE_EXP,
1593
+ expressions: nodes
1594
+ };
1595
+ }
1596
+ } else {
1597
+ this.throwError("Unclosed (");
1598
+ }
1599
+ }
1600
+ /**
1601
+ * Responsible for parsing Array literals `[1, 2, 3]`
1602
+ * This function assumes that it needs to gobble the opening bracket
1603
+ * and then tries to gobble the expressions as arguments.
1604
+ * @returns {jsep.ArrayExpression}
1605
+ */
1606
+ gobbleArray() {
1607
+ this.index++;
1608
+ return {
1609
+ type: _Jsep.ARRAY_EXP,
1610
+ elements: this.gobbleArguments(_Jsep.CBRACK_CODE)
1611
+ };
1612
+ }
1613
+ };
1614
+ var hooks = new Hooks();
1615
+ Object.assign(Jsep, {
1616
+ hooks,
1617
+ plugins: new Plugins(Jsep),
1618
+ // Node Types
1619
+ // ----------
1620
+ // This is the full set of types that any JSEP node can be.
1621
+ // Store them here to save space when minified
1622
+ COMPOUND: "Compound",
1623
+ SEQUENCE_EXP: "SequenceExpression",
1624
+ IDENTIFIER: "Identifier",
1625
+ MEMBER_EXP: "MemberExpression",
1626
+ LITERAL: "Literal",
1627
+ THIS_EXP: "ThisExpression",
1628
+ CALL_EXP: "CallExpression",
1629
+ UNARY_EXP: "UnaryExpression",
1630
+ BINARY_EXP: "BinaryExpression",
1631
+ ARRAY_EXP: "ArrayExpression",
1632
+ TAB_CODE: 9,
1633
+ LF_CODE: 10,
1634
+ CR_CODE: 13,
1635
+ SPACE_CODE: 32,
1636
+ PERIOD_CODE: 46,
1637
+ // '.'
1638
+ COMMA_CODE: 44,
1639
+ // ','
1640
+ SQUOTE_CODE: 39,
1641
+ // single quote
1642
+ DQUOTE_CODE: 34,
1643
+ // double quotes
1644
+ OPAREN_CODE: 40,
1645
+ // (
1646
+ CPAREN_CODE: 41,
1647
+ // )
1648
+ OBRACK_CODE: 91,
1649
+ // [
1650
+ CBRACK_CODE: 93,
1651
+ // ]
1652
+ QUMARK_CODE: 63,
1653
+ // ?
1654
+ SEMCOL_CODE: 59,
1655
+ // ;
1656
+ COLON_CODE: 58,
1657
+ // :
1658
+ // Operations
1659
+ // ----------
1660
+ // Use a quickly-accessible map to store all of the unary operators
1661
+ // Values are set to `1` (it really doesn't matter)
1662
+ unary_ops: {
1663
+ "-": 1,
1664
+ "!": 1,
1665
+ "~": 1,
1666
+ "+": 1
1667
+ },
1668
+ // Also use a map for the binary operations but set their values to their
1669
+ // binary precedence for quick reference (higher number = higher precedence)
1670
+ // see [Order of operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
1671
+ binary_ops: {
1672
+ "||": 1,
1673
+ "??": 1,
1674
+ "&&": 2,
1675
+ "|": 3,
1676
+ "^": 4,
1677
+ "&": 5,
1678
+ "==": 6,
1679
+ "!=": 6,
1680
+ "===": 6,
1681
+ "!==": 6,
1682
+ "<": 7,
1683
+ ">": 7,
1684
+ "<=": 7,
1685
+ ">=": 7,
1686
+ "<<": 8,
1687
+ ">>": 8,
1688
+ ">>>": 8,
1689
+ "+": 9,
1690
+ "-": 9,
1691
+ "*": 10,
1692
+ "/": 10,
1693
+ "%": 10,
1694
+ "**": 11
1695
+ },
1696
+ // sets specific binary_ops as right-associative
1697
+ right_associative: /* @__PURE__ */ new Set(["**"]),
1698
+ // Additional valid identifier chars, apart from a-z, A-Z and 0-9 (except on the starting char)
1699
+ additional_identifier_chars: /* @__PURE__ */ new Set(["$", "_"]),
1700
+ // Literals
1701
+ // ----------
1702
+ // Store the values to return for the various literals we may encounter
1703
+ literals: {
1704
+ "true": true,
1705
+ "false": false,
1706
+ "null": null
1707
+ },
1708
+ // Except for `this`, which is special. This could be changed to something like `'self'` as well
1709
+ this_str: "this"
1710
+ });
1711
+ Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
1712
+ Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
1713
+ var jsep = (expr) => new Jsep(expr).parse();
1714
+ var stdClassProps = Object.getOwnPropertyNames(class Test {
1715
+ });
1716
+ Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === void 0).forEach((m) => {
1717
+ jsep[m] = Jsep[m];
1718
+ });
1719
+ jsep.Jsep = Jsep;
1720
+ var CONDITIONAL_EXP = "ConditionalExpression";
1721
+ var ternary = {
1722
+ name: "ternary",
1723
+ init(jsep22) {
1724
+ jsep22.hooks.add("after-expression", function gobbleTernary(env) {
1725
+ if (env.node && this.code === jsep22.QUMARK_CODE) {
1726
+ this.index++;
1727
+ const test = env.node;
1728
+ const consequent = this.gobbleExpression();
1729
+ if (!consequent) {
1730
+ this.throwError("Expected expression");
1731
+ }
1732
+ this.gobbleSpaces();
1733
+ if (this.code === jsep22.COLON_CODE) {
1734
+ this.index++;
1735
+ const alternate = this.gobbleExpression();
1736
+ if (!alternate) {
1737
+ this.throwError("Expected expression");
1738
+ }
1739
+ env.node = {
1740
+ type: CONDITIONAL_EXP,
1741
+ test,
1742
+ consequent,
1743
+ alternate
1744
+ };
1745
+ if (test.operator && jsep22.binary_ops[test.operator] <= 0.9) {
1746
+ let newTest = test;
1747
+ while (newTest.right.operator && jsep22.binary_ops[newTest.right.operator] <= 0.9) {
1748
+ newTest = newTest.right;
1749
+ }
1750
+ env.node.test = newTest.right;
1751
+ newTest.right = env.node;
1752
+ env.node = test;
1753
+ }
1754
+ } else {
1755
+ this.throwError("Expected :");
1756
+ }
1757
+ }
1758
+ });
1759
+ }
1760
+ };
1761
+ jsep.plugins.register(ternary);
1762
+ var runtime_default = jsep;
1763
+
1764
+ // dist/expressions/expression-eval.js
1765
+ var jsep2 = runtime_default;
1766
+ function parse(expression, options) {
1767
+ try {
1768
+ return typeof expression === "string" ? jsep2(expression) : expression;
1769
+ } catch (error) {
1770
+ reportDiagnosticError(options == null ? void 0 : options.log, error);
1771
+ throw error;
1772
+ }
1773
+ }
1774
+
1775
+ // dist/expressions/scalar-type.js
1776
+ var COLUMNAR_SCALAR_TYPES = Object.freeze([
1777
+ "int8",
1778
+ "int16",
1779
+ "int32",
1780
+ "int64",
1781
+ "uint8",
1782
+ "uint16",
1783
+ "uint32",
1784
+ "uint64",
1785
+ "float16",
1786
+ "float32",
1787
+ "float64",
1788
+ "bool",
1789
+ "utf8"
1790
+ ]);
1791
+ function isColumnarScalarType(value) {
1792
+ return typeof value === "string" && COLUMNAR_SCALAR_TYPES.includes(value);
1793
+ }
1794
+
1795
+ // dist/expressions/columnar-predicate.js
1796
+ function getColumnarPredicateColumns(predicate) {
1797
+ return [...new Set(getColumnarPredicatePaths(predicate).map((path) => path[0]))];
1798
+ }
1799
+ function getColumnarPredicatePath(property) {
1800
+ return typeof property.property === "string" ? [property.property] : [...property.property];
1801
+ }
1802
+ function getColumnarPredicatePaths(predicate) {
1803
+ const paths = /* @__PURE__ */ new Map();
1804
+ visitColumnarPredicate(predicate, (child) => {
1805
+ if ("property" in child.args[0]) {
1806
+ const path = getColumnarPredicatePath(child.args[0]);
1807
+ paths.set(path.join("\0"), path);
1808
+ }
1809
+ });
1810
+ return [...paths.values()];
1811
+ }
1812
+ function validateColumnarPredicate(predicate, availableColumns) {
1813
+ visitColumnarPredicate(predicate, (child) => {
1814
+ if (child.op === "and" || child.op === "or") {
1815
+ if (child.args.length < 2)
1816
+ throw new Error(`Columnar predicate ${child.op} requires at least two child predicates`);
1817
+ return;
1818
+ }
1819
+ if (child.op === "not")
1820
+ return;
1821
+ const leaf = child;
1822
+ const casts = leaf.args[0].casts;
1823
+ if (casts !== void 0 && (!Array.isArray(casts) || !casts.length || casts.length > 64 || Array.from(casts).some((type) => !isColumnarScalarType(type))))
1824
+ throw new Error("Invalid columnar predicate casts");
1825
+ const path = getColumnarPredicatePath(leaf.args[0]);
1826
+ if (!path.length || path.some((component) => !component)) {
1827
+ throw new Error("Columnar predicate property path must contain non-empty strings");
1828
+ }
1829
+ if (!availableColumns.has(path[0]))
1830
+ throw new Error(`Columnar predicate column not found: ${path.join(".")}`);
1831
+ if (leaf.op === "in" && leaf.args[1].length === 0) {
1832
+ throw new Error("Columnar predicate in requires at least one value");
1833
+ }
1834
+ });
1835
+ }
1836
+ function isColumnarPredicateParameter(value) {
1837
+ const parameterValue = value;
1838
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 1 && Object.prototype.hasOwnProperty.call(value, "parameter") && typeof parameterValue.parameter === "string" && parameterValue.parameter.length > 0;
1839
+ }
1840
+ function isColumnarPredicateValue(value) {
1841
+ 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;
1842
+ }
1843
+ function bindColumnarPredicateParameters(predicate, parameters) {
1844
+ switch (predicate.op) {
1845
+ case "and":
1846
+ case "or":
1847
+ return {
1848
+ op: predicate.op,
1849
+ args: predicate.args.map((child) => bindColumnarPredicateParameters(child, parameters))
1850
+ };
1851
+ case "not":
1852
+ return {
1853
+ op: "not",
1854
+ args: [bindColumnarPredicateParameters(predicate.args[0], parameters)]
1855
+ };
1856
+ case "isNull":
1857
+ return { op: "isNull", args: [copyColumnarPredicateProperty(predicate.args[0])] };
1858
+ case "in":
1859
+ return {
1860
+ op: "in",
1861
+ args: [
1862
+ copyColumnarPredicateProperty(predicate.args[0]),
1863
+ predicate.args[1].map((value) => bindColumnarPredicateValue(value, parameters))
1864
+ ]
1865
+ };
1866
+ default:
1867
+ return {
1868
+ op: predicate.op,
1869
+ args: [
1870
+ copyColumnarPredicateProperty(predicate.args[0]),
1871
+ bindColumnarPredicateValue(predicate.args[1], parameters)
1872
+ ]
1873
+ };
1874
+ }
1875
+ }
1876
+ function visitColumnarPredicate(predicate, visitor) {
1877
+ visitor(predicate);
1878
+ if (predicate.op === "and" || predicate.op === "or")
1879
+ predicate.args.forEach((child) => visitColumnarPredicate(child, visitor));
1880
+ else if (predicate.op === "not")
1881
+ visitColumnarPredicate(predicate.args[0], visitor);
1882
+ }
1883
+ function bindColumnarPredicateValue(value, parameters) {
1884
+ if (!isColumnarPredicateParameter(value))
1885
+ return value;
1886
+ if (!Object.prototype.hasOwnProperty.call(parameters, value.parameter)) {
1887
+ throw new Error(`Columnar predicate parameter ":${value.parameter}" requires a value`);
1888
+ }
1889
+ const parameterValue = parameters[value.parameter];
1890
+ if (isColumnarPredicateParameter(parameterValue)) {
1891
+ throw new Error(`Columnar predicate parameter ":${value.parameter}" cannot reference another parameter`);
1892
+ }
1893
+ if (!isColumnarPredicateValue(parameterValue)) {
1894
+ throw new Error(`Columnar predicate parameter ":${value.parameter}" has an unsupported value`);
1895
+ }
1896
+ return copyColumnarPredicateValue(parameterValue);
1897
+ }
1898
+ function copyColumnarPredicateProperty(property) {
1899
+ return {
1900
+ ...property,
1901
+ ...property.casts ? { casts: [...property.casts] } : {},
1902
+ property: typeof property.property === "string" ? property.property : [...property.property]
1903
+ };
1904
+ }
1905
+ function copyColumnarPredicateValue(value) {
1906
+ if (value instanceof Uint8Array)
1907
+ return value.slice();
1908
+ if (value instanceof Date)
1909
+ return new Date(value.getTime());
1910
+ return value;
1911
+ }
1912
+
1913
+ // dist/expressions/ast.js
1914
+ var MAXIMUM_EXPRESSION_NODES = 16384;
1915
+ var MAXIMUM_EXPRESSION_DEPTH = 192;
1916
+ function validateExpressionAST(value, options = {}) {
1917
+ visitExpressionAST(value, () => {
1918
+ }, options);
1919
+ }
1920
+ function visitExpressionAST(value, visit, options) {
1921
+ var _a2;
1922
+ const maxNodes = options.maxNodes ?? MAXIMUM_EXPRESSION_NODES, maxDepth = options.maxDepth ?? MAXIMUM_EXPRESSION_DEPTH;
1923
+ if (!Number.isSafeInteger(maxNodes) || maxNodes < 1 || maxNodes > MAXIMUM_EXPRESSION_NODES || !Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > MAXIMUM_EXPRESSION_DEPTH)
1924
+ throw new Error(`Expression AST limits must not exceed ${MAXIMUM_EXPRESSION_NODES} nodes and ${MAXIMUM_EXPRESSION_DEPTH} levels`);
1925
+ const stack = [{ node: value, depth: 0 }];
1926
+ const ancestors = /* @__PURE__ */ new Set();
1927
+ let count = 0;
1928
+ while (stack.length) {
1929
+ const { node: input, depth, exit } = stack.pop();
1930
+ if (!input || typeof input !== "object" || Array.isArray(input))
1931
+ throw new Error("Invalid expression AST node");
1932
+ if (exit) {
1933
+ ancestors.delete(input);
1934
+ continue;
1935
+ }
1936
+ if (++count > maxNodes || depth > maxDepth)
1937
+ throw new Error("Expression AST exceeds node or depth limit");
1938
+ if (ancestors.has(input))
1939
+ throw new Error("Expression AST contains a cycle");
1940
+ ancestors.add(input);
1941
+ stack.push({ node: input, depth, exit: true });
1942
+ const node = input;
1943
+ const children = [];
1944
+ switch (node.type) {
1945
+ case "Identifier":
1946
+ if (typeof node.name !== "string" || !node.name.length || node.name.length > 65536)
1947
+ throw new Error("Invalid expression identifier");
1948
+ break;
1949
+ case "Literal":
1950
+ if (node.value !== null && !["number", "bigint", "boolean", "string"].includes(typeof node.value))
1951
+ throw new Error("Unsupported expression literal");
1952
+ if (node.raw !== void 0 && typeof node.raw !== "string")
1953
+ throw new Error("Invalid literal annotation");
1954
+ break;
1955
+ case "UnaryExpression":
1956
+ if (typeof node.operator !== "string" || !node.operator.length || node.operator.length > 32)
1957
+ throw new Error("Invalid expression operator");
1958
+ if (node.prefix !== void 0 && typeof node.prefix !== "boolean")
1959
+ throw new Error("Invalid unary annotation");
1960
+ children.push(node.argument);
1961
+ break;
1962
+ case "LogicalExpression":
1963
+ if (node.operator !== "&&" && node.operator !== "||")
1964
+ throw new Error("Invalid logical operator");
1965
+ children.push(node.left, node.right);
1966
+ break;
1967
+ case "BinaryExpression":
1968
+ if (typeof node.operator !== "string" || !node.operator.length || node.operator.length > 32)
1969
+ throw new Error("Invalid expression operator");
1970
+ children.push(node.left, node.right);
1971
+ break;
1972
+ case "ConditionalExpression":
1973
+ children.push(node.test, node.consequent, node.alternate);
1974
+ break;
1975
+ case "ArrayExpression":
1976
+ if (!Array.isArray(node.elements))
1977
+ throw new Error("Invalid expression array");
1978
+ if (node.elements.length + count > maxNodes)
1979
+ throw new Error("Expression AST exceeds node limit");
1980
+ for (const element of node.elements) {
1981
+ if (element == null)
1982
+ throw new Error("Expression array contains holes");
1983
+ children.push(element);
1984
+ }
1985
+ break;
1986
+ case "CallExpression":
1987
+ if (((_a2 = node.callee) == null ? void 0 : _a2.type) !== "Identifier" || typeof node.callee.name !== "string" || !node.callee.name.length || node.callee.name.length > 65536 || !Array.isArray(node.arguments) || node.sqlFunction !== void 0 && node.sqlFunction !== true)
1988
+ throw new Error("Expressions require named function calls");
1989
+ if (node.arguments.length + count > maxNodes)
1990
+ throw new Error("Expression AST exceeds node limit");
1991
+ children.push(...node.arguments);
1992
+ break;
1993
+ default:
1994
+ throw new Error(`Unsupported portable expression AST node: ${node.type}`);
1995
+ }
1996
+ if (children.length + count + stack.length - ancestors.size > maxNodes)
1997
+ throw new Error("Expression AST exceeds node limit");
1998
+ visit(node);
1999
+ for (let index = children.length - 1; index >= 0; index--)
2000
+ stack.push({ node: children[index], depth: depth + 1 });
2001
+ }
2002
+ }
2003
+
2004
+ // dist/expressions/predicate-expression.js
2005
+ function columnarPredicateToExpression(predicate, options = {}) {
2006
+ const stack = [{ node: predicate, depth: 0 }];
2007
+ let count = 0;
2008
+ let expressionNodes = 0;
2009
+ while (stack.length) {
2010
+ const { node, depth } = stack.pop();
2011
+ if (++count > 4096 || depth > 64)
2012
+ throw new Error("Predicate exceeds node or depth limit");
2013
+ if (!node || typeof node !== "object" || !Array.isArray(node.args) || !["and", "or", "not", "isNull", "in", "=", "<>", "<", "<=", ">", ">="].includes(node.op))
2014
+ throw new Error("Invalid columnar predicate");
2015
+ if (node.op === "and" || node.op === "or" || node.op === "not") {
2016
+ if (node.op === "not" && node.args.length !== 1)
2017
+ throw new Error("NOT requires one predicate");
2018
+ if (node.args.length + count + stack.length > 4096)
2019
+ throw new Error("Predicate exceeds node limit");
2020
+ expressionNodes += node.op === "not" ? 1 : Math.max(0, node.args.length - 1);
2021
+ for (const child of node.args)
2022
+ stack.push({ node: child, depth: depth + 1 });
2023
+ } else if (node.args.length !== (node.op === "isNull" ? 1 : 2) || !node.args[0] || typeof node.args[0] !== "object" || node.op === "in" && !Array.isArray(node.args[1]))
2024
+ throw new Error("Invalid predicate arguments");
2025
+ if (node.op !== "and" && node.op !== "or" && node.op !== "not") {
2026
+ const property = node.args[0];
2027
+ if (typeof property.property !== "string" && (!Array.isArray(property.property) || property.property.length !== 1))
2028
+ throw new Error("Expression normalization requires top-level columns");
2029
+ const casts = property.casts;
2030
+ if (casts !== void 0 && (!Array.isArray(casts) || casts.length > 64))
2031
+ throw new Error("Invalid columnar predicate casts");
2032
+ const literals = node.op === "in" ? node.args[1].length : node.op === "isNull" ? 0 : 1;
2033
+ if (literals > 4096)
2034
+ throw new Error("Predicate membership exceeds node limit");
2035
+ expressionNodes += 2 + 2 * ((casts == null ? void 0 : casts.length) ?? 0) + literals;
2036
+ }
2037
+ if (expressionNodes > MAXIMUM_EXPRESSION_NODES)
2038
+ throw new Error("Predicate exceeds normalized AST node limit");
2039
+ }
2040
+ const bound = bindColumnarPredicateParameters(predicate, options.parameters ?? {});
2041
+ validateColumnarPredicate(bound, new Set(getColumnarPredicateColumns(bound)));
2042
+ const expression = convert(bound);
2043
+ validateExpressionAST(expression);
2044
+ return expression;
2045
+ }
2046
+ function combine(operator, expressions) {
2047
+ if (expressions.length === 1)
2048
+ return expressions[0];
2049
+ const midpoint = Math.floor(expressions.length / 2);
2050
+ return {
2051
+ type: "BinaryExpression",
2052
+ operator,
2053
+ left: combine(operator, expressions.slice(0, midpoint)),
2054
+ right: combine(operator, expressions.slice(midpoint))
2055
+ };
2056
+ }
2057
+ function convert(predicate) {
2058
+ if (predicate.op === "and" || predicate.op === "or")
2059
+ return combine(predicate.op === "and" ? "&&" : "||", predicate.args.map(convert));
2060
+ if (predicate.op === "not")
2061
+ return {
2062
+ type: "UnaryExpression",
2063
+ operator: "!",
2064
+ prefix: true,
2065
+ argument: convert(predicate.args[0])
2066
+ };
2067
+ const property = predicate.args[0];
2068
+ const path = typeof property.property === "string" ? [property.property] : property.property;
2069
+ if (path.length !== 1)
2070
+ throw new Error("Expression normalization requires top-level columns");
2071
+ let left = { type: "Identifier", name: path[0] };
2072
+ const call = (name, args) => ({ type: "CallExpression", callee: { type: "Identifier", name }, arguments: args });
2073
+ for (const type of property.casts ?? [])
2074
+ left = call("cast", [
2075
+ left,
2076
+ { type: "Literal", value: type, raw: JSON.stringify(type) }
2077
+ ]);
2078
+ const literal = (value) => {
2079
+ var _a2;
2080
+ if (value instanceof Date || value instanceof Uint8Array)
2081
+ throw new Error("Date and binary predicate literals require explicit backend conversion");
2082
+ if (["int64", "uint64"].includes(((_a2 = property.casts) == null ? void 0 : _a2.at(-1)) ?? "") && typeof value === "number" && Number.isSafeInteger(value))
2083
+ value = BigInt(value);
2084
+ return {
2085
+ type: "Literal",
2086
+ value,
2087
+ raw: typeof value === "bigint" ? String(value) : JSON.stringify(value)
2088
+ };
2089
+ };
2090
+ if (predicate.op === "isNull")
2091
+ return call("isNull", [left]);
2092
+ if (predicate.op === "in")
2093
+ return call("in", [left, ...predicate.args[1].map(literal)]);
2094
+ return {
2095
+ type: "BinaryExpression",
2096
+ operator: predicate.op === "=" ? "==" : predicate.op === "<>" ? "!=" : predicate.op,
2097
+ left,
2098
+ right: literal(predicate.args[1])
2099
+ };
2100
+ }
2101
+
2102
+ // dist/expressions/evaluation-error.js
2103
+ var _a;
2104
+ var brand = /* @__PURE__ */ Symbol.for("@math.gl/core/ExpressionEvaluationError");
2105
+ var codes = ["domain", "conversion", "overflow", "divisionByZero"];
2106
+ var ExpressionEvaluationError = class extends Error {
2107
+ constructor(code, message) {
2108
+ super(message);
2109
+ this.code = code;
2110
+ this.name = "ExpressionEvaluationError";
2111
+ this[_a] = true;
2112
+ if (!codes.includes(code))
2113
+ throw new TypeError("Unknown Arrow evaluation error code");
2114
+ }
2115
+ };
2116
+ _a = brand;
2117
+ function isExpressionEvaluationError(error) {
2118
+ return typeof error === "object" && error !== null && error[brand] === true && codes.includes(error.code);
2119
+ }
2120
+
2121
+ // dist/arrow/buffers.js
2122
+ var import_apache_arrow = require("apache-arrow");
2123
+
2124
+ // dist/arrow/float16.js
2125
+ var import_core = require("@math.gl/core");
2126
+ function requireFloat16() {
2127
+ if (!(0, import_core.isFloat16ArrayConstructor)((0, import_core.getFloat16ArrayConstructor)()))
2128
+ throw new Error("Arrow Float16 expressions require native Float16Array support");
2129
+ }
2130
+ function float16Values(values) {
2131
+ if ((0, import_core.isFloat16Array)(values))
2132
+ return values;
2133
+ requireFloat16();
2134
+ const Constructor = (0, import_core.getFloat16ArrayConstructor)();
2135
+ return new Constructor(values.buffer, values.byteOffset, values.length);
2136
+ }
2137
+ function roundFloat16() {
2138
+ const cell = float16Values(new Uint16Array(1));
2139
+ return (value) => {
2140
+ cell[0] = value;
2141
+ return cell[0];
2142
+ };
2143
+ }
2144
+
2145
+ // dist/arrow/buffers.js
2146
+ function valueType(type) {
2147
+ return import_apache_arrow.DataType.isDictionary(type) ? valueType(type.dictionary) : type;
2148
+ }
2149
+ function typeKey(type) {
2150
+ type = valueType(type);
2151
+ if (import_apache_arrow.DataType.isInt(type))
2152
+ return `${type.isSigned ? "i" : "u"}${type.bitWidth}`;
2153
+ if (import_apache_arrow.DataType.isFloat(type)) {
2154
+ if (type.precision === import_apache_arrow.Precision.HALF)
2155
+ requireFloat16();
2156
+ return `f${type.precision}`;
2157
+ }
2158
+ if (import_apache_arrow.DataType.isBool(type))
2159
+ return "bool";
2160
+ if (import_apache_arrow.DataType.isUtf8(type))
2161
+ return "utf8";
2162
+ if (import_apache_arrow.DataType.isDate(type) && type.unit === import_apache_arrow.DateUnit.DAY)
2163
+ return "date32";
2164
+ if (import_apache_arrow.DataType.isTimestamp(type) && type.unit === import_apache_arrow.TimeUnit.MICROSECOND)
2165
+ return `timestamp_us:${type.timezone ?? ""}`;
2166
+ if (import_apache_arrow.DataType.isBinary(type))
2167
+ return "binary";
2168
+ if (import_apache_arrow.DataType.isFixedSizeBinary(type))
2169
+ return `fixedsizebinary:${type.byteWidth}`;
2170
+ if (import_apache_arrow.DataType.isNull(type))
2171
+ return "null";
2172
+ throw new Error(`Unsupported Arrow expression type: ${type}`);
2173
+ }
2174
+ var ColumnReader = class _ColumnReader {
2175
+ constructor(vector) {
2176
+ this.vector = vector;
2177
+ this.ends = [];
2178
+ this.location = [null, 0];
2179
+ this.range = [null, 0, 0];
2180
+ this.half = /* @__PURE__ */ new Map();
2181
+ this.dictionaries = /* @__PURE__ */ new Map();
2182
+ this.decoder = new TextDecoder();
2183
+ let end = 0;
2184
+ for (const data of vector.data) {
2185
+ end += data.length;
2186
+ this.ends.push(end);
2187
+ if (import_apache_arrow.DataType.isFloat(data.type) && data.type.precision === import_apache_arrow.Precision.HALF)
2188
+ this.half.set(data, float16Values(data.values));
2189
+ if (import_apache_arrow.DataType.isDictionary(data.type))
2190
+ this.dictionaries.set(data, new _ColumnReader(data.dictionary));
2191
+ }
2192
+ }
2193
+ /** Locates a chunk without constructing row objects. */
2194
+ chunk(row) {
2195
+ let index = 0;
2196
+ while (row >= this.ends[index])
2197
+ index++;
2198
+ this.location[0] = this.vector.data[index];
2199
+ this.location[1] = row - (index ? this.ends[index - 1] : 0);
2200
+ return this.location;
2201
+ }
2202
+ /** Tests validity with the physical bit offset. */
2203
+ isValid(row) {
2204
+ const [data, index] = this.chunk(row);
2205
+ if (import_apache_arrow.DataType.isNull(data.type))
2206
+ return false;
2207
+ const bit = data.offset + index;
2208
+ if (data.nullCount && !(data.nullBitmap[bit >> 3] & 1 << (bit & 7)))
2209
+ return false;
2210
+ return !import_apache_arrow.DataType.isDictionary(data.type) || this.dictionaries.get(data).isValid(Number(data.values[index]));
2211
+ }
2212
+ /** Reads a primitive; UTF-8 is decoded only for scalar callbacks or output materialization. */
2213
+ get(row) {
2214
+ if (!this.isValid(row))
2215
+ return null;
2216
+ const [data, index] = this.chunk(row);
2217
+ if (import_apache_arrow.DataType.isDictionary(data.type))
2218
+ return this.dictionaries.get(data).get(Number(data.values[index]));
2219
+ if (import_apache_arrow.DataType.isUtf8(data.type))
2220
+ return this.decoder.decode(data.values.subarray(data.valueOffsets[index], data.valueOffsets[index + 1]));
2221
+ if (import_apache_arrow.DataType.isBinary(data.type))
2222
+ return data.values.subarray(data.valueOffsets[index], data.valueOffsets[index + 1]);
2223
+ if (import_apache_arrow.DataType.isFixedSizeBinary(data.type))
2224
+ return data.values.subarray(data.stride * index, data.stride * (index + 1));
2225
+ if (import_apache_arrow.DataType.isBool(data.type)) {
2226
+ const bit = data.offset + index;
2227
+ return Boolean(data.values[bit >> 3] & 1 << (bit & 7));
2228
+ }
2229
+ return this.half.has(data) ? this.half.get(data)[index] : data.values[index];
2230
+ }
2231
+ /** Resolves UTF-8 buffers, including dictionary values, without decoding. */
2232
+ utf8(row) {
2233
+ const [data, index] = this.chunk(row);
2234
+ if (import_apache_arrow.DataType.isDictionary(data.type))
2235
+ return this.dictionaries.get(data).utf8(Number(data.values[index]));
2236
+ this.range[0] = data.values;
2237
+ this.range[1] = Number(data.valueOffsets[index]);
2238
+ this.range[2] = Number(data.valueOffsets[index + 1]);
2239
+ return this.range;
2240
+ }
2241
+ };
2242
+ function createValueValidator(inputType) {
2243
+ const type = valueType(inputType), key = typeKey(type);
2244
+ if (import_apache_arrow.DataType.isInt(type)) {
2245
+ if (type.bitWidth === 64) {
2246
+ const bits = BigInt(type.bitWidth), min2 = type.isSigned ? -(1n << bits - 1n) : 0n;
2247
+ const max2 = type.isSigned ? (1n << bits - 1n) - 1n : (1n << bits) - 1n;
2248
+ return (value) => {
2249
+ if (value === null)
2250
+ return;
2251
+ if (typeof value !== "bigint")
2252
+ throw new Error("64-bit integers require bigint values");
2253
+ if (value < min2 || value > max2)
2254
+ throw new ExpressionEvaluationError("overflow", "Integer expression overflow");
2255
+ };
2256
+ }
2257
+ const min = type.isSigned ? -(2 ** (type.bitWidth - 1)) : 0;
2258
+ const max = type.isSigned ? 2 ** (type.bitWidth - 1) - 1 : 2 ** type.bitWidth - 1;
2259
+ return (value) => {
2260
+ if (value === null)
2261
+ return;
2262
+ if (typeof value !== "number")
2263
+ throw new TypeError("Integer expressions require numeric values");
2264
+ if (!Number.isInteger(value))
2265
+ throw new ExpressionEvaluationError("conversion", "Integer expression requires integral numbers");
2266
+ if (value < min || value > max)
2267
+ throw new ExpressionEvaluationError("overflow", "Integer expression overflow");
2268
+ };
2269
+ }
2270
+ if (key === "date32") {
2271
+ return (value) => {
2272
+ if (value === null)
2273
+ return;
2274
+ if (typeof value !== "number" || !Number.isInteger(value) || value < -2147483648 || value > 2147483647)
2275
+ throw new ExpressionEvaluationError("overflow", "Invalid Date32 epoch day");
2276
+ };
2277
+ }
2278
+ if (key.startsWith("timestamp_us:")) {
2279
+ return (value) => {
2280
+ if (value === null)
2281
+ return;
2282
+ if (typeof value !== "bigint" || value !== BigInt.asIntN(64, value))
2283
+ throw new ExpressionEvaluationError("overflow", "Invalid timestamp epoch microseconds");
2284
+ };
2285
+ }
2286
+ if (import_apache_arrow.DataType.isBinary(type) || import_apache_arrow.DataType.isFixedSizeBinary(type)) {
2287
+ return (value) => {
2288
+ if (value === null)
2289
+ return;
2290
+ if (!(value instanceof Uint8Array) || import_apache_arrow.DataType.isFixedSizeBinary(type) && value.byteLength !== type.byteWidth)
2291
+ throw new Error(`Invalid value for ${type}`);
2292
+ };
2293
+ }
2294
+ const expected = import_apache_arrow.DataType.isFloat(type) ? "number" : key === "bool" ? "boolean" : "string";
2295
+ return (value) => {
2296
+ if (value !== null && (key === "null" || typeof value !== expected))
2297
+ throw new Error(`Invalid value for ${type}`);
2298
+ };
2299
+ }
2300
+ function validateValue(value, type) {
2301
+ createValueValidator(type)(value);
2302
+ }
2303
+
2304
+ // dist/arrow/cast.js
2305
+ var import_apache_arrow3 = require("apache-arrow");
2306
+ var import_utf8 = require("@math.gl/arrow/utf8");
2307
+
2308
+ // dist/arrow/temporal-cast.js
2309
+ var import_apache_arrow2 = require("apache-arrow");
2310
+ var DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
2311
+ var TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|[+-]\d{2}:\d{2})?$/;
2312
+ function bindTemporalCast(source, target) {
2313
+ const dateOnly = target === "date";
2314
+ const zoned = target === "timestamp_utc";
2315
+ const type = dateOnly ? new import_apache_arrow2.DateDay() : new import_apache_arrow2.TimestampMicrosecond(zoned ? "UTC" : void 0);
2316
+ const sourceKey = typeKey(source);
2317
+ if (sourceKey !== "utf8" && sourceKey !== "null" && sourceKey !== typeKey(type))
2318
+ throw new Error("Temporal CAST requires UTF8 or an input of the requested Arrow type");
2319
+ return {
2320
+ type,
2321
+ textInput: false,
2322
+ evaluate(value) {
2323
+ return typeof value === "string" ? parseTemporalValue(value, dateOnly, zoned) : value;
2324
+ }
2325
+ };
2326
+ }
2327
+ function parseTemporalValue(text, dateOnly, zoned) {
2328
+ const match = (dateOnly ? DATE : TIMESTAMP).exec(text.trim());
2329
+ const invalid = () => new ExpressionEvaluationError("conversion", "Invalid text for temporal CAST");
2330
+ if (!match)
2331
+ throw invalid();
2332
+ const [, yearText, monthText, dayText, hourText, minuteText, secondText, fraction, zone] = match;
2333
+ const year = Number(yearText);
2334
+ const month = Number(monthText);
2335
+ const day = Number(dayText);
2336
+ const calendar = /* @__PURE__ */ new Date(0);
2337
+ calendar.setUTCFullYear(year, month - 1, day);
2338
+ if (calendar.getUTCFullYear() !== year || calendar.getUTCMonth() !== month - 1 || calendar.getUTCDate() !== day)
2339
+ throw invalid();
2340
+ if (dateOnly)
2341
+ return calendar.getTime() / 864e5;
2342
+ const hour = Number(hourText);
2343
+ const minute = Number(minuteText);
2344
+ const second = Number(secondText);
2345
+ if (hour > 23 || minute > 59 || second > 59 || zoned !== Boolean(zone))
2346
+ throw invalid();
2347
+ let offsetMinutes = 0;
2348
+ if (zone && zone !== "Z") {
2349
+ const offsetHour = Number(zone.slice(1, 3));
2350
+ const offsetMinute = Number(zone.slice(4));
2351
+ if (offsetHour > 23 || offsetMinute > 59)
2352
+ throw invalid();
2353
+ offsetMinutes = (zone.startsWith("-") ? -1 : 1) * (offsetHour * 60 + offsetMinute);
2354
+ }
2355
+ const seconds = hour * 3600 + minute * 60 + second - offsetMinutes * 60;
2356
+ return BigInt(calendar.getTime() + seconds * 1e3) * 1000n + BigInt((fraction ?? "").padEnd(6, "0"));
2357
+ }
2358
+
2359
+ // dist/arrow/cast.js
2360
+ var CAST_TYPES = {
2361
+ int8: import_apache_arrow3.Int8,
2362
+ int16: import_apache_arrow3.Int16,
2363
+ int32: import_apache_arrow3.Int32,
2364
+ int64: import_apache_arrow3.Int64,
2365
+ uint8: import_apache_arrow3.Uint8,
2366
+ uint16: import_apache_arrow3.Uint16,
2367
+ uint32: import_apache_arrow3.Uint32,
2368
+ uint64: import_apache_arrow3.Uint64,
2369
+ float16: import_apache_arrow3.Float16,
2370
+ float32: import_apache_arrow3.Float32,
2371
+ float64: import_apache_arrow3.Float64,
2372
+ bool: import_apache_arrow3.Bool,
2373
+ utf8: import_apache_arrow3.Utf8
2374
+ };
2375
+ function bindCast(source, target) {
2376
+ if (target === "date" || target === "timestamp" || target === "timestamp_utc")
2377
+ return bindTemporalCast(source, target);
2378
+ const binaryTarget = typeof target === "string" && /^(varbinary|fixedsizebinary):([1-9]\d*)$/.exec(target);
2379
+ if (target === "binary" || binaryTarget) {
2380
+ const byteWidth = binaryTarget ? Number(binaryTarget[2]) : void 0;
2381
+ if (byteWidth !== void 0 && byteWidth > 2147483647)
2382
+ throw new Error("Binary CAST requires a positive 32-bit byte width");
2383
+ const type2 = binaryTarget && binaryTarget[1] === "fixedsizebinary" ? new import_apache_arrow3.FixedSizeBinary(byteWidth) : new import_apache_arrow3.Binary();
2384
+ const sourceKey2 = typeKey(source);
2385
+ const textInput2 = sourceKey2 === "utf8";
2386
+ if (!textInput2 && sourceKey2 !== "null" && sourceKey2 !== "binary" && !sourceKey2.startsWith("fixedsizebinary:"))
2387
+ throw new Error("Binary CAST requires binary or UTF8 input");
2388
+ return {
2389
+ type: type2,
2390
+ textInput: textInput2,
2391
+ evaluate(value, range) {
2392
+ const bytes2 = range ? range[0].subarray(range[1], range[2]) : value;
2393
+ if (bytes2 === null || byteWidth === void 0)
2394
+ return bytes2;
2395
+ if (bytes2.byteLength > byteWidth)
2396
+ throw new ExpressionEvaluationError("overflow", `Binary CAST exceeds ${byteWidth} bytes`);
2397
+ if (import_apache_arrow3.DataType.isFixedSizeBinary(type2) && bytes2.byteLength < byteWidth) {
2398
+ const padded = new Uint8Array(byteWidth);
2399
+ padded.set(bytes2);
2400
+ return padded;
2401
+ }
2402
+ return bytes2;
2403
+ }
2404
+ };
2405
+ }
2406
+ const dictionary = target === "dictionary_utf8_int32";
2407
+ if (dictionary)
2408
+ target = "utf8";
2409
+ if (!isColumnarScalarType(target))
2410
+ throw new Error("Unsupported scalar CAST target");
2411
+ const type = new CAST_TYPES[target]();
2412
+ const integer = import_apache_arrow3.DataType.isInt(type);
2413
+ const wideInteger = integer && type.bitWidth === 64;
2414
+ const sourceKey = typeKey(source);
2415
+ const textInput = sourceKey === "utf8";
2416
+ if (sourceKey === "date32" || sourceKey.startsWith("timestamp_us:"))
2417
+ throw new Error("Temporal CAST requires a matching temporal target");
2418
+ if (sourceKey === "binary" || sourceKey.startsWith("fixedsizebinary:"))
2419
+ throw new Error("CAST from binary requires a binary target");
2420
+ if (sourceKey !== "null" && (sourceKey === "bool" && !["bool", "utf8"].includes(target) || target === "bool" && !["bool", "utf8"].includes(sourceKey)))
2421
+ throw new Error("CAST between Boolean and numeric values is not supported");
2422
+ const validate = createValueValidator(type);
2423
+ const halfRound = target === "float16" ? roundFloat16() : void 0;
2424
+ const encoder2 = new TextEncoder();
2425
+ return {
2426
+ type: dictionary ? new import_apache_arrow3.Dictionary(new import_apache_arrow3.Utf8(), new import_apache_arrow3.Int32()) : type,
2427
+ textInput,
2428
+ evaluate(value, range) {
2429
+ if (value === null && !range)
2430
+ return null;
2431
+ let result;
2432
+ if (target === "utf8") {
2433
+ if (typeof value === "boolean")
2434
+ return value ? "TRUE" : "FALSE";
2435
+ return String(value);
2436
+ }
2437
+ if (textInput) {
2438
+ const input = range ?? (() => {
2439
+ const bytes3 = encoder2.encode(value);
2440
+ return [bytes3, 0, bytes3.length];
2441
+ })();
2442
+ const [bytes2, start, end] = input;
2443
+ result = target === "bool" ? (0, import_utf8.parseUTF8Boolean)(bytes2, start, end) ?? null : integer ? (0, import_utf8.parseUTF8BigInt)(bytes2, start, end) ?? null : (0, import_utf8.parseUTF8Number)(bytes2, start, end) ?? null;
2444
+ if (result === null)
2445
+ throw new ExpressionEvaluationError("conversion", `Invalid text for CAST to ${target}`);
2446
+ if (integer && !wideInteger)
2447
+ result = Number(result);
2448
+ } else if (target === "bool")
2449
+ result = value;
2450
+ else if (wideInteger) {
2451
+ if (typeof value === "number" && !Number.isFinite(value))
2452
+ throw new ExpressionEvaluationError("conversion", "Non-finite integer CAST");
2453
+ result = typeof value === "bigint" ? value : BigInt(Math.trunc(value));
2454
+ } else if (integer)
2455
+ result = Math.trunc(Number(value));
2456
+ else
2457
+ result = Number(value);
2458
+ if (halfRound)
2459
+ result = halfRound(result);
2460
+ if (target === "float32")
2461
+ result = Math.fround(result);
2462
+ if ((target === "float16" || target === "float32" || target === "float64") && !Number.isFinite(result))
2463
+ throw new ExpressionEvaluationError("overflow", "Floating CAST overflow or non-finite value");
2464
+ validate(result);
2465
+ return result;
2466
+ }
2467
+ };
2468
+ }
2469
+
2470
+ // dist/arrow/like.js
2471
+ function compileUTF8Like(pattern, insensitive, escape) {
2472
+ if (escape !== void 0 && [...escape].length !== 1) {
2473
+ throw new Error("LIKE ESCAPE requires one character");
2474
+ }
2475
+ const tokens = [];
2476
+ let escaped = false;
2477
+ for (const character of pattern) {
2478
+ if (!escaped && character === escape) {
2479
+ escaped = true;
2480
+ continue;
2481
+ }
2482
+ tokens.push(!escaped && character === "%" ? -1 : !escaped && character === "_" ? -2 : fold(character.codePointAt(0), insensitive));
2483
+ escaped = false;
2484
+ }
2485
+ if (escaped)
2486
+ throw new Error("LIKE pattern ends with ESCAPE");
2487
+ return (bytes2, start, end) => {
2488
+ let offset = start;
2489
+ let token = 0;
2490
+ let wildcard = -1;
2491
+ let retry = start;
2492
+ while (offset < end) {
2493
+ if (tokens[token] === -1) {
2494
+ wildcard = token++;
2495
+ retry = offset;
2496
+ continue;
2497
+ }
2498
+ const [point, next] = readCodePoint(bytes2, offset);
2499
+ if (tokens[token] === -2 || tokens[token] === fold(point, insensitive)) {
2500
+ token++;
2501
+ offset = next;
2502
+ } else if (wildcard >= 0) {
2503
+ retry = readCodePoint(bytes2, retry)[1];
2504
+ offset = retry;
2505
+ token = wildcard + 1;
2506
+ } else {
2507
+ return false;
2508
+ }
2509
+ }
2510
+ while (tokens[token] === -1)
2511
+ token++;
2512
+ return token === tokens.length;
2513
+ };
2514
+ }
2515
+ function fold(point, insensitive) {
2516
+ if (!insensitive)
2517
+ return point;
2518
+ if (point < 128)
2519
+ return point >= 65 && point <= 90 ? point + 32 : point;
2520
+ const folded = String.fromCodePoint(point).toLowerCase();
2521
+ return folded.length === 1 && folded.charCodeAt(0) < 128 ? folded.charCodeAt(0) : folded;
2522
+ }
2523
+ function readCodePoint(bytes2, offset) {
2524
+ const first = bytes2[offset++];
2525
+ if (first < 128)
2526
+ return [first, offset];
2527
+ const count = first < 224 ? 1 : first < 240 ? 2 : 3;
2528
+ let point = first & (count === 1 ? 31 : count === 2 ? 15 : 7);
2529
+ for (let index = 0; index < count; index++)
2530
+ point = point << 6 | bytes2[offset++] & 63;
2531
+ return [point, offset];
2532
+ }
2533
+
2534
+ // dist/arrow/signature.js
2535
+ var import_apache_arrow4 = require("apache-arrow");
2536
+ function physicalKey(type) {
2537
+ var _a2;
2538
+ try {
2539
+ return import_apache_arrow4.DataType.isDictionary(type) ? `dictionary:${typeKey(type.indices)}:${typeKey(type.dictionary)}:${type.isOrdered}` : typeKey(type);
2540
+ } catch {
2541
+ const properties = [
2542
+ "bitWidth",
2543
+ "isSigned",
2544
+ "precision",
2545
+ "scale",
2546
+ "unit",
2547
+ "timezone",
2548
+ "byteWidth",
2549
+ "listSize",
2550
+ "keysSorted",
2551
+ "isOrdered",
2552
+ "mode"
2553
+ ].map((key) => type[key]);
2554
+ return JSON.stringify([
2555
+ type.typeId,
2556
+ properties,
2557
+ import_apache_arrow4.DataType.isUnion(type) ? Array.from(type.typeIds) : null,
2558
+ import_apache_arrow4.DataType.isDictionary(type) ? [physicalKey(type.indices), physicalKey(type.dictionary), type.isOrdered] : null,
2559
+ (_a2 = type.children) == null ? void 0 : _a2.map((field) => [
2560
+ field.name,
2561
+ physicalKey(field.type),
2562
+ field.nullable,
2563
+ extensionKey(field)
2564
+ ])
2565
+ ]);
2566
+ }
2567
+ }
2568
+ function extensionKey(field) {
2569
+ return JSON.stringify([
2570
+ field.metadata.get("ARROW:extension:name"),
2571
+ field.metadata.get("ARROW:extension:metadata")
2572
+ ]);
2573
+ }
2574
+
2575
+ // dist/arrow/registry.js
2576
+ function createFunctionLookup(declarations = []) {
2577
+ var _a2;
2578
+ const functions = /* @__PURE__ */ new Map();
2579
+ for (const declaration of declarations) {
2580
+ const name = declaration == null ? void 0 : declaration.name;
2581
+ if (typeof name !== "string" || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name))
2582
+ throw new Error("Invalid Arrow function name");
2583
+ if ([
2584
+ "TRY",
2585
+ "COALESCE",
2586
+ "array",
2587
+ "array_float16",
2588
+ "array_float32",
2589
+ "array_float64",
2590
+ "array_uint8",
2591
+ "PACK_UNORM8",
2592
+ "LIST_EXTRACT",
2593
+ "STRUCT_EXTRACT",
2594
+ "cast",
2595
+ "in",
2596
+ "isNull",
2597
+ "isNotNull",
2598
+ "parseNumber",
2599
+ "parseBigInt",
2600
+ "parseBoolean",
2601
+ "toFloat64",
2602
+ "toInt32",
2603
+ "toInt64"
2604
+ ].includes(name))
2605
+ throw new Error(`Reserved Arrow function: ${name}`);
2606
+ if (!Array.isArray(declaration.prototypes) || !declaration.prototypes.length)
2607
+ throw new Error("Arrow functions require one or more prototypes");
2608
+ const prototypes = [...((_a2 = functions.get(name)) == null ? void 0 : _a2.prototypes) ?? []];
2609
+ for (const prototype of declaration.prototypes) {
2610
+ if (!prototype || typeof prototype !== "object" || !Array.isArray(prototype.arguments) || !prototype.result || typeof prototype.evaluate !== "function")
2611
+ throw new Error("Arrow prototypes require argument fields, a result field and evaluate");
2612
+ if (prototype.nullHandling !== void 0 && !["propagate", "call"].includes(prototype.nullHandling))
2613
+ throw new Error("Unsupported null handling");
2614
+ if (prototype.evaluateScalar !== void 0 && typeof prototype.evaluateScalar !== "function")
2615
+ throw new Error("Arrow function evaluateScalar must be a function");
2616
+ const key = JSON.stringify(prototype.arguments.map((field) => [
2617
+ physicalKey(field.type),
2618
+ [...field.metadata].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
2619
+ ]));
2620
+ if (prototypes.some((existing) => JSON.stringify(existing.arguments.map((field) => [
2621
+ physicalKey(field.type),
2622
+ [...field.metadata].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
2623
+ ])) === key))
2624
+ throw new Error(`Duplicate Arrow function signature: ${name}`);
2625
+ prototypes.push(Object.freeze({ ...prototype, arguments: Object.freeze([...prototype.arguments]) }));
2626
+ }
2627
+ functions.set(name, Object.freeze({ name, prototypes: Object.freeze(prototypes) }));
2628
+ }
2629
+ return functions;
2630
+ }
2631
+
2632
+ // dist/arrow/list-values.js
2633
+ var import_apache_arrow5 = require("apache-arrow");
2634
+ function isTupleType(type) {
2635
+ if (!import_apache_arrow5.DataType.isFixedSizeList(type))
2636
+ return false;
2637
+ const child = type.children[0];
2638
+ if (!Number.isSafeInteger(type.listSize) || type.listSize <= 0 || !child || child.nullable)
2639
+ return false;
2640
+ if (!import_apache_arrow5.DataType.isInt(child.type) && !import_apache_arrow5.DataType.isFloat(child.type))
2641
+ return false;
2642
+ typeKey(child.type);
2643
+ return true;
2644
+ }
2645
+ function nullTupleVector(type, length) {
2646
+ const childType = type.children[0].type;
2647
+ const child = (0, import_apache_arrow5.makeData)({
2648
+ type: childType,
2649
+ length: length * type.listSize,
2650
+ data: new childType.ArrayType(length * type.listSize)
2651
+ });
2652
+ return (0, import_apache_arrow5.makeVector)((0, import_apache_arrow5.makeData)({
2653
+ type,
2654
+ length,
2655
+ child,
2656
+ nullCount: length,
2657
+ nullBitmap: new Uint8Array(Math.ceil(length / 8))
2658
+ }));
2659
+ }
2660
+ function maskTupleVector(vector, active) {
2661
+ if (!active.some((value) => !value))
2662
+ return vector;
2663
+ let start = 0;
2664
+ const chunks = vector.data.map((data) => {
2665
+ const bitmap = new Uint8Array(Math.ceil((data.offset + data.length) / 8));
2666
+ let nullCount = 0;
2667
+ for (let row = 0; row < data.length; row++) {
2668
+ if (active[start + row] && data.getValid(row)) {
2669
+ const bit = data.offset + row;
2670
+ bitmap[bit >> 3] |= 1 << (bit & 7);
2671
+ } else
2672
+ nullCount++;
2673
+ }
2674
+ start += data.length;
2675
+ const buffers = data.buffers;
2676
+ buffers[2] = bitmap;
2677
+ return data.clone(data.type, data.offset, data.length, nullCount, buffers);
2678
+ });
2679
+ return new import_apache_arrow5.Vector(chunks);
2680
+ }
2681
+ function validateTupleVector(vector, field, active) {
2682
+ const type = field.type;
2683
+ let start = 0;
2684
+ for (const data of vector.data) {
2685
+ const child = data.children[0];
2686
+ if (!child || child.length < data.length * type.listSize)
2687
+ throw new Error("Invalid fixed-size list child length");
2688
+ for (let row = 0; row < data.length; row++) {
2689
+ if (!active[start + row])
2690
+ continue;
2691
+ if (!data.getValid(row)) {
2692
+ if (!field.nullable)
2693
+ throw new Error(`Function ${field.name} returned null for a non-nullable result`);
2694
+ continue;
2695
+ }
2696
+ for (let component = 0; component < type.listSize; component++) {
2697
+ if (!child.getValid(row * type.listSize + component))
2698
+ throw new Error("Fixed-size list result contains a null non-nullable component");
2699
+ }
2700
+ }
2701
+ start += data.length;
2702
+ }
2703
+ }
2704
+ function selectTupleVectors(type, yes, no, selected, active) {
2705
+ const result = nullTupleVector(type, active.length);
2706
+ const data = result.data[0];
2707
+ const child = data.children[0];
2708
+ const values = import_apache_arrow5.DataType.isFloat(child.type) && child.type.precision === import_apache_arrow5.Precision.HALF ? float16Values(child.values) : child.values;
2709
+ const a = new ColumnReader(yes.getChildAt(0));
2710
+ const b = new ColumnReader(no.getChildAt(0));
2711
+ const aValid = new ColumnReader(yes);
2712
+ const bValid = new ColumnReader(no);
2713
+ for (let row = 0; row < active.length; row++) {
2714
+ if (!active[row])
2715
+ continue;
2716
+ const reader = selected[row] ? a : b;
2717
+ if (!(selected[row] ? aValid : bValid).isValid(row))
2718
+ continue;
2719
+ data.setValid(row, true);
2720
+ for (let component = 0; component < type.listSize; component++) {
2721
+ const index = row * type.listSize + component;
2722
+ values[index] = reader.get(index);
2723
+ }
2724
+ }
2725
+ return result;
2726
+ }
2727
+ function compileArrayLiteral(ast, type) {
2728
+ if (!import_apache_arrow5.DataType.isList(type) && !import_apache_arrow5.DataType.isFixedSizeList(type))
2729
+ throw new Error("Array literals require a declared List or FixedSizeList argument");
2730
+ const listType = type;
2731
+ const child = listType.children[0];
2732
+ if (import_apache_arrow5.DataType.isDictionary(child.type))
2733
+ throw new Error("Array literal elements require primitive types");
2734
+ typeKey(child.type);
2735
+ if (ast.elements.length > 4096)
2736
+ throw new Error("Array literal exceeds 4096 elements");
2737
+ if (import_apache_arrow5.DataType.isFixedSizeList(type) && ast.elements.length !== type.listSize)
2738
+ throw new Error("Array literal length must match its FixedSizeList type");
2739
+ if (import_apache_arrow5.DataType.isFixedSizeList(type) && !isTupleType(type))
2740
+ throw new Error("Fixed-size array literals require non-nullable numeric elements");
2741
+ const round = import_apache_arrow5.DataType.isFloat(child.type) ? child.type.precision === import_apache_arrow5.Precision.HALF ? roundFloat16() : child.type.precision === import_apache_arrow5.Precision.SINGLE ? Math.fround : void 0 : void 0;
2742
+ const values = Array.from(ast.elements, (element) => {
2743
+ var _a2;
2744
+ let value;
2745
+ if ((element == null ? void 0 : element.type) === "Literal")
2746
+ value = element.value;
2747
+ else if ((element == null ? void 0 : element.type) === "UnaryExpression" && ["+", "-"].includes(element.operator) && ((_a2 = element.argument) == null ? void 0 : _a2.type) === "Literal" && typeof element.argument.value === "number")
2748
+ value = element.operator === "-" ? -element.argument.value : element.argument.value;
2749
+ else
2750
+ throw new Error("Array elements must be scalar literals");
2751
+ if (value === null && !child.nullable)
2752
+ throw new Error("Array literal contains a null non-nullable element");
2753
+ validateValue(value, child.type);
2754
+ if (round && typeof value === "number") {
2755
+ const rounded = round(value);
2756
+ if (Number.isFinite(value) && !Number.isFinite(rounded))
2757
+ throw new Error(`Numeric literal overflow for ${child.type}`);
2758
+ return rounded;
2759
+ }
2760
+ return value;
2761
+ });
2762
+ const literal = (0, import_apache_arrow5.vectorFromArray)([values], listType);
2763
+ const dictionaryType = new import_apache_arrow5.Dictionary(listType, new import_apache_arrow5.Uint8());
2764
+ let cached;
2765
+ return (length) => {
2766
+ if (!import_apache_arrow5.DataType.isFixedSizeList(listType) && (cached == null ? void 0 : cached.length) === length)
2767
+ return cached;
2768
+ if (import_apache_arrow5.DataType.isFixedSizeList(listType)) {
2769
+ const result = nullTupleVector(listType, length);
2770
+ const data = result.data[0];
2771
+ const childData = data.children[0];
2772
+ const components = import_apache_arrow5.DataType.isFloat(childData.type) && childData.type.precision === import_apache_arrow5.Precision.HALF ? float16Values(childData.values) : childData.values;
2773
+ for (let row = 0; row < length; row++) {
2774
+ data.setValid(row, true);
2775
+ for (let component = 0; component < listType.listSize; component++)
2776
+ components[row * listType.listSize + component] = values[component];
2777
+ }
2778
+ cached = result;
2779
+ } else {
2780
+ cached = (0, import_apache_arrow5.makeVector)((0, import_apache_arrow5.makeData)({ type: dictionaryType, length, data: new Uint8Array(length), dictionary: literal }));
2781
+ }
2782
+ return cached;
2783
+ };
2784
+ }
2785
+
2786
+ // dist/arrow/compiler.js
2787
+ var encoder = new TextEncoder();
2788
+ var bool = new import_apache_arrow6.Bool();
2789
+ function compileArrowExpression(expression, options) {
2790
+ const fields = [...options.inputSchema.fields];
2791
+ if (new Set(fields.map((field) => field.name)).size !== fields.length)
2792
+ throw new Error("Expression input field names must be unique");
2793
+ const ast = parse(expression);
2794
+ validateExpressionAST(ast);
2795
+ const root = bind(ast, {
2796
+ ...options,
2797
+ functionLookup: createFunctionLookup(options.functions)
2798
+ });
2799
+ const keys = fields.map((field) => ({
2800
+ name: field.name,
2801
+ type: physicalKey(field.type),
2802
+ nullable: field.nullable,
2803
+ extension: extensionKey(field)
2804
+ }));
2805
+ const validateSchema = (schema) => {
2806
+ if (schema.fields.length !== keys.length || schema.fields.some((field, index) => {
2807
+ const expected = keys[index];
2808
+ return field.name !== expected.name || physicalKey(field.type) !== expected.type || field.nullable !== expected.nullable || extensionKey(field) !== expected.extension;
2809
+ }))
2810
+ throw new Error("Arrow expression input schema mismatch");
2811
+ };
2812
+ const validateMask = (mask, length) => {
2813
+ if (mask && (mask.length !== length || mask.some((value) => value !== 0 && value !== 1)))
2814
+ throw new Error("activeRows must contain one 0 or 1 per input row");
2815
+ };
2816
+ const evaluate = (batch, evaluation = {}) => {
2817
+ var _a2, _b;
2818
+ (_a2 = evaluation.signal) == null ? void 0 : _a2.throwIfAborted();
2819
+ validateSchema(batch.schema);
2820
+ validateMask(evaluation.activeRows, batch.numRows);
2821
+ const active = evaluation.activeRows ? evaluation.activeRows.slice() : new Uint8Array(batch.numRows).fill(1);
2822
+ const prepared = root.prepare(batch, active, {});
2823
+ const result = isTupleType(root.field.type) ? maskTupleVector(prepared.vector, active) : isNestedType(root.field.type) ? nestedVector(prepared.vector, root.field.type, active) : prepared.vector && !import_apache_arrow6.DataType.isDictionary(prepared.vector.type) && !active.some((value) => !value) ? prepared.vector : output(root.field, active, prepared.get);
2824
+ (_b = evaluation.signal) == null ? void 0 : _b.throwIfAborted();
2825
+ return result;
2826
+ };
2827
+ return Object.freeze({
2828
+ outputField: root.field,
2829
+ evaluate,
2830
+ evaluateTable(arrowTable, evaluation = {}) {
2831
+ var _a2;
2832
+ (_a2 = evaluation.signal) == null ? void 0 : _a2.throwIfAborted();
2833
+ validateSchema(arrowTable.schema);
2834
+ validateMask(evaluation.activeRows, arrowTable.numRows);
2835
+ let offset = 0;
2836
+ const chunks = arrowTable.batches.flatMap((batch) => {
2837
+ var _a3;
2838
+ const activeRows = (_a3 = evaluation.activeRows) == null ? void 0 : _a3.subarray(offset, offset + batch.numRows);
2839
+ offset += batch.numRows;
2840
+ return evaluate(batch, { ...evaluation, activeRows }).data;
2841
+ });
2842
+ return chunks.length ? new import_apache_arrow6.Vector(chunks) : isTupleType(root.field.type) ? nullTupleVector(root.field.type, 0) : isNestedType(root.field.type) ? (0, import_apache_arrow6.vectorFromArray)([], root.field.type) : output(root.field, new Uint8Array(0), () => null);
2843
+ }
2844
+ });
2845
+ }
2846
+ function compileArrowArray(columns, options) {
2847
+ if (!Array.isArray(columns) || !columns.length || columns.length > 4096 || Array.from(columns).some((name) => typeof name !== "string" || !name.length))
2848
+ throw new Error("ARRAY requires 1 to 4096 source column names");
2849
+ if (options.type !== void 0 && !["float16", "float32", "float64", "uint8"].includes(options.type))
2850
+ throw new Error("Unsupported ARRAY component type");
2851
+ return compileArrowExpression({
2852
+ type: "CallExpression",
2853
+ callee: { type: "Identifier", name: options.type ? `array_${options.type}` : "array" },
2854
+ arguments: columns.map((name) => ({ type: "Identifier", name }))
2855
+ }, options);
2856
+ }
2857
+ function output(field, active, evaluate) {
2858
+ const type = valueType(field.type);
2859
+ const validate = createValueValidator(type);
2860
+ if (import_apache_arrow6.DataType.isUtf8(type) || import_apache_arrow6.DataType.isBinary(type) || import_apache_arrow6.DataType.isFixedSizeBinary(type)) {
2861
+ const values = new Array(active.length).fill(null);
2862
+ for (let row = 0; row < active.length; row++)
2863
+ if (active[row]) {
2864
+ const value = evaluate(row);
2865
+ if (value === null && !field.nullable)
2866
+ throw new Error(`Non-nullable expression ${field.name} returned null`);
2867
+ validate(value);
2868
+ values[row] = value;
2869
+ }
2870
+ return (0, import_apache_arrow6.vectorFromArray)(values, field.type);
2871
+ }
2872
+ if (import_apache_arrow6.DataType.isNull(type)) {
2873
+ for (let row = 0; row < active.length; row++)
2874
+ if (active[row])
2875
+ validate(evaluate(row));
2876
+ return (0, import_apache_arrow6.makeVector)((0, import_apache_arrow6.makeData)({ type, length: active.length }));
2877
+ }
2878
+ const isBoolean = import_apache_arrow6.DataType.isBool(type);
2879
+ const data = isBoolean ? new Uint8Array(Math.ceil(active.length / 8)) : new type.ArrayType(active.length);
2880
+ const numericData = import_apache_arrow6.DataType.isFloat(type) && type.precision === import_apache_arrow6.Precision.HALF ? float16Values(data) : data;
2881
+ const validity = new Uint8Array(Math.ceil(active.length / 8));
2882
+ let nullCount = 0;
2883
+ for (let row = 0; row < active.length; row++) {
2884
+ if (!active[row]) {
2885
+ nullCount++;
2886
+ continue;
2887
+ }
2888
+ const value = evaluate(row);
2889
+ if (value === null) {
2890
+ if (!field.nullable)
2891
+ throw new Error(`Non-nullable expression ${field.name} returned null`);
2892
+ nullCount++;
2893
+ continue;
2894
+ }
2895
+ validate(value);
2896
+ validity[row >> 3] |= 1 << (row & 7);
2897
+ if (isBoolean) {
2898
+ if (value)
2899
+ data[row >> 3] |= 1 << (row & 7);
2900
+ } else
2901
+ numericData[row] = value;
2902
+ }
2903
+ return (0, import_apache_arrow6.makeVector)((0, import_apache_arrow6.makeData)({
2904
+ type,
2905
+ data,
2906
+ length: active.length,
2907
+ nullBitmap: validity,
2908
+ nullCount
2909
+ }));
2910
+ }
2911
+ function sourceReader(vector) {
2912
+ const data = vector.data[0];
2913
+ if (vector.data.length === 1 && (import_apache_arrow6.DataType.isInt(data.type) || import_apache_arrow6.DataType.isFloat(data.type) && data.type.precision !== import_apache_arrow6.Precision.HALF)) {
2914
+ const values = data.values, bitmap = data.nullBitmap, offset = data.offset;
2915
+ const valid = data.nullCount ? (row) => Boolean(bitmap[offset + row >> 3] & 1 << (offset + row & 7)) : () => true;
2916
+ return {
2917
+ vector,
2918
+ get: (row) => valid(row) ? values[row] : null,
2919
+ isNull: (row) => !valid(row)
2920
+ };
2921
+ }
2922
+ const reader = new ColumnReader(vector);
2923
+ return {
2924
+ vector,
2925
+ get: (row) => reader.get(row),
2926
+ isNull: (row) => !reader.isValid(row),
2927
+ bytes: typeKey(vector.type) === "utf8" ? (row) => reader.isValid(row) ? reader.utf8(row) : null : void 0
2928
+ };
2929
+ }
2930
+ function vectorReader(vector) {
2931
+ try {
2932
+ typeKey(vector.type);
2933
+ return sourceReader(vector);
2934
+ } catch {
2935
+ }
2936
+ const reader = new ColumnReader(vector);
2937
+ return {
2938
+ vector,
2939
+ isNull: (row) => !reader.isValid(row),
2940
+ get: () => {
2941
+ throw new Error("Nested values require a vector kernel");
2942
+ }
2943
+ };
2944
+ }
2945
+ function bytes(value, row) {
2946
+ if (value.bytes)
2947
+ return value.bytes(row);
2948
+ const text = value.get(row);
2949
+ if (text === null)
2950
+ return null;
2951
+ const encoded = encoder.encode(text);
2952
+ return [encoded, 0, encoded.length];
2953
+ }
2954
+ function bind(ast, options, expected, vectorInput = false) {
2955
+ const node = bindNode(ast, options, expected, vectorInput);
2956
+ return {
2957
+ ...node,
2958
+ prepare(batch, active, context) {
2959
+ const mask = context.failed ? active.map((value, row) => value && !context.failed[row] ? 1 : 0) : active;
2960
+ const prepared = node.prepare(batch, mask, context);
2961
+ if (!context.failed)
2962
+ return prepared;
2963
+ const guard = (row, read) => {
2964
+ if (!mask[row] || context.failed[row])
2965
+ return null;
2966
+ try {
2967
+ const value = read();
2968
+ return context.failed[row] ? null : value;
2969
+ } catch (error) {
2970
+ if (!isExpressionEvaluationError(error))
2971
+ throw error;
2972
+ context.failed[row] = 1;
2973
+ return null;
2974
+ }
2975
+ };
2976
+ return {
2977
+ ...prepared,
2978
+ get: (row) => guard(row, () => prepared.get(row)),
2979
+ bytes: prepared.bytes ? (row) => guard(row, () => prepared.bytes(row)) : void 0,
2980
+ isNull: (row) => guard(row, () => prepared.isNull ? prepared.isNull(row) : prepared.get(row) === null) ?? true
2981
+ };
2982
+ }
2983
+ };
2984
+ }
2985
+ function prepareInput(node, batch, active, context, force) {
2986
+ const prepared = node.prepare(batch, active, context);
2987
+ if (!context.failed || !force || prepared.vector)
2988
+ return prepared;
2989
+ const mask = active.map((value, row) => value && !context.failed[row] ? 1 : 0);
2990
+ const field = new import_apache_arrow6.Field(node.field.name, node.field.type, true, node.field.metadata);
2991
+ return sourceReader(output(field, mask, prepared.get));
2992
+ }
2993
+ function bindNode(ast, options, expected, vectorInput = false) {
2994
+ if (isSignedLiteral(ast)) {
2995
+ const value = ast.operator === "-" ? -ast.argument.value : ast.argument.value;
2996
+ return bind({ type: "Literal", value }, options, expected, vectorInput);
2997
+ }
2998
+ if (ast.type === "ArrayExpression") {
2999
+ if (!expected)
3000
+ throw new Error("Array literals require a declared list type");
3001
+ const materialize = compileArrayLiteral(ast, expected);
3002
+ return {
3003
+ field: new import_apache_arrow6.Field("literal", expected, false),
3004
+ hasKernel: false,
3005
+ prepare: (_batch, active) => vectorReader(materialize(active.length))
3006
+ };
3007
+ }
3008
+ if (ast.type === "Identifier") {
3009
+ const index = options.inputSchema.fields.findIndex((field) => field.name === ast.name);
3010
+ if (index < 0)
3011
+ throw new Error(`Unknown Arrow expression field: ${ast.name}`);
3012
+ const source = options.inputSchema.fields[index];
3013
+ const tuple = isTupleType(source.type);
3014
+ if (!vectorInput && !tuple)
3015
+ typeKey(source.type);
3016
+ return {
3017
+ field: new import_apache_arrow6.Field(source.name, vectorInput ? source.type : valueType(source.type), source.nullable, source.metadata),
3018
+ hasKernel: false,
3019
+ prepare: (batch) => {
3020
+ const vector = batch.getChildAt(index);
3021
+ return vectorInput || tuple ? vectorReader(vector) : sourceReader(vector);
3022
+ }
3023
+ };
3024
+ }
3025
+ if (ast.type === "Literal") {
3026
+ if (vectorInput && expected && import_apache_arrow6.DataType.isDictionary(expected))
3027
+ throw new Error("Dictionary function arguments require a dictionary-encoded source column");
3028
+ let value = ast.value;
3029
+ if (expected && import_apache_arrow6.DataType.isInt(expected) && expected.bitWidth === 64 && typeof value === "number" && Number.isSafeInteger(value))
3030
+ value = BigInt(value);
3031
+ const type = expected ?? (value === null ? new import_apache_arrow6.Null() : typeof value === "boolean" ? bool : typeof value === "number" ? new import_apache_arrow6.Float64() : typeof value === "bigint" ? new import_apache_arrow6.Int64() : new import_apache_arrow6.Utf8());
3032
+ if (value === null && isTupleType(type))
3033
+ return {
3034
+ field: new import_apache_arrow6.Field("literal", type, true),
3035
+ hasKernel: false,
3036
+ prepare: (_batch, active) => vectorReader(nullTupleVector(type, active.length))
3037
+ };
3038
+ if (value === null && import_apache_arrow6.DataType.isList(type)) {
3039
+ const dictionary = (0, import_apache_arrow6.vectorFromArray)([null], type);
3040
+ return {
3041
+ field: new import_apache_arrow6.Field("literal", type, true),
3042
+ hasKernel: false,
3043
+ prepare: (_batch, active) => vectorReader((0, import_apache_arrow6.makeVector)((0, import_apache_arrow6.makeData)({
3044
+ type: new import_apache_arrow6.Dictionary(type, new import_apache_arrow6.Int32()),
3045
+ length: active.length,
3046
+ data: new Int32Array(active.length),
3047
+ dictionary
3048
+ })))
3049
+ };
3050
+ }
3051
+ if (value === null && isNestedType(type))
3052
+ return {
3053
+ field: new import_apache_arrow6.Field("literal", type, true),
3054
+ hasKernel: false,
3055
+ prepare: (_batch, active) => vectorReader((0, import_apache_arrow6.vectorFromArray)(Array(active.length).fill(null), type))
3056
+ };
3057
+ validateValue(value, type);
3058
+ const rounded = roundToType(type)(value);
3059
+ if (typeof value === "number" && Number.isFinite(value) && !Number.isFinite(rounded))
3060
+ throw new Error(`Numeric literal overflow for ${type}`);
3061
+ const encoded = typeof value === "string" ? encoder.encode(value) : void 0;
3062
+ const range = encoded ? [encoded, 0, encoded.length] : void 0;
3063
+ return {
3064
+ field: new import_apache_arrow6.Field("literal", type, value === null),
3065
+ hasKernel: false,
3066
+ prepare: () => ({
3067
+ get: () => rounded,
3068
+ isNull: () => value === null,
3069
+ bytes: range ? () => range : void 0
3070
+ })
3071
+ };
3072
+ }
3073
+ if (ast.type === "CallExpression")
3074
+ return bindCall(ast, options, expected);
3075
+ if (ast.type === "ConditionalExpression") {
3076
+ const condition = bind(ast.test, options, bool);
3077
+ requireType(condition, "bool");
3078
+ let yes, no;
3079
+ if (isContextualLiteral(ast.consequent) && !isContextualLiteral(ast.alternate)) {
3080
+ no = bind(ast.alternate, options, expected);
3081
+ yes = bind(ast.consequent, options, no.field.type);
3082
+ } else {
3083
+ yes = bind(ast.consequent, options, expected);
3084
+ no = bind(ast.alternate, options, isContextualLiteral(ast.alternate) && !import_apache_arrow6.DataType.isNull(yes.field.type) ? yes.field.type : expected);
3085
+ if (isContextualLiteral(ast.consequent) && !import_apache_arrow6.DataType.isNull(no.field.type))
3086
+ yes = bind(ast.consequent, options, no.field.type);
3087
+ }
3088
+ const tuple = isTupleType(yes.field.type);
3089
+ const list = import_apache_arrow6.DataType.isList(yes.field.type);
3090
+ const nested = isNestedType(yes.field.type);
3091
+ if (nested) {
3092
+ if (physicalKey(yes.field.type) !== physicalKey(no.field.type))
3093
+ throw new Error("Arrow expression operand types must match");
3094
+ if (!isContextualLiteral(ast.consequent) && !isContextualLiteral(ast.alternate) && extensionKey(yes.field) !== extensionKey(no.field))
3095
+ throw new Error("Arrow expression branch extension metadata must match");
3096
+ } else
3097
+ sameType(yes, no);
3098
+ const metadata = isContextualLiteral(ast.consequent) ? no.field.metadata : yes.field.metadata;
3099
+ const field = new import_apache_arrow6.Field("conditional", yes.field.type, yes.field.nullable || no.field.nullable, metadata);
3100
+ return {
3101
+ field,
3102
+ hasKernel: nested || condition.hasKernel || yes.hasKernel || no.hasKernel,
3103
+ prepare(batch, active, context) {
3104
+ const test = condition.prepare(batch, active, context);
3105
+ const selected = nested || yes.hasKernel || no.hasKernel ? active.map((value, row) => value && test.get(row) === true ? 1 : 0) : void 0;
3106
+ const a = yes.prepare(batch, selected ?? active, context);
3107
+ const b = no.prepare(batch, selected ? active.map((value, row) => value && !selected[row] ? 1 : 0) : active, context);
3108
+ if (list && import_apache_arrow6.DataType.isDictionary(a.vector.type) && import_apache_arrow6.DataType.isDictionary(b.vector.type))
3109
+ return vectorReader(selectListVectors(field.type, a.vector, b.vector, selected, active));
3110
+ if (tuple) {
3111
+ const validActive = context.failed ? active.map((value, row) => value && !context.failed[row] ? 1 : 0) : active;
3112
+ const yesMask = validActive.map((value, row) => value && selected[row] ? 1 : 0);
3113
+ const noMask = validActive.map((value, row) => value && !selected[row] ? 1 : 0);
3114
+ validateTupleVector(a.vector, yes.field, yesMask);
3115
+ validateTupleVector(b.vector, no.field, noMask);
3116
+ return vectorReader(selectTupleVectors(field.type, a.vector, b.vector, yesMask, validActive));
3117
+ }
3118
+ if (nested) {
3119
+ const values = Array.from(active, (valid, row) => {
3120
+ var _a2;
3121
+ return valid && !((_a2 = context.failed) == null ? void 0 : _a2[row]) ? nestedValue((selected[row] ? a : b).vector.get(row), field.type) : null;
3122
+ });
3123
+ return vectorReader((0, import_apache_arrow6.vectorFromArray)(values, field.type));
3124
+ }
3125
+ const choose = (row) => (selected ? selected[row] : test.get(row) === true) ? a : b;
3126
+ return {
3127
+ get: (row) => choose(row).get(row),
3128
+ isNull: (row) => {
3129
+ const branch = choose(row);
3130
+ return branch.isNull ? branch.isNull(row) : branch.get(row) === null;
3131
+ },
3132
+ bytes: typeKey(field.type) === "utf8" ? (row) => bytes(choose(row), row) : void 0
3133
+ };
3134
+ }
3135
+ };
3136
+ }
3137
+ if (ast.type === "UnaryExpression") {
3138
+ const argument = bind(ast.argument, options, ast.operator === "!" ? bool : void 0);
3139
+ if (ast.operator === "!")
3140
+ requireType(argument, "bool");
3141
+ else if (ast.operator === "+" || ast.operator === "-")
3142
+ requireNumeric(argument);
3143
+ else
3144
+ throw new Error(`Unsupported unary operator: ${ast.operator}`);
3145
+ const validate = createValueValidator(argument.field.type);
3146
+ const round = roundToType(argument.field.type);
3147
+ return {
3148
+ field: new import_apache_arrow6.Field("unary", argument.field.type, argument.field.nullable),
3149
+ hasKernel: argument.hasKernel,
3150
+ prepare(batch, active, context) {
3151
+ const child = argument.prepare(batch, active, context);
3152
+ return {
3153
+ get: (row) => {
3154
+ const value = child.get(row);
3155
+ if (value === null)
3156
+ return null;
3157
+ const result = ast.operator === "!" ? !value : ast.operator === "+" ? value : -value;
3158
+ validate(result);
3159
+ return round(result);
3160
+ }
3161
+ };
3162
+ }
3163
+ };
3164
+ }
3165
+ if (ast.type === "BinaryExpression" || ast.type === "LogicalExpression")
3166
+ return bindBinary(ast, options);
3167
+ throw new Error(`Unsupported Arrow expression syntax: ${ast.type}`);
3168
+ }
3169
+ function sameType(a, b) {
3170
+ if (typeKey(a.field.type) !== typeKey(b.field.type))
3171
+ throw new Error("Arrow expression operand types must match");
3172
+ }
3173
+ function requireType(node, key) {
3174
+ if (typeKey(node.field.type) !== key)
3175
+ throw new Error(`Arrow expression requires ${key}`);
3176
+ }
3177
+ function requireNumeric(node) {
3178
+ if (!import_apache_arrow6.DataType.isInt(node.field.type) && !import_apache_arrow6.DataType.isFloat(node.field.type))
3179
+ throw new Error("Arrow expression requires numeric operands");
3180
+ }
3181
+ function bindBinary(ast, options) {
3182
+ const op = ast.operator, logical = op === "&&" || op === "||";
3183
+ let left = bind(ast.left, options, logical ? bool : void 0), right = bind(ast.right, options, logical ? bool : void 0);
3184
+ if (!logical) {
3185
+ if (isContextualLiteral(ast.left) && !import_apache_arrow6.DataType.isNull(right.field.type))
3186
+ left = bind(ast.left, options, right.field.type);
3187
+ if (isContextualLiteral(ast.right))
3188
+ right = bind(ast.right, options, left.field.type);
3189
+ }
3190
+ sameType(left, right);
3191
+ const comparison = ["==", "===", "!=", "!==", "<", "<=", ">", ">="].includes(op);
3192
+ if (logical)
3193
+ requireType(left, "bool");
3194
+ else if (!comparison) {
3195
+ if (!["+", "-", "*", "/", "%"].includes(op))
3196
+ throw new Error(`Unsupported binary operator: ${op}`);
3197
+ requireNumeric(left);
3198
+ }
3199
+ const type = left.field.type, utf8 = typeKey(type) === "utf8", binary = import_apache_arrow6.DataType.isBinary(type) || import_apache_arrow6.DataType.isFixedSizeBinary(type), integer = import_apache_arrow6.DataType.isInt(type);
3200
+ const validate = createValueValidator(type);
3201
+ const round = roundToType(type);
3202
+ const field = new import_apache_arrow6.Field("expression", logical || comparison ? bool : type, left.field.nullable || right.field.nullable);
3203
+ return {
3204
+ field,
3205
+ hasKernel: left.hasKernel || right.hasKernel,
3206
+ prepare(batch, active, context) {
3207
+ const a = prepareInput(left, batch, active, context, left.hasKernel || right.hasKernel);
3208
+ let truth;
3209
+ let mask = active;
3210
+ if (logical && right.hasKernel) {
3211
+ truth = new Uint8Array(active.length);
3212
+ mask = active.map((value, row) => {
3213
+ if (!value)
3214
+ return 0;
3215
+ const x = a.get(row);
3216
+ truth[row] = x === null ? 2 : x ? 1 : 0;
3217
+ return (op === "&&" ? x !== false : x !== true) ? 1 : 0;
3218
+ });
3219
+ }
3220
+ const b = right.prepare(batch, mask, context);
3221
+ return {
3222
+ get: (row) => {
3223
+ if (logical) {
3224
+ const x2 = truth ? truth[row] === 2 ? null : truth[row] === 1 : a.get(row);
3225
+ if (op === "&&" && x2 === false)
3226
+ return false;
3227
+ if (op === "||" && x2 === true)
3228
+ return true;
3229
+ const y2 = b.get(row);
3230
+ return op === "&&" ? y2 === false ? false : x2 === null || y2 === null ? null : true : y2 === true ? true : x2 === null || y2 === null ? null : false;
3231
+ }
3232
+ if (utf8) {
3233
+ const x2 = bytes(a, row), y2 = bytes(b, row);
3234
+ if (!x2 || !y2)
3235
+ return null;
3236
+ return compare(op, (0, import_utf82.compareUTF8)(x2[0], x2[1], x2[2], y2[0], y2[1], y2[2]), 0);
3237
+ }
3238
+ const x = a.get(row), y = b.get(row);
3239
+ if (x === null || y === null)
3240
+ return null;
3241
+ if (binary)
3242
+ return compare(op, (0, import_utf82.compareUTF8)(x, 0, x.length, y, 0, y.length), 0);
3243
+ if (comparison)
3244
+ return compare(op, x, y);
3245
+ if ((op === "/" || op === "%") && (y === 0 || y === 0n))
3246
+ throw new ExpressionEvaluationError("divisionByZero", "Division by zero");
3247
+ const result = op === "+" ? x + y : op === "-" ? x - y : op === "*" ? x * y : op === "/" ? integer && typeof x === "number" ? Math.trunc(x / y) : x / y : x % y;
3248
+ validate(result);
3249
+ const rounded = round(result);
3250
+ if (!integer && Number.isFinite(x) && Number.isFinite(y) && !Number.isFinite(rounded))
3251
+ throw new ExpressionEvaluationError("overflow", "Floating expression overflow");
3252
+ return rounded;
3253
+ }
3254
+ };
3255
+ }
3256
+ };
3257
+ }
3258
+ function compare(op, a, b) {
3259
+ switch (op) {
3260
+ case "==":
3261
+ case "===":
3262
+ return a === b;
3263
+ case "!=":
3264
+ case "!==":
3265
+ return a !== b;
3266
+ case "<":
3267
+ return a < b;
3268
+ case "<=":
3269
+ return a <= b;
3270
+ case ">":
3271
+ return a > b;
3272
+ case ">=":
3273
+ return a >= b;
3274
+ default:
3275
+ throw new Error("Invalid comparison");
3276
+ }
3277
+ }
3278
+ function selectListVectors(type, left, right, selected, active) {
3279
+ if (!import_apache_arrow6.DataType.isDictionary(left.type) || !import_apache_arrow6.DataType.isDictionary(right.type))
3280
+ throw new Error("Computed List arguments require array literal branches");
3281
+ const a = left.data[0], b = right.data[0];
3282
+ const leftDictionary = a.dictionary, rightDictionary = b.dictionary;
3283
+ const indices = new Int32Array(active.length);
3284
+ const valid = new Uint8Array(active.length);
3285
+ for (let row = 0; row < active.length; row++) {
3286
+ if (!active[row])
3287
+ continue;
3288
+ if (selected[row]) {
3289
+ indices[row] = Number(a.values[row]);
3290
+ valid[row] = a.getValid(row) ? 1 : 0;
3291
+ } else {
3292
+ indices[row] = leftDictionary.length + Number(b.values[row]);
3293
+ valid[row] = b.getValid(row) ? 1 : 0;
3294
+ }
3295
+ }
3296
+ return maskTupleVector((0, import_apache_arrow6.makeVector)((0, import_apache_arrow6.makeData)({
3297
+ type: new import_apache_arrow6.Dictionary(type, new import_apache_arrow6.Int32()),
3298
+ length: active.length,
3299
+ data: indices,
3300
+ dictionary: leftDictionary.concat(rightDictionary)
3301
+ })), valid);
3302
+ }
3303
+ function bindRecovery(name, expressions, options, expected) {
3304
+ if (expected && import_apache_arrow6.DataType.isDictionary(expected))
3305
+ throw new Error("Dictionary function arguments require a dictionary-encoded source column");
3306
+ if (name === "TRY" ? expressions.length < 1 || expressions.length > 2 : !expressions.length)
3307
+ throw new Error(`${name} has an invalid argument count`);
3308
+ const indices = expressions.map((_, index) => index);
3309
+ const ordered = [
3310
+ ...indices.filter((index) => !isContextualLiteral(expressions[index])),
3311
+ ...indices.filter((index) => isContextualLiteral(expressions[index]))
3312
+ ];
3313
+ let anchor = 0;
3314
+ let candidate;
3315
+ for (const index of ordered) {
3316
+ const expression = expressions[index];
3317
+ if (!expected && isContextualLiteral(expression) && containsContextualArray(expression))
3318
+ continue;
3319
+ const node = bind(expression, options, expected);
3320
+ if (!candidate || !import_apache_arrow6.DataType.isNull(node.field.type)) {
3321
+ anchor = index;
3322
+ candidate = node;
3323
+ }
3324
+ if (!import_apache_arrow6.DataType.isNull(node.field.type))
3325
+ break;
3326
+ }
3327
+ const first = candidate ?? bind(expressions[anchor], options, expected);
3328
+ const nodes = expressions.map((expression, index) => index === anchor ? first : bind(expression, options, first.field.type));
3329
+ for (const [index, node] of nodes.entries()) {
3330
+ if (physicalKey(node.field.type) !== physicalKey(first.field.type) || !isContextualLiteral(expressions[index]) && extensionKey(node.field) !== extensionKey(first.field))
3331
+ throw new Error(`${name} arguments must have matching types and metadata`);
3332
+ }
3333
+ const field = new import_apache_arrow6.Field(name.toLowerCase(), first.field.type, true, first.field.metadata);
3334
+ const tuple = isTupleType(field.type);
3335
+ const list = Boolean(expected && import_apache_arrow6.DataType.isList(expected) && import_apache_arrow6.DataType.isList(field.type));
3336
+ if (!tuple && !list)
3337
+ typeKey(field.type);
3338
+ return {
3339
+ field,
3340
+ hasKernel: true,
3341
+ prepare(batch, active, context) {
3342
+ const failed = new Uint8Array(active.length);
3343
+ const childContext = name === "TRY" ? { failed } : context;
3344
+ const child = nodes[0].prepare(batch, active, childContext);
3345
+ const nullable = (node) => new import_apache_arrow6.Field(node.field.name, node.field.type, true, node.field.metadata);
3346
+ const materialize = (node, prepared, mask) => tuple || list ? maskTupleVector(prepared.vector, mask) : output(nullable(node), mask, prepared.get);
3347
+ const original = materialize(nodes[0], child, active);
3348
+ const reader = tuple ? void 0 : new ColumnReader(original);
3349
+ let result = original;
3350
+ let pending = active.map((value, row) => value && (name === "TRY" ? failed[row] : tuple ? !original.isValid(row) : !reader.isValid(row)) ? 1 : 0);
3351
+ if ((tuple || list) && name === "TRY")
3352
+ result = maskTupleVector(result, active.map((value, row) => value && !failed[row] ? 1 : 0));
3353
+ for (let index = 1; index < nodes.length && pending.some(Boolean); index++) {
3354
+ const node = nodes[index];
3355
+ const fallback = node.prepare(batch, pending, context);
3356
+ const vector = materialize(node, fallback, pending);
3357
+ const keep = active.map((value, row) => value && !pending[row] ? 1 : 0);
3358
+ if (tuple)
3359
+ result = selectTupleVectors(field.type, result, vector, keep, active);
3360
+ else if (list)
3361
+ result = selectListVectors(field.type, result, vector, keep, active);
3362
+ else {
3363
+ const a = new ColumnReader(result), b = new ColumnReader(vector);
3364
+ result = output(field, active, (row) => pending[row] ? b.get(row) : a.get(row));
3365
+ }
3366
+ const next = tuple ? void 0 : new ColumnReader(vector);
3367
+ pending = pending.map((value, row) => value && (tuple ? !vector.isValid(row) : !next.isValid(row)) ? 1 : 0);
3368
+ }
3369
+ return vectorReader(result);
3370
+ }
3371
+ };
3372
+ }
3373
+ function bindGeometryCast(argument) {
3374
+ const source = valueType(argument.field.type);
3375
+ const metadata = new Map(argument.field.metadata);
3376
+ const extension = metadata.get("ARROW:extension:name");
3377
+ if (!import_apache_arrow6.DataType.isBinary(source) && !import_apache_arrow6.DataType.isNull(source) || extension && extension !== "geoarrow.wkb")
3378
+ throw new Error("GEOMETRY CAST requires Binary WKB input");
3379
+ metadata.set("ARROW:extension:name", "geoarrow.wkb");
3380
+ return {
3381
+ ...argument,
3382
+ field: new import_apache_arrow6.Field("cast", new import_apache_arrow6.Binary(), argument.field.nullable, metadata),
3383
+ prepare(batch, active, context) {
3384
+ const child = argument.prepare(batch, active, context);
3385
+ return { get: (row) => child.get(row) };
3386
+ }
3387
+ };
3388
+ }
3389
+ function bindMembership(arguments_, options) {
3390
+ if (arguments_.length < 2 || arguments_.length > 4097 || arguments_.slice(1).some((value) => value.type !== "Literal" && !isSignedLiteral(value)))
3391
+ throw new Error("IN requires a value and 1 to 4096 scalar literals");
3392
+ const argument = bind(arguments_[0], options);
3393
+ const utf8 = typeKey(argument.field.type) === "utf8";
3394
+ const literals = arguments_.slice(1).map((value) => bind(value, options, argument.field.type));
3395
+ return {
3396
+ field: new import_apache_arrow6.Field("in", bool, argument.field.nullable || literals.some((value) => value.field.nullable)),
3397
+ hasKernel: argument.hasKernel,
3398
+ prepare(batch, active, context) {
3399
+ const source = argument.prepare(batch, active, context);
3400
+ const constantMask = Uint8Array.of(1);
3401
+ const prepared = literals.map((value) => value.prepare(batch, constantMask, {}));
3402
+ const values = new Set(prepared.map((value) => value.get(0)));
3403
+ const ranges = utf8 ? prepared.map((value) => bytes(value, 0)).filter((range) => range !== null) : [];
3404
+ return {
3405
+ get(row) {
3406
+ if (utf8) {
3407
+ const value = bytes(source, row);
3408
+ if (!value)
3409
+ return null;
3410
+ if (ranges.some((range) => (0, import_utf82.compareUTF8)(value[0], value[1], value[2], range[0], range[1], range[2]) === 0))
3411
+ return true;
3412
+ } else {
3413
+ const value = source.get(row);
3414
+ if (value === null)
3415
+ return null;
3416
+ if (!Number.isNaN(value) && values.has(value))
3417
+ return true;
3418
+ }
3419
+ return values.has(null) ? null : false;
3420
+ }
3421
+ };
3422
+ }
3423
+ };
3424
+ }
3425
+ function bindLike(args, options, insensitive) {
3426
+ if (args.length < 2 || args.length > 3)
3427
+ throw new Error("LIKE requires two or three arguments");
3428
+ const value = bind(args[0], options, new import_apache_arrow6.Utf8());
3429
+ const pattern = bind(args[1], options, new import_apache_arrow6.Utf8());
3430
+ requireType(value, "utf8");
3431
+ requireType(pattern, "utf8");
3432
+ const escape = args[2];
3433
+ if (escape && (escape.type !== "Literal" || typeof escape.value !== "string")) {
3434
+ throw new Error("LIKE ESCAPE requires a literal character");
3435
+ }
3436
+ const compile2 = (text) => compileUTF8Like(text, insensitive, escape == null ? void 0 : escape.value);
3437
+ const literal = args[1].type === "Literal" && typeof args[1].value === "string";
3438
+ const matcher = literal ? compile2(args[1].value) : void 0;
3439
+ return {
3440
+ field: new import_apache_arrow6.Field("like", bool, value.field.nullable || pattern.field.nullable),
3441
+ hasKernel: value.hasKernel || pattern.hasKernel,
3442
+ prepare(batch, active, context) {
3443
+ const source = value.prepare(batch, active, context);
3444
+ const patterns = pattern.prepare(batch, active, context);
3445
+ return {
3446
+ get(row) {
3447
+ const range = bytes(source, row);
3448
+ const text = patterns.get(row);
3449
+ if (!range || text === null)
3450
+ return null;
3451
+ return (matcher || compile2(text))(...range);
3452
+ }
3453
+ };
3454
+ }
3455
+ };
3456
+ }
3457
+ function convertByte(value, normalized) {
3458
+ if (!Number.isFinite(value))
3459
+ throw new ExpressionEvaluationError("conversion", "Byte conversion requires a finite number");
3460
+ if (normalized) {
3461
+ if (value < 0 || value > 1)
3462
+ throw new ExpressionEvaluationError("domain", "PACK_UNORM8 requires values in [0, 1]");
3463
+ return Math.round(value * 255);
3464
+ }
3465
+ const integer = Math.trunc(value);
3466
+ if (integer < 0 || integer > 255)
3467
+ throw new ExpressionEvaluationError("overflow", "UINT8 cast overflow");
3468
+ return integer;
3469
+ }
3470
+ function bindPackUnorm8(arguments_, options) {
3471
+ if (arguments_.length !== 1)
3472
+ throw new Error("PACK_UNORM8 requires one fixed-size numeric array");
3473
+ const argument = bind(arguments_[0], options, void 0, true);
3474
+ const inputType = argument.field.type;
3475
+ if (!import_apache_arrow6.DataType.isFixedSizeList(inputType) || !inputType.listSize || inputType.listSize > 4096)
3476
+ throw new Error("PACK_UNORM8 requires a fixed-size numeric array of 1 to 4096 components");
3477
+ const width = inputType.listSize;
3478
+ const child = inputType.children[0];
3479
+ if (!import_apache_arrow6.DataType.isInt(valueType(child.type)) && !import_apache_arrow6.DataType.isFloat(valueType(child.type)))
3480
+ throw new Error("PACK_UNORM8 requires numeric components");
3481
+ const type = new import_apache_arrow6.FixedSizeList(width, new import_apache_arrow6.Field("value", new import_apache_arrow6.Uint8(), false));
3482
+ const field = new import_apache_arrow6.Field("pack_unorm8", type, argument.field.nullable || child.nullable);
3483
+ return {
3484
+ field,
3485
+ hasKernel: true,
3486
+ prepare(batch, active, context) {
3487
+ var _a2;
3488
+ const input = argument.prepare(batch, active, context).vector;
3489
+ const parent = new ColumnReader(input);
3490
+ const components = new ColumnReader(input.getChildAt(0));
3491
+ const result = nullTupleVector(type, active.length);
3492
+ const data = result.data[0];
3493
+ const bytes2 = data.children[0].values;
3494
+ const rowValues = new Float64Array(width);
3495
+ for (let row = 0; row < active.length; row++) {
3496
+ if (!active[row] || ((_a2 = context.failed) == null ? void 0 : _a2[row]) || !parent.isValid(row))
3497
+ continue;
3498
+ const start = row * width;
3499
+ let valid = true;
3500
+ for (let component = 0; component < width; component++) {
3501
+ const value = components.get(start + component);
3502
+ if (value === null) {
3503
+ valid = false;
3504
+ break;
3505
+ }
3506
+ rowValues[component] = Number(value);
3507
+ }
3508
+ if (!valid)
3509
+ continue;
3510
+ try {
3511
+ for (let component = 0; component < width; component++)
3512
+ bytes2[start + component] = convertByte(rowValues[component], true);
3513
+ } catch (error) {
3514
+ if (!context.failed || !isExpressionEvaluationError(error))
3515
+ throw error;
3516
+ context.failed[row] = 1;
3517
+ bytes2.fill(0, start, start + width);
3518
+ continue;
3519
+ }
3520
+ data.setValid(row, true);
3521
+ }
3522
+ return vectorReader(result);
3523
+ }
3524
+ };
3525
+ }
3526
+ function isNestedType(type) {
3527
+ return import_apache_arrow6.DataType.isStruct(type) || import_apache_arrow6.DataType.isList(type) || import_apache_arrow6.DataType.isFixedSizeList(type);
3528
+ }
3529
+ function nestedValue(value, type) {
3530
+ if (value == null)
3531
+ return null;
3532
+ if (import_apache_arrow6.DataType.isList(type) || import_apache_arrow6.DataType.isFixedSizeList(type))
3533
+ return Array.from(value, (item) => nestedValue(item, type.valueType));
3534
+ if (import_apache_arrow6.DataType.isStruct(type))
3535
+ return Object.fromEntries(type.children.map((field) => [field.name, nestedValue(value[field.name], field.type)]));
3536
+ return value;
3537
+ }
3538
+ function nestedVector(vector, type, active) {
3539
+ if (!active.includes(0))
3540
+ return vector;
3541
+ return (0, import_apache_arrow6.vectorFromArray)(Array.from(active, (valid, row) => valid ? nestedValue(vector.get(row), type) : null), type);
3542
+ }
3543
+ function bindNestedExtract(name, args, options) {
3544
+ if (args.length !== 2)
3545
+ throw new Error(`${name} requires two arguments`);
3546
+ const input = bind(args[0], options, void 0, true);
3547
+ const inputType = input.field.type;
3548
+ const selector = args[1];
3549
+ let child;
3550
+ let index;
3551
+ if (name === "LIST_EXTRACT") {
3552
+ if (!import_apache_arrow6.DataType.isList(inputType) && !import_apache_arrow6.DataType.isFixedSizeList(inputType))
3553
+ throw new Error("LIST_EXTRACT requires an Arrow List or FixedSizeList");
3554
+ child = inputType.children[0];
3555
+ index = bind(selector, options);
3556
+ if (!import_apache_arrow6.DataType.isInt(index.field.type) && !import_apache_arrow6.DataType.isFloat(index.field.type) && !import_apache_arrow6.DataType.isNull(index.field.type))
3557
+ throw new Error("LIST_EXTRACT requires an integer index");
3558
+ } else {
3559
+ if (!import_apache_arrow6.DataType.isStruct(inputType))
3560
+ throw new Error("STRUCT_EXTRACT requires an Arrow Struct");
3561
+ if (selector.type !== "Literal" || typeof selector.value !== "string")
3562
+ throw new Error("STRUCT_EXTRACT requires a literal field name");
3563
+ const field2 = inputType.children.find((candidate) => candidate.name === selector.value);
3564
+ if (!field2)
3565
+ throw new Error(`Unknown Arrow struct field: ${selector.value}`);
3566
+ child = field2;
3567
+ }
3568
+ const field = new import_apache_arrow6.Field(child.name, valueType(child.type), true, child.metadata);
3569
+ return {
3570
+ field,
3571
+ hasKernel: true,
3572
+ prepare(batch, active, context) {
3573
+ const inputValues = input.prepare(batch, active, context).vector;
3574
+ const positions = index == null ? void 0 : index.prepare(batch, active, context);
3575
+ const childValues = index ? void 0 : inputValues.getChild(child.name);
3576
+ const values = Array.from(active, (valid, row) => {
3577
+ if (!valid || !inputValues.isValid(row))
3578
+ return null;
3579
+ if (!positions)
3580
+ return nestedValue(childValues.get(row), field.type);
3581
+ const position = positions.get(row);
3582
+ if (position === null)
3583
+ return null;
3584
+ const offset = Number(position);
3585
+ if (!Number.isSafeInteger(offset))
3586
+ return null;
3587
+ const list = inputValues.get(row);
3588
+ const element = offset < 0 ? list.length + offset : offset - 1;
3589
+ return element >= 0 && element < list.length ? nestedValue(list.get(element), field.type) : null;
3590
+ });
3591
+ return vectorReader((0, import_apache_arrow6.vectorFromArray)(values, field.type));
3592
+ }
3593
+ };
3594
+ }
3595
+ function bindCall(ast, options, expected) {
3596
+ var _a2, _b;
3597
+ if (ast.callee.type !== "Identifier")
3598
+ throw new Error("Only registered named function calls are supported");
3599
+ let name = ast.callee.name;
3600
+ const recovery = recoveryName(ast);
3601
+ if (recovery)
3602
+ return bindRecovery(recovery, ast.arguments, options, expected);
3603
+ if (ast.sqlFunction) {
3604
+ const matches = [
3605
+ ...options.functionLookup.keys(),
3606
+ "array",
3607
+ "array_float16",
3608
+ "array_float32",
3609
+ "array_float64",
3610
+ "array_uint8",
3611
+ "PACK_UNORM8",
3612
+ "LIST_EXTRACT",
3613
+ "STRUCT_EXTRACT",
3614
+ "cast",
3615
+ "like",
3616
+ "ilike",
3617
+ "concat",
3618
+ "concatStrict",
3619
+ "upper",
3620
+ "lower",
3621
+ "capitalize",
3622
+ "isNull",
3623
+ "isNotNull",
3624
+ "parseNumber",
3625
+ "parseBigInt",
3626
+ "parseBoolean",
3627
+ "toFloat64",
3628
+ "toInt32",
3629
+ "toInt64"
3630
+ ].filter((key) => key.toUpperCase() === name.toUpperCase());
3631
+ if (matches.length > 1)
3632
+ throw new Error(`Ambiguous SQL function: ${name}`);
3633
+ name = matches[0] ?? name;
3634
+ }
3635
+ if (name === "LIST_EXTRACT" || name === "STRUCT_EXTRACT")
3636
+ return bindNestedExtract(name, ast.arguments, options);
3637
+ if (name === "PACK_UNORM8")
3638
+ return bindPackUnorm8(ast.arguments, options);
3639
+ if (["array", "array_float16", "array_float32", "array_float64", "array_uint8"].includes(name)) {
3640
+ if (!ast.arguments.length || ast.arguments.length > 4096)
3641
+ throw new Error("ARRAY requires 1 to 4096 numeric expressions");
3642
+ const arguments_2 = ast.arguments.map((value) => bind(value, options));
3643
+ if (arguments_2.some((value) => !import_apache_arrow6.DataType.isFloat(valueType(value.field.type)) && !import_apache_arrow6.DataType.isInt(valueType(value.field.type))))
3644
+ throw new Error("ARRAY requires numeric expressions");
3645
+ const component = name === "array_uint8" ? new import_apache_arrow6.Uint8() : name === "array_float16" ? new import_apache_arrow6.Float16() : name === "array_float32" ? new import_apache_arrow6.Float32() : name === "array_float64" || arguments_2.every((value) => import_apache_arrow6.DataType.isInt(valueType(value.field.type))) || arguments_2.some((value) => typeKey(value.field.type) === "f2") ? new import_apache_arrow6.Float64() : arguments_2.some((value) => typeKey(value.field.type) === "f1") ? new import_apache_arrow6.Float32() : new import_apache_arrow6.Float16();
3646
+ const type = new import_apache_arrow6.FixedSizeList(arguments_2.length, new import_apache_arrow6.Field("value", component, false));
3647
+ const field2 = new import_apache_arrow6.Field("array", type, arguments_2.some((value) => value.field.nullable));
3648
+ return {
3649
+ field: field2,
3650
+ hasKernel: true,
3651
+ prepare(batch, active, context) {
3652
+ const values = arguments_2.map((value) => prepareInput(value, batch, active, context, arguments_2.some((argument) => argument.hasKernel)));
3653
+ const vector = nullTupleVector(type, active.length), data = vector.data[0], output2 = import_apache_arrow6.DataType.isFloat(component) && component.precision === import_apache_arrow6.Precision.HALF ? float16Values(data.children[0].values) : data.children[0].values;
3654
+ const rowValues = new Array(values.length);
3655
+ for (let row = 0; row < active.length; row++) {
3656
+ if (!active[row])
3657
+ continue;
3658
+ for (let column = 0; column < values.length; column++)
3659
+ rowValues[column] = values[column].get(row);
3660
+ if (rowValues.some((value) => value === null))
3661
+ continue;
3662
+ try {
3663
+ for (let column = 0; column < values.length; column++) {
3664
+ const index = row * values.length + column;
3665
+ const value = Number(rowValues[column]);
3666
+ output2[index] = name === "array_uint8" ? convertByte(value, false) : value;
3667
+ if (Number.isFinite(value) && !Number.isFinite(output2[index]))
3668
+ throw new ExpressionEvaluationError("overflow", "ARRAY cast overflow");
3669
+ }
3670
+ } catch (error) {
3671
+ if (!context.failed || !isExpressionEvaluationError(error))
3672
+ throw error;
3673
+ context.failed[row] = 1;
3674
+ output2.fill(0, row * values.length, (row + 1) * values.length);
3675
+ continue;
3676
+ }
3677
+ data.setValid(row, true);
3678
+ }
3679
+ return vectorReader(vector);
3680
+ }
3681
+ };
3682
+ }
3683
+ if (name === "like" || name === "ilike")
3684
+ return bindLike(ast.arguments, options, name === "ilike");
3685
+ if (name === "upper" || name === "lower" || name === "capitalize") {
3686
+ if (ast.arguments.length !== 1)
3687
+ throw new Error("Case conversion requires one argument");
3688
+ const arg = bind(ast.arguments[0], options, new import_apache_arrow6.Utf8());
3689
+ requireType(arg, "utf8");
3690
+ return {
3691
+ field: new import_apache_arrow6.Field(name, new import_apache_arrow6.Utf8(), arg.field.nullable),
3692
+ hasKernel: arg.hasKernel,
3693
+ prepare(batch, active, context) {
3694
+ const input = arg.prepare(batch, active, context);
3695
+ return {
3696
+ get(row) {
3697
+ const value = input.get(row);
3698
+ if (!value)
3699
+ return value;
3700
+ if (name === "upper")
3701
+ return value.toUpperCase();
3702
+ if (name === "lower")
3703
+ return value.toLowerCase();
3704
+ const first = String.fromCodePoint(value.codePointAt(0));
3705
+ return first.toUpperCase() + value.slice(first.length);
3706
+ }
3707
+ };
3708
+ }
3709
+ };
3710
+ }
3711
+ if (name === "concat" || name === "concatStrict") {
3712
+ if (!ast.arguments.length)
3713
+ throw new Error("CONCAT requires at least one argument");
3714
+ const args = ast.arguments.map((arg) => bind(arg, options, new import_apache_arrow6.Utf8()));
3715
+ for (const arg of args)
3716
+ requireType(arg, "utf8");
3717
+ const strict = name === "concatStrict";
3718
+ return {
3719
+ field: new import_apache_arrow6.Field("concat", new import_apache_arrow6.Utf8(), strict && args.some((arg) => arg.field.nullable)),
3720
+ hasKernel: args.some((arg) => arg.hasKernel),
3721
+ prepare(batch, active, context) {
3722
+ const inputs = args.map((arg) => arg.prepare(batch, active, context));
3723
+ return {
3724
+ get(row) {
3725
+ let result2 = "";
3726
+ for (const input of inputs) {
3727
+ const value = input.get(row);
3728
+ if (value === null && strict)
3729
+ return null;
3730
+ if (value !== null)
3731
+ result2 += value;
3732
+ }
3733
+ return result2;
3734
+ }
3735
+ };
3736
+ }
3737
+ };
3738
+ }
3739
+ if (name === "in")
3740
+ return bindMembership(ast.arguments, options);
3741
+ if (name === "cast") {
3742
+ if (ast.arguments.length !== 2 || ((_a2 = ast.arguments[1]) == null ? void 0 : _a2.type) !== "Literal")
3743
+ throw new Error("cast requires a value and a literal scalar target");
3744
+ const argument = bind(ast.arguments[0], options);
3745
+ const target = ast.arguments[1].value;
3746
+ if (target === "geometry")
3747
+ return bindGeometryCast(argument);
3748
+ const cast = bindCast(argument.field.type, target);
3749
+ return {
3750
+ field: new import_apache_arrow6.Field("cast", cast.type, argument.field.nullable),
3751
+ hasKernel: argument.hasKernel,
3752
+ prepare(batch, active, context) {
3753
+ const child = argument.prepare(batch, active, context);
3754
+ return {
3755
+ get: (row) => cast.textInput && !import_apache_arrow6.DataType.isUtf8(valueType(cast.type)) ? cast.evaluate(null, bytes(child, row)) : cast.evaluate(child.get(row))
3756
+ };
3757
+ }
3758
+ };
3759
+ }
3760
+ const conversion = ["toFloat64", "toInt32", "toInt64"].includes(name);
3761
+ const nullTest = name === "isNull" || name === "isNotNull";
3762
+ if (conversion || nullTest || ["parseNumber", "parseBigInt", "parseBoolean"].includes(name)) {
3763
+ if (ast.arguments.length !== 1)
3764
+ throw new Error(`${name} requires one argument`);
3765
+ const argument = bind(ast.arguments[0], options);
3766
+ if (conversion)
3767
+ requireNumeric(argument);
3768
+ else if (!nullTest)
3769
+ requireType(argument, "utf8");
3770
+ const type = name === "parseNumber" || name === "toFloat64" ? new import_apache_arrow6.Float64() : name === "toInt32" ? new import_apache_arrow6.Int32() : name === "parseBigInt" || name === "toInt64" ? new import_apache_arrow6.Int64() : bool;
3771
+ const validate2 = createValueValidator(type);
3772
+ const round2 = roundToType(type);
3773
+ const field2 = new import_apache_arrow6.Field(name, type, conversion ? argument.field.nullable : !nullTest);
3774
+ return {
3775
+ field: field2,
3776
+ hasKernel: argument.hasKernel,
3777
+ prepare(batch, active, context) {
3778
+ const child = argument.prepare(batch, active, context);
3779
+ return {
3780
+ get: (row) => {
3781
+ if (nullTest) {
3782
+ const missing = child.isNull ? child.isNull(row) : child.get(row) === null;
3783
+ return name === "isNull" ? missing : !missing;
3784
+ }
3785
+ if (conversion) {
3786
+ const value = child.get(row);
3787
+ if (value === null)
3788
+ return null;
3789
+ if (name === "toInt64" && typeof value === "number" && !Number.isInteger(value))
3790
+ throw new ExpressionEvaluationError("conversion", "Int64 conversion requires a finite integer");
3791
+ const result3 = name === "toInt64" ? BigInt(value) : Number(value);
3792
+ validate2(result3);
3793
+ return result3;
3794
+ }
3795
+ const range = bytes(child, row);
3796
+ if (!range)
3797
+ return null;
3798
+ const [buffer, start, end] = range;
3799
+ const result2 = (name === "parseNumber" ? (0, import_utf82.parseUTF8Number)(buffer, start, end) : name === "parseBigInt" ? (0, import_utf82.parseUTF8BigInt)(buffer, start, end) : (0, import_utf82.parseUTF8Boolean)(buffer, start, end)) ?? null;
3800
+ validate2(result2);
3801
+ return round2(result2);
3802
+ }
3803
+ };
3804
+ }
3805
+ };
3806
+ }
3807
+ const group = options.functionLookup.get(name);
3808
+ if (!group)
3809
+ throw new Error(`Unknown Arrow function: ${name}`);
3810
+ const inferred = ast.arguments.map((argument) => needsArgumentContext(argument) ? void 0 : bind(argument, options, void 0, true));
3811
+ const candidates = [];
3812
+ const allLiteralArguments = ast.arguments.every(isContextualLiteral);
3813
+ let contextualError;
3814
+ for (const prototype of group.prototypes) {
3815
+ if (ast.arguments.length !== prototype.arguments.length)
3816
+ continue;
3817
+ let cost = 0;
3818
+ const arguments_2 = [];
3819
+ let compatible = true;
3820
+ for (let index = 0; index < ast.arguments.length; index++) {
3821
+ const argument = ast.arguments[index], field2 = prototype.arguments[index], source = inferred[index];
3822
+ let bound;
3823
+ if (isContextualLiteral(argument) || !source) {
3824
+ try {
3825
+ bound = bind(argument, options, field2.type, !prototype.evaluateScalar);
3826
+ } catch (error) {
3827
+ contextualError = error;
3828
+ compatible = false;
3829
+ break;
3830
+ }
3831
+ if (source && allLiteralArguments && physicalKey(valueType(source.field.type)) !== physicalKey(field2.type))
3832
+ cost += 4;
3833
+ } else {
3834
+ bound = source;
3835
+ }
3836
+ const sourceType = valueType(bound.field.type);
3837
+ if (import_apache_arrow6.DataType.isDictionary(bound.field.type) && !import_apache_arrow6.DataType.isDictionary(field2.type))
3838
+ cost += 1;
3839
+ if (physicalKey(import_apache_arrow6.DataType.isDictionary(field2.type) ? bound.field.type : sourceType) !== physicalKey(field2.type)) {
3840
+ if (import_apache_arrow6.DataType.isFloat(sourceType) && import_apache_arrow6.DataType.isFloat(field2.type) && sourceType.precision < field2.type.precision) {
3841
+ cost += field2.type.precision - sourceType.precision;
3842
+ const child = bound, round2 = roundToType(field2.type);
3843
+ bound = {
3844
+ field: new import_apache_arrow6.Field(child.field.name, field2.type, child.field.nullable, child.field.metadata),
3845
+ hasKernel: child.hasKernel,
3846
+ prepare(batch, active, context) {
3847
+ const prepared = child.prepare(batch, active, context);
3848
+ return { get: (row) => round2(prepared.get(row)) };
3849
+ }
3850
+ };
3851
+ } else {
3852
+ compatible = false;
3853
+ break;
3854
+ }
3855
+ }
3856
+ if ([...field2.metadata].some(([key, value]) => bound.field.metadata.get(key) !== value) || prototype.nullHandling === "call" && bound.field.nullable && !field2.nullable) {
3857
+ compatible = false;
3858
+ break;
3859
+ }
3860
+ arguments_2.push(bound);
3861
+ }
3862
+ if (compatible)
3863
+ candidates.push({ prototype, arguments: arguments_2, cost });
3864
+ }
3865
+ const untypedNumeric = (value) => value.type === "Literal" && (value.value === null || typeof value.value === "number") || isSignedLiteral(value) || Boolean(recoveryName(value) && value.arguments.every(untypedNumeric)) || value.type === "ConditionalExpression" && untypedNumeric(value.consequent) && untypedNumeric(value.alternate);
3866
+ const allFloat64 = (prototype) => prototype.arguments.every((field2) => import_apache_arrow6.DataType.isFloat(field2.type) && field2.type.precision === import_apache_arrow6.Precision.DOUBLE);
3867
+ if (ast.arguments.every(untypedNumeric) && candidates.every((candidate) => candidate.prototype.arguments.every((field2) => import_apache_arrow6.DataType.isInt(field2.type) || import_apache_arrow6.DataType.isFloat(field2.type))) && candidates.some((candidate) => allFloat64(candidate.prototype))) {
3868
+ for (const candidate of candidates)
3869
+ if (!allFloat64(candidate.prototype))
3870
+ candidate.cost++;
3871
+ }
3872
+ candidates.sort((a, b) => a.cost - b.cost);
3873
+ if (!candidates.length && group.prototypes.length === 1 && contextualError)
3874
+ throw contextualError;
3875
+ if (!candidates.length)
3876
+ throw new Error(`Argument type mismatch or wrong argument count for ${name}`);
3877
+ if (((_b = candidates[1]) == null ? void 0 : _b.cost) === candidates[0].cost)
3878
+ throw new Error(`Ambiguous Arrow function call: ${name}`);
3879
+ const declaration = candidates[0].prototype;
3880
+ const arguments_ = candidates[0].arguments;
3881
+ const evaluateVector = declaration.evaluateScalar ? void 0 : declaration.evaluate;
3882
+ const result = declaration.result;
3883
+ const tuple = isTupleType(result.type);
3884
+ if (tuple && declaration.evaluateScalar)
3885
+ throw new Error("Fixed-size list results require a vector-only function");
3886
+ if (declaration.evaluateScalar)
3887
+ for (const argument of arguments_)
3888
+ typeKey(argument.field.type);
3889
+ if (!tuple)
3890
+ typeKey(result.type);
3891
+ const validate = tuple ? void 0 : createValueValidator(result.type);
3892
+ const round = tuple ? void 0 : roundToType(result.type);
3893
+ const field = new import_apache_arrow6.Field(result.name, valueType(result.type), result.nullable || declaration.nullHandling !== "call" && arguments_.some((argument) => argument.field.nullable), result.metadata);
3894
+ return {
3895
+ field,
3896
+ hasKernel: Boolean(evaluateVector) || arguments_.some((argument) => argument.hasKernel),
3897
+ prepare(batch, active, context) {
3898
+ const children = arguments_.map((argument) => prepareInput(argument, batch, active, context, Boolean(evaluateVector) || arguments_.some((value) => value.hasKernel)));
3899
+ let kernel;
3900
+ let mask = active;
3901
+ if (evaluateVector && active.some(Boolean)) {
3902
+ const vectors = children.map((child, index) => child.vector ?? output(arguments_[index].field, context.failed ? active.map((value, row) => value && !context.failed[row] ? 1 : 0) : active, child.get));
3903
+ const readers = vectors.map((vector) => new ColumnReader(vector));
3904
+ mask = active.map((value, row) => {
3905
+ var _a3;
3906
+ return value && !((_a3 = context.failed) == null ? void 0 : _a3[row]) && (declaration.nullHandling === "call" || readers.every((reader) => reader.isValid(row))) ? 1 : 0;
3907
+ });
3908
+ if (mask.some(Boolean)) {
3909
+ const vector = evaluateVector(vectors, {
3910
+ activeRows: mask,
3911
+ length: active.length,
3912
+ reportError(row, error) {
3913
+ if (!Number.isInteger(row) || row < 0 || row >= active.length || !mask[row])
3914
+ throw new Error("Kernel reported an inactive or invalid row");
3915
+ if (!context.failed || !isExpressionEvaluationError(error))
3916
+ throw error;
3917
+ context.failed[row] = 1;
3918
+ mask[row] = 0;
3919
+ }
3920
+ });
3921
+ if (vector.length !== active.length || (tuple ? physicalKey(vector.type) !== physicalKey(result.type) : typeKey(vector.type) !== typeKey(result.type)))
3922
+ throw new Error(`Invalid kernel result for ${name}`);
3923
+ if (tuple) {
3924
+ validateTupleVector(vector, result, mask);
3925
+ return vectorReader(maskTupleVector(vector, mask));
3926
+ }
3927
+ kernel = sourceReader(vector);
3928
+ }
3929
+ }
3930
+ if (isTupleType(result.type))
3931
+ return vectorReader(nullTupleVector(result.type, active.length));
3932
+ return {
3933
+ get: (row) => {
3934
+ var _a3;
3935
+ let value;
3936
+ if (evaluateVector) {
3937
+ if (!mask[row] || !kernel)
3938
+ return null;
3939
+ value = kernel.get(row);
3940
+ } else {
3941
+ const args = children.map((child) => child.get(row));
3942
+ if ((_a3 = context.failed) == null ? void 0 : _a3[row])
3943
+ return null;
3944
+ if (declaration.nullHandling !== "call" && args.some((value2) => value2 === null))
3945
+ return null;
3946
+ value = declaration.evaluateScalar(...args);
3947
+ }
3948
+ if (value === null && !result.nullable)
3949
+ throw new Error(`Function ${name} returned null for a non-nullable result`);
3950
+ validate(value);
3951
+ return round(value);
3952
+ }
3953
+ };
3954
+ }
3955
+ };
3956
+ }
3957
+ function roundToType(type) {
3958
+ if (typeKey(type) === "f0") {
3959
+ const round = roundFloat16();
3960
+ return (value) => value === null ? null : round(value);
3961
+ }
3962
+ return typeKey(type) === "f1" ? (value) => value === null ? null : Math.fround(value) : (value) => value;
3963
+ }
3964
+ function isSignedLiteral(ast) {
3965
+ return ast.type === "UnaryExpression" && (ast.operator === "+" || ast.operator === "-") && ast.argument.type === "Literal" && typeof ast.argument.value === "number";
3966
+ }
3967
+ function recoveryName(ast) {
3968
+ if (ast.type !== "CallExpression" || ast.callee.type !== "Identifier")
3969
+ return void 0;
3970
+ const name = ast.sqlFunction ? ast.callee.name.toUpperCase() : ast.callee.name;
3971
+ return name === "TRY" || name === "COALESCE" ? name : void 0;
3972
+ }
3973
+ function containsContextualArray(ast) {
3974
+ return ast.type === "ArrayExpression" || ast.type === "ConditionalExpression" && (containsContextualArray(ast.consequent) || containsContextualArray(ast.alternate)) || Boolean(recoveryName(ast) && ast.arguments.some(containsContextualArray));
3975
+ }
3976
+ function isContextualLiteral(ast) {
3977
+ return ast.type === "Literal" || ast.type === "ArrayExpression" || isSignedLiteral(ast) || Boolean(recoveryName(ast) && ast.arguments.every(isContextualLiteral)) || ast.type === "ConditionalExpression" && isContextualLiteral(ast.consequent) && isContextualLiteral(ast.alternate);
3978
+ }
3979
+ function needsArgumentContext(ast) {
3980
+ return ast.type === "ArrayExpression" || ast.type === "Literal" && ast.value === null || Boolean(recoveryName(ast) && ast.arguments.some(containsContextualArray)) || ast.type === "ConditionalExpression" && (needsArgumentContext(ast.consequent) || needsArgumentContext(ast.alternate));
3981
+ }
3982
+
3983
+ // dist/arrow/predicate.js
3984
+ function compileArrowPredicate(predicate, options) {
3985
+ return compileArrowExpression(columnarPredicateToExpression(predicate, options), options);
3986
+ }
3987
+
3988
+ // dist/arrow/relational-query.js
3989
+ var import_apache_arrow8 = require("apache-arrow");
3990
+ var import_arrow = require("@math.gl/arrow");
3991
+
3992
+ // dist/arrow/aggregates.js
3993
+ var import_apache_arrow7 = require("apache-arrow");
3994
+ var import_utf83 = require("@math.gl/arrow/utf8");
3995
+ var reductions = /* @__PURE__ */ new Set([
3996
+ "MIN",
3997
+ "MAX",
3998
+ "EVERY",
3999
+ "BOOL_AND",
4000
+ "BOOL_OR",
4001
+ "BIT_AND",
4002
+ "BIT_OR",
4003
+ "BIT_XOR"
4004
+ ]);
4005
+ function compileArrowAggregates(aggregates, options) {
4006
+ const groups = [];
4007
+ const byExpression = /* @__PURE__ */ new Map();
4008
+ const outputs = Object.entries(aggregates).map(([name, aggregate]) => {
4009
+ const { operation, expression } = aggregate;
4010
+ if (!reductions.has(operation) && !["COUNT", "SUM", "AVG"].includes(operation))
4011
+ throw new Error(`Unsupported Arrow aggregate: ${operation}`);
4012
+ if (expression === void 0 && operation !== "COUNT")
4013
+ throw new Error(`${operation} requires an expression`);
4014
+ let group = byExpression.get(expression);
4015
+ if (!group) {
4016
+ const compiled = expression === void 0 ? void 0 : compileArrowExpression(expression, options);
4017
+ const type2 = compiled && valueType(compiled.outputField.type);
4018
+ group = {
4019
+ expression: compiled,
4020
+ operations: /* @__PURE__ */ new Set(),
4021
+ integer: Boolean(type2 && import_apache_arrow7.DataType.isInt(type2)),
4022
+ wide: Boolean(type2 && import_apache_arrow7.DataType.isInt(type2) && type2.bitWidth === 64),
4023
+ utf8: Boolean(type2 && import_apache_arrow7.DataType.isUtf8(type2)),
4024
+ sums: false,
4025
+ reductions: []
4026
+ };
4027
+ byExpression.set(expression, group);
4028
+ groups.push(group);
4029
+ }
4030
+ const type = group.expression && valueType(group.expression.outputField.type);
4031
+ if (type && !import_apache_arrow7.DataType.isNull(type) && operation !== "COUNT") {
4032
+ const numeric = group.integer || import_apache_arrow7.DataType.isFloat(type);
4033
+ const supported = operation.startsWith("BIT_") ? group.integer : operation === "EVERY" || operation.startsWith("BOOL_") ? import_apache_arrow7.DataType.isBool(type) : numeric || group.utf8 && (operation === "MIN" || operation === "MAX");
4034
+ if (!supported)
4035
+ throw new Error(`${operation} does not support Arrow type ${type}`);
4036
+ }
4037
+ group.operations.add(operation);
4038
+ return { name, operation, group };
4039
+ });
4040
+ for (const group of groups) {
4041
+ group.sums = group.operations.has("SUM") || group.operations.has("AVG");
4042
+ group.reductions = [...group.operations].filter((operation) => reductions.has(operation));
4043
+ }
4044
+ const resultFor = (states) => Object.fromEntries(outputs.map(({ name, operation, group }) => [
4045
+ name,
4046
+ finish(operation, group, states.get(group))
4047
+ ]));
4048
+ const accumulators = /* @__PURE__ */ new WeakMap();
4049
+ const createAccumulator = () => {
4050
+ const states = new Map(groups.map((group) => [group, emptyState(group)]));
4051
+ const accumulator = {
4052
+ update(batch, { signal } = {}) {
4053
+ signal == null ? void 0 : signal.throwIfAborted();
4054
+ const partials = groups.map((group) => summarize(group, batch, signal)[0]);
4055
+ signal == null ? void 0 : signal.throwIfAborted();
4056
+ groups.forEach((group, index) => mergeState(group, states.get(group), partials[index]));
4057
+ },
4058
+ merge(other) {
4059
+ const source = accumulators.get(other);
4060
+ if (!source || other === accumulator)
4061
+ throw new Error("Merge requires another accumulator from the same Arrow aggregate plan");
4062
+ for (const group of groups)
4063
+ mergeState(group, states.get(group), source.get(group));
4064
+ },
4065
+ result() {
4066
+ return resultFor(states);
4067
+ }
4068
+ };
4069
+ accumulators.set(accumulator, states);
4070
+ return accumulator;
4071
+ };
4072
+ return {
4073
+ createAccumulator,
4074
+ createGroupedAccumulator(groupBy) {
4075
+ const keyExpression = compileArrowExpression(groupBy, options);
4076
+ const type = valueType(keyExpression.outputField.type);
4077
+ if (!(import_apache_arrow7.DataType.isInt(type) || import_apache_arrow7.DataType.isFloat(type) || import_apache_arrow7.DataType.isBool(type) || import_apache_arrow7.DataType.isUtf8(type) || import_apache_arrow7.DataType.isNull(type))) {
4078
+ throw new Error(`Unsupported Arrow aggregate group key type: ${type}`);
4079
+ }
4080
+ const statesByKey = /* @__PURE__ */ new Map();
4081
+ return {
4082
+ update(batch, { signal } = {}) {
4083
+ const partition = partitionRows(keyExpression, batch, signal);
4084
+ const partials = groups.map((group) => summarize(group, batch, signal, partition));
4085
+ signal == null ? void 0 : signal.throwIfAborted();
4086
+ for (const [key, index] of partition.indexByKey) {
4087
+ let states = statesByKey.get(key);
4088
+ if (!states) {
4089
+ states = new Map(groups.map((group) => [group, emptyState(group)]));
4090
+ statesByKey.set(key, states);
4091
+ }
4092
+ groups.forEach((group, groupIndex) => mergeState(group, states.get(group), partials[groupIndex][index]));
4093
+ }
4094
+ },
4095
+ result() {
4096
+ return new Map(Array.from(statesByKey, ([key, states]) => [key, resultFor(states)]));
4097
+ }
4098
+ };
4099
+ },
4100
+ evaluate(input, evaluation) {
4101
+ var _a2;
4102
+ (_a2 = evaluation == null ? void 0 : evaluation.signal) == null ? void 0 : _a2.throwIfAborted();
4103
+ const accumulator = createAccumulator();
4104
+ for (const batch of "batches" in input ? input.batches : input)
4105
+ accumulator.update(batch, evaluation);
4106
+ return accumulator.result();
4107
+ },
4108
+ async evaluateInBatches(input, evaluation) {
4109
+ var _a2, _b;
4110
+ (_a2 = evaluation == null ? void 0 : evaluation.signal) == null ? void 0 : _a2.throwIfAborted();
4111
+ const accumulator = createAccumulator();
4112
+ for await (const batch of input)
4113
+ accumulator.update(batch, evaluation);
4114
+ (_b = evaluation == null ? void 0 : evaluation.signal) == null ? void 0 : _b.throwIfAborted();
4115
+ return accumulator.result();
4116
+ }
4117
+ };
4118
+ }
4119
+ function emptyState(group) {
4120
+ return { count: 0n, sum: group.integer ? 0n : 0, values: /* @__PURE__ */ new Map() };
4121
+ }
4122
+ function partitionRows(expression, batch, signal) {
4123
+ const reader = new ColumnReader(expression.evaluate(batch, { signal }));
4124
+ const indexByKey = /* @__PURE__ */ new Map();
4125
+ const indexByRow = new Uint32Array(batch.numRows);
4126
+ const rowCounts = [];
4127
+ for (let row = 0; row < batch.numRows; row++) {
4128
+ if (row % 1024 === 0)
4129
+ signal == null ? void 0 : signal.throwIfAborted();
4130
+ const key = reader.get(row);
4131
+ if (typeof key === "number" && !Number.isFinite(key))
4132
+ throw new Error("Arrow aggregate group keys must be finite");
4133
+ let index = indexByKey.get(key);
4134
+ if (index === void 0) {
4135
+ index = indexByKey.size;
4136
+ indexByKey.set(key, index);
4137
+ rowCounts.push(0);
4138
+ }
4139
+ indexByRow[row] = index;
4140
+ rowCounts[index]++;
4141
+ }
4142
+ return { indexByKey, indexByRow, rowCounts };
4143
+ }
4144
+ function summarize(group, batch, signal, partition) {
4145
+ const states = Array.from({ length: (partition == null ? void 0 : partition.indexByKey.size) ?? 1 }, () => emptyState(group));
4146
+ if (!group.expression) {
4147
+ for (let index = 0; index < states.length; index++)
4148
+ states[index].count = BigInt((partition == null ? void 0 : partition.rowCounts[index]) ?? batch.numRows);
4149
+ return states;
4150
+ }
4151
+ const vector = group.expression.evaluate(batch, { signal });
4152
+ const countOnly = !group.sums && !group.reductions.length;
4153
+ if (countOnly && !partition) {
4154
+ states[0].count = BigInt(vector.length - vector.nullCount);
4155
+ return states;
4156
+ }
4157
+ const reader = new ColumnReader(vector);
4158
+ const counts = Array.from({ length: states.length }, () => 0);
4159
+ for (let row = 0; row < vector.length; row++) {
4160
+ if (row % 1024 === 0)
4161
+ signal == null ? void 0 : signal.throwIfAborted();
4162
+ const index = (partition == null ? void 0 : partition.indexByRow[row]) ?? 0;
4163
+ const state = states[index];
4164
+ if (countOnly || group.utf8) {
4165
+ if (!reader.isValid(row))
4166
+ continue;
4167
+ counts[index]++;
4168
+ if (countOnly)
4169
+ continue;
4170
+ const bytes2 = reader.utf8(row);
4171
+ for (const operation of group.reductions) {
4172
+ const previous = state.values.get(operation);
4173
+ if (winsUTF8(operation, bytes2, previous))
4174
+ state.values.set(operation, bytes2[0].slice(bytes2[1], bytes2[2]));
4175
+ }
4176
+ } else {
4177
+ const value = reader.get(row);
4178
+ if (value === null)
4179
+ continue;
4180
+ counts[index]++;
4181
+ if (group.sums)
4182
+ state.sum = add(group, state.sum, value);
4183
+ for (const operation of group.reductions) {
4184
+ const operand = operation.startsWith("BIT_") ? BigInt(value) : value;
4185
+ state.values.set(operation, reduce(operation, state.values.get(operation), operand));
4186
+ }
4187
+ }
4188
+ }
4189
+ states.forEach((state, index) => {
4190
+ state.count = BigInt(counts[index]);
4191
+ });
4192
+ return states;
4193
+ }
4194
+ function add(group, left, right) {
4195
+ return group.integer ? BigInt(left) + BigInt(right) : Number(left) + Number(right);
4196
+ }
4197
+ function winsUTF8(operation, [bytes2, start, end], previous) {
4198
+ if (!previous)
4199
+ return true;
4200
+ const order = (0, import_utf83.compareUTF8)(bytes2, start, end, previous, 0, previous.length);
4201
+ return operation === "MIN" ? order < 0 : order > 0;
4202
+ }
4203
+ function reduce(operation, left, right) {
4204
+ if (left === void 0)
4205
+ return right;
4206
+ switch (operation) {
4207
+ case "MIN":
4208
+ return typeof left === "number" ? Math.min(left, right) : left < right ? left : right;
4209
+ case "MAX":
4210
+ return typeof left === "number" ? Math.max(left, right) : left > right ? left : right;
4211
+ case "EVERY":
4212
+ case "BOOL_AND":
4213
+ return Boolean(left && right);
4214
+ case "BOOL_OR":
4215
+ return Boolean(left || right);
4216
+ case "BIT_AND":
4217
+ return left & right;
4218
+ case "BIT_OR":
4219
+ return left | right;
4220
+ case "BIT_XOR":
4221
+ return left ^ right;
4222
+ default:
4223
+ throw new Error(`Invalid Arrow reduction: ${operation}`);
4224
+ }
4225
+ }
4226
+ function mergeState(group, target, source) {
4227
+ if (!source.count)
4228
+ return;
4229
+ target.count += source.count;
4230
+ if (group.sums)
4231
+ target.sum = add(group, target.sum, source.sum);
4232
+ for (const [operation, value] of source.values) {
4233
+ const previous = target.values.get(operation);
4234
+ if (value instanceof Uint8Array) {
4235
+ if (winsUTF8(operation, [value, 0, value.length], previous))
4236
+ target.values.set(operation, value);
4237
+ } else {
4238
+ target.values.set(operation, reduce(operation, previous, value));
4239
+ }
4240
+ }
4241
+ }
4242
+ function finish(operation, group, state) {
4243
+ if (operation === "COUNT")
4244
+ return state.count;
4245
+ if (!state.count)
4246
+ return null;
4247
+ if (operation === "SUM")
4248
+ return state.sum;
4249
+ if (operation === "AVG")
4250
+ return Number(state.sum) / Number(state.count);
4251
+ const value = state.values.get(operation);
4252
+ if (value instanceof Uint8Array)
4253
+ return new TextDecoder().decode(value);
4254
+ return operation.startsWith("BIT_") && !group.wide ? Number(value) : value;
4255
+ }
4256
+
4257
+ // dist/arrow/relational-query.js
4258
+ var import_utf84 = require("@math.gl/arrow/utf8");
4259
+ function unionArrowTables(source, inputs) {
4260
+ for (const table of inputs) {
4261
+ (0, import_arrow.validateArrowTableSchema)(table, source.schema, {
4262
+ rejectExtraFields: true,
4263
+ schemaName: "UNION ALL"
4264
+ });
4265
+ }
4266
+ return new import_apache_arrow8.Table(source.schema, [source, ...inputs].flatMap((table) => table.batches));
4267
+ }
4268
+ function joinArrowTables(left, join, signal) {
4269
+ const right = join.table;
4270
+ const { vector: leftKey } = getScalarColumn(left, join.left);
4271
+ const { vector: rightKey } = getScalarColumn(right, join.right);
4272
+ const fields = [
4273
+ ...left.schema.fields,
4274
+ ...right.schema.fields.map((field) => field.clone({ name: join.rightPrefix + field.name }))
4275
+ ];
4276
+ if (new Set(fields.map((field) => field.name)).size !== fields.length)
4277
+ throw new Error("Duplicate Arrow join output name");
4278
+ const schema = new import_apache_arrow8.Schema(fields, left.schema.metadata, void 0, left.schema.metadataVersion);
4279
+ const rightRows = /* @__PURE__ */ new Map();
4280
+ for (let row = 0; row < right.numRows; row++) {
4281
+ signal == null ? void 0 : signal.throwIfAborted();
4282
+ const key = normalizeJoinKey(rightKey.get(row));
4283
+ if (key === null || typeof key === "number" && Number.isNaN(key))
4284
+ continue;
4285
+ const matches = rightRows.get(key);
4286
+ if (matches)
4287
+ matches.push(row);
4288
+ else
4289
+ rightRows.set(key, [row]);
4290
+ }
4291
+ const leftIndexes = [];
4292
+ const rightIndexes = [];
4293
+ for (let row = 0; row < left.numRows; row++) {
4294
+ signal == null ? void 0 : signal.throwIfAborted();
4295
+ const key = normalizeJoinKey(leftKey.get(row));
4296
+ for (const match of rightRows.get(key) ?? []) {
4297
+ leftIndexes.push(row);
4298
+ rightIndexes.push(match);
4299
+ }
4300
+ }
4301
+ if (!leftIndexes.length)
4302
+ return new import_apache_arrow8.Table(schema, []);
4303
+ const tables = [
4304
+ (0, import_arrow.takeArrowTableRows)(left, Int32Array.from(leftIndexes)),
4305
+ (0, import_arrow.takeArrowTableRows)(right, Int32Array.from(rightIndexes))
4306
+ ];
4307
+ const columns = tables.flatMap((table) => table.schema.fields.map((_, index) => table.getChildAt(index)));
4308
+ return new import_apache_arrow8.Table(schema, Object.fromEntries(fields.map((field, index) => [field.name, columns[index]])));
4309
+ }
4310
+ function normalizeJoinKey(value) {
4311
+ return typeof value === "number" && Number.isInteger(value) ? BigInt(value) : value;
4312
+ }
4313
+ function orderArrowTable(table, orderBy, offset, limit, signal) {
4314
+ const keys = orderBy.map((key) => {
4315
+ const { field, vector } = getScalarColumn(table, key.column);
4316
+ return {
4317
+ ...key,
4318
+ reader: vector && new ColumnReader(vector),
4319
+ utf8: import_apache_arrow8.DataType.isUtf8(valueType(field.type))
4320
+ };
4321
+ });
4322
+ const indexes = Array.from({ length: table.numRows }, (_, index) => index);
4323
+ indexes.sort((left, right) => {
4324
+ signal == null ? void 0 : signal.throwIfAborted();
4325
+ for (const { reader, utf8, direction, nulls } of keys) {
4326
+ const leftValid = reader.isValid(left);
4327
+ const rightValid = reader.isValid(right);
4328
+ if (!leftValid || !rightValid) {
4329
+ if (leftValid === rightValid)
4330
+ continue;
4331
+ return (leftValid ? 1 : -1) * (nulls === "first" ? 1 : -1);
4332
+ }
4333
+ let order;
4334
+ if (utf8) {
4335
+ const [a, start, end] = reader.utf8(left);
4336
+ order = (0, import_utf84.compareUTF8)(a, start, end, ...reader.utf8(right));
4337
+ } else {
4338
+ const a = reader.get(left);
4339
+ const b = reader.get(right);
4340
+ order = a < b ? -1 : a > b ? 1 : Number(Number.isNaN(a)) - Number(Number.isNaN(b));
4341
+ }
4342
+ if (order)
4343
+ return direction === "desc" ? -order : order;
4344
+ }
4345
+ return 0;
4346
+ });
4347
+ return (0, import_arrow.takeArrowTableRows)(table, Int32Array.from(indexes.slice(offset, limit === void 0 ? void 0 : offset + limit)));
4348
+ }
4349
+ function groupArrowTable(table, groupBy, aggregates, options) {
4350
+ var _a2;
4351
+ const keys = groupBy.map((name) => getScalarColumn(table, name));
4352
+ const fields = keys.map(({ field }) => field);
4353
+ const definitions = Object.entries(aggregates);
4354
+ const names = [...groupBy, ...definitions.map(([name]) => name)];
4355
+ if (new Set(names).size !== names.length)
4356
+ throw new Error("Duplicate Arrow grouping output name");
4357
+ const compiled = compileArrowAggregates(aggregates, options);
4358
+ const groups = /* @__PURE__ */ new Map();
4359
+ if (!groupBy.length)
4360
+ groups.set("[]", []);
4361
+ for (let row = 0; groupBy.length && row < table.numRows; row++) {
4362
+ (_a2 = options.signal) == null ? void 0 : _a2.throwIfAborted();
4363
+ const key = JSON.stringify(keys.map(({ vector }) => {
4364
+ const value = vector.get(row);
4365
+ return [typeof value, String(value)];
4366
+ }));
4367
+ const rows2 = groups.get(key);
4368
+ if (rows2)
4369
+ rows2.push(row);
4370
+ else
4371
+ groups.set(key, [row]);
4372
+ }
4373
+ const rows = [...groups.values()];
4374
+ const representatives = rows.flatMap((indexes) => indexes.length ? [indexes[0]] : []);
4375
+ const selected = (0, import_arrow.takeArrowTableRows)(table, Int32Array.from(representatives));
4376
+ const results = rows.map((indexes) => compiled.evaluate(groupBy.length ? (0, import_arrow.takeArrowTableRows)(table, Int32Array.from(indexes)) : table, options));
4377
+ const aggregateFields = getArrowAggregateFields(aggregates, options);
4378
+ const schema = new import_apache_arrow8.Schema([...fields, ...aggregateFields], table.schema.metadata);
4379
+ if (!results.length)
4380
+ return new import_apache_arrow8.Table(schema, []);
4381
+ const columns = [
4382
+ ...fields.map((field) => selected.getChild(field.name)),
4383
+ ...aggregateFields.map((field) => (0, import_apache_arrow8.vectorFromArray)(results.map((result) => result[field.name]), field.type))
4384
+ ];
4385
+ return new import_apache_arrow8.Table(schema, Object.fromEntries(names.map((name, index) => [name, columns[index]])));
4386
+ }
4387
+ function getArrowAggregateFields(aggregates, options) {
4388
+ return Object.entries(aggregates).map(([name, aggregate]) => {
4389
+ const expression = aggregate.expression === void 0 ? void 0 : compileArrowExpression(aggregate.expression, options);
4390
+ const inputType = expression && valueType(expression.outputField.type);
4391
+ const type = aggregate.operation === "COUNT" || aggregate.operation === "SUM" && inputType && import_apache_arrow8.DataType.isInt(inputType) ? new import_apache_arrow8.Int64() : aggregate.operation === "AVG" || !inputType ? new import_apache_arrow8.Float64() : inputType;
4392
+ return new import_apache_arrow8.Field(name, type, aggregate.operation !== "COUNT");
4393
+ });
4394
+ }
4395
+ function getScalarColumn(table, name) {
4396
+ const field = table.schema.fields.find((field2) => field2.name === name);
4397
+ if (!field)
4398
+ throw new Error(`Arrow query column not found: ${name}`);
4399
+ const type = valueType(field.type);
4400
+ if (!(import_apache_arrow8.DataType.isNull(type) || import_apache_arrow8.DataType.isBool(type) || import_apache_arrow8.DataType.isInt(type) || import_apache_arrow8.DataType.isFloat(type) || import_apache_arrow8.DataType.isUtf8(type))) {
4401
+ throw new Error(`Unsupported Arrow relational key type: ${type}`);
4402
+ }
4403
+ return { field, vector: table.getChild(name) };
4404
+ }
4405
+
4406
+ // dist/arrow/query-arrow-table.js
4407
+ function queryArrowTable(source, query = {}) {
4408
+ const { select, where, offset = 0, limit, functions, parameters, signal } = query;
4409
+ signal == null ? void 0 : signal.throwIfAborted();
4410
+ validatePagination(offset, limit);
4411
+ const { union, join, groupBy, aggregates, orderBy } = query;
4412
+ if (union == null ? void 0 : union.length)
4413
+ source = unionArrowTables(source, union);
4414
+ if (join)
4415
+ source = joinArrowTables(source, join, signal);
4416
+ if ((groupBy == null ? void 0 : groupBy.length) || Object.keys(aggregates ?? {}).length || (orderBy == null ? void 0 : orderBy.length)) {
4417
+ source = queryArrowTable(source, { where, functions, parameters, signal });
4418
+ if ((groupBy == null ? void 0 : groupBy.length) || Object.keys(aggregates ?? {}).length) {
4419
+ source = groupArrowTable(source, groupBy ?? [], aggregates ?? {}, {
4420
+ inputSchema: source.schema,
4421
+ functions,
4422
+ signal
4423
+ });
4424
+ }
4425
+ if (orderBy == null ? void 0 : orderBy.length) {
4426
+ source = orderArrowTable(source, orderBy, offset, limit, signal);
4427
+ return queryArrowTable(source, { select, functions, signal });
4428
+ }
4429
+ return queryArrowTable(source, { select, offset, limit, functions, signal });
4430
+ }
4431
+ const plan = compileArrowQuery(source.schema, query);
4432
+ const result = [];
4433
+ for (const batch of source.batches) {
4434
+ if (plan.done())
4435
+ break;
4436
+ for (const output2 of plan.execute(batch))
4437
+ result.push(output2);
4438
+ }
4439
+ return new import_apache_arrow9.Table(plan.schema, result);
4440
+ }
4441
+ async function* queryArrowTableInBatches(input, inputSchema, query = {}) {
4442
+ var _a2, _b;
4443
+ (_a2 = query.signal) == null ? void 0 : _a2.throwIfAborted();
4444
+ validatePagination(query.offset ?? 0, query.limit);
4445
+ const plan = compileArrowQuery(inputSchema, query);
4446
+ if (plan.done())
4447
+ return;
4448
+ for await (const batch of input) {
4449
+ (_b = query.signal) == null ? void 0 : _b.throwIfAborted();
4450
+ if (batch.schema !== inputSchema) {
4451
+ (0, import_arrow2.validateArrowTableSchema)(new import_apache_arrow9.Table(batch.schema, []), inputSchema, {
4452
+ rejectExtraFields: true,
4453
+ schemaName: "query input schema"
4454
+ });
4455
+ }
4456
+ yield* plan.execute(batch, query.emitEmptyBatches);
4457
+ if (plan.done())
4458
+ return;
4459
+ }
4460
+ }
4461
+ function validatePagination(offset, limit) {
4462
+ if (!Number.isSafeInteger(offset) || offset < 0)
4463
+ throw new Error("Invalid Arrow query offset");
4464
+ if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0))
4465
+ throw new Error("Invalid Arrow query limit");
4466
+ }
4467
+ function compileArrowQuery(inputSchema, query) {
4468
+ const { select, where, offset = 0, limit, functions, parameters, signal } = query;
4469
+ const options = { inputSchema, functions };
4470
+ const predicate = where ? "expression" in where ? compileArrowExpression(where.expression, options) : compileArrowPredicate(where, { ...options, parameters }) : void 0;
4471
+ if (predicate && !import_apache_arrow9.DataType.isBool(predicate.outputField.type))
4472
+ throw new Error("Arrow query WHERE requires a Boolean expression");
4473
+ const names = /* @__PURE__ */ new Set();
4474
+ for (const selection of select ?? []) {
4475
+ const name = typeof selection === "string" ? selection : selection.as ?? ("column" in selection ? selection.column : void 0);
4476
+ if (name === void 0)
4477
+ continue;
4478
+ if (names.has(name) || typeof selection !== "string" && selection.as === "")
4479
+ throw new Error(`Invalid or duplicate Arrow query output name: ${name}`);
4480
+ names.add(name);
4481
+ }
4482
+ const projection = select ? select.map((selection, ordinal) => {
4483
+ if (typeof selection !== "string" && ("array" in selection || "expression" in selection)) {
4484
+ const expression = "array" in selection ? compileArrowArray(selection.array, { ...options, type: selection.type }) : compileArrowExpression(selection.expression, options);
4485
+ let name = selection.as;
4486
+ if (name === void 0) {
4487
+ name = `expression_${ordinal + 1}`;
4488
+ while (names.has(name))
4489
+ name += "_";
4490
+ names.add(name);
4491
+ }
4492
+ return { expression, field: expression.outputField.clone({ name }) };
4493
+ }
4494
+ const column = typeof selection === "string" ? selection : selection.column;
4495
+ const index = inputSchema.fields.findIndex((field2) => field2.name === column);
4496
+ if (index < 0)
4497
+ throw new Error(`Arrow query column not found: ${column}`);
4498
+ const field = inputSchema.fields[index];
4499
+ return {
4500
+ index,
4501
+ field: typeof selection === "string" ? field : field.clone({ name: selection.as ?? column })
4502
+ };
4503
+ }) : inputSchema.fields.map((field, index) => ({ field, index }));
4504
+ const schema = select ? new import_apache_arrow9.Schema(projection.map(({ field }) => field), inputSchema.metadata, void 0, inputSchema.metadataVersion) : inputSchema;
4505
+ let skip = offset;
4506
+ let remaining = limit ?? Infinity;
4507
+ function* execute(batch, emitEmpty = false) {
4508
+ signal == null ? void 0 : signal.throwIfAborted();
4509
+ const metadata = (0, import_arrow2.getRecordBatchMetadata)(batch);
4510
+ const mask = predicate == null ? void 0 : predicate.evaluate(batch, { signal });
4511
+ let selected;
4512
+ if (mask) {
4513
+ const indexes = [];
4514
+ for (let row = 0; row < batch.numRows && indexes.length < remaining; row++) {
4515
+ if ((row & 1023) === 0)
4516
+ signal == null ? void 0 : signal.throwIfAborted();
4517
+ if (mask.get(row) !== true)
4518
+ continue;
4519
+ if (skip > 0)
4520
+ skip--;
4521
+ else
4522
+ indexes.push(row);
4523
+ }
4524
+ if (indexes.length === batch.numRows)
4525
+ selected = batch;
4526
+ else if (indexes.length && indexes[indexes.length - 1] - indexes[0] + 1 === indexes.length) {
4527
+ selected = (0, import_arrow2.createRecordBatchWithMetadata)(batch.schema, batch.data.slice(indexes[0], indexes.length), metadata);
4528
+ } else if (indexes.length) {
4529
+ const gathered = (0, import_arrow2.takeArrowTableRows)(new import_apache_arrow9.Table(inputSchema, [batch]), Int32Array.from(indexes));
4530
+ selected = makeQueryBatch(inputSchema, gathered.batches[0].data.children, indexes.length, metadata);
4531
+ }
4532
+ } else {
4533
+ const start2 = Math.min(skip, batch.numRows);
4534
+ skip -= start2;
4535
+ const end = start2 + Math.min(batch.numRows - start2, remaining);
4536
+ if (end > start2)
4537
+ selected = start2 === 0 && end === batch.numRows ? batch : (0, import_arrow2.createRecordBatchWithMetadata)(batch.schema, batch.data.slice(start2, end - start2), metadata);
4538
+ }
4539
+ if (!(selected == null ? void 0 : selected.numRows)) {
4540
+ if (emitEmpty) {
4541
+ const children = schema.fields.map((field) => (0, import_apache_arrow9.makeData)({ type: field.type, nullCount: 0 }));
4542
+ yield makeQueryBatch(schema, children, 0, metadata);
4543
+ }
4544
+ return;
4545
+ }
4546
+ remaining -= selected.numRows;
4547
+ if (!select) {
4548
+ yield selected;
4549
+ return;
4550
+ }
4551
+ const columns = projection.map((item) => "index" in item ? selected.data.children[item.index] : item.expression.evaluate(selected, { signal }));
4552
+ const boundaries = /* @__PURE__ */ new Set([selected.numRows]);
4553
+ for (const column of columns) {
4554
+ if ("children" in column)
4555
+ continue;
4556
+ let end = 0;
4557
+ for (const chunk of column.data) {
4558
+ end += chunk.length;
4559
+ if (end > 0)
4560
+ boundaries.add(end);
4561
+ }
4562
+ }
4563
+ let start = 0;
4564
+ for (const end of [...boundaries].sort((left, right) => left - right)) {
4565
+ const children = columns.map((column) => "children" in column ? start === 0 && end === column.length ? column : column.slice(start, end - start) : column.slice(start, end).data[0]);
4566
+ yield makeQueryBatch(schema, children, end - start, metadata);
4567
+ start = end;
4568
+ }
4569
+ }
4570
+ return { schema, done: () => remaining === 0, execute };
4571
+ }
4572
+ function makeQueryBatch(schema, children, length, metadata) {
4573
+ const data = new import_apache_arrow9.Data(new import_apache_arrow9.Struct(schema.fields), 0, length, 0, void 0, children);
4574
+ return (0, import_arrow2.createRecordBatchWithMetadata)(schema, data, metadata);
4575
+ }
4576
+
4577
+ // dist/arrow/query-arrow-sql.js
4578
+ function queryArrowSQL(sql, tables, options = {}) {
4579
+ const { inputs, orderBy, offset, limit } = parseSQLSelectCompound(sql, options);
4580
+ const execution = { signal: options.signal, functions: options.functions };
4581
+ const [first, ...rest] = inputs.map((input) => executeSelect(input, tables, execution));
4582
+ return queryArrowTable(first, {
4583
+ ...execution,
4584
+ union: rest.map((table) => {
4585
+ if (table.numCols !== first.numCols)
4586
+ throw new Error("Arrow SQL UNION ALL requires the same number of columns in each input");
4587
+ return queryArrowTable(table, {
4588
+ select: table.schema.fields.map((field, index) => ({
4589
+ column: field.name,
4590
+ as: first.schema.fields[index].name
4591
+ })),
4592
+ signal: execution.signal
4593
+ });
4594
+ }),
4595
+ orderBy: planOrder(orderBy),
4596
+ offset,
4597
+ limit
4598
+ });
4599
+ }
4600
+ function planOrder(orderBy) {
4601
+ return orderBy == null ? void 0 : orderBy.map(({ expression, direction, nulls }) => ({
4602
+ column: requireColumn(expression),
4603
+ direction,
4604
+ nulls
4605
+ }));
4606
+ }
4607
+ function executeSelect(statement, tables, execution) {
4608
+ var _a2, _b;
4609
+ const source = getTable(tables, statement.from.name);
4610
+ const leftAlias = statement.from.alias ?? statement.from.name;
4611
+ const [right] = statement.joins;
4612
+ let join;
4613
+ let rightAlias;
4614
+ let rightTable;
4615
+ if (right) {
4616
+ if (statement.joins.length > 1 || right.type !== "inner")
4617
+ throw new Error("Arrow SQL supports one INNER JOIN per SELECT");
4618
+ rightAlias = right.table.alias ?? right.table.name;
4619
+ rightTable = getTable(tables, right.table.name);
4620
+ if (leftAlias === rightAlias)
4621
+ throw new Error("Duplicate Arrow SQL table alias");
4622
+ const { on } = right;
4623
+ if (on.type !== "BinaryExpression" || on.operator !== "==")
4624
+ throw new Error("Arrow SQL JOIN requires equality between two columns");
4625
+ const sides = [on.left, on.right].map((node) => qualifiedColumn(node));
4626
+ const left = sides.find((column) => (column == null ? void 0 : column.qualifier) === leftAlias);
4627
+ const rightColumn = sides.find((column) => (column == null ? void 0 : column.qualifier) === rightAlias);
4628
+ if (!left || !rightColumn)
4629
+ throw new Error("Qualify both Arrow SQL JOIN keys");
4630
+ join = {
4631
+ table: rightTable,
4632
+ left: left.name,
4633
+ right: rightColumn.name,
4634
+ rightPrefix: rightAlias + "."
4635
+ };
4636
+ }
4637
+ const bind2 = (node) => bindColumns(node, (column) => {
4638
+ if (column.qualifier === leftAlias)
4639
+ return column.name;
4640
+ if (column.qualifier && column.qualifier === rightAlias)
4641
+ return column.qualifier + "." + column.name;
4642
+ if (column.qualifier) {
4643
+ if ([source, rightTable].some((table) => table == null ? void 0 : table.schema.fields.some((field) => field.name === column.qualifier)))
4644
+ return void 0;
4645
+ throw new Error(`Unknown Arrow SQL table alias: ${column.qualifier}`);
4646
+ }
4647
+ const onRight = rightTable == null ? void 0 : rightTable.schema.fields.some((field) => field.name === column.name);
4648
+ if (!onRight)
4649
+ return column.name;
4650
+ if (source.schema.fields.some((field) => field.name === column.name))
4651
+ throw new Error(`Ambiguous Arrow SQL column: ${column.name}`);
4652
+ return rightAlias + "." + column.name;
4653
+ });
4654
+ const groupBy = (_a2 = statement.groupBy) == null ? void 0 : _a2.map((expression) => requireColumn(bind2(expression)));
4655
+ const aggregates = /* @__PURE__ */ new Map();
4656
+ const select = (_b = statement.select) == null ? void 0 : _b.map(({ expression, alias }, index) => {
4657
+ const aggregate = planAggregate(expression, bind2);
4658
+ if (aggregate) {
4659
+ const name = alias ?? `aggregate_${index + 1}`;
4660
+ if (aggregates.has(name) || (groupBy == null ? void 0 : groupBy.includes(name)))
4661
+ throw new Error(`Duplicate Arrow SQL aggregate name: ${name}`);
4662
+ aggregates.set(name, aggregate);
4663
+ return name;
4664
+ }
4665
+ const bound = bind2(expression);
4666
+ if (bound.type === "Identifier")
4667
+ return { column: bound.name, as: alias };
4668
+ return { expression: bound, as: alias };
4669
+ });
4670
+ return queryArrowTable(source, {
4671
+ ...execution,
4672
+ join,
4673
+ select,
4674
+ where: statement.where && { expression: bind2(statement.where) },
4675
+ groupBy,
4676
+ aggregates: Object.fromEntries(aggregates)
4677
+ });
4678
+ }
4679
+ function getTable(tables, name) {
4680
+ const table = tables.get(name);
4681
+ if (!table)
4682
+ throw new Error(`Unknown Arrow SQL table: ${name}`);
4683
+ return table;
4684
+ }
4685
+ function qualifiedColumn(node) {
4686
+ if (node.type === "Identifier")
4687
+ return { name: node.name };
4688
+ if (node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && node.property.type === "Identifier")
4689
+ return { name: String(node.property["name"]), qualifier: String(node.object["name"]) };
4690
+ return void 0;
4691
+ }
4692
+ function requireColumn(node) {
4693
+ if (node.type !== "Identifier")
4694
+ throw new Error("Arrow SQL requires a column name in this clause");
4695
+ return node.name;
4696
+ }
4697
+ function bindColumns(node, resolve) {
4698
+ const column = qualifiedColumn(node);
4699
+ const name = column && resolve(column);
4700
+ if (name !== void 0)
4701
+ return { type: "Identifier", name };
4702
+ const bind2 = (child) => bindColumns(child, resolve);
4703
+ switch (node.type) {
4704
+ case "BinaryExpression":
4705
+ case "LogicalExpression":
4706
+ return { ...node, left: bind2(node.left), right: bind2(node.right) };
4707
+ case "UnaryExpression":
4708
+ return { ...node, argument: bind2(node.argument) };
4709
+ case "CallExpression":
4710
+ return { ...node, arguments: node.arguments.map(bind2) };
4711
+ case "MemberExpression": {
4712
+ if (node.computed || node.property.type !== "Identifier")
4713
+ throw new Error("Arrow SQL struct access requires a field identifier");
4714
+ const name2 = String(node.property["name"]);
4715
+ return {
4716
+ type: "CallExpression",
4717
+ callee: { type: "Identifier", name: "STRUCT_EXTRACT" },
4718
+ arguments: [bind2(node.object), { type: "Literal", value: name2, raw: JSON.stringify(name2) }]
4719
+ };
4720
+ }
4721
+ case "ConditionalExpression":
4722
+ return {
4723
+ ...node,
4724
+ test: bind2(node.test),
4725
+ consequent: bind2(node.consequent),
4726
+ alternate: bind2(node.alternate)
4727
+ };
4728
+ default:
4729
+ return node;
4730
+ }
4731
+ }
4732
+ var aggregateOperations = /* @__PURE__ */ new Set([
4733
+ "COUNT",
4734
+ "SUM",
4735
+ "MIN",
4736
+ "MAX",
4737
+ "AVG",
4738
+ "EVERY",
4739
+ "BOOL_AND",
4740
+ "BOOL_OR",
4741
+ "BIT_AND",
4742
+ "BIT_OR",
4743
+ "BIT_XOR"
4744
+ ]);
4745
+ function planAggregate(node, bind2) {
4746
+ if (node.type !== "CallExpression" || node.callee.type !== "Identifier" || !node.sqlFunction)
4747
+ return void 0;
4748
+ const operation = String(node.callee["name"]).toUpperCase();
4749
+ if (!aggregateOperations.has(operation))
4750
+ return void 0;
4751
+ if (node.arguments.length !== 1)
4752
+ throw new Error(`Arrow SQL ${operation} requires one argument`);
4753
+ const argument = node.arguments[0];
4754
+ return operation === "COUNT" && argument.sqlWildcard ? { operation } : { operation, expression: bind2(argument) };
4755
+ }
4756
+
4757
+ // dist/arrow/query-arrow-aggregate-snapshots.js
4758
+ var import_apache_arrow10 = require("apache-arrow");
4759
+ async function* queryArrowAggregateSnapshots(input, inputSchema, options) {
4760
+ var _a2, _b;
4761
+ const { aggregates, groupBy, emitEveryBatches = 1, ...query } = options;
4762
+ (_a2 = query.signal) == null ? void 0 : _a2.throwIfAborted();
4763
+ if (!Number.isSafeInteger(emitEveryBatches) || emitEveryBatches < 1) {
4764
+ throw new Error("emitEveryBatches must be a positive safe integer");
4765
+ }
4766
+ if (!Object.keys(aggregates).length)
4767
+ throw new Error("Expected at least one Arrow aggregate");
4768
+ const groupField = groupBy === void 0 ? void 0 : inputSchema.fields.find((field) => field.name === groupBy);
4769
+ if (groupBy !== void 0 && !groupField)
4770
+ throw new Error(`Unknown Arrow group column: ${groupBy}`);
4771
+ if (groupField && Object.prototype.hasOwnProperty.call(aggregates, groupField.name)) {
4772
+ throw new Error("Duplicate Arrow grouping output name");
4773
+ }
4774
+ const compileOptions = { inputSchema, functions: query.functions };
4775
+ const plan = compileArrowAggregates(aggregates, compileOptions);
4776
+ const grouped = groupField ? plan.createGroupedAccumulator({ type: "Identifier", name: groupField.name }) : void 0;
4777
+ const scalar = grouped ? void 0 : plan.createAccumulator();
4778
+ const aggregateFields = getArrowAggregateFields(aggregates, compileOptions);
4779
+ const outputGroupField = groupField && import_apache_arrow10.DataType.isDictionary(groupField.type) ? groupField.clone({ type: groupField.type.dictionary }) : groupField;
4780
+ const schema = new import_apache_arrow10.Schema(outputGroupField ? [outputGroupField, ...aggregateFields] : aggregateFields, inputSchema.metadata);
4781
+ let rowsProcessed = 0;
4782
+ let batchesSinceEmission = 0;
4783
+ function snapshot(final) {
4784
+ const groups = grouped == null ? void 0 : grouped.result();
4785
+ const rows = groups ? [...groups.values()] : [scalar.result()];
4786
+ const columns = new Map(aggregateFields.map((field) => [
4787
+ field.name,
4788
+ (0, import_apache_arrow10.vectorFromArray)(rows.map((row) => row[field.name]), field.type)
4789
+ ]));
4790
+ if (outputGroupField && groups) {
4791
+ columns.set(outputGroupField.name, (0, import_apache_arrow10.vectorFromArray)([...groups.keys()], outputGroupField.type));
4792
+ }
4793
+ return {
4794
+ table: new import_apache_arrow10.Table(schema, Object.fromEntries(schema.fields.map((field) => [field.name, columns.get(field.name)]))),
4795
+ rowsProcessed,
4796
+ final
4797
+ };
4798
+ }
4799
+ for await (const batch of queryArrowTableInBatches(input, inputSchema, query)) {
4800
+ (grouped ?? scalar).update(batch, { signal: query.signal });
4801
+ rowsProcessed += batch.numRows;
4802
+ if (++batchesSinceEmission === emitEveryBatches) {
4803
+ yield snapshot(false);
4804
+ batchesSinceEmission = 0;
4805
+ }
4806
+ }
4807
+ (_b = query.signal) == null ? void 0 : _b.throwIfAborted();
4808
+ yield snapshot(true);
4809
+ }
4810
+
4811
+ // dist/arrow/replace-arrow-columns.js
4812
+ var import_apache_arrow11 = require("apache-arrow");
4813
+ function replaceArrowColumns(table, replacements, options = {}) {
4814
+ if (!replacements.length)
4815
+ return table;
4816
+ const fields = [...table.schema.fields];
4817
+ const indices = new Map(fields.map((field, index) => [field.name, index]));
4818
+ if (indices.size !== fields.length)
4819
+ throw new Error("Arrow input column names must be unique");
4820
+ const seen = /* @__PURE__ */ new Set();
4821
+ const plan = replacements.map(({ as, expression }) => {
4822
+ const index = indices.get(as);
4823
+ if (index === void 0)
4824
+ throw new Error(`Unknown Arrow replacement column: ${as}`);
4825
+ if (seen.has(as))
4826
+ throw new Error(`Duplicate Arrow replacement column: ${as}`);
4827
+ seen.add(as);
4828
+ return {
4829
+ as,
4830
+ index,
4831
+ compiled: compileArrowExpression(expression, { ...options, inputSchema: table.schema })
4832
+ };
4833
+ });
4834
+ for (const { as, index, compiled } of plan) {
4835
+ fields[index] = compiled.outputField.clone({ name: as });
4836
+ }
4837
+ const schema = new import_apache_arrow11.Schema(fields, table.schema.metadata, void 0, table.schema.metadataVersion);
4838
+ const struct = new import_apache_arrow11.Struct(fields);
4839
+ const batches = table.batches.flatMap((batch) => {
4840
+ const columns = plan.map(({ index, compiled }) => ({ index, vector: compiled.evaluate(batch) }));
4841
+ const boundaries = /* @__PURE__ */ new Set([batch.numRows]);
4842
+ for (const { vector } of columns) {
4843
+ let end = 0;
4844
+ for (const chunk of vector.data) {
4845
+ end += chunk.length;
4846
+ if (end > 0)
4847
+ boundaries.add(end);
4848
+ }
4849
+ }
4850
+ let start = 0;
4851
+ return [...boundaries].sort((a, b) => a - b).map((end) => {
4852
+ const wholeBatch = start === 0 && end === batch.numRows;
4853
+ const source = wholeBatch ? batch.data : batch.data.slice(start, end - start);
4854
+ const children = [...source.children];
4855
+ for (const { index, vector } of columns) {
4856
+ children[index] = (wholeBatch ? vector : vector.slice(start, end)).data[0];
4857
+ }
4858
+ start = end;
4859
+ const data = source.clone(struct, source.offset, source.length, source.nullCount, source.buffers, children);
4860
+ return Object.assign(new import_apache_arrow11.RecordBatch(schema, data), { data });
4861
+ });
4862
+ });
4863
+ return new import_apache_arrow11.Table(schema, batches);
4864
+ }
4865
+ //# sourceMappingURL=index.cjs.map