@uwdata/mosaic-core 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -123,7 +123,6 @@ var MosaicClient = class {
123
123
  * @returns {this}
124
124
  */
125
125
  queryError(error) {
126
- console.error(error);
127
126
  return this;
128
127
  }
129
128
  /**
@@ -147,7 +146,7 @@ var MosaicClient = class {
147
146
  /**
148
147
  * Requests a client update.
149
148
  * For example to (re-)render an interface component.
150
- *
149
+ *
151
150
  * @returns {this | Promise<any>}
152
151
  */
153
152
  update() {
@@ -211,16 +210,24 @@ function __await(v2) {
211
210
  function __asyncGenerator(thisArg, _arguments, generator) {
212
211
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
213
212
  var g2 = generator.apply(thisArg, _arguments || []), i, q2 = [];
214
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
213
+ return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
215
214
  return this;
216
215
  }, i;
217
- function verb(n) {
218
- if (g2[n]) i[n] = function(v2) {
219
- return new Promise(function(a2, b2) {
220
- q2.push([n, v2, a2, b2]) > 1 || resume(n, v2);
221
- });
216
+ function awaitReturn(f2) {
217
+ return function(v2) {
218
+ return Promise.resolve(v2).then(f2, reject);
222
219
  };
223
220
  }
221
+ function verb(n, f2) {
222
+ if (g2[n]) {
223
+ i[n] = function(v2) {
224
+ return new Promise(function(a2, b2) {
225
+ q2.push([n, v2, a2, b2]) > 1 || resume(n, v2);
226
+ });
227
+ };
228
+ if (f2) i[n] = f2(i[n]);
229
+ }
230
+ }
224
231
  function resume(n, v2) {
225
232
  try {
226
233
  step(g2[n](v2));
@@ -840,26 +847,26 @@ var IntervalUnit;
840
847
  IntervalUnit4[IntervalUnit4["MONTH_DAY_NANO"] = 2] = "MONTH_DAY_NANO";
841
848
  })(IntervalUnit || (IntervalUnit = {}));
842
849
 
843
- // ../../node_modules/flatbuffers/mjs/constants.js
850
+ // ../../node_modules/apache-arrow/node_modules/flatbuffers/mjs/constants.js
844
851
  var SIZEOF_SHORT = 2;
845
852
  var SIZEOF_INT = 4;
846
853
  var FILE_IDENTIFIER_LENGTH = 4;
847
854
  var SIZE_PREFIX_LENGTH = 4;
848
855
 
849
- // ../../node_modules/flatbuffers/mjs/utils.js
856
+ // ../../node_modules/apache-arrow/node_modules/flatbuffers/mjs/utils.js
850
857
  var int32 = new Int32Array(2);
851
858
  var float32 = new Float32Array(int32.buffer);
852
859
  var float64 = new Float64Array(int32.buffer);
853
860
  var isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
854
861
 
855
- // ../../node_modules/flatbuffers/mjs/encoding.js
862
+ // ../../node_modules/apache-arrow/node_modules/flatbuffers/mjs/encoding.js
856
863
  var Encoding;
857
- (function(Encoding2) {
858
- Encoding2[Encoding2["UTF8_BYTES"] = 1] = "UTF8_BYTES";
859
- Encoding2[Encoding2["UTF16_STRING"] = 2] = "UTF16_STRING";
864
+ (function(Encoding3) {
865
+ Encoding3[Encoding3["UTF8_BYTES"] = 1] = "UTF8_BYTES";
866
+ Encoding3[Encoding3["UTF16_STRING"] = 2] = "UTF16_STRING";
860
867
  })(Encoding || (Encoding = {}));
861
868
 
862
- // ../../node_modules/flatbuffers/mjs/byte-buffer.js
869
+ // ../../node_modules/apache-arrow/node_modules/flatbuffers/mjs/byte-buffer.js
863
870
  var ByteBuffer = class _ByteBuffer {
864
871
  /**
865
872
  * Create a new ByteBuffer with a given array of bytes (`Uint8Array`)
@@ -1103,7 +1110,7 @@ var ByteBuffer = class _ByteBuffer {
1103
1110
  }
1104
1111
  };
1105
1112
 
1106
- // ../../node_modules/flatbuffers/mjs/builder.js
1113
+ // ../../node_modules/apache-arrow/node_modules/flatbuffers/mjs/builder.js
1107
1114
  var Builder = class _Builder {
1108
1115
  /**
1109
1116
  * Create a FlatBufferBuilder.
@@ -1543,9 +1550,22 @@ var Builder = class _Builder {
1543
1550
  this.addInt8(0);
1544
1551
  this.startVector(1, utf8.length, 1);
1545
1552
  this.bb.setPosition(this.space -= utf8.length);
1546
- for (let i = 0, offset = this.space, bytes = this.bb.bytes(); i < utf8.length; i++) {
1547
- bytes[offset++] = utf8[i];
1553
+ this.bb.bytes().set(utf8, this.space);
1554
+ return this.endVector();
1555
+ }
1556
+ /**
1557
+ * Create a byte vector.
1558
+ *
1559
+ * @param v The bytes to add
1560
+ * @returns The offset in the buffer where the byte vector starts
1561
+ */
1562
+ createByteVector(v2) {
1563
+ if (v2 === null || v2 === void 0) {
1564
+ return 0;
1548
1565
  }
1566
+ this.startVector(1, v2.length, 1);
1567
+ this.bb.setPosition(this.space -= v2.length);
1568
+ this.bb.bytes().set(v2, this.space);
1549
1569
  return this.endVector();
1550
1570
  }
1551
1571
  /**
@@ -3148,9 +3168,9 @@ var BufferType;
3148
3168
  // ../../node_modules/apache-arrow/util/vector.mjs
3149
3169
  var vector_exports = {};
3150
3170
  __export(vector_exports, {
3151
- clampIndex: () => clampIndex,
3152
3171
  clampRange: () => clampRange,
3153
- createElementComparator: () => createElementComparator
3172
+ createElementComparator: () => createElementComparator,
3173
+ wrapIndex: () => wrapIndex
3154
3174
  });
3155
3175
 
3156
3176
  // ../../node_modules/apache-arrow/util/pretty.mjs
@@ -3191,9 +3211,23 @@ var bn_exports = {};
3191
3211
  __export(bn_exports, {
3192
3212
  BN: () => BN,
3193
3213
  bigNumToBigInt: () => bigNumToBigInt,
3214
+ bigNumToNumber: () => bigNumToNumber,
3194
3215
  bigNumToString: () => bigNumToString,
3195
3216
  isArrowBigNumSymbol: () => isArrowBigNumSymbol
3196
3217
  });
3218
+
3219
+ // ../../node_modules/apache-arrow/util/bigint.mjs
3220
+ function bigIntToNumber(number) {
3221
+ if (typeof number === "bigint" && (number < Number.MIN_SAFE_INTEGER || number > Number.MAX_SAFE_INTEGER)) {
3222
+ throw new TypeError(`${number} is not safe to convert to a number.`);
3223
+ }
3224
+ return Number(number);
3225
+ }
3226
+ function divideBigInts(number, divisor) {
3227
+ return bigIntToNumber(number / divisor) + bigIntToNumber(number % divisor) / bigIntToNumber(divisor);
3228
+ }
3229
+
3230
+ // ../../node_modules/apache-arrow/util/bn.mjs
3197
3231
  var isArrowBigNumSymbol = Symbol.for("isArrowBigNum");
3198
3232
  function BigNum(x3, ...xs) {
3199
3233
  if (xs.length === 0) {
@@ -3205,8 +3239,8 @@ BigNum.prototype[isArrowBigNumSymbol] = true;
3205
3239
  BigNum.prototype.toJSON = function() {
3206
3240
  return `"${bigNumToString(this)}"`;
3207
3241
  };
3208
- BigNum.prototype.valueOf = function() {
3209
- return bigNumToNumber(this);
3242
+ BigNum.prototype.valueOf = function(scale) {
3243
+ return bigNumToNumber(this, scale);
3210
3244
  };
3211
3245
  BigNum.prototype.toString = function() {
3212
3246
  return bigNumToString(this);
@@ -3237,25 +3271,34 @@ Object.setPrototypeOf(DecimalBigNum.prototype, Object.create(Uint32Array.prototy
3237
3271
  Object.assign(SignedBigNum.prototype, BigNum.prototype, { "constructor": SignedBigNum, "signed": true, "TypedArray": Int32Array, "BigIntArray": BigInt64Array });
3238
3272
  Object.assign(UnsignedBigNum.prototype, BigNum.prototype, { "constructor": UnsignedBigNum, "signed": false, "TypedArray": Uint32Array, "BigIntArray": BigUint64Array });
3239
3273
  Object.assign(DecimalBigNum.prototype, BigNum.prototype, { "constructor": DecimalBigNum, "signed": true, "TypedArray": Uint32Array, "BigIntArray": BigUint64Array });
3240
- function bigNumToNumber(bn) {
3241
- const { buffer, byteOffset, length: length2, "signed": signed } = bn;
3242
- const words = new BigUint64Array(buffer, byteOffset, length2);
3274
+ var TWO_TO_THE_64 = BigInt(4294967296) * BigInt(4294967296);
3275
+ var TWO_TO_THE_64_MINUS_1 = TWO_TO_THE_64 - BigInt(1);
3276
+ function bigNumToNumber(bn, scale) {
3277
+ const { buffer, byteOffset, byteLength, "signed": signed } = bn;
3278
+ const words = new BigUint64Array(buffer, byteOffset, byteLength / 8);
3243
3279
  const negative = signed && words.at(-1) & BigInt(1) << BigInt(63);
3244
- let number = negative ? BigInt(1) : BigInt(0);
3245
- let i = BigInt(0);
3246
- if (!negative) {
3280
+ let number = BigInt(0);
3281
+ let i = 0;
3282
+ if (negative) {
3247
3283
  for (const word of words) {
3248
- number += word * (BigInt(1) << BigInt(32) * i++);
3284
+ number |= (word ^ TWO_TO_THE_64_MINUS_1) * (BigInt(1) << BigInt(64 * i++));
3249
3285
  }
3286
+ number *= BigInt(-1);
3287
+ number -= BigInt(1);
3250
3288
  } else {
3251
3289
  for (const word of words) {
3252
- number += ~word * (BigInt(1) << BigInt(32) * i++);
3290
+ number |= word * (BigInt(1) << BigInt(64 * i++));
3253
3291
  }
3254
- number *= BigInt(-1);
3255
3292
  }
3256
- return number;
3293
+ if (typeof scale === "number") {
3294
+ const denominator = BigInt(Math.pow(10, scale));
3295
+ const quotient = number / denominator;
3296
+ const remainder = number % denominator;
3297
+ return bigIntToNumber(quotient) + bigIntToNumber(remainder) / bigIntToNumber(denominator);
3298
+ }
3299
+ return bigIntToNumber(number);
3257
3300
  }
3258
- var bigNumToString = (a2) => {
3301
+ function bigNumToString(a2) {
3259
3302
  if (a2.byteLength === 8) {
3260
3303
  const bigIntArray = new a2["BigIntArray"](a2.buffer, a2.byteOffset, 1);
3261
3304
  return `${bigIntArray[0]}`;
@@ -3278,15 +3321,15 @@ var bigNumToString = (a2) => {
3278
3321
  }
3279
3322
  const negated = unsignedBigNumToString(array);
3280
3323
  return `-${negated}`;
3281
- };
3282
- var bigNumToBigInt = (a2) => {
3324
+ }
3325
+ function bigNumToBigInt(a2) {
3283
3326
  if (a2.byteLength === 8) {
3284
3327
  const bigIntArray = new a2["BigIntArray"](a2.buffer, a2.byteOffset, 1);
3285
3328
  return bigIntArray[0];
3286
3329
  } else {
3287
3330
  return bigNumToString(a2);
3288
3331
  }
3289
- };
3332
+ }
3290
3333
  function unsignedBigNumToString(a2) {
3291
3334
  let digits = "";
3292
3335
  const base64 = new Uint32Array(2);
@@ -3343,14 +3386,6 @@ var BN = class _BN {
3343
3386
  }
3344
3387
  };
3345
3388
 
3346
- // ../../node_modules/apache-arrow/util/bigint.mjs
3347
- function bigIntToNumber(number) {
3348
- if (typeof number === "bigint" && (number < Number.MIN_SAFE_INTEGER || number > Number.MAX_SAFE_INTEGER)) {
3349
- throw new TypeError(`${number} is not safe to convert to a number.`);
3350
- }
3351
- return Number(number);
3352
- }
3353
-
3354
3389
  // ../../node_modules/apache-arrow/type.mjs
3355
3390
  var _a;
3356
3391
  var _b;
@@ -3725,11 +3760,13 @@ var Date_ = class extends DataType {
3725
3760
  toString() {
3726
3761
  return `Date${(this.unit + 1) * 32}<${DateUnit[this.unit]}>`;
3727
3762
  }
3763
+ get ArrayType() {
3764
+ return this.unit === DateUnit.DAY ? Int32Array : BigInt64Array;
3765
+ }
3728
3766
  };
3729
3767
  _l = Symbol.toStringTag;
3730
3768
  Date_[_l] = ((proto) => {
3731
3769
  proto.unit = null;
3732
- proto.ArrayType = Int32Array;
3733
3770
  return proto[Symbol.toStringTag] = "Date";
3734
3771
  })(Date_.prototype);
3735
3772
  var Time_ = class extends DataType {
@@ -3771,7 +3808,7 @@ _o = Symbol.toStringTag;
3771
3808
  Timestamp_[_o] = ((proto) => {
3772
3809
  proto.unit = null;
3773
3810
  proto.timezone = null;
3774
- proto.ArrayType = Int32Array;
3811
+ proto.ArrayType = BigInt64Array;
3775
3812
  return proto[Symbol.toStringTag] = "Timestamp";
3776
3813
  })(Timestamp_.prototype);
3777
3814
  var Interval_ = class extends DataType {
@@ -3976,10 +4013,6 @@ function strideForType(type) {
3976
4013
  switch (type.typeId) {
3977
4014
  case Type2.Decimal:
3978
4015
  return type.bitWidth / 32;
3979
- case Type2.Timestamp:
3980
- return 2;
3981
- case Type2.Date:
3982
- return 1 + t.unit;
3983
4016
  case Type2.Interval:
3984
4017
  return 1 + t.unit;
3985
4018
  case Type2.FixedSizeList:
@@ -4446,19 +4479,7 @@ function wrapSet(fn) {
4446
4479
  };
4447
4480
  }
4448
4481
  var setEpochMsToDays = (data, index, epochMs) => {
4449
- data[index] = Math.trunc(epochMs / 864e5);
4450
- };
4451
- var setEpochMsToMillisecondsLong = (data, index, epochMs) => {
4452
- data[index] = Math.trunc(epochMs % 4294967296);
4453
- data[index + 1] = Math.trunc(epochMs / 4294967296);
4454
- };
4455
- var setEpochMsToMicrosecondsLong = (data, index, epochMs) => {
4456
- data[index] = Math.trunc(epochMs * 1e3 % 4294967296);
4457
- data[index + 1] = Math.trunc(epochMs * 1e3 / 4294967296);
4458
- };
4459
- var setEpochMsToNanosecondsLong = (data, index, epochMs) => {
4460
- data[index] = Math.trunc(epochMs * 1e6 % 4294967296);
4461
- data[index + 1] = Math.trunc(epochMs * 1e6 / 4294967296);
4482
+ data[index] = Math.floor(epochMs / 864e5);
4462
4483
  };
4463
4484
  var setVariableWidthBytes = (values, valueOffsets, index, value) => {
4464
4485
  if (index + 1 < valueOffsets.length) {
@@ -4493,7 +4514,7 @@ var setDateDay = ({ values }, index, value) => {
4493
4514
  setEpochMsToDays(values, index, value.valueOf());
4494
4515
  };
4495
4516
  var setDateMillisecond = ({ values }, index, value) => {
4496
- setEpochMsToMillisecondsLong(values, index * 2, value.valueOf());
4517
+ values[index] = BigInt(value);
4497
4518
  };
4498
4519
  var setFixedSizeBinary = ({ stride, values }, index, value) => {
4499
4520
  values.set(value.subarray(0, stride), stride * index);
@@ -4503,10 +4524,18 @@ var setUtf8 = ({ values, valueOffsets }, index, value) => setVariableWidthBytes(
4503
4524
  var setDate = (data, index, value) => {
4504
4525
  data.type.unit === DateUnit.DAY ? setDateDay(data, index, value) : setDateMillisecond(data, index, value);
4505
4526
  };
4506
- var setTimestampSecond = ({ values }, index, value) => setEpochMsToMillisecondsLong(values, index * 2, value / 1e3);
4507
- var setTimestampMillisecond = ({ values }, index, value) => setEpochMsToMillisecondsLong(values, index * 2, value);
4508
- var setTimestampMicrosecond = ({ values }, index, value) => setEpochMsToMicrosecondsLong(values, index * 2, value);
4509
- var setTimestampNanosecond = ({ values }, index, value) => setEpochMsToNanosecondsLong(values, index * 2, value);
4527
+ var setTimestampSecond = ({ values }, index, value) => {
4528
+ values[index] = BigInt(value / 1e3);
4529
+ };
4530
+ var setTimestampMillisecond = ({ values }, index, value) => {
4531
+ values[index] = BigInt(value);
4532
+ };
4533
+ var setTimestampMicrosecond = ({ values }, index, value) => {
4534
+ values[index] = BigInt(value * 1e3);
4535
+ };
4536
+ var setTimestampNanosecond = ({ values }, index, value) => {
4537
+ values[index] = BigInt(value * 1e6);
4538
+ };
4510
4539
  var setTimestamp = (data, index, value) => {
4511
4540
  switch (data.type.unit) {
4512
4541
  case TimeUnit.SECOND:
@@ -4811,12 +4840,6 @@ function wrapGet(fn) {
4811
4840
  return (data, _1) => data.getValid(_1) ? fn(data, _1) : null;
4812
4841
  }
4813
4842
  var epochDaysToMs = (data, index) => 864e5 * data[index];
4814
- var epochMillisecondsLongToMs = (data, index) => 4294967296 * data[index + 1] + (data[index] >>> 0);
4815
- var epochMicrosecondsLongToMs = (data, index) => 4294967296 * (data[index + 1] / 1e3) + (data[index] >>> 0) / 1e3;
4816
- var epochNanosecondsLongToMs = (data, index) => 4294967296 * (data[index + 1] / 1e6) + (data[index] >>> 0) / 1e6;
4817
- var epochMillisecondsToDate = (epochMs) => new Date(epochMs);
4818
- var epochDaysToDate = (data, index) => epochMillisecondsToDate(epochDaysToMs(data, index));
4819
- var epochMillisecondsLongToDate = (data, index) => epochMillisecondsToDate(epochMillisecondsLongToMs(data, index));
4820
4843
  var getNull = (_data, _index) => null;
4821
4844
  var getVariableWidthBytes = (values, valueOffsets, index) => {
4822
4845
  if (index + 1 >= valueOffsets.length) {
@@ -4831,8 +4854,8 @@ var getBool = ({ offset, values }, index) => {
4831
4854
  const byte = values[idx >> 3];
4832
4855
  return (byte & 1 << idx % 8) !== 0;
4833
4856
  };
4834
- var getDateDay = ({ values }, index) => epochDaysToDate(values, index);
4835
- var getDateMillisecond = ({ values }, index) => epochMillisecondsLongToDate(values, index * 2);
4857
+ var getDateDay = ({ values }, index) => epochDaysToMs(values, index);
4858
+ var getDateMillisecond = ({ values }, index) => bigIntToNumber(values[index]);
4836
4859
  var getNumeric = ({ stride, values }, index) => values[stride * index];
4837
4860
  var getFloat16 = ({ stride, values }, index) => uint16ToFloat64(values[stride * index]);
4838
4861
  var getBigInts = ({ values }, index) => values[index];
@@ -4845,10 +4868,10 @@ var getUtf8 = ({ values, valueOffsets }, index) => {
4845
4868
  var getInt = ({ values }, index) => values[index];
4846
4869
  var getFloat = ({ type, values }, index) => type.precision !== Precision.HALF ? values[index] : uint16ToFloat64(values[index]);
4847
4870
  var getDate = (data, index) => data.type.unit === DateUnit.DAY ? getDateDay(data, index) : getDateMillisecond(data, index);
4848
- var getTimestampSecond = ({ values }, index) => 1e3 * epochMillisecondsLongToMs(values, index * 2);
4849
- var getTimestampMillisecond = ({ values }, index) => epochMillisecondsLongToMs(values, index * 2);
4850
- var getTimestampMicrosecond = ({ values }, index) => epochMicrosecondsLongToMs(values, index * 2);
4851
- var getTimestampNanosecond = ({ values }, index) => epochNanosecondsLongToMs(values, index * 2);
4871
+ var getTimestampSecond = ({ values }, index) => 1e3 * bigIntToNumber(values[index]);
4872
+ var getTimestampMillisecond = ({ values }, index) => bigIntToNumber(values[index]);
4873
+ var getTimestampMicrosecond = ({ values }, index) => divideBigInts(values[index], BigInt(1e3));
4874
+ var getTimestampNanosecond = ({ values }, index) => divideBigInts(values[index], BigInt(1e6));
4852
4875
  var getTimestamp = (data, index) => {
4853
4876
  switch (data.type.unit) {
4854
4877
  case TimeUnit.SECOND:
@@ -4997,12 +5020,18 @@ var instance2 = new GetVisitor();
4997
5020
  // ../../node_modules/apache-arrow/row/map.mjs
4998
5021
  var kKeys = Symbol.for("keys");
4999
5022
  var kVals = Symbol.for("vals");
5023
+ var kKeysAsStrings = Symbol.for("kKeysAsStrings");
5024
+ var _kKeysAsStrings = Symbol.for("_kKeysAsStrings");
5000
5025
  var MapRow = class {
5001
5026
  constructor(slice) {
5002
5027
  this[kKeys] = new Vector([slice.children[0]]).memoize();
5003
5028
  this[kVals] = slice.children[1];
5004
5029
  return new Proxy(this, new MapRowProxyHandler());
5005
5030
  }
5031
+ /** @ignore */
5032
+ get [kKeysAsStrings]() {
5033
+ return this[_kKeysAsStrings] || (this[_kKeysAsStrings] = Array.from(this[kKeys].toArray(), String));
5034
+ }
5006
5035
  [Symbol.iterator]() {
5007
5036
  return new MapRowIterator(this[kKeys], this[kVals]);
5008
5037
  }
@@ -5064,13 +5093,13 @@ var MapRowProxyHandler = class {
5064
5093
  return true;
5065
5094
  }
5066
5095
  ownKeys(row) {
5067
- return row[kKeys].toArray().map(String);
5096
+ return row[kKeysAsStrings];
5068
5097
  }
5069
5098
  has(row, key) {
5070
- return row[kKeys].includes(key);
5099
+ return row[kKeysAsStrings].includes(key);
5071
5100
  }
5072
5101
  getOwnPropertyDescriptor(row, key) {
5073
- const idx = row[kKeys].indexOf(key);
5102
+ const idx = row[kKeysAsStrings].indexOf(key);
5074
5103
  if (idx !== -1) {
5075
5104
  return { writable: true, enumerable: true, configurable: true };
5076
5105
  }
@@ -5080,7 +5109,7 @@ var MapRowProxyHandler = class {
5080
5109
  if (Reflect.has(row, key)) {
5081
5110
  return row[key];
5082
5111
  }
5083
- const idx = row[kKeys].indexOf(key);
5112
+ const idx = row[kKeysAsStrings].indexOf(key);
5084
5113
  if (idx !== -1) {
5085
5114
  const val = instance2.visit(Reflect.get(row, kVals), idx);
5086
5115
  Reflect.set(row, key, val);
@@ -5088,7 +5117,7 @@ var MapRowProxyHandler = class {
5088
5117
  }
5089
5118
  }
5090
5119
  set(row, key, val) {
5091
- const idx = row[kKeys].indexOf(key);
5120
+ const idx = row[kKeysAsStrings].indexOf(key);
5092
5121
  if (idx !== -1) {
5093
5122
  instance.visit(Reflect.get(row, kVals), idx, val);
5094
5123
  return Reflect.set(row, key, val);
@@ -5101,15 +5130,11 @@ var MapRowProxyHandler = class {
5101
5130
  Object.defineProperties(MapRow.prototype, {
5102
5131
  [Symbol.toStringTag]: { enumerable: false, configurable: false, value: "Row" },
5103
5132
  [kKeys]: { writable: true, enumerable: false, configurable: false, value: null },
5104
- [kVals]: { writable: true, enumerable: false, configurable: false, value: null }
5133
+ [kVals]: { writable: true, enumerable: false, configurable: false, value: null },
5134
+ [_kKeysAsStrings]: { writable: true, enumerable: false, configurable: false, value: null }
5105
5135
  });
5106
5136
 
5107
5137
  // ../../node_modules/apache-arrow/util/vector.mjs
5108
- function clampIndex(source, index, then) {
5109
- const length2 = source.length;
5110
- const adjust = index > -1 ? index : length2 + index % length2;
5111
- return then ? then(source, adjust) : adjust;
5112
- }
5113
5138
  var tmp;
5114
5139
  function clampRange(source, begin, end, then) {
5115
5140
  const { length: len = 0 } = source;
@@ -5121,6 +5146,7 @@ function clampRange(source, begin, end, then) {
5121
5146
  rhs > len && (rhs = len);
5122
5147
  return then ? then(source, lhs, rhs) : [lhs, rhs];
5123
5148
  }
5149
+ var wrapIndex = (index, len) => index < 0 ? len + index : index;
5124
5150
  var isNaNFast = (value) => value !== value;
5125
5151
  function createElementComparator(search) {
5126
5152
  const typeofSearch = typeof search;
@@ -5409,7 +5435,10 @@ var Data = class _Data {
5409
5435
  let nullCount = this._nullCount;
5410
5436
  let nullBitmap;
5411
5437
  if (nullCount <= kUnknownNullCount && (nullBitmap = this.nullBitmap)) {
5412
- this._nullCount = nullCount = this.length - popcnt_bit_range(nullBitmap, this.offset, this.offset + this.length);
5438
+ this._nullCount = nullCount = nullBitmap.length === 0 ? (
5439
+ // no null bitmap, so all values are valid
5440
+ 0
5441
+ ) : this.length - popcnt_bit_range(nullBitmap, this.offset, this.offset + this.length);
5413
5442
  }
5414
5443
  return nullCount;
5415
5444
  }
@@ -5471,12 +5500,14 @@ var Data = class _Data {
5471
5500
  nullBitmap = new Uint8Array((offset + length2 + 63 & ~63) >> 3).fill(255);
5472
5501
  if (this.nullCount > 0) {
5473
5502
  nullBitmap.set(truncateBitmap(offset, length2, this.nullBitmap), 0);
5503
+ Object.assign(this, { nullBitmap });
5504
+ } else {
5505
+ Object.assign(this, { nullBitmap, _nullCount: 0 });
5474
5506
  }
5475
- Object.assign(this, { nullBitmap, _nullCount: -1 });
5476
5507
  }
5477
5508
  const byte = nullBitmap[byteOffset];
5478
5509
  prev = (byte & mask) !== 0;
5479
- value ? nullBitmap[byteOffset] = byte | mask : nullBitmap[byteOffset] = byte & ~mask;
5510
+ nullBitmap[byteOffset] = value ? byte | mask : byte & ~mask;
5480
5511
  }
5481
5512
  if (prev !== !!value) {
5482
5513
  this._nullCount = this.nullCount + (value ? -1 : 1);
@@ -5917,7 +5948,9 @@ var IteratorVisitor = class extends Visitor {
5917
5948
  };
5918
5949
  function vectorIterator(vector) {
5919
5950
  const { type } = vector;
5920
- if (vector.nullCount === 0 && vector.stride === 1 && (type.typeId === Type2.Timestamp || type instanceof Int_ && type.bitWidth !== 64 || type instanceof Time_ && type.bitWidth !== 64 || type instanceof Float && type.precision !== Precision.HALF)) {
5951
+ if (vector.nullCount === 0 && vector.stride === 1 && // Don't defer to native iterator for timestamps since Numbers are expected
5952
+ // (DataType.isTimestamp(type)) && type.unit === TimeUnit.MILLISECOND ||
5953
+ (DataType.isInt(type) && type.bitWidth !== 64 || DataType.isTime(type) && type.bitWidth !== 64 || DataType.isFloat(type) && type.precision !== Precision.HALF)) {
5921
5954
  return new ChunkedIterator(vector.data.length, (chunkIndex) => {
5922
5955
  const data = vector.data[chunkIndex];
5923
5956
  return data.values.subarray(0, data.length)[Symbol.iterator]();
@@ -6091,6 +6124,13 @@ var Vector = class _Vector {
6091
6124
  get(index) {
6092
6125
  return null;
6093
6126
  }
6127
+ /**
6128
+ * Get an element value by position.
6129
+ * @param index The index of the element to read. A negative index will count back from the last element.
6130
+ */
6131
+ at(index) {
6132
+ return this.get(wrapIndex(index, this.length));
6133
+ }
6094
6134
  /**
6095
6135
  * Set an element value by position.
6096
6136
  * @param index The index of the element to write.
@@ -7368,8 +7408,8 @@ var AsyncByteStreamSource = class {
7368
7408
  return (yield this.next(size, "peek")).value;
7369
7409
  });
7370
7410
  }
7371
- next(size, cmd = "read") {
7372
- return __awaiter(this, void 0, void 0, function* () {
7411
+ next(size_1) {
7412
+ return __awaiter(this, arguments, void 0, function* (size, cmd = "read") {
7373
7413
  return yield this.source.next({ cmd, size });
7374
7414
  });
7375
7415
  }
@@ -8946,6 +8986,14 @@ var Table = class _Table {
8946
8986
  get(index) {
8947
8987
  return null;
8948
8988
  }
8989
+ /**
8990
+ * Get an element value by position.
8991
+ * @param index The index of the element to read. A negative index will count back from the last element.
8992
+ */
8993
+ // @ts-ignore
8994
+ at(index) {
8995
+ return this.get(wrapIndex(index, this.numRows));
8996
+ }
8949
8997
  /**
8950
8998
  * Set an element value by position.
8951
8999
  *
@@ -9183,7 +9231,7 @@ var RecordBatch2 = class _RecordBatch {
9183
9231
  return this.data.nullCount;
9184
9232
  }
9185
9233
  /**
9186
- * Check whether an element is null.
9234
+ * Check whether an row is null.
9187
9235
  * @param index The index at which to read the validity bitmap.
9188
9236
  */
9189
9237
  isValid(index) {
@@ -9191,14 +9239,21 @@ var RecordBatch2 = class _RecordBatch {
9191
9239
  }
9192
9240
  /**
9193
9241
  * Get a row by position.
9194
- * @param index The index of the element to read.
9242
+ * @param index The index of the row to read.
9195
9243
  */
9196
9244
  get(index) {
9197
9245
  return instance2.visit(this.data, index);
9198
9246
  }
9247
+ /**
9248
+ * Get a row value by position.
9249
+ * @param index The index of the row to read. A negative index will count back from the last row.
9250
+ */
9251
+ at(index) {
9252
+ return this.get(wrapIndex(index, this.numRows));
9253
+ }
9199
9254
  /**
9200
9255
  * Set a row by position.
9201
- * @param index The index of the element to write.
9256
+ * @param index The index of the row to write.
9202
9257
  * @param value The value to set.
9203
9258
  */
9204
9259
  set(index, value) {
@@ -9235,7 +9290,7 @@ var RecordBatch2 = class _RecordBatch {
9235
9290
  /**
9236
9291
  * Return a zero-copy sub-section of this RecordBatch.
9237
9292
  * @param start The beginning of the specified portion of the RecordBatch.
9238
- * @param end The end of the specified portion of the RecordBatch. This is exclusive of the element at the index 'end'.
9293
+ * @param end The end of the specified portion of the RecordBatch. This is exclusive of the row at the index 'end'.
9239
9294
  */
9240
9295
  slice(begin, end) {
9241
9296
  const [slice] = new Vector([this.data]).slice(begin, end).data;
@@ -10323,8 +10378,8 @@ var AsyncMessageReader = class {
10323
10378
  );
10324
10379
  });
10325
10380
  }
10326
- readSchema(throwIfNull = false) {
10327
- return __awaiter(this, void 0, void 0, function* () {
10381
+ readSchema() {
10382
+ return __awaiter(this, arguments, void 0, function* (throwIfNull = false) {
10328
10383
  const type = MessageHeader.Schema;
10329
10384
  const message = yield this.readMessage(type);
10330
10385
  const schema = message === null || message === void 0 ? void 0 : message.header();
@@ -10572,8 +10627,8 @@ var AsyncRecordBatchStreamReader = class extends RecordBatchReader {
10572
10627
  this._impl = _impl;
10573
10628
  }
10574
10629
  readAll() {
10575
- var _a9, e_1, _b3, _c3;
10576
10630
  return __awaiter(this, void 0, void 0, function* () {
10631
+ var _a9, e_1, _b3, _c3;
10577
10632
  const batches = new Array();
10578
10633
  try {
10579
10634
  for (var _d3 = true, _e3 = __asyncValues(this), _f3; _f3 = yield _e3.next(), _a9 = _f3.done, !_a9; _d3 = true) {
@@ -10946,8 +11001,8 @@ var AsyncRecordBatchFileReaderImpl = class extends AsyncRecordBatchStreamReaderI
10946
11001
  });
10947
11002
  }
10948
11003
  readRecordBatch(index) {
10949
- var _a9;
10950
11004
  return __awaiter(this, void 0, void 0, function* () {
11005
+ var _a9;
10951
11006
  if (this.closed) {
10952
11007
  return null;
10953
11008
  }
@@ -10968,8 +11023,8 @@ var AsyncRecordBatchFileReaderImpl = class extends AsyncRecordBatchStreamReaderI
10968
11023
  });
10969
11024
  }
10970
11025
  _readDictionaryBatch(index) {
10971
- var _a9;
10972
11026
  return __awaiter(this, void 0, void 0, function* () {
11027
+ var _a9;
10973
11028
  const block = (_a9 = this._footer) === null || _a9 === void 0 ? void 0 : _a9.getDictionaryBatch(index);
10974
11029
  if (block && (yield this._handle.seek(block.offset))) {
10975
11030
  const message = yield this._reader.readMessage(MessageHeader.DictionaryBatch);
@@ -11474,9 +11529,9 @@ function writeAll(writer, input) {
11474
11529
  return writer.finish();
11475
11530
  }
11476
11531
  function writeAllAsync(writer, batches) {
11477
- var _a9, batches_1, batches_1_1;
11478
- var _b3, e_1, _c3, _d3;
11479
11532
  return __awaiter(this, void 0, void 0, function* () {
11533
+ var _a9, batches_1, batches_1_1;
11534
+ var _b3, e_1, _c3, _d3;
11480
11535
  try {
11481
11536
  for (_a9 = true, batches_1 = __asyncValues(batches); batches_1_1 = yield batches_1.next(), _b3 = batches_1_1.done, !_b3; _a9 = true) {
11482
11537
  _d3 = batches_1_1.value;
@@ -11839,6 +11894,13 @@ function socketConnector(uri = "ws://localhost:3000/") {
11839
11894
  get connected() {
11840
11895
  return connected;
11841
11896
  },
11897
+ /**
11898
+ * Query the DuckDB server.
11899
+ * @param {object} query
11900
+ * @param {'exec' | 'arrow' | 'json'} [query.type] The query type: 'exec', 'arrow', or 'json'.
11901
+ * @param {string} query.sql A SQL query string.
11902
+ * @returns the query result
11903
+ */
11842
11904
  query(query) {
11843
11905
  return new Promise(
11844
11906
  (resolve, reject) => enqueue(query, resolve, reject)
@@ -11909,7 +11971,7 @@ function literalToSQL(value) {
11909
11971
  case "boolean":
11910
11972
  return value ? "TRUE" : "FALSE";
11911
11973
  case "string":
11912
- return `'${value}'`;
11974
+ return `'${value.replace(`'`, `''`)}'`;
11913
11975
  case "number":
11914
11976
  return Number.isFinite(value) ? String(value) : "NULL";
11915
11977
  default:
@@ -11992,7 +12054,7 @@ var SQLExpression = class {
11992
12054
  /**
11993
12055
  * Annotate this expression instance with additional properties.
11994
12056
  * @param {object[]} [props] One or more objects with properties to add.
11995
- * @returns {this} This SQL expression.
12057
+ * @returns This SQL expression.
11996
12058
  */
11997
12059
  annotate(...props) {
11998
12060
  return Object.assign(this, ...props);
@@ -12050,6 +12112,12 @@ function sql(strings, ...exprs) {
12050
12112
  return new SQLExpression(spans, cols);
12051
12113
  }
12052
12114
 
12115
+ // ../sql/src/literal.js
12116
+ var literal = (value) => ({
12117
+ value,
12118
+ toString: () => literalToSQL(value)
12119
+ });
12120
+
12053
12121
  // ../sql/src/operators.js
12054
12122
  function visit(callback) {
12055
12123
  callback(this.op, this);
@@ -12248,6 +12316,9 @@ var last_value = winf("LAST_VALUE");
12248
12316
  var nth_value = winf("NTH_VALUE");
12249
12317
 
12250
12318
  // ../sql/src/aggregates.js
12319
+ function agg(strings, ...exprs) {
12320
+ return sql(strings, ...exprs).annotate({ aggregate: true });
12321
+ }
12251
12322
  var AggregateFunction = class _AggregateFunction extends SQLExpression {
12252
12323
  /**
12253
12324
  * Create a new AggregateFunction instance.
@@ -12378,6 +12449,7 @@ var entropy = aggf("ENTROPY");
12378
12449
  var varPop = aggf("VAR_POP");
12379
12450
  var stddevPop = aggf("STDDEV_POP");
12380
12451
  var corr = aggf("CORR");
12452
+ var covariance = aggf("COVAR_SAMP");
12381
12453
  var covarPop = aggf("COVAR_POP");
12382
12454
  var regrIntercept = aggf("REGR_INTERCEPT");
12383
12455
  var regrSlope = aggf("REGR_SLOPE");
@@ -12520,7 +12592,8 @@ var Query = class _Query {
12520
12592
  }
12521
12593
  }
12522
12594
  }
12523
- query.select = query.select.concat(list);
12595
+ const keys = new Set(list.map((x3) => x3.as));
12596
+ query.select = query.select.filter((x3) => !keys.has(x3.as)).concat(list.filter((x3) => x3.expr));
12524
12597
  return this;
12525
12598
  }
12526
12599
  }
@@ -12993,6 +13066,7 @@ function scaleTime() {
12993
13066
  };
12994
13067
  }
12995
13068
  var scales = {
13069
+ identity: scaleLinear,
12996
13070
  linear: scaleLinear,
12997
13071
  log: scaleLog,
12998
13072
  symlog: scaleSymlog,
@@ -13015,179 +13089,97 @@ function create(name, query, {
13015
13089
  return "CREATE" + (replace ? " OR REPLACE " : " ") + (temp ? "TEMP " : "") + (view ? "VIEW" : "TABLE") + (replace ? " " : " IF NOT EXISTS ") + name + " AS " + query;
13016
13090
  }
13017
13091
 
13018
- // src/util/hash.js
13019
- function fnv_hash(v2) {
13020
- let a2 = 2166136261;
13021
- for (let i = 0, n = v2.length; i < n; ++i) {
13022
- const c = v2.charCodeAt(i);
13023
- const d = c & 65280;
13024
- if (d) a2 = fnv_multiply(a2 ^ d >> 8);
13025
- a2 = fnv_multiply(a2 ^ c & 255);
13026
- }
13027
- return fnv_mix(a2);
13028
- }
13029
- function fnv_multiply(a2) {
13030
- return a2 + (a2 << 1) + (a2 << 4) + (a2 << 7) + (a2 << 8) + (a2 << 24);
13031
- }
13032
- function fnv_mix(a2) {
13033
- a2 += a2 << 13;
13034
- a2 ^= a2 >>> 7;
13035
- a2 += a2 << 3;
13036
- a2 ^= a2 >>> 17;
13037
- a2 += a2 << 5;
13038
- return a2 & 4294967295;
13039
- }
13040
-
13041
- // src/DataCubeIndexer.js
13042
- var DataCubeIndexer = class {
13043
- /**
13044
- *
13045
- * @param {import('./Coordinator.js').Coordinator} mc a Mosaic coordinator
13046
- * @param {*} options Options hash to configure the data cube indexes and pass selections to the coordinator.
13047
- */
13048
- constructor(mc, { selection, temp = true }) {
13049
- this.mc = mc;
13050
- this.selection = selection;
13051
- this.temp = temp;
13052
- this.reset();
13053
- }
13054
- reset() {
13055
- this.enabled = false;
13056
- this.clients = null;
13057
- this.indices = null;
13058
- this.activeView = null;
13059
- }
13060
- clear() {
13061
- if (this.indices) {
13062
- this.mc.cancel(Array.from(this.indices.values(), (index) => index.result));
13063
- this.indices = null;
13064
- }
13065
- }
13066
- index(clients, active) {
13067
- if (this.clients !== clients) {
13068
- const cols = Array.from(clients, getIndexColumns);
13069
- const from = cols[0]?.from;
13070
- this.enabled = cols.every((c) => c && c.from === from);
13071
- this.clients = clients;
13072
- this.activeView = null;
13073
- this.clear();
13074
- }
13075
- if (!this.enabled) return false;
13076
- active = active || this.selection.active;
13077
- const { source } = active;
13078
- if (source && source === this.activeView?.source) return true;
13079
- this.clear();
13080
- if (!source) return false;
13081
- const activeView = this.activeView = getActiveView(active);
13082
- if (!activeView) return false;
13083
- this.mc.logger().warn("DATA CUBE INDEX CONSTRUCTION");
13084
- const sel = this.selection.remove(source);
13085
- const indices = this.indices = /* @__PURE__ */ new Map();
13086
- const { mc, temp } = this;
13087
- for (const client of clients) {
13088
- if (sel.skip(client, active)) continue;
13089
- const index = getIndexColumns(client);
13090
- const query = client.query(sel.predicate(client)).select({ ...activeView.columns, ...index.aux }).groupby(Object.keys(activeView.columns));
13091
- const [subq] = query.subqueries;
13092
- if (subq) {
13093
- const cols = Object.values(activeView.columns).map((c) => c.columns[0]);
13094
- subqueryPushdown(subq, cols);
13095
- }
13096
- const order = query.orderby();
13097
- query.query.orderby = [];
13098
- const sql2 = query.toString();
13099
- const id = (fnv_hash(sql2) >>> 0).toString(16);
13100
- const table = `cube_index_${id}`;
13101
- const result = mc.exec(create(table, sql2, { temp }));
13102
- indices.set(client, { table, result, order, ...index });
13103
- }
13104
- return true;
13105
- }
13106
- async update() {
13107
- const { clients, selection, activeView } = this;
13108
- const filter = activeView.predicate(selection.active.predicate);
13109
- return Promise.all(
13110
- Array.from(clients).map((client) => this.updateClient(client, filter))
13111
- );
13112
- }
13113
- async updateClient(client, filter) {
13114
- const index = this.indices.get(client);
13115
- if (!index) return;
13116
- if (!filter) {
13117
- filter = this.activeView.predicate(this.selection.active.predicate);
13118
- }
13119
- const { table, dims, aggr, order = [] } = index;
13120
- const query = Query.select(dims, aggr).from(table).groupby(dims).where(filter).orderby(order);
13121
- return this.mc.updateClient(client, query);
13122
- }
13123
- };
13124
- function getActiveView(clause) {
13125
- const { source, schema } = clause;
13126
- let columns = clause.predicate?.columns;
13127
- if (!schema || !columns) return null;
13128
- const { type, scales: scales2, pixelSize = 1 } = schema;
13129
- let predicate;
13130
- if (type === "interval" && scales2) {
13131
- const bins = scales2.map((s) => binInterval(s, pixelSize));
13132
- if (bins.some((b2) => b2 == null)) return null;
13133
- if (bins.length === 1) {
13134
- predicate = (p2) => p2 ? isBetween("active0", p2.range.map(bins[0])) : [];
13135
- columns = { active0: bins[0](clause.predicate.field) };
13136
- } else {
13137
- predicate = (p2) => p2 ? and(p2.children.map(({ range }, i) => isBetween(`active${i}`, range.map(bins[i])))) : [];
13138
- columns = Object.fromEntries(
13139
- clause.predicate.children.map((p2, i) => [`active${i}`, bins[i](p2.field)])
13140
- );
13141
- }
13142
- } else if (type === "point") {
13143
- predicate = (x3) => x3;
13144
- columns = Object.fromEntries(columns.map((col) => [col.toString(), col]));
13145
- } else {
13146
- return null;
13147
- }
13148
- return { source, columns, predicate };
13149
- }
13150
- function binInterval(scale, pixelSize) {
13151
- const { apply, sqlApply } = scaleTransform(scale);
13152
- if (apply) {
13153
- const { domain, range } = scale;
13154
- const lo = apply(Math.min(...domain));
13155
- const hi = apply(Math.max(...domain));
13156
- const a2 = Math.abs(range[1] - range[0]) / (hi - lo) / pixelSize;
13157
- const s = pixelSize === 1 ? "" : `${pixelSize}::INTEGER * `;
13158
- return (value) => sql`${s}FLOOR(${a2}::DOUBLE * (${sqlApply(value)} - ${lo}::DOUBLE))::INTEGER`;
13159
- }
13160
- }
13161
- var NO_INDEX = { from: NaN };
13162
- function getIndexColumns(client) {
13163
- if (!client.filterIndexable) return NO_INDEX;
13092
+ // src/util/index-columns.js
13093
+ function indexColumns(client) {
13094
+ if (!client.filterIndexable) return null;
13164
13095
  const q2 = client.query();
13165
13096
  const from = getBaseTable(q2);
13166
- if (!from || !q2.groupby) return NO_INDEX;
13167
- const g2 = new Set(q2.groupby().map((c) => c.column));
13097
+ if (typeof from !== "string" || !q2.select) return null;
13168
13098
  const aggr = [];
13169
13099
  const dims = [];
13170
13100
  const aux = {};
13171
- let auxAs;
13172
13101
  for (const entry of q2.select()) {
13173
13102
  const { as, expr: { aggregate, args } } = entry;
13174
13103
  const op = aggregate?.toUpperCase?.();
13175
13104
  switch (op) {
13176
13105
  case "COUNT":
13177
13106
  case "SUM":
13178
- aggr.push({ [as]: sql`SUM("${as}")::DOUBLE` });
13107
+ aggr.push({ [as]: agg`SUM("${as}")::DOUBLE` });
13179
13108
  break;
13180
13109
  case "AVG":
13181
- aux[auxAs = "__count__"] = sql`COUNT(*)`;
13182
- aggr.push({ [as]: sql`(SUM("${as}" * ${auxAs}) / SUM(${auxAs}))::DOUBLE` });
13110
+ aggr.push({ [as]: avgExpr(aux, as, args[0]) });
13183
13111
  break;
13184
13112
  case "ARG_MAX":
13185
- aux[auxAs = `__max_${as}__`] = sql`MAX(${args[1]})`;
13186
- aggr.push({ [as]: sql`ARG_MAX("${as}", ${auxAs})` });
13113
+ aggr.push({ [as]: argmaxExpr(aux, as, args) });
13187
13114
  break;
13188
13115
  case "ARG_MIN":
13189
- aux[auxAs = `__min_${as}__`] = sql`MIN(${args[1]})`;
13190
- aggr.push({ [as]: sql`ARG_MIN("${as}", ${auxAs})` });
13116
+ aggr.push({ [as]: argminExpr(aux, as, args) });
13117
+ break;
13118
+ case "VARIANCE":
13119
+ case "VAR_SAMP":
13120
+ aux[as] = null;
13121
+ aggr.push({ [as]: varianceExpr(aux, args[0], from) });
13122
+ break;
13123
+ case "VAR_POP":
13124
+ aux[as] = null;
13125
+ aggr.push({ [as]: varianceExpr(aux, args[0], from, false) });
13126
+ break;
13127
+ case "STDDEV":
13128
+ case "STDDEV_SAMP":
13129
+ aux[as] = null;
13130
+ aggr.push({ [as]: agg`SQRT(${varianceExpr(aux, args[0], from)})` });
13131
+ break;
13132
+ case "STDDEV_POP":
13133
+ aux[as] = null;
13134
+ aggr.push({ [as]: agg`SQRT(${varianceExpr(aux, args[0], from, false)})` });
13135
+ break;
13136
+ case "COVAR_SAMP":
13137
+ aux[as] = null;
13138
+ aggr.push({ [as]: covarianceExpr(aux, args, from) });
13139
+ break;
13140
+ case "COVAR_POP":
13141
+ aux[as] = null;
13142
+ aggr.push({ [as]: covarianceExpr(aux, args, from, false) });
13143
+ break;
13144
+ case "CORR":
13145
+ aux[as] = null;
13146
+ aggr.push({ [as]: corrExpr(aux, args, from) });
13147
+ break;
13148
+ case "REGR_COUNT":
13149
+ aux[as] = null;
13150
+ aggr.push({ [as]: agg`${regrCountExpr(aux, args)}::DOUBLE` });
13151
+ break;
13152
+ case "REGR_AVGX":
13153
+ aux[as] = null;
13154
+ aggr.push({ [as]: regrAvgXExpr(aux, args) });
13155
+ break;
13156
+ case "REGR_AVGY":
13157
+ aux[as] = null;
13158
+ aggr.push({ [as]: regrAvgYExpr(aux, args) });
13159
+ break;
13160
+ case "REGR_SYY":
13161
+ aux[as] = null;
13162
+ aggr.push({ [as]: regrVarExpr(aux, 0, args, from) });
13163
+ break;
13164
+ case "REGR_SXX":
13165
+ aux[as] = null;
13166
+ aggr.push({ [as]: regrVarExpr(aux, 1, args, from) });
13167
+ break;
13168
+ case "REGR_SXY":
13169
+ aux[as] = null;
13170
+ aggr.push({ [as]: covarianceExpr(aux, args, from, null) });
13171
+ break;
13172
+ case "REGR_SLOPE":
13173
+ aux[as] = null;
13174
+ aggr.push({ [as]: regrSlopeExpr(aux, args, from) });
13175
+ break;
13176
+ case "REGR_INTERCEPT":
13177
+ aux[as] = null;
13178
+ aggr.push({ [as]: regrInterceptExpr(aux, args, from) });
13179
+ break;
13180
+ case "REGR_R2":
13181
+ aux[as] = null;
13182
+ aggr.push({ [as]: agg`(${corrExpr(aux, args, from)}) ** 2` });
13191
13183
  break;
13192
13184
  case "MAX":
13193
13185
  case "MIN":
@@ -13197,14 +13189,22 @@ function getIndexColumns(client) {
13197
13189
  case "BOOL_AND":
13198
13190
  case "BOOL_OR":
13199
13191
  case "PRODUCT":
13200
- aggr.push({ [as]: sql`${op}("${as}")` });
13192
+ aggr.push({ [as]: agg`${op}("${as}")` });
13201
13193
  break;
13202
13194
  default:
13203
- if (g2.has(as)) dims.push(as);
13195
+ if (!aggregate) dims.push(as);
13204
13196
  else return null;
13205
13197
  }
13206
13198
  }
13207
- return { aggr, dims, aux, from };
13199
+ if (!aggr.length) return null;
13200
+ return { from, dims, aggr, aux };
13201
+ }
13202
+ function auxName(type, ...args) {
13203
+ const cols = args.length ? "_" + args.map(sanitize).join("_") : "";
13204
+ return `__${type}${cols}__`;
13205
+ }
13206
+ function sanitize(col) {
13207
+ return `${col}`.replaceAll('"', "").replaceAll(" ", "_");
13208
13208
  }
13209
13209
  function getBaseTable(query) {
13210
13210
  const subq = query.subqueries;
@@ -13221,90 +13221,362 @@ function getBaseTable(query) {
13221
13221
  }
13222
13222
  return base;
13223
13223
  }
13224
- function subqueryPushdown(query, cols) {
13225
- const memo = /* @__PURE__ */ new Set();
13226
- const pushdown = (q2) => {
13227
- if (memo.has(q2)) return;
13228
- memo.add(q2);
13229
- if (q2.select && q2.from().length) {
13230
- q2.select(cols);
13231
- }
13232
- q2.subqueries.forEach(pushdown);
13233
- };
13234
- pushdown(query);
13224
+ function countExpr(aux, arg) {
13225
+ const n = auxName("count", arg);
13226
+ aux[n] = agg`COUNT(${arg})`;
13227
+ return agg`SUM(${n})`.annotate({ name: n });
13228
+ }
13229
+ function avgExpr(aux, as, arg) {
13230
+ const n = countExpr(aux, arg);
13231
+ return agg`(SUM("${as}" * ${n.name}) / ${n})`;
13232
+ }
13233
+ function avg2(x3, from) {
13234
+ return sql`(SELECT AVG(${x3}) FROM "${from}")`;
13235
+ }
13236
+ function argmaxExpr(aux, as, [, y3]) {
13237
+ const max2 = auxName("max", y3);
13238
+ aux[max2] = agg`MAX(${y3})`;
13239
+ return agg`ARG_MAX("${as}", ${max2})`;
13240
+ }
13241
+ function argminExpr(aux, as, [, y3]) {
13242
+ const min2 = auxName("min", y3);
13243
+ aux[min2] = agg`MIN(${y3})`;
13244
+ return agg`ARG_MIN("${as}", ${min2})`;
13245
+ }
13246
+ function varianceExpr(aux, x3, from, correction = true) {
13247
+ const n = countExpr(aux, x3);
13248
+ const ssq = auxName("rssq", x3);
13249
+ const sum3 = auxName("rsum", x3);
13250
+ const delta = sql`${x3} - ${avg2(x3, from)}`;
13251
+ aux[ssq] = agg`SUM((${delta}) ** 2)`;
13252
+ aux[sum3] = agg`SUM(${delta})`;
13253
+ const adj = correction ? ` - 1` : "";
13254
+ return agg`(SUM(${ssq}) - (SUM(${sum3}) ** 2 / ${n})) / (${n}${adj})`;
13255
+ }
13256
+ function covarianceExpr(aux, args, from, correction = true) {
13257
+ const n = regrCountExpr(aux, args);
13258
+ const sxy = regrSumXYExpr(aux, args, from);
13259
+ const sx = regrSumExpr(aux, 1, args, from);
13260
+ const sy = regrSumExpr(aux, 0, args, from);
13261
+ const adj = correction === null ? "" : correction ? ` / (${n} - 1)` : ` / ${n}`;
13262
+ return agg`(${sxy} - ${sx} * ${sy} / ${n})${adj}`;
13263
+ }
13264
+ function corrExpr(aux, args, from) {
13265
+ const n = regrCountExpr(aux, args);
13266
+ const sxy = regrSumXYExpr(aux, args, from);
13267
+ const sxx = regrSumSqExpr(aux, 1, args, from);
13268
+ const syy = regrSumSqExpr(aux, 0, args, from);
13269
+ const sx = regrSumExpr(aux, 1, args, from);
13270
+ const sy = regrSumExpr(aux, 0, args, from);
13271
+ const vx = agg`(${sxx} - (${sx} ** 2) / ${n})`;
13272
+ const vy = agg`(${syy} - (${sy} ** 2) / ${n})`;
13273
+ return agg`(${sxy} - ${sx} * ${sy} / ${n}) / SQRT(${vx} * ${vy})`;
13274
+ }
13275
+ function regrCountExpr(aux, [y3, x3]) {
13276
+ const n = auxName("count", y3, x3);
13277
+ aux[n] = agg`REGR_COUNT(${y3}, ${x3})`;
13278
+ return agg`SUM(${n})`.annotate({ name: n });
13279
+ }
13280
+ function regrSumExpr(aux, i, args, from) {
13281
+ const v2 = args[i];
13282
+ const o = args[1 - i];
13283
+ const sum3 = auxName("rs", v2);
13284
+ aux[sum3] = agg`SUM(${v2} - ${avg2(v2, from)}) FILTER (${o} IS NOT NULL)`;
13285
+ return agg`SUM(${sum3})`;
13286
+ }
13287
+ function regrSumSqExpr(aux, i, args, from) {
13288
+ const v2 = args[i];
13289
+ const u = args[1 - i];
13290
+ const ssq = auxName("rss", v2);
13291
+ aux[ssq] = agg`SUM((${v2} - ${avg2(v2, from)}) ** 2) FILTER (${u} IS NOT NULL)`;
13292
+ return agg`SUM(${ssq})`;
13293
+ }
13294
+ function regrSumXYExpr(aux, args, from) {
13295
+ const [y3, x3] = args;
13296
+ const sxy = auxName("sxy", y3, x3);
13297
+ aux[sxy] = agg`SUM((${x3} - ${avg2(x3, from)}) * (${y3} - ${avg2(y3, from)}))`;
13298
+ return agg`SUM(${sxy})`;
13299
+ }
13300
+ function regrAvgXExpr(aux, args) {
13301
+ const [y3, x3] = args;
13302
+ const n = regrCountExpr(aux, args);
13303
+ const a2 = auxName("avg", x3, y3);
13304
+ aux[a2] = agg`REGR_AVGX(${y3}, ${x3})`;
13305
+ return agg`(SUM(${a2} * ${n.name}) / ${n})`;
13306
+ }
13307
+ function regrAvgYExpr(aux, args) {
13308
+ const [y3, x3] = args;
13309
+ const n = regrCountExpr(aux, args);
13310
+ const a2 = auxName("avg", y3, x3);
13311
+ aux[a2] = agg`REGR_AVGY(${y3}, ${x3})`;
13312
+ return agg`(SUM(${a2} * ${n.name}) / ${n})`;
13313
+ }
13314
+ function regrVarExpr(aux, i, args, from) {
13315
+ const n = regrCountExpr(aux, args);
13316
+ const sum3 = regrSumExpr(aux, i, args, from);
13317
+ const ssq = regrSumSqExpr(aux, i, args, from);
13318
+ return agg`(${ssq} - (${sum3} ** 2 / ${n}))`;
13319
+ }
13320
+ function regrSlopeExpr(aux, args, from) {
13321
+ const cov = covarianceExpr(aux, args, from, null);
13322
+ const varx = regrVarExpr(aux, 1, args, from);
13323
+ return agg`(${cov}) / ${varx}`;
13324
+ }
13325
+ function regrInterceptExpr(aux, args, from) {
13326
+ const ax = regrAvgXExpr(aux, args);
13327
+ const ay = regrAvgYExpr(aux, args);
13328
+ const m2 = regrSlopeExpr(aux, args, from);
13329
+ return agg`${ay} - (${m2}) * ${ax}`;
13330
+ }
13331
+
13332
+ // src/util/hash.js
13333
+ function fnv_hash(v2) {
13334
+ let a2 = 2166136261;
13335
+ for (let i = 0, n = v2.length; i < n; ++i) {
13336
+ const c = v2.charCodeAt(i);
13337
+ const d = c & 65280;
13338
+ if (d) a2 = fnv_multiply(a2 ^ d >> 8);
13339
+ a2 = fnv_multiply(a2 ^ c & 255);
13340
+ }
13341
+ return fnv_mix(a2);
13342
+ }
13343
+ function fnv_multiply(a2) {
13344
+ return a2 + (a2 << 1) + (a2 << 4) + (a2 << 7) + (a2 << 8) + (a2 << 24);
13345
+ }
13346
+ function fnv_mix(a2) {
13347
+ a2 += a2 << 13;
13348
+ a2 ^= a2 >>> 7;
13349
+ a2 += a2 << 3;
13350
+ a2 ^= a2 >>> 17;
13351
+ a2 += a2 << 5;
13352
+ return a2 & 4294967295;
13235
13353
  }
13236
13354
 
13237
- // src/FilterGroup.js
13238
- var FilterGroup = class {
13355
+ // src/DataCubeIndexer.js
13356
+ var Skip = { skip: true, result: null };
13357
+ var DataCubeIndexer = class {
13239
13358
  /**
13240
- * @param {import('./Coordinator.js').Coordinator} coordinator The Mosaic coordinator.
13241
- * @param {*} selection The shared filter selection.
13242
- * @param {*} index Boolean flag or options hash for data cube indexer.
13243
- * Falsy values disable indexing.
13359
+ * Create a new data cube index table manager.
13360
+ * @param {import('./Coordinator.js').Coordinator} coordinator A Mosaic coordinator.
13361
+ * @param {object} [options] Indexer options.
13362
+ * @param {boolean} [options.enabled=true] Flag to enable/disable indexer.
13363
+ * @param {boolean} [options.temp=true] Flag to indicate if generated data
13364
+ * cube index tables should be temporary tables.
13244
13365
  */
13245
- constructor(coordinator2, selection, index = true) {
13366
+ constructor(coordinator2, {
13367
+ enabled = true,
13368
+ temp = true
13369
+ } = {}) {
13370
+ this.indexes = /* @__PURE__ */ new Map();
13371
+ this.active = null;
13372
+ this.temp = temp;
13246
13373
  this.mc = coordinator2;
13247
- this.selection = selection;
13248
- this.clients = /* @__PURE__ */ new Set();
13249
- this.indexer = index ? new DataCubeIndexer(this.mc, { ...index, selection }) : null;
13250
- const { value, activate } = this.handlers = {
13251
- value: () => this.update(),
13252
- activate: (clause) => this.indexer?.index(this.clients, clause)
13253
- };
13254
- selection.addEventListener("value", value);
13255
- selection.addEventListener("activate", activate);
13256
- }
13257
- finalize() {
13258
- const { value, activate } = this.handlers;
13259
- this.selection.removeEventListener("value", value);
13260
- this.selection.removeEventListener("activate", activate);
13261
- }
13262
- reset() {
13263
- this.indexer?.reset();
13264
- }
13265
- add(client) {
13266
- (this.clients = new Set(this.clients)).add(client);
13267
- return this;
13374
+ this._enabled = enabled;
13268
13375
  }
13269
- remove(client) {
13270
- if (this.clients.has(client)) {
13271
- (this.clients = new Set(this.clients)).delete(client);
13376
+ /**
13377
+ * Set the enabled state of this indexer. If false, any cached state is
13378
+ * cleared and subsequent index calls will return null until re-enabled.
13379
+ * @param {boolean} state The enabled state.
13380
+ */
13381
+ enabled(state) {
13382
+ if (state === void 0) {
13383
+ return this._enabled;
13384
+ } else if (this._enabled !== state) {
13385
+ if (!state) this.clear();
13386
+ this._enabled = state;
13272
13387
  }
13273
- return this;
13274
13388
  }
13275
13389
  /**
13276
- * Internal method to process a selection update.
13277
- * The return value is passed as a selection callback value.
13278
- * @returns {Promise} A Promise that resolves when the update completes.
13390
+ * Clear the cache of data cube index table entries for the current active
13391
+ * selection clause. This method will also cancel any queued data cube table
13392
+ * creation queries that have not yet been submitted to the database. This
13393
+ * method does _not_ drop any existing data cube tables.
13279
13394
  */
13280
- update() {
13281
- const { mc, indexer, clients, selection } = this;
13282
- const hasIndex = indexer?.index(clients);
13283
- return hasIndex ? indexer.update() : defaultUpdate(mc, clients, selection);
13395
+ clear() {
13396
+ this.mc.cancel(Array.from(this.indexes.values(), (info) => info?.result));
13397
+ this.indexes.clear();
13398
+ this.active = null;
13399
+ }
13400
+ /**
13401
+ * Return data cube index table information for the active state of a
13402
+ * client-selection pair, or null if the client is not indexable. This
13403
+ * method has multiple possible side effects, including data cube table
13404
+ * generation and updating internal caches.
13405
+ * @param {import('./MosaicClient.js').MosaicClient} client A Mosaic client.
13406
+ * @param {import('./Selection.js').Selection} selection A Mosaic selection
13407
+ * to filter the client by.
13408
+ * @param {import('./util/selection-types.js').SelectionClause} activeClause
13409
+ * A representative active selection clause for which to (possibly) generate
13410
+ * data cube index tables.
13411
+ * @returns {DataCubeInfo | Skip | null} Data cube index table
13412
+ * information and query generator, or null if the client is not indexable.
13413
+ */
13414
+ index(client, selection, activeClause) {
13415
+ if (!this._enabled) return null;
13416
+ const { indexes, mc, temp } = this;
13417
+ const { source } = activeClause;
13418
+ if (!source) return null;
13419
+ if (this.active) {
13420
+ if (this.active.source !== source) this.clear();
13421
+ if (this.active?.source === null) return null;
13422
+ }
13423
+ let { active } = this;
13424
+ if (!active) {
13425
+ this.active = active = activeColumns(activeClause);
13426
+ if (active.source === null) return null;
13427
+ }
13428
+ if (indexes.has(client)) {
13429
+ return indexes.get(client);
13430
+ }
13431
+ const indexCols = indexColumns(client);
13432
+ let info;
13433
+ if (!indexCols) {
13434
+ info = null;
13435
+ } else if (selection.skip(client, activeClause)) {
13436
+ info = Skip;
13437
+ } else {
13438
+ const filter = selection.remove(source).predicate(client);
13439
+ info = dataCubeInfo(client.query(filter), active, indexCols);
13440
+ info.result = mc.exec(create(info.table, info.create, { temp }));
13441
+ info.result.catch((e) => mc.logger().error(e));
13442
+ }
13443
+ indexes.set(client, info);
13444
+ return info;
13284
13445
  }
13285
13446
  };
13286
- function defaultUpdate(mc, clients, selection) {
13287
- return Promise.all(Array.from(clients).map((client) => {
13288
- const filter = selection.predicate(client);
13289
- if (filter != null) {
13290
- return mc.updateClient(client, client.query(filter));
13291
- }
13292
- }));
13447
+ function activeColumns(clause) {
13448
+ const { source, meta } = clause;
13449
+ const clausePred = clause.predicate;
13450
+ const clauseCols = clausePred?.columns;
13451
+ let predicate;
13452
+ let columns;
13453
+ if (!meta || !clauseCols) {
13454
+ return { source: null, columns, predicate };
13455
+ }
13456
+ const { type, scales: scales2, bin, pixelSize = 1 } = meta;
13457
+ if (type === "point") {
13458
+ predicate = (x3) => x3;
13459
+ columns = Object.fromEntries(
13460
+ clauseCols.map((col) => [`${col}`, asColumn(col)])
13461
+ );
13462
+ } else if (type === "interval" && scales2) {
13463
+ const bins = scales2.map((s) => binInterval(s, pixelSize, bin));
13464
+ if (bins.some((b2) => !b2)) {
13465
+ } else if (bins.length === 1) {
13466
+ predicate = (p2) => p2 ? isBetween("active0", p2.range.map(bins[0])) : [];
13467
+ columns = { active0: bins[0](clausePred.field) };
13468
+ } else {
13469
+ predicate = (p2) => p2 ? and(p2.children.map(
13470
+ ({ range }, i) => isBetween(`active${i}`, range.map(bins[i]))
13471
+ )) : [];
13472
+ columns = Object.fromEntries(
13473
+ // @ts-ignore
13474
+ clausePred.children.map((p2, i) => [`active${i}`, bins[i](p2.field)])
13475
+ );
13476
+ }
13477
+ }
13478
+ return { source: columns ? source : null, columns, predicate };
13479
+ }
13480
+ var BIN = { ceil: "CEIL", round: "ROUND" };
13481
+ function binInterval(scale, pixelSize, bin) {
13482
+ const { type, domain, range, apply, sqlApply } = scaleTransform(scale);
13483
+ if (!apply) return;
13484
+ const fn = BIN[`${bin}`.toLowerCase()] || "FLOOR";
13485
+ const lo = apply(Math.min(...domain));
13486
+ const hi = apply(Math.max(...domain));
13487
+ const a2 = type === "identity" ? 1 : Math.abs(range[1] - range[0]) / (hi - lo);
13488
+ const s = a2 / pixelSize === 1 ? "" : `${a2 / pixelSize}::DOUBLE * `;
13489
+ const d = lo === 0 ? "" : ` - ${lo}::DOUBLE`;
13490
+ return (value) => sql`${fn}(${s}(${sqlApply(value)}${d}))::INTEGER`;
13491
+ }
13492
+ function dataCubeInfo(clientQuery, active, indexCols) {
13493
+ const { dims, aggr, aux } = indexCols;
13494
+ const { columns } = active;
13495
+ const query = clientQuery.select({ ...columns, ...aux }).groupby(Object.keys(columns));
13496
+ const [subq] = query.subqueries;
13497
+ if (subq) {
13498
+ const cols = Object.values(columns).flatMap((c) => c.columns);
13499
+ subqueryPushdown(subq, cols);
13500
+ }
13501
+ const order = query.orderby();
13502
+ query.query.orderby = [];
13503
+ const create2 = query.toString();
13504
+ const id = (fnv_hash(create2) >>> 0).toString(16);
13505
+ const table = `cube_index_${id}`;
13506
+ const select = Query.select(dims, aggr).from(table).groupby(dims).orderby(order);
13507
+ return new DataCubeInfo({ table, create: create2, active, select });
13508
+ }
13509
+ function subqueryPushdown(query, cols) {
13510
+ const memo = /* @__PURE__ */ new Set();
13511
+ const pushdown = (q2) => {
13512
+ if (memo.has(q2)) return;
13513
+ memo.add(q2);
13514
+ if (q2.select && q2.from().length) {
13515
+ q2.select(cols);
13516
+ }
13517
+ q2.subqueries.forEach(pushdown);
13518
+ };
13519
+ pushdown(query);
13293
13520
  }
13521
+ var DataCubeInfo = class {
13522
+ /**
13523
+ * Create a new DataCubeInfo instance.
13524
+ * @param {object} options
13525
+ */
13526
+ constructor({ table, create: create2, active, select } = {}) {
13527
+ this.table = table;
13528
+ this.create = create2;
13529
+ this.result = null;
13530
+ this.active = active;
13531
+ this.select = select;
13532
+ this.skip = false;
13533
+ }
13534
+ /**
13535
+ * Generate a data cube index table query for the given predicate.
13536
+ * @param {import('@uwdata/mosaic-sql').SQLExpression} predicate The current
13537
+ * active clause predicate.
13538
+ * @returns {Query} A data cube index table query.
13539
+ */
13540
+ query(predicate) {
13541
+ return this.select.clone().where(this.active.predicate(predicate));
13542
+ }
13543
+ };
13294
13544
 
13295
13545
  // src/util/query-result.js
13296
- function queryResult() {
13297
- let resolve;
13298
- let reject;
13299
- const p2 = new Promise((r, e) => {
13300
- resolve = r;
13301
- reject = e;
13302
- });
13303
- return Object.assign(p2, {
13304
- fulfill: (value) => (resolve(value), p2),
13305
- reject: (err) => (reject(err), p2)
13306
- });
13307
- }
13546
+ var QueryResult = class extends Promise {
13547
+ /**
13548
+ * Create a new query result Promise.
13549
+ */
13550
+ constructor() {
13551
+ let resolve;
13552
+ let reject;
13553
+ super((r, e) => {
13554
+ resolve = r;
13555
+ reject = e;
13556
+ });
13557
+ this._resolve = resolve;
13558
+ this._reject = reject;
13559
+ }
13560
+ /**
13561
+ * Resolve the result Promise with the provided value.
13562
+ * @param {*} value The result value.
13563
+ * @returns {this}
13564
+ */
13565
+ fulfill(value) {
13566
+ this._resolve(value);
13567
+ return this;
13568
+ }
13569
+ /**
13570
+ * Rejects the result Promise with the provided error.
13571
+ * @param {*} error The error value.
13572
+ * @returns {this}
13573
+ */
13574
+ reject(error) {
13575
+ this._reject(error);
13576
+ return this;
13577
+ }
13578
+ };
13579
+ QueryResult.prototype.constructor = Promise;
13308
13580
 
13309
13581
  // src/QueryConsolidator.js
13310
13582
  function wait(callback) {
@@ -13380,7 +13652,7 @@ function consolidate(group, enqueue, record) {
13380
13652
  record: false,
13381
13653
  query: group.query = consolidatedQuery(group, record)
13382
13654
  },
13383
- result: group.result = queryResult()
13655
+ result: group.result = new QueryResult()
13384
13656
  });
13385
13657
  } else {
13386
13658
  for (const { entry, priority } of group) {
@@ -13596,115 +13868,124 @@ function priorityQueue(ranks) {
13596
13868
 
13597
13869
  // src/QueryManager.js
13598
13870
  var Priority = { High: 0, Normal: 1, Low: 2 };
13599
- function QueryManager() {
13600
- const queue = priorityQueue(3);
13601
- let db;
13602
- let clientCache;
13603
- let logger;
13604
- let recorders = [];
13605
- let pending = null;
13606
- let consolidate2;
13607
- function next() {
13608
- if (pending || queue.isEmpty()) return;
13609
- const { request, result } = queue.next();
13610
- pending = submit(request, result);
13611
- pending.finally(() => {
13612
- pending = null;
13613
- next();
13871
+ var QueryManager = class {
13872
+ constructor() {
13873
+ this.queue = priorityQueue(3);
13874
+ this.db = null;
13875
+ this.clientCache = null;
13876
+ this._logger = null;
13877
+ this._logQueries = false;
13878
+ this.recorders = [];
13879
+ this.pending = null;
13880
+ this._consolidate = null;
13881
+ }
13882
+ next() {
13883
+ if (this.pending || this.queue.isEmpty()) return;
13884
+ const { request, result } = this.queue.next();
13885
+ this.pending = this.submit(request, result);
13886
+ this.pending.finally(() => {
13887
+ this.pending = null;
13888
+ this.next();
13614
13889
  });
13615
13890
  }
13616
- function enqueue(entry, priority = Priority.Normal) {
13617
- queue.insert(entry, priority);
13618
- next();
13891
+ enqueue(entry, priority = Priority.Normal) {
13892
+ this.queue.insert(entry, priority);
13893
+ this.next();
13619
13894
  }
13620
- function recordQuery(sql2) {
13621
- if (recorders.length && sql2) {
13622
- recorders.forEach((rec) => rec.add(sql2));
13895
+ recordQuery(sql2) {
13896
+ if (this.recorders.length && sql2) {
13897
+ this.recorders.forEach((rec) => rec.add(sql2));
13623
13898
  }
13624
13899
  }
13625
- async function submit(request, result) {
13900
+ async submit(request, result) {
13626
13901
  try {
13627
13902
  const { query, type, cache = false, record = true, options } = request;
13628
13903
  const sql2 = query ? `${query}` : null;
13629
13904
  if (record) {
13630
- recordQuery(sql2);
13905
+ this.recordQuery(sql2);
13631
13906
  }
13632
13907
  if (cache) {
13633
- const cached = clientCache.get(sql2);
13908
+ const cached = this.clientCache.get(sql2);
13634
13909
  if (cached) {
13635
- logger.debug("Cache");
13910
+ this._logger.debug("Cache");
13636
13911
  result.fulfill(cached);
13637
13912
  return;
13638
13913
  }
13639
13914
  }
13640
13915
  const t0 = performance.now();
13641
- const data = await db.query({ type, sql: sql2, ...options });
13642
- if (cache) clientCache.set(sql2, data);
13643
- logger.debug(`Request: ${(performance.now() - t0).toFixed(1)}`);
13916
+ if (this._logQueries) {
13917
+ this._logger.debug("Query", { type, sql: sql2, ...options });
13918
+ }
13919
+ const data = await this.db.query({ type, sql: sql2, ...options });
13920
+ if (cache) this.clientCache.set(sql2, data);
13921
+ this._logger.debug(`Request: ${(performance.now() - t0).toFixed(1)}`);
13644
13922
  result.fulfill(data);
13645
13923
  } catch (err) {
13646
13924
  result.reject(err);
13647
13925
  }
13648
13926
  }
13649
- return {
13650
- cache(value) {
13651
- return value !== void 0 ? clientCache = value === true ? lruCache() : value || voidCache() : clientCache;
13652
- },
13653
- logger(value) {
13654
- return value ? logger = value : logger;
13655
- },
13656
- connector(connector) {
13657
- return connector ? db = connector : db;
13658
- },
13659
- consolidate(flag) {
13660
- if (flag && !consolidate2) {
13661
- consolidate2 = consolidator(enqueue, clientCache, recordQuery);
13662
- } else if (!flag && consolidate2) {
13663
- consolidate2 = null;
13664
- }
13665
- },
13666
- request(request, priority = Priority.Normal) {
13667
- const result = queryResult();
13668
- const entry = { request, result };
13669
- if (consolidate2) {
13670
- consolidate2.add(entry, priority);
13671
- } else {
13672
- enqueue(entry, priority);
13673
- }
13674
- return result;
13675
- },
13676
- cancel(requests) {
13677
- const set = new Set(requests);
13678
- queue.remove(({ result }) => set.has(result));
13679
- },
13680
- clear() {
13681
- queue.remove(({ result }) => {
13682
- result.reject("Cleared");
13683
- return true;
13684
- });
13685
- },
13686
- record() {
13687
- let state = [];
13688
- const recorder = {
13689
- add(query) {
13690
- state.push(query);
13691
- },
13692
- reset() {
13693
- state = [];
13694
- },
13695
- snapshot() {
13696
- return state.slice();
13697
- },
13698
- stop() {
13699
- recorders = recorders.filter((x3) => x3 !== recorder);
13700
- return state;
13701
- }
13702
- };
13703
- recorders.push(recorder);
13704
- return recorder;
13927
+ cache(value) {
13928
+ return value !== void 0 ? this.clientCache = value === true ? lruCache() : value || voidCache() : this.clientCache;
13929
+ }
13930
+ logger(value) {
13931
+ return value ? this._logger = value : this._logger;
13932
+ }
13933
+ logQueries(value) {
13934
+ return value !== void 0 ? this._logQueries = !!value : this._logQueries;
13935
+ }
13936
+ connector(connector) {
13937
+ return connector ? this.db = connector : this.db;
13938
+ }
13939
+ consolidate(flag) {
13940
+ if (flag && !this._consolidate) {
13941
+ this._consolidate = consolidator(this.enqueue.bind(this), this.clientCache, this.recordQuery.bind(this));
13942
+ } else if (!flag && this._consolidate) {
13943
+ this._consolidate = null;
13705
13944
  }
13706
- };
13707
- }
13945
+ }
13946
+ request(request, priority = Priority.Normal) {
13947
+ const result = new QueryResult();
13948
+ const entry = { request, result };
13949
+ if (this._consolidate) {
13950
+ this._consolidate.add(entry, priority);
13951
+ } else {
13952
+ this.enqueue(entry, priority);
13953
+ }
13954
+ return result;
13955
+ }
13956
+ cancel(requests) {
13957
+ const set = new Set(requests);
13958
+ if (set.size) {
13959
+ this.queue.remove(({ result }) => set.has(result));
13960
+ }
13961
+ }
13962
+ clear() {
13963
+ this.queue.remove(({ result }) => {
13964
+ result.reject("Cleared");
13965
+ return true;
13966
+ });
13967
+ }
13968
+ record() {
13969
+ let state = [];
13970
+ const recorder = {
13971
+ add(query) {
13972
+ state.push(query);
13973
+ },
13974
+ reset() {
13975
+ state = [];
13976
+ },
13977
+ snapshot() {
13978
+ return state.slice();
13979
+ },
13980
+ stop() {
13981
+ this.recorders = this.recorders.filter((x3) => x3 !== recorder);
13982
+ return state;
13983
+ }
13984
+ };
13985
+ this.recorders.push(recorder);
13986
+ return recorder;
13987
+ }
13988
+ };
13708
13989
 
13709
13990
  // src/util/js-type.js
13710
13991
  function jsType(type) {
@@ -13788,23 +14069,26 @@ function convertArrowColumn(column2) {
13788
14069
  }
13789
14070
  if (DataType.isInt(type) && type.bitWidth >= 64) {
13790
14071
  const size = column2.length;
13791
- const array = new Float64Array(size);
14072
+ const array = column2.nullCount ? new Array(size) : new Float64Array(size);
13792
14073
  for (let row = 0; row < size; ++row) {
13793
14074
  const v2 = column2.get(row);
13794
- array[row] = v2 == null ? NaN : Number(v2);
14075
+ array[row] = v2 == null ? null : Number(v2);
13795
14076
  }
13796
14077
  return array;
13797
14078
  }
13798
14079
  if (DataType.isDecimal(type)) {
13799
14080
  const scale = 1 / Math.pow(10, type.scale);
13800
14081
  const size = column2.length;
13801
- const array = new Float64Array(size);
14082
+ const array = column2.nullCount ? new Array(size) : new Float64Array(size);
13802
14083
  for (let row = 0; row < size; ++row) {
13803
14084
  const v2 = column2.get(row);
13804
- array[row] = v2 == null ? NaN : decimalToNumber(v2, scale);
14085
+ array[row] = v2 == null ? null : decimalToNumber(v2, scale);
13805
14086
  }
13806
14087
  return array;
13807
14088
  }
14089
+ if (column2.nullCount) {
14090
+ return Array.from(column2);
14091
+ }
13808
14092
  return column2.toArray();
13809
14093
  }
13810
14094
  var BASE32 = Array.from(
@@ -13911,58 +14195,92 @@ function coordinator(instance16) {
13911
14195
  return _instance;
13912
14196
  }
13913
14197
  var Coordinator = class {
13914
- constructor(db = socketConnector(), options = {}) {
13915
- const {
13916
- logger = console,
13917
- manager = QueryManager()
13918
- } = options;
14198
+ constructor(db = socketConnector(), {
14199
+ logger = console,
14200
+ manager = new QueryManager(),
14201
+ cache = true,
14202
+ consolidate: consolidate2 = true,
14203
+ indexes = {}
14204
+ } = {}) {
13919
14205
  this.manager = manager;
14206
+ this.manager.cache(cache);
14207
+ this.manager.consolidate(consolidate2);
14208
+ this.dataCubeIndexer = new DataCubeIndexer(this, indexes);
13920
14209
  this.logger(logger);
13921
- this.configure(options);
13922
14210
  this.databaseConnector(db);
13923
14211
  this.clear();
13924
14212
  }
13925
- logger(logger) {
13926
- if (arguments.length) {
13927
- this._logger = logger || voidLogger();
13928
- this.manager.logger(this._logger);
13929
- }
13930
- return this._logger;
13931
- }
13932
14213
  /**
13933
- * Set configuration options for this coordinator.
13934
- * @param {object} [options] Configration options.
13935
- * @param {boolean} [options.cache=true] Boolean flag to enable/disable query caching.
13936
- * @param {boolean} [options.consolidate=true] Boolean flag to enable/disable query consolidation.
13937
- * @param {boolean|object} [options.indexes=true] Boolean flag to enable/disable
13938
- * automatic data cube indexes or an index options object.
14214
+ * Clear the coordinator state.
14215
+ * @param {object} [options] Options object.
14216
+ * @param {boolean} [options.clients=true] If true, disconnect all clients.
14217
+ * @param {boolean} [options.cache=true] If true, clear the query cache.
13939
14218
  */
13940
- configure({ cache = true, consolidate: consolidate2 = true, indexes = true } = {}) {
13941
- this.manager.cache(cache);
13942
- this.manager.consolidate(consolidate2);
13943
- this.indexes = indexes;
13944
- }
13945
14219
  clear({ clients = true, cache = true } = {}) {
13946
14220
  this.manager.clear();
13947
14221
  if (clients) {
14222
+ this.filterGroups?.forEach((group) => group.disconnect());
14223
+ this.filterGroups = /* @__PURE__ */ new Map();
13948
14224
  this.clients?.forEach((client) => this.disconnect(client));
13949
- this.filterGroups?.forEach((group) => group.finalize());
13950
14225
  this.clients = /* @__PURE__ */ new Set();
13951
- this.filterGroups = /* @__PURE__ */ new Map();
13952
14226
  }
13953
14227
  if (cache) this.manager.cache().clear();
13954
14228
  }
14229
+ /**
14230
+ * Get or set the database connector.
14231
+ * @param {*} [db] The database connector to use.
14232
+ * @returns The current database connector.
14233
+ */
13955
14234
  databaseConnector(db) {
13956
14235
  return this.manager.connector(db);
13957
14236
  }
14237
+ /**
14238
+ * Get or set the logger.
14239
+ * @param {*} logger The logger to use.
14240
+ * @returns The current logger
14241
+ */
14242
+ logger(logger) {
14243
+ if (arguments.length) {
14244
+ this._logger = logger || voidLogger();
14245
+ this.manager.logger(this._logger);
14246
+ }
14247
+ return this._logger;
14248
+ }
13958
14249
  // -- Query Management ----
14250
+ /**
14251
+ * Cancel previosuly submitted query requests. These queries will be
14252
+ * canceled if they are queued but have not yet been submitted.
14253
+ * @param {import('./util/query-result.js').QueryResult[]} requests An array
14254
+ * of query result objects, such as those returned by the `query` method.
14255
+ */
13959
14256
  cancel(requests) {
13960
14257
  this.manager.cancel(requests);
13961
14258
  }
14259
+ /**
14260
+ * Issue a query for which no result (return value) is needed.
14261
+ * @param {import('@uwdata/mosaic-sql').Query | string} query The query.
14262
+ * @param {object} [options] An options object.
14263
+ * @param {number} [options.priority] The query priority, defaults to
14264
+ * `Priority.Normal`.
14265
+ * @returns {import('./util/query-result.js').QueryResult} A query result
14266
+ * promise.
14267
+ */
13962
14268
  exec(query, { priority = Priority.Normal } = {}) {
13963
14269
  query = Array.isArray(query) ? query.join(";\n") : query;
13964
14270
  return this.manager.request({ type: "exec", query }, priority);
13965
14271
  }
14272
+ /**
14273
+ * Issue a query to the backing database. The submitted query may be
14274
+ * consolidate with other queries and its results may be cached.
14275
+ * @param {import('@uwdata/mosaic-sql').Query | string} query The query.
14276
+ * @param {object} [options] An options object.
14277
+ * @param {'arrow' | 'json'} [options.type] The query result format type.
14278
+ * @param {boolean} [options.cache=true] If true, cache the query result.
14279
+ * @param {number} [options.priority] The query priority, defaults to
14280
+ * `Priority.Normal`.
14281
+ * @returns {import('./util/query-result.js').QueryResult} A query result
14282
+ * promise.
14283
+ */
13966
14284
  query(query, {
13967
14285
  type = "arrow",
13968
14286
  cache = true,
@@ -13971,6 +14289,15 @@ var Coordinator = class {
13971
14289
  } = {}) {
13972
14290
  return this.manager.request({ type, query, cache, options }, priority);
13973
14291
  }
14292
+ /**
14293
+ * Issue a query to prefetch data for later use. The query result is cached
14294
+ * for efficient future access.
14295
+ * @param {import('@uwdata/mosaic-sql').Query | string} query The query.
14296
+ * @param {object} [options] An options object.
14297
+ * @param {'arrow' | 'json'} [options.type] The query result format type.
14298
+ * @returns {import('./util/query-result.js').QueryResult} A query result
14299
+ * promise.
14300
+ */
13974
14301
  prefetch(query, options = {}) {
13975
14302
  return this.query(query, { ...options, cache: true, priority: Priority.Low });
13976
14303
  }
@@ -13983,26 +14310,44 @@ var Coordinator = class {
13983
14310
  return this.manager.request({ type: "load-bundle", options }, priority);
13984
14311
  }
13985
14312
  // -- Client Management ----
14313
+ /**
14314
+ * Update client data by submitting the given query and returning the
14315
+ * data (or error) to the client.
14316
+ * @param {import('./MosaicClient.js').MosaicClient} client A Mosaic client.
14317
+ * @param {import('@uwdata/mosaic-sql').Query | string} query The data query.
14318
+ * @param {number} [priority] The query priority.
14319
+ * @returns {Promise} A Promise that resolves upon completion of the update.
14320
+ */
13986
14321
  updateClient(client, query, priority = Priority.Normal) {
13987
14322
  client.queryPending();
13988
14323
  return this.query(query, { priority }).then(
13989
14324
  (data) => client.queryResult(data).update(),
13990
14325
  (err) => {
13991
- client.queryError(err);
13992
14326
  this._logger.error(err);
14327
+ client.queryError(err);
13993
14328
  }
13994
- );
14329
+ ).catch((err) => this._logger.error(err));
13995
14330
  }
14331
+ /**
14332
+ * Issue a query request for a client. If the query is null or undefined,
14333
+ * the client is simply updated. Otherwise `updateClient` is called. As a
14334
+ * side effect, this method clears the current data cube indexer state.
14335
+ * @param {import('./MosaicClient.js').MosaicClient} client The client
14336
+ * to update.
14337
+ * @param {import('@uwdata/mosaic-sql').Query | string | null} [query]
14338
+ * The query to issue.
14339
+ */
13996
14340
  requestQuery(client, query) {
13997
- this.filterGroups.get(client.filterBy)?.reset();
14341
+ this.dataCubeIndexer.clear();
13998
14342
  return query ? this.updateClient(client, query) : client.update();
13999
14343
  }
14000
14344
  /**
14001
14345
  * Connect a client to the coordinator.
14002
- * @param {import('./MosaicClient.js').MosaicClient} client the client to disconnect
14346
+ * @param {import('./MosaicClient.js').MosaicClient} client The Mosaic
14347
+ * client to connect.
14003
14348
  */
14004
14349
  async connect(client) {
14005
- const { clients, filterGroups, indexes } = this;
14350
+ const { clients } = this;
14006
14351
  if (clients.has(client)) {
14007
14352
  throw new Error("Client already connected.");
14008
14353
  }
@@ -14012,30 +14357,64 @@ var Coordinator = class {
14012
14357
  if (fields?.length) {
14013
14358
  client.fieldInfo(await queryFieldInfo(this, fields));
14014
14359
  }
14015
- const filter = client.filterBy;
14016
- if (filter) {
14017
- if (filterGroups.has(filter)) {
14018
- filterGroups.get(filter).add(client);
14019
- } else {
14020
- const group = new FilterGroup(this, filter, indexes);
14021
- filterGroups.set(filter, group.add(client));
14022
- }
14023
- }
14360
+ connectSelection(this, client.filterBy, client);
14024
14361
  client.requestQuery();
14025
14362
  }
14026
14363
  /**
14027
14364
  * Disconnect a client from the coordinator.
14028
- *
14029
- * @param {import('./MosaicClient.js').MosaicClient} client the client to disconnect
14365
+ * @param {import('./MosaicClient.js').MosaicClient} client The Mosaic
14366
+ * client to disconnect.
14030
14367
  */
14031
14368
  disconnect(client) {
14032
14369
  const { clients, filterGroups } = this;
14033
14370
  if (!clients.has(client)) return;
14034
14371
  clients.delete(client);
14035
- filterGroups.get(client.filterBy)?.remove(client);
14036
14372
  client.coordinator = null;
14373
+ const group = filterGroups.get(client.filterBy);
14374
+ if (group) {
14375
+ group.clients.delete(client);
14376
+ }
14037
14377
  }
14038
14378
  };
14379
+ function connectSelection(mc, selection, client) {
14380
+ if (!selection) return;
14381
+ let entry = mc.filterGroups.get(selection);
14382
+ if (!entry) {
14383
+ const activate = (clause) => activateSelection(mc, selection, clause);
14384
+ const value = () => updateSelection(mc, selection);
14385
+ selection.addEventListener("activate", activate);
14386
+ selection.addEventListener("value", value);
14387
+ entry = {
14388
+ selection,
14389
+ clients: /* @__PURE__ */ new Set(),
14390
+ disconnect() {
14391
+ selection.removeEventListener("activate", activate);
14392
+ selection.removeEventListener("value", value);
14393
+ }
14394
+ };
14395
+ mc.filterGroups.set(selection, entry);
14396
+ }
14397
+ entry.clients.add(client);
14398
+ }
14399
+ function activateSelection(mc, selection, clause) {
14400
+ const { dataCubeIndexer, filterGroups } = mc;
14401
+ const { clients } = filterGroups.get(selection);
14402
+ for (const client of clients) {
14403
+ dataCubeIndexer.index(client, selection, clause);
14404
+ }
14405
+ }
14406
+ function updateSelection(mc, selection) {
14407
+ const { dataCubeIndexer, filterGroups } = mc;
14408
+ const { clients } = filterGroups.get(selection);
14409
+ const { active } = selection;
14410
+ return Promise.allSettled(Array.from(clients, (client) => {
14411
+ const info = dataCubeIndexer.index(client, selection, active);
14412
+ const filter = info ? null : selection.predicate(client);
14413
+ if (info?.skip || !info && !filter) return;
14414
+ const query = info?.query(active.predicate) ?? client.query(filter);
14415
+ return mc.updateClient(client, query);
14416
+ }));
14417
+ }
14039
14418
 
14040
14419
  // src/util/AsyncDispatch.js
14041
14420
  var AsyncDispatch = class {
@@ -14092,7 +14471,7 @@ var AsyncDispatch = class {
14092
14471
  * queue of unemitted event values prior to enqueueing a new value.
14093
14472
  * This default implementation simply returns null, indicating that
14094
14473
  * any other unemitted event values should be dropped (that is, all
14095
- * queued events are filtered)
14474
+ * queued events are filtered).
14096
14475
  * @param {string} type The event type.
14097
14476
  * @param {*} value The new event value that will be enqueued.
14098
14477
  * @returns {(value: *) => boolean|null} A dispatch queue filter
@@ -14109,6 +14488,16 @@ var AsyncDispatch = class {
14109
14488
  const entry = this._callbacks.get(type);
14110
14489
  entry?.queue.clear();
14111
14490
  }
14491
+ /**
14492
+ * Returns a promise that resolves when any pending updates complete for
14493
+ * the event of the given type currently being processed. The Promise will
14494
+ * resolve immediately if the queue for the given event type is empty.
14495
+ * @param {string} type The event type to wait for.
14496
+ * @returns {Promise} A pending event promise.
14497
+ */
14498
+ async pending(type) {
14499
+ await this._callbacks.get(type)?.pending;
14500
+ }
14112
14501
  /**
14113
14502
  * Emit an event value to listeners for the given event type.
14114
14503
  * If a previous emit has not yet resolved, the event value
@@ -14296,10 +14685,13 @@ var Selection = class _Selection extends Param {
14296
14685
  * @param {boolean} [options.cross=false] Boolean flag indicating
14297
14686
  * cross-filtered resolution. If true, selection clauses will not
14298
14687
  * be applied to the clients they are associated with.
14688
+ * @param {boolean} [options.empty=false] Boolean flag indicating if a lack
14689
+ * of clauses should correspond to an empty selection with no records. This
14690
+ * setting determines the default selection state.
14299
14691
  * @returns {Selection} The new Selection instance.
14300
14692
  */
14301
- static intersect({ cross = false } = {}) {
14302
- return new _Selection(new SelectionResolver({ cross }));
14693
+ static intersect({ cross = false, empty = false } = {}) {
14694
+ return new _Selection(new SelectionResolver({ cross, empty }));
14303
14695
  }
14304
14696
  /**
14305
14697
  * Create a new Selection instance with a
@@ -14308,10 +14700,13 @@ var Selection = class _Selection extends Param {
14308
14700
  * @param {boolean} [options.cross=false] Boolean flag indicating
14309
14701
  * cross-filtered resolution. If true, selection clauses will not
14310
14702
  * be applied to the clients they are associated with.
14703
+ * @param {boolean} [options.empty=false] Boolean flag indicating if a lack
14704
+ * of clauses should correspond to an empty selection with no records. This
14705
+ * setting determines the default selection state.
14311
14706
  * @returns {Selection} The new Selection instance.
14312
14707
  */
14313
- static union({ cross = false } = {}) {
14314
- return new _Selection(new SelectionResolver({ cross, union: true }));
14708
+ static union({ cross = false, empty = false } = {}) {
14709
+ return new _Selection(new SelectionResolver({ cross, empty, union: true }));
14315
14710
  }
14316
14711
  /**
14317
14712
  * Create a new Selection instance with a singular resolution strategy
@@ -14320,18 +14715,25 @@ var Selection = class _Selection extends Param {
14320
14715
  * @param {boolean} [options.cross=false] Boolean flag indicating
14321
14716
  * cross-filtered resolution. If true, selection clauses will not
14322
14717
  * be applied to the clients they are associated with.
14718
+ * @param {boolean} [options.empty=false] Boolean flag indicating if a lack
14719
+ * of clauses should correspond to an empty selection with no records. This
14720
+ * setting determines the default selection state.
14323
14721
  * @returns {Selection} The new Selection instance.
14324
14722
  */
14325
- static single({ cross = false } = {}) {
14326
- return new _Selection(new SelectionResolver({ cross, single: true }));
14723
+ static single({ cross = false, empty = false } = {}) {
14724
+ return new _Selection(new SelectionResolver({ cross, empty, single: true }));
14327
14725
  }
14328
14726
  /**
14329
14727
  * Create a new Selection instance with a
14330
14728
  * cross-filtered intersect resolution strategy.
14729
+ * @param {object} [options] The selection options.
14730
+ * @param {boolean} [options.empty=false] Boolean flag indicating if a lack
14731
+ * of clauses should correspond to an empty selection with no records. This
14732
+ * setting determines the default selection state.
14331
14733
  * @returns {Selection} The new Selection instance.
14332
14734
  */
14333
- static crossfilter() {
14334
- return new _Selection(new SelectionResolver({ cross: true }));
14735
+ static crossfilter({ empty = false } = {}) {
14736
+ return new _Selection(new SelectionResolver({ cross: true, empty }));
14335
14737
  }
14336
14738
  /**
14337
14739
  * Create a new Selection instance.
@@ -14364,6 +14766,24 @@ var Selection = class _Selection extends Param {
14364
14766
  s._value.active = { source };
14365
14767
  return s;
14366
14768
  }
14769
+ /**
14770
+ * The selection clause resolver.
14771
+ */
14772
+ get resolver() {
14773
+ return this._resolver;
14774
+ }
14775
+ /**
14776
+ * Indicate if this selection has a single resolution strategy.
14777
+ */
14778
+ get single() {
14779
+ return this._resolver.single;
14780
+ }
14781
+ /**
14782
+ * The current array of selection clauses.
14783
+ */
14784
+ get clauses() {
14785
+ return super.value;
14786
+ }
14367
14787
  /**
14368
14788
  * The current active (most recently updated) selection clause.
14369
14789
  */
@@ -14378,16 +14798,12 @@ var Selection = class _Selection extends Param {
14378
14798
  return this.active?.value;
14379
14799
  }
14380
14800
  /**
14381
- * The current array of selection clauses.
14382
- */
14383
- get clauses() {
14384
- return super.value;
14385
- }
14386
- /**
14387
- * Indicate if this selection has a single resolution strategy.
14801
+ * The value corresponding to a given source. Returns undefined if
14802
+ * this selection does not include a clause from this source.
14803
+ * @param {*} source The clause source to look up the value for.
14388
14804
  */
14389
- get single() {
14390
- return this._resolver.single;
14805
+ valueFor(source) {
14806
+ return this.clauses.find((c) => c.source === source)?.value;
14391
14807
  }
14392
14808
  /**
14393
14809
  * Emit an activate event with the given selection clause.
@@ -14465,11 +14881,15 @@ var SelectionResolver = class {
14465
14881
  * If false, an intersection strategy is used.
14466
14882
  * @param {boolean} [options.cross=false] Boolean flag to indicate cross-filtering.
14467
14883
  * @param {boolean} [options.single=false] Boolean flag to indicate single clauses only.
14884
+ * @param {boolean} [options.empty=false] Boolean flag indicating if a lack
14885
+ * of clauses should correspond to an empty selection with no records. This
14886
+ * setting determines the default selection state.
14468
14887
  */
14469
- constructor({ union, cross, single } = {}) {
14888
+ constructor({ union, cross, single, empty } = {}) {
14470
14889
  this.union = !!union;
14471
14890
  this.cross = !!cross;
14472
14891
  this.single = !!single;
14892
+ this.empty = !!empty;
14473
14893
  }
14474
14894
  /**
14475
14895
  * Resolve a list of selection clauses according to the resolution strategy.
@@ -14504,7 +14924,10 @@ var SelectionResolver = class {
14504
14924
  * based on the current state of this selection.
14505
14925
  */
14506
14926
  predicate(clauseList, active, client) {
14507
- const { union } = this;
14927
+ const { empty, union } = this;
14928
+ if (empty && !clauseList.length) {
14929
+ return ["FALSE"];
14930
+ }
14508
14931
  if (this.skip(client, active)) return void 0;
14509
14932
  const predicates = clauseList.filter((clause) => !this.skip(client, clause)).map((clause) => clause.predicate);
14510
14933
  return union && predicates.length > 1 ? or(predicates) : predicates;
@@ -14527,6 +14950,13 @@ var SelectionResolver = class {
14527
14950
  // src/connectors/rest.js
14528
14951
  function restConnector(uri = "http://localhost:3000/") {
14529
14952
  return {
14953
+ /**
14954
+ * Query the DuckDB server.
14955
+ * @param {object} query
14956
+ * @param {'exec' | 'arrow' | 'json'} [query.type] The query type: 'exec', 'arrow', or 'json'.
14957
+ * @param {string} query.sql A SQL query string.
14958
+ * @returns the query result
14959
+ */
14530
14960
  async query(query) {
14531
14961
  const req = fetch(uri, {
14532
14962
  method: "POST",
@@ -15168,7 +15598,7 @@ var BufferType2;
15168
15598
  // ../../node_modules/@duckdb/duckdb-wasm/node_modules/apache-arrow/util/vector.mjs
15169
15599
  var vector_exports2 = {};
15170
15600
  __export(vector_exports2, {
15171
- clampIndex: () => clampIndex2,
15601
+ clampIndex: () => clampIndex,
15172
15602
  clampRange: () => clampRange2,
15173
15603
  createElementComparator: () => createElementComparator2
15174
15604
  });
@@ -16467,15 +16897,15 @@ function wrapSet2(fn) {
16467
16897
  var setEpochMsToDays2 = (data, index, epochMs) => {
16468
16898
  data[index] = Math.trunc(epochMs / 864e5);
16469
16899
  };
16470
- var setEpochMsToMillisecondsLong2 = (data, index, epochMs) => {
16900
+ var setEpochMsToMillisecondsLong = (data, index, epochMs) => {
16471
16901
  data[index] = Math.trunc(epochMs % 4294967296);
16472
16902
  data[index + 1] = Math.trunc(epochMs / 4294967296);
16473
16903
  };
16474
- var setEpochMsToMicrosecondsLong2 = (data, index, epochMs) => {
16904
+ var setEpochMsToMicrosecondsLong = (data, index, epochMs) => {
16475
16905
  data[index] = Math.trunc(epochMs * 1e3 % 4294967296);
16476
16906
  data[index + 1] = Math.trunc(epochMs * 1e3 / 4294967296);
16477
16907
  };
16478
- var setEpochMsToNanosecondsLong2 = (data, index, epochMs) => {
16908
+ var setEpochMsToNanosecondsLong = (data, index, epochMs) => {
16479
16909
  data[index] = Math.trunc(epochMs * 1e6 % 4294967296);
16480
16910
  data[index + 1] = Math.trunc(epochMs * 1e6 / 4294967296);
16481
16911
  };
@@ -16511,7 +16941,7 @@ var setDateDay2 = ({ values }, index, value) => {
16511
16941
  setEpochMsToDays2(values, index, value.valueOf());
16512
16942
  };
16513
16943
  var setDateMillisecond2 = ({ values }, index, value) => {
16514
- setEpochMsToMillisecondsLong2(values, index * 2, value.valueOf());
16944
+ setEpochMsToMillisecondsLong(values, index * 2, value.valueOf());
16515
16945
  };
16516
16946
  var setFixedSizeBinary2 = ({ stride, values }, index, value) => {
16517
16947
  values.set(value.subarray(0, stride), stride * index);
@@ -16523,10 +16953,10 @@ var setUtf82 = ({ values, valueOffsets }, index, value) => {
16523
16953
  var setDate2 = (data, index, value) => {
16524
16954
  data.type.unit === DateUnit2.DAY ? setDateDay2(data, index, value) : setDateMillisecond2(data, index, value);
16525
16955
  };
16526
- var setTimestampSecond2 = ({ values }, index, value) => setEpochMsToMillisecondsLong2(values, index * 2, value / 1e3);
16527
- var setTimestampMillisecond2 = ({ values }, index, value) => setEpochMsToMillisecondsLong2(values, index * 2, value);
16528
- var setTimestampMicrosecond2 = ({ values }, index, value) => setEpochMsToMicrosecondsLong2(values, index * 2, value);
16529
- var setTimestampNanosecond2 = ({ values }, index, value) => setEpochMsToNanosecondsLong2(values, index * 2, value);
16956
+ var setTimestampSecond2 = ({ values }, index, value) => setEpochMsToMillisecondsLong(values, index * 2, value / 1e3);
16957
+ var setTimestampMillisecond2 = ({ values }, index, value) => setEpochMsToMillisecondsLong(values, index * 2, value);
16958
+ var setTimestampMicrosecond2 = ({ values }, index, value) => setEpochMsToMicrosecondsLong(values, index * 2, value);
16959
+ var setTimestampNanosecond2 = ({ values }, index, value) => setEpochMsToNanosecondsLong(values, index * 2, value);
16530
16960
  var setTimestamp2 = (data, index, value) => {
16531
16961
  switch (data.type.unit) {
16532
16962
  case TimeUnit2.SECOND:
@@ -16829,12 +17259,12 @@ function wrapGet2(fn) {
16829
17259
  return (data, _1) => data.getValid(_1) ? fn(data, _1) : null;
16830
17260
  }
16831
17261
  var epochDaysToMs2 = (data, index) => 864e5 * data[index];
16832
- var epochMillisecondsLongToMs2 = (data, index) => 4294967296 * data[index + 1] + (data[index] >>> 0);
16833
- var epochMicrosecondsLongToMs2 = (data, index) => 4294967296 * (data[index + 1] / 1e3) + (data[index] >>> 0) / 1e3;
16834
- var epochNanosecondsLongToMs2 = (data, index) => 4294967296 * (data[index + 1] / 1e6) + (data[index] >>> 0) / 1e6;
16835
- var epochMillisecondsToDate2 = (epochMs) => new Date(epochMs);
16836
- var epochDaysToDate2 = (data, index) => epochMillisecondsToDate2(epochDaysToMs2(data, index));
16837
- var epochMillisecondsLongToDate2 = (data, index) => epochMillisecondsToDate2(epochMillisecondsLongToMs2(data, index));
17262
+ var epochMillisecondsLongToMs = (data, index) => 4294967296 * data[index + 1] + (data[index] >>> 0);
17263
+ var epochMicrosecondsLongToMs = (data, index) => 4294967296 * (data[index + 1] / 1e3) + (data[index] >>> 0) / 1e3;
17264
+ var epochNanosecondsLongToMs = (data, index) => 4294967296 * (data[index + 1] / 1e6) + (data[index] >>> 0) / 1e6;
17265
+ var epochMillisecondsToDate = (epochMs) => new Date(epochMs);
17266
+ var epochDaysToDate = (data, index) => epochMillisecondsToDate(epochDaysToMs2(data, index));
17267
+ var epochMillisecondsLongToDate = (data, index) => epochMillisecondsToDate(epochMillisecondsLongToMs(data, index));
16838
17268
  var getNull2 = (_data, _index) => null;
16839
17269
  var getVariableWidthBytes2 = (values, valueOffsets, index) => {
16840
17270
  if (index + 1 >= valueOffsets.length) {
@@ -16849,8 +17279,8 @@ var getBool3 = ({ offset, values }, index) => {
16849
17279
  const byte = values[idx >> 3];
16850
17280
  return (byte & 1 << idx % 8) !== 0;
16851
17281
  };
16852
- var getDateDay2 = ({ values }, index) => epochDaysToDate2(values, index);
16853
- var getDateMillisecond2 = ({ values }, index) => epochMillisecondsLongToDate2(values, index * 2);
17282
+ var getDateDay2 = ({ values }, index) => epochDaysToDate(values, index);
17283
+ var getDateMillisecond2 = ({ values }, index) => epochMillisecondsLongToDate(values, index * 2);
16854
17284
  var getNumeric2 = ({ stride, values }, index) => values[stride * index];
16855
17285
  var getFloat162 = ({ stride, values }, index) => uint16ToFloat642(values[stride * index]);
16856
17286
  var getBigInts2 = ({ values }, index) => values[index];
@@ -16863,10 +17293,10 @@ var getUtf82 = ({ values, valueOffsets }, index) => {
16863
17293
  var getInt2 = ({ values }, index) => values[index];
16864
17294
  var getFloat2 = ({ type, values }, index) => type.precision !== Precision2.HALF ? values[index] : uint16ToFloat642(values[index]);
16865
17295
  var getDate2 = (data, index) => data.type.unit === DateUnit2.DAY ? getDateDay2(data, index) : getDateMillisecond2(data, index);
16866
- var getTimestampSecond2 = ({ values }, index) => 1e3 * epochMillisecondsLongToMs2(values, index * 2);
16867
- var getTimestampMillisecond2 = ({ values }, index) => epochMillisecondsLongToMs2(values, index * 2);
16868
- var getTimestampMicrosecond2 = ({ values }, index) => epochMicrosecondsLongToMs2(values, index * 2);
16869
- var getTimestampNanosecond2 = ({ values }, index) => epochNanosecondsLongToMs2(values, index * 2);
17296
+ var getTimestampSecond2 = ({ values }, index) => 1e3 * epochMillisecondsLongToMs(values, index * 2);
17297
+ var getTimestampMillisecond2 = ({ values }, index) => epochMillisecondsLongToMs(values, index * 2);
17298
+ var getTimestampMicrosecond2 = ({ values }, index) => epochMicrosecondsLongToMs(values, index * 2);
17299
+ var getTimestampNanosecond2 = ({ values }, index) => epochNanosecondsLongToMs(values, index * 2);
16870
17300
  var getTimestamp2 = (data, index) => {
16871
17301
  switch (data.type.unit) {
16872
17302
  case TimeUnit2.SECOND:
@@ -17121,7 +17551,7 @@ Object.defineProperties(MapRow2.prototype, {
17121
17551
  });
17122
17552
 
17123
17553
  // ../../node_modules/@duckdb/duckdb-wasm/node_modules/apache-arrow/util/vector.mjs
17124
- function clampIndex2(source, index, then) {
17554
+ function clampIndex(source, index, then) {
17125
17555
  const length2 = source.length;
17126
17556
  const adjust = index > -1 ? index : length2 + index % length2;
17127
17557
  return then ? then(source, adjust) : adjust;
@@ -18721,133 +19151,880 @@ var Builder5 = class {
18721
19151
  });
18722
19152
  }
18723
19153
  /**
18724
- * Finalize this `Builder`, and child builders if applicable.
18725
- * @returns {this} The finalized `Builder` instance.
19154
+ * Finalize this `Builder`, and child builders if applicable.
19155
+ * @returns {this} The finalized `Builder` instance.
19156
+ */
19157
+ finish() {
19158
+ this.finished = true;
19159
+ for (const child of this.children)
19160
+ child.finish();
19161
+ return this;
19162
+ }
19163
+ /**
19164
+ * Clear this Builder's internal state, including child Builders if applicable, and reset the length to 0.
19165
+ * @returns {this} The cleared `Builder` instance.
19166
+ */
19167
+ clear() {
19168
+ var _a9, _b3, _c3, _d3;
19169
+ this.length = 0;
19170
+ (_a9 = this._nulls) === null || _a9 === void 0 ? void 0 : _a9.clear();
19171
+ (_b3 = this._values) === null || _b3 === void 0 ? void 0 : _b3.clear();
19172
+ (_c3 = this._offsets) === null || _c3 === void 0 ? void 0 : _c3.clear();
19173
+ (_d3 = this._typeIds) === null || _d3 === void 0 ? void 0 : _d3.clear();
19174
+ for (const child of this.children)
19175
+ child.clear();
19176
+ return this;
19177
+ }
19178
+ };
19179
+ Builder5.prototype.length = 1;
19180
+ Builder5.prototype.stride = 1;
19181
+ Builder5.prototype.children = null;
19182
+ Builder5.prototype.finished = false;
19183
+ Builder5.prototype.nullValues = null;
19184
+ Builder5.prototype._isValid = () => true;
19185
+ var FixedWidthBuilder2 = class extends Builder5 {
19186
+ constructor(opts) {
19187
+ super(opts);
19188
+ this._values = new DataBufferBuilder2(new this.ArrayType(0), this.stride);
19189
+ }
19190
+ setValue(index, value) {
19191
+ const values = this._values;
19192
+ values.reserve(index - values.length + 1);
19193
+ return super.setValue(index, value);
19194
+ }
19195
+ };
19196
+ var VariableWidthBuilder2 = class extends Builder5 {
19197
+ constructor(opts) {
19198
+ super(opts);
19199
+ this._pendingLength = 0;
19200
+ this._offsets = new OffsetsBufferBuilder2();
19201
+ }
19202
+ setValue(index, value) {
19203
+ const pending = this._pending || (this._pending = /* @__PURE__ */ new Map());
19204
+ const current = pending.get(index);
19205
+ current && (this._pendingLength -= current.length);
19206
+ this._pendingLength += value instanceof MapRow2 ? value[kKeys2].length : value.length;
19207
+ pending.set(index, value);
19208
+ }
19209
+ setValid(index, isValid) {
19210
+ if (!super.setValid(index, isValid)) {
19211
+ (this._pending || (this._pending = /* @__PURE__ */ new Map())).set(index, void 0);
19212
+ return false;
19213
+ }
19214
+ return true;
19215
+ }
19216
+ clear() {
19217
+ this._pendingLength = 0;
19218
+ this._pending = void 0;
19219
+ return super.clear();
19220
+ }
19221
+ flush() {
19222
+ this._flush();
19223
+ return super.flush();
19224
+ }
19225
+ finish() {
19226
+ this._flush();
19227
+ return super.finish();
19228
+ }
19229
+ _flush() {
19230
+ const pending = this._pending;
19231
+ const pendingLength = this._pendingLength;
19232
+ this._pendingLength = 0;
19233
+ this._pending = void 0;
19234
+ if (pending && pending.size > 0) {
19235
+ this._flushPending(pending, pendingLength);
19236
+ }
19237
+ return this;
19238
+ }
19239
+ };
19240
+
19241
+ // ../../node_modules/@duckdb/duckdb-wasm/node_modules/apache-arrow/fb/block.mjs
19242
+ var Block2 = class {
19243
+ constructor() {
19244
+ this.bb = null;
19245
+ this.bb_pos = 0;
19246
+ }
19247
+ __init(i, bb) {
19248
+ this.bb_pos = i;
19249
+ this.bb = bb;
19250
+ return this;
19251
+ }
19252
+ /**
19253
+ * Index to the start of the RecordBlock (note this is past the Message header)
19254
+ */
19255
+ offset() {
19256
+ return this.bb.readInt64(this.bb_pos);
19257
+ }
19258
+ /**
19259
+ * Length of the metadata
19260
+ */
19261
+ metaDataLength() {
19262
+ return this.bb.readInt32(this.bb_pos + 8);
19263
+ }
19264
+ /**
19265
+ * Length of the data (this is aligned so there can be a gap between this and
19266
+ * the metadata).
19267
+ */
19268
+ bodyLength() {
19269
+ return this.bb.readInt64(this.bb_pos + 16);
19270
+ }
19271
+ static sizeOf() {
19272
+ return 24;
19273
+ }
19274
+ static createBlock(builder, offset, metaDataLength, bodyLength) {
19275
+ builder.prep(8, 24);
19276
+ builder.writeInt64(BigInt(bodyLength !== null && bodyLength !== void 0 ? bodyLength : 0));
19277
+ builder.pad(4);
19278
+ builder.writeInt32(metaDataLength);
19279
+ builder.writeInt64(BigInt(offset !== null && offset !== void 0 ? offset : 0));
19280
+ return builder.offset();
19281
+ }
19282
+ };
19283
+
19284
+ // ../../node_modules/flatbuffers/mjs/constants.js
19285
+ var SIZEOF_SHORT2 = 2;
19286
+ var SIZEOF_INT2 = 4;
19287
+ var FILE_IDENTIFIER_LENGTH2 = 4;
19288
+ var SIZE_PREFIX_LENGTH2 = 4;
19289
+
19290
+ // ../../node_modules/flatbuffers/mjs/utils.js
19291
+ var int322 = new Int32Array(2);
19292
+ var float322 = new Float32Array(int322.buffer);
19293
+ var float642 = new Float64Array(int322.buffer);
19294
+ var isLittleEndian2 = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
19295
+
19296
+ // ../../node_modules/flatbuffers/mjs/encoding.js
19297
+ var Encoding2;
19298
+ (function(Encoding3) {
19299
+ Encoding3[Encoding3["UTF8_BYTES"] = 1] = "UTF8_BYTES";
19300
+ Encoding3[Encoding3["UTF16_STRING"] = 2] = "UTF16_STRING";
19301
+ })(Encoding2 || (Encoding2 = {}));
19302
+
19303
+ // ../../node_modules/flatbuffers/mjs/byte-buffer.js
19304
+ var ByteBuffer4 = class _ByteBuffer {
19305
+ /**
19306
+ * Create a new ByteBuffer with a given array of bytes (`Uint8Array`)
19307
+ */
19308
+ constructor(bytes_) {
19309
+ this.bytes_ = bytes_;
19310
+ this.position_ = 0;
19311
+ this.text_decoder_ = new TextDecoder();
19312
+ }
19313
+ /**
19314
+ * Create and allocate a new ByteBuffer with a given size.
19315
+ */
19316
+ static allocate(byte_size) {
19317
+ return new _ByteBuffer(new Uint8Array(byte_size));
19318
+ }
19319
+ clear() {
19320
+ this.position_ = 0;
19321
+ }
19322
+ /**
19323
+ * Get the underlying `Uint8Array`.
19324
+ */
19325
+ bytes() {
19326
+ return this.bytes_;
19327
+ }
19328
+ /**
19329
+ * Get the buffer's position.
19330
+ */
19331
+ position() {
19332
+ return this.position_;
19333
+ }
19334
+ /**
19335
+ * Set the buffer's position.
19336
+ */
19337
+ setPosition(position) {
19338
+ this.position_ = position;
19339
+ }
19340
+ /**
19341
+ * Get the buffer's capacity.
19342
+ */
19343
+ capacity() {
19344
+ return this.bytes_.length;
19345
+ }
19346
+ readInt8(offset) {
19347
+ return this.readUint8(offset) << 24 >> 24;
19348
+ }
19349
+ readUint8(offset) {
19350
+ return this.bytes_[offset];
19351
+ }
19352
+ readInt16(offset) {
19353
+ return this.readUint16(offset) << 16 >> 16;
19354
+ }
19355
+ readUint16(offset) {
19356
+ return this.bytes_[offset] | this.bytes_[offset + 1] << 8;
19357
+ }
19358
+ readInt32(offset) {
19359
+ return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24;
19360
+ }
19361
+ readUint32(offset) {
19362
+ return this.readInt32(offset) >>> 0;
19363
+ }
19364
+ readInt64(offset) {
19365
+ return BigInt.asIntN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
19366
+ }
19367
+ readUint64(offset) {
19368
+ return BigInt.asUintN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
19369
+ }
19370
+ readFloat32(offset) {
19371
+ int322[0] = this.readInt32(offset);
19372
+ return float322[0];
19373
+ }
19374
+ readFloat64(offset) {
19375
+ int322[isLittleEndian2 ? 0 : 1] = this.readInt32(offset);
19376
+ int322[isLittleEndian2 ? 1 : 0] = this.readInt32(offset + 4);
19377
+ return float642[0];
19378
+ }
19379
+ writeInt8(offset, value) {
19380
+ this.bytes_[offset] = value;
19381
+ }
19382
+ writeUint8(offset, value) {
19383
+ this.bytes_[offset] = value;
19384
+ }
19385
+ writeInt16(offset, value) {
19386
+ this.bytes_[offset] = value;
19387
+ this.bytes_[offset + 1] = value >> 8;
19388
+ }
19389
+ writeUint16(offset, value) {
19390
+ this.bytes_[offset] = value;
19391
+ this.bytes_[offset + 1] = value >> 8;
19392
+ }
19393
+ writeInt32(offset, value) {
19394
+ this.bytes_[offset] = value;
19395
+ this.bytes_[offset + 1] = value >> 8;
19396
+ this.bytes_[offset + 2] = value >> 16;
19397
+ this.bytes_[offset + 3] = value >> 24;
19398
+ }
19399
+ writeUint32(offset, value) {
19400
+ this.bytes_[offset] = value;
19401
+ this.bytes_[offset + 1] = value >> 8;
19402
+ this.bytes_[offset + 2] = value >> 16;
19403
+ this.bytes_[offset + 3] = value >> 24;
19404
+ }
19405
+ writeInt64(offset, value) {
19406
+ this.writeInt32(offset, Number(BigInt.asIntN(32, value)));
19407
+ this.writeInt32(offset + 4, Number(BigInt.asIntN(32, value >> BigInt(32))));
19408
+ }
19409
+ writeUint64(offset, value) {
19410
+ this.writeUint32(offset, Number(BigInt.asUintN(32, value)));
19411
+ this.writeUint32(offset + 4, Number(BigInt.asUintN(32, value >> BigInt(32))));
19412
+ }
19413
+ writeFloat32(offset, value) {
19414
+ float322[0] = value;
19415
+ this.writeInt32(offset, int322[0]);
19416
+ }
19417
+ writeFloat64(offset, value) {
19418
+ float642[0] = value;
19419
+ this.writeInt32(offset, int322[isLittleEndian2 ? 0 : 1]);
19420
+ this.writeInt32(offset + 4, int322[isLittleEndian2 ? 1 : 0]);
19421
+ }
19422
+ /**
19423
+ * Return the file identifier. Behavior is undefined for FlatBuffers whose
19424
+ * schema does not include a file_identifier (likely points at padding or the
19425
+ * start of a the root vtable).
19426
+ */
19427
+ getBufferIdentifier() {
19428
+ if (this.bytes_.length < this.position_ + SIZEOF_INT2 + FILE_IDENTIFIER_LENGTH2) {
19429
+ throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");
19430
+ }
19431
+ let result = "";
19432
+ for (let i = 0; i < FILE_IDENTIFIER_LENGTH2; i++) {
19433
+ result += String.fromCharCode(this.readInt8(this.position_ + SIZEOF_INT2 + i));
19434
+ }
19435
+ return result;
19436
+ }
19437
+ /**
19438
+ * Look up a field in the vtable, return an offset into the object, or 0 if the
19439
+ * field is not present.
19440
+ */
19441
+ __offset(bb_pos, vtable_offset) {
19442
+ const vtable = bb_pos - this.readInt32(bb_pos);
19443
+ return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0;
19444
+ }
19445
+ /**
19446
+ * Initialize any Table-derived type to point to the union at the given offset.
19447
+ */
19448
+ __union(t, offset) {
19449
+ t.bb_pos = offset + this.readInt32(offset);
19450
+ t.bb = this;
19451
+ return t;
19452
+ }
19453
+ /**
19454
+ * Create a JavaScript string from UTF-8 data stored inside the FlatBuffer.
19455
+ * This allocates a new string and converts to wide chars upon each access.
19456
+ *
19457
+ * To avoid the conversion to string, pass Encoding.UTF8_BYTES as the
19458
+ * "optionalEncoding" argument. This is useful for avoiding conversion when
19459
+ * the data will just be packaged back up in another FlatBuffer later on.
19460
+ *
19461
+ * @param offset
19462
+ * @param opt_encoding Defaults to UTF16_STRING
19463
+ */
19464
+ __string(offset, opt_encoding) {
19465
+ offset += this.readInt32(offset);
19466
+ const length2 = this.readInt32(offset);
19467
+ offset += SIZEOF_INT2;
19468
+ const utf8bytes = this.bytes_.subarray(offset, offset + length2);
19469
+ if (opt_encoding === Encoding2.UTF8_BYTES)
19470
+ return utf8bytes;
19471
+ else
19472
+ return this.text_decoder_.decode(utf8bytes);
19473
+ }
19474
+ /**
19475
+ * Handle unions that can contain string as its member, if a Table-derived type then initialize it,
19476
+ * if a string then return a new one
19477
+ *
19478
+ * WARNING: strings are immutable in JS so we can't change the string that the user gave us, this
19479
+ * makes the behaviour of __union_with_string different compared to __union
19480
+ */
19481
+ __union_with_string(o, offset) {
19482
+ if (typeof o === "string") {
19483
+ return this.__string(offset);
19484
+ }
19485
+ return this.__union(o, offset);
19486
+ }
19487
+ /**
19488
+ * Retrieve the relative offset stored at "offset"
19489
+ */
19490
+ __indirect(offset) {
19491
+ return offset + this.readInt32(offset);
19492
+ }
19493
+ /**
19494
+ * Get the start of data of a vector whose offset is stored at "offset" in this object.
19495
+ */
19496
+ __vector(offset) {
19497
+ return offset + this.readInt32(offset) + SIZEOF_INT2;
19498
+ }
19499
+ /**
19500
+ * Get the length of a vector whose offset is stored at "offset" in this object.
19501
+ */
19502
+ __vector_len(offset) {
19503
+ return this.readInt32(offset + this.readInt32(offset));
19504
+ }
19505
+ __has_identifier(ident) {
19506
+ if (ident.length != FILE_IDENTIFIER_LENGTH2) {
19507
+ throw new Error("FlatBuffers: file identifier must be length " + FILE_IDENTIFIER_LENGTH2);
19508
+ }
19509
+ for (let i = 0; i < FILE_IDENTIFIER_LENGTH2; i++) {
19510
+ if (ident.charCodeAt(i) != this.readInt8(this.position() + SIZEOF_INT2 + i)) {
19511
+ return false;
19512
+ }
19513
+ }
19514
+ return true;
19515
+ }
19516
+ /**
19517
+ * A helper function for generating list for obj api
19518
+ */
19519
+ createScalarList(listAccessor, listLength) {
19520
+ const ret = [];
19521
+ for (let i = 0; i < listLength; ++i) {
19522
+ const val = listAccessor(i);
19523
+ if (val !== null) {
19524
+ ret.push(val);
19525
+ }
19526
+ }
19527
+ return ret;
19528
+ }
19529
+ /**
19530
+ * A helper function for generating list for obj api
19531
+ * @param listAccessor function that accepts an index and return data at that index
19532
+ * @param listLength listLength
19533
+ * @param res result list
19534
+ */
19535
+ createObjList(listAccessor, listLength) {
19536
+ const ret = [];
19537
+ for (let i = 0; i < listLength; ++i) {
19538
+ const val = listAccessor(i);
19539
+ if (val !== null) {
19540
+ ret.push(val.unpack());
19541
+ }
19542
+ }
19543
+ return ret;
19544
+ }
19545
+ };
19546
+
19547
+ // ../../node_modules/flatbuffers/mjs/builder.js
19548
+ var Builder6 = class _Builder {
19549
+ /**
19550
+ * Create a FlatBufferBuilder.
19551
+ */
19552
+ constructor(opt_initial_size) {
19553
+ this.minalign = 1;
19554
+ this.vtable = null;
19555
+ this.vtable_in_use = 0;
19556
+ this.isNested = false;
19557
+ this.object_start = 0;
19558
+ this.vtables = [];
19559
+ this.vector_num_elems = 0;
19560
+ this.force_defaults = false;
19561
+ this.string_maps = null;
19562
+ this.text_encoder = new TextEncoder();
19563
+ let initial_size;
19564
+ if (!opt_initial_size) {
19565
+ initial_size = 1024;
19566
+ } else {
19567
+ initial_size = opt_initial_size;
19568
+ }
19569
+ this.bb = ByteBuffer4.allocate(initial_size);
19570
+ this.space = initial_size;
19571
+ }
19572
+ clear() {
19573
+ this.bb.clear();
19574
+ this.space = this.bb.capacity();
19575
+ this.minalign = 1;
19576
+ this.vtable = null;
19577
+ this.vtable_in_use = 0;
19578
+ this.isNested = false;
19579
+ this.object_start = 0;
19580
+ this.vtables = [];
19581
+ this.vector_num_elems = 0;
19582
+ this.force_defaults = false;
19583
+ this.string_maps = null;
19584
+ }
19585
+ /**
19586
+ * In order to save space, fields that are set to their default value
19587
+ * don't get serialized into the buffer. Forcing defaults provides a
19588
+ * way to manually disable this optimization.
19589
+ *
19590
+ * @param forceDefaults true always serializes default values
19591
+ */
19592
+ forceDefaults(forceDefaults) {
19593
+ this.force_defaults = forceDefaults;
19594
+ }
19595
+ /**
19596
+ * Get the ByteBuffer representing the FlatBuffer. Only call this after you've
19597
+ * called finish(). The actual data starts at the ByteBuffer's current position,
19598
+ * not necessarily at 0.
19599
+ */
19600
+ dataBuffer() {
19601
+ return this.bb;
19602
+ }
19603
+ /**
19604
+ * Get the bytes representing the FlatBuffer. Only call this after you've
19605
+ * called finish().
19606
+ */
19607
+ asUint8Array() {
19608
+ return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
19609
+ }
19610
+ /**
19611
+ * Prepare to write an element of `size` after `additional_bytes` have been
19612
+ * written, e.g. if you write a string, you need to align such the int length
19613
+ * field is aligned to 4 bytes, and the string data follows it directly. If all
19614
+ * you need to do is alignment, `additional_bytes` will be 0.
19615
+ *
19616
+ * @param size This is the of the new element to write
19617
+ * @param additional_bytes The padding size
19618
+ */
19619
+ prep(size, additional_bytes) {
19620
+ if (size > this.minalign) {
19621
+ this.minalign = size;
19622
+ }
19623
+ const align_size = ~(this.bb.capacity() - this.space + additional_bytes) + 1 & size - 1;
19624
+ while (this.space < align_size + size + additional_bytes) {
19625
+ const old_buf_size = this.bb.capacity();
19626
+ this.bb = _Builder.growByteBuffer(this.bb);
19627
+ this.space += this.bb.capacity() - old_buf_size;
19628
+ }
19629
+ this.pad(align_size);
19630
+ }
19631
+ pad(byte_size) {
19632
+ for (let i = 0; i < byte_size; i++) {
19633
+ this.bb.writeInt8(--this.space, 0);
19634
+ }
19635
+ }
19636
+ writeInt8(value) {
19637
+ this.bb.writeInt8(this.space -= 1, value);
19638
+ }
19639
+ writeInt16(value) {
19640
+ this.bb.writeInt16(this.space -= 2, value);
19641
+ }
19642
+ writeInt32(value) {
19643
+ this.bb.writeInt32(this.space -= 4, value);
19644
+ }
19645
+ writeInt64(value) {
19646
+ this.bb.writeInt64(this.space -= 8, value);
19647
+ }
19648
+ writeFloat32(value) {
19649
+ this.bb.writeFloat32(this.space -= 4, value);
19650
+ }
19651
+ writeFloat64(value) {
19652
+ this.bb.writeFloat64(this.space -= 8, value);
19653
+ }
19654
+ /**
19655
+ * Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary).
19656
+ * @param value The `int8` to add the buffer.
19657
+ */
19658
+ addInt8(value) {
19659
+ this.prep(1, 0);
19660
+ this.writeInt8(value);
19661
+ }
19662
+ /**
19663
+ * Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary).
19664
+ * @param value The `int16` to add the buffer.
19665
+ */
19666
+ addInt16(value) {
19667
+ this.prep(2, 0);
19668
+ this.writeInt16(value);
19669
+ }
19670
+ /**
19671
+ * Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary).
19672
+ * @param value The `int32` to add the buffer.
19673
+ */
19674
+ addInt32(value) {
19675
+ this.prep(4, 0);
19676
+ this.writeInt32(value);
19677
+ }
19678
+ /**
19679
+ * Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary).
19680
+ * @param value The `int64` to add the buffer.
19681
+ */
19682
+ addInt64(value) {
19683
+ this.prep(8, 0);
19684
+ this.writeInt64(value);
19685
+ }
19686
+ /**
19687
+ * Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary).
19688
+ * @param value The `float32` to add the buffer.
19689
+ */
19690
+ addFloat32(value) {
19691
+ this.prep(4, 0);
19692
+ this.writeFloat32(value);
19693
+ }
19694
+ /**
19695
+ * Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary).
19696
+ * @param value The `float64` to add the buffer.
19697
+ */
19698
+ addFloat64(value) {
19699
+ this.prep(8, 0);
19700
+ this.writeFloat64(value);
19701
+ }
19702
+ addFieldInt8(voffset, value, defaultValue) {
19703
+ if (this.force_defaults || value != defaultValue) {
19704
+ this.addInt8(value);
19705
+ this.slot(voffset);
19706
+ }
19707
+ }
19708
+ addFieldInt16(voffset, value, defaultValue) {
19709
+ if (this.force_defaults || value != defaultValue) {
19710
+ this.addInt16(value);
19711
+ this.slot(voffset);
19712
+ }
19713
+ }
19714
+ addFieldInt32(voffset, value, defaultValue) {
19715
+ if (this.force_defaults || value != defaultValue) {
19716
+ this.addInt32(value);
19717
+ this.slot(voffset);
19718
+ }
19719
+ }
19720
+ addFieldInt64(voffset, value, defaultValue) {
19721
+ if (this.force_defaults || value !== defaultValue) {
19722
+ this.addInt64(value);
19723
+ this.slot(voffset);
19724
+ }
19725
+ }
19726
+ addFieldFloat32(voffset, value, defaultValue) {
19727
+ if (this.force_defaults || value != defaultValue) {
19728
+ this.addFloat32(value);
19729
+ this.slot(voffset);
19730
+ }
19731
+ }
19732
+ addFieldFloat64(voffset, value, defaultValue) {
19733
+ if (this.force_defaults || value != defaultValue) {
19734
+ this.addFloat64(value);
19735
+ this.slot(voffset);
19736
+ }
19737
+ }
19738
+ addFieldOffset(voffset, value, defaultValue) {
19739
+ if (this.force_defaults || value != defaultValue) {
19740
+ this.addOffset(value);
19741
+ this.slot(voffset);
19742
+ }
19743
+ }
19744
+ /**
19745
+ * Structs are stored inline, so nothing additional is being added. `d` is always 0.
19746
+ */
19747
+ addFieldStruct(voffset, value, defaultValue) {
19748
+ if (value != defaultValue) {
19749
+ this.nested(value);
19750
+ this.slot(voffset);
19751
+ }
19752
+ }
19753
+ /**
19754
+ * Structures are always stored inline, they need to be created right
19755
+ * where they're used. You'll get this assertion failure if you
19756
+ * created it elsewhere.
19757
+ */
19758
+ nested(obj) {
19759
+ if (obj != this.offset()) {
19760
+ throw new TypeError("FlatBuffers: struct must be serialized inline.");
19761
+ }
19762
+ }
19763
+ /**
19764
+ * Should not be creating any other object, string or vector
19765
+ * while an object is being constructed
19766
+ */
19767
+ notNested() {
19768
+ if (this.isNested) {
19769
+ throw new TypeError("FlatBuffers: object serialization must not be nested.");
19770
+ }
19771
+ }
19772
+ /**
19773
+ * Set the current vtable at `voffset` to the current location in the buffer.
19774
+ */
19775
+ slot(voffset) {
19776
+ if (this.vtable !== null)
19777
+ this.vtable[voffset] = this.offset();
19778
+ }
19779
+ /**
19780
+ * @returns Offset relative to the end of the buffer.
19781
+ */
19782
+ offset() {
19783
+ return this.bb.capacity() - this.space;
19784
+ }
19785
+ /**
19786
+ * Doubles the size of the backing ByteBuffer and copies the old data towards
19787
+ * the end of the new buffer (since we build the buffer backwards).
19788
+ *
19789
+ * @param bb The current buffer with the existing data
19790
+ * @returns A new byte buffer with the old data copied
19791
+ * to it. The data is located at the end of the buffer.
19792
+ *
19793
+ * uint8Array.set() formally takes {Array<number>|ArrayBufferView}, so to pass
19794
+ * it a uint8Array we need to suppress the type check:
19795
+ * @suppress {checkTypes}
19796
+ */
19797
+ static growByteBuffer(bb) {
19798
+ const old_buf_size = bb.capacity();
19799
+ if (old_buf_size & 3221225472) {
19800
+ throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
19801
+ }
19802
+ const new_buf_size = old_buf_size << 1;
19803
+ const nbb = ByteBuffer4.allocate(new_buf_size);
19804
+ nbb.setPosition(new_buf_size - old_buf_size);
19805
+ nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size);
19806
+ return nbb;
19807
+ }
19808
+ /**
19809
+ * Adds on offset, relative to where it will be written.
19810
+ *
19811
+ * @param offset The offset to add.
19812
+ */
19813
+ addOffset(offset) {
19814
+ this.prep(SIZEOF_INT2, 0);
19815
+ this.writeInt32(this.offset() - offset + SIZEOF_INT2);
19816
+ }
19817
+ /**
19818
+ * Start encoding a new object in the buffer. Users will not usually need to
19819
+ * call this directly. The FlatBuffers compiler will generate helper methods
19820
+ * that call this method internally.
19821
+ */
19822
+ startObject(numfields) {
19823
+ this.notNested();
19824
+ if (this.vtable == null) {
19825
+ this.vtable = [];
19826
+ }
19827
+ this.vtable_in_use = numfields;
19828
+ for (let i = 0; i < numfields; i++) {
19829
+ this.vtable[i] = 0;
19830
+ }
19831
+ this.isNested = true;
19832
+ this.object_start = this.offset();
19833
+ }
19834
+ /**
19835
+ * Finish off writing the object that is under construction.
19836
+ *
19837
+ * @returns The offset to the object inside `dataBuffer`
19838
+ */
19839
+ endObject() {
19840
+ if (this.vtable == null || !this.isNested) {
19841
+ throw new Error("FlatBuffers: endObject called without startObject");
19842
+ }
19843
+ this.addInt32(0);
19844
+ const vtableloc = this.offset();
19845
+ let i = this.vtable_in_use - 1;
19846
+ for (; i >= 0 && this.vtable[i] == 0; i--) {
19847
+ }
19848
+ const trimmed_size = i + 1;
19849
+ for (; i >= 0; i--) {
19850
+ this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0);
19851
+ }
19852
+ const standard_fields = 2;
19853
+ this.addInt16(vtableloc - this.object_start);
19854
+ const len = (trimmed_size + standard_fields) * SIZEOF_SHORT2;
19855
+ this.addInt16(len);
19856
+ let existing_vtable = 0;
19857
+ const vt1 = this.space;
19858
+ outer_loop: for (i = 0; i < this.vtables.length; i++) {
19859
+ const vt2 = this.bb.capacity() - this.vtables[i];
19860
+ if (len == this.bb.readInt16(vt2)) {
19861
+ for (let j2 = SIZEOF_SHORT2; j2 < len; j2 += SIZEOF_SHORT2) {
19862
+ if (this.bb.readInt16(vt1 + j2) != this.bb.readInt16(vt2 + j2)) {
19863
+ continue outer_loop;
19864
+ }
19865
+ }
19866
+ existing_vtable = this.vtables[i];
19867
+ break;
19868
+ }
19869
+ }
19870
+ if (existing_vtable) {
19871
+ this.space = this.bb.capacity() - vtableloc;
19872
+ this.bb.writeInt32(this.space, existing_vtable - vtableloc);
19873
+ } else {
19874
+ this.vtables.push(this.offset());
19875
+ this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc);
19876
+ }
19877
+ this.isNested = false;
19878
+ return vtableloc;
19879
+ }
19880
+ /**
19881
+ * Finalize a buffer, poiting to the given `root_table`.
19882
+ */
19883
+ finish(root_table, opt_file_identifier, opt_size_prefix) {
19884
+ const size_prefix = opt_size_prefix ? SIZE_PREFIX_LENGTH2 : 0;
19885
+ if (opt_file_identifier) {
19886
+ const file_identifier = opt_file_identifier;
19887
+ this.prep(this.minalign, SIZEOF_INT2 + FILE_IDENTIFIER_LENGTH2 + size_prefix);
19888
+ if (file_identifier.length != FILE_IDENTIFIER_LENGTH2) {
19889
+ throw new TypeError("FlatBuffers: file identifier must be length " + FILE_IDENTIFIER_LENGTH2);
19890
+ }
19891
+ for (let i = FILE_IDENTIFIER_LENGTH2 - 1; i >= 0; i--) {
19892
+ this.writeInt8(file_identifier.charCodeAt(i));
19893
+ }
19894
+ }
19895
+ this.prep(this.minalign, SIZEOF_INT2 + size_prefix);
19896
+ this.addOffset(root_table);
19897
+ if (size_prefix) {
19898
+ this.addInt32(this.bb.capacity() - this.space);
19899
+ }
19900
+ this.bb.setPosition(this.space);
19901
+ }
19902
+ /**
19903
+ * Finalize a size prefixed buffer, pointing to the given `root_table`.
19904
+ */
19905
+ finishSizePrefixed(root_table, opt_file_identifier) {
19906
+ this.finish(root_table, opt_file_identifier, true);
19907
+ }
19908
+ /**
19909
+ * This checks a required field has been set in a given table that has
19910
+ * just been constructed.
19911
+ */
19912
+ requiredField(table, field) {
19913
+ const table_start = this.bb.capacity() - table;
19914
+ const vtable_start = table_start - this.bb.readInt32(table_start);
19915
+ const ok = field < this.bb.readInt16(vtable_start) && this.bb.readInt16(vtable_start + field) != 0;
19916
+ if (!ok) {
19917
+ throw new TypeError("FlatBuffers: field " + field + " must be set");
19918
+ }
19919
+ }
19920
+ /**
19921
+ * Start a new array/vector of objects. Users usually will not call
19922
+ * this directly. The FlatBuffers compiler will create a start/end
19923
+ * method for vector types in generated code.
19924
+ *
19925
+ * @param elem_size The size of each element in the array
19926
+ * @param num_elems The number of elements in the array
19927
+ * @param alignment The alignment of the array
18726
19928
  */
18727
- finish() {
18728
- this.finished = true;
18729
- for (const child of this.children)
18730
- child.finish();
18731
- return this;
19929
+ startVector(elem_size, num_elems, alignment) {
19930
+ this.notNested();
19931
+ this.vector_num_elems = num_elems;
19932
+ this.prep(SIZEOF_INT2, elem_size * num_elems);
19933
+ this.prep(alignment, elem_size * num_elems);
18732
19934
  }
18733
19935
  /**
18734
- * Clear this Builder's internal state, including child Builders if applicable, and reset the length to 0.
18735
- * @returns {this} The cleared `Builder` instance.
19936
+ * Finish off the creation of an array and all its elements. The array must be
19937
+ * created with `startVector`.
19938
+ *
19939
+ * @returns The offset at which the newly created array
19940
+ * starts.
18736
19941
  */
18737
- clear() {
18738
- var _a9, _b3, _c3, _d3;
18739
- this.length = 0;
18740
- (_a9 = this._nulls) === null || _a9 === void 0 ? void 0 : _a9.clear();
18741
- (_b3 = this._values) === null || _b3 === void 0 ? void 0 : _b3.clear();
18742
- (_c3 = this._offsets) === null || _c3 === void 0 ? void 0 : _c3.clear();
18743
- (_d3 = this._typeIds) === null || _d3 === void 0 ? void 0 : _d3.clear();
18744
- for (const child of this.children)
18745
- child.clear();
18746
- return this;
18747
- }
18748
- };
18749
- Builder5.prototype.length = 1;
18750
- Builder5.prototype.stride = 1;
18751
- Builder5.prototype.children = null;
18752
- Builder5.prototype.finished = false;
18753
- Builder5.prototype.nullValues = null;
18754
- Builder5.prototype._isValid = () => true;
18755
- var FixedWidthBuilder2 = class extends Builder5 {
18756
- constructor(opts) {
18757
- super(opts);
18758
- this._values = new DataBufferBuilder2(new this.ArrayType(0), this.stride);
18759
- }
18760
- setValue(index, value) {
18761
- const values = this._values;
18762
- values.reserve(index - values.length + 1);
18763
- return super.setValue(index, value);
18764
- }
18765
- };
18766
- var VariableWidthBuilder2 = class extends Builder5 {
18767
- constructor(opts) {
18768
- super(opts);
18769
- this._pendingLength = 0;
18770
- this._offsets = new OffsetsBufferBuilder2();
18771
- }
18772
- setValue(index, value) {
18773
- const pending = this._pending || (this._pending = /* @__PURE__ */ new Map());
18774
- const current = pending.get(index);
18775
- current && (this._pendingLength -= current.length);
18776
- this._pendingLength += value instanceof MapRow2 ? value[kKeys2].length : value.length;
18777
- pending.set(index, value);
19942
+ endVector() {
19943
+ this.writeInt32(this.vector_num_elems);
19944
+ return this.offset();
18778
19945
  }
18779
- setValid(index, isValid) {
18780
- if (!super.setValid(index, isValid)) {
18781
- (this._pending || (this._pending = /* @__PURE__ */ new Map())).set(index, void 0);
18782
- return false;
19946
+ /**
19947
+ * Encode the string `s` in the buffer using UTF-8. If the string passed has
19948
+ * already been seen, we return the offset of the already written string
19949
+ *
19950
+ * @param s The string to encode
19951
+ * @return The offset in the buffer where the encoded string starts
19952
+ */
19953
+ createSharedString(s) {
19954
+ if (!s) {
19955
+ return 0;
18783
19956
  }
18784
- return true;
18785
- }
18786
- clear() {
18787
- this._pendingLength = 0;
18788
- this._pending = void 0;
18789
- return super.clear();
18790
- }
18791
- flush() {
18792
- this._flush();
18793
- return super.flush();
18794
- }
18795
- finish() {
18796
- this._flush();
18797
- return super.finish();
18798
- }
18799
- _flush() {
18800
- const pending = this._pending;
18801
- const pendingLength = this._pendingLength;
18802
- this._pendingLength = 0;
18803
- this._pending = void 0;
18804
- if (pending && pending.size > 0) {
18805
- this._flushPending(pending, pendingLength);
19957
+ if (!this.string_maps) {
19958
+ this.string_maps = /* @__PURE__ */ new Map();
18806
19959
  }
18807
- return this;
18808
- }
18809
- };
18810
-
18811
- // ../../node_modules/@duckdb/duckdb-wasm/node_modules/apache-arrow/fb/block.mjs
18812
- var Block2 = class {
18813
- constructor() {
18814
- this.bb = null;
18815
- this.bb_pos = 0;
18816
- }
18817
- __init(i, bb) {
18818
- this.bb_pos = i;
18819
- this.bb = bb;
18820
- return this;
19960
+ if (this.string_maps.has(s)) {
19961
+ return this.string_maps.get(s);
19962
+ }
19963
+ const offset = this.createString(s);
19964
+ this.string_maps.set(s, offset);
19965
+ return offset;
18821
19966
  }
18822
19967
  /**
18823
- * Index to the start of the RecordBlock (note this is past the Message header)
19968
+ * Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed
19969
+ * instead of a string, it is assumed to contain valid UTF-8 encoded data.
19970
+ *
19971
+ * @param s The string to encode
19972
+ * @return The offset in the buffer where the encoded string starts
18824
19973
  */
18825
- offset() {
18826
- return this.bb.readInt64(this.bb_pos);
19974
+ createString(s) {
19975
+ if (s === null || s === void 0) {
19976
+ return 0;
19977
+ }
19978
+ let utf8;
19979
+ if (s instanceof Uint8Array) {
19980
+ utf8 = s;
19981
+ } else {
19982
+ utf8 = this.text_encoder.encode(s);
19983
+ }
19984
+ this.addInt8(0);
19985
+ this.startVector(1, utf8.length, 1);
19986
+ this.bb.setPosition(this.space -= utf8.length);
19987
+ for (let i = 0, offset = this.space, bytes = this.bb.bytes(); i < utf8.length; i++) {
19988
+ bytes[offset++] = utf8[i];
19989
+ }
19990
+ return this.endVector();
18827
19991
  }
18828
19992
  /**
18829
- * Length of the metadata
19993
+ * A helper function to pack an object
19994
+ *
19995
+ * @returns offset of obj
18830
19996
  */
18831
- metaDataLength() {
18832
- return this.bb.readInt32(this.bb_pos + 8);
19997
+ createObjectOffset(obj) {
19998
+ if (obj === null) {
19999
+ return 0;
20000
+ }
20001
+ if (typeof obj === "string") {
20002
+ return this.createString(obj);
20003
+ } else {
20004
+ return obj.pack(this);
20005
+ }
18833
20006
  }
18834
20007
  /**
18835
- * Length of the data (this is aligned so there can be a gap between this and
18836
- * the metadata).
20008
+ * A helper function to pack a list of object
20009
+ *
20010
+ * @returns list of offsets of each non null object
18837
20011
  */
18838
- bodyLength() {
18839
- return this.bb.readInt64(this.bb_pos + 16);
18840
- }
18841
- static sizeOf() {
18842
- return 24;
20012
+ createObjectOffsetList(list) {
20013
+ const ret = [];
20014
+ for (let i = 0; i < list.length; ++i) {
20015
+ const val = list[i];
20016
+ if (val !== null) {
20017
+ ret.push(this.createObjectOffset(val));
20018
+ } else {
20019
+ throw new TypeError("FlatBuffers: Argument for createObjectOffsetList cannot contain null.");
20020
+ }
20021
+ }
20022
+ return ret;
18843
20023
  }
18844
- static createBlock(builder, offset, metaDataLength, bodyLength) {
18845
- builder.prep(8, 24);
18846
- builder.writeInt64(BigInt(bodyLength !== null && bodyLength !== void 0 ? bodyLength : 0));
18847
- builder.pad(4);
18848
- builder.writeInt32(metaDataLength);
18849
- builder.writeInt64(BigInt(offset !== null && offset !== void 0 ? offset : 0));
18850
- return builder.offset();
20024
+ createStructOffsetList(list, startFunc) {
20025
+ startFunc(this, list.length);
20026
+ this.createObjectOffsetList(list.slice().reverse());
20027
+ return this.endVector();
18851
20028
  }
18852
20029
  };
18853
20030
 
@@ -18866,7 +20043,7 @@ var KeyValue2 = class _KeyValue {
18866
20043
  return (obj || new _KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
18867
20044
  }
18868
20045
  static getSizePrefixedRootAsKeyValue(bb, obj) {
18869
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20046
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
18870
20047
  return (obj || new _KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
18871
20048
  }
18872
20049
  key(optionalEncoding) {
@@ -18936,7 +20113,7 @@ var Int2 = class _Int {
18936
20113
  return (obj || new _Int()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
18937
20114
  }
18938
20115
  static getSizePrefixedRootAsInt(bb, obj) {
18939
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20116
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
18940
20117
  return (obj || new _Int()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
18941
20118
  }
18942
20119
  bitWidth() {
@@ -18983,7 +20160,7 @@ var DictionaryEncoding2 = class _DictionaryEncoding {
18983
20160
  return (obj || new _DictionaryEncoding()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
18984
20161
  }
18985
20162
  static getSizePrefixedRootAsDictionaryEncoding(bb, obj) {
18986
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20163
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
18987
20164
  return (obj || new _DictionaryEncoding()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
18988
20165
  }
18989
20166
  /**
@@ -19056,7 +20233,7 @@ var Binary4 = class _Binary {
19056
20233
  return (obj || new _Binary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19057
20234
  }
19058
20235
  static getSizePrefixedRootAsBinary(bb, obj) {
19059
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20236
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19060
20237
  return (obj || new _Binary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19061
20238
  }
19062
20239
  static startBinary(builder) {
@@ -19087,7 +20264,7 @@ var Bool4 = class _Bool {
19087
20264
  return (obj || new _Bool()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19088
20265
  }
19089
20266
  static getSizePrefixedRootAsBool(bb, obj) {
19090
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20267
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19091
20268
  return (obj || new _Bool()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19092
20269
  }
19093
20270
  static startBool(builder) {
@@ -19125,7 +20302,7 @@ var Date3 = class _Date {
19125
20302
  return (obj || new _Date()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19126
20303
  }
19127
20304
  static getSizePrefixedRootAsDate(bb, obj) {
19128
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20305
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19129
20306
  return (obj || new _Date()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19130
20307
  }
19131
20308
  unit() {
@@ -19164,7 +20341,7 @@ var Decimal4 = class _Decimal {
19164
20341
  return (obj || new _Decimal()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19165
20342
  }
19166
20343
  static getSizePrefixedRootAsDecimal(bb, obj) {
19167
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20344
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19168
20345
  return (obj || new _Decimal()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19169
20346
  }
19170
20347
  /**
@@ -19238,7 +20415,7 @@ var Duration4 = class _Duration {
19238
20415
  return (obj || new _Duration()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19239
20416
  }
19240
20417
  static getSizePrefixedRootAsDuration(bb, obj) {
19241
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20418
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19242
20419
  return (obj || new _Duration()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19243
20420
  }
19244
20421
  unit() {
@@ -19277,7 +20454,7 @@ var FixedSizeBinary4 = class _FixedSizeBinary {
19277
20454
  return (obj || new _FixedSizeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19278
20455
  }
19279
20456
  static getSizePrefixedRootAsFixedSizeBinary(bb, obj) {
19280
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20457
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19281
20458
  return (obj || new _FixedSizeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19282
20459
  }
19283
20460
  /**
@@ -19319,7 +20496,7 @@ var FixedSizeList4 = class _FixedSizeList {
19319
20496
  return (obj || new _FixedSizeList()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19320
20497
  }
19321
20498
  static getSizePrefixedRootAsFixedSizeList(bb, obj) {
19322
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20499
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19323
20500
  return (obj || new _FixedSizeList()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19324
20501
  }
19325
20502
  /**
@@ -19369,7 +20546,7 @@ var FloatingPoint2 = class _FloatingPoint {
19369
20546
  return (obj || new _FloatingPoint()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19370
20547
  }
19371
20548
  static getSizePrefixedRootAsFloatingPoint(bb, obj) {
19372
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20549
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19373
20550
  return (obj || new _FloatingPoint()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19374
20551
  }
19375
20552
  precision() {
@@ -19416,7 +20593,7 @@ var Interval2 = class _Interval {
19416
20593
  return (obj || new _Interval()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19417
20594
  }
19418
20595
  static getSizePrefixedRootAsInterval(bb, obj) {
19419
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20596
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19420
20597
  return (obj || new _Interval()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19421
20598
  }
19422
20599
  unit() {
@@ -19455,7 +20632,7 @@ var List4 = class _List {
19455
20632
  return (obj || new _List()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19456
20633
  }
19457
20634
  static getSizePrefixedRootAsList(bb, obj) {
19458
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20635
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19459
20636
  return (obj || new _List()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19460
20637
  }
19461
20638
  static startList(builder) {
@@ -19486,7 +20663,7 @@ var Map3 = class _Map {
19486
20663
  return (obj || new _Map()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19487
20664
  }
19488
20665
  static getSizePrefixedRootAsMap(bb, obj) {
19489
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20666
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19490
20667
  return (obj || new _Map()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19491
20668
  }
19492
20669
  /**
@@ -19528,7 +20705,7 @@ var Null4 = class _Null {
19528
20705
  return (obj || new _Null()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19529
20706
  }
19530
20707
  static getSizePrefixedRootAsNull(bb, obj) {
19531
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20708
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19532
20709
  return (obj || new _Null()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19533
20710
  }
19534
20711
  static startNull(builder) {
@@ -19559,7 +20736,7 @@ var Struct_2 = class _Struct_ {
19559
20736
  return (obj || new _Struct_()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19560
20737
  }
19561
20738
  static getSizePrefixedRootAsStruct_(bb, obj) {
19562
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20739
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19563
20740
  return (obj || new _Struct_()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19564
20741
  }
19565
20742
  static startStruct_(builder) {
@@ -19590,7 +20767,7 @@ var Time2 = class _Time {
19590
20767
  return (obj || new _Time()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19591
20768
  }
19592
20769
  static getSizePrefixedRootAsTime(bb, obj) {
19593
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20770
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19594
20771
  return (obj || new _Time()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19595
20772
  }
19596
20773
  unit() {
@@ -19637,7 +20814,7 @@ var Timestamp2 = class _Timestamp {
19637
20814
  return (obj || new _Timestamp()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19638
20815
  }
19639
20816
  static getSizePrefixedRootAsTimestamp(bb, obj) {
19640
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20817
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19641
20818
  return (obj || new _Timestamp()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19642
20819
  }
19643
20820
  unit() {
@@ -19691,7 +20868,7 @@ var Union2 = class _Union {
19691
20868
  return (obj || new _Union()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19692
20869
  }
19693
20870
  static getSizePrefixedRootAsUnion(bb, obj) {
19694
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20871
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19695
20872
  return (obj || new _Union()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19696
20873
  }
19697
20874
  mode() {
@@ -19756,7 +20933,7 @@ var Utf84 = class _Utf8 {
19756
20933
  return (obj || new _Utf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19757
20934
  }
19758
20935
  static getSizePrefixedRootAsUtf8(bb, obj) {
19759
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20936
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19760
20937
  return (obj || new _Utf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19761
20938
  }
19762
20939
  static startUtf8(builder) {
@@ -19815,7 +20992,7 @@ var Field3 = class _Field {
19815
20992
  return (obj || new _Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19816
20993
  }
19817
20994
  static getSizePrefixedRootAsField(bb, obj) {
19818
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
20995
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19819
20996
  return (obj || new _Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19820
20997
  }
19821
20998
  name(optionalEncoding) {
@@ -19935,7 +21112,7 @@ var Schema3 = class _Schema {
19935
21112
  return (obj || new _Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19936
21113
  }
19937
21114
  static getSizePrefixedRootAsSchema(bb, obj) {
19938
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
21115
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
19939
21116
  return (obj || new _Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
19940
21117
  }
19941
21118
  /**
@@ -20054,7 +21231,7 @@ var Footer2 = class _Footer {
20054
21231
  return (obj || new _Footer()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
20055
21232
  }
20056
21233
  static getSizePrefixedRootAsFooter(bb, obj) {
20057
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
21234
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
20058
21235
  return (obj || new _Footer()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
20059
21236
  }
20060
21237
  version() {
@@ -20255,19 +21432,19 @@ function generateDictionaryMap2(fields, dictionaries = /* @__PURE__ */ new Map()
20255
21432
  }
20256
21433
 
20257
21434
  // ../../node_modules/@duckdb/duckdb-wasm/node_modules/apache-arrow/ipc/metadata/file.mjs
20258
- var Builder6 = Builder;
20259
- var ByteBuffer4 = ByteBuffer;
21435
+ var Builder7 = Builder6;
21436
+ var ByteBuffer5 = ByteBuffer4;
20260
21437
  var Footer_2 = class {
20261
21438
  /** @nocollapse */
20262
21439
  static decode(buf) {
20263
- buf = new ByteBuffer4(toUint8Array2(buf));
21440
+ buf = new ByteBuffer5(toUint8Array2(buf));
20264
21441
  const footer = Footer2.getRootAsFooter(buf);
20265
21442
  const schema = Schema4.decode(footer.schema(), /* @__PURE__ */ new Map(), footer.version());
20266
21443
  return new OffHeapFooter2(schema, footer);
20267
21444
  }
20268
21445
  /** @nocollapse */
20269
21446
  static encode(footer) {
20270
- const b2 = new Builder6();
21447
+ const b2 = new Builder7();
20271
21448
  const schemaOffset = Schema4.encode(b2, footer.schema);
20272
21449
  Footer2.startRecordBatchesVector(b2, footer.numRecordBatches);
20273
21450
  for (const rb of [...footer.recordBatches()].slice().reverse()) {
@@ -22625,7 +23802,7 @@ var BodyCompression2 = class _BodyCompression {
22625
23802
  return (obj || new _BodyCompression()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
22626
23803
  }
22627
23804
  static getSizePrefixedRootAsBodyCompression(bb, obj) {
22628
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
23805
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
22629
23806
  return (obj || new _BodyCompression()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
22630
23807
  }
22631
23808
  /**
@@ -22755,7 +23932,7 @@ var RecordBatch5 = class _RecordBatch {
22755
23932
  return (obj || new _RecordBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
22756
23933
  }
22757
23934
  static getSizePrefixedRootAsRecordBatch(bb, obj) {
22758
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
23935
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
22759
23936
  return (obj || new _RecordBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
22760
23937
  }
22761
23938
  /**
@@ -22842,7 +24019,7 @@ var DictionaryBatch3 = class _DictionaryBatch {
22842
24019
  return (obj || new _DictionaryBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
22843
24020
  }
22844
24021
  static getSizePrefixedRootAsDictionaryBatch(bb, obj) {
22845
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
24022
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
22846
24023
  return (obj || new _DictionaryBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
22847
24024
  }
22848
24025
  id() {
@@ -22906,7 +24083,7 @@ var Message3 = class _Message {
22906
24083
  return (obj || new _Message()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
22907
24084
  }
22908
24085
  static getSizePrefixedRootAsMessage(bb, obj) {
22909
- bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
24086
+ bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH2);
22910
24087
  return (obj || new _Message()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
22911
24088
  }
22912
24089
  version() {
@@ -23236,8 +24413,8 @@ function typeFromJSON2(f2, children) {
23236
24413
  }
23237
24414
 
23238
24415
  // ../../node_modules/@duckdb/duckdb-wasm/node_modules/apache-arrow/ipc/metadata/message.mjs
23239
- var Builder7 = Builder;
23240
- var ByteBuffer5 = ByteBuffer;
24416
+ var Builder8 = Builder6;
24417
+ var ByteBuffer6 = ByteBuffer4;
23241
24418
  var Message4 = class _Message {
23242
24419
  /** @nocollapse */
23243
24420
  static fromJSON(msg, headerType) {
@@ -23247,7 +24424,7 @@ var Message4 = class _Message {
23247
24424
  }
23248
24425
  /** @nocollapse */
23249
24426
  static decode(buf) {
23250
- buf = new ByteBuffer5(toUint8Array2(buf));
24427
+ buf = new ByteBuffer6(toUint8Array2(buf));
23251
24428
  const _message = Message3.getRootAsMessage(buf);
23252
24429
  const bodyLength = _message.bodyLength();
23253
24430
  const version = _message.version();
@@ -23258,7 +24435,7 @@ var Message4 = class _Message {
23258
24435
  }
23259
24436
  /** @nocollapse */
23260
24437
  static encode(message) {
23261
- const b2 = new Builder7();
24438
+ const b2 = new Builder8();
23262
24439
  let headerOffset = -1;
23263
24440
  if (message.isSchema()) {
23264
24441
  headerOffset = Schema4.encode(b2, message.header());
@@ -23749,7 +24926,7 @@ var MessageReader2 = class {
23749
24926
  }
23750
24927
  readMetadataLength() {
23751
24928
  const buf = this.source.read(PADDING2);
23752
- const bb = buf && new ByteBuffer(buf);
24929
+ const bb = buf && new ByteBuffer4(buf);
23753
24930
  const len = (bb === null || bb === void 0 ? void 0 : bb.readInt32(0)) || 0;
23754
24931
  return { done: len === 0, value: len };
23755
24932
  }
@@ -23838,7 +25015,7 @@ var AsyncMessageReader2 = class {
23838
25015
  readMetadataLength() {
23839
25016
  return __awaiter(this, void 0, void 0, function* () {
23840
25017
  const buf = yield this.source.read(PADDING2);
23841
- const bb = buf && new ByteBuffer(buf);
25018
+ const bb = buf && new ByteBuffer4(buf);
23842
25019
  const len = (bb === null || bb === void 0 ? void 0 : bb.readInt32(0)) || 0;
23843
25020
  return { done: len === 0, value: len };
23844
25021
  });
@@ -25903,7 +27080,7 @@ function wasmConnector(options = {}) {
25903
27080
  /**
25904
27081
  * Query the DuckDB-WASM instance.
25905
27082
  * @param {object} query
25906
- * @param {string} [query.type] The query type: 'exec', 'arrow', or 'json'.
27083
+ * @param {'exec' | 'arrow' | 'json'} [query.type] The query type: 'exec', 'arrow', or 'json'.
25907
27084
  * @param {string} query.sql A SQL query string.
25908
27085
  * @returns the query result
25909
27086
  */
@@ -25911,7 +27088,7 @@ function wasmConnector(options = {}) {
25911
27088
  const { type, sql: sql2 } = query;
25912
27089
  const con2 = await getConnection();
25913
27090
  const result = await con2.query(sql2);
25914
- return type === "exec" ? void 0 : type === "arrow" ? result : Array.from(result);
27091
+ return type === "exec" ? void 0 : type === "arrow" ? result : result.toArray();
25915
27092
  }
25916
27093
  };
25917
27094
  }
@@ -25931,6 +27108,74 @@ async function initDatabase({
25931
27108
  return db;
25932
27109
  }
25933
27110
 
27111
+ // src/SelectionClause.js
27112
+ function clausePoint(field, value, {
27113
+ source,
27114
+ clients = source ? /* @__PURE__ */ new Set([source]) : void 0
27115
+ }) {
27116
+ const predicate = value !== void 0 ? isNotDistinct(field, literal(value)) : null;
27117
+ return {
27118
+ meta: { type: "point" },
27119
+ source,
27120
+ clients,
27121
+ value,
27122
+ predicate
27123
+ };
27124
+ }
27125
+ function clausePoints(fields, value, {
27126
+ source,
27127
+ clients = source ? /* @__PURE__ */ new Set([source]) : void 0
27128
+ }) {
27129
+ let predicate = null;
27130
+ if (value) {
27131
+ const clauses = value.map((vals) => {
27132
+ const list = vals.map((v2, i) => isNotDistinct(fields[i], literal(v2)));
27133
+ return list.length > 1 ? and(list) : list[0];
27134
+ });
27135
+ predicate = clauses.length > 1 ? or(clauses) : clauses[0];
27136
+ }
27137
+ return {
27138
+ meta: { type: "point" },
27139
+ source,
27140
+ clients,
27141
+ value,
27142
+ predicate
27143
+ };
27144
+ }
27145
+ function clauseInterval(field, value, {
27146
+ source,
27147
+ clients = source ? /* @__PURE__ */ new Set([source]) : void 0,
27148
+ bin,
27149
+ scale,
27150
+ pixelSize = 1
27151
+ }) {
27152
+ const predicate = value != null ? isBetween(field, value) : null;
27153
+ const meta = { type: "interval", scales: scale && [scale], bin, pixelSize };
27154
+ return { meta, source, clients, value, predicate };
27155
+ }
27156
+ function clauseIntervals(fields, value, {
27157
+ source,
27158
+ clients = source ? /* @__PURE__ */ new Set([source]) : void 0,
27159
+ bin,
27160
+ scales: scales2 = [],
27161
+ pixelSize = 1
27162
+ }) {
27163
+ const predicate = value != null ? and(fields.map((f2, i) => isBetween(f2, value[i]))) : null;
27164
+ const meta = { type: "interval", scales: scales2, bin, pixelSize };
27165
+ return { meta, source, clients, value, predicate };
27166
+ }
27167
+ var MATCH_METHODS = { contains, prefix, suffix, regexp: regexp_matches };
27168
+ function clauseMatch(field, value, {
27169
+ source,
27170
+ clients = void 0,
27171
+ method = "contains"
27172
+ }) {
27173
+ let fn = MATCH_METHODS[method];
27174
+ const predicate = value ? fn(field, literal(value)) : null;
27175
+ const meta = { type: "match", method };
27176
+ return { meta, source, clients, value, predicate };
27177
+ }
27178
+
25934
27179
  // src/util/synchronizer.js
25935
27180
  function synchronizer() {
25936
27181
  const set = /* @__PURE__ */ new Set();
@@ -25974,12 +27219,50 @@ function synchronizer() {
25974
27219
  }
25975
27220
  };
25976
27221
  }
27222
+
27223
+ // src/util/to-data-columns.js
27224
+ function toDataColumns(data) {
27225
+ return isArrowTable(data) ? arrowToColumns(data) : arrayToColumns(data);
27226
+ }
27227
+ function arrowToColumns(data) {
27228
+ const { numRows, numCols, schema: { fields } } = data;
27229
+ const columns = {};
27230
+ for (let col = 0; col < numCols; ++col) {
27231
+ const name = fields[col].name;
27232
+ if (columns[name]) {
27233
+ console.warn(`Redundant column name "${name}". Skipping...`);
27234
+ } else {
27235
+ columns[name] = convertArrowColumn(data.getChildAt(col));
27236
+ }
27237
+ }
27238
+ return { numRows, columns };
27239
+ }
27240
+ function arrayToColumns(data) {
27241
+ const numRows = data.length;
27242
+ if (typeof data[0] === "object") {
27243
+ const names = numRows ? Object.keys(data[0]) : [];
27244
+ const columns = {};
27245
+ if (names.length > 0) {
27246
+ names.forEach((name) => {
27247
+ columns[name] = data.map((d) => d[name]);
27248
+ });
27249
+ }
27250
+ return { numRows, columns };
27251
+ } else {
27252
+ return { numRows, values: data };
27253
+ }
27254
+ }
25977
27255
  export {
25978
27256
  Coordinator,
25979
27257
  MosaicClient,
25980
27258
  Param,
25981
27259
  Priority,
25982
27260
  Selection,
27261
+ clauseInterval,
27262
+ clauseIntervals,
27263
+ clauseMatch,
27264
+ clausePoint,
27265
+ clausePoints,
25983
27266
  convertArrowArrayType,
25984
27267
  convertArrowColumn,
25985
27268
  convertArrowValue,
@@ -25992,5 +27275,6 @@ export {
25992
27275
  socketConnector,
25993
27276
  synchronizer,
25994
27277
  throttle,
27278
+ toDataColumns,
25995
27279
  wasmConnector
25996
27280
  };